This commit is contained in:
Julius Marminge committed 2026-06-13 22:46:37 -07:00
1 parent acc41f4742
commit dbb184bb8a
59 files changed
+2364 -1228

No files matched your search

@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed<string | null>(null)),
Effect.orElseSucceed((): string | null => null),
);
const dnsName =
input.statusJson === undefined
@@ -9,13 +9,13 @@ import { ProviderInstanceId, type ProviderReplayEntry } from "@t3tools/contracts
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Random from "effect/Random";
import {
makeClaudeQueryOptions,
makeClaudeUserMessage,
type ClaudeAgentSdkQueryOptions,
} from "../src/orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import { randomUuidV4 } from "../src/orchestration-v2/RandomUuid.ts";
import { makeCheckpointWorkspace } from "../src/orchestration-v2/testkit/ReplayFixtureWorkspace.ts";
const SCENARIO = "thread_fork_native_fork_local_rollback";
@@ -227,7 +227,7 @@ const pathFragments = [
[process.env.HOME ?? "", "/home/replay-user"],
] as const;
const sessionId =
process.env.T3_CLAUDE_REPLAY_SESSION_ID ?? (await Effect.runPromise(Random.nextUUIDv4));
process.env.T3_CLAUDE_REPLAY_SESSION_ID ?? (await Effect.runPromise(randomUuidV4));
const entries: Array<ProviderReplayEntry> = [];
const metadata: Record<string, unknown> = {
prompts: [SOURCE_PROMPT, FORK_FIRST_PROMPT, FORK_SECOND_PROMPT, FORK_AFTER_ROLLBACK_PROMPT],
@@ -20,6 +20,8 @@ import {
PROVIDER_THREAD_RESUME_FIRST_PROMPT,
PROVIDER_THREAD_RESUME_SECOND_PROMPT,
SIMPLE_PROMPT,
SUBAGENT_CONTINUE_PARENT_PROMPT,
SUBAGENT_CONTINUE_PROMPT,
SUBAGENT_PROMPT,
THREAD_ROLLBACK_AFTER_PROMPT,
THREAD_ROLLBACK_FIRST_PROMPT,
@@ -64,6 +66,7 @@ const SCENARIO_NAMES = [
"tool_call_workspace_never",
"tool_call_restricted_granular",
"subagent",
"subagent_continue",
"multi_turn",
"provider_thread_resume",
"todo_list",
@@ -411,6 +414,31 @@ function scenarios(): ReadonlyArray<ReplayScenario> {
},
],
},
{
name: "subagent_continue",
fileName: "subagent_continue.ndjson",
description:
"A root turn spawns one native Codex subagent, then a later root turn resumes and messages the same child thread.",
runs: [
{
name: "continued-subagent",
description:
"The second root turn asks Codex to continue the subagent created by the first root turn.",
steps: [
{
type: "turn",
label: "spawn-subagent",
prompt: SUBAGENT_CONTINUE_PROMPT,
},
{
type: "turn",
label: "continue-subagent",
prompt: SUBAGENT_CONTINUE_PARENT_PROMPT,
},
],
},
],
},
{
name: "multi_turn",
fileName: "multi_turn.ndjson",
@@ -2,6 +2,7 @@ import {
ClaudeSettings,
MessageId,
NodeId,
ProjectId,
ProviderInstanceId,
ProviderSessionId,
ProviderTurnId,
@@ -32,6 +33,8 @@ import {
} from "./ClaudeAdapterV2.ts";
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({});
describe("ClaudeAdapterV2 runtime query policy", () => {
it("maps canonical read-only never policy to Claude dontAsk with read-only tools", () => {
const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(
@@ -240,7 +243,7 @@ describe("ClaudeAdapterV2 native fork", () => {
}> = [];
const adapter = makeClaudeAdapterV2({
instanceId: CLAUDE_DEFAULT_INSTANCE_ID,
settings: Schema.decodeSync(ClaudeSettings)({}),
settings: DEFAULT_CLAUDE_SETTINGS,
environment: {},
idAllocator,
queryRunner: {
@@ -333,9 +336,35 @@ describe("ClaudeAdapterV2 native fork", () => {
assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, providerTurnId);
yield* runtime.startTurn({
appThread: {
id: targetThreadId,
projectId: ProjectId.make("project-claude-fork-target"),
title: "Claude fork target",
defaultProvider: ProviderInstanceId.make(CLAUDE_PROVIDER),
modelSelection: {
instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER),
model: "claude-sonnet-4-6",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: forkedProviderThread.id,
lineage: {
parentThreadId: sourceThreadId,
relationshipToParent: "fork",
rootThreadId: sourceThreadId,
},
forkedFrom: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
deletedAt: null,
},
threadId: targetThreadId,
runId: RunId.make("run-claude-fork-target"),
runOrdinal: 1,
providerTurnOrdinal: 1,
attemptId: RunAttemptId.make("run-attempt-claude-fork-target"),
rootNodeId: NodeId.make("node-claude-fork-target-root"),
providerThread: forkedProviderThread,
@@ -17,7 +17,6 @@ import {
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
@@ -39,6 +38,7 @@ import {
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts";
import { makeDriverLayer as makeProviderAdapterRegistryDriverLayer } from "../ProviderAdapterRegistry.ts";
import { randomUuidV4 } from "../RandomUuid.ts";
import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
export const CLAUDE_AGENT_SDK_REPLAY_PROTOCOL = "claude-agent-sdk.query" as const;
@@ -59,7 +59,7 @@ export class ClaudeReplayTranscriptDecodeError extends Schema.TaggedErrorClass<C
provider: Schema.optional(Schema.String),
protocol: Schema.optional(Schema.String),
scenario: Schema.optional(Schema.String),
cause: Schema.Defect,
cause: Schema.Defect(),
},
) {
override get message(): string {
@@ -140,7 +140,7 @@ export class ClaudeReplayDriverError extends Schema.TaggedErrorClass<ClaudeRepla
"ClaudeReplayDriverError",
{
scenario: Schema.String,
cause: Schema.Defect,
cause: Schema.Defect(),
},
) {
override get message(): string {
@@ -2166,7 +2166,7 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
}
const entries: Array<ProviderReplayEntry> = [];
const sessionId = input.sessionId ?? (await Effect.runPromise(Random.nextUUIDv4));
const sessionId = input.sessionId ?? (await Effect.runPromise(randomUuidV4));
const queryMode = input.queryMode ?? "streaming";
const recordingMetadata: Record<string, unknown> = {};
if (queryMode === "streaming") {
@@ -39,6 +39,7 @@ import {
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -47,7 +48,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
@@ -90,11 +90,17 @@ import {
type ProviderAdapterDriver,
type ProviderAdapterDriverCreateInput,
} from "../ProviderAdapterDriver.ts";
import {
makeSubagentChildThread,
makeSubagentConversationArtifacts,
subagentThreadTitle,
} from "../SubagentProjection.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);
const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({});
export const ClaudeProviderCapabilitiesV2 = {
sessions: {
@@ -255,7 +261,7 @@ export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedErrorClass<Clau
"ClaudeAgentSdkQueryRunnerError",
{
method: Schema.String,
cause: Schema.Defect,
cause: Schema.Defect(),
},
) {
override get message(): string {
@@ -277,7 +283,7 @@ export interface ClaudeAgentSdkQueryRunnerShape {
export class ClaudeAgentSdkQueryRunner extends Context.Service<
ClaudeAgentSdkQueryRunner,
ClaudeAgentSdkQueryRunnerShape
>()("t3/orchestration-v2/ClaudeAgentSdkQueryRunner") {}
>()("t3/orchestration-v2/Adapters/ClaudeAdapterV2/ClaudeAgentSdkQueryRunner") {}
export interface ClaudeAgentSdkSessionForkInput {
readonly sessionId: string;
@@ -437,17 +443,20 @@ export function makeClaudeAgentSdkProtocolLogger(input: {
export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<
ClaudeAgentSdkQueryRunner,
never,
ServerConfig
Crypto.Crypto | ServerConfig
> = Layer.effect(
ClaudeAgentSdkQueryRunner,
Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const crypto = yield* Crypto.Crypto;
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
return ClaudeAgentSdkQueryRunner.of({
allocateSessionId: Random.nextUUIDv4,
allocateSessionId: crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => queryRunnerError(cause, "allocateSessionId")),
),
open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(function* (
input: ClaudeAgentSdkQueryOpenInput,
) {
@@ -1211,6 +1220,31 @@ function claudeNativeToolOutputText(output: ClaudeNativeToolOutput): string {
return typeof value === "string" ? value : value === undefined ? "" : jsonStringifyForTool(value);
}
function claudeSubagentResultText(output: ClaudeNativeToolOutput): string {
const value = claudeNativeToolOutputValue(output);
if (typeof value === "object" && value !== null && "content" in value) {
const content = value.content;
if (Array.isArray(content)) {
const text = content
.flatMap((part) =>
typeof part === "object" &&
part !== null &&
"type" in part &&
part.type === "text" &&
"text" in part &&
typeof part.text === "string"
? [part.text]
: [],
)
.join("\n");
if (text.length > 0) {
return text;
}
}
}
return claudeNativeToolOutputText(output);
}
function webSearchPatternsFromClaudeTool(input: {
readonly toolInput: ClaudeNativeToolInput;
readonly output: ClaudeNativeToolOutput;
@@ -1266,6 +1300,7 @@ function outputFromClaudeToolResult(
return toolResult.content;
case "bash_code_execution_tool_result":
case "code_execution_tool_result":
case "advisor_tool_result":
case "text_editor_code_execution_tool_result":
case "tool_search_tool_result":
case "web_fetch_tool_result":
@@ -1302,6 +1337,7 @@ function isClaudeToolResultError(toolResult: ClaudeToolResultContentBlock): bool
return toolResult.is_error;
case "bash_code_execution_tool_result":
case "code_execution_tool_result":
case "advisor_tool_result":
case "text_editor_code_execution_tool_result":
case "tool_search_tool_result":
case "web_fetch_tool_result":
@@ -1318,6 +1354,8 @@ function toolNameFromClaudeToolResult(toolResult: ClaudeToolResultContentBlock):
return "bash_code_execution";
case "code_execution_tool_result":
return "code_execution";
case "advisor_tool_result":
return "advisor";
case "mcp_tool_result":
return "mcp_tool";
case "text_editor_code_execution_tool_result":
@@ -1569,14 +1607,18 @@ interface ActiveClaudeTurnContext {
};
readonly toolCalls: Map<string, ActiveClaudeToolCall>;
readonly subagentsByTaskId: Map<string, ActiveClaudeSubagent>;
readonly subagentsByToolUseId: Map<string, ActiveClaudeSubagent>;
readonly subagentNodesByTaskId: Map<string, OrchestrationV2ExecutionNode["id"]>;
readonly subagentNodesByToolUseId: Map<string, OrchestrationV2ExecutionNode["id"]>;
}
interface ActiveClaudeSubagent {
task: OrchestrationV2Subagent;
readonly childThreadId: ThreadId;
readonly childRootNodeId: OrchestrationV2ExecutionNode["id"];
readonly turnItemId: OrchestrationV2TurnItem["id"];
readonly turnItemOrdinal: number;
nextChildItemOrdinal: number;
resultItemOrdinal: number | null;
}
interface ClaudeLiveQueryContext {
@@ -1592,7 +1634,11 @@ interface ActiveClaudeToolCall {
readonly toolName: string;
readonly classification: ClaudeToolClassification;
readonly input: ClaudeNativeToolInput;
readonly threadId: ThreadId;
readonly runId: ProviderAdapterV2TurnInput["runId"] | null;
readonly rootNodeId: OrchestrationV2ExecutionNode["id"];
readonly parentNodeId: OrchestrationV2ExecutionNode["id"];
readonly ordinal: number;
readonly startedAt: DateTime.Utc;
}
@@ -1635,7 +1681,6 @@ export function makeClaudeAdapterV2(
const steeredTurns = yield* Ref.make(new Set<OrchestrationV2ProviderTurn["id"]>());
const queryContext = yield* Ref.make<ClaudeLiveQueryContext | null>(null);
const openedNativeThreads = yield* Ref.make(new Set<string>());
const nextProviderTurnOrdinals = yield* Ref.make(new Map<string, number>());
const itemOrdinals = yield* Ref.make(new Map<string, number>());
const nextItemOrdinalsByTurn = yield* Ref.make(new Map<string, number>());
const pendingRuntimeRequests = yield* Ref.make(
@@ -1692,13 +1737,17 @@ export function makeClaudeAdapterV2(
completedAt: input.completedAt,
});
const buildToolCallArtifacts = Effect.fnUntraced(function* (input: {
const buildToolCallArtifacts = (input: {
readonly context: ActiveClaudeTurnContext;
readonly nativeItemId: string;
readonly toolName: string;
readonly classification: ClaudeToolClassification;
readonly toolInput: ClaudeNativeToolInput;
readonly threadId: ThreadId;
readonly runId: ProviderAdapterV2TurnInput["runId"] | null;
readonly rootNodeId: OrchestrationV2ExecutionNode["id"];
readonly parentNodeId: OrchestrationV2ExecutionNode["id"];
readonly ordinal: number;
readonly output: ClaudeNativeToolOutput;
readonly status: Extract<
OrchestrationV2TurnItem["status"],
@@ -1706,7 +1755,7 @@ export function makeClaudeAdapterV2(
>;
readonly startedAt: DateTime.Utc;
readonly updatedAt: DateTime.Utc;
}) {
}) => {
const completedAt = input.status === "running" ? null : input.updatedAt;
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CLAUDE_PROVIDER,
@@ -1721,18 +1770,17 @@ export function makeClaudeAdapterV2(
nativeId: input.nativeItemId,
strength: "strong" as const,
};
const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.threadId,
runId: input.runId,
parentNodeId: input.parentNodeId,
rootNodeId: input.context.input.rootNodeId,
rootNodeId: input.rootNodeId,
kind: "tool_call",
status: input.status,
countsForRun: false,
providerThreadId: input.context.input.providerThread.id,
providerTurnId: input.context.providerTurnId,
providerThreadId: input.runId === null ? null : input.context.input.providerThread.id,
providerTurnId: input.runId === null ? null : input.context.providerTurnId,
nativeItemRef,
runtimeRequestId: null,
checkpointScopeId: null,
@@ -1741,14 +1789,14 @@ export function makeClaudeAdapterV2(
};
const itemBase = {
id: turnItemId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.threadId,
runId: input.runId,
nodeId,
providerThreadId: input.context.input.providerThread.id,
providerTurnId: input.context.providerTurnId,
providerThreadId: input.runId === null ? null : input.context.input.providerThread.id,
providerTurnId: input.runId === null ? null : input.context.providerTurnId,
nativeItemRef,
parentItemId: null,
ordinal,
ordinal: input.ordinal,
status: input.status,
title: null,
startedAt: input.startedAt,
@@ -1811,7 +1859,7 @@ export function makeClaudeAdapterV2(
...(outputValue === undefined ? {} : { output: outputValue }),
};
return { node, turnItem };
});
};
const emitToolCallArtifacts = Effect.fnUntraced(function* (artifacts: {
readonly node: OrchestrationV2ExecutionNode;
@@ -1841,30 +1889,38 @@ export function makeClaudeAdapterV2(
"running" | "completed" | "failed" | "cancelled"
>;
}) {
const existingNodeId =
input.context.subagentNodesByTaskId.get(input.taskId) ??
const existingSubagent =
input.context.subagentsByTaskId.get(input.taskId) ??
(input.toolUseId === undefined
? undefined
: input.context.subagentNodesByToolUseId.get(input.toolUseId));
if (existingNodeId === undefined && input.status !== "running") {
: input.context.subagentsByToolUseId.get(input.toolUseId));
if (existingSubagent === undefined && input.status !== "running") {
return;
}
const now = yield* DateTime.now;
const nativeItemId = `task:${input.taskId}`;
const nodeId =
existingNodeId ??
existingSubagent?.task.id ??
idAllocator.derive.nodeFromProviderItem({
provider: CLAUDE_PROVIDER,
nativeItemId,
});
if (existingNodeId === undefined) {
const childRootNodeId =
existingSubagent?.childRootNodeId ??
idAllocator.derive.nodeFromProviderItem({
provider: CLAUDE_PROVIDER,
nativeItemId: `${nativeItemId}:thread-root`,
});
const childThreadId =
existingSubagent?.childThreadId ??
idAllocator.derive.threadFromProviderThread({
provider: CLAUDE_PROVIDER,
nativeThreadId: `${input.context.input.providerThread.id}:${input.taskId}`,
});
if (existingSubagent === undefined) {
input.context.subagentNodesByTaskId.set(input.taskId, nodeId);
if (input.toolUseId !== undefined) {
input.context.subagentNodesByToolUseId.set(input.toolUseId, nodeId);
}
}
const existingSubagent = input.context.subagentsByTaskId.get(input.taskId);
const turnItemOrdinal =
existingSubagent?.turnItemOrdinal ??
(yield* resolveItemOrdinal(input.context, `${nativeItemId}:subagent`));
@@ -1878,7 +1934,7 @@ export function makeClaudeAdapterV2(
createdBy: "agent" as const,
provider: CLAUDE_PROVIDER,
providerThreadId: null,
childThreadId: null,
childThreadId,
nativeTaskRef: {
provider: CLAUDE_PROVIDER,
nativeId: input.taskId,
@@ -1899,6 +1955,8 @@ export function makeClaudeAdapterV2(
} satisfies OrchestrationV2Subagent;
const subagent = {
task,
childThreadId,
childRootNodeId,
turnItemId:
existingSubagent?.turnItemId ??
idAllocator.derive.turnItemFromProviderItem({
@@ -1906,8 +1964,36 @@ export function makeClaudeAdapterV2(
nativeItemId: `${nativeItemId}:subagent`,
}),
turnItemOrdinal,
nextChildItemOrdinal: existingSubagent?.nextChildItemOrdinal ?? 100,
resultItemOrdinal: existingSubagent?.resultItemOrdinal ?? null,
} satisfies ActiveClaudeSubagent;
input.context.subagentsByTaskId.set(input.taskId, subagent);
if (input.toolUseId !== undefined) {
input.context.subagentsByToolUseId.set(input.toolUseId, subagent);
}
if (existingSubagent === undefined) {
const childThread = makeSubagentChildThread({
parentThread: input.context.input.appThread,
childThreadId,
parentNodeId: nodeId,
activeProviderThreadId: null,
providerInstanceId: input.context.input.modelSelection.instanceId,
modelSelection: input.context.input.modelSelection,
title: subagentThreadTitle({
parentTitle: input.context.input.appThread.title,
prompt: task.prompt,
title: task.title,
ordinal: input.context.subagentsByTaskId.size,
}),
now,
});
yield* emitProviderEvent({
type: "app_thread.created",
provider: CLAUDE_PROVIDER,
appThread: childThread,
});
}
yield* emitProviderEvent({
type: "node.updated",
@@ -1934,6 +2020,63 @@ export function makeClaudeAdapterV2(
completedAt: input.status === "running" ? null : now,
},
});
yield* emitProviderEvent({
type: "node.updated",
provider: CLAUDE_PROVIDER,
node: {
id: childRootNodeId,
threadId: childThreadId,
runId: null,
parentNodeId: null,
rootNodeId: childRootNodeId,
kind: "root_turn",
status: input.status,
countsForRun: false,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: task.nativeTaskRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: task.startedAt,
completedAt: input.status === "running" ? null : now,
},
});
if (existingSubagent === undefined) {
const promptNativeItemId = `${nativeItemId}:prompt`;
const promptArtifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({
provider: CLAUDE_PROVIDER,
nativeItemId: promptNativeItemId,
}),
turnItemId: idAllocator.derive.turnItemFromProviderItem({
provider: CLAUDE_PROVIDER,
nativeItemId: promptNativeItemId,
}),
threadId: childThreadId,
rootNodeId: childRootNodeId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: {
provider: CLAUDE_PROVIDER,
nativeId: promptNativeItemId,
strength: "strong",
},
role: "user",
text: task.prompt,
ordinal: 100,
now,
});
yield* emitProviderEvent({
type: "message.updated",
provider: CLAUDE_PROVIDER,
message: promptArtifacts.message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CLAUDE_PROVIDER,
turnItem: promptArtifacts.turnItem,
});
}
yield* emitProviderEvent({
type: "subagent.updated",
provider: CLAUDE_PROVIDER,
@@ -1966,6 +2109,49 @@ export function makeClaudeAdapterV2(
result: task.result,
},
});
if (
input.result !== undefined &&
input.result.trim().length > 0 &&
input.status !== "running"
) {
const resultNativeItemId = `${nativeItemId}:result`;
const resultItemOrdinal = subagent.resultItemOrdinal ?? ++subagent.nextChildItemOrdinal;
subagent.resultItemOrdinal = resultItemOrdinal;
const resultArtifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({
provider: CLAUDE_PROVIDER,
nativeItemId: resultNativeItemId,
}),
turnItemId: idAllocator.derive.turnItemFromProviderItem({
provider: CLAUDE_PROVIDER,
nativeItemId: resultNativeItemId,
}),
threadId: childThreadId,
rootNodeId: childRootNodeId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: {
provider: CLAUDE_PROVIDER,
nativeId: resultNativeItemId,
strength: "strong",
},
role: "assistant",
text: input.result,
ordinal: resultItemOrdinal,
now,
});
yield* emitProviderEvent({
type: "message.updated",
provider: CLAUDE_PROVIDER,
message: resultArtifacts.message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CLAUDE_PROVIDER,
turnItem: resultArtifacts.turnItem,
});
}
});
const ensureToolCallStarted = Effect.fnUntraced(function* (input: {
@@ -1981,32 +2167,49 @@ export function makeClaudeAdapterV2(
}
const startedAt = yield* DateTime.now;
const classification = classifyClaudeNativeTool(input.toolName);
const parentNodeId =
const subagent =
input.parentToolUseId === null
? input.context.input.rootNodeId
: (input.context.subagentNodesByToolUseId.get(input.parentToolUseId) ??
input.context.input.rootNodeId);
? undefined
: input.context.subagentsByToolUseId.get(input.parentToolUseId);
const threadId = subagent?.childThreadId ?? input.context.input.threadId;
const runId = subagent === undefined ? input.context.input.runId : null;
const rootNodeId = subagent?.childRootNodeId ?? input.context.input.rootNodeId;
const parentNodeId = rootNodeId;
const ordinal =
subagent === undefined
? yield* resolveItemOrdinal(input.context, input.nativeItemId)
: ++subagent.nextChildItemOrdinal;
const toolCall: ActiveClaudeToolCall = {
nativeItemId: input.nativeItemId,
toolName: input.toolName,
classification,
input: input.toolInput,
threadId,
runId,
rootNodeId,
parentNodeId,
ordinal,
startedAt,
};
input.context.toolCalls.set(input.nativeItemId, toolCall);
yield* buildToolCallArtifacts({
context: input.context,
nativeItemId: input.nativeItemId,
toolName: input.toolName,
classification,
toolInput: input.toolInput,
parentNodeId,
output: NO_CLAUDE_NATIVE_TOOL_OUTPUT,
status: "running",
startedAt,
updatedAt: startedAt,
}).pipe(Effect.flatMap(emitToolCallArtifacts));
yield* emitToolCallArtifacts(
buildToolCallArtifacts({
context: input.context,
nativeItemId: input.nativeItemId,
toolName: input.toolName,
classification,
toolInput: input.toolInput,
threadId,
runId,
rootNodeId,
parentNodeId,
ordinal,
output: NO_CLAUDE_NATIVE_TOOL_OUTPUT,
status: "running",
startedAt,
updatedAt: startedAt,
}),
);
return toolCall;
});
@@ -2110,13 +2313,17 @@ export function makeClaudeAdapterV2(
readonly completedAt: DateTime.Utc;
}) {
for (const toolCall of input.context.toolCalls.values()) {
const artifacts = yield* buildToolCallArtifacts({
const artifacts = buildToolCallArtifacts({
context: input.context,
nativeItemId: toolCall.nativeItemId,
toolName: toolCall.toolName,
classification: toolCall.classification,
toolInput: toolCall.input,
threadId: toolCall.threadId,
runId: toolCall.runId,
rootNodeId: toolCall.rootNodeId,
parentNodeId: toolCall.parentNodeId,
ordinal: toolCall.ordinal,
output: NO_CLAUDE_NATIVE_TOOL_OUTPUT,
status: "failed",
startedAt: toolCall.startedAt,
@@ -2286,6 +2493,9 @@ export function makeClaudeAdapterV2(
}
for (const toolUse of claudeToolUseBlocksFromAssistantMessage(message)) {
if (toolUse.name === "Agent") {
continue;
}
yield* ensureToolCallStarted({
context,
nativeItemId: toolUse.id,
@@ -2296,6 +2506,18 @@ export function makeClaudeAdapterV2(
}
for (const { toolResult, output } of claudeToolResultEntriesFromMessage(message)) {
const subagent = context.subagentsByToolUseId.get(toolResult.tool_use_id);
if (subagent !== undefined) {
const result = claudeSubagentResultText(output);
yield* updateClaudeSubagentNode({
context,
taskId: subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id),
toolUseId: toolResult.tool_use_id,
...(result.length === 0 ? {} : { result }),
status: isClaudeToolResultError(toolResult) ? "failed" : "completed",
});
continue;
}
const parentToolUseId = parentToolUseIdFromSdkMessage(message);
const toolCall =
context.toolCalls.get(toolResult.tool_use_id) ??
@@ -2307,13 +2529,17 @@ export function makeClaudeAdapterV2(
parentToolUseId,
}));
const completedAt = yield* DateTime.now;
const artifacts = yield* buildToolCallArtifacts({
const artifacts = buildToolCallArtifacts({
context,
nativeItemId: toolCall.nativeItemId,
toolName: toolCall.toolName,
classification: toolCall.classification,
toolInput: toolCall.input,
threadId: toolCall.threadId,
runId: toolCall.runId,
rootNodeId: toolCall.rootNodeId,
parentNodeId: toolCall.parentNodeId,
ordinal: toolCall.ordinal,
output,
status: isClaudeToolResultError(toolResult) ? "failed" : "completed",
startedAt: toolCall.startedAt,
@@ -2376,13 +2602,15 @@ export function makeClaudeAdapterV2(
const nativeRequestId = callbackOptions.toolUseID;
const nativeToolInput = claudeNativeToolInputFromRecord(toolInput);
yield* ensureToolCallStarted({
context,
nativeItemId: nativeRequestId,
toolName,
toolInput: nativeToolInput,
parentToolUseId: null,
});
if (toolName !== "Agent") {
yield* ensureToolCallStarted({
context,
nativeItemId: nativeRequestId,
toolName,
toolInput: nativeToolInput,
parentToolUseId: null,
});
}
const requestKind = providerRequestKindFromClaudeTool(toolName);
const prompt =
@@ -2551,16 +2779,7 @@ export function makeClaudeAdapterV2(
provider: CLAUDE_PROVIDER,
nativeTurnId,
});
const providerTurnOrdinal = yield* Ref.modify(nextProviderTurnOrdinals, (current) => {
const previous = current.get(String(turnInput.providerThread.id));
const next =
previous === undefined
? turnInput.runOrdinal
: Math.max(previous + 1, turnInput.runOrdinal);
const updated = new Map(current);
updated.set(String(turnInput.providerThread.id), next);
return [next, updated];
});
const providerTurnOrdinal = turnInput.providerTurnOrdinal;
const currentTurn = yield* Ref.get(activeTurn);
if (currentTurn !== null) {
return yield* new ProviderAdapterProtocolError({
@@ -2581,8 +2800,8 @@ export function makeClaudeAdapterV2(
},
toolCalls: new Map(),
subagentsByTaskId: new Map(),
subagentsByToolUseId: new Map(),
subagentNodesByTaskId: new Map(),
subagentNodesByToolUseId: new Map(),
};
const querySession = yield* openQuery(turnInput, nativeThreadId);
yield* Ref.set(activeTurn, context);
@@ -3016,7 +3235,7 @@ export const ClaudeAdapterV2Driver: ProviderAdapterDriver<
> = {
driverKind: CLAUDE_DRIVER_KIND,
configSchema: ClaudeSettings,
defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}),
defaultConfig: (): ClaudeSettings => DEFAULT_CLAUDE_SETTINGS,
create: Effect.fn("ClaudeAdapterV2Driver.create")(
function* (input: ProviderAdapterDriverCreateInput<ClaudeSettings>) {
const { instanceId, environment, enabled, config } = input;
@@ -3053,7 +3272,7 @@ const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function*
return makeClaudeAdapterV2({
instanceId: CLAUDE_DEFAULT_INSTANCE_ID,
settings: Schema.decodeSync(ClaudeSettings)({}),
settings: DEFAULT_CLAUDE_SETTINGS,
environment: process.env,
idAllocator,
queryRunner,
@@ -28,7 +28,7 @@ export class CodexReplayTranscriptDecodeError extends Schema.TaggedErrorClass<Co
provider: Schema.optional(Schema.String),
protocol: Schema.optional(Schema.String),
scenario: Schema.optional(Schema.String),
cause: Schema.Defect,
cause: Schema.Defect(),
},
) {
override get message(): string {
@@ -75,10 +75,16 @@ import {
type ProviderAdapterV2SteerInput,
type ProviderAdapterV2TurnInput,
} from "../ProviderAdapter.ts";
import {
makeSubagentChildThread,
makeSubagentConversationArtifacts,
subagentThreadTitle,
} from "../SubagentProjection.ts";
const CODEX_PROVIDER = "codex" as const;
export const CODEX_DRIVER_KIND = ProviderDriverKind.make(CODEX_PROVIDER);
export const CODEX_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CODEX_DRIVER_KIND);
const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({});
const CODEX_CLIENT_INFO = {
name: "t3code_desktop",
title: "T3 Code Desktop",
@@ -197,6 +203,15 @@ function codexTimestamp(seconds: number | null | undefined): DateTime.Utc {
: DateTime.makeUnsafe(seconds * 1000);
}
function codexUserMessageText(
content: ReadonlyArray<CodexSchema.V2ItemCompletedNotification__UserInput>,
): string {
return content
.flatMap((item) => (item.type === "text" ? [item.text] : []))
.join("\n")
.trim();
}
function mapCodexTurnStatus(
status: CodexSchema.V2TurnCompletedNotification__TurnStatus,
): OrchestrationV2ProviderTurn["status"] {
@@ -589,6 +604,8 @@ export const resolveCodexRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveRo
interface ActiveCodexTurnContext {
readonly input: ProviderAdapterV2TurnInput;
readonly projectionThreadId: ThreadId;
readonly projectionRunId: ProviderAdapterV2TurnInput["runId"] | null;
readonly nativeTurnId: string;
readonly providerThread: OrchestrationV2ProviderThread;
readonly providerTurnId: ProviderTurnId;
@@ -598,6 +615,7 @@ interface ActiveCodexTurnContext {
readonly providerNodeStartedAt: DateTime.Utc | null;
readonly itemParentNodeId: OrchestrationV2ExecutionNode["id"];
readonly rootNodeId: OrchestrationV2ExecutionNode["id"];
readonly subagent: CodexSubagentThreadContext | null;
readonly startedAt: DateTime.Utc;
}
@@ -605,6 +623,8 @@ interface CodexSubagentThreadContext {
readonly parentContext: ActiveCodexTurnContext;
readonly providerThread: OrchestrationV2ProviderThread;
readonly subagentNodeId: OrchestrationV2ExecutionNode["id"];
readonly childRootNodeId: OrchestrationV2ExecutionNode["id"];
readonly childThreadId: ThreadId;
readonly nativeToolCallId: string;
readonly ordinal: number;
readonly startedAt: DateTime.Utc;
@@ -659,7 +679,7 @@ export interface CodexAppServerClientFactoryShape {
export class CodexAppServerClientFactory extends Context.Service<
CodexAppServerClientFactory,
CodexAppServerClientFactoryShape
>()("t3/orchestration-v2/CodexAppServerClientFactory") {}
>()("t3/orchestration-v2/Adapters/CodexAdapterV2/CodexAppServerClientFactory") {}
export const makeCodexAppServerClientFactoryCommandLayer = (
options: CodexClient.CodexAppServerCommandLayerOptions,
@@ -792,7 +812,7 @@ export type CodexAdapterV2DriverEnv =
export const CodexAdapterV2Driver: ProviderAdapterDriver<CodexSettings, CodexAdapterV2DriverEnv> = {
driverKind: CODEX_DRIVER_KIND,
configSchema: CodexSettings,
defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}),
defaultConfig: (): CodexSettings => DEFAULT_CODEX_SETTINGS,
create: ({ instanceId, environment, enabled, config }) =>
Effect.gen(function* () {
const clientFactory = yield* CodexAppServerClientFactory;
@@ -845,7 +865,7 @@ export const layer: Layer.Layer<
return makeCodexAdapterV2({
instanceId: CODEX_DEFAULT_INSTANCE_ID,
settings: Schema.decodeSync(CodexSettings)({}),
settings: DEFAULT_CODEX_SETTINGS,
environment: process.env,
clientFactory,
fileSystem,
@@ -910,6 +930,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
const pendingSubagentTurns = yield* Ref.make(
new Map<string, ReadonlyArray<PendingCodexSubagentTurnStarted>>(),
);
const nextProviderTurnOrdinals = yield* Ref.make(new Map<string, number>());
const itemOrdinals = yield* Ref.make(new Map<string, number>());
const nextItemOrdinalsByTurn = yield* Ref.make(new Map<string, number>());
const agentMessageDeltas = yield* Ref.make(new Map<string, string>());
@@ -953,6 +974,18 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return nextOrdinal;
});
const nextProviderTurnOrdinal = (
providerThreadId: OrchestrationV2ProviderThread["id"],
minimum: number,
) =>
Ref.modify(nextProviderTurnOrdinals, (current) => {
const previous = current.get(String(providerThreadId));
const next = previous === undefined ? minimum : Math.max(previous + 1, minimum);
const updated = new Map(current);
updated.set(String(providerThreadId), next);
return [next, updated];
});
const emitSubagentTaskUpdate = (input: {
readonly subagent: CodexSubagentThreadContext;
readonly status: OrchestrationV2Subagent["status"];
@@ -1019,18 +1052,31 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
provider: CODEX_PROVIDER,
nativeTurnId: turn.nativeTurnId,
});
const providerTurnOrdinal = yield* nextProviderTurnOrdinal(
subagent.providerThread.id,
1,
);
const providerNodeId =
providerTurnOrdinal === 1
? subagent.childRootNodeId
: idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: `${turn.nativeTurnId}:thread-root`,
});
const activeContext: ActiveCodexTurnContext = {
input: subagent.parentContext.input,
projectionThreadId: subagent.childThreadId,
projectionRunId: null,
nativeTurnId: turn.nativeTurnId,
providerThread: subagent.providerThread,
providerTurnId,
providerTurnOrdinal:
subagent.parentContext.providerTurnOrdinal * 100 + subagent.ordinal,
providerNodeId: subagent.subagentNodeId,
providerNodeKind: "subagent",
providerNodeStartedAt: subagent.startedAt,
itemParentNodeId: subagent.subagentNodeId,
rootNodeId: subagent.parentContext.rootNodeId,
providerTurnOrdinal,
providerNodeId,
providerNodeKind: "root_turn",
providerNodeStartedAt: turn.startedAt,
itemParentNodeId: providerNodeId,
rootNodeId: providerNodeId,
subagent,
startedAt: turn.startedAt,
};
yield* Ref.update(activeTurns, (current) => {
@@ -1051,11 +1097,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
yield* emitProviderEvent({
type: "provider_turn.updated",
provider: CODEX_PROVIDER,
threadId: subagent.childThreadId,
providerTurn: {
id: providerTurnId,
providerThreadId: subagent.providerThread.id,
nodeId: subagent.subagentNodeId,
runAttemptId: subagent.parentContext.input.attemptId,
nodeId: providerNodeId,
runAttemptId: null,
nativeTurnRef: {
provider: CODEX_PROVIDER,
nativeId: turn.nativeTurnId,
@@ -1067,6 +1114,27 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
completedAt: null,
},
});
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: {
id: providerNodeId,
threadId: subagent.childThreadId,
runId: null,
parentNodeId: null,
rootNodeId: providerNodeId,
kind: "root_turn",
status: "running",
countsForRun: false,
providerThreadId: subagent.providerThread.id,
providerTurnId,
nativeItemRef: subagent.task.nativeTaskRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: turn.startedAt,
completedAt: null,
},
});
});
const rememberSubagentTurnStarted = (input: {
@@ -1104,11 +1172,24 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
const now = yield* DateTime.now;
for (const [index, nativeThreadId] of input.item.receiverThreadIds.entries()) {
const registeredSubagents = yield* Ref.get(subagentThreads);
if (registeredSubagents.has(nativeThreadId)) {
continue;
}
const nativeItemId = `${input.item.id}:${nativeThreadId}`;
const subagentNodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId,
});
const childRootNodeId = idAllocator.derive.nodeFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: `${nativeItemId}:thread-root`,
});
const childThreadId = idAllocator.derive.threadFromProviderThread({
provider: CODEX_PROVIDER,
nativeThreadId,
});
const turnItemOrdinal = yield* resolveItemOrdinal(input.context, nativeItemId);
const providerThread = {
id: idAllocator.derive.providerThread({
@@ -1117,8 +1198,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
}),
provider: CODEX_PROVIDER,
providerSessionId: input.context.providerThread.providerSessionId,
appThreadId: null,
ownerNodeId: subagentNodeId,
appThreadId: childThreadId,
ownerNodeId: null,
nativeThreadRef: {
provider: CODEX_PROVIDER,
nativeId: nativeThreadId,
@@ -1126,8 +1207,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
},
nativeConversationHeadRef: null,
status: "idle" as const,
firstRunOrdinal: input.context.input.runOrdinal,
lastRunOrdinal: input.context.input.runOrdinal,
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: {
providerThreadId: input.context.providerThread.id,
@@ -1145,7 +1226,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
createdBy: "agent",
provider: CODEX_PROVIDER,
providerThreadId: providerThread.id,
childThreadId: null,
childThreadId,
nativeTaskRef: codexNativeItemRef(nativeItemId),
prompt: input.item.prompt ?? "",
title: null,
@@ -1163,6 +1244,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
parentContext: input.context,
providerThread,
subagentNodeId,
childRootNodeId,
childThreadId,
nativeToolCallId: input.item.id,
ordinal: index + 1,
startedAt: now,
@@ -1179,6 +1262,49 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
updated.set(nativeThreadId, subagent);
return updated;
});
const childThread = makeSubagentChildThread({
parentThread: input.context.input.appThread,
childThreadId,
parentNodeId: subagentNodeId,
activeProviderThreadId: providerThread.id,
providerInstanceId: input.context.input.modelSelection.instanceId,
modelSelection: {
...input.context.input.modelSelection,
model: task.model ?? input.context.input.modelSelection.model,
},
title: subagentThreadTitle({
parentTitle: input.context.input.appThread.title,
prompt: task.prompt,
title: task.title,
ordinal: index + 1,
}),
now,
});
const promptNativeItemId = `${nativeItemId}:prompt`;
const promptArtifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: promptNativeItemId,
}),
turnItemId: idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: promptNativeItemId,
}),
threadId: childThreadId,
rootNodeId: childRootNodeId,
providerThreadId: providerThread.id,
providerTurnId: null,
nativeItemRef: codexNativeItemRef(promptNativeItemId),
role: "user",
text: task.prompt,
ordinal: 100,
now,
});
yield* emitProviderEvent({
type: "app_thread.created",
provider: CODEX_PROVIDER,
appThread: childThread,
});
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
@@ -1200,11 +1326,42 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
completedAt: null,
},
});
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: {
id: childRootNodeId,
threadId: childThreadId,
runId: null,
parentNodeId: null,
rootNodeId: childRootNodeId,
kind: "root_turn",
status: "running",
countsForRun: false,
providerThreadId: providerThread.id,
providerTurnId: null,
nativeItemRef: codexNativeItemRef(nativeItemId),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: now,
completedAt: null,
},
});
yield* emitProviderEvent({
type: "provider_thread.updated",
provider: CODEX_PROVIDER,
providerThread,
});
yield* emitProviderEvent({
type: "message.updated",
provider: CODEX_PROVIDER,
message: promptArtifacts.message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: promptArtifacts.turnItem,
});
yield* emitSubagentTaskUpdate({
subagent,
status: "running",
@@ -1229,6 +1386,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
>;
}) =>
Effect.gen(function* () {
if (input.item.tool !== "spawnAgent") {
return;
}
const subagents = yield* Ref.get(subagentThreads);
for (const [nativeThreadId, state] of Object.entries(input.item.agentsStates)) {
const subagent = subagents.get(nativeThreadId);
@@ -1259,8 +1420,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return existing;
}
const planId = yield* idAllocator.allocate.plan({
threadId: context.input.threadId,
runId: context.input.runId,
threadId: context.projectionThreadId,
...(context.projectionRunId === null ? {} : { runId: context.projectionRunId }),
provider: CODEX_PROVIDER,
});
yield* Ref.update(planIds, (current) => {
@@ -1340,8 +1501,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
});
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.input.threadId,
runId: context.input.runId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
parentNodeId: context.itemParentNodeId,
rootNodeId: context.rootNodeId,
kind: "assistant_message",
@@ -1357,8 +1518,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const message: OrchestrationV2ConversationMessage = {
id: messageId,
threadId: context.input.threadId,
runId: context.input.runId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
nodeId,
role: "assistant",
text: item.text,
@@ -1369,8 +1530,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: context.input.threadId,
runId: context.input.runId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
nodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
@@ -1390,6 +1551,56 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return { node, message, turnItem };
});
const emitSubagentUserMessage = (
context: ActiveCodexTurnContext,
item: Extract<
| CodexSchema.V2ItemStartedNotification__ThreadItem
| CodexSchema.V2ItemCompletedNotification__ThreadItem,
{ type: "userMessage" }
>,
) =>
Effect.gen(function* () {
if (context.subagent === null || context.providerTurnOrdinal === 1) {
return false;
}
const text = codexUserMessageText(item.content);
if (text.length === 0) {
return false;
}
const now = yield* DateTime.now;
const ordinal = yield* resolveItemOrdinal(context, item.id);
const artifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
}),
turnItemId: idAllocator.derive.turnItemFromProviderItem({
provider: CODEX_PROVIDER,
nativeItemId: item.id,
}),
threadId: context.projectionThreadId,
rootNodeId: context.rootNodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
role: "user",
text,
ordinal,
now,
});
yield* emitProviderEvent({
type: "message.updated",
provider: CODEX_PROVIDER,
message: artifacts.message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return true;
});
const buildCommandExecutionArtifacts = (
context: ActiveCodexTurnContext,
item: Extract<
@@ -1413,8 +1624,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
const ordinal = yield* resolveItemOrdinal(context, item.id);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.input.threadId,
runId: context.input.runId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
parentNodeId: context.itemParentNodeId,
rootNodeId: context.rootNodeId,
kind: "tool_call",
@@ -1430,8 +1641,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: context.input.threadId,
runId: context.input.runId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
nodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
@@ -1482,8 +1693,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
const ordinal = yield* resolveItemOrdinal(context, item.id);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.input.threadId,
runId: context.input.runId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
parentNodeId: context.itemParentNodeId,
rootNodeId: context.rootNodeId,
kind: "tool_call",
@@ -1499,8 +1710,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: context.input.threadId,
runId: context.input.runId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
nodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
@@ -1540,8 +1751,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
const status = input.completed ? "completed" : "running";
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
parentNodeId: input.context.itemParentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "tool_call",
@@ -1557,8 +1768,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
@@ -1598,8 +1809,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
const plan: OrchestrationV2PlanArtifact = {
id: planId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
nodeId,
kind: "proposed_plan",
status: input.status,
@@ -1607,8 +1818,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
parentNodeId: input.context.itemParentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "plan",
@@ -1624,8 +1835,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
@@ -1668,8 +1879,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
const plan: OrchestrationV2PlanArtifact = {
id: planId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
nodeId,
kind: "todo_list",
status: input.status,
@@ -1678,8 +1889,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
parentNodeId: input.context.itemParentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "todo_list",
@@ -1695,8 +1906,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
@@ -1747,8 +1958,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
}
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
parentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "approval_request",
@@ -1782,8 +1993,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const turnItem: OrchestrationV2TurnItem = {
id: idAllocator.derive.approvalTurnItem({ requestId }),
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
@@ -1845,8 +2056,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
parentNodeId: input.context.itemParentNodeId,
rootNodeId: input.context.rootNodeId,
kind: "user_input_request",
@@ -1880,8 +2091,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
nodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
@@ -2002,6 +2213,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return;
}
if (payload.item.type === "userMessage") {
if (yield* emitSubagentUserMessage(context, payload.item)) {
return;
}
}
if (payload.item.type === "commandExecution") {
const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item);
yield* emitProviderEvent({
@@ -2046,6 +2263,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return;
}
if (payload.item.type === "userMessage") {
if (yield* emitSubagentUserMessage(context, payload.item)) {
return;
}
}
if (payload.item.type === "commandExecution") {
const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item);
yield* emitProviderEvent({
@@ -2168,6 +2391,17 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
provider: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
if (
context.subagent !== null &&
context.providerTurnOrdinal === 1 &&
payload.item.phase !== "commentary"
) {
yield* emitSubagentTaskUpdate({
subagent: context.subagent,
status: context.subagent.task.status,
result: text,
});
}
}).pipe(Effect.orDie),
);
@@ -2210,6 +2444,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
yield* emitProviderEvent({
type: "runtime_request.updated",
provider: CODEX_PROVIDER,
threadId: artifacts.node.threadId,
runtimeRequest: artifacts.request,
});
yield* emitProviderEvent({
@@ -2269,6 +2504,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
yield* emitProviderEvent({
type: "runtime_request.updated",
provider: CODEX_PROVIDER,
threadId: artifacts.node.threadId,
runtimeRequest: artifacts.request,
});
yield* emitProviderEvent({
@@ -2329,6 +2565,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
yield* emitProviderEvent({
type: "runtime_request.updated",
provider: CODEX_PROVIDER,
threadId: artifacts.node.threadId,
runtimeRequest: artifacts.request,
});
yield* emitProviderEvent({
@@ -2390,6 +2627,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
yield* emitProviderEvent({
type: "runtime_request.updated",
provider: CODEX_PROVIDER,
threadId: artifacts.node.threadId,
runtimeRequest: artifacts.request,
});
yield* emitProviderEvent({
@@ -2449,6 +2687,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
yield* emitProviderEvent({
type: "runtime_request.updated",
provider: CODEX_PROVIDER,
threadId: artifacts.node.threadId,
runtimeRequest: artifacts.request,
});
yield* emitProviderEvent({
@@ -2506,6 +2745,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
yield* emitProviderEvent({
type: "runtime_request.updated",
provider: CODEX_PROVIDER,
threadId: artifacts.node.threadId,
runtimeRequest: artifacts.request,
});
yield* emitProviderEvent({
@@ -2540,11 +2780,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
yield* emitProviderEvent({
type: "provider_turn.updated",
provider: CODEX_PROVIDER,
threadId: context.projectionThreadId,
providerTurn: {
id: context.providerTurnId,
providerThreadId: context.providerThread.id,
nodeId: context.providerNodeId,
runAttemptId: context.input.attemptId,
runAttemptId: context.subagent === null ? context.input.attemptId : null,
nativeTurnRef: {
provider: CODEX_PROVIDER,
nativeId: payload.turn.id,
@@ -2556,22 +2797,22 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
completedAt,
},
});
if (context.providerNodeKind === "subagent") {
if (context.subagent !== null) {
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: {
id: context.providerNodeId,
threadId: context.input.threadId,
runId: context.input.runId,
parentNodeId: context.rootNodeId,
threadId: context.projectionThreadId,
runId: null,
parentNodeId: null,
rootNodeId: context.rootNodeId,
kind: "subagent",
kind: "root_turn",
status,
countsForRun: false,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: null,
nativeItemRef: context.subagent.task.nativeTaskRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: context.providerNodeStartedAt,
@@ -2587,19 +2828,36 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
updatedAt: completedAt,
},
});
const nativeThreadId = context.providerThread.nativeThreadRef?.nativeId;
if (nativeThreadId !== null && nativeThreadId !== undefined) {
const subagent = (yield* Ref.get(subagentThreads)).get(nativeThreadId);
if (subagent !== undefined) {
yield* emitSubagentTaskUpdate({
subagent,
if (context.providerTurnOrdinal === 1) {
yield* emitProviderEvent({
type: "node.updated",
provider: CODEX_PROVIDER,
node: {
id: context.subagent.subagentNodeId,
threadId: context.subagent.parentContext.projectionThreadId,
runId: context.subagent.parentContext.projectionRunId,
parentNodeId: context.subagent.parentContext.rootNodeId,
rootNodeId: context.subagent.parentContext.rootNodeId,
kind: "subagent",
status,
countsForRun: false,
providerThreadId: context.providerThread.id,
providerTurnId: context.subagent.parentContext.providerTurnId,
nativeItemRef: context.subagent.task.nativeTaskRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: context.subagent.startedAt,
completedAt,
});
}
},
});
yield* emitSubagentTaskUpdate({
subagent: context.subagent,
status,
completedAt,
});
}
}
if (context.providerNodeKind === "root_turn") {
if (context.subagent === null) {
yield* emitProviderEvent({
type: "turn.terminal",
provider: CODEX_PROVIDER,
@@ -2696,9 +2954,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
provider: CODEX_PROVIDER,
nativeTurnId,
});
const providerTurnOrdinal = turnInput.runOrdinal;
const providerTurnOrdinal = turnInput.providerTurnOrdinal;
const context: ActiveCodexTurnContext = {
input: turnInput,
projectionThreadId: turnInput.threadId,
projectionRunId: turnInput.runId,
nativeTurnId,
providerThread: turnInput.providerThread,
providerTurnId: pTurnId,
@@ -2708,6 +2968,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
providerNodeStartedAt: startedAt,
itemParentNodeId: turnInput.rootNodeId,
rootNodeId: turnInput.rootNodeId,
subagent: null,
startedAt,
};
yield* Ref.update(activeTurns, (current) => {
@@ -2718,6 +2979,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
yield* emitProviderEvent({
type: "provider_turn.updated",
provider: CODEX_PROVIDER,
threadId: turnInput.threadId,
providerTurn: {
id: pTurnId,
providerThreadId: turnInput.providerThread.id,
@@ -19,7 +19,7 @@ export class CheckpointPolicyPrepareRunError extends Schema.TaggedErrorClass<Che
{
threadId: ThreadId,
runId: RunId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -33,7 +33,7 @@ export class CheckpointPolicyFinalizeNodeError extends Schema.TaggedErrorClass<C
threadId: ThreadId,
nodeId: NodeId,
scopeId: Schema.optional(CheckpointScopeId),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -47,7 +47,7 @@ export class CheckpointPolicyRollbackError extends Schema.TaggedErrorClass<Check
threadId: ThreadId,
scopeId: CheckpointScopeId,
checkpointId: CheckpointId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -81,4 +81,4 @@ export interface CheckpointPolicyV2Shape {
export class CheckpointPolicyV2 extends Context.Service<
CheckpointPolicyV2,
CheckpointPolicyV2Shape
>()("t3/orchestration-v2/CheckpointPolicy") {}
>()("t3/orchestration-v2/CheckpointPolicy/CheckpointPolicyV2") {}
@@ -30,7 +30,7 @@ export class CheckpointRootScopePrepareError extends Schema.TaggedErrorClass<Che
{
threadId: ThreadId,
runId: RunId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -42,7 +42,7 @@ export class CheckpointScopeEnsureError extends Schema.TaggedErrorClass<Checkpoi
"CheckpointScopeEnsureError",
{
scopeId: CheckpointScopeId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -55,7 +55,7 @@ export class CheckpointBaselineCaptureError extends Schema.TaggedErrorClass<Chec
{
scopeId: CheckpointScopeId,
ordinalWithinScope: Schema.Number,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -68,7 +68,7 @@ export class CheckpointCaptureError extends Schema.TaggedErrorClass<CheckpointCa
{
scopeId: CheckpointScopeId,
parentCheckpointId: Schema.optional(CheckpointId),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -81,7 +81,7 @@ export class CheckpointRestoreError extends Schema.TaggedErrorClass<CheckpointRe
{
scopeId: CheckpointScopeId,
checkpointId: CheckpointId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -94,7 +94,7 @@ export class CheckpointDeleteStaleRefsError extends Schema.TaggedErrorClass<Chec
{
scopeId: CheckpointScopeId,
checkpointIds: Schema.Array(CheckpointId),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -149,7 +149,7 @@ export interface CheckpointServiceV2Shape {
export class CheckpointServiceV2 extends Context.Service<
CheckpointServiceV2,
CheckpointServiceV2Shape
>()("t3/orchestration-v2/CheckpointService") {}
>()("t3/orchestration-v2/CheckpointService/CheckpointServiceV2") {}
function checkpointRefForScopeOrdinal(input: {
readonly scopeId: CheckpointScopeId;
@@ -264,7 +264,7 @@ export const layer: Layer.Layer<CheckpointServiceV2, never, CheckpointStore | Id
Effect.flatMap(getWorkspaceSemaphore(cwd), (semaphore) => semaphore.withPermits(1)(effect));
const isGitCheckpointable = (cwd: string) =>
checkpointStore.isGitRepository(cwd).pipe(Effect.catch(() => Effect.succeed(false)));
checkpointStore.isGitRepository(cwd).pipe(Effect.orElseSucceed(() => false));
const ensureScope: CheckpointServiceV2Shape["ensureScope"] = (scope) => Effect.succeed(scope);
@@ -62,7 +62,7 @@ export class CommandPolicyMessageDispatchError extends Schema.TaggedErrorClass<C
{
commandId: CommandId,
threadId: ThreadId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -150,7 +150,7 @@ export interface CommandPolicyV2Shape {
}
export class CommandPolicyV2 extends Context.Service<CommandPolicyV2, CommandPolicyV2Shape>()(
"t3/orchestration-v2/CommandPolicy",
"t3/orchestration-v2/CommandPolicy/CommandPolicyV2",
) {}
function unsupported(
@@ -14,7 +14,7 @@ export class CommandReceiptStoreWriteError extends Schema.TaggedErrorClass<Comma
"CommandReceiptStoreWriteError",
{
commandId: CommandId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -26,7 +26,7 @@ export class CommandReceiptStoreReadError extends Schema.TaggedErrorClass<Comman
"CommandReceiptStoreReadError",
{
commandId: CommandId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -67,7 +67,7 @@ export interface CommandReceiptStoreV2Shape {
export class CommandReceiptStoreV2 extends Context.Service<
CommandReceiptStoreV2,
CommandReceiptStoreV2Shape
>()("t3/orchestration-v2/CommandReceiptStore") {}
>()("t3/orchestration-v2/CommandReceiptStore/CommandReceiptStoreV2") {}
/**
* IMPLEMENTATIONS
@@ -21,7 +21,7 @@ export class ContextHandoffPrepareError extends Schema.TaggedErrorClass<ContextH
targetRunId: RunId,
fromProviderThreadIds: Schema.Array(ProviderThreadId),
toProviderThreadId: ProviderThreadId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -73,7 +73,7 @@ export interface ContextHandoffServiceV2Shape {
export class ContextHandoffServiceV2 extends Context.Service<
ContextHandoffServiceV2,
ContextHandoffServiceV2Shape
>()("t3/orchestration-v2/ContextHandoffService") {}
>()("t3/orchestration-v2/ContextHandoffService/ContextHandoffServiceV2") {}
function compactText(text: string, maxLength = 240): string {
const compacted = text.replace(/\s+/g, " ").trim();
@@ -55,7 +55,7 @@ export class CorrelationBindError extends Schema.TaggedErrorClass<CorrelationBin
scope: CorrelationScopeV2,
providerRef: OrchestrationV2ProviderRef,
entity: CorrelationEntityV2,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -69,7 +69,7 @@ export class CorrelationLookupError extends Schema.TaggedErrorClass<CorrelationL
scope: CorrelationScopeV2,
providerRef: Schema.optional(OrchestrationV2ProviderRef),
entity: Schema.optional(CorrelationEntityV2),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -82,7 +82,7 @@ export class CorrelationOrdinalError extends Schema.TaggedErrorClass<Correlation
{
scope: CorrelationScopeV2,
key: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -116,4 +116,4 @@ export interface CorrelationStoreV2Shape {
export class CorrelationStoreV2 extends Context.Service<
CorrelationStoreV2,
CorrelationStoreV2Shape
>()("t3/orchestration-v2/CorrelationStore") {}
>()("t3/orchestration-v2/CorrelationStore/CorrelationStoreV2") {}
@@ -23,7 +23,7 @@ export class EventSinkWriteError extends Schema.TaggedErrorClass<EventSinkWriteE
{
eventCount: Schema.Number,
commandId: Schema.optional(CommandId),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -36,7 +36,7 @@ export class EventSinkStreamError extends Schema.TaggedErrorClass<EventSinkStrea
{
threadId: Schema.optional(ThreadId),
afterSequence: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -70,7 +70,7 @@ export interface EventSinkV2Shape {
}
export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>()(
"t3/orchestration-v2/EventSink",
"t3/orchestration-v2/EventSink/EventSinkV2",
) {}
/**
@@ -19,7 +19,7 @@ export class EventStoreAppendEventsError extends Schema.TaggedErrorClass<EventSt
"EventStoreAppendEventsError",
{
eventCount: Schema.Number,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -32,7 +32,7 @@ export class EventStoreReadEventsError extends Schema.TaggedErrorClass<EventStor
{
afterSequence: Schema.optional(Schema.Number),
threadId: Schema.optional(ThreadId),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -70,7 +70,7 @@ export interface EventStoreV2Shape {
}
export class EventStoreV2 extends Context.Service<EventStoreV2, EventStoreV2Shape>()(
"t3/orchestration-v2/EventStore",
"t3/orchestration-v2/EventStore/EventStoreV2",
) {}
/**
+24 -15
View File
@@ -23,9 +23,10 @@ import {
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import { randomUuidV4 } from "./RandomUuid.ts";
export const IdAllocatorV2Kind = Schema.Literals([
"command",
"event",
@@ -54,7 +55,7 @@ export class IdAllocatorV2AllocationError extends Schema.TaggedErrorClass<IdAllo
{
kind: IdAllocatorV2Kind,
input: Schema.optional(Schema.Unknown),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -125,6 +126,10 @@ export interface IdAllocatorV2AllocateShape {
}
export interface IdAllocatorV2DeriveShape {
readonly threadFromProviderThread: (input: {
readonly provider: ProviderKind;
readonly nativeThreadId: string;
}) => ThreadId;
readonly run: (input: { readonly threadId: ThreadId; readonly ordinal: number }) => RunId;
readonly runAttempt: (input: {
readonly runId: RunId;
@@ -170,7 +175,7 @@ export interface IdAllocatorV2Shape {
}
export class IdAllocatorV2 extends Context.Service<IdAllocatorV2, IdAllocatorV2Shape>()(
"t3/orchestration-v2/IdAllocator",
"t3/orchestration-v2/IdAllocator/IdAllocatorV2",
) {}
const encodePart = (part: string | number): string => encodeURIComponent(String(part));
@@ -186,7 +191,7 @@ const randomId =
readonly make: (value: string) => Id;
}) =>
(allocationInput: Input): Effect.Effect<Id, IdAllocatorV2Error> =>
Random.nextUUIDv4.pipe(
randomUuidV4.pipe(
Effect.map((uuid) => input.make(joinId(input.prefix, ...input.parts, uuid))),
Effect.mapError(
(cause) =>
@@ -203,14 +208,14 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
IdAllocatorV2.of({
allocate: {
command: (input) =>
randomId<typeof CommandId.Type, typeof input>({
randomId<CommandId, typeof input>({
kind: "command",
prefix: "command",
parts: ["fixture", input.fixtureName, input.commandName],
make: CommandId.make,
})(input),
event: (input) =>
randomId<typeof EventId.Type, typeof input>({
randomId<EventId, typeof input>({
kind: "event",
prefix: "event",
parts: [
@@ -223,7 +228,7 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
make: EventId.make,
})(input),
rawEvent: (input) =>
randomId<typeof RawEventId.Type, typeof input>({
randomId<RawEventId, typeof input>({
kind: "raw_event",
prefix: "raw-event",
parts: [
@@ -234,14 +239,14 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
make: RawEventId.make,
})(input),
project: (input) =>
randomId<typeof ProjectId.Type, typeof input>({
randomId<ProjectId, typeof input>({
kind: "project",
prefix: "project",
parts: ["fixture", input.fixtureName],
make: ProjectId.make,
})(input),
thread: (input) =>
randomId<typeof ThreadId.Type, typeof input>({
randomId<ThreadId, typeof input>({
kind: "thread",
prefix: "thread",
parts: [
@@ -251,21 +256,21 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
make: ThreadId.make,
})(input),
message: (input) =>
randomId<typeof MessageId.Type, typeof input>({
randomId<MessageId, typeof input>({
kind: "message",
prefix: "message",
parts: ["thread", input.threadId, "ordinal", input.ordinal],
make: MessageId.make,
})(input),
providerSession: (input) =>
randomId<typeof ProviderSessionId.Type, typeof input>({
randomId<ProviderSessionId, typeof input>({
kind: "provider_session",
prefix: "provider-session",
parts: ["provider", input.provider, "thread", input.threadId],
make: ProviderSessionId.make,
})(input),
runtimeRequest: (input) =>
randomId<typeof RuntimeRequestId.Type, typeof input>({
randomId<RuntimeRequestId, typeof input>({
kind: "runtime_request",
prefix: "runtime-request",
parts: [
@@ -291,7 +296,7 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
),
),
contextHandoff: (input) =>
randomId<typeof ContextHandoffId.Type, typeof input>({
randomId<ContextHandoffId, typeof input>({
kind: "context_handoff",
prefix: "context-handoff",
parts: [
@@ -305,7 +310,7 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
make: ContextHandoffId.make,
})(input),
contextTransfer: (input) =>
randomId<typeof ContextTransferId.Type, typeof input>({
randomId<ContextTransferId, typeof input>({
kind: "context_transfer",
prefix: "context-transfer",
parts: [
@@ -319,7 +324,7 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
make: ContextTransferId.make,
})(input),
plan: (input) =>
randomId<typeof PlanId.Type, typeof input>({
randomId<PlanId, typeof input>({
kind: "plan",
prefix: "plan",
parts: [
@@ -333,6 +338,10 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
})(input),
},
derive: {
threadFromProviderThread: (input) =>
ThreadId.make(
joinId("thread", "provider", input.provider, "native-thread", input.nativeThreadId),
),
run: (input) => RunId.make(joinId("run", "thread", input.threadId, "ordinal", input.ordinal)),
runAttempt: (input) =>
RunAttemptId.make(
@@ -53,7 +53,7 @@ export class OrchestratorDispatchError extends Schema.TaggedErrorClass<Orchestra
{
commandId: CommandId,
commandType: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -65,7 +65,7 @@ export class OrchestratorProjectionError extends Schema.TaggedErrorClass<Orchest
"OrchestratorProjectionError",
{
threadId: ThreadId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -76,7 +76,7 @@ export class OrchestratorProjectionError extends Schema.TaggedErrorClass<Orchest
export class OrchestratorDomainEventStreamError extends Schema.TaggedErrorClass<OrchestratorDomainEventStreamError>()(
"OrchestratorDomainEventStreamError",
{
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -89,7 +89,7 @@ export class OrchestratorProviderAdapterError extends Schema.TaggedErrorClass<Or
{
commandId: CommandId,
provider: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -140,7 +140,7 @@ export interface OrchestratorV2Shape {
}
export class OrchestratorV2 extends Context.Service<OrchestratorV2, OrchestratorV2Shape>()(
"t3/orchestration-v2/Orchestrator",
"t3/orchestration-v2/Orchestrator/OrchestratorV2",
) {}
function nextRunOrdinal(projection: OrchestrationV2ThreadProjection): number {
@@ -172,6 +172,20 @@ function nextTurnItemOrdinal(projection: OrchestrationV2ThreadProjection): numbe
return Math.max(0, ...projection.turnItems.map((item) => item.ordinal)) + 1;
}
function nextProviderTurnOrdinal(
projection: OrchestrationV2ThreadProjection,
providerThreadId: OrchestrationV2ProviderThread["id"],
): number {
return (
Math.max(
0,
...projection.providerTurns
.filter((turn) => turn.providerThreadId === providerThreadId)
.map((turn) => turn.ordinal),
) + 1
);
}
function isBlockingRun(run: OrchestrationV2Run): boolean {
return run.status === "starting" || run.status === "running" || run.status === "waiting";
}
@@ -626,6 +640,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
yield* runExecution.startRootRun({
commandId: CommandId.make(`command:system:start-queued:${queuedRun.id}`),
appThread: projection.thread,
providerSessionId,
session,
run: runningRun,
@@ -634,6 +649,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
providerThread,
attempt: runningAttempt,
attemptId,
providerTurnOrdinal: nextProviderTurnOrdinal(projection, providerThread.id),
shouldFinalizeRun: () =>
projectionStore.getThreadProjection(threadId).pipe(
Effect.map((current) => {
@@ -1338,6 +1354,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
yield* runExecution
.startRootRun({
commandId: input.command.commandId,
appThread: input.projection.thread,
providerSessionId: providerThread.providerSessionId,
session,
run: restartedRun,
@@ -1346,6 +1363,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
providerThread,
attempt: nextAttempt,
attemptId: nextAttemptId,
providerTurnOrdinal: nextProviderTurnOrdinal(input.projection, providerThread.id),
shouldFinalizeRun: () =>
projectionStore.getThreadProjection(input.command.threadId).pipe(
Effect.map((current) => {
@@ -2548,6 +2566,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
yield* runExecution
.startRootRun({
commandId: command.commandId,
appThread: projection.thread,
providerSessionId,
session,
run,
@@ -2556,6 +2575,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
providerThread,
attempt,
attemptId,
providerTurnOrdinal: nextProviderTurnOrdinal(projection, providerThread.id),
shouldFinalizeRun: () =>
projectionStore.getThreadProjection(command.threadId).pipe(
Effect.map((current) => {
@@ -41,7 +41,7 @@ export class ProjectionStoreApplyEventError extends Schema.TaggedErrorClass<Proj
"ProjectionStoreApplyEventError",
{
eventType: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -52,7 +52,7 @@ export class ProjectionStoreApplyEventError extends Schema.TaggedErrorClass<Proj
export class ProjectionStoreSetupError extends Schema.TaggedErrorClass<ProjectionStoreSetupError>()(
"ProjectionStoreSetupError",
{
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -75,7 +75,7 @@ export class ProjectionStoreReadError extends Schema.TaggedErrorClass<Projection
"ProjectionStoreReadError",
{
threadId: ThreadId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -105,7 +105,7 @@ export interface ProjectionStoreV2Shape {
}
export class ProjectionStoreV2 extends Context.Service<ProjectionStoreV2, ProjectionStoreV2Shape>()(
"t3/orchestration-v2/ProjectionStore",
"t3/orchestration-v2/ProjectionStore/ProjectionStoreV2",
) {}
function upsertById<T extends { readonly id: string }>(items: ReadonlyArray<T>, next: T): Array<T> {
@@ -1027,7 +1027,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
updated_at = excluded.updated_at,
payload_json = excluded.payload_json
`;
if (event.payload.appThreadId !== null && event.payload.ownerNodeId === null) {
if (event.payload.appThreadId !== null) {
const threadRows = yield* sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_threads
@@ -1506,6 +1506,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
FROM orchestration_v2_projection_nodes
WHERE thread_id = ${threadId}
)
OR provider_thread_id IN (
SELECT provider_thread_id
FROM orchestration_v2_projection_subagents
WHERE thread_id = ${threadId}
AND provider_thread_id IS NOT NULL
)
ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC
`,
sql<PayloadRow>`
@@ -4,6 +4,7 @@ import {
MessageId,
ModelSelection,
NodeId,
OrchestrationV2AppThread,
OrchestrationV2ConversationMessage,
OrchestrationV2ExecutionNode,
OrchestrationV2ProviderSession,
@@ -63,6 +64,11 @@ export const ProviderAdapterV2SessionStatus = Schema.Literals([
export type ProviderAdapterV2SessionStatus = typeof ProviderAdapterV2SessionStatus.Type;
export const ProviderAdapterV2Event = Schema.Union([
Schema.Struct({
type: Schema.Literal("app_thread.created"),
provider: ProviderKind,
appThread: OrchestrationV2AppThread,
}),
Schema.Struct({
type: Schema.Literal("provider_session.updated"),
provider: ProviderKind,
@@ -76,6 +82,7 @@ export const ProviderAdapterV2Event = Schema.Union([
Schema.Struct({
type: Schema.Literal("provider_turn.updated"),
provider: ProviderKind,
threadId: Schema.optional(ThreadId),
providerTurn: OrchestrationV2ProviderTurn,
}),
Schema.Struct({
@@ -101,6 +108,7 @@ export const ProviderAdapterV2Event = Schema.Union([
Schema.Struct({
type: Schema.Literal("runtime_request.updated"),
provider: ProviderKind,
threadId: Schema.optional(ThreadId),
runtimeRequest: OrchestrationV2RuntimeRequest,
}),
Schema.Struct({
@@ -121,7 +129,7 @@ export class ProviderAdapterCapabilitiesError extends Schema.TaggedErrorClass<Pr
"ProviderAdapterCapabilitiesError",
{
provider: ProviderKind,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -134,7 +142,7 @@ export class ProviderAdapterOpenSessionError extends Schema.TaggedErrorClass<Pro
{
provider: ProviderKind,
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -147,7 +155,7 @@ export class ProviderAdapterCloseSessionError extends Schema.TaggedErrorClass<Pr
{
provider: ProviderKind,
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -161,7 +169,7 @@ export class ProviderAdapterResumeThreadError extends Schema.TaggedErrorClass<Pr
provider: ProviderKind,
providerSessionId: ProviderSessionId,
providerThreadId: ProviderThreadId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -174,7 +182,7 @@ export class ProviderAdapterEnsureThreadError extends Schema.TaggedErrorClass<Pr
{
provider: ProviderKind,
threadId: ThreadId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -187,7 +195,7 @@ export class ProviderAdapterReadThreadSnapshotError extends Schema.TaggedErrorCl
{
provider: ProviderKind,
providerThreadId: ProviderThreadId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -201,7 +209,7 @@ export class ProviderAdapterRollbackThreadError extends Schema.TaggedErrorClass<
provider: ProviderKind,
providerThreadId: ProviderThreadId,
checkpointId: Schema.optional(CheckpointId),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -214,7 +222,7 @@ export class ProviderAdapterForkThreadError extends Schema.TaggedErrorClass<Prov
{
provider: ProviderKind,
providerThreadId: ProviderThreadId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -229,7 +237,7 @@ export class ProviderAdapterTurnStartError extends Schema.TaggedErrorClass<Provi
threadId: ThreadId,
providerThreadId: ProviderThreadId,
runId: RunId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -255,7 +263,7 @@ export class ProviderAdapterSteerRunError extends Schema.TaggedErrorClass<Provid
provider: ProviderKind,
providerThreadId: ProviderThreadId,
providerTurnId: ProviderTurnId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -269,7 +277,7 @@ export class ProviderAdapterInterruptError extends Schema.TaggedErrorClass<Provi
provider: ProviderKind,
providerThreadId: ProviderThreadId,
providerTurnId: ProviderTurnId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -282,7 +290,7 @@ export class ProviderAdapterRuntimeRequestResponseError extends Schema.TaggedErr
{
provider: ProviderKind,
requestId: RuntimeRequestId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -295,7 +303,7 @@ export class ProviderAdapterEventStreamError extends Schema.TaggedErrorClass<Pro
{
provider: ProviderKind,
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -352,9 +360,11 @@ export interface ProviderAdapterV2EnsureThreadInput {
}
export interface ProviderAdapterV2TurnInput {
readonly appThread: OrchestrationV2AppThread;
readonly threadId: ThreadId;
readonly runId: RunId;
readonly runOrdinal: number;
readonly providerTurnOrdinal: number;
readonly attemptId: RunAttemptId;
readonly rootNodeId: NodeId;
readonly providerThread: OrchestrationV2ProviderThread;
@@ -471,5 +481,5 @@ export interface ProviderAdapterV2Shape {
}
export class ProviderAdapterV2 extends Context.Service<ProviderAdapterV2, ProviderAdapterV2Shape>()(
"t3/orchestration-v2/ProviderAdapter",
"t3/orchestration-v2/ProviderAdapter/ProviderAdapterV2",
) {}
@@ -15,7 +15,7 @@ export class ProviderAdapterDriverCreateError extends Schema.TaggedErrorClass<Pr
driver: ProviderDriverKind,
instanceId: ProviderInstanceId,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -52,7 +52,7 @@ export interface ProviderAdapterRegistryV2Shape {
export class ProviderAdapterRegistryV2 extends Context.Service<
ProviderAdapterRegistryV2,
ProviderAdapterRegistryV2Shape
>()("t3/orchestration-v2/ProviderAdapterRegistry") {}
>()("t3/orchestration-v2/ProviderAdapterRegistry/ProviderAdapterRegistryV2") {}
export const ProviderAdapterRegistryBuildError = Schema.Union([ProviderAdapterDriverCreateError]);
export type ProviderAdapterRegistryBuildError = typeof ProviderAdapterRegistryBuildError.Type;
@@ -1,6 +1,8 @@
import { assert, it } from "@effect/vitest";
import {
MessageId,
type ModelSelection,
NodeId,
type OrchestrationV2AppThread,
type OrchestrationV2DomainEvent,
type OrchestrationV2ProviderThread,
@@ -212,4 +214,75 @@ layer("ProviderEventIngestorV2", (it) => {
assert.deepEqual(normalized, []);
}),
);
it.effect("routes provider-owned child artifacts to their child app thread", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const ingestor = yield* ProviderEventIngestorV2;
const idAllocator = yield* IdAllocatorV2;
const rootEvent = yield* threadCreatedEvent(now);
if (rootEvent.type !== "thread.created") {
throw new Error("Expected a thread.created fixture event");
}
const childThreadId = idAllocator.derive.threadFromProviderThread({
provider: "codex",
nativeThreadId: "native-subagent-thread",
});
const childRootNodeId = NodeId.make("node:subagent-root");
const childThread: OrchestrationV2AppThread = {
...rootEvent.payload,
id: childThreadId,
title: "Subagent: inspect package",
activeProviderThreadId: null,
lineage: {
parentThreadId: rootEvent.threadId,
relationshipToParent: "subagent",
rootThreadId: rootEvent.threadId,
},
forkedFrom: {
type: "node",
nodeId: NodeId.make("node:parent-subagent"),
},
};
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
threadId: rootEvent.threadId,
});
const threadEvents = yield* ingestor.normalize({
providerSessionId,
threadId: rootEvent.threadId,
event: {
type: "app_thread.created",
provider: "codex",
appThread: childThread,
},
});
const messageEvents = yield* ingestor.normalize({
providerSessionId,
threadId: rootEvent.threadId,
event: {
type: "message.updated",
provider: "codex",
message: {
id: MessageId.make("message:subagent-response"),
threadId: childThreadId,
runId: null,
nodeId: childRootNodeId,
role: "assistant",
text: "Subagent result",
attachments: [],
streaming: false,
createdAt: now,
updatedAt: now,
},
},
});
assert.equal(threadEvents[0]?.type, "thread.created");
assert.equal(threadEvents[0]?.threadId, childThreadId);
assert.equal(messageEvents[0]?.type, "message.updated");
assert.equal(messageEvents[0]?.threadId, childThreadId);
}),
);
});
@@ -24,7 +24,7 @@ export class ProviderEventNormalizeError extends Schema.TaggedErrorClass<Provide
providerSessionId: ProviderSessionId,
threadId: ThreadId,
providerEvent: ProviderAdapterV2Event,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -37,7 +37,7 @@ export class ProviderEventPublishError extends Schema.TaggedErrorClass<ProviderE
{
providerSessionId: ProviderSessionId,
eventCount: Schema.Number,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -75,7 +75,7 @@ export interface ProviderEventIngestorV2Shape {
export class ProviderEventIngestorV2 extends Context.Service<
ProviderEventIngestorV2,
ProviderEventIngestorV2Shape
>()("t3/orchestration-v2/ProviderEventIngestor") {}
>()("t3/orchestration-v2/ProviderEventIngestor/ProviderEventIngestorV2") {}
function compactUndefined<T extends Record<string, unknown>>(record: T): T {
return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T;
@@ -101,13 +101,15 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
payloadInput: {
readonly type: OrchestrationV2DomainEvent["type"];
readonly payload: OrchestrationV2DomainEvent["payload"];
readonly threadId?: ThreadId;
readonly runId?: RunId | null;
readonly nodeId?: NodeId | null;
},
) =>
Effect.gen(function* () {
const threadId = payloadInput.threadId ?? input.threadId;
const eventId = yield* idAllocator.allocate.event({
threadId: input.threadId,
threadId,
providerSessionId: input.providerSessionId,
});
const occurredAt = yield* DateTime.now;
@@ -115,7 +117,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
compactUndefined({
id: eventId,
type: payloadInput.type,
threadId: input.threadId,
threadId,
runId: payloadInput.runId ?? input.runId,
nodeId: payloadInput.nodeId ?? input.nodeId,
provider: input.event.provider,
@@ -129,6 +131,14 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
const normalize: ProviderEventIngestorV2Shape["normalize"] = (input) =>
Effect.gen(function* () {
switch (input.event.type) {
case "app_thread.created":
return [
yield* makeDomainEvent(input, {
type: "thread.created",
threadId: input.event.appThread.id,
payload: input.event.appThread,
}),
];
case "provider_session.updated":
return [
yield* makeDomainEvent(input, {
@@ -140,6 +150,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
return [
yield* makeDomainEvent(input, {
type: "provider-thread.updated",
threadId: input.event.providerThread.appThreadId ?? input.threadId,
payload: input.event.providerThread,
}),
];
@@ -147,6 +158,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
return [
yield* makeDomainEvent(input, {
type: "provider-turn.updated",
...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
payload: input.event.providerTurn,
nodeId: input.event.providerTurn.nodeId,
}),
@@ -155,6 +167,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
return [
yield* makeDomainEvent(input, {
type: "node.updated",
threadId: input.event.node.threadId,
payload: input.event.node,
runId: input.event.node.runId,
nodeId: input.event.node.id,
@@ -164,6 +177,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
return [
yield* makeDomainEvent(input, {
type: "subagent.updated",
threadId: input.event.subagent.threadId,
payload: input.event.subagent,
runId: input.event.subagent.runId,
nodeId: input.event.subagent.id,
@@ -173,6 +187,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
return [
yield* makeDomainEvent(input, {
type: "message.updated",
threadId: input.event.message.threadId,
payload: input.event.message,
runId: input.event.message.runId,
nodeId: input.event.message.nodeId,
@@ -182,6 +197,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
return [
yield* makeDomainEvent(input, {
type: "turn-item.updated",
threadId: input.event.turnItem.threadId,
payload: input.event.turnItem,
runId: input.event.turnItem.runId,
nodeId: input.event.turnItem.nodeId,
@@ -191,6 +207,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
return [
yield* makeDomainEvent(input, {
type: "runtime-request.updated",
...(input.event.threadId === undefined ? {} : { threadId: input.event.threadId }),
payload: input.event.runtimeRequest,
nodeId: input.event.runtimeRequest.nodeId,
}),
@@ -199,6 +216,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
return [
yield* makeDomainEvent(input, {
type: "plan.updated",
threadId: input.event.plan.threadId,
payload: input.event.plan,
runId: input.event.plan.runId,
nodeId: input.event.plan.nodeId,
@@ -463,10 +463,13 @@ it.effect(
runtimePolicy,
});
yield* runtime.events.pipe(Stream.runDrain, Effect.forkScoped);
const appThread = (yield* projectionStore.getThreadProjection(threadId)).thread;
yield* runtime.startTurn({
appThread,
threadId,
runId,
runOrdinal: 1,
providerTurnOrdinal: 1,
attemptId,
rootNodeId,
providerThread,
@@ -686,6 +689,7 @@ it.effect(
const eventSink = yield* EventSinkV2;
const idAllocator = yield* IdAllocatorV2;
const manager = yield* ProviderSessionManagerV2;
const projectionStore = yield* ProjectionStoreV2;
const now = yield* DateTime.now;
const projectId = yield* idAllocator.allocate.project({
fixtureName: "provider-session-manager-multi-thread-active",
@@ -744,10 +748,14 @@ it.effect(
runtimePolicy,
});
yield* runtime.events.pipe(Stream.runDrain, Effect.forkScoped);
const firstAppThread = (yield* projectionStore.getThreadProjection(firstThreadId)).thread;
const secondAppThread = (yield* projectionStore.getThreadProjection(secondThreadId)).thread;
yield* runtime.startTurn({
appThread: firstAppThread,
threadId: firstThreadId,
runId: firstRunId,
runOrdinal: 1,
providerTurnOrdinal: 1,
attemptId: idAllocator.derive.runAttempt({ runId: firstRunId, attemptOrdinal: 1 }),
rootNodeId: idAllocator.derive.rootNode({ runId: firstRunId }),
providerThread: firstProviderThread,
@@ -760,9 +768,11 @@ it.effect(
runtimePolicy,
});
yield* runtime.startTurn({
appThread: secondAppThread,
threadId: secondThreadId,
runId: secondRunId,
runOrdinal: 1,
providerTurnOrdinal: 1,
attemptId: idAllocator.derive.runAttempt({ runId: secondRunId, attemptOrdinal: 1 }),
rootNodeId: idAllocator.derive.rootNode({ runId: secondRunId }),
providerThread: secondProviderThread,
@@ -62,7 +62,7 @@ export class ProviderSessionOpenError extends Schema.TaggedErrorClass<ProviderSe
{
instanceId: ProviderInstanceId,
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -74,7 +74,7 @@ export class ProviderSessionLookupError extends Schema.TaggedErrorClass<Provider
"ProviderSessionLookupError",
{
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -86,7 +86,7 @@ export class ProviderSessionCloseError extends Schema.TaggedErrorClass<ProviderS
"ProviderSessionCloseError",
{
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -99,7 +99,7 @@ export class ProviderSessionReleaseError extends Schema.TaggedErrorClass<Provide
{
providerSessionId: ProviderSessionId,
reason: ProviderSessionReleaseReason,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -111,7 +111,7 @@ export class ProviderSessionActivityError extends Schema.TaggedErrorClass<Provid
"ProviderSessionActivityError",
{
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -152,7 +152,7 @@ export interface ProviderSessionManagerV2Shape {
export class ProviderSessionManagerV2 extends Context.Service<
ProviderSessionManagerV2,
ProviderSessionManagerV2Shape
>()("t3/orchestration-v2/ProviderSessionManager") {}
>()("t3/orchestration-v2/ProviderSessionManager/ProviderSessionManagerV2") {}
interface LiveSessionEntry {
readonly attachedThreadIds: ReadonlySet<ThreadId>;
@@ -30,7 +30,7 @@ export class ProviderSwitchPlanError extends Schema.TaggedErrorClass<ProviderSwi
threadId: ThreadId,
targetRunId: RunId,
targetProvider: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -44,7 +44,7 @@ export class ProviderSwitchApplyError extends Schema.TaggedErrorClass<ProviderSw
threadId: ThreadId,
targetRunId: RunId,
strategy: ProviderSwitchStrategyV2,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -75,4 +75,4 @@ export interface ProviderSwitchServiceV2Shape {
export class ProviderSwitchServiceV2 extends Context.Service<
ProviderSwitchServiceV2,
ProviderSwitchServiceV2Shape
>()("t3/orchestration-v2/ProviderSwitchService") {}
>()("t3/orchestration-v2/ProviderSwitchService/ProviderSwitchServiceV2") {}
@@ -0,0 +1,13 @@
import * as Effect from "effect/Effect";
import * as Random from "effect/Random";
export const randomUuidV4 = Effect.all(
Array.from({ length: 16 }, () => Random.nextIntBetween(0, 256, { halfOpen: true })),
).pipe(
Effect.map((bytes) => {
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = bytes.map((byte) => byte.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}),
);
@@ -1,6 +1,7 @@
import {
CommandId,
type ModelSelection,
type OrchestrationV2AppThread,
type OrchestrationV2Checkpoint,
type OrchestrationV2CheckpointScope,
type OrchestrationV2ExecutionNode,
@@ -38,7 +39,7 @@ export class RunExecutionStartError extends Schema.TaggedErrorClass<RunExecution
{
commandId: CommandId,
runId: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -50,7 +51,7 @@ export class RunExecutionIngestError extends Schema.TaggedErrorClass<RunExecutio
"RunExecutionIngestError",
{
runId: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -69,6 +70,7 @@ export type RunExecutionServiceV2Error = typeof RunExecutionServiceV2Error.Type;
*/
export interface RunExecutionServiceV2StartRootRunInput {
readonly commandId: CommandId;
readonly appThread: OrchestrationV2AppThread;
readonly providerSessionId: ProviderSessionId;
readonly session: ProviderAdapterV2SessionRuntime;
readonly run: OrchestrationV2Run;
@@ -77,6 +79,7 @@ export interface RunExecutionServiceV2StartRootRunInput {
readonly providerThread: OrchestrationV2ProviderThread;
readonly attempt: OrchestrationV2RunAttempt;
readonly attemptId: RunAttemptId;
readonly providerTurnOrdinal: number;
readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
readonly message: ProviderAdapterV2TurnMessage;
readonly modelSelection: ModelSelection;
@@ -92,7 +95,7 @@ export interface RunExecutionServiceV2Shape {
export class RunExecutionServiceV2 extends Context.Service<
RunExecutionServiceV2,
RunExecutionServiceV2Shape
>()("t3/orchestration-v2/RunExecutionService") {}
>()("t3/orchestration-v2/RunExecutionService/RunExecutionServiceV2") {}
/**
* IMPLEMENTATIONS
@@ -381,9 +384,11 @@ export const layer: Layer.Layer<
yield* input.session
.startTurn({
appThread: input.appThread,
threadId: input.run.threadId,
runId: input.run.id,
runOrdinal: input.run.ordinal,
providerTurnOrdinal: input.providerTurnOrdinal,
attemptId: input.attemptId,
rootNodeId: input.rootNode.id,
providerThread: input.providerThread,
@@ -16,7 +16,7 @@ export class RuntimePolicyResolveError extends Schema.TaggedErrorClass<RuntimePo
"RuntimePolicyResolveError",
{
provider: ProviderKind,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -46,7 +46,7 @@ export interface RuntimePolicyV2Shape {
}
export class RuntimePolicyV2 extends Context.Service<RuntimePolicyV2, RuntimePolicyV2Shape>()(
"t3/orchestration-v2/RuntimePolicy",
"t3/orchestration-v2/RuntimePolicy/RuntimePolicyV2",
) {}
/**
@@ -16,7 +16,7 @@ export class RuntimeRequestOpenError extends Schema.TaggedErrorClass<RuntimeRequ
requestId: RuntimeRequestId,
nodeId: NodeId,
kind: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -41,7 +41,7 @@ export class RuntimeRequestRespondError extends Schema.TaggedErrorClass<RuntimeR
{
threadId: ThreadId,
requestId: RuntimeRequestId,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -72,4 +72,4 @@ export interface RuntimeRequestServiceV2Shape {
export class RuntimeRequestServiceV2 extends Context.Service<
RuntimeRequestServiceV2,
RuntimeRequestServiceV2Shape
>()("t3/orchestration-v2/RuntimeRequestService") {}
>()("t3/orchestration-v2/RuntimeRequestService/RuntimeRequestServiceV2") {}
@@ -0,0 +1,129 @@
import type {
MessageId,
ModelSelection,
NodeId,
OrchestrationV2AppThread,
OrchestrationV2ConversationMessage,
OrchestrationV2ProviderRef,
OrchestrationV2TurnItem,
ProviderInstanceId,
ProviderThreadId,
ProviderTurnId,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import type * as DateTime from "effect/DateTime";
function trimmed(value: string | null | undefined): string | undefined {
const result = value?.trim();
return result && result.length > 0 ? result : undefined;
}
export function subagentThreadTitle(input: {
readonly parentTitle: string;
readonly title?: string | null;
readonly prompt: string;
readonly ordinal: number;
}): string {
const detail = trimmed(input.title) ?? trimmed(input.prompt);
if (detail === undefined) {
return `${input.parentTitle} subagent ${input.ordinal}`;
}
const clipped = detail.length > 72 ? `${detail.slice(0, 69)}...` : detail;
return `Subagent: ${clipped}`;
}
export function makeSubagentChildThread(input: {
readonly parentThread: OrchestrationV2AppThread;
readonly childThreadId: ThreadId;
readonly parentNodeId: NodeId;
readonly activeProviderThreadId: ProviderThreadId | null;
readonly providerInstanceId: ProviderInstanceId;
readonly modelSelection: ModelSelection;
readonly title: string;
readonly now: DateTime.Utc;
}): OrchestrationV2AppThread {
return {
...input.parentThread,
id: input.childThreadId,
title: input.title,
defaultProvider: input.providerInstanceId,
modelSelection: input.modelSelection,
activeProviderThreadId: input.activeProviderThreadId,
lineage: {
parentThreadId: input.parentThread.id,
relationshipToParent: "subagent",
rootThreadId: input.parentThread.lineage.rootThreadId,
},
forkedFrom: {
type: "node",
nodeId: input.parentNodeId,
},
createdAt: input.now,
updatedAt: input.now,
archivedAt: null,
deletedAt: null,
};
}
export function makeSubagentConversationArtifacts(input: {
readonly messageId: MessageId;
readonly turnItemId: TurnItemId;
readonly threadId: ThreadId;
readonly rootNodeId: NodeId;
readonly providerThreadId: ProviderThreadId | null;
readonly providerTurnId: ProviderTurnId | null;
readonly nativeItemRef: OrchestrationV2ProviderRef | null;
readonly role: "user" | "assistant";
readonly text: string;
readonly ordinal: number;
readonly now: DateTime.Utc;
}): {
readonly message: OrchestrationV2ConversationMessage;
readonly turnItem: OrchestrationV2TurnItem;
} {
const message: OrchestrationV2ConversationMessage = {
id: input.messageId,
threadId: input.threadId,
runId: null,
nodeId: input.rootNodeId,
role: input.role,
text: input.text,
attachments: [],
streaming: false,
createdAt: input.now,
updatedAt: input.now,
};
const base = {
id: input.turnItemId,
threadId: input.threadId,
runId: null,
nodeId: input.rootNodeId,
providerThreadId: input.providerThreadId,
providerTurnId: input.providerTurnId,
nativeItemRef: input.nativeItemRef,
parentItemId: null,
ordinal: input.ordinal,
status: "completed" as const,
title: null,
startedAt: input.now,
completedAt: input.now,
updatedAt: input.now,
messageId: input.messageId,
text: input.text,
};
const turnItem: OrchestrationV2TurnItem =
input.role === "user"
? {
...base,
type: "user_message",
inputIntent: "turn_start",
attachments: [],
}
: {
...base,
type: "assistant_message",
streaming: false,
};
return { message, turnItem };
}
@@ -12,7 +12,7 @@ export class ThreadForkPlanError extends Schema.TaggedErrorClass<ThreadForkPlanE
{
targetThreadId: ThreadId,
sourcePoint: OrchestrationV2ThreadForkSourcePoint,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -25,7 +25,7 @@ export class ThreadForkApplyError extends Schema.TaggedErrorClass<ThreadForkAppl
{
targetThreadId: ThreadId,
sourcePoint: OrchestrationV2ThreadForkSourcePoint,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -55,4 +55,4 @@ export interface ThreadForkServiceV2Shape {
export class ThreadForkServiceV2 extends Context.Service<
ThreadForkServiceV2,
ThreadForkServiceV2Shape
>()("t3/orchestration-v2/ThreadForkService") {}
>()("t3/orchestration-v2/ThreadForkService/ThreadForkServiceV2") {}
@@ -26,27 +26,14 @@ import {
THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER,
THREAD_MERGE_BACK_SOURCE_MARKER,
} from "./fixtures/shared.ts";
import { makeCheckpointWorkspace } from "./ReplayFixtureWorkspace.ts";
import { checkpointWorkspace } from "./ReplayFixtureWorkspace.ts";
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
const text = await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return yield* fs.readFileString(decodeURIComponent(file.pathname));
}).pipe(Effect.provide(NodeServices.layer)),
);
return await Effect.runPromise(decodeProviderReplayNdjson(text));
}
async function removeDirectory(path: string): Promise<void> {
await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(path, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
}
const readTranscript = Effect.fn("readClaudeReplayFixture")(function* (file: URL) {
const fs = yield* FileSystem.FileSystem;
const text = yield* fs.readFileString(decodeURIComponent(file.pathname));
return yield* decodeProviderReplayNdjson(text);
}, Effect.provide(NodeServices.layer));
function claudeFixture(name: string) {
const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find((entry) => entry.name === name);
@@ -57,10 +44,8 @@ function claudeFixture(name: string) {
return { fixture, provider };
}
async function readClaudeTranscriptFixture(path: string): Promise<ProviderReplayTranscript> {
return await readTranscript(
new URL(`./fixtures/${path}/claude_transcript.ndjson`, import.meta.url),
);
function readClaudeTranscriptFixture(path: string) {
return readTranscript(new URL(`./fixtures/${path}/claude_transcript.ndjson`, import.meta.url));
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -152,248 +137,263 @@ function claudeToolUseNamesFromTranscript(
}
describe("Claude Agent SDK replay fixtures", () => {
it("classifies every Claude fixture tool use through the native tool table", async () => {
const unknownToolNames = new Set<string>();
const seenToolNames = new Set<string>();
it.effect("classifies every Claude fixture tool use through the native tool table", () =>
Effect.gen(function* () {
const unknownToolNames = new Set<string>();
const seenToolNames = new Set<string>();
for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
for (const provider of fixture.providers) {
if (provider.provider !== "claudeAgent") {
continue;
}
for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
for (const provider of fixture.providers) {
if (provider.provider !== "claudeAgent") {
continue;
}
const transcript = await readTranscript(provider.transcriptFile);
for (const toolName of claudeToolUseNamesFromTranscript(transcript)) {
seenToolNames.add(toolName);
const classification = classifyClaudeNativeTool(toolName);
if (!classification.known) {
unknownToolNames.add(`${fixture.name}:${toolName}`);
const transcript = yield* readTranscript(provider.transcriptFile);
for (const toolName of claudeToolUseNamesFromTranscript(transcript)) {
seenToolNames.add(toolName);
const classification = classifyClaudeNativeTool(toolName);
if (!classification.known) {
unknownToolNames.add(`${fixture.name}:${toolName}`);
}
}
}
}
}
assert.isAtLeast(seenToolNames.size, 1, "expected Claude fixtures to contain tool uses");
assert.deepEqual([...unknownToolNames], []);
});
assert.isAtLeast(seenToolNames.size, 1, "expected Claude fixtures to contain tool uses");
assert.deepEqual([...unknownToolNames], []);
}),
);
it("keeps unregistered native conversation-state transcripts reviewable", async () => {
const rollback = await readClaudeTranscriptFixture("thread_rollback");
assert.equal(rollback.metadata?.queryMode, "resume_at_cursor");
const rollbackCursor = metadataString(rollback, "resumeSessionAt");
const rollbackResumeFrame = findEntryFrame(rollback, "query.open:resume_at_cursor");
const rollbackResumeOptions = rollbackResumeFrame.options;
if (!isRecord(rollbackResumeOptions)) {
throw new Error("Rollback resume query.open options must be an object.");
}
assert.equal(rollbackResumeOptions.resumeSessionAt, rollbackCursor);
const rollbackFinalText = successResultTexts(rollback).at(-1) ?? "";
assert.include(rollbackFinalText, "rollback fixture first turn complete");
assert.notInclude(rollbackFinalText, "rollback fixture second turn complete");
it.effect("keeps unregistered native conversation-state transcripts reviewable", () =>
Effect.gen(function* () {
const rollback = yield* readClaudeTranscriptFixture("thread_rollback");
assert.equal(rollback.metadata?.queryMode, "resume_at_cursor");
const rollbackCursor = metadataString(rollback, "resumeSessionAt");
const rollbackResumeFrame = findEntryFrame(rollback, "query.open:resume_at_cursor");
const rollbackResumeOptions = rollbackResumeFrame.options;
if (!isRecord(rollbackResumeOptions)) {
throw new Error("Rollback resume query.open options must be an object.");
}
assert.equal(rollbackResumeOptions.resumeSessionAt, rollbackCursor);
const rollbackFinalText = successResultTexts(rollback).at(-1) ?? "";
assert.include(rollbackFinalText, "rollback fixture first turn complete");
assert.notInclude(rollbackFinalText, "rollback fixture second turn complete");
const latestFork = await readClaudeTranscriptFixture("thread_fork_native");
assert.equal(latestFork.metadata?.queryMode, "fork_session");
const latestForkedSessionId = metadataString(latestFork, "forkedNativeSessionId");
const latestForkedFrame = findEntryFrame(latestFork, "session.forked");
assert.equal(latestForkedFrame.sessionId, latestForkedSessionId);
const latestFork = yield* readClaudeTranscriptFixture("thread_fork_native");
assert.equal(latestFork.metadata?.queryMode, "fork_session");
const latestForkedSessionId = metadataString(latestFork, "forkedNativeSessionId");
const latestForkedFrame = findEntryFrame(latestFork, "session.forked");
assert.equal(latestForkedFrame.sessionId, latestForkedSessionId);
const priorFork = await readClaudeTranscriptFixture("thread_fork_native_prior_turn");
assert.equal(priorFork.metadata?.queryMode, "fork_session_prior_turn");
const priorForkCursor = metadataString(priorFork, "forkUpToMessageId");
const priorForkFrame = findEntryFrame(priorFork, "session.fork");
const priorForkOptions = priorForkFrame.options;
if (!isRecord(priorForkOptions)) {
throw new Error("Prior-turn fork options must be an object.");
}
assert.equal(priorForkOptions.upToMessageId, priorForkCursor);
const priorForkFinalText = successResultTexts(priorFork).at(-1) ?? "";
assert.include(priorForkFinalText, "fork boundary alpha");
assert.notInclude(priorForkFinalText, "fork boundary beta");
const priorFork = yield* readClaudeTranscriptFixture("thread_fork_native_prior_turn");
assert.equal(priorFork.metadata?.queryMode, "fork_session_prior_turn");
const priorForkCursor = metadataString(priorFork, "forkUpToMessageId");
const priorForkFrame = findEntryFrame(priorFork, "session.fork");
const priorForkOptions = priorForkFrame.options;
if (!isRecord(priorForkOptions)) {
throw new Error("Prior-turn fork options must be an object.");
}
assert.equal(priorForkOptions.upToMessageId, priorForkCursor);
const priorForkFinalText = successResultTexts(priorFork).at(-1) ?? "";
assert.include(priorForkFinalText, "fork boundary alpha");
assert.notInclude(priorForkFinalText, "fork boundary beta");
const continuedFork = await readClaudeTranscriptFixture("thread_fork_native_continue");
assert.equal(continuedFork.metadata?.queryMode, "fork_session_continue");
const continuedForkSessionId = metadataString(continuedFork, "forkedNativeSessionId");
const continuedForkOpenFrame = findEntryFrame(continuedFork, "query.open:fork");
const continuedForkOptions = continuedForkOpenFrame.options;
if (!isRecord(continuedForkOptions)) {
throw new Error("Continued fork query.open options must be an object.");
}
assert.equal(continuedForkOptions.resume, continuedForkSessionId);
const continuedForkResults = successResultTexts(continuedFork);
assert.deepEqual(continuedForkResults.slice(0, 2), [
"source marker stored",
"fork marker stored",
]);
assert.equal(
continuedForkResults.at(-1)?.replace(/\s*\|\s*/u, "|"),
THREAD_FORK_NATIVE_CONTINUE_RECALL,
);
const recallPromptFrame = findEntryFrame(continuedFork, "prompt.offer:3");
const recallMessage = recallPromptFrame.message;
const recallMessageBody = isRecord(recallMessage) ? recallMessage.message : undefined;
const recallPrompt =
isRecord(recallMessageBody) && typeof recallMessageBody.content === "string"
? recallMessageBody.content
: "";
assert.notInclude(recallPrompt, THREAD_FORK_NATIVE_CONTINUE_SOURCE_MARKER);
assert.notInclude(recallPrompt, THREAD_FORK_NATIVE_CONTINUE_FORK_MARKER);
const continuedFork = yield* readClaudeTranscriptFixture("thread_fork_native_continue");
assert.equal(continuedFork.metadata?.queryMode, "fork_session_continue");
const continuedForkSessionId = metadataString(continuedFork, "forkedNativeSessionId");
const continuedForkOpenFrame = findEntryFrame(continuedFork, "query.open:fork");
const continuedForkOptions = continuedForkOpenFrame.options;
if (!isRecord(continuedForkOptions)) {
throw new Error("Continued fork query.open options must be an object.");
}
assert.equal(continuedForkOptions.resume, continuedForkSessionId);
const continuedForkResults = successResultTexts(continuedFork);
assert.deepEqual(continuedForkResults.slice(0, 2), [
"source marker stored",
"fork marker stored",
]);
assert.equal(
continuedForkResults.at(-1)?.replace(/\s*\|\s*/u, "|"),
THREAD_FORK_NATIVE_CONTINUE_RECALL,
);
const recallPromptFrame = findEntryFrame(continuedFork, "prompt.offer:3");
const recallMessage = recallPromptFrame.message;
const recallMessageBody = isRecord(recallMessage) ? recallMessage.message : undefined;
const recallPrompt =
isRecord(recallMessageBody) && typeof recallMessageBody.content === "string"
? recallMessageBody.content
: "";
assert.notInclude(recallPrompt, THREAD_FORK_NATIVE_CONTINUE_SOURCE_MARKER);
assert.notInclude(recallPrompt, THREAD_FORK_NATIVE_CONTINUE_FORK_MARKER);
const siblingForks = await readClaudeTranscriptFixture("thread_fork_native_siblings");
assert.equal(siblingForks.metadata?.queryMode, "fork_session_siblings");
const siblingSessionIds = metadataStringArray(siblingForks, "forkedNativeSessionIds");
assert.lengthOf(siblingSessionIds, 2);
assert.notEqual(siblingSessionIds[0], siblingSessionIds[1]);
const siblingResults = successResultTexts(siblingForks).map((text) =>
text.replace(/\s*\|\s*/u, "|"),
);
assert.deepEqual(siblingResults, [
"sibling source stored",
"sibling-source-8R3D|sibling-first-5L2P",
"sibling-source-8R3D|sibling-second-9N6C",
]);
assert.notInclude(siblingResults[1] ?? "", "sibling-second-9N6C");
assert.notInclude(siblingResults[2] ?? "", "sibling-first-5L2P");
const siblingForks = yield* readClaudeTranscriptFixture("thread_fork_native_siblings");
assert.equal(siblingForks.metadata?.queryMode, "fork_session_siblings");
const siblingSessionIds = metadataStringArray(siblingForks, "forkedNativeSessionIds");
assert.lengthOf(siblingSessionIds, 2);
assert.notEqual(siblingSessionIds[0], siblingSessionIds[1]);
const siblingResults = successResultTexts(siblingForks).map((text) =>
text.replace(/\s*\|\s*/u, "|"),
);
assert.deepEqual(siblingResults, [
"sibling source stored",
"sibling-source-8R3D|sibling-first-5L2P",
"sibling-source-8R3D|sibling-second-9N6C",
]);
assert.notInclude(siblingResults[1] ?? "", "sibling-second-9N6C");
assert.notInclude(siblingResults[2] ?? "", "sibling-first-5L2P");
const mergeBack = await readClaudeTranscriptFixture("thread_merge_back_continue");
assert.equal(mergeBack.metadata?.queryMode, "fork_session_merge_back");
const mergeBackSourceSessionId = metadataString(mergeBack, "nativeSessionId");
const mergeBackContinuationFrame = findEntryFrame(mergeBack, "query.open:source-continuation");
const mergeBackContinuationOptions = mergeBackContinuationFrame.options;
if (!isRecord(mergeBackContinuationOptions)) {
throw new Error("Merge-back source continuation options must be an object.");
}
assert.equal(mergeBackContinuationOptions.resume, mergeBackSourceSessionId);
const mergeBackRecallFrame = findEntryFrame(mergeBack, "prompt.offer:4");
const mergeBackRecallMessage = mergeBackRecallFrame.message;
const mergeBackRecallBody = isRecord(mergeBackRecallMessage)
? mergeBackRecallMessage.message
: undefined;
const mergeBackRecallPrompt =
isRecord(mergeBackRecallBody) && typeof mergeBackRecallBody.content === "string"
? mergeBackRecallBody.content
: "";
assert.notInclude(mergeBackRecallPrompt, THREAD_MERGE_BACK_SOURCE_MARKER);
assert.notInclude(mergeBackRecallPrompt, THREAD_MERGE_BACK_FORK_MARKER);
assert.equal(
successResultTexts(mergeBack)
.at(-1)
?.replace(/\s*\|\s*/gu, "|"),
THREAD_MERGE_BACK_RECALL,
);
const mergeBack = yield* readClaudeTranscriptFixture("thread_merge_back_continue");
assert.equal(mergeBack.metadata?.queryMode, "fork_session_merge_back");
const mergeBackSourceSessionId = metadataString(mergeBack, "nativeSessionId");
const mergeBackContinuationFrame = findEntryFrame(
mergeBack,
"query.open:source-continuation",
);
const mergeBackContinuationOptions = mergeBackContinuationFrame.options;
if (!isRecord(mergeBackContinuationOptions)) {
throw new Error("Merge-back source continuation options must be an object.");
}
assert.equal(mergeBackContinuationOptions.resume, mergeBackSourceSessionId);
const mergeBackRecallFrame = findEntryFrame(mergeBack, "prompt.offer:4");
const mergeBackRecallMessage = mergeBackRecallFrame.message;
const mergeBackRecallBody = isRecord(mergeBackRecallMessage)
? mergeBackRecallMessage.message
: undefined;
const mergeBackRecallPrompt =
isRecord(mergeBackRecallBody) && typeof mergeBackRecallBody.content === "string"
? mergeBackRecallBody.content
: "";
assert.notInclude(mergeBackRecallPrompt, THREAD_MERGE_BACK_SOURCE_MARKER);
assert.notInclude(mergeBackRecallPrompt, THREAD_MERGE_BACK_FORK_MARKER);
assert.equal(
successResultTexts(mergeBack)
.at(-1)
?.replace(/\s*\|\s*/gu, "|"),
THREAD_MERGE_BACK_RECALL,
);
const siblingMergeBack = await readClaudeTranscriptFixture("thread_merge_back_siblings");
assert.equal(siblingMergeBack.metadata?.queryMode, "fork_session_merge_back_siblings");
const siblingMergeSessionIds = metadataStringArray(siblingMergeBack, "forkedNativeSessionIds");
assert.lengthOf(siblingMergeSessionIds, 2);
assert.notEqual(siblingMergeSessionIds[0], siblingMergeSessionIds[1]);
const siblingMergeRecallFrame = findEntryFrame(siblingMergeBack, "prompt.offer:6");
const siblingMergeRecallMessage = siblingMergeRecallFrame.message;
const siblingMergeRecallBody = isRecord(siblingMergeRecallMessage)
? siblingMergeRecallMessage.message
: undefined;
const siblingMergeRecallPrompt =
isRecord(siblingMergeRecallBody) && typeof siblingMergeRecallBody.content === "string"
? siblingMergeRecallBody.content
: "";
assert.notInclude(siblingMergeRecallPrompt, THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER);
assert.notInclude(siblingMergeRecallPrompt, THREAD_MERGE_BACK_SIBLINGS_FIRST_MARKER);
assert.notInclude(siblingMergeRecallPrompt, THREAD_MERGE_BACK_SIBLINGS_SECOND_MARKER);
assert.equal(
successResultTexts(siblingMergeBack)
.at(-1)
?.replace(/\s*\|\s*/gu, "|"),
THREAD_MERGE_BACK_SIBLINGS_RECALL,
);
const siblingMergeBack = yield* readClaudeTranscriptFixture("thread_merge_back_siblings");
assert.equal(siblingMergeBack.metadata?.queryMode, "fork_session_merge_back_siblings");
const siblingMergeSessionIds = metadataStringArray(
siblingMergeBack,
"forkedNativeSessionIds",
);
assert.lengthOf(siblingMergeSessionIds, 2);
assert.notEqual(siblingMergeSessionIds[0], siblingMergeSessionIds[1]);
const siblingMergeRecallFrame = findEntryFrame(siblingMergeBack, "prompt.offer:6");
const siblingMergeRecallMessage = siblingMergeRecallFrame.message;
const siblingMergeRecallBody = isRecord(siblingMergeRecallMessage)
? siblingMergeRecallMessage.message
: undefined;
const siblingMergeRecallPrompt =
isRecord(siblingMergeRecallBody) && typeof siblingMergeRecallBody.content === "string"
? siblingMergeRecallBody.content
: "";
assert.notInclude(siblingMergeRecallPrompt, THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER);
assert.notInclude(siblingMergeRecallPrompt, THREAD_MERGE_BACK_SIBLINGS_FIRST_MARKER);
assert.notInclude(siblingMergeRecallPrompt, THREAD_MERGE_BACK_SIBLINGS_SECOND_MARKER);
assert.equal(
successResultTexts(siblingMergeBack)
.at(-1)
?.replace(/\s*\|\s*/gu, "|"),
THREAD_MERGE_BACK_SIBLINGS_RECALL,
);
const forkLocalRollback = await readClaudeTranscriptFixture(
"thread_fork_native_fork_local_rollback",
);
assert.equal(forkLocalRollback.metadata?.queryMode, "fork_session_resume_at_fork_cursor");
const forkLocalRollbackCursor = metadataString(forkLocalRollback, "resumeSessionAt");
const forkLocalRollbackFrame = findEntryFrame(
forkLocalRollback,
"query.open:fork-resume-at-cursor",
);
const forkLocalRollbackOptions = forkLocalRollbackFrame.options;
if (!isRecord(forkLocalRollbackOptions)) {
throw new Error("Fork-local rollback resume query.open options must be an object.");
}
assert.equal(forkLocalRollbackOptions.resumeSessionAt, forkLocalRollbackCursor);
const forkLocalRollbackFinalText = successResultTexts(forkLocalRollback).at(-1) ?? "";
assert.include(forkLocalRollbackFinalText, "fork local source alpha");
assert.include(forkLocalRollbackFinalText, "fork local first");
assert.notInclude(forkLocalRollbackFinalText, "fork local second");
});
const forkLocalRollback = yield* readClaudeTranscriptFixture(
"thread_fork_native_fork_local_rollback",
);
assert.equal(forkLocalRollback.metadata?.queryMode, "fork_session_resume_at_fork_cursor");
const forkLocalRollbackCursor = metadataString(forkLocalRollback, "resumeSessionAt");
const forkLocalRollbackFrame = findEntryFrame(
forkLocalRollback,
"query.open:fork-resume-at-cursor",
);
const forkLocalRollbackOptions = forkLocalRollbackFrame.options;
if (!isRecord(forkLocalRollbackOptions)) {
throw new Error("Fork-local rollback resume query.open options must be an object.");
}
assert.equal(forkLocalRollbackOptions.resumeSessionAt, forkLocalRollbackCursor);
const forkLocalRollbackFinalText = successResultTexts(forkLocalRollback).at(-1) ?? "";
assert.include(forkLocalRollbackFinalText, "fork local source alpha");
assert.include(forkLocalRollbackFinalText, "fork local first");
assert.notInclude(forkLocalRollbackFinalText, "fork local second");
}),
);
it.skipIf(process.env.T3_RECORD_CLAUDE_AGENT_SDK_FIXTURE !== "1")(
"records simple from real Claude Code query() output",
async () => {
const { fixture, provider } = claudeFixture("simple");
() =>
Effect.scoped(
Effect.gen(function* () {
const { fixture, provider } = claudeFixture("simple");
const checkpointWorkspace = await makeCheckpointWorkspace("claude-simple-record");
try {
const transcript = await recordClaudeAgentSdkReplayTranscript({
scenario: fixture.name,
prompts: [SIMPLE_PROMPT],
modelSelection: provider.modelSelection,
cwd: checkpointWorkspace,
});
const workspace = yield* checkpointWorkspace("claude-simple-record");
const transcript = yield* Effect.promise(() =>
recordClaudeAgentSdkReplayTranscript({
scenario: fixture.name,
prompts: [SIMPLE_PROMPT],
modelSelection: provider.modelSelection,
cwd: workspace,
}),
);
assert.equal(transcript.provider, "claudeAgent");
assert.equal(transcript.protocol, "claude-agent-sdk.query");
assert.isAtLeast(transcript.entries.length, 3);
} finally {
await removeDirectory(checkpointWorkspace);
}
},
assert.equal(transcript.provider, "claudeAgent");
assert.equal(transcript.protocol, "claude-agent-sdk.query");
assert.isAtLeast(transcript.entries.length, 3);
}),
),
);
it("replays simple as typed Claude Agent SDK query messages", async () => {
const { provider } = claudeFixture("simple");
it.effect("replays simple as typed Claude Agent SDK query messages", () =>
Effect.gen(function* () {
const { provider } = claudeFixture("simple");
const rawTranscript = await readTranscript(provider.transcriptFile);
const transcript = await Effect.runPromise(
ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript),
);
const rawTranscript = yield* readTranscript(provider.transcriptFile);
const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript);
const messages = await replayClaudeAgentSdkTranscript({
transcript,
prompts: [SIMPLE_PROMPT],
modelSelection: provider.modelSelection,
});
const messages = yield* Effect.promise(() =>
replayClaudeAgentSdkTranscript({
transcript,
prompts: [SIMPLE_PROMPT],
modelSelection: provider.modelSelection,
}),
);
assert.include(
messages
assert.include(
messages
.filter((message) => message.type === "assistant")
.flatMap((message) =>
message.message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])),
)
.join(""),
"fixture simple ok",
);
}),
);
it.effect("replays multi_turn as typed Claude Agent SDK query messages", () =>
Effect.gen(function* () {
const { provider } = claudeFixture("multi_turn");
const rawTranscript = yield* readTranscript(provider.transcriptFile);
const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript);
const messages = yield* Effect.promise(() =>
replayClaudeAgentSdkTranscript({
transcript,
prompts: [MULTI_TURN_FIRST_PROMPT, MULTI_TURN_SECOND_PROMPT],
modelSelection: provider.modelSelection,
}),
);
const assistantText = messages
.filter((message) => message.type === "assistant")
.flatMap((message) =>
message.message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])),
)
.join(""),
"fixture simple ok",
);
});
it("replays multi_turn as typed Claude Agent SDK query messages", async () => {
const { provider } = claudeFixture("multi_turn");
const rawTranscript = await readTranscript(provider.transcriptFile);
const transcript = await Effect.runPromise(
ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript),
);
const messages = await replayClaudeAgentSdkTranscript({
transcript,
prompts: [MULTI_TURN_FIRST_PROMPT, MULTI_TURN_SECOND_PROMPT],
modelSelection: provider.modelSelection,
});
const assistantText = messages
.filter((message) => message.type === "assistant")
.flatMap((message) =>
message.message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])),
)
.join("\n");
assert.include(assistantText, "first fixture turn complete");
assert.include(assistantText, "second fixture turn complete");
});
.join("\n");
assert.include(assistantText, "first fixture turn complete");
assert.include(assistantText, "second fixture turn complete");
}),
);
});
@@ -116,6 +116,26 @@ const scenarioExpectations = {
turnCompletedCount: 3,
approvalRequestCount: 0,
},
subagent_continue: {
outgoing: [
"initialize",
"initialized",
"thread/start",
"turn/start/spawn",
"turn/start/continue",
],
incoming: [
"turn/started/root-1",
"turn/completed/child-1",
"turn/completed/root-1",
"turn/started/root-2",
"turn/completed/child-2",
"turn/completed/root-2",
],
turnStartCount: 0,
turnCompletedCount: 0,
approvalRequestCount: 0,
},
multi_turn: {
outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
@@ -235,15 +255,14 @@ const scenarioExpectations = {
},
} as const;
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
const text = await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return yield* fs.readFileString(decodeURIComponent(file.pathname));
}).pipe(Effect.provide(NodeServices.layer)),
);
return await Effect.runPromise(decodeProviderReplayNdjson(text));
}
const decodeCodexTranscript = Schema.decodeUnknownEffect(
CodexReplay.CodexAppServerReplayTranscript,
);
const readTranscript = Effect.fn("readCodexReplayFixture")(function* (file: URL) {
const fs = yield* FileSystem.FileSystem;
const text = yield* fs.readFileString(decodeURIComponent(file.pathname));
return yield* decodeProviderReplayNdjson(text);
}, Effect.provide(NodeServices.layer));
function labels(
transcript: ProviderReplayTranscript,
@@ -585,44 +604,46 @@ function assertSiblingMergeBackSemantics(transcript: ProviderReplayTranscript) {
}
describe("Codex replay fixtures", () => {
it("loads every current Codex fixture as a codex app-server replay transcript", async () => {
for (const fixture of CODEX_REPLAY_FIXTURES) {
const transcript = await readTranscript(fixture.transcriptFile);
const codexTranscript = Schema.decodeUnknownSync(CodexReplay.CodexAppServerReplayTranscript)(
transcript,
);
const first = transcript.entries[0];
it.effect("loads every current Codex fixture as a codex app-server replay transcript", () =>
Effect.gen(function* () {
for (const fixture of CODEX_REPLAY_FIXTURES) {
const transcript = yield* readTranscript(fixture.transcriptFile);
const codexTranscript = yield* decodeCodexTranscript(transcript);
const first = transcript.entries[0];
assert.equal(codexTranscript.provider, "codex");
assert.equal(codexTranscript.protocol, "codex.app-server");
assert.equal(codexTranscript.scenario, fixture.scenario);
assert.deepEqual(codexTranscript.entries.at(-1), {
type: "runtime_exit",
status: "success",
});
assert.equal(first?.type, "expect_outbound");
if (first?.type !== "expect_outbound") {
throw new Error(`Expected ${fixture.scenario} to start with initialize outbound frame.`);
assert.equal(codexTranscript.provider, "codex");
assert.equal(codexTranscript.protocol, "codex.app-server");
assert.equal(codexTranscript.scenario, fixture.scenario);
assert.deepEqual(codexTranscript.entries.at(-1), {
type: "runtime_exit",
status: "success",
});
assert.equal(first?.type, "expect_outbound");
if (first?.type !== "expect_outbound") {
throw new Error(`Expected ${fixture.scenario} to start with initialize outbound frame.`);
}
assert.equal(first.label, "initialize");
assertScenarioExpectations(transcript);
assertProviderThreadResumeSemantics(transcript);
assertContinuedForkSemantics(transcript);
assertSiblingForkSemantics(transcript);
assertMergeBackSemantics(transcript);
assertSiblingMergeBackSemantics(transcript);
}
assert.equal(first.label, "initialize");
}),
);
assertScenarioExpectations(transcript);
assertProviderThreadResumeSemantics(transcript);
assertContinuedForkSemantics(transcript);
assertSiblingForkSemantics(transcript);
assertMergeBackSemantics(transcript);
assertSiblingMergeBackSemantics(transcript);
}
});
it.effect("covers the expected replay suite exactly", () =>
Effect.gen(function* () {
const transcripts = yield* Effect.forEach(CODEX_REPLAY_FIXTURES, (fixture) =>
readTranscript(fixture.transcriptFile),
);
it("covers the expected replay suite exactly", async () => {
const transcripts = await Promise.all(
CODEX_REPLAY_FIXTURES.map((fixture) => readTranscript(fixture.transcriptFile)),
);
assert.deepEqual(
transcripts.map((transcript) => transcript.scenario).toSorted(),
Object.keys(scenarioExpectations).toSorted(),
);
});
assert.deepEqual(
transcripts.map((transcript) => transcript.scenario).toSorted(),
Object.keys(scenarioExpectations).toSorted(),
);
}),
);
});
@@ -1,6 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { OrchestrationV2Command, type ProviderReplayTranscript } from "@t3tools/contracts";
import { OrchestrationV2Command } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";
@@ -11,99 +11,100 @@ import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
import { materializeFixtureInput } from "./fixtures/shared.ts";
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
const text = await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return yield* fs.readFileString(decodeURIComponent(file.pathname));
}).pipe(Effect.provide(NodeServices.layer)),
);
return await Effect.runPromise(decodeProviderReplayNdjson(text));
}
const decodeCommand = Schema.decodeUnknownEffect(OrchestrationV2Command);
const readTranscript = Effect.fn("readOrchestratorReplayContractTranscript")(function* (file: URL) {
const fs = yield* FileSystem.FileSystem;
const text = yield* fs.readFileString(decodeURIComponent(file.pathname));
return yield* decodeProviderReplayNdjson(text);
}, Effect.provide(NodeServices.layer));
function assertUnique(values: ReadonlyArray<string>, label: string) {
assert.deepEqual(new Set(values).size, values.length, `${label} must be unique`);
}
describe("orchestrator replay fixture contract", () => {
it("defines one stable input and provider-specific replay/output contracts per scenario", async () => {
assertUnique(
ORCHESTRATOR_REPLAY_FIXTURES.map((fixture) => fixture.name),
"fixture names",
);
for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
assert.isAtLeast(fixture.providers.length, 1, `${fixture.name} must have providers`);
assertUnique(
fixture.providers.map((provider) => provider.provider),
`${fixture.name} provider variants`,
);
for (const provider of fixture.providers) {
const transcript = await readTranscript(provider.transcriptFile);
const materialized = await Effect.runPromise(
materializeFixtureInput({
scenario: fixture.name,
fixtureInput: fixture.buildInput(),
modelSelection: provider.modelSelection,
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime),
);
const firstCommand = materialized.commands[0];
assert.equal(transcript.scenario, fixture.name);
assert.equal(transcript.provider, provider.provider);
assert.equal(provider.modelSelection.instanceId, provider.provider);
assert.isDefined(materialized.projectionThreadIds[0]);
assert.equal(firstCommand?.type, "thread.create");
if (firstCommand?.type !== "thread.create") {
throw new Error(`${fixture.name}/${provider.provider} must start with thread.create`);
}
assert.equal(firstCommand.threadId, materialized.projectionThreadIds[0]);
assert.equal(materialized.commands.length, fixture.buildInput().steps.length + 1);
assert.isAtLeast(materialized.steps.length, materialized.commands.length);
assert.equal(typeof provider.assertOutput, "function");
it.effect(
"defines one stable input and provider-specific replay/output contracts per scenario",
() =>
Effect.gen(function* () {
assertUnique(
materialized.commands.map((command) => command.commandId),
`${fixture.name}/${provider.provider} command IDs`,
ORCHESTRATOR_REPLAY_FIXTURES.map((fixture) => fixture.name),
"fixture names",
);
for (const command of materialized.commands) {
Schema.decodeUnknownSync(OrchestrationV2Command)(command);
}
for (const command of materialized.commands) {
assert.isTrue(
materialized.steps.some(
(step) =>
(step.type === "dispatch" && step.command === command) ||
(step.type === "respond_to_next_runtime_request" &&
step.commandId === command.commandId),
),
`${fixture.name}/${provider.provider} command ${command.commandId} must appear in the timeline`,
for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
assert.isAtLeast(fixture.providers.length, 1, `${fixture.name} must have providers`);
assertUnique(
fixture.providers.map((provider) => provider.provider),
`${fixture.name} provider variants`,
);
for (const provider of fixture.providers) {
const transcript = yield* readTranscript(provider.transcriptFile);
const materialized = yield* materializeFixtureInput({
scenario: fixture.name,
fixtureInput: fixture.buildInput(),
modelSelection: provider.modelSelection,
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
const firstCommand = materialized.commands[0];
assert.equal(transcript.scenario, fixture.name);
assert.equal(transcript.provider, provider.provider);
assert.equal(provider.modelSelection.instanceId, provider.provider);
assert.isDefined(materialized.projectionThreadIds[0]);
assert.equal(firstCommand?.type, "thread.create");
if (firstCommand?.type !== "thread.create") {
throw new Error(`${fixture.name}/${provider.provider} must start with thread.create`);
}
assert.equal(firstCommand.threadId, materialized.projectionThreadIds[0]);
assert.equal(materialized.commands.length, fixture.buildInput().steps.length + 1);
assert.isAtLeast(materialized.steps.length, materialized.commands.length);
assert.equal(typeof provider.assertOutput, "function");
assertUnique(
materialized.commands.map((command) => command.commandId),
`${fixture.name}/${provider.provider} command IDs`,
);
for (const command of materialized.commands) {
yield* decodeCommand(command);
}
for (const command of materialized.commands) {
assert.isTrue(
materialized.steps.some(
(step) =>
(step.type === "dispatch" && step.command === command) ||
(step.type === "respond_to_next_runtime_request" &&
step.commandId === command.commandId),
),
`${fixture.name}/${provider.provider} command ${command.commandId} must appear in the timeline`,
);
}
}
}
}),
);
it.effect("keeps Codex fixture transcripts at the codex app-server boundary", () =>
Effect.gen(function* () {
for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
for (const provider of fixture.providers.filter((entry) => entry.provider === "codex")) {
const transcript = yield* readTranscript(provider.transcriptFile);
const first = transcript.entries[0];
const last = transcript.entries.at(-1);
assert.equal(transcript.protocol, "codex.app-server");
assert.equal(first?.type, "expect_outbound");
if (first?.type === "expect_outbound") {
assert.equal(first.label, "initialize");
}
assert.deepEqual(last, {
type: "runtime_exit",
status: "success",
});
}
}
}
});
it("keeps Codex fixture transcripts at the codex app-server boundary", async () => {
for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
for (const provider of fixture.providers.filter((entry) => entry.provider === "codex")) {
const transcript = await readTranscript(provider.transcriptFile);
const first = transcript.entries[0];
const last = transcript.entries.at(-1);
assert.equal(transcript.protocol, "codex.app-server");
assert.equal(first?.type, "expect_outbound");
if (first?.type === "expect_outbound") {
assert.equal(first.label, "initialize");
}
assert.deepEqual(last, {
type: "runtime_exit",
status: "success",
});
}
}
});
}),
);
});
@@ -18,106 +18,96 @@ import {
runOrchestratorV2ProviderReplayScenario,
type OrchestratorV2ProviderReplayHarness,
} from "./ProviderReplayHarness.ts";
import { makeCheckpointWorkspace } from "./ReplayFixtureWorkspace.ts";
import { checkpointWorkspace } from "./ReplayFixtureWorkspace.ts";
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
const text = await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return yield* fs.readFileString(decodeURIComponent(file.pathname));
}).pipe(Effect.provide(NodeServices.layer)),
);
return await Effect.runPromise(decodeProviderReplayNdjson(text));
const readTranscript = Effect.fn("readOrchestratorReplayTranscript")(function* (file: URL) {
const fs = yield* FileSystem.FileSystem;
const text = yield* fs.readFileString(decodeURIComponent(file.pathname));
return yield* decodeProviderReplayNdjson(text);
}, Effect.provide(NodeServices.layer));
function normalizeTestError(cause: unknown): Error {
return cause instanceof Error ? cause : new Error(String(cause));
}
async function removeDirectory(path: string): Promise<void> {
await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(path, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
}
async function runFixtureProvider<Transcript extends ProviderReplayTranscript, Error>(input: {
const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
Transcript extends ProviderReplayTranscript,
Error,
>(input: {
readonly fixtureName: string;
readonly buildInput: () => OrchestratorFixtureInput;
readonly provider: ProviderOrchestratorReplayVariant;
readonly harness: OrchestratorV2ProviderReplayHarness<Transcript, Error>;
}) {
const rawTranscript = await readTranscript(input.provider.transcriptFile);
const transcript = await Effect.runPromise(input.harness.decodeTranscript(rawTranscript));
const checkpointWorkspace = await makeCheckpointWorkspace(input.fixtureName);
const materialized = await Effect.runPromise(
materializeFixtureInput({
scenario: input.fixtureName,
fixtureInput: input.buildInput(),
modelSelection: input.provider.modelSelection,
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime),
const rawTranscript = yield* readTranscript(input.provider.transcriptFile);
const transcript = yield* input.harness.decodeTranscript(rawTranscript);
const workspace = yield* checkpointWorkspace(input.fixtureName);
const materialized = yield* materializeFixtureInput({
scenario: input.fixtureName,
fixtureInput: input.buildInput(),
modelSelection: input.provider.modelSelection,
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
const scenario = {
name: `${input.fixtureName}/${input.provider.provider}`,
transcript,
commands: materialized.commands,
steps: materialized.steps,
projectionThreadIds: materialized.projectionThreadIds,
runtimePolicyOverride: {
...input.provider.runtimePolicyOverride,
cwd: workspace,
},
};
const result = yield* runOrchestratorV2ProviderReplayScenario(scenario, input.harness).pipe(
provideDeterministicTestRuntime,
);
try {
const scenario = {
name: `${input.fixtureName}/${input.provider.provider}`,
transcript,
commands: materialized.commands,
steps: materialized.steps,
projectionThreadIds: materialized.projectionThreadIds,
runtimePolicyOverride: {
...input.provider.runtimePolicyOverride,
cwd: checkpointWorkspace,
},
};
const result = await Effect.runPromise(
runOrchestratorV2ProviderReplayScenario(scenario, input.harness).pipe(
provideDeterministicTestRuntime,
),
);
input.provider.assertOutput(result, transcript);
const projectionThreadId = materialized.projectionThreadIds[0];
assert.isDefined(projectionThreadId);
const projection = result.projections.get(projectionThreadId);
assert.isDefined(projection);
const latestRun = projection.runs.at(-1);
assert.deepEqual(latestRun?.modelSelection, input.provider.modelSelection);
});
input.provider.assertOutput(result, transcript);
const projectionThreadId = materialized.projectionThreadIds[0];
assert.isDefined(projectionThreadId);
const projection = result.projections.get(projectionThreadId);
assert.isDefined(projection);
const latestRun = projection.runs.at(-1);
assert.deepEqual(latestRun?.modelSelection, input.provider.modelSelection);
} finally {
await removeDirectory(checkpointWorkspace);
}
}
async function runFixtureProviderWithRegisteredHarness(input: {
function runFixtureProviderWithRegisteredHarness(input: {
readonly fixtureName: string;
readonly buildInput: () => OrchestratorFixtureInput;
readonly provider: ProviderOrchestratorReplayVariant;
}) {
switch (input.provider.provider) {
case "codex":
return await runFixtureProvider({
return runFixtureProvider({
...input,
harness: CodexOrchestratorReplayHarness,
});
}).pipe(Effect.mapError(normalizeTestError), Effect.scoped);
case "claudeAgent":
return await runFixtureProvider({
return runFixtureProvider({
...input,
harness: ClaudeOrchestratorReplayHarness,
});
}).pipe(Effect.mapError(normalizeTestError), Effect.scoped);
default:
throw new Error(`No replay harness registered for provider ${input.provider.provider}.`);
return Effect.die(
new Error(`No replay harness registered for provider ${input.provider.provider}.`),
);
}
}
describe("orchestrator replay fixtures", () => {
for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
for (const provider of fixture.providers) {
it(`runs ${fixture.name}/${provider.provider} through OrchestratorV2 using deterministic replay`, async () => {
await runFixtureProviderWithRegisteredHarness({
fixtureName: fixture.name,
buildInput: fixture.buildInput,
provider,
});
});
it.effect(
`runs ${fixture.name}/${provider.provider} through OrchestratorV2 using deterministic replay`,
() =>
runFixtureProviderWithRegisteredHarness({
fixtureName: fixture.name,
buildInput: fixture.buildInput,
provider,
}),
);
}
}
});
@@ -38,20 +38,19 @@ const SECOND_PROMPT =
const FIRST_FINAL = "provider thread resume fixture first turn complete";
const SECOND_FINAL = "provider thread resume fixture second turn complete";
async function readCodexTranscript(): Promise<CodexReplay.CodexAppServerReplayTranscript> {
const decodeCodexTranscript = Schema.decodeUnknownEffect(
CodexReplay.CodexAppServerReplayTranscript,
);
const readCodexTranscript = Effect.fn("readCodexRecoveryTranscript")(function* () {
const file = new URL(
"./fixtures/provider_thread_resume/codex_transcript.ndjson",
import.meta.url,
);
const text = await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return yield* fs.readFileString(decodeURIComponent(file.pathname));
}).pipe(Effect.provide(NodeServices.layer)),
);
const transcript = await Effect.runPromise(decodeProviderReplayNdjson(text));
return Schema.decodeUnknownSync(CodexReplay.CodexAppServerReplayTranscript)(transcript);
}
const fs = yield* FileSystem.FileSystem;
const text = yield* fs.readFileString(decodeURIComponent(file.pathname));
const transcript = yield* decodeProviderReplayNdjson(text);
return yield* decodeCodexTranscript(transcript);
});
function splitAfterFirstIdle(materialized: MaterializedOrchestratorFixtureInput) {
const splitIndex = materialized.steps.findIndex((step) => step.type === "await_thread_idle");
@@ -70,84 +69,91 @@ function splitAfterFirstIdle(materialized: MaterializedOrchestratorFixtureInput)
}
describe("orchestrator replay recovery", () => {
it("resumes a provider-native Codex thread after recreating the orchestrator runtime", async () => {
const transcript = await readCodexTranscript();
it.effect(
"resumes a provider-native Codex thread after recreating the orchestrator runtime",
() =>
Effect.scoped(
Effect.gen(function* () {
const transcript = yield* readCodexTranscript();
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* Effect.acquireRelease(
fs.makeTempDirectory({
prefix: "t3-orchestration-v2-recovery-",
}),
(directory) =>
fs.remove(directory, { recursive: true, force: true }).pipe(Effect.orDie),
);
yield* fs.makeDirectory(tempDir, { recursive: true });
const dbPath = path.join(tempDir, "state.sqlite");
const driver = yield* CodexReplay.makeReplayDriver(transcript);
const materialized = yield* materializeFixtureInput({
scenario: "provider_thread_resume",
fixtureInput: {
steps: [
{ type: "message", text: FIRST_PROMPT },
{ type: "message", text: SECOND_PROMPT },
],
},
modelSelection: CODEX_MODEL_SELECTION,
});
const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
splitAfterFirstIdle(materialized);
await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fs.makeTempDirectory({
prefix: "t3-orchestration-v2-recovery-",
});
yield* fs.makeDirectory(tempDir, { recursive: true });
const dbPath = path.join(tempDir, "state.sqlite");
const driver = yield* CodexReplay.makeReplayDriver(transcript);
const materialized = yield* materializeFixtureInput({
scenario: "provider_thread_resume",
fixtureInput: {
steps: [
{ type: "message", text: FIRST_PROMPT },
{ type: "message", text: SECOND_PROMPT },
],
},
modelSelection: CODEX_MODEL_SELECTION,
});
const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
splitAfterFirstIdle(materialized);
const harness = {
...CodexOrchestratorReplayHarness,
makeProviderAdapterRegistryLayer: () =>
makeCodexProviderAdapterRegistryReplayLayer({ transcript, driver }),
};
const options = {
databaseLayer: makeSqlitePersistenceLive(dbPath).pipe(
Layer.provide(NodeServices.layer),
),
};
const harness = {
...CodexOrchestratorReplayHarness,
makeProviderAdapterRegistryLayer: () =>
makeCodexProviderAdapterRegistryReplayLayer({ transcript, driver }),
};
const options = {
databaseLayer: makeSqlitePersistenceLive(dbPath).pipe(Layer.provide(NodeServices.layer)),
};
yield* runOrchestratorV2ProviderReplayScenario(
{
name: "provider_thread_resume/codex:first-runtime",
transcript,
commands: phase1Commands,
steps: phase1Steps,
projectionThreadIds: materialized.projectionThreadIds,
},
harness,
options,
);
yield* runOrchestratorV2ProviderReplayScenario(
{
name: "provider_thread_resume/codex:first-runtime",
const result = yield* runOrchestratorV2ProviderReplayScenario(
{
name: "provider_thread_resume/codex:second-runtime",
transcript,
commands: phase2Commands,
steps: phase2Steps,
projectionThreadIds: materialized.projectionThreadIds,
},
harness,
options,
);
assertBaseProjection({
result,
transcript,
commands: phase1Commands,
steps: phase1Steps,
projectionThreadIds: materialized.projectionThreadIds,
},
harness,
options,
);
const result = yield* runOrchestratorV2ProviderReplayScenario(
{
name: "provider_thread_resume/codex:second-runtime",
transcript,
commands: phase2Commands,
steps: phase2Steps,
projectionThreadIds: materialized.projectionThreadIds,
},
harness,
options,
);
assertBaseProjection({
result,
transcript,
runCount: 2,
runStatuses: ["completed", "completed"],
});
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertRunOrdinals(projection, [1, 2]);
assertConversationMessageRoles(projection, ["user", "assistant", "user", "assistant"]);
assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
assertUserMessagesInclude(projection, [FIRST_PROMPT, SECOND_PROMPT]);
assertAssistantTextIncludes(projection, FIRST_FINAL);
assertAssistantTextIncludes(projection, SECOND_FINAL);
assert.lengthOf(projection.providerThreads, 1);
}).pipe(
Effect.provide(Layer.mergeAll(idAllocatorLayer, NodeServices.layer)),
provideDeterministicTestRuntime,
runCount: 2,
runStatuses: ["completed", "completed"],
});
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertRunOrdinals(projection, [1, 2]);
assertConversationMessageRoles(projection, ["user", "assistant", "user", "assistant"]);
assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
assertUserMessagesInclude(projection, [FIRST_PROMPT, SECOND_PROMPT]);
assertAssistantTextIncludes(projection, FIRST_FINAL);
assertAssistantTextIncludes(projection, SECOND_FINAL);
assert.lengthOf(projection.providerThreads, 1);
}).pipe(
provideDeterministicTestRuntime,
Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer)),
),
),
);
});
);
});
@@ -337,11 +337,15 @@ export function runOrchestratorV2Scenario(
yield* awaitDispatch(key);
}
const shellSnapshot = yield* orchestrator.getShellSnapshot();
const projectionThreadIds = new Set(collectProjectionThreadIds(scenario));
for (const thread of shellSnapshot.threads) {
projectionThreadIds.add(thread.id);
}
const projections = new Map<ThreadId, OrchestrationV2ThreadProjection>();
for (const threadId of collectProjectionThreadIds(scenario)) {
for (const threadId of projectionThreadIds) {
projections.set(threadId, yield* orchestrator.getThreadProjection(threadId));
}
const shellSnapshot = yield* orchestrator.getShellSnapshot();
yield* Effect.yieldNow;
@@ -1,4 +1,3 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import {
CommandId,
@@ -18,7 +17,6 @@ import {
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
@@ -34,7 +32,7 @@ import {
import { makeLayer as makeProviderAdapterRegistryLayer } from "../ProviderAdapterRegistry.ts";
import { CLAUDE_MODEL_SELECTION, CODEX_MODEL_SELECTION } from "./fixtures/shared.ts";
import { makeOrchestratorV2ReplayLayerWithRegistry } from "./ProviderReplayHarness.ts";
import { makeCheckpointWorkspace } from "./ReplayFixtureWorkspace.ts";
import { checkpointWorkspace } from "./ReplayFixtureWorkspace.ts";
const threadId = ThreadId.make("thread:provider-switch");
const projectId = ProjectId.make("project:provider-switch");
@@ -227,78 +225,78 @@ const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
});
describe("orchestration v2 provider switching", () => {
it("switches Codex to Claude and returns to the original Codex thread with handoffs", async () => {
const cwd = await makeCheckpointWorkspace("provider-switch");
const capturedTurns = await Effect.runPromise(Ref.make<ReadonlyArray<CapturedTurn>>([]));
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: {
1: "codex before switch",
3: "codex after return",
},
capturedTurns,
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 2: "claude switched response" },
capturedTurns,
}),
]);
const commands = [
{
type: "thread.create",
commandId: CommandId.make("command:provider-switch:create"),
threadId,
projectId,
title: "Provider switch",
modelSelection: CODEX_MODEL_SELECTION,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
},
{
type: "message.dispatch",
commandId: CommandId.make("command:provider-switch:codex"),
threadId,
messageId: MessageId.make("message:provider-switch:codex"),
text: firstPrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "message.dispatch",
commandId: CommandId.make("command:provider-switch:claude"),
threadId,
messageId: MessageId.make("message:provider-switch:claude"),
text: claudePrompt,
attachments: [],
modelSelection: CLAUDE_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "message.dispatch",
commandId: CommandId.make("command:provider-switch:return"),
threadId,
messageId: MessageId.make("message:provider-switch:return"),
text: returnPrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
] satisfies ReadonlyArray<OrchestrationV2Command>;
it.live("switches Codex to Claude and returns to the original Codex thread with handoffs", () =>
Effect.scoped(
Effect.gen(function* () {
const cwd = yield* checkpointWorkspace("provider-switch");
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: {
1: "codex before switch",
3: "codex after return",
},
capturedTurns,
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 2: "claude switched response" },
capturedTurns,
}),
]);
const commands = [
{
type: "thread.create",
commandId: CommandId.make("command:provider-switch:create"),
threadId,
projectId,
title: "Provider switch",
modelSelection: CODEX_MODEL_SELECTION,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
},
{
type: "message.dispatch",
commandId: CommandId.make("command:provider-switch:codex"),
threadId,
messageId: MessageId.make("message:provider-switch:codex"),
text: firstPrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "message.dispatch",
commandId: CommandId.make("command:provider-switch:claude"),
threadId,
messageId: MessageId.make("message:provider-switch:claude"),
text: claudePrompt,
attachments: [],
modelSelection: CLAUDE_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "message.dispatch",
commandId: CommandId.make("command:provider-switch:return"),
threadId,
messageId: MessageId.make("message:provider-switch:return"),
text: returnPrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
] satisfies ReadonlyArray<OrchestrationV2Command>;
try {
const projection = await Effect.runPromise(
Effect.gen(function* () {
const projection = yield* Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
yield* orchestrator.dispatch(commands[0]!);
yield* orchestrator.dispatch(commands[1]!);
@@ -325,143 +323,136 @@ describe("orchestration v2 provider switching", () => {
registryLayer,
),
),
),
);
const turns = await Effect.runPromise(Ref.get(capturedTurns));
);
const turns = yield* Ref.get(capturedTurns);
assert.deepEqual(
projection.runs.map((run) => [run.provider, run.status]),
[
["codex", "completed"],
["claudeAgent", "completed"],
["codex", "completed"],
],
);
assert.lengthOf(projection.providerThreads, 2);
assert.equal(projection.runs[0]?.providerThreadId, projection.runs[2]?.providerThreadId);
assert.notEqual(projection.runs[0]?.providerThreadId, projection.runs[1]?.providerThreadId);
assert.deepEqual(
projection.contextHandoffs.map((handoff) => handoff.strategy),
["full_thread_summary", "delta_since_target_last_seen"],
);
assert.deepEqual(
projection.contextTransfers.map((transfer) => [
transfer.type,
transfer.status,
transfer.resolution?.strategy,
]),
[
["provider_handoff", "consumed", "portable_context"],
["provider_handoff", "consumed", "delta_context"],
],
);
assert.deepEqual(
projection.turnItems
.filter((item) => item.type === "user_message")
.map((item) => item.text),
[firstPrompt, claudePrompt, returnPrompt],
);
assert.deepEqual(
projection.providerThreads.map((providerThread) => [
providerThread.provider,
providerThread.status,
providerThread.handoffIds.length,
]),
[
["codex", "idle", 1],
["claudeAgent", "idle", 1],
],
);
assert.equal(turns[0]?.text, firstPrompt);
assert.include(turns[1]?.text ?? "", "Context handoff (full_thread_summary):");
assert.include(turns[1]?.text ?? "", "codex before switch");
assert.include(turns[1]?.text ?? "", claudePrompt);
assert.include(turns[2]?.text ?? "", "Context handoff (delta_since_target_last_seen):");
assert.include(turns[2]?.text ?? "", "claude switched response");
assert.include(turns[2]?.text ?? "", returnPrompt);
assert.notInclude(turns[2]?.text ?? "", "codex before switch");
assert.equal(turns[0]?.providerThreadId, turns[2]?.providerThreadId);
} finally {
await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(cwd, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
}
});
it("resolves a Claude fork into portable Codex context on first dispatch", async () => {
const sourceThreadId = ThreadId.make("thread:cross-provider-fork:source");
const targetThreadId = ThreadId.make("thread:cross-provider-fork:target");
const sourcePrompt = "Remember that the release color is violet.";
const targetPrompt = "What release color did we choose?";
const cwd = await makeCheckpointWorkspace("cross-provider-fork");
const capturedTurns = await Effect.runPromise(Ref.make<ReadonlyArray<CapturedTurn>>([]));
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: { 1: "The release color is violet." },
capturedTurns,
assert.deepEqual(
projection.runs.map((run) => [run.provider, run.status]),
[
["codex", "completed"],
["claudeAgent", "completed"],
["codex", "completed"],
],
);
assert.lengthOf(projection.providerThreads, 2);
assert.equal(projection.runs[0]?.providerThreadId, projection.runs[2]?.providerThreadId);
assert.notEqual(projection.runs[0]?.providerThreadId, projection.runs[1]?.providerThreadId);
assert.deepEqual(
projection.contextHandoffs.map((handoff) => handoff.strategy),
["full_thread_summary", "delta_since_target_last_seen"],
);
assert.deepEqual(
projection.contextTransfers.map((transfer) => [
transfer.type,
transfer.status,
transfer.resolution?.strategy,
]),
[
["provider_handoff", "consumed", "portable_context"],
["provider_handoff", "consumed", "delta_context"],
],
);
assert.deepEqual(
projection.turnItems
.filter((item) => item.type === "user_message")
.map((item) => item.text),
[firstPrompt, claudePrompt, returnPrompt],
);
assert.deepEqual(
projection.providerThreads.map((providerThread) => [
providerThread.provider,
providerThread.status,
providerThread.handoffIds.length,
]),
[
["codex", "idle", 1],
["claudeAgent", "idle", 1],
],
);
assert.equal(turns[0]?.text, firstPrompt);
assert.include(turns[1]?.text ?? "", "Context handoff (full_thread_summary):");
assert.include(turns[1]?.text ?? "", "codex before switch");
assert.include(turns[1]?.text ?? "", claudePrompt);
assert.include(turns[2]?.text ?? "", "Context handoff (delta_since_target_last_seen):");
assert.include(turns[2]?.text ?? "", "claude switched response");
assert.include(turns[2]?.text ?? "", returnPrompt);
assert.notInclude(turns[2]?.text ?? "", "codex before switch");
assert.equal(turns[0]?.providerThreadId, turns[2]?.providerThreadId);
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 1: "I will remember violet." },
capturedTurns,
}),
]);
const commands = [
{
type: "thread.create",
commandId: CommandId.make("command:cross-provider-fork:create"),
threadId: sourceThreadId,
projectId,
title: "Cross-provider fork source",
modelSelection: CLAUDE_MODEL_SELECTION,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-fork:source"),
threadId: sourceThreadId,
messageId: MessageId.make("message:cross-provider-fork:source"),
text: sourcePrompt,
attachments: [],
modelSelection: CLAUDE_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "thread.fork",
commandId: CommandId.make("command:cross-provider-fork:fork"),
sourceThreadId,
targetThreadId,
sourcePoint: { type: "latest_stable" },
title: "Cross-provider fork target",
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-fork:target"),
threadId: targetThreadId,
messageId: MessageId.make("message:cross-provider-fork:target"),
text: targetPrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
] satisfies ReadonlyArray<OrchestrationV2Command>;
),
);
try {
const targetProjection = await Effect.runPromise(
Effect.gen(function* () {
it.live("resolves a Claude fork into portable Codex context on first dispatch", () =>
Effect.scoped(
Effect.gen(function* () {
const sourceThreadId = ThreadId.make("thread:cross-provider-fork:source");
const targetThreadId = ThreadId.make("thread:cross-provider-fork:target");
const sourcePrompt = "Remember that the release color is violet.";
const targetPrompt = "What release color did we choose?";
const cwd = yield* checkpointWorkspace("cross-provider-fork");
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: { 1: "The release color is violet." },
capturedTurns,
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 1: "I will remember violet." },
capturedTurns,
}),
]);
const commands = [
{
type: "thread.create",
commandId: CommandId.make("command:cross-provider-fork:create"),
threadId: sourceThreadId,
projectId,
title: "Cross-provider fork source",
modelSelection: CLAUDE_MODEL_SELECTION,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-fork:source"),
threadId: sourceThreadId,
messageId: MessageId.make("message:cross-provider-fork:source"),
text: sourcePrompt,
attachments: [],
modelSelection: CLAUDE_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "thread.fork",
commandId: CommandId.make("command:cross-provider-fork:fork"),
sourceThreadId,
targetThreadId,
sourcePoint: { type: "latest_stable" },
title: "Cross-provider fork target",
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-fork:target"),
threadId: targetThreadId,
messageId: MessageId.make("message:cross-provider-fork:target"),
text: targetPrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
] satisfies ReadonlyArray<OrchestrationV2Command>;
const targetProjection = yield* Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
yield* orchestrator.dispatch(commands[0]!);
yield* orchestrator.dispatch(commands[1]!);
@@ -487,157 +478,150 @@ describe("orchestration v2 provider switching", () => {
registryLayer,
),
),
),
);
const turns = await Effect.runPromise(Ref.get(capturedTurns));
const targetTurn = turns.find((turn) => turn.threadId === targetThreadId);
);
const turns = yield* Ref.get(capturedTurns);
const targetTurn = turns.find((turn) => turn.threadId === targetThreadId);
assert.deepEqual(
targetProjection.runs.map((run) => [run.provider, run.status]),
[["codex", "completed"]],
);
assert.lengthOf(targetProjection.providerThreads, 1);
assert.equal(targetProjection.providerThreads[0]?.provider, "codex");
assert.isNull(targetProjection.providerThreads[0]?.forkedFrom);
assert.deepEqual(
targetProjection.contextTransfers.map((transfer) => [
transfer.type,
transfer.status,
transfer.resolution?.strategy,
]),
[["fork", "consumed", "portable_context"]],
);
assert.deepEqual(
targetProjection.contextHandoffs.map((handoff) => handoff.strategy),
["full_thread_summary"],
);
assert.equal(
targetProjection.runs[0]?.contextHandoffId,
targetProjection.contextHandoffs[0]?.id,
);
assert.include(targetTurn?.text ?? "", "Context handoff (full_thread_summary):");
assert.include(targetTurn?.text ?? "", sourcePrompt);
assert.include(targetTurn?.text ?? "", "I will remember violet.");
assert.include(targetTurn?.text ?? "", targetPrompt);
} finally {
await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(cwd, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
}
});
it("switches providers while consuming a pending cross-provider merge-back", async () => {
const sourceThreadId = ThreadId.make("thread:cross-provider-merge:source");
const forkThreadId = ThreadId.make("thread:cross-provider-merge:fork");
const firstSourcePrompt = "Remember that the first source marker is amber.";
const secondSourcePrompt = "Remember that the second source marker is violet.";
const forkPrompt = "Remember that the fork marker is cobalt.";
const mergePrompt = "Report all three remembered markers.";
const cwd = await makeCheckpointWorkspace("cross-provider-merge");
const capturedTurns = await Effect.runPromise(Ref.make<ReadonlyArray<CapturedTurn>>([]));
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: {},
responseByThreadId: {
[sourceThreadId]: {
1: "I will remember amber.",
3: "The markers are amber, violet, and cobalt.",
},
[forkThreadId]: {
1: "I will remember cobalt.",
},
},
capturedTurns,
assert.deepEqual(
targetProjection.runs.map((run) => [run.provider, run.status]),
[["codex", "completed"]],
);
assert.lengthOf(targetProjection.providerThreads, 1);
assert.equal(targetProjection.providerThreads[0]?.provider, "codex");
assert.isNull(targetProjection.providerThreads[0]?.forkedFrom);
assert.deepEqual(
targetProjection.contextTransfers.map((transfer) => [
transfer.type,
transfer.status,
transfer.resolution?.strategy,
]),
[["fork", "consumed", "portable_context"]],
);
assert.deepEqual(
targetProjection.contextHandoffs.map((handoff) => handoff.strategy),
["full_thread_summary"],
);
assert.equal(
targetProjection.runs[0]?.contextHandoffId,
targetProjection.contextHandoffs[0]?.id,
);
assert.include(targetTurn?.text ?? "", "Context handoff (full_thread_summary):");
assert.include(targetTurn?.text ?? "", sourcePrompt);
assert.include(targetTurn?.text ?? "", "I will remember violet.");
assert.include(targetTurn?.text ?? "", targetPrompt);
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 2: "I will remember violet." },
capturedTurns,
}),
]);
const commands = [
{
type: "thread.create",
commandId: CommandId.make("command:cross-provider-merge:create"),
threadId: sourceThreadId,
projectId,
title: "Cross-provider merge source",
modelSelection: CODEX_MODEL_SELECTION,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-merge:first-source"),
threadId: sourceThreadId,
messageId: MessageId.make("message:cross-provider-merge:first-source"),
text: firstSourcePrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-merge:second-source"),
threadId: sourceThreadId,
messageId: MessageId.make("message:cross-provider-merge:second-source"),
text: secondSourcePrompt,
attachments: [],
modelSelection: CLAUDE_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "thread.fork",
commandId: CommandId.make("command:cross-provider-merge:fork"),
sourceThreadId,
targetThreadId: forkThreadId,
sourcePoint: { type: "latest_stable" },
title: "Cross-provider merge fork",
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-merge:fork-turn"),
threadId: forkThreadId,
messageId: MessageId.make("message:cross-provider-merge:fork-turn"),
text: forkPrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "thread.merge_back",
commandId: CommandId.make("command:cross-provider-merge:merge"),
sourceThreadId: forkThreadId,
targetThreadId: sourceThreadId,
sourcePoint: { type: "latest_stable" },
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-merge:consume"),
threadId: sourceThreadId,
messageId: MessageId.make("message:cross-provider-merge:consume"),
text: mergePrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
] satisfies ReadonlyArray<OrchestrationV2Command>;
),
);
try {
const projection = await Effect.runPromise(
Effect.gen(function* () {
it.live("switches providers while consuming a pending cross-provider merge-back", () =>
Effect.scoped(
Effect.gen(function* () {
const sourceThreadId = ThreadId.make("thread:cross-provider-merge:source");
const forkThreadId = ThreadId.make("thread:cross-provider-merge:fork");
const firstSourcePrompt = "Remember that the first source marker is amber.";
const secondSourcePrompt = "Remember that the second source marker is violet.";
const forkPrompt = "Remember that the fork marker is cobalt.";
const mergePrompt = "Report all three remembered markers.";
const cwd = yield* checkpointWorkspace("cross-provider-merge");
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: {},
responseByThreadId: {
[sourceThreadId]: {
1: "I will remember amber.",
3: "The markers are amber, violet, and cobalt.",
},
[forkThreadId]: {
1: "I will remember cobalt.",
},
},
capturedTurns,
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 2: "I will remember violet." },
capturedTurns,
}),
]);
const commands = [
{
type: "thread.create",
commandId: CommandId.make("command:cross-provider-merge:create"),
threadId: sourceThreadId,
projectId,
title: "Cross-provider merge source",
modelSelection: CODEX_MODEL_SELECTION,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-merge:first-source"),
threadId: sourceThreadId,
messageId: MessageId.make("message:cross-provider-merge:first-source"),
text: firstSourcePrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-merge:second-source"),
threadId: sourceThreadId,
messageId: MessageId.make("message:cross-provider-merge:second-source"),
text: secondSourcePrompt,
attachments: [],
modelSelection: CLAUDE_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "thread.fork",
commandId: CommandId.make("command:cross-provider-merge:fork"),
sourceThreadId,
targetThreadId: forkThreadId,
sourcePoint: { type: "latest_stable" },
title: "Cross-provider merge fork",
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-merge:fork-turn"),
threadId: forkThreadId,
messageId: MessageId.make("message:cross-provider-merge:fork-turn"),
text: forkPrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
{
type: "thread.merge_back",
commandId: CommandId.make("command:cross-provider-merge:merge"),
sourceThreadId: forkThreadId,
targetThreadId: sourceThreadId,
sourcePoint: { type: "latest_stable" },
},
{
type: "message.dispatch",
commandId: CommandId.make("command:cross-provider-merge:consume"),
threadId: sourceThreadId,
messageId: MessageId.make("message:cross-provider-merge:consume"),
text: mergePrompt,
attachments: [],
modelSelection: CODEX_MODEL_SELECTION,
dispatchMode: { type: "start_immediately" },
},
] satisfies ReadonlyArray<OrchestrationV2Command>;
const projection = yield* Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
yield* orchestrator.dispatch(commands[0]!);
yield* orchestrator.dispatch(commands[1]!);
@@ -668,37 +652,30 @@ describe("orchestration v2 provider switching", () => {
registryLayer,
),
),
),
);
const turns = await Effect.runPromise(Ref.get(capturedTurns));
const mergedTurn = turns.findLast(
(turn) => turn.threadId === sourceThreadId && turn.provider === "codex",
);
const mergeTransfer = projection.contextTransfers.find(
(transfer) => transfer.type === "merge_back",
);
);
const turns = yield* Ref.get(capturedTurns);
const mergedTurn = turns.findLast(
(turn) => turn.threadId === sourceThreadId && turn.provider === "codex",
);
const mergeTransfer = projection.contextTransfers.find(
(transfer) => transfer.type === "merge_back",
);
assert.isDefined(mergedTurn);
assert.include(mergedTurn.text, "Context handoff (full_thread_summary):");
assert.include(mergedTurn.text, firstSourcePrompt);
assert.include(mergedTurn.text, "I will remember amber.");
assert.include(mergedTurn.text, secondSourcePrompt);
assert.include(mergedTurn.text, "I will remember violet.");
assert.include(mergedTurn.text, "Context handoff (merge_back / fork_delta_summary):");
assert.include(mergedTurn.text, forkPrompt);
assert.include(mergedTurn.text, "I will remember cobalt.");
assert.include(mergedTurn.text, mergePrompt);
assert.isDefined(mergeTransfer);
assert.equal(mergeTransfer.status, "consumed");
assert.equal(mergeTransfer.targetProvider, "codex");
assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context");
} finally {
await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(cwd, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
}
});
assert.isDefined(mergedTurn);
assert.include(mergedTurn.text, "Context handoff (full_thread_summary):");
assert.include(mergedTurn.text, firstSourcePrompt);
assert.include(mergedTurn.text, "I will remember amber.");
assert.include(mergedTurn.text, secondSourcePrompt);
assert.include(mergedTurn.text, "I will remember violet.");
assert.include(mergedTurn.text, "Context handoff (merge_back / fork_delta_summary):");
assert.include(mergedTurn.text, forkPrompt);
assert.include(mergedTurn.text, "I will remember cobalt.");
assert.include(mergedTurn.text, mergePrompt);
assert.isDefined(mergeTransfer);
assert.equal(mergeTransfer.status, "consumed");
assert.equal(mergeTransfer.targetProvider, "codex");
assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context");
}),
),
);
});
@@ -38,21 +38,37 @@ function runGit(
});
}
export const makeCheckpointWorkspaceEffect = Effect.fn("makeCheckpointWorkspace")(function* (
fixtureName: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cwd = yield* fs.makeTempDirectory({
prefix: `t3-orchestrator-v2-${fixtureName}-`,
});
yield* runGit(cwd, ["init"]);
yield* runGit(cwd, ["config", "user.name", "T3 Code Test"]);
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
yield* fs.writeFileString(path.join(cwd, "README.md"), `# ${fixtureName}\n`);
yield* runGit(cwd, ["add", "README.md"]);
yield* runGit(cwd, ["commit", "-m", "initial"]);
return cwd;
});
export const removeCheckpointWorkspaceEffect = Effect.fn("removeCheckpointWorkspace")(function* (
cwd: string,
) {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(cwd, { recursive: true });
});
export const checkpointWorkspace = (fixtureName: string) =>
Effect.acquireRelease(makeCheckpointWorkspaceEffect(fixtureName), (cwd) =>
removeCheckpointWorkspaceEffect(cwd).pipe(Effect.orDie),
).pipe(Effect.provide(NodeServices.layer));
export async function makeCheckpointWorkspace(fixtureName: string): Promise<string> {
return await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cwd = yield* fs.makeTempDirectory({
prefix: `t3-orchestrator-v2-${fixtureName}-`,
});
yield* runGit(cwd, ["init"]);
yield* runGit(cwd, ["config", "user.name", "T3 Code Test"]);
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
yield* fs.writeFileString(path.join(cwd, "README.md"), `# ${fixtureName}\n`);
yield* runGit(cwd, ["add", "README.md"]);
yield* runGit(cwd, ["commit", "-m", "initial"]);
return cwd;
}).pipe(Effect.provide(NodeServices.layer)),
makeCheckpointWorkspaceEffect(fixtureName).pipe(Effect.provide(NodeServices.layer)),
);
}
@@ -5,6 +5,8 @@ import * as Schema from "effect/Schema";
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
const encodeParseError = Schema.encodeUnknownEffect(ProviderReplayNdjsonParseError);
describe("decodeProviderReplayNdjson", () => {
it.effect("decodes a self-describing provider replay fixture", () =>
Effect.gen(function* () {
@@ -48,7 +50,7 @@ describe("decodeProviderReplayNdjson", () => {
it.effect("returns a schema-serializable typed parse error", () =>
Effect.gen(function* () {
const error = yield* decodeProviderReplayNdjson(`{"type":`).pipe(Effect.flip);
const encoded = Schema.encodeUnknownSync(ProviderReplayNdjsonParseError)(error);
const encoded = yield* encodeParseError(error);
assert.equal(error._tag, "ProviderReplayNdjsonLineParseError");
assert.equal(encoded._tag, "ProviderReplayNdjsonLineParseError");
@@ -57,19 +59,14 @@ describe("decodeProviderReplayNdjson", () => {
}
assert.equal(encoded.lineNumber, 1);
assert.equal(encoded.line, '{"type":');
assert.deepEqual(encoded.cause, {
name: "Error",
message: "SyntaxError: Unexpected end of JSON input",
});
assert.deepEqual(encoded, {
_tag: "ProviderReplayNdjsonLineParseError",
lineNumber: 1,
line: '{"type":',
cause: {
name: "Error",
message: "SyntaxError: Unexpected end of JSON input",
},
});
const cause = encoded.cause;
if (typeof cause !== "object" || cause === null || Array.isArray(cause)) {
throw new Error("Expected encoded parse cause to be a JSON object.");
}
const causeRecord = cause as Record<string, unknown>;
assert.equal(causeRecord.name, "SchemaError");
assert.equal(causeRecord._tag, "SchemaError");
assert.doesNotThrow(() => JSON.stringify(encoded));
}),
);
});
@@ -12,7 +12,7 @@ export class ProviderReplayNdjsonLineParseError extends Schema.TaggedErrorClass<
{
lineNumber: Schema.Number,
line: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
@@ -16,6 +16,8 @@ import { simpleInput } from "./simple/input.ts";
import { assertSubagentOutput } from "./subagent/codex_output.ts";
import { assertClaudeSubagentOutput } from "./subagent/claude_output.ts";
import { subagentInput } from "./subagent/input.ts";
import { assertSubagentContinueOutput } from "./subagent_continue/codex_output.ts";
import { subagentContinueInput } from "./subagent_continue/input.ts";
import { assertClaudeThreadRollbackOutput } from "./thread_rollback/claude_output.ts";
import { assertThreadRollbackOutput } from "./thread_rollback/codex_output.ts";
import { threadRollbackInput } from "./thread_rollback/input.ts";
@@ -182,6 +184,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
},
],
},
{
name: "subagent_continue",
buildInput: subagentContinueInput,
providers: [
{
provider: "codex",
transcriptFile: new URL("./subagent_continue/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
assertOutput: assertSubagentContinueOutput,
},
],
},
{
name: "multi_turn",
buildInput: multiTurnInput,
@@ -42,6 +42,11 @@ export const MESSAGE_STEERING_INITIAL_PROMPT =
"Respond with exactly: steering fixture initial response";
export const SUBAGENT_PROMPT =
"Spawn 2 subagents, one to read package.json and one to read tsconfig.json";
export const SUBAGENT_CONTINUE_PROMPT =
"Spawn one subagent and have it reply exactly: initial subagent response";
export const SUBAGENT_CONTINUE_PARENT_PROMPT =
"@hooke have the same subagent reply exactly: continued subagent response";
export const SUBAGENT_CONTINUE_CHILD_PROMPT = "Reply exactly: continued subagent response";
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 =
@@ -588,9 +593,11 @@ export function projectionFor(
result: OrchestratorV2ScenarioResult,
scenario: string,
): OrchestrationV2ThreadProjection {
const projections = [...result.projections.values()];
const projections = [...result.projections.values()].filter(
(projection) => projection.thread.lineage.parentThreadId === null,
);
assert.equal(projections.length, 1, `expected one projection for ${scenario}`);
assert.equal(projections.length, 1, `expected one root projection for ${scenario}`);
const projection = projections[0];
assert.isDefined(projection, `missing projection for ${scenario}`);
return projection;
@@ -28,18 +28,18 @@ export function assertClaudeSubagentOutput(
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertExecutionNodeKinds(projection, ["root_turn", "subagent", "tool_call"]);
assertTurnItemTypes(projection, [
"user_message",
"subagent",
"dynamic_tool",
"assistant_message",
]);
assertExecutionNodeKinds(projection, ["root_turn", "subagent"]);
assertTurnItemTypes(projection, ["user_message", "subagent", "assistant_message"]);
assertRunProviderTurnCardinality({ projection, rootRunCount: 1 });
assertNoExtraAppRunsForProviderChildren({ projection, expectedAppRuns: 1 });
assertUserMessagesInclude(projection, [SUBAGENT_PROMPT]);
assertAssistantTextIncludes(projection, "claude-read-only-fixture");
assertAssistantTextIncludes(projection, "ES2022");
assert.lengthOf(
projection.turnItems.filter((item) => item.type === "dynamic_tool"),
0,
"subagent tools must not be projected into the parent thread",
);
const subagentNodes = projection.nodes.filter((node) => node.kind === "subagent");
assert.lengthOf(subagentNodes, 2);
@@ -49,12 +49,13 @@ export function assertClaudeSubagentOutput(
);
assert.lengthOf(projection.subagents, 2);
assert.lengthOf(result.shellSnapshot.threads, 3);
assert.isTrue(
projection.subagents.some(
(subagent) =>
subagent.prompt ===
"Read the file `package.json` in the current working directory and return its full contents." &&
subagent.result === "Read package.json",
subagent.result?.includes("claude-read-only-fixture"),
),
);
assert.isTrue(
@@ -62,7 +63,7 @@ export function assertClaudeSubagentOutput(
(subagent) =>
subagent.prompt ===
"Read the file `tsconfig.json` in the current working directory and return its full contents." &&
subagent.result === "Read tsconfig.json",
subagent.result?.includes("ES2022"),
),
);
for (const subagent of projection.subagents) {
@@ -71,17 +72,32 @@ export function assertClaudeSubagentOutput(
assert.equal(subagent.provider, "claudeAgent");
assert.equal(subagent.status, "completed");
assert.isNull(subagent.providerThreadId);
assert.isNull(subagent.childThreadId);
assert.isNotNull(subagent.childThreadId);
assert.isNotNull(subagent.nativeTaskRef);
assert.isNotNull(subagent.completedAt);
}
if (subagent.childThreadId === null) {
throw new Error(`Subagent ${subagent.id} is missing its child thread`);
}
const subagentNodeIds = new Set(subagentNodes.map((node) => node.id));
const nestedToolNodes = projection.nodes.filter(
(node) =>
node.kind === "tool_call" &&
node.parentNodeId !== null &&
subagentNodeIds.has(node.parentNodeId),
);
assert.isAtLeast(nestedToolNodes.length, 2);
const childProjection = result.projections.get(subagent.childThreadId);
assert.isDefined(childProjection);
assert.equal(childProjection.thread.lineage.parentThreadId, projection.thread.id);
assert.equal(childProjection.thread.lineage.relationshipToParent, "subagent");
assert.isNull(childProjection.thread.activeProviderThreadId);
assert.lengthOf(childProjection.runs, 0);
assert.lengthOf(childProjection.providerThreads, 0);
assert.lengthOf(childProjection.providerTurns, 0);
assertExecutionNodeKinds(childProjection, ["root_turn", "tool_call"]);
assertTurnItemTypes(childProjection, ["user_message", "dynamic_tool", "assistant_message"]);
assertUserMessagesInclude(childProjection, [subagent.prompt]);
assert.isTrue(
childProjection.turnItems.some(
(item) =>
item.type === "assistant_message" &&
subagent.result !== null &&
item.text.includes(subagent.result.slice(0, 40)),
),
`child thread ${subagent.childThreadId} must contain the subagent response`,
);
}
}
@@ -22,7 +22,6 @@ export function assertSubagentOutput(
result,
transcript,
runCount: 1,
providerTurnCountAtLeast: 3,
runStatuses: ["completed"],
});
@@ -30,12 +29,18 @@ export function assertSubagentOutput(
assertSemanticProjectionIntegrity(projection);
assertTurnItemTypes(projection, ["user_message", "subagent", "assistant_message"]);
assertExecutionNodeKinds(projection, ["root_turn", "subagent"]);
assertRunProviderTurnCardinality({ projection, rootRunCount: 1, providerTurnCountAtLeast: 3 });
assertRunProviderTurnCardinality({ projection, rootRunCount: 1 });
assertNoExtraAppRunsForProviderChildren({ projection, expectedAppRuns: 1 });
assertUserMessagesInclude(projection, [SUBAGENT_PROMPT]);
assert.equal(projection.runs.length, 1, "subagent provider turns must not become app runs");
assert.lengthOf(
projection.turnItems.filter((item) => item.type === "command_execution"),
0,
"subagent commands must not be projected into the parent thread",
);
assert.lengthOf(projection.subagents, 2);
assert.lengthOf(result.shellSnapshot.threads, 3);
assert.deepEqual(
projection.subagents.map((subagent) => subagent.status),
["completed", "completed"],
@@ -59,21 +64,48 @@ export function assertSubagentOutput(
assert.equal(subagent.origin, "provider_native");
assert.equal(subagent.createdBy, "agent");
assert.equal(subagent.provider, "codex");
assert.isNull(subagent.childThreadId);
assert.isNotNull(subagent.childThreadId);
assert.isNotNull(subagent.providerThreadId);
assert.isNotNull(subagent.nativeTaskRef);
assert.isNotNull(subagent.completedAt);
if (subagent.childThreadId === null) {
throw new Error(`Subagent ${subagent.id} is missing its child thread`);
}
const providerThread = projection.providerThreads.find(
(thread) => thread.id === subagent.providerThreadId,
);
assert.isDefined(providerThread);
assert.isNull(providerThread.appThreadId);
assert.equal(providerThread.ownerNodeId, subagent.id);
assert.equal(providerThread.appThreadId, subagent.childThreadId);
assert.isNull(providerThread.ownerNodeId);
const childProjection = result.projections.get(subagent.childThreadId);
assert.isDefined(childProjection);
assert.equal(childProjection.thread.lineage.parentThreadId, projection.thread.id);
assert.equal(childProjection.thread.lineage.relationshipToParent, "subagent");
assert.equal(childProjection.thread.activeProviderThreadId, providerThread.id);
assert.lengthOf(childProjection.runs, 0);
assert.lengthOf(childProjection.providerThreads, 1);
assert.lengthOf(childProjection.providerTurns, 1);
assertTurnItemTypes(childProjection, [
"user_message",
"command_execution",
"assistant_message",
]);
assertUserMessagesInclude(childProjection, [subagent.prompt]);
assert.isTrue(
childProjection.turnItems.some(
(item) =>
item.type === "assistant_message" &&
subagent.result !== null &&
item.text.includes(subagent.result.slice(0, 40)),
),
`child thread ${subagent.childThreadId} must contain the subagent response`,
);
}
const rootProviderThread = projection.providerThreads.find(
(thread) => thread.ownerNodeId === null,
(thread) => thread.ownerNodeId === null && thread.appThreadId === projection.thread.id,
);
assert.isDefined(rootProviderThread);
assert.equal(rootProviderThread.appThreadId, projection.thread.id);
@@ -0,0 +1,28 @@
# Continued Native Subagent
This fixture records Codex continuing a native subagent from a later parent turn.
```text
Parent app thread / Codex thread A
Turn 1: spawn one subagent
|
+-- spawnAgent
|
v
Child app thread / Codex thread B
Turn 1: initial prompt
Assistant: initial subagent response
Turn 2: @hooke continue the same subagent
|
+-- resumeAgent + sendInput
|
v
Child app thread / Codex thread B
Turn 2: continuation prompt
Assistant: continued subagent response
```
The original parent `subagent` item represents only the spawn lifecycle. It must
remain completed with the first result while the child thread accumulates later
conversation turns.
@@ -0,0 +1,59 @@
import { assert } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
import {
assertBaseProjection,
assertNoExtraAppRunsForProviderChildren,
assertSemanticProjectionIntegrity,
assertUserMessagesInclude,
projectionFor,
SUBAGENT_CONTINUE_CHILD_PROMPT,
SUBAGENT_CONTINUE_PARENT_PROMPT,
SUBAGENT_CONTINUE_PROMPT,
} from "../shared.ts";
export function assertSubagentContinueOutput(
result: OrchestratorV2ScenarioResult,
transcript: ProviderReplayTranscript,
) {
assertBaseProjection({
result,
transcript,
runCount: 2,
runStatuses: ["completed", "completed"],
});
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertNoExtraAppRunsForProviderChildren({ projection, expectedAppRuns: 2 });
assertUserMessagesInclude(projection, [
SUBAGENT_CONTINUE_PROMPT,
SUBAGENT_CONTINUE_PARENT_PROMPT,
]);
assert.lengthOf(projection.subagents, 1);
const subagent = projection.subagents[0]!;
assert.equal(subagent.status, "completed");
assert.equal(subagent.result, "initial subagent response");
assert.isNotNull(subagent.childThreadId);
if (subagent.childThreadId === null) {
throw new Error("Continued subagent is missing its child thread");
}
const childProjection = result.projections.get(subagent.childThreadId);
assert.isDefined(childProjection);
assert.lengthOf(childProjection.runs, 0);
assert.lengthOf(childProjection.providerTurns, 2);
assertUserMessagesInclude(childProjection, [subagent.prompt, SUBAGENT_CONTINUE_CHILD_PROMPT]);
assert.isTrue(
childProjection.turnItems.some(
(item) => item.type === "assistant_message" && item.text === "initial subagent response",
),
);
assert.isTrue(
childProjection.turnItems.some(
(item) => item.type === "assistant_message" && item.text === "continued subagent response",
),
);
}
@@ -0,0 +1,33 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.137.0","scenario":"subagent_continue","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"subagent_continue.ndjson","description":"A root turn spawns one native Codex subagent, then a later root turn resumes and messages the same child thread."}}
{"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.137.0","codexHome":"/tmp/codex-home","platformFamily":"unix","platformOs":"macos"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{}}}
{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"native-root-thread","sessionId":"native-root-thread","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1781051850,"updatedAt":1781051850,"status":{"type":"idle"},"path":"/tmp/root-thread.jsonl","cwd":"/tmp","cliVersion":"0.137.0","source":"vscode","threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":null,"cwd":"/tmp","instructionSources":[],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false},"reasoningEffort":"high"}}}
{"type":"expect_outbound","label":"turn/start/spawn","frame":{"id":3,"method":"turn/start","params":{"input":[{"text":"Spawn one subagent and have it reply exactly: initial subagent response","type":"text"}],"threadId":"native-root-thread"}}}
{"type":"emit_inbound","label":"turn/start/spawn","frame":{"id":3,"result":{"turn":{"id":"native-root-turn-1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
{"type":"emit_inbound","label":"turn/started/root-1","frame":{"method":"turn/started","params":{"threadId":"native-root-thread","turn":{"id":"native-root-turn-1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1781051851,"completedAt":null,"durationMs":null}}}}
{"type":"emit_inbound","label":"item/completed/root-user-1","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"root-user-1","content":[{"type":"text","text":"Spawn one subagent and have it reply exactly: initial subagent response","text_elements":[]}]},"threadId":"native-root-thread","turnId":"native-root-turn-1","completedAtMs":1781051851000}}}
{"type":"emit_inbound","label":"item/started/spawnAgent","frame":{"method":"item/started","params":{"item":{"type":"collabAgentToolCall","id":"spawn-call-1","tool":"spawnAgent","status":"inProgress","senderThreadId":"native-root-thread","receiverThreadIds":[],"prompt":"Reply exactly: initial subagent response","model":"","reasoningEffort":"medium","agentsStates":{}},"threadId":"native-root-thread","turnId":"native-root-turn-1","startedAtMs":1781051852000}}}
{"type":"emit_inbound","label":"item/completed/spawnAgent","frame":{"method":"item/completed","params":{"item":{"type":"collabAgentToolCall","id":"spawn-call-1","tool":"spawnAgent","status":"completed","senderThreadId":"native-root-thread","receiverThreadIds":["native-child-thread"],"prompt":"Reply exactly: initial subagent response","model":"kindle-alpha","reasoningEffort":"high","agentsStates":{"native-child-thread":{"status":"pendingInit","message":null}}},"threadId":"native-root-thread","turnId":"native-root-turn-1","completedAtMs":1781051852100}}}
{"type":"emit_inbound","label":"turn/started/child-1","frame":{"method":"turn/started","params":{"threadId":"native-child-thread","turn":{"id":"native-child-turn-1","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1781051852,"completedAt":null,"durationMs":null}}}}
{"type":"emit_inbound","label":"item/completed/child-user-1","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"child-user-1","content":[{"type":"text","text":"Reply exactly: initial subagent response","text_elements":[]}]},"threadId":"native-child-thread","turnId":"native-child-turn-1","completedAtMs":1781051852200}}}
{"type":"emit_inbound","label":"item/completed/child-answer-1","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"child-answer-1","text":"initial subagent response","phase":"final_answer","memoryCitation":null},"threadId":"native-child-thread","turnId":"native-child-turn-1","completedAtMs":1781051853000}}}
{"type":"emit_inbound","label":"turn/completed/child-1","frame":{"method":"turn/completed","params":{"threadId":"native-child-thread","turn":{"id":"native-child-turn-1","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1781051852,"completedAt":1781051853,"durationMs":1000}}}}
{"type":"emit_inbound","label":"item/completed/wait-1","frame":{"method":"item/completed","params":{"item":{"type":"collabAgentToolCall","id":"wait-call-1","tool":"wait","status":"completed","senderThreadId":"native-root-thread","receiverThreadIds":["native-child-thread"],"prompt":null,"model":null,"reasoningEffort":null,"agentsStates":{"native-child-thread":{"status":"completed","message":"initial subagent response"}}},"threadId":"native-root-thread","turnId":"native-root-turn-1","completedAtMs":1781051853100}}}
{"type":"emit_inbound","label":"item/completed/root-answer-1","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"root-answer-1","text":"Hooke says: initial subagent response","phase":"final_answer","memoryCitation":null},"threadId":"native-root-thread","turnId":"native-root-turn-1","completedAtMs":1781051854000}}}
{"type":"emit_inbound","label":"turn/completed/root-1","frame":{"method":"turn/completed","params":{"threadId":"native-root-thread","turn":{"id":"native-root-turn-1","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1781051851,"completedAt":1781051854,"durationMs":3000}}}}
{"type":"expect_outbound","label":"turn/start/continue","frame":{"id":4,"method":"turn/start","params":{"input":[{"text":"@hooke have the same subagent reply exactly: continued subagent response","type":"text"}],"threadId":"native-root-thread"}}}
{"type":"emit_inbound","label":"turn/start/continue","frame":{"id":4,"result":{"turn":{"id":"native-root-turn-2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
{"type":"emit_inbound","label":"turn/started/root-2","frame":{"method":"turn/started","params":{"threadId":"native-root-thread","turn":{"id":"native-root-turn-2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1781051860,"completedAt":null,"durationMs":null}}}}
{"type":"emit_inbound","label":"item/completed/root-user-2","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"root-user-2","content":[{"type":"text","text":"@hooke have the same subagent reply exactly: continued subagent response","text_elements":[]}]},"threadId":"native-root-thread","turnId":"native-root-turn-2","completedAtMs":1781051860000}}}
{"type":"emit_inbound","label":"item/completed/resumeAgent","frame":{"method":"item/completed","params":{"item":{"type":"collabAgentToolCall","id":"resume-call-1","tool":"resumeAgent","status":"completed","senderThreadId":"native-root-thread","receiverThreadIds":["native-child-thread"],"prompt":null,"model":null,"reasoningEffort":null,"agentsStates":{"native-child-thread":{"status":"completed","message":"initial subagent response"}}},"threadId":"native-root-thread","turnId":"native-root-turn-2","completedAtMs":1781051860100}}}
{"type":"emit_inbound","label":"item/completed/sendInput","frame":{"method":"item/completed","params":{"item":{"type":"collabAgentToolCall","id":"send-input-call-1","tool":"sendInput","status":"completed","senderThreadId":"native-root-thread","receiverThreadIds":["native-child-thread"],"prompt":"Reply exactly: continued subagent response","model":null,"reasoningEffort":null,"agentsStates":{"native-child-thread":{"status":"completed","message":"initial subagent response"}}},"threadId":"native-root-thread","turnId":"native-root-turn-2","completedAtMs":1781051860200}}}
{"type":"emit_inbound","label":"turn/started/child-2","frame":{"method":"turn/started","params":{"threadId":"native-child-thread","turn":{"id":"native-child-turn-2","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1781051861,"completedAt":null,"durationMs":null}}}}
{"type":"emit_inbound","label":"item/completed/child-user-2","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"child-user-2","content":[{"type":"text","text":"Reply exactly: continued subagent response","text_elements":[]}]},"threadId":"native-child-thread","turnId":"native-child-turn-2","completedAtMs":1781051861100}}}
{"type":"emit_inbound","label":"item/completed/child-answer-2","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"child-answer-2","text":"continued subagent response","phase":"final_answer","memoryCitation":null},"threadId":"native-child-thread","turnId":"native-child-turn-2","completedAtMs":1781051862000}}}
{"type":"emit_inbound","label":"turn/completed/child-2","frame":{"method":"turn/completed","params":{"threadId":"native-child-thread","turn":{"id":"native-child-turn-2","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1781051861,"completedAt":1781051862,"durationMs":1000}}}}
{"type":"emit_inbound","label":"item/completed/wait-2","frame":{"method":"item/completed","params":{"item":{"type":"collabAgentToolCall","id":"wait-call-2","tool":"wait","status":"completed","senderThreadId":"native-root-thread","receiverThreadIds":["native-child-thread"],"prompt":null,"model":null,"reasoningEffort":null,"agentsStates":{"native-child-thread":{"status":"completed","message":"continued subagent response"}}},"threadId":"native-root-thread","turnId":"native-root-turn-2","completedAtMs":1781051862100}}}
{"type":"emit_inbound","label":"item/completed/root-answer-2","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"root-answer-2","text":"Hooke says: continued subagent response","phase":"final_answer","memoryCitation":null},"threadId":"native-root-thread","turnId":"native-root-turn-2","completedAtMs":1781051863000}}}
{"type":"emit_inbound","label":"turn/completed/root-2","frame":{"method":"turn/completed","params":{"threadId":"native-root-thread","turn":{"id":"native-root-turn-2","items":[],"itemsView":"notLoaded","status":"completed","error":null,"startedAt":1781051860,"completedAt":1781051863,"durationMs":3000}}}}
{"type":"runtime_exit","status":"success"}
@@ -0,0 +1,14 @@
import {
SUBAGENT_CONTINUE_PARENT_PROMPT,
SUBAGENT_CONTINUE_PROMPT,
type OrchestratorFixtureInput,
} from "../shared.ts";
export function subagentContinueInput(): OrchestratorFixtureInput {
return {
steps: [
{ type: "message", text: SUBAGENT_CONTINUE_PROMPT },
{ type: "message", text: SUBAGENT_CONTINUE_PARENT_PROMPT },
],
};
}
@@ -0,0 +1,49 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("033_034_OrchestrationV2", (it) => {
it.effect("installs the orchestration v2 and subagent schemas", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 34 });
const migrations = yield* sql<{
readonly migration_id: number;
readonly name: string;
}>`
SELECT migration_id, name
FROM effect_sql_migrations
WHERE migration_id IN (33, 34)
ORDER BY migration_id
`;
assert.deepStrictEqual(migrations, [
{
migration_id: 33,
name: "OrchestrationV2",
},
{
migration_id: 34,
name: "OrchestrationV2Subagents",
},
]);
const eventColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(orchestration_v2_events)
`;
const subagentColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(orchestration_v2_projection_subagents)
`;
assert.ok(eventColumns.some((column) => column.name === "event_id"));
assert.ok(subagentColumns.some((column) => column.name === "child_thread_id"));
}),
);
});
@@ -1,6 +1,7 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
// Base schema for the orchestration V2 event log and projections.
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
+4 -1
View File
@@ -264,7 +264,7 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
Layer.provideMerge(OrchestrationLayerLive),
);
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
const RuntimeCoreDependenciesBaseLive = ReactorLayerLive.pipe(
// Core Services
Layer.provideMerge(CheckpointingLayerLive),
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
@@ -288,6 +288,9 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
// Provided once at the runtime level so every consumer sees the same
// logger instances.
Layer.provideMerge(ProviderEventLoggersLive),
);
const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe(
// `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
// `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
// the rewritten registry reads snapshots off the instance registry and
@@ -93,6 +93,12 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {
subscribeShell: vi.fn(() => () => undefined),
subscribeThread: mockSubscribeThread,
},
orchestrationV2: {
dispatchCommand: vi.fn(),
getThreadProjection: vi.fn(),
subscribeShell: vi.fn(() => () => undefined),
subscribeThread: vi.fn(() => () => undefined),
},
terminal: {
open: vi.fn(),
attach: vi.fn(() => () => undefined),
+30 -1
View File
@@ -1361,7 +1361,11 @@ function ThreadTreeRow(props: {
>
<span
className={`mt-1 size-2 rounded-full ${
relationship === "fork" ? "bg-sky-500" : "bg-emerald-500"
relationship === "fork"
? "bg-sky-500"
: relationship === "subagent"
? "bg-violet-500"
: "bg-emerald-500"
}`}
/>
<span className="min-w-0">
@@ -2131,6 +2135,12 @@ function OrchestrationV2DebugRoute() {
<ItemTimelinePanel
title={PANEL_TITLES.item}
projection={projection}
parentThread={
projection?.thread.lineage.parentThreadId === null ||
projection?.thread.lineage.parentThreadId === undefined
? null
: (shellThreadsById.get(projection.thread.lineage.parentThreadId) ?? null)
}
errorMessage={projectionError}
rows={itemTimeline}
activeTurn={activeTurn}
@@ -2521,6 +2531,7 @@ type ItemViewMode = "chat" | "raw";
function ItemTimelinePanel(props: {
readonly title: string;
readonly projection: OrchestrationV2ThreadProjection | null;
readonly parentThread: OrchestrationV2ThreadShell | null;
readonly errorMessage: string | null;
readonly rows: ReadonlyArray<ItemTimelineRow>;
readonly activeTurn: ActiveTurn | null;
@@ -2538,6 +2549,7 @@ function ItemTimelinePanel(props: {
const nowMs = useNow();
const rowCount = props.rows.length;
const activeTurnStartMs = props.activeTurn?.startMs ?? null;
const parentThread = props.parentThread;
const scrollRef = usePinnedAutoScroll(
rowCount,
`${viewMode}:${activeTurnStartMs ?? "idle"}`,
@@ -2559,6 +2571,23 @@ function ItemTimelinePanel(props: {
</>
}
/>
{parentThread === null ? null : (
<div className="flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-2 sm:px-4">
<span className="shrink-0 rounded-full border border-border bg-background px-1.5 py-px text-[10px] font-medium uppercase text-muted-foreground">
{props.projection?.thread.lineage.relationshipToParent ?? "child"}
</span>
<button
type="button"
onClick={() => {
props.onOpenThread(parentThread.id);
}}
className="min-w-0 truncate text-left text-xs font-medium text-foreground underline-offset-4 hover:underline focus-visible:rounded-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500"
title={`Open parent thread ${parentThread.id}`}
>
← {parentThread.title}
</button>
</div>
)}
{rowCount === 0 && activeTurnStartMs === null && props.errorMessage !== null ? (
<div className="flex min-h-48 flex-col items-center justify-center gap-2 p-6 text-center">
<p className="text-sm font-medium text-destructive">Failed to load projection.</p>
+3 -3
View File
@@ -1560,7 +1560,7 @@ export class OrchestrationV2DispatchCommandError extends Schema.TaggedErrorClass
commandType: Schema.String,
message: Schema.String,
detail: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {}
@@ -1569,7 +1569,7 @@ export class OrchestrationV2GetThreadProjectionError extends Schema.TaggedErrorC
{
threadId: ThreadId,
message: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {}
@@ -1577,7 +1577,7 @@ export class OrchestrationV2GetShellSnapshotError extends Schema.TaggedErrorClas
"OrchestrationV2GetShellSnapshotError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect),
cause: Schema.optional(Schema.Defect()),
},
) {}
@@ -10,6 +10,10 @@ import * as CodexClient from "./client.ts";
import * as CodexError from "./errors.ts";
import * as CodexReplay from "./replay.ts";
const isCodexAppServerTransportError = Schema.is(CodexError.CodexAppServerTransportError);
const decodeReplayError = Schema.decodeUnknownEffect(CodexReplay.CodexAppServerReplayError);
const encodeReplayError = Schema.encodeUnknownEffect(CodexReplay.CodexAppServerReplayError);
const initializeParams = {
clientInfo: {
name: "effect-codex-app-server-test",
@@ -120,14 +124,12 @@ it.effect("fails pending client requests with a schema-serializable replay misma
}).pipe(Effect.provide(context), Effect.flip, Effect.ensuring(Scope.close(scope, Exit.void)));
assert.equal(error._tag, "CodexAppServerTransportError");
if (!Schema.is(CodexError.CodexAppServerTransportError)(error)) {
if (!isCodexAppServerTransportError(error)) {
throw new Error("Expected transport error.");
}
const replayError = Schema.decodeUnknownSync(CodexReplay.CodexAppServerReplayError)(
error.cause,
);
const encoded = Schema.encodeUnknownSync(CodexReplay.CodexAppServerReplayError)(replayError);
const replayError = yield* decodeReplayError(error.cause);
const encoded = yield* encodeReplayError(replayError);
assert.equal(encoded._tag, "CodexAppServerReplayFrameMismatchError");
if (encoded._tag !== "CodexAppServerReplayFrameMismatchError") {
@@ -49,7 +49,7 @@ export class CodexAppServerReplayJsonParseError extends Schema.TaggedErrorClass<
{
scenario: Schema.String,
line: Schema.String,
cause: Schema.Defect,
cause: Schema.Defect(),
},
) {
override get message(): string {