Add turn-interrupt replay coverage and protocol logging

- add interrupt and mid-tool replay fixtures for Claude and Codex
- log Claude Agent SDK protocol frames to native event traces
- project Codex commandExecution start events into orchestration updates
This commit is contained in:
Julius Marminge committed 2026-08-07 13:17:27 +02:00
1 parent 29934f5dd8
commit fa9a1916f8
22 files changed
+2472 -74

No files matched your search

@@ -25,6 +25,9 @@ import {
TOOL_CALL_READ_ONLY_PROMPT,
TOOL_CALL_READ_ONLY_WORKSPACE_ROOT,
TOOL_CALL_WRITE_PROMPT,
TURN_INTERRUPT_MID_TOOL_PROMPT,
TURN_INTERRUPT_PROMPT,
TURN_INTERRUPT_RECOVERY_PROMPT,
WORKSPACE_NEVER_POLICY,
WEB_SEARCH_PROMPT,
} from "../src/orchestration-v2/testkit/fixtures/shared.ts";
@@ -60,6 +63,26 @@ const CLAUDE_RECORDINGS = {
queryMode: "active_steering",
enableTools: true,
},
turn_interrupt_mid_tool: {
prompts: [TURN_INTERRUPT_MID_TOOL_PROMPT],
defaultTranscriptFile: "fixtures/turn_interrupt_mid_tool/claude_transcript.ndjson",
queryMode: "interrupt",
enableTools: true,
interruptAfter: "tool_use",
},
turn_interrupt: {
prompts: [TURN_INTERRUPT_PROMPT],
defaultTranscriptFile: "fixtures/turn_interrupt/claude_transcript.ndjson",
queryMode: "interrupt",
enableTools: true,
},
turn_interrupt_restart: {
prompts: [TURN_INTERRUPT_MID_TOOL_PROMPT, TURN_INTERRUPT_RECOVERY_PROMPT],
defaultTranscriptFile: "fixtures/turn_interrupt_restart/claude_transcript.ndjson",
queryMode: "interrupt_restart",
enableTools: true,
interruptAfter: "tool_use",
},
tool_call_read_only: {
prompts: [TOOL_CALL_READ_ONLY_PROMPT],
defaultTranscriptFile: "fixtures/tool_call_read_only/claude_transcript.ndjson",
@@ -102,7 +125,12 @@ function readArgValue(name: string): string | undefined {
return index >= 0 ? args[index + 1] : undefined;
}
type ClaudeRecordingQueryMode = "streaming" | "restart" | "active_steering" | "interrupt_restart";
type ClaudeRecordingQueryMode =
| "streaming"
| "restart"
| "active_steering"
| "interrupt"
| "interrupt_restart";
function selectedQueryMode(defaultMode: ClaudeRecordingQueryMode): ClaudeRecordingQueryMode {
const raw = readArgValue("--query-mode") ?? process.env.T3_CLAUDE_REPLAY_QUERY_MODE;
@@ -113,12 +141,13 @@ function selectedQueryMode(defaultMode: ClaudeRecordingQueryMode): ClaudeRecordi
raw === "streaming" ||
raw === "restart" ||
raw === "active_steering" ||
raw === "interrupt" ||
raw === "interrupt_restart"
) {
return raw;
}
throw new Error(
`Unsupported Claude replay query mode '${raw}'. Use 'streaming', 'restart', 'active_steering', or 'interrupt_restart'.`,
`Unsupported Claude replay query mode '${raw}'. Use 'streaming', 'restart', 'active_steering', 'interrupt', or 'interrupt_restart'.`,
);
}
@@ -253,6 +282,7 @@ try {
? {}
: { allowDangerouslySkipPermissions: queryPolicy.allowDangerouslySkipPermissions }),
...(queryPolicy.installPermissionCallback ? { enablePermissionCallback: true } : {}),
...("interruptAfter" in recording ? { interruptAfter: recording.interruptAfter } : {}),
});
await mkdir(path.dirname(outputPath), { recursive: true });
await writeFile(outputPath, encodeTranscriptNdjson(transcript), "utf8");
@@ -23,6 +23,7 @@ import {
THREAD_ROLLBACK_SECOND_PROMPT,
TODO_LIST_PROMPT,
TOOL_CALL_WRITE_PROMPT,
TURN_INTERRUPT_MID_TOOL_PROMPT,
TURN_INTERRUPT_PROMPT,
} from "../src/orchestration-v2/testkit/fixtures/shared.ts";
@@ -51,6 +52,7 @@ const SCENARIO_NAMES = [
"proposed_plan",
"message_steering",
"turn_interrupt",
"turn_interrupt_mid_tool",
"thread_rollback",
] as const;
@@ -89,7 +91,8 @@ type ReplayStep =
readonly type: "interruptedTurn";
readonly label: string;
readonly prompt: string;
readonly interruptAfterMs: number;
readonly interruptAfterMs?: number;
readonly interruptAfterCommandExecutionStarted?: boolean;
readonly turnOverrides?: Omit<TurnStartParams, "input" | "threadId">;
}
| {
@@ -527,6 +530,31 @@ function scenarios(): ReadonlyArray<ReplayScenario> {
},
],
},
{
name: "turn_interrupt_mid_tool",
fileName: "turn_interrupt_mid_tool.ndjson",
description:
"One active turn is interrupted after Codex has already executed a local command.",
runs: [
{
name: "interrupt-after-command-execution",
description: "Start a turn, wait for command execution, then send turn/interrupt.",
prompt: TURN_INTERRUPT_MID_TOOL_PROMPT,
turnDefaults: {
approvalPolicy: "never",
sandboxPolicy: workspaceWriteSandbox(),
},
steps: [
{
type: "interruptedTurn",
label: "interrupt-after-command-execution",
prompt: TURN_INTERRUPT_MID_TOOL_PROMPT,
interruptAfterCommandExecutionStarted: true,
},
],
},
],
},
{
name: "thread_rollback",
fileName: "thread_rollback.ndjson",
@@ -679,11 +707,13 @@ function installReplayHandlers({
client,
startTurn,
completeTurn,
startCommandExecution,
beforeApprovalResponse,
}: {
readonly client: CodexClient.CodexAppServerClientShape;
readonly startTurn: (turnId: string) => Effect.Effect<void>;
readonly completeTurn: (turnId: string) => Effect.Effect<void>;
readonly startCommandExecution: (turnId: string) => Effect.Effect<void>;
readonly beforeApprovalResponse: () => Effect.Effect<void>;
}) {
return Effect.all(
@@ -746,6 +776,16 @@ function installReplayHandlers({
client.handleServerNotification("turn/completed", (payload) =>
completeTurn(payload.turn.id).pipe(Effect.ignore),
),
client.handleServerNotification("item/completed", (payload) =>
isRecord(payload.item) && payload.item.type === "commandExecution"
? startCommandExecution(payload.turnId).pipe(Effect.ignore)
: Effect.void,
),
client.handleServerNotification("item/started", (payload) =>
isRecord(payload.item) && payload.item.type === "commandExecution"
? startCommandExecution(payload.turnId).pipe(Effect.ignore)
: Effect.void,
),
],
{ discard: true },
);
@@ -763,6 +803,7 @@ function runReplaySession({
return Effect.gen(function* () {
const startedTurns = new Map<string, Deferred.Deferred<void>>();
const completedTurns = new Map<string, Deferred.Deferred<void>>();
const startedCommandExecutions = new Map<string, Deferred.Deferred<void>>();
let approvalGate: Deferred.Deferred<void> | undefined;
const getStarted = (turnId: string) => {
const existing = startedTurns.get(turnId);
@@ -782,17 +823,36 @@ function runReplaySession({
Effect.tap((deferred) => Effect.sync(() => completedTurns.set(turnId, deferred))),
);
};
const getCommandExecutionStarted = (turnId: string) => {
const existing = startedCommandExecutions.get(turnId);
if (existing) {
return Effect.succeed(existing);
}
return Deferred.make<void>().pipe(
Effect.tap((deferred) => Effect.sync(() => startedCommandExecutions.set(turnId, deferred))),
);
};
const startTurn = (turnId: string) =>
getStarted(turnId).pipe(Effect.flatMap((deferred) => Deferred.succeed(deferred, void 0)));
const completeTurn = (turnId: string) =>
getCompletion(turnId).pipe(Effect.flatMap((deferred) => Deferred.succeed(deferred, void 0)));
const startCommandExecution = (turnId: string) =>
getCommandExecutionStarted(turnId).pipe(
Effect.flatMap((deferred) => Deferred.succeed(deferred, void 0)),
);
const beforeApprovalResponse = () =>
approvalGate ? Deferred.await(approvalGate) : Effect.void;
const initializeClient = Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;
yield* installReplayHandlers({ client, startTurn, completeTurn, beforeApprovalResponse });
yield* installReplayHandlers({
client,
startTurn,
completeTurn,
startCommandExecution,
beforeApprovalResponse,
});
yield* client.request("initialize", {
clientInfo: CODEX_CLIENT_INFO,
@@ -840,7 +900,12 @@ function runReplaySession({
}
if (step.type === "interruptedTurn") {
yield* Effect.sleep(`${step.interruptAfterMs} millis`);
if (step.interruptAfterCommandExecutionStarted === true) {
const commandExecutionStarted = yield* getCommandExecutionStarted(turnId);
yield* Deferred.await(commandExecutionStarted);
} else {
yield* Effect.sleep(`${step.interruptAfterMs ?? 1_500} millis`);
}
yield* client.request("turn/interrupt", {
threadId,
turnId,
@@ -1,9 +1,16 @@
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
import {
CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
CLAUDE_READ_ONLY_ALLOWED_TOOLS,
claudeRuntimeQueryPolicyForRuntimePolicy,
loggedClaudeQueryOptions,
makeClaudeAgentSdkProtocolLogger,
type ClaudeAgentSdkQueryOptions,
} from "./ClaudeAdapterV2.ts";
describe("ClaudeAdapterV2 runtime query policy", () => {
@@ -93,3 +100,104 @@ describe("ClaudeAdapterV2 runtime query policy", () => {
});
});
});
describe("ClaudeAdapterV2 native protocol logging", () => {
it.effect("writes Claude Agent SDK protocol frames to the native provider log", () =>
Effect.gen(function* () {
const writes: Array<{
readonly event: unknown;
readonly threadId: ThreadId | null;
}> = [];
const logger: EventNdjsonLogger = {
filePath: "/tmp/events.log",
write: (event, threadId) =>
Effect.sync(() => {
writes.push({ event, threadId });
}),
close: () => Effect.void,
};
const threadId = ThreadId.make("thread-1");
const providerSessionId = ProviderSessionId.make("provider-session-1");
const protocolLogger = makeClaudeAgentSdkProtocolLogger({
nativeEventLogger: logger,
threadId,
providerSessionId,
});
assert.notEqual(protocolLogger, undefined);
if (protocolLogger === undefined) {
return;
}
yield* protocolLogger({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.interrupt",
},
});
assert.equal(writes.length, 1);
assert.equal(writes[0]?.threadId, threadId);
assert.deepEqual(writes[0]?.event, {
provider: "claudeAgent",
protocol: CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
kind: "protocol",
providerSessionId,
event: {
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.interrupt",
},
},
});
}),
);
it("does not install a protocol logger when native logging is unavailable", () => {
const protocolLogger = makeClaudeAgentSdkProtocolLogger({
nativeEventLogger: undefined,
threadId: ThreadId.make("thread-1"),
providerSessionId: ProviderSessionId.make("provider-session-1"),
});
assert.equal(protocolLogger, undefined);
});
it("logs query options without leaking environment values or callback functions", () => {
const options: ClaudeAgentSdkQueryOptions = {
model: "claude-sonnet-4-6",
tools: {
type: "preset",
preset: "claude_code",
},
permissionMode: "default",
sessionId: "native-thread-1",
cwd: "/workspace",
env: {
ANTHROPIC_API_KEY: "secret",
},
canUseTool: (_toolName, input, callbackOptions) =>
Promise.resolve({
behavior: "allow",
updatedInput: input,
toolUseID: callbackOptions.toolUseID,
decisionClassification: "user_temporary",
}),
};
assert.deepEqual(loggedClaudeQueryOptions(options), {
model: "claude-sonnet-4-6",
tools: {
type: "preset",
preset: "claude_code",
},
permissionMode: "default",
sessionId: "native-thread-1",
cwd: "/workspace",
hasCanUseTool: true,
hasEnvironment: true,
});
});
});
@@ -305,7 +305,9 @@ function stableClaudeQueryOptions(options: ClaudeAgentSdkQueryOptions): ClaudeAg
: { ...stable, resume: options.resume };
}
function makeClaudeQueryOpenFrame(input: ClaudeAgentSdkQueryOpenInput): ClaudeQueryOpenFrame {
function makeClaudeQueryOpenFrame(
input: Pick<ClaudeAgentSdkQueryOpenInput, "options">,
): ClaudeQueryOpenFrame {
return {
type: "query.open",
options: stableClaudeQueryOptions(input.options),
@@ -835,26 +837,37 @@ async function recordMessagesUntilIteratorDone(input: {
}
}
async function recordFirstInboundMessage(input: {
function sdkMessageHasToolUse(message: SDKMessage): boolean {
return (
message.type === "assistant" && message.message.content.some((part) => part.type === "tool_use")
);
}
async function recordMessagesUntilFirstToolUse(input: {
readonly iterator: AsyncIterator<SDKMessage>;
readonly entries: Array<ProviderReplayEntry>;
readonly scenario: string;
}): Promise<void> {
const next = await input.iterator.next();
if (next.done === true) {
throw new Error(`Claude query ended before ${input.scenario} could be interrupted.`);
}
const replayMessage = sanitizeSdkMessageForReplay({
message: next.value,
scenario: input.scenario,
});
input.entries.push({
type: "emit_inbound",
label: replayMessage.type,
frame: replayMessage,
});
if (replayMessage.type === "result") {
throw new Error(`Claude query completed before ${input.scenario} could be interrupted.`);
while (true) {
const next = await input.iterator.next();
if (next.done === true) {
throw new Error(`Claude query ended before ${input.scenario} started a tool use.`);
}
const replayMessage = sanitizeSdkMessageForReplay({
message: next.value,
scenario: input.scenario,
});
input.entries.push({
type: "emit_inbound",
label: replayMessage.type,
frame: replayMessage,
});
if (replayMessage.type === "result") {
throw new Error(`Claude query completed before ${input.scenario} started a tool use.`);
}
if (sdkMessageHasToolUse(replayMessage)) {
return;
}
}
}
@@ -1192,13 +1205,18 @@ async function recordClaudeRestartingQueries(input: {
}
}
async function recordClaudeInterruptRestartQuery(input: {
async function recordInterruptedClaudeQuery(input: {
readonly scenario: string;
readonly prompts: ReadonlyArray<string>;
readonly prompt: string;
readonly modelSelection: ModelSelection;
readonly cwd: string;
readonly sessionId: string;
readonly resume: boolean;
readonly entries: Array<ProviderReplayEntry>;
readonly queryOpenLabel: string;
readonly promptOfferLabel: string;
readonly interruptLabel: string;
readonly interruptAfter?: "prompt_offer" | "tool_use";
readonly enableTools?: boolean;
readonly tools?: ClaudeAgentSdkQueryTools;
readonly permissionMode?: ClaudeAgentSdkQueryOptions["permissionMode"];
@@ -1206,17 +1224,11 @@ async function recordClaudeInterruptRestartQuery(input: {
readonly disallowedTools?: ReadonlyArray<string>;
readonly allowDangerouslySkipPermissions?: boolean;
}): Promise<void> {
if (input.prompts.length !== 2) {
throw new Error(
`Claude interrupt-restart replay scenario ${input.scenario} requires exactly two prompts.`,
);
}
const firstPromptQueue = new RecordingPromptQueue();
const firstOptions = makeClaudeQueryOptions({
const promptQueue = new RecordingPromptQueue();
const options = makeClaudeQueryOptions({
modelSelection: input.modelSelection,
nativeThreadId: input.sessionId,
resume: false,
resume: input.resume,
cwd: input.cwd,
...(input.enableTools === true
? {
@@ -1234,49 +1246,53 @@ async function recordClaudeInterruptRestartQuery(input: {
});
input.entries.push({
type: "expect_outbound",
label: "query.open:1",
frame: makeClaudeQueryOpenFrame({ options: firstOptions }),
label: input.queryOpenLabel,
frame: makeClaudeQueryOpenFrame({ options }),
});
const firstRuntime = query({
prompt: firstPromptQueue,
options: firstOptions,
const runtime = query({
prompt: promptQueue,
options,
});
const firstIterator = firstRuntime[Symbol.asyncIterator]();
const firstMessage = makeClaudeUserMessage({ text: input.prompts[0]! });
const iterator = runtime[Symbol.asyncIterator]();
const message = makeClaudeUserMessage({ text: input.prompt });
input.entries.push({
type: "expect_outbound",
label: "prompt.offer:1",
frame: makeClaudePromptOfferFrame(firstMessage),
});
firstPromptQueue.offer(firstMessage);
await recordFirstInboundMessage({
iterator: firstIterator,
entries: input.entries,
scenario: input.scenario,
label: input.promptOfferLabel,
frame: makeClaudePromptOfferFrame(message),
});
promptQueue.offer(message);
if (input.interruptAfter === "tool_use") {
await recordMessagesUntilFirstToolUse({
iterator,
entries: input.entries,
scenario: input.scenario,
});
await new Promise((resolve) => setTimeout(resolve, 250));
}
input.entries.push({
type: "expect_outbound",
label: "query.interrupt:1",
label: input.interruptLabel,
frame: { type: "query.interrupt" },
});
try {
let cancelledError: unknown;
try {
await firstRuntime.interrupt();
await runtime.interrupt();
} catch (error) {
cancelledError = error;
}
firstPromptQueue.close();
promptQueue.close();
runtime.close();
try {
await recordMessagesUntilIteratorDone({
iterator: firstIterator,
iterator,
entries: input.entries,
scenario: input.scenario,
});
} catch (error) {
cancelledError = error;
}
firstRuntime.close();
input.entries.push({
type: "runtime_exit",
status: cancelledError === undefined ? "success" : "cancelled",
@@ -1285,7 +1301,8 @@ async function recordClaudeInterruptRestartQuery(input: {
: { error: serializeReplayError(cancelledError, input.scenario) }),
});
} catch (error) {
firstPromptQueue.close();
promptQueue.close();
runtime.close();
input.entries.push({
type: "runtime_exit",
status: "error",
@@ -1293,6 +1310,94 @@ async function recordClaudeInterruptRestartQuery(input: {
});
throw error;
}
}
async function recordClaudeInterruptQuery(input: {
readonly scenario: string;
readonly prompts: ReadonlyArray<string>;
readonly modelSelection: ModelSelection;
readonly cwd: string;
readonly sessionId: string;
readonly entries: Array<ProviderReplayEntry>;
readonly enableTools?: boolean;
readonly tools?: ClaudeAgentSdkQueryTools;
readonly permissionMode?: ClaudeAgentSdkQueryOptions["permissionMode"];
readonly allowedTools?: ReadonlyArray<string>;
readonly disallowedTools?: ReadonlyArray<string>;
readonly allowDangerouslySkipPermissions?: boolean;
readonly interruptAfter?: "prompt_offer" | "tool_use";
}): Promise<void> {
if (input.prompts.length !== 1) {
throw new Error(
`Claude interrupt replay scenario ${input.scenario} requires exactly one prompt.`,
);
}
await recordInterruptedClaudeQuery({
scenario: input.scenario,
prompt: input.prompts[0]!,
modelSelection: input.modelSelection,
cwd: input.cwd,
sessionId: input.sessionId,
resume: false,
entries: input.entries,
queryOpenLabel: "query.open",
promptOfferLabel: "prompt.offer:1",
interruptLabel: "query.interrupt:1",
...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }),
...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }),
...(input.tools === undefined ? {} : { tools: input.tools }),
...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }),
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }),
...(input.allowDangerouslySkipPermissions === undefined
? {}
: { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }),
});
}
async function recordClaudeInterruptRestartQuery(input: {
readonly scenario: string;
readonly prompts: ReadonlyArray<string>;
readonly modelSelection: ModelSelection;
readonly cwd: string;
readonly sessionId: string;
readonly entries: Array<ProviderReplayEntry>;
readonly enableTools?: boolean;
readonly tools?: ClaudeAgentSdkQueryTools;
readonly permissionMode?: ClaudeAgentSdkQueryOptions["permissionMode"];
readonly allowedTools?: ReadonlyArray<string>;
readonly disallowedTools?: ReadonlyArray<string>;
readonly allowDangerouslySkipPermissions?: boolean;
readonly interruptAfter?: "prompt_offer" | "tool_use";
}): Promise<void> {
if (input.prompts.length !== 2) {
throw new Error(
`Claude interrupt-restart replay scenario ${input.scenario} requires exactly two prompts.`,
);
}
await recordInterruptedClaudeQuery({
scenario: input.scenario,
prompt: input.prompts[0]!,
modelSelection: input.modelSelection,
cwd: input.cwd,
sessionId: input.sessionId,
resume: false,
entries: input.entries,
queryOpenLabel: "query.open:1",
promptOfferLabel: "prompt.offer:1",
interruptLabel: "query.interrupt:1",
...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }),
...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }),
...(input.tools === undefined ? {} : { tools: input.tools }),
...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }),
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }),
...(input.allowDangerouslySkipPermissions === undefined
? {}
: { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }),
});
const secondPromptQueue = new RecordingPromptQueue();
const secondOptions = makeClaudeQueryOptions({
@@ -1361,7 +1466,12 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
readonly modelSelection: ModelSelection;
readonly cwd: string;
readonly sessionId?: string;
readonly queryMode?: "streaming" | "restart" | "active_steering" | "interrupt_restart";
readonly queryMode?:
| "streaming"
| "restart"
| "active_steering"
| "interrupt"
| "interrupt_restart";
readonly enableTools?: boolean;
readonly tools?: ClaudeAgentSdkQueryTools;
readonly permissionMode?: ClaudeAgentSdkQueryOptions["permissionMode"];
@@ -1370,6 +1480,7 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
readonly allowDangerouslySkipPermissions?: boolean;
readonly enablePermissionCallback?: boolean;
readonly permissionDecision?: ProviderApprovalDecision;
readonly interruptAfter?: "prompt_offer" | "tool_use";
}): Promise<ClaudeAgentSdkReplayTranscript> {
if (input.prompts.length === 0) {
throw new Error(
@@ -1443,6 +1554,24 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
? {}
: { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }),
});
} else if (queryMode === "interrupt") {
await recordClaudeInterruptQuery({
scenario: input.scenario,
prompts: input.prompts,
modelSelection: input.modelSelection,
cwd: input.cwd,
sessionId,
entries,
...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }),
...(input.tools === undefined ? {} : { tools: input.tools }),
...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }),
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }),
...(input.allowDangerouslySkipPermissions === undefined
? {}
: { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }),
...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }),
});
} else {
await recordClaudeInterruptRestartQuery({
scenario: input.scenario,
@@ -1459,6 +1588,7 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
...(input.allowDangerouslySkipPermissions === undefined
? {}
: { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }),
...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }),
});
}
@@ -1482,6 +1612,7 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
...(input.permissionDecision === undefined
? {}
: { permissionDecision: input.permissionDecision }),
...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }),
generatedBy: "recordClaudeAgentSdkReplayTranscript",
},
entries,
@@ -28,6 +28,7 @@ import {
ProviderDriverKind,
type ProviderInstanceId,
type ProviderRequestKind,
type ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
@@ -45,6 +46,13 @@ import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ServerConfig } from "../../config.ts";
import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts";
import {
type EventNdjsonLogger,
makeEventNdjsonLogger,
} from "../../provider/Layers/EventNdjsonLogger.ts";
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts";
import {
ProviderAdapterEnsureThreadError,
@@ -76,6 +84,9 @@ import {
} from "../ProviderAdapterDriver.ts";
export const CLAUDE_PROVIDER = "claudeAgent" as const;
export const CLAUDE_AGENT_SDK_QUERY_PROTOCOL = "claude-agent-sdk.query" as const;
export const CLAUDE_DRIVER_KIND = ProviderDriverKind.make(CLAUDE_PROVIDER);
export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_DRIVER_KIND);
export const ClaudeProviderCapabilitiesV2 = {
sessions: {
@@ -218,6 +229,8 @@ export type ClaudeAgentSdkQueryOptions = Omit<
export interface ClaudeAgentSdkQueryOpenInput {
readonly options: ClaudeAgentSdkQueryOptions;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}
export interface ClaudeAgentSdkQuerySession {
@@ -268,14 +281,146 @@ function closeClaudeQuery(queryRuntime: ClaudeQuery) {
});
}
export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<ClaudeAgentSdkQueryRunner> =
Layer.succeed(
ClaudeAgentSdkQueryRunner,
ClaudeAgentSdkQueryRunner.of({
export interface ClaudeAgentSdkLoggedQueryOptions {
readonly model: ClaudeAgentSdkQueryOptions["model"];
readonly tools: ClaudeAgentSdkQueryOptions["tools"];
readonly permissionMode: ClaudeAgentSdkQueryOptions["permissionMode"];
readonly sessionId?: string;
readonly resume?: string;
readonly cwd?: ClaudeAgentSdkQueryOptions["cwd"];
readonly allowedTools?: ClaudeAgentSdkQueryOptions["allowedTools"];
readonly disallowedTools?: ClaudeAgentSdkQueryOptions["disallowedTools"];
readonly settings?: ClaudeAgentSdkQueryOptions["settings"];
readonly pathToClaudeCodeExecutable?: ClaudeAgentSdkQueryOptions["pathToClaudeCodeExecutable"];
readonly extraArgs?: ClaudeAgentSdkQueryOptions["extraArgs"];
readonly allowDangerouslySkipPermissions?: true;
readonly hasCanUseTool?: true;
readonly hasEnvironment?: true;
}
export type ClaudeAgentSdkProtocolLogEvent =
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.open";
readonly options: ClaudeAgentSdkLoggedQueryOptions;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "prompt.offer";
readonly message: SDKUserMessage;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.set_model";
readonly model: string;
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.interrupt";
};
}
| {
readonly direction: "outgoing";
readonly stage: "decoded";
readonly payload: {
readonly type: "query.close";
};
}
| {
readonly direction: "incoming";
readonly stage: "decoded";
readonly payload: SDKMessage;
};
export type ClaudeAgentSdkProtocolLogger = (
event: ClaudeAgentSdkProtocolLogEvent,
) => Effect.Effect<void>;
export function loggedClaudeQueryOptions(
options: ClaudeAgentSdkQueryOptions,
): ClaudeAgentSdkLoggedQueryOptions {
return {
model: options.model,
tools: options.tools,
permissionMode: options.permissionMode,
...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),
...(options.resume === undefined ? {} : { resume: options.resume }),
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
...(options.settings === undefined ? {} : { settings: options.settings }),
...(options.pathToClaudeCodeExecutable === undefined
? {}
: { pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable }),
...(options.extraArgs === undefined ? {} : { extraArgs: options.extraArgs }),
...(options.allowDangerouslySkipPermissions === true
? { allowDangerouslySkipPermissions: true }
: {}),
...(options.canUseTool === undefined ? {} : { hasCanUseTool: true }),
...(options.env === undefined ? {} : { hasEnvironment: true }),
};
}
export function makeClaudeAgentSdkProtocolLogger(input: {
readonly nativeEventLogger: EventNdjsonLogger | undefined;
readonly threadId: ThreadId;
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
}): ClaudeAgentSdkProtocolLogger | undefined {
const { nativeEventLogger } = input;
if (nativeEventLogger === undefined) {
return undefined;
}
return (event) =>
nativeEventLogger
.write(
{
provider: CLAUDE_PROVIDER,
protocol: CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
kind: "protocol",
providerSessionId: input.providerSessionId,
event,
},
input.threadId,
)
.pipe(Effect.ignore);
}
export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<
ClaudeAgentSdkQueryRunner,
never,
ServerConfig
> = Layer.effect(
ClaudeAgentSdkQueryRunner,
Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
return ClaudeAgentSdkQueryRunner.of({
allocateSessionId: Random.nextUUIDv4,
open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(function* (
input: ClaudeAgentSdkQueryOpenInput,
) {
const protocolLogger = makeClaudeAgentSdkProtocolLogger({
nativeEventLogger,
threadId: input.threadId,
providerSessionId: input.providerSessionId,
});
const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
protocolLogger === undefined ? Effect.void : protocolLogger(event);
const promptQueue = yield* Queue.unbounded<SDKUserMessage>();
const prompt = Stream.fromQueue(promptQueue).pipe(
Stream.catchCause((cause) =>
@@ -291,27 +436,89 @@ export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<ClaudeAgentSdkQuery
}),
catch: (cause) => queryRunnerError(cause, "query"),
});
yield* logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.open",
options: loggedClaudeQueryOptions(input.options),
},
});
return {
messages: Stream.fromAsyncIterable(queryRuntime, (cause) =>
queryRunnerError(cause, "fromAsyncIterable"),
).pipe(
Stream.tap((message) =>
logProtocolEvent({
direction: "incoming",
stage: "decoded",
payload: message,
}),
),
),
offer: (message) => Queue.offer(promptQueue, message).pipe(Effect.asVoid),
offer: (message) =>
Queue.offer(promptQueue, message).pipe(
Effect.asVoid,
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "prompt.offer",
message,
},
}),
),
),
setModel: (model) =>
Effect.tryPromise({
try: () => queryRuntime.setModel(model),
catch: (cause) => queryRunnerError(cause, "setModel"),
}),
}).pipe(
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.set_model",
model,
},
}),
),
),
interrupt: Effect.tryPromise({
try: () => queryRuntime.interrupt(),
catch: (cause) => queryRunnerError(cause, "interupt"),
}),
close: Queue.shutdown(promptQueue).pipe(Effect.andThen(closeClaudeQuery(queryRuntime))),
catch: (cause) => queryRunnerError(cause, "interrupt"),
}).pipe(
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.interrupt",
},
}),
),
),
close: Queue.shutdown(promptQueue).pipe(
Effect.andThen(closeClaudeQuery(queryRuntime)),
Effect.tap(() =>
logProtocolEvent({
direction: "outgoing",
stage: "decoded",
payload: {
type: "query.close",
},
}),
),
),
} satisfies ClaudeAgentSdkQuerySession;
}),
assertComplete: Effect.void,
}),
);
});
}),
);
export function makeClaudeQueryOptions(input: {
readonly modelSelection: ModelSelection;
@@ -1871,6 +2078,8 @@ export function makeClaudeAdapterV2(
return [false, updated];
});
const querySession = yield* queryRunner.open({
threadId: turnInput.threadId,
providerSessionId: input.providerSessionId,
options: makeClaudeQueryOptions({
modelSelection: turnInput.modelSelection,
nativeThreadId,
@@ -1455,10 +1455,799 @@ export const layer: Layer.Layer<
}),
);
yield* client.handleServerNotification("item/plan/delta", (payload) =>
Effect.gen(function* () {
const context = (yield* Ref.get(activeTurns)).get(payload.turnId);
if (context === undefined) {
const resolveCodexAttachment = (attachment: ChatAttachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (attachmentPath === null) {
return yield* toProtocolError(`Invalid attachment id '${attachment.id}'`);
}
const bytes = yield* fileSystem
.readFile(attachmentPath)
.pipe(
Effect.mapError((cause) =>
toProtocolError(`Failed to read attachment '${attachment.id}'.`, cause),
),
);
return {
type: "image" as const,
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
} satisfies CodexSchema.V2TurnStartParams__UserInput;
});
const toCodexInput = (
turnInput: Pick<ProviderAdapterV2TurnInput | ProviderAdapterV2SteerInput, "message">,
) =>
Effect.gen(function* () {
const inputItems: Array<CodexSchema.V2TurnStartParams__UserInput> = [];
if (turnInput.message.text.length > 0) {
inputItems.push({
type: "text",
text: turnInput.message.text,
});
}
const attachmentItems = yield* Effect.forEach(
turnInput.message.attachments,
resolveCodexAttachment,
{ concurrency: 1 },
);
inputItems.push(...attachmentItems);
if (inputItems.length === 0) {
return yield* toProtocolError("Turn requires non-empty text or attachments.");
}
return inputItems;
});
const buildAgentMessageArtifacts = (
context: ActiveCodexTurnContext,
item: Extract<
CodexSchema.V2ItemCompletedNotification__ThreadItem,
{ type: "agentMessage" }
>,
) =>
Effect.gen(function* () {
const completedAt = yield* DateTime.now;
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
});
const ordinal = yield* resolveItemOrdinal(context, item.id);
const messageId = idAllocator.derive.messageFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
});
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.input.threadId,
runId: context.input.runId,
parentNodeId: context.itemParentNodeId,
rootNodeId: context.rootNodeId,
kind: "assistant_message",
status: "completed",
countsForRun: false,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: context.startedAt,
completedAt,
};
const message: OrchestrationV2ConversationMessage = {
id: messageId,
threadId: context.input.threadId,
runId: context.input.runId,
nodeId,
role: "assistant",
text: item.text,
attachments: [],
streaming: false,
createdAt: completedAt,
updatedAt: completedAt,
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: context.input.threadId,
runId: context.input.runId,
nodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
parentItemId: null,
ordinal,
status: "completed",
title: null,
startedAt: context.startedAt,
completedAt,
updatedAt: completedAt,
type: "assistant_message",
messageId,
text: item.text,
streaming: false,
};
return { node, message, turnItem };
});
const buildCommandExecutionArtifacts = (
context: ActiveCodexTurnContext,
item: Extract<
| CodexSchema.V2ItemStartedNotification__ThreadItem
| CodexSchema.V2ItemCompletedNotification__ThreadItem,
{ type: "commandExecution" }
>,
) =>
Effect.gen(function* () {
const updatedAt = yield* DateTime.now;
const status = codexItemStatus(item.status);
const completedAt = status.completed ? updatedAt : null;
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
});
const ordinal = yield* resolveItemOrdinal(context, item.id);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.input.threadId,
runId: context.input.runId,
parentNodeId: context.itemParentNodeId,
rootNodeId: context.rootNodeId,
kind: "tool_call",
status: status.node,
countsForRun: false,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: context.startedAt,
completedAt,
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: context.input.threadId,
runId: context.input.runId,
nodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
parentItemId: null,
ordinal,
status: status.turnItem,
title: null,
startedAt: context.startedAt,
completedAt,
updatedAt,
type: "command_execution",
input: item.command,
...(item.aggregatedOutput === null || item.aggregatedOutput === undefined
? {}
: { output: item.aggregatedOutput }),
...(item.exitCode === null || item.exitCode === undefined
? {}
: { exitCode: item.exitCode }),
};
return { node, turnItem };
});
const buildFileChangeArtifacts = (
context: ActiveCodexTurnContext,
item: Extract<
CodexSchema.V2ItemCompletedNotification__ThreadItem,
{ type: "fileChange" }
>,
) =>
Effect.gen(function* () {
const firstChange = item.changes[0];
if (firstChange === undefined) {
return null;
}
const updatedAt = yield* DateTime.now;
const status = codexItemStatus(item.status);
const completedAt = status.completed ? updatedAt : null;
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
});
const ordinal = yield* resolveItemOrdinal(context, item.id);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.input.threadId,
runId: context.input.runId,
parentNodeId: context.itemParentNodeId,
rootNodeId: context.rootNodeId,
kind: "tool_call",
status: status.node,
countsForRun: false,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: context.startedAt,
completedAt,
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: context.input.threadId,
runId: context.input.runId,
nodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
parentItemId: null,
ordinal,
status: status.turnItem,
title: null,
startedAt: context.startedAt,
completedAt,
updatedAt,
type: "file_change",
fileName: firstChange.path,
diffStr: firstChange.diff,
};
return { node, turnItem };
});
const buildWebSearchArtifacts = (input: {
readonly context: ActiveCodexTurnContext;
readonly item: CodexWebSearchItem;
readonly completed: boolean;
}) =>
Effect.gen(function* () {
const updatedAt = yield* DateTime.now;
const completedAt = input.completed ? updatedAt : null;
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: input.item.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: input.item.id,
});
const ordinal = yield* resolveItemOrdinal(input.context, input.item.id);
const patterns = webSearchPatterns(input.item);
const status = input.completed ? "completed" : "running";
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
parentNodeId: input.context.itemParentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "tool_call",
status,
countsForRun: false,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.item.id),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: input.context.startedAt,
completedAt,
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.item.id),
parentItemId: null,
ordinal,
status,
title: null,
startedAt: input.context.startedAt,
completedAt,
updatedAt,
type: "web_search",
...(patterns.length === 0 ? {} : { patterns: [...patterns] }),
};
return { node, turnItem };
});
const buildProposedPlanArtifacts = (input: {
readonly context: ActiveCodexTurnContext;
readonly nativeItemId: string;
readonly status: OrchestrationV2PlanArtifact["status"];
readonly markdown: string;
readonly completed?: boolean;
}) =>
Effect.gen(function* () {
const updatedAt = yield* DateTime.now;
const completedAt = input.completed === true ? updatedAt : null;
const planId = yield* resolvePlanId(input.context, input.nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: input.nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: input.nativeItemId,
});
const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
const plan: OrchestrationV2PlanArtifact = {
id: planId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
nodeId,
kind: "proposed_plan",
status: input.status,
markdown: input.markdown,
};
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
parentNodeId: input.context.itemParentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "plan",
status: input.completed === true ? "completed" : "running",
countsForRun: false,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.nativeItemId),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: input.context.startedAt,
completedAt,
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.nativeItemId),
parentItemId: null,
ordinal,
status: input.completed === true ? "completed" : "running",
title: null,
startedAt: input.context.startedAt,
completedAt,
updatedAt,
type: "proposed_plan",
planId,
markdown: input.markdown,
streaming: input.completed !== true,
};
return { node, plan, turnItem };
});
const buildTodoListArtifacts = (input: {
readonly context: ActiveCodexTurnContext;
readonly nativeItemId: string;
readonly status: OrchestrationV2PlanArtifact["status"];
readonly steps: ReadonlyArray<OrchestrationV2PlanStep>;
readonly explanation?: string;
readonly completed?: boolean;
}) =>
Effect.gen(function* () {
const updatedAt = yield* DateTime.now;
const completedAt = input.completed === true ? updatedAt : null;
const planId = yield* resolvePlanId(input.context, input.nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: input.nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: input.nativeItemId,
});
const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
const plan: OrchestrationV2PlanArtifact = {
id: planId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
nodeId,
kind: "todo_list",
status: input.status,
steps: [...input.steps],
...(input.explanation === undefined ? {} : { explanation: input.explanation }),
};
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
parentNodeId: input.context.itemParentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "todo_list",
status: input.completed === true ? "completed" : "running",
countsForRun: false,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.nativeItemId),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: input.context.startedAt,
completedAt,
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.nativeItemId),
parentItemId: null,
ordinal,
status: input.completed === true ? "completed" : "running",
title: null,
startedAt: input.context.startedAt,
completedAt,
updatedAt,
type: "todo_list",
planId,
steps: [...input.steps],
...(input.explanation === undefined ? {} : { explanation: input.explanation }),
};
return { node, plan, turnItem };
});
const buildApprovalRequestArtifacts = (input: {
readonly context: ActiveCodexTurnContext;
readonly nativeItemId: string;
readonly nativeRequestId: string;
readonly requestKind: ProviderRequestKind;
readonly prompt?: string | null;
}) =>
Effect.gen(function* () {
const createdAt = yield* DateTime.now;
const parentNodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: input.nativeItemId,
});
const ordinal = yield* resolveItemOrdinal(
input.context,
`${input.nativeItemId}:approval:${input.nativeRequestId}`,
);
const requestId = yield* idAllocator.allocate.runtimeRequest({
provider: CODEX_PROVIDER,
providerTurnId: input.context.providerTurnId,
nativeRequestId: input.nativeRequestId,
});
const nodeId = idAllocator.derive.approvalNode({ requestId });
const providerSessionId = input.context.input.providerThread.providerSessionId;
if (providerSessionId === null) {
return yield* toProtocolError(
`Provider thread ${input.context.providerThread.id} is missing a provider session id.`,
);
}
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
parentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "approval_request",
status: "waiting",
countsForRun: false,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.nativeItemId),
runtimeRequestId: requestId,
checkpointScopeId: null,
startedAt: createdAt,
completedAt: null,
};
const request: OrchestrationV2RuntimeRequest = {
id: requestId,
nodeId,
providerTurnId: input.context.providerTurnId,
nativeRequestRef: {
provider: CODEX_PROVIDER,
nativeId: input.nativeRequestId,
strength: "strong",
},
kind: input.requestKind,
status: "pending",
responseCapability: {
type: "live",
providerSessionId,
},
createdAt,
resolvedAt: null,
};
const turnItem: OrchestrationV2TurnItem = {
id: idAllocator.derive.approvalTurnItem({ requestId }),
threadId: input.context.input.threadId,
runId: input.context.input.runId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.nativeItemId),
parentItemId: null,
ordinal,
status: "waiting",
title: null,
startedAt: createdAt,
completedAt: null,
updatedAt: createdAt,
type: "approval_request",
requestId,
requestKind: input.requestKind,
...(input.prompt === null || input.prompt === undefined
? {}
: { prompt: input.prompt }),
};
return { node, request, turnItem };
});
const buildUserInputRequestArtifacts = (input: {
readonly context: ActiveCodexTurnContext;
readonly nativeItemId: string;
readonly nativeRequestId: string;
readonly questions: ReadonlyArray<CodexSchema.ToolRequestUserInputParams__ToolRequestUserInputQuestion>;
}) =>
Effect.gen(function* () {
const createdAt = yield* DateTime.now;
const requestId = yield* idAllocator.allocate.runtimeRequest({
provider: CODEX_PROVIDER,
providerTurnId: input.context.providerTurnId,
nativeRequestId: input.nativeRequestId,
});
const providerSessionId = input.context.input.providerThread.providerSessionId;
if (providerSessionId === null) {
return yield* toProtocolError(
`Provider thread ${input.context.providerThread.id} is missing a provider session id.`,
);
}
const questions = input.questions.map((question, index) => ({
id: nonEmptyText(question.id, `question-${index + 1}`),
header: nonEmptyText(question.header, "Question"),
question: nonEmptyText(question.question, "Choose an answer."),
options:
question.options?.map((option, optionIndex) => ({
label: nonEmptyText(option.label, `Option ${optionIndex + 1}`),
description: nonEmptyText(option.description, option.label),
})) ?? [],
}));
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: input.nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: input.nativeItemId,
});
const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
parentNodeId: input.context.itemParentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "user_input_request",
status: "waiting",
countsForRun: false,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.nativeItemId),
runtimeRequestId: requestId,
checkpointScopeId: null,
startedAt: createdAt,
completedAt: null,
};
const request: OrchestrationV2RuntimeRequest = {
id: requestId,
nodeId,
providerTurnId: input.context.providerTurnId,
nativeRequestRef: {
provider: CODEX_PROVIDER,
nativeId: input.nativeRequestId,
strength: "strong",
},
kind: "user_input",
status: "pending",
responseCapability: {
type: "live",
providerSessionId,
},
createdAt,
resolvedAt: null,
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: codexNativeItemRef(input.nativeItemId),
parentItemId: null,
ordinal,
status: "waiting",
title: null,
startedAt: createdAt,
completedAt: null,
updatedAt: createdAt,
type: "user_input_request",
requestId,
questions,
};
return { node, request, turnItem };
});
yield* client.handleServerNotification("item/agentMessage/delta", (payload) =>
Ref.update(agentMessageDeltas, (current) => {
const updated = new Map(current);
updated.set(payload.itemId, `${updated.get(payload.itemId) ?? ""}${payload.delta}`);
return updated;
}),
);
yield* client.handleServerNotification("item/plan/delta", (payload) =>
Effect.gen(function* () {
const context = (yield* Ref.get(activeTurns)).get(payload.turnId);
if (context === undefined) {
return;
}
const markdown = yield* Ref.modify(planDeltas, (current) => {
const updated = new Map(current);
const next = `${updated.get(payload.itemId) ?? ""}${payload.delta}`;
updated.set(payload.itemId, next);
return [next, updated];
});
const artifacts = yield* buildProposedPlanArtifacts({
context,
nativeItemId: payload.itemId,
status: "active",
markdown,
});
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "plan.updated",
provider: CODEX_PROVIDER,
plan: artifacts.plan,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
}).pipe(Effect.orDie),
);
yield* client.handleServerNotification("turn/plan/updated", (payload) =>
Effect.gen(function* () {
const context = (yield* Ref.get(activeTurns)).get(payload.turnId);
if (context === undefined) {
return;
}
const steps = payload.plan.map((step, index) => ({
id: `step-${index + 1}`,
text: nonEmptyText(step.step, `Step ${index + 1}`),
status: codexPlanStepStatus(step.status),
}));
const explanation = trimText(payload.explanation);
const artifacts = yield* buildTodoListArtifacts({
context,
nativeItemId: `turn-plan:${payload.turnId}`,
status: "active",
...(explanation === undefined ? {} : { explanation }),
steps,
});
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "plan.updated",
provider: CODEX_PROVIDER,
plan: artifacts.plan,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
}).pipe(Effect.orDie),
);
yield* client.handleServerNotification("turn/started", (payload) =>
Effect.gen(function* () {
const context = (yield* Ref.get(activeTurns)).get(payload.turn.id);
if (context !== undefined) {
return;
}
yield* rememberSubagentTurnStarted({
nativeThreadId: payload.threadId,
nativeTurnId: payload.turn.id,
startedAt: codexTimestamp(payload.turn.startedAt),
});
}).pipe(Effect.orDie),
);
yield* client.handleServerNotification("item/started", (payload) =>
Effect.gen(function* () {
const context = (yield* Ref.get(activeTurns)).get(payload.turnId);
if (context === undefined) {
return;
}
if (payload.item.type === "commandExecution") {
const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item);
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return;
}
if (payload.item.type !== "webSearch") {
return;
}
const artifacts = yield* buildWebSearchArtifacts({
context,
item: payload.item,
completed: false,
});
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
}).pipe(Effect.orDie),
);
yield* client.handleServerNotification("item/completed", (payload) =>
Effect.gen(function* () {
const context = (yield* Ref.get(activeTurns)).get(payload.turnId);
if (context === undefined) {
return;
}
if (payload.item.type === "commandExecution") {
const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item);
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return;
}
if (payload.item.type === "fileChange") {
const artifacts = yield* buildFileChangeArtifacts(context, payload.item);
if (artifacts === null) {
return;
}
const markdown = yield* Ref.modify(planDeltas, (current) => {
@@ -135,6 +135,13 @@ const scenarioExpectations = {
turnCompletedCount: 1,
approvalRequestCount: 0,
},
turn_interrupt_mid_tool: {
outgoing: ["initialize", "initialized", "thread/start", "turn/start", "turn/interrupt"],
incoming: ["turn/started", "item/started", "turn/completed"],
turnStartCount: 1,
turnCompletedCount: 1,
approvalRequestCount: 0,
},
thread_rollback: {
outgoing: ["initialize", "initialized", "thread/start", "turn/start", "thread/rollback"],
incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
@@ -6,6 +6,7 @@ import type {
OrchestrationV2ShellSnapshot,
OrchestrationV2StoredEvent,
OrchestrationV2ThreadProjection,
OrchestrationV2TurnItem,
ProviderApprovalDecision,
ProviderUserInputAnswers,
CommandId,
@@ -43,6 +44,12 @@ export type OrchestratorV2ScenarioStep =
readonly threadId: ThreadId;
readonly runId: OrchestrationV2Run["id"];
}
| {
readonly type: "await_run_turn_item";
readonly threadId: ThreadId;
readonly runId: OrchestrationV2Run["id"];
readonly itemType: OrchestrationV2TurnItem["type"];
}
| {
readonly type: "respond_to_next_runtime_request";
readonly threadId: ThreadId;
@@ -241,6 +248,30 @@ export function runOrchestratorV2Scenario(
return yield* waitForRunSteerable(threadId, runId, attemptsRemaining - 1);
});
const waitForRunTurnItem = (
threadId: ThreadId,
runId: OrchestrationV2Run["id"],
itemType: OrchestrationV2TurnItem["type"],
attemptsRemaining = 1_000,
): Effect.Effect<void, OrchestratorV2Error | OrchestratorV2ScenarioStepError, never> =>
Effect.gen(function* () {
const projection = yield* orchestrator.getThreadProjection(threadId);
const hasTurnItem = projection.turnItems.some(
(item) => item.runId === runId && item.type === itemType,
);
if (hasTurnItem) {
return;
}
if (attemptsRemaining <= 0) {
return yield* new OrchestratorV2ScenarioStepError({
scenario: scenario.name,
step: `await_run_turn_item:${runId}:${itemType}`,
});
}
yield* Effect.yieldNow;
return yield* waitForRunTurnItem(threadId, runId, itemType, attemptsRemaining - 1);
});
for (const step of scenarioSteps(scenario)) {
switch (step.type) {
case "dispatch": {
@@ -278,6 +309,9 @@ export function runOrchestratorV2Scenario(
case "await_run_steerable":
yield* waitForRunSteerable(step.threadId, step.runId);
break;
case "await_run_turn_item":
yield* waitForRunTurnItem(step.threadId, step.runId, step.itemType);
break;
case "respond_to_next_runtime_request": {
const request = yield* waitForPendingRuntimeRequest(step.threadId);
const result = yield* orchestrator.dispatch({
@@ -30,8 +30,14 @@ import { toolCallRestrictedGranularInput } from "./tool_call_restricted_granular
import { assertToolCallWorkspaceNeverClaudeOutput } from "./tool_call_workspace_never/claude_output.ts";
import { assertToolCallWorkspaceNeverOutput } from "./tool_call_workspace_never/codex_output.ts";
import { toolCallWorkspaceNeverInput } from "./tool_call_workspace_never/input.ts";
import { assertTurnInterruptClaudeOutput } from "./turn_interrupt/claude_output.ts";
import { assertTurnInterruptOutput } from "./turn_interrupt/codex_output.ts";
import { turnInterruptInput } from "./turn_interrupt/input.ts";
import { assertTurnInterruptMidToolClaudeOutput } from "./turn_interrupt_mid_tool/claude_output.ts";
import { assertTurnInterruptMidToolCodexOutput } from "./turn_interrupt_mid_tool/codex_output.ts";
import { turnInterruptMidToolInput } from "./turn_interrupt_mid_tool/input.ts";
import { assertTurnInterruptRestartClaudeOutput } from "./turn_interrupt_restart/claude_output.ts";
import { turnInterruptRestartInput } from "./turn_interrupt_restart/input.ts";
import { assertClaudeWebSearchOutput } from "./web_search/claude_output.ts";
import { assertWebSearchOutput } from "./web_search/codex_output.ts";
import { webSearchInput } from "./web_search/input.ts";
@@ -302,6 +308,55 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
assertOutput: assertTurnInterruptOutput,
},
{
provider: "claudeAgent",
transcriptFile: new URL("./turn_interrupt/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
assertOutput: assertTurnInterruptClaudeOutput,
},
],
},
{
name: "turn_interrupt_mid_tool",
buildInput: turnInterruptMidToolInput,
providers: [
{
provider: "codex",
transcriptFile: new URL(
"./turn_interrupt_mid_tool/codex_transcript.ndjson",
import.meta.url,
),
modelSelection: CODEX_MODEL_SELECTION,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
assertOutput: assertTurnInterruptMidToolCodexOutput,
},
{
provider: "claudeAgent",
transcriptFile: new URL(
"./turn_interrupt_mid_tool/claude_transcript.ndjson",
import.meta.url,
),
modelSelection: CLAUDE_MODEL_SELECTION,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
assertOutput: assertTurnInterruptMidToolClaudeOutput,
},
],
},
{
name: "turn_interrupt_restart",
buildInput: turnInterruptRestartInput,
providers: [
{
provider: "claudeAgent",
transcriptFile: new URL(
"./turn_interrupt_restart/claude_transcript.ndjson",
import.meta.url,
),
modelSelection: CLAUDE_MODEL_SELECTION,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
assertOutput: assertTurnInterruptRestartClaudeOutput,
},
],
},
{
@@ -325,10 +380,6 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
// `tool_call_restricted_granular/claude_transcript.ndjson`, and
// docs/orchestration-v2/provider-capability-system.md.
// TODO(claude-v2/control): add a Claude interrupt fixture once explicit run interrupt behavior
// is fully hardened. Cross-reference `turn_interrupt/codex_transcript.ndjson` and
// docs/orchestration-v2/feature-lifecycles.md.
// TODO(claude-v2/context-transfer): add provider-switch handoff and return fixtures when portable
// context handoff is implemented. Cross-reference docs/orchestration-v2/provider-switching-and-context.md
// and docs/orchestration-v2/thread-lineage-and-context-transfer.md. The return fixture should
@@ -43,6 +43,10 @@ export const SUBAGENT_PROMPT =
"Spawn 2 subagents, one to read package.json and one to read tsconfig.json";
export const TURN_INTERRUPT_PROMPT =
"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.";
export const TURN_INTERRUPT_MID_TOOL_PROMPT =
"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.";
export const TURN_INTERRUPT_RECOVERY_PROMPT =
"Respond with exactly: interrupt recovery fixture complete";
export const MESSAGE_STEERING_STEER_PROMPT =
"Actually, respond with exactly: steering fixture observed";
export const THREAD_ROLLBACK_FIRST_PROMPT =
@@ -79,6 +83,7 @@ export type OrchestratorFixtureInputStep =
| {
readonly type: "interrupt";
readonly targetRunIndex: number;
readonly waitForTurnItemType?: OrchestrationV2TurnItem["type"];
}
| {
readonly type: "approve_next_runtime_request";
@@ -441,6 +446,14 @@ export function materializeFixtureInput(input: {
}
break;
case "interrupt":
if (step.waitForTurnItemType !== undefined) {
steps.push({
type: "await_run_turn_item",
threadId: ids.threadId,
runId: runIdFor(step.targetRunIndex),
itemType: step.waitForTurnItemType,
});
}
pushDispatch(
{
type: "run.interrupt",
@@ -0,0 +1,51 @@
import { assert } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
import {
assertBaseProjection,
assertSemanticProjectionIntegrity,
assertTurnItemTypes,
assertUserMessagesInclude,
assertVisibleTurnItemsMirrorLocalTurnItems,
projectionFor,
TURN_INTERRUPT_PROMPT,
} from "../shared.ts";
export function assertTurnInterruptClaudeOutput(
result: OrchestratorV2ScenarioResult,
transcript: ProviderReplayTranscript,
) {
assert.equal(transcript.provider, "claudeAgent");
assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["interrupted"] });
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
assertTurnItemTypes(projection, [
"user_message",
"run_interrupt_request",
"run_interrupt_result",
]);
assertUserMessagesInclude(projection, [TURN_INTERRUPT_PROMPT]);
const interruptRequest = projection.turnItems.find(
(item) => item.type === "run_interrupt_request",
);
const interruptResult = projection.turnItems.find((item) => item.type === "run_interrupt_result");
assert.isDefined(interruptRequest);
assert.isDefined(interruptResult);
assert.equal(interruptRequest.status, "completed");
assert.equal(interruptResult.status, "interrupted");
assert.equal(interruptResult.parentItemId, interruptRequest.id);
assert.deepEqual(
projection.attempts.map((attempt) => attempt.status),
["interrupted"],
);
assert.deepEqual(
projection.nodes.map((node) => node.status),
["interrupted"],
);
assert.equal(projection.providerThreads[0]?.status, "idle");
assert.equal(projection.providerTurns[0]?.status, "interrupted");
}
@@ -0,0 +1,7 @@
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"turn_interrupt","metadata":{"prompts":["Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally."],"model":"claude-sonnet-4-6","nativeSessionId":"2da9a7f1-f9cd-4d45-abd7-25f5370301f3","queryMode":"interrupt","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript"}}
{"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"2da9a7f1-f9cd-4d45-abd7-25f5370301f3"}}}
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally."},"parent_tool_use_id":null}}}
{"type":"expect_outbound","label":"query.interrupt:1","frame":{"type":"query.interrupt"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"7dd3898f-86a3-4aac-ae8a-222fe62cb13f","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"34154a8b-b7bb-4204-8c14-d9feb1971e17","session_id":"2da9a7f1-f9cd-4d45-abd7-25f5370301f3"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"7dd3898f-86a3-4aac-ae8a-222fe62cb13f","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"3e1cab63-3de4-4a98-a36c-a237d01bbea6","session_id":"2da9a7f1-f9cd-4d45-abd7-25f5370301f3"}}
{"type":"runtime_exit","status":"success"}
@@ -0,0 +1,95 @@
import { assert } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
import {
assertBaseProjection,
assertSemanticProjectionIntegrity,
assertTurnItemTypes,
assertUserMessagesInclude,
assertVisibleTurnItemsMirrorLocalTurnItems,
projectionFor,
TURN_INTERRUPT_MID_TOOL_PROMPT,
} from "../shared.ts";
function frameType(frame: unknown): string | undefined {
return typeof frame === "object" && frame !== null && "type" in frame
? (frame as { readonly type?: string }).type
: undefined;
}
function assistantHasToolUse(frame: unknown): boolean {
if (frameType(frame) !== "assistant") {
return false;
}
const message = (frame as { readonly message?: unknown }).message;
const content =
typeof message === "object" && message !== null && "content" in message
? (message as { readonly content?: unknown }).content
: undefined;
return (
Array.isArray(content) &&
content.some(
(part) =>
typeof part === "object" &&
part !== null &&
"type" in part &&
(part as { readonly type?: string }).type === "tool_use",
)
);
}
function assertClaudeInterruptAfterToolUse(transcript: ProviderReplayTranscript) {
const toolUseIndex = transcript.entries.findIndex(
(entry) => entry.type === "emit_inbound" && assistantHasToolUse(entry.frame),
);
const interruptIndex = transcript.entries.findIndex(
(entry) => entry.type === "expect_outbound" && frameType(entry.frame) === "query.interrupt",
);
assert.isAtLeast(toolUseIndex, 0, "Claude interrupt fixture must record a started tool use");
assert.isAbove(
interruptIndex,
toolUseIndex,
"Claude interrupt must be issued after the replayed tool use starts",
);
}
export function assertTurnInterruptMidToolClaudeOutput(
result: OrchestratorV2ScenarioResult,
transcript: ProviderReplayTranscript,
) {
assert.equal(transcript.provider, "claudeAgent");
assertClaudeInterruptAfterToolUse(transcript);
assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["interrupted"] });
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
assertTurnItemTypes(projection, [
"user_message",
"command_execution",
"run_interrupt_request",
"run_interrupt_result",
]);
assertUserMessagesInclude(projection, [TURN_INTERRUPT_MID_TOOL_PROMPT]);
const commandItem = projection.turnItems.find((item) => item.type === "command_execution");
const interruptRequest = projection.turnItems.find(
(item) => item.type === "run_interrupt_request",
);
const interruptResult = projection.turnItems.find((item) => item.type === "run_interrupt_result");
assert.isDefined(commandItem);
assert.isDefined(interruptRequest);
assert.isDefined(interruptResult);
assert.equal(commandItem.status, "failed");
assert.include(commandItem.input, "node -e");
assert.equal(interruptRequest.status, "completed");
assert.equal(interruptResult.status, "interrupted");
assert.equal(interruptResult.parentItemId, interruptRequest.id);
assert.deepEqual(
projection.attempts.map((attempt) => attempt.status),
["interrupted"],
);
assert.equal(projection.providerThreads[0]?.status, "idle");
assert.equal(projection.providerTurns[0]?.status, "interrupted");
}
@@ -0,0 +1,11 @@
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"turn_interrupt_mid_tool","metadata":{"prompts":["Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."],"model":"claude-sonnet-4-6","nativeSessionId":"7d29f78b-4ff3-4147-b35f-4d0f89c5d7f5","queryMode":"interrupt","tools":"claude_code","permissionMode":"bypassPermissions","interruptAfter":"tool_use","generatedBy":"recordClaudeAgentSdkReplayTranscript"}}
{"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"7d29f78b-4ff3-4147-b35f-4d0f89c5d7f5"}}}
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."},"parent_tool_use_id":null}}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"8557ae70-649c-47ed-94c4-555567ddf93f","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"5f8a6db0-da77-4ac6-a34e-1502fdddcb2d","session_id":"7d29f78b-4ff3-4147-b35f-4d0f89c5d7f5"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"8557ae70-649c-47ed-94c4-555567ddf93f","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"93406e3b-e131-447a-8e21-066c7ac7da5a","session_id":"7d29f78b-4ff3-4147-b35f-4d0f89c5d7f5"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-turn_interrupt_mid_tool","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"24114010-ef49-4403-92e8-d76b3234d9eb","session_id":"7d29f78b-4ff3-4147-b35f-4d0f89c5d7f5"}}
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_0134LoSqmeAtmiGfT8XBAnc4","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a specific command that will take 30 seconds to complete (due to the setTimeout). Let me run it.","signature":"ErcCClsIDRgCKkCX7DIBv4J2HjLNPifJq4HAANiIdEr2/GYMGyhdF9zkHFjE9AwbyKNoDI3MXdCly81YpJMMr6ky4//OnX7XrJcAMhFjbGF1ZGUtc29ubmV0LTQtNjgAEgzvtPfUQk3cHbNsLsEaDASyv+jHKV/wcM5HASIw415m94Xy244+UXxpWThWU7A8/9DEtOQ9sLzR9/duaPYc2SeKjvmhKOg1oQZi3nczKokB2YWThB+/yKnsTc2k+1xsUcUYXPcNk6jCZsnJtwkFDA0j7ar6Z5cY0ZaNli+aFbVGJrreiWvsGf8icWy0GedLUshQHGjvwXTbQ/F1kcR2NMBgBjot13Q3iN8/zcGMp6ViJu/R+roW7q6se2i0vbbRBg+1UtYrQ5rkbSBQ3TAlNmYDqe78XtexmHoYAQ=="}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2377,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2377},"output_tokens":8,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"7d29f78b-4ff3-4147-b35f-4d0f89c5d7f5","uuid":"6574c500-9646-4151-ab05-a0d7065adc47"}}
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_0134LoSqmeAtmiGfT8XBAnc4","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01FAyzzWN34naNJKvPcD7B1D","name":"Bash","input":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":60000},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2377,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2377},"output_tokens":8,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"7d29f78b-4ff3-4147-b35f-4d0f89c5d7f5","uuid":"ae2c90aa-4ded-4184-941b-ff32527cc9de"}}
{"type":"expect_outbound","label":"query.interrupt:1","frame":{"type":"query.interrupt"}}
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"0f354af4-9fdf-463f-a3bc-75c31eeaa074","session_id":"7d29f78b-4ff3-4147-b35f-4d0f89c5d7f5"}}
{"type":"runtime_exit","status":"success"}
@@ -0,0 +1,94 @@
import { assert } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
import {
assertBaseProjection,
assertSemanticProjectionIntegrity,
assertTurnItemTypes,
assertUserMessagesInclude,
assertVisibleTurnItemsMirrorLocalTurnItems,
projectionFor,
TURN_INTERRUPT_MID_TOOL_PROMPT,
} from "../shared.ts";
function protocolMethod(frame: unknown): string | undefined {
return typeof frame === "object" && frame !== null && "method" in frame
? (frame as { readonly method?: string }).method
: undefined;
}
function isCommandExecutionStartedFrame(frame: unknown): boolean {
if (protocolMethod(frame) !== "item/started") {
return false;
}
const params =
typeof frame === "object" && frame !== null && "params" in frame
? (frame as { readonly params?: unknown }).params
: undefined;
const item =
typeof params === "object" && params !== null && "item" in params
? (params as { readonly item?: unknown }).item
: undefined;
return (
typeof item === "object" &&
item !== null &&
"type" in item &&
(item as { readonly type?: string }).type === "commandExecution"
);
}
function assertCodexInterruptAfterCommandExecution(transcript: ProviderReplayTranscript) {
const commandIndex = transcript.entries.findIndex(
(entry) => entry.type === "emit_inbound" && isCommandExecutionStartedFrame(entry.frame),
);
const interruptIndex = transcript.entries.findIndex(
(entry) => entry.type === "expect_outbound" && protocolMethod(entry.frame) === "turn/interrupt",
);
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",
);
}
export function assertTurnInterruptMidToolCodexOutput(
result: OrchestratorV2ScenarioResult,
transcript: ProviderReplayTranscript,
) {
assert.equal(transcript.provider, "codex");
assertCodexInterruptAfterCommandExecution(transcript);
assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["interrupted"] });
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
assertTurnItemTypes(projection, [
"user_message",
"command_execution",
"run_interrupt_request",
"run_interrupt_result",
]);
assertUserMessagesInclude(projection, [TURN_INTERRUPT_MID_TOOL_PROMPT]);
const commandItem = projection.turnItems.find((item) => item.type === "command_execution");
const interruptRequest = projection.turnItems.find(
(item) => item.type === "run_interrupt_request",
);
const interruptResult = projection.turnItems.find((item) => item.type === "run_interrupt_result");
assert.isDefined(commandItem);
assert.isDefined(interruptRequest);
assert.isDefined(interruptResult);
assert.include(["running", "completed", "failed"], commandItem.status);
assert.include(commandItem.input, "node -e");
assert.equal(interruptRequest.status, "completed");
assert.equal(interruptResult.status, "interrupted");
assert.equal(interruptResult.parentItemId, interruptRequest.id);
assert.deepEqual(
projection.attempts.map((attempt) => attempt.status),
["interrupted"],
);
assert.equal(projection.providerThreads[0]?.status, "idle");
assert.include(["interrupted", "cancelled"], projection.providerTurns[0]?.status);
}
@@ -0,0 +1,33 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.128.0","scenario":"turn_interrupt_mid_tool","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"turn_interrupt_mid_tool.ndjson","description":"One active turn is interrupted after Codex has already executed a local command."}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true},"clientInfo":{"name":"t3code_desktop","title":"T3 Code Desktop","version":"0.1.0"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.128.0 (Mac OS 26.4.1; arm64) dumb (t3code_desktop; 0.1.0)","codexHome":"/Users/julius/.codex_p","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":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","environmentId":null}}}
{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1778178891,"updatedAt":1778178891,"status":{"type":"idle"},"path":"/Users/julius/.codex_p/sessions/2026/05/07/rollout-2026-05-07T11-34-51-019e03b8-9e5c-7b32-88ab-f742a29b75b8.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","cliVersion":"0.128.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.5","modelProvider":"openai","serviceTier":"fast","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","instructionSources":["/Users/julius/.codex_p/AGENTS.md","/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":["/Users/julius/.codex_p/memories"],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"permissionProfile":{"type":"managed","network":{"enabled":false},"fileSystem":{"type":"restricted","entries":[{"path":{"type":"special","value":{"kind":"root"}},"access":"read"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":null}},"access":"write"},{"path":{"type":"special","value":{"kind":"slash_tmp"}},"access":"write"},{"path":{"type":"special","value":{"kind":"tmpdir"}},"access":"write"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":".git"}},"access":"read"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":".agents"}},"access":"read"},{"path":{"type":"special","value":{"kind":"project_roots","subpath":".codex"}},"access":"read"},{"path":{"type":"path","path":"/Users/julius/.codex_p/memories"},"access":"write"}]}},"activePermissionProfile":{"id":":workspace","extends":null,"modifications":[]},"reasoningEffort":"medium"}}}
{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","input":[{"text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","type":"text"}],"sandboxPolicy":{"networkAccess":false,"readOnlyAccess":{"type":"fullAccess"},"type":"workspaceWrite","writableRoots":[]},"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8"}}}
{"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1778178891,"updatedAt":1778178891,"status":{"type":"idle"},"path":"/Users/julius/.codex_p/sessions/2026/05/07/rollout-2026-05-07T11-34-51-019e03b8-9e5c-7b32-88ab-f742a29b75b8.jsonl","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","cliVersion":"0.128.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}}}}
{"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"`[features].collab` is deprecated. Use `[features].multi_agent` instead.","details":"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details."}}}
{"type":"emit_inbound","label":"warning","frame":{"method":"warning","params":{"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","message":"Under-development features enabled: apply_patch_freeform. Under-development features are incomplete and may behave unpredictably. To suppress this warning, set `suppress_unstable_features_warning = true` in /Users/julius/.codex_p/config.toml."}}}
{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"starting","error":null}}}
{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"starting","error":null}}}
{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"openaiDeveloperDocs","status":"starting","error":null}}}
{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"starting","error":null}}}
{"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"019e03b8-9f34-7bb1-8267-ad79b7e2e69a","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","status":{"type":"active","activeFlags":[]}}}}
{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","turn":{"id":"019e03b8-9f34-7bb1-8267-ad79b7e2e69a","items":[],"status":"inProgress","error":null,"startedAt":1778178891,"completedAt":null,"durationMs":null}}}}
{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"computer-use","status":"ready","error":null}}}
{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"openaiDeveloperDocs","status":"ready","error":null}}}
{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"codex_apps","status":"ready","error":null}}}
{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"name":"uidotsh","status":"ready","error":null}}}
{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"ed97ce32-6075-4da5-9c7e-7518427a7bb6","content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","text_elements":[]}]},"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","turnId":"019e03b8-9f34-7bb1-8267-ad79b7e2e69a"}}}
{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"ed97ce32-6075-4da5-9c7e-7518427a7bb6","content":[{"type":"text","text":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","text_elements":[]}]},"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","turnId":"019e03b8-9f34-7bb1-8267-ad79b7e2e69a"}}}
{"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":6,"windowDurationMins":300,"resetsAt":1778193273},"secondary":{"usedPercent":32,"windowDurationMins":10080,"resetsAt":1778539136},"credits":null,"planType":"pro","rateLimitReachedType":null}}}}
{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","turnId":"019e03b8-9f34-7bb1-8267-ad79b7e2e69a","tokenUsage":{"total":{"totalTokens":17497,"inputTokens":17444,"cachedInputTokens":7552,"outputTokens":53,"reasoningOutputTokens":0},"last":{"totalTokens":17497,"inputTokens":17444,"cachedInputTokens":7552,"outputTokens":53,"reasoningOutputTokens":0},"modelContextWindow":258400}}}}
{"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":6,"windowDurationMins":300,"resetsAt":1778193273},"secondary":{"usedPercent":32,"windowDurationMins":10080,"resetsAt":1778539136},"credits":null,"planType":"pro","rateLimitReachedType":null}}}}
{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"call_m8JXk02QAzuzBMHNgh1RsGaw","command":"/bin/zsh -lc \"node -e \\\"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\\\"\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server","processId":"4275","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"unknown","command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\""}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","turnId":"019e03b8-9f34-7bb1-8267-ad79b7e2e69a"}}}
{"type":"expect_outbound","label":"turn/interrupt","frame":{"id":4,"method":"turn/interrupt","params":{"threadId":"019e03b8-9e5c-7b32-88ab-f742a29b75b8","turnId":"019e03b8-9f34-7bb1-8267-ad79b7e2e69a"}}}
{"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":"runtime_exit","status":"success"}
@@ -0,0 +1,10 @@
import { TURN_INTERRUPT_MID_TOOL_PROMPT, type OrchestratorFixtureInput } from "../shared.ts";
export function turnInterruptMidToolInput(): OrchestratorFixtureInput {
return {
steps: [
{ type: "message", text: TURN_INTERRUPT_MID_TOOL_PROMPT },
{ type: "interrupt", targetRunIndex: 1, waitForTurnItemType: "command_execution" },
],
};
}
@@ -0,0 +1,129 @@
import { assert } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
import {
assertAssistantTextIncludes,
assertBaseProjection,
assertConversationMessageRoles,
assertRunOrdinals,
assertSemanticProjectionIntegrity,
assertTurnItemTypes,
assertUserMessagesInclude,
assertVisibleTurnItemsMirrorLocalTurnItems,
projectionFor,
TURN_INTERRUPT_MID_TOOL_PROMPT,
TURN_INTERRUPT_RECOVERY_PROMPT,
} from "../shared.ts";
function isReplayFrameWithType(
frame: unknown,
type: string,
): frame is { readonly type: string; readonly options?: Record<string, unknown> } {
return (
typeof frame === "object" &&
frame !== null &&
"type" in frame &&
(frame as { readonly type?: unknown }).type === type
);
}
function frameType(frame: unknown): string | undefined {
return typeof frame === "object" && frame !== null && "type" in frame
? (frame as { readonly type?: string }).type
: undefined;
}
function assistantHasToolUse(frame: unknown): boolean {
if (frameType(frame) !== "assistant") {
return false;
}
const message = (frame as { readonly message?: unknown }).message;
const content =
typeof message === "object" && message !== null && "content" in message
? (message as { readonly content?: unknown }).content
: undefined;
return (
Array.isArray(content) &&
content.some(
(part) =>
typeof part === "object" &&
part !== null &&
"type" in part &&
(part as { readonly type?: string }).type === "tool_use",
)
);
}
function assertClaudeInterruptAfterToolUse(transcript: ProviderReplayTranscript) {
const toolUseIndex = transcript.entries.findIndex(
(entry) => entry.type === "emit_inbound" && assistantHasToolUse(entry.frame),
);
const interruptIndex = transcript.entries.findIndex(
(entry) => entry.type === "expect_outbound" && frameType(entry.frame) === "query.interrupt",
);
assert.isAtLeast(toolUseIndex, 0, "Claude interrupt fixture must record a started tool use");
assert.isAbove(
interruptIndex,
toolUseIndex,
"Claude interrupt must be issued after the replayed tool use starts",
);
}
export function assertTurnInterruptRestartClaudeOutput(
result: OrchestratorV2ScenarioResult,
transcript: ProviderReplayTranscript,
) {
assert.equal(transcript.provider, "claudeAgent");
assertClaudeInterruptAfterToolUse(transcript);
assertBaseProjection({
result,
transcript,
runCount: 2,
runStatuses: ["interrupted", "completed"],
});
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
assertRunOrdinals(projection, [1, 2]);
assertConversationMessageRoles(projection, ["user", "user", "assistant"]);
assertTurnItemTypes(projection, [
"user_message",
"command_execution",
"run_interrupt_request",
"run_interrupt_result",
"assistant_message",
]);
assertUserMessagesInclude(projection, [
TURN_INTERRUPT_MID_TOOL_PROMPT,
TURN_INTERRUPT_RECOVERY_PROMPT,
]);
assertAssistantTextIncludes(projection, "interrupt recovery fixture complete");
assert.deepEqual(
projection.attempts.map((attempt) => attempt.status),
["interrupted", "completed"],
);
assert.deepEqual(
projection.providerTurns.map((turn) => turn.status),
["interrupted", "completed"],
);
assert.equal(projection.providerThreads[0]?.status, "idle");
const commandItem = projection.turnItems.find((item) => item.type === "command_execution");
assert.isDefined(commandItem);
assert.equal(commandItem.status, "failed");
assert.include(commandItem.input, "node -e");
const outboundFrames = transcript.entries.flatMap((entry) =>
entry.type === "expect_outbound" ? [entry.frame] : [],
);
const queryOpenFrames = outboundFrames.filter((frame) =>
isReplayFrameWithType(frame, "query.open"),
);
const interruptFrames = outboundFrames.filter((frame) =>
isReplayFrameWithType(frame, "query.interrupt"),
);
assert.lengthOf(queryOpenFrames, 2);
assert.isString(queryOpenFrames[1]?.options?.resume);
assert.lengthOf(interruptFrames, 1);
}
@@ -0,0 +1,20 @@
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"turn_interrupt_restart","metadata":{"prompts":["Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.","Respond with exactly: interrupt recovery fixture complete"],"model":"claude-sonnet-4-6","nativeSessionId":"fb591f8f-073f-4981-bf67-9b5bffb537d5","queryMode":"interrupt_restart","tools":"claude_code","permissionMode":"bypassPermissions","interruptAfter":"tool_use","generatedBy":"recordClaudeAgentSdkReplayTranscript"}}
{"type":"expect_outbound","label":"query.open:1","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"fb591f8f-073f-4981-bf67-9b5bffb537d5"}}}
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally."},"parent_tool_use_id":null}}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"9e9d889c-c7cc-41c8-862c-691efcebe3a4","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"ac49901c-0458-4870-b5d7-9c8ed20ffa68","session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"9e9d889c-c7cc-41c8-862c-691efcebe3a4","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"1f69ab12-dcff-4bb3-9dc7-6284fc356fd4","session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-turn_interrupt_restart","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"a3d73993-da1f-4dd2-ae3f-6d9fbfde4e17","session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5"}}
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01Ri3g1NyAvmxateKU6RpTZt","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a specific command that will take 30 seconds to complete (due to the setTimeout). Let me run it.","signature":"ErcCClsIDRgCKkCX7DIBv4J2HjLNPifJq4HAANiIdEr2/GYMGyhdF9zkHFjE9AwbyKNoDI3MXdCly81YpJMMr6ky4//OnX7XrJcAMhFjbGF1ZGUtc29ubmV0LTQtNjgAEgyvpmUstPaO3mULIDoaDFDTBmO2AKTDNHheWCIwmltJgzr/Y82edEUCc2SZ/vmduVXkEGJFBpYfDgWg++UCyftnJ2jIuU7OjMrgnlGyKokBovHsKA1SGudP3mxdKaHpo9wyKvUQgjmjBUYndKN68q/l/LSN27pia+/x2C99K8iJTvWWykEjSvXn59qOQJI49MVav3hPKR0t0kQcrdM17ceB/ZYPcAxNN4u+EB2cxxeUAGXmcoJ5H69FBoNxtnDf1ECnTp3cdcd7af7W5oTUKX075fqAXS7rKJ4YAQ=="}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2377,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2377},"output_tokens":8,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5","uuid":"d7c45832-9ef6-4a07-81ef-2f3c5bfbbb60"}}
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01Ri3g1NyAvmxateKU6RpTZt","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01KHpBiM7muckukoYeKCJnSn","name":"Bash","input":{"command":"node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"","timeout":60000},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2377,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2377},"output_tokens":8,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5","uuid":"a4208b49-5191-48bf-ae90-9e25f49822de"}}
{"type":"expect_outbound","label":"query.interrupt:1","frame":{"type":"query.interrupt"}}
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"72dd2e75-8bf4-4119-85b4-0176e138ca89","session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5"}}
{"type":"runtime_exit","status":"success"}
{"type":"expect_outbound","label":"query.open:2","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"fb591f8f-073f-4981-bf67-9b5bffb537d5"}}}
{"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with exactly: interrupt recovery fixture complete"},"parent_tool_use_id":null}}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"b6eca4f5-a876-4c87-b985-ac51dfdcd45a","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"333f23b1-5e16-416a-ad70-28fc820390b8","session_id":"be6cf26c-092d-4fe1-8a63-057bfd8b4723"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"b6eca4f5-a876-4c87-b985-ac51dfdcd45a","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"29fb9baf-b0ed-4097-b8fc-be223aa6dd76","session_id":"be6cf26c-092d-4fe1-8a63-057bfd8b4723"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-turn_interrupt_restart","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"1b86dd32-214c-4c7e-81d1-2a73befc5da8","session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5"}}
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_015EmKr5Mwpb1EixMz3GZupx","type":"message","role":"assistant","content":[{"type":"text","text":"interrupt recovery fixture complete"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":243,"cache_read_input_tokens":11832,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":243},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5","uuid":"dd46fcd4-0fca-4418-bcd6-30e6df3e9479"}}
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"0548e03f-e3ea-431d-b6d2-100d02680b4d","session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5"}}
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":9358,"duration_api_ms":8922,"num_turns":1,"result":"interrupt recovery fixture complete","stop_reason":"end_turn","session_id":"fb591f8f-073f-4981-bf67-9b5bffb537d5","total_cost_usd":0.00457485,"usage":{"input_tokens":3,"cache_creation_input_tokens":243,"cache_read_input_tokens":11832,"output_tokens":7,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":243,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":7,"cache_read_input_tokens":11832,"cache_creation_input_tokens":243,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":243},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":7,"cacheReadInputTokens":11832,"cacheCreationInputTokens":243,"webSearchRequests":0,"costUSD":0.00457485,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"aaf4e093-6e70-4418-8507-99d62cece13e"}}
{"type":"runtime_exit","status":"success"}
@@ -0,0 +1,15 @@
import {
TURN_INTERRUPT_MID_TOOL_PROMPT,
TURN_INTERRUPT_RECOVERY_PROMPT,
type OrchestratorFixtureInput,
} from "../shared.ts";
export function turnInterruptRestartInput(): OrchestratorFixtureInput {
return {
steps: [
{ type: "message", text: TURN_INTERRUPT_MID_TOOL_PROMPT },
{ type: "interrupt", targetRunIndex: 1, waitForTurnItemType: "command_execution" },
{ type: "message", text: TURN_INTERRUPT_RECOVERY_PROMPT },
],
};
}
+1
View File
@@ -13,6 +13,7 @@ V2 is designed around the real provider behavior observed in the Codex app-serve
- [Feature Lifecycles](./feature-lifecycles.md)
- [Thread Lineage And Context Transfer](./thread-lineage-and-context-transfer.md)
- [Provider Switching And Context Handoff](./provider-switching-and-context.md)
- [Orchestrator MCP Server](./orchestrator-mcp-server.md)
- [Provider Capability System](./provider-capability-system.md)
- [Testing Strategy](./testing-strategy.md)
@@ -0,0 +1,495 @@
# Orchestrator MCP Server
## Purpose
T3 should ship an app-owned MCP server that lets provider agents ask the V2
orchestrator for orchestration work. The first tool family is delegated work:
a parent provider turn can request another provider/model/agent to run a task
as a child execution node, then receive a durable result back.
This is not a subagent-only design. The MCP server is the provider-neutral
bridge for future model-controlled orchestration actions. Subagents are just
the first action because MCP is the most common extension point across the
current provider harnesses.
## External Provider Wiring
### Codex
Codex supports MCP through Codex configuration. Official docs say MCP servers
are stored in `config.toml`, normally `~/.codex/config.toml`, and can also be
project-scoped through `.codex/config.toml` for trusted projects. Stdio servers
use `[mcp_servers.<server-name>]` with `command`, `args`, `env`, `env_vars`,
`cwd`, timeout, enabled, required, and tool allow/deny options.
Local fit:
- Current Codex sessions start `codex app-server` with `CODEX_HOME` supplied
by `CodexSessionRuntimeOptions.homePath`.
- The generated app-server protocol already includes
`config/mcpServer/reload`, `mcpServerStatus/list`,
`mcpServer/resource/read`, `mcpServer/tool/call`, OAuth completion, and MCP
startup status notifications.
- Current `CodexHomeLayout` can create shadow homes, but it currently symlinks
`config.toml` from the shared home. V2 should add an app-managed MCP config
projection instead of mutating arbitrary user TOML blindly.
Recommended projection:
```toml
[mcp_servers.t3_orchestrator]
command = "/path/to/t3"
args = ["mcp", "orchestrator", "--transport", "stdio"]
env = {
T3_ORCH_MCP_TOKEN = "<short-lived capability token>",
T3_ORCH_MCP_ENDPOINT = "http://127.0.0.1:<port>",
T3_ORCH_MCP_CONTEXT = "<signed parent context id>"
}
enabled = true
required = false
tool_timeout_sec = 600
enabled_tools = [
"orchestrator_capabilities",
"delegate_task",
"task_status",
"task_cancel"
]
```
Implementation note: prefer a structured TOML merge into an app-managed
session home. If we must touch a user-visible `config.toml`, own only the
`mcp_servers.t3_orchestrator` table, preserve all other tables, and call
`config/mcpServer/reload` after updating a running app-server.
### Claude Agent SDK
Claude Agent SDK exposes MCP directly in `query` options. Official docs show
`mcpServers` entries in the SDK options and require `allowedTools` for Claude
to use those tools without broad permission bypass. Tool names are granted as
`mcp__<serverName>__<toolName>` or with a server wildcard.
Local fit:
- `ClaudeAdapter` already builds a `ClaudeQueryOptions` object in
`startSession`.
- Add `mcpServers.t3_orchestrator` and `allowedTools:
["mcp__t3_orchestrator__*"]` there.
- This is per Claude query/session startup. There is no hot reload path in our
current Claude adapter, so changing the MCP projection should restart or
recreate the Claude query runtime.
Recommended projection:
```ts
const queryOptions: ClaudeQueryOptions = {
...existing,
mcpServers: {
...existing.mcpServers,
t3_orchestrator: {
command: t3BinaryPath,
args: ["mcp", "orchestrator", "--transport", "stdio"],
env: buildOrchestratorMcpEnv(parentContext),
},
},
allowedTools: [...existingAllowedTools, "mcp__t3_orchestrator__*"],
};
```
### OpenCode
OpenCode supports local and remote MCP servers under the `mcp` config object.
Local servers use `type: "local"`, `command: string[]`, optional
`environment`, `enabled`, and timeout. Remote servers use `type: "remote"`,
`url`, headers, OAuth, and timeout. OpenCode tools are managed by glob-like
tool names, and MCP tools are prefixed by server name.
Local fit:
- Our local OpenCode server path spawns `opencode serve` and currently sets
`OPENCODE_CONFIG_CONTENT` to `JSON.stringify({})`.
- When T3 owns the OpenCode server process, V2 can merge the orchestrator MCP
config into that generated config content before process start.
- When `serverUrl` points at an external OpenCode server, T3 does not own the
server config. Treat automatic MCP injection as unsupported unless OpenCode
exposes a runtime config API we intentionally adopt.
Recommended projection for owned servers:
```ts
const opencodeConfig = {
...existingGeneratedConfig,
mcp: {
...existingGeneratedConfig.mcp,
t3_orchestrator: {
type: "local",
command: [t3BinaryPath, "mcp", "orchestrator", "--transport", "stdio"],
environment: buildOrchestratorMcpEnv(parentContext),
enabled: true,
timeout: 600_000,
},
},
tools: {
...existingGeneratedConfig.tools,
"t3_orchestrator_*": true,
},
};
```
### Cursor ACP
Cursor CLI supports MCP, but the current T3 harness uses Cursor through ACP.
The local ACP session creation sends `mcpServers: []`, and there is no current
adapter hook that projects a T3 MCP server into Cursor through ACP. Cursor CLI
docs indicate the agent discovers MCP from the same editor `mcp.json`
configuration and has `cursor-agent mcp` commands for listing servers,
listing tools, login, and disabling.
Recommended V2 posture:
- Mark Cursor's app-injected MCP support as `external_config_only` until ACP
exposes a reliable config input or we decide to manage `.cursor/mcp.json`.
- Do not silently write project/global Cursor config from a provider session.
Project config mutation is user-visible and should be an explicit user
setting or setup step.
- Preserve the ACP `mcpServers` field in our capability model as provider
evidence, but do not treat the current empty array as an injection path.
## V2 Capability Additions
Extend provider capabilities instead of branching on provider kind:
```ts
type ToolCapabilities = {
exposesToolItemIds: boolean;
emitsToolStarted: boolean;
emitsToolCompleted: boolean;
emitsToolOutput: boolean;
supportsMcpTools: boolean;
supportsDynamicToolCallbacks: boolean;
mcpInjection:
| { type: "none" }
| { type: "sdk_options"; reload: "restart_required" }
| { type: "config_file"; reload: "hot_reload" | "restart_required" }
| { type: "process_env_config"; reload: "restart_required" }
| { type: "external_config_only" };
};
type SubagentCapabilities = {
supportsSubagents: boolean;
exposesSubagentThreadIds: boolean;
emitsSubagentLifecycle: boolean;
canWaitForSubagents: boolean;
canCloseSubagents: boolean;
canForkSubagentThread: boolean;
supportsCrossProviderDelegationViaMcp: boolean;
};
```
Expected initial values:
```text
codex mcpInjection=config_file/hot_reload, native subagents=yes
claudeAgent mcpInjection=sdk_options/restart_required
openCode mcpInjection=process_env_config/restart_required for owned servers
cursor mcpInjection=external_config_only
```
## MCP Server Shape
The server should be named `t3_orchestrator` and should expose a small stable
tool surface. Tool names should stay generic because this server will outgrow
subagents.
### Tools
`orchestrator_capabilities`
Returns the providers, provider instances, models, runtime modes, and
delegation features currently available to the parent context.
```ts
type OrchestratorCapabilitiesResult = {
providers: Array<{
providerInstanceId: string;
driverKind: string;
displayName?: string;
models: Array<{ id: string; label?: string }>;
canRunChildTask: boolean;
canRunSameProviderNativeSubagent: boolean;
canRunCrossProviderChildTask: boolean;
constraints: string[];
}>;
};
```
`delegate_task`
Requests a child execution task. The orchestrator decides whether this becomes
a same-provider native subagent, a child app thread/run on another provider, or
a rejected request with a model-visible error.
```ts
type DelegateTaskInput = {
task: string;
target?: {
providerInstanceId?: string;
driverKind?: string;
model?: string;
};
role?: "implementation" | "research" | "review" | "design" | "test" | "general";
mode?: "async" | "wait";
timeoutMs?: number;
clientRequestId?: string;
context?: {
summary?: string;
files?: string[];
sourcePoint?: {
threadId?: string;
runId?: string;
nodeId?: string;
checkpointId?: string;
};
};
runtimeMode?: "inherit" | "read_only" | "workspace_write" | "full_access";
};
type DelegateTaskResult = {
taskId: string;
childThreadId?: string;
childRunId?: string;
childNodeId: string;
status: "queued" | "running" | "completed" | "failed" | "cancelled";
providerInstanceId: string;
model?: string;
summary?: string;
resultContextTransferId?: string;
};
```
`task_status`
Returns the latest durable state for a delegated task, including final summary,
artifact refs, child thread/run/node ids, failure reason, and whether the
parent can wait longer.
`task_cancel`
Cancels a delegated task through the V2 command layer. This should target app
ids and let the adapter translate to native interruption.
Future tools can use the same server:
- `context_read` for bounded, orchestrator-curated context resources.
- `handoff_request` for agent-initiated provider switching.
- `checkpoint_create` for explicit child scopes.
- `plan_review_request` for app-owned plan review flows.
### MCP Tool Result Rules
MCP clients call tools with `tools/call` and arguments. Results should include
both `content` and `structuredContent` so weaker clients still see text while
T3-aware clients can validate typed output. Tool execution errors that the
model can act on should return `isError: true` in the result rather than a
protocol-level JSON-RPC error. Unknown tools, malformed requests, and protocol
failures should remain JSON-RPC errors.
For long-running work, prefer:
```text
delegate_task(mode="async")
-> returns taskId immediately
task_status(taskId)
-> model polls when it needs result
```
`delegate_task(mode="wait")` may block until completion or timeout, but it
still creates the same durable child node and returns the same ids.
## Orchestrator Integration
The MCP server must not call provider adapters directly. It should be another
command ingress into V2 orchestration.
```text
provider model
-> MCP tools/call delegate_task
-> T3 MCP server validates token and input
-> V2 command: delegated_task.request
-> durable event: DelegatedTaskRequested
-> execution graph: child ExecutionNode(parentNodeId=caller node)
-> ContextTransfer(type=subagent_spawn, createdBy=agent)
-> provider effect request starts/resumes selected child provider
-> child provider events normalize into graph
-> ContextTransfer(type=subagent_result) materializes result
-> MCP result / task_status returns durable child state
```
Important boundaries:
- Authentication is through a short-lived capability token scoped to the
parent session/thread/run/node and delivered through MCP server env.
- Authorization is app-owned. The tool input can ask for a provider, model,
files, and runtime mode; policy decides what is allowed.
- Runtime mode can only stay the same or narrow without explicit user
approval. A parent in read-only mode cannot create a full-access child.
- Child tasks use app ids. Native provider ids are refs and are scoped through
normal V2 identity bindings.
- `clientRequestId` makes MCP retries idempotent within the parent MCP session.
- The parent tool call item should be linked to the child `ExecutionNode` so
the UI can show progress under the parent turn.
- The child result should flow back through `ContextTransfer`, not hidden prompt
concatenation.
## Pseudo-Code
Provider projection contract:
```ts
type OrchestratorMcpProjection = {
serverName: "t3_orchestrator";
command: string;
args: string[];
env: Record<string, string>;
allowedToolNames: string[];
};
type ProviderMcpProjector = {
support: ToolCapabilities["mcpInjection"];
buildProjection(input: {
parentThreadId: string;
parentRunId?: string;
parentNodeId?: string;
providerInstanceId: string;
cwd: string;
}): OrchestratorMcpProjection;
};
```
MCP server entrypoint:
```ts
async function startOrchestratorMcpServer(env: NodeJS.ProcessEnv) {
const auth = await verifyCapabilityToken(env.T3_ORCH_MCP_TOKEN);
const transport = new StdioServerTransport();
const server = new McpServer({
name: "t3_orchestrator",
version: APP_VERSION,
});
server.tool("orchestrator_capabilities", capabilitiesSchema, async () => {
const result = await orchestration.readDelegationCapabilities(auth.scope);
return toolResult(result);
});
server.tool("delegate_task", delegateTaskSchema, async (input) => {
const commandId = stableCommandId(auth.mcpSessionId, input.clientRequestId);
const receipt = await orchestration.dispatch({
type: "delegated_task.request",
commandId,
causation: {
source: "mcp",
providerInstanceId: auth.providerInstanceId,
parentThreadId: auth.parentThreadId,
parentRunId: auth.parentRunId,
parentNodeId: auth.parentNodeId,
},
input,
});
if (input.mode !== "wait") {
return toolResult(toDelegateTaskResult(receipt));
}
const finalState = await orchestration.waitForDelegatedTask(
receipt.taskId,
input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS,
);
return toolResult(toDelegateTaskResult(finalState));
});
server.tool("task_status", taskStatusSchema, async (input) => {
return toolResult(await orchestration.readDelegatedTask(auth.scope, input.taskId));
});
server.tool("task_cancel", taskCancelSchema, async (input) => {
return toolResult(await orchestration.cancelDelegatedTask(auth.scope, input.taskId));
});
await server.connect(transport);
}
```
Provider hooks:
```ts
function applyCodexProjection(home: CodexHome, projection: OrchestratorMcpProjection) {
mergeTomlTable(home.configToml, "mcp_servers.t3_orchestrator", {
command: projection.command,
args: projection.args,
env: projection.env,
enabled_tools: projection.allowedToolNames,
enabled: true,
required: false,
});
codexRpc.request("config/mcpServer/reload");
}
function applyClaudeProjection(options: ClaudeQueryOptions, projection: OrchestratorMcpProjection) {
options.mcpServers = {
...options.mcpServers,
[projection.serverName]: {
command: projection.command,
args: projection.args,
env: projection.env,
},
};
options.allowedTools = [...(options.allowedTools ?? []), `mcp__${projection.serverName}__*`];
}
function buildOpenCodeConfig(projection: OrchestratorMcpProjection) {
return {
mcp: {
[projection.serverName]: {
type: "local",
command: [projection.command, ...projection.args],
environment: projection.env,
enabled: true,
},
},
tools: {
[`${projection.serverName}_*`]: true,
},
};
}
```
## Testing Plan
- Unit test provider projection builders for Codex TOML, Claude query options,
OpenCode JSON config, and Cursor unsupported/external-only behavior.
- Unit test MCP schemas and error mapping: validation errors return
`isError: true` when actionable, protocol errors stay JSON-RPC errors.
- Replay-backed integration test: a synthetic parent MCP `delegate_task` call
creates `DelegatedTaskRequested`, a child execution node, a child provider
effect, child runtime events, and a result context transfer.
- Failure tests: provider unavailable, missing model, runtime mode escalation,
duplicate `clientRequestId`, child timeout, child cancellation, and parent
session restart.
- Provider-specific tests should mock only external harness/process layers,
not orchestration business logic.
## Sources Checked
- OpenAI Codex MCP configuration:
https://developers.openai.com/codex/mcp
- OpenAI Codex app-server lifecycle and MCP app-server methods observed in
generated local protocol:
https://developers.openai.com/codex/app-server
- Claude Agent SDK MCP options and `allowedTools`:
https://code.claude.com/docs/en/agent-sdk/mcp
- OpenCode MCP configuration:
https://opencode.ai/docs/mcp-servers
- Cursor CLI MCP behavior:
https://docs.cursor.com/cli/mcp
- MCP tool call and result schema:
https://modelcontextprotocol.io/specification/2025-06-18/schema