Complete orchestration V2 application services
This commit is contained in:
1 parent
28ea5e1104
commit
2fd952bd3d
30 files changed
+2619
-128
No files matched your search
@@ -292,6 +292,8 @@ Add coverage for:
|
||||
|
||||
## Shape 2: Application Services Around V2
|
||||
|
||||
Implementation status: complete. The production WebSocket/client cutover remains intentionally deferred to Shape 3.
|
||||
|
||||
### Goal
|
||||
|
||||
Recreate the application behavior currently hidden in V1 reactors and WebSocket handlers using explicit V2 services and durable workflows.
|
||||
|
||||
@@ -66,11 +66,6 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
|
||||
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,
|
||||
@@ -78,7 +73,6 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("terminal.cleanup"),
|
||||
runId: RunId,
|
||||
}),
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("attachment.cleanup"),
|
||||
@@ -144,6 +138,7 @@ export interface EffectOutboxV2Shape {
|
||||
readonly listByCommandId: (
|
||||
commandId: CommandId,
|
||||
) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
|
||||
readonly reclaimRunning: Effect.Effect<number, EffectOutboxError>;
|
||||
readonly claimNext: (input: {
|
||||
readonly workerId: string;
|
||||
readonly leaseDurationMs: number;
|
||||
@@ -294,6 +289,22 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
|
||||
: new EffectOutboxError({ operation: "list", cause }),
|
||||
),
|
||||
),
|
||||
reclaimRunning: 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 = 'pending',
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
available_at = ${now},
|
||||
updated_at = ${now}
|
||||
WHERE status = 'running'
|
||||
RETURNING effect_id
|
||||
`;
|
||||
if (rows.length > 0) yield* Queue.offer(available, undefined);
|
||||
return rows.length;
|
||||
}).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "reclaim", cause }))),
|
||||
claimNext: ({ workerId, leaseDurationMs }) =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
|
||||
@@ -7,7 +7,8 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { CheckpointCaptureServiceV2 } from "./CheckpointCaptureService.ts";
|
||||
import { RunFinalizationService } from "./RunFinalizationService.ts";
|
||||
import { ResourceCleanupService } from "./ResourceCleanupService.ts";
|
||||
import { EffectOutboxV2, type OrchestrationEffectV2 } from "./EffectOutbox.ts";
|
||||
import { CheckpointRollbackServiceV2 } from "./CheckpointRollbackService.ts";
|
||||
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
|
||||
@@ -39,7 +40,7 @@ export const executorLayer: Layer.Layer<
|
||||
OrchestrationEffectExecutorV2,
|
||||
never,
|
||||
| ProviderSessionManagerV2
|
||||
| CheckpointCaptureServiceV2
|
||||
| RunFinalizationService
|
||||
| CheckpointRollbackServiceV2
|
||||
| ProviderTurnControlServiceV2
|
||||
| ProviderTurnStartServiceV2
|
||||
@@ -47,7 +48,8 @@ export const executorLayer: Layer.Layer<
|
||||
> = Layer.effect(
|
||||
OrchestrationEffectExecutorV2,
|
||||
Effect.gen(function* () {
|
||||
const checkpointCapture = yield* CheckpointCaptureServiceV2;
|
||||
const runFinalization = yield* RunFinalizationService;
|
||||
const resourceCleanup = yield* ResourceCleanupService;
|
||||
const checkpointRollback = yield* CheckpointRollbackServiceV2;
|
||||
const providerSessions = yield* ProviderSessionManagerV2;
|
||||
const providerTurnControl = yield* ProviderTurnControlServiceV2;
|
||||
@@ -190,8 +192,8 @@ export const executorLayer: Layer.Layer<
|
||||
),
|
||||
);
|
||||
case "checkpoint.capture":
|
||||
return checkpointCapture
|
||||
.execute({
|
||||
return runFinalization
|
||||
.finalize({
|
||||
threadId: effect.threadId,
|
||||
runId: effect.request.runId,
|
||||
scopeId: effect.request.scopeId,
|
||||
@@ -206,15 +208,27 @@ export const executorLayer: Layer.Layer<
|
||||
}),
|
||||
),
|
||||
);
|
||||
case "provider-thread.fork":
|
||||
case "terminal.cleanup":
|
||||
return resourceCleanup.cleanupTerminals(effect.threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationEffectExecutionError({
|
||||
effectId: effect.id,
|
||||
effectType: effect.request.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
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}.`,
|
||||
}),
|
||||
return resourceCleanup.cleanupAttachments(effect.request.attachmentIds).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationEffectExecutionError({
|
||||
effectId: effect.id,
|
||||
effectType: effect.request.type,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -354,6 +354,44 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
|
||||
);
|
||||
assert.equal(claims.filter(Option.isSome).length, 1);
|
||||
assert.equal(claims.filter(Option.isNone).length, 1);
|
||||
const claimedByA = claims[0];
|
||||
const claimedByB = claims[1];
|
||||
if (Option.isSome(claimedByA)) {
|
||||
yield* outbox.succeed({ effectId: claimedByA.value.id, workerId: "worker-a" });
|
||||
}
|
||||
if (Option.isSome(claimedByB)) {
|
||||
yield* outbox.succeed({ effectId: claimedByB.value.id, workerId: "worker-b" });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reclaims running effects immediately during startup recovery", () =>
|
||||
Effect.gen(function* () {
|
||||
const outbox = yield* EffectOutboxV2;
|
||||
const commandId = CommandId.make("command:foundation-reclaim-running");
|
||||
yield* outbox.enqueue([
|
||||
{
|
||||
id: "effect:foundation-reclaim-running",
|
||||
commandId,
|
||||
threadId: ThreadId.make("thread:foundation-reclaim-running"),
|
||||
request: {
|
||||
type: "provider-turn.start",
|
||||
runId: RunId.make("run:foundation-reclaim-running"),
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.isTrue(
|
||||
Option.isSome(
|
||||
yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
|
||||
),
|
||||
);
|
||||
assert.equal(yield* outbox.reclaimRunning, 1);
|
||||
const reclaimed = yield* outbox.claimNext({
|
||||
workerId: "recovery-worker",
|
||||
leaseDurationMs: 30_000,
|
||||
});
|
||||
assert.isTrue(Option.isSome(reclaimed));
|
||||
if (Option.isSome(reclaimed)) assert.equal(reclaimed.value.attemptCount, 2);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -815,16 +815,91 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
payload: updatedThread,
|
||||
});
|
||||
|
||||
if (command.type === "thread.delete") {
|
||||
const emitEvent = emit(events, command);
|
||||
const activeRunIds = new Set(
|
||||
projection.runs
|
||||
.filter((run) => ["queued", "starting", "running", "waiting"].includes(run.status))
|
||||
.map((run) => run.id),
|
||||
);
|
||||
for (const run of projection.runs.filter((candidate) => activeRunIds.has(candidate.id))) {
|
||||
yield* emitEvent({
|
||||
type: "run.updated",
|
||||
threadId: command.threadId,
|
||||
runId: run.id,
|
||||
providerInstanceId: run.providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
|
||||
});
|
||||
}
|
||||
for (const attempt of projection.attempts.filter(
|
||||
(candidate) =>
|
||||
activeRunIds.has(candidate.runId) &&
|
||||
(candidate.status === "pending" || candidate.status === "running"),
|
||||
)) {
|
||||
const run = projection.runs.find((candidate) => candidate.id === attempt.runId)!;
|
||||
yield* emitEvent({
|
||||
type: "run-attempt.updated",
|
||||
threadId: command.threadId,
|
||||
runId: attempt.runId,
|
||||
nodeId: attempt.rootNodeId,
|
||||
providerInstanceId: run.providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: { ...attempt, status: "cancelled", completedAt: now },
|
||||
});
|
||||
}
|
||||
for (const node of projection.nodes.filter(
|
||||
(candidate) =>
|
||||
candidate.runId !== null &&
|
||||
activeRunIds.has(candidate.runId) &&
|
||||
["pending", "running", "waiting"].includes(candidate.status),
|
||||
)) {
|
||||
const run = projection.runs.find((candidate) => candidate.id === node.runId)!;
|
||||
yield* emitEvent({
|
||||
type: "node.updated",
|
||||
threadId: command.threadId,
|
||||
runId: run.id,
|
||||
nodeId: node.id,
|
||||
providerInstanceId: run.providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: { ...node, status: "cancelled", completedAt: now },
|
||||
});
|
||||
}
|
||||
for (const request of projection.runtimeRequests.filter(
|
||||
(candidate) => candidate.status === "pending",
|
||||
)) {
|
||||
yield* emitEvent({
|
||||
type: "runtime-request.updated",
|
||||
threadId: command.threadId,
|
||||
nodeId: request.nodeId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
...request,
|
||||
status: "cancelled",
|
||||
responseCapability: {
|
||||
type: "not_resumable",
|
||||
reason: "The thread was deleted.",
|
||||
},
|
||||
resolvedAt: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const detachSessionIds = new Set(
|
||||
command.type === "thread.archive" || command.type === "thread.delete"
|
||||
? projection.providerSessions.map((session) => session.id)
|
||||
: command.type === "thread.runtime-mode.set"
|
||||
? projection.providerSessions
|
||||
.filter(
|
||||
(session) => !session.capabilities.sessions.supportsRuntimeModeSwitchInSession,
|
||||
)
|
||||
.map((session) => session.id)
|
||||
: (providerSwitchPlan?.releaseProviderSessionIds ?? []),
|
||||
: command.type === "thread.metadata.update" &&
|
||||
command.worktreePath !== undefined &&
|
||||
command.worktreePath !== thread.worktreePath
|
||||
? projection.providerSessions.map((session) => session.id)
|
||||
: command.type === "thread.runtime-mode.set"
|
||||
? projection.providerSessions
|
||||
.filter(
|
||||
(session) => !session.capabilities.sessions.supportsRuntimeModeSwitchInSession,
|
||||
)
|
||||
.map((session) => session.id)
|
||||
: (providerSwitchPlan?.releaseProviderSessionIds ?? []),
|
||||
);
|
||||
if (detachSessionIds.size > 0) {
|
||||
const liveSessions = projection.providerSessions.filter(
|
||||
@@ -854,9 +929,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
? "Thread archived."
|
||||
: command.type === "thread.delete"
|
||||
? "Thread deleted."
|
||||
: command.type === "thread.runtime-mode.set"
|
||||
? "Runtime mode changed."
|
||||
: "Provider or model selection changed.",
|
||||
: command.type === "thread.metadata.update"
|
||||
? "Workspace changed."
|
||||
: command.type === "thread.runtime-mode.set"
|
||||
? "Runtime mode changed."
|
||||
: "Provider or model selection changed.",
|
||||
},
|
||||
});
|
||||
const pendingEffect = {
|
||||
@@ -871,9 +948,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
? "Thread archived."
|
||||
: command.type === "thread.delete"
|
||||
? "Thread deleted."
|
||||
: command.type === "thread.runtime-mode.set"
|
||||
? "Runtime mode changed."
|
||||
: "Provider or model selection changed.",
|
||||
: command.type === "thread.metadata.update"
|
||||
? "Workspace changed."
|
||||
: command.type === "thread.runtime-mode.set"
|
||||
? "Runtime mode changed."
|
||||
: "Provider or model selection changed.",
|
||||
},
|
||||
} satisfies PendingOrchestrationEffectV2;
|
||||
yield* Ref.update(effects, (existing) => [...existing, pendingEffect]);
|
||||
@@ -881,6 +960,37 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
}
|
||||
|
||||
if (command.type === "thread.archive" || command.type === "thread.delete") {
|
||||
yield* Ref.update(effects, (existing) => [
|
||||
...existing,
|
||||
{
|
||||
id: `effect:${command.commandId}:terminal.cleanup`,
|
||||
commandId: command.commandId,
|
||||
threadId: command.threadId,
|
||||
request: { type: "terminal.cleanup" },
|
||||
} satisfies PendingOrchestrationEffectV2,
|
||||
]);
|
||||
}
|
||||
|
||||
if (command.type === "thread.delete") {
|
||||
const attachmentIds = Array.from(
|
||||
new Set(
|
||||
projection.messages.flatMap((message) => message.attachments.map((item) => item.id)),
|
||||
),
|
||||
);
|
||||
if (attachmentIds.length > 0) {
|
||||
yield* Ref.update(effects, (existing) => [
|
||||
...existing,
|
||||
{
|
||||
id: `effect:${command.commandId}:attachment.cleanup`,
|
||||
commandId: command.commandId,
|
||||
threadId: command.threadId,
|
||||
request: { type: "attachment.cleanup", attachmentIds },
|
||||
} satisfies PendingOrchestrationEffectV2,
|
||||
]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const dispatchProviderSessionDetach = Effect.fn("orchestrationV2.dispatch.providerSessionDetach")(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
ProviderInstanceId,
|
||||
type OrchestrationV2ProviderCapabilities,
|
||||
type ProviderDriverKind,
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceConfigMap,
|
||||
@@ -29,8 +30,14 @@ export class ProviderAdapterRegistryLookupError extends Schema.TaggedErrorClass<
|
||||
}
|
||||
}
|
||||
|
||||
export class ProviderAdapterRegistryMetadataError extends Schema.TaggedErrorClass<ProviderAdapterRegistryMetadataError>()(
|
||||
"ProviderAdapterRegistryMetadataError",
|
||||
{ instanceId: ProviderInstanceId, cause: Schema.Defect() },
|
||||
) {}
|
||||
|
||||
export const ProviderAdapterRegistryV2Error = Schema.Union([
|
||||
ProviderAdapterRegistryLookupError,
|
||||
ProviderAdapterRegistryMetadataError,
|
||||
ProviderAdapterDriverCreateError,
|
||||
]);
|
||||
export type ProviderAdapterRegistryV2Error = typeof ProviderAdapterRegistryV2Error.Type;
|
||||
@@ -39,7 +46,16 @@ export interface ProviderAdapterRegistryV2Shape {
|
||||
readonly get: (
|
||||
provider: ProviderKind,
|
||||
) => Effect.Effect<ProviderAdapterV2Shape, ProviderAdapterRegistryV2Error>;
|
||||
readonly list: () => Effect.Effect<ReadonlyArray<ProviderKind>>;
|
||||
readonly list: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
|
||||
readonly getMetadata?: (instanceId: ProviderInstanceId) => Effect.Effect<
|
||||
{
|
||||
readonly driver: ProviderAdapterV2Shape["driver"];
|
||||
readonly continuationKey: string;
|
||||
readonly enabled: boolean;
|
||||
readonly capabilities: OrchestrationV2ProviderCapabilities;
|
||||
},
|
||||
ProviderAdapterRegistryV2Error
|
||||
>;
|
||||
}
|
||||
|
||||
export class ProviderAdapterRegistryV2 extends Context.Service<
|
||||
@@ -75,6 +91,26 @@ export const layerFromProviderInstanceRegistry: Layer.Layer<
|
||||
instances.listInstances.pipe(
|
||||
Effect.map((available) => available.map((instance) => instance.instanceId)),
|
||||
),
|
||||
getMetadata: (instanceId) =>
|
||||
Effect.gen(function* () {
|
||||
const instance = yield* instances.getInstance(instanceId);
|
||||
if (instance === undefined) {
|
||||
return yield* new ProviderAdapterRegistryLookupError({ instanceId });
|
||||
}
|
||||
const capabilities = yield* instance.orchestrationAdapter
|
||||
.getCapabilities()
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ProviderAdapterRegistryMetadataError({ instanceId, cause }),
|
||||
),
|
||||
);
|
||||
return {
|
||||
driver: instance.driverKind,
|
||||
continuationKey: instance.continuationIdentity.continuationKey,
|
||||
enabled: instance.enabled,
|
||||
capabilities,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import {
|
||||
NodeId,
|
||||
RuntimeRequestId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as EffectWorker from "./EffectWorker.ts";
|
||||
import * as EffectOutbox from "./EffectOutbox.ts";
|
||||
import * as EventSink from "./EventSink.ts";
|
||||
import * as IdAllocator from "./IdAllocator.ts";
|
||||
import * as ProjectionStore from "./ProjectionStore.ts";
|
||||
import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
|
||||
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
|
||||
|
||||
const { decideProviderRuntimeRecovery } = ProviderRuntimeRecovery;
|
||||
|
||||
it("retries process and transport failures only within the idempotent retry budget", () => {
|
||||
assert.deepEqual(
|
||||
decideProviderRuntimeRecovery({
|
||||
kind: "process_exited",
|
||||
attempt: 1,
|
||||
maxAttempts: 3,
|
||||
idempotent: true,
|
||||
online: true,
|
||||
}),
|
||||
{ type: "retry_now" },
|
||||
);
|
||||
assert.equal(
|
||||
decideProviderRuntimeRecovery({
|
||||
kind: "transport_unavailable",
|
||||
attempt: 3,
|
||||
maxAttempts: 3,
|
||||
idempotent: true,
|
||||
online: true,
|
||||
}).type,
|
||||
"terminalize",
|
||||
);
|
||||
});
|
||||
|
||||
it("waits for connectivity and requires retry-after for rate limits", () => {
|
||||
assert.deepEqual(
|
||||
decideProviderRuntimeRecovery({
|
||||
kind: "network_unavailable",
|
||||
attempt: 0,
|
||||
maxAttempts: 3,
|
||||
idempotent: true,
|
||||
online: false,
|
||||
}),
|
||||
{ type: "wait_for_connectivity" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
decideProviderRuntimeRecovery({
|
||||
kind: "provider_rate_limited",
|
||||
attempt: 0,
|
||||
maxAttempts: 3,
|
||||
idempotent: true,
|
||||
retryAfterMs: 250,
|
||||
online: true,
|
||||
}),
|
||||
{ type: "retry_after", delayMs: 250 },
|
||||
);
|
||||
});
|
||||
|
||||
it("terminalizes non-recoverable provider failures", () => {
|
||||
for (const kind of [
|
||||
"provider_quota_exceeded",
|
||||
"auth_invalid",
|
||||
"permission_denied",
|
||||
"invalid_request",
|
||||
"unsupported_model",
|
||||
] as const) {
|
||||
assert.equal(
|
||||
decideProviderRuntimeRecovery({
|
||||
kind,
|
||||
attempt: 0,
|
||||
maxAttempts: 3,
|
||||
idempotent: true,
|
||||
online: true,
|
||||
}).type,
|
||||
"terminalize",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("classifies wrapped provider failures without provider-name checks", () => {
|
||||
assert.deepEqual(
|
||||
ProviderRuntimeRecovery.classifyProviderRuntimeFailure({
|
||||
_tag: "ProviderSessionOpenError",
|
||||
cause: { code: "rate_limit_exceeded", retryAfterMs: 125 },
|
||||
}),
|
||||
{ kind: "provider_rate_limited", retryAfterMs: 125 },
|
||||
);
|
||||
assert.deepEqual(
|
||||
ProviderRuntimeRecovery.classifyProviderRuntimeFailure({
|
||||
cause: { status: 401, message: "authentication failed" },
|
||||
}),
|
||||
{ kind: "auth_invalid" },
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("executes bounded transport retries and returns the resumed value", () =>
|
||||
Effect.gen(function* () {
|
||||
const attempts = yield* Ref.make(0);
|
||||
const value = yield* ProviderRuntimeRecovery.recoverWithPolicy({
|
||||
operation: Ref.getAndUpdate(attempts, (count) => count + 1).pipe(
|
||||
Effect.flatMap((count) =>
|
||||
count < 2 ? Effect.fail("transport down") : Effect.succeed("resumed"),
|
||||
),
|
||||
),
|
||||
classify: () => ({ kind: "transport_unavailable" }),
|
||||
connectivity: { isOnline: Effect.succeed(true), awaitOnline: Effect.void },
|
||||
maxAttempts: 3,
|
||||
idempotent: true,
|
||||
});
|
||||
assert.equal(value, "resumed");
|
||||
assert.equal(yield* Ref.get(attempts), 3);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("waits for connectivity before retrying a network failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const attempts = yield* Ref.make(0);
|
||||
const online = yield* Ref.make(false);
|
||||
const waits = yield* Ref.make(0);
|
||||
const value = yield* ProviderRuntimeRecovery.recoverWithPolicy({
|
||||
operation: Ref.getAndUpdate(attempts, (count) => count + 1).pipe(
|
||||
Effect.flatMap((count) =>
|
||||
count === 0 ? Effect.fail("offline") : Effect.succeed("resumed"),
|
||||
),
|
||||
),
|
||||
classify: () => ({ kind: "network_unavailable" }),
|
||||
connectivity: {
|
||||
isOnline: Ref.get(online),
|
||||
awaitOnline: Ref.set(online, true).pipe(
|
||||
Effect.andThen(Ref.update(waits, (count) => count + 1)),
|
||||
),
|
||||
},
|
||||
maxAttempts: 3,
|
||||
idempotent: true,
|
||||
});
|
||||
assert.equal(value, "resumed");
|
||||
assert.equal(yield* Ref.get(waits), 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not retry unrecoverable failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const attempts = yield* Ref.make(0);
|
||||
const result = yield* Effect.result(
|
||||
ProviderRuntimeRecovery.recoverWithPolicy({
|
||||
operation: Ref.update(attempts, (count) => count + 1).pipe(
|
||||
Effect.andThen(Effect.fail("invalid credentials")),
|
||||
),
|
||||
classify: () => ({ kind: "auth_invalid" }),
|
||||
connectivity: { isOnline: Effect.succeed(true), awaitOnline: Effect.void },
|
||||
maxAttempts: 3,
|
||||
idempotent: true,
|
||||
}),
|
||||
);
|
||||
assert.equal(result._tag, "Failure");
|
||||
assert.equal(yield* Ref.get(attempts), 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drains durable effects before reporting recovery complete", () =>
|
||||
Effect.gen(function* () {
|
||||
const runs = yield* Ref.make(0);
|
||||
const layer = ProviderRuntimeRecovery.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
schemaVersion: 2,
|
||||
snapshotSequence: 0,
|
||||
threads: [],
|
||||
archivedThreads: [],
|
||||
}),
|
||||
}),
|
||||
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
|
||||
Layer.mock(EventSink.EventSinkV2)({}),
|
||||
IdAllocator.layer,
|
||||
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
|
||||
runOnce: Ref.getAndUpdate(runs, (count) => count + 1).pipe(
|
||||
Effect.map((count) => count < 2),
|
||||
),
|
||||
}),
|
||||
Layer.mock(EffectOutbox.EffectOutboxV2)({ reclaimRunning: Effect.succeed(0) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
const summary = yield* Effect.gen(function* () {
|
||||
return yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover;
|
||||
}).pipe(Effect.provide(layer));
|
||||
assert.deepEqual(summary, { resumedSessions: 0, terminalizedRuns: 0, executedEffects: 2 });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("expires orphaned runtime requests before command readiness", () => {
|
||||
const threadId = ThreadId.make("thread_recovery_requests");
|
||||
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
|
||||
null;
|
||||
const committed = vi.fn(
|
||||
(input: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0]) => {
|
||||
committedInput = input;
|
||||
return Effect.succeed({ committed: true } as never);
|
||||
},
|
||||
);
|
||||
const projection = {
|
||||
thread: { id: threadId },
|
||||
runtimeRequests: [
|
||||
{
|
||||
id: RuntimeRequestId.make("request_orphaned"),
|
||||
nodeId: NodeId.make("node_orphaned"),
|
||||
status: "pending",
|
||||
responseCapability: { type: "not_resumable", reason: "old process" },
|
||||
},
|
||||
],
|
||||
providerSessions: [],
|
||||
runs: [],
|
||||
nodes: [],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const layer = ProviderRuntimeRecovery.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
schemaVersion: 2,
|
||||
snapshotSequence: 0,
|
||||
threads: [{ id: threadId }],
|
||||
archivedThreads: [],
|
||||
} as never),
|
||||
getThreadProjection: () => Effect.succeed(projection),
|
||||
}),
|
||||
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
|
||||
Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
|
||||
IdAllocator.layer,
|
||||
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
|
||||
Layer.mock(EffectOutbox.EffectOutboxV2)({ reclaimRunning: Effect.succeed(0) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Effect.gen(function* () {
|
||||
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover;
|
||||
const command = committedInput;
|
||||
assert.isNotNull(command);
|
||||
if (command === null) return;
|
||||
assert.equal(command?.events[0]?.type, "runtime-request.updated");
|
||||
if (command?.events[0]?.type === "runtime-request.updated") {
|
||||
assert.equal(command.events[0].payload.status, "expired");
|
||||
assert.equal(command.events[0].payload.responseCapability.type, "not_resumable");
|
||||
}
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
@@ -0,0 +1,508 @@
|
||||
import {
|
||||
CommandId,
|
||||
type OrchestrationV2DomainEvent,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as EffectWorker from "./EffectWorker.ts";
|
||||
import * as EffectOutbox from "./EffectOutbox.ts";
|
||||
import * as EventSink from "./EventSink.ts";
|
||||
import * as IdAllocator from "./IdAllocator.ts";
|
||||
import * as ProjectionStore from "./ProjectionStore.ts";
|
||||
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
|
||||
|
||||
export class ProviderRuntimeRecoveryError extends Schema.TaggedErrorClass<ProviderRuntimeRecoveryError>()(
|
||||
"ProviderRuntimeRecoveryError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"read-projections",
|
||||
"resume-session",
|
||||
"terminalize",
|
||||
"drain-outbox",
|
||||
]),
|
||||
threadId: Schema.optional(ThreadId),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider runtime recovery failed during ${this.operation}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProviderRuntimeRecoverySummary {
|
||||
readonly resumedSessions: number;
|
||||
readonly terminalizedRuns: number;
|
||||
readonly executedEffects: number;
|
||||
}
|
||||
|
||||
export const ProviderRuntimeFailureKind = Schema.Literals([
|
||||
"process_exited",
|
||||
"transport_unavailable",
|
||||
"network_unavailable",
|
||||
"provider_rate_limited",
|
||||
"provider_quota_exceeded",
|
||||
"auth_invalid",
|
||||
"permission_denied",
|
||||
"invalid_request",
|
||||
"unsupported_model",
|
||||
]);
|
||||
export type ProviderRuntimeFailureKind = typeof ProviderRuntimeFailureKind.Type;
|
||||
|
||||
export type ProviderRuntimeRecoveryDecision =
|
||||
| { readonly type: "retry_now" }
|
||||
| { readonly type: "retry_after"; readonly delayMs: number }
|
||||
| { readonly type: "wait_for_connectivity" }
|
||||
| { readonly type: "terminalize"; readonly reason: string };
|
||||
|
||||
export function decideProviderRuntimeRecovery(input: {
|
||||
readonly kind: ProviderRuntimeFailureKind;
|
||||
readonly attempt: number;
|
||||
readonly maxAttempts: number;
|
||||
readonly idempotent: boolean;
|
||||
readonly retryAfterMs?: number;
|
||||
readonly online: boolean;
|
||||
}): ProviderRuntimeRecoveryDecision {
|
||||
if (input.attempt >= input.maxAttempts) {
|
||||
return { type: "terminalize", reason: "Provider recovery retry budget was exhausted." };
|
||||
}
|
||||
switch (input.kind) {
|
||||
case "process_exited":
|
||||
case "transport_unavailable":
|
||||
return input.idempotent
|
||||
? { type: "retry_now" }
|
||||
: { type: "terminalize", reason: "The interrupted operation is not idempotent." };
|
||||
case "network_unavailable":
|
||||
return input.online ? { type: "retry_now" } : { type: "wait_for_connectivity" };
|
||||
case "provider_rate_limited":
|
||||
return input.idempotent && input.retryAfterMs !== undefined
|
||||
? { type: "retry_after", delayMs: Math.max(0, input.retryAfterMs) }
|
||||
: {
|
||||
type: "terminalize",
|
||||
reason: "Rate-limit recovery requires retry-after and an idempotent operation.",
|
||||
};
|
||||
case "provider_quota_exceeded":
|
||||
case "auth_invalid":
|
||||
case "permission_denied":
|
||||
case "invalid_request":
|
||||
case "unsupported_model":
|
||||
return { type: "terminalize", reason: `Provider failure ${input.kind} is not recoverable.` };
|
||||
}
|
||||
}
|
||||
|
||||
export interface ConnectivityServiceShape {
|
||||
readonly isOnline: Effect.Effect<boolean>;
|
||||
readonly awaitOnline: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class ConnectivityService extends Context.Reference<ConnectivityServiceShape>(
|
||||
"t3/orchestration-v2/ConnectivityService",
|
||||
{
|
||||
defaultValue: () => ({ isOnline: Effect.succeed(true), awaitOnline: Effect.void }),
|
||||
},
|
||||
) {}
|
||||
|
||||
export interface ClassifiedProviderRuntimeFailure {
|
||||
readonly kind: ProviderRuntimeFailureKind;
|
||||
readonly retryAfterMs?: number;
|
||||
}
|
||||
|
||||
export function classifyProviderRuntimeFailure(cause: unknown): ClassifiedProviderRuntimeFailure {
|
||||
const record =
|
||||
cause !== null && typeof cause === "object"
|
||||
? (cause as Record<string, unknown>)
|
||||
: ({} as Record<string, unknown>);
|
||||
const serialized = (() => {
|
||||
try {
|
||||
return JSON.stringify(cause);
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
})();
|
||||
const description = [
|
||||
record._tag,
|
||||
record.code,
|
||||
record.status,
|
||||
record.message,
|
||||
record.detail,
|
||||
serialized,
|
||||
]
|
||||
.filter((value) => typeof value === "string" || typeof value === "number")
|
||||
.join(" ")
|
||||
.toLowerCase();
|
||||
const nestedCause =
|
||||
record.cause !== null && typeof record.cause === "object"
|
||||
? (record.cause as Record<string, unknown>)
|
||||
: undefined;
|
||||
const retryAfter =
|
||||
record.retryAfterMs ??
|
||||
record.retry_after_ms ??
|
||||
nestedCause?.retryAfterMs ??
|
||||
nestedCause?.retry_after_ms;
|
||||
const retryAfterMs = typeof retryAfter === "number" ? retryAfter : undefined;
|
||||
if (description.includes("rate") && description.includes("limit")) {
|
||||
return {
|
||||
kind: "provider_rate_limited",
|
||||
...(retryAfterMs === undefined ? {} : { retryAfterMs }),
|
||||
};
|
||||
}
|
||||
if (description.includes("quota")) return { kind: "provider_quota_exceeded" };
|
||||
if (description.includes("auth") || description.includes("unauthorized")) {
|
||||
return { kind: "auth_invalid" };
|
||||
}
|
||||
if (description.includes("permission") || description.includes("forbidden")) {
|
||||
return { kind: "permission_denied" };
|
||||
}
|
||||
if (description.includes("unsupported") && description.includes("model")) {
|
||||
return { kind: "unsupported_model" };
|
||||
}
|
||||
if (description.includes("invalid") && description.includes("request")) {
|
||||
return { kind: "invalid_request" };
|
||||
}
|
||||
if (
|
||||
description.includes("network") ||
|
||||
description.includes("offline") ||
|
||||
description.includes("econnreset") ||
|
||||
description.includes("enotfound")
|
||||
) {
|
||||
return { kind: "network_unavailable" };
|
||||
}
|
||||
if (description.includes("exit") || description.includes("terminated")) {
|
||||
return { kind: "process_exited" };
|
||||
}
|
||||
return { kind: "transport_unavailable" };
|
||||
}
|
||||
|
||||
export class ProviderRuntimeFailureClassifier extends Context.Reference<{
|
||||
readonly classify: (cause: unknown) => ClassifiedProviderRuntimeFailure;
|
||||
}>("t3/orchestration-v2/ProviderRuntimeFailureClassifier", {
|
||||
defaultValue: () => ({ classify: classifyProviderRuntimeFailure }),
|
||||
}) {}
|
||||
|
||||
export class ProviderRuntimeRecoveryPolicy extends Context.Reference<{
|
||||
readonly maxAttempts: number;
|
||||
}>("t3/orchestration-v2/ProviderRuntimeRecoveryPolicy", {
|
||||
defaultValue: () => ({ maxAttempts: 3 }),
|
||||
}) {}
|
||||
|
||||
export function recoverWithPolicy<A, E>(input: {
|
||||
readonly operation: Effect.Effect<A, E>;
|
||||
readonly classify: (cause: E) => ClassifiedProviderRuntimeFailure;
|
||||
readonly connectivity: ConnectivityServiceShape;
|
||||
readonly maxAttempts: number;
|
||||
readonly idempotent: boolean;
|
||||
}): Effect.Effect<A, E> {
|
||||
const attempt = (attemptNumber: number): Effect.Effect<A, E> =>
|
||||
input.operation.pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.gen(function* () {
|
||||
const classified = input.classify(cause);
|
||||
const online = yield* input.connectivity.isOnline;
|
||||
const decision = decideProviderRuntimeRecovery({
|
||||
kind: classified.kind,
|
||||
attempt: attemptNumber,
|
||||
maxAttempts: input.maxAttempts,
|
||||
idempotent: input.idempotent,
|
||||
online,
|
||||
...(classified.retryAfterMs === undefined
|
||||
? {}
|
||||
: { retryAfterMs: classified.retryAfterMs }),
|
||||
});
|
||||
switch (decision.type) {
|
||||
case "retry_now":
|
||||
return yield* attempt(attemptNumber + 1);
|
||||
case "retry_after":
|
||||
yield* Effect.sleep(Duration.millis(decision.delayMs));
|
||||
return yield* attempt(attemptNumber + 1);
|
||||
case "wait_for_connectivity":
|
||||
yield* input.connectivity.awaitOnline;
|
||||
return yield* attempt(attemptNumber + 1);
|
||||
case "terminalize":
|
||||
return yield* Effect.fail(cause);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
return attempt(1);
|
||||
}
|
||||
|
||||
export class ProviderRuntimeRecoveryService extends Context.Service<
|
||||
ProviderRuntimeRecoveryService,
|
||||
{
|
||||
readonly recover: Effect.Effect<ProviderRuntimeRecoverySummary, ProviderRuntimeRecoveryError>;
|
||||
}
|
||||
>()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {}
|
||||
|
||||
function activeRuns(projection: OrchestrationV2ThreadProjection) {
|
||||
return projection.runs.filter(
|
||||
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const projections = yield* ProjectionStore.ProjectionStoreV2;
|
||||
const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
|
||||
const eventSink = yield* EventSink.EventSinkV2;
|
||||
const ids = yield* IdAllocator.IdAllocatorV2;
|
||||
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
|
||||
const outbox = yield* EffectOutbox.EffectOutboxV2;
|
||||
const connectivity = yield* ConnectivityService;
|
||||
const classifier = yield* ProviderRuntimeFailureClassifier;
|
||||
const recoveryPolicy = yield* ProviderRuntimeRecoveryPolicy;
|
||||
|
||||
const terminalize = Effect.fn("ProviderRuntimeRecoveryService.terminalize")(function* (
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
detail: string,
|
||||
) {
|
||||
const now = yield* DateTime.now;
|
||||
const runs = activeRuns(projection);
|
||||
if (runs.length === 0) return 0;
|
||||
const commandId = CommandId.make(`command:recovery:terminalize:${projection.thread.id}`);
|
||||
const allocateEventId = () =>
|
||||
ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderRuntimeRecoveryError({
|
||||
operation: "terminalize",
|
||||
threadId: projection.thread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const events: Array<OrchestrationV2DomainEvent> = [];
|
||||
for (const run of runs) {
|
||||
events.push({
|
||||
id: yield* allocateEventId(),
|
||||
type: "run.updated",
|
||||
threadId: projection.thread.id,
|
||||
runId: run.id,
|
||||
providerInstanceId: run.providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: { ...run, status: "failed", completedAt: now },
|
||||
});
|
||||
for (const node of projection.nodes.filter(
|
||||
(candidate) =>
|
||||
candidate.runId === run.id &&
|
||||
(candidate.status === "pending" ||
|
||||
candidate.status === "running" ||
|
||||
candidate.status === "waiting"),
|
||||
)) {
|
||||
events.push({
|
||||
id: yield* allocateEventId(),
|
||||
type: "node.updated",
|
||||
threadId: projection.thread.id,
|
||||
runId: run.id,
|
||||
nodeId: node.id,
|
||||
providerInstanceId: run.providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: { ...node, status: "failed", completedAt: now },
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* eventSink
|
||||
.commitCommand({
|
||||
commandId,
|
||||
threadId: projection.thread.id,
|
||||
commandType: "provider-runtime.recovery-terminalize",
|
||||
acceptedAt: now,
|
||||
events,
|
||||
effects: [],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderRuntimeRecoveryError({
|
||||
operation: "terminalize",
|
||||
threadId: projection.thread.id,
|
||||
cause: { detail, cause },
|
||||
}),
|
||||
),
|
||||
);
|
||||
return runs.length;
|
||||
});
|
||||
|
||||
const expireOrphanedRequests = Effect.fn("ProviderRuntimeRecoveryService.expireOrphanedRequests")(
|
||||
function* (projection: OrchestrationV2ThreadProjection) {
|
||||
const requests = projection.runtimeRequests.filter((request) => request.status === "pending");
|
||||
if (requests.length === 0) return;
|
||||
const now = yield* DateTime.now;
|
||||
const commandId = CommandId.make(`command:recovery:expire-requests:${projection.thread.id}`);
|
||||
const events: Array<OrchestrationV2DomainEvent> = [];
|
||||
for (const request of requests) {
|
||||
events.push({
|
||||
id: yield* ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderRuntimeRecoveryError({
|
||||
operation: "terminalize",
|
||||
threadId: projection.thread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
type: "runtime-request.updated",
|
||||
threadId: projection.thread.id,
|
||||
nodeId: request.nodeId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
...request,
|
||||
status: "expired",
|
||||
responseCapability: {
|
||||
type: "not_resumable",
|
||||
reason: "The server restarted before this runtime request was resolved.",
|
||||
},
|
||||
resolvedAt: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* eventSink
|
||||
.commitCommand({
|
||||
commandId,
|
||||
threadId: projection.thread.id,
|
||||
commandType: "provider-runtime.expire-orphaned-requests",
|
||||
acceptedAt: now,
|
||||
events,
|
||||
effects: [],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderRuntimeRecoveryError({
|
||||
operation: "terminalize",
|
||||
threadId: projection.thread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const recoverProjection = Effect.fn("ProviderRuntimeRecoveryService.recoverProjection")(
|
||||
function* (projection: OrchestrationV2ThreadProjection) {
|
||||
yield* expireOrphanedRequests(projection);
|
||||
let resumedSessions = 0;
|
||||
for (const session of projection.providerSessions.filter(
|
||||
(candidate) => candidate.status !== "stopped" && candidate.status !== "error",
|
||||
)) {
|
||||
const resume = sessions
|
||||
.open({
|
||||
threadId: projection.thread.id,
|
||||
providerSessionId: session.id,
|
||||
modelSelection: projection.thread.modelSelection,
|
||||
runtimePolicy: {
|
||||
runtimeMode: projection.thread.runtimeMode,
|
||||
interactionMode: projection.thread.interactionMode,
|
||||
cwd: session.cwd,
|
||||
},
|
||||
resumeFromSession: session,
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((runtime) =>
|
||||
Effect.forEach(
|
||||
projection.providerThreads.filter(
|
||||
(providerThread) =>
|
||||
providerThread.providerSessionId === session.id &&
|
||||
providerThread.appThreadId === projection.thread.id &&
|
||||
providerThread.status !== "closed" &&
|
||||
providerThread.status !== "archived",
|
||||
),
|
||||
(providerThread) =>
|
||||
runtime.resumeThread({
|
||||
providerThread,
|
||||
threadId: projection.thread.id,
|
||||
modelSelection: projection.thread.modelSelection,
|
||||
runtimePolicy: {
|
||||
runtimeMode: projection.thread.runtimeMode,
|
||||
interactionMode: projection.thread.interactionMode,
|
||||
cwd: session.cwd,
|
||||
},
|
||||
}),
|
||||
{ discard: true },
|
||||
),
|
||||
),
|
||||
);
|
||||
const recovered = yield* Effect.result(
|
||||
recoverWithPolicy({
|
||||
operation: resume,
|
||||
classify: classifier.classify,
|
||||
connectivity,
|
||||
maxAttempts: recoveryPolicy.maxAttempts,
|
||||
idempotent: true,
|
||||
}),
|
||||
);
|
||||
if (recovered._tag === "Failure") {
|
||||
const terminalizedRuns = yield* terminalize(
|
||||
projection,
|
||||
`Unable to resume provider session ${session.id}.`,
|
||||
);
|
||||
return { resumedSessions, terminalizedRuns };
|
||||
}
|
||||
resumedSessions += 1;
|
||||
}
|
||||
if (
|
||||
resumedSessions === 0 &&
|
||||
projection.runs.some((run) => run.status === "running" || run.status === "waiting")
|
||||
) {
|
||||
const terminalizedRuns = yield* terminalize(
|
||||
projection,
|
||||
"No resumable provider session remained for the active run.",
|
||||
);
|
||||
return { resumedSessions, terminalizedRuns };
|
||||
}
|
||||
return { resumedSessions, terminalizedRuns: 0 };
|
||||
},
|
||||
);
|
||||
|
||||
const recover = Effect.gen(function* () {
|
||||
const shell = yield* projections
|
||||
.getShellSnapshot()
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
|
||||
),
|
||||
);
|
||||
let resumedSessions = 0;
|
||||
let terminalizedRuns = 0;
|
||||
for (const thread of shell.threads) {
|
||||
const projection = yield* projections.getThreadProjection(thread.id).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderRuntimeRecoveryError({
|
||||
operation: "read-projections",
|
||||
threadId: thread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const result = yield* recoverProjection(projection);
|
||||
resumedSessions += result.resumedSessions;
|
||||
terminalizedRuns += result.terminalizedRuns;
|
||||
}
|
||||
let executedEffects = 0;
|
||||
yield* outbox.reclaimRunning.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
|
||||
),
|
||||
);
|
||||
while (
|
||||
yield* worker.runOnce.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
|
||||
),
|
||||
)
|
||||
) {
|
||||
executedEffects += 1;
|
||||
}
|
||||
return { resumedSessions, terminalizedRuns, executedEffects };
|
||||
});
|
||||
|
||||
return ProviderRuntimeRecoveryService.of({ recover });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);
|
||||
@@ -1205,23 +1205,3 @@ it.effect(
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.todo(
|
||||
"ProviderRuntimeRecoveryService restarts process_exited or transport_unavailable sessions with a bounded retry policy and resumes the native provider thread",
|
||||
);
|
||||
|
||||
it.todo(
|
||||
"ProviderRuntimeRecoveryService waits for ConnectivityService online before recovering network_unavailable sessions",
|
||||
);
|
||||
|
||||
it.todo(
|
||||
"ProviderRuntimeRecoveryService does not auto-recover provider_quota_exceeded, auth_invalid, permission_denied, invalid_request, or unsupported_model failures",
|
||||
);
|
||||
|
||||
it.todo(
|
||||
"ProviderRuntimeRecoveryService retries provider_rate_limited failures only when retry-after, idempotency, and retry budget allow it",
|
||||
);
|
||||
|
||||
it.todo(
|
||||
"ProviderRuntimeRecoveryService marks pending approvals and user-input requests non-live when a provider session is released or crashes",
|
||||
);
|
||||
@@ -88,3 +88,23 @@ it("uses portable handoff for incompatible continuation identities", () => {
|
||||
{ type: "create_with_handoff" },
|
||||
);
|
||||
});
|
||||
|
||||
it("uses portable handoff for cross-driver transitions", () => {
|
||||
const claudeDriver = ProviderDriverKind.make("claude");
|
||||
assert.deepEqual(
|
||||
decideProviderSessionTransition({
|
||||
current: base,
|
||||
target: {
|
||||
...base,
|
||||
driver: claudeDriver,
|
||||
continuationIdentity: { driverKind: claudeDriver, continuationKey: "claude:account:one" },
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claude"),
|
||||
model: "claude-opus-4-1",
|
||||
},
|
||||
available: true,
|
||||
},
|
||||
}),
|
||||
{ type: "create_with_handoff" },
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ProviderSessionId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
||||
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
|
||||
import * as ProviderSwitch from "./ProviderSwitchService.ts";
|
||||
|
||||
const driver = ProviderDriverKind.make("codex");
|
||||
const currentInstanceId = ProviderInstanceId.make("codex_primary");
|
||||
const currentSessionId = ProviderSessionId.make("session_primary");
|
||||
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
|
||||
const capabilitiesWithoutModelSwitch = {
|
||||
...CodexProviderCapabilitiesV2,
|
||||
sessions: {
|
||||
...CodexProviderCapabilitiesV2.sessions,
|
||||
supportsModelSwitchInSession: false,
|
||||
},
|
||||
};
|
||||
|
||||
function projection(): OrchestrationV2ThreadProjection {
|
||||
return {
|
||||
thread: {
|
||||
id: ThreadId.make("thread_switch_service"),
|
||||
modelSelection: { instanceId: currentInstanceId, model: "gpt-5.1-codex" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
worktreePath: "/repo",
|
||||
},
|
||||
providerSessions: [
|
||||
{
|
||||
id: currentSessionId,
|
||||
providerInstanceId: currentInstanceId,
|
||||
status: "ready",
|
||||
cwd: "/repo",
|
||||
capabilities: capabilitiesWithoutModelSwitch,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
providerThreads: [],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
}
|
||||
|
||||
function testLayer(metadata: Readonly<Record<string, { continuationKey: string }>>) {
|
||||
const registry = Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
|
||||
getMetadata: (instanceId) => {
|
||||
const value = metadata[instanceId];
|
||||
return value === undefined
|
||||
? Effect.fail(
|
||||
new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }),
|
||||
)
|
||||
: Effect.succeed({
|
||||
driver,
|
||||
continuationKey: value.continuationKey,
|
||||
enabled: true,
|
||||
capabilities: capabilitiesWithoutModelSwitch,
|
||||
});
|
||||
},
|
||||
});
|
||||
return ProviderSwitch.layer.pipe(Layer.provide(registry));
|
||||
}
|
||||
|
||||
it.effect(
|
||||
"restarts and releases the current session for unsupported in-session model changes",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
|
||||
const result = yield* service.plan({
|
||||
projection: projection(),
|
||||
targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
|
||||
});
|
||||
assert.equal(result.transition.type, "restart_and_resume");
|
||||
assert.deepEqual(result.releaseProviderSessionIds, [currentSessionId]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("distinguishes compatible and incompatible instances of the same driver", () =>
|
||||
Effect.gen(function* () {
|
||||
const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
|
||||
const compatibleId = ProviderInstanceId.make("codex_compatible");
|
||||
const incompatibleId = ProviderInstanceId.make("codex_incompatible");
|
||||
const compatible = yield* service.plan({
|
||||
projection: projection(),
|
||||
targetModelSelection: { instanceId: compatibleId, model: "gpt-5.1-codex" },
|
||||
});
|
||||
const incompatible = yield* service.plan({
|
||||
projection: projection(),
|
||||
targetModelSelection: { instanceId: incompatibleId, model: "gpt-5.1-codex" },
|
||||
});
|
||||
assert.equal(compatible.transition.type, "restart_and_resume");
|
||||
assert.equal(incompatible.transition.type, "create_with_handoff");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer({
|
||||
[currentInstanceId]: { continuationKey: "codex:account:primary" },
|
||||
codex_compatible: { continuationKey: "codex:account:primary" },
|
||||
codex_incompatible: { continuationKey: "codex:account:other" },
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -9,13 +9,21 @@ 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 * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
|
||||
import {
|
||||
decideProviderSessionTransition,
|
||||
type ProviderSessionTransition,
|
||||
} from "./ProviderSessionTransitionPolicy.ts";
|
||||
|
||||
export interface ProviderSwitchPlanV2 {
|
||||
readonly instanceChanged: boolean;
|
||||
readonly modelChanged: boolean;
|
||||
readonly targetProviderThreadId: ProviderThreadId | null;
|
||||
readonly releaseProviderSessionIds: ReadonlyArray<ProviderSessionId>;
|
||||
readonly transition: ProviderSessionTransition;
|
||||
}
|
||||
|
||||
export class ProviderSwitchPlanError extends Schema.TaggedErrorClass<ProviderSwitchPlanError>()(
|
||||
@@ -39,49 +47,128 @@ export class ProviderSwitchServiceV2 extends Context.Service<
|
||||
ProviderSwitchServiceV2Shape
|
||||
>()("t3/orchestration-v2/ProviderSwitchService/ProviderSwitchServiceV2") {}
|
||||
|
||||
export const layer: Layer.Layer<ProviderSwitchServiceV2> = Layer.succeed(
|
||||
export const layer: Layer.Layer<
|
||||
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({
|
||||
never,
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistryV2
|
||||
> = Layer.effect(
|
||||
ProviderSwitchServiceV2,
|
||||
Effect.gen(function* () {
|
||||
const adapters = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
|
||||
return ProviderSwitchServiceV2.of({
|
||||
plan: ({ projection, targetModelSelection }) =>
|
||||
Effect.gen(function* () {
|
||||
const current = projection.thread.modelSelection;
|
||||
const instanceChanged = current.instanceId !== targetModelSelection.instanceId;
|
||||
const modelChanged = current.model !== targetModelSelection.model;
|
||||
const getMetadata = (instanceId: typeof current.instanceId) =>
|
||||
adapters.getMetadata !== undefined
|
||||
? adapters.getMetadata(instanceId)
|
||||
: adapters.get(instanceId).pipe(
|
||||
Effect.flatMap((adapter) =>
|
||||
adapter.getCapabilities().pipe(
|
||||
Effect.map((capabilities) => ({
|
||||
driver: adapter.driver,
|
||||
continuationKey: `${adapter.driver}:instance:${instanceId}`,
|
||||
enabled: true,
|
||||
capabilities,
|
||||
})),
|
||||
),
|
||||
),
|
||||
);
|
||||
const currentInstance = yield* Effect.option(getMetadata(current.instanceId));
|
||||
const targetInstance = yield* Effect.option(getMetadata(targetModelSelection.instanceId));
|
||||
const currentSession = projection.providerSessions
|
||||
.filter((session) => session.providerInstanceId === current.instanceId)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
|
||||
)[0];
|
||||
const transition = Option.isNone(targetInstance)
|
||||
? ({
|
||||
type: "reject",
|
||||
reason: "The target provider instance is unavailable.",
|
||||
} as const)
|
||||
: decideProviderSessionTransition({
|
||||
current:
|
||||
Option.isNone(currentInstance) || currentSession === undefined
|
||||
? null
|
||||
: {
|
||||
driver: currentInstance.value.driver,
|
||||
continuationIdentity: {
|
||||
driverKind: currentInstance.value.driver,
|
||||
continuationKey: currentInstance.value.continuationKey,
|
||||
},
|
||||
modelSelection: current,
|
||||
runtimeMode: projection.thread.runtimeMode,
|
||||
interactionMode: projection.thread.interactionMode,
|
||||
workspace: currentSession.cwd,
|
||||
capabilities: currentSession.capabilities,
|
||||
},
|
||||
target: {
|
||||
driver: targetInstance.value.driver,
|
||||
continuationIdentity: {
|
||||
driverKind: targetInstance.value.driver,
|
||||
continuationKey: targetInstance.value.continuationKey,
|
||||
},
|
||||
modelSelection: targetModelSelection,
|
||||
runtimeMode: projection.thread.runtimeMode,
|
||||
interactionMode: projection.thread.interactionMode,
|
||||
workspace:
|
||||
projection.thread.worktreePath ??
|
||||
currentSession?.cwd ??
|
||||
"<unresolved-workspace>",
|
||||
capabilities: targetInstance.value.capabilities,
|
||||
available: targetInstance.value.enabled,
|
||||
},
|
||||
});
|
||||
if (transition.type === "reject") {
|
||||
return yield* new ProviderSwitchPlanError({
|
||||
threadId: projection.thread.id,
|
||||
targetProviderInstanceId: targetModelSelection.instanceId,
|
||||
cause,
|
||||
}),
|
||||
cause: transition.reason,
|
||||
});
|
||||
}
|
||||
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 (transition.type === "restart_and_resume") {
|
||||
return session.id === currentSession?.id;
|
||||
}
|
||||
if (transition.type === "create_with_handoff") {
|
||||
return session.providerInstanceId !== targetModelSelection.instanceId;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.map((session) => session.id);
|
||||
return {
|
||||
instanceChanged,
|
||||
modelChanged,
|
||||
targetProviderThreadId: targetProviderThread?.id ?? null,
|
||||
releaseProviderSessionIds,
|
||||
transition,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSwitchPlanError({
|
||||
threadId: projection.thread.id,
|
||||
targetProviderInstanceId: targetModelSelection.instanceId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -15,7 +15,10 @@ import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import { providerMessageWithContextHandoffs } from "./ContextHandoffService.ts";
|
||||
import {
|
||||
ContextHandoffServiceV2,
|
||||
providerMessageWithContextHandoffs,
|
||||
} from "./ContextHandoffService.ts";
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
|
||||
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
|
||||
@@ -46,6 +49,7 @@ export const layer: Layer.Layer<
|
||||
ProviderTurnStartServiceV2,
|
||||
never,
|
||||
| EventSinkV2
|
||||
| ContextHandoffServiceV2
|
||||
| IdAllocatorV2
|
||||
| ProjectionStoreV2
|
||||
| ProviderSessionManagerV2
|
||||
@@ -55,6 +59,7 @@ export const layer: Layer.Layer<
|
||||
ProviderTurnStartServiceV2,
|
||||
Effect.gen(function* () {
|
||||
const eventSink = yield* EventSinkV2;
|
||||
const contextHandoffService = yield* ContextHandoffServiceV2;
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const projectionStore = yield* ProjectionStoreV2;
|
||||
const providerSessions = yield* ProviderSessionManagerV2;
|
||||
@@ -95,6 +100,15 @@ export const layer: Layer.Layer<
|
||||
transfer.status === "pending" &&
|
||||
transfer.resolution === null,
|
||||
);
|
||||
const existingResumeFallback = projection.contextTransfers.find(
|
||||
(transfer) =>
|
||||
transfer.type === "provider_handoff" &&
|
||||
transfer.sourceThreadId === projection.thread.id &&
|
||||
transfer.targetThreadId === projection.thread.id &&
|
||||
transfer.targetRunId === run.id &&
|
||||
transfer.status === "resolved_portable" &&
|
||||
transfer.resolution?.strategy === "portable_context",
|
||||
);
|
||||
if (
|
||||
rootNode === undefined ||
|
||||
attempt === undefined ||
|
||||
@@ -126,6 +140,7 @@ export const layer: Layer.Layer<
|
||||
? {}
|
||||
: { resumeFromSession: existingSessionProjection }),
|
||||
});
|
||||
let effectiveHandoffs = handoffs;
|
||||
const loadedProviderThread = yield* Effect.gen(function* () {
|
||||
if (nativeForkTransfer !== undefined) {
|
||||
const sourceProjection = yield* projectionStore.getThreadProjection(
|
||||
@@ -160,19 +175,95 @@ export const layer: Layer.Layer<
|
||||
...(sourceProviderTurn === undefined ? {} : { providerTurnId: sourceProviderTurn.id }),
|
||||
});
|
||||
}
|
||||
return providerThread.nativeThreadRef === null
|
||||
? yield* session.ensureThread({
|
||||
if (providerThread.nativeThreadRef === null) {
|
||||
return yield* session.ensureThread({
|
||||
threadId: projection.thread.id,
|
||||
modelSelection: run.modelSelection,
|
||||
runtimePolicy: resolvedRuntimePolicy,
|
||||
providerSessionId,
|
||||
});
|
||||
}
|
||||
const resumed = yield* Effect.result(
|
||||
session.resumeThread({
|
||||
providerThread,
|
||||
threadId: projection.thread.id,
|
||||
modelSelection: run.modelSelection,
|
||||
runtimePolicy: resolvedRuntimePolicy,
|
||||
}),
|
||||
);
|
||||
if (resumed._tag === "Success") {
|
||||
return resumed.success;
|
||||
}
|
||||
|
||||
const replacement = yield* session.ensureThread({
|
||||
threadId: projection.thread.id,
|
||||
modelSelection: run.modelSelection,
|
||||
runtimePolicy: resolvedRuntimePolicy,
|
||||
providerSessionId,
|
||||
});
|
||||
if (existingResumeFallback !== undefined) {
|
||||
return replacement;
|
||||
}
|
||||
const transferId = yield* idAllocator.allocate.contextTransfer({
|
||||
sourceThreadId: projection.thread.id,
|
||||
targetThreadId: projection.thread.id,
|
||||
type: "provider_resume_fallback",
|
||||
});
|
||||
const createdAt = yield* DateTime.now;
|
||||
const handoff = yield* contextHandoffService.prepareProviderHandoff({
|
||||
threadId: projection.thread.id,
|
||||
targetRunId: run.id,
|
||||
transferId,
|
||||
fromProviderThreadIds: [providerThread.id],
|
||||
toProviderThreadId: providerThread.id,
|
||||
fromProviderInstanceId: providerThread.providerInstanceId,
|
||||
toProviderInstanceId: run.providerInstanceId,
|
||||
coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },
|
||||
strategy: "full_thread_summary",
|
||||
items: projection.turnItems,
|
||||
createdAt,
|
||||
});
|
||||
effectiveHandoffs = [...handoffs, handoff];
|
||||
yield* eventSink.write({
|
||||
events: [
|
||||
{
|
||||
id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
|
||||
type: "context-handoff.updated",
|
||||
threadId: projection.thread.id,
|
||||
modelSelection: run.modelSelection,
|
||||
runtimePolicy: resolvedRuntimePolicy,
|
||||
providerSessionId,
|
||||
})
|
||||
: yield* session.resumeThread({
|
||||
providerThread,
|
||||
runId: run.id,
|
||||
providerInstanceId: run.providerInstanceId,
|
||||
occurredAt: createdAt,
|
||||
payload: handoff,
|
||||
},
|
||||
{
|
||||
id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
|
||||
type: "context-transfer.updated",
|
||||
threadId: projection.thread.id,
|
||||
modelSelection: run.modelSelection,
|
||||
runtimePolicy: resolvedRuntimePolicy,
|
||||
});
|
||||
runId: run.id,
|
||||
providerInstanceId: run.providerInstanceId,
|
||||
occurredAt: createdAt,
|
||||
payload: {
|
||||
id: transferId,
|
||||
type: "provider_handoff",
|
||||
sourceThreadId: projection.thread.id,
|
||||
targetThreadId: projection.thread.id,
|
||||
sourcePoint: { threadId: projection.thread.id },
|
||||
basePoint: null,
|
||||
sourceProviderInstanceId: providerThread.providerInstanceId,
|
||||
targetProviderInstanceId: run.providerInstanceId,
|
||||
targetRunId: run.id,
|
||||
status: "resolved_portable",
|
||||
resolution: { strategy: "portable_context", contextHandoffId: handoff.id },
|
||||
createdBy: "system",
|
||||
error: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
consumedAt: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
return replacement;
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const runningProviderThread: OrchestrationV2ProviderThread = {
|
||||
@@ -322,9 +413,12 @@ export const layer: Layer.Layer<
|
||||
message: {
|
||||
messageId: message.id,
|
||||
text:
|
||||
handoffs.length === 0
|
||||
effectiveHandoffs.length === 0
|
||||
? message.text
|
||||
: providerMessageWithContextHandoffs({ handoffs, userText: message.text }),
|
||||
: providerMessageWithContextHandoffs({
|
||||
handoffs: effectiveHandoffs,
|
||||
userText: message.text,
|
||||
}),
|
||||
attachments: message.attachments,
|
||||
createdBy: message.createdBy,
|
||||
creationSource: message.creationSource,
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { resolveAttachmentPathById } from "../attachmentStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as TerminalManager from "../terminal/Manager.ts";
|
||||
|
||||
export class ResourceCleanupError extends Schema.TaggedErrorClass<ResourceCleanupError>()(
|
||||
"ResourceCleanupError",
|
||||
{
|
||||
operation: Schema.Literals(["terminal", "attachment"]),
|
||||
threadId: Schema.optional(Schema.String),
|
||||
attachmentId: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {}
|
||||
|
||||
export class ResourceCleanupService extends Context.Reference<{
|
||||
readonly cleanupTerminals: (threadId: string) => Effect.Effect<void, ResourceCleanupError>;
|
||||
readonly cleanupAttachments: (
|
||||
attachmentIds: ReadonlyArray<string>,
|
||||
) => Effect.Effect<void, ResourceCleanupError>;
|
||||
}>("t3/orchestration-v2/ResourceCleanupService", {
|
||||
defaultValue: () => ({
|
||||
cleanupTerminals: () => Effect.void,
|
||||
cleanupAttachments: () => Effect.void,
|
||||
}),
|
||||
}) {}
|
||||
|
||||
export const live = Layer.effect(
|
||||
ResourceCleanupService,
|
||||
Effect.gen(function* () {
|
||||
const terminals = yield* TerminalManager.TerminalManager;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
return {
|
||||
cleanupTerminals: (threadId: string) =>
|
||||
terminals
|
||||
.close({ threadId, deleteHistory: true })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ResourceCleanupError({ operation: "terminal", threadId, cause }),
|
||||
),
|
||||
),
|
||||
cleanupAttachments: (attachmentIds: ReadonlyArray<string>) =>
|
||||
Effect.forEach(
|
||||
attachmentIds,
|
||||
(attachmentId) => {
|
||||
const path = resolveAttachmentPathById({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
attachmentId,
|
||||
});
|
||||
return path === null
|
||||
? Effect.void
|
||||
: fileSystem
|
||||
.remove(path, { force: true })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ResourceCleanupError({ operation: "attachment", attachmentId, cause }),
|
||||
),
|
||||
);
|
||||
},
|
||||
{ discard: true, concurrency: 4 },
|
||||
),
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,41 @@
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import {
|
||||
CheckpointScopeId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as CheckpointCapture from "./CheckpointCaptureService.ts";
|
||||
import * as ProjectionStore from "./ProjectionStore.ts";
|
||||
import * as RunFinalization from "./RunFinalizationService.ts";
|
||||
|
||||
it.effect("captures the root checkpoint and refreshes workspace state", () => {
|
||||
const threadId = ThreadId.make("thread_finalize");
|
||||
const runId = RunId.make("run_finalize");
|
||||
const scopeId = CheckpointScopeId.make("scope_finalize");
|
||||
const capture = vi.fn(() => Effect.void);
|
||||
const refresh = vi.fn(() => Effect.void);
|
||||
const projection = {
|
||||
checkpointScopes: [{ id: scopeId, cwd: "/repo" }],
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
const layer = RunFinalization.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(CheckpointCapture.CheckpointCaptureServiceV2)({ execute: capture }),
|
||||
Layer.mock(ProjectionStore.ProjectionStoreV2)({
|
||||
getThreadProjection: () => Effect.succeed(projection),
|
||||
}),
|
||||
Layer.succeed(RunFinalization.RunFinalizationObserver, { refresh }),
|
||||
),
|
||||
),
|
||||
);
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* RunFinalization.RunFinalizationService;
|
||||
yield* service.finalize({ threadId, runId, scopeId });
|
||||
assert.equal(capture.mock.calls.length, 1);
|
||||
assert.deepEqual(refresh.mock.calls[0], ["/repo"]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { CheckpointScopeId, RunId, ThreadId } 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 VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
|
||||
import * as WorkspaceEntries from "../workspace/WorkspaceEntries.ts";
|
||||
import * as CheckpointCapture from "./CheckpointCaptureService.ts";
|
||||
import * as ProjectionStore from "./ProjectionStore.ts";
|
||||
|
||||
export class RunFinalizationError extends Schema.TaggedErrorClass<RunFinalizationError>()(
|
||||
"RunFinalizationError",
|
||||
{
|
||||
threadId: ThreadId,
|
||||
runId: RunId,
|
||||
scopeId: CheckpointScopeId,
|
||||
operation: Schema.Literals(["capture-checkpoint", "refresh-workspace"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {}
|
||||
|
||||
export class RunFinalizationRefreshError extends Schema.TaggedErrorClass<RunFinalizationRefreshError>()(
|
||||
"RunFinalizationRefreshError",
|
||||
{ cwd: Schema.String, cause: Schema.Defect() },
|
||||
) {}
|
||||
|
||||
export class RunFinalizationObserver extends Context.Reference<{
|
||||
readonly refresh: (cwd: string) => Effect.Effect<void, RunFinalizationRefreshError>;
|
||||
}>("t3/orchestration-v2/RunFinalizationObserver", {
|
||||
defaultValue: () => ({ refresh: () => Effect.void }),
|
||||
}) {}
|
||||
|
||||
export class RunFinalizationService extends Context.Service<
|
||||
RunFinalizationService,
|
||||
{
|
||||
readonly finalize: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly runId: RunId;
|
||||
readonly scopeId: CheckpointScopeId;
|
||||
}) => Effect.Effect<void, RunFinalizationError>;
|
||||
}
|
||||
>()("t3/orchestration-v2/RunFinalizationService") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const checkpointCapture = yield* CheckpointCapture.CheckpointCaptureServiceV2;
|
||||
const projections = yield* ProjectionStore.ProjectionStoreV2;
|
||||
const observer = yield* RunFinalizationObserver;
|
||||
|
||||
const finalize: RunFinalizationService["Service"]["finalize"] = Effect.fn(
|
||||
"RunFinalizationService.finalize",
|
||||
)(function* (input) {
|
||||
yield* checkpointCapture
|
||||
.execute(input)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new RunFinalizationError({ ...input, operation: "capture-checkpoint", cause }),
|
||||
),
|
||||
);
|
||||
const projection = yield* projections
|
||||
.getThreadProjection(input.threadId)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new RunFinalizationError({ ...input, operation: "refresh-workspace", cause }),
|
||||
),
|
||||
);
|
||||
const cwd = projection.checkpointScopes.find((scope) => scope.id === input.scopeId)?.cwd;
|
||||
if (cwd !== undefined) {
|
||||
yield* observer
|
||||
.refresh(cwd)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new RunFinalizationError({ ...input, operation: "refresh-workspace", cause }),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
return RunFinalizationService.of({ finalize });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(RunFinalizationService, make);
|
||||
|
||||
export const observerLive = Layer.effect(
|
||||
RunFinalizationObserver,
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
|
||||
const vcsStatus = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
return {
|
||||
refresh: (cwd: string) =>
|
||||
Effect.all([workspaceEntries.refresh(cwd), vcsStatus.refreshStatus(cwd)], {
|
||||
discard: true,
|
||||
concurrency: "unbounded",
|
||||
}).pipe(Effect.mapError((cause) => new RunFinalizationRefreshError({ cwd, cause }))),
|
||||
};
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,260 @@
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import {
|
||||
EventId,
|
||||
CommandId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationV2DomainEvent,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
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 Stream from "effect/Stream";
|
||||
|
||||
import * as GitWorkflow from "../git/GitWorkflowService.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as ProjectService from "../project/ProjectService.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as IdAllocator from "./IdAllocator.ts";
|
||||
import { OrchestratorDispatchError, type OrchestratorV2DispatchResult } from "./Orchestrator.ts";
|
||||
import { emptyProjection } from "./ProjectionStore.ts";
|
||||
import * as ThreadLaunch from "./ThreadLaunchService.ts";
|
||||
import * as ThreadManagement from "./ThreadManagementService.ts";
|
||||
|
||||
const projectId = ProjectId.make("project_launch_test");
|
||||
const modelSelection = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.1-codex",
|
||||
} as const;
|
||||
const project = {
|
||||
id: projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo",
|
||||
repositoryIdentity: null,
|
||||
faviconPath: null,
|
||||
defaultModelSelection: modelSelection,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
updatedAt: "2026-06-20T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
} as const;
|
||||
|
||||
function projectionFor(threadId: ThreadId): OrchestrationV2ThreadProjection {
|
||||
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
|
||||
const event = {
|
||||
id: EventId.make(`event:${threadId}`),
|
||||
type: "thread.created",
|
||||
threadId,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
} satisfies Extract<OrchestrationV2DomainEvent, { readonly type: "thread.created" }>;
|
||||
return emptyProjection(event);
|
||||
}
|
||||
|
||||
const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup?: boolean }) => {
|
||||
const projections = new Map<ThreadId, OrchestrationV2ThreadProjection>();
|
||||
const dispatch = vi.fn(
|
||||
(
|
||||
command: Parameters<ThreadManagement.ThreadManagementService["Service"]["dispatch"]>[0],
|
||||
): Effect.Effect<OrchestratorV2DispatchResult, OrchestratorDispatchError> => {
|
||||
if (command.type !== "thread.create") return Effect.die("unexpected command");
|
||||
if (options?.failCreate) {
|
||||
return Effect.fail(
|
||||
new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: "create failed",
|
||||
}),
|
||||
);
|
||||
}
|
||||
projections.set(command.threadId, projectionFor(command.threadId));
|
||||
return Effect.succeed({ sequence: 1, storedEvents: [] });
|
||||
},
|
||||
);
|
||||
const createWorktree = vi.fn(() =>
|
||||
Effect.succeed({
|
||||
worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" },
|
||||
} as never),
|
||||
);
|
||||
const removeWorktree = vi.fn(() => Effect.void);
|
||||
const runForThread = vi.fn(() =>
|
||||
options?.failSetup
|
||||
? Effect.fail(
|
||||
new ProjectSetupScriptRunner.ProjectSetupScriptOperationError({
|
||||
threadId: "thread",
|
||||
worktreePath: "/repo-worktrees/feature",
|
||||
operation: "openTerminal",
|
||||
cause: "setup failed",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({ status: "no-script" as const }),
|
||||
);
|
||||
const sendToThread = vi.fn(() =>
|
||||
Effect.succeed({} as ThreadManagement.ThreadManagementSendResult),
|
||||
);
|
||||
|
||||
const dependencies = Layer.mergeAll(
|
||||
Layer.succeed(ProjectService.ProjectService, {
|
||||
create: () => Effect.die("unused"),
|
||||
bootstrap: () => Effect.die("unused"),
|
||||
update: () => Effect.die("unused"),
|
||||
delete: () => Effect.die("unused"),
|
||||
getById: (id) => Effect.succeed(id === projectId ? Option.some(project) : Option.none()),
|
||||
getByWorkspaceRoot: () => Effect.succeed(Option.some(project)),
|
||||
snapshot: Effect.die("unused"),
|
||||
changes: Stream.empty,
|
||||
}),
|
||||
Layer.mock(GitWorkflow.GitWorkflowService)({ createWorktree, removeWorktree }),
|
||||
Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, {
|
||||
runForThread,
|
||||
}),
|
||||
Layer.mock(TextGeneration.TextGeneration)({
|
||||
generateThreadTitle: () => Effect.succeed({ title: "Generated title" }),
|
||||
generateBranchName: () => Effect.succeed({ branch: "generated-branch" }),
|
||||
}),
|
||||
Layer.mock(ThreadManagement.ThreadManagementService)({
|
||||
dispatch,
|
||||
getThreadProjection: (threadId) =>
|
||||
projections.has(threadId)
|
||||
? Effect.succeed(projections.get(threadId)!)
|
||||
: Effect.die("missing projection"),
|
||||
sendToThread,
|
||||
}),
|
||||
IdAllocator.layer,
|
||||
);
|
||||
return {
|
||||
layer: ThreadLaunch.layer.pipe(
|
||||
Layer.provideMerge(dependencies),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
),
|
||||
dispatch,
|
||||
createWorktree,
|
||||
removeWorktree,
|
||||
runForThread,
|
||||
sendToThread,
|
||||
};
|
||||
};
|
||||
|
||||
it.effect("persists root-workspace launches and returns the committed workflow on retry", () => {
|
||||
const test = makeLayer();
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
const input = {
|
||||
commandId: CommandId.make("command_launch_root"),
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access" as const,
|
||||
interactionMode: "default" as const,
|
||||
workspaceStrategy: { type: "root" as const },
|
||||
createdBy: "user" as const,
|
||||
creationSource: "web" as const,
|
||||
};
|
||||
const first = yield* service.launch(input);
|
||||
const retry = yield* service.launch(input);
|
||||
assert.equal(first.threadId, retry.threadId);
|
||||
assert.isFalse(first.resumed);
|
||||
assert.isTrue(retry.resumed);
|
||||
assert.equal(test.dispatch.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"generates first-run title and branch, runs setup once, and sends the initial message",
|
||||
() => {
|
||||
const test = makeLayer();
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
const input = {
|
||||
commandId: CommandId.make("command_launch_generated"),
|
||||
projectId,
|
||||
title: "New thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access" as const,
|
||||
interactionMode: "default" as const,
|
||||
workspaceStrategy: { type: "worktree" as const, baseRef: "main" },
|
||||
initialMessage: { text: "Build the feature", attachments: [] },
|
||||
createdBy: "user" as const,
|
||||
creationSource: "web" as const,
|
||||
};
|
||||
yield* service.launch(input);
|
||||
yield* service.launch(input);
|
||||
const createCommand = test.dispatch.mock.calls[0]?.[0];
|
||||
assert.equal(createCommand?.type, "thread.create");
|
||||
if (createCommand?.type === "thread.create") {
|
||||
assert.equal(createCommand.title, "Generated title");
|
||||
assert.equal(createCommand.branch, "feature");
|
||||
}
|
||||
assert.equal(test.runForThread.mock.calls.length, 1);
|
||||
assert.equal(test.sendToThread.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("removes a new worktree and does not create a thread when setup fails", () => {
|
||||
const test = makeLayer({ failSetup: true });
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
yield* service
|
||||
.launch({
|
||||
commandId: CommandId.make("command_launch_setup_failure"),
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
workspaceStrategy: { type: "worktree", baseRef: "main", branch: "feature" },
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
assert.equal(test.removeWorktree.mock.calls.length, 1);
|
||||
assert.equal(test.dispatch.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
});
|
||||
|
||||
it.effect("compensates a newly-created worktree when thread creation fails", () => {
|
||||
const test = makeLayer({ failCreate: true });
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLaunch.ThreadLaunchService;
|
||||
yield* service
|
||||
.launch({
|
||||
commandId: CommandId.make("command_launch_worktree"),
|
||||
projectId,
|
||||
title: "Thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
workspaceStrategy: { type: "worktree", baseRef: "main", branch: "feature" },
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
assert.equal(test.createWorktree.mock.calls.length, 1);
|
||||
assert.equal(test.removeWorktree.mock.calls.length, 1);
|
||||
}).pipe(Effect.provide(test.layer));
|
||||
});
|
||||
@@ -0,0 +1,410 @@
|
||||
import {
|
||||
CommandId,
|
||||
type ChatAttachment,
|
||||
type ModelSelection,
|
||||
type OrchestrationV2Actor,
|
||||
type OrchestrationV2CreationSource,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type ProviderInteractionMode,
|
||||
ProjectId,
|
||||
type RuntimeMode,
|
||||
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 * as Semaphore from "effect/Semaphore";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import * as GitWorkflow from "../git/GitWorkflowService.ts";
|
||||
import * as ProjectService from "../project/ProjectService.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as IdAllocator from "./IdAllocator.ts";
|
||||
import * as ThreadManagement from "./ThreadManagementService.ts";
|
||||
|
||||
export type ThreadLaunchWorkspaceStrategy =
|
||||
| { readonly type: "root" }
|
||||
| {
|
||||
readonly type: "worktree";
|
||||
readonly baseRef: string;
|
||||
readonly branch?: string;
|
||||
};
|
||||
|
||||
export interface ThreadLaunchInitialMessage {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
}
|
||||
|
||||
export interface ThreadLaunchInput {
|
||||
readonly commandId: CommandId;
|
||||
readonly projectId: ProjectId;
|
||||
readonly title: string;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy;
|
||||
readonly initialMessage?: ThreadLaunchInitialMessage;
|
||||
readonly createdBy: OrchestrationV2Actor;
|
||||
readonly creationSource: OrchestrationV2CreationSource;
|
||||
}
|
||||
|
||||
export interface ThreadLaunchResult {
|
||||
readonly threadId: ThreadId;
|
||||
readonly projection: OrchestrationV2ThreadProjection;
|
||||
readonly resumed: boolean;
|
||||
}
|
||||
|
||||
export class ThreadLaunchError extends Schema.TaggedErrorClass<ThreadLaunchError>()(
|
||||
"ThreadLaunchError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"resolve-project",
|
||||
"load-workflow",
|
||||
"persist-workflow",
|
||||
"generate-metadata",
|
||||
"provision-worktree",
|
||||
"run-setup-script",
|
||||
"create-thread",
|
||||
"dispatch-message",
|
||||
"compensate-worktree",
|
||||
]),
|
||||
commandId: CommandId,
|
||||
projectId: ProjectId,
|
||||
threadId: Schema.optional(ThreadId),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Thread launch ${this.commandId} failed during ${this.operation}.`;
|
||||
}
|
||||
}
|
||||
|
||||
type WorkflowRow = {
|
||||
readonly command_id: string;
|
||||
readonly thread_id: string;
|
||||
readonly project_id: string;
|
||||
readonly status: string;
|
||||
readonly title: string;
|
||||
readonly worktree_path: string | null;
|
||||
readonly branch: string | null;
|
||||
readonly setup_committed: number;
|
||||
readonly thread_committed: number;
|
||||
readonly message_committed: number;
|
||||
};
|
||||
|
||||
export class ThreadLaunchService extends Context.Service<
|
||||
ThreadLaunchService,
|
||||
{
|
||||
readonly launch: (
|
||||
input: ThreadLaunchInput,
|
||||
) => Effect.Effect<ThreadLaunchResult, ThreadLaunchError>;
|
||||
}
|
||||
>()("t3/orchestration-v2/ThreadLaunchService") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const projects = yield* ProjectService.ProjectService;
|
||||
const git = yield* GitWorkflow.GitWorkflowService;
|
||||
const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const textGeneration = yield* TextGeneration.TextGeneration;
|
||||
const ids = yield* IdAllocator.IdAllocatorV2;
|
||||
const threads = yield* ThreadManagement.ThreadManagementService;
|
||||
const launchSemaphore = yield* Semaphore.make(1);
|
||||
|
||||
const mapError =
|
||||
(input: ThreadLaunchInput, operation: ThreadLaunchError["operation"], threadId?: ThreadId) =>
|
||||
(cause: unknown) =>
|
||||
new ThreadLaunchError({
|
||||
operation,
|
||||
commandId: input.commandId,
|
||||
projectId: input.projectId,
|
||||
...(threadId === undefined ? {} : { threadId }),
|
||||
cause,
|
||||
});
|
||||
|
||||
const loadWorkflow = Effect.fn("ThreadLaunchService.loadWorkflow")(function* (
|
||||
input: ThreadLaunchInput,
|
||||
) {
|
||||
const rows = yield* sql<WorkflowRow>`
|
||||
SELECT * FROM orchestration_v2_thread_launch_workflows
|
||||
WHERE command_id = ${input.commandId}
|
||||
`.pipe(Effect.mapError(mapError(input, "load-workflow")));
|
||||
return rows[0] ?? null;
|
||||
});
|
||||
|
||||
const saveWorkflow = Effect.fn("ThreadLaunchService.saveWorkflow")(function* (
|
||||
input: ThreadLaunchInput,
|
||||
row: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly status: string;
|
||||
readonly title: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly branch: string | null;
|
||||
readonly setupCommitted: boolean;
|
||||
readonly threadCommitted: boolean;
|
||||
readonly messageCommitted: boolean;
|
||||
readonly lastError?: string | null;
|
||||
},
|
||||
) {
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_v2_thread_launch_workflows (
|
||||
command_id, thread_id, project_id, status, title, worktree_path, branch, setup_committed,
|
||||
thread_committed, message_committed, last_error, created_at, updated_at
|
||||
) VALUES (
|
||||
${input.commandId}, ${row.threadId}, ${input.projectId}, ${row.status}, ${row.title},
|
||||
${row.worktreePath}, ${row.branch}, ${row.setupCommitted ? 1 : 0}, ${row.threadCommitted ? 1 : 0},
|
||||
${row.messageCommitted ? 1 : 0}, ${row.lastError ?? null}, ${now}, ${now}
|
||||
) ON CONFLICT(command_id) DO UPDATE SET
|
||||
status = excluded.status,
|
||||
title = excluded.title,
|
||||
worktree_path = excluded.worktree_path,
|
||||
branch = excluded.branch,
|
||||
setup_committed = excluded.setup_committed,
|
||||
thread_committed = excluded.thread_committed,
|
||||
message_committed = excluded.message_committed,
|
||||
last_error = excluded.last_error,
|
||||
updated_at = excluded.updated_at
|
||||
`.pipe(Effect.mapError(mapError(input, "persist-workflow", row.threadId)));
|
||||
});
|
||||
|
||||
const launchWorkflow: ThreadLaunchService["Service"]["launch"] = Effect.fn(
|
||||
"ThreadLaunchService.launch",
|
||||
)(function* (input) {
|
||||
const project = yield* projects.getById(input.projectId).pipe(
|
||||
Effect.mapError(mapError(input, "resolve-project")),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.fail(mapError(input, "resolve-project")("Project not found.")),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const stored = yield* loadWorkflow(input);
|
||||
const threadId =
|
||||
stored === null
|
||||
? yield* ids.allocate
|
||||
.thread({ projectId: input.projectId })
|
||||
.pipe(Effect.mapError(mapError(input, "persist-workflow")))
|
||||
: ThreadId.make(stored.thread_id);
|
||||
if (stored?.status === "completed") {
|
||||
return {
|
||||
threadId,
|
||||
projection: yield* threads
|
||||
.getThreadProjection(threadId)
|
||||
.pipe(Effect.mapError(mapError(input, "create-thread", threadId))),
|
||||
resumed: true,
|
||||
};
|
||||
}
|
||||
|
||||
let branch = stored?.branch ?? null;
|
||||
let title = stored?.title ?? input.title;
|
||||
if (input.initialMessage !== undefined) {
|
||||
if (title === "New thread") {
|
||||
title = yield* textGeneration
|
||||
.generateThreadTitle({
|
||||
cwd: project.workspaceRoot,
|
||||
message: input.initialMessage.text,
|
||||
attachments: input.initialMessage.attachments,
|
||||
modelSelection: input.modelSelection,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => result.title),
|
||||
Effect.mapError(mapError(input, "generate-metadata", threadId)),
|
||||
);
|
||||
}
|
||||
if (input.workspaceStrategy.type === "worktree" && branch === null) {
|
||||
branch = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: project.workspaceRoot,
|
||||
message: input.initialMessage.text,
|
||||
attachments: input.initialMessage.attachments,
|
||||
modelSelection: input.modelSelection,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => result.branch),
|
||||
Effect.mapError(mapError(input, "generate-metadata", threadId)),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (input.workspaceStrategy.type === "worktree") {
|
||||
branch = branch ?? input.workspaceStrategy.branch ?? `thread-${threadId}`;
|
||||
}
|
||||
|
||||
let worktreePath = stored?.worktree_path ?? null;
|
||||
const threadCommitted = stored?.thread_committed === 1;
|
||||
let setupCommitted = stored?.setup_committed === 1;
|
||||
let messageCommitted = stored?.message_committed === 1;
|
||||
if (input.workspaceStrategy.type === "worktree" && worktreePath === null) {
|
||||
const worktree = yield* git
|
||||
.createWorktree({
|
||||
cwd: project.workspaceRoot,
|
||||
refName: input.workspaceStrategy.baseRef,
|
||||
newRefName: branch!,
|
||||
baseRefName: input.workspaceStrategy.baseRef,
|
||||
path: null,
|
||||
})
|
||||
.pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
|
||||
worktreePath = worktree.worktree.path;
|
||||
branch = worktree.worktree.refName;
|
||||
yield* saveWorkflow(input, {
|
||||
threadId,
|
||||
status: "workspace_ready",
|
||||
title,
|
||||
worktreePath,
|
||||
branch,
|
||||
setupCommitted,
|
||||
threadCommitted,
|
||||
messageCommitted,
|
||||
});
|
||||
}
|
||||
const cwd = worktreePath ?? project.workspaceRoot;
|
||||
|
||||
if (!setupCommitted) {
|
||||
const setupExit = yield* Effect.exit(
|
||||
setupScripts.runForThread({
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
projectCwd: project.workspaceRoot,
|
||||
worktreePath: cwd,
|
||||
project: {
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
scripts: project.scripts,
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (setupExit._tag === "Failure") {
|
||||
if (worktreePath !== null && !threadCommitted) {
|
||||
yield* git
|
||||
.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath })
|
||||
.pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId)));
|
||||
worktreePath = null;
|
||||
}
|
||||
yield* saveWorkflow(input, {
|
||||
threadId,
|
||||
status: "setup_failed",
|
||||
title,
|
||||
worktreePath,
|
||||
branch,
|
||||
setupCommitted: false,
|
||||
threadCommitted,
|
||||
messageCommitted,
|
||||
lastError: "Project setup script failed.",
|
||||
});
|
||||
return yield* Effect.failCause(setupExit.cause).pipe(
|
||||
Effect.mapError(mapError(input, "run-setup-script", threadId)),
|
||||
);
|
||||
}
|
||||
setupCommitted = true;
|
||||
yield* saveWorkflow(input, {
|
||||
threadId,
|
||||
status: "setup_ready",
|
||||
title,
|
||||
worktreePath,
|
||||
branch,
|
||||
setupCommitted,
|
||||
threadCommitted,
|
||||
messageCommitted,
|
||||
});
|
||||
}
|
||||
|
||||
if (!threadCommitted) {
|
||||
const createExit = yield* Effect.exit(
|
||||
threads.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: input.commandId,
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch,
|
||||
worktreePath,
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
}),
|
||||
);
|
||||
if (createExit._tag === "Failure") {
|
||||
if (worktreePath !== null) {
|
||||
yield* git
|
||||
.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath })
|
||||
.pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId)));
|
||||
worktreePath = null;
|
||||
setupCommitted = false;
|
||||
}
|
||||
yield* saveWorkflow(input, {
|
||||
threadId,
|
||||
status: "thread_create_failed",
|
||||
title,
|
||||
worktreePath,
|
||||
branch,
|
||||
setupCommitted,
|
||||
threadCommitted: false,
|
||||
messageCommitted,
|
||||
lastError: "Thread creation failed.",
|
||||
});
|
||||
return yield* Effect.failCause(createExit.cause).pipe(
|
||||
Effect.mapError(mapError(input, "create-thread", threadId)),
|
||||
);
|
||||
}
|
||||
yield* saveWorkflow(input, {
|
||||
threadId,
|
||||
status: "thread_created",
|
||||
title,
|
||||
worktreePath,
|
||||
branch,
|
||||
setupCommitted,
|
||||
threadCommitted: true,
|
||||
messageCommitted,
|
||||
});
|
||||
}
|
||||
|
||||
if (input.initialMessage !== undefined && !messageCommitted) {
|
||||
const messageId = yield* ids.allocate
|
||||
.message({ threadId, ordinal: 1 })
|
||||
.pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
|
||||
yield* threads
|
||||
.sendToThread({
|
||||
projectId: input.projectId,
|
||||
commandId: CommandId.make(`${input.commandId}:initial-message`),
|
||||
threadId,
|
||||
messageId,
|
||||
text: input.initialMessage.text,
|
||||
attachments: input.initialMessage.attachments,
|
||||
mode: "auto",
|
||||
createdBy: input.createdBy,
|
||||
creationSource: input.creationSource,
|
||||
})
|
||||
.pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)));
|
||||
messageCommitted = true;
|
||||
}
|
||||
yield* saveWorkflow(input, {
|
||||
threadId,
|
||||
status: "completed",
|
||||
title,
|
||||
worktreePath,
|
||||
branch,
|
||||
setupCommitted,
|
||||
threadCommitted: true,
|
||||
messageCommitted,
|
||||
});
|
||||
return {
|
||||
threadId,
|
||||
projection: yield* threads
|
||||
.getThreadProjection(threadId)
|
||||
.pipe(Effect.mapError(mapError(input, "create-thread", threadId))),
|
||||
resumed: stored !== null,
|
||||
};
|
||||
});
|
||||
|
||||
return ThreadLaunchService.of({
|
||||
launch: (input) => launchSemaphore.withPermit(launchWorkflow(input)),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ThreadLaunchService, make);
|
||||
@@ -0,0 +1,60 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as ThreadLifecycle from "./ThreadLifecycleService.ts";
|
||||
import * as ThreadManagement from "./ThreadManagementService.ts";
|
||||
|
||||
it.effect("maps application lifecycle operations to V2-native commands", () => {
|
||||
const threadId = ThreadId.make("thread_lifecycle_service");
|
||||
const commands: Array<string> = [];
|
||||
const projection = { thread: { id: threadId } } as OrchestrationV2ThreadProjection;
|
||||
const layer = ThreadLifecycle.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(ThreadManagement.ThreadManagementService)({
|
||||
dispatch: (command) => {
|
||||
commands.push(command.type);
|
||||
return Effect.succeed({ sequence: commands.length, storedEvents: [] });
|
||||
},
|
||||
getThreadProjection: () => Effect.succeed(projection),
|
||||
}),
|
||||
),
|
||||
);
|
||||
return Effect.gen(function* () {
|
||||
const service = yield* ThreadLifecycle.ThreadLifecycleService;
|
||||
yield* service.archive({ commandId: CommandId.make("archive"), threadId });
|
||||
yield* service.unarchive({ commandId: CommandId.make("unarchive"), threadId });
|
||||
yield* service.updateMetadata({ commandId: CommandId.make("metadata"), threadId, title: "T" });
|
||||
yield* service.setRuntimeMode({
|
||||
commandId: CommandId.make("runtime"),
|
||||
threadId,
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
yield* service.setInteractionMode({
|
||||
commandId: CommandId.make("interaction"),
|
||||
threadId,
|
||||
interactionMode: "plan",
|
||||
});
|
||||
yield* service.setModelSelection({
|
||||
commandId: CommandId.make("model"),
|
||||
threadId,
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.2" },
|
||||
});
|
||||
yield* service.delete({ commandId: CommandId.make("delete"), threadId });
|
||||
assert.deepEqual(commands, [
|
||||
"thread.archive",
|
||||
"thread.unarchive",
|
||||
"thread.metadata.update",
|
||||
"thread.runtime-mode.set",
|
||||
"thread.interaction-mode.set",
|
||||
"thread.model-selection.set",
|
||||
"thread.delete",
|
||||
]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import {
|
||||
CommandId,
|
||||
type ModelSelection,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
ThreadId,
|
||||
} 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 ThreadManagement from "./ThreadManagementService.ts";
|
||||
|
||||
export class ThreadLifecycleError extends Schema.TaggedErrorClass<ThreadLifecycleError>()(
|
||||
"ThreadLifecycleError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"archive",
|
||||
"unarchive",
|
||||
"delete",
|
||||
"update-metadata",
|
||||
"set-runtime-mode",
|
||||
"set-interaction-mode",
|
||||
"set-model-selection",
|
||||
]),
|
||||
threadId: ThreadId,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Thread lifecycle operation '${this.operation}' failed for ${this.threadId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ThreadLifecycleService extends Context.Service<
|
||||
ThreadLifecycleService,
|
||||
{
|
||||
readonly archive: (input: {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadLifecycleError>;
|
||||
readonly unarchive: (input: {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadLifecycleError>;
|
||||
readonly delete: (input: {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadLifecycleError>;
|
||||
readonly updateMetadata: (input: {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly title?: string;
|
||||
readonly branch?: string | null;
|
||||
readonly worktreePath?: string | null;
|
||||
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadLifecycleError>;
|
||||
readonly setRuntimeMode: (input: {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadLifecycleError>;
|
||||
readonly setInteractionMode: (input: {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadLifecycleError>;
|
||||
readonly setModelSelection: (input: {
|
||||
readonly commandId: CommandId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadLifecycleError>;
|
||||
}
|
||||
>()("t3/orchestration-v2/ThreadLifecycleService") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const threads = yield* ThreadManagement.ThreadManagementService;
|
||||
|
||||
const dispatch = <Operation extends ThreadLifecycleError["operation"]>(
|
||||
operation: Operation,
|
||||
threadId: ThreadId,
|
||||
command: Parameters<ThreadManagement.ThreadManagementService["Service"]["dispatch"]>[0],
|
||||
) =>
|
||||
threads.dispatch(command).pipe(
|
||||
Effect.andThen(threads.getThreadProjection(threadId)),
|
||||
Effect.mapError((cause) => new ThreadLifecycleError({ operation, threadId, cause })),
|
||||
);
|
||||
|
||||
return ThreadLifecycleService.of({
|
||||
archive: (input) =>
|
||||
dispatch("archive", input.threadId, {
|
||||
type: "thread.archive",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
}),
|
||||
unarchive: (input) =>
|
||||
dispatch("unarchive", input.threadId, {
|
||||
type: "thread.unarchive",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
}),
|
||||
delete: (input) =>
|
||||
dispatch("delete", input.threadId, {
|
||||
type: "thread.delete",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
}),
|
||||
updateMetadata: (input) =>
|
||||
dispatch("update-metadata", input.threadId, {
|
||||
type: "thread.metadata.update",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
...(input.title === undefined ? {} : { title: input.title }),
|
||||
...(input.branch === undefined ? {} : { branch: input.branch }),
|
||||
...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
|
||||
}),
|
||||
setRuntimeMode: (input) =>
|
||||
dispatch("set-runtime-mode", input.threadId, {
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
runtimeMode: input.runtimeMode,
|
||||
}),
|
||||
setInteractionMode: (input) =>
|
||||
dispatch("set-interaction-mode", input.threadId, {
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
interactionMode: input.interactionMode,
|
||||
}),
|
||||
setModelSelection: (input) =>
|
||||
dispatch("set-model-selection", input.threadId, {
|
||||
type: "thread.model-selection.set",
|
||||
commandId: input.commandId,
|
||||
threadId: input.threadId,
|
||||
modelSelection: input.modelSelection,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ThreadLifecycleService, make);
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { ProjectionProjectRepositoryLive } from "../persistence/Layers/ProjectionProjects.ts";
|
||||
import { layer as projectServiceLayer } from "../project/ProjectService.ts";
|
||||
import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts";
|
||||
import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.ts";
|
||||
import { live as resourceCleanupLive } from "./ResourceCleanupService.ts";
|
||||
import { observerLive as runFinalizationObserverLive } from "./RunFinalizationService.ts";
|
||||
|
||||
const projectServiceProvided = projectServiceLayer.pipe(
|
||||
Layer.provide(ProjectionProjectRepositoryLive),
|
||||
);
|
||||
|
||||
const applicationServices = Layer.mergeAll(
|
||||
threadLaunchServiceLayer,
|
||||
threadLifecycleServiceLayer,
|
||||
).pipe(Layer.provideMerge(projectServiceProvided));
|
||||
|
||||
export const OrchestrationV2ApplicationLayer = Layer.mergeAll(
|
||||
applicationServices,
|
||||
resourceCleanupLive,
|
||||
runFinalizationObserverLive,
|
||||
);
|
||||
@@ -25,6 +25,7 @@ import { OrchestratorV2 } from "./Orchestrator.ts";
|
||||
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
|
||||
import { OrchestrationV2LayerLive } from "./runtimeLayer.ts";
|
||||
import { shellStreamItemFromSnapshot } from "./ShellStream.ts";
|
||||
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-orchestration-v2-runtime-layer-",
|
||||
@@ -43,7 +44,7 @@ const driver = ProviderDriverKind.make("codex");
|
||||
const orchestrationAdapter = {
|
||||
instanceId: modelSelection.instanceId,
|
||||
driver,
|
||||
getCapabilities: () => Effect.die("capabilities are not used by lifecycle tests"),
|
||||
getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
|
||||
openSession: () => Effect.die("sessions are not used by lifecycle tests"),
|
||||
} as ProviderAdapterV2Shape;
|
||||
const providerInstance = {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { layer as checkpointCaptureServiceLayer } from "./CheckpointCaptureService.ts";
|
||||
import { layer as checkpointServiceLayer } from "./CheckpointService.ts";
|
||||
import { layer as checkpointRollbackServiceLayer } from "./CheckpointRollbackService.ts";
|
||||
@@ -20,10 +21,15 @@ 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 providerRuntimeRecoveryLayer,
|
||||
ProviderRuntimeRecoveryService,
|
||||
} from "./ProviderRuntimeRecoveryService.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 runFinalizationServiceLayer } from "./RunFinalizationService.ts";
|
||||
import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts";
|
||||
import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts";
|
||||
import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts";
|
||||
@@ -53,6 +59,9 @@ const contextHandoffServiceProvided = contextHandoffServiceLayer.pipe(
|
||||
);
|
||||
|
||||
const providerAdapterRegistryProvided = providerAdapterRegistryLayerFromProviderInstances;
|
||||
const providerSwitchServiceProvided = providerSwitchServiceLayer.pipe(
|
||||
Layer.provide(providerAdapterRegistryProvided),
|
||||
);
|
||||
|
||||
const providerAdapterRegistryProvided = providerAdapterRegistryLayerFromEffect(
|
||||
Effect.all([
|
||||
@@ -86,6 +95,7 @@ const runExecutionServiceProvided = runExecutionServiceLayer.pipe(
|
||||
const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
contextHandoffServiceProvided,
|
||||
eventSinkProvided,
|
||||
idAllocatorLayer,
|
||||
projectionStoreLayer,
|
||||
@@ -124,11 +134,14 @@ const checkpointCaptureServiceProvided = checkpointCaptureServiceLayer.pipe(
|
||||
),
|
||||
),
|
||||
);
|
||||
const runFinalizationServiceProvided = runFinalizationServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(checkpointCaptureServiceProvided, projectionStoreLayer)),
|
||||
);
|
||||
|
||||
const effectExecutorProvided = effectExecutorLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
checkpointCaptureServiceProvided,
|
||||
runFinalizationServiceProvided,
|
||||
checkpointRollbackServiceProvided,
|
||||
providerSessionManagerProvided,
|
||||
providerTurnControlServiceProvided,
|
||||
@@ -144,6 +157,22 @@ const effectWorkerDaemonProvided = effectWorkerDaemonLayer.pipe(
|
||||
Layer.provide(effectWorkerProvided),
|
||||
);
|
||||
|
||||
const providerRuntimeRecoveryProvided = providerRuntimeRecoveryLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
effectWorkerProvided,
|
||||
storesLayer,
|
||||
eventSinkProvided,
|
||||
idAllocatorLayer,
|
||||
projectionStoreLayer,
|
||||
providerSessionManagerProvided,
|
||||
),
|
||||
),
|
||||
);
|
||||
const providerRuntimeRecoveryStartupProvided = Layer.effectDiscard(
|
||||
Effect.flatMap(ProviderRuntimeRecoveryService, (recovery) => recovery.recover),
|
||||
).pipe(Layer.provide(providerRuntimeRecoveryProvided));
|
||||
|
||||
const orchestratorProvided = orchestratorLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
@@ -159,16 +188,17 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
providerEventIngestorProvided,
|
||||
runtimePolicyLayer,
|
||||
providerSessionManagerProvided,
|
||||
providerSwitchServiceLayer,
|
||||
providerSwitchServiceProvided,
|
||||
runExecutionServiceProvided,
|
||||
threadForkServiceLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const OrchestrationV2LayerLive = Layer.mergeAll(
|
||||
orchestratorProvided,
|
||||
threadManagementServiceLayer.pipe(Layer.provide(orchestratorProvided)),
|
||||
effectWorkerDaemonProvided,
|
||||
providerRuntimeRecoveryStartupProvided,
|
||||
providerRuntimeRecoveryProvided,
|
||||
projectionMaintenanceProvided,
|
||||
);
|
||||
@@ -40,6 +40,7 @@ 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 runFinalizationServiceLayer } from "../RunFinalizationService.ts";
|
||||
import {
|
||||
layer as runtimePolicyLayer,
|
||||
layerWithOverride as runtimePolicyLayerWithOverride,
|
||||
@@ -264,6 +265,9 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
|
||||
const providerSessionManagerProvided = providerSessionManagerLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(registryLayer, eventSinkProvided, idAllocatorLayer, storesLayer)),
|
||||
);
|
||||
const providerSwitchServiceProvided = providerSwitchServiceLayer.pipe(
|
||||
Layer.provide(registryLayer),
|
||||
);
|
||||
const runExecutionServiceProvided = runExecutionServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
@@ -278,6 +282,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
|
||||
const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
contextHandoffServiceProvided,
|
||||
eventSinkProvided,
|
||||
idAllocatorLayer,
|
||||
storesLayer,
|
||||
@@ -310,10 +315,13 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
|
||||
Layer.mergeAll(checkpointServiceProvided, eventSinkProvided, idAllocatorLayer, storesLayer),
|
||||
),
|
||||
);
|
||||
const runFinalizationServiceProvided = runFinalizationServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(checkpointCaptureServiceProvided, storesLayer)),
|
||||
);
|
||||
const effectExecutorProvided = effectExecutorLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
checkpointCaptureServiceProvided,
|
||||
runFinalizationServiceProvided,
|
||||
checkpointRollbackServiceProvided,
|
||||
providerSessionManagerProvided,
|
||||
providerTurnControlServiceProvided,
|
||||
@@ -339,7 +347,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
|
||||
registryLayer,
|
||||
runtimeLayer,
|
||||
providerSessionManagerProvided,
|
||||
providerSwitchServiceLayer,
|
||||
providerSwitchServiceProvided,
|
||||
runExecutionServiceProvided,
|
||||
threadForkServiceLayer,
|
||||
),
|
||||
|
||||
@@ -67,6 +67,7 @@ function makeTestAdapter(input: {
|
||||
readonly responseByRunOrdinal: Readonly<Record<number, string>>;
|
||||
readonly responseByThreadId?: Readonly<Record<string, Readonly<Record<number, string>>>>;
|
||||
readonly capturedTurns: Ref.Ref<ReadonlyArray<CapturedTurn>>;
|
||||
readonly failResume?: boolean;
|
||||
}): ProviderAdapterV2Shape {
|
||||
return {
|
||||
instanceId: input.instanceId,
|
||||
@@ -122,7 +123,10 @@ function makeTestAdapter(input: {
|
||||
updatedAt: createdAt,
|
||||
} satisfies OrchestrationV2ProviderThread;
|
||||
}),
|
||||
resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
|
||||
resumeThread: ({ providerThread }) =>
|
||||
input.failResume
|
||||
? unimplemented(input.driver, "simulated native resume failure")
|
||||
: Effect.succeed(providerThread),
|
||||
startTurn: (turnInput) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
@@ -235,7 +239,7 @@ const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
|
||||
});
|
||||
|
||||
describe("orchestration v2 provider switching", () => {
|
||||
it.live("switches Codex to Claude and returns to the original Codex thread with handoffs", () =>
|
||||
it.live("uses portable fallback when native resume fails after a provider switch", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* checkpointWorkspace("provider-switch");
|
||||
@@ -251,6 +255,7 @@ describe("orchestration v2 provider switching", () => {
|
||||
3: "codex after return",
|
||||
},
|
||||
capturedTurns,
|
||||
failResume: true,
|
||||
}),
|
||||
makeTestAdapter({
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
|
||||
@@ -49,6 +49,7 @@ import Migration0033 from "./Migrations/033_OrchestrationV2.ts";
|
||||
import Migration0034 from "./Migrations/034_OrchestrationV2Subagents.ts";
|
||||
import Migration0035 from "./Migrations/035_OrchestrationV2Foundation.ts";
|
||||
import Migration0036 from "./Migrations/036_OrchestrationV2ProviderSessionBindings.ts";
|
||||
import Migration0037 from "./Migrations/037_OrchestrationV2ThreadLaunchWorkflows.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -97,6 +98,7 @@ export const migrationEntries = [
|
||||
[34, "OrchestrationV2Subagents", Migration0034],
|
||||
[35, "OrchestrationV2Foundation", Migration0035],
|
||||
[36, "OrchestrationV2ProviderSessionBindings", Migration0036],
|
||||
[37, "OrchestrationV2ThreadLaunchWorkflows", Migration0037],
|
||||
] as const;
|
||||
|
||||
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS orchestration_v2_thread_launch_workflows (
|
||||
command_id TEXT PRIMARY KEY,
|
||||
thread_id TEXT NOT NULL,
|
||||
project_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
worktree_path TEXT,
|
||||
branch TEXT,
|
||||
setup_committed INTEGER NOT NULL DEFAULT 0,
|
||||
thread_committed INTEGER NOT NULL DEFAULT 0,
|
||||
message_committed INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
`;
|
||||
});
|
||||
@@ -129,4 +129,24 @@ it.layer(TestLayer)("ProjectService", (it) => {
|
||||
assert.equal(error._tag, "ProjectConflictError");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("auto-bootstraps a workspace exactly once", () =>
|
||||
Effect.gen(function* () {
|
||||
const service = yield* ProjectService.ProjectService;
|
||||
yield* TestClock.setTime(Date.parse("2026-06-20T10:00:00.000Z"));
|
||||
const input = {
|
||||
projectId: ProjectId.make("project:bootstrap"),
|
||||
title: "Bootstrap",
|
||||
workspaceRoot: "/work/bootstrap/",
|
||||
};
|
||||
const first = yield* service.bootstrap(input);
|
||||
const second = yield* service.bootstrap({
|
||||
...input,
|
||||
projectId: ProjectId.make("project:bootstrap:unused"),
|
||||
});
|
||||
assert.isTrue(first.created);
|
||||
assert.isFalse(second.created);
|
||||
assert.equal(second.project.id, first.project.id);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -37,6 +37,8 @@ export interface ProjectUpdateInput {
|
||||
readonly scripts?: ReadonlyArray<ProjectScript>;
|
||||
}
|
||||
|
||||
export interface ProjectBootstrapInput extends ProjectCreateInput {}
|
||||
|
||||
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
|
||||
"ProjectNotFoundError",
|
||||
{ projectId: ProjectId },
|
||||
@@ -88,6 +90,12 @@ export class ProjectService extends Context.Service<
|
||||
ProjectService,
|
||||
{
|
||||
readonly create: (input: ProjectCreateInput) => Effect.Effect<Project, ProjectServiceError>;
|
||||
readonly bootstrap: (
|
||||
input: ProjectBootstrapInput,
|
||||
) => Effect.Effect<
|
||||
{ readonly project: Project; readonly created: boolean },
|
||||
ProjectServiceError
|
||||
>;
|
||||
readonly update: (input: ProjectUpdateInput) => Effect.Effect<Project, ProjectServiceError>;
|
||||
readonly delete: (projectId: ProjectId) => Effect.Effect<Project, ProjectServiceError>;
|
||||
readonly getById: (
|
||||
@@ -309,6 +317,14 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const bootstrap: ProjectService["Service"]["bootstrap"] = Effect.fn("ProjectService.bootstrap")(
|
||||
function* (input) {
|
||||
const existing = yield* getByWorkspaceRoot(input.workspaceRoot);
|
||||
if (Option.isSome(existing)) return { project: existing.value, created: false };
|
||||
return { project: yield* create(input), created: true };
|
||||
},
|
||||
);
|
||||
|
||||
const deleteProject: ProjectService["Service"]["delete"] = Effect.fn("ProjectService.delete")(
|
||||
function* (projectId) {
|
||||
const existing = yield* projects
|
||||
@@ -351,6 +367,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return ProjectService.of({
|
||||
create,
|
||||
bootstrap,
|
||||
update,
|
||||
delete: deleteProject,
|
||||
getById,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ProjectId } from "@t3tools/contracts";
|
||||
import { ProjectId, type ProjectScript } from "@t3tools/contracts";
|
||||
import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -31,6 +31,10 @@ export interface ProjectSetupScriptRunnerInput {
|
||||
readonly projectCwd?: string;
|
||||
readonly worktreePath: string;
|
||||
readonly preferredTerminalId?: string;
|
||||
readonly project?: {
|
||||
readonly workspaceRoot: string;
|
||||
readonly scripts: ReadonlyArray<ProjectScript>;
|
||||
};
|
||||
}
|
||||
|
||||
export class ProjectSetupScriptOperationError extends Schema.TaggedErrorClass<ProjectSetupScriptOperationError>()(
|
||||
@@ -91,20 +95,24 @@ export const make = Effect.gen(function* () {
|
||||
...(input.projectId === undefined ? {} : { projectId: input.projectId }),
|
||||
...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),
|
||||
};
|
||||
const projectById = input.projectId
|
||||
? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).pipe(
|
||||
Effect.map(Option.getOrUndefined),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectSetupScriptOperationError({
|
||||
...errorContext,
|
||||
operation: "resolveProject",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const suppliedProject = input.project;
|
||||
const projectById =
|
||||
suppliedProject ??
|
||||
(input.projectId
|
||||
? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).pipe(
|
||||
Effect.map(Option.getOrUndefined),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectSetupScriptOperationError({
|
||||
...errorContext,
|
||||
operation: "resolveProject",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: null);
|
||||
const project =
|
||||
suppliedProject ??
|
||||
projectById ??
|
||||
(input.projectCwd
|
||||
? yield* projectionSnapshotQuery.getActiveProjectByWorkspaceRoot(input.projectCwd).pipe(
|
||||
|
||||
Reference in new issue
Block a user