Map Codex turns into orchestration v2

- Add Codex adapter and replay harness wiring
- Introduce in-memory orchestration projections and provider registry
- Expand orchestration contracts for turn and runtime events
This commit is contained in:
Julius Marminge authored and maria-rcks committed 2026-08-03 11:44:56 -04:00
1 parent e124f3b462
commit 8a6d895830
23 files changed
+1706 -525

No files matched your search

@@ -0,0 +1,62 @@
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import * as CodexReplay from "effect-codex-app-server/replay";
import { Effect, Layer, Schema } from "effect";
import { ProviderAdapterRegistryV2FromSingleAdapterLayer } from "../Layers/ProviderAdapterRegistryStatic.ts";
import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
import { CodexAdapterV2LiveLayer } from "./CodexAdapterV2.ts";
export class CodexReplayTranscriptDecodeError extends Schema.TaggedErrorClass<CodexReplayTranscriptDecodeError>()(
"CodexReplayTranscriptDecodeError",
{
provider: Schema.optional(Schema.String),
protocol: Schema.optional(Schema.String),
scenario: Schema.optional(Schema.String),
cause: Schema.Defect,
},
) {
override get message(): string {
return `Failed to decode Codex app-server replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
}
}
export const CodexOrchestratorReplayHarnessError = Schema.Union([
CodexReplayTranscriptDecodeError,
CodexReplay.CodexAppServerReplayError,
]);
export type CodexOrchestratorReplayHarnessError = typeof CodexOrchestratorReplayHarnessError.Type;
function metadataFromTranscript(transcript: ProviderReplayTranscript): {
readonly provider?: string;
readonly protocol?: string;
readonly scenario?: string;
} {
return {
provider: transcript.provider,
protocol: transcript.protocol,
scenario: transcript.scenario,
};
}
export const CodexOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
CodexReplay.CodexAppServerReplayTranscript,
CodexOrchestratorReplayHarnessError
> = {
provider: "codex",
decodeTranscript: (transcript) =>
Schema.decodeUnknownEffect(CodexReplay.CodexAppServerReplayTranscript)(transcript).pipe(
Effect.mapError(
(cause) =>
new CodexReplayTranscriptDecodeError({
...metadataFromTranscript(transcript),
cause,
}),
),
),
makeProviderAdapterRegistryLayer: (transcript) => {
const replayLayer = CodexReplay.layerReplay(transcript);
const adapterLayer = CodexAdapterV2LiveLayer.pipe(Layer.provide(replayLayer));
return ProviderAdapterRegistryV2FromSingleAdapterLayer.pipe(Layer.provide(adapterLayer));
},
};
@@ -0,0 +1,232 @@
import type {
OrchestrationV2ProviderCapabilities,
OrchestrationV2ProviderThread,
ProviderThreadId,
} from "@t3tools/contracts";
import { ProviderThreadId as ProviderThreadIdSchema } from "@t3tools/contracts";
import * as CodexClient from "effect-codex-app-server/client";
import * as CodexError from "effect-codex-app-server/errors";
import { DateTime, Effect, Layer, Stream } from "effect";
import {
ProviderAdapterEnsureThreadError,
ProviderAdapterInterruptError,
ProviderAdapterProtocolError,
ProviderAdapterResumeThreadError,
ProviderAdapterRuntimeRequestResponseError,
ProviderAdapterSteerRunUnsupportedError,
ProviderAdapterTurnStartError,
ProviderAdapterV2,
type ProviderAdapterV2Shape,
} from "../Services/ProviderAdapter.ts";
const CODEX_PROVIDER = "codex" as const;
export const CodexProviderCapabilitiesV2 = {
sessions: {
supportsMultipleProviderThreadsPerSession: true,
supportsModelSwitchInSession: true,
supportsProviderSwitchingViaHandoff: true,
supportsRuntimeModeSwitchInSession: true,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: true,
canReadThreadSnapshot: true,
canRollbackThread: true,
canForkThread: true,
canForkFromTurn: true,
canForkFromSubagentThread: true,
exposesNativeThreadId: true,
},
turns: {
exposesNativeTurnId: true,
emitsTurnStarted: true,
emitsTurnCompleted: true,
supportsInterrupt: true,
supportsActiveSteering: true,
supportsSteeringByInterruptRestart: true,
supportsQueuedMessages: true,
terminalStatusQuality: "strong",
},
streaming: {
streamsAssistantText: true,
streamsReasoning: true,
streamsToolOutput: true,
streamsPlanText: true,
emitsMessageCompleted: true,
},
tools: {
exposesToolItemIds: true,
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: true,
supportsDynamicToolCallbacks: true,
},
approvals: {
supportsCommandApproval: true,
supportsFileReadApproval: true,
supportsFileChangeApproval: true,
supportsApplyPatchApproval: true,
approvalsHaveNativeRequestIds: true,
approvalCallbacksAreLiveOnly: true,
approvalsCanOriginateFromSubagents: true,
},
planning: {
emitsPlanUpdated: true,
emitsTodoList: true,
emitsProposedPlan: true,
supportsStructuredQuestions: true,
planDeltasHaveItemIds: true,
},
subagents: {
supportsSubagents: true,
exposesSubagentThreadIds: true,
emitsSubagentLifecycle: true,
canWaitForSubagents: true,
canCloseSubagents: true,
canForkSubagentThread: true,
},
context: {
acceptsSystemContext: true,
acceptsDeveloperContext: true,
acceptsSyntheticUserContext: true,
canGenerateSummaries: true,
canConsumeHandoffSummaries: true,
supportsDeltaHandoff: true,
supportsFullThreadHandoff: true,
maxRecommendedHandoffChars: null,
},
checkpointing: {
appCanCheckpointFilesystem: true,
supportsNestedCheckpointScopes: true,
providerCanRollbackConversation: true,
providerRollbackReturnsSnapshot: true,
providerCanReadConversationSnapshot: true,
},
identity: {
nativeThreadIds: "strong",
nativeTurnIds: "strong",
nativeItemIds: "strong",
nativeRequestIds: "strong",
},
} satisfies OrchestrationV2ProviderCapabilities;
function providerThreadId(nativeThreadId: string): ProviderThreadId {
return ProviderThreadIdSchema.make(`codex:${nativeThreadId}`);
}
function toProtocolError(detail: string, payload?: unknown): ProviderAdapterProtocolError {
return new ProviderAdapterProtocolError({
provider: CODEX_PROVIDER,
detail,
...(payload === undefined ? {} : { payload }),
});
}
function normalizeCodexCause(error: CodexError.CodexAppServerError): unknown {
return error;
}
function codexTimestamp(seconds: number | null | undefined): DateTime.Utc {
return seconds === null || seconds === undefined
? DateTime.nowUnsafe()
: DateTime.fromDateUnsafe(new Date(seconds * 1000));
}
export const CodexAdapterV2LiveLayer: Layer.Layer<
ProviderAdapterV2,
never,
CodexClient.CodexAppServerClient
> = Layer.effect(
ProviderAdapterV2,
Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;
const adapter: ProviderAdapterV2Shape = {
provider: CODEX_PROVIDER,
getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
ensureThread: (input) =>
client.request("thread/start", {}).pipe(
Effect.map((response): OrchestrationV2ProviderThread => {
const nativeThreadId = response.thread.id;
return {
id: providerThreadId(nativeThreadId),
provider: CODEX_PROVIDER,
providerSessionId: input.providerSessionId ?? null,
appThreadId: input.threadId,
ownerNodeId: null,
nativeThreadRef: {
provider: CODEX_PROVIDER,
nativeId: nativeThreadId,
strength: "strong",
},
status: "idle",
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: null,
createdAt: codexTimestamp(response.thread.createdAt),
updatedAt: codexTimestamp(response.thread.updatedAt),
};
}),
Effect.mapError(
(cause) =>
new ProviderAdapterEnsureThreadError({
provider: CODEX_PROVIDER,
threadId: input.threadId,
cause: normalizeCodexCause(cause),
}),
),
),
resumeThread: (input) =>
Effect.fail(
new ProviderAdapterResumeThreadError({
provider: CODEX_PROVIDER,
providerSessionId: input.providerSessionId,
providerThreadId: input.providerThreadId,
cause: toProtocolError("Codex resumeThread adapter mapping is not implemented yet"),
}),
),
startTurn: (input) =>
Stream.fail(
new ProviderAdapterTurnStartError({
provider: CODEX_PROVIDER,
threadId: input.threadId,
providerThreadId: input.providerThread.id,
runId: input.runId,
cause: toProtocolError("Codex startTurn adapter mapping is not implemented yet"),
}),
),
steerTurn: (input) =>
Stream.fail(
new ProviderAdapterSteerRunUnsupportedError({
provider: CODEX_PROVIDER,
providerThreadId: input.providerThread.id,
}),
),
interruptTurn: (input) =>
Effect.fail(
new ProviderAdapterInterruptError({
provider: CODEX_PROVIDER,
providerThreadId: input.providerThread.id,
providerTurnId: input.providerTurnId,
cause: toProtocolError("Codex interruptTurn adapter mapping is not implemented yet"),
}),
),
respondToRuntimeRequest: (input) =>
Effect.fail(
new ProviderAdapterRuntimeRequestResponseError({
provider: CODEX_PROVIDER,
requestId: input.requestId,
cause: toProtocolError(
"Codex runtime request response adapter mapping is not implemented yet",
),
}),
),
};
return ProviderAdapterV2.of(adapter);
}),
);
@@ -0,0 +1,485 @@
import {
EventId,
NodeId,
OrchestrationV2Command,
type OrchestrationV2ConversationMessage,
type OrchestrationV2DomainEvent,
type OrchestrationV2ExecutionNode,
type OrchestrationV2Run,
type OrchestrationV2RunAttempt,
type OrchestrationV2ThreadProjection,
type OrchestrationV2TurnItem,
RunAttemptId,
RunId,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import { DateTime, Effect, Layer, Ref, Stream } from "effect";
import {
OrchestratorDispatchError,
OrchestratorProjectionError,
OrchestratorProviderAdapterError,
OrchestratorV2,
type OrchestratorV2Shape,
} from "../Services/Orchestrator.ts";
import type { ProviderAdapterV2Event } from "../Services/ProviderAdapter.ts";
import { ProviderAdapterRegistryV2 } from "../Services/ProviderAdapterRegistry.ts";
import { ProjectionStoreV2 } from "../Services/ProjectionStore.ts";
import { ProjectionStoreV2MemoryLayer } from "./ProjectionStoreMemory.ts";
function entityKey(threadId: ThreadId): string {
const raw = String(threadId);
return raw.startsWith("thread:") ? raw.slice("thread:".length) : raw;
}
function runIdFor(threadId: ThreadId, ordinal: number): RunId {
return RunId.make(`run:${entityKey(threadId)}:${ordinal}`);
}
function runAttemptIdFor(threadId: ThreadId, ordinal: number): RunAttemptId {
return RunAttemptId.make(`run-attempt:${entityKey(threadId)}:${ordinal}:1`);
}
function rootNodeIdFor(threadId: ThreadId, ordinal: number): NodeId {
return NodeId.make(`node:${entityKey(threadId)}:${ordinal}:root`);
}
function userTurnItemIdFor(command: Extract<OrchestrationV2Command, { type: "message.dispatch" }>) {
return TurnItemId.make(`turn-item:user:${command.messageId}`);
}
function nextRunOrdinal(projection: OrchestrationV2ThreadProjection): number {
return projection.runs.length + 1;
}
function adapterEventToDomainEvent(input: {
readonly event: ProviderAdapterV2Event;
readonly threadId: ThreadId;
readonly runId?: RunId;
readonly nodeId?: NodeId;
readonly occurredAt: DateTime.Utc;
}): Omit<OrchestrationV2DomainEvent, "id"> | null {
switch (input.event.type) {
case "provider_thread.updated":
return {
type: "provider-thread.updated",
threadId: input.threadId,
provider: input.event.provider,
occurredAt: input.occurredAt,
payload: input.event.providerThread,
};
case "provider_turn.updated":
return {
type: "provider-turn.updated",
threadId: input.threadId,
runId: input.runId,
nodeId: input.nodeId,
provider: input.event.provider,
occurredAt: input.occurredAt,
payload: input.event.providerTurn,
};
case "message.updated":
return {
type: "message.updated",
threadId: input.threadId,
runId: input.event.message.runId ?? undefined,
nodeId: input.event.message.nodeId ?? undefined,
provider: input.event.provider,
occurredAt: input.occurredAt,
payload: input.event.message,
};
case "turn_item.updated":
return {
type: "turn-item.updated",
threadId: input.threadId,
runId: input.event.turnItem.runId ?? undefined,
nodeId: input.event.turnItem.nodeId ?? undefined,
provider: input.event.provider,
occurredAt: input.occurredAt,
payload: input.event.turnItem,
};
case "runtime_item.updated":
return {
type: "runtime-item.updated",
threadId: input.threadId,
runId: input.runId,
nodeId: input.event.runtimeItem.nodeId,
provider: input.event.provider,
occurredAt: input.occurredAt,
payload: input.event.runtimeItem,
};
case "runtime_request.updated":
return {
type: "runtime-request.updated",
threadId: input.threadId,
runId: input.runId,
nodeId: input.event.runtimeRequest.nodeId,
provider: input.event.provider,
occurredAt: input.occurredAt,
payload: input.event.runtimeRequest,
};
case "plan.updated":
return {
type: "plan.updated",
threadId: input.threadId,
runId: input.event.plan.runId ?? undefined,
nodeId: input.event.plan.nodeId,
provider: input.event.provider,
occurredAt: input.occurredAt,
payload: input.event.plan,
};
case "turn.terminal":
return null;
}
}
export const OrchestratorV2LiveLayer: Layer.Layer<
OrchestratorV2,
never,
ProviderAdapterRegistryV2
> = Layer.effect(
OrchestratorV2,
Effect.gen(function* () {
const projectionStore = yield* ProjectionStoreV2;
const adapterRegistry = yield* ProviderAdapterRegistryV2;
const eventSequence = yield* Ref.make(0);
const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
Effect.gen(function* () {
const sequence = yield* Ref.updateAndGet(eventSequence, (current) => current + 1);
return {
...event,
id: EventId.make(`event:${sequence}`),
} as Event;
});
const emit =
(events: Ref.Ref<Array<OrchestrationV2DomainEvent>>, command: OrchestrationV2Command) =>
<Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
Effect.gen(function* () {
const withId = yield* makeEvent(event);
yield* projectionStore.apply(withId).pipe(
Effect.mapError(
() =>
new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
}),
),
);
yield* Ref.update(events, (existing) => [...existing, withId]);
return withId;
});
const dispatchThreadCreate = (
command: Extract<OrchestrationV2Command, { readonly type: "thread.create" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
) =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const emitEvent = emit(events, command);
const adapter = yield* adapterRegistry.get(command.modelSelection.provider).pipe(
Effect.mapError(
(cause) =>
new OrchestratorProviderAdapterError({
commandId: command.commandId,
provider: command.modelSelection.provider,
cause,
}),
),
);
const providerThread = yield* adapter
.ensureThread({
threadId: command.threadId,
modelSelection: command.modelSelection,
runtimePolicy: {
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
cwd: command.worktreePath,
},
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestratorProviderAdapterError({
commandId: command.commandId,
provider: command.modelSelection.provider,
cause,
}),
),
);
yield* emitEvent({
type: "thread.created",
threadId: command.threadId,
provider: command.modelSelection.provider,
occurredAt: now,
payload: {
id: command.threadId,
projectId: command.projectId,
title: command.title,
defaultProvider: command.modelSelection.provider,
modelSelection: command.modelSelection,
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
branch: command.branch,
worktreePath: command.worktreePath,
activeProviderThreadId: providerThread.id,
forkedFrom: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
deletedAt: null,
},
});
yield* emitEvent({
type: "provider-thread.updated",
threadId: command.threadId,
provider: command.modelSelection.provider,
occurredAt: now,
payload: providerThread,
});
});
const dispatchMessage = (
command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
) =>
Effect.gen(function* () {
const projection = yield* projectionStore
.getThreadProjection(command.threadId)
.pipe(
Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })),
);
const modelSelection = command.modelSelection ?? projection.thread.modelSelection;
const adapter = yield* adapterRegistry.get(modelSelection.provider).pipe(
Effect.mapError(
(cause) =>
new OrchestratorProviderAdapterError({
commandId: command.commandId,
provider: modelSelection.provider,
cause,
}),
),
);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === projection.thread.activeProviderThreadId,
);
if (!providerThread) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
});
}
const now = yield* DateTime.now;
const ordinal = nextRunOrdinal(projection);
const runId = runIdFor(command.threadId, ordinal);
const attemptId = runAttemptIdFor(command.threadId, ordinal);
const rootNodeId = rootNodeIdFor(command.threadId, ordinal);
const emitEvent = emit(events, command);
const run: OrchestrationV2Run = {
id: runId,
threadId: command.threadId,
ordinal,
provider: modelSelection.provider,
providerThreadId: providerThread.id,
userMessageId: command.messageId,
rootNodeId,
activeAttemptId: attemptId,
status: "running",
requestedAt: now,
startedAt: now,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
};
const attempt: OrchestrationV2RunAttempt = {
id: attemptId,
runId,
attemptOrdinal: 1,
rootNodeId,
provider: modelSelection.provider,
providerThreadId: providerThread.id,
providerTurnId: null,
reason: "initial",
status: "running",
startedAt: now,
completedAt: null,
};
const rootNode: OrchestrationV2ExecutionNode = {
id: rootNodeId,
threadId: command.threadId,
runId,
parentNodeId: null,
rootNodeId,
kind: "root_turn",
status: "running",
countsForRun: true,
providerThreadId: providerThread.id,
providerTurnId: null,
runtimeItemId: null,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: now,
completedAt: null,
};
const message: OrchestrationV2ConversationMessage = {
id: command.messageId,
threadId: command.threadId,
runId,
nodeId: rootNodeId,
role: "user",
text: command.text,
attachments: command.attachments,
streaming: false,
createdAt: now,
updatedAt: now,
};
const turnItem: OrchestrationV2TurnItem = {
id: userTurnItemIdFor(command),
threadId: command.threadId,
runId,
nodeId: rootNodeId,
providerThreadId: providerThread.id,
providerTurnId: null,
runtimeItemId: null,
parentItemId: null,
ordinal: (ordinal - 1) * 100,
status: "completed",
title: null,
startedAt: now,
completedAt: now,
updatedAt: now,
type: "user_message",
messageId: command.messageId,
text: command.text,
attachments: command.attachments,
};
yield* emitEvent({
type: "run.created",
threadId: command.threadId,
runId,
nodeId: rootNodeId,
provider: modelSelection.provider,
occurredAt: now,
payload: run,
});
yield* emitEvent({
type: "run-attempt.created",
threadId: command.threadId,
runId,
nodeId: rootNodeId,
provider: modelSelection.provider,
occurredAt: now,
payload: attempt,
});
yield* emitEvent({
type: "node.updated",
threadId: command.threadId,
runId,
nodeId: rootNodeId,
provider: modelSelection.provider,
occurredAt: now,
payload: rootNode,
});
yield* emitEvent({
type: "message.updated",
threadId: command.threadId,
runId,
nodeId: rootNodeId,
provider: modelSelection.provider,
occurredAt: now,
payload: message,
});
yield* emitEvent({
type: "turn-item.updated",
threadId: command.threadId,
runId,
nodeId: rootNodeId,
provider: modelSelection.provider,
occurredAt: now,
payload: turnItem,
});
const adapterEvents = yield* adapter
.startTurn({
threadId: command.threadId,
runId,
attemptId,
rootNodeId,
providerThread,
message: {
messageId: command.messageId,
text: command.text,
},
modelSelection,
runtimePolicy: {
runtimeMode: projection.thread.runtimeMode,
interactionMode: projection.thread.interactionMode,
cwd: projection.thread.worktreePath,
},
})
.pipe(
Stream.runCollect,
Effect.mapError(
(cause) =>
new OrchestratorProviderAdapterError({
commandId: command.commandId,
provider: modelSelection.provider,
cause,
}),
),
);
for (const adapterEvent of adapterEvents) {
const occurredAt = yield* DateTime.now;
const domainEvent = adapterEventToDomainEvent({
event: adapterEvent,
threadId: command.threadId,
runId,
nodeId: rootNodeId,
occurredAt,
});
if (domainEvent) {
yield* emitEvent(domainEvent);
}
}
});
const dispatchUnsupported = (command: OrchestrationV2Command) =>
Effect.fail(
new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
}),
);
const service: OrchestratorV2Shape = {
dispatch: (command) =>
Effect.gen(function* () {
const events = yield* Ref.make<Array<OrchestrationV2DomainEvent>>([]);
switch (command.type) {
case "thread.create":
yield* dispatchThreadCreate(command, events);
break;
case "message.dispatch":
yield* dispatchMessage(command, events);
break;
default:
return yield* dispatchUnsupported(command);
}
return yield* Ref.get(events);
}),
getThreadProjection: (threadId) =>
projectionStore
.getThreadProjection(threadId)
.pipe(Effect.mapError(() => new OrchestratorProjectionError({ threadId }))),
streamDomainEvents: Stream.empty,
};
return service;
}).pipe(Effect.provide(ProjectionStoreV2MemoryLayer)),
);
@@ -0,0 +1,177 @@
import type {
OrchestrationV2DomainEvent,
OrchestrationV2ThreadProjection,
ThreadId,
} from "@t3tools/contracts";
import { Effect, Layer, Ref } from "effect";
import {
ProjectionStoreThreadNotFoundError,
ProjectionStoreV2,
type ProjectionStoreV2Shape,
} from "../Services/ProjectionStore.ts";
function upsertById<T extends { readonly id: string }>(items: ReadonlyArray<T>, next: T): Array<T> {
const index = items.findIndex((item) => item.id === next.id);
if (index === -1) {
return [...items, next];
}
const updated = [...items];
updated[index] = next;
return updated;
}
function emptyProjection(
event: Extract<OrchestrationV2DomainEvent, { readonly type: "thread.created" }>,
): OrchestrationV2ThreadProjection {
return {
thread: event.payload,
runs: [],
attempts: [],
nodes: [],
providerSessions: [],
providerThreads: [],
providerTurns: [],
runtimeItems: [],
runtimeRequests: [],
messages: [],
plans: [],
turnItems: [],
checkpointScopes: [],
checkpoints: [],
contextHandoffs: [],
updatedAt: event.occurredAt,
};
}
function applyToProjection(
projection: OrchestrationV2ThreadProjection,
event: OrchestrationV2DomainEvent,
): OrchestrationV2ThreadProjection {
const base = {
...projection,
updatedAt: event.occurredAt,
};
switch (event.type) {
case "thread.created":
return {
...base,
thread: event.payload,
};
case "run.created":
case "run.updated":
return {
...base,
runs: upsertById(base.runs, event.payload),
};
case "run-attempt.created":
return {
...base,
attempts: upsertById(base.attempts, event.payload),
};
case "node.updated":
return {
...base,
nodes: upsertById(base.nodes, event.payload),
};
case "provider-thread.updated":
return {
...base,
providerThreads: upsertById(base.providerThreads, event.payload),
};
case "provider-turn.updated":
return {
...base,
providerTurns: upsertById(base.providerTurns, event.payload),
};
case "runtime-item.updated":
return {
...base,
runtimeItems: upsertById(base.runtimeItems, event.payload),
};
case "runtime-request.updated":
return {
...base,
runtimeRequests: upsertById(base.runtimeRequests, event.payload),
};
case "message.updated":
return {
...base,
messages: upsertById(base.messages, event.payload),
};
case "turn-item.updated":
return {
...base,
turnItems: upsertById(base.turnItems, event.payload),
};
case "plan.updated":
return {
...base,
plans: upsertById(base.plans, event.payload),
};
case "checkpoint-scope.created":
return {
...base,
checkpointScopes: upsertById(base.checkpointScopes, event.payload),
};
case "checkpoint.captured":
return {
...base,
checkpoints: upsertById(base.checkpoints, event.payload),
};
case "context-handoff.updated":
return {
...base,
contextHandoffs: upsertById(base.contextHandoffs, event.payload),
};
}
}
export const ProjectionStoreV2MemoryLayer: Layer.Layer<ProjectionStoreV2> = Layer.effect(
ProjectionStoreV2,
Effect.gen(function* () {
const projections = yield* Ref.make(new Map<ThreadId, OrchestrationV2ThreadProjection>());
const service: ProjectionStoreV2Shape = {
apply: (event) =>
Effect.gen(function* () {
const result = yield* Ref.modify(projections, (existing) => {
const next = new Map(existing);
if (event.type === "thread.created" && !next.has(event.threadId)) {
next.set(event.threadId, emptyProjection(event));
return [undefined, next] as const;
}
const projection = next.get(event.threadId);
if (!projection) {
return [
new ProjectionStoreThreadNotFoundError({ threadId: event.threadId }),
existing,
] as const;
}
next.set(event.threadId, applyToProjection(projection, event));
return [undefined, next] as const;
});
if (result) {
return yield* result;
}
}),
getThreadProjection: (threadId) =>
Effect.gen(function* () {
const existing = yield* Ref.get(projections);
const projection = existing.get(threadId);
if (!projection) {
return yield* new ProjectionStoreThreadNotFoundError({ threadId });
}
return projection;
}),
};
return service;
}),
);
@@ -0,0 +1,52 @@
import type { ProviderKind } from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { ProviderAdapterV2, type ProviderAdapterV2Shape } from "../Services/ProviderAdapter.ts";
import {
ProviderAdapterRegistryLookupError,
ProviderAdapterRegistryV2,
type ProviderAdapterRegistryV2Shape,
} from "../Services/ProviderAdapterRegistry.ts";
export function makeProviderAdapterRegistryV2Layer(
adapters: ReadonlyArray<ProviderAdapterV2Shape>,
): Layer.Layer<ProviderAdapterRegistryV2> {
return Layer.succeed(
ProviderAdapterRegistryV2,
ProviderAdapterRegistryV2.of({
get: (provider) =>
Effect.gen(function* () {
const adapter = adapters.find((candidate) => candidate.provider === provider);
if (!adapter) {
return yield* new ProviderAdapterRegistryLookupError({ provider });
}
return adapter;
}),
list: () => Effect.succeed(adapters.map((adapter) => adapter.provider as ProviderKind)),
} satisfies ProviderAdapterRegistryV2Shape),
);
}
export function makeSingleProviderAdapterRegistryV2Layer(
adapter: ProviderAdapterV2Shape,
): Layer.Layer<ProviderAdapterRegistryV2> {
return makeProviderAdapterRegistryV2Layer([adapter]);
}
export const ProviderAdapterRegistryV2FromSingleAdapterLayer: Layer.Layer<
ProviderAdapterRegistryV2,
never,
ProviderAdapterV2
> = Layer.effect(
ProviderAdapterRegistryV2,
Effect.gen(function* () {
const adapter = yield* ProviderAdapterV2;
return ProviderAdapterRegistryV2.of({
get: (provider) =>
adapter.provider === provider
? Effect.succeed(adapter)
: Effect.fail(new ProviderAdapterRegistryLookupError({ provider })),
list: () => Effect.succeed([adapter.provider]),
} satisfies ProviderAdapterRegistryV2Shape);
}),
);
@@ -44,10 +44,24 @@ export class OrchestratorDomainEventStreamError extends Schema.TaggedErrorClass<
}
}
export class OrchestratorProviderAdapterError extends Schema.TaggedErrorClass<OrchestratorProviderAdapterError>()(
"OrchestratorProviderAdapterError",
{
commandId: CommandId,
provider: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Provider adapter failed while dispatching orchestration command ${this.commandId}.`;
}
}
export const OrchestratorV2Error = Schema.Union([
OrchestratorDispatchError,
OrchestratorProjectionError,
OrchestratorDomainEventStreamError,
OrchestratorProviderAdapterError,
]);
export type OrchestratorV2Error = typeof OrchestratorV2Error.Type;
@@ -1,16 +1,91 @@
import {
MessageId,
ModelSelection,
NodeId,
OrchestrationV2ConversationMessage,
OrchestrationV2PlanArtifact,
OrchestrationV2ProviderCapabilities,
OrchestrationV2ProviderThread,
OrchestrationV2ProviderTurn,
OrchestrationV2RawProviderEvent,
OrchestrationV2RuntimeItem,
OrchestrationV2RuntimeRequest,
OrchestrationV2TurnItem,
ProviderApprovalDecision,
ProviderInteractionMode,
ProviderKind,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
RuntimeMode,
RuntimeRequestId,
RunAttemptId,
RunId,
ThreadId,
} from "@t3tools/contracts";
import { Context, Schema } from "effect";
import type { Effect, Stream } from "effect";
export const ProviderAdapterV2RuntimePolicy = Schema.Struct({
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
cwd: Schema.NullOr(Schema.String),
approvalPolicy: Schema.optional(Schema.Unknown),
sandboxPolicy: Schema.optional(Schema.Unknown),
reasoningEffort: Schema.optional(Schema.String),
});
export type ProviderAdapterV2RuntimePolicy = typeof ProviderAdapterV2RuntimePolicy.Type;
export const ProviderAdapterV2TurnMessage = Schema.Struct({
messageId: MessageId,
text: Schema.String,
});
export type ProviderAdapterV2TurnMessage = typeof ProviderAdapterV2TurnMessage.Type;
export const ProviderAdapterV2Event = Schema.Union([
Schema.Struct({
type: Schema.Literal("provider_thread.updated"),
provider: ProviderKind,
providerThread: OrchestrationV2ProviderThread,
}),
Schema.Struct({
type: Schema.Literal("provider_turn.updated"),
provider: ProviderKind,
providerTurn: OrchestrationV2ProviderTurn,
}),
Schema.Struct({
type: Schema.Literal("message.updated"),
provider: ProviderKind,
message: OrchestrationV2ConversationMessage,
}),
Schema.Struct({
type: Schema.Literal("turn_item.updated"),
provider: ProviderKind,
turnItem: OrchestrationV2TurnItem,
}),
Schema.Struct({
type: Schema.Literal("runtime_item.updated"),
provider: ProviderKind,
runtimeItem: OrchestrationV2RuntimeItem,
}),
Schema.Struct({
type: Schema.Literal("runtime_request.updated"),
provider: ProviderKind,
runtimeRequest: OrchestrationV2RuntimeRequest,
}),
Schema.Struct({
type: Schema.Literal("plan.updated"),
provider: ProviderKind,
plan: OrchestrationV2PlanArtifact,
}),
Schema.Struct({
type: Schema.Literal("turn.terminal"),
provider: ProviderKind,
providerTurnId: ProviderTurnId,
status: Schema.Literals(["completed", "interrupted", "failed", "cancelled"]),
}),
]);
export type ProviderAdapterV2Event = typeof ProviderAdapterV2Event.Type;
export class ProviderAdapterCapabilitiesError extends Schema.TaggedErrorClass<ProviderAdapterCapabilitiesError>()(
"ProviderAdapterCapabilitiesError",
{
@@ -41,26 +116,27 @@ export class ProviderAdapterEnsureThreadError extends Schema.TaggedErrorClass<Pr
"ProviderAdapterEnsureThreadError",
{
provider: ProviderKind,
providerSessionId: ProviderSessionId,
nativeThreadRef: Schema.optional(Schema.Unknown),
threadId: ThreadId,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Failed to ensure ${this.provider} provider thread.`;
return `Failed to ensure ${this.provider} provider thread for app thread ${this.threadId}.`;
}
}
export class ProviderAdapterSendRunError extends Schema.TaggedErrorClass<ProviderAdapterSendRunError>()(
"ProviderAdapterSendRunError",
export class ProviderAdapterTurnStartError extends Schema.TaggedErrorClass<ProviderAdapterTurnStartError>()(
"ProviderAdapterTurnStartError",
{
provider: ProviderKind,
threadId: ThreadId,
providerThreadId: ProviderThreadId,
runId: RunId,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Failed to send run to ${this.provider} provider thread ${this.providerThreadId}.`;
return `Failed to start run ${this.runId} on ${this.provider} provider thread ${this.providerThreadId}.`;
}
}
@@ -81,11 +157,12 @@ export class ProviderAdapterSteerRunError extends Schema.TaggedErrorClass<Provid
{
provider: ProviderKind,
providerThreadId: ProviderThreadId,
providerTurnId: ProviderTurnId,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Failed to steer active run on ${this.provider} provider thread ${this.providerThreadId}.`;
return `Failed to steer active run ${this.providerTurnId} on ${this.provider} provider thread ${this.providerThreadId}.`;
}
}
@@ -94,12 +171,12 @@ export class ProviderAdapterInterruptError extends Schema.TaggedErrorClass<Provi
{
provider: ProviderKind,
providerThreadId: ProviderThreadId,
providerTurnId: Schema.optional(Schema.String),
providerTurnId: ProviderTurnId,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Failed to interrupt ${this.provider} provider thread ${this.providerThreadId}.`;
return `Failed to interrupt ${this.provider} provider turn ${this.providerTurnId}.`;
}
}
@@ -116,15 +193,16 @@ export class ProviderAdapterRuntimeRequestResponseError extends Schema.TaggedErr
}
}
export class ProviderAdapterRawEventStreamError extends Schema.TaggedErrorClass<ProviderAdapterRawEventStreamError>()(
"ProviderAdapterRawEventStreamError",
export class ProviderAdapterProtocolError extends Schema.TaggedErrorClass<ProviderAdapterProtocolError>()(
"ProviderAdapterProtocolError",
{
provider: ProviderKind,
cause: Schema.optional(Schema.Defect),
detail: Schema.String,
payload: Schema.optional(Schema.Unknown),
},
) {
override get message(): string {
return `Failed while streaming raw ${this.provider} provider events.`;
return `${this.provider} provider protocol error: ${this.detail}.`;
}
}
@@ -132,23 +210,51 @@ export const ProviderAdapterV2Error = Schema.Union([
ProviderAdapterCapabilitiesError,
ProviderAdapterResumeThreadError,
ProviderAdapterEnsureThreadError,
ProviderAdapterSendRunError,
ProviderAdapterTurnStartError,
ProviderAdapterSteerRunUnsupportedError,
ProviderAdapterSteerRunError,
ProviderAdapterInterruptError,
ProviderAdapterRuntimeRequestResponseError,
ProviderAdapterRawEventStreamError,
ProviderAdapterProtocolError,
]);
export type ProviderAdapterV2Error = typeof ProviderAdapterV2Error.Type;
export interface ProviderAdapterV2SendRunInput {
readonly providerThreadId: ProviderThreadId;
readonly input: unknown;
export interface ProviderAdapterV2EnsureThreadInput {
readonly threadId: ThreadId;
readonly modelSelection: ModelSelection;
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
readonly providerSessionId?: ProviderSessionId;
readonly existingProviderThread?: OrchestrationV2ProviderThread;
}
export interface ProviderAdapterV2ResumeInput {
readonly providerSessionId: ProviderSessionId;
readonly providerThreadId: ProviderThreadId;
export interface ProviderAdapterV2TurnInput {
readonly threadId: ThreadId;
readonly runId: RunId;
readonly attemptId: RunAttemptId;
readonly rootNodeId: NodeId;
readonly providerThread: OrchestrationV2ProviderThread;
readonly message: ProviderAdapterV2TurnMessage;
readonly modelSelection: ModelSelection;
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
}
export interface ProviderAdapterV2SteerInput {
readonly threadId: ThreadId;
readonly runId: RunId;
readonly providerThread: OrchestrationV2ProviderThread;
readonly providerTurnId: ProviderTurnId;
readonly message: ProviderAdapterV2TurnMessage;
}
export interface ProviderAdapterV2InterruptInput {
readonly providerThread: OrchestrationV2ProviderThread;
readonly providerTurnId: ProviderTurnId;
}
export interface ProviderAdapterV2RuntimeRequestResponseInput {
readonly requestId: RuntimeRequestId;
readonly decision?: ProviderApprovalDecision;
readonly response?: unknown;
}
export interface ProviderAdapterV2Shape {
@@ -157,28 +263,25 @@ export interface ProviderAdapterV2Shape {
OrchestrationV2ProviderCapabilities,
ProviderAdapterV2Error
>;
readonly resumeThread: (
input: ProviderAdapterV2ResumeInput,
readonly ensureThread: (
input: ProviderAdapterV2EnsureThreadInput,
) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
readonly ensureThread: (input: {
readonly resumeThread: (input: {
readonly providerSessionId: ProviderSessionId;
readonly nativeThreadRef?: unknown;
}) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
readonly sendRun: (
input: ProviderAdapterV2SendRunInput,
) => Effect.Effect<OrchestrationV2ProviderTurn, ProviderAdapterV2Error>;
readonly steerRun: (
input: ProviderAdapterV2SendRunInput,
) => Effect.Effect<OrchestrationV2ProviderTurn, ProviderAdapterV2Error>;
readonly interrupt: (input: {
readonly providerThreadId: ProviderThreadId;
readonly providerTurnId?: string;
}) => Effect.Effect<void, ProviderAdapterV2Error>;
readonly respondToRequest: (input: {
readonly requestId: RuntimeRequestId;
readonly response: unknown;
}) => Effect.Effect<void, ProviderAdapterV2Error>;
readonly streamRawEvents: Stream.Stream<OrchestrationV2RawProviderEvent, ProviderAdapterV2Error>;
}) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
readonly startTurn: (
input: ProviderAdapterV2TurnInput,
) => Stream.Stream<ProviderAdapterV2Event, ProviderAdapterV2Error>;
readonly steerTurn: (
input: ProviderAdapterV2SteerInput,
) => Stream.Stream<ProviderAdapterV2Event, ProviderAdapterV2Error>;
readonly interruptTurn: (
input: ProviderAdapterV2InterruptInput,
) => Effect.Effect<void, ProviderAdapterV2Error>;
readonly respondToRuntimeRequest: (
input: ProviderAdapterV2RuntimeRequestResponseInput,
) => Effect.Effect<void, ProviderAdapterV2Error>;
}
export class ProviderAdapterV2 extends Context.Service<ProviderAdapterV2, ProviderAdapterV2Shape>()(
@@ -0,0 +1,31 @@
import { ProviderKind } from "@t3tools/contracts";
import { Context, Schema } from "effect";
import type { Effect } from "effect";
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
export class ProviderAdapterRegistryLookupError extends Schema.TaggedErrorClass<ProviderAdapterRegistryLookupError>()(
"ProviderAdapterRegistryLookupError",
{
provider: ProviderKind,
},
) {
override get message(): string {
return `No orchestration provider adapter is registered for ${this.provider}.`;
}
}
export const ProviderAdapterRegistryV2Error = Schema.Union([ProviderAdapterRegistryLookupError]);
export type ProviderAdapterRegistryV2Error = typeof ProviderAdapterRegistryV2Error.Type;
export interface ProviderAdapterRegistryV2Shape {
readonly get: (
provider: ProviderKind,
) => Effect.Effect<ProviderAdapterV2Shape, ProviderAdapterRegistryV2Error>;
readonly list: () => Effect.Effect<ReadonlyArray<ProviderKind>>;
}
export class ProviderAdapterRegistryV2 extends Context.Service<
ProviderAdapterRegistryV2,
ProviderAdapterRegistryV2Shape
>()("t3/orchestration-v2/Services/ProviderAdapterRegistry") {}
@@ -1,95 +0,0 @@
import type { ProviderReplayEntry } from "@t3tools/contracts";
import { Context, Schema } from "effect";
import type { Effect } from "effect";
export type ProviderRuntimeInbound =
| { readonly type: "frame"; readonly frame: unknown }
| Extract<ProviderReplayEntry, { readonly type: "runtime_exit" }>;
export class ProviderRuntimeTranscriptExhaustedError extends Schema.TaggedErrorClass<ProviderRuntimeTranscriptExhaustedError>()(
"ProviderRuntimeTranscriptExhaustedError",
{
scenario: Schema.String,
direction: Schema.Literals(["outbound", "inbound"]),
frame: Schema.optional(Schema.Unknown),
},
) {
override get message(): string {
return `Replay transcript '${this.scenario}' is exhausted before ${this.direction} frame.`;
}
}
export class ProviderRuntimeUnexpectedOutboundError extends Schema.TaggedErrorClass<ProviderRuntimeUnexpectedOutboundError>()(
"ProviderRuntimeUnexpectedOutboundError",
{
scenario: Schema.String,
index: Schema.Number,
expectedEntry: Schema.optional(Schema.Unknown),
actualFrame: Schema.Unknown,
},
) {
override get message(): string {
return `Replay transcript '${this.scenario}' expected inbound data at index ${this.index}, but transport sent an outbound frame.`;
}
}
export class ProviderRuntimeUnexpectedInboundPullError extends Schema.TaggedErrorClass<ProviderRuntimeUnexpectedInboundPullError>()(
"ProviderRuntimeUnexpectedInboundPullError",
{
scenario: Schema.String,
index: Schema.Number,
expectedFrame: Schema.optional(Schema.Unknown),
},
) {
override get message(): string {
return `Replay transcript '${this.scenario}' expected outbound frame at index ${this.index}, but transport was pulled for inbound data.`;
}
}
export class ProviderRuntimeOutboundMismatchError extends Schema.TaggedErrorClass<ProviderRuntimeOutboundMismatchError>()(
"ProviderRuntimeOutboundMismatchError",
{
scenario: Schema.String,
index: Schema.Number,
expectedFrame: Schema.Unknown,
actualFrame: Schema.Unknown,
},
) {
override get message(): string {
return `Replay transcript '${this.scenario}' outbound frame mismatch at index ${this.index}.`;
}
}
export class ProviderRuntimeIncompleteTranscriptError extends Schema.TaggedErrorClass<ProviderRuntimeIncompleteTranscriptError>()(
"ProviderRuntimeIncompleteTranscriptError",
{
scenario: Schema.String,
index: Schema.Number,
total: Schema.Number,
nextEntry: Schema.optional(Schema.Unknown),
},
) {
override get message(): string {
return `Replay transcript '${this.scenario}' stopped at index ${this.index} of ${this.total}.`;
}
}
export const ProviderRuntimeTransportError = Schema.Union([
ProviderRuntimeTranscriptExhaustedError,
ProviderRuntimeUnexpectedOutboundError,
ProviderRuntimeUnexpectedInboundPullError,
ProviderRuntimeOutboundMismatchError,
ProviderRuntimeIncompleteTranscriptError,
]);
export type ProviderRuntimeTransportError = typeof ProviderRuntimeTransportError.Type;
export interface ProviderRuntimeTransportShape {
readonly send: (frame: unknown) => Effect.Effect<void, ProviderRuntimeTransportError>;
readonly receive: () => Effect.Effect<ProviderRuntimeInbound, ProviderRuntimeTransportError>;
readonly assertComplete: () => Effect.Effect<void, ProviderRuntimeTransportError>;
}
export class ProviderRuntimeTransport extends Context.Service<
ProviderRuntimeTransport,
ProviderRuntimeTransportShape
>()("t3/orchestration-v2/Services/ProviderRuntimeTransport") {}
@@ -1,111 +0,0 @@
import { ProviderReplayTranscript } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import { Effect, Fiber, Random, Schema } from "effect";
import { TestClock } from "effect/testing";
import { makeReplayProviderRuntime } from "./ReplayProviderRuntime.ts";
import {
ProviderRuntimeOutboundMismatchError,
ProviderRuntimeTransportError,
} from "../Services/ProviderRuntimeTransport.ts";
function makeDeterministicRandomService(seed = 0x1234_5678): {
nextIntUnsafe: () => number;
nextDoubleUnsafe: () => number;
} {
let state = seed >>> 0;
const nextIntUnsafe = (): number => {
state = (Math.imul(1_664_525, state) + 1_013_904_223) >>> 0;
return state;
};
return {
nextIntUnsafe,
nextDoubleUnsafe: () => nextIntUnsafe() / 0x1_0000_0000,
};
}
const transcript = Schema.decodeUnknownSync(ProviderReplayTranscript)({
provider: "codex",
protocol: "codex.app-server",
version: "0.120.0",
scenario: "replay-runtime-smoke",
entries: [
{
type: "expect_outbound",
frame: {
id: 1,
method: "initialize",
params: { capabilities: { experimentalApi: true } },
},
},
{
type: "emit_inbound",
afterMs: 25,
frame: {
id: 1,
result: { userAgent: "fixture" },
},
},
{
type: "runtime_exit",
status: "success",
},
],
});
describe("ReplayProviderRuntime", () => {
it.effect("asserts outbound frames and replays inbound frames deterministically", () =>
Effect.gen(function* () {
const runtime = yield* makeReplayProviderRuntime(transcript);
const generatedId = yield* Random.nextUUIDv4;
yield* runtime.send({
params: { capabilities: { experimentalApi: true } },
method: "initialize",
id: 1,
});
const inboundFiber = yield* runtime.receive().pipe(Effect.forkScoped);
yield* TestClock.adjust("25 millis");
const inbound = yield* Fiber.join(inboundFiber);
assert.deepEqual(inbound, {
type: "frame",
frame: {
id: 1,
result: { userAgent: "fixture" },
},
});
const exit = yield* runtime.receive();
assert.deepEqual(exit, { type: "runtime_exit", status: "success" });
yield* runtime.assertComplete();
assert.equal(generatedId, "776ac12c-9b3e-4520-bf52-8954a3a6cdc8");
}).pipe(
Effect.provide(TestClock.layer()),
Effect.provideService(Random.Random, makeDeterministicRandomService()),
),
);
it.effect("fails on outbound mismatch instead of skipping adapter behavior", () =>
Effect.gen(function* () {
const runtime = yield* makeReplayProviderRuntime(transcript);
const error = yield* runtime.send({ id: 1, method: "wrong", params: {} }).pipe(Effect.flip);
assert.instanceOf(error, ProviderRuntimeOutboundMismatchError);
assert.deepEqual(Schema.encodeUnknownSync(ProviderRuntimeTransportError)(error), {
_tag: "ProviderRuntimeOutboundMismatchError",
scenario: "replay-runtime-smoke",
index: 0,
expectedFrame: {
id: 1,
method: "initialize",
params: { capabilities: { experimentalApi: true } },
},
actualFrame: { id: 1, method: "wrong", params: {} },
});
}),
);
});
@@ -1,129 +0,0 @@
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import { Duration, Effect, Layer, Ref } from "effect";
import {
ProviderRuntimeTransport,
ProviderRuntimeIncompleteTranscriptError,
ProviderRuntimeOutboundMismatchError,
ProviderRuntimeTranscriptExhaustedError,
ProviderRuntimeUnexpectedInboundPullError,
ProviderRuntimeUnexpectedOutboundError,
type ProviderRuntimeInbound,
type ProviderRuntimeTransportShape,
} from "../Services/ProviderRuntimeTransport.ts";
function stableStringify(value: unknown): string {
if (value === null || typeof value !== "object") {
return JSON.stringify(value);
}
if (Array.isArray(value)) {
return `[${value.map(stableStringify).join(",")}]`;
}
const entries = Object.entries(value as Record<string, unknown>).toSorted(([left], [right]) =>
left.localeCompare(right),
);
return `{${entries
.map(([key, nested]) => `${JSON.stringify(key)}:${stableStringify(nested)}`)
.join(",")}}`;
}
function framesEqual(left: unknown, right: unknown): boolean {
return stableStringify(left) === stableStringify(right);
}
export function makeReplayProviderRuntime(
transcript: ProviderReplayTranscript,
): Effect.Effect<ProviderRuntimeTransportShape> {
return Effect.gen(function* () {
const cursor = yield* Ref.make(0);
const readNext = Ref.get(cursor).pipe(
Effect.map((index) => ({
index,
entry: transcript.entries[index],
})),
);
const advance = Ref.update(cursor, (index) => index + 1);
const transport: ProviderRuntimeTransportShape = {
send: (frame) =>
Effect.gen(function* () {
const { entry, index } = yield* readNext;
if (!entry) {
return yield* new ProviderRuntimeTranscriptExhaustedError({
scenario: transcript.scenario,
direction: "outbound",
frame,
});
}
if (entry.type !== "expect_outbound") {
return yield* new ProviderRuntimeUnexpectedOutboundError({
scenario: transcript.scenario,
index,
expectedEntry: entry,
actualFrame: frame,
});
}
if (!framesEqual(entry.frame, frame)) {
return yield* new ProviderRuntimeOutboundMismatchError({
scenario: transcript.scenario,
index,
expectedFrame: entry.frame,
actualFrame: frame,
});
}
yield* advance;
}),
receive: () =>
Effect.gen(function* () {
const { entry, index } = yield* readNext;
if (!entry) {
return yield* new ProviderRuntimeTranscriptExhaustedError({
scenario: transcript.scenario,
direction: "inbound",
});
}
if (entry.type === "expect_outbound") {
return yield* new ProviderRuntimeUnexpectedInboundPullError({
scenario: transcript.scenario,
index,
expectedFrame: entry.frame,
});
}
if (entry.type === "runtime_exit") {
yield* advance;
return entry satisfies ProviderRuntimeInbound;
}
if (entry.afterMs !== undefined && entry.afterMs > 0) {
yield* Effect.sleep(Duration.millis(entry.afterMs));
}
yield* advance;
return {
type: "frame",
frame: entry.frame,
} satisfies ProviderRuntimeInbound;
}),
assertComplete: () =>
Effect.gen(function* () {
const index = yield* Ref.get(cursor);
if (index !== transcript.entries.length) {
return yield* new ProviderRuntimeIncompleteTranscriptError({
scenario: transcript.scenario,
index,
total: transcript.entries.length,
nextEntry: transcript.entries[index],
});
}
}),
};
return transport;
});
}
export function makeReplayProviderRuntimeLayer(
transcript: ProviderReplayTranscript,
): Layer.Layer<ProviderRuntimeTransport> {
return Layer.effect(ProviderRuntimeTransport, makeReplayProviderRuntime(transcript));
}
@@ -1,42 +0,0 @@
import { describe, it } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import { Effect } from "effect";
import { readFile } from "node:fs/promises";
import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
import { materializeFixtureInput } from "./fixtures/shared.ts";
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
import { runOrchestratorV2ReplayScenario } from "./OrchestratorScenario.ts";
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
const text = await readFile(file, "utf8");
return await Effect.runPromise(decodeProviderReplayNdjson(text));
}
describe("Codex 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 () => {
const transcript = await readTranscript(provider.transcriptFile);
const input = materializeFixtureInput({
scenario: fixture.name,
fixtureInput: fixture.buildInput(),
modelSelection: provider.modelSelection,
});
const scenario = {
name: `${fixture.name}/${provider.provider}`,
transcript,
commands: input.commands,
projectionThreadIds: input.projectionThreadIds,
};
const result = await Effect.runPromise(
runOrchestratorV2ReplayScenario(scenario).pipe(provideDeterministicTestRuntime),
);
provider.assertOutput(result, transcript);
});
}
}
});
@@ -1,9 +1,9 @@
import { assert, describe, it } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import { Effect } from "effect";
import * as CodexReplay from "effect-codex-app-server/replay";
import { Effect, Schema } from "effect";
import { readFile } from "node:fs/promises";
import { makeReplayProviderRuntime } from "../replay/ReplayProviderRuntime.ts";
import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
@@ -146,45 +146,22 @@ function assertScenarioExpectations(transcript: ProviderReplayTranscript) {
assert.equal(countApprovalRequests(transcript), expectation.approvalRequestCount);
}
function replayTranscript(transcript: ProviderReplayTranscript) {
return Effect.gen(function* () {
const runtime = yield* makeReplayProviderRuntime(transcript);
for (const entry of transcript.entries) {
switch (entry.type) {
case "expect_outbound":
yield* runtime.send(entry.frame);
break;
case "emit_inbound": {
const inbound = yield* runtime.receive();
assert.deepEqual(inbound, {
type: "frame",
frame: entry.frame,
});
break;
}
case "runtime_exit": {
const inbound = yield* runtime.receive();
assert.deepEqual(inbound, entry);
break;
}
}
}
yield* runtime.assertComplete();
});
}
describe("Codex replay fixtures", () => {
it("loads and replays every current Codex fixture directly from minimal NDJSON", async () => {
it("loads every current Codex fixture as a codex app-server replay transcript", async () => {
for (const fixture of CURRENT_CODEX_REPLAY_FIXTURES) {
const transcript = await readTranscript(fixture.transcriptFile);
const codexTranscript = Schema.decodeUnknownSync(CodexReplay.CodexAppServerReplayTranscript)(
transcript,
);
const first = transcript.entries[0];
assert.equal(transcript.provider, "codex");
assert.equal(transcript.protocol, "codex.app-server");
assert.equal(transcript.scenario, fixture.scenario);
assert.deepEqual(transcript.entries.at(-1), { type: "runtime_exit", status: "success" });
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.`);
@@ -192,7 +169,6 @@ describe("Codex replay fixtures", () => {
assert.equal(first.label, "initialize");
assertScenarioExpectations(transcript);
await Effect.runPromise(replayTranscript(transcript));
}
});
@@ -0,0 +1,94 @@
import { assert, describe, it } from "@effect/vitest";
import { OrchestrationV2Command, type ProviderReplayTranscript } from "@t3tools/contracts";
import { Effect, Schema } from "effect";
import { readFile } from "node:fs/promises";
import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
import { fixtureIds, materializeFixtureInput } from "./fixtures/shared.ts";
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
const text = await readFile(file, "utf8");
return await Effect.runPromise(decodeProviderReplayNdjson(text));
}
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 = materializeFixtureInput({
scenario: fixture.name,
fixtureInput: fixture.buildInput(),
modelSelection: provider.modelSelection,
});
const ids = fixtureIds(fixture.name);
const firstCommand = materialized.commands[0];
assert.equal(transcript.scenario, fixture.name);
assert.equal(transcript.provider, provider.provider);
assert.equal(provider.modelSelection.provider, provider.provider);
assert.equal(materialized.projectionThreadIds[0], ids.threadId);
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, ids.threadId);
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) {
Schema.decodeUnknownSync(OrchestrationV2Command)(command);
}
for (const command of materialized.commands) {
assert.isTrue(
materialized.steps.some((step) => step.type === "dispatch" && step.command === command),
`${fixture.name}/${provider.provider} command ${command.commandId} must appear in the timeline`,
);
}
}
}
});
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",
});
}
}
});
});
@@ -0,0 +1,78 @@
import { describe, it } from "@effect/vitest";
import type { ProviderKind, ProviderReplayTranscript } from "@t3tools/contracts";
import { Effect } from "effect";
import { readFile } from "node:fs/promises";
import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts";
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
import {
materializeFixtureInput,
type OrchestratorFixtureInput,
type ProviderOrchestratorReplayVariant,
} from "./fixtures/shared.ts";
import {
runOrchestratorV2ProviderReplayScenario,
type OrchestratorV2ProviderReplayHarness,
} from "./ProviderReplayHarness.ts";
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
const PROVIDER_REPLAY_HARNESSES = [CodexOrchestratorReplayHarness] as const;
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
const text = await readFile(file, "utf8");
return await Effect.runPromise(decodeProviderReplayNdjson(text));
}
function harnessFor(provider: ProviderKind) {
const harness = PROVIDER_REPLAY_HARNESSES.find((candidate) => candidate.provider === provider);
if (!harness) {
throw new Error(`No replay harness registered for provider ${provider}.`);
}
return harness;
}
async function runFixtureProvider<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 materialized = materializeFixtureInput({
scenario: input.fixtureName,
fixtureInput: input.buildInput(),
modelSelection: input.provider.modelSelection,
});
const scenario = {
name: `${input.fixtureName}/${input.provider.provider}`,
transcript,
commands: materialized.commands,
steps: materialized.steps,
projectionThreadIds: materialized.projectionThreadIds,
};
const result = await Effect.runPromise(
runOrchestratorV2ProviderReplayScenario(scenario, input.harness).pipe(
provideDeterministicTestRuntime,
),
);
input.provider.assertOutput(result, transcript);
}
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 runFixtureProvider({
fixtureName: fixture.name,
buildInput: fixture.buildInput,
provider,
harness: harnessFor(provider.provider),
});
});
}
}
});
@@ -2,27 +2,37 @@ import type {
OrchestrationV2Command,
OrchestrationV2DomainEvent,
OrchestrationV2ThreadProjection,
ProviderReplayTranscript,
ThreadId,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { Duration, Effect, Fiber, Schema } from "effect";
import { TestClock } from "effect/testing";
import { OrchestratorV2, type OrchestratorV2Error } from "../Services/Orchestrator.ts";
import {
ProviderRuntimeTransport,
type ProviderRuntimeTransportError,
} from "../Services/ProviderRuntimeTransport.ts";
import { makeReplayProviderRuntimeLayer } from "../replay/ReplayProviderRuntime.ts";
export type OrchestratorV2ScenarioStep =
| {
readonly type: "dispatch";
readonly command: OrchestrationV2Command;
readonly await?: boolean;
readonly key?: string;
}
| {
readonly type: "advance_clock";
readonly duration: Duration.Input;
}
| {
readonly type: "await";
readonly key: string;
}
| {
readonly type: "await_all";
};
export interface OrchestratorV2Scenario {
readonly name: string;
readonly commands: ReadonlyArray<OrchestrationV2Command>;
readonly steps?: ReadonlyArray<OrchestratorV2ScenarioStep>;
readonly projectionThreadIds?: ReadonlyArray<ThreadId>;
readonly assertReplayComplete?: boolean;
}
export interface OrchestratorV2ReplayScenario extends OrchestratorV2Scenario {
readonly transcript: ProviderReplayTranscript;
}
export interface OrchestratorV2ScenarioResult {
@@ -30,6 +40,18 @@ export interface OrchestratorV2ScenarioResult {
readonly projections: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>;
}
export class OrchestratorV2ScenarioStepError extends Schema.TaggedErrorClass<OrchestratorV2ScenarioStepError>()(
"OrchestratorV2ScenarioStepError",
{
scenario: Schema.String,
step: Schema.String,
},
) {
override get message(): string {
return `Invalid orchestrator scenario step ${this.step} in ${this.scenario}.`;
}
}
function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<ThreadId> {
switch (command.type) {
case "thread.create":
@@ -46,13 +68,32 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
}
}
function scenarioSteps(
scenario: OrchestratorV2Scenario,
): ReadonlyArray<OrchestratorV2ScenarioStep> {
return (
scenario.steps ??
scenario.commands.map((command) => ({
type: "dispatch" as const,
command,
await: true,
}))
);
}
function scenarioCommands(scenario: OrchestratorV2Scenario): ReadonlyArray<OrchestrationV2Command> {
return scenarioSteps(scenario).flatMap((step) =>
step.type === "dispatch" ? [step.command] : [],
);
}
function collectProjectionThreadIds(scenario: OrchestratorV2Scenario): ReadonlyArray<ThreadId> {
if (scenario.projectionThreadIds) {
return scenario.projectionThreadIds;
}
const ids = new Set<ThreadId>();
for (const command of scenario.commands) {
for (const command of scenarioCommands(scenario)) {
for (const threadId of commandThreadIds(command)) {
ids.add(threadId);
}
@@ -64,40 +105,76 @@ export function runOrchestratorV2Scenario(
scenario: OrchestratorV2Scenario,
): Effect.Effect<
OrchestratorV2ScenarioResult,
OrchestratorV2Error | ProviderRuntimeTransportError,
OrchestratorV2 | ProviderRuntimeTransport
> {
return Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
const runtime = yield* ProviderRuntimeTransport;
const domainEventGroups = yield* Effect.forEach(scenario.commands, orchestrator.dispatch, {
concurrency: 1,
});
if (scenario.assertReplayComplete ?? true) {
yield* runtime.assertComplete();
}
const projections = new Map<ThreadId, OrchestrationV2ThreadProjection>();
for (const threadId of collectProjectionThreadIds(scenario)) {
projections.set(threadId, yield* orchestrator.getThreadProjection(threadId));
}
return {
domainEvents: domainEventGroups.flat(),
projections,
};
});
}
export function runOrchestratorV2ReplayScenario(
scenario: OrchestratorV2ReplayScenario,
): Effect.Effect<
OrchestratorV2ScenarioResult,
OrchestratorV2Error | ProviderRuntimeTransportError,
OrchestratorV2Error | OrchestratorV2ScenarioStepError,
OrchestratorV2
> {
return runOrchestratorV2Scenario(scenario).pipe(
Effect.provide(makeReplayProviderRuntimeLayer(scenario.transcript)),
return Effect.scoped(
Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
const domainEventGroups: Array<ReadonlyArray<OrchestrationV2DomainEvent>> = [];
const backgroundDispatches = new Map<
string,
Fiber.Fiber<ReadonlyArray<OrchestrationV2DomainEvent>, OrchestratorV2Error>
>();
let anonymousBackgroundDispatchIndex = 0;
const awaitDispatch = (key: string) =>
Effect.gen(function* () {
const fiber = backgroundDispatches.get(key);
if (!fiber) {
return yield* new OrchestratorV2ScenarioStepError({
scenario: scenario.name,
step: `await:${key}`,
});
}
const events = yield* Fiber.join(fiber);
backgroundDispatches.delete(key);
domainEventGroups.push(events);
});
for (const step of scenarioSteps(scenario)) {
switch (step.type) {
case "dispatch": {
if (step.await ?? true) {
domainEventGroups.push(yield* orchestrator.dispatch(step.command));
break;
}
anonymousBackgroundDispatchIndex += 1;
const key = step.key ?? `dispatch:${anonymousBackgroundDispatchIndex}`;
backgroundDispatches.set(
key,
yield* orchestrator.dispatch(step.command).pipe(Effect.forkScoped),
);
break;
}
case "advance_clock":
yield* TestClock.adjust(step.duration);
break;
case "await":
yield* awaitDispatch(step.key);
break;
case "await_all":
for (const key of Array.from(backgroundDispatches.keys())) {
yield* awaitDispatch(key);
}
break;
}
}
for (const key of Array.from(backgroundDispatches.keys())) {
yield* awaitDispatch(key);
}
const projections = new Map<ThreadId, OrchestrationV2ThreadProjection>();
for (const threadId of collectProjectionThreadIds(scenario)) {
projections.set(threadId, yield* orchestrator.getThreadProjection(threadId));
}
return {
domainEvents: domainEventGroups.flat(),
projections,
};
}),
);
}
@@ -0,0 +1,48 @@
import type { ProviderKind, ProviderReplayTranscript } from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { OrchestratorV2LiveLayer } from "../Layers/OrchestratorLive.ts";
import type { OrchestratorV2Error } from "../Services/Orchestrator.ts";
import { ProviderAdapterRegistryV2 } from "../Services/ProviderAdapterRegistry.ts";
import {
runOrchestratorV2Scenario,
type OrchestratorV2ScenarioStepError,
type OrchestratorV2Scenario,
type OrchestratorV2ScenarioResult,
} from "./OrchestratorScenario.ts";
export interface OrchestratorV2ProviderReplayScenario<
Transcript extends ProviderReplayTranscript = ProviderReplayTranscript,
> extends OrchestratorV2Scenario {
readonly transcript: Transcript;
}
export interface OrchestratorV2ProviderReplayHarness<
Transcript extends ProviderReplayTranscript = ProviderReplayTranscript,
Error = never,
> {
readonly provider: ProviderKind;
readonly decodeTranscript: (
transcript: ProviderReplayTranscript,
) => Effect.Effect<Transcript, Error>;
readonly makeProviderAdapterRegistryLayer: (
transcript: Transcript,
) => Layer.Layer<ProviderAdapterRegistryV2, Error>;
}
export function runOrchestratorV2ProviderReplayScenario<
Transcript extends ProviderReplayTranscript,
Error,
>(
scenario: OrchestratorV2ProviderReplayScenario<Transcript>,
harness: OrchestratorV2ProviderReplayHarness<Transcript, Error>,
): Effect.Effect<
OrchestratorV2ScenarioResult,
OrchestratorV2Error | OrchestratorV2ScenarioStepError | Error,
never
> {
const registryLayer = harness.makeProviderAdapterRegistryLayer(scenario.transcript);
const layer = OrchestratorV2LiveLayer.pipe(Layer.provide(registryLayer));
return runOrchestratorV2Scenario(scenario).pipe(Effect.provide(layer));
}
@@ -34,6 +34,6 @@ export function assertMultiTurnOutput(
"Respond with exactly: second fixture turn complete",
]);
assert.equal(projection.turnItems.filter((item) => item.type === "user_message").length, 2);
assertAssistantTextIncludes(projection, "multi-turn fixture first response");
assertAssistantTextIncludes(projection, "multi-turn fixture second response");
assertAssistantTextIncludes(projection, "first fixture turn complete");
assertAssistantTextIncludes(projection, "second fixture turn complete");
}
@@ -17,7 +17,10 @@ import {
type ProviderReplayTranscript,
} from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../OrchestratorScenario.ts";
import type {
OrchestratorV2ScenarioResult,
OrchestratorV2ScenarioStep,
} from "../OrchestratorScenario.ts";
export const SIMPLE_PROMPT = "Respond with the following text: fixture simple ok";
export const TOOL_CALL_WRITE_PROMPT =
@@ -69,6 +72,7 @@ export interface OrchestratorReplayFixture {
export interface MaterializedOrchestratorFixtureInput {
readonly commands: ReadonlyArray<OrchestrationV2Command>;
readonly steps: ReadonlyArray<OrchestratorV2ScenarioStep>;
readonly projectionThreadIds: ReadonlyArray<ThreadId>;
}
@@ -157,32 +161,68 @@ export function materializeFixtureInput(input: {
readonly modelSelection: ModelSelection;
}): MaterializedOrchestratorFixtureInput {
const ids = fixtureIds(input.scenario);
const commands: Array<OrchestrationV2Command> = [
const commands: Array<OrchestrationV2Command> = [];
const steps: Array<OrchestratorV2ScenarioStep> = [];
let messageIndex = 0;
const activeRunDispatchKeys = new Set<string>();
const pushDispatch = (
command: OrchestrationV2Command,
options: {
readonly await?: boolean;
readonly key?: string;
readonly advanceClockAfter?: boolean;
} = {},
) => {
commands.push(command);
steps.push({
type: "dispatch",
command,
await: options.await ?? true,
...(options.key === undefined ? {} : { key: options.key }),
});
if (options.advanceClockAfter ?? true) {
steps.push({ type: "advance_clock", duration: "1 millis" });
}
};
pushDispatch(
createThreadCommand({
scenario: input.scenario,
ids,
modelSelection: input.modelSelection,
}),
];
let messageIndex = 0;
);
for (const step of input.fixtureInput.steps) {
for (const [stepIndex, step] of input.fixtureInput.steps.entries()) {
switch (step.type) {
case "message":
messageIndex += 1;
commands.push(
dispatchMessageCommand({
scenario: input.scenario,
ids,
modelSelection: input.modelSelection,
text: step.text,
index: messageIndex,
}),
);
{
const nextStep = input.fixtureInput.steps[stepIndex + 1];
const shouldRunInBackground =
nextStep !== undefined &&
(nextStep.type === "steer" || nextStep.type === "interrupt") &&
nextStep.targetRunIndex === messageIndex;
const key = `run:${messageIndex}`;
pushDispatch(
dispatchMessageCommand({
scenario: input.scenario,
ids,
modelSelection: input.modelSelection,
text: step.text,
index: messageIndex,
}),
shouldRunInBackground ? { await: false, key } : undefined,
);
if (shouldRunInBackground) {
activeRunDispatchKeys.add(key);
}
}
break;
case "steer":
messageIndex += 1;
commands.push(
pushDispatch(
dispatchMessageCommand({
scenario: input.scenario,
ids,
@@ -195,17 +235,27 @@ export function materializeFixtureInput(input: {
},
}),
);
if (activeRunDispatchKeys.delete(`run:${step.targetRunIndex}`)) {
steps.push({ type: "await", key: `run:${step.targetRunIndex}` });
}
break;
case "interrupt":
commands.push({
type: "run.interrupt",
commandId: commandId(input.scenario, `interrupt-${step.targetRunIndex}`),
threadId: ids.threadId,
runId: runId(input.scenario, step.targetRunIndex),
});
pushDispatch(
{
type: "run.interrupt",
commandId: commandId(input.scenario, `interrupt-${step.targetRunIndex}`),
threadId: ids.threadId,
runId: runId(input.scenario, step.targetRunIndex),
},
{ advanceClockAfter: false },
);
if (activeRunDispatchKeys.delete(`run:${step.targetRunIndex}`)) {
steps.push({ type: "await", key: `run:${step.targetRunIndex}` });
}
steps.push({ type: "advance_clock", duration: "1 millis" });
break;
case "rollback":
commands.push({
pushDispatch({
type: "checkpoint.rollback",
commandId: commandId(input.scenario, `rollback-${step.checkpointSuffix}`),
threadId: ids.threadId,
@@ -216,8 +266,13 @@ export function materializeFixtureInput(input: {
}
}
if (activeRunDispatchKeys.size > 0) {
steps.push({ type: "await_all" });
}
return {
commands,
steps,
projectionThreadIds: [ids.threadId],
};
}
@@ -1,3 +1,4 @@
export * from "./DeterministicRuntime.ts";
export * from "./OrchestratorScenario.ts";
export * from "./ProviderReplayHarness.ts";
export * from "./ReplayTranscriptNdjson.ts";
@@ -774,6 +774,11 @@ export const OrchestrationV2DomainEvent = Schema.Union([
type: Schema.Literal("message.updated"),
payload: OrchestrationV2ConversationMessage,
}),
Schema.Struct({
...OrchestrationV2EventBase.fields,
type: Schema.Literal("turn-item.updated"),
payload: OrchestrationV2TurnItem,
}),
Schema.Struct({
...OrchestrationV2EventBase.fields,
type: Schema.Literal("plan.updated"),
@@ -19,6 +19,10 @@
"types": "./src/protocol.ts",
"import": "./src/protocol.ts"
},
"./replay": {
"types": "./src/replay.ts",
"import": "./src/replay.ts"
},
"./errors": {
"types": "./src/errors.ts",
"import": "./src/errors.ts"
@@ -0,0 +1,64 @@
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { CodexAppServerClient } from "./client.ts";
export const CodexAppServerReplayEntry = Schema.Union([
Schema.Struct({
type: Schema.Literal("expect_outbound"),
label: Schema.optional(Schema.String),
frame: Schema.Unknown,
}),
Schema.Struct({
type: Schema.Literal("emit_inbound"),
label: Schema.optional(Schema.String),
frame: Schema.Unknown,
afterMs: Schema.optional(Schema.Number),
}),
Schema.Struct({
type: Schema.Literal("runtime_exit"),
status: Schema.Literals(["success", "error", "cancelled"]),
error: Schema.optional(Schema.Unknown),
}),
]);
export type CodexAppServerReplayEntry = typeof CodexAppServerReplayEntry.Type;
export const CodexAppServerReplayTranscript = Schema.Struct({
provider: Schema.Literal("codex"),
protocol: Schema.Literal("codex.app-server"),
version: Schema.String,
scenario: Schema.String,
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
entries: Schema.Array(CodexAppServerReplayEntry),
});
export type CodexAppServerReplayTranscript = typeof CodexAppServerReplayTranscript.Type;
export class CodexAppServerReplayLayerNotImplementedError extends Schema.TaggedErrorClass<CodexAppServerReplayLayerNotImplementedError>()(
"CodexAppServerReplayLayerNotImplementedError",
{
scenario: Schema.String,
},
) {
override get message(): string {
return `Codex app-server replay layer is not implemented for scenario ${this.scenario}.`;
}
}
export const CodexAppServerReplayError = Schema.Union([
CodexAppServerReplayLayerNotImplementedError,
]);
export type CodexAppServerReplayError = typeof CodexAppServerReplayError.Type;
export function layerReplay(
transcript: CodexAppServerReplayTranscript,
): Layer.Layer<CodexAppServerClient, CodexAppServerReplayError> {
return Layer.effect(
CodexAppServerClient,
Effect.fail(
new CodexAppServerReplayLayerNotImplementedError({
scenario: transcript.scenario,
}),
),
);
}