Add V2 command capability policy
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
81a47cfe19
commit
885bde7c3d
7 files changed
+564
-43
No files matched your search
@@ -0,0 +1,187 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { CommandId, type OrchestrationV2ProviderCapabilities, ThreadId } from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
||||
import {
|
||||
CommandPolicyCapabilityUnsupportedError,
|
||||
CommandPolicyV2,
|
||||
layer as commandPolicyLayer,
|
||||
} from "./CommandPolicy.ts";
|
||||
|
||||
const commandId = CommandId.make("command-policy-test");
|
||||
const threadId = ThreadId.make("command-policy-thread");
|
||||
|
||||
const baseCapabilities: OrchestrationV2ProviderCapabilities = CodexProviderCapabilitiesV2;
|
||||
|
||||
function capabilities(
|
||||
override: (current: OrchestrationV2ProviderCapabilities) => OrchestrationV2ProviderCapabilities,
|
||||
): OrchestrationV2ProviderCapabilities {
|
||||
return override(baseCapabilities);
|
||||
}
|
||||
|
||||
const layer = it.layer(commandPolicyLayer);
|
||||
|
||||
layer("CommandPolicyV2", (it) => {
|
||||
it.effect("prefers direct active steering when the provider supports it", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
const result = yield* policy.decideSteeringExecution({
|
||||
commandId,
|
||||
threadId,
|
||||
provider: "codex",
|
||||
capabilities: baseCapabilities,
|
||||
});
|
||||
|
||||
assert.equal(result, "active_steering");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses interrupt-and-restart steering when direct steering is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
const result = yield* policy.decideSteeringExecution({
|
||||
commandId,
|
||||
threadId,
|
||||
provider: "codex",
|
||||
capabilities: capabilities((current) => ({
|
||||
...current,
|
||||
turns: {
|
||||
...current.turns,
|
||||
supportsActiveSteering: false,
|
||||
supportsInterrupt: true,
|
||||
supportsSteeringByInterruptRestart: true,
|
||||
},
|
||||
})),
|
||||
});
|
||||
|
||||
assert.equal(result, "interrupt_restart");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns typed capability errors for unsupported active steering", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
const error = yield* policy
|
||||
.decideSteeringExecution({
|
||||
commandId,
|
||||
threadId,
|
||||
provider: "codex",
|
||||
capabilities: capabilities((current) => ({
|
||||
...current,
|
||||
turns: {
|
||||
...current.turns,
|
||||
supportsActiveSteering: false,
|
||||
supportsInterrupt: false,
|
||||
supportsSteeringByInterruptRestart: false,
|
||||
},
|
||||
})),
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, CommandPolicyCapabilityUnsupportedError);
|
||||
assert.equal(error.capability, "active_steering");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("guards native fork behind fork and identity capabilities", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
const error = yield* policy
|
||||
.ensureNativeFork({
|
||||
commandId,
|
||||
threadId,
|
||||
provider: "codex",
|
||||
fromSpecificTurn: true,
|
||||
capabilities: capabilities((current) => ({
|
||||
...current,
|
||||
identity: {
|
||||
...current.identity,
|
||||
nativeThreadIds: "weak",
|
||||
},
|
||||
})),
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, CommandPolicyCapabilityUnsupportedError);
|
||||
assert.equal(error.capability, "native_fork");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("guards rollback behind provider rollback snapshot support", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
const error = yield* policy
|
||||
.ensureRollback({
|
||||
commandId,
|
||||
threadId,
|
||||
provider: "codex",
|
||||
capabilities: capabilities((current) => ({
|
||||
...current,
|
||||
checkpointing: {
|
||||
...current.checkpointing,
|
||||
providerRollbackReturnsSnapshot: false,
|
||||
},
|
||||
})),
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, CommandPolicyCapabilityUnsupportedError);
|
||||
assert.equal(error.capability, "rollback_snapshot");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("guards fork-delta handoff behind context handoff capabilities", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
const error = yield* policy
|
||||
.ensureContextHandoff({
|
||||
commandId,
|
||||
threadId,
|
||||
provider: "codex",
|
||||
strategy: "fork_delta_context",
|
||||
capabilities: capabilities((current) => ({
|
||||
...current,
|
||||
context: {
|
||||
...current.context,
|
||||
supportsDeltaHandoff: false,
|
||||
},
|
||||
})),
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, CommandPolicyCapabilityUnsupportedError);
|
||||
assert.equal(error.capability, "context_handoff");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("guards queued turns behind queued-message support", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* CommandPolicyV2;
|
||||
|
||||
const error = yield* policy
|
||||
.ensureQueuedMessages({
|
||||
commandId,
|
||||
threadId,
|
||||
provider: "codex",
|
||||
capabilities: capabilities((current) => ({
|
||||
...current,
|
||||
turns: {
|
||||
...current.turns,
|
||||
supportsQueuedMessages: false,
|
||||
},
|
||||
})),
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, CommandPolicyCapabilityUnsupportedError);
|
||||
assert.equal(error.capability, "queued_messages");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -8,8 +8,7 @@ import {
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Schema } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import { Context, Effect, Layer, Schema } from "effect";
|
||||
|
||||
export const MessageDispatchDecisionV2 = Schema.Union([
|
||||
Schema.Struct({
|
||||
@@ -38,6 +37,23 @@ export const MessageDispatchDecisionV2 = Schema.Union([
|
||||
]);
|
||||
export type MessageDispatchDecisionV2 = typeof MessageDispatchDecisionV2.Type;
|
||||
|
||||
export const SteeringExecutionPolicyV2 = Schema.Literals(["active_steering", "interrupt_restart"]);
|
||||
export type SteeringExecutionPolicyV2 = typeof SteeringExecutionPolicyV2.Type;
|
||||
|
||||
export const CommandPolicyCapability = Schema.Literals([
|
||||
"queued_messages",
|
||||
"active_steering",
|
||||
"interrupt",
|
||||
"interrupt_restart_steering",
|
||||
"native_fork",
|
||||
"fork_from_turn",
|
||||
"rollback",
|
||||
"rollback_snapshot",
|
||||
"context_handoff",
|
||||
"strong_terminal_status",
|
||||
]);
|
||||
export type CommandPolicyCapability = typeof CommandPolicyCapability.Type;
|
||||
|
||||
export class CommandPolicyMessageDispatchError extends Schema.TaggedErrorClass<CommandPolicyMessageDispatchError>()(
|
||||
"CommandPolicyMessageDispatchError",
|
||||
{
|
||||
@@ -65,12 +81,35 @@ export class CommandPolicyUnsupportedError extends Schema.TaggedErrorClass<Comma
|
||||
}
|
||||
}
|
||||
|
||||
export class CommandPolicyCapabilityUnsupportedError extends Schema.TaggedErrorClass<CommandPolicyCapabilityUnsupportedError>()(
|
||||
"CommandPolicyCapabilityUnsupportedError",
|
||||
{
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
provider: ProviderKind,
|
||||
capability: CommandPolicyCapability,
|
||||
detail: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.provider} cannot satisfy ${this.capability} for command ${this.commandId}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const CommandPolicyV2Error = Schema.Union([
|
||||
CommandPolicyMessageDispatchError,
|
||||
CommandPolicyUnsupportedError,
|
||||
CommandPolicyCapabilityUnsupportedError,
|
||||
]);
|
||||
export type CommandPolicyV2Error = typeof CommandPolicyV2Error.Type;
|
||||
|
||||
interface CapabilityCheckInput {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly capabilities: OrchestrationV2ProviderCapabilities;
|
||||
}
|
||||
|
||||
export interface CommandPolicyV2Shape {
|
||||
readonly decideMessageDispatch: (input: {
|
||||
readonly commandId: CommandId;
|
||||
@@ -83,8 +122,240 @@ export interface CommandPolicyV2Shape {
|
||||
| { readonly type: "start_immediately" };
|
||||
readonly capabilities: OrchestrationV2ProviderCapabilities;
|
||||
}) => Effect.Effect<MessageDispatchDecisionV2, CommandPolicyV2Error>;
|
||||
readonly ensureQueuedMessages: (
|
||||
input: CapabilityCheckInput,
|
||||
) => Effect.Effect<void, CommandPolicyV2Error>;
|
||||
readonly decideSteeringExecution: (
|
||||
input: CapabilityCheckInput,
|
||||
) => Effect.Effect<SteeringExecutionPolicyV2, CommandPolicyV2Error>;
|
||||
readonly ensureInterrupt: (
|
||||
input: CapabilityCheckInput,
|
||||
) => Effect.Effect<void, CommandPolicyV2Error>;
|
||||
readonly ensureNativeFork: (
|
||||
input: CapabilityCheckInput & {
|
||||
readonly fromSpecificTurn: boolean;
|
||||
},
|
||||
) => Effect.Effect<void, CommandPolicyV2Error>;
|
||||
readonly ensureRollback: (
|
||||
input: CapabilityCheckInput,
|
||||
) => Effect.Effect<void, CommandPolicyV2Error>;
|
||||
readonly ensureContextHandoff: (
|
||||
input: CapabilityCheckInput & {
|
||||
readonly strategy: "fork_delta_context" | "delta_context" | "full_thread_summary";
|
||||
},
|
||||
) => Effect.Effect<void, CommandPolicyV2Error>;
|
||||
}
|
||||
|
||||
export class CommandPolicyV2 extends Context.Service<CommandPolicyV2, CommandPolicyV2Shape>()(
|
||||
"t3/orchestration-v2/CommandPolicy",
|
||||
) {}
|
||||
|
||||
function unsupported(
|
||||
input: CapabilityCheckInput,
|
||||
capability: CommandPolicyCapability,
|
||||
detail: string,
|
||||
) {
|
||||
return new CommandPolicyCapabilityUnsupportedError({
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
provider: input.provider,
|
||||
capability,
|
||||
detail,
|
||||
});
|
||||
}
|
||||
|
||||
const ensureQueuedMessages: CommandPolicyV2Shape["ensureQueuedMessages"] = (input) =>
|
||||
input.capabilities.turns.supportsQueuedMessages
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
unsupported(input, "queued_messages", "provider does not support app-owned queued turns"),
|
||||
);
|
||||
|
||||
const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {
|
||||
if (input.capabilities.turns.supportsActiveSteering) {
|
||||
return Effect.succeed("active_steering");
|
||||
}
|
||||
if (
|
||||
input.capabilities.turns.supportsInterrupt &&
|
||||
input.capabilities.turns.supportsSteeringByInterruptRestart
|
||||
) {
|
||||
return Effect.succeed("interrupt_restart");
|
||||
}
|
||||
return Effect.fail(
|
||||
unsupported(
|
||||
input,
|
||||
input.capabilities.turns.supportsInterrupt ? "interrupt_restart_steering" : "active_steering",
|
||||
"provider cannot steer active turns directly or by interrupt-and-restart",
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) =>
|
||||
input.capabilities.turns.supportsInterrupt
|
||||
? Effect.void
|
||||
: Effect.fail(unsupported(input, "interrupt", "provider 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"),
|
||||
);
|
||||
}
|
||||
if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) {
|
||||
return Effect.fail(
|
||||
unsupported(input, "fork_from_turn", "provider 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"),
|
||||
);
|
||||
}
|
||||
return Effect.void;
|
||||
};
|
||||
|
||||
const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
|
||||
if (
|
||||
!input.capabilities.threads.canRollbackThread ||
|
||||
!input.capabilities.checkpointing.providerCanRollbackConversation
|
||||
) {
|
||||
return Effect.fail(
|
||||
unsupported(input, "rollback", "provider conversation rollback is unavailable"),
|
||||
);
|
||||
}
|
||||
if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) {
|
||||
return Effect.fail(
|
||||
unsupported(input, "rollback_snapshot", "rollback must return a provider thread snapshot"),
|
||||
);
|
||||
}
|
||||
return Effect.void;
|
||||
};
|
||||
|
||||
const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => {
|
||||
if (!input.capabilities.context.canConsumeHandoffSummaries) {
|
||||
return Effect.fail(
|
||||
unsupported(input, "context_handoff", "provider cannot consume handoff summaries"),
|
||||
);
|
||||
}
|
||||
if (!input.capabilities.context.acceptsSyntheticUserContext) {
|
||||
return Effect.fail(
|
||||
unsupported(input, "context_handoff", "provider cannot receive synthetic user context"),
|
||||
);
|
||||
}
|
||||
if (
|
||||
(input.strategy === "fork_delta_context" || input.strategy === "delta_context") &&
|
||||
!input.capabilities.context.supportsDeltaHandoff
|
||||
) {
|
||||
return Effect.fail(
|
||||
unsupported(input, "context_handoff", "provider does not support delta handoff"),
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.strategy === "full_thread_summary" &&
|
||||
!input.capabilities.context.supportsFullThreadHandoff
|
||||
) {
|
||||
return Effect.fail(
|
||||
unsupported(input, "context_handoff", "provider does not support full-thread handoff"),
|
||||
);
|
||||
}
|
||||
return Effect.void;
|
||||
};
|
||||
|
||||
const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (input) => {
|
||||
const activeRun = input.projection.runs.find(
|
||||
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
|
||||
);
|
||||
const modelSelection = input.requestedModelSelection ?? input.projection.thread.modelSelection;
|
||||
|
||||
switch (input.requestedMode.type) {
|
||||
case "steer_active": {
|
||||
if (activeRun?.id !== input.requestedMode.targetRunId) {
|
||||
return Effect.fail(
|
||||
new CommandPolicyUnsupportedError({
|
||||
commandId: input.commandId,
|
||||
threadId: input.projection.thread.id,
|
||||
requestedMode: input.requestedMode.type,
|
||||
provider: modelSelection.provider,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const providerTurnId =
|
||||
activeRun.activeAttemptId === null
|
||||
? undefined
|
||||
: input.projection.providerTurns.find(
|
||||
(turn) =>
|
||||
turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
|
||||
)?.id;
|
||||
return providerTurnId === undefined
|
||||
? Effect.fail(
|
||||
new CommandPolicyMessageDispatchError({
|
||||
commandId: input.commandId,
|
||||
threadId: input.projection.thread.id,
|
||||
cause: `No running provider turn found for active run ${activeRun.id}.`,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
type: "steer_active",
|
||||
targetRunId: activeRun.id,
|
||||
providerTurnId,
|
||||
});
|
||||
}
|
||||
case "restart_active": {
|
||||
if (activeRun?.id !== input.requestedMode.targetRunId || activeRun.activeAttemptId === null) {
|
||||
return Effect.fail(
|
||||
new CommandPolicyUnsupportedError({
|
||||
commandId: input.commandId,
|
||||
threadId: input.projection.thread.id,
|
||||
requestedMode: input.requestedMode.type,
|
||||
provider: modelSelection.provider,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const providerTurnId = input.projection.providerTurns.find(
|
||||
(turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
|
||||
)?.id;
|
||||
return providerTurnId === undefined
|
||||
? Effect.fail(
|
||||
new CommandPolicyMessageDispatchError({
|
||||
commandId: input.commandId,
|
||||
threadId: input.projection.thread.id,
|
||||
cause: `No running provider turn found for active run ${activeRun.id}.`,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
type: "restart_active",
|
||||
targetRunId: activeRun.id,
|
||||
interruptProviderTurnId: providerTurnId,
|
||||
});
|
||||
}
|
||||
case "queue_after_active":
|
||||
return activeRun === undefined
|
||||
? Effect.succeed({ type: "start_run", modelSelection })
|
||||
: ensureQueuedMessages({
|
||||
commandId: input.commandId,
|
||||
threadId: input.projection.thread.id,
|
||||
provider: modelSelection.provider,
|
||||
capabilities: input.capabilities,
|
||||
}).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
|
||||
case "start_immediately":
|
||||
if (activeRun === undefined) {
|
||||
return Effect.succeed({ type: "start_run", modelSelection });
|
||||
}
|
||||
return ensureQueuedMessages({
|
||||
commandId: input.commandId,
|
||||
threadId: input.projection.thread.id,
|
||||
provider: modelSelection.provider,
|
||||
capabilities: input.capabilities,
|
||||
}).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id }));
|
||||
}
|
||||
};
|
||||
|
||||
export const layer: Layer.Layer<CommandPolicyV2> = Layer.succeed(CommandPolicyV2, {
|
||||
decideMessageDispatch,
|
||||
ensureQueuedMessages,
|
||||
decideSteeringExecution,
|
||||
ensureInterrupt,
|
||||
ensureNativeFork,
|
||||
ensureRollback,
|
||||
ensureContextHandoff,
|
||||
});
|
||||
@@ -25,6 +25,7 @@ import { Context, DateTime, Effect, Layer, Option, Ref, Schema, Stream } from "e
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||
import { CommandPolicyV2 } from "./CommandPolicy.ts";
|
||||
import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";
|
||||
import {
|
||||
ContextHandoffServiceV2,
|
||||
@@ -302,6 +303,7 @@ function visibleDeltaRunOrdinals(
|
||||
|
||||
const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(function* () {
|
||||
const checkpointService = yield* CheckpointServiceV2;
|
||||
const commandPolicy = yield* CommandPolicyV2;
|
||||
const contextHandoffService = yield* ContextHandoffServiceV2;
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const commandReceipts = yield* CommandReceiptStoreV2;
|
||||
@@ -326,6 +328,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
),
|
||||
);
|
||||
|
||||
const enforceCommandPolicy =
|
||||
(command: OrchestrationV2Command) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, OrchestratorDispatchError, R> =>
|
||||
effect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const makeEvent = <Event extends OrchestrationV2DomainEvent>(
|
||||
command: OrchestrationV2Command,
|
||||
event: Omit<Event, "id">,
|
||||
@@ -1032,7 +1048,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
});
|
||||
});
|
||||
|
||||
if (session.providerSession.capabilities.turns.supportsActiveSteering) {
|
||||
const steeringPolicy = yield* enforceCommandPolicy(input.command)(
|
||||
commandPolicy.decideSteeringExecution({
|
||||
commandId: input.command.commandId,
|
||||
threadId: input.command.threadId,
|
||||
provider: targetRun.provider,
|
||||
capabilities: session.providerSession.capabilities,
|
||||
}),
|
||||
);
|
||||
|
||||
if (steeringPolicy === "active_steering") {
|
||||
yield* session
|
||||
.steerTurn({
|
||||
threadId: input.command.threadId,
|
||||
@@ -1063,14 +1088,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
return;
|
||||
}
|
||||
|
||||
if (!session.providerSession.capabilities.turns.supportsSteeringByInterruptRestart) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: input.command.commandId,
|
||||
commandType: input.command.type,
|
||||
cause: `Provider ${targetRun.provider} cannot steer or restart active turns.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* session.interruptTurn({ providerThread, providerTurnId: providerTurn.id }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -1353,6 +1370,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
cause: `Queued dispatch for provider ${modelSelection.provider} cannot run behind active provider ${queueProviderThread.provider}.`,
|
||||
});
|
||||
}
|
||||
const existingProviderSession =
|
||||
queueProviderThread.providerSessionId === null
|
||||
? undefined
|
||||
: projection.providerSessions.find(
|
||||
(candidate) => candidate.id === queueProviderThread.providerSessionId,
|
||||
);
|
||||
if (existingProviderSession !== undefined) {
|
||||
yield* enforceCommandPolicy(command)(
|
||||
commandPolicy.ensureQueuedMessages({
|
||||
commandId: command.commandId,
|
||||
threadId: command.threadId,
|
||||
provider: modelSelection.provider,
|
||||
capabilities: existingProviderSession.capabilities,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const resolvedRuntimePolicy = yield* runtimePolicy
|
||||
.resolve({ thread: projection.thread, modelSelection })
|
||||
@@ -1371,12 +1404,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
|
||||
const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
|
||||
const rootNodeId = idAllocator.derive.rootNode({ runId });
|
||||
const existingProviderSession =
|
||||
queueProviderThread.providerSessionId === null
|
||||
? undefined
|
||||
: projection.providerSessions.find(
|
||||
(candidate) => candidate.id === queueProviderThread.providerSessionId,
|
||||
);
|
||||
const checkpointScope = yield* checkpointService
|
||||
.prepareRootRunScope({
|
||||
threadId: command.threadId,
|
||||
@@ -1684,15 +1711,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (
|
||||
pendingForkTransfer !== undefined &&
|
||||
!session.providerSession.capabilities.threads.canForkThread
|
||||
) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Provider ${modelSelection.provider} does not support native fork resolution.`,
|
||||
});
|
||||
if (pendingForkTransfer !== undefined) {
|
||||
yield* enforceCommandPolicy(command)(
|
||||
commandPolicy.ensureNativeFork({
|
||||
commandId: command.commandId,
|
||||
threadId: command.threadId,
|
||||
provider: modelSelection.provider,
|
||||
capabilities: session.providerSession.capabilities,
|
||||
fromSpecificTurn: sourceRun !== null,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const ensuredProviderThread =
|
||||
@@ -1802,6 +1830,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source provider thread.`,
|
||||
});
|
||||
}
|
||||
if (pendingMergeBackTransfer !== undefined) {
|
||||
yield* enforceCommandPolicy(command)(
|
||||
commandPolicy.ensureContextHandoff({
|
||||
commandId: command.commandId,
|
||||
threadId: command.threadId,
|
||||
provider: modelSelection.provider,
|
||||
capabilities: session.providerSession.capabilities,
|
||||
strategy: "fork_delta_context",
|
||||
}),
|
||||
);
|
||||
}
|
||||
const mergeBackDeltaItems =
|
||||
mergeBackSourceProjection === null || mergeBackSourceRun === null
|
||||
? []
|
||||
@@ -2598,6 +2637,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
cause: `Provider session ${providerThread.providerSessionId} is not active.`,
|
||||
});
|
||||
}
|
||||
yield* enforceCommandPolicy(command)(
|
||||
commandPolicy.ensureInterrupt({
|
||||
commandId: command.commandId,
|
||||
threadId: command.threadId,
|
||||
provider: run.provider,
|
||||
capabilities: sessionOption.value.providerSession.capabilities,
|
||||
}),
|
||||
);
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const emitEvent = emit(events, command);
|
||||
@@ -2734,6 +2781,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* enforceCommandPolicy(command)(
|
||||
commandPolicy.ensureRollback({
|
||||
commandId: command.commandId,
|
||||
threadId: command.threadId,
|
||||
provider: modelSelection.provider,
|
||||
capabilities: session.providerSession.capabilities,
|
||||
}),
|
||||
);
|
||||
|
||||
const targetCheckpoint = projection.checkpoints.find(
|
||||
(candidate) => candidate.id === command.checkpointId,
|
||||
@@ -3084,6 +3139,7 @@ export const layer: Layer.Layer<
|
||||
OrchestratorV2,
|
||||
never,
|
||||
| CheckpointServiceV2
|
||||
| CommandPolicyV2
|
||||
| CommandReceiptStoreV2
|
||||
| ContextHandoffServiceV2
|
||||
| EventSinkV2
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Layer } from "effect";
|
||||
import { layer as codexAdapterLayer } from "./Adapters/CodexAdapterV2.ts";
|
||||
import { codexAppServerClientFactoryFromSettingsLayer } from "./Adapters/CodexAdapterV2.ts";
|
||||
import { layer as checkpointServiceLayer } from "./CheckpointService.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";
|
||||
@@ -66,6 +67,7 @@ export const OrchestrationV2LayerLive = orchestratorLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
checkpointServiceProvided,
|
||||
commandPolicyLayer,
|
||||
storesLayer,
|
||||
eventSinkProvided,
|
||||
commandReceiptStoreProvided,
|
||||
|
||||
+2
-17
@@ -1,11 +1,7 @@
|
||||
import { describe, it } from "@effect/vitest";
|
||||
import type { ProviderKind, ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
|
||||
import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts";
|
||||
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
|
||||
@@ -20,27 +16,16 @@ import {
|
||||
runOrchestratorV2ProviderReplayScenario,
|
||||
type OrchestratorV2ProviderReplayHarness,
|
||||
} from "./ProviderReplayHarness.ts";
|
||||
import { makeCheckpointWorkspace } from "./ReplayFixtureWorkspace.ts";
|
||||
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
|
||||
|
||||
const PROVIDER_REPLAY_HARNESSES = [CodexOrchestratorReplayHarness] as const;
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
|
||||
const text = await readFile(file, "utf8");
|
||||
return await Effect.runPromise(decodeProviderReplayNdjson(text));
|
||||
}
|
||||
|
||||
async function makeCheckpointWorkspace(fixtureName: string): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(tmpdir(), `t3-orchestrator-v2-${fixtureName}-`));
|
||||
await execFileAsync("git", ["init"], { cwd });
|
||||
await execFileAsync("git", ["config", "user.name", "T3 Code Test"], { cwd });
|
||||
await execFileAsync("git", ["config", "user.email", "[email protected]"], { cwd });
|
||||
await writeFile(path.join(cwd, "README.md"), `# ${fixtureName}\n`, "utf8");
|
||||
await execFileAsync("git", ["add", "README.md"], { cwd });
|
||||
await execFileAsync("git", ["commit", "-m", "initial"], { cwd });
|
||||
return cwd;
|
||||
}
|
||||
|
||||
function harnessFor(provider: ProviderKind) {
|
||||
const harness = PROVIDER_REPLAY_HARNESSES.find((candidate) => candidate.provider === provider);
|
||||
if (!harness) {
|
||||
|
||||
@@ -13,6 +13,7 @@ import { ServerConfig, type ServerConfigShape } from "../../config.ts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { layer as checkpointServiceLayer } from "../CheckpointService.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";
|
||||
@@ -220,6 +221,7 @@ export function makeOrchestratorV2ProviderReplayLayer<
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
checkpointServiceProvided,
|
||||
commandPolicyLayer,
|
||||
contextHandoffServiceProvided,
|
||||
persistenceLayer,
|
||||
runtimeLayer,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export async function makeCheckpointWorkspace(fixtureName: string): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(tmpdir(), `t3-orchestrator-v2-${fixtureName}-`));
|
||||
await execFileAsync("git", ["init"], { cwd });
|
||||
await execFileAsync("git", ["config", "user.name", "T3 Code Test"], { cwd });
|
||||
await execFileAsync("git", ["config", "user.email", "[email protected]"], { cwd });
|
||||
await writeFile(path.join(cwd, "README.md"), `# ${fixtureName}\n`, "utf8");
|
||||
await execFileAsync("git", ["add", "README.md"], { cwd });
|
||||
await execFileAsync("git", ["commit", "-m", "initial"], { cwd });
|
||||
return cwd;
|
||||
}
|
||||
Reference in new issue
Block a user