feat(orchestration-v2): support cross-provider handoff
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
f929f667f8
commit
404393a840
4 files changed
+699
-18
No files matched your search
@@ -52,6 +52,22 @@ export interface ContextHandoffServiceV2Shape {
|
||||
readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
}) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
|
||||
readonly prepareProviderHandoff: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly targetRunId: RunId;
|
||||
readonly transferId: NonNullable<OrchestrationV2ContextHandoff["transferId"]>;
|
||||
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
|
||||
readonly toProviderThreadId: ProviderThreadId;
|
||||
readonly fromProvider: ProviderKind;
|
||||
readonly toProvider: ProviderKind;
|
||||
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
|
||||
readonly strategy: Extract<
|
||||
OrchestrationV2ContextHandoff["strategy"],
|
||||
"delta_since_target_last_seen" | "full_thread_summary"
|
||||
>;
|
||||
readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
}) => Effect.Effect<OrchestrationV2ContextHandoff, ContextHandoffServiceV2Error>;
|
||||
}
|
||||
|
||||
export class ContextHandoffServiceV2 extends Context.Service<
|
||||
@@ -107,12 +123,46 @@ function makeForkDeltaSummary(input: {
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function makeProviderHandoffSummary(input: {
|
||||
readonly fromProvider: ProviderKind;
|
||||
readonly toProvider: ProviderKind;
|
||||
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
|
||||
readonly strategy: Extract<
|
||||
OrchestrationV2ContextHandoff["strategy"],
|
||||
"delta_since_target_last_seen" | "full_thread_summary"
|
||||
>;
|
||||
readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
|
||||
}): string {
|
||||
const itemLines = input.items.flatMap((item) => {
|
||||
if (item.type === "handoff") {
|
||||
return [];
|
||||
}
|
||||
const line = summarizeDeltaItem(item);
|
||||
return line === null ? [] : [line];
|
||||
});
|
||||
return [
|
||||
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}`,
|
||||
`Covered app runs: ${input.coveredRunOrdinals.from}-${input.coveredRunOrdinals.to}`,
|
||||
"",
|
||||
"Canonical conversation context:",
|
||||
...(itemLines.length === 0 ? ["- No user-visible context items."] : itemLines),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function providerMessageWithContextHandoff(input: {
|
||||
readonly handoff: OrchestrationV2ContextHandoff;
|
||||
readonly userText: string;
|
||||
}): string {
|
||||
const label =
|
||||
input.handoff.strategy === "fork_delta_summary"
|
||||
? "merge_back / fork_delta_summary"
|
||||
: input.handoff.strategy;
|
||||
return [
|
||||
"Context handoff (merge_back / fork_delta_summary):",
|
||||
`Context handoff (${label}):`,
|
||||
input.handoff.summaryText,
|
||||
"",
|
||||
"User message:",
|
||||
@@ -218,9 +268,64 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi
|
||||
},
|
||||
);
|
||||
|
||||
const prepareProviderHandoff = Effect.fn(
|
||||
"orchestrationV2.contextHandoff.prepareProviderHandoff",
|
||||
)(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly targetRunId: RunId;
|
||||
readonly transferId: NonNullable<OrchestrationV2ContextHandoff["transferId"]>;
|
||||
readonly fromProviderThreadIds: ReadonlyArray<ProviderThreadId>;
|
||||
readonly toProviderThreadId: ProviderThreadId;
|
||||
readonly fromProvider: ProviderKind;
|
||||
readonly toProvider: ProviderKind;
|
||||
readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
|
||||
readonly strategy: Extract<
|
||||
OrchestrationV2ContextHandoff["strategy"],
|
||||
"delta_since_target_last_seen" | "full_thread_summary"
|
||||
>;
|
||||
readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
}) {
|
||||
const handoffId = yield* idAllocator.allocate
|
||||
.contextHandoff({
|
||||
threadId: input.threadId,
|
||||
fromProvider: input.fromProvider,
|
||||
toProvider: input.toProvider,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ContextHandoffPrepareError({
|
||||
threadId: input.threadId,
|
||||
targetRunId: input.targetRunId,
|
||||
fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
|
||||
toProviderThreadId: input.toProviderThreadId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
id: handoffId,
|
||||
transferId: input.transferId,
|
||||
threadId: input.threadId,
|
||||
targetRunId: input.targetRunId,
|
||||
fromProviderThreadIds: Array.from(input.fromProviderThreadIds),
|
||||
toProviderThreadId: input.toProviderThreadId,
|
||||
coveredRunOrdinals: input.coveredRunOrdinals,
|
||||
strategy: input.strategy,
|
||||
status: "ready",
|
||||
summaryMessageId: null,
|
||||
summaryText: makeProviderHandoffSummary(input),
|
||||
createdByProvider: null,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.createdAt,
|
||||
} satisfies OrchestrationV2ContextHandoff;
|
||||
});
|
||||
|
||||
return ContextHandoffServiceV2.of({
|
||||
prepare,
|
||||
prepareForkDelta,
|
||||
prepareProviderHandoff,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -318,6 +318,24 @@ function visibleDeltaRunOrdinals(
|
||||
};
|
||||
}
|
||||
|
||||
function rootProviderThreadsForProvider(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
provider: ModelSelection["instanceId"],
|
||||
): ReadonlyArray<OrchestrationV2ProviderThread> {
|
||||
return projection.providerThreads
|
||||
.filter(
|
||||
(providerThread) =>
|
||||
providerThread.provider === provider &&
|
||||
providerThread.appThreadId === projection.thread.id &&
|
||||
providerThread.ownerNodeId === null,
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
(right.lastRunOrdinal ?? 0) - (left.lastRunOrdinal ?? 0) ||
|
||||
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
|
||||
);
|
||||
}
|
||||
|
||||
const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(function* () {
|
||||
const checkpointService = yield* CheckpointServiceV2;
|
||||
const commandPolicy = yield* CommandPolicyV2;
|
||||
@@ -1645,6 +1663,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const now = yield* DateTime.now;
|
||||
const ordinal = nextRunOrdinal(projection);
|
||||
const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
|
||||
const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed");
|
||||
const isProviderSwitch =
|
||||
activeProviderThread !== undefined &&
|
||||
activeProviderThread.provider !== modelSelection.instanceId;
|
||||
if (isProviderSwitch && pendingMergeBackTransfer !== undefined) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Thread ${command.threadId} cannot switch providers while merge-back transfer ${pendingMergeBackTransfer.id} is pending.`,
|
||||
});
|
||||
}
|
||||
const sourceProjection =
|
||||
pendingForkTransfer === undefined
|
||||
? null
|
||||
@@ -1705,8 +1734,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
}
|
||||
}
|
||||
|
||||
const targetProviderThread = isProviderSwitch
|
||||
? rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0]
|
||||
: activeProviderThread;
|
||||
const providerSessionId =
|
||||
activeProviderThread?.providerSessionId ??
|
||||
targetProviderThread?.providerSessionId ??
|
||||
(yield* mapDispatchError(command)(
|
||||
idAllocator.allocate.providerSession({
|
||||
provider: modelSelection.provider,
|
||||
@@ -1794,7 +1826,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
}),
|
||||
),
|
||||
)
|
||||
: activeProviderThread === undefined
|
||||
: targetProviderThread === undefined
|
||||
? yield* session
|
||||
.ensureThread({
|
||||
threadId: command.threadId,
|
||||
@@ -1813,10 +1845,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
),
|
||||
)
|
||||
: Option.isSome(activeSession)
|
||||
? activeProviderThread
|
||||
? targetProviderThread
|
||||
: yield* session
|
||||
.resumeThread({
|
||||
providerThread: activeProviderThread,
|
||||
providerThread: targetProviderThread,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
@@ -1828,11 +1860,92 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
}),
|
||||
),
|
||||
);
|
||||
const providerSwitchCoveredRuns =
|
||||
!isProviderSwitch || latestCompletedRun === undefined
|
||||
? []
|
||||
: projection.runs.filter(
|
||||
(run) =>
|
||||
run.status === "completed" &&
|
||||
run.ordinal > (targetProviderThread?.lastRunOrdinal ?? 0) &&
|
||||
run.ordinal <= latestCompletedRun.ordinal,
|
||||
);
|
||||
const providerSwitchItems =
|
||||
providerSwitchCoveredRuns.length === 0
|
||||
? []
|
||||
: projection.turnItems.filter(
|
||||
(item) =>
|
||||
item.runId !== null &&
|
||||
providerSwitchCoveredRuns.some((run) => run.id === item.runId),
|
||||
);
|
||||
const providerSwitchTransferId =
|
||||
providerSwitchCoveredRuns.length === 0 || latestCompletedRun === undefined
|
||||
? null
|
||||
: yield* mapDispatchError(command)(
|
||||
idAllocator.allocate.contextTransfer({
|
||||
sourceThreadId: command.threadId,
|
||||
targetThreadId: command.threadId,
|
||||
type: "provider_handoff",
|
||||
}),
|
||||
);
|
||||
if (providerSwitchTransferId !== null) {
|
||||
yield* enforceCommandPolicy(command)(
|
||||
commandPolicy.ensureContextHandoff({
|
||||
commandId: command.commandId,
|
||||
threadId: command.threadId,
|
||||
provider: modelSelection.instanceId,
|
||||
capabilities: session.providerSession.capabilities,
|
||||
strategy: targetProviderThread === undefined ? "full_thread_summary" : "delta_context",
|
||||
}),
|
||||
);
|
||||
}
|
||||
const providerSwitchHandoff =
|
||||
providerSwitchTransferId === null || latestCompletedRun === undefined
|
||||
? null
|
||||
: yield* contextHandoffService
|
||||
.prepareProviderHandoff({
|
||||
threadId: command.threadId,
|
||||
targetRunId: runId,
|
||||
transferId: providerSwitchTransferId,
|
||||
fromProviderThreadIds: Array.from(
|
||||
new Set(
|
||||
providerSwitchCoveredRuns.flatMap((run) =>
|
||||
run.providerThreadId === null ? [] : [run.providerThreadId],
|
||||
),
|
||||
),
|
||||
),
|
||||
toProviderThreadId: ensuredProviderThread.id,
|
||||
fromProvider: latestCompletedRun.provider,
|
||||
toProvider: modelSelection.instanceId,
|
||||
coveredRunOrdinals: {
|
||||
from: providerSwitchCoveredRuns[0]!.ordinal,
|
||||
to: providerSwitchCoveredRuns.at(-1)!.ordinal,
|
||||
},
|
||||
strategy:
|
||||
targetProviderThread === undefined
|
||||
? "full_thread_summary"
|
||||
: "delta_since_target_last_seen",
|
||||
items: providerSwitchItems,
|
||||
createdAt: now,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const providerThread: OrchestrationV2ProviderThread = {
|
||||
...ensuredProviderThread,
|
||||
status: "active",
|
||||
firstRunOrdinal: ensuredProviderThread.firstRunOrdinal ?? ordinal,
|
||||
lastRunOrdinal: ordinal,
|
||||
handoffIds:
|
||||
providerSwitchHandoff === null
|
||||
? ensuredProviderThread.handoffIds
|
||||
: [...ensuredProviderThread.handoffIds, providerSwitchHandoff.id],
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
@@ -1969,7 +2082,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: mergeBackHandoff?.id ?? null,
|
||||
contextHandoffId: providerSwitchHandoff?.id ?? mergeBackHandoff?.id ?? null,
|
||||
};
|
||||
const attempt: OrchestrationV2RunAttempt = {
|
||||
id: attemptId,
|
||||
@@ -2035,12 +2148,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
attachments: command.attachments,
|
||||
};
|
||||
const handoffTurnItem: OrchestrationV2TurnItem | null =
|
||||
mergeBackHandoff === null
|
||||
providerSwitchHandoff === null && mergeBackHandoff === null
|
||||
? null
|
||||
: {
|
||||
id: idAllocator.derive.runSignalTurnItem({
|
||||
runId,
|
||||
signal: `context-handoff:${mergeBackHandoff.id}`,
|
||||
signal: `context-handoff:${(providerSwitchHandoff ?? mergeBackHandoff)!.id}`,
|
||||
}),
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
@@ -2051,18 +2164,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
parentItemId: null,
|
||||
ordinal: ordinal * 100 - 1,
|
||||
status: "completed",
|
||||
title: "Merge-back context",
|
||||
title: providerSwitchHandoff === null ? "Merge-back context" : "Provider handoff",
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "handoff",
|
||||
contextHandoffId: mergeBackHandoff.id,
|
||||
fromProviderThreadIds: mergeBackHandoff.fromProviderThreadIds,
|
||||
toProviderThreadId: mergeBackHandoff.toProviderThreadId,
|
||||
fromProviders: mergeBackSourceRun === null ? [] : [mergeBackSourceRun.provider],
|
||||
toProvider: modelSelection.provider,
|
||||
strategy: "fork_delta_summary",
|
||||
summary: mergeBackHandoff.summaryText,
|
||||
contextHandoffId: (providerSwitchHandoff ?? mergeBackHandoff)!.id,
|
||||
fromProviderThreadIds: (providerSwitchHandoff ?? mergeBackHandoff)!
|
||||
.fromProviderThreadIds,
|
||||
toProviderThreadId: (providerSwitchHandoff ?? mergeBackHandoff)!.toProviderThreadId,
|
||||
fromProviders:
|
||||
providerSwitchHandoff === null
|
||||
? mergeBackSourceRun === null
|
||||
? []
|
||||
: [mergeBackSourceRun.provider]
|
||||
: Array.from(new Set(providerSwitchCoveredRuns.map((run) => run.provider))),
|
||||
toProvider: modelSelection.instanceId,
|
||||
strategy: (providerSwitchHandoff ?? mergeBackHandoff)!.strategy,
|
||||
summary: (providerSwitchHandoff ?? mergeBackHandoff)!.summaryText,
|
||||
};
|
||||
const nativeForkResolution: OrchestrationV2ContextTransferResolution | null =
|
||||
pendingForkTransfer === undefined || providerThread.nativeThreadRef === null
|
||||
@@ -2111,6 +2230,63 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: providerThread,
|
||||
});
|
||||
if (
|
||||
providerSwitchTransferId !== null &&
|
||||
providerSwitchHandoff !== null &&
|
||||
latestCompletedRun !== undefined
|
||||
) {
|
||||
const transfer: OrchestrationV2ContextTransfer = {
|
||||
id: providerSwitchTransferId,
|
||||
type: "provider_handoff",
|
||||
sourceThreadId: command.threadId,
|
||||
targetThreadId: command.threadId,
|
||||
sourcePoint: contextSourcePointForRun(projection, latestCompletedRun),
|
||||
basePoint:
|
||||
targetProviderThread?.lastRunOrdinal === null ||
|
||||
targetProviderThread?.lastRunOrdinal === undefined
|
||||
? null
|
||||
: (() => {
|
||||
const baseRun = projection.runs.find(
|
||||
(run) => run.ordinal === targetProviderThread.lastRunOrdinal,
|
||||
);
|
||||
return baseRun === undefined
|
||||
? null
|
||||
: contextSourcePointForRun(projection, baseRun);
|
||||
})(),
|
||||
sourceProvider: latestCompletedRun.provider,
|
||||
targetProvider: modelSelection.instanceId,
|
||||
targetRunId: runId,
|
||||
status: "consumed",
|
||||
resolution: {
|
||||
strategy:
|
||||
providerSwitchHandoff.strategy === "full_thread_summary"
|
||||
? "portable_context"
|
||||
: "delta_context",
|
||||
contextHandoffId: providerSwitchHandoff.id,
|
||||
},
|
||||
createdBy: "user",
|
||||
error: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
consumedAt: now,
|
||||
};
|
||||
yield* emitEvent({
|
||||
type: "context-transfer.created",
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
provider: modelSelection.instanceId,
|
||||
occurredAt: now,
|
||||
payload: transfer,
|
||||
});
|
||||
yield* emitEvent({
|
||||
type: "context-handoff.updated",
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
provider: modelSelection.instanceId,
|
||||
occurredAt: now,
|
||||
payload: providerSwitchHandoff,
|
||||
});
|
||||
}
|
||||
if (mergeBackHandoff !== null) {
|
||||
yield* emitEvent({
|
||||
type: "context-handoff.updated",
|
||||
@@ -2253,10 +2429,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
}
|
||||
|
||||
const providerMessageText =
|
||||
mergeBackHandoff === null
|
||||
providerSwitchHandoff === null && mergeBackHandoff === null
|
||||
? command.text
|
||||
: providerMessageWithContextHandoff({
|
||||
handoff: mergeBackHandoff,
|
||||
handoff: (providerSwitchHandoff ?? mergeBackHandoff)!,
|
||||
userText: command.text,
|
||||
});
|
||||
yield* runExecution
|
||||
|
||||
@@ -180,6 +180,19 @@ export function makeOrchestratorV2ProviderReplayLayer<
|
||||
} = {},
|
||||
): Layer.Layer<OrchestratorV2, Error | MigrationError | PlatformError.PlatformError | SqlError> {
|
||||
const registryLayer = harness.makeProviderAdapterRegistryLayer(scenario.transcript);
|
||||
return makeOrchestratorV2ReplayLayerWithRegistry(scenario, registryLayer, options);
|
||||
}
|
||||
|
||||
export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
|
||||
scenario: Pick<OrchestratorV2ProviderReplayScenario, "name" | "runtimePolicyOverride">,
|
||||
registryLayer: Layer.Layer<ProviderAdapterRegistryV2, Error>,
|
||||
options: {
|
||||
readonly databaseLayer?: Layer.Layer<
|
||||
SqlClient.SqlClient,
|
||||
MigrationError | PlatformError.PlatformError | SqlError
|
||||
>;
|
||||
} = {},
|
||||
): Layer.Layer<OrchestratorV2, Error | MigrationError | PlatformError.PlatformError | SqlError> {
|
||||
const serverConfigLayer = Layer.effect(
|
||||
ServerConfig,
|
||||
makeReplayServerConfig(scenario.name).pipe(Effect.orDie),
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type ModelSelection,
|
||||
type OrchestrationV2Command,
|
||||
type OrchestrationV2ProviderCapabilities,
|
||||
type OrchestrationV2ProviderSession,
|
||||
type OrchestrationV2ProviderThread,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
type ProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ClaudeProviderCapabilitiesV2 } from "../Adapters/ClaudeAdapterV2.ts";
|
||||
import { CodexProviderCapabilitiesV2 } from "../Adapters/CodexAdapterV2.ts";
|
||||
import { OrchestratorV2 } from "../Orchestrator.ts";
|
||||
import {
|
||||
type ProviderAdapterV2Event,
|
||||
ProviderAdapterProtocolError,
|
||||
type ProviderAdapterV2Shape,
|
||||
} from "../ProviderAdapter.ts";
|
||||
import { makeLayer as makeProviderAdapterRegistryLayer } from "../ProviderAdapterRegistry.ts";
|
||||
import { CLAUDE_MODEL_SELECTION, CODEX_MODEL_SELECTION } from "./fixtures/shared.ts";
|
||||
import { makeOrchestratorV2ReplayLayerWithRegistry } from "./ProviderReplayHarness.ts";
|
||||
import { makeCheckpointWorkspace } from "./ReplayFixtureWorkspace.ts";
|
||||
|
||||
const threadId = ThreadId.make("thread:provider-switch");
|
||||
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";
|
||||
|
||||
interface CapturedTurn {
|
||||
readonly provider: ProviderKind;
|
||||
readonly providerThreadId: ProviderThreadId;
|
||||
readonly text: string;
|
||||
}
|
||||
|
||||
function unimplemented(provider: ProviderKind, detail: string) {
|
||||
return Effect.fail(new ProviderAdapterProtocolError({ provider, detail }));
|
||||
}
|
||||
|
||||
function makeTestAdapter(input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly capabilities: OrchestrationV2ProviderCapabilities;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly responseByRunOrdinal: Readonly<Record<number, string>>;
|
||||
readonly capturedTurns: Ref.Ref<ReadonlyArray<CapturedTurn>>;
|
||||
}): ProviderAdapterV2Shape {
|
||||
return {
|
||||
instanceId: input.instanceId,
|
||||
provider: input.provider,
|
||||
getCapabilities: () => Effect.succeed(input.capabilities),
|
||||
openSession: (sessionInput) =>
|
||||
Effect.gen(function* () {
|
||||
const events = yield* PubSub.unbounded<ProviderAdapterV2Event>();
|
||||
const now = yield* DateTime.now;
|
||||
const providerSession: OrchestrationV2ProviderSession = {
|
||||
id: sessionInput.providerSessionId,
|
||||
provider: input.provider,
|
||||
status: "ready",
|
||||
cwd: sessionInput.runtimePolicy.cwd ?? process.cwd(),
|
||||
model: input.modelSelection.model,
|
||||
capabilities: input.capabilities,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
lastError: null,
|
||||
};
|
||||
|
||||
return {
|
||||
instanceId: input.instanceId,
|
||||
provider: input.provider,
|
||||
providerSessionId: sessionInput.providerSessionId,
|
||||
providerSession,
|
||||
rawEvents: Stream.empty,
|
||||
events: Stream.fromPubSub(events),
|
||||
ensureThread: (threadInput) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = yield* DateTime.now;
|
||||
const nativeThreadId = `${input.provider}:${threadInput.threadId}`;
|
||||
return {
|
||||
id: ProviderThreadId.make(`provider-thread:${nativeThreadId}`),
|
||||
provider: input.provider,
|
||||
providerSessionId: sessionInput.providerSessionId,
|
||||
appThreadId: threadInput.threadId,
|
||||
ownerNodeId: null,
|
||||
nativeThreadRef: {
|
||||
provider: input.provider,
|
||||
nativeId: nativeThreadId,
|
||||
strength: "strong",
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle",
|
||||
firstRunOrdinal: null,
|
||||
lastRunOrdinal: null,
|
||||
handoffIds: [],
|
||||
forkedFrom: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
} satisfies OrchestrationV2ProviderThread;
|
||||
}),
|
||||
resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
|
||||
startTurn: (turnInput) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.update(input.capturedTurns, (turns) => [
|
||||
...turns,
|
||||
{
|
||||
provider: input.provider,
|
||||
providerThreadId: turnInput.providerThread.id,
|
||||
text: turnInput.message.text,
|
||||
},
|
||||
]);
|
||||
const eventTime = yield* DateTime.now;
|
||||
const providerTurnId = ProviderTurnId.make(
|
||||
`provider-turn:${input.provider}:${turnInput.runOrdinal}`,
|
||||
);
|
||||
const response =
|
||||
input.responseByRunOrdinal[turnInput.runOrdinal] ??
|
||||
`${input.provider} response for run ${turnInput.runOrdinal}`;
|
||||
const providerEvents: ReadonlyArray<ProviderAdapterV2Event> = [
|
||||
{
|
||||
type: "provider_turn.updated",
|
||||
provider: input.provider,
|
||||
providerTurn: {
|
||||
id: providerTurnId,
|
||||
providerThreadId: turnInput.providerThread.id,
|
||||
nodeId: turnInput.rootNodeId,
|
||||
runAttemptId: turnInput.attemptId,
|
||||
nativeTurnRef: {
|
||||
provider: input.provider,
|
||||
nativeId: `native-turn:${turnInput.runOrdinal}`,
|
||||
strength: "strong",
|
||||
},
|
||||
ordinal: turnInput.runOrdinal,
|
||||
status: "completed",
|
||||
startedAt: eventTime,
|
||||
completedAt: eventTime,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn_item.updated",
|
||||
provider: input.provider,
|
||||
turnItem: {
|
||||
id: TurnItemId.make(
|
||||
`turn-item:${input.provider}:${turnInput.runOrdinal}:assistant`,
|
||||
),
|
||||
threadId: turnInput.threadId,
|
||||
runId: turnInput.runId,
|
||||
nodeId: turnInput.rootNodeId,
|
||||
providerThreadId: turnInput.providerThread.id,
|
||||
providerTurnId,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: turnInput.runOrdinal * 100 + 1,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: eventTime,
|
||||
completedAt: eventTime,
|
||||
updatedAt: eventTime,
|
||||
type: "assistant_message",
|
||||
messageId: MessageId.make(
|
||||
`message:${input.provider}:${turnInput.runOrdinal}:assistant`,
|
||||
),
|
||||
text: response,
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.terminal",
|
||||
provider: input.provider,
|
||||
providerTurnId,
|
||||
status: "completed",
|
||||
},
|
||||
];
|
||||
for (const event of providerEvents) {
|
||||
yield* PubSub.publish(events, event);
|
||||
}
|
||||
}),
|
||||
steerTurn: () => Effect.void,
|
||||
interruptTurn: () => Effect.void,
|
||||
respondToRuntimeRequest: () => Effect.void,
|
||||
readThreadSnapshot: () =>
|
||||
unimplemented(input.provider, "readThreadSnapshot unused in provider switch test"),
|
||||
rollbackThread: () =>
|
||||
unimplemented(input.provider, "rollbackThread unused in provider switch test"),
|
||||
forkThread: () =>
|
||||
unimplemented(input.provider, "forkThread unused in provider switch test"),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
for (let attempt = 0; attempt < 1_000; attempt += 1) {
|
||||
const projection = yield* orchestrator.getThreadProjection(threadId);
|
||||
if (
|
||||
projection.runs.every(
|
||||
(run) => !["queued", "starting", "running", "waiting"].includes(run.status),
|
||||
)
|
||||
) {
|
||||
return projection;
|
||||
}
|
||||
yield* Effect.sleep("5 millis");
|
||||
}
|
||||
return yield* Effect.die(new Error("Provider switch test timed out waiting for idle"));
|
||||
});
|
||||
|
||||
describe("orchestration v2 provider switching", () => {
|
||||
it("switches Codex to Claude and returns to the original Codex thread with handoffs", async () => {
|
||||
const cwd = await makeCheckpointWorkspace("provider-switch");
|
||||
const capturedTurns = await Effect.runPromise(Ref.make<ReadonlyArray<CapturedTurn>>([]));
|
||||
const registryLayer = makeProviderAdapterRegistryLayer([
|
||||
makeTestAdapter({
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
provider: "codex",
|
||||
capabilities: CodexProviderCapabilitiesV2,
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
responseByRunOrdinal: {
|
||||
1: "codex before switch",
|
||||
3: "codex after return",
|
||||
},
|
||||
capturedTurns,
|
||||
}),
|
||||
makeTestAdapter({
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
provider: "claudeAgent",
|
||||
capabilities: ClaudeProviderCapabilitiesV2,
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
responseByRunOrdinal: { 2: "claude switched response" },
|
||||
capturedTurns,
|
||||
}),
|
||||
]);
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("command:provider-switch:create"),
|
||||
threadId,
|
||||
projectId,
|
||||
title: "Provider switch",
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: CommandId.make("command:provider-switch:codex"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:provider-switch:codex"),
|
||||
text: firstPrompt,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: CommandId.make("command:provider-switch:claude"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:provider-switch:claude"),
|
||||
text: claudePrompt,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: CommandId.make("command:provider-switch:return"),
|
||||
threadId,
|
||||
messageId: MessageId.make("message:provider-switch:return"),
|
||||
text: returnPrompt,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestrationV2Command>;
|
||||
|
||||
try {
|
||||
const projection = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
yield* orchestrator.dispatch(commands[0]!);
|
||||
yield* orchestrator.dispatch(commands[1]!);
|
||||
yield* waitForIdle();
|
||||
yield* orchestrator.dispatch(commands[2]!);
|
||||
yield* waitForIdle();
|
||||
yield* orchestrator.dispatch(commands[3]!);
|
||||
return yield* waitForIdle();
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeOrchestratorV2ReplayLayerWithRegistry(
|
||||
{
|
||||
name: "provider-switch",
|
||||
runtimePolicyOverride: {
|
||||
cwd,
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "readOnly",
|
||||
access: { type: "fullAccess" },
|
||||
networkAccess: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
registryLayer,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const turns = await Effect.runPromise(Ref.get(capturedTurns));
|
||||
|
||||
assert.deepEqual(
|
||||
projection.runs.map((run) => [run.provider, run.status]),
|
||||
[
|
||||
["codex", "completed"],
|
||||
["claudeAgent", "completed"],
|
||||
["codex", "completed"],
|
||||
],
|
||||
);
|
||||
assert.lengthOf(projection.providerThreads, 2);
|
||||
assert.equal(projection.runs[0]?.providerThreadId, projection.runs[2]?.providerThreadId);
|
||||
assert.notEqual(projection.runs[0]?.providerThreadId, projection.runs[1]?.providerThreadId);
|
||||
assert.deepEqual(
|
||||
projection.contextHandoffs.map((handoff) => handoff.strategy),
|
||||
["full_thread_summary", "delta_since_target_last_seen"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
projection.contextTransfers.map((transfer) => [
|
||||
transfer.type,
|
||||
transfer.status,
|
||||
transfer.resolution?.strategy,
|
||||
]),
|
||||
[
|
||||
["provider_handoff", "consumed", "portable_context"],
|
||||
["provider_handoff", "consumed", "delta_context"],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
projection.turnItems
|
||||
.filter((item) => item.type === "user_message")
|
||||
.map((item) => item.text),
|
||||
[firstPrompt, claudePrompt, returnPrompt],
|
||||
);
|
||||
assert.deepEqual(
|
||||
projection.providerThreads.map((providerThread) => [
|
||||
providerThread.provider,
|
||||
providerThread.status,
|
||||
providerThread.handoffIds.length,
|
||||
]),
|
||||
[
|
||||
["codex", "idle", 1],
|
||||
["claudeAgent", "idle", 1],
|
||||
],
|
||||
);
|
||||
assert.equal(turns[0]?.text, firstPrompt);
|
||||
assert.include(turns[1]?.text ?? "", "Context handoff (full_thread_summary):");
|
||||
assert.include(turns[1]?.text ?? "", "codex before switch");
|
||||
assert.include(turns[1]?.text ?? "", claudePrompt);
|
||||
assert.include(turns[2]?.text ?? "", "Context handoff (delta_since_target_last_seen):");
|
||||
assert.include(turns[2]?.text ?? "", "claude switched response");
|
||||
assert.include(turns[2]?.text ?? "", returnPrompt);
|
||||
assert.notInclude(turns[2]?.text ?? "", "codex before switch");
|
||||
assert.equal(turns[0]?.providerThreadId, turns[2]?.providerThreadId);
|
||||
} finally {
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.remove(cwd, { recursive: true, force: true });
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user