Map orchestration turns to provider instances

- Separate provider driver identity from configured provider instances
- Add durable event, effect, checkpoint, and turn-position persistence
- Route turn lifecycle and recovery through shared orchestration services
This commit is contained in:
Julius Marminge authored and maria-rcks committed 2026-08-03 11:45:02 -04:00
1 parent ddb255a7db
commit 27897acd26
109 files changed
+8377 -3593

No files matched your search

@@ -439,7 +439,7 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null {
case "compaction":
return item.summary ?? null;
case "handoff":
return item.summary ?? `${item.strategy} handoff to ${item.toProvider}`;
return item.summary ?? `${item.strategy} handoff to ${item.toProviderInstanceId}`;
case "fork":
return `Forked to thread ${item.targetThreadId}.`;
case "subagent":
@@ -673,7 +673,7 @@ const make = Effect.gen(function* () {
childRunId: childRun?.id ?? null,
childNodeId: task.id,
status,
providerInstanceId: ProviderInstanceId.make(task.provider),
providerInstanceId: ProviderInstanceId.make(task.driver),
model: task.model,
summary: derivedResult,
resultContextTransferId: resultTransfer?.id ?? null,
@@ -742,7 +742,7 @@ const make = Effect.gen(function* () {
if (
parentRun === undefined ||
parentRun.rootNodeId === null ||
parentRun.provider !== scope.providerInstanceId
parentRun.providerInstanceId !== scope.providerInstanceId
) {
return yield* failure(
"parent_not_active",
@@ -21,7 +21,6 @@ import {
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
type ProviderKind,
ProviderThreadId,
ProviderTurnId,
type ServerProvider,
@@ -94,8 +93,8 @@ interface CapturedTurn {
readonly text: string;
}
function unsupported(provider: ProviderKind, detail: string) {
return Effect.fail(new ProviderAdapterProtocolError({ provider, detail }));
function unsupported(driver: ProviderDriverKind, detail: string) {
return Effect.fail(new ProviderAdapterProtocolError({ driver, detail }));
}
function makeProviderSnapshot(input: {
@@ -127,7 +126,7 @@ function makeProviderSnapshot(input: {
function makeDeterministicAdapter(input: {
readonly instanceId: ProviderInstanceId;
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly capabilities: OrchestrationV2ProviderCapabilities;
readonly capturedTurns: Ref.Ref<ReadonlyArray<CapturedTurn>>;
readonly shouldComplete: (turn: ProviderAdapterV2TurnInput) => boolean;
@@ -135,7 +134,7 @@ function makeDeterministicAdapter(input: {
}): ProviderAdapterV2Shape {
return {
instanceId: input.instanceId,
provider: input.provider,
driver: input.driver,
getCapabilities: () => Effect.succeed(input.capabilities),
openSession: (sessionInput) =>
Effect.gen(function* () {
@@ -143,7 +142,8 @@ function makeDeterministicAdapter(input: {
const now = yield* DateTime.now;
const providerSession: OrchestrationV2ProviderSession = {
id: sessionInput.providerSessionId,
provider: input.provider,
driver: input.driver,
providerInstanceId: input.instanceId,
status: "ready",
cwd: sessionInput.runtimePolicy.cwd ?? process.cwd(),
model: sessionInput.modelSelection.model,
@@ -160,7 +160,7 @@ function makeDeterministicAdapter(input: {
return {
instanceId: input.instanceId,
provider: input.provider,
driver: input.driver,
providerSessionId: sessionInput.providerSessionId,
providerSession,
rawEvents: Stream.empty,
@@ -168,15 +168,16 @@ function makeDeterministicAdapter(input: {
ensureThread: (threadInput) =>
Effect.gen(function* () {
const createdAt = yield* DateTime.now;
const nativeThreadId = `${input.provider}:${threadInput.threadId}`;
const nativeThreadId = `${input.driver}:${threadInput.threadId}`;
return {
id: ProviderThreadId.make(`provider-thread:${nativeThreadId}`),
provider: input.provider,
driver: input.driver,
providerInstanceId: input.instanceId,
providerSessionId: sessionInput.providerSessionId,
appThreadId: threadInput.threadId,
ownerNodeId: null,
nativeThreadRef: {
provider: input.provider,
driver: input.driver,
nativeId: nativeThreadId,
strength: "strong",
},
@@ -208,14 +209,14 @@ function makeDeterministicAdapter(input: {
yield* publish([
{
type: "provider_turn.updated",
provider: input.provider,
driver: input.driver,
providerTurn: {
id: providerTurnId,
providerThreadId: turnInput.providerThread.id,
nodeId: turnInput.rootNodeId,
runAttemptId: turnInput.attemptId,
nativeTurnRef: {
provider: input.provider,
driver: input.driver,
nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`,
strength: "strong",
},
@@ -233,14 +234,14 @@ function makeDeterministicAdapter(input: {
yield* publish([
{
type: "provider_turn.updated",
provider: input.provider,
driver: input.driver,
providerTurn: {
id: providerTurnId,
providerThreadId: turnInput.providerThread.id,
nodeId: turnInput.rootNodeId,
runAttemptId: turnInput.attemptId,
nativeTurnRef: {
provider: input.provider,
driver: input.driver,
nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`,
strength: "strong",
},
@@ -252,7 +253,7 @@ function makeDeterministicAdapter(input: {
},
{
type: "turn_item.updated",
provider: input.provider,
driver: input.driver,
turnItem: {
id: TurnItemId.make(
`turn-item:${input.instanceId}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
@@ -280,7 +281,7 @@ function makeDeterministicAdapter(input: {
},
{
type: "turn.terminal",
provider: input.provider,
driver: input.driver,
providerTurnId,
status: "completed",
},
@@ -290,16 +291,15 @@ function makeDeterministicAdapter(input: {
interruptTurn: ({ providerTurnId }) =>
PubSub.publish(events, {
type: "turn.terminal",
provider: input.provider,
driver: input.driver,
providerTurnId,
status: "interrupted",
}).pipe(Effect.asVoid),
respondToRuntimeRequest: () => Effect.void,
readThreadSnapshot: () =>
unsupported(input.provider, "readThreadSnapshot is unused in this test"),
rollbackThread: () =>
unsupported(input.provider, "rollbackThread is unused in this test"),
forkThread: () => unsupported(input.provider, "forkThread is unused in this test"),
unsupported(input.driver, "readThreadSnapshot is unused in this test"),
rollbackThread: () => unsupported(input.driver, "rollbackThread is unused in this test"),
forkThread: () => unsupported(input.driver, "forkThread is unused in this test"),
};
}),
};
@@ -345,7 +345,7 @@ describe("orchestrator MCP toolkit", () => {
const registryLayer = makeProviderAdapterRegistryLayer([
makeDeterministicAdapter({
instanceId: codexInstanceId,
provider: "codex",
driver: ProviderDriverKind.make("codex"),
capabilities: CodexProviderCapabilitiesV2,
capturedTurns,
shouldComplete: (turn) =>
@@ -354,7 +354,7 @@ describe("orchestrator MCP toolkit", () => {
}),
makeDeterministicAdapter({
instanceId: claudeInstanceId,
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
capabilities: ClaudeProviderCapabilitiesV2,
capturedTurns,
shouldComplete: () => true,
@@ -12,11 +12,18 @@ import {
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import { describe } from "vite-plus/test";
import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts";
import { ServerConfig } from "../config.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../provider/Layers/ProviderEventLoggers.ts";
import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
@@ -43,25 +50,38 @@ const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe(
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer));
const serverSettingsLayer = ServerSettingsService.layerTest({
providerInstances: {
[liveInstanceId]: {
driver: ProviderDriverKind.make("acpRegistry"),
displayName: `ACP Registry: ${liveAgentId}`,
enabled: true,
config: {
agentId: liveAgentId,
...(liveCommandPath ? { commandPath: liveCommandPath } : {}),
},
},
},
});
const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
Layer.provide(
Layer.mergeAll(
serverConfigLayer.pipe(Layer.provide(NodeServices.layer)),
serverSettingsLayer,
NodeServices.layer,
FetchHttpClient.layer,
OpenCodeRuntimeLive.pipe(Layer.provide(NodeServices.layer)),
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
),
),
);
const liveLayer = OrchestrationV2LayerLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(checkpointStoreLayer),
Layer.provide(serverConfigLayer),
Layer.provide(
ServerSettingsService.layerTest({
providerInstances: {
[liveInstanceId]: {
driver: ProviderDriverKind.make("acpRegistry"),
displayName: `ACP Registry: ${liveAgentId}`,
enabled: true,
config: {
agentId: liveAgentId,
...(liveCommandPath ? { commandPath: liveCommandPath } : {}),
},
},
},
}),
),
Layer.provide(serverSettingsLayer),
Layer.provide(providerInstanceRegistryLayer),
Layer.provide(NodeServices.layer),
);
@@ -132,7 +152,7 @@ describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")(
)?.text;
assert.deepEqual(
firstProjection.runs.map((run) => [run.provider, run.status]),
firstProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[[liveInstanceId, "completed"]],
);
assert.include(firstAssistant ?? "", marker);
@@ -156,7 +176,7 @@ describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")(
)?.text;
assert.deepEqual(
finalProjection.runs.map((run) => [run.provider, run.status]),
finalProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[
[liveInstanceId, "completed"],
[liveInstanceId, "completed"],
@@ -4,6 +4,7 @@ import {
MessageId,
NodeId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ProviderSessionId,
RunAttemptId,
@@ -40,6 +41,7 @@ const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
}).pipe(Layer.provide(NodeServices.layer));
const testLayer = Layer.mergeAll(NodeServices.layer, idAllocatorLayer, serverConfigLayer);
const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test");
function makeMockRuntime(input: {
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
@@ -86,7 +88,7 @@ function makeTurnInput(input: {
id: input.threadId,
projectId: ProjectId.make(`project:${input.threadId}`),
title: "ACP adapter test",
defaultProvider: "acp-test",
providerInstanceId: input.instanceId,
modelSelection,
runtimeMode: "approval-required",
interactionMode: "default",
@@ -140,7 +142,7 @@ describe("AcpAdapterV2", () => {
const adapter = makeAcpAdapterV2({
instanceId,
flavor: {
provider: "acp-test",
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime,
},
@@ -197,7 +199,7 @@ describe("AcpAdapterV2", () => {
const adapter = makeAcpAdapterV2({
instanceId,
flavor: {
provider: "acp-test",
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime: makeMockRuntime({
childProcessSpawner,
@@ -282,7 +284,7 @@ describe("AcpAdapterV2", () => {
const adapter = makeAcpAdapterV2({
instanceId,
flavor: {
provider: "acp-test",
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime: makeMockRuntime({
childProcessSpawner,
@@ -328,7 +330,7 @@ describe("AcpAdapterV2", () => {
Stream.runHead,
);
const providerTurnId = idAllocator.derive.providerTurn({
provider: "acp-test",
driver: ACP_TEST_DRIVER,
nativeTurnId: "mock-session-1:turn:1",
});
const interruptFiber = yield* runtime
@@ -1,5 +1,5 @@
import {
ProviderKind,
ProviderDriverKind,
ProviderReplayEntry,
type ProviderReplayTranscript,
} from "@t3tools/contracts";
@@ -18,7 +18,7 @@ import {
import { ACP_PROTOCOL, type AcpAdapterV2RuntimeInput } from "./AcpAdapterV2.ts";
export const AcpReplayTranscript = Schema.Struct({
provider: ProviderKind,
provider: ProviderDriverKind,
protocol: Schema.Literal(ACP_PROTOCOL),
version: Schema.String,
scenario: Schema.String,
@@ -32,8 +32,8 @@ const decodeAcpReplayTranscriptSchema = Schema.decodeUnknownEffect(AcpReplayTran
export class AcpReplayTranscriptDecodeError extends Schema.TaggedErrorClass<AcpReplayTranscriptDecodeError>()(
"AcpReplayTranscriptDecodeError",
{
expectedProvider: ProviderKind,
provider: Schema.optional(Schema.String),
expectedProvider: ProviderDriverKind,
driver: Schema.optional(Schema.String),
protocol: Schema.optional(Schema.String),
scenario: Schema.optional(Schema.String),
cause: Schema.Defect(),
@@ -60,7 +60,7 @@ function metadataFromTranscript(transcript: ProviderReplayTranscript): {
export function decodeAcpReplayTranscript(
transcript: ProviderReplayTranscript,
expectedProvider: ProviderKind,
expectedProvider: ProviderDriverKind,
options: { readonly retargetProvider?: boolean } = {},
): Effect.Effect<AcpReplayTranscript, AcpReplayTranscriptDecodeError> {
const candidate = options.retargetProvider
@@ -15,7 +15,7 @@ import {
type OrchestrationV2UserInputQuestion,
type ProviderApprovalDecision,
type ProviderInstanceId,
type ProviderKind,
type ProviderDriverKind,
type ProviderRequestKind,
type ProviderUserInputAnswers,
type RuntimeRequestId,
@@ -97,7 +97,7 @@ export interface AcpAdapterV2ExtensionContext {
}
export interface AcpAdapterV2Flavor {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly capabilities: OrchestrationV2ProviderCapabilities;
readonly makeRuntime: (
input: AcpAdapterV2RuntimeInput,
@@ -265,11 +265,11 @@ function acpMcpServers(threadId: ThreadId): ReadonlyArray<EffectAcpSchema.McpSer
];
}
function nativeThreadId(provider: ProviderKind, thread: OrchestrationV2ProviderThread): string {
function nativeThreadId(driver: ProviderDriverKind, thread: OrchestrationV2ProviderThread): string {
const id = thread.nativeThreadRef?.nativeId;
if (id === null || id === undefined || id.trim().length === 0) {
throw new ProviderAdapterProtocolError({
provider,
driver,
detail: `Provider thread ${thread.id} is missing its ACP session id`,
});
}
@@ -277,7 +277,8 @@ function nativeThreadId(provider: ProviderKind, thread: OrchestrationV2ProviderT
}
function makeProviderThread(input: {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly providerInstanceId: ProviderInstanceId;
readonly idAllocator: IdAllocatorV2Shape;
readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
@@ -288,15 +289,16 @@ function makeProviderThread(input: {
}): OrchestrationV2ProviderThread {
return {
id: input.idAllocator.derive.providerThread({
provider: input.provider,
driver: input.driver,
nativeThreadId: input.nativeThreadId,
}),
provider: input.provider,
driver: input.driver,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
appThreadId: input.appThreadId,
ownerNodeId: input.ownerNodeId ?? null,
nativeThreadRef: {
provider: input.provider,
driver: input.driver,
nativeId: input.nativeThreadId,
strength: "strong",
},
@@ -491,9 +493,11 @@ function jsonRpcId(value: unknown): string | number | null {
function elicitationContent(
answers: ProviderUserInputAnswers,
allowedKeys: ReadonlySet<string>,
): Record<string, EffectAcpSchema.ElicitationContentValue> {
const content: Record<string, EffectAcpSchema.ElicitationContentValue> = {};
for (const [key, value] of Object.entries(answers)) {
if (!allowedKeys.has(key)) continue;
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
content[key] = value;
} else if (Array.isArray(value)) {
@@ -596,11 +600,11 @@ function oppositeDirection(direction: "incoming" | "outgoing"): "incoming" | "ou
export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV2Shape {
const { flavor, fileSystem, idAllocator, serverConfig } = options;
const provider = flavor.provider;
const driver = flavor.driver;
return ProviderAdapterV2.of({
instanceId: options.instanceId,
provider,
driver,
getCapabilities: () => Effect.succeed(flavor.capabilities),
openSession: Effect.fn("AcpAdapterV2.openSession")(
function* (input: ProviderAdapterV2OpenSessionInput) {
@@ -662,7 +666,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
yield* Queue.offer(rawEvents, {
id: rawEventId,
provider,
driver,
providerInstanceId: options.instanceId,
providerSessionId: input.providerSessionId,
sequence: state.sequence,
direction: event.direction,
@@ -676,7 +681,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("orchestration-v2.acp-raw-event-failed", {
provider,
driver,
providerSessionId: input.providerSessionId,
cause,
}),
@@ -744,21 +749,21 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const now = yield* DateTime.now;
const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider,
driver,
nativeItemId: segment.nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider,
driver,
nativeItemId: segment.nativeItemId,
});
const nativeItemRef = {
provider,
driver,
nativeId: segment.nativeItemId,
strength: "weak" as const,
};
yield* emitProviderEvent({
type: "node.updated",
provider,
driver,
node: {
id: nodeId,
threadId: context.input.threadId,
@@ -779,7 +784,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
if (kind === "assistant") {
const messageId = idAllocator.derive.messageFromProviderItem({
provider,
driver,
nativeItemId: segment.nativeItemId,
});
const message: OrchestrationV2ConversationMessage = {
@@ -796,10 +801,10 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
createdAt: segment.startedAt,
updatedAt: now,
};
yield* emitProviderEvent({ type: "message.updated", provider, message });
yield* emitProviderEvent({ type: "message.updated", driver, message });
yield* emitProviderEvent({
type: "turn_item.updated",
provider,
driver,
turnItem: {
id: turnItemId,
threadId: context.input.threadId,
@@ -826,7 +831,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
}
yield* emitProviderEvent({
type: "turn_item.updated",
provider,
driver,
turnItem: {
id: turnItemId,
threadId: context.input.threadId,
@@ -896,15 +901,15 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
context.tools.set(toolCall.toolCallId, toolCall);
const status = toolStatus(toolCall.status);
const now = yield* DateTime.now;
const nativeItemId = `${nativeThreadId(provider, context.input.providerThread)}:tool:${toolCall.toolCallId}`;
const nativeItemId = `${nativeThreadId(driver, context.input.providerThread)}:tool:${toolCall.toolCallId}`;
const ordinal = yield* resolveItemOrdinal(context, nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({ provider, nativeItemId });
const nodeId = idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId });
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider,
driver,
nativeItemId,
});
const nativeItemRef = {
provider,
driver,
nativeId: toolCall.toolCallId,
strength: "strong" as const,
};
@@ -914,7 +919,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const title = toolCall.title ?? null;
yield* emitProviderEvent({
type: "node.updated",
provider,
driver,
node: {
id: nodeId,
threadId: context.input.threadId,
@@ -1028,7 +1033,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
...(rawOutput === undefined ? {} : { output: rawOutput }),
};
}
yield* emitProviderEvent({ type: "turn_item.updated", provider, turnItem });
yield* emitProviderEvent({ type: "turn_item.updated", driver, turnItem });
});
const emitPlan = Effect.fnUntraced(function* (
@@ -1039,9 +1044,9 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const nativeItemId = `${context.nativeTurnId}:plan`;
const ordinal = yield* resolveItemOrdinal(context, nativeItemId);
const now = yield* DateTime.now;
const nodeId = idAllocator.derive.nodeFromProviderItem({ provider, nativeItemId });
const nodeId = idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId });
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider,
driver,
nativeItemId,
});
if (context.plan === null) {
@@ -1049,7 +1054,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
id: yield* idAllocator.allocate.plan({
threadId: context.input.threadId,
runId: context.input.runId,
provider,
driver,
}),
startedAt: now,
};
@@ -1066,7 +1071,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
: "pending",
}));
const completed = steps.length > 0 && steps.every((step) => step.status === "completed");
const nativeItemRef = { provider, nativeId: nativeItemId, strength: "weak" as const };
const nativeItemRef = { driver, nativeId: nativeItemId, strength: "weak" as const };
const plan: OrchestrationV2PlanArtifact = {
id: planId,
threadId: context.input.threadId,
@@ -1079,7 +1084,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
};
yield* emitProviderEvent({
type: "node.updated",
provider,
driver,
node: {
id: nodeId,
threadId: context.input.threadId,
@@ -1098,10 +1103,10 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
completedAt: completed ? now : null,
},
});
yield* emitProviderEvent({ type: "plan.updated", provider, plan });
yield* emitProviderEvent({ type: "plan.updated", driver, plan });
yield* emitProviderEvent({
type: "turn_item.updated",
provider,
driver,
turnItem: {
id: turnItemId,
threadId: context.input.threadId,
@@ -1138,7 +1143,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const loadingIndex = startsNew ? current.loadingIndex + 1 : current.loadingIndex;
const nativeItemId = `${notification.sessionId}:history:${role}:${loadingIndex}`;
const messageId = idAllocator.derive.messageFromProviderItem({
provider,
driver,
nativeItemId,
});
const key = String(messageId);
@@ -1249,7 +1254,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const parsed = parsePermissionRequest(params);
const nativeRequestId = params.toolCall.toolCallId;
const requestId = yield* idAllocator.allocate.runtimeRequest({
provider,
driver,
providerTurnId: context.providerTurnId,
nativeRequestId,
});
@@ -1257,7 +1262,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const now = yield* DateTime.now;
const nodeId = idAllocator.derive.approvalNode({ requestId });
const requestKind = providerRequestKind(parsed.kind);
const nativeItemRef = { provider, nativeId: nativeRequestId, strength: "weak" as const };
const nativeItemRef = { driver, nativeId: nativeRequestId, strength: "weak" as const };
const ordinal = yield* resolveItemOrdinal(
context,
`${context.nativeTurnId}:approval:${nativeRequestId}`,
@@ -1327,18 +1332,18 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
yield* emitProviderEvent({
type: "node.updated",
provider,
driver,
node,
});
yield* emitProviderEvent({
type: "runtime_request.updated",
provider,
driver,
threadId: context.input.threadId,
runtimeRequest,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider,
driver,
turnItem,
});
const resolved = yield* Deferred.await(decision).pipe(
@@ -1394,22 +1399,22 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const context = yield* activeContext;
yield* closeTextStreams(context);
const requestId = yield* idAllocator.allocate.runtimeRequest({
provider,
driver,
providerTurnId: context.providerTurnId,
nativeRequestId: request.nativeRequestId,
});
const answers = yield* Deferred.make<ProviderUserInputAnswers | null>();
const now = yield* DateTime.now;
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider,
driver,
nativeItemId: request.nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider,
driver,
nativeItemId: request.nativeItemId,
});
const nativeItemRef = {
provider,
driver,
nativeId: request.nativeItemId,
strength: "weak" as const,
};
@@ -1419,7 +1424,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
nodeId,
providerTurnId: context.providerTurnId,
nativeRequestRef: {
provider,
driver,
nativeId: request.nativeRequestId,
strength: "weak",
},
@@ -1482,18 +1487,18 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
yield* emitProviderEvent({
type: "node.updated",
provider,
driver,
node,
});
yield* emitProviderEvent({
type: "runtime_request.updated",
provider,
driver,
threadId: context.input.threadId,
runtimeRequest,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider,
driver,
turnItem,
});
return yield* Deferred.await(answers).pipe(
@@ -1534,7 +1539,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
yield* emitProviderEvent({
type: "runtime_request.updated",
provider,
driver,
threadId: request.node.threadId,
runtimeRequest: {
...request.runtimeRequest,
@@ -1544,7 +1549,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
yield* emitProviderEvent({
type: "node.updated",
provider,
driver,
node: {
...request.node,
status: "cancelled",
@@ -1553,7 +1558,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider,
driver,
turnItem: {
...request.turnItem,
status: "cancelled",
@@ -1606,7 +1611,15 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
return answers === null
? ({ action: { action: "cancel" } } as const)
: ({ action: { action: "accept", content: elicitationContent(answers) } } as const);
: ({
action: {
action: "accept",
content: elicitationContent(
answers,
new Set(Object.keys(params.requestedSchema.properties ?? {})),
),
},
} as const);
}),
);
@@ -1631,7 +1644,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
return yield* runtime.resumeSession(sessionId);
}
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: `ACP driver cannot load or resume session ${sessionId}`,
});
});
@@ -1679,7 +1692,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const createdAt = yield* DateTime.now;
const providerSession: OrchestrationV2ProviderSession = {
id: input.providerSessionId,
provider,
driver,
providerInstanceId: options.instanceId,
status: "ready",
cwd: input.runtimePolicy.cwd ?? process.cwd(),
model: input.modelSelection.model,
@@ -1699,7 +1713,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
nodeId: context.input.rootNodeId,
runAttemptId: context.input.attemptId,
nativeTurnRef: {
provider,
driver,
nativeId: context.nativeTurnId,
strength: "weak",
},
@@ -1725,13 +1739,13 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
yield* emitProviderEvent({
type: "provider_turn.updated",
provider,
driver,
threadId: context.input.threadId,
providerTurn: turn,
});
yield* emitProviderEvent({
type: "provider_thread.updated",
provider,
driver,
providerThread: {
...context.input.providerThread,
providerSessionId: input.providerSessionId,
@@ -1744,7 +1758,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
yield* emitProviderEvent({
type: "turn.terminal",
provider,
driver,
providerTurnId: context.providerTurnId,
status,
});
@@ -1761,7 +1775,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
}
if (turnInput.message.attachments.length > 0 && !supportsImagePrompts) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: "ACP driver did not negotiate image prompt support",
});
}
@@ -1772,7 +1786,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
if (path === null) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: `Invalid attachment id '${attachment.id}'`,
});
}
@@ -1780,7 +1794,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
Effect.mapError(
(cause) =>
new ProviderAdapterProtocolError({
provider,
driver,
detail: `Failed to read attachment '${attachment.id}'`,
payload: cause,
}),
@@ -1794,7 +1808,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
}
if (prompt.length === 0) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: "ACP turn requires non-empty text or attachments",
});
}
@@ -1806,11 +1820,11 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const existing = yield* Ref.get(activeTurn);
if (existing !== null) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: `ACP provider turn ${existing.providerTurnId} is still active`,
});
}
const requestedSessionId = nativeThreadId(provider, turnInput.providerThread);
const requestedSessionId = nativeThreadId(driver, turnInput.providerThread);
if ((yield* Ref.get(activeSessionId)) !== requestedSessionId) {
const activated = yield* activateSession(requestedSessionId);
yield* Ref.set(activeSessionId, activated.sessionId);
@@ -1819,7 +1833,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const prompt = yield* resolvePromptParts(turnInput);
const startedAt = yield* DateTime.now;
const nativeTurnId = `${requestedSessionId}:turn:${turnInput.providerTurnOrdinal}`;
const providerTurnId = idAllocator.derive.providerTurn({ provider, nativeTurnId });
const providerTurnId = idAllocator.derive.providerTurn({ driver, nativeTurnId });
const completed = yield* Deferred.make<void, never>();
const context: ActiveAcpTurn = {
input: turnInput,
@@ -1844,13 +1858,13 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
yield* emitProviderEvent({
type: "provider_turn.updated",
provider,
driver,
threadId: turnInput.threadId,
providerTurn: runningTurn,
});
yield* emitProviderEvent({
type: "provider_thread.updated",
provider,
driver,
providerThread: {
...turnInput.providerThread,
providerSessionId: input.providerSessionId,
@@ -1886,7 +1900,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
finalizeTurn(context, context.interrupted ? "interrupted" : "failed").pipe(
Effect.andThen(
Effect.logWarning("orchestration-v2.acp-prompt-failed", {
provider,
driver,
providerSessionId: input.providerSessionId,
providerThreadId: turnInput.providerThread.id,
providerTurnId,
@@ -1903,7 +1917,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
Effect.mapError(
(cause) =>
new ProviderAdapterTurnStartError({
provider,
driver,
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
runId: turnInput.runId,
@@ -1937,7 +1951,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const sessionRuntime: ProviderAdapterV2SessionRuntime = {
instanceId: options.instanceId,
provider,
driver,
providerSessionId: input.providerSessionId,
providerSession,
rawEvents: Stream.fromEffectRepeat(Queue.take(rawEvents)),
@@ -1948,12 +1962,13 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const sessionId = yield* Ref.get(activeSessionId);
if (sessionId === null) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: "ACP runtime did not produce a session id",
});
}
return makeProviderThread({
provider,
driver,
providerInstanceId: options.instanceId,
idAllocator,
appThreadId: threadInput.threadId,
providerSessionId: input.providerSessionId,
@@ -1966,7 +1981,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
Effect.mapError(
(cause) =>
new ProviderAdapterEnsureThreadError({
provider,
driver,
threadId: threadInput.threadId,
cause,
}),
@@ -1975,7 +1990,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
),
resumeThread: Effect.fn("AcpAdapterV2.resumeThread")(
function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) {
const sessionId = nativeThreadId(provider, threadInput.providerThread);
const sessionId = nativeThreadId(driver, threadInput.providerThread);
if ((yield* Ref.get(activeSessionId)) !== sessionId) {
yield* Ref.set(snapshot, {
order: [],
@@ -2000,7 +2015,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
Effect.mapError(
(cause) =>
new ProviderAdapterResumeThreadError({
provider,
driver,
providerSessionId: input.providerSessionId,
providerThreadId: threadInput.providerThread.id,
cause,
@@ -2012,7 +2027,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
steerTurn: (turnInput) =>
Effect.fail(
new ProviderAdapterSteerRunUnsupportedError({
provider,
driver,
providerThreadId: turnInput.providerThread.id,
}),
),
@@ -2021,7 +2036,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const context = yield* Ref.get(activeTurn);
if (context?.providerTurnId !== turnInput.providerTurnId) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: `ACP provider turn ${turnInput.providerTurnId} is not active`,
});
}
@@ -2032,7 +2047,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
);
if (Option.isNone(stopped)) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: `ACP provider turn ${turnInput.providerTurnId} did not acknowledge cancellation before the interrupt timeout`,
});
}
@@ -2042,7 +2057,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
Effect.mapError(
(cause) =>
new ProviderAdapterInterruptError({
provider,
driver,
providerThreadId: turnInput.providerThread.id,
providerTurnId: turnInput.providerTurnId,
cause,
@@ -2057,7 +2072,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
);
if (pending === undefined) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: `No pending ACP runtime request ${requestInput.requestId}`,
});
}
@@ -2067,7 +2082,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
}
if (requestInput.decision === undefined) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: `ACP approval request ${requestInput.requestId} requires a decision`,
});
}
@@ -2076,7 +2091,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
Effect.mapError(
(cause) =>
new ProviderAdapterRuntimeRequestResponseError({
provider,
driver,
requestId: requestInput.requestId,
cause,
}),
@@ -2084,11 +2099,11 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
),
readThreadSnapshot: Effect.fn("AcpAdapterV2.readThreadSnapshot")(
function* (snapshotInput) {
const sessionId = nativeThreadId(provider, snapshotInput.providerThread);
const sessionId = nativeThreadId(driver, snapshotInput.providerThread);
if ((yield* Ref.get(activeSessionId)) !== sessionId) {
if (!capabilities.threads.canReadThreadSnapshot) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: "ACP driver does not support session/load snapshots",
});
}
@@ -2124,7 +2139,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
Effect.mapError(
(cause) =>
new ProviderAdapterReadThreadSnapshotError({
provider,
driver,
providerThreadId: snapshotInput.providerThread.id,
cause,
}),
@@ -2134,7 +2149,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
rollbackThread: (rollbackInput) =>
Effect.fail(
new ProviderAdapterRollbackThreadError({
provider,
driver,
providerThreadId: rollbackInput.providerThread.id,
checkpointId: rollbackInput.target.checkpointId,
cause: "ACP does not define conversation rollback.",
@@ -2144,22 +2159,23 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
function* (forkInput) {
if (!capabilities.threads.canForkThread) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: "ACP driver did not negotiate session/fork",
});
}
if (forkInput.providerTurnId !== undefined) {
return yield* new ProviderAdapterProtocolError({
provider,
driver,
detail: "ACP session/fork can only fork the current session head",
});
}
const sourceSessionId = nativeThreadId(provider, forkInput.sourceProviderThread);
const sourceSessionId = nativeThreadId(driver, forkInput.sourceProviderThread);
const forked = yield* runtime.forkSession(sourceSessionId);
yield* Ref.set(activeSessionId, forked.sessionId);
const now = yield* DateTime.now;
return makeProviderThread({
provider,
driver,
providerInstanceId: options.instanceId,
idAllocator,
appThreadId: forkInput.targetThreadId,
providerSessionId: input.providerSessionId,
@@ -2181,7 +2197,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
Effect.mapError(
(cause) =>
new ProviderAdapterForkThreadError({
provider,
driver,
providerThreadId: forkInput.sourceProviderThread.id,
cause,
}),
@@ -2196,7 +2212,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
Effect.mapError(
(cause) =>
new ProviderAdapterOpenSessionError({
provider,
driver,
providerSessionId: input.providerSessionId,
cause,
}),
@@ -148,7 +148,7 @@ describe("AcpRegistryAdapterV2", () => {
runtimePolicy,
});
assert.equal(runtime.providerSession.provider, "acpRegistry");
assert.equal(runtime.providerSession.driver, "acpRegistry");
assert.equal(providerThread.nativeThreadRef?.nativeId, "mock-session-1");
assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot);
assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread);
@@ -80,7 +80,7 @@ export const AcpRegistryOrchestratorReplayHarness: OrchestratorV2ProviderReplayH
AcpReplayTranscript,
AcpReplayTranscriptDecodeError
> = {
provider: ACP_REGISTRY_PROVIDER,
driver: ACP_REGISTRY_PROVIDER,
decodeTranscript: (transcript) =>
decodeAcpReplayTranscript(transcript, ACP_REGISTRY_PROVIDER, {
retargetProvider: true,
@@ -37,8 +37,8 @@ import {
type AcpAdapterV2RuntimeInput,
} from "./AcpAdapterV2.ts";
export const ACP_REGISTRY_PROVIDER = "acpRegistry" as const;
export const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make(ACP_REGISTRY_PROVIDER);
export const ACP_REGISTRY_PROVIDER = ProviderDriverKind.make("acpRegistry");
export const ACP_REGISTRY_DRIVER_KIND = ACP_REGISTRY_PROVIDER;
export const ACP_REGISTRY_DEFAULT_INSTANCE_ID =
defaultInstanceIdForDriver(ACP_REGISTRY_DRIVER_KIND);
@@ -92,7 +92,7 @@ function makeAcpRegistryRuntime(options: AcpRegistryAdapterV2Options) {
export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) {
const flavor: AcpAdapterV2Flavor = {
provider: ACP_REGISTRY_PROVIDER,
driver: ACP_REGISTRY_PROVIDER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(options),
...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
@@ -357,7 +357,7 @@ describe("ClaudeAdapterV2 native fork", () => {
nodeId: NodeId.make("node-claude-source"),
runAttemptId: RunAttemptId.make("run-attempt-claude-source"),
nativeTurnRef: {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: "assistant-message-cursor",
strength: "weak",
},
@@ -393,7 +393,7 @@ describe("ClaudeAdapterV2 native fork", () => {
id: targetThreadId,
projectId: ProjectId.make("project-claude-fork-target"),
title: "Claude fork target",
defaultProvider: ProviderInstanceId.make(CLAUDE_PROVIDER),
providerInstanceId: ProviderInstanceId.make(CLAUDE_PROVIDER),
modelSelection: {
instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER),
model: "claude-sonnet-4-6",
@@ -53,7 +53,7 @@ type ClaudeAgentSdkReplayTranscript = typeof ClaudeAgentSdkReplayTranscript.Type
export class ClaudeReplayTranscriptDecodeError extends Schema.TaggedErrorClass<ClaudeReplayTranscriptDecodeError>()(
"ClaudeReplayTranscriptDecodeError",
{
provider: Schema.optional(Schema.String),
driver: Schema.optional(Schema.String),
protocol: Schema.optional(Schema.String),
scenario: Schema.optional(Schema.String),
cause: Schema.Defect(),
@@ -2359,7 +2359,7 @@ export const ClaudeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarnes
ClaudeAgentSdkReplayTranscript,
ClaudeAgentSdkReplayError
> = {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
decodeTranscript: (transcript) =>
Schema.decodeUnknownEffect(ClaudeAgentSdkReplayTranscript)(transcript).pipe(
Effect.mapError(
@@ -96,9 +96,9 @@ import {
subagentThreadTitle,
} from "../SubagentProjection.ts";
export const CLAUDE_PROVIDER = "claudeAgent" as const;
export const CLAUDE_PROVIDER = ProviderDriverKind.make("claudeAgent");
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_DRIVER_KIND = CLAUDE_PROVIDER;
export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_DRIVER_KIND);
const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({});
@@ -674,13 +674,15 @@ export function claudeMcpQueryOverrides(input: {
function providerSession(input: {
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
readonly providerInstanceId: ProviderInstanceId;
readonly cwd: string | null;
readonly model: string;
readonly now: DateTime.Utc;
}): OrchestrationV2ProviderSession {
return {
id: input.providerSessionId,
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerInstanceId: input.providerInstanceId,
status: "ready",
cwd: input.cwd ?? process.cwd(),
model: input.model,
@@ -721,6 +723,7 @@ function resultTextFromSdkMessage(
function makeProviderThread(input: {
readonly idAllocator: IdAllocatorV2Shape;
readonly providerInstanceId: ProviderInstanceId;
readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"];
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
@@ -730,15 +733,16 @@ function makeProviderThread(input: {
}): OrchestrationV2ProviderThread {
return {
id: input.idAllocator.derive.providerThread({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeThreadId: input.nativeThreadId,
}),
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
appThreadId: input.appThreadId,
ownerNodeId: input.ownerNodeId ?? null,
nativeThreadRef: {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: input.nativeThreadId,
strength: "strong",
},
@@ -759,7 +763,7 @@ const getNativeThreadId = Effect.fnUntraced(function* (
const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
if (nativeThreadId === undefined || nativeThreadId === null) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Provider thread ${providerThread.id} is missing a native Claude session id.`,
});
}
@@ -781,15 +785,15 @@ const getNativeConversationHeadId = Effect.fnUntraced(function* (
if (nativeHeadRef === null) {
return undefined;
}
if (nativeHeadRef.provider !== CLAUDE_PROVIDER) {
if (nativeHeadRef.driver !== CLAUDE_PROVIDER) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Provider thread ${providerThread.id} has a non-Claude native conversation head reference.`,
});
}
if (nativeHeadRef.nativeId === null) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Provider thread ${providerThread.id} has a Claude native conversation head reference without a native id.`,
});
}
@@ -808,7 +812,7 @@ const resolveClaudeForkUpToMessageId = Effect.fn("ClaudeAdapterV2.resolveForkUpT
const boundaryIndex = sourceTurns.findIndex((turn) => turn.id === input.providerTurnId);
if (boundaryIndex < 0) {
return yield* new ProviderAdapterForkThreadError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThreadId: input.sourceProviderThread.id,
cause: `Cannot fork Claude thread from provider turn ${input.providerTurnId}: source turn was not found in provider thread ${input.sourceProviderThread.id}.`,
});
@@ -831,7 +835,7 @@ const resolveClaudeForkUpToMessageId = Effect.fn("ClaudeAdapterV2.resolveForkUpT
}
return yield* new ProviderAdapterForkThreadError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThreadId: input.sourceProviderThread.id,
cause: `Cannot fork Claude thread from prior provider turn ${input.providerTurnId}: no SDK assistant message cursor was recorded for that turn.`,
});
@@ -848,7 +852,7 @@ const resolveClaudeRollbackResumeSessionAt = Effect.fn(
const target = input.target;
if (target.providerTurn.providerThreadId !== input.providerThread.id) {
return yield* new ProviderAdapterRollbackThreadError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThreadId: input.providerThread.id,
cause: `Cannot roll back Claude thread ${input.providerThread.id} to provider turn ${target.providerTurn.id}: target turn belongs to provider thread ${target.providerTurn.providerThreadId}.`,
});
@@ -857,7 +861,7 @@ const resolveClaudeRollbackResumeSessionAt = Effect.fn(
const nativeTurnRef = target.providerTurn.nativeTurnRef;
if (
nativeTurnRef !== null &&
nativeTurnRef.provider === CLAUDE_PROVIDER &&
nativeTurnRef.driver === CLAUDE_PROVIDER &&
nativeTurnRef.nativeId !== null &&
!isSyntheticClaudeTurnId(nativeTurnRef.nativeId)
) {
@@ -872,7 +876,7 @@ const resolveClaudeRollbackResumeSessionAt = Effect.fn(
}
return yield* new ProviderAdapterRollbackThreadError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThreadId: input.providerThread.id,
cause: `Cannot roll back Claude thread ${input.providerThread.id} to provider turn ${target.providerTurn.id}: no SDK assistant message cursor was recorded for that turn.`,
});
@@ -1553,19 +1557,19 @@ function buildAssistantArtifacts(input: {
readonly turnItem: OrchestrationV2TurnItem;
} {
const nodeId = input.idAllocator.derive.nodeFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: input.nativeItemId,
});
const messageId = input.idAllocator.derive.messageFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: input.nativeItemId,
});
const turnItemId = input.idAllocator.derive.turnItemFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: input.nativeItemId,
});
const nativeItemRef = {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: input.nativeItemId,
strength: "strong" as const,
};
@@ -1694,7 +1698,7 @@ export function makeClaudeAdapterV2(
return ProviderAdapterV2.of({
instanceId: adapterOptions.instanceId,
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2),
openSession: Effect.fn("ClaudeAdapterV2.openSession")(
function* (input: ProviderAdapterV2OpenSessionInput) {
@@ -1702,6 +1706,7 @@ export function makeClaudeAdapterV2(
const now = yield* DateTime.now;
const session = providerSession({
providerSessionId: input.providerSessionId,
providerInstanceId: adapterOptions.instanceId,
cwd: input.runtimePolicy.cwd,
model: input.modelSelection.model,
now,
@@ -1758,7 +1763,7 @@ export function makeClaudeAdapterV2(
nodeId: input.context.input.rootNodeId,
runAttemptId: input.context.input.attemptId,
nativeTurnRef: {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: input.context.nativeMessageCursor ?? input.context.nativeTurnId,
strength: "weak",
},
@@ -1789,15 +1794,15 @@ export function makeClaudeAdapterV2(
}) => {
const completedAt = input.status === "running" ? null : input.updatedAt;
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: input.nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: input.nativeItemId,
});
const nativeItemRef = {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: input.nativeItemId,
strength: "strong" as const,
};
@@ -1898,12 +1903,12 @@ export function makeClaudeAdapterV2(
}) {
yield* emitProviderEvent({
type: "node.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
turnItem: artifacts.turnItem,
});
});
@@ -1934,19 +1939,19 @@ export function makeClaudeAdapterV2(
const nodeId =
existingSubagent?.task.id ??
idAllocator.derive.nodeFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId,
});
const childRootNodeId =
existingSubagent?.childRootNodeId ??
idAllocator.derive.nodeFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: `${nativeItemId}:thread-root`,
});
const childThreadId =
existingSubagent?.childThreadId ??
idAllocator.derive.threadFromProviderThread({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeThreadId: `${input.context.input.providerThread.id}:${input.taskId}`,
});
if (existingSubagent === undefined) {
@@ -1963,11 +1968,12 @@ export function makeClaudeAdapterV2(
parentNodeId: input.context.input.rootNodeId,
origin: "provider_native" as const,
createdBy: "agent" as const,
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerInstanceId: input.context.input.modelSelection.instanceId,
providerThreadId: null,
childThreadId,
nativeTaskRef: {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: input.taskId,
strength: "strong" as const,
},
@@ -1991,7 +1997,7 @@ export function makeClaudeAdapterV2(
turnItemId:
existingSubagent?.turnItemId ??
idAllocator.derive.turnItemFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: `${nativeItemId}:subagent`,
}),
turnItemOrdinal,
@@ -2023,14 +2029,14 @@ export function makeClaudeAdapterV2(
});
yield* emitProviderEvent({
type: "app_thread.created",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
appThread: childThread,
});
}
yield* emitProviderEvent({
type: "node.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
node: {
id: nodeId,
threadId: input.context.input.threadId,
@@ -2043,7 +2049,7 @@ export function makeClaudeAdapterV2(
providerThreadId: input.context.input.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: input.taskId,
strength: "strong",
},
@@ -2055,7 +2061,7 @@ export function makeClaudeAdapterV2(
});
yield* emitProviderEvent({
type: "node.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
node: {
id: childRootNodeId,
threadId: childThreadId,
@@ -2078,11 +2084,11 @@ export function makeClaudeAdapterV2(
const promptNativeItemId = `${nativeItemId}:prompt`;
const promptArtifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: promptNativeItemId,
}),
turnItemId: idAllocator.derive.turnItemFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: promptNativeItemId,
}),
threadId: childThreadId,
@@ -2090,7 +2096,7 @@ export function makeClaudeAdapterV2(
providerThreadId: null,
providerTurnId: null,
nativeItemRef: {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: promptNativeItemId,
strength: "strong",
},
@@ -2101,23 +2107,23 @@ export function makeClaudeAdapterV2(
});
yield* emitProviderEvent({
type: "message.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
message: promptArtifacts.message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
turnItem: promptArtifacts.turnItem,
});
}
yield* emitProviderEvent({
type: "subagent.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
subagent: task,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
turnItem: {
id: subagent.turnItemId,
threadId: task.threadId,
@@ -2136,7 +2142,8 @@ export function makeClaudeAdapterV2(
type: "subagent",
subagentId: task.id,
origin: task.origin,
provider: task.provider,
driver: task.driver,
providerInstanceId: task.providerInstanceId,
childThreadId: task.childThreadId,
prompt: task.prompt,
result: task.result,
@@ -2153,11 +2160,11 @@ export function makeClaudeAdapterV2(
subagent.resultItemOrdinal = resultItemOrdinal;
const resultArtifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: resultNativeItemId,
}),
turnItemId: idAllocator.derive.turnItemFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: resultNativeItemId,
}),
threadId: childThreadId,
@@ -2165,7 +2172,7 @@ export function makeClaudeAdapterV2(
providerThreadId: null,
providerTurnId: null,
nativeItemRef: {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: resultNativeItemId,
strength: "strong",
},
@@ -2176,12 +2183,12 @@ export function makeClaudeAdapterV2(
});
yield* emitProviderEvent({
type: "message.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
message: resultArtifacts.message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
turnItem: resultArtifacts.turnItem,
});
}
@@ -2255,7 +2262,7 @@ export function makeClaudeAdapterV2(
}) {
const createdAt = yield* DateTime.now;
const requestId = yield* idAllocator.allocate.runtimeRequest({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerTurnId: input.context.providerTurnId,
nativeRequestId: input.nativeRequestId,
});
@@ -2263,7 +2270,7 @@ export function makeClaudeAdapterV2(
const providerSessionId = input.context.input.providerThread.providerSessionId;
if (providerSessionId === null) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Provider thread ${input.context.input.providerThread.id} is missing a provider session id.`,
});
}
@@ -2272,7 +2279,7 @@ export function makeClaudeAdapterV2(
`${input.nativeItemId}:approval:${input.nativeRequestId}`,
);
const nativeItemRef = {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: input.nativeRequestId,
strength: "strong" as const,
};
@@ -2281,7 +2288,7 @@ export function makeClaudeAdapterV2(
threadId: input.context.input.threadId,
runId: input.context.input.runId,
parentNodeId: idAllocator.derive.nodeFromProviderItem({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeItemId: input.nativeItemId,
}),
rootNodeId: input.context.input.rootNodeId,
@@ -2301,7 +2308,7 @@ export function makeClaudeAdapterV2(
nodeId,
providerTurnId: input.context.providerTurnId,
nativeRequestRef: {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: input.nativeRequestId,
strength: "strong",
},
@@ -2385,17 +2392,17 @@ export function makeClaudeAdapterV2(
[
emitProviderEvent({
type: "node.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
node: artifacts.node,
}),
emitProviderEvent({
type: "message.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
message: artifacts.message,
}),
emitProviderEvent({
type: "turn_item.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
turnItem: artifacts.turnItem,
}),
],
@@ -2407,7 +2414,7 @@ export function makeClaudeAdapterV2(
[
emitProviderEvent({
type: "provider_turn.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerTurn: providerTurnPayload({
context: input.context,
status: input.status,
@@ -2419,7 +2426,7 @@ export function makeClaudeAdapterV2(
? [
emitProviderEvent({
type: "provider_thread.updated" as const,
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThread: {
...input.context.input.providerThread,
providerSessionId: session.id,
@@ -2436,7 +2443,7 @@ export function makeClaudeAdapterV2(
: []),
emitProviderEvent({
type: "turn.terminal",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerTurnId: input.context.providerTurnId,
status: input.status,
}),
@@ -2672,17 +2679,17 @@ export function makeClaudeAdapterV2(
[
emitProviderEvent({
type: "node.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
node: artifacts.node,
}),
emitProviderEvent({
type: "runtime_request.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
runtimeRequest: artifacts.request,
}),
emitProviderEvent({
type: "turn_item.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
turnItem: artifacts.turnItem,
}),
],
@@ -2813,14 +2820,14 @@ export function makeClaudeAdapterV2(
const nativeThreadId = yield* getNativeThreadId(turnInput.providerThread);
const nativeTurnId = `turn:${turnInput.attemptId}`;
const providerTurnId = idAllocator.derive.providerTurn({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeTurnId,
});
const providerTurnOrdinal = turnInput.providerTurnOrdinal;
const currentTurn = yield* Ref.get(activeTurn);
if (currentTurn !== null) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Claude provider turn ${currentTurn.providerTurnId} is still active.`,
});
}
@@ -2844,7 +2851,7 @@ export function makeClaudeAdapterV2(
yield* Ref.set(activeTurn, context);
yield* emitProviderEvent({
type: "provider_turn.updated",
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerTurn: providerTurnPayload({
context,
status: "running",
@@ -2860,7 +2867,7 @@ export function makeClaudeAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterTurnStartError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
runId: turnInput.runId,
@@ -2875,14 +2882,14 @@ export function makeClaudeAdapterV2(
const existing = yield* Ref.get(queryContext);
if (existing === null) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Claude provider thread ${turnInput.providerThread.id} has no live query.`,
});
}
const currentTurn = yield* Ref.get(activeTurn);
if (currentTurn?.providerTurnId !== turnInput.providerTurnId) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`,
});
}
@@ -2921,7 +2928,7 @@ export function makeClaudeAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterInterruptError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThreadId: turnInput.providerThread.id,
providerTurnId: turnInput.providerTurnId,
cause,
@@ -2935,14 +2942,14 @@ export function makeClaudeAdapterV2(
const existing = yield* Ref.get(queryContext);
if (existing === null) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Claude provider thread ${turnInput.providerThread.id} has no live query.`,
});
}
const currentTurn = yield* Ref.get(activeTurn);
if (currentTurn?.providerTurnId !== turnInput.providerTurnId) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`,
});
}
@@ -2960,7 +2967,7 @@ export function makeClaudeAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterSteerRunError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThreadId: turnInput.providerThread.id,
providerTurnId: turnInput.providerTurnId,
cause,
@@ -3012,7 +3019,7 @@ export function makeClaudeAdapterV2(
const runtime: ProviderAdapterV2SessionRuntime = {
instanceId: adapterOptions.instanceId,
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerSessionId: input.providerSessionId,
providerSession: session,
rawEvents: Stream.empty,
@@ -3023,6 +3030,7 @@ export function makeClaudeAdapterV2(
const nativeThreadId = yield* queryRunner.allocateSessionId;
return makeProviderThread({
idAllocator,
providerInstanceId: adapterOptions.instanceId,
appThreadId: threadInput.threadId,
providerSessionId: input.providerSessionId,
nativeThreadId,
@@ -3034,7 +3042,7 @@ export function makeClaudeAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterEnsureThreadError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
threadId: threadInput.threadId,
cause,
}),
@@ -3056,7 +3064,7 @@ export function makeClaudeAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterResumeThreadError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerSessionId: input.providerSessionId,
providerThreadId: threadInput.providerThread.id,
cause,
@@ -3074,20 +3082,20 @@ export function makeClaudeAdapterV2(
);
if (pending === undefined) {
return yield* new ProviderAdapterRuntimeRequestResponseError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
requestId: requestInput.requestId,
cause: new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `No pending Claude runtime request ${requestInput.requestId}.`,
}),
});
}
if (requestInput.decision === undefined) {
return yield* new ProviderAdapterRuntimeRequestResponseError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
requestId: requestInput.requestId,
cause: new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Claude ${pending.requestKind} request ${requestInput.requestId} requires an approval decision.`,
}),
});
@@ -3100,7 +3108,7 @@ export function makeClaudeAdapterV2(
Schema.is(ProviderAdapterRuntimeRequestResponseError)(cause)
? cause
: new ProviderAdapterRuntimeRequestResponseError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
requestId: requestInput.requestId,
cause,
}),
@@ -3110,7 +3118,7 @@ export function makeClaudeAdapterV2(
readThreadSnapshot: (snapshotInput) =>
Effect.fail(
new ProviderAdapterReadThreadSnapshotError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThreadId: snapshotInput.providerThread.id,
cause: "Claude V2 adapter does not implement snapshots.",
}),
@@ -3120,7 +3128,7 @@ export function makeClaudeAdapterV2(
const currentTurn = yield* Ref.get(activeTurn);
if (currentTurn !== null) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Cannot roll back Claude provider thread ${rollbackInput.providerThread.id} while provider turn ${currentTurn.providerTurnId} is active.`,
});
}
@@ -3135,6 +3143,7 @@ export function makeClaudeAdapterV2(
providerThread: {
...makeProviderThread({
idAllocator,
providerInstanceId: adapterOptions.instanceId,
appThreadId: rollbackInput.providerThread.appThreadId,
...(rollbackInput.providerThread.ownerNodeId === null
? {}
@@ -3163,7 +3172,7 @@ export function makeClaudeAdapterV2(
resumeSessionAt === null
? null
: {
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
nativeId: resumeSessionAt,
strength: "weak" as const,
},
@@ -3182,7 +3191,7 @@ export function makeClaudeAdapterV2(
Schema.is(ProviderAdapterRollbackThreadError)(cause)
? cause
: new ProviderAdapterRollbackThreadError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThreadId: rollbackInput.providerThread.id,
cause,
}),
@@ -3194,7 +3203,7 @@ export function makeClaudeAdapterV2(
const currentTurn = yield* Ref.get(activeTurn);
if (currentTurn !== null) {
return yield* new ProviderAdapterProtocolError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
detail: `Cannot fork Claude provider thread ${forkInput.sourceProviderThread.id} while provider turn ${currentTurn.providerTurnId} is active.`,
});
}
@@ -3220,6 +3229,7 @@ export function makeClaudeAdapterV2(
const now = yield* DateTime.now;
return makeProviderThread({
idAllocator,
providerInstanceId: adapterOptions.instanceId,
appThreadId: forkInput.targetThreadId,
ownerNodeId: forkInput.ownerNodeId ?? null,
providerSessionId: input.providerSessionId,
@@ -3238,7 +3248,7 @@ export function makeClaudeAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterForkThreadError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerThreadId: forkInput.sourceProviderThread.id,
cause,
}),
@@ -3254,7 +3264,7 @@ export function makeClaudeAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterOpenSessionError({
provider: CLAUDE_PROVIDER,
driver: CLAUDE_PROVIDER,
providerSessionId: input.providerSessionId,
cause,
}),
@@ -22,6 +22,7 @@ import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
import {
buildCodexTurnStartParams,
CODEX_DRIVER_KIND,
codexAppServerMcpLaunchConfig,
makeCodexAppServerProtocolLogger,
makeCodexAppServerSpawnCommand,
@@ -284,12 +285,13 @@ describe("CodexAdapterV2 rollback mapping", () => {
const providerThreadId = ProviderThreadId.make("provider-thread-codex-rollback");
const providerThread: OrchestrationV2ProviderThread = {
id: providerThreadId,
provider: "codex",
driver: CODEX_DRIVER_KIND,
providerInstanceId: ProviderInstanceId.make("codex"),
providerSessionId: ProviderSessionId.make("provider-session-codex-rollback"),
appThreadId: ThreadId.make("thread-codex-rollback"),
ownerNodeId: null,
nativeThreadRef: {
provider: "codex",
driver: CODEX_DRIVER_KIND,
nativeId: "native-thread-codex-rollback",
strength: "strong",
},
@@ -312,7 +314,7 @@ describe("CodexAdapterV2 rollback mapping", () => {
nodeId: NodeId.make(`node-${id}`),
runAttemptId: RunAttemptId.make(`run-attempt-${id}`),
nativeTurnRef: {
provider: "codex",
driver: CODEX_DRIVER_KIND,
nativeId: `native-${id}`,
strength: "strong",
},
@@ -19,7 +19,7 @@ import { CodexAppServerClientFactory, layer as codexAdapterLayer } from "./Codex
export class CodexReplayTranscriptDecodeError extends Schema.TaggedErrorClass<CodexReplayTranscriptDecodeError>()(
"CodexReplayTranscriptDecodeError",
{
provider: Schema.optional(Schema.String),
driver: Schema.optional(Schema.String),
protocol: Schema.optional(Schema.String),
scenario: Schema.optional(Schema.String),
cause: Schema.Defect(),
@@ -142,7 +142,7 @@ export function makeCodexProviderAdapterRegistryReplayLayer(input: {
Effect.mapError(
(cause) =>
new ProviderAdapterOpenSessionError({
provider: "codex",
driver: CODEX_DRIVER_KIND,
providerSessionId: openInput.providerSessionId,
cause,
}),
@@ -182,7 +182,7 @@ export const CodexOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness
CodexReplay.CodexAppServerReplayTranscript,
CodexOrchestratorReplayHarnessError
> = {
provider: "codex",
driver: CODEX_DRIVER_KIND,
decodeTranscript: (transcript) =>
Schema.decodeUnknownEffect(CodexReplay.CodexAppServerReplayTranscript)(transcript).pipe(
Effect.mapError(
File diff suppressed because it is too large. Load diff
@@ -58,7 +58,7 @@ const decodeCursorAgentSdkReplayTranscript = Schema.decodeUnknownEffect(
export class CursorReplayTranscriptDecodeError extends Schema.TaggedErrorClass<CursorReplayTranscriptDecodeError>()(
"CursorReplayTranscriptDecodeError",
{
provider: Schema.optional(Schema.String),
driver: Schema.optional(Schema.String),
protocol: Schema.optional(Schema.String),
scenario: Schema.optional(Schema.String),
cause: Schema.Defect(),
@@ -628,7 +628,7 @@ export const CursorOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarnes
CursorAgentSdkReplayTranscript,
CursorOrchestratorReplayHarnessError
> = {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
decodeTranscript: (transcript) =>
decodeCursorAgentSdkReplayTranscript(transcript).pipe(
Effect.mapError(
@@ -24,7 +24,6 @@ import {
type OrchestrationV2ProviderTurn,
type OrchestrationV2Subagent,
type OrchestrationV2TurnItem,
ProviderDriverKind,
type ProviderInstanceId,
type ThreadId,
} from "@t3tools/contracts";
@@ -87,7 +86,7 @@ import {
export { CURSOR_PROVIDER } from "./CursorAgentSdk.ts";
export const CURSOR_DRIVER_KIND = ProviderDriverKind.make(CURSOR_PROVIDER);
export const CURSOR_DRIVER_KIND = CURSOR_PROVIDER;
export const CURSOR_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CURSOR_DRIVER_KIND);
const DEFAULT_CURSOR_SETTINGS = Schema.decodeSync(CursorSettings)({});
@@ -241,13 +240,15 @@ export function cursorMcpServers(threadId: ThreadId): Record<string, McpServerCo
function providerSession(input: {
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
readonly providerInstanceId: ProviderInstanceId;
readonly cwd: string | null;
readonly model: string;
readonly now: DateTime.Utc;
}): OrchestrationV2ProviderSession {
return {
id: input.providerSessionId,
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerInstanceId: input.providerInstanceId,
status: "ready",
cwd: input.cwd ?? process.cwd(),
model: input.model,
@@ -260,6 +261,7 @@ function providerSession(input: {
function makeProviderThread(input: {
readonly idAllocator: IdAllocatorV2Shape;
readonly providerInstanceId: ProviderInstanceId;
readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
readonly nativeThreadId: string;
@@ -269,15 +271,16 @@ function makeProviderThread(input: {
}): OrchestrationV2ProviderThread {
return {
id: input.idAllocator.derive.providerThread({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeThreadId: input.nativeThreadId,
}),
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
appThreadId: input.appThreadId,
ownerNodeId: input.ownerNodeId ?? null,
nativeThreadRef: {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: input.nativeThreadId,
strength: "strong",
},
@@ -296,7 +299,7 @@ function nativeThreadId(providerThread: OrchestrationV2ProviderThread): string {
const id = providerThread.nativeThreadRef?.nativeId;
if (id === null || id === undefined) {
throw new ProviderAdapterProtocolError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
detail: `Provider thread ${providerThread.id} is missing its Cursor agent id.`,
});
}
@@ -826,7 +829,7 @@ export function makeCursorAdapterV2(
return ProviderAdapterV2.of({
instanceId: adapterOptions.instanceId,
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
getCapabilities: () => Effect.succeed(CursorProviderCapabilitiesV2),
openSession: Effect.fn("CursorAdapterV2.openSession")(
function* (input: ProviderAdapterV2OpenSessionInput) {
@@ -834,6 +837,7 @@ export function makeCursorAdapterV2(
const createdAt = yield* DateTime.now;
const session = providerSession({
providerSessionId: input.providerSessionId,
providerInstanceId: adapterOptions.instanceId,
cwd: input.runtimePolicy.cwd,
model: input.modelSelection.model,
now: createdAt,
@@ -882,7 +886,7 @@ export function makeCursorAdapterV2(
const planId = yield* idAllocator.allocate.plan({
threadId: context.input.threadId,
runId: context.input.runId,
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
});
yield* Ref.update(planIds, (current) => {
const updated = new Map(current);
@@ -912,25 +916,25 @@ export function makeCursorAdapterV2(
const now = yield* DateTime.now;
const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: segment.nativeItemId,
});
const messageId = idAllocator.derive.messageFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: segment.nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: segment.nativeItemId,
});
const nativeItemRef = {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: segment.nativeItemId,
strength: "weak" as const,
};
yield* emitProviderEvent({
type: "node.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
node: {
id: nodeId,
threadId: context.input.threadId,
@@ -951,7 +955,7 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "message.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
message: {
createdBy: "agent",
creationSource: "provider",
@@ -969,7 +973,7 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
turnItem: {
id: turnItemId,
threadId: context.input.threadId,
@@ -1004,21 +1008,21 @@ export function makeCursorAdapterV2(
const now = yield* DateTime.now;
const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: segment.nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: segment.nativeItemId,
});
const nativeItemRef = {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: segment.nativeItemId,
strength: "weak" as const,
};
yield* emitProviderEvent({
type: "node.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
node: {
id: nodeId,
threadId: context.input.threadId,
@@ -1039,7 +1043,7 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
turnItem: {
id: turnItemId,
threadId: context.input.threadId,
@@ -1105,15 +1109,15 @@ export function makeCursorAdapterV2(
const failed = input.completed && cursorToolFailed(toolCall);
const status = input.completed ? (failed ? "failed" : "completed") : "running";
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: active.callId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: active.callId,
});
const nativeItemRef = {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: active.callId,
strength: "strong" as const,
};
@@ -1236,12 +1240,12 @@ export function makeCursorAdapterV2(
}
yield* emitProviderEvent({
type: "node.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
turnItem,
});
});
@@ -1282,16 +1286,16 @@ export function makeCursorAdapterV2(
const planId = yield* resolvePlanId(input.context, nativeItemId);
const ordinal = yield* resolveItemOrdinal(input.context, nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId,
});
const status = input.failed ? "failed" : input.completed ? "completed" : "running";
const nativeItemRef = {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: input.callId,
strength: "strong" as const,
};
@@ -1306,7 +1310,7 @@ export function makeCursorAdapterV2(
};
yield* emitProviderEvent({
type: "node.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
node: {
id: nodeId,
threadId: input.context.input.threadId,
@@ -1327,12 +1331,12 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "plan.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
plan,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
turnItem: {
id: turnItemId,
threadId: input.context.input.threadId,
@@ -1368,23 +1372,23 @@ export function makeCursorAdapterV2(
const planId = yield* resolvePlanId(input.context, nativeItemId);
const ordinal = yield* resolveItemOrdinal(input.context, nativeItemId);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId,
});
const status = input.failed ? "failed" : input.completed ? "completed" : "running";
const steps = cursorTodoSteps(input.toolCall);
const nativeItemRef = {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: input.callId,
strength: "strong" as const,
};
yield* emitProviderEvent({
type: "node.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
node: {
id: nodeId,
threadId: input.context.input.threadId,
@@ -1405,7 +1409,7 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "plan.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
plan: {
id: planId,
threadId: input.context.input.threadId,
@@ -1418,7 +1422,7 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
turnItem: {
id: turnItemId,
threadId: input.context.input.threadId,
@@ -1467,19 +1471,19 @@ export function makeCursorAdapterV2(
const nodeId =
existing?.task.id ??
idAllocator.derive.nodeFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId,
});
const childRootNodeId =
existing?.childRootNodeId ??
idAllocator.derive.nodeFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: `${nativeItemId}:child-root`,
});
const childThreadId =
existing?.childThreadId ??
idAllocator.derive.threadFromProviderThread({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeThreadId: `${input.context.run.runId}:task:${input.callId}`,
});
const task: OrchestrationV2Subagent = {
@@ -1490,11 +1494,12 @@ export function makeCursorAdapterV2(
parentNodeId: input.context.input.rootNodeId,
origin: "provider_native" as const,
createdBy: "agent" as const,
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerInstanceId: input.context.input.modelSelection.instanceId,
providerThreadId: null,
childThreadId,
nativeTaskRef: {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: input.callId,
strength: "strong" as const,
},
@@ -1505,7 +1510,7 @@ export function makeCursorAdapterV2(
startedAt: now,
}),
nativeTaskRef: {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: input.callId,
strength: "strong" as const,
},
@@ -1522,7 +1527,7 @@ export function makeCursorAdapterV2(
turnItemId:
existing?.turnItemId ??
idAllocator.derive.turnItemFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId,
}),
turnItemOrdinal:
@@ -1535,7 +1540,7 @@ export function makeCursorAdapterV2(
if (existing === undefined) {
yield* emitProviderEvent({
type: "app_thread.created",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
appThread: makeSubagentChildThread({
parentThread: input.context.input.appThread,
childThreadId,
@@ -1557,11 +1562,11 @@ export function makeCursorAdapterV2(
const promptNativeId = `${nativeItemId}:prompt`;
const promptArtifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: promptNativeId,
}),
turnItemId: idAllocator.derive.turnItemFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: promptNativeId,
}),
threadId: childThreadId,
@@ -1569,7 +1574,7 @@ export function makeCursorAdapterV2(
providerThreadId: null,
providerTurnId: null,
nativeItemRef: {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: promptNativeId,
strength: "weak",
},
@@ -1580,19 +1585,19 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "message.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
message: promptArtifacts.message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
turnItem: promptArtifacts.turnItem,
});
}
yield* emitProviderEvent({
type: "node.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
node: {
id: nodeId,
threadId: input.context.input.threadId,
@@ -1613,7 +1618,7 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "node.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
node: {
id: childRootNodeId,
threadId: childThreadId,
@@ -1634,12 +1639,12 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "subagent.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
subagent: task,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
turnItem: {
id: subagent.turnItemId,
threadId: input.context.input.threadId,
@@ -1658,7 +1663,8 @@ export function makeCursorAdapterV2(
type: "subagent",
subagentId: task.id,
origin: task.origin,
provider: task.provider,
driver: task.driver,
providerInstanceId: task.providerInstanceId,
childThreadId,
prompt: task.prompt,
result: task.result,
@@ -1692,11 +1698,11 @@ export function makeCursorAdapterV2(
const resultNativeId = `${nativeItemId}:result`;
const resultArtifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: resultNativeId,
}),
turnItemId: idAllocator.derive.turnItemFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: resultNativeId,
}),
threadId: childThreadId,
@@ -1704,7 +1710,7 @@ export function makeCursorAdapterV2(
providerThreadId: null,
providerTurnId: null,
nativeItemRef: {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: resultNativeId,
strength: "weak",
},
@@ -1715,12 +1721,12 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "message.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
message: resultArtifacts.message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
turnItem: resultArtifacts.turnItem,
});
}
@@ -1863,7 +1869,7 @@ export function makeCursorAdapterV2(
nodeId: input.context.input.rootNodeId,
runAttemptId: input.context.input.attemptId,
nativeTurnRef: {
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeId: input.context.run.runId,
strength: "strong",
},
@@ -1893,7 +1899,7 @@ export function makeCursorAdapterV2(
yield* completeAssistant(input.context);
yield* emitProviderEvent({
type: "provider_turn.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerTurn: providerTurnPayload({
context: input.context,
status: input.status,
@@ -1902,7 +1908,7 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "provider_thread.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerThread: {
...input.context.input.providerThread,
providerSessionId: session.id,
@@ -1916,7 +1922,7 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "turn.terminal",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerTurnId: input.context.providerTurnId,
status: input.status,
});
@@ -1998,7 +2004,7 @@ export function makeCursorAdapterV2(
});
if (path === null) {
return yield* new ProviderAdapterProtocolError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
@@ -2006,7 +2012,7 @@ export function makeCursorAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterProtocolError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
detail: `Failed to read attachment '${attachment.id}'.`,
payload: cause,
}),
@@ -2021,7 +2027,7 @@ export function makeCursorAdapterV2(
);
if (turnInput.message.text.length === 0 && images.length === 0) {
return yield* new ProviderAdapterProtocolError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
detail: "Cursor turn requires non-empty text or attachments.",
});
}
@@ -2038,7 +2044,7 @@ export function makeCursorAdapterV2(
const current = yield* Ref.get(activeTurn);
if (current !== null) {
return yield* new ProviderAdapterProtocolError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
detail: `Cursor provider turn ${current.providerTurnId} is still active.`,
});
}
@@ -2073,7 +2079,7 @@ export function makeCursorAdapterV2(
const startedAt = yield* DateTime.now;
const completed = yield* Deferred.make<void, never>();
const providerTurnId = idAllocator.derive.providerTurn({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeTurnId: sdkRun.runId,
});
context = {
@@ -2098,7 +2104,7 @@ export function makeCursorAdapterV2(
yield* Ref.set(activeTurn, context);
yield* emitProviderEvent({
type: "provider_turn.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerTurn: providerTurnPayload({
context,
status: "running",
@@ -2107,7 +2113,7 @@ export function makeCursorAdapterV2(
});
yield* emitProviderEvent({
type: "provider_thread.updated",
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerThread: {
...turnInput.providerThread,
providerSessionId: session.id,
@@ -2167,7 +2173,7 @@ export function makeCursorAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterTurnStartError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
runId: turnInput.runId,
@@ -2196,7 +2202,7 @@ export function makeCursorAdapterV2(
const runtime: ProviderAdapterV2SessionRuntime = {
instanceId: adapterOptions.instanceId,
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerSessionId: input.providerSessionId,
providerSession: session,
rawEvents: Stream.empty,
@@ -2212,6 +2218,7 @@ export function makeCursorAdapterV2(
const now = yield* DateTime.now;
return makeProviderThread({
idAllocator,
providerInstanceId: adapterOptions.instanceId,
appThreadId: threadInput.threadId,
providerSessionId: input.providerSessionId,
nativeThreadId: opened.nativeThreadId,
@@ -2223,7 +2230,7 @@ export function makeCursorAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterEnsureThreadError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
threadId: threadInput.threadId,
cause,
}),
@@ -2253,7 +2260,7 @@ export function makeCursorAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterResumeThreadError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerSessionId: input.providerSessionId,
providerThreadId: threadInput.providerThread.id,
cause,
@@ -2265,7 +2272,7 @@ export function makeCursorAdapterV2(
steerTurn: (turnInput) =>
Effect.fail(
new ProviderAdapterSteerRunUnsupportedError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerThreadId: turnInput.providerThread.id,
}),
),
@@ -2274,7 +2281,7 @@ export function makeCursorAdapterV2(
const context = yield* Ref.get(activeTurn);
if (context?.providerTurnId !== turnInput.providerTurnId) {
return yield* new ProviderAdapterProtocolError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
detail: `Cursor provider turn ${turnInput.providerTurnId} is not active.`,
});
}
@@ -2298,7 +2305,7 @@ export function makeCursorAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterInterruptError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerThreadId: turnInput.providerThread.id,
providerTurnId: turnInput.providerTurnId,
cause,
@@ -2309,10 +2316,10 @@ export function makeCursorAdapterV2(
respondToRuntimeRequest: (requestInput) =>
Effect.fail(
new ProviderAdapterRuntimeRequestResponseError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
requestId: requestInput.requestId,
cause: new ProviderAdapterProtocolError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
detail: "Cursor Agent SDK does not expose interactive approval requests.",
}),
}),
@@ -2341,7 +2348,7 @@ export function makeCursorAdapterV2(
createdBy: message.type === "user" ? "user" : "agent",
creationSource: "provider",
id: idAllocator.derive.messageFromProviderItem({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
nativeItemId: message.uuid,
}),
threadId,
@@ -2378,7 +2385,7 @@ export function makeCursorAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterReadThreadSnapshotError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerThreadId: snapshotInput.providerThread.id,
cause,
}),
@@ -2388,7 +2395,7 @@ export function makeCursorAdapterV2(
rollbackThread: (rollbackInput) =>
Effect.fail(
new ProviderAdapterRollbackThreadError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerThreadId: rollbackInput.providerThread.id,
checkpointId: rollbackInput.target.checkpointId,
cause: "Cursor Agent SDK does not expose conversation rollback.",
@@ -2397,7 +2404,7 @@ export function makeCursorAdapterV2(
forkThread: (forkInput) =>
Effect.fail(
new ProviderAdapterForkThreadError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerThreadId: forkInput.sourceProviderThread.id,
cause: "Cursor Agent SDK does not expose native agent forks.",
}),
@@ -2410,7 +2417,7 @@ export function makeCursorAdapterV2(
Effect.mapError(
(cause) =>
new ProviderAdapterOpenSessionError({
provider: CURSOR_PROVIDER,
driver: CURSOR_PROVIDER,
providerSessionId: input.providerSessionId,
cause,
}),
@@ -7,7 +7,11 @@ import {
type SDKUserMessage,
type SendOptions,
} from "@cursor/sdk";
import type { OrchestrationV2ProviderSession, ThreadId } from "@t3tools/contracts";
import {
type OrchestrationV2ProviderSession,
ProviderDriverKind,
type ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -20,7 +24,7 @@ import {
} from "../../provider/Layers/EventNdjsonLogger.ts";
export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const;
export const CURSOR_PROVIDER = "cursor" as const;
export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor");
export class CursorAgentSdkRunnerError extends Schema.TaggedErrorClass<CursorAgentSdkRunnerError>()(
"CursorAgentSdkRunnerError",
@@ -70,7 +70,7 @@ export const GrokOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
AcpReplayTranscript,
AcpReplayTranscriptDecodeError
> = {
provider: GROK_PROVIDER,
driver: GROK_PROVIDER,
decodeTranscript: (transcript) => decodeAcpReplayTranscript(transcript, GROK_PROVIDER),
makeProviderAdapterRegistryLayer: makeGrokProviderAdapterRegistryReplayLayer,
};
@@ -41,8 +41,8 @@ import {
type AcpAdapterV2RuntimeInput,
} from "./AcpAdapterV2.ts";
export const GROK_PROVIDER = "grok" as const;
export const GROK_DRIVER_KIND = ProviderDriverKind.make(GROK_PROVIDER);
export const GROK_PROVIDER = ProviderDriverKind.make("grok");
export const GROK_DRIVER_KIND = GROK_PROVIDER;
export const GROK_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(GROK_DRIVER_KIND);
const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({});
@@ -119,7 +119,7 @@ export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["register
export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
const flavor: AcpAdapterV2Flavor = {
provider: GROK_PROVIDER,
driver: GROK_PROVIDER,
capabilities: GrokProviderCapabilitiesV2,
resolveModelId: (selection) => resolveGrokAcpBaseModelId(selection.model),
makeRuntime:
@@ -12,6 +12,7 @@ import {
openCodePermissionRules,
openCodePermissionRequestKind,
openCodeToolProjectionKind,
OPENCODE_PROVIDER,
OpenCodeProviderCapabilitiesV2,
} from "./OpenCodeAdapterV2.ts";
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
@@ -46,7 +47,7 @@ function providerTurn(input: {
nativeTurnRef:
input.nativeId === null
? null
: { provider: "opencode", nativeId: input.nativeId, strength: "weak" },
: { driver: OPENCODE_PROVIDER, nativeId: input.nativeId, strength: "weak" },
ordinal: input.ordinal,
status: "completed",
startedAt: null,
@@ -42,7 +42,7 @@ const decodeOpenCodeSdkReplayTranscript = Schema.decodeUnknownEffect(OpenCodeSdk
export class OpenCodeReplayTranscriptDecodeError extends Schema.TaggedErrorClass<OpenCodeReplayTranscriptDecodeError>()(
"OpenCodeReplayTranscriptDecodeError",
{
provider: Schema.optional(Schema.String),
driver: Schema.optional(Schema.String),
protocol: Schema.optional(Schema.String),
scenario: Schema.optional(Schema.String),
cause: Schema.Defect(),
@@ -370,7 +370,7 @@ export const OpenCodeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarn
OpenCodeSdkReplayTranscript,
OpenCodeOrchestratorReplayHarnessError
> = {
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
decodeTranscript: (transcript) =>
decodeOpenCodeSdkReplayTranscript(transcript).pipe(
Effect.mapError(
@@ -92,8 +92,8 @@ import {
} from "../ProviderAdapterDriver.ts";
import { makeSubagentChildThread, subagentThreadTitle } from "../SubagentProjection.ts";
export const OPENCODE_PROVIDER = "opencode" as const;
export const OPENCODE_DRIVER_KIND = ProviderDriverKind.make(OPENCODE_PROVIDER);
export const OPENCODE_PROVIDER = ProviderDriverKind.make("opencode");
export const OPENCODE_DRIVER_KIND = OPENCODE_PROVIDER;
export const OPENCODE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(OPENCODE_DRIVER_KIND);
const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettingsSchema)({});
@@ -274,7 +274,7 @@ export interface OpenCodeAdapterV2Options {
function protocolError(detail: string, payload?: unknown): ProviderAdapterProtocolError {
return new ProviderAdapterProtocolError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
detail,
...(payload === undefined ? {} : { payload }),
});
@@ -628,6 +628,7 @@ function taskSessionId(part: ToolPart): string | null {
function makeProviderThread(input: {
readonly idAllocator: IdAllocatorV2Shape;
readonly providerInstanceId: ProviderInstanceId;
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"];
@@ -638,15 +639,16 @@ function makeProviderThread(input: {
const createdAt = dateTimeFromEpoch(input.nativeSession.time.created, input.now);
return {
id: input.idAllocator.derive.providerThread({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeThreadId: input.nativeSession.id,
}),
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
appThreadId: input.appThreadId,
ownerNodeId: input.ownerNodeId ?? null,
nativeThreadRef: {
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeId: input.nativeSession.id,
strength: "strong",
},
@@ -663,7 +665,7 @@ function makeProviderThread(input: {
function providerRef(nativeId: string, strength: "strong" | "weak" = "strong") {
return {
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeId,
strength,
} satisfies OrchestrationV2ProviderRef;
@@ -701,7 +703,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
return ProviderAdapterV2.of({
instanceId: options.instanceId,
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
getCapabilities: () => Effect.succeed(OpenCodeProviderCapabilitiesV2),
openSession: Effect.fn("OpenCodeAdapterV2.openSession")(
function* (input: ProviderAdapterV2OpenSessionInput) {
@@ -738,7 +740,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const now = yield* DateTime.now;
let sessionEntity: OrchestrationV2ProviderSession = {
id: input.providerSessionId,
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
status: "ready",
cwd,
model: input.modelSelection.model,
@@ -775,7 +778,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
yield* Queue.offer(rawEvents, {
id: rawEventId,
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
providerSessionId: input.providerSessionId,
sequence,
direction: raw.direction,
@@ -825,7 +829,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
sessionEntity = { ...sessionEntity, status, lastError, updatedAt };
yield* emitProviderEvent({
type: "provider_session.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerSession: sessionEntity,
});
});
@@ -839,7 +843,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
state.providerThread = { ...state.providerThread, ...patch, updatedAt };
yield* emitProviderEvent({
type: "provider_thread.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerThread: state.providerThread,
});
});
@@ -871,7 +875,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
state.providerTurns.set(String(providerTurn.id), providerTurn);
return emitProviderEvent({
type: "provider_turn.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
threadId: turn.threadId,
providerTurn,
});
@@ -891,17 +895,17 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const completedAt = isCompleted ? dateTimeFromEpoch(part.time?.end, emittedAt) : null;
const nativeItemRef = providerRef(part.id);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const ordinal = itemOrdinal(turn, part.id);
yield* emitProviderEvent({
type: "node.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
@@ -922,7 +926,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
if (part.type === "text") {
const messageId = idAllocator.derive.messageFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const message: OrchestrationV2ConversationMessage = {
@@ -942,12 +946,12 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
state.messages.set(String(message.id), message);
yield* emitProviderEvent({
type: "message.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
turnItem: {
id: turnItemId,
threadId: turn.threadId,
@@ -973,7 +977,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
}
yield* emitProviderEvent({
type: "turn_item.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
turnItem: {
id: turnItemId,
threadId: turn.threadId,
@@ -1004,11 +1008,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const now = yield* DateTime.now;
const nativeItemRef = providerRef(part.id);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const input = toolInput(part);
@@ -1036,11 +1040,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
if (childSessionId !== null && context.childSessionId === null) {
context.childSessionId = childSessionId;
context.childThreadId = idAllocator.derive.threadFromProviderThread({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeThreadId: childSessionId,
});
context.childProviderThreadId = idAllocator.derive.providerThread({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeThreadId: childSessionId,
});
subagentsByChildSessionId.set(childSessionId, context);
@@ -1067,7 +1071,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
const childProviderThread: OrchestrationV2ProviderThread = {
id: context.childProviderThreadId,
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
providerSessionId: inputProviderSessionId,
appThreadId: context.childThreadId,
ownerNodeId: nodeId,
@@ -1115,12 +1120,12 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
yield* emitProviderEvent({
type: "app_thread.created",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
appThread: childThread,
});
yield* emitProviderEvent({
type: "provider_thread.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerThread: childProviderThread,
});
}
@@ -1143,7 +1148,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
parentNodeId: turn.rootNodeId,
origin: "provider_native",
createdBy: "agent",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
providerThreadId: context.childProviderThreadId,
childThreadId: context.childThreadId,
nativeTaskRef: nativeItemRef,
@@ -1158,7 +1164,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
};
yield* emitProviderEvent({
type: "node.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
@@ -1179,12 +1185,12 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
yield* emitProviderEvent({
type: "subagent.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
subagent,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
turnItem: {
id: turnItemId,
threadId: turn.threadId,
@@ -1203,7 +1209,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
type: "subagent",
subagentId: nodeId,
origin: "provider_native",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
childThreadId: context.childThreadId,
prompt,
result: context.result,
@@ -1230,11 +1237,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const completedAt = toolCompletedAt(part, now);
const nativeItemRef = providerRef(part.id);
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const base = {
@@ -1344,7 +1351,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
}
yield* emitProviderEvent({
type: "node.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
@@ -1365,7 +1372,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
turnItem,
});
});
@@ -1380,17 +1387,17 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
turn.planId = yield* idAllocator.allocate.plan({
threadId: turn.threadId,
...(turn.runId === null ? {} : { runId: turn.runId }),
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
});
}
const planId = turn.planId;
const nativeItemId = `${state.nativeSessionId}:todo:${turn.providerTurnId}`;
const nodeId = idAllocator.derive.nodeFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId,
});
const steps: Array<OrchestrationV2PlanStep> = todos.map((todo, index) => ({
@@ -1406,7 +1413,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const completed = steps.length > 0 && steps.every((step) => step.status === "completed");
yield* emitProviderEvent({
type: "node.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
@@ -1427,7 +1434,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
yield* emitProviderEvent({
type: "plan.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
plan: {
id: planId,
threadId: turn.threadId,
@@ -1440,7 +1447,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
turnItem: {
id: turnItemId,
threadId: turn.threadId,
@@ -1532,7 +1539,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
if (pendingRequestsByNativeId.has(nativeRequestId)) return;
const now = yield* DateTime.now;
const requestId = yield* idAllocator.allocate.runtimeRequest({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerTurnId: turn.providerTurnId,
nativeRequestId,
});
@@ -1583,7 +1590,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
state.runtimeRequests.set(String(requestId), runtimeRequest);
yield* emitProviderEvent({
type: "node.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
@@ -1604,13 +1611,13 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
yield* emitProviderEvent({
type: "runtime_request.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
threadId: turn.threadId,
runtimeRequest,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
turnItem: runtimeRequestTurnItem(pending, "waiting", null, now),
});
yield* updateProviderSession("waiting", null);
@@ -1633,14 +1640,14 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
pending.state.runtimeRequests.set(String(pending.requestId), resolved);
yield* emitProviderEvent({
type: "runtime_request.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
threadId: pending.turn.threadId,
runtimeRequest: resolved,
});
}
yield* emitProviderEvent({
type: "node.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
node: {
id: pending.nodeId,
threadId: pending.turn.threadId,
@@ -1661,7 +1668,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
turnItem: runtimeRequestTurnItem(
pending,
status === "resolved" ? "completed" : "cancelled",
@@ -1707,7 +1714,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
if (!turn.isRoot) {
yield* emitProviderEvent({
type: "node.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
node: {
id: turn.rootNodeId,
threadId: turn.threadId,
@@ -1737,7 +1744,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
);
yield* emitProviderEvent({
type: "turn.terminal",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerTurnId: turn.providerTurnId,
status,
});
@@ -1751,11 +1758,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const now = yield* DateTime.now;
const startedAt = dateTimeFromEpoch(message.time.created, now);
const rootNodeId = idAllocator.derive.nodeFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: `${state.nativeSessionId}:root:${message.id}`,
});
const providerTurnId = idAllocator.derive.providerTurn({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeTurnId: message.id,
});
const providerTurn: OrchestrationV2ProviderTurn = {
@@ -1795,7 +1802,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
state.providerTurns.set(String(providerTurnId), providerTurn);
yield* emitProviderEvent({
type: "node.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
node: {
id: rootNodeId,
threadId: turn.threadId,
@@ -1825,11 +1832,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
) {
const now = yield* DateTime.now;
const messageId = idAllocator.derive.messageFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: part.messageID,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: part.messageID,
});
const projected: OrchestrationV2ConversationMessage = {
@@ -1849,12 +1856,12 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
state.messages.set(String(messageId), projected);
yield* emitProviderEvent({
type: "message.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
message: projected,
});
yield* emitProviderEvent({
type: "turn_item.updated",
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
turnItem: {
createdBy: "agent",
creationSource: "provider",
@@ -2198,7 +2205,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
createdBy: info.role === "user" ? "user" : "agent",
creationSource: "provider",
id: idAllocator.derive.messageFromProviderItem({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeItemId: info.id,
}),
threadId: providerThread.appThreadId ?? input.threadId,
@@ -2236,7 +2243,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const runtimeSession: ProviderAdapterV2SessionRuntime = {
instanceId: options.instanceId,
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerSessionId: input.providerSessionId,
providerSession: sessionEntity,
rawEvents: Stream.fromEffectRepeat(Queue.take(rawEvents)),
@@ -2264,6 +2271,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const createdAt = yield* DateTime.now;
const providerThread = makeProviderThread({
idAllocator,
providerInstanceId: options.instanceId,
providerSessionId: input.providerSessionId,
appThreadId: threadInput.threadId,
nativeSession,
@@ -2275,7 +2283,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterEnsureThreadError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
threadId: threadInput.threadId,
cause,
}),
@@ -2301,7 +2309,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterResumeThreadError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerSessionId: input.providerSessionId,
providerThreadId: threadInput.providerThread.id,
cause,
@@ -2330,7 +2338,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const startedAt = yield* DateTime.now;
const syntheticNativeTurnId = `${sessionId}:attempt:${turnInput.attemptId}`;
const providerTurnId = idAllocator.derive.providerTurn({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
nativeTurnId: syntheticNativeTurnId,
});
const providerTurn: OrchestrationV2ProviderTurn = {
@@ -2405,7 +2413,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterTurnStartError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
runId: turnInput.runId,
@@ -2463,7 +2471,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterSteerRunError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerThreadId: steerInput.providerThread.id,
providerTurnId: steerInput.providerTurnId,
cause,
@@ -2492,7 +2500,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterInterruptError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerThreadId: interruptInput.providerThread.id,
providerTurnId: interruptInput.providerTurnId,
cause,
@@ -2544,7 +2552,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterRuntimeRequestResponseError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
requestId: requestInput.requestId,
cause,
}),
@@ -2555,7 +2563,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterReadThreadSnapshotError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerThreadId: snapshotInput.providerThread.id,
cause,
}),
@@ -2606,7 +2614,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterRollbackThreadError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerThreadId: rollbackInput.providerThread.id,
checkpointId: rollbackInput.target.checkpointId,
cause,
@@ -2649,6 +2657,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
const forkedAt = yield* DateTime.now;
const providerThread = makeProviderThread({
idAllocator,
providerInstanceId: options.instanceId,
providerSessionId: input.providerSessionId,
appThreadId: forkInput.targetThreadId,
...(forkInput.ownerNodeId === undefined
@@ -2669,7 +2678,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterForkThreadError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerThreadId: forkInput.sourceProviderThread.id,
cause,
}),
@@ -2684,7 +2693,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid
Effect.mapError(
(cause) =>
new ProviderAdapterOpenSessionError({
provider: OPENCODE_PROVIDER,
driver: OPENCODE_PROVIDER,
providerSessionId: input.providerSessionId,
cause,
}),
@@ -0,0 +1,217 @@
import {
CheckpointScopeId,
CommandId,
type OrchestrationV2Checkpoint,
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderThread,
type OrchestrationV2Run,
type OrchestrationV2TurnItem,
RunId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { CheckpointServiceV2 } from "./CheckpointService.ts";
import { EventSinkV2 } from "./EventSink.ts";
import { IdAllocatorV2, type IdAllocatorV2Shape } from "./IdAllocator.ts";
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
export class CheckpointCaptureExecutionError extends Schema.TaggedErrorClass<CheckpointCaptureExecutionError>()(
"CheckpointCaptureExecutionError",
{
threadId: ThreadId,
runId: RunId,
scopeId: CheckpointScopeId,
cause: Schema.optional(Schema.Defect()),
},
) {}
export interface CheckpointCaptureServiceV2Shape {
readonly execute: (input: {
readonly threadId: ThreadId;
readonly runId: RunId;
readonly scopeId: CheckpointScopeId;
}) => Effect.Effect<void, CheckpointCaptureExecutionError>;
}
export class CheckpointCaptureServiceV2 extends Context.Service<
CheckpointCaptureServiceV2,
CheckpointCaptureServiceV2Shape
>()("t3/orchestration-v2/CheckpointCaptureService/CheckpointCaptureServiceV2") {}
export const layer: Layer.Layer<
CheckpointCaptureServiceV2,
never,
CheckpointServiceV2 | EventSinkV2 | IdAllocatorV2 | ProjectionStoreV2
> = Layer.effect(
CheckpointCaptureServiceV2,
Effect.gen(function* () {
const checkpoints = yield* CheckpointServiceV2;
const eventSink = yield* EventSinkV2;
const ids = yield* IdAllocatorV2;
const projections = yield* ProjectionStoreV2;
const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: {
readonly threadId: ThreadId;
readonly runId: RunId;
readonly scopeId: CheckpointScopeId;
}) {
const projection = yield* projections.getThreadProjection(input.threadId);
const run = projection.runs.find((candidate) => candidate.id === input.runId);
// The effect is at-least-once. A completed run with a checkpoint proves
// that an earlier execution committed its result.
if (run?.status === "completed" && run.checkpointId !== null) {
return;
}
const rootNode = projection.nodes.find((candidate) => candidate.id === run?.rootNodeId);
const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === run?.providerThreadId,
);
if (
run === undefined ||
run.status !== "waiting" ||
rootNode === undefined ||
scope === undefined ||
rootNode.checkpointScopeId !== scope.id ||
providerThread === undefined
) {
return yield* new CheckpointCaptureExecutionError({
threadId: input.threadId,
runId: input.runId,
scopeId: input.scopeId,
cause: "The persisted checkpoint capture target is incomplete or no longer waiting.",
});
}
const capturedAt = yield* DateTime.now;
const checkpoint = yield* checkpoints.capture({
scope,
runId: run.id,
nodeId: rootNode.id,
ordinalWithinScope: run.ordinal,
appRunOrdinal: run.ordinal,
capturedAt,
});
const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`);
yield* eventSink.commitCommand({
commandId,
threadId: input.threadId,
commandType: "checkpoint.capture",
acceptedAt: capturedAt,
effects: [],
events: [
{
id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
type: "checkpoint.captured",
threadId: input.threadId,
runId: run.id,
nodeId: rootNode.id,
driver: providerThread.driver,
providerInstanceId: run.providerInstanceId,
occurredAt: capturedAt,
payload: checkpoint,
},
{
id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
type: "turn-item.updated",
threadId: input.threadId,
runId: run.id,
nodeId: rootNode.id,
driver: providerThread.driver,
providerInstanceId: run.providerInstanceId,
occurredAt: capturedAt,
payload: makeCheckpointTurnItem({
idAllocator: ids,
run,
rootNode,
providerThread,
checkpoint,
completedAt: capturedAt,
}),
},
{
id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
type: "run.updated",
threadId: input.threadId,
runId: run.id,
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: capturedAt,
payload: {
...run,
status: "completed",
completedAt: capturedAt,
checkpointId: checkpoint.id,
},
},
{
id: yield* ids.allocate.event({ threadId: input.threadId, commandId }),
type: "node.updated",
threadId: input.threadId,
runId: run.id,
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: capturedAt,
payload: {
...rootNode,
status: "completed",
completedAt: capturedAt,
checkpointScopeId: scope.id,
},
},
],
});
});
return CheckpointCaptureServiceV2.of({
execute: (input) =>
execute(input).pipe(
Effect.mapError((cause) =>
Schema.is(CheckpointCaptureExecutionError)(cause)
? cause
: new CheckpointCaptureExecutionError({ ...input, cause }),
),
),
});
}),
);
function makeCheckpointTurnItem(input: {
readonly idAllocator: IdAllocatorV2Shape;
readonly run: OrchestrationV2Run;
readonly rootNode: OrchestrationV2ExecutionNode;
readonly providerThread: OrchestrationV2ProviderThread;
readonly checkpoint: OrchestrationV2Checkpoint;
readonly completedAt: DateTime.Utc;
}): OrchestrationV2TurnItem {
return {
id: input.idAllocator.derive.turnItemFromProviderItem({
driver: input.providerThread.driver,
nativeItemId: `checkpoint:${input.checkpoint.id}`,
}),
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
providerThreadId: input.providerThread.id,
providerTurnId: input.rootNode.providerTurnId,
nativeItemRef: null,
parentItemId: null,
ordinal: input.run.ordinal * 100 + 99,
status: "completed",
title: null,
startedAt: input.completedAt,
completedAt: input.completedAt,
updatedAt: input.completedAt,
type: "checkpoint",
checkpointId: input.checkpoint.id,
scopeId: input.checkpoint.scopeId,
files: input.checkpoint.files,
};
}
@@ -0,0 +1,254 @@
import {
CheckpointId,
CheckpointScopeId,
type OrchestrationV2DomainEvent,
ProviderThreadId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { CheckpointServiceV2 } from "./CheckpointService.ts";
import { EventSinkV2 } from "./EventSink.ts";
import { IdAllocatorV2 } from "./IdAllocator.ts";
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
import type { ProviderAdapterV2RollbackTarget } from "./ProviderAdapter.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
export class CheckpointRollbackExecutionError extends Schema.TaggedErrorClass<CheckpointRollbackExecutionError>()(
"CheckpointRollbackExecutionError",
{
threadId: ThreadId,
providerThreadId: ProviderThreadId,
checkpointId: CheckpointId,
cause: Schema.optional(Schema.Defect()),
},
) {}
export interface CheckpointRollbackServiceV2Shape {
readonly execute: (input: {
readonly threadId: ThreadId;
readonly providerThreadId: ProviderThreadId;
readonly checkpointId: CheckpointId;
readonly scopeId: CheckpointScopeId;
}) => Effect.Effect<void, CheckpointRollbackExecutionError>;
}
export class CheckpointRollbackServiceV2 extends Context.Service<
CheckpointRollbackServiceV2,
CheckpointRollbackServiceV2Shape
>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
export const layer: Layer.Layer<
CheckpointRollbackServiceV2,
never,
| CheckpointServiceV2
| EventSinkV2
| IdAllocatorV2
| ProjectionStoreV2
| ProviderSessionManagerV2
| RuntimePolicyV2
> = Layer.effect(
CheckpointRollbackServiceV2,
Effect.gen(function* () {
const checkpoints = yield* CheckpointServiceV2;
const eventSink = yield* EventSinkV2;
const ids = yield* IdAllocatorV2;
const projections = yield* ProjectionStoreV2;
const sessions = yield* ProviderSessionManagerV2;
const runtimePolicy = yield* RuntimePolicyV2;
const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: {
readonly threadId: ThreadId;
readonly providerThreadId: ProviderThreadId;
readonly checkpointId: CheckpointId;
readonly scopeId: CheckpointScopeId;
}) {
const projection = yield* projections.getThreadProjection(input.threadId);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === input.providerThreadId,
);
const checkpoint = projection.checkpoints.find(
(candidate) => candidate.id === input.checkpointId,
);
const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId);
if (
providerThread === undefined ||
providerThread.providerSessionId === null ||
checkpoint === undefined ||
scope === undefined ||
checkpoint.scopeId !== scope.id
) {
return yield* new CheckpointRollbackExecutionError({
threadId: input.threadId,
providerThreadId: input.providerThreadId,
checkpointId: input.checkpointId,
cause: "The persisted rollback target is incomplete or no longer valid.",
});
}
const modelSelection = projection.thread.modelSelection;
const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
thread: projection.thread,
modelSelection,
});
const existingSession = projection.providerSessions.find(
(candidate) => candidate.id === providerThread.providerSessionId,
);
const session = yield* sessions.open({
threadId: input.threadId,
providerSessionId: providerThread.providerSessionId,
modelSelection,
runtimePolicy: resolvedRuntimePolicy,
...(existingSession === undefined ? {} : { resumeFromSession: existingSession }),
});
const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
const runsToRollback = projection.runs.filter(
(run) => run.ordinal > targetOrdinal && run.status === "completed",
);
const providerThreadTurns = projection.providerTurns.filter(
(turn) => turn.providerThreadId === providerThread.id,
);
const rollbackTarget: ProviderAdapterV2RollbackTarget =
targetOrdinal === 0
? {
type: "thread_start",
checkpointId: checkpoint.id,
appRunOrdinal: 0,
}
: yield* Effect.gen(function* () {
const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
const targetAttempt = projection.attempts.find(
(attempt) => attempt.id === targetRun?.activeAttemptId,
);
const targetTurn = projection.providerTurns.find(
(turn) =>
turn.id === targetAttempt?.providerTurnId ||
turn.runAttemptId === targetAttempt?.id,
);
if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) {
return yield* new CheckpointRollbackExecutionError({
threadId: input.threadId,
providerThreadId: input.providerThreadId,
checkpointId: input.checkpointId,
cause: "The provider rollback turn is unavailable.",
});
}
return {
type: "provider_turn" as const,
checkpointId: checkpoint.id,
appRunOrdinal: targetOrdinal,
providerTurn: targetTurn,
};
});
yield* checkpoints.restore({ scope, checkpoint });
const snapshot =
runsToRollback.length === 0
? { providerThread }
: yield* session.rollbackThread({
providerThread,
target: rollbackTarget,
providerThreadTurns,
});
const staleCheckpoints = projection.checkpoints.filter(
(candidate) =>
candidate.scopeId === scope.id &&
candidate.appRunOrdinal !== null &&
candidate.appRunOrdinal > targetOrdinal &&
candidate.status === "ready",
);
if (staleCheckpoints.length > 0) {
yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints });
}
const now = yield* DateTime.now;
const makeEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
Effect.map(
ids.allocate.event({ threadId: event.threadId }),
(id) =>
({
...event,
id,
}) as Event,
);
const events: Array<OrchestrationV2DomainEvent> = [];
events.push(
yield* makeEvent({
type: "provider-thread.updated",
threadId: input.threadId,
driver: providerThread.driver,
providerInstanceId: providerThread.providerInstanceId,
occurredAt: now,
payload: {
...snapshot.providerThread,
lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal,
updatedAt: now,
},
}),
);
for (const staleCheckpoint of staleCheckpoints) {
events.push(
yield* makeEvent({
type: "checkpoint.captured",
threadId: input.threadId,
...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }),
nodeId: staleCheckpoint.nodeId,
providerInstanceId: providerThread.providerInstanceId,
occurredAt: now,
payload: { ...staleCheckpoint, status: "stale" },
}),
);
}
for (const run of runsToRollback) {
const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
events.push(
yield* makeEvent({
type: "run.updated",
threadId: input.threadId,
runId: run.id,
...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...run, status: "rolled_back", completedAt: now },
}),
);
if (rootNode !== undefined) {
events.push(
yield* makeEvent({
type: "node.updated",
threadId: input.threadId,
runId: run.id,
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...rootNode, status: "rolled_back", completedAt: now },
}),
);
}
}
yield* eventSink.write({ events });
});
return CheckpointRollbackServiceV2.of({
execute: (input) =>
execute(input).pipe(
Effect.mapError((cause) =>
Schema.is(CheckpointRollbackExecutionError)(cause)
? cause
: new CheckpointRollbackExecutionError({
threadId: input.threadId,
providerThreadId: input.providerThreadId,
checkpointId: input.checkpointId,
cause,
}),
),
),
});
}),
);
@@ -1,5 +1,10 @@
import { assert, it } from "@effect/vitest";
import { CommandId, type OrchestrationV2ProviderCapabilities, ThreadId } from "@t3tools/contracts";
import {
CommandId,
type OrchestrationV2ProviderCapabilities,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
@@ -32,7 +37,7 @@ layer("CommandPolicyV2", (it) => {
const result = yield* policy.decideSteeringExecution({
commandId,
threadId,
provider: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: baseCapabilities,
});
@@ -47,7 +52,7 @@ layer("CommandPolicyV2", (it) => {
const result = yield* policy.decideSteeringExecution({
commandId,
threadId,
provider: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: capabilities((current) => ({
...current,
turns: {
@@ -70,7 +75,7 @@ layer("CommandPolicyV2", (it) => {
const result = yield* policy.decideSteeringExecution({
commandId,
threadId,
provider: "grok",
providerInstanceId: ProviderInstanceId.make("grok"),
capabilities: GrokProviderCapabilitiesV2,
});
@@ -85,7 +90,7 @@ layer("CommandPolicyV2", (it) => {
const result = yield* policy.decideSteeringExecution({
commandId,
threadId,
provider: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: CodexProviderCapabilitiesV2,
forceRestart: true,
});
@@ -102,7 +107,7 @@ layer("CommandPolicyV2", (it) => {
.decideSteeringExecution({
commandId,
threadId,
provider: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: capabilities((current) => ({
...current,
turns: {
@@ -128,7 +133,7 @@ layer("CommandPolicyV2", (it) => {
.ensureNativeFork({
commandId,
threadId,
provider: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
fromSpecificTurn: true,
capabilities: capabilities((current) => ({
...current,
@@ -152,7 +157,7 @@ layer("CommandPolicyV2", (it) => {
const result = yield* policy.decideForkExecution({
commandId,
threadId,
provider: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: CodexProviderCapabilitiesV2,
sameProvider: true,
hasStrongNativeSource: true,
@@ -170,7 +175,7 @@ layer("CommandPolicyV2", (it) => {
const result = yield* policy.decideForkExecution({
commandId,
threadId,
provider: "cursor",
providerInstanceId: ProviderInstanceId.make("cursor"),
capabilities: CursorProviderCapabilitiesV2,
sameProvider: true,
hasStrongNativeSource: true,
@@ -188,7 +193,7 @@ layer("CommandPolicyV2", (it) => {
const result = yield* policy.decideForkExecution({
commandId,
threadId,
provider: "grok",
providerInstanceId: ProviderInstanceId.make("grok"),
capabilities: GrokProviderCapabilitiesV2,
sameProvider: true,
hasStrongNativeSource: true,
@@ -207,7 +212,7 @@ layer("CommandPolicyV2", (it) => {
.decideForkExecution({
commandId,
threadId,
provider: "cursor",
providerInstanceId: ProviderInstanceId.make("cursor"),
capabilities: capabilities((current) => ({
...current,
threads: {
@@ -238,7 +243,7 @@ layer("CommandPolicyV2", (it) => {
.ensureRollback({
commandId,
threadId,
provider: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: capabilities((current) => ({
...current,
checkpointing: {
@@ -262,7 +267,7 @@ layer("CommandPolicyV2", (it) => {
.ensureContextHandoff({
commandId,
threadId,
provider: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
strategy: "fork_delta_context",
capabilities: capabilities((current) => ({
...current,
@@ -287,7 +292,7 @@ layer("CommandPolicyV2", (it) => {
.ensureQueuedMessages({
commandId,
threadId,
provider: "codex",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: capabilities((current) => ({
...current,
turns: {
@@ -3,7 +3,7 @@ import {
ModelSelection,
OrchestrationV2ProviderCapabilities,
OrchestrationV2ThreadProjection,
ProviderKind,
ProviderInstanceId,
ProviderTurnId,
RunId,
ThreadId,
@@ -34,7 +34,7 @@ export const MessageDispatchDecisionV2 = Schema.Union([
}),
Schema.Struct({
type: Schema.Literal("switch_provider"),
fromProvider: ProviderKind,
fromProviderInstanceId: ProviderInstanceId,
toModelSelection: ModelSelection,
}),
]);
@@ -79,11 +79,11 @@ export class CommandPolicyUnsupportedError extends Schema.TaggedErrorClass<Comma
commandId: CommandId,
threadId: ThreadId,
requestedMode: Schema.String,
provider: ProviderKind,
providerInstanceId: ProviderInstanceId,
},
) {
override get message(): string {
return `${this.provider} cannot satisfy message dispatch mode ${this.requestedMode} for command ${this.commandId}.`;
return `${this.providerInstanceId} cannot satisfy message dispatch mode ${this.requestedMode} for command ${this.commandId}.`;
}
}
@@ -92,13 +92,13 @@ export class CommandPolicyCapabilityUnsupportedError extends Schema.TaggedErrorC
{
commandId: CommandId,
threadId: ThreadId,
provider: ProviderKind,
providerInstanceId: ProviderInstanceId,
capability: CommandPolicyCapability,
detail: Schema.String,
},
) {
override get message(): string {
return `${this.provider} cannot satisfy ${this.capability} for command ${this.commandId}: ${this.detail}`;
return `${this.providerInstanceId} cannot satisfy ${this.capability} for command ${this.commandId}: ${this.detail}`;
}
}
@@ -112,7 +112,7 @@ export type CommandPolicyV2Error = typeof CommandPolicyV2Error.Type;
interface CapabilityCheckInput {
readonly commandId: CommandId;
readonly threadId: ThreadId;
readonly provider: ProviderKind;
readonly providerInstanceId: ProviderInstanceId;
readonly capabilities: OrchestrationV2ProviderCapabilities;
}
@@ -173,7 +173,7 @@ function unsupported(
return new CommandPolicyCapabilityUnsupportedError({
commandId: input.commandId,
threadId: input.threadId,
provider: input.provider,
providerInstanceId: input.providerInstanceId,
capability,
detail,
});
@@ -183,7 +183,11 @@ const ensureQueuedMessages: CommandPolicyV2Shape["ensureQueuedMessages"] = (inpu
input.capabilities.turns.supportsQueuedMessages
? Effect.void
: Effect.fail(
unsupported(input, "queued_messages", "provider does not support app-owned queued turns"),
unsupported(
input,
"queued_messages",
"providerInstanceId does not support app-owned queued turns",
),
);
const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {
@@ -200,7 +204,7 @@ const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] =
unsupported(
input,
input.capabilities.turns.supportsInterrupt ? "interrupt_restart_steering" : "active_steering",
"provider cannot steer active turns directly or by interrupt-and-restart",
"providerInstanceId cannot steer active turns directly or by interrupt-and-restart",
),
);
};
@@ -208,22 +212,32 @@ const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] =
const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) =>
input.capabilities.turns.supportsInterrupt
? Effect.void
: Effect.fail(unsupported(input, "interrupt", "provider does not support turn interrupts"));
: Effect.fail(
unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"),
);
const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
if (!input.capabilities.threads.canForkThread) {
return Effect.fail(
unsupported(input, "native_fork", "provider does not support native thread forks"),
unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"),
);
}
if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) {
return Effect.fail(
unsupported(input, "fork_from_turn", "provider cannot fork from a specific completed turn"),
unsupported(
input,
"fork_from_turn",
"providerInstanceId cannot fork from a specific completed turn",
),
);
}
if (input.capabilities.identity.nativeThreadIds !== "strong") {
return Effect.fail(
unsupported(input, "native_fork", "provider does not expose strong native thread ids"),
unsupported(
input,
"native_fork",
"providerInstanceId does not expose strong native thread ids",
),
);
}
return Effect.void;
@@ -235,12 +249,16 @@ const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
!input.capabilities.checkpointing.providerCanRollbackConversation
) {
return Effect.fail(
unsupported(input, "rollback", "provider conversation rollback is unavailable"),
unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"),
);
}
if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) {
return Effect.fail(
unsupported(input, "rollback_snapshot", "rollback must return a provider thread snapshot"),
unsupported(
input,
"rollback_snapshot",
"rollback must return a providerInstanceId thread snapshot",
),
);
}
return Effect.void;
@@ -249,12 +267,16 @@ const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => {
if (!input.capabilities.context.canConsumeHandoffSummaries) {
return Effect.fail(
unsupported(input, "context_handoff", "provider cannot consume handoff summaries"),
unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"),
);
}
if (!input.capabilities.context.acceptsSyntheticUserContext) {
return Effect.fail(
unsupported(input, "context_handoff", "provider cannot receive synthetic user context"),
unsupported(
input,
"context_handoff",
"providerInstanceId cannot receive synthetic user context",
),
);
}
if (
@@ -262,7 +284,7 @@ const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (inpu
!input.capabilities.context.supportsDeltaHandoff
) {
return Effect.fail(
unsupported(input, "context_handoff", "provider does not support delta handoff"),
unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"),
);
}
if (
@@ -270,7 +292,11 @@ const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (inpu
!input.capabilities.context.supportsFullThreadHandoff
) {
return Effect.fail(
unsupported(input, "context_handoff", "provider does not support full-thread handoff"),
unsupported(
input,
"context_handoff",
"providerInstanceId does not support full-thread handoff",
),
);
}
return Effect.void;
@@ -291,7 +317,7 @@ const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input)
return ensureContextHandoff({
commandId: input.commandId,
threadId: input.threadId,
provider: input.provider,
providerInstanceId: input.providerInstanceId,
capabilities: input.capabilities,
strategy: "full_thread_summary",
}).pipe(Effect.as("portable_context"));
@@ -311,7 +337,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in
commandId: input.commandId,
threadId: input.projection.thread.id,
requestedMode: input.requestedMode.type,
provider: modelSelection.provider,
providerInstanceId: modelSelection.instanceId,
}),
);
}
@@ -327,7 +353,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in
new CommandPolicyMessageDispatchError({
commandId: input.commandId,
threadId: input.projection.thread.id,
cause: `No running provider turn found for active run ${activeRun.id}.`,
cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`,
}),
)
: Effect.succeed({
@@ -343,7 +369,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in
commandId: input.commandId,
threadId: input.projection.thread.id,
requestedMode: input.requestedMode.type,
provider: modelSelection.provider,
providerInstanceId: modelSelection.instanceId,
}),
);
}
@@ -355,7 +381,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in
new CommandPolicyMessageDispatchError({
commandId: input.commandId,
threadId: input.projection.thread.id,
cause: `No running provider turn found for active run ${activeRun.id}.`,
cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`,
}),
)
: Effect.succeed({
@@ -370,7 +396,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in
: ensureQueuedMessages({
commandId: input.commandId,
threadId: input.projection.thread.id,
provider: modelSelection.provider,
providerInstanceId: modelSelection.instanceId,
capabilities: input.capabilities,
}).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
case "start_immediately":
@@ -380,7 +406,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in
return ensureQueuedMessages({
commandId: input.commandId,
threadId: input.projection.thread.id,
provider: modelSelection.provider,
providerInstanceId: modelSelection.instanceId,
capabilities: input.capabilities,
}).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
}
@@ -58,6 +58,9 @@ export const CommandReceiptV2 = Schema.Struct({
export type CommandReceiptV2 = typeof CommandReceiptV2.Type;
export interface CommandReceiptStoreV2Shape {
readonly insertIfAbsent: (
receipt: CommandReceiptV2,
) => Effect.Effect<boolean, CommandReceiptStoreV2Error>;
readonly upsert: (receipt: CommandReceiptV2) => Effect.Effect<void, CommandReceiptStoreV2Error>;
readonly getByCommandId: (
commandId: CommandId,
@@ -107,6 +110,38 @@ export const layer: Layer.Layer<CommandReceiptStoreV2, never, SqlClient.SqlClien
const sql = yield* SqlClient.SqlClient;
return CommandReceiptStoreV2.of({
insertIfAbsent: (receipt) =>
sql<{ readonly command_id: string }>`
INSERT INTO orchestration_v2_command_receipts (
command_id,
thread_id,
command_type,
accepted_at,
result_sequence,
status,
error
)
VALUES (
${receipt.commandId},
${receipt.threadId},
${receipt.commandType},
${DateTime.formatIso(receipt.acceptedAt)},
${receipt.resultSequence},
${receipt.status},
${receipt.error}
)
ON CONFLICT(command_id) DO NOTHING
RETURNING command_id
`.pipe(
Effect.map((rows) => rows.length === 1),
Effect.mapError(
(cause) =>
new CommandReceiptStoreWriteError({
commandId: receipt.commandId,
cause,
}),
),
),
upsert: (receipt) =>
sql`
INSERT INTO orchestration_v2_command_receipts (
@@ -1,7 +1,7 @@
import {
OrchestrationV2ContextHandoff,
type OrchestrationV2TurnItem,
type ProviderKind,
ProviderInstanceId,
ProviderThreadId,
RunId,
ThreadId,
@@ -46,8 +46,8 @@ export interface ContextHandoffServiceV2Shape {
readonly transferId: OrchestrationV2ContextHandoff["transferId"];
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
readonly toProviderThreadId: ProviderThreadId;
readonly fromProvider: ProviderKind;
readonly toProvider: ProviderKind;
readonly fromProviderInstanceId: ProviderInstanceId;
readonly toProviderInstanceId: ProviderInstanceId;
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
readonly createdAt: DateTime.Utc;
@@ -58,8 +58,8 @@ export interface ContextHandoffServiceV2Shape {
readonly transferId: NonNullable<OrchestrationV2ContextHandoff["transferId"]>;
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
readonly toProviderThreadId: ProviderThreadId;
readonly fromProvider: ProviderKind;
readonly toProvider: ProviderKind;
readonly fromProviderInstanceId: ProviderInstanceId;
readonly toProviderInstanceId: ProviderInstanceId;
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
readonly strategy: Extract<
OrchestrationV2ContextHandoff["strategy"],
@@ -124,8 +124,8 @@ function makeForkDeltaSummary(input: {
}
function makeProviderHandoffSummary(input: {
readonly fromProvider: ProviderKind;
readonly toProvider: ProviderKind;
readonly fromProviderInstanceId: ProviderInstanceId;
readonly toProviderInstanceId: ProviderInstanceId;
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
readonly strategy: Extract<
OrchestrationV2ContextHandoff["strategy"],
@@ -144,8 +144,8 @@ function makeProviderHandoffSummary(input: {
input.strategy === "full_thread_summary"
? "Full conversation context for provider handoff."
: "Conversation delta since this provider last participated.",
`From provider: ${input.fromProvider}`,
`To provider: ${input.toProvider}`,
`From driver: ${input.fromProviderInstanceId}`,
`To driver: ${input.toProviderInstanceId}`,
`Covered app runs: ${input.coveredRunOrdinals.from}-${input.coveredRunOrdinals.to}`,
"",
"Canonical conversation context:",
@@ -191,8 +191,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
const handoffId = yield* idAllocator.allocate
.contextHandoff({
threadId: input.threadId,
fromProvider: "codex",
toProvider: "codex",
fromProviderInstanceId: ProviderInstanceId.make("manual"),
toProviderInstanceId: ProviderInstanceId.make("manual"),
})
.pipe(
Effect.mapError(
@@ -218,7 +218,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
status: "ready",
summaryMessageId: null,
summaryText: "Manual context handoff.",
createdByProvider: null,
createdByProviderInstanceId: null,
createdAt: now,
updatedAt: now,
} satisfies OrchestrationV2ContextHandoff;
@@ -232,8 +232,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
readonly transferId: OrchestrationV2ContextHandoff["transferId"];
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
readonly toProviderThreadId: ProviderThreadId;
readonly fromProvider: ProviderKind;
readonly toProvider: ProviderKind;
readonly fromProviderInstanceId: ProviderInstanceId;
readonly toProviderInstanceId: ProviderInstanceId;
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
readonly createdAt: DateTime.Utc;
@@ -241,8 +241,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
const handoffId = yield* idAllocator.allocate
.contextHandoff({
threadId: input.targetThreadId,
fromProvider: input.fromProvider,
toProvider: input.toProvider,
fromProviderInstanceId: input.fromProviderInstanceId,
toProviderInstanceId: input.toProviderInstanceId,
})
.pipe(
Effect.mapError(
@@ -268,7 +268,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
status: "ready",
summaryMessageId: null,
summaryText: makeForkDeltaSummary(input),
createdByProvider: null,
createdByProviderInstanceId: null,
createdAt: input.createdAt,
updatedAt: input.createdAt,
} satisfies OrchestrationV2ContextHandoff;
@@ -283,8 +283,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
readonly transferId: NonNullable<OrchestrationV2ContextHandoff["transferId"]>;
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
readonly toProviderThreadId: ProviderThreadId;
readonly fromProvider: ProviderKind;
readonly toProvider: ProviderKind;
readonly fromProviderInstanceId: ProviderInstanceId;
readonly toProviderInstanceId: ProviderInstanceId;
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
readonly strategy: Extract<
OrchestrationV2ContextHandoff["strategy"],
@@ -296,8 +296,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
const handoffId = yield* idAllocator.allocate
.contextHandoff({
threadId: input.threadId,
fromProvider: input.fromProvider,
toProvider: input.toProvider,
fromProviderInstanceId: input.fromProviderInstanceId,
toProviderInstanceId: input.toProviderInstanceId,
})
.pipe(
Effect.mapError(
@@ -323,7 +323,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
status: "ready",
summaryMessageId: null,
summaryText: makeProviderHandoffSummary(input),
createdByProvider: null,
createdByProviderInstanceId: null,
createdAt: input.createdAt,
updatedAt: input.createdAt,
} satisfies OrchestrationV2ContextHandoff;
@@ -1,119 +0,0 @@
import {
MessageId,
NodeId,
OrchestrationV2ProviderRef,
ProviderKind,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
RawEventId,
RunAttemptId,
RunId,
RuntimeRequestId,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type * as Effect from "effect/Effect";
export const CorrelationScopeV2 = Schema.Struct({
provider: ProviderKind,
providerSessionId: Schema.optional(ProviderSessionId),
providerThreadId: Schema.optional(ProviderThreadId),
providerTurnId: Schema.optional(ProviderTurnId),
});
export type CorrelationScopeV2 = typeof CorrelationScopeV2.Type;
export const CorrelationEntityV2 = Schema.Union([
Schema.Struct({ type: Schema.Literal("thread"), id: ThreadId }),
Schema.Struct({ type: Schema.Literal("run"), id: RunId }),
Schema.Struct({ type: Schema.Literal("run_attempt"), id: RunAttemptId }),
Schema.Struct({ type: Schema.Literal("node"), id: NodeId }),
Schema.Struct({ type: Schema.Literal("message"), id: MessageId }),
Schema.Struct({ type: Schema.Literal("provider_session"), id: ProviderSessionId }),
Schema.Struct({ type: Schema.Literal("provider_thread"), id: ProviderThreadId }),
Schema.Struct({ type: Schema.Literal("provider_turn"), id: ProviderTurnId }),
Schema.Struct({ type: Schema.Literal("runtime_request"), id: RuntimeRequestId }),
Schema.Struct({ type: Schema.Literal("turn_item"), id: TurnItemId }),
Schema.Struct({ type: Schema.Literal("raw_event"), id: RawEventId }),
]);
export type CorrelationEntityV2 = typeof CorrelationEntityV2.Type;
export const CorrelationBindingV2 = Schema.Struct({
scope: CorrelationScopeV2,
providerRef: OrchestrationV2ProviderRef,
entity: CorrelationEntityV2,
createdByRawEventId: Schema.optional(RawEventId),
});
export type CorrelationBindingV2 = typeof CorrelationBindingV2.Type;
export class CorrelationBindError extends Schema.TaggedErrorClass<CorrelationBindError>()(
"CorrelationBindError",
{
scope: CorrelationScopeV2,
providerRef: OrchestrationV2ProviderRef,
entity: CorrelationEntityV2,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to bind ${this.scope.provider} provider ref to ${this.entity.type}.`;
}
}
export class CorrelationLookupError extends Schema.TaggedErrorClass<CorrelationLookupError>()(
"CorrelationLookupError",
{
scope: CorrelationScopeV2,
providerRef: Schema.optional(OrchestrationV2ProviderRef),
entity: Schema.optional(CorrelationEntityV2),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to look up ${this.scope.provider} provider correlation.`;
}
}
export class CorrelationOrdinalError extends Schema.TaggedErrorClass<CorrelationOrdinalError>()(
"CorrelationOrdinalError",
{
scope: CorrelationScopeV2,
key: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to allocate correlation ordinal for ${this.scope.provider}:${this.key}.`;
}
}
export const CorrelationStoreV2Error = Schema.Union([
CorrelationBindError,
CorrelationLookupError,
CorrelationOrdinalError,
]);
export type CorrelationStoreV2Error = typeof CorrelationStoreV2Error.Type;
export interface CorrelationStoreV2Shape {
readonly bind: (binding: CorrelationBindingV2) => Effect.Effect<void, CorrelationStoreV2Error>;
readonly lookupByProviderRef: (input: {
readonly scope: CorrelationScopeV2;
readonly providerRef: OrchestrationV2ProviderRef;
}) => Effect.Effect<Option.Option<CorrelationBindingV2>, CorrelationStoreV2Error>;
readonly lookupByEntity: (input: {
readonly scope: CorrelationScopeV2;
readonly entity: CorrelationEntityV2;
}) => Effect.Effect<Option.Option<CorrelationBindingV2>, CorrelationStoreV2Error>;
readonly nextOrdinal: (input: {
readonly scope: CorrelationScopeV2;
readonly key: string;
}) => Effect.Effect<number, CorrelationStoreV2Error>;
}
export class CorrelationStoreV2 extends Context.Service<
CorrelationStoreV2,
CorrelationStoreV2Shape
>()("t3/orchestration-v2/CorrelationStore/CorrelationStoreV2") {}
@@ -10,11 +10,18 @@ import {
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import { describe } from "vite-plus/test";
import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts";
import { ServerConfig } from "../config.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../provider/Layers/ProviderEventLoggers.ts";
import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
@@ -34,17 +41,30 @@ const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe(
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer));
const serverSettingsLayer = ServerSettingsService.layerTest({
providers: {
cursor: { enabled: true },
},
});
const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
Layer.provide(
Layer.mergeAll(
serverConfigLayer.pipe(Layer.provide(NodeServices.layer)),
serverSettingsLayer,
NodeServices.layer,
FetchHttpClient.layer,
OpenCodeRuntimeLive.pipe(Layer.provide(NodeServices.layer)),
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
),
),
);
const liveLayer = OrchestrationV2LayerLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(checkpointStoreLayer),
Layer.provide(serverConfigLayer),
Layer.provide(
ServerSettingsService.layerTest({
providers: {
cursor: { enabled: true },
},
}),
),
Layer.provide(serverSettingsLayer),
Layer.provide(providerInstanceRegistryLayer),
Layer.provide(NodeServices.layer),
);
@@ -141,11 +161,11 @@ describe.runIf(process.env.T3_CURSOR_LIVE_ORCHESTRATOR === "1")(
.join("\n");
assert.deepEqual(
sourceProjection.runs.map((run) => [run.provider, run.status]),
sourceProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[["cursor", "completed"]],
);
assert.deepEqual(
targetProjection.runs.map((run) => [run.provider, run.status]),
targetProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[["cursor", "completed"]],
);
assert.deepEqual(
@@ -0,0 +1,410 @@
import {
CheckpointId,
CheckpointScopeId,
CommandId,
MessageId,
ProviderSessionId,
RunAttemptId,
ProviderApprovalDecision,
ProviderUserInputAnswers,
ProviderThreadId,
ProviderTurnId,
RunId,
RuntimeRequestId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export const OrchestrationEffectRequestV2 = Schema.Union([
Schema.Struct({
type: Schema.Literal("provider-session.release"),
providerSessionId: ProviderSessionId,
reason: Schema.Literals([
"idle_timeout",
"runtime_error",
"manual_shutdown",
"server_shutdown",
]),
detail: Schema.optional(Schema.String),
}),
Schema.Struct({
type: Schema.Literal("provider-turn.start"),
runId: RunId,
}),
Schema.Struct({
type: Schema.Literal("provider-turn.interrupt"),
providerSessionId: ProviderSessionId,
providerThreadId: ProviderThreadId,
providerTurnId: ProviderTurnId,
}),
Schema.Struct({
type: Schema.Literal("provider-turn.steer"),
providerSessionId: ProviderSessionId,
providerThreadId: ProviderThreadId,
providerTurnId: ProviderTurnId,
messageId: MessageId,
}),
Schema.Struct({
type: Schema.Literal("provider-turn.restart"),
providerSessionId: ProviderSessionId,
providerThreadId: ProviderThreadId,
providerTurnId: ProviderTurnId,
interruptedAttemptId: RunAttemptId,
runId: RunId,
}),
Schema.Struct({
type: Schema.Literal("runtime-request.respond"),
providerSessionId: ProviderSessionId,
requestId: RuntimeRequestId,
decision: Schema.optional(ProviderApprovalDecision),
answers: Schema.optional(ProviderUserInputAnswers),
}),
Schema.Struct({
type: Schema.Literal("provider-thread.rollback"),
providerThreadId: ProviderThreadId,
checkpointId: CheckpointId,
scopeId: CheckpointScopeId,
}),
Schema.Struct({
type: Schema.Literal("provider-thread.fork"),
sourceProviderThreadId: ProviderThreadId,
targetProviderThreadId: ProviderThreadId,
}),
Schema.Struct({
type: Schema.Literal("checkpoint.capture"),
runId: RunId,
scopeId: CheckpointScopeId,
}),
Schema.Struct({
type: Schema.Literal("terminal.cleanup"),
runId: RunId,
}),
Schema.Struct({
type: Schema.Literal("attachment.cleanup"),
attachmentIds: Schema.Array(Schema.String),
}),
]);
export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type;
export const OrchestrationEffectStatusV2 = Schema.Literals([
"pending",
"running",
"succeeded",
"failed",
]);
export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type;
export interface OrchestrationEffectV2 {
readonly id: string;
readonly commandId: CommandId;
readonly threadId: ThreadId;
readonly request: OrchestrationEffectRequestV2;
readonly status: OrchestrationEffectStatusV2;
readonly attemptCount: number;
readonly availableAt: string;
readonly leaseOwner: string | null;
readonly leaseExpiresAt: string | null;
readonly createdAt: string;
readonly updatedAt: string;
readonly completedAt: string | null;
readonly lastError: string | null;
}
export interface PendingOrchestrationEffectV2 {
readonly id: string;
readonly commandId: CommandId;
readonly threadId: ThreadId;
readonly request: OrchestrationEffectRequestV2;
readonly availableAt?: DateTime.Utc;
}
export class EffectOutboxError extends Schema.TaggedErrorClass<EffectOutboxError>()(
"EffectOutboxError",
{
operation: Schema.String,
effectId: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Orchestration effect outbox ${this.operation} failed${this.effectId === undefined ? "" : ` for ${this.effectId}`}.`;
}
}
export interface EffectOutboxV2Shape {
readonly awaitAvailable: Effect.Effect<void>;
readonly notifyAvailable: Effect.Effect<void>;
readonly enqueue: (
effects: ReadonlyArray<PendingOrchestrationEffectV2>,
) => Effect.Effect<void, EffectOutboxError>;
readonly get: (
effectId: string,
) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
readonly listByCommandId: (
commandId: CommandId,
) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
readonly claimNext: (input: {
readonly workerId: string;
readonly leaseDurationMs: number;
}) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
readonly succeed: (input: {
readonly effectId: string;
readonly workerId: string;
}) => Effect.Effect<boolean, EffectOutboxError>;
readonly retry: (input: {
readonly effectId: string;
readonly workerId: string;
readonly error: string;
readonly delayMs: number;
}) => Effect.Effect<boolean, EffectOutboxError>;
readonly fail: (input: {
readonly effectId: string;
readonly workerId: string;
readonly error: string;
}) => Effect.Effect<boolean, EffectOutboxError>;
}
export class EffectOutboxV2 extends Context.Service<EffectOutboxV2, EffectOutboxV2Shape>()(
"t3/orchestration-v2/EffectOutbox/EffectOutboxV2",
) {}
type EffectRow = {
readonly effect_id: string;
readonly command_id: string;
readonly thread_id: string;
readonly effect_type: string;
readonly payload_json: string;
readonly status: string;
readonly attempt_count: number;
readonly available_at: string;
readonly lease_owner: string | null;
readonly lease_expires_at: string | null;
readonly created_at: string;
readonly updated_at: string;
readonly completed_at: string | null;
readonly last_error: string | null;
};
const encodeRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
const decodeRequest = Schema.decodeUnknownEffect(
Schema.fromJsonString(OrchestrationEffectRequestV2),
);
const rowToEffect = (row: EffectRow) =>
decodeRequest(row.payload_json).pipe(
Effect.map(
(request): OrchestrationEffectV2 => ({
id: row.effect_id,
commandId: CommandId.make(row.command_id),
threadId: ThreadId.make(row.thread_id),
request,
status: row.status as OrchestrationEffectStatusV2,
attemptCount: row.attempt_count,
availableAt: row.available_at,
leaseOwner: row.lease_owner,
leaseExpiresAt: row.lease_expires_at,
createdAt: row.created_at,
updatedAt: row.updated_at,
completedAt: row.completed_at,
lastError: row.last_error,
}),
),
);
export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layer.effect(
EffectOutboxV2,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const available = yield* Queue.unbounded<void>();
const decodeRows = (operation: string, rows: ReadonlyArray<EffectRow>) =>
Effect.forEach(rows, rowToEffect).pipe(
Effect.mapError((cause) => new EffectOutboxError({ operation, cause })),
);
const service: EffectOutboxV2Shape = {
enqueue: (effects) =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const nowIso = DateTime.formatIso(now);
yield* Effect.forEach(
effects,
(effect) => sql`
INSERT INTO orchestration_v2_effect_outbox (
effect_id,
command_id,
thread_id,
effect_type,
payload_json,
status,
attempt_count,
available_at,
created_at,
updated_at
)
VALUES (
${effect.id},
${effect.commandId},
${effect.threadId},
${effect.request.type},
${encodeRequest(effect.request)},
'pending',
0,
${DateTime.formatIso(effect.availableAt ?? now)},
${nowIso},
${nowIso}
)
ON CONFLICT(effect_id) DO NOTHING
`,
{ concurrency: 1, discard: true },
);
if (effects.length > 0) {
yield* Queue.offer(available, undefined);
}
}).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))),
get: (effectId) =>
sql<EffectRow>`
SELECT *
FROM orchestration_v2_effect_outbox
WHERE effect_id = ${effectId}
LIMIT 1
`.pipe(
Effect.flatMap((rows) => {
const row = rows[0];
return row === undefined
? Effect.succeed(Option.none())
: rowToEffect(row).pipe(Effect.map(Option.some));
}),
Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
),
awaitAvailable: Queue.take(available),
notifyAvailable: Queue.offer(available, undefined).pipe(Effect.asVoid),
listByCommandId: (commandId) =>
sql<EffectRow>`
SELECT *
FROM orchestration_v2_effect_outbox
WHERE command_id = ${commandId}
ORDER BY created_at ASC, effect_id ASC
`.pipe(
Effect.flatMap((rows) => decodeRows("list", rows)),
Effect.mapError((cause) =>
Schema.is(EffectOutboxError)(cause)
? cause
: new EffectOutboxError({ operation: "list", cause }),
),
),
claimNext: ({ workerId, leaseDurationMs }) =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const nowIso = DateTime.formatIso(now);
const leaseExpiresAt = DateTime.formatIso(
DateTime.add(now, { milliseconds: Math.max(1, leaseDurationMs) }),
);
const rows = yield* sql<EffectRow>`
UPDATE orchestration_v2_effect_outbox
SET
status = 'running',
attempt_count = attempt_count + 1,
lease_owner = ${workerId},
lease_expires_at = ${leaseExpiresAt},
updated_at = ${nowIso},
last_error = NULL
WHERE effect_id = (
SELECT effect_id
FROM orchestration_v2_effect_outbox
WHERE available_at <= ${nowIso}
AND (
status = 'pending'
OR (status = 'running' AND lease_expires_at <= ${nowIso})
)
ORDER BY available_at ASC, created_at ASC, effect_id ASC
LIMIT 1
)
RETURNING *
`;
const row = rows[0];
return row === undefined ? Option.none() : Option.some(yield* rowToEffect(row));
}).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))),
succeed: ({ effectId, workerId }) =>
Effect.gen(function* () {
const now = DateTime.formatIso(yield* DateTime.now);
const rows = yield* sql<{ readonly effect_id: string }>`
UPDATE orchestration_v2_effect_outbox
SET
status = 'succeeded',
lease_owner = NULL,
lease_expires_at = NULL,
completed_at = ${now},
updated_at = ${now},
last_error = NULL
WHERE effect_id = ${effectId}
AND status = 'running'
AND lease_owner = ${workerId}
RETURNING effect_id
`;
return rows.length === 1;
}).pipe(
Effect.mapError(
(cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
),
),
retry: ({ effectId, workerId, error, delayMs }) =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const nowIso = DateTime.formatIso(now);
const availableAt = DateTime.formatIso(
DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
);
const rows = yield* sql<{ readonly effect_id: string }>`
UPDATE orchestration_v2_effect_outbox
SET
status = 'pending',
available_at = ${availableAt},
lease_owner = NULL,
lease_expires_at = NULL,
updated_at = ${nowIso},
last_error = ${error}
WHERE effect_id = ${effectId}
AND status = 'running'
AND lease_owner = ${workerId}
RETURNING effect_id
`;
return rows.length === 1;
}).pipe(
Effect.mapError(
(cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
),
),
fail: ({ effectId, workerId, error }) =>
Effect.gen(function* () {
const now = DateTime.formatIso(yield* DateTime.now);
const rows = yield* sql<{ readonly effect_id: string }>`
UPDATE orchestration_v2_effect_outbox
SET
status = 'failed',
lease_owner = NULL,
lease_expires_at = NULL,
completed_at = ${now},
updated_at = ${now},
last_error = ${error}
WHERE effect_id = ${effectId}
AND status = 'running'
AND lease_owner = ${workerId}
RETURNING effect_id
`;
return rows.length === 1;
}).pipe(
Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })),
),
};
return service;
}),
);
@@ -0,0 +1,352 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { CheckpointCaptureServiceV2 } from "./CheckpointCaptureService.ts";
import { EffectOutboxV2, type OrchestrationEffectV2 } from "./EffectOutbox.ts";
import { CheckpointRollbackServiceV2 } from "./CheckpointRollbackService.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts";
import { ProviderTurnStartServiceV2 } from "./ProviderTurnStartService.ts";
import { RuntimeRequestServiceV2 } from "./RuntimeRequestService.ts";
export class OrchestrationEffectExecutionError extends Schema.TaggedErrorClass<OrchestrationEffectExecutionError>()(
"OrchestrationEffectExecutionError",
{
effectId: Schema.String,
effectType: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {}
export interface OrchestrationEffectExecutorV2Shape {
readonly execute: (
effect: OrchestrationEffectV2,
) => Effect.Effect<void, OrchestrationEffectExecutionError>;
}
export class OrchestrationEffectExecutorV2 extends Context.Service<
OrchestrationEffectExecutorV2,
OrchestrationEffectExecutorV2Shape
>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectExecutorV2") {}
export const executorLayer: Layer.Layer<
OrchestrationEffectExecutorV2,
never,
| ProviderSessionManagerV2
| CheckpointCaptureServiceV2
| CheckpointRollbackServiceV2
| ProviderTurnControlServiceV2
| ProviderTurnStartServiceV2
| RuntimeRequestServiceV2
> = Layer.effect(
OrchestrationEffectExecutorV2,
Effect.gen(function* () {
const checkpointCapture = yield* CheckpointCaptureServiceV2;
const checkpointRollback = yield* CheckpointRollbackServiceV2;
const providerSessions = yield* ProviderSessionManagerV2;
const providerTurnControl = yield* ProviderTurnControlServiceV2;
const providerTurnStart = yield* ProviderTurnStartServiceV2;
const runtimeRequests = yield* RuntimeRequestServiceV2;
return OrchestrationEffectExecutorV2.of({
execute: (effect) => {
switch (effect.request.type) {
case "provider-session.release":
return providerSessions
.release({
providerSessionId: effect.request.providerSessionId,
reason: effect.request.reason,
...(effect.request.detail === undefined ? {} : { detail: effect.request.detail }),
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
case "provider-turn.start":
return providerTurnStart
.start({ threadId: effect.threadId, runId: effect.request.runId })
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
case "provider-turn.interrupt":
return providerTurnControl
.interrupt({
threadId: effect.threadId,
providerSessionId: effect.request.providerSessionId,
providerThreadId: effect.request.providerThreadId,
providerTurnId: effect.request.providerTurnId,
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
case "provider-turn.steer":
return providerTurnControl
.steer({
threadId: effect.threadId,
providerSessionId: effect.request.providerSessionId,
providerThreadId: effect.request.providerThreadId,
providerTurnId: effect.request.providerTurnId,
messageId: effect.request.messageId,
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
case "provider-turn.restart":
return providerTurnControl
.interruptAndAwaitTerminal({
threadId: effect.threadId,
providerSessionId: effect.request.providerSessionId,
providerThreadId: effect.request.providerThreadId,
providerTurnId: effect.request.providerTurnId,
interruptedAttemptId: effect.request.interruptedAttemptId,
})
.pipe(
Effect.andThen(
providerTurnStart.start({
threadId: effect.threadId,
runId: effect.request.runId,
}),
),
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
case "runtime-request.respond":
return runtimeRequests
.respond({
threadId: effect.threadId,
providerSessionId: effect.request.providerSessionId,
requestId: effect.request.requestId,
...(effect.request.decision === undefined
? {}
: { decision: effect.request.decision }),
...(effect.request.answers === undefined
? {}
: { answers: effect.request.answers }),
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
case "provider-thread.rollback":
return checkpointRollback
.execute({
threadId: effect.threadId,
providerThreadId: effect.request.providerThreadId,
checkpointId: effect.request.checkpointId,
scopeId: effect.request.scopeId,
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
case "checkpoint.capture":
return checkpointCapture
.execute({
threadId: effect.threadId,
runId: effect.request.runId,
scopeId: effect.request.scopeId,
})
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause,
}),
),
);
case "provider-thread.fork":
case "terminal.cleanup":
case "attachment.cleanup":
return Effect.fail(
new OrchestrationEffectExecutionError({
effectId: effect.id,
effectType: effect.request.type,
cause: `No Shape 1 executor is registered for ${effect.request.type}.`,
}),
);
}
},
});
}),
);
export class OrchestrationEffectWorkerError extends Schema.TaggedErrorClass<OrchestrationEffectWorkerError>()(
"OrchestrationEffectWorkerError",
{
operation: Schema.String,
effectId: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
},
) {}
export interface OrchestrationEffectWorkerV2Shape {
readonly awaitWork: Effect.Effect<void>;
readonly runOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
readonly drain: (maxEffects?: number) => Effect.Effect<number, OrchestrationEffectWorkerError>;
}
export class OrchestrationEffectWorkerV2 extends Context.Service<
OrchestrationEffectWorkerV2,
OrchestrationEffectWorkerV2Shape
>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {}
export interface OrchestrationEffectWorkerOptions {
readonly workerId?: string;
readonly leaseDurationMs?: number;
readonly maxAttempts?: number;
}
export const layerWithOptions = (
options: OrchestrationEffectWorkerOptions = {},
): Layer.Layer<
OrchestrationEffectWorkerV2,
never,
EffectOutboxV2 | OrchestrationEffectExecutorV2
> =>
Layer.effect(
OrchestrationEffectWorkerV2,
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
const executor = yield* OrchestrationEffectExecutorV2;
const workerId = options.workerId ?? `orchestration-v2:${process.pid}`;
const leaseDurationMs = Math.max(1, options.leaseDurationMs ?? 30_000);
const maxAttempts = Math.max(1, options.maxAttempts ?? 5);
const runOnce = Effect.gen(function* () {
const claimed = yield* outbox.claimNext({ workerId, leaseDurationMs });
if (Option.isNone(claimed)) {
return false;
}
const effect = claimed.value;
const exit = yield* Effect.exit(executor.execute(effect));
if (Exit.isSuccess(exit)) {
const completed = yield* outbox.succeed({ effectId: effect.id, workerId });
if (!completed) {
return yield* new OrchestrationEffectWorkerError({
operation: "complete",
effectId: effect.id,
cause: "The worker no longer owns the effect lease.",
});
}
return true;
}
const error = Cause.pretty(exit.cause);
yield* Effect.logWarning("Orchestration effect execution failed", {
effectId: effect.id,
effectType: effect.request.type,
attemptCount: effect.attemptCount,
error,
});
const updated =
effect.attemptCount >= maxAttempts
? yield* outbox.fail({ effectId: effect.id, workerId, error })
: yield* outbox.retry({
effectId: effect.id,
workerId,
error,
delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)),
});
if (!updated) {
return yield* new OrchestrationEffectWorkerError({
operation: "reschedule",
effectId: effect.id,
cause: "The worker no longer owns the effect lease.",
});
}
return true;
}).pipe(
Effect.mapError((cause) =>
Schema.is(OrchestrationEffectWorkerError)(cause)
? cause
: new OrchestrationEffectWorkerError({ operation: "run", cause }),
),
);
return OrchestrationEffectWorkerV2.of({
awaitWork: outbox.awaitAvailable,
runOnce,
drain: (maxEffects = Number.MAX_SAFE_INTEGER) =>
Effect.gen(function* () {
let completed = 0;
while (completed < maxEffects && (yield* runOnce)) {
completed += 1;
}
return completed;
}),
});
}),
);
export const layer = layerWithOptions();
export const daemonLayer: Layer.Layer<never, never, OrchestrationEffectWorkerV2> =
Layer.effectDiscard(
Effect.gen(function* () {
const worker = yield* OrchestrationEffectWorkerV2;
yield* Effect.forever(
worker.runOnce.pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)),
),
Effect.flatMap((worked) =>
worked
? Effect.yieldNow
: Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))),
),
),
).pipe(Effect.forkScoped);
}),
);
+311 -20
View File
@@ -5,15 +5,31 @@ import {
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
CommandReceiptStoreV2,
type CommandReceiptV2,
layer as commandReceiptStoreLayer,
} from "./CommandReceiptStore.ts";
import {
EffectOutboxV2,
type PendingOrchestrationEffectV2,
layer as effectOutboxLayer,
} from "./EffectOutbox.ts";
import { EventStoreV2 } from "./EventStore.ts";
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
import {
TurnItemPositionStoreV2,
layer as turnItemPositionStoreLayer,
} from "./TurnItemPositionStore.ts";
/**
* ERRORS
@@ -57,6 +73,33 @@ export interface EventSinkV2Shape {
readonly commandId?: CommandId;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
readonly writeWithEffects: (input: {
readonly commandId?: CommandId;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
readonly effects: ReadonlyArray<PendingOrchestrationEffectV2>;
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
readonly commitCommand: (input: {
readonly commandId: CommandId;
readonly threadId: ThreadId;
readonly commandType: string;
readonly acceptedAt: DateTime.Utc;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
readonly effects: ReadonlyArray<PendingOrchestrationEffectV2>;
}) => Effect.Effect<
{
readonly receipt: CommandReceiptV2;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
readonly committed: boolean;
},
EventSinkV2Error
>;
readonly commitRejectedCommand: (input: {
readonly commandId: CommandId;
readonly threadId: ThreadId;
readonly commandType: string;
readonly rejectedAt: DateTime.Utc;
readonly error: string;
}) => Effect.Effect<CommandReceiptV2, EventSinkV2Error>;
readonly stream: (input?: {
readonly threadId?: ThreadId;
readonly afterSequence?: number;
@@ -76,20 +119,76 @@ export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>(
/**
* IMPLEMENTATIONS
*/
export const layer: Layer.Layer<
const baseLayer: Layer.Layer<
EventSinkV2,
never,
EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient
| CommandReceiptStoreV2
| EffectOutboxV2
| EventStoreV2
| ProjectionStoreV2
| SqlClient.SqlClient
| TurnItemPositionStoreV2
> = Layer.effect(
EventSinkV2,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const commandReceipts = yield* CommandReceiptStoreV2;
const effectOutbox = yield* EffectOutboxV2;
const eventStore = yield* EventStoreV2;
const projectionStore = yield* ProjectionStoreV2;
const turnItemPositions = yield* TurnItemPositionStoreV2;
const liveEvents = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
const normalizeEvents = (events: ReadonlyArray<OrchestrationV2DomainEvent>) => {
const runOrdinals = new Map(
events.flatMap((event) =>
event.type === "run.created" || event.type === "run.updated"
? [[event.payload.id, event.payload.ordinal] as const]
: [],
),
);
return Effect.forEach(
events,
(event): Effect.Effect<OrchestrationV2DomainEvent, unknown> =>
event.type === "turn-item.updated"
? turnItemPositions
.normalize(
event.payload,
event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId),
)
.pipe(Effect.map((payload) => ({ ...event, payload })))
: Effect.succeed(event),
{ concurrency: 1 },
);
};
const applyStoredEvents = (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) =>
Effect.gen(function* () {
yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), {
concurrency: 1,
});
const sequence = storedEvents.at(-1)?.sequence;
if (sequence !== undefined) {
const now = DateTime.formatIso(yield* DateTime.now);
yield* sql`
INSERT INTO orchestration_v2_projection_metadata (
projection_name,
schema_version,
last_sequence,
updated_at
)
VALUES ('thread-projections', 1, ${sequence}, ${now})
ON CONFLICT(projection_name)
DO UPDATE SET
schema_version = excluded.schema_version,
last_sequence = excluded.last_sequence,
updated_at = excluded.updated_at
`;
}
});
const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* (
input: Parameters<EventSinkV2Shape["write"]>[0],
input: Parameters<EventSinkV2Shape["writeWithEffects"]>[0],
) {
yield* Effect.annotateCurrentSpan({
"orchestration_v2.command_id": input.commandId ?? null,
@@ -99,22 +198,186 @@ export const layer: Layer.Layer<
const storedEvents = yield* sql.withTransaction(
Effect.gen(function* () {
const normalized = yield* normalizeEvents(input.events);
const committed = yield* eventStore.append({
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
events: input.events,
});
yield* Effect.forEach(committed, (stored) => projectionStore.apply(stored.event), {
concurrency: 1,
events: normalized,
});
yield* applyStoredEvents(committed);
yield* effectOutbox.enqueue(input.effects);
return committed;
}),
);
if (input.effects.length > 0) {
yield* effectOutbox.notifyAvailable;
}
yield* PubSub.publishAll(liveEvents, storedEvents);
return storedEvents;
});
const existingCommandResult = (commandId: CommandId) =>
Effect.gen(function* () {
const existing = yield* commandReceipts.getByCommandId(commandId);
if (Option.isNone(existing)) {
return yield* Effect.die(
new Error(`Command receipt ${commandId} disappeared during its transaction.`),
);
}
const storedEvents = yield* eventStore.readByCommandId({ commandId }).pipe(
Stream.runCollect,
Effect.map((events): ReadonlyArray<OrchestrationV2StoredEvent> => Array.from(events)),
);
return { receipt: existing.value, storedEvents };
});
const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* (
input: Parameters<EventSinkV2Shape["commitCommand"]>[0],
) {
const result = yield* sql.withTransaction(
Effect.gen(function* () {
const reserved = yield* commandReceipts.insertIfAbsent({
commandId: input.commandId,
threadId: input.threadId,
commandType: input.commandType,
acceptedAt: input.acceptedAt,
resultSequence: 0,
status: "accepted",
error: null,
});
if (!reserved) {
const existing = yield* existingCommandResult(input.commandId);
return { ...existing, committed: false as const };
}
const normalized = yield* normalizeEvents(input.events);
const storedEvents = yield* eventStore.append({
commandId: input.commandId,
events: normalized,
});
const sequence = storedEvents.at(-1)?.sequence;
if (sequence === undefined) {
return yield* Effect.die(
new Error(`Command ${input.commandId} produced no orchestration events.`),
);
}
yield* applyStoredEvents(storedEvents);
yield* effectOutbox.enqueue(input.effects);
const receipt: CommandReceiptV2 = {
commandId: input.commandId,
threadId: input.threadId,
commandType: input.commandType,
acceptedAt: input.acceptedAt,
resultSequence: sequence,
status: "accepted",
error: null,
};
yield* commandReceipts.upsert(receipt);
return { receipt, storedEvents, committed: true as const };
}),
);
if (input.effects.length > 0) {
yield* effectOutbox.notifyAvailable;
}
if (result.committed) {
yield* PubSub.publishAll(liveEvents, result.storedEvents);
}
return result;
});
const commitRejectedCommandEffect = Effect.fn(
"orchestrationV2.EventSink.commitRejectedCommand",
)(function* (input: Parameters<EventSinkV2Shape["commitRejectedCommand"]>[0]) {
return yield* sql.withTransaction(
Effect.gen(function* () {
const sequence = yield* eventStore.latestSequence({ threadId: input.threadId });
const receipt: CommandReceiptV2 = {
commandId: input.commandId,
threadId: input.threadId,
commandType: input.commandType,
acceptedAt: input.rejectedAt,
resultSequence: sequence,
status: "rejected",
error: input.error,
};
const inserted = yield* commandReceipts.insertIfAbsent(receipt);
if (inserted) {
return receipt;
}
const existing = yield* commandReceipts.getByCommandId(input.commandId);
return Option.getOrElse(existing, () => receipt);
}),
);
});
const catchUp = (input: {
readonly afterSequence: number;
readonly throughSequence: number;
readonly threadId?: ThreadId;
}): Stream.Stream<OrchestrationV2StoredEvent, unknown> => {
const pageSize = 256;
const loop = (afterSequence: number): Stream.Stream<OrchestrationV2StoredEvent, unknown> =>
Stream.unwrap(
eventStore
.read({
afterSequence,
throughSequence: input.throughSequence,
...(input.threadId === undefined ? {} : { threadId: input.threadId }),
limit: pageSize,
})
.pipe(
Stream.runCollect,
Effect.map((chunk) => Array.from(chunk)),
Effect.map((events) => {
if (events.length === 0) {
return Stream.empty;
}
const current = Stream.fromIterable(events);
const last = events.at(-1)?.sequence ?? input.throughSequence;
return events.length < pageSize || last >= input.throughSequence
? current
: Stream.concat(current, loop(last));
}),
),
);
return loop(input.afterSequence);
};
const stream = (input?: { readonly threadId?: ThreadId; readonly afterSequence?: number }) =>
Stream.unwrap(
Effect.gen(function* () {
// Subscribe first, then capture the database high-water mark. Events
// committed between those operations are buffered by the subscription.
const subscription = yield* PubSub.subscribe(liveEvents);
const highWater = yield* eventStore.latestSequence();
const afterSequence = input?.afterSequence ?? 0;
const replay = catchUp({
afterSequence,
throughSequence: highWater,
...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
});
const live = Stream.fromSubscription(subscription).pipe(
Stream.filter((stored) => stored.sequence > Math.max(highWater, afterSequence)),
Stream.filter(
(stored) => input?.threadId === undefined || stored.event.threadId === input.threadId,
),
);
return Stream.concat(replay, live);
}),
);
return EventSinkV2.of({
write: (input) =>
writeEffect({ ...input, effects: [] }).pipe(
Effect.mapError(
(cause) =>
new EventSinkWriteError({
eventCount: input.events.length,
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
cause,
}),
),
),
writeWithEffects: (input) =>
writeEffect(input).pipe(
Effect.mapError(
(cause) =>
@@ -125,20 +388,30 @@ export const layer: Layer.Layer<
}),
),
),
stream: (input) =>
eventStore.read(input).pipe(
Stream.concat(
Stream.fromPubSub(liveEvents).pipe(
Stream.filter(
(stored) =>
input?.threadId === undefined || stored.event.threadId === input.threadId,
),
Stream.filter(
(stored) =>
input?.afterSequence === undefined || stored.sequence > input.afterSequence,
),
),
commitCommand: (input) =>
commitCommandEffect(input).pipe(
Effect.mapError(
(cause) =>
new EventSinkWriteError({
commandId: input.commandId,
eventCount: input.events.length,
cause,
}),
),
),
commitRejectedCommand: (input) =>
commitRejectedCommandEffect(input).pipe(
Effect.mapError(
(cause) =>
new EventSinkWriteError({
commandId: input.commandId,
eventCount: 0,
cause,
}),
),
),
stream: (input) =>
stream(input).pipe(
Stream.mapError(
(cause) =>
new EventSinkStreamError({
@@ -172,3 +445,21 @@ export const layer: Layer.Layer<
} satisfies EventSinkV2Shape);
}),
);
/**
* Event sink layer for application compositions that already own the
* persistence services. Keeping the outbox instance shared with the worker is
* important because enqueue notifications are in-memory wakeups backed by the
* durable SQL queue.
*/
export const layerFromStores = baseLayer;
export const layer: Layer.Layer<
EventSinkV2,
never,
EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient
> = baseLayer.pipe(
Layer.provide(
Layer.mergeAll(commandReceiptStoreLayer, effectOutboxLayer, turnItemPositionStoreLayer),
),
);
+16 -7
View File
@@ -58,6 +58,7 @@ export interface EventStoreV2Shape {
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventStoreV2Error>;
readonly read: (input?: {
readonly afterSequence?: number;
readonly throughSequence?: number;
readonly threadId?: ThreadId;
readonly limit?: number;
}) => Stream.Stream<OrchestrationV2StoredEvent, EventStoreV2Error>;
@@ -83,7 +84,8 @@ type EventRow = {
readonly thread_id: string;
readonly run_id: string | null;
readonly node_id: string | null;
readonly provider: string | null;
readonly driver: string | null;
readonly provider_instance_id: string | null;
readonly raw_event_id: string | null;
readonly event_type: string;
readonly occurred_at: string;
@@ -119,7 +121,8 @@ export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = Laye
threadId: row.thread_id,
runId: row.run_id ?? undefined,
nodeId: row.node_id ?? undefined,
provider: row.provider ?? undefined,
driver: row.driver ?? undefined,
providerInstanceId: row.provider_instance_id ?? undefined,
rawEventId: row.raw_event_id ?? undefined,
type: row.event_type,
occurredAt: row.occurred_at,
@@ -161,7 +164,8 @@ export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = Laye
thread_id,
run_id,
node_id,
provider,
driver,
provider_instance_id,
raw_event_id,
event_type,
occurred_at,
@@ -173,7 +177,8 @@ export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = Laye
${event.threadId},
${event.runId ?? null},
${event.nodeId ?? null},
${event.provider ?? null},
${event.driver ?? null},
${event.providerInstanceId ?? null},
${event.rawEventId ?? null},
${event.type},
${normalized.occurredAt},
@@ -186,7 +191,8 @@ export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = Laye
thread_id,
run_id,
node_id,
provider,
driver,
provider_instance_id,
raw_event_id,
event_type,
occurred_at,
@@ -230,13 +236,15 @@ export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = Laye
thread_id,
run_id,
node_id,
provider,
driver,
provider_instance_id,
raw_event_id,
event_type,
occurred_at,
payload_json
FROM orchestration_v2_events
WHERE sequence > ${input?.afterSequence ?? 0}
AND sequence <= ${input?.throughSequence ?? Number.MAX_SAFE_INTEGER}
AND (${input?.threadId ?? null} IS NULL OR thread_id = ${input?.threadId ?? null})
ORDER BY sequence ASC
LIMIT ${input?.limit ?? 1000}
@@ -267,7 +275,8 @@ export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = Laye
thread_id,
run_id,
node_id,
provider,
driver,
provider_instance_id,
raw_event_id,
event_type,
occurred_at,
@@ -0,0 +1,475 @@
import { assert, it } from "@effect/vitest";
import {
CheckpointId,
CheckpointRef,
CheckpointScopeId,
CommandId,
EventId,
MessageId,
type ModelSelection,
NodeId,
type OrchestrationV2AppThread,
type OrchestrationV2DomainEvent,
ProjectId,
ProviderInstanceId,
RunId,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { CommandReceiptStoreV2, layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts";
import { EffectOutboxV2, layer as effectOutboxLayer } from "./EffectOutbox.ts";
import {
layerWithOptions as effectWorkerLayerWithOptions,
OrchestrationEffectExecutorV2,
OrchestrationEffectWorkerV2,
} from "./EffectWorker.ts";
import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts";
import { EventStoreV2, layer as eventStoreLayer } from "./EventStore.ts";
import {
ProjectionMaintenanceV2,
layer as projectionMaintenanceLayer,
} from "./ProjectionMaintenance.ts";
import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts";
const databaseLayer = SqlitePersistenceMemory;
const eventStoreProvided = eventStoreLayer.pipe(Layer.provideMerge(databaseLayer));
const projectionStoreProvided = projectionStoreLayer.pipe(Layer.provideMerge(databaseLayer));
const storesProvided = Layer.mergeAll(databaseLayer, eventStoreProvided, projectionStoreProvided);
const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesProvided));
const effectOutboxProvided = effectOutboxLayer.pipe(Layer.provide(databaseLayer));
const commandReceiptStoreProvided = commandReceiptStoreLayer.pipe(Layer.provide(databaseLayer));
const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(
Layer.provide(storesProvided),
);
const TestLayer = Layer.mergeAll(
storesProvided,
eventSinkProvided,
effectOutboxProvided,
commandReceiptStoreProvided,
projectionMaintenanceProvided,
);
const providerInstanceId = ProviderInstanceId.make("codex");
const modelSelection = {
instanceId: providerInstanceId,
model: "gpt-5.4",
} satisfies ModelSelection;
function makeThread(threadId: ThreadId, now: DateTime.Utc): OrchestrationV2AppThread {
return {
createdBy: "user",
creationSource: "web",
id: threadId,
projectId: ProjectId.make(`project:${threadId}`),
title: `Thread ${threadId}`,
providerInstanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: {
parentThreadId: null,
relationshipToParent: null,
rootThreadId: threadId,
},
forkedFrom: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
deletedAt: null,
};
}
function threadCreatedEvent(input: {
readonly id: string;
readonly thread: OrchestrationV2AppThread;
readonly now: DateTime.Utc;
}): OrchestrationV2DomainEvent {
return {
id: EventId.make(input.id),
type: "thread.created",
threadId: input.thread.id,
providerInstanceId,
occurredAt: input.now,
payload: input.thread,
};
}
it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
it.effect("paginates catch-up beyond the event-store read limit", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread:foundation-large-catch-up");
const thread = makeThread(threadId, now);
const eventCount = 1_005;
const events: Array<OrchestrationV2DomainEvent> = [
threadCreatedEvent({ id: "event:foundation-catch-up:0", thread, now }),
...Array.from({ length: eventCount - 1 }, (_, index) => ({
id: EventId.make(`event:foundation-catch-up:${index + 1}`),
type: "thread.metadata-updated" as const,
threadId,
providerInstanceId,
occurredAt: now,
payload: {
...thread,
title: `Catch-up update ${index + 1}`,
},
})),
];
yield* eventSink.write({ events });
const replayed = yield* eventSink.stream({ afterSequence: 0 }).pipe(
Stream.take(eventCount),
Stream.runCollect,
Effect.map((events) => Array.from(events)),
);
assert.lengthOf(replayed, eventCount);
assert.deepEqual(
replayed.map((stored) => stored.sequence),
Array.from({ length: eventCount }, (_, index) => index + 1),
);
}),
);
it.effect("does not lose or duplicate events while transitioning from catch-up to live", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread:foundation-stream-race");
const thread = makeThread(threadId, now);
const created = yield* eventSink.write({
events: [threadCreatedEvent({ id: "event:foundation-stream-race:0", thread, now })],
});
let afterSequence = created[0]!.sequence;
for (let index = 1; index <= 32; index += 1) {
const nextEvent = {
id: EventId.make(`event:foundation-stream-race:${index}`),
type: "thread.metadata-updated" as const,
threadId,
providerInstanceId,
occurredAt: now,
payload: { ...thread, title: `Race update ${index}` },
} satisfies OrchestrationV2DomainEvent;
const reader = yield* eventSink
.stream({ threadId, afterSequence })
.pipe(Stream.runHead, Effect.forkChild);
yield* Effect.yieldNow;
const written = yield* eventSink.write({ events: [nextEvent] });
const received = yield* Fiber.join(reader);
if (Option.isNone(received)) {
return yield* Effect.die("The event stream ended before delivering the live event.");
}
assert.equal(received.value.sequence, written[0]?.sequence);
assert.equal(received.value.event.id, nextEvent.id);
afterSequence = received.value.sequence;
}
}),
);
it.effect(
"rolls back events, projections, receipts, and effects after a projection failure",
() =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const eventStore = yield* EventStoreV2;
const receipts = yield* CommandReceiptStoreV2;
const outbox = yield* EffectOutboxV2;
const sql = yield* SqlClient.SqlClient;
const now = yield* DateTime.now;
const commandId = CommandId.make("command:foundation-atomic-failure");
const threadId = ThreadId.make("thread:foundation-atomic-failure");
const scopeId = CheckpointScopeId.make("scope:foundation-atomic-failure");
const checkpoint = (index: number) => ({
id: CheckpointId.make(`checkpoint:foundation-atomic-failure:${index}`),
threadId,
scopeId,
runId: null,
nodeId: NodeId.make("node:foundation-atomic-failure"),
parentCheckpointId: null,
ordinalWithinScope: 1,
appRunOrdinal: null,
ref: CheckpointRef.make(`checkpoint-ref:foundation-atomic-failure:${index}`),
status: "ready" as const,
files: [],
capturedAt: now,
});
const events = [1, 2].map(
(index) =>
({
id: EventId.make(`event:foundation-atomic-failure:${index}`),
type: "checkpoint.captured",
threadId,
occurredAt: now,
payload: checkpoint(index),
}) satisfies OrchestrationV2DomainEvent,
);
const exit = yield* Effect.exit(
eventSink.commitCommand({
commandId,
threadId,
commandType: "checkpoint.atomicity-test",
acceptedAt: now,
events,
effects: [
{
id: "effect:foundation-atomic-failure",
commandId,
threadId,
request: {
type: "provider-turn.start",
runId: RunId.make("run:foundation-atomic-failure"),
},
},
],
}),
);
assert.equal(exit._tag, "Failure");
assert.isTrue(Option.isNone(yield* receipts.getByCommandId(commandId)));
assert.deepEqual(yield* outbox.listByCommandId(commandId), []);
assert.deepEqual(
yield* eventStore.readByCommandId({ commandId }).pipe(
Stream.runCollect,
Effect.map((events) => Array.from(events)),
),
[],
);
const checkpointRows = yield* sql<{ readonly count: number }>`
SELECT COUNT(*) AS count
FROM orchestration_v2_projection_checkpoints
WHERE thread_id = ${threadId}
`;
assert.equal(checkpointRows[0]?.count, 0);
}),
);
it.effect("keeps one durable effect across command retries and executes it after recovery", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const outbox = yield* EffectOutboxV2;
const now = yield* DateTime.now;
const commandId = CommandId.make("command:foundation-effect-recovery");
const threadId = ThreadId.make("thread:foundation-effect-recovery");
const thread = makeThread(threadId, now);
const event = threadCreatedEvent({
id: "event:foundation-effect-recovery",
thread,
now,
});
const effect = {
id: "effect:foundation-effect-recovery",
commandId,
threadId,
request: {
type: "provider-turn.start" as const,
runId: RunId.make("run:foundation-effect-recovery"),
},
};
const first = yield* eventSink.commitCommand({
commandId,
threadId,
commandType: "foundation.effect-recovery",
acceptedAt: now,
events: [event],
effects: [effect],
});
const retry = yield* eventSink.commitCommand({
commandId,
threadId,
commandType: "foundation.effect-recovery",
acceptedAt: now,
events: [event],
effects: [effect],
});
assert.isTrue(first.committed);
assert.isFalse(retry.committed);
assert.equal(retry.receipt.resultSequence, first.receipt.resultSequence);
assert.lengthOf(retry.storedEvents, 1);
assert.lengthOf(yield* outbox.listByCommandId(commandId), 1);
const executionCount = yield* Ref.make(0);
const executorLayer = Layer.succeed(
OrchestrationEffectExecutorV2,
OrchestrationEffectExecutorV2.of({
execute: () => Ref.update(executionCount, (count) => count + 1),
}),
);
const workerLayer = effectWorkerLayerWithOptions({ workerId: "recovery-worker" }).pipe(
Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer)),
);
yield* Effect.gen(function* () {
const worker = yield* OrchestrationEffectWorkerV2;
assert.isTrue(yield* worker.runOnce);
assert.isFalse(yield* worker.runOnce);
}).pipe(Effect.provide(workerLayer));
assert.equal(yield* Ref.get(executionCount), 1);
const storedEffect = yield* outbox.get(effect.id);
assert.isTrue(Option.isSome(storedEffect));
if (Option.isSome(storedEffect)) {
assert.equal(storedEffect.value.status, "succeeded");
}
}),
);
it.effect("allows only one worker to claim an available effect", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
const commandId = CommandId.make("command:foundation-exclusive-claim");
yield* outbox.enqueue([
{
id: "effect:foundation-exclusive-claim",
commandId,
threadId: ThreadId.make("thread:foundation-exclusive-claim"),
request: {
type: "provider-turn.start",
runId: RunId.make("run:foundation-exclusive-claim"),
},
},
]);
const claims = yield* Effect.all(
[
outbox.claimNext({ workerId: "worker-a", leaseDurationMs: 30_000 }),
outbox.claimNext({ workerId: "worker-b", leaseDurationMs: 30_000 }),
],
{ concurrency: "unbounded" },
);
assert.equal(claims.filter(Option.isSome).length, 1);
assert.equal(claims.filter(Option.isNone).length, 1);
}),
);
it.effect("allocates collision-free positions beyond 100 items and rebuilds equivalently", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const projectionStore = yield* ProjectionStoreV2;
const maintenance = yield* ProjectionMaintenanceV2;
const sql = yield* SqlClient.SqlClient;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread:foundation-many-items");
const runId = RunId.make("run:foundation-many-items");
const thread = makeThread(threadId, now);
const runEvent = {
id: EventId.make("event:foundation-many-items:run"),
type: "run.created" as const,
threadId,
runId,
providerInstanceId,
occurredAt: now,
payload: {
id: runId,
threadId,
ordinal: 1,
providerInstanceId,
modelSelection,
providerThreadId: null,
userMessageId: MessageId.make("message:foundation-many-items"),
rootNodeId: null,
activeAttemptId: null,
status: "completed" as const,
queuePosition: null,
requestedAt: now,
startedAt: now,
completedAt: now,
checkpointId: null,
contextHandoffId: null,
},
} satisfies OrchestrationV2DomainEvent;
const items = Array.from({ length: 151 }, (_, index) => ({
id: TurnItemId.make(`turn-item:foundation-many-items:${index}`),
threadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: index % 3,
status: "completed" as const,
title: null,
startedAt: now,
completedAt: now,
updatedAt: now,
type: "dynamic_tool" as const,
toolName: `tool-${index}`,
input: { index },
output: { completed: true },
}));
const itemEvents = items.map(
(item, index) =>
({
id: EventId.make(`event:foundation-many-items:item:${index}`),
type: "turn-item.updated",
threadId,
runId,
providerInstanceId,
occurredAt: now,
payload: item,
}) satisfies OrchestrationV2DomainEvent,
);
yield* eventSink.write({
events: [
threadCreatedEvent({ id: "event:foundation-many-items:thread", thread, now }),
runEvent,
...itemEvents,
],
});
const beforeUpdate = yield* projectionStore.getThreadProjection(threadId);
const ordinals = beforeUpdate.turnItems.map((item) => item.ordinal);
assert.lengthOf(ordinals, 151);
assert.equal(new Set(ordinals).size, 151);
assert.isTrue(ordinals.every((ordinal) => ordinal > 1_000_000));
assert.isTrue(
ordinals.every((ordinal, index) => index === 0 || ordinal > ordinals[index - 1]!),
);
yield* eventSink.write({
events: [
{
id: EventId.make("event:foundation-many-items:update"),
type: "turn-item.updated",
threadId,
runId,
providerInstanceId,
occurredAt: now,
payload: { ...items[0]!, ordinal: 99_999_999, title: "Updated" },
},
],
});
const afterUpdate = yield* projectionStore.getThreadProjection(threadId);
assert.equal(afterUpdate.turnItems[0]?.ordinal, ordinals[0]);
assert.equal((yield* maintenance.verify).valid, true);
yield* sql`
DELETE FROM orchestration_v2_projection_turn_items
WHERE turn_item_id = ${items[75]!.id}
`;
const broken = yield* maintenance.verify;
assert.isFalse(broken.valid);
assert.deepEqual(broken.differingThreadIds, [threadId]);
const rebuilt = yield* maintenance.rebuild;
assert.isTrue(rebuilt.valid);
assert.lengthOf((yield* projectionStore.getThreadProjection(threadId)).turnItems, 151);
}),
);
});
@@ -10,11 +10,18 @@ import {
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import { describe } from "vite-plus/test";
import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts";
import { ServerConfig } from "../config.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../provider/Layers/ProviderEventLoggers.ts";
import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
@@ -34,17 +41,30 @@ const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe(
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer));
const serverSettingsLayer = ServerSettingsService.layerTest({
providers: {
grok: { enabled: true },
},
});
const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
Layer.provide(
Layer.mergeAll(
serverConfigLayer.pipe(Layer.provide(NodeServices.layer)),
serverSettingsLayer,
NodeServices.layer,
FetchHttpClient.layer,
OpenCodeRuntimeLive.pipe(Layer.provide(NodeServices.layer)),
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
),
),
);
const liveLayer = OrchestrationV2LayerLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(checkpointStoreLayer),
Layer.provide(serverConfigLayer),
Layer.provide(
ServerSettingsService.layerTest({
providers: {
grok: { enabled: true },
},
}),
),
Layer.provide(serverSettingsLayer),
Layer.provide(providerInstanceRegistryLayer),
Layer.provide(NodeServices.layer),
);
@@ -139,11 +159,11 @@ describe.runIf(process.env.T3_GROK_LIVE_ORCHESTRATOR === "1")("Grok V2 live orch
.join("\n");
assert.deepEqual(
sourceProjection.runs.map((run) => [run.provider, run.status]),
sourceProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[["grok", "completed"]],
);
assert.deepEqual(
targetProjection.runs.map((run) => [run.provider, run.status]),
targetProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[["grok", "completed"]],
);
assert.deepEqual(
+26 -25
View File
@@ -9,7 +9,8 @@ import {
NodeId,
PlanId,
ProjectId,
ProviderKind,
ProviderDriverKind,
ProviderInstanceId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
@@ -92,11 +93,11 @@ export interface IdAllocatorV2AllocateShape {
readonly ordinal: number;
}) => Effect.Effect<MessageId, IdAllocatorV2Error>;
readonly providerSession: (input: {
readonly provider: ProviderKind;
readonly providerInstanceId: ProviderInstanceId;
readonly threadId: ThreadId;
}) => Effect.Effect<ProviderSessionId, IdAllocatorV2Error>;
readonly runtimeRequest: (input: {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly providerTurnId?: ProviderTurnId;
readonly nativeRequestId?: string;
}) => Effect.Effect<RuntimeRequestId, IdAllocatorV2Error>;
@@ -110,8 +111,8 @@ export interface IdAllocatorV2AllocateShape {
}) => Effect.Effect<CheckpointId, IdAllocatorV2Error>;
readonly contextHandoff: (input: {
readonly threadId: ThreadId;
readonly fromProvider: ProviderKind;
readonly toProvider: ProviderKind;
readonly fromProviderInstanceId: ProviderInstanceId;
readonly toProviderInstanceId: ProviderInstanceId;
}) => Effect.Effect<ContextHandoffId, IdAllocatorV2Error>;
readonly contextTransfer: (input: {
readonly sourceThreadId: ThreadId;
@@ -121,7 +122,7 @@ export interface IdAllocatorV2AllocateShape {
readonly plan: (input: {
readonly threadId: ThreadId;
readonly runId?: RunId;
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
}) => Effect.Effect<PlanId, IdAllocatorV2Error>;
}
@@ -131,7 +132,7 @@ export interface IdAllocatorV2DeriveShape {
readonly delegatedTaskMessage: (input: { readonly commandId: CommandId }) => MessageId;
readonly delegatedTaskTurnItem: (input: { readonly commandId: CommandId }) => TurnItemId;
readonly threadFromProviderThread: (input: {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly nativeThreadId: string;
}) => ThreadId;
readonly run: (input: { readonly threadId: ThreadId; readonly ordinal: number }) => RunId;
@@ -150,23 +151,23 @@ export interface IdAllocatorV2DeriveShape {
readonly signal: string;
}) => TurnItemId;
readonly providerThread: (input: {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly nativeThreadId: string;
}) => ProviderThreadId;
readonly providerTurn: (input: {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly nativeTurnId: string;
}) => ProviderTurnId;
readonly nodeFromProviderItem: (input: {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly nativeItemId: string;
}) => NodeId;
readonly messageFromProviderItem: (input: {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly nativeItemId: string;
}) => MessageId;
readonly turnItemFromProviderItem: (input: {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly nativeItemId: string;
}) => TurnItemId;
readonly approvalNode: (input: { readonly requestId: RuntimeRequestId }) => NodeId;
@@ -270,7 +271,7 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
randomId<ProviderSessionId, typeof input>({
kind: "provider_session",
prefix: "provider-session",
parts: ["provider", input.provider, "thread", input.threadId],
parts: ["provider-instance", input.providerInstanceId, "thread", input.threadId],
make: ProviderSessionId.make,
})(input),
runtimeRequest: (input) =>
@@ -279,7 +280,7 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
prefix: "runtime-request",
parts: [
"provider",
input.provider,
input.driver,
...(input.providerTurnId === undefined ? [] : ["provider-turn", input.providerTurnId]),
...(input.nativeRequestId === undefined
? []
@@ -306,10 +307,10 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
parts: [
"thread",
input.threadId,
"from-provider",
input.fromProvider,
"to-provider",
input.toProvider,
"from-provider-instance",
input.fromProviderInstanceId,
"to-provider-instance",
input.toProviderInstanceId,
],
make: ContextHandoffId.make,
})(input),
@@ -335,7 +336,7 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
"thread",
input.threadId,
"provider",
input.provider,
input.driver,
...(input.runId === undefined ? [] : ["run", input.runId]),
],
make: PlanId.make,
@@ -351,7 +352,7 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
TurnItemId.make(joinId("turn-item", "delegated-task", input.commandId)),
threadFromProviderThread: (input) =>
ThreadId.make(
joinId("thread", "provider", input.provider, "native-thread", input.nativeThreadId),
joinId("thread", "provider", input.driver, "native-thread", input.nativeThreadId),
),
run: (input) => RunId.make(joinId("run", "thread", input.threadId, "ordinal", input.ordinal)),
runAttempt: (input) =>
@@ -369,24 +370,24 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
joinId(
"provider-thread",
"provider",
input.provider,
input.driver,
"native-thread",
input.nativeThreadId,
),
),
providerTurn: (input) =>
ProviderTurnId.make(
joinId("provider-turn", "provider", input.provider, "native-turn", input.nativeTurnId),
joinId("provider-turn", "provider", input.driver, "native-turn", input.nativeTurnId),
),
nodeFromProviderItem: (input) =>
NodeId.make(joinId("node", "provider", input.provider, "native-item", input.nativeItemId)),
NodeId.make(joinId("node", "provider", input.driver, "native-item", input.nativeItemId)),
messageFromProviderItem: (input) =>
MessageId.make(
joinId("message", "provider", input.provider, "native-item", input.nativeItemId),
joinId("message", "provider", input.driver, "native-item", input.nativeItemId),
),
turnItemFromProviderItem: (input) =>
TurnItemId.make(
joinId("turn-item", "provider", input.provider, "native-item", input.nativeItemId),
joinId("turn-item", "provider", input.driver, "native-item", input.nativeItemId),
),
approvalNode: (input) => NodeId.make(joinId("node", "runtime-request", input.requestId)),
approvalTurnItem: (input) =>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,271 @@
import {
type OrchestrationV2StoredEvent,
type OrchestrationV2ThreadProjection,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { EventStoreV2 } from "./EventStore.ts";
import {
applyToProjection,
emptyProjection,
ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
ProjectionStoreV2,
} from "./ProjectionStore.ts";
export interface ProjectionVerificationV2 {
readonly valid: boolean;
readonly schemaVersion: number;
readonly expectedSequence: number;
readonly projectionSequence: number;
readonly differingThreadIds: ReadonlyArray<ThreadId>;
readonly missingThreadIds: ReadonlyArray<ThreadId>;
readonly unexpectedThreadIds: ReadonlyArray<ThreadId>;
}
export class ProjectionMaintenanceError extends Schema.TaggedErrorClass<ProjectionMaintenanceError>()(
"ProjectionMaintenanceError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {}
export interface ProjectionMaintenanceV2Shape {
readonly verify: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
readonly rebuild: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
}
export class ProjectionMaintenanceV2 extends Context.Service<
ProjectionMaintenanceV2,
ProjectionMaintenanceV2Shape
>()("t3/orchestration-v2/ProjectionMaintenance/ProjectionMaintenanceV2") {}
type ProjectionMetadataRow = {
readonly schema_version: number;
readonly last_sequence: number;
};
function sortedProjection(projection: OrchestrationV2ThreadProjection): unknown {
const sortById = <A extends { readonly id: string }>(values: ReadonlyArray<A>) =>
values.toSorted((left, right) => left.id.localeCompare(right.id));
return {
...projection,
runs: sortById(projection.runs),
attempts: sortById(projection.attempts),
nodes: sortById(projection.nodes),
subagents: sortById(projection.subagents),
providerSessions: sortById(projection.providerSessions),
providerThreads: sortById(projection.providerThreads),
providerTurns: sortById(projection.providerTurns),
runtimeRequests: sortById(projection.runtimeRequests),
messages: sortById(projection.messages),
plans: sortById(projection.plans),
turnItems: sortById(projection.turnItems),
checkpointScopes: sortById(projection.checkpointScopes),
checkpoints: sortById(projection.checkpoints),
contextHandoffs: sortById(projection.contextHandoffs),
contextTransfers: sortById(projection.contextTransfers),
// This is a derived lineage view. Its source entities are compared above.
visibleTurnItems: [],
};
}
function stableStringify(value: unknown): string {
if (Array.isArray(value)) {
return `[${value.map(stableStringify).join(",")}]`;
}
if (typeof value === "object" && value !== null) {
const record = value as Record<string, unknown>;
return `{${Object.keys(record)
.toSorted()
.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
.join(",")}}`;
}
return JSON.stringify(value);
}
export const layer: Layer.Layer<
ProjectionMaintenanceV2,
never,
EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient
> = Layer.effect(
ProjectionMaintenanceV2,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const eventStore = yield* EventStoreV2;
const projectionStore = yield* ProjectionStoreV2;
const readAllEvents = Effect.gen(function* () {
const events: Array<OrchestrationV2StoredEvent> = [];
const pageSize = 500;
let afterSequence = 0;
while (true) {
const page = yield* eventStore.read({ afterSequence, limit: pageSize }).pipe(
Stream.runCollect,
Effect.map((chunk) => Array.from(chunk)),
);
events.push(...page);
if (page.length < pageSize) {
break;
}
afterSequence = page.at(-1)?.sequence ?? afterSequence;
}
return events;
});
const expectedProjections = (events: ReadonlyArray<OrchestrationV2StoredEvent>) => {
const projections = new Map<ThreadId, OrchestrationV2ThreadProjection>();
for (const stored of events) {
const event = stored.event;
if (event.type === "thread.created") {
projections.set(event.threadId, emptyProjection(event));
continue;
}
const current = projections.get(event.threadId);
if (current !== undefined) {
projections.set(event.threadId, applyToProjection(current, event));
}
}
return projections;
};
const verify = Effect.gen(function* () {
const events = yield* readAllEvents;
const expected = expectedProjections(events);
const projectionRows = yield* sql<{ readonly thread_id: string }>`
SELECT thread_id
FROM orchestration_v2_projection_threads
ORDER BY thread_id ASC
`;
const actualIds = projectionRows.map((row) => ThreadId.make(row.thread_id));
const expectedIds = [...expected.keys()].toSorted((left, right) => left.localeCompare(right));
const actualSet = new Set(actualIds);
const expectedSet = new Set(expectedIds);
const missingThreadIds = expectedIds.filter((threadId) => !actualSet.has(threadId));
const unexpectedThreadIds = actualIds.filter((threadId) => !expectedSet.has(threadId));
const differingThreadIds: Array<ThreadId> = [];
for (const threadId of expectedIds) {
if (!actualSet.has(threadId)) {
continue;
}
const actual = yield* projectionStore.getThreadProjection(threadId);
const expectedProjection = expected.get(threadId);
if (
expectedProjection === undefined ||
stableStringify(sortedProjection(actual)) !==
stableStringify(sortedProjection(expectedProjection))
) {
differingThreadIds.push(threadId);
}
}
const metadata = yield* sql<ProjectionMetadataRow>`
SELECT schema_version, last_sequence
FROM orchestration_v2_projection_metadata
WHERE projection_name = 'thread-projections'
LIMIT 1
`;
const expectedSequence = events.at(-1)?.sequence ?? 0;
const schemaVersion = metadata[0]?.schema_version ?? 0;
const projectionSequence = metadata[0]?.last_sequence ?? 0;
return {
valid:
schemaVersion === ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION &&
projectionSequence === expectedSequence &&
missingThreadIds.length === 0 &&
unexpectedThreadIds.length === 0 &&
differingThreadIds.length === 0,
schemaVersion,
expectedSequence,
projectionSequence,
differingThreadIds,
missingThreadIds,
unexpectedThreadIds,
} satisfies ProjectionVerificationV2;
});
const rebuild = Effect.gen(function* () {
const events = yield* readAllEvents;
yield* sql.withTransaction(
Effect.gen(function* () {
yield* sql`DELETE FROM orchestration_v2_projection_context_transfers`;
yield* sql`DELETE FROM orchestration_v2_projection_context_handoffs`;
yield* sql`DELETE FROM orchestration_v2_projection_checkpoints`;
yield* sql`DELETE FROM orchestration_v2_projection_checkpoint_scopes`;
yield* sql`DELETE FROM orchestration_v2_projection_turn_items`;
yield* sql`DELETE FROM orchestration_v2_projection_plans`;
yield* sql`DELETE FROM orchestration_v2_projection_messages`;
yield* sql`DELETE FROM orchestration_v2_projection_runtime_requests`;
yield* sql`DELETE FROM orchestration_v2_projection_provider_turns`;
yield* sql`DELETE FROM orchestration_v2_projection_provider_threads`;
yield* sql`DELETE FROM orchestration_v2_projection_provider_sessions`;
yield* sql`DELETE FROM orchestration_v2_projection_subagents`;
yield* sql`DELETE FROM orchestration_v2_projection_nodes`;
yield* sql`DELETE FROM orchestration_v2_projection_run_attempts`;
yield* sql`DELETE FROM orchestration_v2_projection_runs`;
yield* sql`DELETE FROM orchestration_v2_projection_threads`;
yield* sql`DELETE FROM orchestration_v2_turn_item_positions`;
for (const stored of events) {
yield* projectionStore.apply(stored.event);
if (stored.event.type === "turn-item.updated") {
yield* sql`
INSERT INTO orchestration_v2_turn_item_positions (
thread_id,
turn_item_id,
ordinal
)
VALUES (
${stored.event.threadId},
${stored.event.payload.id},
${stored.event.payload.ordinal}
)
ON CONFLICT(thread_id, turn_item_id) DO UPDATE SET
ordinal = excluded.ordinal
`;
}
}
const now = DateTime.formatIso(yield* DateTime.now);
const lastSequence = events.at(-1)?.sequence ?? 0;
yield* sql`
INSERT INTO orchestration_v2_projection_metadata (
projection_name,
schema_version,
last_sequence,
updated_at
)
VALUES (
'thread-projections',
${ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
${lastSequence},
${now}
)
ON CONFLICT(projection_name) DO UPDATE SET
schema_version = excluded.schema_version,
last_sequence = excluded.last_sequence,
updated_at = excluded.updated_at
`;
}),
);
return yield* verify;
});
const mapError =
(operation: string) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.mapError((cause) => new ProjectionMaintenanceError({ operation, cause })),
);
return ProjectionMaintenanceV2.of({
verify: mapError("verify")(verify),
rebuild: mapError("rebuild")(rebuild),
});
}),
);
@@ -5,6 +5,7 @@ import {
type ModelSelection,
NodeId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ProviderThreadId,
ProviderTurnId,
@@ -30,6 +31,8 @@ const modelSelection = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
} satisfies ModelSelection;
const driver = ProviderDriverKind.make("codex");
const providerInstanceId = modelSelection.instanceId;
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
it.layer(TestLayer)("ProjectionStoreV2", (it) => {
@@ -53,11 +56,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
id: threadId,
projectId,
title: "Projection shell",
defaultProvider: "codex",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
},
providerInstanceId,
modelSelection: modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
@@ -177,7 +177,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
id: threadId,
projectId,
title: "Projection rollback prune",
defaultProvider: "codex",
providerInstanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
@@ -200,11 +200,12 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
id: EventId.make("event:projection-rollback-prune:provider-thread"),
type: "provider-thread.updated",
threadId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: providerThreadId,
provider: "codex",
driver,
providerInstanceId,
providerSessionId: null,
appThreadId: threadId,
ownerNodeId: null,
@@ -225,13 +226,13 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: rootNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: runId,
threadId,
ordinal: 1,
provider: "codex",
providerInstanceId,
modelSelection,
providerThreadId,
userMessageId,
@@ -251,14 +252,14 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: rootNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: attemptId,
runId,
attemptOrdinal: 1,
rootNodeId,
provider: "codex",
providerInstanceId,
providerThreadId,
providerTurnId,
reason: "initial",
@@ -273,7 +274,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: rootNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: rootNodeId,
@@ -299,7 +300,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: assistantNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: assistantNodeId,
@@ -325,7 +326,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: rootNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: providerTurnId,
@@ -345,7 +346,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: rootNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
createdBy: "user",
@@ -368,7 +369,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: assistantNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
createdBy: "agent",
@@ -391,7 +392,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: rootNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
createdBy: "user",
@@ -423,7 +424,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: assistantNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: assistantTurnItemId,
@@ -452,13 +453,13 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: rootNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: runId,
threadId,
ordinal: 1,
provider: "codex",
providerInstanceId,
modelSelection,
providerThreadId,
userMessageId,
@@ -478,7 +479,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId,
runId,
nodeId: rootNodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: rootNodeId,
@@ -548,7 +549,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
id: sourceThreadId,
projectId,
title: "Projection fork source rollback source",
defaultProvider: "codex",
providerInstanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
@@ -578,7 +579,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
id: targetThreadId,
projectId,
title: "Projection fork source rollback target",
defaultProvider: "codex",
providerInstanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
@@ -612,13 +613,13 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId: sourceThreadId,
runId,
nodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: runId,
threadId: sourceThreadId,
ordinal,
provider: "codex",
providerInstanceId,
modelSelection,
providerThreadId: sourceProviderThreadId,
userMessageId: MessageId.make(
@@ -640,7 +641,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId: sourceThreadId,
runId,
nodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
createdBy: "user",
@@ -672,7 +673,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId: sourceThreadId,
runId,
nodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: TurnItemId.make(`turn-item:projection-fork-source-rollback:assistant:${ordinal}`),
@@ -711,13 +712,13 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
threadId: sourceThreadId,
runId: sourceRun2Id,
nodeId: sourceRun2NodeId,
provider: "codex",
driver,
occurredAt: now,
payload: {
id: sourceRun2Id,
threadId: sourceThreadId,
ordinal: 2,
provider: "codex",
providerInstanceId,
modelSelection,
providerThreadId: sourceProviderThreadId,
userMessageId: MessageId.make("message:projection-fork-source-rollback:user:2"),
@@ -106,12 +106,22 @@ export interface ProjectionStoreV2Shape {
readonly getThreadProjection: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadProjection, ProjectionStoreV2Error>;
readonly getThreadSnapshot: (threadId: ThreadId) => Effect.Effect<
{
readonly schemaVersion: number;
readonly snapshotSequence: number;
readonly projection: OrchestrationV2ThreadProjection;
},
ProjectionStoreV2Error
>;
}
export class ProjectionStoreV2 extends Context.Service<ProjectionStoreV2, ProjectionStoreV2Shape>()(
"t3/orchestration-v2/ProjectionStore/ProjectionStoreV2",
) {}
export const ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION = 1;
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) {
@@ -154,11 +164,23 @@ export function applyToProjection(
): OrchestrationV2ThreadProjection {
const base = {
...projection,
thread: {
...projection.thread,
updatedAt: event.occurredAt,
},
updatedAt: event.occurredAt,
};
switch (event.type) {
case "thread.created":
case "thread.archived":
case "thread.unarchived":
case "thread.deleted":
case "thread.metadata-updated":
case "thread.runtime-mode-updated":
case "thread.interaction-mode-updated":
case "thread.model-selection-updated":
case "thread.provider-switched":
return {
...base,
thread: event.payload,
@@ -230,6 +252,8 @@ export function applyToProjection(
...base,
checkpoints: upsertById(base.checkpoints, event.payload),
};
case "checkpoint.rollback-requested":
return base;
case "context-handoff.updated":
return {
...base,
@@ -253,6 +277,9 @@ type ShellThreadRow = {
readonly payload_json: string;
readonly latest_run_id: string | null;
readonly latest_run_status: string | null;
readonly active_run_id: string | null;
readonly pending_request_payload_json: string | null;
readonly latest_message_payload_json: string | null;
readonly item_count: number;
};
@@ -587,32 +614,77 @@ export function threadShellFromProjection(
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2ThreadShell {
const latestRun = projection.runs.at(-1) ?? null;
const activeRun =
projection.runs
.filter(isBlockingRunForShell)
.toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
const pendingRuntimeRequest =
projection.runtimeRequests
.filter((request) => request.status === "pending")
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt),
)[0] ?? null;
const latestVisibleMessage =
projection.messages.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
)[0] ?? null;
return {
createdBy: projection.thread.createdBy,
creationSource: projection.thread.creationSource,
id: projection.thread.id,
projectId: projection.thread.projectId,
title: projection.thread.title,
defaultProvider: projection.thread.defaultProvider,
providerInstanceId: projection.thread.providerInstanceId,
modelSelection: projection.thread.modelSelection,
runtimeMode: projection.thread.runtimeMode,
interactionMode: projection.thread.interactionMode,
branch: projection.thread.branch,
worktreePath: projection.thread.worktreePath,
lineage: projection.thread.lineage,
forkedFrom: projection.thread.forkedFrom,
activeProviderThreadId: projection.thread.activeProviderThreadId,
latestRunId: latestRun?.id ?? null,
activeRunId: activeRun?.id ?? null,
status: latestRun?.status ?? "idle",
pendingRuntimeRequest:
pendingRuntimeRequest === null
? null
: {
id: pendingRuntimeRequest.id,
kind: pendingRuntimeRequest.kind,
createdAt: pendingRuntimeRequest.createdAt,
},
latestVisibleMessage:
latestVisibleMessage === null
? null
: {
id: latestVisibleMessage.id,
role: latestVisibleMessage.role,
text: latestVisibleMessage.text,
updatedAt: latestVisibleMessage.updatedAt,
},
itemCount: activeLocalTurnItems(projection).length,
visibleItemCount: projection.visibleTurnItems.length,
createdAt: projection.thread.createdAt,
updatedAt: projection.updatedAt,
archivedAt: projection.thread.archivedAt,
deletedAt: projection.thread.deletedAt,
};
}
function isBlockingRunForShell(run: OrchestrationV2ThreadProjection["runs"][number]): boolean {
return run.status === "starting" || run.status === "running" || run.status === "waiting";
}
type ShellThreadState = {
readonly thread: OrchestrationV2ThreadProjection["thread"];
readonly latestRunId: RunId | null;
readonly latestRunStatus: OrchestrationV2ShellThreadStatus;
readonly activeRunId: RunId | null;
readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null;
readonly latestVisibleMessage: OrchestrationV2ConversationMessage | null;
readonly itemCount: number;
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
readonly runOrdinalById: ReadonlyMap<RunId, number>;
@@ -710,19 +782,41 @@ function shellFromState(input: {
id: input.state.thread.id,
projectId: input.state.thread.projectId,
title: input.state.thread.title,
defaultProvider: input.state.thread.defaultProvider,
providerInstanceId: input.state.thread.providerInstanceId,
modelSelection: input.state.thread.modelSelection,
runtimeMode: input.state.thread.runtimeMode,
interactionMode: input.state.thread.interactionMode,
branch: input.state.thread.branch,
worktreePath: input.state.thread.worktreePath,
lineage: input.state.thread.lineage,
forkedFrom: input.state.thread.forkedFrom,
activeProviderThreadId: input.state.thread.activeProviderThreadId,
latestRunId: input.state.latestRunId,
activeRunId: input.state.activeRunId,
status: input.state.latestRunStatus,
pendingRuntimeRequest:
input.state.pendingRuntimeRequest === null
? null
: {
id: input.state.pendingRuntimeRequest.id,
kind: input.state.pendingRuntimeRequest.kind,
createdAt: input.state.pendingRuntimeRequest.createdAt,
},
latestVisibleMessage:
input.state.latestVisibleMessage === null
? null
: {
id: input.state.latestVisibleMessage.id,
role: input.state.latestVisibleMessage.role,
text: input.state.latestVisibleMessage.text,
updatedAt: input.state.latestVisibleMessage.updatedAt,
},
itemCount: input.state.itemCount,
visibleItemCount: input.visibleItemCount,
createdAt: input.state.thread.createdAt,
updatedAt: input.state.updatedAt,
archivedAt: input.state.thread.archivedAt,
deletedAt: input.state.thread.deletedAt,
};
}
@@ -734,7 +828,15 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
const apply: ProjectionStoreV2Shape["apply"] = (event) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.created": {
case "thread.created":
case "thread.archived":
case "thread.unarchived":
case "thread.deleted":
case "thread.metadata-updated":
case "thread.runtime-mode-updated":
case "thread.interaction-mode-updated":
case "thread.model-selection-updated":
case "thread.provider-switched": {
const payloadJson = yield* encodeThreadPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
yield* sql`
@@ -743,6 +845,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
project_id,
title,
default_provider,
provider_instance_id,
runtime_mode,
interaction_mode,
active_provider_thread_id,
@@ -756,7 +859,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
${event.payload.id},
${event.payload.projectId},
${event.payload.title},
${event.payload.defaultProvider},
${event.payload.providerInstanceId},
${event.payload.providerInstanceId},
${event.payload.runtimeMode},
${event.payload.interactionMode},
${event.payload.activeProviderThreadId},
@@ -771,6 +875,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
project_id = excluded.project_id,
title = excluded.title,
default_provider = excluded.default_provider,
provider_instance_id = excluded.provider_instance_id,
runtime_mode = excluded.runtime_mode,
interaction_mode = excluded.interaction_mode,
active_provider_thread_id = excluded.active_provider_thread_id,
@@ -792,6 +897,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
thread_id,
ordinal,
provider,
provider_instance_id,
provider_thread_id,
status,
requested_at,
@@ -802,7 +908,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
${event.payload.id},
${event.payload.threadId},
${event.payload.ordinal},
${event.payload.provider},
${event.payload.providerInstanceId},
${event.payload.providerInstanceId},
${event.payload.providerThreadId},
${event.payload.status},
${stringField(payload, "requestedAt")},
@@ -814,6 +921,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
thread_id = excluded.thread_id,
ordinal = excluded.ordinal,
provider = excluded.provider,
provider_instance_id = excluded.provider_instance_id,
provider_thread_id = excluded.provider_thread_id,
status = excluded.status,
requested_at = excluded.requested_at,
@@ -833,6 +941,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
attempt_ordinal,
root_node_id,
provider,
provider_instance_id,
provider_thread_id,
provider_turn_id,
status,
@@ -844,7 +953,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
${event.payload.runId},
${event.payload.attemptOrdinal},
${event.payload.rootNodeId},
${event.payload.provider},
${event.payload.providerInstanceId},
${event.payload.providerInstanceId},
${event.payload.providerThreadId},
${event.payload.providerTurnId},
${event.payload.status},
@@ -857,6 +967,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
attempt_ordinal = excluded.attempt_ordinal,
root_node_id = excluded.root_node_id,
provider = excluded.provider,
provider_instance_id = excluded.provider_instance_id,
provider_thread_id = excluded.provider_thread_id,
provider_turn_id = excluded.provider_turn_id,
status = excluded.status,
@@ -928,6 +1039,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
run_id,
parent_node_id,
provider,
driver,
provider_instance_id,
provider_thread_id,
child_thread_id,
origin,
@@ -942,7 +1055,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
${event.payload.threadId},
${event.payload.runId},
${event.payload.parentNodeId},
${event.payload.provider},
${event.payload.providerInstanceId},
${event.payload.driver},
${event.payload.providerInstanceId},
${event.payload.providerThreadId},
${event.payload.childThreadId},
${event.payload.origin},
@@ -958,6 +1073,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
run_id = excluded.run_id,
parent_node_id = excluded.parent_node_id,
provider = excluded.provider,
driver = excluded.driver,
provider_instance_id = excluded.provider_instance_id,
provider_thread_id = excluded.provider_thread_id,
child_thread_id = excluded.child_thread_id,
origin = excluded.origin,
@@ -977,6 +1094,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
provider_session_id,
thread_id,
provider,
driver,
provider_instance_id,
status,
model,
updated_at,
@@ -985,7 +1104,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
VALUES (
${event.payload.id},
${event.threadId},
${event.payload.provider},
${event.payload.providerInstanceId},
${event.payload.driver},
${event.payload.providerInstanceId},
${event.payload.status},
${event.payload.model},
${stringField(payload, "updatedAt")},
@@ -995,6 +1116,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
DO UPDATE SET
thread_id = excluded.thread_id,
provider = excluded.provider,
driver = excluded.driver,
provider_instance_id = excluded.provider_instance_id,
status = excluded.status,
model = excluded.model,
updated_at = excluded.updated_at,
@@ -1011,6 +1134,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
thread_id,
owner_node_id,
provider,
driver,
provider_instance_id,
provider_session_id,
status,
first_run_ordinal,
@@ -1022,7 +1147,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
${event.payload.id},
${event.payload.appThreadId},
${event.payload.ownerNodeId},
${event.payload.provider},
${event.payload.providerInstanceId},
${event.payload.driver},
${event.payload.providerInstanceId},
${event.payload.providerSessionId},
${event.payload.status},
${event.payload.firstRunOrdinal},
@@ -1035,6 +1162,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
thread_id = excluded.thread_id,
owner_node_id = excluded.owner_node_id,
provider = excluded.provider,
driver = excluded.driver,
provider_instance_id = excluded.provider_instance_id,
provider_session_id = excluded.provider_session_id,
status = excluded.status,
first_run_ordinal = excluded.first_run_ordinal,
@@ -1360,6 +1489,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
`;
break;
}
case "checkpoint.rollback-requested":
break;
case "context-handoff.updated": {
const payloadJson = yield* encodeContextHandoffPayload(event.payload);
const payload = parseEncodedPayload(payloadJson);
@@ -1410,6 +1541,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
status,
source_provider,
target_provider,
source_provider_instance_id,
target_provider_instance_id,
updated_at,
payload_json
)
@@ -1420,8 +1553,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
${event.payload.targetRunId},
${event.payload.type},
${event.payload.status},
${event.payload.sourceProvider},
${event.payload.targetProvider},
${event.payload.sourceProviderInstanceId},
${event.payload.targetProviderInstanceId},
${event.payload.sourceProviderInstanceId},
${event.payload.targetProviderInstanceId},
${stringField(payload, "updatedAt")},
${payloadJson}
)
@@ -1434,12 +1569,46 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
status = excluded.status,
source_provider = excluded.source_provider,
target_provider = excluded.target_provider,
source_provider_instance_id = excluded.source_provider_instance_id,
target_provider_instance_id = excluded.target_provider_instance_id,
updated_at = excluded.updated_at,
payload_json = excluded.payload_json
`;
break;
}
}
if (
event.type !== "thread.created" &&
event.type !== "thread.archived" &&
event.type !== "thread.unarchived" &&
event.type !== "thread.deleted" &&
event.type !== "thread.metadata-updated" &&
event.type !== "thread.runtime-mode-updated" &&
event.type !== "thread.interaction-mode-updated" &&
event.type !== "thread.model-selection-updated" &&
event.type !== "thread.provider-switched"
) {
const rows = yield* sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_threads
WHERE thread_id = ${event.threadId}
LIMIT 1
`;
const row = rows[0];
if (row !== undefined) {
const thread = yield* decodeThreadPayload(row.payload_json);
const updatedThread = { ...thread, updatedAt: event.occurredAt };
const payloadJson = yield* encodeThreadPayload(updatedThread);
yield* sql`
UPDATE orchestration_v2_projection_threads
SET
updated_at = ${stringField(parseEncodedPayload(payloadJson), "updatedAt")},
payload_json = ${payloadJson}
WHERE thread_id = ${event.threadId}
`;
}
}
}).pipe(
Effect.mapError(
(cause) =>
@@ -1575,13 +1744,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
SELECT payload_json
FROM orchestration_v2_projection_context_handoffs
WHERE thread_id = ${threadId}
ORDER BY updated_at ASC, context_handoff_id ASC
ORDER BY rowid ASC
`,
sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_context_transfers
WHERE source_thread_id = ${threadId} OR target_thread_id = ${threadId}
ORDER BY updated_at ASC, context_transfer_id ASC
ORDER BY rowid ASC
`,
]);
@@ -1678,10 +1847,38 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) =>
readProjection(threadId, new Set());
const getThreadSnapshot: ProjectionStoreV2Shape["getThreadSnapshot"] = (threadId) =>
sql
.withTransaction(
Effect.gen(function* () {
const projection = yield* getThreadProjection(threadId);
const rows = yield* sql<{ readonly snapshot_sequence: number | null }>`
SELECT MAX(sequence) AS snapshot_sequence
FROM orchestration_v2_events
WHERE thread_id = ${threadId}
`;
return {
schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
snapshotSequence: rows[0]?.snapshot_sequence ?? 0,
projection,
};
}),
)
.pipe(
Effect.mapError((cause) =>
Schema.is(ProjectionStoreThreadNotFoundError)(cause) ||
Schema.is(ProjectionStoreReadError)(cause)
? cause
: new ProjectionStoreReadError({ threadId, cause }),
),
);
const getShellSnapshot: ProjectionStoreV2Shape["getShellSnapshot"] = () =>
Effect.gen(function* () {
const [threadRows, runRows, itemCountRows] = yield* Effect.all([
sql<ShellThreadRow>`
sql
.withTransaction(
Effect.gen(function* () {
const [threadRows, runRows, itemCountRows, sequenceRows] = yield* Effect.all([
sql<ShellThreadRow>`
SELECT
t.thread_id,
t.payload_json,
@@ -1699,6 +1896,29 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS latest_run_status,
(
SELECT r.run_id
FROM orchestration_v2_projection_runs r
WHERE r.thread_id = t.thread_id
AND r.status IN ('starting', 'running', 'waiting')
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS active_run_id,
(
SELECT request.payload_json
FROM orchestration_v2_projection_runtime_requests request
WHERE request.thread_id = t.thread_id
AND request.status = 'pending'
ORDER BY request.created_at DESC, request.runtime_request_id DESC
LIMIT 1
) AS pending_request_payload_json,
(
SELECT message.payload_json
FROM orchestration_v2_projection_messages message
WHERE message.thread_id = t.thread_id
ORDER BY message.updated_at DESC, message.message_id DESC
LIMIT 1
) AS latest_message_payload_json,
(
SELECT COUNT(*)
FROM orchestration_v2_projection_turn_items i
@@ -1711,80 +1931,102 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
WHERE t.deleted_at IS NULL
ORDER BY t.updated_at ASC, t.thread_id ASC
`,
sql<ShellRunRow>`
sql<ShellRunRow>`
SELECT thread_id, run_id, ordinal
FROM orchestration_v2_projection_runs
`,
sql<ShellRunItemCountRow>`
sql<ShellRunItemCountRow>`
SELECT thread_id, run_id, COUNT(*) AS item_count
FROM orchestration_v2_projection_turn_items
WHERE run_id IS NOT NULL
GROUP BY thread_id, run_id
`,
]);
sql<{ readonly snapshot_sequence: number | null }>`
SELECT MAX(sequence) AS snapshot_sequence
FROM orchestration_v2_events
`,
]);
const runOrdinalsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of runRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = runOrdinalsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.ordinal);
runOrdinalsByThreadId.set(threadId, existing);
}
const runOrdinalsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of runRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = runOrdinalsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.ordinal);
runOrdinalsByThreadId.set(threadId, existing);
}
const itemCountsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of itemCountRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = itemCountsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.item_count);
itemCountsByThreadId.set(threadId, existing);
}
const itemCountsByThreadId = new Map<ThreadId, Map<RunId, number>>();
for (const row of itemCountRows) {
const threadId = ThreadId.make(row.thread_id);
const runId = RunId.make(row.run_id);
const existing = itemCountsByThreadId.get(threadId) ?? new Map<RunId, number>();
existing.set(runId, row.item_count);
itemCountsByThreadId.set(threadId, existing);
}
const states = yield* Effect.forEach(threadRows, (row) =>
decodeThreadPayload(row.payload_json).pipe(
Effect.map(
(thread): ShellThreadState => ({
thread,
latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id),
latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status),
itemCount: row.item_count,
updatedAt: thread.updatedAt,
runOrdinalById:
runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
itemCountByRunId:
itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
const states = yield* Effect.forEach(threadRows, (row) =>
Effect.gen(function* () {
const thread = yield* decodeThreadPayload(row.payload_json);
const pendingRuntimeRequest =
row.pending_request_payload_json === null
? null
: yield* decodeRuntimeRequestPayload(row.pending_request_payload_json);
const latestVisibleMessage =
row.latest_message_payload_json === null
? null
: yield* decodeMessagePayload(row.latest_message_payload_json);
return {
thread,
latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id),
latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status),
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
pendingRuntimeRequest,
latestVisibleMessage,
itemCount: row.item_count,
updatedAt: thread.updatedAt,
runOrdinalById:
runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
itemCountByRunId:
itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
} satisfies ShellThreadState;
}),
);
const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
const shells = states.map((state) =>
shellFromState({
state,
visibleItemCount: visibleItemCountForShell({
threadId: state.thread.id,
statesByThreadId,
}),
}),
);
return {
schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
snapshotSequence: sequenceRows[0]?.snapshot_sequence ?? 0,
threads: shells.filter((thread) => thread.archivedAt === null),
archivedThreads: shells.filter((thread) => thread.archivedAt !== null),
};
}),
)
.pipe(
Effect.mapError(
(cause) =>
new ProjectionStoreReadError({
threadId: ThreadId.make("thread:shell"),
cause,
}),
),
),
);
const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
return {
threads: states.map((state) =>
shellFromState({
state,
visibleItemCount: visibleItemCountForShell({
threadId: state.thread.id,
statesByThreadId,
}),
}),
),
};
}).pipe(
Effect.mapError(
(cause) =>
new ProjectionStoreReadError({
threadId: ThreadId.make("thread:shell"),
cause,
}),
),
);
return {
apply,
getShellSnapshot,
getThreadProjection,
getThreadSnapshot,
} satisfies ProjectionStoreV2Shape;
}),
);
@@ -1793,6 +2035,7 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
ProjectionStoreV2,
Effect.gen(function* () {
const projections = yield* Ref.make(new Map<ThreadId, OrchestrationV2ThreadProjection>());
const sequence = yield* Ref.make(0);
const service: ProjectionStoreV2Shape = {
apply: (event) =>
@@ -1820,6 +2063,7 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
if (result) {
return yield* result;
}
yield* Ref.update(sequence, (current) => current + 1);
}),
getShellSnapshot: () =>
Effect.gen(function* () {
@@ -1831,7 +2075,13 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
(threadId) =>
service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)),
);
return { threads: shells };
const visible = shells.filter((thread) => thread.deletedAt === null);
return {
schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
snapshotSequence: yield* Ref.get(sequence),
threads: visible.filter((thread) => thread.archivedAt === null),
archivedThreads: visible.filter((thread) => thread.archivedAt !== null),
};
}),
getThreadProjection: (threadId) =>
Effect.gen(function* () {
@@ -1866,6 +2116,18 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
}
return projection;
}),
getThreadSnapshot: (threadId) =>
service.getThreadProjection(threadId).pipe(
Effect.flatMap((projection) =>
Ref.get(sequence).pipe(
Effect.map((snapshotSequence) => ({
schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
snapshotSequence,
projection,
})),
),
),
),
};
return service;
@@ -18,7 +18,8 @@ import {
OrchestrationV2TurnItem,
ProviderApprovalDecision,
ProviderInteractionMode,
ProviderKind,
ProviderDriverKind,
ProviderInstanceId,
ProviderUserInputAnswers,
ProviderSessionId,
ProviderThreadId,
@@ -67,59 +68,59 @@ export type ProviderAdapterV2SessionStatus = typeof ProviderAdapterV2SessionStat
export const ProviderAdapterV2Event = Schema.Union([
Schema.Struct({
type: Schema.Literal("app_thread.created"),
provider: ProviderKind,
driver: ProviderDriverKind,
appThread: OrchestrationV2AppThread,
}),
Schema.Struct({
type: Schema.Literal("provider_session.updated"),
provider: ProviderKind,
driver: ProviderDriverKind,
providerSession: OrchestrationV2ProviderSession,
}),
Schema.Struct({
type: Schema.Literal("provider_thread.updated"),
provider: ProviderKind,
driver: ProviderDriverKind,
providerThread: OrchestrationV2ProviderThread,
}),
Schema.Struct({
type: Schema.Literal("provider_turn.updated"),
provider: ProviderKind,
driver: ProviderDriverKind,
threadId: Schema.optional(ThreadId),
providerTurn: OrchestrationV2ProviderTurn,
}),
Schema.Struct({
type: Schema.Literal("node.updated"),
provider: ProviderKind,
driver: ProviderDriverKind,
node: OrchestrationV2ExecutionNode,
}),
Schema.Struct({
type: Schema.Literal("subagent.updated"),
provider: ProviderKind,
driver: ProviderDriverKind,
subagent: OrchestrationV2Subagent,
}),
Schema.Struct({
type: Schema.Literal("message.updated"),
provider: ProviderKind,
driver: ProviderDriverKind,
message: OrchestrationV2ConversationMessage,
}),
Schema.Struct({
type: Schema.Literal("turn_item.updated"),
provider: ProviderKind,
driver: ProviderDriverKind,
turnItem: OrchestrationV2TurnItem,
}),
Schema.Struct({
type: Schema.Literal("runtime_request.updated"),
provider: ProviderKind,
driver: ProviderDriverKind,
threadId: Schema.optional(ThreadId),
runtimeRequest: OrchestrationV2RuntimeRequest,
}),
Schema.Struct({
type: Schema.Literal("plan.updated"),
provider: ProviderKind,
driver: ProviderDriverKind,
plan: OrchestrationV2PlanArtifact,
}),
Schema.Struct({
type: Schema.Literal("turn.terminal"),
provider: ProviderKind,
driver: ProviderDriverKind,
providerTurnId: ProviderTurnId,
status: Schema.Literals(["completed", "interrupted", "failed", "cancelled"]),
}),
@@ -129,112 +130,112 @@ export type ProviderAdapterV2Event = typeof ProviderAdapterV2Event.Type;
export class ProviderAdapterCapabilitiesError extends Schema.TaggedErrorClass<ProviderAdapterCapabilitiesError>()(
"ProviderAdapterCapabilitiesError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to read ${this.provider} provider capabilities.`;
return `Failed to read ${this.driver} provider capabilities.`;
}
}
export class ProviderAdapterOpenSessionError extends Schema.TaggedErrorClass<ProviderAdapterOpenSessionError>()(
"ProviderAdapterOpenSessionError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to open ${this.provider} provider session ${this.providerSessionId}.`;
return `Failed to open ${this.driver} provider session ${this.providerSessionId}.`;
}
}
export class ProviderAdapterCloseSessionError extends Schema.TaggedErrorClass<ProviderAdapterCloseSessionError>()(
"ProviderAdapterCloseSessionError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to close ${this.provider} provider session ${this.providerSessionId}.`;
return `Failed to close ${this.driver} provider session ${this.providerSessionId}.`;
}
}
export class ProviderAdapterResumeThreadError extends Schema.TaggedErrorClass<ProviderAdapterResumeThreadError>()(
"ProviderAdapterResumeThreadError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerSessionId: ProviderSessionId,
providerThreadId: ProviderThreadId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to resume ${this.provider} provider thread ${this.providerThreadId}.`;
return `Failed to resume ${this.driver} provider thread ${this.providerThreadId}.`;
}
}
export class ProviderAdapterEnsureThreadError extends Schema.TaggedErrorClass<ProviderAdapterEnsureThreadError>()(
"ProviderAdapterEnsureThreadError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
threadId: ThreadId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to ensure ${this.provider} provider thread for app thread ${this.threadId}.`;
return `Failed to ensure ${this.driver} provider thread for app thread ${this.threadId}.`;
}
}
export class ProviderAdapterReadThreadSnapshotError extends Schema.TaggedErrorClass<ProviderAdapterReadThreadSnapshotError>()(
"ProviderAdapterReadThreadSnapshotError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerThreadId: ProviderThreadId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to read ${this.provider} provider thread snapshot ${this.providerThreadId}.`;
return `Failed to read ${this.driver} provider thread snapshot ${this.providerThreadId}.`;
}
}
export class ProviderAdapterRollbackThreadError extends Schema.TaggedErrorClass<ProviderAdapterRollbackThreadError>()(
"ProviderAdapterRollbackThreadError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerThreadId: ProviderThreadId,
checkpointId: Schema.optional(CheckpointId),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to roll back ${this.provider} provider thread ${this.providerThreadId}.`;
return `Failed to roll back ${this.driver} provider thread ${this.providerThreadId}.`;
}
}
export class ProviderAdapterForkThreadError extends Schema.TaggedErrorClass<ProviderAdapterForkThreadError>()(
"ProviderAdapterForkThreadError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerThreadId: ProviderThreadId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to fork ${this.provider} provider thread ${this.providerThreadId}.`;
return `Failed to fork ${this.driver} provider thread ${this.providerThreadId}.`;
}
}
export class ProviderAdapterTurnStartError extends Schema.TaggedErrorClass<ProviderAdapterTurnStartError>()(
"ProviderAdapterTurnStartError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
threadId: ThreadId,
providerThreadId: ProviderThreadId,
runId: RunId,
@@ -242,86 +243,86 @@ export class ProviderAdapterTurnStartError extends Schema.TaggedErrorClass<Provi
},
) {
override get message(): string {
return `Failed to start run ${this.runId} on ${this.provider} provider thread ${this.providerThreadId}.`;
return `Failed to start run ${this.runId} on ${this.driver} provider thread ${this.providerThreadId}.`;
}
}
export class ProviderAdapterSteerRunUnsupportedError extends Schema.TaggedErrorClass<ProviderAdapterSteerRunUnsupportedError>()(
"ProviderAdapterSteerRunUnsupportedError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerThreadId: ProviderThreadId,
},
) {
override get message(): string {
return `${this.provider} provider thread ${this.providerThreadId} does not support active-run steering.`;
return `${this.driver} provider thread ${this.providerThreadId} does not support active-run steering.`;
}
}
export class ProviderAdapterSteerRunError extends Schema.TaggedErrorClass<ProviderAdapterSteerRunError>()(
"ProviderAdapterSteerRunError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerThreadId: ProviderThreadId,
providerTurnId: ProviderTurnId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to steer active run ${this.providerTurnId} on ${this.provider} provider thread ${this.providerThreadId}.`;
return `Failed to steer active run ${this.providerTurnId} on ${this.driver} provider thread ${this.providerThreadId}.`;
}
}
export class ProviderAdapterInterruptError extends Schema.TaggedErrorClass<ProviderAdapterInterruptError>()(
"ProviderAdapterInterruptError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerThreadId: ProviderThreadId,
providerTurnId: ProviderTurnId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to interrupt ${this.provider} provider turn ${this.providerTurnId}.`;
return `Failed to interrupt ${this.driver} provider turn ${this.providerTurnId}.`;
}
}
export class ProviderAdapterRuntimeRequestResponseError extends Schema.TaggedErrorClass<ProviderAdapterRuntimeRequestResponseError>()(
"ProviderAdapterRuntimeRequestResponseError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
requestId: RuntimeRequestId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to respond to ${this.provider} runtime request ${this.requestId}.`;
return `Failed to respond to ${this.driver} runtime request ${this.requestId}.`;
}
}
export class ProviderAdapterEventStreamError extends Schema.TaggedErrorClass<ProviderAdapterEventStreamError>()(
"ProviderAdapterEventStreamError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
providerSessionId: ProviderSessionId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed while streaming ${this.provider} provider session ${this.providerSessionId} events.`;
return `Failed while streaming ${this.driver} provider session ${this.providerSessionId} events.`;
}
}
export class ProviderAdapterProtocolError extends Schema.TaggedErrorClass<ProviderAdapterProtocolError>()(
"ProviderAdapterProtocolError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
detail: Schema.String,
payload: Schema.optional(Schema.Unknown),
},
) {
override get message(): string {
return `${this.provider} provider protocol error: ${this.detail}.`;
return `${this.driver} provider protocol error: ${this.detail}.`;
}
}
@@ -434,7 +435,8 @@ export interface ProviderAdapterV2ForkThreadInput {
}
export interface ProviderAdapterV2SessionRuntime {
readonly provider: ProviderKind;
readonly instanceId: ProviderInstanceId;
readonly driver: ProviderDriverKind;
readonly providerSessionId: ProviderSessionId;
readonly providerSession: OrchestrationV2ProviderSession;
readonly rawEvents: Stream.Stream<OrchestrationV2RawProviderEvent, ProviderAdapterV2Error>;
@@ -469,7 +471,8 @@ export interface ProviderAdapterV2SessionRuntime {
}
export interface ProviderAdapterV2Shape {
readonly provider: ProviderKind;
readonly instanceId: ProviderInstanceId;
readonly driver: ProviderDriverKind;
readonly getCapabilities: () => Effect.Effect<
OrchestrationV2ProviderCapabilities,
ProviderAdapterV2Error
@@ -1,177 +1,69 @@
import { assert, it } from "@effect/vitest";
import {
ProviderDriverKind,
ProviderInstanceId,
type OrchestrationV2ProviderCapabilities,
} from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ServerSettingsService } from "../serverSettings.ts";
import type { ProviderAdapterDriver } from "./ProviderAdapterDriver.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
import {
makeDriverLayerFromSettings,
layerFromProviderInstanceRegistry,
ProviderAdapterRegistryV2,
} from "./ProviderAdapterRegistry.ts";
const capabilities = {
sessions: {
supportsMultipleProviderThreadsPerSession: false,
supportsModelSwitchInSession: false,
supportsProviderSwitchingViaHandoff: false,
supportsRuntimeModeSwitchInSession: false,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: false,
canReadThreadSnapshot: false,
canRollbackThread: false,
canForkThread: false,
canForkFromTurn: false,
canForkFromSubagentThread: false,
exposesNativeThreadId: false,
},
turns: {
exposesNativeTurnId: false,
emitsTurnStarted: false,
emitsTurnCompleted: false,
supportsInterrupt: false,
supportsActiveSteering: false,
supportsSteeringByInterruptRestart: false,
supportsQueuedMessages: false,
terminalStatusQuality: "weak",
},
streaming: {
streamsAssistantText: false,
streamsReasoning: false,
streamsToolOutput: false,
streamsPlanText: false,
emitsMessageCompleted: false,
},
tools: {
exposesToolItemIds: false,
emitsToolStarted: false,
emitsToolCompleted: false,
emitsToolOutput: false,
supportsMcpTools: false,
supportsDynamicToolCallbacks: false,
},
approvals: {
supportsCommandApproval: false,
supportsFileReadApproval: false,
supportsFileChangeApproval: false,
supportsApplyPatchApproval: false,
approvalsHaveNativeRequestIds: false,
approvalCallbacksAreLiveOnly: false,
approvalsCanOriginateFromSubagents: false,
},
planning: {
emitsPlanUpdated: false,
emitsTodoList: false,
emitsProposedPlan: false,
supportsStructuredQuestions: false,
planDeltasHaveItemIds: false,
},
subagents: {
supportsSubagents: false,
exposesSubagentThreadIds: false,
emitsSubagentLifecycle: false,
canWaitForSubagents: false,
canCloseSubagents: false,
canForkSubagentThread: false,
},
context: {
acceptsSystemContext: false,
acceptsDeveloperContext: false,
acceptsSyntheticUserContext: false,
canGenerateSummaries: false,
canConsumeHandoffSummaries: false,
supportsDeltaHandoff: false,
supportsFullThreadHandoff: false,
maxRecommendedHandoffChars: null,
},
checkpointing: {
appCanCheckpointFilesystem: false,
supportsNestedCheckpointScopes: false,
providerCanRollbackConversation: false,
providerRollbackReturnsSnapshot: false,
providerCanReadConversationSnapshot: false,
},
identity: {
nativeThreadIds: "none",
nativeTurnIds: "none",
nativeItemIds: "none",
nativeRequestIds: "none",
},
} satisfies OrchestrationV2ProviderCapabilities;
const driver = ProviderDriverKind.make("codex");
const personalId = ProviderInstanceId.make("codex_personal");
const workId = ProviderInstanceId.make("codex_work");
const FakeConfig = Schema.Struct({});
type FakeConfig = typeof FakeConfig.Type;
const makeAdapter = (instanceId: ProviderInstanceId): ProviderAdapterV2Shape =>
({
instanceId,
driver,
getCapabilities: () => Effect.die("capabilities are not used by this registry test"),
openSession: () => Effect.die("sessions are not used by this registry test"),
}) as ProviderAdapterV2Shape;
function makeFakeDriver(driverKind: ProviderDriverKind): ProviderAdapterDriver<FakeConfig> {
return {
driverKind,
configSchema: FakeConfig,
defaultConfig: () => ({}),
create: ({ instanceId }) =>
Effect.succeed({
instanceId,
provider: driverKind,
getCapabilities: () => Effect.succeed(capabilities),
openSession: () => Effect.die("fake adapter does not open sessions"),
}),
};
}
const codexDriver = ProviderDriverKind.make("codex");
const claudeDriver = ProviderDriverKind.make("claudeAgent");
const codexWork = ProviderInstanceId.make("codex_work");
const claudeWork = ProviderInstanceId.make("claude_work");
const TestSettingsLayer = ServerSettingsService.layerTest({
providerInstances: {
[codexWork]: { driver: codexDriver, config: {} },
[claudeWork]: { driver: claudeDriver, config: {} },
const makeInstance = (
instanceId: ProviderInstanceId,
orchestrationAdapter: ProviderAdapterV2Shape,
): ProviderInstance => ({
instanceId,
driverKind: driver,
continuationIdentity: {
driverKind: driver,
continuationKey: `codex:test:${instanceId}`,
},
displayName: String(instanceId),
enabled: true,
snapshot: {} as ProviderInstance["snapshot"],
adapter: {} as ProviderInstance["adapter"],
orchestrationAdapter,
textGeneration: {} as ProviderInstance["textGeneration"],
});
const TestLayer = makeDriverLayerFromSettings({
drivers: [makeFakeDriver(codexDriver), makeFakeDriver(claudeDriver)],
}).pipe(Layer.provideMerge(TestSettingsLayer));
it.effect("builds one V2 adapter per configured provider instance", () =>
const personalAdapter = makeAdapter(personalId);
const workAdapter = makeAdapter(workId);
const instances = [
makeInstance(personalId, personalAdapter),
makeInstance(workId, workAdapter),
] as const;
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(instances.find((instance) => instance.instanceId === instanceId)),
listInstances: Effect.succeed(instances),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.never,
});
const TestLayer = layerFromProviderInstanceRegistry.pipe(Layer.provide(instanceRegistryLayer));
it.effect("routes two configured instances of the same driver independently", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistryV2;
const instances = yield* registry.list();
const codexWorkAdapter = yield* registry.get(codexWork);
const claudeWorkAdapter = yield* registry.get(claudeWork);
assert.deepEqual(instances, [
codexWork,
claudeWork,
ProviderInstanceId.make("codex"),
ProviderInstanceId.make("claudeAgent"),
]);
assert.equal(codexWorkAdapter.instanceId, codexWork);
assert.equal(claudeWorkAdapter.instanceId, claudeWork);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("resolves provider instances added after the V2 registry was constructed", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistryV2;
const settings = yield* ServerSettingsService;
const codexAfterStart = ProviderInstanceId.make("codex_after_start");
yield* settings.updateSettings({
providerInstances: {
[codexAfterStart]: { driver: codexDriver, config: {} },
},
});
const adapter = yield* registry.get(codexAfterStart);
const instances = yield* registry.list();
assert.equal(adapter.instanceId, codexAfterStart);
assert.isTrue(instances.includes(codexAfterStart));
assert.strictEqual(yield* registry.get(personalId), personalAdapter);
assert.strictEqual(yield* registry.get(workId), workAdapter);
assert.deepEqual(yield* registry.list(), [personalId, workId]);
}).pipe(Effect.provide(TestLayer)),
);
@@ -1,23 +1,21 @@
import {
defaultInstanceIdForDriver,
ProviderDriverKind as ProviderDriverKindSchema,
ProviderInstanceId,
type ProviderDriverKind,
type ProviderInstanceConfig,
type ProviderInstanceConfigMap,
type ServerSettings,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts";
import {
ProviderAdapterDriverCreateError,
type AnyProviderAdapterDriver,
} from "./ProviderAdapterDriver.ts";
import { ProviderAdapterV2, type ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
export class ProviderAdapterRegistryLookupError extends Schema.TaggedErrorClass<ProviderAdapterRegistryLookupError>()(
@@ -49,6 +47,41 @@ export class ProviderAdapterRegistryV2 extends Context.Service<
ProviderAdapterRegistryV2Shape
>()("t3/orchestration-v2/ProviderAdapterRegistry/ProviderAdapterRegistryV2") {}
/**
* Production facade over the canonical provider-instance registry. Adapter
* lookup stays dynamic so instance hot reloads and removals are visible
* without maintaining a second settings watcher or instance map.
*/
export const layerFromProviderInstanceRegistry: Layer.Layer<
ProviderAdapterRegistryV2,
never,
ProviderInstanceRegistry
> = Layer.effect(
ProviderAdapterRegistryV2,
Effect.gen(function* () {
const instances = yield* ProviderInstanceRegistry;
return ProviderAdapterRegistryV2.of({
get: (instanceId) =>
instances
.getInstance(instanceId)
.pipe(
Effect.flatMap((instance) =>
instance === undefined
? new ProviderAdapterRegistryLookupError({ instanceId })
: Effect.succeed(instance.orchestrationAdapter),
),
),
list: () =>
instances.listInstances.pipe(
Effect.map((available) => available.map((instance) => instance.instanceId)),
),
});
}),
);
export const ProviderAdapterRegistryBuildError = Schema.Union([ProviderAdapterDriverCreateError]);
export type ProviderAdapterRegistryBuildError = typeof ProviderAdapterRegistryBuildError.Type;
function makeRegistry(
adapters: ReadonlyArray<ProviderAdapterV2Shape>,
): ProviderAdapterRegistryV2Shape {
@@ -89,35 +122,6 @@ export function makeSingleLayer(
return makeLayer([adapter]);
}
export function deriveProviderAdapterInstanceConfigMap<R>(input: {
readonly settings: ServerSettings;
readonly drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>;
}): ProviderInstanceConfigMap {
const merged: Record<string, ProviderInstanceConfig> = {
...input.settings.providerInstances,
};
for (const driver of input.drivers) {
const instanceId = defaultInstanceIdForDriver(driver.driverKind);
if (instanceId in merged) {
continue;
}
const legacyKey = driver.driverKind as keyof ServerSettings["providers"];
const legacyConfig = input.settings.providers[legacyKey];
if (legacyConfig === undefined) {
continue;
}
merged[instanceId] = {
driver: driver.driverKind,
config: legacyConfig,
};
}
return merged as ProviderInstanceConfigMap;
}
const decodedConfigEnabled = (config: unknown): boolean | undefined => {
if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) {
return undefined;
@@ -132,17 +136,6 @@ interface LiveAdapterEntry {
readonly entry: ProviderInstanceConfig;
}
const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>
Equal.equals(a, b);
const makeSettingsReadError = (cause: unknown): ProviderAdapterDriverCreateError =>
new ProviderAdapterDriverCreateError({
driver: ProviderDriverKindSchema.make("settings"),
instanceId: ProviderInstanceId.make("settings"),
detail: "Failed to read server settings before building provider adapters.",
cause,
});
function makeDriversById<R>(
drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>,
): ReadonlyMap<ProviderDriverKind, AnyProviderAdapterDriver<R>> {
@@ -244,9 +237,6 @@ const buildAdaptersFromConfigMap = Effect.fn("ProviderAdapterRegistry.buildAdapt
},
);
const closeAdapterEntry = (entry: LiveAdapterEntry): Effect.Effect<void> =>
Scope.close(entry.scope, Exit.void).pipe(Effect.ignore);
export function makeRegistryFromConfigMap<R>(input: {
readonly drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
@@ -274,169 +264,6 @@ export function makeDriverLayer<R>(input: {
) as Layer.Layer<ProviderAdapterRegistryV2, ProviderAdapterRegistryBuildError, R>;
}
export function makeDriverLayerFromSettings<R>(input: {
readonly drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>;
}): Layer.Layer<
ProviderAdapterRegistryV2,
ProviderAdapterRegistryBuildError,
R | ServerSettingsService
> {
return Layer.effect(
ProviderAdapterRegistryV2,
Effect.gen(function* () {
const settingsService = yield* ServerSettingsService;
const parentScope = yield* Effect.scope;
const driverContext = yield* Effect.context<R>();
const settings = yield* settingsService.getSettings.pipe(
Effect.mapError((cause) => makeSettingsReadError(cause)),
);
const configMap = deriveProviderAdapterInstanceConfigMap({
settings,
drivers: input.drivers,
});
const initialAdapters = yield* buildAdaptersFromConfigMap({
drivers: input.drivers,
configMap,
parentScope,
});
const adaptersRef = yield* Ref.make(initialAdapters);
const reconcileSemaphore = yield* Semaphore.make(1);
const driversById = makeDriversById(input.drivers);
const reconcileConfigMapWithR = Effect.fn("ProviderAdapterRegistry.reconcileConfigMap")(
function* (
nextConfigMap: ProviderInstanceConfigMap,
): Effect.fn.Return<void, ProviderAdapterRegistryBuildError, R> {
const previous = yield* Ref.get(adaptersRef);
const nextEntries = new Map<ProviderInstanceId, LiveAdapterEntry>();
const staleEntries: Array<LiveAdapterEntry> = [];
const nextIds = new Set<ProviderInstanceId>();
for (const [rawInstanceId, entry] of Object.entries(nextConfigMap)) {
const instanceId = ProviderInstanceId.make(rawInstanceId);
nextIds.add(instanceId);
if (!driversById.has(entry.driver)) {
yield* Effect.logWarning(
"Skipping orchestration-v2 provider adapter with unknown driver",
{
instanceId,
driver: entry.driver,
},
);
continue;
}
const existing = previous.get(instanceId);
if (existing !== undefined && entryEqual(existing.entry, entry)) {
nextEntries.set(instanceId, existing);
continue;
}
const nextEntry = yield* createAdapterEntryFromConfigEntry({
driversById,
parentScope,
instanceId,
entry,
});
nextEntries.set(instanceId, nextEntry);
if (existing !== undefined) {
staleEntries.push(existing);
}
}
for (const [instanceId, existing] of previous) {
if (!nextIds.has(instanceId)) {
staleEntries.push(existing);
}
}
yield* Ref.set(adaptersRef, nextEntries);
for (const entry of staleEntries) {
yield* closeAdapterEntry(entry);
}
},
);
const reconcileConfigMap = (nextConfigMap: ProviderInstanceConfigMap) =>
reconcileConfigMapWithR(nextConfigMap).pipe(Effect.provideContext(driverContext));
const refreshFromSettings = Effect.fn("ProviderAdapterRegistry.refreshFromSettings")(
function* (): Effect.fn.Return<void, ProviderAdapterRegistryV2Error, never> {
const latestSettings = yield* settingsService.getSettings.pipe(
Effect.mapError((cause) => makeSettingsReadError(cause)),
);
yield* reconcileConfigMap(
deriveProviderAdapterInstanceConfigMap({
settings: latestSettings,
drivers: input.drivers,
}),
);
},
);
yield* settingsService.streamChanges.pipe(
Stream.runForEach((nextSettings) =>
reconcileSemaphore.withPermits(1)(
reconcileConfigMap(
deriveProviderAdapterInstanceConfigMap({
settings: nextSettings,
drivers: input.drivers,
}),
).pipe(
Effect.catchCause((cause) =>
Effect.logError("Orchestration-v2 provider adapter registry reconcile failed", {
cause,
}),
),
),
),
),
Effect.forkScoped,
);
const refreshAndGet = Effect.fn("ProviderAdapterRegistry.refreshAndGet")(function* (
instanceId: ProviderInstanceId,
): Effect.fn.Return<ProviderAdapterV2Shape, ProviderAdapterRegistryV2Error, never> {
return yield* reconcileSemaphore.withPermits(1)(
Effect.gen(function* () {
const cached = (yield* Ref.get(adaptersRef)).get(instanceId);
if (cached !== undefined) {
return cached.adapter;
}
yield* refreshFromSettings();
const refreshed = (yield* Ref.get(adaptersRef)).get(instanceId);
if (refreshed === undefined) {
return yield* new ProviderAdapterRegistryLookupError({ instanceId });
}
return refreshed.adapter;
}),
);
});
const get = Effect.fn("ProviderAdapterRegistry.get")(function* (
instanceId: ProviderInstanceId,
): Effect.fn.Return<ProviderAdapterV2Shape, ProviderAdapterRegistryV2Error, never> {
const cached = (yield* Ref.get(adaptersRef)).get(instanceId);
if (cached !== undefined) {
return cached.adapter;
}
return yield* refreshAndGet(instanceId);
});
return ProviderAdapterRegistryV2.of({
get,
list: () =>
Ref.get(adaptersRef).pipe(
Effect.map((adapters) =>
Array.from(adapters.values()).map((entry) => entry.adapter.instanceId),
),
),
} satisfies ProviderAdapterRegistryV2Shape);
}),
);
}
export const layerFromProviderAdapter: Layer.Layer<
ProviderAdapterRegistryV2,
never,
@@ -6,6 +6,8 @@ import {
type OrchestrationV2AppThread,
type OrchestrationV2DomainEvent,
type OrchestrationV2ProviderThread,
ProviderDriverKind,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -43,6 +45,11 @@ const TestLayer = Layer.mergeAll(
Layer.provide(Layer.mergeAll(TestStoresLayer, TestEventSinkLayer, idAllocatorLayer)),
),
);
const modelSelection = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
} satisfies ModelSelection;
const CODEX_DRIVER = ProviderDriverKind.make("codex");
function threadCreatedEvent(
now: DateTime.Utc,
@@ -57,7 +64,7 @@ function threadCreatedEvent(
projectId,
});
const providerThreadId = idAllocator.derive.providerThread({
provider: "codex",
driver: CODEX_DRIVER,
nativeThreadId: "native-thread",
});
const thread: OrchestrationV2AppThread = {
@@ -66,11 +73,8 @@ function threadCreatedEvent(
id: threadId,
projectId,
title: "Provider event ingestor",
defaultProvider: "codex",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
},
providerInstanceId: modelSelection.instanceId,
modelSelection: modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
@@ -111,20 +115,21 @@ layer("ProviderEventIngestorV2", (it) => {
const idAllocator = yield* IdAllocatorV2;
const threadEvent = yield* threadCreatedEvent(now);
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId: threadEvent.threadId,
});
const providerThread: OrchestrationV2ProviderThread = {
id: idAllocator.derive.providerThread({
provider: "codex",
driver: CODEX_DRIVER,
nativeThreadId: "native-thread",
}),
provider: "codex",
driver: CODEX_DRIVER,
providerInstanceId: modelSelection.instanceId,
providerSessionId,
appThreadId: threadEvent.threadId,
ownerNodeId: null,
nativeThreadRef: {
provider: "codex",
driver: CODEX_DRIVER,
nativeId: "native-thread",
strength: "strong",
},
@@ -141,10 +146,11 @@ layer("ProviderEventIngestorV2", (it) => {
yield* eventSink.write({ events: [threadEvent] });
const storedEvents = yield* ingestor.ingestNormalized({
providerSessionId,
providerInstanceId: modelSelection.instanceId,
threadId: threadEvent.threadId,
event: {
type: "provider_thread.updated",
provider: "codex",
driver: CODEX_DRIVER,
providerThread,
},
});
@@ -194,17 +200,18 @@ layer("ProviderEventIngestorV2", (it) => {
projectId,
});
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId,
});
const normalized = yield* ingestor.normalize({
providerSessionId,
providerInstanceId: modelSelection.instanceId,
threadId,
event: {
type: "turn.terminal",
provider: "codex",
driver: CODEX_DRIVER,
providerTurnId: idAllocator.derive.providerTurn({
provider: "codex",
driver: CODEX_DRIVER,
nativeTurnId: "native-turn",
}),
status: "completed",
@@ -225,7 +232,7 @@ layer("ProviderEventIngestorV2", (it) => {
throw new Error("Expected a thread.created fixture event");
}
const childThreadId = idAllocator.derive.threadFromProviderThread({
provider: "codex",
driver: CODEX_DRIVER,
nativeThreadId: "native-subagent-thread",
});
const childRootNodeId = NodeId.make("node:subagent-root");
@@ -245,25 +252,27 @@ layer("ProviderEventIngestorV2", (it) => {
},
};
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId: rootEvent.threadId,
});
const threadEvents = yield* ingestor.normalize({
providerSessionId,
providerInstanceId: modelSelection.instanceId,
threadId: rootEvent.threadId,
event: {
type: "app_thread.created",
provider: "codex",
driver: CODEX_DRIVER,
appThread: childThread,
},
});
const messageEvents = yield* ingestor.normalize({
providerSessionId,
providerInstanceId: modelSelection.instanceId,
threadId: rootEvent.threadId,
event: {
type: "message.updated",
provider: "codex",
driver: CODEX_DRIVER,
message: {
createdBy: "agent",
creationSource: "provider",
@@ -3,6 +3,7 @@ import {
CommandId,
OrchestrationV2DomainEvent,
OrchestrationV2StoredEvent,
ProviderInstanceId,
ProviderSessionId,
RawEventId,
RunId,
@@ -54,6 +55,7 @@ export type ProviderEventIngestorV2Error = typeof ProviderEventIngestorV2Error.T
export interface ProviderEventIngestorV2Shape {
readonly normalize: (input: {
readonly providerSessionId: ProviderSessionId;
readonly providerInstanceId: ProviderInstanceId;
readonly commandId?: CommandId;
readonly threadId: ThreadId;
readonly runId?: RunId;
@@ -63,6 +65,7 @@ export interface ProviderEventIngestorV2Shape {
}) => Effect.Effect<ReadonlyArray<OrchestrationV2DomainEvent>, ProviderEventIngestorV2Error>;
readonly ingestNormalized: (input: {
readonly providerSessionId: ProviderSessionId;
readonly providerInstanceId: ProviderInstanceId;
readonly commandId?: CommandId;
readonly threadId: ThreadId;
readonly runId?: RunId;
@@ -91,6 +94,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
const makeDomainEvent = (
input: {
readonly providerSessionId: ProviderSessionId;
readonly providerInstanceId: ProviderInstanceId;
readonly commandId?: CommandId;
readonly threadId: ThreadId;
readonly runId?: RunId;
@@ -120,7 +124,8 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
threadId,
runId: payloadInput.runId ?? input.runId,
nodeId: payloadInput.nodeId ?? input.nodeId,
provider: input.event.provider,
driver: input.event.driver,
providerInstanceId: input.providerInstanceId,
rawEventId: input.rawEventId,
occurredAt,
payload: payloadInput.payload,
@@ -8,6 +8,8 @@ import {
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
ProviderDriverKind,
ProviderInstanceId,
type ProviderSessionId,
ThreadId,
} from "@t3tools/contracts";
@@ -74,6 +76,7 @@ const modelSelection = {
provider: "codex",
model: "gpt-5.4",
} satisfies ModelSelection;
const CODEX_DRIVER = ProviderDriverKind.make("codex");
const runtimePolicy = {
runtimeMode: "full-access",
@@ -87,7 +90,8 @@ function makeProviderSession(input: {
}): OrchestrationV2ProviderSession {
return {
id: input.providerSessionId,
provider: "codex",
driver: CODEX_DRIVER,
providerInstanceId: modelSelection.instanceId,
status: "ready",
cwd: process.cwd(),
model: "gpt-5.4",
@@ -108,7 +112,7 @@ function makeThreadCreatedEvent(input: {
fixtureName: "provider-session-manager",
});
const providerThreadId = input.idAllocator.derive.providerThread({
provider: "codex",
driver: CODEX_DRIVER,
nativeThreadId: "native-thread",
});
const thread: OrchestrationV2AppThread = {
@@ -117,7 +121,7 @@ function makeThreadCreatedEvent(input: {
id: input.threadId,
projectId,
title: "Provider session manager",
defaultProvider: "codex",
providerInstanceId: modelSelection.instanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
@@ -153,15 +157,16 @@ function makeProviderThread(input: {
}): OrchestrationV2ProviderThread {
return {
id: input.idAllocator.derive.providerThread({
provider: "codex",
driver: CODEX_DRIVER,
nativeThreadId: "native-thread",
}),
provider: "codex",
driver: CODEX_DRIVER,
providerInstanceId: modelSelection.instanceId,
providerSessionId: input.providerSessionId,
appThreadId: input.threadId,
ownerNodeId: null,
nativeThreadRef: {
provider: "codex",
driver: CODEX_DRIVER,
nativeId: "native-thread",
strength: "strong",
},
@@ -179,7 +184,7 @@ function makeProviderThread(input: {
function unimplemented(detail: string) {
return Effect.fail(
new ProviderAdapterProtocolError({
provider: "codex",
driver: CODEX_DRIVER,
detail,
}),
);
@@ -195,7 +200,8 @@ function makeProviderAdapter(
} = {},
): ProviderAdapterV2Shape {
return {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
driver: CODEX_DRIVER,
getCapabilities: () => Effect.succeed(CodexCapabilities),
openSession: (input) =>
Effect.gen(function* () {
@@ -228,14 +234,15 @@ function makeProviderAdapter(
);
return {
provider: "codex",
instanceId: ProviderInstanceId.make("codex"),
driver: CODEX_DRIVER,
providerSessionId: input.providerSessionId,
providerSession: session,
rawEvents: Stream.empty,
events: options.failEventStream
? Stream.fail(
new ProviderAdapterEventStreamError({
provider: "codex",
driver: CODEX_DRIVER,
providerSessionId: input.providerSessionId,
cause: "process exited",
}),
@@ -306,7 +313,7 @@ function makePendingRuntimeRequestEvents(input: {
}) {
return Effect.gen(function* () {
const requestId = yield* input.idAllocator.allocate.runtimeRequest({
provider: "codex",
driver: CODEX_DRIVER,
nativeRequestId: "pending-approval",
});
const nodeId = input.idAllocator.derive.approvalNode({ requestId });
@@ -332,7 +339,7 @@ function makePendingRuntimeRequestEvents(input: {
nodeId,
providerTurnId: null,
nativeRequestRef: {
provider: "codex" as const,
driver: CODEX_DRIVER,
nativeId: "pending-approval",
strength: "strong" as const,
},
@@ -373,7 +380,7 @@ function makePendingRuntimeRequestEvents(input: {
type: "node.updated" as const,
threadId: input.threadId,
nodeId,
provider: "codex" as const,
driver: CODEX_DRIVER,
occurredAt: input.now,
payload: node,
},
@@ -385,7 +392,7 @@ function makePendingRuntimeRequestEvents(input: {
type: "runtime-request.updated" as const,
threadId: input.threadId,
nodeId,
provider: "codex" as const,
driver: CODEX_DRIVER,
occurredAt: input.now,
payload: request,
},
@@ -397,7 +404,7 @@ function makePendingRuntimeRequestEvents(input: {
type: "turn-item.updated" as const,
threadId: input.threadId,
nodeId,
provider: "codex" as const,
driver: CODEX_DRIVER,
occurredAt: input.now,
payload: turnItem,
},
@@ -415,7 +422,7 @@ it.effect("ProviderSessionManagerV2 releases live sessions when its layer shuts
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-shutdown");
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId,
});
@@ -463,7 +470,7 @@ it.effect(
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread-provider-session-manager-mcp");
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId,
});
@@ -522,7 +529,7 @@ it.effect("ProviderSessionManagerV2 releases idle sessions without sweeping all
projectId,
});
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId,
});
@@ -572,7 +579,7 @@ it.effect(
projectId,
});
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId,
});
const providerThread = makeProviderThread({
@@ -585,7 +592,7 @@ it.effect(
const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
const rootNodeId = idAllocator.derive.rootNode({ runId });
const providerTurnId = idAllocator.derive.providerTurn({
provider: "codex",
driver: CODEX_DRIVER,
nativeTurnId: "native-turn",
});
@@ -628,7 +635,7 @@ it.effect(
assert.isDefined(queue);
yield* Queue.offer(queue!, {
type: "turn.terminal",
provider: "codex",
driver: CODEX_DRIVER,
providerTurnId,
status: "completed",
});
@@ -663,7 +670,7 @@ it.effect("ProviderSessionManagerV2 uses the same release path for runtime failu
projectId,
});
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId,
});
@@ -713,7 +720,7 @@ it.effect("ProviderSessionManagerV2 releases sessions when provider event stream
projectId,
});
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId,
});
@@ -767,7 +774,7 @@ it.effect("ProviderSessionManagerV2 marks pending runtime requests non-live on r
projectId,
});
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId,
});
const providerThread = makeProviderThread({
@@ -841,7 +848,7 @@ it.effect(
projectId,
});
const providerSessionId = yield* idAllocator.allocate.providerSession({
provider: "codex",
providerInstanceId: modelSelection.instanceId,
threadId: firstThreadId,
});
const firstProviderThread = makeProviderThread({
@@ -859,11 +866,11 @@ it.effect(
const firstRunId = idAllocator.derive.run({ threadId: firstThreadId, ordinal: 1 });
const secondRunId = idAllocator.derive.run({ threadId: secondThreadId, ordinal: 1 });
const firstProviderTurnId = idAllocator.derive.providerTurn({
provider: "codex",
driver: CODEX_DRIVER,
nativeTurnId: "native-turn-a",
});
const secondProviderTurnId = idAllocator.derive.providerTurn({
provider: "codex",
driver: CODEX_DRIVER,
nativeTurnId: "native-turn-b",
});
@@ -934,7 +941,7 @@ it.effect(
assert.isDefined(queue);
yield* Queue.offer(queue!, {
type: "turn.terminal",
provider: "codex",
driver: CODEX_DRIVER,
providerTurnId: firstProviderTurnId,
status: "completed",
});
@@ -944,7 +951,7 @@ it.effect(
yield* Queue.offer(queue!, {
type: "turn.terminal",
provider: "codex",
driver: CODEX_DRIVER,
providerTurnId: secondProviderTurnId,
status: "completed",
});
@@ -250,7 +250,7 @@ export const layerWithOptions = (
}),
type: "provider-session.updated",
threadId,
provider: input.entry.runtime.provider,
driver: input.entry.runtime.driver,
occurredAt: now,
payload,
} satisfies OrchestrationV2DomainEvent;
@@ -291,7 +291,7 @@ export const layerWithOptions = (
type: "runtime-request.updated",
threadId,
nodeId: request.nodeId,
provider: input.entry.runtime.provider,
driver: input.entry.runtime.driver,
occurredAt: now,
payload: {
...request,
@@ -315,7 +315,7 @@ export const layerWithOptions = (
threadId,
...(requestNode.runId === null ? {} : { runId: requestNode.runId }),
nodeId: requestNode.id,
provider: input.entry.runtime.provider,
driver: input.entry.runtime.driver,
occurredAt: now,
payload: {
...requestNode,
@@ -338,7 +338,7 @@ export const layerWithOptions = (
threadId,
...(turnItem.runId === null ? {} : { runId: turnItem.runId }),
...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
provider: input.entry.runtime.provider,
driver: input.entry.runtime.driver,
occurredAt: now,
payload: {
...turnItem,
@@ -426,7 +426,7 @@ export const layerWithOptions = (
cancelIdleFiber: false,
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("orchestration-v2.provider-session.idle-release-failed", {
Effect.logWarning("orchestration-v2.driver-session.idle-release-failed", {
providerSessionId: input.providerSessionId,
cause,
}),
@@ -578,7 +578,7 @@ export const layerWithOptions = (
) =>
activity.pipe(
Effect.catchCause((cause) =>
Effect.logWarning("orchestration-v2.provider-session.activity-failed", {
Effect.logWarning("orchestration-v2.driver-session.activity-failed", {
providerSessionId,
cause,
}),
@@ -661,7 +661,7 @@ export const layerWithOptions = (
reason: "server_shutdown",
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("orchestration-v2.provider-session.shutdown-release-failed", {
Effect.logWarning("orchestration-v2.driver-session.shutdown-release-failed", {
providerSessionId: entry.runtime.providerSessionId,
cause,
}),
@@ -1,78 +1,87 @@
import {
ModelSelection,
OrchestrationV2ContextHandoff,
OrchestrationV2ThreadProjection,
ProviderSessionId,
ProviderThreadId,
RunId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Schema from "effect/Schema";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
export const ProviderSwitchStrategyV2 = Schema.Literals([
"resume_with_delta_handoff",
"resume_with_full_handoff",
"new_thread_with_full_handoff",
]);
export type ProviderSwitchStrategyV2 = typeof ProviderSwitchStrategyV2.Type;
export const ProviderSwitchPlanV2 = Schema.Struct({
strategy: ProviderSwitchStrategyV2,
targetProviderThreadId: Schema.NullOr(ProviderThreadId),
handoff: Schema.NullOr(OrchestrationV2ContextHandoff),
});
export type ProviderSwitchPlanV2 = typeof ProviderSwitchPlanV2.Type;
export interface ProviderSwitchPlanV2 {
readonly instanceChanged: boolean;
readonly modelChanged: boolean;
readonly targetProviderThreadId: ProviderThreadId | null;
readonly releaseProviderSessionIds: ReadonlyArray<ProviderSessionId>;
}
export class ProviderSwitchPlanError extends Schema.TaggedErrorClass<ProviderSwitchPlanError>()(
"ProviderSwitchPlanError",
{
threadId: ThreadId,
targetRunId: RunId,
targetProvider: Schema.String,
targetProviderInstanceId: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to plan provider switch to ${this.targetProvider} for run ${this.targetRunId}.`;
}
}
export class ProviderSwitchApplyError extends Schema.TaggedErrorClass<ProviderSwitchApplyError>()(
"ProviderSwitchApplyError",
{
threadId: ThreadId,
targetRunId: RunId,
strategy: ProviderSwitchStrategyV2,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to apply provider switch strategy ${this.strategy} for run ${this.targetRunId}.`;
}
}
export const ProviderSwitchServiceV2Error = Schema.Union([
ProviderSwitchPlanError,
ProviderSwitchApplyError,
]);
export type ProviderSwitchServiceV2Error = typeof ProviderSwitchServiceV2Error.Type;
) {}
export interface ProviderSwitchServiceV2Shape {
readonly plan: (input: {
readonly projection: OrchestrationV2ThreadProjection;
readonly targetRunId: RunId;
readonly targetModelSelection: ModelSelection;
}) => Effect.Effect<ProviderSwitchPlanV2, ProviderSwitchServiceV2Error>;
readonly apply: (input: {
readonly projection: OrchestrationV2ThreadProjection;
readonly targetRunId: RunId;
readonly targetModelSelection: ModelSelection;
readonly plan: ProviderSwitchPlanV2;
}) => Effect.Effect<ProviderSwitchPlanV2, ProviderSwitchServiceV2Error>;
}) => Effect.Effect<ProviderSwitchPlanV2, ProviderSwitchPlanError>;
}
export class ProviderSwitchServiceV2 extends Context.Service<
ProviderSwitchServiceV2,
ProviderSwitchServiceV2Shape
>()("t3/orchestration-v2/ProviderSwitchService/ProviderSwitchServiceV2") {}
export const layer: Layer.Layer<ProviderSwitchServiceV2> = Layer.succeed(
ProviderSwitchServiceV2,
ProviderSwitchServiceV2.of({
plan: ({ projection, targetModelSelection }) =>
Effect.sync(() => {
const current = projection.thread.modelSelection;
const instanceChanged = current.instanceId !== targetModelSelection.instanceId;
const modelChanged = current.model !== targetModelSelection.model;
const targetProviderThread = projection.providerThreads
.filter(
(thread) =>
thread.appThreadId === projection.thread.id &&
thread.ownerNodeId === null &&
thread.providerInstanceId === targetModelSelection.instanceId,
)
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
)[0];
const releaseProviderSessionIds = projection.providerSessions
.filter((session) => {
if (session.status === "stopped" || session.status === "error") return false;
if (instanceChanged) {
return session.providerInstanceId !== targetModelSelection.instanceId;
}
return modelChanged && !session.capabilities.sessions.supportsModelSwitchInSession;
})
.map((session) => session.id);
return {
instanceChanged,
modelChanged,
targetProviderThreadId: targetProviderThread?.id ?? null,
releaseProviderSessionIds,
};
}).pipe(
Effect.mapError(
(cause) =>
new ProviderSwitchPlanError({
threadId: projection.thread.id,
targetProviderInstanceId: targetModelSelection.instanceId,
cause,
}),
),
),
}),
);
@@ -0,0 +1,236 @@
import {
MessageId,
ProviderSessionId,
ProviderThreadId,
ProviderTurnId,
RunAttemptId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
const yieldToRuntime = Effect.yieldNow.pipe(
Effect.andThen(
Effect.promise(
() =>
new Promise<void>((resolve) => {
setImmediate(resolve);
}),
),
),
);
export class ProviderTurnControlError extends Schema.TaggedErrorClass<ProviderTurnControlError>()(
"ProviderTurnControlError",
{
threadId: ThreadId,
operation: Schema.Literals(["interrupt", "restart", "steer"]),
providerTurnId: ProviderTurnId,
cause: Schema.optional(Schema.Defect()),
},
) {}
export interface ProviderTurnControlServiceV2Shape {
readonly interrupt: (input: {
readonly threadId: ThreadId;
readonly providerSessionId: ProviderSessionId;
readonly providerThreadId: ProviderThreadId;
readonly providerTurnId: ProviderTurnId;
}) => Effect.Effect<void, ProviderTurnControlError>;
readonly steer: (input: {
readonly threadId: ThreadId;
readonly providerSessionId: ProviderSessionId;
readonly providerThreadId: ProviderThreadId;
readonly providerTurnId: ProviderTurnId;
readonly messageId: MessageId;
}) => Effect.Effect<void, ProviderTurnControlError>;
readonly interruptAndAwaitTerminal: (input: {
readonly threadId: ThreadId;
readonly providerSessionId: ProviderSessionId;
readonly providerThreadId: ProviderThreadId;
readonly providerTurnId: ProviderTurnId;
readonly interruptedAttemptId: RunAttemptId;
}) => Effect.Effect<void, ProviderTurnControlError>;
}
export class ProviderTurnControlServiceV2 extends Context.Service<
ProviderTurnControlServiceV2,
ProviderTurnControlServiceV2Shape
>()("t3/orchestration-v2/ProviderTurnControlService/ProviderTurnControlServiceV2") {}
export const layer: Layer.Layer<
ProviderTurnControlServiceV2,
never,
ProjectionStoreV2 | ProviderSessionManagerV2
> = Layer.effect(
ProviderTurnControlServiceV2,
Effect.gen(function* () {
const projections = yield* ProjectionStoreV2;
const sessions = yield* ProviderSessionManagerV2;
const load = (input: {
readonly threadId: ThreadId;
readonly providerSessionId: ProviderSessionId;
readonly providerThreadId: ProviderThreadId;
readonly providerTurnId: ProviderTurnId;
readonly operation: "interrupt" | "restart" | "steer";
}) =>
Effect.gen(function* () {
const projection = yield* projections.getThreadProjection(input.threadId);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === input.providerThreadId,
);
const providerTurn = projection.providerTurns.find(
(candidate) => candidate.id === input.providerTurnId,
);
if (
providerThread === undefined ||
providerTurn === undefined ||
providerThread.providerSessionId !== input.providerSessionId ||
providerTurn.providerThreadId !== providerThread.id
) {
return yield* new ProviderTurnControlError({
threadId: input.threadId,
operation: input.operation,
providerTurnId: input.providerTurnId,
cause: "The recorded provider execution target is no longer valid.",
});
}
if (providerTurn.status !== "running") {
return { projection, providerThread, providerTurn, session: Option.none() };
}
const session = yield* sessions.get(input.providerSessionId);
if (Option.isNone(session)) {
return yield* new ProviderTurnControlError({
threadId: input.threadId,
operation: input.operation,
providerTurnId: input.providerTurnId,
cause: `Provider session ${input.providerSessionId} is not active.`,
});
}
return { projection, providerThread, providerTurn, session };
});
return ProviderTurnControlServiceV2.of({
interrupt: (input) =>
Effect.gen(function* () {
const loaded = yield* load({ ...input, operation: "interrupt" });
if (Option.isNone(loaded.session)) return;
yield* loaded.session.value.interruptTurn({
providerThread: loaded.providerThread,
providerTurnId: loaded.providerTurn.id,
});
}).pipe(
Effect.mapError((cause) =>
Schema.is(ProviderTurnControlError)(cause)
? cause
: new ProviderTurnControlError({
threadId: input.threadId,
operation: "interrupt",
providerTurnId: input.providerTurnId,
cause,
}),
),
),
interruptAndAwaitTerminal: (input) =>
Effect.gen(function* () {
const loaded = yield* load({ ...input, operation: "restart" });
if (Option.isSome(loaded.session)) {
yield* loaded.session.value.interruptTurn({
providerThread: loaded.providerThread,
providerTurnId: loaded.providerTurn.id,
});
}
for (let remaining = 1_000; remaining > 0; remaining -= 1) {
const projection = yield* projections.getThreadProjection(input.threadId);
const providerTurn = projection.providerTurns.find(
(candidate) => candidate.id === input.providerTurnId,
);
const attempt = projection.attempts.find(
(candidate) => candidate.id === input.interruptedAttemptId,
);
if (
providerTurn !== undefined &&
providerTurn.status !== "running" &&
attempt !== undefined &&
attempt.status !== "running"
) {
return;
}
// Provider terminal events are projected on a detached ingestion
// fiber. Yield through the Node event loop instead of sleeping on
// Effect's clock so deterministic runtimes cannot deadlock a
// command that is waiting for that projection.
yield* yieldToRuntime;
}
return yield* new ProviderTurnControlError({
threadId: input.threadId,
operation: "restart",
providerTurnId: input.providerTurnId,
cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
});
}).pipe(
Effect.mapError((cause) =>
Schema.is(ProviderTurnControlError)(cause)
? cause
: new ProviderTurnControlError({
threadId: input.threadId,
operation: "restart",
providerTurnId: input.providerTurnId,
cause,
}),
),
),
steer: (input) =>
Effect.gen(function* () {
const loaded = yield* load({ ...input, operation: "steer" });
if (Option.isNone(loaded.session)) return;
const message = loaded.projection.messages.find(
(candidate) => candidate.id === input.messageId,
);
const run = loaded.projection.runs.find(
(candidate) => candidate.activeAttemptId === loaded.providerTurn.runAttemptId,
);
if (message === undefined || run === undefined) {
return yield* new ProviderTurnControlError({
threadId: input.threadId,
operation: "steer",
providerTurnId: input.providerTurnId,
cause: "The persisted steering message or target run is missing.",
});
}
yield* loaded.session.value.steerTurn({
threadId: input.threadId,
runId: run.id,
providerThread: loaded.providerThread,
providerTurnId: loaded.providerTurn.id,
message: {
messageId: message.id,
text: message.text,
attachments: message.attachments,
createdBy: message.createdBy,
creationSource: message.creationSource,
},
});
}).pipe(
Effect.mapError((cause) =>
Schema.is(ProviderTurnControlError)(cause)
? cause
: new ProviderTurnControlError({
threadId: input.threadId,
operation: "steer",
providerTurnId: input.providerTurnId,
cause,
}),
),
),
});
}),
);
@@ -0,0 +1,339 @@
import {
CommandId,
type OrchestrationV2DomainEvent,
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderThread,
type OrchestrationV2Run,
type OrchestrationV2RunAttempt,
RunId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { EventSinkV2 } from "./EventSink.ts";
import { providerMessageWithContextHandoffs } from "./ContextHandoffService.ts";
import { IdAllocatorV2 } from "./IdAllocator.ts";
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { RunExecutionServiceV2 } from "./RunExecutionService.ts";
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
export class ProviderTurnStartError extends Schema.TaggedErrorClass<ProviderTurnStartError>()(
"ProviderTurnStartError",
{
runId: RunId,
cause: Schema.optional(Schema.Defect()),
},
) {}
export interface ProviderTurnStartServiceV2Shape {
readonly start: (input: {
readonly threadId: ThreadId;
readonly runId: RunId;
}) => Effect.Effect<void, ProviderTurnStartError>;
}
export class ProviderTurnStartServiceV2 extends Context.Service<
ProviderTurnStartServiceV2,
ProviderTurnStartServiceV2Shape
>()("t3/orchestration-v2/ProviderTurnStartService/ProviderTurnStartServiceV2") {}
export const layer: Layer.Layer<
ProviderTurnStartServiceV2,
never,
| EventSinkV2
| IdAllocatorV2
| ProjectionStoreV2
| ProviderSessionManagerV2
| RunExecutionServiceV2
| RuntimePolicyV2
> = Layer.effect(
ProviderTurnStartServiceV2,
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const idAllocator = yield* IdAllocatorV2;
const projectionStore = yield* ProjectionStoreV2;
const providerSessions = yield* ProviderSessionManagerV2;
const runExecution = yield* RunExecutionServiceV2;
const runtimePolicy = yield* RuntimePolicyV2;
const start = Effect.fn("orchestrationV2.providerTurnStart.start")(function* (input: {
readonly threadId: ThreadId;
readonly runId: RunId;
}) {
const { runId } = input;
const projection = yield* projectionStore.getThreadProjection(input.threadId);
const run = projection.runs.find((candidate) => candidate.id === runId);
if (run === undefined) {
return yield* new ProviderTurnStartError({ runId, cause: `Run ${runId} was not found.` });
}
if (run.status !== "starting") {
// The effect is idempotent once the run has advanced or terminalized.
return;
}
const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId);
const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === run.providerThreadId,
);
const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
const checkpointScope = projection.checkpointScopes.find(
(candidate) => candidate.id === rootNode?.checkpointScopeId,
);
const handoffs = projection.contextHandoffs.filter(
(handoff) => handoff.targetRunId === run.id && handoff.status === "ready",
);
const nativeForkTransfer = projection.contextTransfers.find(
(transfer) =>
transfer.type === "fork" &&
transfer.targetThreadId === input.threadId &&
transfer.targetRunId === run.id &&
transfer.status === "pending" &&
transfer.resolution === null,
);
if (
rootNode === undefined ||
attempt === undefined ||
providerThread === undefined ||
providerThread.providerSessionId === null ||
message === undefined ||
checkpointScope === undefined
) {
return yield* new ProviderTurnStartError({
runId,
cause: `Run ${runId} is missing its execution projection state.`,
});
}
const providerSessionId = providerThread.providerSessionId;
const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
thread: projection.thread,
modelSelection: run.modelSelection,
});
const existingSessionProjection = projection.providerSessions.find(
(candidate) => candidate.id === providerSessionId,
);
const activeSession = yield* providerSessions.get(providerSessionId);
const session = yield* providerSessions.open({
threadId: projection.thread.id,
providerSessionId,
modelSelection: run.modelSelection,
runtimePolicy: resolvedRuntimePolicy,
...(existingSessionProjection === undefined
? {}
: { resumeFromSession: existingSessionProjection }),
});
const loadedProviderThread = yield* Effect.gen(function* () {
if (nativeForkTransfer !== undefined) {
const sourceProjection = yield* projectionStore.getThreadProjection(
nativeForkTransfer.sourceThreadId,
);
const sourceRun = sourceProjection.runs.find(
(candidate) => candidate.id === nativeForkTransfer.sourcePoint.runId,
);
const sourceProviderThread = sourceProjection.providerThreads.find(
(candidate) => candidate.id === sourceRun?.providerThreadId,
);
const sourceAttempt = sourceProjection.attempts.find(
(candidate) => candidate.id === sourceRun?.activeAttemptId,
);
const sourceProviderTurn = sourceProjection.providerTurns.find(
(candidate) =>
candidate.id === sourceAttempt?.providerTurnId ||
candidate.runAttemptId === sourceAttempt?.id,
);
if (sourceRun === undefined || sourceProviderThread === undefined) {
return yield* new ProviderTurnStartError({
runId,
cause: `Native fork transfer ${nativeForkTransfer.id} has no source provider execution.`,
});
}
return yield* session.forkThread({
sourceProviderThread,
sourceProviderTurns: sourceProjection.providerTurns,
targetThreadId: projection.thread.id,
...(sourceProviderTurn === undefined ? {} : { providerTurnId: sourceProviderTurn.id }),
});
}
return providerThread.nativeThreadRef === null
? yield* session.ensureThread({
threadId: projection.thread.id,
modelSelection: run.modelSelection,
runtimePolicy: resolvedRuntimePolicy,
providerSessionId,
})
: Option.isSome(activeSession)
? providerThread
: yield* session.resumeThread({ providerThread });
});
const now = yield* DateTime.now;
const runningProviderThread: OrchestrationV2ProviderThread = {
...loadedProviderThread,
id: providerThread.id,
driver: session.driver,
providerInstanceId: run.providerInstanceId,
providerSessionId,
appThreadId: projection.thread.id,
ownerNodeId: providerThread.ownerNodeId,
firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,
lastRunOrdinal: run.ordinal,
handoffIds: providerThread.handoffIds,
forkedFrom: providerThread.forkedFrom,
status: "active",
createdAt: providerThread.createdAt,
updatedAt: now,
};
const runningRun: OrchestrationV2Run = {
...run,
status: "running",
startedAt: now,
};
const runningAttempt: OrchestrationV2RunAttempt = {
...attempt,
status: "running",
startedAt: now,
};
const runningRootNode: OrchestrationV2ExecutionNode = {
...rootNode,
status: "running",
startedAt: now,
};
const events: Array<OrchestrationV2DomainEvent> = [
{
id: yield* idAllocator.allocate.event({
threadId: projection.thread.id,
providerSessionId,
}),
type: "provider-session.updated",
threadId: projection.thread.id,
driver: session.driver,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: session.providerSession,
},
{
id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
type: "provider-thread.updated",
threadId: projection.thread.id,
driver: session.driver,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: runningProviderThread,
},
...(nativeForkTransfer === undefined || runningProviderThread.nativeThreadRef === null
? []
: [
{
id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
type: "context-transfer.updated" as const,
threadId: projection.thread.id,
runId: run.id,
driver: session.driver,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: {
...nativeForkTransfer,
targetProviderInstanceId: run.providerInstanceId,
targetRunId: run.id,
status: "consumed" as const,
resolution: {
strategy: "native_fork" as const,
providerThreadRef: runningProviderThread.nativeThreadRef,
},
error: null,
updatedAt: now,
consumedAt: now,
},
},
]),
{
id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
type: "run.updated",
threadId: projection.thread.id,
runId: run.id,
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: runningRun,
},
{
id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
type: "run-attempt.updated",
threadId: projection.thread.id,
runId: run.id,
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: runningAttempt,
},
{
id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
type: "node.updated",
threadId: projection.thread.id,
runId: run.id,
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: runningRootNode,
},
];
yield* eventSink.write({ events });
yield* runExecution.startRootRun({
commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`),
appThread: projection.thread,
providerSessionId,
session,
run: runningRun,
rootNode: runningRootNode,
checkpointScope,
providerThread: runningProviderThread,
attempt: runningAttempt,
attemptId: attempt.id,
providerTurnOrdinal:
Math.max(
0,
...projection.providerTurns
.filter((turn) => turn.providerThreadId === providerThread.id)
.map((turn) => turn.ordinal),
) + 1,
shouldFinalizeRun: () =>
projectionStore.getThreadProjection(projection.thread.id).pipe(
Effect.map(
(current) =>
current.runs.find((candidate) => candidate.id === run.id)?.activeAttemptId ===
attempt.id,
),
Effect.catchCause(() => Effect.succeed(false)),
),
message: {
messageId: message.id,
text:
handoffs.length === 0
? message.text
: providerMessageWithContextHandoffs({ handoffs, userText: message.text }),
attachments: message.attachments,
createdBy: message.createdBy,
creationSource: message.creationSource,
},
modelSelection: run.modelSelection,
runtimePolicy: resolvedRuntimePolicy,
});
});
return ProviderTurnStartServiceV2.of({
start: (input) =>
start(input).pipe(
Effect.mapError((cause) =>
Schema.is(ProviderTurnStartError)(cause)
? cause
: new ProviderTurnStartError({ runId: input.runId, cause }),
),
),
});
}),
);
@@ -2,7 +2,6 @@ import {
CommandId,
type ModelSelection,
type OrchestrationV2AppThread,
type OrchestrationV2Checkpoint,
type OrchestrationV2CheckpointScope,
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderThread,
@@ -150,7 +149,6 @@ export const layer: Layer.Layer<
OrchestrationV2Run["status"],
"completed" | "interrupted" | "failed" | "cancelled"
>;
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
}) =>
Effect.gen(function* () {
const completedAt = yield* DateTime.now;
@@ -162,43 +160,43 @@ export const layer: Layer.Layer<
const shouldFinalizeRun =
input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun();
if (!shouldFinalizeRun) {
yield* eventSink.write({
events: [
{
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
type: "run-attempt.updated" as const,
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
provider: input.run.provider,
occurredAt: completedAt,
payload: finalizedAttempt,
},
],
});
// A newer attempt already owns the run and the command that created
// it terminalized this attempt as superseded. Preserve that domain
// status while retaining the provider's interruption artifact.
if (input.status === "interrupted") {
yield* eventSink.write({
events: [
{
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
type: "turn-item.updated" as const,
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
providerInstanceId: input.run.providerInstanceId,
occurredAt: completedAt,
payload: makeInterruptResultTurnItem({
idAllocator,
run: input.run,
rootNode: input.rootNode,
providerThread: input.providerThread,
completedAt,
}),
},
],
});
}
return;
}
const checkpoint =
input.status === "completed"
? yield* checkpointService.capture({
scope: input.checkpointScope,
runId: input.run.id,
nodeId: input.rootNode.id,
ordinalWithinScope: input.run.ordinal,
appRunOrdinal: input.run.ordinal,
capturedAt: completedAt,
})
: null;
const persistedStatus = input.status === "completed" ? "waiting" : input.status;
const finalizedRun: OrchestrationV2Run = {
...input.run,
status: input.status,
completedAt,
checkpointId: checkpoint?.id ?? input.run.checkpointId,
status: persistedStatus,
completedAt: input.status === "completed" ? null : completedAt,
};
const finalizedRootNode: OrchestrationV2ExecutionNode = {
...input.rootNode,
status: input.status,
completedAt,
status: persistedStatus,
completedAt: input.status === "completed" ? null : completedAt,
checkpointScopeId: input.checkpointScope.id,
};
const finalizedProviderThread: OrchestrationV2ProviderThread = {
@@ -211,7 +209,25 @@ export const layer: Layer.Layer<
const providerThreadEventId = yield* idAllocator.allocate.event({
threadId: input.run.threadId,
});
yield* eventSink.write({
const checkpointCaptureCommandId = CommandId.make(
`command:effect:checkpoint.capture:${input.run.id}`,
);
yield* eventSink.writeWithEffects({
effects:
input.status === "completed"
? [
{
id: `effect:checkpoint.capture:${input.run.id}`,
commandId: checkpointCaptureCommandId,
threadId: input.run.threadId,
request: {
type: "checkpoint.capture" as const,
runId: input.run.id,
scopeId: input.checkpointScope.id,
},
},
]
: [],
events: [
...(finalizedAttempt === null
? []
@@ -222,42 +238,11 @@ export const layer: Layer.Layer<
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
provider: input.run.provider,
providerInstanceId: input.run.providerInstanceId,
occurredAt: completedAt,
payload: finalizedAttempt,
},
]),
...(checkpoint === null
? []
: [
{
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
type: "checkpoint.captured" as const,
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
provider: input.run.provider,
occurredAt: completedAt,
payload: checkpoint,
},
{
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
type: "turn-item.updated" as const,
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
provider: input.run.provider,
occurredAt: completedAt,
payload: makeCheckpointTurnItem({
idAllocator,
run: input.run,
rootNode: input.rootNode,
providerThread: input.providerThread,
checkpoint,
completedAt,
}),
},
]),
...(input.status === "interrupted"
? [
{
@@ -266,7 +251,7 @@ export const layer: Layer.Layer<
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
provider: input.run.provider,
providerInstanceId: input.run.providerInstanceId,
occurredAt: completedAt,
payload: makeInterruptResultTurnItem({
idAllocator,
@@ -284,7 +269,7 @@ export const layer: Layer.Layer<
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
provider: input.run.provider,
providerInstanceId: input.run.providerInstanceId,
occurredAt: completedAt,
payload: finalizedRun,
},
@@ -294,7 +279,7 @@ export const layer: Layer.Layer<
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
provider: input.run.provider,
providerInstanceId: input.run.providerInstanceId,
occurredAt: completedAt,
payload: finalizedRootNode,
},
@@ -302,7 +287,7 @@ export const layer: Layer.Layer<
id: providerThreadEventId,
type: "provider-thread.updated",
threadId: input.run.threadId,
provider: input.run.provider,
providerInstanceId: input.run.providerInstanceId,
occurredAt: completedAt,
payload: finalizedProviderThread,
},
@@ -336,6 +321,7 @@ export const layer: Layer.Layer<
if (shouldDeliverProviderEvent(event, assistantStreamingEnabled)) {
yield* providerEventIngestor.ingestNormalized({
providerSessionId: input.providerSessionId,
providerInstanceId: input.run.providerInstanceId,
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
@@ -370,7 +356,6 @@ export const layer: Layer.Layer<
? {}
: { shouldFinalizeRun: input.shouldFinalizeRun }),
status,
runtimePolicy: input.runtimePolicy,
}).pipe(
Effect.mapError(
(cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
@@ -379,7 +364,11 @@ export const layer: Layer.Layer<
}),
),
Effect.catchCause((cause) =>
Ref.get(latestProviderThread).pipe(
Effect.logWarning("orchestration V2 provider event ingestion failed", {
runId: input.run.id,
cause,
}).pipe(
Effect.andThen(Ref.get(latestProviderThread)),
Effect.flatMap((providerThread) =>
writeFinalRunEvents({
run: input.run,
@@ -391,7 +380,6 @@ export const layer: Layer.Layer<
? {}
: { shouldFinalizeRun: input.shouldFinalizeRun }),
status: "failed",
runtimePolicy: input.runtimePolicy,
}),
),
Effect.mapError(
@@ -438,7 +426,11 @@ export const layer: Layer.Layer<
})
.pipe(
Effect.catchCause((cause) =>
Fiber.interrupt(providerEventFiber).pipe(
Effect.logError("orchestration V2 provider turn start failed", {
runId: input.run.id,
cause,
}).pipe(
Effect.andThen(Fiber.interrupt(providerEventFiber)),
Effect.andThen(Ref.get(latestProviderThread)),
Effect.flatMap((providerThread) =>
writeFinalRunEvents({
@@ -451,7 +443,6 @@ export const layer: Layer.Layer<
? {}
: { shouldFinalizeRun: input.shouldFinalizeRun }),
status: "failed",
runtimePolicy: input.runtimePolicy,
}),
),
Effect.mapError(
@@ -470,39 +461,6 @@ export const layer: Layer.Layer<
}),
);
function makeCheckpointTurnItem(input: {
readonly idAllocator: IdAllocatorV2Shape;
readonly run: OrchestrationV2Run;
readonly rootNode: OrchestrationV2ExecutionNode;
readonly providerThread: OrchestrationV2ProviderThread;
readonly checkpoint: OrchestrationV2Checkpoint;
readonly completedAt: DateTime.Utc;
}): OrchestrationV2TurnItem {
return {
id: input.idAllocator.derive.turnItemFromProviderItem({
provider: input.run.provider,
nativeItemId: `checkpoint:${input.checkpoint.id}`,
}),
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
providerThreadId: input.providerThread.id,
providerTurnId: input.rootNode.providerTurnId,
nativeItemRef: null,
parentItemId: null,
ordinal: input.run.ordinal * 100 + 99,
status: "completed",
title: null,
startedAt: input.completedAt,
completedAt: input.completedAt,
updatedAt: input.completedAt,
type: "checkpoint",
checkpointId: input.checkpoint.id,
scopeId: input.checkpoint.scopeId,
files: input.checkpoint.files,
};
}
function makeInterruptResultTurnItem(input: {
readonly idAllocator: IdAllocatorV2Shape;
readonly run: OrchestrationV2Run;
@@ -1,4 +1,4 @@
import { ModelSelection, OrchestrationV2AppThread, ProviderKind } from "@t3tools/contracts";
import { ModelSelection, OrchestrationV2AppThread, ProviderDriverKind } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -15,12 +15,12 @@ import {
export class RuntimePolicyResolveError extends Schema.TaggedErrorClass<RuntimePolicyResolveError>()(
"RuntimePolicyResolveError",
{
provider: ProviderKind,
driver: ProviderDriverKind,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to resolve runtime policy for ${this.provider}.`;
return `Failed to resolve runtime policy for ${this.driver}.`;
}
}
@@ -1,75 +1,101 @@
import {
NodeId,
OrchestrationV2RuntimeRequest,
ProviderApprovalDecision,
ProviderSessionId,
ProviderUserInputAnswers,
RuntimeRequestId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type * as Effect from "effect/Effect";
export class RuntimeRequestOpenError extends Schema.TaggedErrorClass<RuntimeRequestOpenError>()(
"RuntimeRequestOpenError",
{
requestId: RuntimeRequestId,
nodeId: NodeId,
kind: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to open runtime request ${this.requestId} (${this.kind}).`;
}
}
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
export class RuntimeRequestNotFoundError extends Schema.TaggedErrorClass<RuntimeRequestNotFoundError>()(
"RuntimeRequestNotFoundError",
{
threadId: ThreadId,
requestId: RuntimeRequestId,
},
) {
override get message(): string {
return `Runtime request ${this.requestId} was not found in thread ${this.threadId}.`;
}
}
export class RuntimeRequestRespondError extends Schema.TaggedErrorClass<RuntimeRequestRespondError>()(
"RuntimeRequestRespondError",
export class RuntimeRequestResponseExecutionError extends Schema.TaggedErrorClass<RuntimeRequestResponseExecutionError>()(
"RuntimeRequestResponseExecutionError",
{
threadId: ThreadId,
requestId: RuntimeRequestId,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to respond to runtime request ${this.requestId} in thread ${this.threadId}.`;
}
}
export const RuntimeRequestServiceV2Error = Schema.Union([
RuntimeRequestOpenError,
RuntimeRequestNotFoundError,
RuntimeRequestRespondError,
]);
export type RuntimeRequestServiceV2Error = typeof RuntimeRequestServiceV2Error.Type;
) {}
export interface RuntimeRequestServiceV2Shape {
readonly open: (
request: OrchestrationV2RuntimeRequest,
) => Effect.Effect<void, RuntimeRequestServiceV2Error>;
readonly respond: (input: {
readonly threadId: ThreadId;
readonly providerSessionId: ProviderSessionId;
readonly requestId: RuntimeRequestId;
readonly decision?: ProviderApprovalDecision;
readonly answers?: ProviderUserInputAnswers;
readonly response?: unknown;
}) => Effect.Effect<OrchestrationV2RuntimeRequest, RuntimeRequestServiceV2Error>;
}) => Effect.Effect<void, RuntimeRequestResponseExecutionError>;
}
export class RuntimeRequestServiceV2 extends Context.Service<
RuntimeRequestServiceV2,
RuntimeRequestServiceV2Shape
>()("t3/orchestration-v2/RuntimeRequestService/RuntimeRequestServiceV2") {}
export const layer: Layer.Layer<
RuntimeRequestServiceV2,
never,
ProjectionStoreV2 | ProviderSessionManagerV2
> = Layer.effect(
RuntimeRequestServiceV2,
Effect.gen(function* () {
const projections = yield* ProjectionStoreV2;
const sessions = yield* ProviderSessionManagerV2;
return RuntimeRequestServiceV2.of({
respond: (input) =>
Effect.gen(function* () {
const projection = yield* projections.getThreadProjection(input.threadId);
const request = projection.runtimeRequests.find(
(candidate) => candidate.id === input.requestId,
);
if (request === undefined) {
return yield* new RuntimeRequestResponseExecutionError({
threadId: input.threadId,
requestId: input.requestId,
cause: "The runtime request no longer exists.",
});
}
if (
request.responseCapability.type !== "live" ||
request.responseCapability.providerSessionId !== input.providerSessionId
) {
return yield* new RuntimeRequestResponseExecutionError({
threadId: input.threadId,
requestId: input.requestId,
cause: "The runtime request is not resumable on the recorded provider session.",
});
}
const session = yield* sessions.get(input.providerSessionId);
if (Option.isNone(session)) {
return yield* new RuntimeRequestResponseExecutionError({
threadId: input.threadId,
requestId: input.requestId,
cause: `Provider session ${input.providerSessionId} is not active.`,
});
}
yield* session.value.respondToRuntimeRequest({
requestId: input.requestId,
...(input.decision === undefined ? {} : { decision: input.decision }),
...(input.answers === undefined ? {} : { answers: input.answers }),
});
}).pipe(
Effect.mapError((cause) =>
Schema.is(RuntimeRequestResponseExecutionError)(cause)
? cause
: new RuntimeRequestResponseExecutionError({
threadId: input.threadId,
requestId: input.requestId,
cause,
}),
),
),
});
}),
);
@@ -0,0 +1,43 @@
import type {
OrchestrationV2ShellSnapshot,
OrchestrationV2ShellStreamItem,
OrchestrationV2StoredEvent,
} from "@t3tools/contracts";
/** Converts a committed event and its resulting shell snapshot into one delta. */
export function shellStreamItemFromSnapshot(input: {
readonly stored: OrchestrationV2StoredEvent;
readonly snapshot: OrchestrationV2ShellSnapshot;
}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
const active = input.snapshot.threads.find((thread) => thread.id === input.stored.event.threadId);
if (active !== undefined) {
return {
kind: "thread.updated",
sequence: input.stored.sequence,
location: "active",
thread: active,
};
}
const archived = input.snapshot.archivedThreads.find(
(thread) => thread.id === input.stored.event.threadId,
);
if (archived !== undefined) {
return {
kind: "thread.updated",
sequence: input.stored.sequence,
location: "archive",
thread: archived,
};
}
return {
kind: "thread.removed",
sequence: input.stored.sequence,
location:
input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null
? "archive"
: "active",
threadId: input.stored.event.threadId,
};
}
@@ -55,7 +55,7 @@ export function makeSubagentChildThread(input: {
creationSource: input.creationSource,
id: input.childThreadId,
title: input.title,
defaultProvider: input.providerInstanceId,
providerInstanceId: input.providerInstanceId,
modelSelection: input.modelSelection,
activeProviderThreadId: input.activeProviderThreadId,
lineage: {
@@ -1,58 +1,111 @@
import {
ContextTransferId,
OrchestrationV2Actor,
OrchestrationV2AppThread,
OrchestrationV2ThreadForkSourcePoint,
OrchestrationV2ContextSourcePoint,
OrchestrationV2ContextTransfer,
OrchestrationV2CreationSource,
OrchestrationV2ProviderThread,
OrchestrationV2Run,
OrchestrationV2ThreadProjection,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import type * as Effect from "effect/Effect";
export interface ThreadForkPlanV2 {
readonly targetThread: OrchestrationV2AppThread;
readonly transfer: OrchestrationV2ContextTransfer;
}
export class ThreadForkPlanError extends Schema.TaggedErrorClass<ThreadForkPlanError>()(
"ThreadForkPlanError",
{
sourceThreadId: ThreadId,
targetThreadId: ThreadId,
sourcePoint: OrchestrationV2ThreadForkSourcePoint,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to plan fork into thread ${this.targetThreadId}.`;
}
}
export class ThreadForkApplyError extends Schema.TaggedErrorClass<ThreadForkApplyError>()(
"ThreadForkApplyError",
{
targetThreadId: ThreadId,
sourcePoint: OrchestrationV2ThreadForkSourcePoint,
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to apply fork into thread ${this.targetThreadId}.`;
}
}
export const ThreadForkServiceV2Error = Schema.Union([ThreadForkPlanError, ThreadForkApplyError]);
export type ThreadForkServiceV2Error = typeof ThreadForkServiceV2Error.Type;
export interface ThreadForkPlanV2 {
readonly sourcePoint: OrchestrationV2ThreadForkSourcePoint;
readonly targetThreadId: ThreadId;
readonly targetThread: OrchestrationV2AppThread;
}
) {}
export interface ThreadForkServiceV2Shape {
readonly plan: (input: {
readonly sourcePoint: OrchestrationV2ThreadForkSourcePoint;
readonly sourceProjection: OrchestrationV2ThreadProjection;
readonly sourceRun: OrchestrationV2Run;
readonly sourceProviderThread: OrchestrationV2ProviderThread | undefined;
readonly canonicalSourcePoint: OrchestrationV2ContextSourcePoint;
readonly transferId: ContextTransferId;
readonly targetThreadId: ThreadId;
}) => Effect.Effect<ThreadForkPlanV2, ThreadForkServiceV2Error>;
readonly apply: (
plan: ThreadForkPlanV2,
) => Effect.Effect<ThreadForkPlanV2, ThreadForkServiceV2Error>;
readonly title?: string;
readonly createdBy: OrchestrationV2Actor;
readonly creationSource: OrchestrationV2CreationSource;
readonly createdAt: DateTime.Utc;
}) => Effect.Effect<ThreadForkPlanV2, ThreadForkPlanError>;
}
export class ThreadForkServiceV2 extends Context.Service<
ThreadForkServiceV2,
ThreadForkServiceV2Shape
>()("t3/orchestration-v2/ThreadForkService/ThreadForkServiceV2") {}
export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
ThreadForkServiceV2,
ThreadForkServiceV2.of({
plan: (input) =>
Effect.gen(function* () {
if (input.sourceRun.status !== "completed") {
return yield* new ThreadForkPlanError({
sourceThreadId: input.sourceProjection.thread.id,
targetThreadId: input.targetThreadId,
cause: `Fork source run ${input.sourceRun.id} is ${input.sourceRun.status}.`,
});
}
const targetThread: OrchestrationV2AppThread = {
...input.sourceProjection.thread,
createdBy: input.createdBy,
creationSource: input.creationSource,
id: input.targetThreadId,
title: input.title ?? `${input.sourceProjection.thread.title} fork`,
activeProviderThreadId: null,
lineage: {
parentThreadId: input.sourceProjection.thread.id,
relationshipToParent: "fork",
rootThreadId: input.sourceProjection.thread.lineage.rootThreadId,
},
forkedFrom: {
type: "run",
threadId: input.sourceProjection.thread.id,
runId: input.sourceRun.id,
},
createdAt: input.createdAt,
updatedAt: input.createdAt,
archivedAt: null,
deletedAt: null,
};
const transfer: OrchestrationV2ContextTransfer = {
id: input.transferId,
type: "fork",
sourceThreadId: input.sourceProjection.thread.id,
targetThreadId: input.targetThreadId,
sourcePoint: input.canonicalSourcePoint,
basePoint: null,
sourceProviderInstanceId: input.sourceRun.providerInstanceId,
targetProviderInstanceId: null,
targetRunId: null,
status: "pending",
resolution: null,
createdBy: input.createdBy,
error:
input.sourceProviderThread?.nativeThreadRef?.strength === "strong"
? null
: "Source provider thread does not expose a strong native thread ref.",
createdAt: input.createdAt,
updatedAt: input.createdAt,
consumedAt: null,
};
return { targetThread, transfer };
}),
}),
);
@@ -138,6 +138,7 @@ export interface ThreadManagementServiceShape {
readonly getThreadProjection: (
threadId: ThreadId,
) => Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorV2Error>;
readonly getThreadSnapshot: OrchestratorV2["Service"]["getThreadSnapshot"];
readonly getProjectThread: (input: {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
@@ -158,6 +159,7 @@ export interface ThreadManagementServiceShape {
) => Effect.Effect<ThreadManagementInterruptResult, ThreadManagementFailure>;
readonly getThreadEventSequence: OrchestratorV2["Service"]["getThreadEventSequence"];
readonly streamStoredEvents: OrchestratorV2["Service"]["streamStoredEvents"];
readonly streamStoredEventsFrom: OrchestratorV2["Service"]["streamStoredEventsFrom"];
readonly streamDomainEvents: OrchestratorV2["Service"]["streamDomainEvents"];
}
@@ -442,6 +444,7 @@ const make = Effect.gen(function* () {
return ThreadManagementService.of({
dispatch: orchestrator.dispatch,
getThreadProjection: orchestrator.getThreadProjection,
getThreadSnapshot: orchestrator.getThreadSnapshot,
getProjectThread,
getShellSnapshot: orchestrator.getShellSnapshot,
listProjectThreads,
@@ -450,6 +453,7 @@ const make = Effect.gen(function* () {
interruptThread,
getThreadEventSequence: orchestrator.getThreadEventSequence,
streamStoredEvents: orchestrator.streamStoredEvents,
streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
streamDomainEvents: orchestrator.streamDomainEvents,
});
});
@@ -0,0 +1,105 @@
import { OrchestrationV2TurnItem, RunId, ThreadId, TurnItemId } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export class TurnItemPositionStoreError extends Schema.TaggedErrorClass<TurnItemPositionStoreError>()(
"TurnItemPositionStoreError",
{
threadId: ThreadId,
turnItemId: TurnItemId,
cause: Schema.optional(Schema.Defect()),
},
) {}
export interface TurnItemPositionStoreV2Shape {
readonly allocate: (input: {
readonly threadId: ThreadId;
readonly turnItemId: TurnItemId;
readonly runId: RunId | null;
readonly runOrdinal?: number;
}) => Effect.Effect<number, TurnItemPositionStoreError>;
readonly normalize: (
item: OrchestrationV2TurnItem,
runOrdinal?: number,
) => Effect.Effect<OrchestrationV2TurnItem, TurnItemPositionStoreError>;
}
export class TurnItemPositionStoreV2 extends Context.Service<
TurnItemPositionStoreV2,
TurnItemPositionStoreV2Shape
>()("t3/orchestration-v2/TurnItemPositionStore/TurnItemPositionStoreV2") {}
export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlClient> = Layer.effect(
TurnItemPositionStoreV2,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const allocate: TurnItemPositionStoreV2Shape["allocate"] = ({
threadId,
turnItemId,
runId,
runOrdinal: suppliedRunOrdinal,
}) =>
Effect.gen(function* () {
const runRows =
runId === null
? []
: yield* sql<{ readonly ordinal: number }>`
SELECT ordinal
FROM orchestration_v2_projection_runs
WHERE thread_id = ${threadId} AND run_id = ${runId}
LIMIT 1
`;
const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;
const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;
const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;
yield* sql`
INSERT INTO orchestration_v2_turn_item_positions (thread_id, turn_item_id, ordinal)
SELECT
${threadId},
${turnItemId},
COALESCE(MAX(ordinal), ${lowerBound}) + 1
FROM orchestration_v2_turn_item_positions
WHERE thread_id = ${threadId}
AND ordinal >= ${lowerBound}
AND ordinal <= ${upperBound}
ON CONFLICT(thread_id, turn_item_id) DO NOTHING
`;
const rows = yield* sql<{ readonly ordinal: number }>`
SELECT ordinal
FROM orchestration_v2_turn_item_positions
WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
LIMIT 1
`;
const ordinal = rows[0]?.ordinal;
if (ordinal === undefined) {
return yield* new TurnItemPositionStoreError({
threadId,
turnItemId,
cause: "Position allocation returned no row.",
});
}
return ordinal;
}).pipe(
Effect.mapError((cause) =>
Schema.is(TurnItemPositionStoreError)(cause)
? cause
: new TurnItemPositionStoreError({ threadId, turnItemId, cause }),
),
);
return TurnItemPositionStoreV2.of({
allocate,
normalize: (item, runOrdinal) =>
allocate({
threadId: item.threadId,
turnItemId: item.id,
runId: item.runId,
...(runOrdinal === undefined ? {} : { runOrdinal }),
}).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal }))),
});
}),
);
@@ -4,19 +4,27 @@ import {
CommandId,
type ModelSelection,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts";
import { ServerConfig } from "../config.ts";
import { GitCoreLive } from "../git/Layers/GitCore.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import { OrchestratorV2 } from "./Orchestrator.ts";
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
import { OrchestrationV2LayerLive } from "./runtimeLayer.ts";
import { shellStreamItemFromSnapshot } from "./ShellStream.ts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-orchestration-v2-runtime-layer-",
@@ -32,11 +40,43 @@ const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
Layer.provide(NodeServices.layer),
);
const driver = ProviderDriverKind.make("codex");
const orchestrationAdapter = {
instanceId: modelSelection.instanceId,
driver,
getCapabilities: () => Effect.die("capabilities are not used by lifecycle tests"),
openSession: () => Effect.die("sessions are not used by lifecycle tests"),
} as ProviderAdapterV2Shape;
const providerInstance = {
instanceId: modelSelection.instanceId,
driverKind: driver,
continuationIdentity: {
driverKind: driver,
continuationKey: "codex:test",
},
displayName: "Codex test",
enabled: true,
snapshot: {} as ProviderInstance["snapshot"],
adapter: {} as ProviderInstance["adapter"],
orchestrationAdapter,
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const TestProviderInstanceRegistry = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(instanceId === providerInstance.instanceId ? providerInstance : undefined),
listInstances: Effect.succeed([providerInstance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.never,
});
const TestLayer = OrchestrationV2LayerLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(CheckpointStoreTestLayer),
Layer.provide(ServerConfigLayer),
Layer.provide(ServerSettingsService.layerTest()),
Layer.provide(TestProviderInstanceRegistry),
Layer.provide(NodeServices.layer),
);
@@ -70,8 +110,139 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => {
assert.equal(result.sequence, 1);
assert.equal(projection.thread.id, threadId);
assert.equal(projection.thread.projectId, projectId);
assert.equal(projection.thread.defaultProvider, "codex");
assert.equal(projection.thread.providerInstanceId, "codex");
assert.deepEqual(projection.runs, []);
}),
);
it.effect("applies lifecycle commands idempotently and emits archive/removal shell deltas", () =>
Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
const threadId = ThreadId.make("runtime-layer-lifecycle-thread");
const create = {
type: "thread.create" as const,
createdBy: "user" as const,
creationSource: "web" as const,
commandId: CommandId.make("runtime-layer-lifecycle-create"),
threadId,
projectId: ProjectId.make("runtime-layer-lifecycle-project"),
title: "Lifecycle thread",
modelSelection,
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
branch: null,
worktreePath: null,
};
const firstCreate = yield* orchestrator.dispatch(create);
const retriedCreate = yield* orchestrator.dispatch(create);
assert.equal(retriedCreate.sequence, firstCreate.sequence);
assert.lengthOf(retriedCreate.storedEvents, 1);
yield* orchestrator.dispatch({
type: "thread.metadata.update",
commandId: CommandId.make("runtime-layer-lifecycle-metadata"),
threadId,
title: "Renamed lifecycle thread",
branch: "feature/v2",
worktreePath: "/tmp/t3-v2-worktree",
});
yield* orchestrator.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("runtime-layer-lifecycle-runtime"),
threadId,
runtimeMode: "approval-required",
});
yield* orchestrator.dispatch({
type: "thread.interaction-mode.set",
commandId: CommandId.make("runtime-layer-lifecycle-interaction"),
threadId,
interactionMode: "plan",
});
yield* orchestrator.dispatch({
type: "thread.model-selection.set",
commandId: CommandId.make("runtime-layer-lifecycle-model"),
threadId,
modelSelection: { ...modelSelection, model: "gpt-5.5" },
});
const archive = yield* orchestrator.dispatch({
type: "thread.archive",
commandId: CommandId.make("runtime-layer-lifecycle-archive"),
threadId,
});
const archivedShell = yield* orchestrator.getShellSnapshot();
assert.notInclude(
archivedShell.threads.map((thread) => thread.id),
threadId,
);
assert.include(
archivedShell.archivedThreads.map((thread) => thread.id),
threadId,
);
assert.deepEqual(
shellStreamItemFromSnapshot({
stored: archive.storedEvents[0]!,
snapshot: archivedShell,
}),
{
kind: "thread.updated",
sequence: archive.sequence,
location: "archive",
thread: archivedShell.archivedThreads[0]!,
},
);
const remove = yield* orchestrator.dispatch({
type: "thread.delete",
commandId: CommandId.make("runtime-layer-lifecycle-delete"),
threadId,
});
const deletedShell = yield* orchestrator.getShellSnapshot();
assert.notInclude(
deletedShell.threads.map((thread) => thread.id),
threadId,
);
assert.notInclude(
deletedShell.archivedThreads.map((thread) => thread.id),
threadId,
);
assert.deepEqual(
shellStreamItemFromSnapshot({ stored: remove.storedEvents[0]!, snapshot: deletedShell }),
{
kind: "thread.removed",
sequence: remove.sequence,
location: "archive",
threadId,
},
);
const projection = yield* orchestrator.getThreadProjection(threadId);
assert.equal(projection.thread.title, "Renamed lifecycle thread");
assert.equal(projection.thread.branch, "feature/v2");
assert.equal(projection.thread.worktreePath, "/tmp/t3-v2-worktree");
assert.equal(projection.thread.runtimeMode, "approval-required");
assert.equal(projection.thread.interactionMode, "plan");
assert.equal(projection.thread.modelSelection.model, "gpt-5.5");
assert.isNotNull(projection.thread.archivedAt);
assert.isNotNull(projection.thread.deletedAt);
}),
);
it.effect("persists rejected command receipts across retries", () =>
Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
const command = {
type: "thread.archive" as const,
commandId: CommandId.make("runtime-layer-rejected-command"),
threadId: ThreadId.make("runtime-layer-missing-thread"),
};
const first = yield* orchestrator.dispatch(command).pipe(Effect.flip);
const retry = yield* orchestrator.dispatch(command).pipe(Effect.flip);
assert.equal(first._tag, "OrchestratorProjectionError");
assert.equal(retry._tag, "OrchestratorCommandPreviouslyRejectedError");
}),
);
});
@@ -1,31 +1,45 @@
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts";
import { claudeAgentSdkQueryRunnerLiveLayer } from "./Adapters/ClaudeAdapterV2.ts";
import { codexAppServerClientFactoryFromSettingsLayer } from "./Adapters/CodexAdapterV2.ts";
import { cursorAgentSdkRunnerLiveLayer } from "./Adapters/CursorAgentSdk.ts";
import { BUILT_IN_PROVIDER_ADAPTER_DRIVERS_V2 } from "./builtInProviderAdapterDrivers.ts";
import { layer as checkpointCaptureServiceLayer } from "./CheckpointCaptureService.ts";
import { layer as checkpointServiceLayer } from "./CheckpointService.ts";
import { layer as checkpointRollbackServiceLayer } from "./CheckpointRollbackService.ts";
import { layer as commandPolicyLayer } from "./CommandPolicy.ts";
import { layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts";
import { layer as contextHandoffServiceLayer } from "./ContextHandoffService.ts";
import { layer as eventSinkLayer } from "./EventSink.ts";
import { layer as effectOutboxLayer } from "./EffectOutbox.ts";
import {
daemonLayer as effectWorkerDaemonLayer,
executorLayer as effectExecutorLayer,
layer as effectWorkerLayer,
} from "./EffectWorker.ts";
import { layerFromStores as eventSinkLayer } from "./EventSink.ts";
import { layer as eventStoreLayer } from "./EventStore.ts";
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
import { layer as orchestratorLayer } from "./Orchestrator.ts";
import { layer as projectionStoreLayer } from "./ProjectionStore.ts";
import { ProviderAdapterV2 } from "./ProviderAdapter.ts";
import { makeLayerEffect as providerAdapterRegistryLayerFromEffect } from "./ProviderAdapterRegistry.ts";
import { layer as projectionMaintenanceLayer } from "./ProjectionMaintenance.ts";
import { layerFromProviderInstanceRegistry as providerAdapterRegistryLayerFromProviderInstances } from "./ProviderAdapterRegistry.ts";
import { layer as providerEventIngestorLayer } from "./ProviderEventIngestor.ts";
import { layer as providerSessionManagerLayer } from "./ProviderSessionManager.ts";
import { layer as providerSwitchServiceLayer } from "./ProviderSwitchService.ts";
import { layer as providerTurnControlServiceLayer } from "./ProviderTurnControlService.ts";
import { layer as providerTurnStartServiceLayer } from "./ProviderTurnStartService.ts";
import { layer as runExecutionServiceLayer } from "./RunExecutionService.ts";
import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts";
import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts";
import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts";
import { layer as threadForkServiceLayer } from "./ThreadForkService.ts";
import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts";
const storesLayer = Layer.merge(eventStoreLayer, projectionStoreLayer);
const storesLayer = Layer.mergeAll(
eventStoreLayer,
projectionStoreLayer,
commandReceiptStoreLayer,
effectOutboxLayer,
turnItemPositionStoreLayer,
);
const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesLayer));
const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(Layer.provide(storesLayer));
const commandReceiptStoreProvided = commandReceiptStoreLayer;
@@ -38,18 +52,7 @@ const contextHandoffServiceProvided = contextHandoffServiceLayer.pipe(
Layer.provide(idAllocatorLayer),
);
const codexAdapterProvided = codexAdapterLayer.pipe(
Layer.provide(codexAppServerClientFactoryFromSettingsLayer),
Layer.provide(idAllocatorLayer),
);
const claudeAdapterProvided = claudeAdapterLayer.pipe(
Layer.provide(claudeAgentSdkQueryRunnerLiveLayer),
Layer.provide(cursorAgentSdkRunnerLiveLayer),
Layer.provide(OpenCodeRuntimeLive),
Layer.provide(FetchHttpClient.layer),
Layer.provide(idAllocatorLayer),
);
const providerAdapterRegistryProvided = providerAdapterRegistryLayerFromProviderInstances;
const providerAdapterRegistryProvided = providerAdapterRegistryLayerFromEffect(
Effect.all([
@@ -80,6 +83,67 @@ const runExecutionServiceProvided = runExecutionServiceLayer.pipe(
),
);
const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(
eventSinkProvided,
idAllocatorLayer,
projectionStoreLayer,
providerSessionManagerProvided,
runExecutionServiceProvided,
runtimePolicyLayer,
),
),
);
const providerTurnControlServiceProvided = providerTurnControlServiceLayer.pipe(
Layer.provide(Layer.merge(projectionStoreLayer, providerSessionManagerProvided)),
);
const runtimeRequestServiceProvided = runtimeRequestServiceLayer.pipe(
Layer.provide(Layer.merge(projectionStoreLayer, providerSessionManagerProvided)),
);
const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(
checkpointServiceProvided,
eventSinkProvided,
idAllocatorLayer,
projectionStoreLayer,
providerSessionManagerProvided,
runtimePolicyLayer,
),
),
);
const checkpointCaptureServiceProvided = checkpointCaptureServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(
checkpointServiceProvided,
eventSinkProvided,
idAllocatorLayer,
projectionStoreLayer,
),
),
);
const effectExecutorProvided = effectExecutorLayer.pipe(
Layer.provide(
Layer.mergeAll(
checkpointCaptureServiceProvided,
checkpointRollbackServiceProvided,
providerSessionManagerProvided,
providerTurnControlServiceProvided,
providerTurnStartServiceProvided,
runtimeRequestServiceProvided,
),
),
);
const effectWorkerProvided = effectWorkerLayer.pipe(
Layer.provide(Layer.merge(storesLayer, effectExecutorProvided)),
);
const effectWorkerDaemonProvided = effectWorkerDaemonLayer.pipe(
Layer.provide(effectWorkerProvided),
);
const orchestratorProvided = orchestratorLayer.pipe(
Layer.provide(
Layer.mergeAll(
@@ -87,18 +151,24 @@ const orchestratorProvided = orchestratorLayer.pipe(
commandPolicyLayer,
storesLayer,
eventSinkProvided,
effectWorkerProvided,
commandReceiptStoreProvided,
contextHandoffServiceProvided,
idAllocatorLayer,
providerAdapterRegistryProvided,
providerEventIngestorProvided,
runtimePolicyLayer,
providerSessionManagerProvided,
providerSwitchServiceLayer,
runExecutionServiceProvided,
threadForkServiceLayer,
),
),
);
export const OrchestrationV2LayerLive = Layer.merge(
export const OrchestrationV2LayerLive = Layer.mergeAll(
orchestratorProvided,
threadManagementServiceLayer.pipe(Layer.provide(orchestratorProvided)),
effectWorkerDaemonProvided,
projectionMaintenanceProvided,
);
@@ -37,7 +37,7 @@ const readTranscript = Effect.fn("readClaudeReplayFixture")(function* (file: URL
function claudeFixture(name: string) {
const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find((entry) => entry.name === name);
const provider = fixture?.providers.find((entry) => entry.provider === "claudeAgent");
const provider = fixture?.providers.find((entry) => entry.driver === "claudeAgent");
if (fixture === undefined || provider === undefined) {
throw new Error(`Missing ${name}/claudeAgent replay fixture.`);
}
@@ -144,7 +144,7 @@ describe("Claude Agent SDK replay fixtures", () => {
for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
for (const provider of fixture.providers) {
if (provider.provider !== "claudeAgent") {
if (provider.driver !== "claudeAgent") {
continue;
}
@@ -31,7 +31,7 @@ type ProtocolReplayEntry = Extract<
const CODEX_REPLAY_FIXTURES = ORCHESTRATOR_REPLAY_FIXTURES.flatMap((fixture) =>
fixture.providers
.filter((provider) => provider.provider === "codex")
.filter((provider) => provider.driver === "codex")
.map((provider) => ({
scenario: fixture.name,
transcriptFile: provider.transcriptFile,
@@ -1,6 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { OrchestrationV2Command } from "@t3tools/contracts";
import { OrchestrationV2Command, ProviderInstanceId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";
@@ -35,7 +35,7 @@ describe("orchestrator replay fixture contract", () => {
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.providers.map((provider) => provider.driver),
`${fixture.name} provider variants`,
);
@@ -44,25 +44,29 @@ describe("orchestrator replay fixture contract", () => {
const materialized = yield* materializeFixtureInput({
scenario: fixture.name,
fixtureInput: fixture.buildInput(),
driver: provider.driver,
modelSelection: provider.modelSelection,
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
const firstCommand = materialized.commands[0];
assert.equal(transcript.scenario, fixture.name);
if (provider.provider === "acpRegistry") {
if (provider.driver === "acpRegistry") {
assert.include(
["acpRegistry", "grok"],
transcript.provider,
"ACP Registry may retarget protocol-standard Grok ACP evidence",
);
} else {
assert.equal(transcript.provider, provider.provider);
assert.equal(transcript.provider, provider.driver);
}
assert.equal(provider.modelSelection.instanceId, provider.provider);
assert.equal(
provider.modelSelection.instanceId,
ProviderInstanceId.make(provider.driver),
);
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`);
throw new Error(`${fixture.name}/${provider.driver} must start with thread.create`);
}
assert.equal(firstCommand.threadId, materialized.projectionThreadIds[0]);
assert.equal(materialized.commands.length, fixture.buildInput().steps.length + 1);
@@ -71,7 +75,7 @@ describe("orchestrator replay fixture contract", () => {
assertUnique(
materialized.commands.map((command) => command.commandId),
`${fixture.name}/${provider.provider} command IDs`,
`${fixture.name}/${provider.driver} command IDs`,
);
for (const command of materialized.commands) {
@@ -86,7 +90,7 @@ describe("orchestrator replay fixture contract", () => {
(step.type === "respond_to_next_runtime_request" &&
step.commandId === command.commandId),
),
`${fixture.name}/${provider.provider} command ${command.commandId} must appear in the timeline`,
`${fixture.name}/${provider.driver} command ${command.commandId} must appear in the timeline`,
);
}
}
@@ -97,7 +101,7 @@ describe("orchestrator replay fixture contract", () => {
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")) {
for (const provider of fixture.providers.filter((entry) => entry.driver === "codex")) {
const transcript = yield* readTranscript(provider.transcriptFile);
const first = transcript.entries[0];
const last = transcript.entries.at(-1);
@@ -55,26 +55,27 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
>(input: {
readonly fixtureName: string;
readonly buildInput: () => OrchestratorFixtureInput;
readonly provider: ProviderOrchestratorReplayVariant;
readonly driver: ProviderOrchestratorReplayVariant;
readonly harness: OrchestratorV2ProviderReplayHarness<Transcript, Error>;
readonly enableAssistantStreaming?: boolean;
}) {
const rawTranscript = yield* readTranscript(input.provider.transcriptFile);
const rawTranscript = yield* readTranscript(input.driver.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,
driver: input.driver.driver,
modelSelection: input.driver.modelSelection,
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
const scenario = {
name: `${input.fixtureName}/${input.provider.provider}`,
name: `${input.fixtureName}/${input.driver.driver}`,
transcript,
commands: materialized.commands,
steps: materialized.steps,
projectionThreadIds: materialized.projectionThreadIds,
runtimePolicyOverride: {
...input.provider.runtimePolicyOverride,
...input.driver.runtimePolicyOverride,
cwd: workspace,
},
};
@@ -82,8 +83,7 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
const result = yield* runOrchestratorV2ProviderReplayScenario(scenario, input.harness, {
enableAssistantStreaming: input.enableAssistantStreaming ?? false,
}).pipe(provideDeterministicTestRuntime);
input.provider.assertOutput(result, transcript);
input.driver.assertOutput(result, transcript);
if (input.enableAssistantStreaming !== true) {
assert.isFalse(
result.domainEvents.some(isStreamingAssistantEvent),
@@ -95,17 +95,17 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
const projection = result.projections.get(projectionThreadId);
assert.isDefined(projection);
const latestRun = projection.runs.at(-1);
assert.deepEqual(latestRun?.modelSelection, input.provider.modelSelection);
assert.deepEqual(latestRun?.modelSelection, input.driver.modelSelection);
return result;
});
function runFixtureProviderWithRegisteredHarness(input: {
readonly fixtureName: string;
readonly buildInput: () => OrchestratorFixtureInput;
readonly provider: ProviderOrchestratorReplayVariant;
readonly driver: ProviderOrchestratorReplayVariant;
readonly enableAssistantStreaming?: boolean;
}) {
switch (input.provider.provider) {
switch (input.driver.driver) {
case "codex":
return runFixtureProvider({
...input,
@@ -138,7 +138,7 @@ function runFixtureProviderWithRegisteredHarness(input: {
}).pipe(Effect.mapError(normalizeTestError), Effect.scoped);
default:
return Effect.die(
new Error(`No replay harness registered for provider ${input.provider.provider}.`),
new Error(`No replay harness registered for provider ${input.driver.driver}.`),
);
}
}
@@ -147,12 +147,12 @@ describe("orchestrator replay fixtures", () => {
for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
for (const provider of fixture.providers) {
it.effect(
`runs ${fixture.name}/${provider.provider} through OrchestratorV2 using deterministic replay`,
`runs ${fixture.name}/${provider.driver} through OrchestratorV2 using deterministic replay`,
() =>
runFixtureProviderWithRegisteredHarness({
fixtureName: fixture.name,
buildInput: fixture.buildInput,
provider,
driver: provider,
}),
);
}
@@ -162,21 +162,21 @@ describe("orchestrator replay fixtures", () => {
(fixture) => fixture.name === "message_steering",
);
const cursorSteeringProvider = steeringFixture?.providers.find(
(provider) => provider.provider === "cursor",
(provider) => provider.driver === "cursor",
);
if (cursorSteeringProvider !== undefined) {
it.effect("executes explicit Cursor restart_active through the recorded SDK boundary", () =>
runFixtureProviderWithRegisteredHarness({
fixtureName: "message_steering",
buildInput: messageRestartInput,
provider: cursorSteeringProvider,
driver: cursorSteeringProvider,
}),
);
}
const simpleFixture = ORCHESTRATOR_REPLAY_FIXTURES.find((fixture) => fixture.name === "simple");
const simpleCursorProvider = simpleFixture?.providers.find(
(provider) => provider.provider === "cursor",
(provider) => provider.driver === "cursor",
);
if (simpleFixture !== undefined && simpleCursorProvider !== undefined) {
it.effect("streams Cursor assistant artifacts only when streaming is enabled", () =>
@@ -184,7 +184,7 @@ describe("orchestrator replay fixtures", () => {
const result = yield* runFixtureProviderWithRegisteredHarness({
fixtureName: "simple-cursor-streaming",
buildInput: simpleFixture.buildInput,
provider: simpleCursorProvider,
driver: simpleCursorProvider,
enableAssistantStreaming: true,
});
@@ -6,6 +6,7 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as CodexReplay from "effect-codex-app-server/replay";
import { ProviderDriverKind } from "@t3tools/contracts";
import {
CodexOrchestratorReplayHarness,
@@ -103,6 +104,7 @@ const runCursorRecovery = Effect.fn("runCursorRecovery")(function* (input: {
{ type: "message", text: PROVIDER_THREAD_RESUME_SECOND_PROMPT },
],
},
driver: ProviderDriverKind.make("cursor"),
modelSelection: CURSOR_MODEL_SELECTION,
});
const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
@@ -196,6 +198,7 @@ describe("orchestrator replay recovery", () => {
{ type: "message", text: PROVIDER_THREAD_RESUME_SECOND_PROMPT },
],
},
driver: ProviderDriverKind.make("codex"),
modelSelection: CODEX_MODEL_SELECTION,
});
const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
@@ -92,6 +92,14 @@ export class OrchestratorV2ScenarioStepError extends Schema.TaggedErrorClass<Orc
function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<ThreadId> {
switch (command.type) {
case "thread.create":
case "thread.archive":
case "thread.unarchive":
case "thread.delete":
case "thread.metadata.update":
case "thread.runtime-mode.set":
case "thread.interaction-mode.set":
case "thread.model-selection.set":
case "provider-session.release":
case "message.dispatch":
case "run.interrupt":
case "queued-message.promote-to-steer":
@@ -213,9 +221,10 @@ export function runOrchestratorV2Scenario(
return request;
}
if (attemptsRemaining <= 0) {
const runState = projection.runs.map((run) => `${run.id}:${run.status}`).join(",");
return yield* new OrchestratorV2ScenarioStepError({
scenario: scenario.name,
step: `respond_to_next_runtime_request:${threadId}`,
step: `respond_to_next_runtime_request:${threadId}:runs=${runState}:providerTurns=${projection.providerTurns.length}`,
});
}
yield* yieldToRuntime;
@@ -232,9 +241,17 @@ export function runOrchestratorV2Scenario(
return;
}
if (attemptsRemaining <= 0) {
const activeRuns = projection.runs
.filter((run) => ["queued", "starting", "running", "waiting"].includes(run.status))
.map((run) => `${run.id}:${run.status}`)
.join(",");
const pendingRequests = projection.runtimeRequests
.filter((request) => request.status === "pending")
.map((request) => `${request.id}:${request.kind}`)
.join(",");
return yield* new OrchestratorV2ScenarioStepError({
scenario: scenario.name,
step: `await_thread_idle:${threadId}`,
step: `await_thread_idle:${threadId}:runs=${activeRuns}:requests=${pendingRequests}`,
});
}
yield* yieldToRuntime;
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import type { ProviderKind, ProviderReplayTranscript } from "@t3tools/contracts";
import type { ProviderDriverKind, ProviderReplayTranscript } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -16,11 +16,19 @@ import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { layer as checkpointCaptureServiceLayer } from "../CheckpointCaptureService.ts";
import { layer as checkpointServiceLayer } from "../CheckpointService.ts";
import { layer as checkpointRollbackServiceLayer } from "../CheckpointRollbackService.ts";
import { layer as commandPolicyLayer } from "../CommandPolicy.ts";
import { layer as commandReceiptStoreLayer } from "../CommandReceiptStore.ts";
import { layer as contextHandoffServiceLayer } from "../ContextHandoffService.ts";
import { layer as eventSinkLayer } from "../EventSink.ts";
import { layer as effectOutboxLayer } from "../EffectOutbox.ts";
import {
daemonLayer as effectWorkerDaemonLayer,
executorLayer as effectExecutorLayer,
layer as effectWorkerLayer,
} from "../EffectWorker.ts";
import { layerFromStores as eventSinkLayer } from "../EventSink.ts";
import { layer as eventStoreLayer } from "../EventStore.ts";
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
import { layer as orchestratorLayer } from "../Orchestrator.ts";
@@ -29,12 +37,18 @@ import type { OrchestratorV2, OrchestratorV2Error } from "../Orchestrator.ts";
import { ProviderAdapterRegistryV2 } from "../ProviderAdapterRegistry.ts";
import { layer as providerEventIngestorLayer } from "../ProviderEventIngestor.ts";
import { layer as providerSessionManagerLayer } from "../ProviderSessionManager.ts";
import { layer as providerSwitchServiceLayer } from "../ProviderSwitchService.ts";
import { layer as providerTurnControlServiceLayer } from "../ProviderTurnControlService.ts";
import { layer as providerTurnStartServiceLayer } from "../ProviderTurnStartService.ts";
import { layer as runExecutionServiceLayer } from "../RunExecutionService.ts";
import {
layer as runtimePolicyLayer,
layerWithOverride as runtimePolicyLayerWithOverride,
type RuntimePolicyV2Override,
} from "../RuntimePolicy.ts";
import { layer as turnItemPositionStoreLayer } from "../TurnItemPositionStore.ts";
import { layer as runtimeRequestServiceLayer } from "../RuntimeRequestService.ts";
import { layer as threadForkServiceLayer } from "../ThreadForkService.ts";
import {
runOrchestratorV2Scenario,
type OrchestratorV2ScenarioStepError,
@@ -133,7 +147,7 @@ export interface OrchestratorV2ProviderReplayHarness<
Transcript extends ProviderReplayTranscript = ProviderReplayTranscript,
Error = never,
> {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly decodeTranscript: (
transcript: ProviderReplayTranscript,
) => Effect.Effect<Transcript, Error>;
@@ -213,9 +227,13 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
const serverSettingsLayer = ServerSettingsService.layerTest({
enableAssistantStreaming: options.enableAssistantStreaming ?? false,
}).pipe(Layer.orDie);
const storesLayer = Layer.merge(eventStoreLayer, projectionStoreLayer).pipe(
Layer.provide(databaseLayer),
);
const storesLayer = Layer.mergeAll(
eventStoreLayer,
projectionStoreLayer,
commandReceiptStoreLayer,
effectOutboxLayer,
turnItemPositionStoreLayer,
).pipe(Layer.provide(databaseLayer));
const eventSinkProvided = eventSinkLayer.pipe(
Layer.provide(Layer.mergeAll(storesLayer, databaseLayer)),
);
@@ -258,17 +276,75 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
),
),
);
return orchestratorLayer.pipe(
const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(
eventSinkProvided,
idAllocatorLayer,
storesLayer,
providerSessionManagerProvided,
runExecutionServiceProvided,
runtimeLayer,
),
),
);
const providerTurnControlServiceProvided = providerTurnControlServiceLayer.pipe(
Layer.provide(Layer.merge(storesLayer, providerSessionManagerProvided)),
);
const runtimeRequestServiceProvided = runtimeRequestServiceLayer.pipe(
Layer.provide(Layer.merge(storesLayer, providerSessionManagerProvided)),
);
const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(
checkpointServiceProvided,
eventSinkProvided,
idAllocatorLayer,
storesLayer,
providerSessionManagerProvided,
runtimeLayer,
),
),
);
const checkpointCaptureServiceProvided = checkpointCaptureServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(checkpointServiceProvided, eventSinkProvided, idAllocatorLayer, storesLayer),
),
);
const effectExecutorProvided = effectExecutorLayer.pipe(
Layer.provide(
Layer.mergeAll(
checkpointCaptureServiceProvided,
checkpointRollbackServiceProvided,
providerSessionManagerProvided,
providerTurnControlServiceProvided,
providerTurnStartServiceProvided,
runtimeRequestServiceProvided,
),
),
);
const effectWorkerProvided = effectWorkerLayer.pipe(
Layer.provide(Layer.merge(storesLayer, effectExecutorProvided)),
);
const effectWorkerDaemonProvided = effectWorkerDaemonLayer.pipe(
Layer.provide(effectWorkerProvided),
);
const orchestratorProvided = orchestratorLayer.pipe(
Layer.provide(
Layer.mergeAll(
checkpointServiceProvided,
commandPolicyLayer,
contextHandoffServiceProvided,
effectWorkerProvided,
persistenceLayer,
registryLayer,
runtimeLayer,
providerSessionManagerProvided,
providerSwitchServiceLayer,
runExecutionServiceProvided,
threadForkServiceLayer,
),
),
);
return Layer.merge(orchestratorProvided, effectWorkerDaemonProvided);
}
@@ -13,7 +13,7 @@ import {
ProviderTurnId,
ThreadId,
TurnItemId,
type ProviderKind,
ProviderDriverKind,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -44,21 +44,24 @@ const projectId = ProjectId.make("project:provider-switch");
const firstPrompt = "Respond with exactly: codex before switch";
const claudePrompt = "Respond with exactly: claude switched response";
const returnPrompt = "Respond with exactly: codex after return";
const CODEX_DRIVER = ProviderDriverKind.make("codex");
const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent");
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
interface CapturedTurn {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly threadId: ThreadId;
readonly providerThreadId: ProviderThreadId;
readonly text: string;
}
function unimplemented(provider: ProviderKind, detail: string) {
return Effect.fail(new ProviderAdapterProtocolError({ provider, detail }));
function unimplemented(driver: ProviderDriverKind, detail: string) {
return Effect.fail(new ProviderAdapterProtocolError({ driver, detail }));
}
function makeTestAdapter(input: {
readonly instanceId: ProviderInstanceId;
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly capabilities: OrchestrationV2ProviderCapabilities;
readonly modelSelection: ModelSelection;
readonly responseByRunOrdinal: Readonly<Record<number, string>>;
@@ -67,7 +70,7 @@ function makeTestAdapter(input: {
}): ProviderAdapterV2Shape {
return {
instanceId: input.instanceId,
provider: input.provider,
driver: input.driver,
getCapabilities: () => Effect.succeed(input.capabilities),
openSession: (sessionInput) =>
Effect.gen(function* () {
@@ -75,7 +78,8 @@ function makeTestAdapter(input: {
const now = yield* DateTime.now;
const providerSession: OrchestrationV2ProviderSession = {
id: sessionInput.providerSessionId,
provider: input.provider,
driver: input.driver,
providerInstanceId: input.instanceId,
status: "ready",
cwd: sessionInput.runtimePolicy.cwd ?? process.cwd(),
model: input.modelSelection.model,
@@ -87,7 +91,7 @@ function makeTestAdapter(input: {
return {
instanceId: input.instanceId,
provider: input.provider,
driver: input.driver,
providerSessionId: sessionInput.providerSessionId,
providerSession,
rawEvents: Stream.empty,
@@ -95,15 +99,16 @@ function makeTestAdapter(input: {
ensureThread: (threadInput) =>
Effect.gen(function* () {
const createdAt = yield* DateTime.now;
const nativeThreadId = `${input.provider}:${threadInput.threadId}`;
const nativeThreadId = `${input.driver}:${threadInput.threadId}`;
return {
id: ProviderThreadId.make(`provider-thread:${nativeThreadId}`),
provider: input.provider,
driver: input.driver,
providerInstanceId: input.instanceId,
providerSessionId: sessionInput.providerSessionId,
appThreadId: threadInput.threadId,
ownerNodeId: null,
nativeThreadRef: {
provider: input.provider,
driver: input.driver,
nativeId: nativeThreadId,
strength: "strong",
},
@@ -124,7 +129,7 @@ function makeTestAdapter(input: {
yield* Ref.update(input.capturedTurns, (turns) => [
...turns,
{
provider: input.provider,
driver: input.driver,
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
text: turnInput.message.text,
@@ -132,23 +137,23 @@ function makeTestAdapter(input: {
]);
const eventTime = yield* DateTime.now;
const providerTurnId = ProviderTurnId.make(
`provider-turn:${input.provider}:${turnInput.threadId}:${turnInput.runOrdinal}`,
`provider-turn:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}`,
);
const response =
input.responseByThreadId?.[turnInput.threadId]?.[turnInput.runOrdinal] ??
input.responseByRunOrdinal[turnInput.runOrdinal] ??
`${input.provider} response for run ${turnInput.runOrdinal}`;
`${input.driver} response for run ${turnInput.runOrdinal}`;
const providerEvents: ReadonlyArray<ProviderAdapterV2Event> = [
{
type: "provider_turn.updated",
provider: input.provider,
driver: input.driver,
providerTurn: {
id: providerTurnId,
providerThreadId: turnInput.providerThread.id,
nodeId: turnInput.rootNodeId,
runAttemptId: turnInput.attemptId,
nativeTurnRef: {
provider: input.provider,
driver: input.driver,
nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`,
strength: "strong",
},
@@ -160,10 +165,10 @@ function makeTestAdapter(input: {
},
{
type: "turn_item.updated",
provider: input.provider,
driver: input.driver,
turnItem: {
id: TurnItemId.make(
`turn-item:${input.provider}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
`turn-item:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
),
threadId: turnInput.threadId,
runId: turnInput.runId,
@@ -180,7 +185,7 @@ function makeTestAdapter(input: {
updatedAt: eventTime,
type: "assistant_message",
messageId: MessageId.make(
`message:${input.provider}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
`message:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`,
),
text: response,
streaming: false,
@@ -188,7 +193,7 @@ function makeTestAdapter(input: {
},
{
type: "turn.terminal",
provider: input.provider,
driver: input.driver,
providerTurnId,
status: "completed",
},
@@ -201,11 +206,11 @@ function makeTestAdapter(input: {
interruptTurn: () => Effect.void,
respondToRuntimeRequest: () => Effect.void,
readThreadSnapshot: () =>
unimplemented(input.provider, "readThreadSnapshot unused in provider switch test"),
unimplemented(input.driver, "readThreadSnapshot unused in provider switch test"),
rollbackThread: () =>
unimplemented(input.provider, "rollbackThread unused in provider switch test"),
unimplemented(input.driver, "rollbackThread unused in provider switch test"),
forkThread: () =>
unimplemented(input.provider, "forkThread unused in provider switch test"),
unimplemented(input.driver, "forkThread unused in provider switch test"),
};
}),
};
@@ -238,7 +243,7 @@ describe("orchestration v2 provider switching", () => {
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
driver: CODEX_DRIVER,
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: {
@@ -249,7 +254,7 @@ describe("orchestration v2 provider switching", () => {
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
driver: CLAUDE_DRIVER,
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 2: "claude switched response" },
@@ -340,7 +345,7 @@ describe("orchestration v2 provider switching", () => {
const turns = yield* Ref.get(capturedTurns);
assert.deepEqual(
projection.runs.map((run) => [run.provider, run.status]),
projection.runs.map((run) => [run.providerInstanceId, run.status]),
[
["codex", "completed"],
["claudeAgent", "completed"],
@@ -373,7 +378,7 @@ describe("orchestration v2 provider switching", () => {
);
assert.deepEqual(
projection.providerThreads.map((providerThread) => [
providerThread.provider,
providerThread.driver,
providerThread.status,
providerThread.handoffIds.length,
]),
@@ -407,7 +412,7 @@ describe("orchestration v2 provider switching", () => {
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
driver: CODEX_DRIVER,
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: { 1: "The release color is violet." },
@@ -415,7 +420,7 @@ describe("orchestration v2 provider switching", () => {
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
driver: CLAUDE_DRIVER,
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 1: "I will remember violet." },
@@ -504,11 +509,11 @@ describe("orchestration v2 provider switching", () => {
const targetTurn = turns.find((turn) => turn.threadId === targetThreadId);
assert.deepEqual(
targetProjection.runs.map((run) => [run.provider, run.status]),
targetProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[["codex", "completed"]],
);
assert.lengthOf(targetProjection.providerThreads, 1);
assert.equal(targetProjection.providerThreads[0]?.provider, "codex");
assert.equal(targetProjection.providerThreads[0]?.driver, "codex");
assert.isNull(targetProjection.providerThreads[0]?.forkedFrom);
assert.deepEqual(
targetProjection.contextTransfers.map((transfer) => [
@@ -547,7 +552,7 @@ describe("orchestration v2 provider switching", () => {
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("cursor"),
provider: "cursor",
driver: CURSOR_DRIVER,
capabilities: CursorProviderCapabilitiesV2,
modelSelection: CURSOR_MODEL_SELECTION,
responseByRunOrdinal: {},
@@ -640,11 +645,11 @@ describe("orchestration v2 provider switching", () => {
const targetTurn = turns.find((turn) => turn.threadId === targetThreadId);
assert.deepEqual(
targetProjection.runs.map((run) => [run.provider, run.status]),
targetProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[["cursor", "completed"]],
);
assert.lengthOf(targetProjection.providerThreads, 1);
assert.equal(targetProjection.providerThreads[0]?.provider, "cursor");
assert.equal(targetProjection.providerThreads[0]?.driver, "cursor");
assert.isNull(targetProjection.providerThreads[0]?.forkedFrom);
assert.deepEqual(
targetProjection.contextTransfers.map((transfer) => [
@@ -680,7 +685,7 @@ describe("orchestration v2 provider switching", () => {
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: ProviderInstanceId.make("codex"),
provider: "codex",
driver: CODEX_DRIVER,
capabilities: CodexProviderCapabilitiesV2,
modelSelection: CODEX_MODEL_SELECTION,
responseByRunOrdinal: {},
@@ -697,7 +702,7 @@ describe("orchestration v2 provider switching", () => {
}),
makeTestAdapter({
instanceId: ProviderInstanceId.make("claudeAgent"),
provider: "claudeAgent",
driver: CLAUDE_DRIVER,
capabilities: ClaudeProviderCapabilitiesV2,
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: { 2: "I will remember violet." },
@@ -822,7 +827,7 @@ describe("orchestration v2 provider switching", () => {
);
const turns = yield* Ref.get(capturedTurns);
const mergedTurn = turns.findLast(
(turn) => turn.threadId === sourceThreadId && turn.provider === "codex",
(turn) => turn.threadId === sourceThreadId && turn.driver === "codex",
);
const mergeTransfer = projection.contextTransfers.find(
(transfer) => transfer.type === "merge_back",
@@ -840,9 +845,120 @@ describe("orchestration v2 provider switching", () => {
assert.include(mergedTurn.text, mergePrompt);
assert.isDefined(mergeTransfer);
assert.equal(mergeTransfer.status, "consumed");
assert.equal(mergeTransfer.targetProvider, "codex");
assert.equal(mergeTransfer.targetProviderInstanceId, "codex");
assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context");
}),
),
);
it.live("routes two custom instances of the same driver independently", () =>
Effect.scoped(
Effect.gen(function* () {
const personalThreadId = ThreadId.make("thread:custom-codex-personal");
const workThreadId = ThreadId.make("thread:custom-codex-work");
const personalSelection = {
instanceId: ProviderInstanceId.make("codex_personal"),
model: "gpt-5.4",
} satisfies ModelSelection;
const workSelection = {
instanceId: ProviderInstanceId.make("codex_work"),
model: "gpt-5.4",
} satisfies ModelSelection;
const cwd = yield* checkpointWorkspace("custom-codex-instances");
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
const registryLayer = makeProviderAdapterRegistryLayer([
makeTestAdapter({
instanceId: personalSelection.instanceId,
driver: CODEX_DRIVER,
capabilities: CodexProviderCapabilitiesV2,
modelSelection: personalSelection,
responseByRunOrdinal: { 1: "personal response" },
capturedTurns,
}),
makeTestAdapter({
instanceId: workSelection.instanceId,
driver: CODEX_DRIVER,
capabilities: CodexProviderCapabilitiesV2,
modelSelection: workSelection,
responseByRunOrdinal: { 1: "work response" },
capturedTurns,
}),
]);
const [personal, work] = yield* Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
for (const [targetThreadId, selection, suffix] of [
[personalThreadId, personalSelection, "personal"],
[workThreadId, workSelection, "work"],
] as const) {
yield* orchestrator.dispatch({
type: "thread.create",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make(`command:custom-codex:${suffix}:create`),
threadId: targetThreadId,
projectId,
title: `Custom Codex ${suffix}`,
modelSelection: selection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
});
yield* orchestrator.dispatch({
type: "message.dispatch",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make(`command:custom-codex:${suffix}:message`),
threadId: targetThreadId,
messageId: MessageId.make(`message:custom-codex:${suffix}`),
text: `${suffix} prompt`,
attachments: [],
modelSelection: selection,
dispatchMode: { type: "start_immediately" },
});
yield* waitForIdle(targetThreadId);
}
return yield* Effect.all([
orchestrator.getThreadProjection(personalThreadId),
orchestrator.getThreadProjection(workThreadId),
]);
}).pipe(
Effect.provide(
makeOrchestratorV2ReplayLayerWithRegistry(
{
name: "custom-codex-instances",
runtimePolicyOverride: {
cwd,
approvalPolicy: "never",
sandboxPolicy: {
type: "readOnly",
access: { type: "fullAccess" },
networkAccess: false,
},
},
},
registryLayer,
),
),
);
assert.equal(personal.runs[0]?.providerInstanceId, personalSelection.instanceId);
assert.equal(
personal.providerSessions[0]?.providerInstanceId,
personalSelection.instanceId,
);
assert.equal(work.runs[0]?.providerInstanceId, workSelection.instanceId);
assert.equal(work.providerSessions[0]?.providerInstanceId, workSelection.instanceId);
assert.notEqual(personal.providerSessions[0]?.id, work.providerSessions[0]?.id);
assert.deepEqual(
(yield* Ref.get(capturedTurns)).map((turn) => [turn.threadId, turn.text]),
[
[personalThreadId, "personal prompt"],
[workThreadId, "work prompt"],
],
);
}),
),
);
});
@@ -548,19 +548,15 @@ describe("orchestration V2 thread fork", () => {
event.threadId === materialized.targetThreadId &&
event.type === "provider-session.updated",
);
const targetRunCreatedIndex = result.domainEvents.findIndex(
(event) => event.threadId === materialized.targetThreadId && event.type === "run.created",
);
assert.isAtLeast(transferCreatedIndex, 0);
assert.isAbove(targetProviderSessionIndex, transferCreatedIndex);
assert.isEmpty(
result.domainEvents
.slice(0, targetProviderSessionIndex)
.filter((event) => event.threadId === materialized.targetThreadId)
.filter(
(event) =>
event.type === "provider-session.updated" ||
event.type === "provider-thread.updated" ||
event.type === "run.created",
),
"thread.fork must not eagerly create provider runtime state for the target thread",
assert.isAbove(
targetProviderSessionIndex,
targetRunCreatedIndex,
"provider runtime state must be materialized only after the target run commits",
);
const forkEvents = result.domainEvents.filter(
@@ -8,7 +8,7 @@ import {
type OrchestrationV2ThreadProjection,
ProjectId,
ProviderInstanceId,
type ProviderKind,
ProviderDriverKind,
type ProviderReplayTranscript,
ThreadId,
} from "@t3tools/contracts";
@@ -53,30 +53,30 @@ const SECOND_SIBLING_MERGE_USER_TEXT =
"Retain the second transferred marker for later. Respond with exactly: second merge delta stored";
interface ProviderVariant {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly modelSelection: ModelSelection;
}
const PROVIDERS: ReadonlyArray<ProviderVariant> = [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
modelSelection: CODEX_MODEL_SELECTION,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
modelSelection: CLAUDE_MODEL_SELECTION,
},
];
function transcriptPath(scenario: string, provider: ProviderKind): string {
const fileName = provider === "codex" ? "codex_transcript.ndjson" : "claude_transcript.ndjson";
function transcriptPath(scenario: string, driver: ProviderDriverKind): string {
const fileName = driver === "codex" ? "codex_transcript.ndjson" : "claude_transcript.ndjson";
return `${import.meta.dirname}/fixtures/${scenario}/${fileName}`;
}
function readTranscript(scenario: string, provider: ProviderKind) {
function readTranscript(scenario: string, driver: ProviderDriverKind) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const text = yield* fs.readFileString(transcriptPath(scenario, provider));
const text = yield* fs.readFileString(transcriptPath(scenario, driver));
return yield* decodeProviderReplayNdjson(text);
});
}
@@ -200,24 +200,24 @@ function makeCreateCommand(input: {
describe("orchestration V2 merge-back provider replay", () => {
for (const variant of PROVIDERS) {
it.effect(`merges one fork delta back into the original ${variant.provider} thread`, () =>
it.effect(`merges one fork delta back into the original ${variant.driver} thread`, () =>
Effect.gen(function* () {
const rawTranscript = yield* readTranscript("thread_merge_back_continue", variant.provider);
const rawTranscript = yield* readTranscript("thread_merge_back_continue", variant.driver);
const materialized = yield* Effect.gen(function* () {
const ids = yield* IdAllocatorV2;
const projectId = yield* ids.allocate.project({
fixtureName: `thread-merge-back-${variant.provider}`,
fixtureName: `thread-merge-back-${variant.driver}`,
});
const sourceThreadId = yield* ids.allocate.thread({
fixtureName: `thread-merge-back-${variant.provider}-source`,
fixtureName: `thread-merge-back-${variant.driver}-source`,
projectId,
});
const forkThreadId = ThreadId.make(`thread-merge-back-${variant.provider}-fork`);
const forkThreadId = ThreadId.make(`thread-merge-back-${variant.driver}-fork`);
const forkRunId = ids.derive.run({ threadId: forkThreadId, ordinal: 1 });
const commands = [
makeCreateCommand({
commandId: yield* ids.allocate.command({
fixtureName: `thread-merge-back-${variant.provider}`,
fixtureName: `thread-merge-back-${variant.driver}`,
commandName: "create",
}),
threadId: sourceThreadId,
@@ -229,11 +229,11 @@ describe("orchestration V2 merge-back provider replay", () => {
createdBy: "user",
creationSource: "web",
commandId: yield* ids.allocate.command({
fixtureName: `thread-merge-back-${variant.provider}`,
fixtureName: `thread-merge-back-${variant.driver}`,
commandName: "source",
}),
threadId: sourceThreadId,
messageId: MessageId.make(`message-merge-source-${variant.provider}`),
messageId: MessageId.make(`message-merge-source-${variant.driver}`),
text: THREAD_MERGE_BACK_SOURCE_PROMPT,
attachments: [],
modelSelection: variant.modelSelection,
@@ -243,7 +243,7 @@ describe("orchestration V2 merge-back provider replay", () => {
type: "thread.fork",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make(`command-merge-fork-${variant.provider}`),
commandId: CommandId.make(`command-merge-fork-${variant.driver}`),
sourceThreadId,
targetThreadId: forkThreadId,
sourcePoint: { type: "latest_stable" },
@@ -254,11 +254,11 @@ describe("orchestration V2 merge-back provider replay", () => {
createdBy: "user",
creationSource: "web",
commandId: yield* ids.allocate.command({
fixtureName: `thread-merge-back-${variant.provider}`,
fixtureName: `thread-merge-back-${variant.driver}`,
commandName: "fork-delta",
}),
threadId: forkThreadId,
messageId: MessageId.make(`message-merge-fork-${variant.provider}`),
messageId: MessageId.make(`message-merge-fork-${variant.driver}`),
text: THREAD_MERGE_BACK_FORK_PROMPT,
attachments: [],
modelSelection: variant.modelSelection,
@@ -268,7 +268,7 @@ describe("orchestration V2 merge-back provider replay", () => {
type: "thread.merge_back",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make(`command-merge-back-${variant.provider}`),
commandId: CommandId.make(`command-merge-back-${variant.driver}`),
sourceThreadId: forkThreadId,
targetThreadId: sourceThreadId,
sourcePoint: { type: "run", runId: forkRunId },
@@ -278,11 +278,11 @@ describe("orchestration V2 merge-back provider replay", () => {
createdBy: "user",
creationSource: "web",
commandId: yield* ids.allocate.command({
fixtureName: `thread-merge-back-${variant.provider}`,
fixtureName: `thread-merge-back-${variant.driver}`,
commandName: "consume-merge",
}),
threadId: sourceThreadId,
messageId: MessageId.make(`message-consume-merge-${variant.provider}`),
messageId: MessageId.make(`message-consume-merge-${variant.driver}`),
text: MERGE_BACK_USER_TEXT,
attachments: [],
modelSelection: variant.modelSelection,
@@ -293,11 +293,11 @@ describe("orchestration V2 merge-back provider replay", () => {
createdBy: "user",
creationSource: "web",
commandId: yield* ids.allocate.command({
fixtureName: `thread-merge-back-${variant.provider}`,
fixtureName: `thread-merge-back-${variant.driver}`,
commandName: "recall",
}),
threadId: sourceThreadId,
messageId: MessageId.make(`message-merge-recall-${variant.provider}`),
messageId: MessageId.make(`message-merge-recall-${variant.driver}`),
text: THREAD_MERGE_BACK_RECALL_PROMPT,
attachments: [],
modelSelection: variant.modelSelection,
@@ -317,7 +317,7 @@ describe("orchestration V2 merge-back provider replay", () => {
[THREAD_MERGE_BACK_HANDOFF_PROMPT, generatedProviderMessage],
]);
const cwd = yield* Effect.acquireRelease(
Effect.promise(() => makeCheckpointWorkspace(`merge-back-${variant.provider}`)),
Effect.promise(() => makeCheckpointWorkspace(`merge-back-${variant.driver}`)),
(directory) =>
Effect.service(FileSystem.FileSystem).pipe(
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
@@ -325,7 +325,7 @@ describe("orchestration V2 merge-back provider replay", () => {
),
);
const scenario = {
name: `thread_merge_back_continue/${variant.provider}`,
name: `thread_merge_back_continue/${variant.driver}`,
commands: materialized.commands,
steps: [
{ type: "dispatch" as const, command: materialized.commands[0]!, await: true },
@@ -345,7 +345,7 @@ describe("orchestration V2 merge-back provider replay", () => {
runtimePolicyOverride: { cwd },
};
const result =
variant.provider === "codex"
variant.driver === "codex"
? yield* runOrchestratorV2ProviderReplayScenario(
{
...scenario,
@@ -392,12 +392,12 @@ describe("orchestration V2 merge-back provider replay", () => {
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect(`merges two sibling fork deltas into the original ${variant.provider} thread`, () =>
it.effect(`merges two sibling fork deltas into the original ${variant.driver} thread`, () =>
Effect.gen(function* () {
const rawTranscript = yield* readTranscript("thread_merge_back_siblings", variant.provider);
const rawTranscript = yield* readTranscript("thread_merge_back_siblings", variant.driver);
const materialized = yield* Effect.gen(function* () {
const ids = yield* IdAllocatorV2;
const fixtureName = `thread-merge-back-siblings-${variant.provider}`;
const fixtureName = `thread-merge-back-siblings-${variant.driver}`;
const projectId = yield* ids.allocate.project({ fixtureName });
const sourceThreadId = yield* ids.allocate.thread({
fixtureName: `${fixtureName}-source`,
@@ -559,7 +559,7 @@ describe("orchestration V2 merge-back provider replay", () => {
],
]);
const cwd = yield* Effect.acquireRelease(
Effect.promise(() => makeCheckpointWorkspace(`merge-back-siblings-${variant.provider}`)),
Effect.promise(() => makeCheckpointWorkspace(`merge-back-siblings-${variant.driver}`)),
(directory) =>
Effect.service(FileSystem.FileSystem).pipe(
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
@@ -587,7 +587,7 @@ describe("orchestration V2 merge-back provider replay", () => {
{ type: "await_thread_idle" as const, threadId: materialized.sourceThreadId },
];
const scenario = {
name: `thread_merge_back_siblings/${variant.provider}`,
name: `thread_merge_back_siblings/${variant.driver}`,
commands: materialized.commands,
steps,
projectionThreadIds: [
@@ -598,7 +598,7 @@ describe("orchestration V2 merge-back provider replay", () => {
runtimePolicyOverride: { cwd },
};
const result =
variant.provider === "codex"
variant.driver === "codex"
? yield* runOrchestratorV2ProviderReplayScenario(
{
...scenario,
@@ -1,3 +1,5 @@
import { ProviderDriverKind } from "@t3tools/contracts";
import { assertClaudeMessageSteeringOutput } from "./message_steering/claude_output.ts";
import { assertMessageSteeringOutput } from "./message_steering/codex_output.ts";
import { assertCursorMessageSteeringOutput } from "./message_steering/cursor_output.ts";
@@ -76,14 +78,14 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: planQuestionsInput,
providers: [
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL("./acp_elicitation/grok_transcript.ndjson", import.meta.url),
modelSelection: GROK_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
assertOutput: assertPlanQuestionsOutput,
},
{
provider: "acpRegistry",
driver: ProviderDriverKind.make("acpRegistry"),
transcriptFile: new URL("./acp_elicitation/grok_transcript.ndjson", import.meta.url),
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
@@ -96,37 +98,37 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: simpleInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./simple/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
assertOutput: assertSimpleOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./simple/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertSimpleClaudeOutput,
},
{
provider: "cursor",
driver: ProviderDriverKind.make("cursor"),
transcriptFile: new URL("./simple/cursor_transcript.ndjson", import.meta.url),
modelSelection: CURSOR_MODEL_SELECTION,
assertOutput: assertSimpleOutput,
},
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL("./simple/grok_transcript.ndjson", import.meta.url),
modelSelection: GROK_MODEL_SELECTION,
assertOutput: assertSimpleOutput,
},
{
provider: "acpRegistry",
driver: ProviderDriverKind.make("acpRegistry"),
transcriptFile: new URL("./simple/grok_transcript.ndjson", import.meta.url),
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
assertOutput: assertSimpleOutput,
},
{
provider: "opencode",
driver: ProviderDriverKind.make("opencode"),
transcriptFile: new URL("./simple/opencode_transcript.ndjson", import.meta.url),
modelSelection: OPENCODE_MODEL_SELECTION,
assertOutput: assertSimpleOutput,
@@ -138,28 +140,28 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: toolCallReadOnlyInput,
providers: [
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./tool_call_read_only/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
assertOutput: assertToolCallReadOnlyClaudeOutput,
},
{
provider: "cursor",
driver: ProviderDriverKind.make("cursor"),
transcriptFile: new URL("./tool_call_read_only/cursor_transcript.ndjson", import.meta.url),
modelSelection: CURSOR_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
assertOutput: assertToolCallReadOnlyCursorOutput,
},
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL("./tool_call_read_only/grok_transcript.ndjson", import.meta.url),
modelSelection: GROK_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
assertOutput: assertToolCallReadOnlyCursorOutput,
},
{
provider: "acpRegistry",
driver: ProviderDriverKind.make("acpRegistry"),
transcriptFile: new URL("./tool_call_read_only/grok_transcript.ndjson", import.meta.url),
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
@@ -172,7 +174,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: toolCallReadOnlyOnRequestInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL(
"./tool_call_read_only_on_request/codex_transcript.ndjson",
import.meta.url,
@@ -182,7 +184,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
assertOutput: assertToolCallReadOnlyOnRequestOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL(
"./tool_call_read_only_on_request/claude_transcript.ndjson",
import.meta.url,
@@ -192,7 +194,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
assertOutput: assertToolCallReadOnlyOnRequestClaudeOutput,
},
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL(
"./tool_call_read_only_on_request/grok_transcript.ndjson",
import.meta.url,
@@ -202,7 +204,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
assertOutput: assertToolCallReadOnlyOnRequestOutput,
},
{
provider: "acpRegistry",
driver: ProviderDriverKind.make("acpRegistry"),
transcriptFile: new URL(
"./tool_call_read_only_on_request/grok_transcript.ndjson",
import.meta.url,
@@ -218,7 +220,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: toolCallWorkspaceNeverInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL(
"./tool_call_workspace_never/codex_transcript.ndjson",
import.meta.url,
@@ -228,7 +230,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
assertOutput: assertToolCallWorkspaceNeverOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL(
"./tool_call_workspace_never/claude_transcript.ndjson",
import.meta.url,
@@ -244,7 +246,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: toolCallRestrictedGranularInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL(
"./tool_call_restricted_granular/codex_transcript.ndjson",
import.meta.url,
@@ -254,7 +256,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
assertOutput: assertToolCallRestrictedGranularOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL(
"./tool_call_restricted_granular/claude_transcript.ndjson",
import.meta.url,
@@ -270,20 +272,20 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: subagentInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./subagent/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY,
assertOutput: assertSubagentOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./subagent/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertClaudeSubagentOutput,
},
{
provider: "cursor",
driver: ProviderDriverKind.make("cursor"),
transcriptFile: new URL("./subagent/cursor_transcript.ndjson", import.meta.url),
modelSelection: CURSOR_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
@@ -296,7 +298,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: subagentContinueInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./subagent_continue/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
assertOutput: assertSubagentContinueOutput,
@@ -308,7 +310,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: openCodeSubagentInput,
providers: [
{
provider: "opencode",
driver: ProviderDriverKind.make("opencode"),
transcriptFile: new URL("./opencode_subagent/opencode_transcript.ndjson", import.meta.url),
modelSelection: OPENCODE_MODEL_SELECTION,
assertOutput: assertOpenCodeSubagentOutput,
@@ -320,31 +322,31 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: multiTurnInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./multi_turn/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
assertOutput: assertMultiTurnOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./multi_turn/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertMultiTurnClaudeOutput,
},
{
provider: "cursor",
driver: ProviderDriverKind.make("cursor"),
transcriptFile: new URL("./multi_turn/cursor_transcript.ndjson", import.meta.url),
modelSelection: CURSOR_MODEL_SELECTION,
assertOutput: assertMultiTurnOutput,
},
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL("./multi_turn/grok_transcript.ndjson", import.meta.url),
modelSelection: GROK_MODEL_SELECTION,
assertOutput: assertMultiTurnOutput,
},
{
provider: "acpRegistry",
driver: ProviderDriverKind.make("acpRegistry"),
transcriptFile: new URL("./multi_turn/grok_transcript.ndjson", import.meta.url),
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
assertOutput: assertMultiTurnOutput,
@@ -356,7 +358,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: multiTurnInput,
providers: [
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./multi_turn_restart/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertMultiTurnClaudeOutput,
@@ -368,31 +370,31 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: queuedTurnInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./queued_turn/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
assertOutput: assertQueuedTurnOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./queued_turn/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertQueuedTurnOutput,
},
{
provider: "cursor",
driver: ProviderDriverKind.make("cursor"),
transcriptFile: new URL("./queued_turn/cursor_transcript.ndjson", import.meta.url),
modelSelection: CURSOR_MODEL_SELECTION,
assertOutput: assertQueuedTurnOutput,
},
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL("./queued_turn/grok_transcript.ndjson", import.meta.url),
modelSelection: GROK_MODEL_SELECTION,
assertOutput: assertQueuedTurnOutput,
},
{
provider: "acpRegistry",
driver: ProviderDriverKind.make("acpRegistry"),
transcriptFile: new URL("./queued_turn/grok_transcript.ndjson", import.meta.url),
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
assertOutput: assertQueuedTurnOutput,
@@ -404,27 +406,27 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: todoListInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./todo_list/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
assertOutput: assertTodoListOutput,
},
{
provider: "cursor",
driver: ProviderDriverKind.make("cursor"),
transcriptFile: new URL("./todo_list/cursor_transcript.ndjson", import.meta.url),
modelSelection: CURSOR_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
assertOutput: assertTodoListCursorOutput,
},
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL("./todo_list/grok_transcript.ndjson", import.meta.url),
modelSelection: GROK_MODEL_SELECTION,
assertOutput: assertTodoListGrokOutput,
},
{
provider: "acpRegistry",
driver: ProviderDriverKind.make("acpRegistry"),
transcriptFile: new URL("./todo_list/grok_transcript.ndjson", import.meta.url),
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
assertOutput: assertTodoListGrokOutput,
@@ -436,13 +438,13 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: webSearchInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./web_search/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
assertOutput: assertWebSearchOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./web_search/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertClaudeWebSearchOutput,
@@ -454,21 +456,21 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: planQuestionsInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./plan_questions/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
assertOutput: assertPlanQuestionsOutput,
},
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL("./plan_questions/grok_transcript.ndjson", import.meta.url),
modelSelection: GROK_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
assertOutput: assertPlanQuestionsOutput,
},
{
provider: "opencode",
driver: ProviderDriverKind.make("opencode"),
transcriptFile: new URL("./plan_questions/opencode_transcript.ndjson", import.meta.url),
modelSelection: OPENCODE_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
@@ -481,14 +483,14 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: proposedPlanInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./proposed_plan/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
assertOutput: assertProposedPlanOutput,
},
{
provider: "cursor",
driver: ProviderDriverKind.make("cursor"),
transcriptFile: new URL("./proposed_plan/cursor_transcript.ndjson", import.meta.url),
modelSelection: CURSOR_MODEL_SELECTION,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
@@ -501,31 +503,31 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: messageSteeringInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./message_steering/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
assertOutput: assertMessageSteeringOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./message_steering/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertClaudeMessageSteeringOutput,
},
{
provider: "cursor",
driver: ProviderDriverKind.make("cursor"),
transcriptFile: new URL("./message_steering/cursor_transcript.ndjson", import.meta.url),
modelSelection: CURSOR_MODEL_SELECTION,
assertOutput: assertCursorMessageSteeringOutput,
},
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL("./message_steering/grok_transcript.ndjson", import.meta.url),
modelSelection: GROK_MODEL_SELECTION,
assertOutput: assertGrokMessageSteeringOutput,
},
{
provider: "acpRegistry",
driver: ProviderDriverKind.make("acpRegistry"),
transcriptFile: new URL("./message_steering/grok_transcript.ndjson", import.meta.url),
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
assertOutput: assertGrokMessageSteeringOutput,
@@ -537,35 +539,35 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: turnInterruptInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./turn_interrupt/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
assertOutput: assertTurnInterruptOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./turn_interrupt/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
assertOutput: assertTurnInterruptClaudeOutput,
},
{
provider: "grok",
driver: ProviderDriverKind.make("grok"),
transcriptFile: new URL("./turn_interrupt/grok_transcript.ndjson", import.meta.url),
modelSelection: GROK_MODEL_SELECTION,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
assertOutput: assertTurnInterruptOutput,
},
{
provider: "acpRegistry",
driver: ProviderDriverKind.make("acpRegistry"),
transcriptFile: new URL("./turn_interrupt/grok_transcript.ndjson", import.meta.url),
modelSelection: ACP_REGISTRY_MODEL_SELECTION,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
assertOutput: assertTurnInterruptOutput,
},
{
provider: "opencode",
driver: ProviderDriverKind.make("opencode"),
transcriptFile: new URL("./turn_interrupt/opencode_transcript.ndjson", import.meta.url),
modelSelection: OPENCODE_MODEL_SELECTION,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
@@ -578,7 +580,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: turnInterruptMidToolInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL(
"./turn_interrupt_mid_tool/codex_transcript.ndjson",
import.meta.url,
@@ -588,7 +590,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
assertOutput: assertTurnInterruptMidToolCodexOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL(
"./turn_interrupt_mid_tool/claude_transcript.ndjson",
import.meta.url,
@@ -598,7 +600,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
assertOutput: assertTurnInterruptMidToolClaudeOutput,
},
{
provider: "cursor",
driver: ProviderDriverKind.make("cursor"),
transcriptFile: new URL(
"./turn_interrupt_mid_tool/cursor_transcript.ndjson",
import.meta.url,
@@ -614,7 +616,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: turnInterruptRestartInput,
providers: [
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL(
"./turn_interrupt_restart/claude_transcript.ndjson",
import.meta.url,
@@ -630,13 +632,13 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
buildInput: threadRollbackInput,
providers: [
{
provider: "codex",
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./thread_rollback/codex_transcript.ndjson", import.meta.url),
modelSelection: CODEX_MODEL_SELECTION,
assertOutput: assertThreadRollbackOutput,
},
{
provider: "claudeAgent",
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL("./thread_rollback/claude_transcript.ndjson", import.meta.url),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertClaudeThreadRollbackOutput,
@@ -36,7 +36,7 @@ export function assertOpenCodeSubagentOutput(
assert.isDefined(subagent);
assert.equal(subagent.origin, "provider_native");
assert.equal(subagent.createdBy, "agent");
assert.equal(subagent.provider, "opencode");
assert.equal(subagent.driver, "opencode");
assert.equal(subagent.status, "completed");
assert.equal(subagent.prompt, "Respond exactly CHILD_OK.");
assert.include(subagent.result ?? "", "CHILD_OK");
@@ -96,7 +96,7 @@
{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"call_A9NEOfTYCCXkUPLqxfWsCNE5","command":"/bin/zsh -lc \"cat package.json && printf '\\\\n--- protocol ---\\\\n' && sed -n '1,220p' src/protocol.ts\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"24242","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"read","command":"cat package.json","name":"package.json","path":"package.json"},{"type":"read","command":"sed -n '1,220p' src/protocol.ts","name":"protocol.ts","path":"src/protocol.ts"}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}}
{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"call_yp787C983Bb0Klnj9F8zRBDd","command":"/bin/zsh -lc \"sed -n '1,220p' test/fixtures/codex-app-server-mock-peer.ts && printf '\\\\n--- sample fixture ---\\\\n' && sed -n '1,80p' test/fixtures/codex-app-server-probes/simple.ndjson\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"80213","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"read","command":"sed -n '1,220p' test/fixtures/codex-app-server-mock-peer.ts","name":"codex-app-server-mock-peer.ts","path":"test/fixtures/codex-app-server-mock-peer.ts"},{"type":"read","command":"sed -n '1,80p' test/fixtures/codex-app-server-probes/simple.ndjson","name":"simple.ndjson","path":"test/fixtures/codex-app-server-probes/simple.ndjson"}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}}
{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"call_A9NEOfTYCCXkUPLqxfWsCNE5","command":"/bin/zsh -lc \"cat package.json && printf '\\\\n--- protocol ---\\\\n' && sed -n '1,220p' src/protocol.ts\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"24242","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"read","command":"cat package.json","name":"package.json","path":"package.json"},{"type":"read","command":"sed -n '1,220p' src/protocol.ts","name":"protocol.ts","path":"src/protocol.ts"}],"aggregatedOutput":"{\n \"name\": \"effect-codex-app-server\",\n \"private\": true,\n \"type\": \"module\",\n \"exports\": {\n \"./client\": {\n \"types\": \"./src/client.ts\",\n \"import\": \"./src/client.ts\"\n },\n \"./schema\": {\n \"types\": \"./src/schema.ts\",\n \"import\": \"./src/schema.ts\"\n },\n \"./rpc\": {\n \"types\": \"./src/rpc.ts\",\n \"import\": \"./src/rpc.ts\"\n },\n \"./protocol\": {\n \"types\": \"./src/protocol.ts\",\n \"import\": \"./src/protocol.ts\"\n },\n \"./replay\": {\n \"types\": \"./src/replay.ts\",\n \"import\": \"./src/replay.ts\"\n },\n \"./errors\": {\n \"types\": \"./src/errors.ts\",\n \"import\": \"./src/errors.ts\"\n }\n },\n \"scripts\": {\n \"dev\": \"tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --watch --clean\",\n \"build\": \"tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --clean\",\n \"prepare\": \"effect-language-service patch\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"generate\": \"bun run scripts/generate.ts\",\n \"probe\": \"bun run test/examples/codex-app-server-probe.ts\"\n },\n \"dependencies\": {\n \"effect\": \"catalog:\"\n },\n \"devDependencies\": {\n \"@effect/language-service\": \"catalog:\",\n \"@effect/openapi-generator\": \"catalog:\",\n \"@effect/platform-node\": \"catalog:\",\n \"@effect/vitest\": \"catalog:\",\n \"tsdown\": \"catalog:\",\n \"typescript\": \"catalog:\",\n \"vitest\": \"catalog:\"\n }\n}\n\n--- protocol ---\nimport * as Cause from \"effect/Cause\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as CodexError from \"./errors.ts\";\nimport { JsonRpcId, JsonRpcResponseEnvelope } from \"./_internal/shared.ts\";\n\nexport interface CodexAppServerProtocolLogEvent {\n readonly direction: \"incoming\" | \"outgoing\";\n readonly stage: \"raw\" | \"decoded\" | \"decode_failed\";\n readonly payload: unknown;\n}\n\nexport interface CodexAppServerIncomingNotification {\n readonly method: string;\n readonly params?: unknown;\n}\n\nexport interface CodexAppServerIncomingRequest {\n readonly id: string | number;\n readonly method: string;\n readonly params?: unknown;\n}\n\nexport interface CodexAppServerPatchedProtocolOptions {\n readonly stdio: Stdio.Stdio;\n readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;\n readonly logIncoming?: boolean;\n readonly logOutgoing?: boolean;\n readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;\n readonly onNotification?: (\n notification: CodexAppServerIncomingNotification,\n ) => Effect.Effect<void, never>;\n readonly onRequest?: (\n request: CodexAppServerIncomingRequest,\n ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;\n readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;\n}\n\nexport interface CodexAppServerPatchedProtocol {\n readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;\n readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;\n readonly request: (\n method: string,\n payload?: unknown,\n ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;\n readonly notify: (\n method: string,\n payload?: unknown,\n ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n readonly respond: (\n requestId: string | number,\n result: unknown,\n ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n readonly respondError: (\n requestId: string | number,\n error: CodexError.CodexAppServerRequestError,\n ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isIncomingRequest(value: unknown): value is CodexAppServerIncomiLine truncated
{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"call_0B2ieGRdMDXmQA8peWORTcTz","command":"/bin/zsh -lc \"sed -n '1,220p' src/replay.ts && printf '\\\\n--- replay.test ---\\\\n' && sed -n '1,240p' src/replay.test.ts\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"16103","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"read","command":"sed -n '1,220p' src/replay.ts","name":"replay.ts","path":"src/replay.ts"},{"type":"read","command":"sed -n '1,240p' src/replay.test.ts","name":"replay.test.ts","path":"src/replay.test.ts"}],"aggregatedOutput":"import * as Cause from \"effect/Cause\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\n\nimport { CodexAppServerClient } from \"./client.ts\";\nimport * as CodexClient from \"./client.ts\";\nimport * as CodexError from \"./errors.ts\";\n\nexport const CodexAppServerReplayEntry = Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"expect_outbound\"),\n label: Schema.optional(Schema.String),\n frame: Schema.Unknown,\n }),\n Schema.Struct({\n type: Schema.Literal(\"emit_inbound\"),\n label: Schema.optional(Schema.String),\n frame: Schema.Unknown,\n afterMs: Schema.optional(Schema.Number),\n }),\n Schema.Struct({\n type: Schema.Literal(\"runtime_exit\"),\n status: Schema.Literals([\"success\", \"error\", \"cancelled\"]),\n error: Schema.optional(Schema.Unknown),\n }),\n]);\nexport type CodexAppServerReplayEntry = typeof CodexAppServerReplayEntry.Type;\n\nexport const CodexAppServerReplayTranscript = Schema.Struct({\n provider: Schema.Literal(\"codex\"),\n protocol: Schema.Literal(\"codex.app-server\"),\n version: Schema.String,\n scenario: Schema.String,\n metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n entries: Schema.Array(CodexAppServerReplayEntry),\n});\nexport type CodexAppServerReplayTranscript = typeof CodexAppServerReplayTranscript.Type;\n\nexport class CodexAppServerReplayJsonParseError extends Schema.TaggedErrorClass<CodexAppServerReplayJsonParseError>()(\n \"CodexAppServerReplayJsonParseError\",\n {\n scenario: Schema.String,\n line: Schema.String,\n cause: Schema.Defect,\n },\n) {\n override get message(): string {\n return `Failed to parse outbound Codex app-server replay frame for scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayExhaustedError extends Schema.TaggedErrorClass<CodexAppServerReplayExhaustedError>()(\n \"CodexAppServerReplayExhaustedError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Codex app-server replay transcript exhausted before outbound frame ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayUnexpectedOutboundError extends Schema.TaggedErrorClass<CodexAppServerReplayUnexpectedOutboundError>()(\n \"CodexAppServerReplayUnexpectedOutboundError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n expectedType: Schema.String,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Unexpected outbound Codex app-server frame at replay cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayFrameMismatchError extends Schema.TaggedErrorClass<CodexAppServerReplayFrameMismatchError>()(\n \"CodexAppServerReplayFrameMismatchError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n label: Schema.optional(Schema.String),\n expected: Schema.Unknown,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Outbound Codex app-server frame did not match replay cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayRuntimeExitError extends Schema.TaggedErrorClass<CodexAppServerReplayRuntimeExitError>()(\n \"CodexAppServerReplayRuntimeExitError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n status: Schema.Literals([\"error\", \"cancelled\"]),\n error: Schema.optional(Schema.Unknown),\n },\n) {\n override get message(): string {\n return `Codex app-server replay exited with status ${this.status} at cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayIncompleteError extends Schema.TaggedErrorClass<CodexAppServerReplayIncompleteError>()(\n \"CodexAppServerReplayIncompleteError\",\n {\n scenario: Schema.String,\n cursor: Line truncated
{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"call_0B2ieGRdMDXmQA8peWORTcTz","command":"/bin/zsh -lc \"sed -n '1,220p' src/replay.ts && printf '\\\\n--- replay.test ---\\\\n' && sed -n '1,240p' src/replay.test.ts\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"16103","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"read","command":"sed -n '1,220p' src/replay.ts","name":"replay.ts","path":"src/replay.ts"},{"type":"read","command":"sed -n '1,240p' src/replay.test.ts","name":"replay.test.ts","path":"src/replay.test.ts"}],"aggregatedOutput":"import * as Cause from \"effect/Cause\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\n\nimport { CodexAppServerClient } from \"./client.ts\";\nimport * as CodexClient from \"./client.ts\";\nimport * as CodexError from \"./errors.ts\";\n\nexport const CodexAppServerReplayEntry = Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"expect_outbound\"),\n label: Schema.optional(Schema.String),\n frame: Schema.Unknown,\n }),\n Schema.Struct({\n type: Schema.Literal(\"emit_inbound\"),\n label: Schema.optional(Schema.String),\n frame: Schema.Unknown,\n afterMs: Schema.optional(Schema.Number),\n }),\n Schema.Struct({\n type: Schema.Literal(\"runtime_exit\"),\n status: Schema.Literals([\"success\", \"error\", \"cancelled\"]),\n error: Schema.optional(Schema.Unknown),\n }),\n]);\nexport type CodexAppServerReplayEntry = typeof CodexAppServerReplayEntry.Type;\n\nexport const CodexAppServerReplayTranscript = Schema.Struct({\n driver: Schema.Literal(\"codex\"),\n protocol: Schema.Literal(\"codex.app-server\"),\n version: Schema.String,\n scenario: Schema.String,\n metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n entries: Schema.Array(CodexAppServerReplayEntry),\n});\nexport type CodexAppServerReplayTranscript = typeof CodexAppServerReplayTranscript.Type;\n\nexport class CodexAppServerReplayJsonParseError extends Schema.TaggedErrorClass<CodexAppServerReplayJsonParseError>()(\n \"CodexAppServerReplayJsonParseError\",\n {\n scenario: Schema.String,\n line: Schema.String,\n cause: Schema.Defect,\n },\n) {\n override get message(): string {\n return `Failed to parse outbound Codex app-server replay frame for scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayExhaustedError extends Schema.TaggedErrorClass<CodexAppServerReplayExhaustedError>()(\n \"CodexAppServerReplayExhaustedError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Codex app-server replay transcript exhausted before outbound frame ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayUnexpectedOutboundError extends Schema.TaggedErrorClass<CodexAppServerReplayUnexpectedOutboundError>()(\n \"CodexAppServerReplayUnexpectedOutboundError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n expectedType: Schema.String,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Unexpected outbound Codex app-server frame at replay cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayFrameMismatchError extends Schema.TaggedErrorClass<CodexAppServerReplayFrameMismatchError>()(\n \"CodexAppServerReplayFrameMismatchError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n label: Schema.optional(Schema.String),\n expected: Schema.Unknown,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Outbound Codex app-server frame did not match replay cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayRuntimeExitError extends Schema.TaggedErrorClass<CodexAppServerReplayRuntimeExitError>()(\n \"CodexAppServerReplayRuntimeExitError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n status: Schema.Literals([\"error\", \"cancelled\"]),\n error: Schema.optional(Schema.Unknown),\n },\n) {\n override get message(): string {\n return `Codex app-server replay exited with status ${this.status} at cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayIncompleteError extends Schema.TaggedErrorClass<CodexAppServerReplayIncompleteError>()(\n \"CodexAppServerReplayIncompleteError\",\n {\n scenario: Schema.String,\n cursor: ScLine truncated
{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"call_yp787C983Bb0Klnj9F8zRBDd","command":"/bin/zsh -lc \"sed -n '1,220p' test/fixtures/codex-app-server-mock-peer.ts && printf '\\\\n--- sample fixture ---\\\\n' && sed -n '1,80p' test/fixtures/codex-app-server-probes/simple.ndjson\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"80213","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"read","command":"sed -n '1,220p' test/fixtures/codex-app-server-mock-peer.ts","name":"codex-app-server-mock-peer.ts","path":"test/fixtures/codex-app-server-mock-peer.ts"},{"type":"read","command":"sed -n '1,80p' test/fixtures/codex-app-server-probes/simple.ndjson","name":"simple.ndjson","path":"test/fixtures/codex-app-server-probes/simple.ndjson"}],"aggregatedOutput":"let nextServerRequestId = 10_000;\nlet pendingSkillsListRequestId: number | string | null = null;\nlet pendingUserInputRequestId: number | null = null;\n\nconst writeMessage = (message: unknown) => {\n process.stdout.write(`${JSON.stringify(message)}\\n`);\n};\n\nconst respond = (id: number | string, result: unknown) => {\n writeMessage({ id, result });\n};\n\nconst respondError = (id: number | string, code: number, message: string) => {\n writeMessage({\n id,\n error: {\n code,\n message,\n },\n });\n};\n\nconst sendRequest = (method: string, params: unknown) => {\n const id = nextServerRequestId++;\n writeMessage({ id, method, params });\n return id;\n};\n\nconst handleMethod = (message: Record<string, unknown>) => {\n const method = message.method;\n if (typeof method !== \"string\") {\n return;\n }\n\n switch (method) {\n case \"initialize\": {\n respond(message.id as number | string, {\n userAgent: \"mock-codex-app-server\",\n codexHome: process.cwd(),\n platformFamily: process.platform === \"win32\" ? \"windows\" : \"unix\",\n platformOs: process.platform === \"darwin\" ? \"macos\" : process.platform,\n });\n return;\n }\n case \"initialized\": {\n writeMessage({\n method: \"item/agentMessage/delta\",\n params: {\n delta: \"Mock server is ready.\",\n itemId: \"item-1\",\n threadId: \"thread-1\",\n turnId: \"turn-1\",\n },\n });\n return;\n }\n case \"account/read\": {\n respond(message.id as number | string, {\n account: {\n type: \"chatgpt\",\n email: \"[email protected]\",\n planType: \"plus\",\n },\n requiresOpenaiAuth: false,\n });\n return;\n }\n case \"skills/list\": {\n pendingSkillsListRequestId = message.id as number | string;\n pendingUserInputRequestId = sendRequest(\"item/tool/requestUserInput\", {\n itemId: \"item-approval-1\",\n threadId: \"thread-1\",\n turnId: \"turn-1\",\n questions: [\n {\n id: \"approved\",\n header: \"Approve\",\n question: \"Continue with the mock skills request?\",\n options: [\n {\n label: \"yes\",\n description: \"Approve the request\",\n },\n ],\n },\n ],\n });\n return;\n }\n default: {\n if (message.id !== undefined) {\n respondError(message.id as number | string, -32601, `Unhandled request: ${method}`);\n }\n }\n }\n};\n\nconst handleResponse = (message: Record<string, unknown>) => {\n if (message.id !== pendingUserInputRequestId) {\n return;\n }\n\n pendingUserInputRequestId = null;\n\n respond(pendingSkillsListRequestId!, {\n data: [\n {\n cwd: process.cwd(),\n errors: [],\n skills: [],\n },\n ],\n });\n pendingSkillsListRequestId = null;\n};\n\nlet remainder = \"\";\n\nprocess.stdin.setEncoding(\"utf8\");\nprocess.stdin.on(\"data\", (chunk) => {\n remainder += chunk;\n const lines = remainder.split(\"\\n\");\n remainder = lines.pop() ?? \"\";\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n continue;\n }\n\n const message = JSON.parse(trimmed) as Record<string, unknown>;\n if (\"method\" in message) {\n handleMethod(message);\n continue;\n }\n if (\"id\" in message) {\n handleResponse(message);\n }\n }\n});\n\nprocess.stdin.on(\"end\", () => {\n process.exit(0);\n});\n\n--- sample fixture ---\n{\"type\":\"transcript_start\",\"provider\":\"codex\",\"protocol\":\"codex.app-server\",\"version\":\"0.120.0\",\"scenario\":\"simple\",\"metadata\":{\"source\":\"codex-app-server-probe\",\"fileName\":\"simple.ndjson\",\"description\":\"One thread and one turn with a deterministic text-only response.\"}}\n{\"type\":\"expect_outbound\",\"label\":\"initialize\",\"frame\":{\"iLine truncated
{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"reasoning","id":"rs_0b2955d3a75fd8630169e7fab1e01481999f57bbddc11af4b5","summary":[],"content":[]},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}}
{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"reasoning","id":"rs_0b2955d3a75fd8630169e7fab1e01481999f57bbddc11af4b5","summary":[],"content":[]},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}}
@@ -12,8 +12,9 @@ import {
type OrchestrationV2ThreadProjection,
type OrchestrationV2TurnItem,
type OrchestrationV2UserMessageInputIntent,
type ProviderKind,
ProviderInstanceId,
type ProviderInteractionMode,
type ProviderDriverKind,
type ProviderReplayTranscript,
type ProviderUserInputAnswers,
} from "@t3tools/contracts";
@@ -196,7 +197,7 @@ export interface OrchestratorFixtureInput {
}
export interface ProviderOrchestratorReplayVariant {
readonly provider: ProviderKind;
readonly driver: ProviderDriverKind;
readonly transcriptFile: URL;
readonly modelSelection: ModelSelection;
readonly runtimePolicyOverride?: RuntimePolicyV2Override;
@@ -355,6 +356,7 @@ export function dispatchMessageCommand(input: {
export function materializeFixtureInput(input: {
readonly scenario: string;
readonly fixtureInput: OrchestratorFixtureInput;
readonly driver: ProviderDriverKind;
readonly modelSelection: ModelSelection;
}): Effect.Effect<MaterializedOrchestratorFixtureInput, IdAllocatorV2Error, IdAllocatorV2> {
return Effect.gen(function* () {
@@ -483,7 +485,7 @@ export function materializeFixtureInput(input: {
}),
threadId: ids.threadId,
requestId: yield* idAllocator.allocate.runtimeRequest({
provider: input.modelSelection.provider,
driver: input.driver,
nativeRequestId: `fixture-placeholder-${messageIndex}`,
}),
answers: step.answers,
@@ -509,7 +511,7 @@ export function materializeFixtureInput(input: {
}),
threadId: ids.threadId,
requestId: yield* idAllocator.allocate.runtimeRequest({
provider: input.modelSelection.provider,
driver: input.driver,
nativeRequestId: `fixture-placeholder-${messageIndex}`,
}),
decision: step.decision ?? "accept",
@@ -679,7 +681,10 @@ export function assertBaseProjection(input: {
}) {
const projection = projectionFor(input.result, input.transcript.scenario);
assert.equal(projection.thread.defaultProvider, input.transcript.provider);
assert.equal(
projection.thread.providerInstanceId,
ProviderInstanceId.make(input.transcript.provider),
);
assert.lengthOf(projection.runs, input.runCount);
assert.isAtLeast(projection.providerThreads.length, 1);
assert.isAtLeast(
@@ -69,7 +69,7 @@ export function assertClaudeSubagentOutput(
for (const subagent of projection.subagents) {
assert.equal(subagent.origin, "provider_native");
assert.equal(subagent.createdBy, "agent");
assert.equal(subagent.provider, "claudeAgent");
assert.equal(subagent.driver, "claudeAgent");
assert.equal(subagent.status, "completed");
assert.isNull(subagent.providerThreadId);
assert.isNotNull(subagent.childThreadId);
@@ -63,7 +63,7 @@ export function assertSubagentOutput(
for (const subagent of projection.subagents) {
assert.equal(subagent.origin, "provider_native");
assert.equal(subagent.createdBy, "agent");
assert.equal(subagent.provider, "codex");
assert.equal(subagent.driver, "codex");
assert.isNotNull(subagent.childThreadId);
assert.isNotNull(subagent.providerThreadId);
assert.isNotNull(subagent.nativeTaskRef);
@@ -63,7 +63,7 @@ export function assertCursorSubagentOutput(
for (const subagent of projection.subagents) {
assert.equal(subagent.origin, "provider_native");
assert.equal(subagent.createdBy, "agent");
assert.equal(subagent.provider, "cursor");
assert.equal(subagent.driver, "cursor");
assert.isNull(subagent.providerThreadId);
assert.isNotNull(subagent.childThreadId);
assert.isNotNull(subagent.nativeTaskRef);
@@ -47,6 +47,7 @@ import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_OrchestrationV2.ts";
import Migration0034 from "./Migrations/034_OrchestrationV2Subagents.ts";
import Migration0035 from "./Migrations/035_OrchestrationV2Foundation.ts";
/**
* Migration loader with all migrations defined inline.
@@ -93,6 +94,7 @@ export const migrationEntries = [
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "OrchestrationV2", Migration0033],
[34, "OrchestrationV2Subagents", Migration0034],
[35, "OrchestrationV2Foundation", Migration0035],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,172 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
/**
* Production-facing V2 persistence additions.
*
* The original V2 schema used a single `provider` column for both configured
* instance routing and driver identity. Keep those columns in place for
* migration compatibility. They remain write-through shadows where the old
* schema declared them NOT NULL; all V2 reads and indexes use the explicit
* columns added here.
*/
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`ALTER TABLE orchestration_v2_events ADD COLUMN driver TEXT`;
yield* sql`ALTER TABLE orchestration_v2_events ADD COLUMN provider_instance_id TEXT`;
yield* sql`
UPDATE orchestration_v2_events
SET
driver = provider,
provider_instance_id = COALESCE(
json_extract(payload_json, '$.providerInstanceId'),
provider
)
`;
yield* sql`CREATE INDEX orchestration_v2_events_instance_sequence_idx ON orchestration_v2_events(provider_instance_id, sequence)`;
yield* sql`ALTER TABLE orchestration_v2_projection_threads ADD COLUMN provider_instance_id TEXT`;
yield* sql`
UPDATE orchestration_v2_projection_threads
SET provider_instance_id = COALESCE(
json_extract(payload_json, '$.providerInstanceId'),
default_provider
)
`;
yield* sql`ALTER TABLE orchestration_v2_projection_runs ADD COLUMN provider_instance_id TEXT`;
yield* sql`
UPDATE orchestration_v2_projection_runs
SET provider_instance_id = COALESCE(
json_extract(payload_json, '$.providerInstanceId'),
provider
)
`;
yield* sql`ALTER TABLE orchestration_v2_projection_run_attempts ADD COLUMN provider_instance_id TEXT`;
yield* sql`
UPDATE orchestration_v2_projection_run_attempts
SET provider_instance_id = COALESCE(
json_extract(payload_json, '$.providerInstanceId'),
provider
)
`;
yield* sql`ALTER TABLE orchestration_v2_projection_provider_sessions ADD COLUMN driver TEXT`;
yield* sql`ALTER TABLE orchestration_v2_projection_provider_sessions ADD COLUMN provider_instance_id TEXT`;
yield* sql`
UPDATE orchestration_v2_projection_provider_sessions
SET
driver = COALESCE(json_extract(payload_json, '$.driver'), provider),
provider_instance_id = COALESCE(
json_extract(payload_json, '$.providerInstanceId'),
provider
)
`;
yield* sql`CREATE INDEX orchestration_v2_projection_provider_sessions_instance_status_idx ON orchestration_v2_projection_provider_sessions(provider_instance_id, status)`;
yield* sql`ALTER TABLE orchestration_v2_projection_provider_threads ADD COLUMN driver TEXT`;
yield* sql`ALTER TABLE orchestration_v2_projection_provider_threads ADD COLUMN provider_instance_id TEXT`;
yield* sql`
UPDATE orchestration_v2_projection_provider_threads
SET
driver = COALESCE(json_extract(payload_json, '$.driver'), provider),
provider_instance_id = COALESCE(
json_extract(payload_json, '$.providerInstanceId'),
provider
)
`;
yield* sql`CREATE INDEX orchestration_v2_projection_provider_threads_instance_status_idx ON orchestration_v2_projection_provider_threads(provider_instance_id, status)`;
yield* sql`ALTER TABLE orchestration_v2_projection_subagents ADD COLUMN driver TEXT`;
yield* sql`ALTER TABLE orchestration_v2_projection_subagents ADD COLUMN provider_instance_id TEXT`;
yield* sql`
UPDATE orchestration_v2_projection_subagents
SET
driver = json_extract(payload_json, '$.driver'),
provider_instance_id = COALESCE(
json_extract(payload_json, '$.providerInstanceId'),
provider
)
`;
yield* sql`ALTER TABLE orchestration_v2_projection_context_transfers ADD COLUMN source_provider_instance_id TEXT`;
yield* sql`ALTER TABLE orchestration_v2_projection_context_transfers ADD COLUMN target_provider_instance_id TEXT`;
yield* sql`
UPDATE orchestration_v2_projection_context_transfers
SET
source_provider_instance_id = COALESCE(
json_extract(payload_json, '$.sourceProviderInstanceId'),
source_provider
),
target_provider_instance_id = COALESCE(
json_extract(payload_json, '$.targetProviderInstanceId'),
target_provider
)
`;
yield* sql`
CREATE TABLE orchestration_v2_effect_outbox (
effect_id TEXT PRIMARY KEY,
command_id TEXT NOT NULL,
thread_id TEXT NOT NULL,
effect_type TEXT NOT NULL,
payload_json TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'succeeded', 'failed')),
attempt_count INTEGER NOT NULL DEFAULT 0,
available_at TEXT NOT NULL,
lease_owner TEXT,
lease_expires_at TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
completed_at TEXT,
last_error TEXT
)
`;
yield* sql`CREATE INDEX orchestration_v2_effect_outbox_claim_idx ON orchestration_v2_effect_outbox(status, available_at, lease_expires_at, created_at)`;
yield* sql`CREATE INDEX orchestration_v2_effect_outbox_command_idx ON orchestration_v2_effect_outbox(command_id, effect_id)`;
yield* sql`
CREATE TABLE orchestration_v2_turn_item_positions (
thread_id TEXT NOT NULL,
turn_item_id TEXT NOT NULL,
ordinal INTEGER NOT NULL,
PRIMARY KEY (thread_id, turn_item_id),
UNIQUE (thread_id, ordinal)
)
`;
yield* sql`
INSERT OR IGNORE INTO orchestration_v2_turn_item_positions (
thread_id,
turn_item_id,
ordinal
)
SELECT thread_id, turn_item_id, ordinal
FROM orchestration_v2_projection_turn_items
ORDER BY thread_id, ordinal, turn_item_id
`;
yield* sql`
CREATE TABLE orchestration_v2_projection_metadata (
projection_name TEXT PRIMARY KEY,
schema_version INTEGER NOT NULL,
last_sequence INTEGER NOT NULL,
updated_at TEXT NOT NULL
)
`;
yield* sql`
INSERT INTO orchestration_v2_projection_metadata (
projection_name,
schema_version,
last_sequence,
updated_at
)
VALUES (
'thread-projections',
1,
COALESCE((SELECT MAX(sequence) FROM orchestration_v2_events), 0),
strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
)
`;
});
@@ -0,0 +1,171 @@
import {
AcpRegistrySettings,
ProviderDriverKind,
TextGenerationError,
type ServerProvider,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as DateTime from "effect/DateTime";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import {
AcpRegistryAdapterV2Driver,
type AcpRegistryAdapterV2DriverEnv,
} from "../../orchestration-v2/Adapters/AcpRegistryAdapterV2.ts";
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { ProviderAdapterRequestError, ProviderDriverError } from "../Errors.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
type ProviderInstance,
} from "../ProviderDriver.ts";
const DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
const unsupportedLegacyCall = (operation: string) =>
Effect.fail(
new ProviderAdapterRequestError({
provider: DRIVER_KIND,
method: operation,
detail: "ACP Registry instances are available through orchestration V2 only.",
}),
);
const makeLegacyAdapter = (): ProviderInstance["adapter"] => ({
provider: DRIVER_KIND,
capabilities: { sessionModelSwitch: "unsupported" },
startSession: () => unsupportedLegacyCall("startSession"),
sendTurn: () => unsupportedLegacyCall("sendTurn"),
interruptTurn: () => unsupportedLegacyCall("interruptTurn"),
respondToRequest: () => unsupportedLegacyCall("respondToRequest"),
respondToUserInput: () => unsupportedLegacyCall("respondToUserInput"),
stopSession: () => Effect.void,
listSessions: () => Effect.succeed([]),
hasSession: () => Effect.succeed(false),
readThread: () => unsupportedLegacyCall("readThread"),
rollbackThread: () => unsupportedLegacyCall("rollbackThread"),
stopAll: () => Effect.void,
streamEvents: Stream.empty,
});
const makeUnsupportedTextGeneration = (): TextGenerationShape => {
const unsupported = (operation: string) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "ACP Registry instances do not provide application text generation.",
}),
);
return {
generateCommitMessage: () => unsupported("generateCommitMessage"),
generatePrContent: () => unsupported("generatePrContent"),
generateBranchName: () => unsupported("generateBranchName"),
generateThreadTitle: () => unsupported("generateThreadTitle"),
};
};
const makeSnapshot = (input: {
readonly instanceId: ProviderInstance["instanceId"];
readonly displayName: string | undefined;
readonly accentColor: string | undefined;
readonly enabled: boolean;
readonly settings: AcpRegistrySettings;
readonly continuationKey: string;
readonly checkedAt: string;
}): ServerProvider => {
const modelIds = Array.from(new Set(["default", ...input.settings.customModels]));
return {
instanceId: input.instanceId,
driver: DRIVER_KIND,
...(input.displayName ? { displayName: input.displayName } : {}),
...(input.accentColor ? { accentColor: input.accentColor } : {}),
continuation: { groupKey: input.continuationKey },
enabled: input.enabled,
installed: true,
version: null,
status: input.enabled ? "ready" : "disabled",
auth: { status: "unknown" },
checkedAt: input.checkedAt,
models: modelIds.map((model) => ({
slug: model,
name: model,
isCustom: model !== "default",
capabilities: null,
})),
slashCommands: [],
skills: [],
};
};
export type AcpRegistryDriverEnv = AcpRegistryAdapterV2DriverEnv;
/** Canonical provider-instance wrapper for ACP Registry orchestration adapters. */
export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryDriverEnv> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "ACP Registry",
supportsMultipleInstances: true,
},
configSchema: AcpRegistrySettings,
defaultConfig: () => decodeSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
instanceId,
});
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({
instanceId,
displayName,
accentColor,
environment,
enabled,
config,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build ACP Registry orchestration adapter.",
cause,
}),
),
);
const currentSnapshot = () =>
makeSnapshot({
instanceId,
displayName,
accentColor,
enabled,
settings: config,
continuationKey: continuationIdentity.continuationKey,
checkedAt,
});
return {
instanceId,
driverKind: DRIVER_KIND,
continuationIdentity,
displayName,
accentColor,
enabled,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
packageName: null,
}),
getSnapshot: Effect.sync(currentSnapshot),
refresh: Effect.sync(currentSnapshot),
streamChanges: Stream.empty,
},
adapter: makeLegacyAdapter(),
orchestrationAdapter,
textGeneration: makeUnsupportedTextGeneration(),
} satisfies ProviderInstance;
}),
};
@@ -26,7 +26,10 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
ClaudeAdapterV2Driver,
type ClaudeAdapterV2DriverEnv,
} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
import {
@@ -82,7 +85,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
});
export type ClaudeDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| ClaudeAdapterV2DriverEnv
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -149,6 +152,24 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
};
const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions);
const orchestrationAdapter = yield* ClaudeAdapterV2Driver.create({
instanceId,
displayName,
accentColor,
environment,
enabled,
config,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build Claude orchestration adapter.",
cause,
}),
),
);
const textGeneration = yield* makeClaudeTextGeneration(effectiveConfig, processEnv);
// Per-instance capabilities cache: keyed on binary + resolved HOME so
@@ -215,6 +236,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
enabled,
snapshot,
adapter,
orchestrationAdapter,
textGeneration,
} satisfies ProviderInstance;
}),
@@ -33,7 +33,10 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
CodexAdapterV2Driver,
type CodexAdapterV2DriverEnv,
} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
@@ -73,7 +76,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
* registered driver and the runtime satisfies them once.
*/
export type CodexDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| CodexAdapterV2DriverEnv
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -160,6 +163,24 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
environment: processEnv,
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
});
const orchestrationAdapter = yield* CodexAdapterV2Driver.create({
instanceId,
displayName,
accentColor,
environment,
enabled,
config,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build Codex orchestration adapter.",
cause,
}),
),
);
const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);
// Build a managed snapshot whose settings never change — mutations come
@@ -207,6 +228,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
enabled,
snapshot,
adapter,
orchestrationAdapter,
textGeneration,
} satisfies ProviderInstance;
}),
@@ -24,6 +24,10 @@ import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
import {
CursorAdapterV2Driver,
type CursorAdapterV2DriverEnv,
} from "../../orchestration-v2/Adapters/CursorAdapterV2.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
import {
@@ -66,7 +70,7 @@ const UPDATE: ProviderMaintenanceCapabilitiesResolver = {
};
export type CursorDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| CursorAdapterV2DriverEnv
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -131,6 +135,24 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
instanceId,
});
const orchestrationAdapter = yield* CursorAdapterV2Driver.create({
instanceId,
displayName,
accentColor,
environment,
enabled,
config,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build Cursor orchestration adapter.",
cause,
}),
),
);
const textGeneration = yield* makeCursorTextGeneration(effectiveConfig, processEnv);
const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe(
@@ -183,6 +205,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
enabled,
snapshot,
adapter,
orchestrationAdapter,
textGeneration,
} satisfies ProviderInstance;
}),
+24 -1
View File
@@ -11,6 +11,10 @@ import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
import {
GrokAdapterV2Driver,
type GrokAdapterV2DriverEnv,
} from "../../orchestration-v2/Adapters/GrokAdapterV2.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
import {
@@ -48,7 +52,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
);
export type GrokDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| GrokAdapterV2DriverEnv
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -111,6 +115,24 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
instanceId,
});
const orchestrationAdapter = yield* GrokAdapterV2Driver.create({
instanceId,
displayName,
accentColor,
environment,
enabled,
config,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build Grok orchestration adapter.",
cause,
}),
),
);
const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
@@ -157,6 +179,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
enabled,
snapshot,
adapter,
orchestrationAdapter,
textGeneration,
} satisfies ProviderInstance;
}),
@@ -24,7 +24,10 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
OpenCodeAdapterV2Driver,
type OpenCodeAdapterV2DriverEnv,
} from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
import {
@@ -77,7 +80,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
});
export type OpenCodeDriverEnv =
| BackgroundPolicy.BackgroundPolicy
| OpenCodeAdapterV2DriverEnv
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -141,6 +144,24 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
environment: processEnv,
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
});
const orchestrationAdapter = yield* OpenCodeAdapterV2Driver.create({
instanceId,
displayName,
accentColor,
environment,
enabled,
config,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: "Failed to build OpenCode orchestration adapter.",
cause,
}),
),
);
const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig, processEnv);
const checkProvider = checkOpenCodeProviderStatus(
@@ -188,6 +209,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
enabled,
snapshot,
adapter,
orchestrationAdapter,
textGeneration,
} satisfies ProviderInstance;
}),
@@ -96,19 +96,60 @@ const fakeCursorAdapter: CursorAdapterShape = {
streamEvents: Stream.empty,
};
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLive,
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),
Layer.succeed(CursorAdapter, fakeCursorAdapter),
),
),
NodeServices.layer,
),
// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry —
// it walks `listInstances` once at boot and surfaces the default-instance
// adapter keyed by its driver kind. To test the facade we supply four fake
// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so
// they pass the default-instance filter.
const makeFakeInstance = (
driverKindString: "codex" | "claudeAgent" | "cursor" | "opencode",
adapter: ProviderInstance["adapter"],
): ProviderInstance => {
const driverKind = ProviderDriverKind.make(driverKindString);
return {
instanceId: defaultInstanceIdForDriver(driverKind),
driverKind,
continuationIdentity: {
driverKind,
continuationKey: `${driverKind}:instance:${defaultInstanceIdForDriver(driverKind)}`,
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: driverKind,
packageName: null,
}),
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
refresh: Effect.succeed({} as unknown as ServerProvider),
streamChanges: Stream.empty,
},
adapter,
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
textGeneration: {} as unknown as TextGenerationShape,
};
};
const fakeInstances: ReadonlyArray<ProviderInstance> = [
makeFakeInstance("codex", fakeCodexAdapter),
makeFakeInstance("claudeAgent", fakeClaudeAdapter),
makeFakeInstance("opencode", fakeOpenCodeAdapter),
makeFakeInstance("cursor", fakeCursorAdapter),
];
const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)),
listInstances: Effect.succeed(fakeInstances),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
// Tests never drive changes through this fake; acquire a throwaway
// subscription on an unused PubSub so the shape is satisfied.
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) => PubSub.subscribe(pubsub)),
});
const layer = Layer.mergeAll(
Layer.provide(ProviderAdapterRegistryLive, fakeInstanceRegistryLayer),
NodeServices.layer,
);
@@ -56,6 +56,14 @@ import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";
import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
import {
type ProviderOrchestrationAdapterInfrastructure,
ProviderOrchestrationAdapterInfrastructureLive,
} from "./ProviderOrchestrationAdapterInfrastructure.ts";
type ProviderInstanceRegistryHydrationEnv =
| Exclude<BuiltInDriversEnv, ProviderOrchestrationAdapterInfrastructure>
| ServerSettingsService;
/**
* Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
@@ -152,7 +160,7 @@ const SettingsWatcherLive = Layer.effectDiscard(
export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
ProviderInstanceRegistry,
never,
BuiltInDriversEnv | ServerSettingsService
ProviderInstanceRegistryHydrationEnv
> = Layer.unwrap(
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
@@ -167,8 +175,8 @@ export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
const mutableLayer = ProviderInstanceRegistryMutableLayer({
drivers: BUILT_IN_DRIVERS,
configMap: initialConfigMap,
});
}).pipe(Layer.provide(ProviderOrchestrationAdapterInfrastructureLive));
return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
}),
) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;
) as Layer.Layer<ProviderInstanceRegistry, never, ProviderInstanceRegistryHydrationEnv>;
@@ -43,14 +43,16 @@ import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import type { BuiltInDriversEnv } from "../builtInDrivers.ts";
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
import { CodexDriver } from "../Drivers/CodexDriver.ts";
import { CodexDriver, type CodexDriverEnv } from "../Drivers/CodexDriver.ts";
import { CursorDriver } from "../Drivers/CursorDriver.ts";
import { GrokDriver } from "../Drivers/GrokDriver.ts";
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
import { ProviderOrchestrationAdapterInfrastructureLive } from "./ProviderOrchestrationAdapterInfrastructure.ts";
const TestHttpClientLive = Layer.succeed(
HttpClient.HttpClient,
@@ -139,15 +141,19 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
// `NodeServices.layer` through `Layer.provideMerge` to satisfy that
// dependency while still surfacing NodeServices to the test body (the
// codex driver's `create` yields `ChildProcessSpawner` directly).
const testLayer = ServerConfig.layerTest(process.cwd(), {
const baseLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-test",
}).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
const testLayer = ProviderOrchestrationAdapterInfrastructureLive.pipe(
Layer.provideMerge(baseLayer),
);
it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
Effect.gen(function* () {
@@ -178,7 +184,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
},
};
const { registry } = yield* makeProviderInstanceRegistry({
const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv>({
drivers: [CodexDriver],
configMap,
});
@@ -244,7 +250,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
},
};
const { registry } = yield* makeProviderInstanceRegistry({
const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv>({
drivers: [CodexDriver],
configMap,
});
@@ -278,15 +284,19 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
// surfaced; that merged layer then provides `ServerConfig.layerTest`'s
// `FileSystem` dep while keeping everything else surfaced to the test.
const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
const testLayer = ServerConfig.layerTest(process.cwd(), {
const baseLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "provider-instance-registry-all-drivers-test",
}).pipe(
Layer.provideMerge(infraLayer),
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
);
const testLayer = ProviderOrchestrationAdapterInfrastructureLive.pipe(
Layer.provideMerge(baseLayer),
);
it.live("boots one instance of every shipped driver from a single config map", () =>
Effect.gen(function* () {
@@ -338,7 +348,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
},
};
const { registry } = yield* makeProviderInstanceRegistry({
const { registry } = yield* makeProviderInstanceRegistry<BuiltInDriversEnv>({
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
configMap,
});
@@ -0,0 +1,29 @@
import * as Layer from "effect/Layer";
import {
ClaudeAgentSdkQueryRunner,
claudeAgentSdkQueryRunnerLiveLayer,
} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import {
CodexAppServerClientFactory,
codexAppServerClientFactoryFromSettingsLayer,
} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
import {
CursorAgentSdkRunner,
cursorAgentSdkRunnerLiveLayer,
} from "../../orchestration-v2/Adapters/CursorAgentSdk.ts";
import { IdAllocatorV2, layer as idAllocatorLayer } from "../../orchestration-v2/IdAllocator.ts";
export type ProviderOrchestrationAdapterInfrastructure =
| ClaudeAgentSdkQueryRunner
| CodexAppServerClientFactory
| CursorAgentSdkRunner
| IdAllocatorV2;
/** Infrastructure shared by the V2 adapters materialized inside provider instances. */
export const ProviderOrchestrationAdapterInfrastructureLive = Layer.mergeAll(
claudeAgentSdkQueryRunnerLiveLayer,
codexAppServerClientFactoryFromSettingsLayer,
cursorAgentSdkRunnerLiveLayer,
idAllocatorLayer,
);
@@ -659,6 +659,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
streamChanges: Stream.empty,
},
adapter: {} as ProviderInstance["adapter"],
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const instanceRegistryLayer = Layer.succeed(
@@ -701,6 +702,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
streamChanges: Stream.fromPubSub(changes),
},
adapter: {} as ProviderInstance["adapter"],
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const instanceRegistryLayer = Layer.succeed(
@@ -733,7 +735,435 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
assert.strictEqual(spawnCount > 0, true);
const config = yield* ServerConfig;
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
instanceId: cursorInstanceId,
});
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
...initialProvider.models,
]);
yield* PubSub.publish(changes, refreshedProvider);
let cachedProvider = yield* readProviderStatusCache(filePath);
for (
let attempt = 0;
attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt;
attempt += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
cachedProvider = yield* readProviderStatusCache(filePath);
}
assert.deepStrictEqual(cachedProvider, {
...refreshedProvider,
models: [...initialProvider.models],
});
}).pipe(Effect.provide(runtimeServices));
}),
);
it.effect("returns the cached provider list when a manual refresh fails", () =>
Effect.gen(function* () {
const codexDriver = ProviderDriverKind.make("codex");
const codexInstanceId = ProviderInstanceId.make("codex");
const cachedProvider = {
instanceId: codexInstanceId,
driver: codexDriver,
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-04-29T10:00:00.000Z",
version: "1.0.0",
models: [],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const instance = {
instanceId: codexInstanceId,
driverKind: codexDriver,
continuationIdentity: {
driverKind: codexDriver,
continuationKey: "codex:instance:codex",
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: codexDriver,
packageName: null,
}),
getSnapshot: Effect.succeed(cachedProvider),
refresh: Effect.die(new Error("simulated refresh failure")),
streamChanges: Stream.empty,
},
adapter: {} as ProviderInstance["adapter"],
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
PubSub.subscribe(pubsub),
),
});
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-refresh-failure-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
assert.deepStrictEqual(yield* registry.getProviders, [cachedProvider]);
assert.deepStrictEqual(yield* registry.refresh(codexDriver), [cachedProvider]);
assert.deepStrictEqual(yield* registry.refreshInstance(codexInstanceId), [
cachedProvider,
]);
}).pipe(Effect.provide(runtimeServices));
}),
);
it.effect("keeps consuming registry changes after one sync fails", () =>
Effect.gen(function* () {
const codexDriver = ProviderDriverKind.make("codex");
const codexInstanceId = ProviderInstanceId.make("codex");
const claudeDriver = ProviderDriverKind.make("claudeAgent");
const claudeInstanceId = ProviderInstanceId.make("claudeAgent");
const codexProvider = {
instanceId: codexInstanceId,
driver: codexDriver,
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-04-29T10:00:00.000Z",
version: "1.0.0",
models: [],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const claudeProvider = {
instanceId: claudeInstanceId,
driver: claudeDriver,
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
checkedAt: "2026-04-29T10:01:00.000Z",
version: "1.0.0",
models: [],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const makeInstance = (provider: ServerProvider): ProviderInstance => ({
instanceId: provider.instanceId,
driverKind: provider.driver,
continuationIdentity: {
driverKind: provider.driver,
continuationKey: `${provider.driver}:instance:${provider.instanceId}`,
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: provider.driver,
packageName: null,
}),
getSnapshot: Effect.succeed(provider),
refresh: Effect.succeed(provider),
streamChanges: Stream.empty,
},
adapter: {} as ProviderInstance["adapter"],
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
});
const codexInstance = makeInstance(codexProvider);
const claudeInstance = makeInstance(claudeProvider);
const changes = yield* PubSub.unbounded<void>();
const instancesRef = yield* Ref.make<ReadonlyArray<ProviderInstance>>([codexInstance]);
const failNextList = yield* Ref.make(false);
const wait = () => Effect.yieldNow;
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Ref.get(instancesRef).pipe(
Effect.map((instances) =>
instances.find((instance) => instance.instanceId === instanceId),
),
),
listInstances: Effect.gen(function* () {
const shouldFail = yield* Ref.get(failNextList);
if (shouldFail) {
yield* Ref.set(failNextList, false);
return yield* Effect.die(new Error("simulated registry list failure"));
}
return yield* Ref.get(instancesRef);
}),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.fromPubSub(changes),
subscribeChanges: PubSub.subscribe(changes),
});
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-sync-failure-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
assert.deepStrictEqual(yield* registry.getProviders, [codexProvider]);
yield* Ref.set(failNextList, true);
yield* PubSub.publish(changes, undefined);
yield* Ref.set(instancesRef, [codexInstance, claudeInstance]);
yield* PubSub.publish(changes, undefined);
let providers = yield* registry.getProviders;
for (
let attempt = 0;
attempt < 50 &&
!providers.some((provider) => provider.instanceId === claudeInstanceId);
attempt += 1
) {
yield* wait();
providers = yield* registry.getProviders;
}
assert.deepStrictEqual(
providers.map((provider) => provider.instanceId).toSorted(),
[codexInstanceId, claudeInstanceId].toSorted(),
);
}).pipe(Effect.provide(runtimeServices));
}),
);
// This test intentionally avoids `mockCommandSpawnerLayer` so the real
// `probeCodexAppServerProvider` path runs — including the full
// `codex app-server` RPC handshake via `CodexClient.layerChildProcess`.
// We point `binaryPath` at a name that cannot exist on any machine so
// the real `ChildProcessSpawner` deterministically returns ENOENT; the
// probe wraps that as `CodexAppServerSpawnError` and
// `checkCodexProviderStatus` turns it into the user-visible "not
// installed" error snapshot. If the aggregator's `syncLiveSources`
// breaks — the `codex_personal`-never-probes bug we are guarding
// against — that snapshot never lands in `getProviders` and the
// assertions below fail.
it.effect("propagates real Codex probe failures to the aggregator at boot", () =>
Effect.gen(function* () {
const missingBinary = `t3code_codex_missing_`;
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(encodedDefaultServerSettings, {
providers: {
// Disable every built-in probe that would otherwise spawn
// on the CI host. `enabled: false` short-circuits each
// driver's probe *before* it touches the spawner, so the
// test environment stays isolated from the dev
// machine's PATH.
codex: { enabled: false },
claudeAgent: { enabled: false },
cursor: { enabled: false },
grok: { enabled: false },
opencode: { enabled: false },
},
// `providerInstances` keys are branded `ProviderInstanceId`;
// the branded index signature rejects plain string literals
// at the TS level even though the runtime schema happily
// accepts + decodes them. Cast the patch to `unknown` so
// the `Schema.decodeSync` below does the real validation.
providerInstances: {
// Matches the shape the user had in `.t3/dev/settings.json`
// when the bug was reported: a custom enabled Codex instance
// pointing at a binary the server has to actually spawn.
codex_personal: {
driver: "codex",
displayName: "Codex Personal",
enabled: true,
config: {
binaryPath: missingBinary,
homePath: `/tmp/${missingBinary}_home`,
},
},
} as unknown as ContractServerSettings["providerInstances"],
}),
),
);
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
Layer.provideMerge(OpenCodeRuntimeLive),
// NO spawner mock — `ChildProcessSpawner` is supplied by the
// outer `NodeServices.layer` on `it.layer(...)` and will
// genuinely spawn a subprocess. The missing-binary ENOENT is
// what exercises the same failure mode as a misconfigured
// production `binaryPath`.
);
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
Scope.provide(scope),
);
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
let providers = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
providers.find((provider) => provider.instanceId === "codex_personal")?.status !==
"error";
attempts += 1
) {
yield* Effect.yieldNow;
providers = yield* registry.getProviders;
}
const codexPersonal = providers.find(
(provider) => provider.instanceId === "codex_personal",
);
assert.notStrictEqual(
codexPersonal,
undefined,
`Expected the aggregator to know about codex_personal; instead saw: ${providers
.map((provider) => provider.instanceId)
.join(", ")}`,
);
assert.strictEqual(
codexPersonal?.status,
"error",
"Real Codex probe against a missing binary should surface as 'error' in the aggregator",
);
assert.strictEqual(codexPersonal?.installed, false);
assert.strictEqual(
codexPersonal?.message,
"Codex CLI (`codex`) is not installed or not on PATH.",
);
}).pipe(Effect.provide(runtimeServices));
}),
);
// Guards the second half of the reported bug: changing
// `providers.codex.binaryPath` in settings must tear down the live
// instance and rebuild it so a fresh probe runs with the new binary.
// This test drives the real settings stream → registry reconcile →
// aggregator sync pipeline and asserts that `getProviders` reflects
// the new background probe's outcome.
//
it.effect("re-probes when settings change the codex binaryPath", () =>
Effect.gen(function* () {
const firstMissing = `t3code_codex_first_`;
const secondMissing = `t3code_codex_second_`;
const spawnedCommands: Array<string> = [];
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(encodedDefaultServerSettings, {
providers: {
codex: { enabled: true, binaryPath: firstMissing },
claudeAgent: { enabled: false },
cursor: { enabled: false },
grok: { enabled: false },
opencode: { enabled: false },
},
}),
),
);
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
Layer.provideMerge(TestHttpClientLive),
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
Layer.provideMerge(OpenCodeRuntimeLive),
Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>
ChildProcessSpawner.make((command) => {
spawnedCommands.push((command as { readonly command: string }).command);
return spawner.spawn(command);
}),
),
Layer.provideMerge(NodeServices.layer),
);
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
Scope.provide(scope),
);
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
// Boot-time probe: the default codex instance is enabled with
// `firstMissing`, so the real spawner yields ENOENT and the
// snapshot should be `status: "error"`.
let initialProviders = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
initialProviders.find((provider) => provider.instanceId === "codex")?.status !==
"error";
attempts += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
initialProviders = yield* registry.getProviders;
}
const initialCodex = initialProviders.find(
(provider) => provider.instanceId === "codex",
);
assert.strictEqual(initialCodex?.status, "error");
assert.strictEqual(initialCodex?.installed, false);
assert.deepStrictEqual(spawnedCommands, [firstMissing]);
// Drive a settings change. The Hydration layer's
// `SettingsWatcherLive` consumes this via `streamChanges`,
// calls `reconcile`, which rebuilds the codex instance (the
// envelope changed because `binaryPath` differs → `entryEqual`
// is false). The registry's `Stream.runForEach(
// instanceRegistry.streamChanges, () => syncLiveSources)`
// fires `syncLiveSources`, which subscribes and launches a fresh
// background refresh on the rebuilt instance.
yield* serverSettings.updateSettings({
providers: {
codex: { enabled: true, binaryPath: secondMissing },
},
});
// Poll until the injected process boundary observes the new
// executable. This verifies the public settings-to-probe behavior
// without depending on timestamps assigned by TestClock.
const refreshed = yield* Effect.gen(function* () {
for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) {
const providers = yield* registry.getProviders;
+4 -2
View File
@@ -30,7 +30,8 @@ import type * as Effect from "effect/Effect";
import type * as Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import type * as TextGeneration from "../textGeneration/TextGeneration.ts";
import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts";
import type { ProviderAdapterV2Shape } from "../orchestration-v2/ProviderAdapter.ts";
import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
@@ -70,7 +71,8 @@ export interface ProviderInstance {
readonly enabled: boolean;
readonly snapshot: ServerProviderShape;
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly textGeneration: TextGeneration.TextGeneration["Service"];
readonly orchestrationAdapter: ProviderAdapterV2Shape;
readonly textGeneration: TextGenerationShape;
}
export interface ProviderContinuationIdentity {
@@ -20,6 +20,7 @@
*
* @module provider/builtInDrivers
*/
import { AcpRegistryDriver, type AcpRegistryDriverEnv } from "./Drivers/AcpRegistryDriver.ts";
import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts";
import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";
import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts";
@@ -33,6 +34,7 @@ import type { AnyProviderDriver } from "./ProviderDriver.ts";
* layer must provide every service in this union.
*/
export type BuiltInDriversEnv =
| AcpRegistryDriverEnv
| ClaudeDriverEnv
| CodexDriverEnv
| CursorDriverEnv
@@ -50,4 +52,5 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
CursorDriver,
GrokDriver,
OpenCodeDriver,
AcpRegistryDriver,
];
@@ -39,6 +39,7 @@ const makeStubInstance = (
enabled: true,
snapshot: {} as ProviderInstance["snapshot"],
adapter: {} as ProviderInstance["adapter"],
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
textGeneration,
}) satisfies ProviderInstance;
+41 -51
View File
@@ -55,7 +55,8 @@ import {
RpcClientId,
EnvironmentAuthorizationError,
ThreadId,
type OrchestrationV2ThreadShell,
type TerminalAttachStreamEvent,
type TerminalError,
type TerminalEvent,
type TerminalMetadataStreamEvent,
WS_METHODS,
@@ -80,6 +81,7 @@ import {
ThreadManagementService,
withCreationProvenance,
} from "./orchestration-v2/ThreadManagementService.ts";
import { shellStreamItemFromSnapshot } from "./orchestration-v2/ShellStream.ts";
import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts";
import {
observeRpcEffect as instrumentRpcEffect,
@@ -973,7 +975,7 @@ const makeWsRpcLayer = (
"orchestration_v2.thread_id": input.threadId,
});
const projection = yield* threadManagement.getThreadProjection(input.threadId).pipe(
const snapshot = yield* threadManagement.getThreadSnapshot(input.threadId).pipe(
Effect.mapError(
(cause) =>
new OrchestrationV2GetThreadProjectionError({
@@ -983,37 +985,29 @@ const makeWsRpcLayer = (
}),
),
);
const snapshotSequence = yield* threadManagement
.getThreadEventSequence(input.threadId)
const { projection, snapshotSequence } = snapshot;
const liveStream = threadManagement
.streamStoredEventsFrom({
threadId: input.threadId,
afterSequence: snapshotSequence,
})
.pipe(
Effect.mapError(
Stream.map((stored) => ({
kind: "event" as const,
sequence: stored.sequence,
event: stored.event,
})),
Stream.mapError(
(cause) =>
new OrchestrationV2GetThreadProjectionError({
threadId: input.threadId,
message: `Failed to load orchestration V2 sequence for thread ${input.threadId}`,
message: `Failed while streaming orchestration V2 thread ${input.threadId}`,
cause,
}),
),
);
const liveStream = threadManagement.streamStoredEvents.pipe(
Stream.filter((stored) => stored.event.threadId === input.threadId),
Stream.filter((stored) => stored.sequence > snapshotSequence),
Stream.map((stored) => ({
kind: "event" as const,
sequence: stored.sequence,
event: stored.event,
})),
Stream.mapError(
(cause) =>
new OrchestrationV2GetThreadProjectionError({
threadId: input.threadId,
message: `Failed while streaming orchestration V2 thread ${input.threadId}`,
cause,
}),
),
);
return Stream.concat(
Stream.make({
kind: "snapshot" as const,
@@ -1037,35 +1031,31 @@ const makeWsRpcLayer = (
),
);
const liveStream = threadManagement.streamDomainEvents.pipe(
Stream.mapEffect((event) =>
threadManagement.getShellSnapshot().pipe(
Effect.map(
(nextSnapshot) =>
nextSnapshot.threads.find((thread) => thread.id === event.threadId) ?? null,
),
Effect.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
message: `Failed while streaming orchestration V2 shell thread ${event.threadId}`,
cause,
}),
const liveStream = threadManagement
.streamStoredEventsFrom({ afterSequence: snapshot.snapshotSequence })
.pipe(
Stream.mapEffect((stored) =>
threadManagement.getShellSnapshot().pipe(
Effect.map((nextSnapshot) =>
shellStreamItemFromSnapshot({ stored, snapshot: nextSnapshot }),
),
Effect.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
message: `Failed while streaming orchestration V2 shell thread ${stored.event.threadId}`,
cause,
}),
),
),
),
),
Stream.filter((thread): thread is OrchestrationV2ThreadShell => thread !== null),
Stream.map((thread) => ({
kind: "thread.updated" as const,
thread,
})),
Stream.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
message: "Failed while streaming orchestration V2 shell",
cause,
}),
),
);
Stream.mapError(
(cause) =>
new OrchestrationV2GetShellSnapshotError({
message: "Failed while streaming orchestration V2 shell",
cause,
}),
),
);
return Stream.concat(
Stream.make({
+17 -4
View File
@@ -676,7 +676,7 @@ function buildStreamTimeline(logEntries: ReadonlyArray<LogEntry>): ReadonlyArray
title: event.type,
subtitle: compactId(event.threadId),
sequence: value.sequence,
status: stringifyShort(payload.status) ?? stringifyShort(event.provider) ?? "received",
status: stringifyShort(payload.status) ?? stringifyShort(event.driver) ?? "received",
body: readText(payload, ["text", "title", "detail", "markdown"]),
raw: value,
};
@@ -1721,7 +1721,16 @@ function OrchestrationV2DebugRoute() {
unsubscribeRef.current = null;
}, []);
useEffect(() => clearSubscription, [clearSubscription]);
setShellThreadsById((current) => {
const next = new Map(current);
if (item.kind === "thread.removed") {
next.delete(item.threadId);
return next;
}
next.set(item.thread.id, item.thread);
return next;
});
}, [shellSubscription.data]);
useEffect(() => {
shellUnsubscribeRef.current = api.subscribeShell((item) => {
@@ -3296,7 +3305,8 @@ function workLogRowContent(item: OrchestrationV2TurnItem): WorkLogRowContent {
glyph: "⇄",
label: "Handoff",
preview:
clipOneLine(item.summary, 120) ?? `${item.fromProviders.join(", ")} → ${item.toProvider}`,
clipOneLine(item.summary, 120) ??
`${item.fromProviderInstanceIds.join(", ")} → ${item.toProviderInstanceId}`,
tone: "muted",
};
case "fork":
@@ -3749,7 +3759,10 @@ function ChatItem(props: {
return (
<ChatSystemDivider
label="Handoff"
description={item.summary ?? `${item.fromProviders.join(", ")} → ${item.toProvider}`}
description={
item.summary ??
`${item.fromProviderInstanceIds.join(", ")} → ${item.toProviderInstanceId}`
}
timestamp={timestamp}
nowMs={nowMs}
/>
+41
View File
@@ -0,0 +1,41 @@
import * as Schema from "effect/Schema";
import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;
const CHAT_ATTACHMENT_ID_MAX_CHARS = 128;
export const ChatAttachmentId = TrimmedNonEmptyString.check(
Schema.isMaxLength(CHAT_ATTACHMENT_ID_MAX_CHARS),
Schema.isPattern(/^[a-z0-9_-]+$/i),
);
export type ChatAttachmentId = typeof ChatAttachmentId.Type;
export const ChatImageAttachment = Schema.Struct({
type: Schema.Literal("image"),
id: ChatAttachmentId,
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)),
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
});
export type ChatImageAttachment = typeof ChatImageAttachment.Type;
export const UploadChatImageAttachment = Schema.Struct({
type: Schema.Literal("image"),
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)),
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
dataUrl: TrimmedNonEmptyString.check(
Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
),
});
export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;
export const ChatAttachment = Schema.Union([ChatImageAttachment]);
export type ChatAttachment = typeof ChatAttachment.Type;
export const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);
export type UploadChatAttachment = typeof UploadChatAttachment.Type;
+3
View File
@@ -11,6 +11,9 @@ export * from "./terminal.ts";
export * from "./provider.ts";
export * from "./providerInstance.ts";
export * from "./providerRuntime.ts";
export * from "./providerPolicy.ts";
export * from "./modelSelection.ts";
export * from "./chatAttachment.ts";
export * from "./model.ts";
export * from "./keybindings.ts";
export * from "./server.ts";
+63
View File
@@ -0,0 +1,63 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
import { ProviderOptionSelections } from "./model.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
/**
* Selection of a model on a configured provider instance.
*
* `instanceId` is the routing key. The provider driver, credentials,
* environment, and continuation identity are resolved by the provider
* instance registry rather than encoded into the selection itself.
*/
const ModelSelectionWire = Schema.Struct({
instanceId: ProviderInstanceId,
model: TrimmedNonEmptyString,
options: Schema.optionalKey(ProviderOptionSelections),
});
const ModelSelectionSource = Schema.Struct({
provider: Schema.optional(Schema.Unknown),
instanceId: Schema.optional(Schema.Unknown),
model: Schema.Unknown,
options: Schema.optional(Schema.Unknown),
});
/**
* The decoder still accepts the historical `{ provider, model }` shape while
* V1 persistence remains readable. Runtime code only receives the canonical
* instance-based representation.
*/
export const ModelSelection = ModelSelectionSource.pipe(
Schema.decodeTo(
ModelSelectionWire,
SchemaTransformation.transformOrFail({
decode: (raw) => {
const instanceIdSource =
raw.instanceId !== undefined
? raw.instanceId
: typeof raw.provider === "string"
? raw.provider
: undefined;
const base: Record<string, unknown> = {
instanceId: instanceIdSource,
model: raw.model,
};
if (raw.options !== undefined) base.options = raw.options;
return Effect.succeed(base as typeof ModelSelectionWire.Encoded);
},
encode: (value) => {
const base: Record<string, unknown> = {
instanceId: value.instanceId,
model: value.model,
};
if (value.options !== undefined) base.options = value.options;
return Effect.succeed(base as typeof ModelSelectionSource.Encoded);
},
}),
),
);
export type ModelSelection = typeof ModelSelection.Type;
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more