Skip to content
TypeScript

refactor(orchestration): trace reusable service operations (#21995)

Julius Marmingec911f654b9fb
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
index 03efcaa7f38..96a5e10c989 100644
--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
@@ -355,26 +355,30 @@ export const layer: Layer.Layer<
});
return CheckpointRollbackServiceV2.of({
- execute: (input) =>
- Effect.gen(function* () {
+ // The inner execute owns the rollback span; this wrapper selects the workspace lease.
+ execute: Effect.fnUntraced(
+ function* (input) {
// Storage cleanup removes worktrees under the same lease.
const thread = yield* projections.getThread(input.threadId);
yield* thread.worktreePath === null
? execute(input)
: withWorkspaceLease(path.resolve(thread.worktreePath), execute(input));
- }).pipe(
- Effect.mapError((cause) =>
- isCheckpointRollbackExecutionError(cause)
- ? cause
- : new CheckpointRollbackExecutionError({
- reason: "unexpected-failure",
- threadId: input.threadId,
- providerThreadId: input.providerThreadId,
- checkpointId: input.checkpointId,
- cause,
- }),
+ },
+ (effect, input) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ isCheckpointRollbackExecutionError(cause)
+ ? cause
+ : new CheckpointRollbackExecutionError({
+ reason: "unexpected-failure",
+ threadId: input.threadId,
+ providerThreadId: input.providerThreadId,
+ checkpointId: input.checkpointId,
+ cause,
+ }),
+ ),
),
- ),
+ ),
});
}),
);
diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts
index c2f81d044da..529ea60d36c 100644
--- a/apps/server/src/orchestration-v2/CheckpointService.ts
+++ b/apps/server/src/orchestration-v2/CheckpointService.ts
@@ -184,7 +184,7 @@ function checkpointIdForScopeOrdinal(
});
}
-function makeRootRunScope(input: {
+const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(function* (input: {
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
readonly threadId: ThreadId;
readonly runId: RunId;
@@ -193,26 +193,24 @@ function makeRootRunScope(input: {
readonly cwd: string;
readonly createdAt: DateTime.Utc;
}) {
- return Effect.gen(function* () {
- const scopeId = yield* input.idAllocator.allocate.checkpointScope({
- threadId: input.threadId,
- name: ROOT_CHECKPOINT_SCOPE_NAME,
- });
- return {
- id: scopeId,
- threadId: input.threadId,
- runId: input.runId,
- nodeId: input.rootNodeId,
- parentScopeId: null,
- providerThreadId: input.providerThreadId,
- kind: "root_run",
- ordinalWithinParent: 0,
- advancesAppRunCount: true,
- cwd: input.cwd,
- createdAt: input.createdAt,
- } satisfies OrchestrationV2CheckpointScope;
+ const scopeId = yield* input.idAllocator.allocate.checkpointScope({
+ threadId: input.threadId,
+ name: ROOT_CHECKPOINT_SCOPE_NAME,
});
-}
+ return {
+ id: scopeId,
+ threadId: input.threadId,
+ runId: input.runId,
+ nodeId: input.rootNodeId,
+ parentScopeId: null,
+ providerThreadId: input.providerThreadId,
+ kind: "root_run",
+ ordinalWithinParent: 0,
+ advancesAppRunCount: true,
+ cwd: input.cwd,
+ createdAt: input.createdAt,
+ } satisfies OrchestrationV2CheckpointScope;
+});
function makeCheckpoint(input: {
readonly id: CheckpointId;
diff --git a/apps/server/src/orchestration-v2/DelegatedTaskQuestionReactor.ts b/apps/server/src/orchestration-v2/DelegatedTaskQuestionReactor.ts
index 86b369f9136..50ae6c74678 100644
--- a/apps/server/src/orchestration-v2/DelegatedTaskQuestionReactor.ts
+++ b/apps/server/src/orchestration-v2/DelegatedTaskQuestionReactor.ts
@@ -58,8 +58,9 @@ const make = Effect.gen(function* () {
});
});
- const handle: DelegatedTaskQuestionReactor["Service"]["handle"] = (event) =>
- Effect.gen(function* () {
+ // Runs for every domain event; most events return before any work is needed.
+ const handle: DelegatedTaskQuestionReactor["Service"]["handle"] = Effect.fnUntraced(
+ function* (event) {
if (event.type === "run.updated") {
if (!["completed", "failed", "waiting"].includes(event.payload.status)) return;
const parent = yield* projections.getThreadRecords(event.threadId, ["subagents"]);
@@ -154,14 +155,17 @@ const make = Effect.gen(function* () {
return;
}
yield* wakeParent(task, request);
- }).pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("waking the parent of a delegated task question failed", {
- threadId: event.threadId,
- cause,
- }),
+ },
+ (effect, event) =>
+ effect.pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("waking the parent of a delegated task question failed", {
+ threadId: event.threadId,
+ cause,
+ }),
+ ),
),
- );
+ );
const start: DelegatedTaskQuestionReactor["Service"]["start"] = () =>
forkParked(
diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts
index a44b60c2498..d47635a0910 100644
--- a/apps/server/src/orchestration-v2/EffectWorker.ts
+++ b/apps/server/src/orchestration-v2/EffectWorker.ts
@@ -673,8 +673,9 @@ export const layerWithOptions = (
? requeueClaim(effect, cause)
: terminalizeClaim(effect, cause);
- const runOnce = (excludeRestartContinuations = false) =>
- Effect.gen(function* () {
+ // The worker probes for work repeatedly, including when the outbox is empty.
+ const runOnce = Effect.fnUntraced(
+ function* (excludeRestartContinuations = false) {
const claimExit = yield* Effect.exit(
outbox.claimNext({ workerId, leaseDurationMs, excludeRestartContinuations }),
);
@@ -781,13 +782,16 @@ export const layerWithOptions = (
});
}
return true;
- }).pipe(
- Effect.mapError((cause) =>
- isOrchestrationEffectWorkerError(cause)
- ? cause
- : new OrchestrationEffectWorkerError({ operation: "run", cause }),
+ },
+ (effect, _excludeRestartContinuations?: boolean) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ isOrchestrationEffectWorkerError(cause)
+ ? cause
+ : new OrchestrationEffectWorkerError({ operation: "run", cause }),
+ ),
),
- );
+ );
return OrchestrationEffectWorkerV2.of({
awaitWork: outbox.awaitAvailable,
@@ -802,14 +806,13 @@ export const layerWithOptions = (
}),
),
),
- drain: (maxEffects = Number.MAX_SAFE_INTEGER) =>
- Effect.gen(function* () {
- let completed = 0;
- while (completed < maxEffects && (yield* runOnce())) {
- completed += 1;
- }
- return completed;
- }),
+ drain: Effect.fn("EffectWorker.drain")(function* (maxEffects = Number.MAX_SAFE_INTEGER) {
+ let completed = 0;
+ while (completed < maxEffects && (yield* runOnce())) {
+ completed += 1;
+ }
+ return completed;
+ }),
});
}),
);
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 08048e1328f..0a0299ca86f 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -917,11 +917,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
),
);
- const makeEvent = <Event extends OrchestrationV2DomainEvent>(
- command: OrchestrationV2ServerCommand,
- event: Omit<Event, "id">,
- ) =>
- Effect.gen(function* () {
+ const makeEvent =
+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
+ Effect.fnUntraced(function* <Event extends OrchestrationV2DomainEvent>(
+ command: OrchestrationV2ServerCommand,
+ event: Omit<Event, "id">,
+ ) {
const eventId = yield* mapDispatchError(command)(
idAllocator.allocate.event({
threadId: event.threadId,
@@ -993,11 +994,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
);
- const getProjectionWithPendingEvents = (
- threadId: ThreadId,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- ) =>
- Effect.gen(function* () {
+ const getProjectionWithPendingEvents =
+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
+ Effect.fnUntraced(function* (
+ threadId: ThreadId,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ ) {
const pending = (yield* Ref.get(events)).filter((event) => event.threadId === threadId);
const stored = yield* Effect.option(readCommandProjection(threadId));
let projection: OrchestrationV2ThreadProjection;
@@ -1026,8 +1028,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return projection;
});
- const makeSystemEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
- Effect.gen(function* () {
+ const makeSystemEvent =
+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
+ Effect.fnUntraced(function* <Event extends OrchestrationV2DomainEvent>(
+ event: Omit<Event, "id">,
+ ) {
const eventId = yield* idAllocator.allocate.event({
threadId: event.threadId,
});
@@ -1037,11 +1042,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
} as Event;
});
- const writeSystemEvents = (
- events: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">>,
- effects: ReadonlyArray<PendingOrchestrationEffectV2> = [],
- ) =>
- Effect.gen(function* () {
+ const writeSystemEvents =
+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
+ Effect.fnUntraced(function* (
+ events: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">>,
+ effects: ReadonlyArray<PendingOrchestrationEffectV2> = [],
+ ) {
const withIds = yield* Effect.forEach(events, (event) =>
makeSystemEvent(event as Omit<OrchestrationV2DomainEvent, "id">),
);
@@ -1065,8 +1071,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? undefined
: projection.messages.find((candidate) => candidate.id === delivery.messageId);
- const offerDelegatedCompletionDelivery = (threadId: ThreadId, parentRunId: RunId) =>
- Effect.gen(function* () {
+ const offerDelegatedCompletionDelivery =
+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
+ Effect.fnUntraced(function* (threadId: ThreadId, parentRunId: RunId) {
const projection = yield* projectionStore.getThreadRecords(
threadId,
["runs", "messages", "providerTurns", "providerThreads"],
@@ -1111,8 +1118,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
});
- const offerDelegatedCompletionDeliveries = (threadId: ThreadId) =>
- Effect.gen(function* () {
+ const offerDelegatedCompletionDeliveries =
+ /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
+ Effect.fnUntraced(function* (threadId: ThreadId) {
const projection = yield* projectionStore.getThreadRecords(threadId, ["runs"]);
for (const run of projection.runs) {
if (
@@ -1124,14 +1132,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
});
- const emitQueuedRunCancellation = (input: {
- readonly command: OrchestrationV2ServerCommand;
- readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
- readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">;
- readonly run: OrchestrationV2Run;
- readonly now: DateTime.Utc;
- }) =>
- Effect.gen(function* () {
+ const emitQueuedRunCancellation = Effect.fn("Orchestrator.emitQueuedRunCancellation")(
+ function* (input: {
+ readonly command: OrchestrationV2ServerCommand;
+ readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
+ readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">;
+ readonly run: OrchestrationV2Run;
+ readonly now: DateTime.Utc;
+ }) {
const rootNode =
input.run.rootNodeId === null
? undefined
@@ -1187,118 +1195,121 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
});
}
- });
+ },
+ );
- const failQueuedRunStart = (threadId: ThreadId, cause: unknown) =>
- Effect.gen(function* () {
- const projection = yield* projectionStore.getThreadRecords(
- threadId,
- ["runs", "nodes", "attempts", "providerThreads", "turnItems", "messages"],
- { turnItemTypes: [], messageRoles: ["user"] },
- );
- const queuedRun = nextQueuedRun(projection);
- if (queuedRun === undefined) return;
- const now = yield* DateTime.now;
- const rootNode = projection.nodes.find((node) => node.id === queuedRun.rootNodeId);
- const attempt = projection.attempts.find((entry) => entry.id === queuedRun.activeAttemptId);
- const providerThread = projection.providerThreads.find(
- (entry) => entry.id === queuedRun.providerThreadId,
- );
- const handoffUnsupported =
- typeof cause === "object" &&
- cause !== null &&
- "_tag" in cause &&
- cause._tag === "CommandPolicyCapabilityUnsupportedError";
- const failureCause =
- typeof cause === "object" &&
- cause !== null &&
- "_tag" in cause &&
- cause._tag === "OrchestratorDispatchError" &&
- "cause" in cause
- ? cause.cause
- : cause;
- const failure = makeProviderFailure({
- cause: failureCause,
- code: handoffUnsupported ? "context_handoff_unsupported" : "queued_start_failed",
- class: handoffUnsupported ? "validation_error" : "unknown",
- });
- yield* writeSystemEvents([
- ...(attempt !== undefined && rootNode !== undefined
- ? [
- {
- type: "run-attempt.updated" as const,
- threadId,
- runId: queuedRun.id,
- nodeId: rootNode.id,
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: { ...attempt, status: "failed" as const, completedAt: now },
- },
- ]
- : []),
- ...(rootNode === undefined
- ? []
- : [
- {
- type: "node.updated" as const,
- threadId,
- runId: queuedRun.id,
- nodeId: rootNode.id,
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: { ...rootNode, status: "failed" as const, completedAt: now },
- },
- ]),
- ...(rootNode === undefined || providerThread === undefined
- ? []
- : [
- {
- type: "turn-item.updated" as const,
+ const failQueuedRunStart = Effect.fn("Orchestrator.failQueuedRunStart")(function* (
+ threadId: ThreadId,
+ cause: unknown,
+ ) {
+ const projection = yield* projectionStore.getThreadRecords(
+ threadId,
+ ["runs", "nodes", "attempts", "providerThreads", "turnItems", "messages"],
+ { turnItemTypes: [], messageRoles: ["user"] },
+ );
+ const queuedRun = nextQueuedRun(projection);
+ if (queuedRun === undefined) return;
+ const now = yield* DateTime.now;
+ const rootNode = projection.nodes.find((node) => node.id === queuedRun.rootNodeId);
+ const attempt = projection.attempts.find((entry) => entry.id === queuedRun.activeAttemptId);
+ const providerThread = projection.providerThreads.find(
+ (entry) => entry.id === queuedRun.providerThreadId,
+ );
+ const handoffUnsupported =
+ typeof cause === "object" &&
+ cause !== null &&
+ "_tag" in cause &&
+ cause._tag === "CommandPolicyCapabilityUnsupportedError";
+ const failureCause =
+ typeof cause === "object" &&
+ cause !== null &&
+ "_tag" in cause &&
+ cause._tag === "OrchestratorDispatchError" &&
+ "cause" in cause
+ ? cause.cause
+ : cause;
+ const failure = makeProviderFailure({
+ cause: failureCause,
+ code: handoffUnsupported ? "context_handoff_unsupported" : "queued_start_failed",
+ class: handoffUnsupported ? "validation_error" : "unknown",
+ });
+ yield* writeSystemEvents([
+ ...(attempt !== undefined && rootNode !== undefined
+ ? [
+ {
+ type: "run-attempt.updated" as const,
+ threadId,
+ runId: queuedRun.id,
+ nodeId: rootNode.id,
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: { ...attempt, status: "failed" as const, completedAt: now },
+ },
+ ]
+ : []),
+ ...(rootNode === undefined
+ ? []
+ : [
+ {
+ type: "node.updated" as const,
+ threadId,
+ runId: queuedRun.id,
+ nodeId: rootNode.id,
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: { ...rootNode, status: "failed" as const, completedAt: now },
+ },
+ ]),
+ ...(rootNode === undefined || providerThread === undefined
+ ? []
+ : [
+ {
+ type: "turn-item.updated" as const,
+ threadId,
+ runId: queuedRun.id,
+ nodeId: rootNode.id,
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ id: idAllocator.derive.turnItemFromProviderItem({
+ driver: providerThread.driver,
+ nativeItemId: `queued-start-failure:${queuedRun.id}`,
+ }),
threadId,
runId: queuedRun.id,
nodeId: rootNode.id,
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: {
- id: idAllocator.derive.turnItemFromProviderItem({
- driver: providerThread.driver,
- nativeItemId: `queued-start-failure:${queuedRun.id}`,
- }),
- threadId,
- runId: queuedRun.id,
- nodeId: rootNode.id,
- providerThreadId: providerThread.id,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: yield* nextTurnItemOrdinal(projection),
- status: "failed" as const,
- title: "Queued provider could not start",
- startedAt: now,
- completedAt: now,
- updatedAt: now,
- type: "error" as const,
- failure,
- },
+ providerThreadId: providerThread.id,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: yield* nextTurnItemOrdinal(projection),
+ status: "failed" as const,
+ title: "Queued provider could not start",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "error" as const,
+ failure,
},
- ]),
- {
- type: "run.updated",
- threadId,
- runId: queuedRun.id,
- ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: { ...queuedRun, status: "failed", queuePosition: null, completedAt: now },
- },
- ]);
- });
+ },
+ ]),
+ {
+ type: "run.updated",
+ threadId,
+ runId: queuedRun.id,
+ ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: { ...queuedRun, status: "failed", queuePosition: null, completedAt: now },
+ },
+ ]);
+ });
- const startNextQueuedRun = (
- threadId: ThreadId,
- options?: { readonly failedRunId?: RunId; readonly endedRunId?: RunId },
- ) =>
- Effect.gen(function* () {
+ const startNextQueuedRun = Effect.fn("Orchestrator.startNextQueuedRun")(
+ function* (
+ threadId: ThreadId,
+ options?: { readonly failedRunId?: RunId; readonly endedRunId?: RunId },
+ ) {
if (!(yield* projectionStore.canStartQueuedRun(threadId))) return;
const projection = yield* readCommandProjection(threadId);
if (
@@ -1934,7 +1945,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
],
);
- }).pipe(Effect.catch((cause) => failQueuedRunStart(threadId, cause)));
+ },
+ (effect, threadId, _options?) =>
+ effect.pipe(Effect.catch((cause) => failQueuedRunStart(threadId, cause))),
+ );
const resumeQueuedRuns = Effect.gen(function* () {
const threadIds = yield* projectionStore.getRecoveryThreadIds("queued-runs");
@@ -1968,7 +1982,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
),
);
- const dispatchDelegatedTaskCompletionDeliveryResolution = (
+ const dispatchDelegatedTaskCompletionDeliveryResolution = Effect.fn(
+ "Orchestrator.dispatchDelegatedTaskCompletionDeliveryResolution",
+ )(function* (
command: Extract<
OrchestrationV2Command,
{
@@ -1978,71 +1994,47 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- ) =>
- Effect.gen(function* () {
- const projection = yield* projectionStore
- .getThreadRecords(
- command.parentThreadId,
- ["subagents", "runs", "messages", "nodes", "attempts", "turnItems"],
- { turnItemTypes: [], messageRoles: ["user"] },
- )
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorProjectionError({
- threadId: command.parentThreadId,
- cause,
- }),
- ),
- );
- const task = projection.subagents.find(
- (candidate) => candidate.id === command.taskId && candidate.origin === "app_owned",
+ ) {
+ const projection = yield* projectionStore
+ .getThreadRecords(
+ command.parentThreadId,
+ ["subagents", "runs", "messages", "nodes", "attempts", "turnItems"],
+ { turnItemTypes: [], messageRoles: ["user"] },
+ )
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProjectionError({
+ threadId: command.parentThreadId,
+ cause,
+ }),
+ ),
);
- if (task === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Delegated task ${command.taskId} is not an app-owned task of thread ${command.parentThreadId}.`,
- });
- }
- const state =
- command.type === "delegated_task.completion-delivery.acknowledge"
- ? "acknowledged"
- : "disposed";
- const now = yield* DateTime.now;
- const emitEvent = emit(events, command);
- // task_status and t3_thread_read use distinct command IDs, so two
- // valid observations can race after their read preflight. Re-emit the
- // existing task row so the second dispatch is a successful idempotent
- // no-op rather than "already acknowledged/disposed" or empty-events.
- if (
- task.completionDelivery?.state === state ||
- (command.type === "delegated_task.completion-delivery.acknowledge" &&
- task.completionDelivery?.state === "disposed")
- ) {
- yield* emitEvent({
- type: "subagent.updated",
- threadId: command.parentThreadId,
- ...(task.runId === null ? {} : { runId: task.runId }),
- nodeId: task.id,
- driver: task.driver,
- providerInstanceId: task.providerInstanceId,
- occurredAt: now,
- payload: task,
- });
- return;
- }
- const updatedTask: OrchestrationV2Subagent = {
- ...task,
- completionDelivery: {
- state,
- observedByRunId:
- command.type === "delegated_task.completion-delivery.acknowledge"
- ? command.observedByRunId
- : null,
- },
- updatedAt: now,
- };
+ const task = projection.subagents.find(
+ (candidate) => candidate.id === command.taskId && candidate.origin === "app_owned",
+ );
+ if (task === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Delegated task ${command.taskId} is not an app-owned task of thread ${command.parentThreadId}.`,
+ });
+ }
+ const state =
+ command.type === "delegated_task.completion-delivery.acknowledge"
+ ? "acknowledged"
+ : "disposed";
+ const now = yield* DateTime.now;
+ const emitEvent = emit(events, command);
+ // task_status and t3_thread_read use distinct command IDs, so two
+ // valid observations can race after their read preflight. Re-emit the
+ // existing task row so the second dispatch is a successful idempotent
+ // no-op rather than "already acknowledged/disposed" or empty-events.
+ if (
+ task.completionDelivery?.state === state ||
+ (command.type === "delegated_task.completion-delivery.acknowledge" &&
+ task.completionDelivery?.state === "disposed")
+ ) {
yield* emitEvent({
type: "subagent.updated",
threadId: command.parentThreadId,
@@ -2051,90 +2043,115 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
driver: task.driver,
providerInstanceId: task.providerInstanceId,
occurredAt: now,
- payload: updatedTask,
+ payload: task,
});
+ return;
+ }
+ const updatedTask: OrchestrationV2Subagent = {
+ ...task,
+ completionDelivery: {
+ state,
+ observedByRunId:
+ command.type === "delegated_task.completion-delivery.acknowledge"
+ ? command.observedByRunId
+ : null,
+ },
+ updatedAt: now,
+ };
+ yield* emitEvent({
+ type: "subagent.updated",
+ threadId: command.parentThreadId,
+ ...(task.runId === null ? {} : { runId: task.runId }),
+ nodeId: task.id,
+ driver: task.driver,
+ providerInstanceId: task.providerInstanceId,
+ occurredAt: now,
+ payload: updatedTask,
+ });
- const parentRun =
- task.runId === null
- ? undefined
- : projection.runs.find((candidate) => candidate.id === task.runId);
- const cohort = parentRun?.delegatedCompletion;
- const delivery = cohort?.delivery;
- if (
- parentRun === undefined ||
- cohort === undefined ||
- delivery === null ||
- delivery === undefined
- ) {
+ const parentRun =
+ task.runId === null
+ ? undefined
+ : projection.runs.find((candidate) => candidate.id === task.runId);
+ const cohort = parentRun?.delegatedCompletion;
+ const delivery = cohort?.delivery;
+ if (
+ parentRun === undefined ||
+ cohort === undefined ||
+ delivery === null ||
+ delivery === undefined
+ ) {
+ return;
+ }
+ if (!delivery.taskIds.includes(task.id)) {
+ return;
+ }
+
+ const remainingTaskIds = delivery.taskIds.filter((taskId) => taskId !== task.id);
+ const deliveryRun = completionDeliveryRun(projection, delivery);
+ const clearDelivery =
+ remainingTaskIds.length === 0 &&
+ (deliveryRun === undefined || deliveryRun.status === "queued");
+ const updatedCohort: OrchestrationV2DelegatedCompletionCohort = {
+ ...cohort,
+ delivery: clearDelivery
+ ? null
+ : {
+ ...delivery,
+ taskIds: remainingTaskIds,
+ },
+ };
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: command.parentThreadId,
+ runId: parentRun.id,
+ ...(parentRun.rootNodeId === null ? {} : { nodeId: parentRun.rootNodeId }),
+ providerInstanceId: parentRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...parentRun,
+ delegatedCompletion: updatedCohort,
+ },
+ });
+
+ if (deliveryRun?.status === "queued") {
+ if (remainingTaskIds.length === 0) {
+ yield* emitQueuedRunCancellation({
+ command,
+ events,
+ projection,
+ run: deliveryRun,
+ now,
+ });
return;
}
- if (!delivery.taskIds.includes(task.id)) {
- return;
- }
-
- const remainingTaskIds = delivery.taskIds.filter((taskId) => taskId !== task.id);
- const deliveryRun = completionDeliveryRun(projection, delivery);
- const clearDelivery =
- remainingTaskIds.length === 0 &&
- (deliveryRun === undefined || deliveryRun.status === "queued");
- const updatedCohort: OrchestrationV2DelegatedCompletionCohort = {
- ...cohort,
- delivery: clearDelivery
- ? null
- : {
- ...delivery,
+ const message = completionDeliveryMessage(projection, delivery);
+ if (message !== undefined) {
+ yield* emitEvent({
+ type: "message.updated",
+ threadId: command.parentThreadId,
+ runId: deliveryRun.id,
+ ...(deliveryRun.rootNodeId === null ? {} : { nodeId: deliveryRun.rootNodeId }),
+ providerInstanceId: deliveryRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...message,
+ text: delegatedCompletionWakeDetail(remainingTaskIds),
+ delegatedCompletion: {
+ parentRunId: parentRun.id,
+ generation: delivery.generation,
taskIds: remainingTaskIds,
},
- };
- yield* emitEvent({
- type: "run.updated",
- threadId: command.parentThreadId,
- runId: parentRun.id,
- ...(parentRun.rootNodeId === null ? {} : { nodeId: parentRun.rootNodeId }),
- providerInstanceId: parentRun.providerInstanceId,
- occurredAt: now,
- payload: {
- ...parentRun,
- delegatedCompletion: updatedCohort,
- },
- });
-
- if (deliveryRun?.status === "queued") {
- if (remainingTaskIds.length === 0) {
- yield* emitQueuedRunCancellation({
- command,
- events,
- projection,
- run: deliveryRun,
- now,
- });
- return;
- }
- const message = completionDeliveryMessage(projection, delivery);
- if (message !== undefined) {
- yield* emitEvent({
- type: "message.updated",
- threadId: command.parentThreadId,
- runId: deliveryRun.id,
- ...(deliveryRun.rootNodeId === null ? {} : { nodeId: deliveryRun.rootNodeId }),
- providerInstanceId: deliveryRun.providerInstanceId,
- occurredAt: now,
- payload: {
- ...message,
- text: delegatedCompletionWakeDetail(remainingTaskIds),
- delegatedCompletion: {
- parentRunId: parentRun.id,
- generation: delivery.generation,
- taskIds: remainingTaskIds,
- },
- updatedAt: now,
- },
- });
- }
+ updatedAt: now,
+ },
+ });
}
- });
+ }
+ });
- const disposeDelegatedCompletionCohort = (input: {
+ const disposeDelegatedCompletionCohort = Effect.fn(
+ "Orchestrator.disposeDelegatedCompletionCohort",
+ )(function* (input: {
readonly command: OrchestrationV2ServerCommand;
readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
readonly projection: Pick<
@@ -2145,77 +2162,74 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly disposition: "stopped" | "disposed";
readonly now: DateTime.Utc;
readonly cancelQueuedDelivery?: boolean;
- }) =>
- Effect.gen(function* () {
- const parentRun = input.projection.runs.find(
- (candidate) => candidate.id === input.parentRunId,
- );
- if (parentRun === undefined) {
- return;
- }
- const cohort = parentRun.delegatedCompletion;
- const tasks = input.projection.subagents.filter(
- (candidate) => candidate.origin === "app_owned" && candidate.runId === input.parentRunId,
- );
- if (cohort === undefined && tasks.length === 0) {
- return;
+ }) {
+ const parentRun = input.projection.runs.find((candidate) => candidate.id === input.parentRunId);
+ if (parentRun === undefined) {
+ return;
+ }
+ const cohort = parentRun.delegatedCompletion;
+ const tasks = input.projection.subagents.filter(
+ (candidate) => candidate.origin === "app_owned" && candidate.runId === input.parentRunId,
+ );
+ if (cohort === undefined && tasks.length === 0) {
+ return;
+ }
+ const emitEvent = emit(input.events, input.command);
+ const nextDisposition = cohort?.disposition === "disposed" ? "disposed" : input.disposition;
+ const nextCohort = {
+ disposition: nextDisposition,
+ nextGeneration: cohort?.nextGeneration ?? 1,
+ delivery: null,
+ } as const;
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: parentRun.threadId,
+ runId: parentRun.id,
+ ...(parentRun.rootNodeId === null ? {} : { nodeId: parentRun.rootNodeId }),
+ providerInstanceId: parentRun.providerInstanceId,
+ occurredAt: input.now,
+ payload: {
+ ...parentRun,
+ delegatedCompletion: nextCohort,
+ },
+ });
+ for (const task of tasks) {
+ if (
+ task.completionDelivery?.state === "acknowledged" ||
+ task.completionDelivery?.state === "delivered" ||
+ task.completionDelivery?.state === "disposed"
+ ) {
+ continue;
}
- const emitEvent = emit(input.events, input.command);
- const nextDisposition = cohort?.disposition === "disposed" ? "disposed" : input.disposition;
- const nextCohort = {
- disposition: nextDisposition,
- nextGeneration: cohort?.nextGeneration ?? 1,
- delivery: null,
- } as const;
yield* emitEvent({
- type: "run.updated",
+ type: "subagent.updated",
threadId: parentRun.threadId,
- runId: parentRun.id,
- ...(parentRun.rootNodeId === null ? {} : { nodeId: parentRun.rootNodeId }),
- providerInstanceId: parentRun.providerInstanceId,
+ ...(task.runId === null ? {} : { runId: task.runId }),
+ nodeId: task.id,
+ driver: task.driver,
+ providerInstanceId: task.providerInstanceId,
occurredAt: input.now,
payload: {
- ...parentRun,
- delegatedCompletion: nextCohort,
+ ...task,
+ completionDelivery: {
+ state: "disposed",
+ observedByRunId: null,
+ },
+ updatedAt: input.now,
},
});
- for (const task of tasks) {
- if (
- task.completionDelivery?.state === "acknowledged" ||
- task.completionDelivery?.state === "delivered" ||
- task.completionDelivery?.state === "disposed"
- ) {
- continue;
- }
- yield* emitEvent({
- type: "subagent.updated",
- threadId: parentRun.threadId,
- ...(task.runId === null ? {} : { runId: task.runId }),
- nodeId: task.id,
- driver: task.driver,
- providerInstanceId: task.providerInstanceId,
- occurredAt: input.now,
- payload: {
- ...task,
- completionDelivery: {
- state: "disposed",
- observedByRunId: null,
- },
- updatedAt: input.now,
- },
- });
- }
- const deliveryRun = completionDeliveryRun(input.projection, cohort?.delivery ?? null);
- if (input.cancelQueuedDelivery !== false && deliveryRun?.status === "queued") {
- yield* emitQueuedRunCancellation({
- command: input.command,
- events: input.events,
- projection: input.projection,
- run: deliveryRun,
- now: input.now,
- });
- }
- });
+ }
+ const deliveryRun = completionDeliveryRun(input.projection, cohort?.delivery ?? null);
+ if (input.cancelQueuedDelivery !== false && deliveryRun?.status === "queued") {
+ yield* emitQueuedRunCancellation({
+ command: input.command,
+ events: input.events,
+ projection: input.projection,
+ run: deliveryRun,
+ now: input.now,
+ });
+ }
+ });
const disposeAllDelegatedCompletionCohorts = (input: {
readonly command: OrchestrationV2Command;
@@ -3903,7 +3917,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
});
- const dispatchSteerIntoRun = (input: {
+ const dispatchSteerIntoRun = Effect.fn("Orchestrator.dispatchSteerIntoRun")(function* (input: {
readonly command: Extract<
OrchestrationV2Command,
{ readonly type: "message.dispatch" | "queued-message.promote-to-steer" }
@@ -3935,593 +3949,251 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"];
readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"];
readonly forceRestart: boolean;
- }) =>
- Effect.gen(function* () {
- const targetRun = input.projection.runs.find(
- (candidate) => candidate.id === input.targetRunId,
- );
- if (targetRun === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause: `Target run ${input.targetRunId} was not found.`,
- });
- }
- if (isNativeMaintenanceCommand(input)) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause:
- input.text.trim().toLowerCase() === "/compact"
- ? "Context compaction must run as a separate turn. Queue it or wait for the active turn to finish."
- : "Signing out must run as a separate turn. Queue it or wait for the active turn to finish.",
- });
- }
- if (isGoalCommand(input)) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause:
- "Goal commands must run as a separate turn. Queue it or wait for the active turn to finish.",
- });
- }
- const targetMessage = input.projection.messages.find(
- (message) => message.id === targetRun.userMessageId,
- );
- if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause:
- targetMessage.text.trim().toLowerCase() === "/compact"
- ? "Wait for context compaction to finish before steering the thread."
- : "Wait for sign-out to finish before steering the thread.",
- });
- }
- const rootNodeId = targetRun.rootNodeId;
- if (rootNodeId === null) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause: `Target run ${targetRun.id} has no root node.`,
- });
- }
- if (targetRun.status !== "running") {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause: `Target run ${targetRun.id} is ${targetRun.status} and cannot be steered.`,
- });
- }
- // The run reads as running until its provider stops, but a steer accepted
- // after Stop never reaches the agent.
- if (yield* stopReachedRun(input.command, input.command.threadId, targetRun.id)) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause: `Target run ${targetRun.id} is stopping and cannot be steered.`,
- });
- }
- const providerThread = input.projection.providerThreads.find(
- (candidate) => candidate.id === targetRun.providerThreadId,
- );
- if (providerThread === undefined || providerThread.providerSessionId === null) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause: `Provider thread ${targetRun.providerThreadId} has no active provider session for steering.`,
- });
- }
- const providerSessionId = providerThread.providerSessionId;
- const providerTurn = input.projection.providerTurns.find(
- (candidate) =>
- candidate.runAttemptId === targetRun.activeAttemptId && candidate.status === "running",
- );
- if (providerTurn === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause: `No running provider turn found for active run ${targetRun.id}.`,
- });
- }
- const sessionOption = yield* providerSessions.get(providerSessionId).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause,
- }),
- ),
- );
- if (Option.isNone(sessionOption)) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause: `Provider session ${providerThread.providerSessionId} is not active.`,
- });
- }
+ }) {
+ const targetRun = input.projection.runs.find((candidate) => candidate.id === input.targetRunId);
+ if (targetRun === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause: `Target run ${input.targetRunId} was not found.`,
+ });
+ }
+ if (isNativeMaintenanceCommand(input)) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause:
+ input.text.trim().toLowerCase() === "/compact"
+ ? "Context compaction must run as a separate turn. Queue it or wait for the active turn to finish."
+ : "Signing out must run as a separate turn. Queue it or wait for the active turn to finish.",
+ });
+ }
+ if (isGoalCommand(input)) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause:
+ "Goal commands must run as a separate turn. Queue it or wait for the active turn to finish.",
+ });
+ }
+ const targetMessage = input.projection.messages.find(
+ (message) => message.id === targetRun.userMessageId,
+ );
+ if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause:
+ targetMessage.text.trim().toLowerCase() === "/compact"
+ ? "Wait for context compaction to finish before steering the thread."
+ : "Wait for sign-out to finish before steering the thread.",
+ });
+ }
+ const rootNodeId = targetRun.rootNodeId;
+ if (rootNodeId === null) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause: `Target run ${targetRun.id} has no root node.`,
+ });
+ }
+ if (targetRun.status !== "running") {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause: `Target run ${targetRun.id} is ${targetRun.status} and cannot be steered.`,
+ });
+ }
+ // The run reads as running until its provider stops, but a steer accepted
+ // after Stop never reaches the agent.
+ if (yield* stopReachedRun(input.command, input.command.threadId, targetRun.id)) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause: `Target run ${targetRun.id} is stopping and cannot be steered.`,
+ });
+ }
+ const providerThread = input.projection.providerThreads.find(
+ (candidate) => candidate.id === targetRun.providerThreadId,
+ );
+ if (providerThread === undefined || providerThread.providerSessionId === null) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause: `Provider thread ${targetRun.providerThreadId} has no active provider session for steering.`,
+ });
+ }
+ const providerSessionId = providerThread.providerSessionId;
+ const providerTurn = input.projection.providerTurns.find(
+ (candidate) =>
+ candidate.runAttemptId === targetRun.activeAttemptId && candidate.status === "running",
+ );
+ if (providerTurn === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause: `No running provider turn found for active run ${targetRun.id}.`,
+ });
+ }
+ const sessionOption = yield* providerSessions.get(providerSessionId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause,
+ }),
+ ),
+ );
+ if (Option.isNone(sessionOption)) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause: `Provider session ${providerThread.providerSessionId} is not active.`,
+ });
+ }
- const session = sessionOption.value;
- const now = yield* DateTime.now;
- const emitEvent = emit(input.events, input.command);
- const selectionChanged = !modelSelectionsEqual(
- targetRun.modelSelection,
- input.modelSelection,
- );
- const providerInstanceChanged =
- targetRun.providerInstanceId !== input.modelSelection.instanceId;
- const selectionTransition =
- selectionChanged && !providerInstanceChanged
- ? yield* providerAdapters.get(targetRun.providerInstanceId).pipe(
- Effect.flatMap((adapter) =>
- adapter.planSelectionTransition({
- current: targetRun.modelSelection,
- target: input.modelSelection,
- sessionCapabilities: session.providerSession.capabilities,
+ const session = sessionOption.value;
+ const now = yield* DateTime.now;
+ const emitEvent = emit(input.events, input.command);
+ const selectionChanged = !modelSelectionsEqual(targetRun.modelSelection, input.modelSelection);
+ const providerInstanceChanged =
+ targetRun.providerInstanceId !== input.modelSelection.instanceId;
+ const selectionTransition =
+ selectionChanged && !providerInstanceChanged
+ ? yield* providerAdapters.get(targetRun.providerInstanceId).pipe(
+ Effect.flatMap((adapter) =>
+ adapter.planSelectionTransition({
+ current: targetRun.modelSelection,
+ target: input.modelSelection,
+ sessionCapabilities: session.providerSession.capabilities,
+ }),
+ ),
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProviderAdapterError({
+ commandId: input.command.commandId,
+ providerInstanceId: targetRun.providerInstanceId,
+ cause,
}),
- ),
- Effect.mapError(
- (cause) =>
- new OrchestratorProviderAdapterError({
- commandId: input.command.commandId,
- providerInstanceId: targetRun.providerInstanceId,
- cause,
- }),
- ),
- )
- : null;
- if (selectionTransition?.type === "reject") {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause: selectionTransition.reason,
- });
- }
- const appendSteeringMessage = (messageInput: {
+ ),
+ )
+ : null;
+ if (selectionTransition?.type === "reject") {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause: selectionTransition.reason,
+ });
+ }
+ const appendSteeringMessage = Effect.fn("Orchestrator.appendSteeringMessage")(
+ function* (messageInput: {
readonly runId: OrchestrationV2Run["id"];
readonly nodeId: OrchestrationV2ExecutionNode["id"];
readonly providerTurnId: typeof providerTurn.id | null;
readonly providerThreadId: OrchestrationV2ProviderThread["id"];
readonly providerInstanceId: ProviderInstanceId;
- }) =>
- Effect.gen(function* () {
- const message: OrchestrationV2ConversationMessage = {
- createdBy: input.createdBy,
- creationSource: input.creationSource,
- ...(input.delegatedCompletion === undefined
- ? {}
- : { delegatedCompletion: input.delegatedCompletion }),
- ...(input.scheduledTaskId === undefined
- ? {}
- : { scheduledTaskId: input.scheduledTaskId }),
- ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
- id: input.messageId,
- threadId: input.command.threadId,
- runId: messageInput.runId,
- nodeId: messageInput.nodeId,
- role: "user",
- text: input.text,
- attachments: input.attachments,
- ...(input.context ? { context: input.context } : {}),
- streaming: false,
- createdAt: now,
- updatedAt: now,
- };
- const turnItem: OrchestrationV2TurnItem = {
- createdBy: input.createdBy,
- creationSource: input.creationSource,
- ...(input.scheduledTaskId === undefined
- ? {}
- : { scheduledTaskId: input.scheduledTaskId }),
- ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
- id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
- threadId: input.command.threadId,
- runId: messageInput.runId,
- nodeId: messageInput.nodeId,
- providerThreadId: messageInput.providerThreadId,
- providerTurnId: messageInput.providerTurnId,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: yield* nextTurnItemOrdinal(input.projection),
- status: "completed",
- title: null,
- startedAt: now,
- completedAt: now,
- updatedAt: now,
- type: "user_message",
- messageId: input.messageId,
- inputIntent:
- input.command.type === "queued-message.promote-to-steer"
- ? "promoted_queued_to_steer"
- : "steer",
- text: input.text,
- attachments: input.attachments,
- ...(input.context ? { context: input.context } : {}),
- };
- yield* emitEvent({
- type: "message.updated",
- threadId: input.command.threadId,
- runId: messageInput.runId,
- nodeId: messageInput.nodeId,
- providerInstanceId: messageInput.providerInstanceId,
- occurredAt: now,
- payload: message,
- });
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: input.command.threadId,
- runId: messageInput.runId,
- nodeId: messageInput.nodeId,
- providerInstanceId: messageInput.providerInstanceId,
- occurredAt: now,
- payload: notificationTurnItem(turnItem, message, input.projection.subagents),
- });
- });
-
- // A selection the provider applies on its next turn joins the running
- // turn as a steer and waits for the next turn. Restarting the turn for it
- // would end the turn's native subagents, which a steer must never do.
- const selectionMustApplyNow =
- selectionChanged &&
- (providerInstanceChanged || selectionTransition?.type !== "apply_on_next_turn");
- const steeringPolicy = yield* enforceCommandPolicy(input.command)(
- commandPolicy.decideSteeringExecution({
- commandId: input.command.commandId,
- threadId: input.command.threadId,
- providerInstanceId: targetRun.providerInstanceId,
- capabilities: session.providerSession.capabilities,
- forceRestart: input.forceRestart || selectionMustApplyNow,
- }),
- );
-
- if (steeringPolicy === "active_steering") {
- const instanceChanged =
- input.projection.thread.providerInstanceId !== input.modelSelection.instanceId;
- if (
- input.delegatedCompletion === undefined &&
- (instanceChanged ||
- !modelSelectionsEqual(input.projection.thread.modelSelection, input.modelSelection))
- ) {
- yield* emitEvent({
- type: instanceChanged ? "thread.provider-switched" : "thread.model-selection-updated",
- threadId: input.command.threadId,
- providerInstanceId: input.modelSelection.instanceId,
- occurredAt: now,
- payload: {
- ...input.projection.thread,
- providerInstanceId: input.modelSelection.instanceId,
- modelSelection: input.modelSelection,
- updatedAt: now,
- },
- });
- }
- yield* appendSteeringMessage({
- runId: targetRun.id,
- nodeId: rootNodeId,
- providerTurnId: providerTurn.id,
- providerThreadId: providerThread.id,
- providerInstanceId: targetRun.providerInstanceId,
- });
- yield* Ref.update(input.effects, (existing) => [
- ...existing,
- {
- id: `effect:${input.command.commandId}:provider-turn.steer:${providerTurn.id}`,
- commandId: input.command.commandId,
- threadId: input.command.threadId,
- request: {
- type: "provider-turn.steer",
- providerSessionId,
- providerThreadId: providerThread.id,
- providerTurnId: providerTurn.id,
- messageId: input.messageId,
- },
- } satisfies PendingOrchestrationEffectV2,
- ]);
- return;
- }
-
- const currentAttempt = input.projection.attempts.find(
- (candidate) => candidate.id === targetRun.activeAttemptId,
- );
- const currentRootNode = input.projection.nodes.find(
- (candidate) => candidate.id === rootNodeId,
- );
- const attemptOrdinal =
- Math.max(
- 0,
- ...input.projection.attempts
- .filter((candidate) => candidate.runId === targetRun.id)
- .map((candidate) => candidate.attemptOrdinal),
- ) + 1;
- const nextAttemptId = idAllocator.derive.runAttempt({
- runId: targetRun.id,
- attemptOrdinal,
- });
- const nextRootNodeId = idAllocator.derive.rootNodeAttempt({
- runId: targetRun.id,
- attemptOrdinal,
- });
- let restartProviderThread = providerThread;
- let restartSessionTransition:
- | {
- readonly type: "replace";
- readonly replacementProviderSessionId: ProviderSessionId;
- }
- | { readonly type: "detach" }
- | null = null;
- let restartHandoff: OrchestrationV2ContextHandoff | null = null;
- let restartTransfer: OrchestrationV2ContextTransfer | null = null;
- const canResumeAcrossInstances =
- providerInstanceChanged &&
- providerThread.nativeThreadRef !== null &&
- (yield* providerSwitchService
- .plan({
- projection: {
- ...input.projection,
- thread: { ...input.projection.thread, modelSelection: targetRun.modelSelection },
- },
- targetModelSelection: input.modelSelection,
- })
- .pipe(mapDispatchError(input.command))).transition.type === "restart_and_resume";
- const requiresProviderThreadHandoff =
- (providerInstanceChanged && !canResumeAcrossInstances) ||
- selectionTransition?.type === "create_with_handoff";
- const requiresProviderSessionRestart =
- canResumeAcrossInstances || selectionTransition?.type === "restart_session";
- if (requiresProviderThreadHandoff) {
- const targetAdapter = yield* providerAdapters.get(input.modelSelection.instanceId).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorProviderAdapterError({
- commandId: input.command.commandId,
- providerInstanceId: input.modelSelection.instanceId,
- cause,
- }),
- ),
- );
- const targetCapabilities = yield* targetAdapter.getCapabilities().pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorProviderAdapterError({
- commandId: input.command.commandId,
- providerInstanceId: input.modelSelection.instanceId,
- cause,
- }),
- ),
- );
- yield* enforceCommandPolicy(input.command)(
- commandPolicy.ensureContextHandoff({
- commandId: input.command.commandId,
- threadId: input.command.threadId,
- providerInstanceId: input.modelSelection.instanceId,
- capabilities: targetCapabilities,
- strategy: "full_thread_summary",
- }),
- );
- const existingTargetProviderThread = rootProviderThreadsForProvider(
- input.projection,
- input.modelSelection.instanceId,
- ).find((candidate) => candidate.id !== providerThread.id);
- const targetProviderSessionId =
- existingTargetProviderThread?.providerSessionId ??
- (yield* mapDispatchError(input.command)(
- providerSessionIdFor({
- adapter: targetAdapter,
- providerInstanceId: input.modelSelection.instanceId,
- threadId: input.command.threadId,
- }),
- ));
- const targetProviderThreadBase: OrchestrationV2ProviderThread =
- existingTargetProviderThread === undefined
- ? {
- id: idAllocator.derive.providerThread({
- driver: targetAdapter.driver,
- nativeThreadId: `pending:${targetRun.id}:attempt:${attemptOrdinal}`,
- }),
- driver: targetAdapter.driver,
- providerInstanceId: input.modelSelection.instanceId,
- providerSessionId: targetProviderSessionId,
- appThreadId: input.command.threadId,
- ownerNodeId: null,
- nativeThreadRef: null,
- nativeConversationHeadRef: null,
- status: "not_loaded",
- firstRunOrdinal: targetRun.ordinal,
- lastRunOrdinal: targetRun.ordinal,
- handoffIds: [],
- forkedFrom: null,
- createdAt: now,
- updatedAt: now,
- }
- : {
- ...existingTargetProviderThread,
- providerSessionId: targetProviderSessionId,
- lastRunOrdinal: targetRun.ordinal,
- updatedAt: now,
- };
- const transferId = yield* mapDispatchError(input.command)(
- idAllocator.allocate.contextTransfer({
- sourceThreadId: input.command.threadId,
- targetThreadId: input.command.threadId,
- type: "provider_handoff",
- }),
- );
- restartHandoff = yield* contextHandoffService
- .prepareProviderHandoff({
- threadId: input.command.threadId,
- targetRunId: targetRun.id,
- transferId,
- fromProviderThreadIds: [providerThread.id],
- toProviderThreadId: targetProviderThreadBase.id,
- fromProviderInstanceId: targetRun.providerInstanceId,
- toProviderInstanceId: input.modelSelection.instanceId,
- coveredRunOrdinals: { from: 1, to: targetRun.ordinal },
- strategy: "full_thread_summary",
- items: yield* readHandoffItems(input.command.threadId),
- runs: input.projection.runs,
- createdAt: now,
- })
- .pipe(mapDispatchError(input.command));
- restartProviderThread = {
- ...targetProviderThreadBase,
- handoffIds: Array.from(
- new Set([...targetProviderThreadBase.handoffIds, restartHandoff.id]),
- ),
- };
- restartTransfer = {
- id: transferId,
- type: "provider_handoff",
- sourceThreadId: input.command.threadId,
- targetThreadId: input.command.threadId,
- sourcePoint: contextSourcePointForRun(input.projection, targetRun),
- basePoint: null,
- sourceProviderInstanceId: targetRun.providerInstanceId,
- targetProviderInstanceId: input.modelSelection.instanceId,
- targetRunId: targetRun.id,
- status: "consumed",
- resolution: {
- strategy: "portable_context",
- contextHandoffId: restartHandoff.id,
- },
+ }) {
+ const message: OrchestrationV2ConversationMessage = {
createdBy: input.createdBy,
- error: null,
+ creationSource: input.creationSource,
+ ...(input.delegatedCompletion === undefined
+ ? {}
+ : { delegatedCompletion: input.delegatedCompletion }),
+ ...(input.scheduledTaskId === undefined
+ ? {}
+ : { scheduledTaskId: input.scheduledTaskId }),
+ ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
+ id: input.messageId,
+ threadId: input.command.threadId,
+ runId: messageInput.runId,
+ nodeId: messageInput.nodeId,
+ role: "user",
+ text: input.text,
+ attachments: input.attachments,
+ ...(input.context ? { context: input.context } : {}),
+ streaming: false,
createdAt: now,
updatedAt: now,
- consumedAt: now,
};
- restartSessionTransition = { type: "detach" };
- } else if (requiresProviderSessionRestart) {
- const nextProviderSessionId = yield* mapDispatchError(input.command)(
- idAllocator.allocate.providerSession({
- providerInstanceId: input.modelSelection.instanceId,
- threadId: input.command.threadId,
- }),
- );
- restartProviderThread = {
- ...providerThread,
- providerInstanceId: input.modelSelection.instanceId,
- providerSessionId: nextProviderSessionId,
- status: "not_loaded",
+ const turnItem: OrchestrationV2TurnItem = {
+ createdBy: input.createdBy,
+ creationSource: input.creationSource,
+ ...(input.scheduledTaskId === undefined
+ ? {}
+ : { scheduledTaskId: input.scheduledTaskId }),
+ ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
+ id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
+ threadId: input.command.threadId,
+ runId: messageInput.runId,
+ nodeId: messageInput.nodeId,
+ providerThreadId: messageInput.providerThreadId,
+ providerTurnId: messageInput.providerTurnId,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: yield* nextTurnItemOrdinal(input.projection),
+ status: "completed",
+ title: null,
+ startedAt: now,
+ completedAt: now,
updatedAt: now,
+ type: "user_message",
+ messageId: input.messageId,
+ inputIntent:
+ input.command.type === "queued-message.promote-to-steer"
+ ? "promoted_queued_to_steer"
+ : "steer",
+ text: input.text,
+ attachments: input.attachments,
+ ...(input.context ? { context: input.context } : {}),
};
- restartSessionTransition = {
- type: "replace",
- replacementProviderSessionId: nextProviderSessionId,
- };
- }
- const resolvedRuntimePolicy = yield* runtimePolicy
- .resolve({ thread: input.projection.thread, modelSelection: input.modelSelection })
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause,
- }),
- ),
- );
- const checkpointScope = yield* checkpointService
- .prepareRootRunScope({
- threadId: input.command.threadId,
- runId: targetRun.id,
- rootNodeId: nextRootNodeId,
- providerThreadId: restartProviderThread.id,
- cwd:
- resolvedRuntimePolicy.cwd ??
- input.projection.thread.worktreePath ??
- session.providerSession.cwd,
- createdAt: now,
- })
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause,
- }),
- ),
- );
- const ensuredCheckpointScope = yield* checkpointService.ensureScope(checkpointScope).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause,
- }),
- ),
- );
- const restartedRun: OrchestrationV2Run = {
- ...targetRun,
- providerInstanceId: input.modelSelection.instanceId,
- modelSelection: input.modelSelection,
- providerThreadId: restartProviderThread.id,
- rootNodeId: nextRootNodeId,
- activeAttemptId: nextAttemptId,
- userMessageId: input.messageId,
- status: "starting",
- contextHandoffId: restartHandoff?.id ?? targetRun.contextHandoffId,
- };
- const nextAttempt: OrchestrationV2RunAttempt = {
- id: nextAttemptId,
- runId: targetRun.id,
- attemptOrdinal,
- rootNodeId: nextRootNodeId,
- providerInstanceId: input.modelSelection.instanceId,
- providerThreadId: restartProviderThread.id,
- providerTurnId: null,
- reason: "steering_restart",
- status: "pending",
- startedAt: null,
- completedAt: null,
- };
- const nextRootNode: OrchestrationV2ExecutionNode = {
- id: nextRootNodeId,
- threadId: input.command.threadId,
- runId: targetRun.id,
- parentNodeId: null,
- rootNodeId: nextRootNodeId,
- kind: "root_turn",
- status: "pending",
- countsForRun: true,
- providerThreadId: restartProviderThread.id,
- providerTurnId: null,
- nativeItemRef: null,
- runtimeRequestId: null,
- checkpointScopeId: ensuredCheckpointScope.id,
- startedAt: null,
- completedAt: null,
- };
- if (currentAttempt !== undefined) {
yield* emitEvent({
- type: "run-attempt.updated",
+ type: "message.updated",
threadId: input.command.threadId,
- runId: targetRun.id,
- nodeId: rootNodeId,
- providerInstanceId: targetRun.providerInstanceId,
+ runId: messageInput.runId,
+ nodeId: messageInput.nodeId,
+ providerInstanceId: messageInput.providerInstanceId,
occurredAt: now,
- payload: { ...currentAttempt, status: "superseded", completedAt: now },
+ payload: message,
});
- }
- if (currentRootNode !== undefined) {
yield* emitEvent({
- type: "node.updated",
+ type: "turn-item.updated",
threadId: input.command.threadId,
- runId: targetRun.id,
- nodeId: rootNodeId,
- providerInstanceId: targetRun.providerInstanceId,
+ runId: messageInput.runId,
+ nodeId: messageInput.nodeId,
+ providerInstanceId: messageInput.providerInstanceId,
occurredAt: now,
- payload: { ...currentRootNode, status: "interrupted", completedAt: now },
+ payload: notificationTurnItem(turnItem, message, input.projection.subagents),
});
- }
- if (selectionChanged) {
+ },
+ );
+
+ // A selection the provider applies on its next turn joins the running
+ // turn as a steer and waits for the next turn. Restarting the turn for it
+ // would end the turn's native subagents, which a steer must never do.
+ const selectionMustApplyNow =
+ selectionChanged &&
+ (providerInstanceChanged || selectionTransition?.type !== "apply_on_next_turn");
+ const steeringPolicy = yield* enforceCommandPolicy(input.command)(
+ commandPolicy.decideSteeringExecution({
+ commandId: input.command.commandId,
+ threadId: input.command.threadId,
+ providerInstanceId: targetRun.providerInstanceId,
+ capabilities: session.providerSession.capabilities,
+ forceRestart: input.forceRestart || selectionMustApplyNow,
+ }),
+ );
+
+ if (steeringPolicy === "active_steering") {
+ const instanceChanged =
+ input.projection.thread.providerInstanceId !== input.modelSelection.instanceId;
+ if (
+ input.delegatedCompletion === undefined &&
+ (instanceChanged ||
+ !modelSelectionsEqual(input.projection.thread.modelSelection, input.modelSelection))
+ ) {
yield* emitEvent({
- type: providerInstanceChanged
- ? "thread.provider-switched"
- : "thread.model-selection-updated",
+ type: instanceChanged ? "thread.provider-switched" : "thread.model-selection-updated",
threadId: input.command.threadId,
providerInstanceId: input.modelSelection.instanceId,
occurredAt: now,
@@ -4533,823 +4205,1008 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
});
}
- if (requiresProviderThreadHandoff || requiresProviderSessionRestart) {
- yield* emitEvent({
- type: "provider-thread.updated",
- threadId: input.command.threadId,
- driver: restartProviderThread.driver,
- providerInstanceId: input.modelSelection.instanceId,
- occurredAt: now,
- payload: restartProviderThread,
- });
- }
- if (restartHandoff !== null) {
- yield* emitEvent({
- type: "context-handoff.updated",
- threadId: input.command.threadId,
- runId: targetRun.id,
- providerInstanceId: input.modelSelection.instanceId,
- occurredAt: now,
- payload: restartHandoff,
- });
- }
- if (restartTransfer !== null) {
- yield* emitEvent({
- type: "context-transfer.created",
- threadId: input.command.threadId,
- runId: targetRun.id,
- providerInstanceId: input.modelSelection.instanceId,
- occurredAt: now,
- payload: restartTransfer,
- });
- }
- yield* emitEvent({
- type: "run.updated",
- threadId: input.command.threadId,
- runId: targetRun.id,
- nodeId: nextRootNodeId,
- providerInstanceId: input.modelSelection.instanceId,
- occurredAt: now,
- payload: restartedRun,
- });
- yield* emitEvent({
- type: "run-attempt.created",
- threadId: input.command.threadId,
- runId: targetRun.id,
- nodeId: nextRootNodeId,
- providerInstanceId: input.modelSelection.instanceId,
- occurredAt: now,
- payload: nextAttempt,
- });
- yield* emitEvent({
- type: "node.updated",
- threadId: input.command.threadId,
- runId: targetRun.id,
- nodeId: nextRootNodeId,
- providerInstanceId: input.modelSelection.instanceId,
- occurredAt: now,
- payload: nextRootNode,
- });
- yield* emitEvent({
- type: "checkpoint-scope.created",
- threadId: input.command.threadId,
- runId: targetRun.id,
- nodeId: nextRootNodeId,
- providerInstanceId: input.modelSelection.instanceId,
- occurredAt: now,
- payload: ensuredCheckpointScope,
- });
yield* appendSteeringMessage({
runId: targetRun.id,
- nodeId: nextRootNodeId,
- providerTurnId: null,
- providerThreadId: restartProviderThread.id,
- providerInstanceId: input.modelSelection.instanceId,
- });
- const interruptedAttemptId = targetRun.activeAttemptId;
- if (interruptedAttemptId === null) {
- return yield* new OrchestratorDispatchError({
- commandId: input.command.commandId,
- commandType: input.command.type,
- cause: `Active run ${targetRun.id} has no attempt to interrupt.`,
- });
- }
+ nodeId: rootNodeId,
+ providerTurnId: providerTurn.id,
+ providerThreadId: providerThread.id,
+ providerInstanceId: targetRun.providerInstanceId,
+ });
yield* Ref.update(input.effects, (existing) => [
...existing,
{
- id: `effect:${input.command.commandId}:provider-turn.restart:${providerTurn.id}`,
+ id: `effect:${input.command.commandId}:provider-turn.steer:${providerTurn.id}`,
commandId: input.command.commandId,
threadId: input.command.threadId,
request: {
- type: "provider-turn.restart",
+ type: "provider-turn.steer",
providerSessionId,
providerThreadId: providerThread.id,
providerTurnId: providerTurn.id,
- interruptedAttemptId,
- runId: targetRun.id,
- ...(restartSessionTransition === null
- ? {}
- : { sessionTransition: restartSessionTransition }),
+ messageId: input.messageId,
},
} satisfies PendingOrchestrationEffectV2,
]);
+ return;
+ }
+
+ const currentAttempt = input.projection.attempts.find(
+ (candidate) => candidate.id === targetRun.activeAttemptId,
+ );
+ const currentRootNode = input.projection.nodes.find((candidate) => candidate.id === rootNodeId);
+ const attemptOrdinal =
+ Math.max(
+ 0,
+ ...input.projection.attempts
+ .filter((candidate) => candidate.runId === targetRun.id)
+ .map((candidate) => candidate.attemptOrdinal),
+ ) + 1;
+ const nextAttemptId = idAllocator.derive.runAttempt({
+ runId: targetRun.id,
+ attemptOrdinal,
+ });
+ const nextRootNodeId = idAllocator.derive.rootNodeAttempt({
+ runId: targetRun.id,
+ attemptOrdinal,
+ });
+ let restartProviderThread = providerThread;
+ let restartSessionTransition:
+ | {
+ readonly type: "replace";
+ readonly replacementProviderSessionId: ProviderSessionId;
+ }
+ | { readonly type: "detach" }
+ | null = null;
+ let restartHandoff: OrchestrationV2ContextHandoff | null = null;
+ let restartTransfer: OrchestrationV2ContextTransfer | null = null;
+ const canResumeAcrossInstances =
+ providerInstanceChanged &&
+ providerThread.nativeThreadRef !== null &&
+ (yield* providerSwitchService
+ .plan({
+ projection: {
+ ...input.projection,
+ thread: { ...input.projection.thread, modelSelection: targetRun.modelSelection },
+ },
+ targetModelSelection: input.modelSelection,
+ })
+ .pipe(mapDispatchError(input.command))).transition.type === "restart_and_resume";
+ const requiresProviderThreadHandoff =
+ (providerInstanceChanged && !canResumeAcrossInstances) ||
+ selectionTransition?.type === "create_with_handoff";
+ const requiresProviderSessionRestart =
+ canResumeAcrossInstances || selectionTransition?.type === "restart_session";
+ if (requiresProviderThreadHandoff) {
+ const targetAdapter = yield* providerAdapters.get(input.modelSelection.instanceId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProviderAdapterError({
+ commandId: input.command.commandId,
+ providerInstanceId: input.modelSelection.instanceId,
+ cause,
+ }),
+ ),
+ );
+ const targetCapabilities = yield* targetAdapter.getCapabilities().pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProviderAdapterError({
+ commandId: input.command.commandId,
+ providerInstanceId: input.modelSelection.instanceId,
+ cause,
+ }),
+ ),
+ );
+ yield* enforceCommandPolicy(input.command)(
+ commandPolicy.ensureContextHandoff({
+ commandId: input.command.commandId,
+ threadId: input.command.threadId,
+ providerInstanceId: input.modelSelection.instanceId,
+ capabilities: targetCapabilities,
+ strategy: "full_thread_summary",
+ }),
+ );
+ const existingTargetProviderThread = rootProviderThreadsForProvider(
+ input.projection,
+ input.modelSelection.instanceId,
+ ).find((candidate) => candidate.id !== providerThread.id);
+ const targetProviderSessionId =
+ existingTargetProviderThread?.providerSessionId ??
+ (yield* mapDispatchError(input.command)(
+ providerSessionIdFor({
+ adapter: targetAdapter,
+ providerInstanceId: input.modelSelection.instanceId,
+ threadId: input.command.threadId,
+ }),
+ ));
+ const targetProviderThreadBase: OrchestrationV2ProviderThread =
+ existingTargetProviderThread === undefined
+ ? {
+ id: idAllocator.derive.providerThread({
+ driver: targetAdapter.driver,
+ nativeThreadId: `pending:${targetRun.id}:attempt:${attemptOrdinal}`,
+ }),
+ driver: targetAdapter.driver,
+ providerInstanceId: input.modelSelection.instanceId,
+ providerSessionId: targetProviderSessionId,
+ appThreadId: input.command.threadId,
+ ownerNodeId: null,
+ nativeThreadRef: null,
+ nativeConversationHeadRef: null,
+ status: "not_loaded",
+ firstRunOrdinal: targetRun.ordinal,
+ lastRunOrdinal: targetRun.ordinal,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ }
+ : {
+ ...existingTargetProviderThread,
+ providerSessionId: targetProviderSessionId,
+ lastRunOrdinal: targetRun.ordinal,
+ updatedAt: now,
+ };
+ const transferId = yield* mapDispatchError(input.command)(
+ idAllocator.allocate.contextTransfer({
+ sourceThreadId: input.command.threadId,
+ targetThreadId: input.command.threadId,
+ type: "provider_handoff",
+ }),
+ );
+ restartHandoff = yield* contextHandoffService
+ .prepareProviderHandoff({
+ threadId: input.command.threadId,
+ targetRunId: targetRun.id,
+ transferId,
+ fromProviderThreadIds: [providerThread.id],
+ toProviderThreadId: targetProviderThreadBase.id,
+ fromProviderInstanceId: targetRun.providerInstanceId,
+ toProviderInstanceId: input.modelSelection.instanceId,
+ coveredRunOrdinals: { from: 1, to: targetRun.ordinal },
+ strategy: "full_thread_summary",
+ items: yield* readHandoffItems(input.command.threadId),
+ runs: input.projection.runs,
+ createdAt: now,
+ })
+ .pipe(mapDispatchError(input.command));
+ restartProviderThread = {
+ ...targetProviderThreadBase,
+ handoffIds: Array.from(
+ new Set([...targetProviderThreadBase.handoffIds, restartHandoff.id]),
+ ),
+ };
+ restartTransfer = {
+ id: transferId,
+ type: "provider_handoff",
+ sourceThreadId: input.command.threadId,
+ targetThreadId: input.command.threadId,
+ sourcePoint: contextSourcePointForRun(input.projection, targetRun),
+ basePoint: null,
+ sourceProviderInstanceId: targetRun.providerInstanceId,
+ targetProviderInstanceId: input.modelSelection.instanceId,
+ targetRunId: targetRun.id,
+ status: "consumed",
+ resolution: {
+ strategy: "portable_context",
+ contextHandoffId: restartHandoff.id,
+ },
+ createdBy: input.createdBy,
+ error: null,
+ createdAt: now,
+ updatedAt: now,
+ consumedAt: now,
+ };
+ restartSessionTransition = { type: "detach" };
+ } else if (requiresProviderSessionRestart) {
+ const nextProviderSessionId = yield* mapDispatchError(input.command)(
+ idAllocator.allocate.providerSession({
+ providerInstanceId: input.modelSelection.instanceId,
+ threadId: input.command.threadId,
+ }),
+ );
+ restartProviderThread = {
+ ...providerThread,
+ providerInstanceId: input.modelSelection.instanceId,
+ providerSessionId: nextProviderSessionId,
+ status: "not_loaded",
+ updatedAt: now,
+ };
+ restartSessionTransition = {
+ type: "replace",
+ replacementProviderSessionId: nextProviderSessionId,
+ };
+ }
+ const resolvedRuntimePolicy = yield* runtimePolicy
+ .resolve({ thread: input.projection.thread, modelSelection: input.modelSelection })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause,
+ }),
+ ),
+ );
+ const checkpointScope = yield* checkpointService
+ .prepareRootRunScope({
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ rootNodeId: nextRootNodeId,
+ providerThreadId: restartProviderThread.id,
+ cwd:
+ resolvedRuntimePolicy.cwd ??
+ input.projection.thread.worktreePath ??
+ session.providerSession.cwd,
+ createdAt: now,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause,
+ }),
+ ),
+ );
+ const ensuredCheckpointScope = yield* checkpointService.ensureScope(checkpointScope).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause,
+ }),
+ ),
+ );
+ const restartedRun: OrchestrationV2Run = {
+ ...targetRun,
+ providerInstanceId: input.modelSelection.instanceId,
+ modelSelection: input.modelSelection,
+ providerThreadId: restartProviderThread.id,
+ rootNodeId: nextRootNodeId,
+ activeAttemptId: nextAttemptId,
+ userMessageId: input.messageId,
+ status: "starting",
+ contextHandoffId: restartHandoff?.id ?? targetRun.contextHandoffId,
+ };
+ const nextAttempt: OrchestrationV2RunAttempt = {
+ id: nextAttemptId,
+ runId: targetRun.id,
+ attemptOrdinal,
+ rootNodeId: nextRootNodeId,
+ providerInstanceId: input.modelSelection.instanceId,
+ providerThreadId: restartProviderThread.id,
+ providerTurnId: null,
+ reason: "steering_restart",
+ status: "pending",
+ startedAt: null,
+ completedAt: null,
+ };
+ const nextRootNode: OrchestrationV2ExecutionNode = {
+ id: nextRootNodeId,
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ parentNodeId: null,
+ rootNodeId: nextRootNodeId,
+ kind: "root_turn",
+ status: "pending",
+ countsForRun: true,
+ providerThreadId: restartProviderThread.id,
+ providerTurnId: null,
+ nativeItemRef: null,
+ runtimeRequestId: null,
+ checkpointScopeId: ensuredCheckpointScope.id,
+ startedAt: null,
+ completedAt: null,
+ };
+ if (currentAttempt !== undefined) {
+ yield* emitEvent({
+ type: "run-attempt.updated",
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ nodeId: rootNodeId,
+ providerInstanceId: targetRun.providerInstanceId,
+ occurredAt: now,
+ payload: { ...currentAttempt, status: "superseded", completedAt: now },
+ });
+ }
+ if (currentRootNode !== undefined) {
+ yield* emitEvent({
+ type: "node.updated",
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ nodeId: rootNodeId,
+ providerInstanceId: targetRun.providerInstanceId,
+ occurredAt: now,
+ payload: { ...currentRootNode, status: "interrupted", completedAt: now },
+ });
+ }
+ if (selectionChanged) {
+ yield* emitEvent({
+ type: providerInstanceChanged
+ ? "thread.provider-switched"
+ : "thread.model-selection-updated",
+ threadId: input.command.threadId,
+ providerInstanceId: input.modelSelection.instanceId,
+ occurredAt: now,
+ payload: {
+ ...input.projection.thread,
+ providerInstanceId: input.modelSelection.instanceId,
+ modelSelection: input.modelSelection,
+ updatedAt: now,
+ },
+ });
+ }
+ if (requiresProviderThreadHandoff || requiresProviderSessionRestart) {
+ yield* emitEvent({
+ type: "provider-thread.updated",
+ threadId: input.command.threadId,
+ driver: restartProviderThread.driver,
+ providerInstanceId: input.modelSelection.instanceId,
+ occurredAt: now,
+ payload: restartProviderThread,
+ });
+ }
+ if (restartHandoff !== null) {
+ yield* emitEvent({
+ type: "context-handoff.updated",
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ providerInstanceId: input.modelSelection.instanceId,
+ occurredAt: now,
+ payload: restartHandoff,
+ });
+ }
+ if (restartTransfer !== null) {
+ yield* emitEvent({
+ type: "context-transfer.created",
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ providerInstanceId: input.modelSelection.instanceId,
+ occurredAt: now,
+ payload: restartTransfer,
+ });
+ }
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ nodeId: nextRootNodeId,
+ providerInstanceId: input.modelSelection.instanceId,
+ occurredAt: now,
+ payload: restartedRun,
+ });
+ yield* emitEvent({
+ type: "run-attempt.created",
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ nodeId: nextRootNodeId,
+ providerInstanceId: input.modelSelection.instanceId,
+ occurredAt: now,
+ payload: nextAttempt,
+ });
+ yield* emitEvent({
+ type: "node.updated",
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ nodeId: nextRootNodeId,
+ providerInstanceId: input.modelSelection.instanceId,
+ occurredAt: now,
+ payload: nextRootNode,
+ });
+ yield* emitEvent({
+ type: "checkpoint-scope.created",
+ threadId: input.command.threadId,
+ runId: targetRun.id,
+ nodeId: nextRootNodeId,
+ providerInstanceId: input.modelSelection.instanceId,
+ occurredAt: now,
+ payload: ensuredCheckpointScope,
+ });
+ yield* appendSteeringMessage({
+ runId: targetRun.id,
+ nodeId: nextRootNodeId,
+ providerTurnId: null,
+ providerThreadId: restartProviderThread.id,
+ providerInstanceId: input.modelSelection.instanceId,
});
+ const interruptedAttemptId = targetRun.activeAttemptId;
+ if (interruptedAttemptId === null) {
+ return yield* new OrchestratorDispatchError({
+ commandId: input.command.commandId,
+ commandType: input.command.type,
+ cause: `Active run ${targetRun.id} has no attempt to interrupt.`,
+ });
+ }
+ yield* Ref.update(input.effects, (existing) => [
+ ...existing,
+ {
+ id: `effect:${input.command.commandId}:provider-turn.restart:${providerTurn.id}`,
+ commandId: input.command.commandId,
+ threadId: input.command.threadId,
+ request: {
+ type: "provider-turn.restart",
+ providerSessionId,
+ providerThreadId: providerThread.id,
+ providerTurnId: providerTurn.id,
+ interruptedAttemptId,
+ runId: targetRun.id,
+ ...(restartSessionTransition === null
+ ? {}
+ : { sessionTransition: restartSessionTransition }),
+ },
+ } satisfies PendingOrchestrationEffectV2,
+ ]);
+ });
- const dispatchMessage = (
+ const dispatchMessage = Effect.fn("Orchestrator.dispatchMessage")(function* (
command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
- let projection = yield* getProjectionWithPendingEvents(command.threadId, events);
- if (command.manualContinuationOfRunId !== undefined) {
- const source = projection.runs.find((run) => run.id === command.manualContinuationOfRunId);
- const limited = latestRootProviderFailure(source ?? null, projection.turnItems);
- if (
- command.dispatchMode.type !== "start_immediately" ||
- source === undefined ||
- (source.status !== "interrupted" &&
- !(source.status === "failed" && limited?.class === "usage_limit")) ||
- latestExecutedRun(projection.runs)?.id !== source.id ||
- projection.thread.archivedAt !== null ||
- projection.thread.deletedAt !== null ||
- projection.runtimeRequests.some((request) => request.status === "pending")
- ) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "This thread can no longer be resumed from that run.",
- });
- }
- }
- if (command.usageLimitContinuationOfRunId !== undefined) {
- const run = usageLimitBlockedRun(projection.runs, projection.turnItems, null);
- const failure = latestRootProviderFailure(run, projection.turnItems);
- const recovery = projection.thread.limitRecovery;
- const now = yield* DateTime.now;
- if (
- run?.id !== command.usageLimitContinuationOfRunId ||
- failure?.class !== "usage_limit" ||
- threadShellFromProjection(projection).lastErrorClass !== "usage_limit" ||
- !recovery?.autoResume ||
- recovery.requestId !== command.usageLimitRecoveryRequestId ||
- recovery.runId !== run.id ||
- recovery.resetAt !== failure.resetAt ||
- Date.parse(recovery.resetAt) > DateTime.toEpochMillis(now) ||
- projection.thread.archivedAt !== null ||
- projection.thread.deletedAt !== null ||
- projection.thread.settledOverride === "settled" ||
- projection.thread.providerInstanceId !== run.providerInstanceId ||
- projection.runtimeRequests.some((request) => request.status === "pending") ||
- (projection.thread.snoozedUntil != null &&
- DateTime.toEpochMillis(projection.thread.snoozedUntil) > DateTime.toEpochMillis(now))
- ) {
- yield* emit(
- events,
- command,
- )({
- type: "thread.metadata-updated",
- threadId: command.threadId,
- occurredAt: now,
- payload: {
- ...projection.thread,
- ...(recovery?.autoResume &&
- recovery.requestId === command.usageLimitRecoveryRequestId &&
- recovery.runId === command.usageLimitContinuationOfRunId &&
- projection.thread.snoozedUntil != null &&
- DateTime.toEpochMillis(projection.thread.snoozedUntil) > DateTime.toEpochMillis(now)
- ? { limitRecovery: { ...recovery, requestId: command.commandId } }
- : {}),
- },
- });
- return;
- }
+ ) {
+ let projection = yield* getProjectionWithPendingEvents(command.threadId, events);
+ if (command.manualContinuationOfRunId !== undefined) {
+ const source = projection.runs.find((run) => run.id === command.manualContinuationOfRunId);
+ const limited = latestRootProviderFailure(source ?? null, projection.turnItems);
+ if (
+ command.dispatchMode.type !== "start_immediately" ||
+ source === undefined ||
+ (source.status !== "interrupted" &&
+ !(source.status === "failed" && limited?.class === "usage_limit")) ||
+ latestExecutedRun(projection.runs)?.id !== source.id ||
+ projection.thread.archivedAt !== null ||
+ projection.thread.deletedAt !== null ||
+ projection.runtimeRequests.some((request) => request.status === "pending")
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "This thread can no longer be resumed from that run.",
+ });
}
-
- if (command.restartContinuationOfRunId !== undefined) {
- const source = projection.runs.find((run) => run.id === command.restartContinuationOfRunId);
- if (
- !source ||
- !isRestartContinuationSource(source, projection.providerTurns) ||
- projection.thread.archivedAt !== null ||
- projection.thread.deletedAt !== null ||
- projection.thread.providerInstanceId !== source.providerInstanceId ||
- projection.runs.some(
- (run) =>
- run.id !== source.id &&
- run.status !== "queued" &&
- !cancelledBeforeStart(run) &&
- runRanAfter(run, source),
- ) ||
- (yield* stopReachedRun(command, command.threadId, source.id))
- ) {
- // Preserve the current row so stale automatic deliveries receive an
- // accepted receipt without changing work or repeatedly retrying.
- yield* emit(
- events,
- command,
- )({
- type: "thread.metadata-updated",
- threadId: command.threadId,
- occurredAt: yield* DateTime.now,
- payload: projection.thread,
- });
- return;
- }
- }
-
- if (projection.thread.lastVisitedAt === null && !isNativeMaintenanceCommand(command)) {
- const now = yield* DateTime.now;
- // Null keeps imported history read. The first fresh dispatch establishes
- // a read watermark so its completion can be unread on every client.
- // Offset it so a completion in the same millisecond is still unread.
- const event = yield* emit(
+ }
+ if (command.usageLimitContinuationOfRunId !== undefined) {
+ const run = usageLimitBlockedRun(projection.runs, projection.turnItems, null);
+ const failure = latestRootProviderFailure(run, projection.turnItems);
+ const recovery = projection.thread.limitRecovery;
+ const now = yield* DateTime.now;
+ if (
+ run?.id !== command.usageLimitContinuationOfRunId ||
+ failure?.class !== "usage_limit" ||
+ threadShellFromProjection(projection).lastErrorClass !== "usage_limit" ||
+ !recovery?.autoResume ||
+ recovery.requestId !== command.usageLimitRecoveryRequestId ||
+ recovery.runId !== run.id ||
+ recovery.resetAt !== failure.resetAt ||
+ Date.parse(recovery.resetAt) > DateTime.toEpochMillis(now) ||
+ projection.thread.archivedAt !== null ||
+ projection.thread.deletedAt !== null ||
+ projection.thread.settledOverride === "settled" ||
+ projection.thread.providerInstanceId !== run.providerInstanceId ||
+ projection.runtimeRequests.some((request) => request.status === "pending") ||
+ (projection.thread.snoozedUntil != null &&
+ DateTime.toEpochMillis(projection.thread.snoozedUntil) > DateTime.toEpochMillis(now))
+ ) {
+ yield* emit(
events,
command,
)({
type: "thread.metadata-updated",
threadId: command.threadId,
- providerInstanceId: projection.thread.providerInstanceId,
occurredAt: now,
payload: {
...projection.thread,
- lastVisitedAt: DateTime.subtract(now, { milliseconds: 1 }),
+ ...(recovery?.autoResume &&
+ recovery.requestId === command.usageLimitRecoveryRequestId &&
+ recovery.runId === command.usageLimitContinuationOfRunId &&
+ projection.thread.snoozedUntil != null &&
+ DateTime.toEpochMillis(projection.thread.snoozedUntil) > DateTime.toEpochMillis(now)
+ ? { limitRecovery: { ...recovery, requestId: command.commandId } }
+ : {}),
},
});
- projection = applyToProjection(projection, event);
+ return;
}
+ }
- const continuedTaskId = projection.runs.find(
- (run) => run.id === command.restartContinuationOfRunId,
- )?.delegatedTaskId;
-
- if (projection.thread.settledOverride !== null) {
- const now = yield* DateTime.now;
- const thread: OrchestrationV2AppThread = {
- ...projection.thread,
- settledOverride: null,
- settledAt: null,
- unsettledAt:
- projection.thread.settledOverride === "active"
- ? (projection.thread.unsettledAt ?? null)
- : now,
- updatedAt: now,
- };
- yield* emit(
- events,
- command,
- )({
- type: "thread.unsettled",
- threadId: command.threadId,
- providerInstanceId: thread.providerInstanceId,
- occurredAt: now,
- payload: thread,
- });
- projection = yield* getProjectionWithPendingEvents(command.threadId, events);
- }
- if (projection.thread.snoozedUntil != null) {
- const now = yield* DateTime.now;
- const thread: OrchestrationV2AppThread = {
- ...projection.thread,
- snoozedUntil: null,
- snoozedAt: null,
- updatedAt: now,
- };
- yield* emit(
- events,
- command,
- )({
- type: "thread.unsnoozed",
- threadId: command.threadId,
- providerInstanceId: thread.providerInstanceId,
- occurredAt: now,
- payload: thread,
- });
- projection = yield* getProjectionWithPendingEvents(command.threadId, events);
- }
- const userMessages = projection.messages.filter((message) => message.role === "user");
- const onlyMaintenanceHistory =
- userMessages.length > 0 && userMessages.every(isNativeMaintenanceCommand);
+ if (command.restartContinuationOfRunId !== undefined) {
+ const source = projection.runs.find((run) => run.id === command.restartContinuationOfRunId);
if (
- !isNativeMaintenanceCommand(command) &&
- ((command.titleSeed !== undefined &&
- (yield* projectionStore
- .getMessageCount(command.threadId)
- .pipe(mapDispatchError(command))) === 0) ||
- (command.createdBy === "user" && onlyMaintenanceHistory))
+ !source ||
+ !isRestartContinuationSource(source, projection.providerTurns) ||
+ projection.thread.archivedAt !== null ||
+ projection.thread.deletedAt !== null ||
+ projection.thread.providerInstanceId !== source.providerInstanceId ||
+ projection.runs.some(
+ (run) =>
+ run.id !== source.id &&
+ run.status !== "queued" &&
+ !cancelledBeforeStart(run) &&
+ runRanAfter(run, source),
+ ) ||
+ (yield* stopReachedRun(command, command.threadId, source.id))
) {
- const now = yield* DateTime.now;
- const thread: OrchestrationV2AppThread = {
- ...projection.thread,
- title: command.titleSeed ?? projection.thread.title,
- titleRegeneration: { requestId: command.commandId, startedAt: now },
- updatedAt: now,
- };
+ // Preserve the current row so stale automatic deliveries receive an
+ // accepted receipt without changing work or repeatedly retrying.
yield* emit(
events,
command,
)({
type: "thread.metadata-updated",
threadId: command.threadId,
- providerInstanceId: thread.providerInstanceId,
- occurredAt: now,
- payload: thread,
+ occurredAt: yield* DateTime.now,
+ payload: projection.thread,
});
- yield* Ref.update(effects, (existing) => [
- ...existing,
- pendingThreadTitleGenerationEffect(command.commandId, command.threadId, {
- type: "initial",
- messageId: command.messageId,
- }),
- ]);
- projection = yield* getProjectionWithPendingEvents(command.threadId, events);
+ return;
}
- const modelSelection = command.modelSelection ?? projection.thread.modelSelection;
- let dispatchMode = resolveMessageDispatchIntent(
- projection,
- command.dispatchMode,
- command.deliveryIntent,
+ }
+
+ if (projection.thread.lastVisitedAt === null && !isNativeMaintenanceCommand(command)) {
+ const now = yield* DateTime.now;
+ // Null keeps imported history read. The first fresh dispatch establishes
+ // a read watermark so its completion can be unread on every client.
+ // Offset it so a completion in the same millisecond is still unread.
+ const event = yield* emit(
+ events,
+ command,
+ )({
+ type: "thread.metadata-updated",
+ threadId: command.threadId,
+ providerInstanceId: projection.thread.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...projection.thread,
+ lastVisitedAt: DateTime.subtract(now, { milliseconds: 1 }),
+ },
+ });
+ projection = applyToProjection(projection, event);
+ }
+
+ const continuedTaskId = projection.runs.find(
+ (run) => run.id === command.restartContinuationOfRunId,
+ )?.delegatedTaskId;
+
+ if (projection.thread.settledOverride !== null) {
+ const now = yield* DateTime.now;
+ const thread: OrchestrationV2AppThread = {
+ ...projection.thread,
+ settledOverride: null,
+ settledAt: null,
+ unsettledAt:
+ projection.thread.settledOverride === "active"
+ ? (projection.thread.unsettledAt ?? null)
+ : now,
+ updatedAt: now,
+ };
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "thread.unsettled",
+ threadId: command.threadId,
+ providerInstanceId: thread.providerInstanceId,
+ occurredAt: now,
+ payload: thread,
+ });
+ projection = yield* getProjectionWithPendingEvents(command.threadId, events);
+ }
+ if (projection.thread.snoozedUntil != null) {
+ const now = yield* DateTime.now;
+ const thread: OrchestrationV2AppThread = {
+ ...projection.thread,
+ snoozedUntil: null,
+ snoozedAt: null,
+ updatedAt: now,
+ };
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "thread.unsnoozed",
+ threadId: command.threadId,
+ providerInstanceId: thread.providerInstanceId,
+ occurredAt: now,
+ payload: thread,
+ });
+ projection = yield* getProjectionWithPendingEvents(command.threadId, events);
+ }
+ const userMessages = projection.messages.filter((message) => message.role === "user");
+ const onlyMaintenanceHistory =
+ userMessages.length > 0 && userMessages.every(isNativeMaintenanceCommand);
+ if (
+ !isNativeMaintenanceCommand(command) &&
+ ((command.titleSeed !== undefined &&
+ (yield* projectionStore
+ .getMessageCount(command.threadId)
+ .pipe(mapDispatchError(command))) === 0) ||
+ (command.createdBy === "user" && onlyMaintenanceHistory))
+ ) {
+ const now = yield* DateTime.now;
+ const thread: OrchestrationV2AppThread = {
+ ...projection.thread,
+ title: command.titleSeed ?? projection.thread.title,
+ titleRegeneration: { requestId: command.commandId, startedAt: now },
+ updatedAt: now,
+ };
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "thread.metadata-updated",
+ threadId: command.threadId,
+ providerInstanceId: thread.providerInstanceId,
+ occurredAt: now,
+ payload: thread,
+ });
+ yield* Ref.update(effects, (existing) => [
+ ...existing,
+ pendingThreadTitleGenerationEffect(command.commandId, command.threadId, {
+ type: "initial",
+ messageId: command.messageId,
+ }),
+ ]);
+ projection = yield* getProjectionWithPendingEvents(command.threadId, events);
+ }
+ const modelSelection = command.modelSelection ?? projection.thread.modelSelection;
+ let dispatchMode = resolveMessageDispatchIntent(
+ projection,
+ command.dispatchMode,
+ command.deliveryIntent,
+ );
+ if (dispatchMode.type === "steer_active") {
+ const targetRunId = dispatchMode.targetRunId;
+ const target = projection.runs.find((run) => run.id === targetRunId);
+ const turn = latestProviderTurnForAttempt(
+ projection.providerTurns.filter((candidate) => candidate.nodeId === target?.rootNodeId),
+ target?.activeAttemptId,
);
- if (dispatchMode.type === "steer_active") {
- const targetRunId = dispatchMode.targetRunId;
- const target = projection.runs.find((run) => run.id === targetRunId);
- const turn = latestProviderTurnForAttempt(
- projection.providerTurns.filter((candidate) => candidate.nodeId === target?.rootNodeId),
- target?.activeAttemptId,
- );
- // The client may still show a running turn while its completion is being
- // projected. Preserve the submission as a new turn when steering is too late.
- if (
- target !== undefined &&
- (target.status === "completed" ||
- ((target.status === "running" || target.status === "waiting") &&
- turn !== undefined &&
- turn.status === "completed"))
- ) {
- dispatchMode = { type: "start_immediately" };
- }
- }
- // Stop leaves the run reading as running until its provider stops. A plain
- // send in that window queues behind the stopped queue instead of steering
- // text the agent never receives, and like any user send it releases the
- // hold; an explicit steer or restart still fails below.
+ // The client may still show a running turn while its completion is being
+ // projected. Preserve the submission as a new turn when steering is too late.
if (
- command.deliveryIntent === "auto" &&
- (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") &&
- (yield* stopReachedRun(command, command.threadId, dispatchMode.targetRunId))
+ target !== undefined &&
+ (target.status === "completed" ||
+ ((target.status === "running" || target.status === "waiting") &&
+ turn !== undefined &&
+ turn.status === "completed"))
) {
- dispatchMode = { type: "queue_after_active" };
+ dispatchMode = { type: "start_immediately" };
}
+ }
+ // Stop leaves the run reading as running until its provider stops. A plain
+ // send in that window queues behind the stopped queue instead of steering
+ // text the agent never receives, and like any user send it releases the
+ // hold; an explicit steer or restart still fails below.
+ if (
+ command.deliveryIntent === "auto" &&
+ (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") &&
+ (yield* stopReachedRun(command, command.threadId, dispatchMode.targetRunId))
+ ) {
+ dispatchMode = { type: "queue_after_active" };
+ }
+ if (
+ command.notification !== undefined &&
+ (command.createdBy !== "agent" ||
+ (command.creationSource !== "server" && command.creationSource !== "provider") ||
+ (dispatchMode.type !== "queue_after_active" &&
+ !(
+ command.restartContinuationOfRunId !== undefined &&
+ dispatchMode.type === "start_immediately"
+ )))
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Notifications must be server- or provider-created queued messages.",
+ });
+ }
+ let delegatedCompletion: OrchestrationV2ConversationMessage["delegatedCompletion"] | undefined;
+ if (command.delegatedCompletion !== undefined) {
+ const requestedCompletion = command.delegatedCompletion;
if (
- command.notification !== undefined &&
- (command.createdBy !== "agent" ||
- (command.creationSource !== "server" && command.creationSource !== "provider") ||
- (dispatchMode.type !== "queue_after_active" &&
- !(
- command.restartContinuationOfRunId !== undefined &&
- dispatchMode.type === "start_immediately"
- )))
+ command.createdBy !== "agent" ||
+ command.creationSource !== "server" ||
+ dispatchMode.type !== "queue_after_active"
) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
- cause: "Notifications must be server- or provider-created queued messages.",
+ cause: "Delegated completion delivery must be a server-created queued message.",
});
}
- let delegatedCompletion:
- | OrchestrationV2ConversationMessage["delegatedCompletion"]
- | undefined;
- if (command.delegatedCompletion !== undefined) {
- const requestedCompletion = command.delegatedCompletion;
- if (
- command.createdBy !== "agent" ||
- command.creationSource !== "server" ||
- dispatchMode.type !== "queue_after_active"
- ) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "Delegated completion delivery must be a server-created queued message.",
- });
- }
- const parentRun = projection.runs.find(
- (candidate) => candidate.id === requestedCompletion.parentRunId,
- );
- const delivery = parentRun?.delegatedCompletion?.delivery;
- if (
- parentRun?.delegatedCompletion?.disposition !== "open" ||
- delivery === null ||
- delivery === undefined ||
- delivery.generation !== requestedCompletion.generation ||
- delivery.messageId !== command.messageId ||
- (projection.messages.some((candidate) => candidate.id === command.messageId) &&
- !isUndeliveredMailboxSteer(projection, command.messageId))
- ) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "Delegated completion delivery is no longer dispatchable.",
- });
- }
- delegatedCompletion = {
- parentRunId: requestedCompletion.parentRunId,
- generation: delivery.generation,
- taskIds: delivery.taskIds,
- };
- }
- // Route durable mailbox deliveries under the thread lock, using the live
- // session's capabilities. Never interrupt/restart a turn for a notification.
+ const parentRun = projection.runs.find(
+ (candidate) => candidate.id === requestedCompletion.parentRunId,
+ );
+ const delivery = parentRun?.delegatedCompletion?.delivery;
if (
- delegatedCompletion !== undefined &&
- delegatedCompletion.taskIds.every(
- (id) => projection.subagents.find((task) => task.id === id)?.completionWake === "always",
- )
+ parentRun?.delegatedCompletion?.disposition !== "open" ||
+ delivery === null ||
+ delivery === undefined ||
+ delivery.generation !== requestedCompletion.generation ||
+ delivery.messageId !== command.messageId ||
+ (projection.messages.some((candidate) => candidate.id === command.messageId) &&
+ !isUndeliveredMailboxSteer(projection, command.messageId))
) {
- const active = projection.runs.find((run) => run.status === "running");
- const providerThread = projection.providerThreads.find(
- (row) => row.id === active?.providerThreadId,
- );
- const activeTurn = projection.providerTurns.find(
- (turn) => turn.runAttemptId === active?.activeAttemptId && turn.status === "running",
- );
- const activeMessage = projection.messages.find(
- (message) => message.id === active?.userMessageId,
- );
- if (
- active !== undefined &&
- activeTurn !== undefined &&
- providerThread?.providerSessionId != null &&
- (activeMessage === undefined || !isNativeMaintenanceCommand(activeMessage))
- ) {
- const session = yield* providerSessions
- .get(providerThread.providerSessionId)
- .pipe(Effect.orElseSucceed(() => Option.none()));
- if (
- Option.isSome(session) &&
- session.value.providerSession.capabilities.turns.supportsActiveSteering &&
- session.value.providerSession.capabilities.turns.activeSteeringInterruptsTools !== true
- ) {
- dispatchMode = { type: "steer_active", targetRunId: active.id };
- }
- }
- }
- const dispatchText =
- delegatedCompletion === undefined
- ? command.text
- : delegatedCompletionWakeDetail(delegatedCompletion.taskIds);
- const sourcePlanProjection =
- command.sourcePlanRef === undefined
- ? null
- : yield* getProjectionWithPendingEvents(command.sourcePlanRef.threadId, events);
- const sourcePlanArtifact =
- command.sourcePlanRef === undefined
- ? undefined
- : yield* projectionStore
- .getPlan(command.sourcePlanRef.threadId, command.sourcePlanRef.planId)
- .pipe(mapDispatchError(command));
- const sourcePlan = sourcePlanArtifact?.kind === "proposed_plan" ? sourcePlanArtifact : null;
- if (command.sourcePlanRef !== undefined && sourcePlan === null) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
- cause: `Proposed plan ${command.sourcePlanRef.planId} does not exist on thread ${command.sourcePlanRef.threadId}.`,
+ cause: "Delegated completion delivery is no longer dispatchable.",
});
}
+ delegatedCompletion = {
+ parentRunId: requestedCompletion.parentRunId,
+ generation: delivery.generation,
+ taskIds: delivery.taskIds,
+ };
+ }
+ // Route durable mailbox deliveries under the thread lock, using the live
+ // session's capabilities. Never interrupt/restart a turn for a notification.
+ if (
+ delegatedCompletion !== undefined &&
+ delegatedCompletion.taskIds.every(
+ (id) => projection.subagents.find((task) => task.id === id)?.completionWake === "always",
+ )
+ ) {
+ const active = projection.runs.find((run) => run.status === "running");
+ const providerThread = projection.providerThreads.find(
+ (row) => row.id === active?.providerThreadId,
+ );
+ const activeTurn = projection.providerTurns.find(
+ (turn) => turn.runAttemptId === active?.activeAttemptId && turn.status === "running",
+ );
+ const activeMessage = projection.messages.find(
+ (message) => message.id === active?.userMessageId,
+ );
if (
- sourcePlanProjection !== null &&
- sourcePlanProjection.thread.projectId !== projection.thread.projectId
+ active !== undefined &&
+ activeTurn !== undefined &&
+ providerThread?.providerSessionId != null &&
+ (activeMessage === undefined || !isNativeMaintenanceCommand(activeMessage))
) {
+ const session = yield* providerSessions
+ .get(providerThread.providerSessionId)
+ .pipe(Effect.orElseSucceed(() => Option.none()));
+ if (
+ Option.isSome(session) &&
+ session.value.providerSession.capabilities.turns.supportsActiveSteering &&
+ session.value.providerSession.capabilities.turns.activeSteeringInterruptsTools !== true
+ ) {
+ dispatchMode = { type: "steer_active", targetRunId: active.id };
+ }
+ }
+ }
+ const dispatchText =
+ delegatedCompletion === undefined
+ ? command.text
+ : delegatedCompletionWakeDetail(delegatedCompletion.taskIds);
+ const sourcePlanProjection =
+ command.sourcePlanRef === undefined
+ ? null
+ : yield* getProjectionWithPendingEvents(command.sourcePlanRef.threadId, events);
+ const sourcePlanArtifact =
+ command.sourcePlanRef === undefined
+ ? undefined
+ : yield* projectionStore
+ .getPlan(command.sourcePlanRef.threadId, command.sourcePlanRef.planId)
+ .pipe(mapDispatchError(command));
+ const sourcePlan = sourcePlanArtifact?.kind === "proposed_plan" ? sourcePlanArtifact : null;
+ if (command.sourcePlanRef !== undefined && sourcePlan === null) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Proposed plan ${command.sourcePlanRef.planId} does not exist on thread ${command.sourcePlanRef.threadId}.`,
+ });
+ }
+ if (
+ sourcePlanProjection !== null &&
+ sourcePlanProjection.thread.projectId !== projection.thread.projectId
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Proposed plan ${command.sourcePlanRef?.planId} belongs to a different project.`,
+ });
+ }
+ if (sourcePlan !== null && sourcePlan.status !== "active") {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Proposed plan ${sourcePlan.id} is not active.`,
+ });
+ }
+ const completeSourcePlan = (occurredAt: DateTime.Utc) =>
+ sourcePlan === null
+ ? Effect.void
+ : emit(
+ events,
+ command,
+ )({
+ type: "plan.updated",
+ threadId: sourcePlan.threadId,
+ ...(sourcePlan.runId === null ? {} : { runId: sourcePlan.runId }),
+ nodeId: sourcePlan.nodeId,
+ occurredAt,
+ payload: { ...sourcePlan, status: "completed" },
+ });
+
+ if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") {
+ yield* dispatchSteerIntoRun({
+ command,
+ events,
+ effects,
+ projection,
+ modelSelection:
+ delegatedCompletion === undefined
+ ? modelSelection
+ : (projection.runs.find((run) => run.id === dispatchMode.targetRunId)?.modelSelection ??
+ modelSelection),
+ delegatedCompletion,
+ targetRunId: dispatchMode.targetRunId,
+ messageId: command.messageId,
+ text: dispatchText,
+ ...(command.context ? { context: command.context } : {}),
+ attachments: command.attachments,
+ createdBy: command.createdBy,
+ creationSource: command.creationSource,
+ ...(command.scheduledTaskId === undefined
+ ? {}
+ : { scheduledTaskId: command.scheduledTaskId }),
+ ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ forceRestart: dispatchMode.type === "restart_active",
+ });
+ return;
+ }
+
+ const activeProviderThread = projection.providerThreads.find(
+ (candidate) => candidate.id === projection.thread.activeProviderThreadId,
+ );
+ const activeRun = projection.runs.find(isBlockingRun);
+ // A message queued during worktree setup can arrive after that setup failed
+ // without a worktree. It waits, held, like the messages queued before the
+ // failure, instead of starting in the project checkout.
+ const latestRun = latestExecutedRun(projection.runs);
+ const worktreeMissingRun =
+ activeRun === undefined &&
+ dispatchMode.type === "queue_after_active" &&
+ (latestRun?.status === "failed" || latestRun?.status === "interrupted") &&
+ latestRun.workspacePreparation?.type === "worktree" &&
+ projection.thread.worktreePath === null
+ ? latestRun
+ : undefined;
+ const queueBehindRun = activeRun ?? worktreeMissingRun;
+ const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection);
+ const startsOrQueuesRun =
+ dispatchMode.type === "defer_start" ||
+ dispatchMode.type === "start_immediately" ||
+ dispatchMode.type === "queue_after_active";
+ const shouldQueue = queueBehindRun !== undefined && startsOrQueuesRun;
+ // A message the user sends from a client means they are back, so the
+ // queue a stop or a restart held runs again, in its order, rather than
+ // waiting for a Resume.
+ // Continuations and scheduled tasks the server sends for them are not
+ // them coming back. Starting the queue still re-holds it for a failed
+ // provider or a usage limit; a queue held after worktree setup failed
+ // keeps its hold until a worktree exists, even once later messages have
+ // run, since its messages would start in the project checkout.
+ const worktreeSetupUnresolved =
+ projection.thread.worktreePath === null &&
+ projection.runs.some(
+ (run) =>
+ (run.status === "failed" || run.status === "interrupted") &&
+ run.workspacePreparation?.type === "worktree",
+ );
+ const sentByUserFromClient =
+ command.createdBy === "user" &&
+ (command.creationSource === "web" || command.creationSource === "mobile") &&
+ command.scheduledTaskId === undefined;
+ const heldRunsToRelease =
+ sentByUserFromClient && startsOrQueuesRun && !worktreeSetupUnresolved
+ ? projection.runs.filter((run) => run.status === "queued" && run.queueHeld === true)
+ : [];
+ const releasedAt = yield* DateTime.now;
+ for (const held of heldRunsToRelease) {
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "run.updated",
+ threadId: command.threadId,
+ runId: held.id,
+ providerInstanceId: held.providerInstanceId,
+ occurredAt: releasedAt,
+ payload: { ...held, queueHeld: false },
+ });
+ }
+ if (shouldQueue) {
+ if (pendingMergeBackTransfers.length > 0) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
- cause: `Proposed plan ${command.sourcePlanRef?.planId} belongs to a different project.`,
+ cause: `Thread ${command.threadId} has a pending merge-back transfer; queued merge-back consumption is not implemented yet.`,
});
}
- if (sourcePlan !== null && sourcePlan.status !== "active") {
+ const queueProviderThread =
+ activeProviderThread ??
+ projection.providerThreads.find(
+ (candidate) => candidate.id === queueBehindRun.providerThreadId,
+ );
+ if (queueProviderThread === undefined) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
- cause: `Proposed plan ${sourcePlan.id} is not active.`,
+ cause: `Active run ${queueBehindRun.id} has no provider thread for queued dispatch.`,
});
}
- const completeSourcePlan = (occurredAt: DateTime.Utc) =>
- sourcePlan === null
- ? Effect.void
- : emit(
- events,
- command,
- )({
- type: "plan.updated",
- threadId: sourcePlan.threadId,
- ...(sourcePlan.runId === null ? {} : { runId: sourcePlan.runId }),
- nodeId: sourcePlan.nodeId,
- occurredAt,
- payload: { ...sourcePlan, status: "completed" },
- });
-
- if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") {
- yield* dispatchSteerIntoRun({
- command,
- events,
- effects,
- projection,
- modelSelection:
- delegatedCompletion === undefined
- ? modelSelection
- : (projection.runs.find((run) => run.id === dispatchMode.targetRunId)
- ?.modelSelection ?? modelSelection),
- delegatedCompletion,
- targetRunId: dispatchMode.targetRunId,
- messageId: command.messageId,
- text: dispatchText,
- ...(command.context ? { context: command.context } : {}),
- attachments: command.attachments,
- createdBy: command.createdBy,
- creationSource: command.creationSource,
- ...(command.scheduledTaskId === undefined
- ? {}
- : { scheduledTaskId: command.scheduledTaskId }),
- ...(command.senderThreadId === undefined
- ? {}
- : { senderThreadId: command.senderThreadId }),
- forceRestart: dispatchMode.type === "restart_active",
- });
- return;
- }
-
- const activeProviderThread = projection.providerThreads.find(
- (candidate) => candidate.id === projection.thread.activeProviderThreadId,
- );
- const activeRun = projection.runs.find(isBlockingRun);
- // A message queued during worktree setup can arrive after that setup failed
- // without a worktree. It waits, held, like the messages queued before the
- // failure, instead of starting in the project checkout.
- const latestRun = latestExecutedRun(projection.runs);
- const worktreeMissingRun =
- activeRun === undefined &&
- dispatchMode.type === "queue_after_active" &&
- (latestRun?.status === "failed" || latestRun?.status === "interrupted") &&
- latestRun.workspacePreparation?.type === "worktree" &&
- projection.thread.worktreePath === null
- ? latestRun
- : undefined;
- const queueBehindRun = activeRun ?? worktreeMissingRun;
- const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection);
- const startsOrQueuesRun =
- dispatchMode.type === "defer_start" ||
- dispatchMode.type === "start_immediately" ||
- dispatchMode.type === "queue_after_active";
- const shouldQueue = queueBehindRun !== undefined && startsOrQueuesRun;
- // A message the user sends from a client means they are back, so the
- // queue a stop or a restart held runs again, in its order, rather than
- // waiting for a Resume.
- // Continuations and scheduled tasks the server sends for them are not
- // them coming back. Starting the queue still re-holds it for a failed
- // provider or a usage limit; a queue held after worktree setup failed
- // keeps its hold until a worktree exists, even once later messages have
- // run, since its messages would start in the project checkout.
- const worktreeSetupUnresolved =
- projection.thread.worktreePath === null &&
- projection.runs.some(
- (run) =>
- (run.status === "failed" || run.status === "interrupted") &&
- run.workspacePreparation?.type === "worktree",
- );
- const sentByUserFromClient =
- command.createdBy === "user" &&
- (command.creationSource === "web" || command.creationSource === "mobile") &&
- command.scheduledTaskId === undefined;
- const heldRunsToRelease =
- sentByUserFromClient && startsOrQueuesRun && !worktreeSetupUnresolved
- ? projection.runs.filter((run) => run.status === "queued" && run.queueHeld === true)
- : [];
- const releasedAt = yield* DateTime.now;
- for (const held of heldRunsToRelease) {
- yield* emit(
- events,
- command,
- )({
- type: "run.updated",
- threadId: command.threadId,
- runId: held.id,
- providerInstanceId: held.providerInstanceId,
- occurredAt: releasedAt,
- payload: { ...held, queueHeld: false },
- });
- }
- if (shouldQueue) {
- if (pendingMergeBackTransfers.length > 0) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Thread ${command.threadId} has a pending merge-back transfer; queued merge-back consumption is not implemented yet.`,
- });
- }
- const queueProviderThread =
- activeProviderThread ??
- projection.providerThreads.find(
- (candidate) => candidate.id === queueBehindRun.providerThreadId,
- );
- if (queueProviderThread === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Active run ${queueBehindRun.id} has no provider thread for queued dispatch.`,
- });
- }
- const now = yield* DateTime.now;
- const ordinal = nextRunOrdinal(projection);
- const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
- const targetProviderThread =
- modelSelection.instanceId === queueProviderThread.providerInstanceId
- ? queueProviderThread
- : rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0];
- const queuedAdapter = yield* providerAdapters
- .get(modelSelection.instanceId)
- .pipe(mapDispatchError(command));
- const selectedProviderSession =
- targetProviderThread?.providerSessionId === null ||
- targetProviderThread?.providerSessionId === undefined
- ? undefined
- : projection.providerSessions.find(
- (candidate) => candidate.id === targetProviderThread.providerSessionId,
- );
- const queuedCapabilities =
- selectedProviderSession?.capabilities ??
- (yield* queuedAdapter.getCapabilities().pipe(mapDispatchError(command)));
- yield* enforceCommandPolicy(command)(
- commandPolicy.ensureQueuedMessages({
- commandId: command.commandId,
- threadId: command.threadId,
- providerInstanceId: modelSelection.instanceId,
- capabilities: queuedCapabilities,
- }),
- );
- const queuedProviderThread: OrchestrationV2ProviderThread = targetProviderThread ?? {
- id: idAllocator.derive.providerThread({
- driver: queuedAdapter.driver,
- nativeThreadId: `pending:${runId}`,
- }),
- driver: queuedAdapter.driver,
- providerInstanceId: modelSelection.instanceId,
- providerSessionId: null,
- appThreadId: command.threadId,
- ownerNodeId: null,
- nativeThreadRef: null,
- nativeConversationHeadRef: null,
- status: "not_loaded",
- firstRunOrdinal: null,
- lastRunOrdinal: null,
- handoffIds: [],
- forkedFrom: null,
- createdAt: now,
- updatedAt: now,
- };
- const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
- const rootNodeId = idAllocator.derive.rootNode({ runId });
- const checkpointScope =
- queueBehindRun.status === "preparing" || worktreeMissingRun !== undefined
- ? null
- : yield* runtimePolicy.resolve({ thread: projection.thread, modelSelection }).pipe(
- Effect.flatMap((resolvedRuntimePolicy) =>
- checkpointService.prepareRootRunScope({
- threadId: command.threadId,
- runId,
- rootNodeId,
- providerThreadId: queuedProviderThread.id,
- cwd:
- resolvedRuntimePolicy.cwd ??
- selectedProviderSession?.cwd ??
- projection.thread.worktreePath ??
- process.cwd(),
- createdAt: now,
- }),
- ),
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause,
- }),
- ),
- );
- const run: OrchestrationV2Run = {
- id: runId,
- threadId: command.threadId,
- ordinal,
- providerInstanceId: modelSelection.instanceId,
- modelSelection,
- providerThreadId: queuedProviderThread.id,
- userMessageId: command.messageId,
- rootNodeId,
- activeAttemptId: attemptId,
- status: "queued",
- ...(worktreeMissingRun !== undefined ||
- (heldRunsToRelease.length === 0 &&
- projection.runs.some(
- (candidate) => candidate.status === "queued" && candidate.queueHeld === true,
- ))
- ? { queueHeld: true }
- : {}),
- queuePosition:
- Math.max(
- 0,
- ...projection.runs
- .filter((candidate) => candidate.status === "queued")
- .map((candidate) => candidate.queuePosition ?? candidate.ordinal),
- ) + 1,
- requestedAt: now,
- startedAt: null,
- completedAt: null,
- checkpointId: null,
- contextHandoffId: null,
- ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
- ...(command.restartContinuationOfRunId === undefined
- ? {}
- : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
- ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
- };
- const attempt: OrchestrationV2RunAttempt = {
- id: attemptId,
- runId,
- attemptOrdinal: 1,
- rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- providerThreadId: queuedProviderThread.id,
- providerTurnId: null,
- reason: "initial",
- status: "pending",
- startedAt: null,
- completedAt: null,
- };
- const rootNode: OrchestrationV2ExecutionNode = {
- id: rootNodeId,
- threadId: command.threadId,
- runId,
- parentNodeId: null,
- rootNodeId,
- kind: "root_turn",
- status: "pending",
- countsForRun: true,
- providerThreadId: queuedProviderThread.id,
- providerTurnId: null,
- nativeItemRef: null,
- runtimeRequestId: null,
- checkpointScopeId: checkpointScope?.id ?? null,
- startedAt: null,
- completedAt: null,
- };
- const message: OrchestrationV2ConversationMessage = {
- createdBy: command.createdBy,
- creationSource: command.creationSource,
- ...(command.scheduledTaskId === undefined
- ? {}
- : { scheduledTaskId: command.scheduledTaskId }),
- ...(command.senderThreadId === undefined
- ? {}
- : { senderThreadId: command.senderThreadId }),
- id: command.messageId,
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- role: "user",
- text: dispatchText,
- ...(command.context ? { context: command.context } : {}),
- attachments: command.attachments,
- streaming: false,
- createdAt: now,
- updatedAt: now,
- ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
- ...(command.notification === undefined ? {} : { notification: command.notification }),
- };
- const emitEvent = emit(events, command);
- if (targetProviderThread === undefined) {
- yield* emitEvent({
- type: "provider-thread.updated",
- threadId: command.threadId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: queuedProviderThread,
- });
- }
- yield* emitEvent({
- type: "run.created",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: run,
- });
- yield* completeSourcePlan(now);
- yield* emitEvent({
- type: "run-attempt.created",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: attempt,
- });
- yield* emitEvent({
- type: "node.updated",
+ const now = yield* DateTime.now;
+ const ordinal = nextRunOrdinal(projection);
+ const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
+ const targetProviderThread =
+ modelSelection.instanceId === queueProviderThread.providerInstanceId
+ ? queueProviderThread
+ : rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0];
+ const queuedAdapter = yield* providerAdapters
+ .get(modelSelection.instanceId)
+ .pipe(mapDispatchError(command));
+ const selectedProviderSession =
+ targetProviderThread?.providerSessionId === null ||
+ targetProviderThread?.providerSessionId === undefined
+ ? undefined
+ : projection.providerSessions.find(
+ (candidate) => candidate.id === targetProviderThread.providerSessionId,
+ );
+ const queuedCapabilities =
+ selectedProviderSession?.capabilities ??
+ (yield* queuedAdapter.getCapabilities().pipe(mapDispatchError(command)));
+ yield* enforceCommandPolicy(command)(
+ commandPolicy.ensureQueuedMessages({
+ commandId: command.commandId,
threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: rootNode,
- });
- if (checkpointScope !== null) {
- yield* emitEvent({
- type: "checkpoint-scope.created",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: yield* checkpointService.ensureScope(checkpointScope).pipe(
+ capabilities: queuedCapabilities,
+ }),
+ );
+ const queuedProviderThread: OrchestrationV2ProviderThread = targetProviderThread ?? {
+ id: idAllocator.derive.providerThread({
+ driver: queuedAdapter.driver,
+ nativeThreadId: `pending:${runId}`,
+ }),
+ driver: queuedAdapter.driver,
+ providerInstanceId: modelSelection.instanceId,
+ providerSessionId: null,
+ appThreadId: command.threadId,
+ ownerNodeId: null,
+ nativeThreadRef: null,
+ nativeConversationHeadRef: null,
+ status: "not_loaded",
+ firstRunOrdinal: null,
+ lastRunOrdinal: null,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+ const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
+ const rootNodeId = idAllocator.derive.rootNode({ runId });
+ const checkpointScope =
+ queueBehindRun.status === "preparing" || worktreeMissingRun !== undefined
+ ? null
+ : yield* runtimePolicy.resolve({ thread: projection.thread, modelSelection }).pipe(
+ Effect.flatMap((resolvedRuntimePolicy) =>
+ checkpointService.prepareRootRunScope({
+ threadId: command.threadId,
+ runId,
+ rootNodeId,
+ providerThreadId: queuedProviderThread.id,
+ cwd:
+ resolvedRuntimePolicy.cwd ??
+ selectedProviderSession?.cwd ??
+ projection.thread.worktreePath ??
+ process.cwd(),
+ createdAt: now,
+ }),
+ ),
Effect.mapError(
(cause) =>
new OrchestratorDispatchError({
@@ -5358,589 +5215,306 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause,
}),
),
- ),
- });
- }
+ );
+ const run: OrchestrationV2Run = {
+ id: runId,
+ threadId: command.threadId,
+ ordinal,
+ providerInstanceId: modelSelection.instanceId,
+ modelSelection,
+ providerThreadId: queuedProviderThread.id,
+ userMessageId: command.messageId,
+ rootNodeId,
+ activeAttemptId: attemptId,
+ status: "queued",
+ ...(worktreeMissingRun !== undefined ||
+ (heldRunsToRelease.length === 0 &&
+ projection.runs.some(
+ (candidate) => candidate.status === "queued" && candidate.queueHeld === true,
+ ))
+ ? { queueHeld: true }
+ : {}),
+ queuePosition:
+ Math.max(
+ 0,
+ ...projection.runs
+ .filter((candidate) => candidate.status === "queued")
+ .map((candidate) => candidate.queuePosition ?? candidate.ordinal),
+ ) + 1,
+ requestedAt: now,
+ startedAt: null,
+ completedAt: null,
+ checkpointId: null,
+ contextHandoffId: null,
+ ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
+ ...(command.restartContinuationOfRunId === undefined
+ ? {}
+ : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
+ ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
+ };
+ const attempt: OrchestrationV2RunAttempt = {
+ id: attemptId,
+ runId,
+ attemptOrdinal: 1,
+ rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ providerThreadId: queuedProviderThread.id,
+ providerTurnId: null,
+ reason: "initial",
+ status: "pending",
+ startedAt: null,
+ completedAt: null,
+ };
+ const rootNode: OrchestrationV2ExecutionNode = {
+ id: rootNodeId,
+ threadId: command.threadId,
+ runId,
+ parentNodeId: null,
+ rootNodeId,
+ kind: "root_turn",
+ status: "pending",
+ countsForRun: true,
+ providerThreadId: queuedProviderThread.id,
+ providerTurnId: null,
+ nativeItemRef: null,
+ runtimeRequestId: null,
+ checkpointScopeId: checkpointScope?.id ?? null,
+ startedAt: null,
+ completedAt: null,
+ };
+ const message: OrchestrationV2ConversationMessage = {
+ createdBy: command.createdBy,
+ creationSource: command.creationSource,
+ ...(command.scheduledTaskId === undefined
+ ? {}
+ : { scheduledTaskId: command.scheduledTaskId }),
+ ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ id: command.messageId,
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ role: "user",
+ text: dispatchText,
+ ...(command.context ? { context: command.context } : {}),
+ attachments: command.attachments,
+ streaming: false,
+ createdAt: now,
+ updatedAt: now,
+ ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
+ ...(command.notification === undefined ? {} : { notification: command.notification }),
+ };
+ const emitEvent = emit(events, command);
+ if (targetProviderThread === undefined) {
yield* emitEvent({
- type: "message.updated",
+ type: "provider-thread.updated",
threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: message,
+ payload: queuedProviderThread,
});
- const existingItem = projection.turnItems.find(
- (item) => item.type === "user_message" && item.messageId === command.messageId,
- );
- if (existingItem?.type === "user_message") {
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: {
- ...existingItem,
- runId,
- nodeId: rootNodeId,
- providerThreadId: queuedProviderThread.id,
- providerTurnId: null,
- inputIntent: "queued_turn",
- updatedAt: now,
- },
- });
- }
- return;
}
- const pendingForkTransfer = pendingForkTransferForThread(projection);
- const pendingMergeBackSourceThreadIds = new Set(
- pendingMergeBackTransfers.map((transfer) => transfer.sourceThreadId),
- );
- if (pendingMergeBackSourceThreadIds.size > 1) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Thread ${command.threadId} has pending merge-back transfers from multiple forks.`,
+ yield* emitEvent({
+ type: "run.created",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: run,
+ });
+ yield* completeSourcePlan(now);
+ yield* emitEvent({
+ type: "run-attempt.created",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: attempt,
+ });
+ yield* emitEvent({
+ type: "node.updated",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: rootNode,
+ });
+ if (checkpointScope !== null) {
+ yield* emitEvent({
+ type: "checkpoint-scope.created",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: yield* checkpointService.ensureScope(checkpointScope).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause,
+ }),
+ ),
+ ),
});
}
- const pendingMergeBackTransfer = latestContextTransfer(pendingMergeBackTransfers);
- const supersededMergeBackTransfers = pendingMergeBackTransfers.filter(
- (transfer) => transfer.id !== pendingMergeBackTransfer?.id,
+ yield* emitEvent({
+ type: "message.updated",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: message,
+ });
+ const existingItem = projection.turnItems.find(
+ (item) => item.type === "user_message" && item.messageId === command.messageId,
);
- const now = yield* DateTime.now;
- if (
- !modelSelectionsEqual(projection.thread.modelSelection, modelSelection) ||
- projection.thread.providerInstanceId !== modelSelection.instanceId
- ) {
- yield* emit(
- events,
- command,
- )({
- type:
- projection.thread.providerInstanceId === modelSelection.instanceId
- ? "thread.model-selection-updated"
- : "thread.provider-switched",
+ if (existingItem?.type === "user_message") {
+ yield* emitEvent({
+ type: "turn-item.updated",
threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
payload: {
- ...projection.thread,
- providerInstanceId: modelSelection.instanceId,
- modelSelection,
+ ...existingItem,
+ runId,
+ nodeId: rootNodeId,
+ providerThreadId: queuedProviderThread.id,
+ providerTurnId: null,
+ inputIntent: "queued_turn",
updatedAt: now,
},
});
}
- const ordinal = nextRunOrdinal(projection);
- const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
- const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed");
- const latestHandoffRun = projection.runs.findLast(isHandoffSourceRun);
- const legacyImportItems =
- projection.thread.historyOrigin === "v1_import"
- ? yield* readHandoffItems(command.threadId, [null])
- : [];
- const isProviderSwitch =
- activeProviderThread !== undefined &&
- activeProviderThread.providerInstanceId !== modelSelection.instanceId;
- // Account overlays share native history. Selection commands may already
- // have updated the app thread, so classify against the native thread's owner.
- const canResumeAcrossInstances =
- isProviderSwitch &&
- activeProviderThread.nativeThreadRef !== null &&
- (yield* providerSwitchService
- .plan({
- projection: {
- ...projection,
- thread: {
- ...projection.thread,
- modelSelection: {
- ...projection.thread.modelSelection,
- instanceId: activeProviderThread.providerInstanceId,
- },
+ return;
+ }
+ const pendingForkTransfer = pendingForkTransferForThread(projection);
+ const pendingMergeBackSourceThreadIds = new Set(
+ pendingMergeBackTransfers.map((transfer) => transfer.sourceThreadId),
+ );
+ if (pendingMergeBackSourceThreadIds.size > 1) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Thread ${command.threadId} has pending merge-back transfers from multiple forks.`,
+ });
+ }
+ const pendingMergeBackTransfer = latestContextTransfer(pendingMergeBackTransfers);
+ const supersededMergeBackTransfers = pendingMergeBackTransfers.filter(
+ (transfer) => transfer.id !== pendingMergeBackTransfer?.id,
+ );
+ const now = yield* DateTime.now;
+ if (
+ !modelSelectionsEqual(projection.thread.modelSelection, modelSelection) ||
+ projection.thread.providerInstanceId !== modelSelection.instanceId
+ ) {
+ yield* emit(
+ events,
+ command,
+ )({
+ type:
+ projection.thread.providerInstanceId === modelSelection.instanceId
+ ? "thread.model-selection-updated"
+ : "thread.provider-switched",
+ threadId: command.threadId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: {
+ ...projection.thread,
+ providerInstanceId: modelSelection.instanceId,
+ modelSelection,
+ updatedAt: now,
+ },
+ });
+ }
+ const ordinal = nextRunOrdinal(projection);
+ const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
+ const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed");
+ const latestHandoffRun = projection.runs.findLast(isHandoffSourceRun);
+ const legacyImportItems =
+ projection.thread.historyOrigin === "v1_import"
+ ? yield* readHandoffItems(command.threadId, [null])
+ : [];
+ const isProviderSwitch =
+ activeProviderThread !== undefined &&
+ activeProviderThread.providerInstanceId !== modelSelection.instanceId;
+ // Account overlays share native history. Selection commands may already
+ // have updated the app thread, so classify against the native thread's owner.
+ const canResumeAcrossInstances =
+ isProviderSwitch &&
+ activeProviderThread.nativeThreadRef !== null &&
+ (yield* providerSwitchService
+ .plan({
+ projection: {
+ ...projection,
+ thread: {
+ ...projection.thread,
+ modelSelection: {
+ ...projection.thread.modelSelection,
+ instanceId: activeProviderThread.providerInstanceId,
},
},
- targetModelSelection: modelSelection,
- })
- .pipe(mapDispatchError(command))).transition.type === "restart_and_resume";
+ },
+ targetModelSelection: modelSelection,
+ })
+ .pipe(mapDispatchError(command))).transition.type === "restart_and_resume";
- if (
- pendingForkTransfer === undefined &&
- pendingMergeBackTransfer === undefined &&
- !isProviderSwitch
- ) {
- const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorProviderAdapterError({
- commandId: command.commandId,
- providerInstanceId: modelSelection.instanceId,
- cause,
- }),
- ),
- );
- const providerSessionId =
- activeProviderThread?.providerSessionId ??
- (yield* mapDispatchError(command)(
- providerSessionIdFor({
- adapter,
+ if (
+ pendingForkTransfer === undefined &&
+ pendingMergeBackTransfer === undefined &&
+ !isProviderSwitch
+ ) {
+ const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProviderAdapterError({
+ commandId: command.commandId,
providerInstanceId: modelSelection.instanceId,
- threadId: command.threadId,
+ cause,
}),
- ));
- const providerThreadId =
- activeProviderThread?.id ??
- idAllocator.derive.providerThread({
- driver: adapter.driver,
- nativeThreadId: `pending:${runId}`,
- });
- const legacyImportHandoff = shouldPrepareLegacyImportHandoff({
- historyOrigin: projection.thread.historyOrigin,
- hasCompletedRun: latestCompletedRun !== undefined,
- legacyImportItemCount: legacyImportItems.length,
- })
- ? yield* contextHandoffService
- .prepareLegacyImport({
- threadId: command.threadId,
- targetRunId: runId,
- toProviderThreadId: providerThreadId,
- toProviderInstanceId: modelSelection.instanceId,
- items: legacyImportItems,
- createdAt: now,
- })
- .pipe(mapDispatchError(command))
- : null;
- const providerThread: OrchestrationV2ProviderThread =
- activeProviderThread === undefined
- ? {
- id: providerThreadId,
- driver: adapter.driver,
- providerInstanceId: modelSelection.instanceId,
- providerSessionId,
- appThreadId: command.threadId,
- ownerNodeId: null,
- nativeThreadRef: null,
- nativeConversationHeadRef: null,
- status: "not_loaded",
- firstRunOrdinal: ordinal,
- lastRunOrdinal: ordinal,
- handoffIds: legacyImportHandoff === null ? [] : [legacyImportHandoff.id],
- forkedFrom: null,
- createdAt: now,
- updatedAt: now,
- }
- : {
- ...activeProviderThread,
- providerSessionId,
- lastRunOrdinal: ordinal,
- handoffIds: appendContextHandoffId(
- activeProviderThread.handoffIds,
- legacyImportHandoff?.id ?? null,
- ),
- updatedAt: now,
- };
- const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
- const rootNodeId = idAllocator.derive.rootNode({ runId });
- const checkpointScope =
- dispatchMode.type === "defer_start"
- ? null
- : yield* runtimePolicy
- .resolve({
- thread: projection.thread,
- modelSelection,
- })
- .pipe(
- mapDispatchError(command),
- Effect.flatMap((resolvedRuntimePolicy) =>
- checkpointService.prepareRootRunScope({
- threadId: command.threadId,
- runId,
- rootNodeId,
- providerThreadId,
- cwd:
- resolvedRuntimePolicy.cwd ??
- projection.thread.worktreePath ??
- process.cwd(),
- createdAt: now,
- }),
- ),
- mapDispatchError(command),
- );
- const run: OrchestrationV2Run = {
- id: runId,
- threadId: command.threadId,
- ordinal,
- providerInstanceId: modelSelection.instanceId,
- modelSelection,
- providerThreadId,
- userMessageId: command.messageId,
- rootNodeId,
- activeAttemptId: attemptId,
- status: dispatchMode.type === "defer_start" ? "preparing" : "starting",
- queuePosition: null,
- requestedAt: now,
- startedAt: null,
- completedAt: null,
- checkpointId: null,
- contextHandoffId: legacyImportHandoff?.id ?? null,
- ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
- ...(command.restartContinuationOfRunId === undefined
- ? {}
- : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
- ...(dispatchMode.type === "defer_start" && dispatchMode.workspaceStrategy !== undefined
- ? { workspacePreparation: dispatchMode.workspaceStrategy }
- : {}),
- ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
- ...wakeWorkStartedAt(projection.runs, command),
- };
- const attempt: OrchestrationV2RunAttempt = {
- id: attemptId,
- runId,
- attemptOrdinal: 1,
- rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- providerThreadId,
- providerTurnId: null,
- reason: "initial",
- status: "pending",
- startedAt: null,
- completedAt: null,
- };
- const rootNode: OrchestrationV2ExecutionNode = {
- id: rootNodeId,
- threadId: command.threadId,
- runId,
- parentNodeId: null,
- rootNodeId,
- kind: "root_turn",
- status: "pending",
- countsForRun: true,
- providerThreadId,
- providerTurnId: null,
- nativeItemRef: null,
- runtimeRequestId: null,
- checkpointScopeId: checkpointScope?.id ?? null,
- startedAt: null,
- completedAt: null,
- };
- const message: OrchestrationV2ConversationMessage = {
- createdBy: command.createdBy,
- creationSource: command.creationSource,
- ...(command.scheduledTaskId === undefined
- ? {}
- : { scheduledTaskId: command.scheduledTaskId }),
- ...(command.senderThreadId === undefined
- ? {}
- : { senderThreadId: command.senderThreadId }),
- id: command.messageId,
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- role: "user",
- text: dispatchText,
- ...(command.context ? { context: command.context } : {}),
- attachments: command.attachments,
- streaming: false,
- createdAt: now,
- updatedAt: now,
- ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
- ...(command.notification === undefined ? {} : { notification: command.notification }),
- };
- const turnItem: OrchestrationV2TurnItem = {
- createdBy: command.createdBy,
- creationSource: command.creationSource,
- ...(command.scheduledTaskId === undefined
- ? {}
- : { scheduledTaskId: command.scheduledTaskId }),
- ...(command.senderThreadId === undefined
- ? {}
- : { senderThreadId: command.senderThreadId }),
- id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerThreadId,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: yield* nextTurnItemOrdinal(projection),
- status: "completed",
- title: null,
- startedAt: now,
- completedAt: now,
- updatedAt: now,
- type: "user_message",
- messageId: command.messageId,
- inputIntent: "turn_start",
- text: dispatchText,
- ...(command.context ? { context: command.context } : {}),
- attachments: command.attachments,
- };
- const preparationTurnItem: OrchestrationV2TurnItem | null =
- dispatchMode.type === "defer_start"
- ? {
- id: idAllocator.derive.turnItemFromProviderItem({
- driver: adapter.driver,
- nativeItemId: `workspace-preparation:${runId}`,
- }),
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerThreadId,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: turnItem.ordinal + 1,
- status: "running",
- title: WORKSPACE_PREPARATION_INPUT,
- startedAt: now,
- completedAt: null,
- updatedAt: now,
- type: "command_execution",
- input: WORKSPACE_PREPARATION_INPUT,
- }
- : null;
- const emitEvent = emit(events, command);
- yield* emitEvent({
- type: "provider-thread.updated",
- threadId: command.threadId,
+ ),
+ );
+ const providerSessionId =
+ activeProviderThread?.providerSessionId ??
+ (yield* mapDispatchError(command)(
+ providerSessionIdFor({
+ adapter,
+ providerInstanceId: modelSelection.instanceId,
+ threadId: command.threadId,
+ }),
+ ));
+ const providerThreadId =
+ activeProviderThread?.id ??
+ idAllocator.derive.providerThread({
driver: adapter.driver,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: providerThread,
+ nativeThreadId: `pending:${runId}`,
});
- if (legacyImportHandoff !== null) {
- yield* emitEvent({
- type: "context-handoff.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: legacyImportHandoff,
- });
- }
- yield* emitEvent({
- type: "run.created",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: run,
- });
- yield* completeSourcePlan(now);
- yield* emitEvent({
- type: "run-attempt.created",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: attempt,
- });
- yield* emitEvent({
- type: "node.updated",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: rootNode,
- });
- if (checkpointScope !== null) {
- yield* emitEvent({
- type: "checkpoint-scope.created",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: checkpointScope,
- });
- }
- yield* emitEvent({
- type: "message.updated",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: message,
- });
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: notificationTurnItem(turnItem, message, projection.subagents),
- });
- if (preparationTurnItem !== null) {
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: preparationTurnItem,
- });
- }
- const pendingEffect = {
- id: `effect:${command.commandId}:provider-turn.start:${runId}`,
- commandId: command.commandId,
- threadId: command.threadId,
- request: { type: "provider-turn.start", runId },
- } satisfies PendingOrchestrationEffectV2;
- if (dispatchMode.type !== "defer_start") {
- yield* Ref.update(effects, (existing) => [...existing, pendingEffect]);
- }
- return;
- }
- const sourceProjection =
- pendingForkTransfer === undefined
- ? null
- : yield* projectionStore
- .getThreadRecords(pendingForkTransfer.sourceThreadId, [
- "runs",
- "attempts",
- "providerThreads",
- "providerTurns",
- ])
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorProjectionError({
- threadId: pendingForkTransfer.sourceThreadId,
- cause,
- }),
- ),
- );
- const sourceRun =
- pendingForkTransfer?.sourcePoint.runId === undefined || sourceProjection === null
- ? null
- : (sourceProjection.runs.find(
- (candidate) => candidate.id === pendingForkTransfer.sourcePoint.runId,
- ) ?? null);
- const sourceProviderThread =
- sourceProjection === null || sourceRun === null
- ? undefined
- : providerThreadForRun(sourceProjection, sourceRun);
- const sourceProviderTurnId =
- sourceProjection === null || sourceRun === null || sourceRun.activeAttemptId === null
- ? undefined
- : (latestProviderTurnForAttempt(sourceProjection.providerTurns, sourceRun.activeAttemptId)
- ?.id ??
- sourceProjection.attempts.find(
- (candidate) => candidate.id === sourceRun.activeAttemptId,
- )?.providerTurnId ??
- undefined);
- if (pendingForkTransfer !== undefined) {
- if (sourceRun === null || sourceProviderThread === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Pending fork transfer ${pendingForkTransfer.id} has no resolvable source provider thread.`,
- });
- }
- if (pendingForkTransfer.sourceProviderInstanceId === null) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Pending fork transfer ${pendingForkTransfer.id} has no source provider.`,
- });
- }
- }
-
- const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorProviderAdapterError({
- commandId: command.commandId,
- providerInstanceId: modelSelection.instanceId,
- cause,
- }),
- ),
- );
- const targetProviderThread =
- isProviderSwitch && !canResumeAcrossInstances
- ? rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0]
- : activeProviderThread;
- const providerSessionId =
- (canResumeAcrossInstances ? undefined : targetProviderThread?.providerSessionId) ??
- (yield* mapDispatchError(command)(
- providerSessionIdFor({
- adapter,
- providerInstanceId: modelSelection.instanceId,
- threadId: command.threadId,
- }),
- ));
- const existingProviderSession = projection.providerSessions.find(
- (candidate) => candidate.id === providerSessionId,
- );
- const resolvedRuntimePolicy = yield* runtimePolicy
- .resolve({ thread: projection.thread, modelSelection })
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause,
- }),
- ),
- );
-
- const capabilities = yield* adapter.getCapabilities().pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorProviderAdapterError({
- commandId: command.commandId,
- providerInstanceId: modelSelection.instanceId,
- cause,
- }),
- ),
- );
- const forkExecution =
- pendingForkTransfer === undefined || sourceRun === null
- ? null
- : yield* enforceCommandPolicy(command)(
- commandPolicy.decideForkExecution({
- commandId: command.commandId,
- threadId: command.threadId,
- providerInstanceId: modelSelection.instanceId,
- capabilities,
- sameProvider:
- pendingForkTransfer.sourceProviderInstanceId === modelSelection.instanceId,
- hasStrongNativeSource: sourceProviderThread?.nativeThreadRef?.strength === "strong",
- sourceRunStatus: sourceRun.status,
- fromSpecificTurn: sourceRun !== null,
- }),
- );
- const canResolveForkNatively = forkExecution === "native_fork";
- const requiresPortableFork = forkExecution === "portable_context";
-
- if (canResolveForkNatively) {
- yield* enforceCommandPolicy(command)(
- commandPolicy.ensureNativeFork({
- commandId: command.commandId,
- threadId: command.threadId,
- providerInstanceId: modelSelection.instanceId,
- capabilities,
- fromSpecificTurn: sourceRun !== null,
- }),
- );
- }
-
- const ensuredProviderThread: OrchestrationV2ProviderThread =
- targetProviderThread === undefined
+ const legacyImportHandoff = shouldPrepareLegacyImportHandoff({
+ historyOrigin: projection.thread.historyOrigin,
+ hasCompletedRun: latestCompletedRun !== undefined,
+ legacyImportItemCount: legacyImportItems.length,
+ })
+ ? yield* contextHandoffService
+ .prepareLegacyImport({
+ threadId: command.threadId,
+ targetRunId: runId,
+ toProviderThreadId: providerThreadId,
+ toProviderInstanceId: modelSelection.instanceId,
+ items: legacyImportItems,
+ createdAt: now,
+ })
+ .pipe(mapDispatchError(command))
+ : null;
+ const providerThread: OrchestrationV2ProviderThread =
+ activeProviderThread === undefined
? {
- id: idAllocator.derive.providerThread({
- driver: adapter.driver,
- nativeThreadId: `pending:${runId}`,
- }),
+ id: providerThreadId,
driver: adapter.driver,
providerInstanceId: modelSelection.instanceId,
providerSessionId,
@@ -5951,340 +5525,70 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
status: "not_loaded",
firstRunOrdinal: ordinal,
lastRunOrdinal: ordinal,
- handoffIds: [],
- forkedFrom:
- canResolveForkNatively && sourceProviderThread !== undefined
- ? {
- providerThreadId: sourceProviderThread.id,
- ...(sourceProviderTurnId === undefined
- ? {}
- : { providerTurnId: sourceProviderTurnId }),
- }
- : null,
+ handoffIds: legacyImportHandoff === null ? [] : [legacyImportHandoff.id],
+ forkedFrom: null,
createdAt: now,
updatedAt: now,
}
: {
- ...targetProviderThread,
- providerInstanceId: modelSelection.instanceId,
+ ...activeProviderThread,
providerSessionId,
+ lastRunOrdinal: ordinal,
+ handoffIds: appendContextHandoffId(
+ activeProviderThread.handoffIds,
+ legacyImportHandoff?.id ?? null,
+ ),
updatedAt: now,
};
- const portableForkItems =
- !requiresPortableFork || sourceProjection === null || sourceRun === null
- ? []
- : yield* readHandoffItems(sourceProjection.thread.id, [
- ...sourceProjection.runs
- .filter((run) => run.ordinal <= sourceRun.ordinal)
- .map((run) => run.id),
- ...(sourceProjection.thread.historyOrigin === "v1_import" ? [null] : []),
- ]);
- const portableForkHandoff =
- !requiresPortableFork ||
- pendingForkTransfer === undefined ||
- sourceProjection === null ||
- sourceRun === null
- ? null
- : yield* contextHandoffService
- .prepareProviderHandoff({
- threadId: command.threadId,
- targetRunId: runId,
- transferId: pendingForkTransfer.id,
- fromProviderThreadIds:
- sourceProviderThread === undefined ? [] : [sourceProviderThread.id],
- toProviderThreadId: ensuredProviderThread.id,
- fromProviderInstanceId: sourceRun.providerInstanceId,
- toProviderInstanceId: modelSelection.instanceId,
- coveredRunOrdinals: visibleDeltaRunOrdinals(sourceProjection, portableForkItems),
- strategy: "full_thread_summary",
- items: portableForkItems,
- runs: sourceProjection.runs,
- createdAt: now,
- })
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause,
- }),
- ),
- );
- const requiresFullProviderSwitchContext =
- isProviderSwitch && pendingMergeBackTransfer !== undefined;
- const targetLastCompletedRun =
- targetProviderThread === undefined
- ? undefined
- : lastDeliveredRunForProviderThread(projection, targetProviderThread.id);
- const providerSwitchCoveredRuns =
- !isProviderSwitch || canResumeAcrossInstances || latestHandoffRun === undefined
- ? []
- : projection.runs.filter(
- (run) =>
- isHandoffSourceRun(run) &&
- run.ordinal >
- (requiresFullProviderSwitchContext
- ? 0
- : (targetLastCompletedRun?.ordinal ?? 0)) &&
- run.ordinal <= latestHandoffRun.ordinal,
- );
- const providerSwitchItems =
- providerSwitchCoveredRuns.length === 0
- ? []
- : [
- ...(latestCompletedRun !== undefined &&
- (targetProviderThread === undefined || requiresFullProviderSwitchContext)
- ? legacyImportItems
- : []),
- ...(yield* readHandoffItems(
- command.threadId,
- providerSwitchCoveredRuns.map((run) => run.id),
- )),
- ];
- const providerSwitchTransferId =
- providerSwitchCoveredRuns.length === 0 || latestHandoffRun === undefined
- ? null
- : yield* mapDispatchError(command)(
- idAllocator.allocate.contextTransfer({
- sourceThreadId: command.threadId,
- targetThreadId: command.threadId,
- type: "provider_handoff",
- }),
- );
- if (providerSwitchTransferId !== null) {
- yield* enforceCommandPolicy(command)(
- commandPolicy.ensureContextHandoff({
- commandId: command.commandId,
- threadId: command.threadId,
- providerInstanceId: modelSelection.instanceId,
- capabilities,
- strategy:
- targetProviderThread === undefined || requiresFullProviderSwitchContext
- ? "full_thread_summary"
- : "delta_context",
- }),
- );
- }
- const providerSwitchHandoff =
- providerSwitchTransferId === null || latestHandoffRun === undefined
- ? null
- : yield* contextHandoffService
- .prepareProviderHandoff({
- threadId: command.threadId,
- targetRunId: runId,
- transferId: providerSwitchTransferId,
- fromProviderThreadIds: Array.from(
- new Set(
- providerSwitchCoveredRuns.flatMap((run) =>
- run.providerThreadId === null ? [] : [run.providerThreadId],
- ),
- ),
- ),
- toProviderThreadId: ensuredProviderThread.id,
- fromProviderInstanceId: latestHandoffRun.providerInstanceId,
- toProviderInstanceId: modelSelection.instanceId,
- coveredRunOrdinals: {
- from: providerSwitchCoveredRuns[0]!.ordinal,
- to: providerSwitchCoveredRuns.at(-1)!.ordinal,
- },
- strategy:
- targetProviderThread === undefined || requiresFullProviderSwitchContext
- ? "full_thread_summary"
- : "delta_since_target_last_seen",
- items: providerSwitchItems,
- runs: projection.runs,
- createdAt: now,
- })
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause,
- }),
- ),
- );
- const legacyImportRecoveryHandoff =
- isProviderSwitch &&
- !canResumeAcrossInstances &&
- latestCompletedRun === undefined &&
- legacyImportItems.length > 0
- ? yield* contextHandoffService
- .prepareLegacyImport({
- threadId: command.threadId,
- targetRunId: runId,
- toProviderThreadId: ensuredProviderThread.id,
- toProviderInstanceId: modelSelection.instanceId,
- items: legacyImportItems,
- createdAt: now,
- })
- .pipe(mapDispatchError(command))
- : null;
- const providerThread: OrchestrationV2ProviderThread = {
- ...ensuredProviderThread,
- status: "active",
- firstRunOrdinal: ensuredProviderThread.firstRunOrdinal ?? ordinal,
- lastRunOrdinal: ordinal,
- handoffIds: [
- ...ensuredProviderThread.handoffIds,
- ...[portableForkHandoff, providerSwitchHandoff, legacyImportRecoveryHandoff].flatMap(
- (handoff) => (handoff === null ? [] : [handoff.id]),
- ),
- ],
- updatedAt: now,
- };
-
const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
const rootNodeId = idAllocator.derive.rootNode({ runId });
- const emitEvent = emit(events, command);
- const mergeBackSourceProjection =
- pendingMergeBackTransfer === undefined
+ const checkpointScope =
+ dispatchMode.type === "defer_start"
? null
- : yield* projectionStore
- .getThreadRecords(pendingMergeBackTransfer.sourceThreadId, [
- "runs",
- "attempts",
- "providerThreads",
- "providerTurns",
- ])
+ : yield* runtimePolicy
+ .resolve({
+ thread: projection.thread,
+ modelSelection,
+ })
.pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorProjectionError({
- threadId: pendingMergeBackTransfer.sourceThreadId,
- cause,
- }),
+ mapDispatchError(command),
+ Effect.flatMap((resolvedRuntimePolicy) =>
+ checkpointService.prepareRootRunScope({
+ threadId: command.threadId,
+ runId,
+ rootNodeId,
+ providerThreadId,
+ cwd:
+ resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(),
+ createdAt: now,
+ }),
),
+ mapDispatchError(command),
);
- const mergeBackSourceRun =
- pendingMergeBackTransfer?.sourcePoint.runId === undefined ||
- mergeBackSourceProjection === null
- ? null
- : (mergeBackSourceProjection.runs.find(
- (candidate) => candidate.id === pendingMergeBackTransfer.sourcePoint.runId,
- ) ?? null);
- if (pendingMergeBackTransfer !== undefined && mergeBackSourceRun === null) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source run.`,
- });
- }
- const mergeBackSourceProviderThread =
- mergeBackSourceProjection === null || mergeBackSourceRun === null
- ? undefined
- : providerThreadForRun(mergeBackSourceProjection, mergeBackSourceRun);
- if (pendingMergeBackTransfer !== undefined && mergeBackSourceProviderThread === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source provider thread.`,
- });
- }
- if (pendingMergeBackTransfer !== undefined) {
- yield* enforceCommandPolicy(command)(
- commandPolicy.ensureContextHandoff({
- commandId: command.commandId,
- threadId: command.threadId,
- providerInstanceId: modelSelection.instanceId,
- capabilities,
- strategy: "fork_delta_context",
- }),
- );
- }
- const mergeBackDeltaItems =
- mergeBackSourceProjection === null || mergeBackSourceRun === null
- ? []
- : yield* readHandoffItems(
- mergeBackSourceProjection.thread.id,
- mergeBackSourceProjection.runs
- .filter((run) => run.ordinal <= mergeBackSourceRun.ordinal)
- .map((run) => run.id),
- );
- const mergeBackHandoff =
- pendingMergeBackTransfer === undefined ||
- mergeBackSourceProjection === null ||
- mergeBackSourceRun === null ||
- mergeBackSourceProviderThread === undefined
- ? null
- : yield* contextHandoffService
- .prepareForkDelta({
- sourceThreadId: pendingMergeBackTransfer.sourceThreadId,
- targetThreadId: command.threadId,
- targetRunId: runId,
- transferId: pendingMergeBackTransfer.id,
- fromProviderThreadIds: [mergeBackSourceProviderThread.id],
- toProviderThreadId: providerThread.id,
- fromProviderInstanceId: mergeBackSourceRun.providerInstanceId,
- toProviderInstanceId: modelSelection.instanceId,
- coveredRunOrdinals: visibleDeltaRunOrdinals(
- mergeBackSourceProjection,
- mergeBackDeltaItems,
- ),
- deltaItems: mergeBackDeltaItems,
- createdAt: now,
- })
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause,
- }),
- ),
- );
- const checkpointScope = yield* checkpointService
- .prepareRootRunScope({
- threadId: command.threadId,
- runId,
- rootNodeId,
- providerThreadId: providerThread.id,
- cwd:
- resolvedRuntimePolicy.cwd ??
- existingProviderSession?.cwd ??
- projection.thread.worktreePath ??
- process.cwd(),
- createdAt: now,
- })
- .pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause,
- }),
- ),
- );
const run: OrchestrationV2Run = {
id: runId,
threadId: command.threadId,
ordinal,
providerInstanceId: modelSelection.instanceId,
modelSelection,
- providerThreadId: providerThread.id,
+ providerThreadId,
userMessageId: command.messageId,
rootNodeId,
activeAttemptId: attemptId,
- status: "starting",
+ status: dispatchMode.type === "defer_start" ? "preparing" : "starting",
queuePosition: null,
requestedAt: now,
startedAt: null,
completedAt: null,
checkpointId: null,
- contextHandoffId:
- portableForkHandoff?.id ??
- providerSwitchHandoff?.id ??
- mergeBackHandoff?.id ??
- legacyImportRecoveryHandoff?.id ??
- null,
+ contextHandoffId: legacyImportHandoff?.id ?? null,
...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
...(command.restartContinuationOfRunId === undefined
? {}
: { restartContinuationOfRunId: command.restartContinuationOfRunId }),
+ ...(dispatchMode.type === "defer_start" && dispatchMode.workspaceStrategy !== undefined
+ ? { workspacePreparation: dispatchMode.workspaceStrategy }
+ : {}),
...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
...wakeWorkStartedAt(projection.runs, command),
};
@@ -6294,7 +5598,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
attemptOrdinal: 1,
rootNodeId,
providerInstanceId: modelSelection.instanceId,
- providerThreadId: providerThread.id,
+ providerThreadId,
providerTurnId: null,
reason: "initial",
status: "pending",
@@ -6310,11 +5614,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
kind: "root_turn",
status: "pending",
countsForRun: true,
- providerThreadId: providerThread.id,
+ providerThreadId,
providerTurnId: null,
nativeItemRef: null,
runtimeRequestId: null,
- checkpointScopeId: checkpointScope.id,
+ checkpointScopeId: checkpointScope?.id ?? null,
startedAt: null,
completedAt: null,
};
@@ -6328,416 +5632,1103 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
id: command.messageId,
threadId: command.threadId,
runId,
- nodeId: rootNodeId,
- role: "user",
- text: dispatchText,
- ...(command.context ? { context: command.context } : {}),
- attachments: command.attachments,
- streaming: false,
- createdAt: now,
- updatedAt: now,
- ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
- ...(command.notification === undefined ? {} : { notification: command.notification }),
- };
- const turnItem: OrchestrationV2TurnItem = {
- createdBy: command.createdBy,
- creationSource: command.creationSource,
- ...(command.scheduledTaskId === undefined
- ? {}
- : { scheduledTaskId: command.scheduledTaskId }),
- ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
- id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
+ nodeId: rootNodeId,
+ role: "user",
+ text: dispatchText,
+ ...(command.context ? { context: command.context } : {}),
+ attachments: command.attachments,
+ streaming: false,
+ createdAt: now,
+ updatedAt: now,
+ ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
+ ...(command.notification === undefined ? {} : { notification: command.notification }),
+ };
+ const turnItem: OrchestrationV2TurnItem = {
+ createdBy: command.createdBy,
+ creationSource: command.creationSource,
+ ...(command.scheduledTaskId === undefined
+ ? {}
+ : { scheduledTaskId: command.scheduledTaskId }),
+ ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerThreadId,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: yield* nextTurnItemOrdinal(projection),
+ status: "completed",
+ title: null,
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "user_message",
+ messageId: command.messageId,
+ inputIntent: "turn_start",
+ text: dispatchText,
+ ...(command.context ? { context: command.context } : {}),
+ attachments: command.attachments,
+ };
+ const preparationTurnItem: OrchestrationV2TurnItem | null =
+ dispatchMode.type === "defer_start"
+ ? {
+ id: idAllocator.derive.turnItemFromProviderItem({
+ driver: adapter.driver,
+ nativeItemId: `workspace-preparation:${runId}`,
+ }),
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerThreadId,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: turnItem.ordinal + 1,
+ status: "running",
+ title: WORKSPACE_PREPARATION_INPUT,
+ startedAt: now,
+ completedAt: null,
+ updatedAt: now,
+ type: "command_execution",
+ input: WORKSPACE_PREPARATION_INPUT,
+ }
+ : null;
+ const emitEvent = emit(events, command);
+ yield* emitEvent({
+ type: "provider-thread.updated",
+ threadId: command.threadId,
+ driver: adapter.driver,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: providerThread,
+ });
+ if (legacyImportHandoff !== null) {
+ yield* emitEvent({
+ type: "context-handoff.updated",
+ threadId: command.threadId,
+ runId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: legacyImportHandoff,
+ });
+ }
+ yield* emitEvent({
+ type: "run.created",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: run,
+ });
+ yield* completeSourcePlan(now);
+ yield* emitEvent({
+ type: "run-attempt.created",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: attempt,
+ });
+ yield* emitEvent({
+ type: "node.updated",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: rootNode,
+ });
+ if (checkpointScope !== null) {
+ yield* emitEvent({
+ type: "checkpoint-scope.created",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: checkpointScope,
+ });
+ }
+ yield* emitEvent({
+ type: "message.updated",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: message,
+ });
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: notificationTurnItem(turnItem, message, projection.subagents),
+ });
+ if (preparationTurnItem !== null) {
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: preparationTurnItem,
+ });
+ }
+ const pendingEffect = {
+ id: `effect:${command.commandId}:provider-turn.start:${runId}`,
+ commandId: command.commandId,
+ threadId: command.threadId,
+ request: { type: "provider-turn.start", runId },
+ } satisfies PendingOrchestrationEffectV2;
+ if (dispatchMode.type !== "defer_start") {
+ yield* Ref.update(effects, (existing) => [...existing, pendingEffect]);
+ }
+ return;
+ }
+ const sourceProjection =
+ pendingForkTransfer === undefined
+ ? null
+ : yield* projectionStore
+ .getThreadRecords(pendingForkTransfer.sourceThreadId, [
+ "runs",
+ "attempts",
+ "providerThreads",
+ "providerTurns",
+ ])
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProjectionError({
+ threadId: pendingForkTransfer.sourceThreadId,
+ cause,
+ }),
+ ),
+ );
+ const sourceRun =
+ pendingForkTransfer?.sourcePoint.runId === undefined || sourceProjection === null
+ ? null
+ : (sourceProjection.runs.find(
+ (candidate) => candidate.id === pendingForkTransfer.sourcePoint.runId,
+ ) ?? null);
+ const sourceProviderThread =
+ sourceProjection === null || sourceRun === null
+ ? undefined
+ : providerThreadForRun(sourceProjection, sourceRun);
+ const sourceProviderTurnId =
+ sourceProjection === null || sourceRun === null || sourceRun.activeAttemptId === null
+ ? undefined
+ : (latestProviderTurnForAttempt(sourceProjection.providerTurns, sourceRun.activeAttemptId)
+ ?.id ??
+ sourceProjection.attempts.find((candidate) => candidate.id === sourceRun.activeAttemptId)
+ ?.providerTurnId ??
+ undefined);
+ if (pendingForkTransfer !== undefined) {
+ if (sourceRun === null || sourceProviderThread === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Pending fork transfer ${pendingForkTransfer.id} has no resolvable source provider thread.`,
+ });
+ }
+ if (pendingForkTransfer.sourceProviderInstanceId === null) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Pending fork transfer ${pendingForkTransfer.id} has no source provider.`,
+ });
+ }
+ }
+
+ const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProviderAdapterError({
+ commandId: command.commandId,
+ providerInstanceId: modelSelection.instanceId,
+ cause,
+ }),
+ ),
+ );
+ const targetProviderThread =
+ isProviderSwitch && !canResumeAcrossInstances
+ ? rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0]
+ : activeProviderThread;
+ const providerSessionId =
+ (canResumeAcrossInstances ? undefined : targetProviderThread?.providerSessionId) ??
+ (yield* mapDispatchError(command)(
+ providerSessionIdFor({
+ adapter,
+ providerInstanceId: modelSelection.instanceId,
+ threadId: command.threadId,
+ }),
+ ));
+ const existingProviderSession = projection.providerSessions.find(
+ (candidate) => candidate.id === providerSessionId,
+ );
+ const resolvedRuntimePolicy = yield* runtimePolicy
+ .resolve({ thread: projection.thread, modelSelection })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause,
+ }),
+ ),
+ );
+
+ const capabilities = yield* adapter.getCapabilities().pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProviderAdapterError({
+ commandId: command.commandId,
+ providerInstanceId: modelSelection.instanceId,
+ cause,
+ }),
+ ),
+ );
+ const forkExecution =
+ pendingForkTransfer === undefined || sourceRun === null
+ ? null
+ : yield* enforceCommandPolicy(command)(
+ commandPolicy.decideForkExecution({
+ commandId: command.commandId,
+ threadId: command.threadId,
+ providerInstanceId: modelSelection.instanceId,
+ capabilities,
+ sameProvider:
+ pendingForkTransfer.sourceProviderInstanceId === modelSelection.instanceId,
+ hasStrongNativeSource: sourceProviderThread?.nativeThreadRef?.strength === "strong",
+ sourceRunStatus: sourceRun.status,
+ fromSpecificTurn: sourceRun !== null,
+ }),
+ );
+ const canResolveForkNatively = forkExecution === "native_fork";
+ const requiresPortableFork = forkExecution === "portable_context";
+
+ if (canResolveForkNatively) {
+ yield* enforceCommandPolicy(command)(
+ commandPolicy.ensureNativeFork({
+ commandId: command.commandId,
+ threadId: command.threadId,
+ providerInstanceId: modelSelection.instanceId,
+ capabilities,
+ fromSpecificTurn: sourceRun !== null,
+ }),
+ );
+ }
+
+ const ensuredProviderThread: OrchestrationV2ProviderThread =
+ targetProviderThread === undefined
+ ? {
+ id: idAllocator.derive.providerThread({
+ driver: adapter.driver,
+ nativeThreadId: `pending:${runId}`,
+ }),
+ driver: adapter.driver,
+ providerInstanceId: modelSelection.instanceId,
+ providerSessionId,
+ appThreadId: command.threadId,
+ ownerNodeId: null,
+ nativeThreadRef: null,
+ nativeConversationHeadRef: null,
+ status: "not_loaded",
+ firstRunOrdinal: ordinal,
+ lastRunOrdinal: ordinal,
+ handoffIds: [],
+ forkedFrom:
+ canResolveForkNatively && sourceProviderThread !== undefined
+ ? {
+ providerThreadId: sourceProviderThread.id,
+ ...(sourceProviderTurnId === undefined
+ ? {}
+ : { providerTurnId: sourceProviderTurnId }),
+ }
+ : null,
+ createdAt: now,
+ updatedAt: now,
+ }
+ : {
+ ...targetProviderThread,
+ providerInstanceId: modelSelection.instanceId,
+ providerSessionId,
+ updatedAt: now,
+ };
+ const portableForkItems =
+ !requiresPortableFork || sourceProjection === null || sourceRun === null
+ ? []
+ : yield* readHandoffItems(sourceProjection.thread.id, [
+ ...sourceProjection.runs
+ .filter((run) => run.ordinal <= sourceRun.ordinal)
+ .map((run) => run.id),
+ ...(sourceProjection.thread.historyOrigin === "v1_import" ? [null] : []),
+ ]);
+ const portableForkHandoff =
+ !requiresPortableFork ||
+ pendingForkTransfer === undefined ||
+ sourceProjection === null ||
+ sourceRun === null
+ ? null
+ : yield* contextHandoffService
+ .prepareProviderHandoff({
+ threadId: command.threadId,
+ targetRunId: runId,
+ transferId: pendingForkTransfer.id,
+ fromProviderThreadIds:
+ sourceProviderThread === undefined ? [] : [sourceProviderThread.id],
+ toProviderThreadId: ensuredProviderThread.id,
+ fromProviderInstanceId: sourceRun.providerInstanceId,
+ toProviderInstanceId: modelSelection.instanceId,
+ coveredRunOrdinals: visibleDeltaRunOrdinals(sourceProjection, portableForkItems),
+ strategy: "full_thread_summary",
+ items: portableForkItems,
+ runs: sourceProjection.runs,
+ createdAt: now,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause,
+ }),
+ ),
+ );
+ const requiresFullProviderSwitchContext =
+ isProviderSwitch && pendingMergeBackTransfer !== undefined;
+ const targetLastCompletedRun =
+ targetProviderThread === undefined
+ ? undefined
+ : lastDeliveredRunForProviderThread(projection, targetProviderThread.id);
+ const providerSwitchCoveredRuns =
+ !isProviderSwitch || canResumeAcrossInstances || latestHandoffRun === undefined
+ ? []
+ : projection.runs.filter(
+ (run) =>
+ isHandoffSourceRun(run) &&
+ run.ordinal >
+ (requiresFullProviderSwitchContext ? 0 : (targetLastCompletedRun?.ordinal ?? 0)) &&
+ run.ordinal <= latestHandoffRun.ordinal,
+ );
+ const providerSwitchItems =
+ providerSwitchCoveredRuns.length === 0
+ ? []
+ : [
+ ...(latestCompletedRun !== undefined &&
+ (targetProviderThread === undefined || requiresFullProviderSwitchContext)
+ ? legacyImportItems
+ : []),
+ ...(yield* readHandoffItems(
+ command.threadId,
+ providerSwitchCoveredRuns.map((run) => run.id),
+ )),
+ ];
+ const providerSwitchTransferId =
+ providerSwitchCoveredRuns.length === 0 || latestHandoffRun === undefined
+ ? null
+ : yield* mapDispatchError(command)(
+ idAllocator.allocate.contextTransfer({
+ sourceThreadId: command.threadId,
+ targetThreadId: command.threadId,
+ type: "provider_handoff",
+ }),
+ );
+ if (providerSwitchTransferId !== null) {
+ yield* enforceCommandPolicy(command)(
+ commandPolicy.ensureContextHandoff({
+ commandId: command.commandId,
+ threadId: command.threadId,
+ providerInstanceId: modelSelection.instanceId,
+ capabilities,
+ strategy:
+ targetProviderThread === undefined || requiresFullProviderSwitchContext
+ ? "full_thread_summary"
+ : "delta_context",
+ }),
+ );
+ }
+ const providerSwitchHandoff =
+ providerSwitchTransferId === null || latestHandoffRun === undefined
+ ? null
+ : yield* contextHandoffService
+ .prepareProviderHandoff({
+ threadId: command.threadId,
+ targetRunId: runId,
+ transferId: providerSwitchTransferId,
+ fromProviderThreadIds: Array.from(
+ new Set(
+ providerSwitchCoveredRuns.flatMap((run) =>
+ run.providerThreadId === null ? [] : [run.providerThreadId],
+ ),
+ ),
+ ),
+ toProviderThreadId: ensuredProviderThread.id,
+ fromProviderInstanceId: latestHandoffRun.providerInstanceId,
+ toProviderInstanceId: modelSelection.instanceId,
+ coveredRunOrdinals: {
+ from: providerSwitchCoveredRuns[0]!.ordinal,
+ to: providerSwitchCoveredRuns.at(-1)!.ordinal,
+ },
+ strategy:
+ targetProviderThread === undefined || requiresFullProviderSwitchContext
+ ? "full_thread_summary"
+ : "delta_since_target_last_seen",
+ items: providerSwitchItems,
+ runs: projection.runs,
+ createdAt: now,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause,
+ }),
+ ),
+ );
+ const legacyImportRecoveryHandoff =
+ isProviderSwitch &&
+ !canResumeAcrossInstances &&
+ latestCompletedRun === undefined &&
+ legacyImportItems.length > 0
+ ? yield* contextHandoffService
+ .prepareLegacyImport({
+ threadId: command.threadId,
+ targetRunId: runId,
+ toProviderThreadId: ensuredProviderThread.id,
+ toProviderInstanceId: modelSelection.instanceId,
+ items: legacyImportItems,
+ createdAt: now,
+ })
+ .pipe(mapDispatchError(command))
+ : null;
+ const providerThread: OrchestrationV2ProviderThread = {
+ ...ensuredProviderThread,
+ status: "active",
+ firstRunOrdinal: ensuredProviderThread.firstRunOrdinal ?? ordinal,
+ lastRunOrdinal: ordinal,
+ handoffIds: [
+ ...ensuredProviderThread.handoffIds,
+ ...[portableForkHandoff, providerSwitchHandoff, legacyImportRecoveryHandoff].flatMap(
+ (handoff) => (handoff === null ? [] : [handoff.id]),
+ ),
+ ],
+ updatedAt: now,
+ };
+
+ const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
+ const rootNodeId = idAllocator.derive.rootNode({ runId });
+ const emitEvent = emit(events, command);
+ const mergeBackSourceProjection =
+ pendingMergeBackTransfer === undefined
+ ? null
+ : yield* projectionStore
+ .getThreadRecords(pendingMergeBackTransfer.sourceThreadId, [
+ "runs",
+ "attempts",
+ "providerThreads",
+ "providerTurns",
+ ])
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProjectionError({
+ threadId: pendingMergeBackTransfer.sourceThreadId,
+ cause,
+ }),
+ ),
+ );
+ const mergeBackSourceRun =
+ pendingMergeBackTransfer?.sourcePoint.runId === undefined ||
+ mergeBackSourceProjection === null
+ ? null
+ : (mergeBackSourceProjection.runs.find(
+ (candidate) => candidate.id === pendingMergeBackTransfer.sourcePoint.runId,
+ ) ?? null);
+ if (pendingMergeBackTransfer !== undefined && mergeBackSourceRun === null) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source run.`,
+ });
+ }
+ const mergeBackSourceProviderThread =
+ mergeBackSourceProjection === null || mergeBackSourceRun === null
+ ? undefined
+ : providerThreadForRun(mergeBackSourceProjection, mergeBackSourceRun);
+ if (pendingMergeBackTransfer !== undefined && mergeBackSourceProviderThread === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source provider thread.`,
+ });
+ }
+ if (pendingMergeBackTransfer !== undefined) {
+ yield* enforceCommandPolicy(command)(
+ commandPolicy.ensureContextHandoff({
+ commandId: command.commandId,
+ threadId: command.threadId,
+ providerInstanceId: modelSelection.instanceId,
+ capabilities,
+ strategy: "fork_delta_context",
+ }),
+ );
+ }
+ const mergeBackDeltaItems =
+ mergeBackSourceProjection === null || mergeBackSourceRun === null
+ ? []
+ : yield* readHandoffItems(
+ mergeBackSourceProjection.thread.id,
+ mergeBackSourceProjection.runs
+ .filter((run) => run.ordinal <= mergeBackSourceRun.ordinal)
+ .map((run) => run.id),
+ );
+ const mergeBackHandoff =
+ pendingMergeBackTransfer === undefined ||
+ mergeBackSourceProjection === null ||
+ mergeBackSourceRun === null ||
+ mergeBackSourceProviderThread === undefined
+ ? null
+ : yield* contextHandoffService
+ .prepareForkDelta({
+ sourceThreadId: pendingMergeBackTransfer.sourceThreadId,
+ targetThreadId: command.threadId,
+ targetRunId: runId,
+ transferId: pendingMergeBackTransfer.id,
+ fromProviderThreadIds: [mergeBackSourceProviderThread.id],
+ toProviderThreadId: providerThread.id,
+ fromProviderInstanceId: mergeBackSourceRun.providerInstanceId,
+ toProviderInstanceId: modelSelection.instanceId,
+ coveredRunOrdinals: visibleDeltaRunOrdinals(
+ mergeBackSourceProjection,
+ mergeBackDeltaItems,
+ ),
+ deltaItems: mergeBackDeltaItems,
+ createdAt: now,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause,
+ }),
+ ),
+ );
+ const checkpointScope = yield* checkpointService
+ .prepareRootRunScope({
+ threadId: command.threadId,
+ runId,
+ rootNodeId,
+ providerThreadId: providerThread.id,
+ cwd:
+ resolvedRuntimePolicy.cwd ??
+ existingProviderSession?.cwd ??
+ projection.thread.worktreePath ??
+ process.cwd(),
+ createdAt: now,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause,
+ }),
+ ),
+ );
+ const run: OrchestrationV2Run = {
+ id: runId,
+ threadId: command.threadId,
+ ordinal,
+ providerInstanceId: modelSelection.instanceId,
+ modelSelection,
+ providerThreadId: providerThread.id,
+ userMessageId: command.messageId,
+ rootNodeId,
+ activeAttemptId: attemptId,
+ status: "starting",
+ queuePosition: null,
+ requestedAt: now,
+ startedAt: null,
+ completedAt: null,
+ checkpointId: null,
+ contextHandoffId:
+ portableForkHandoff?.id ??
+ providerSwitchHandoff?.id ??
+ mergeBackHandoff?.id ??
+ legacyImportRecoveryHandoff?.id ??
+ null,
+ ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
+ ...(command.restartContinuationOfRunId === undefined
+ ? {}
+ : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
+ ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
+ ...wakeWorkStartedAt(projection.runs, command),
+ };
+ const attempt: OrchestrationV2RunAttempt = {
+ id: attemptId,
+ runId,
+ attemptOrdinal: 1,
+ rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ providerThreadId: providerThread.id,
+ providerTurnId: null,
+ reason: "initial",
+ status: "pending",
+ startedAt: null,
+ completedAt: null,
+ };
+ const rootNode: OrchestrationV2ExecutionNode = {
+ id: rootNodeId,
+ threadId: command.threadId,
+ runId,
+ parentNodeId: null,
+ rootNodeId,
+ kind: "root_turn",
+ status: "pending",
+ countsForRun: true,
+ providerThreadId: providerThread.id,
+ providerTurnId: null,
+ nativeItemRef: null,
+ runtimeRequestId: null,
+ checkpointScopeId: checkpointScope.id,
+ startedAt: null,
+ completedAt: null,
+ };
+ const message: OrchestrationV2ConversationMessage = {
+ createdBy: command.createdBy,
+ creationSource: command.creationSource,
+ ...(command.scheduledTaskId === undefined
+ ? {}
+ : { scheduledTaskId: command.scheduledTaskId }),
+ ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ id: command.messageId,
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ role: "user",
+ text: dispatchText,
+ ...(command.context ? { context: command.context } : {}),
+ attachments: command.attachments,
+ streaming: false,
+ createdAt: now,
+ updatedAt: now,
+ ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
+ ...(command.notification === undefined ? {} : { notification: command.notification }),
+ };
+ const turnItem: OrchestrationV2TurnItem = {
+ createdBy: command.createdBy,
+ creationSource: command.creationSource,
+ ...(command.scheduledTaskId === undefined
+ ? {}
+ : { scheduledTaskId: command.scheduledTaskId }),
+ ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerThreadId: providerThread.id,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: ordinal * 100,
+ status: "completed",
+ title: null,
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "user_message",
+ messageId: command.messageId,
+ inputIntent: "turn_start",
+ text: dispatchText,
+ ...(command.context ? { context: command.context } : {}),
+ attachments: command.attachments,
+ };
+ const activeHandoff = portableForkHandoff ?? mergeBackHandoff ?? providerSwitchHandoff;
+ const handoffSourceRuns =
+ portableForkHandoff !== null
+ ? sourceRun === null
+ ? []
+ : [sourceRun]
+ : providerSwitchHandoff === null
+ ? mergeBackSourceRun === null
+ ? []
+ : [mergeBackSourceRun]
+ : providerSwitchCoveredRuns;
+ const handoffFromModelSelections = Array.from(
+ new Map(
+ handoffSourceRuns.map((run) => [
+ `${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
+ run.modelSelection,
+ ]),
+ ).values(),
+ );
+ const handoffTurnItem: OrchestrationV2TurnItem | null =
+ activeHandoff === null
+ ? null
+ : {
+ id: idAllocator.derive.runSignalTurnItem({
+ runId,
+ signal: `context-handoff:${activeHandoff.id}`,
+ }),
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerThreadId: providerThread.id,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: ordinal * 100 - 1,
+ status: "completed",
+ title:
+ portableForkHandoff !== null
+ ? "Fork context"
+ : providerSwitchHandoff !== null
+ ? "Provider handoff"
+ : "Merge-back context",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "handoff",
+ contextHandoffId: activeHandoff.id,
+ fromProviderThreadIds: activeHandoff.fromProviderThreadIds,
+ toProviderThreadId: activeHandoff.toProviderThreadId,
+ fromProviderInstanceIds: Array.from(
+ new Set(handoffSourceRuns.map((run) => run.providerInstanceId)),
+ ),
+ toProviderInstanceId: modelSelection.instanceId,
+ fromModelSelections: handoffFromModelSelections,
+ toModel: modelSelection.model,
+ strategy: activeHandoff.strategy,
+ summary: activeHandoff.summaryText,
+ };
+ const nativeForkResolution: OrchestrationV2ContextTransferResolution | null =
+ !canResolveForkNatively || providerThread.nativeThreadRef === null
+ ? null
+ : {
+ strategy: "native_fork",
+ providerThreadRef: providerThread.nativeThreadRef,
+ };
+ const portableForkResolution: OrchestrationV2ContextTransferResolution | null =
+ pendingForkTransfer === undefined || portableForkHandoff === null
+ ? null
+ : {
+ strategy: "portable_context",
+ contextHandoffId: portableForkHandoff.id,
+ };
+ const mergeBackResolution: OrchestrationV2ContextTransferResolution | null =
+ pendingMergeBackTransfer === undefined || mergeBackHandoff === null
+ ? null
+ : {
+ strategy: "fork_delta_context",
+ contextHandoffId: mergeBackHandoff.id,
+ };
+
+ if (pendingForkTransfer !== undefined && canResolveForkNatively) {
+ yield* emitEvent({
+ type: "context-transfer.updated",
+ threadId: command.threadId,
+ runId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: {
+ ...pendingForkTransfer,
+ targetProviderInstanceId: modelSelection.instanceId,
+ targetRunId: runId,
+ status: "pending",
+ resolution: null,
+ error: null,
+ updatedAt: now,
+ },
+ });
+ }
+ if (pendingForkTransfer !== undefined && portableForkResolution !== null) {
+ yield* emitEvent({
+ type: "context-transfer.updated",
+ threadId: command.threadId,
+ runId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: {
+ ...pendingForkTransfer,
+ targetProviderInstanceId: modelSelection.instanceId,
+ targetRunId: runId,
+ status: "resolved_portable",
+ resolution: portableForkResolution,
+ error: null,
+ updatedAt: now,
+ },
+ });
+ }
+ yield* emitEvent({
+ type: "provider-thread.updated",
+ threadId: command.threadId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: providerThread,
+ });
+ if (portableForkHandoff !== null) {
+ yield* emitEvent({
+ type: "context-handoff.updated",
+ threadId: command.threadId,
+ runId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: portableForkHandoff,
+ });
+ }
+ if (legacyImportRecoveryHandoff !== null) {
+ yield* emitEvent({
+ type: "context-handoff.updated",
threadId: command.threadId,
runId,
- nodeId: rootNodeId,
- providerThreadId: providerThread.id,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: ordinal * 100,
- status: "completed",
- title: null,
- startedAt: now,
- completedAt: now,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: legacyImportRecoveryHandoff,
+ });
+ }
+ if (
+ providerSwitchTransferId !== null &&
+ providerSwitchHandoff !== null &&
+ latestHandoffRun !== undefined
+ ) {
+ const transfer: OrchestrationV2ContextTransfer = {
+ id: providerSwitchTransferId,
+ type: "provider_handoff",
+ sourceThreadId: command.threadId,
+ targetThreadId: command.threadId,
+ sourcePoint: contextSourcePointForRun(projection, latestHandoffRun),
+ basePoint:
+ requiresFullProviderSwitchContext || targetLastCompletedRun === undefined
+ ? null
+ : contextSourcePointForRun(projection, targetLastCompletedRun),
+ sourceProviderInstanceId: latestHandoffRun.providerInstanceId,
+ targetProviderInstanceId: modelSelection.instanceId,
+ targetRunId: runId,
+ status: "consumed",
+ resolution: {
+ strategy:
+ providerSwitchHandoff.strategy === "full_thread_summary"
+ ? "portable_context"
+ : "delta_context",
+ contextHandoffId: providerSwitchHandoff.id,
+ },
+ createdBy: command.createdBy,
+ error: null,
+ createdAt: now,
updatedAt: now,
- type: "user_message",
- messageId: command.messageId,
- inputIntent: "turn_start",
- text: dispatchText,
- ...(command.context ? { context: command.context } : {}),
- attachments: command.attachments,
+ consumedAt: now,
};
- const activeHandoff = portableForkHandoff ?? mergeBackHandoff ?? providerSwitchHandoff;
- const handoffSourceRuns =
- portableForkHandoff !== null
- ? sourceRun === null
- ? []
- : [sourceRun]
- : providerSwitchHandoff === null
- ? mergeBackSourceRun === null
- ? []
- : [mergeBackSourceRun]
- : providerSwitchCoveredRuns;
- const handoffFromModelSelections = Array.from(
- new Map(
- handoffSourceRuns.map((run) => [
- `${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
- run.modelSelection,
- ]),
- ).values(),
- );
- const handoffTurnItem: OrchestrationV2TurnItem | null =
- activeHandoff === null
- ? null
- : {
- id: idAllocator.derive.runSignalTurnItem({
- runId,
- signal: `context-handoff:${activeHandoff.id}`,
- }),
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerThreadId: providerThread.id,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: ordinal * 100 - 1,
- status: "completed",
- title:
- portableForkHandoff !== null
- ? "Fork context"
- : providerSwitchHandoff !== null
- ? "Provider handoff"
- : "Merge-back context",
- startedAt: now,
- completedAt: now,
- updatedAt: now,
- type: "handoff",
- contextHandoffId: activeHandoff.id,
- fromProviderThreadIds: activeHandoff.fromProviderThreadIds,
- toProviderThreadId: activeHandoff.toProviderThreadId,
- fromProviderInstanceIds: Array.from(
- new Set(handoffSourceRuns.map((run) => run.providerInstanceId)),
- ),
- toProviderInstanceId: modelSelection.instanceId,
- fromModelSelections: handoffFromModelSelections,
- toModel: modelSelection.model,
- strategy: activeHandoff.strategy,
- summary: activeHandoff.summaryText,
- };
- const nativeForkResolution: OrchestrationV2ContextTransferResolution | null =
- !canResolveForkNatively || providerThread.nativeThreadRef === null
- ? null
- : {
- strategy: "native_fork",
- providerThreadRef: providerThread.nativeThreadRef,
- };
- const portableForkResolution: OrchestrationV2ContextTransferResolution | null =
- pendingForkTransfer === undefined || portableForkHandoff === null
- ? null
- : {
- strategy: "portable_context",
- contextHandoffId: portableForkHandoff.id,
- };
- const mergeBackResolution: OrchestrationV2ContextTransferResolution | null =
- pendingMergeBackTransfer === undefined || mergeBackHandoff === null
- ? null
- : {
- strategy: "fork_delta_context",
- contextHandoffId: mergeBackHandoff.id,
- };
-
- if (pendingForkTransfer !== undefined && canResolveForkNatively) {
- yield* emitEvent({
- type: "context-transfer.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: {
- ...pendingForkTransfer,
- targetProviderInstanceId: modelSelection.instanceId,
- targetRunId: runId,
- status: "pending",
- resolution: null,
- error: null,
- updatedAt: now,
- },
- });
- }
- if (pendingForkTransfer !== undefined && portableForkResolution !== null) {
- yield* emitEvent({
- type: "context-transfer.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: {
- ...pendingForkTransfer,
- targetProviderInstanceId: modelSelection.instanceId,
- targetRunId: runId,
- status: "resolved_portable",
- resolution: portableForkResolution,
- error: null,
- updatedAt: now,
- },
- });
- }
yield* emitEvent({
- type: "provider-thread.updated",
+ type: "context-transfer.created",
threadId: command.threadId,
+ runId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: providerThread,
+ payload: transfer,
});
- if (portableForkHandoff !== null) {
- yield* emitEvent({
- type: "context-handoff.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: portableForkHandoff,
- });
- }
- if (legacyImportRecoveryHandoff !== null) {
- yield* emitEvent({
- type: "context-handoff.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: legacyImportRecoveryHandoff,
- });
- }
- if (
- providerSwitchTransferId !== null &&
- providerSwitchHandoff !== null &&
- latestHandoffRun !== undefined
- ) {
- const transfer: OrchestrationV2ContextTransfer = {
- id: providerSwitchTransferId,
- type: "provider_handoff",
- sourceThreadId: command.threadId,
- targetThreadId: command.threadId,
- sourcePoint: contextSourcePointForRun(projection, latestHandoffRun),
- basePoint:
- requiresFullProviderSwitchContext || targetLastCompletedRun === undefined
- ? null
- : contextSourcePointForRun(projection, targetLastCompletedRun),
- sourceProviderInstanceId: latestHandoffRun.providerInstanceId,
- targetProviderInstanceId: modelSelection.instanceId,
- targetRunId: runId,
- status: "consumed",
- resolution: {
- strategy:
- providerSwitchHandoff.strategy === "full_thread_summary"
- ? "portable_context"
- : "delta_context",
- contextHandoffId: providerSwitchHandoff.id,
- },
- createdBy: command.createdBy,
- error: null,
- createdAt: now,
- updatedAt: now,
- consumedAt: now,
- };
- yield* emitEvent({
- type: "context-transfer.created",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: transfer,
- });
- yield* emitEvent({
- type: "context-handoff.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: providerSwitchHandoff,
- });
- }
- if (mergeBackHandoff !== null) {
- yield* emitEvent({
- type: "context-handoff.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: mergeBackHandoff,
- });
- }
- for (const supersededTransfer of supersededMergeBackTransfers) {
- yield* emitEvent({
- type: "context-transfer.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: {
- ...supersededTransfer,
- status: "superseded",
- error:
- pendingMergeBackTransfer === undefined
- ? "Superseded while consuming merge-back transfer."
- : `Superseded by merge-back transfer ${pendingMergeBackTransfer.id}.`,
- updatedAt: now,
- },
- });
- }
- if (pendingMergeBackTransfer !== undefined && mergeBackResolution !== null) {
- yield* emitEvent({
- type: "context-transfer.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: {
- ...pendingMergeBackTransfer,
- targetProviderInstanceId: modelSelection.instanceId,
- targetRunId: runId,
- status: "consumed",
- resolution: mergeBackResolution,
- error: null,
- updatedAt: now,
- consumedAt: now,
- },
- });
- }
yield* emitEvent({
- type: "run.created",
+ type: "context-handoff.updated",
threadId: command.threadId,
runId,
- nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: run,
+ payload: providerSwitchHandoff,
});
- yield* completeSourcePlan(now);
+ }
+ if (mergeBackHandoff !== null) {
yield* emitEvent({
- type: "run-attempt.created",
+ type: "context-handoff.updated",
threadId: command.threadId,
runId,
- nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: attempt,
+ payload: mergeBackHandoff,
});
+ }
+ for (const supersededTransfer of supersededMergeBackTransfers) {
yield* emitEvent({
- type: "node.updated",
+ type: "context-transfer.updated",
threadId: command.threadId,
runId,
- nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: rootNode,
+ payload: {
+ ...supersededTransfer,
+ status: "superseded",
+ error:
+ pendingMergeBackTransfer === undefined
+ ? "Superseded while consuming merge-back transfer."
+ : `Superseded by merge-back transfer ${pendingMergeBackTransfer.id}.`,
+ updatedAt: now,
+ },
});
+ }
+ if (pendingMergeBackTransfer !== undefined && mergeBackResolution !== null) {
yield* emitEvent({
- type: "checkpoint-scope.created",
+ type: "context-transfer.updated",
threadId: command.threadId,
runId,
- nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: yield* checkpointService.ensureScope(checkpointScope).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause,
- }),
- ),
- ),
+ payload: {
+ ...pendingMergeBackTransfer,
+ targetProviderInstanceId: modelSelection.instanceId,
+ targetRunId: runId,
+ status: "consumed",
+ resolution: mergeBackResolution,
+ error: null,
+ updatedAt: now,
+ consumedAt: now,
+ },
});
- if (handoffTurnItem !== null) {
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId,
- nodeId: rootNodeId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: handoffTurnItem,
- });
- }
+ }
+ yield* emitEvent({
+ type: "run.created",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: run,
+ });
+ yield* completeSourcePlan(now);
+ yield* emitEvent({
+ type: "run-attempt.created",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: attempt,
+ });
+ yield* emitEvent({
+ type: "node.updated",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: rootNode,
+ });
+ yield* emitEvent({
+ type: "checkpoint-scope.created",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: yield* checkpointService.ensureScope(checkpointScope).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause,
+ }),
+ ),
+ ),
+ });
+ if (handoffTurnItem !== null) {
yield* emitEvent({
- type: "message.updated",
+ type: "turn-item.updated",
threadId: command.threadId,
runId,
nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: message,
+ payload: handoffTurnItem,
});
+ }
+ yield* emitEvent({
+ type: "message.updated",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: message,
+ });
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ runId,
+ nodeId: rootNodeId,
+ providerInstanceId: modelSelection.instanceId,
+ occurredAt: now,
+ payload: notificationTurnItem(turnItem, message, projection.subagents),
+ });
+ const forkResolution = nativeForkResolution ?? portableForkResolution;
+ if (pendingForkTransfer !== undefined && forkResolution !== null) {
yield* emitEvent({
- type: "turn-item.updated",
+ type: "context-transfer.updated",
threadId: command.threadId,
runId,
- nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: notificationTurnItem(turnItem, message, projection.subagents),
+ payload: {
+ ...pendingForkTransfer,
+ targetProviderInstanceId: modelSelection.instanceId,
+ targetRunId: runId,
+ status: "consumed",
+ resolution: forkResolution,
+ error: null,
+ updatedAt: now,
+ consumedAt: now,
+ },
});
- const forkResolution = nativeForkResolution ?? portableForkResolution;
- if (pendingForkTransfer !== undefined && forkResolution !== null) {
- yield* emitEvent({
- type: "context-transfer.updated",
- threadId: command.threadId,
- runId,
- providerInstanceId: modelSelection.instanceId,
- occurredAt: now,
- payload: {
- ...pendingForkTransfer,
- targetProviderInstanceId: modelSelection.instanceId,
- targetRunId: runId,
- status: "consumed",
- resolution: forkResolution,
- error: null,
- updatedAt: now,
- consumedAt: now,
- },
- });
- }
+ }
- if (canResumeAcrossInstances && activeProviderThread.providerSessionId !== null) {
- const previousProviderSessionId = activeProviderThread.providerSessionId;
- yield* emitEvent({
- type: "provider-session.detached",
+ if (canResumeAcrossInstances && activeProviderThread.providerSessionId !== null) {
+ const previousProviderSessionId = activeProviderThread.providerSessionId;
+ yield* emitEvent({
+ type: "provider-session.detached",
+ threadId: command.threadId,
+ driver: activeProviderThread.driver,
+ providerInstanceId: activeProviderThread.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ providerSessionId: previousProviderSessionId,
+ detachedAt: now,
+ reason: "Provider account changed; continuing the native thread.",
+ },
+ });
+ yield* Ref.update(effects, (existing) => [
+ ...existing,
+ {
+ id: `effect:${command.commandId}:provider-session.detach:${previousProviderSessionId}`,
+ commandId: command.commandId,
threadId: command.threadId,
- driver: activeProviderThread.driver,
- providerInstanceId: activeProviderThread.providerInstanceId,
- occurredAt: now,
- payload: {
+ request: {
+ type: "provider-session.detach",
providerSessionId: previousProviderSessionId,
- detachedAt: now,
- reason: "Provider account changed; continuing the native thread.",
+ detail: "Provider account changed; continuing the native thread.",
},
- });
- yield* Ref.update(effects, (existing) => [
- ...existing,
- {
- id: `effect:${command.commandId}:provider-session.detach:${previousProviderSessionId}`,
- commandId: command.commandId,
- threadId: command.threadId,
- request: {
- type: "provider-session.detach",
- providerSessionId: previousProviderSessionId,
- detail: "Provider account changed; continuing the native thread.",
- },
- } satisfies PendingOrchestrationEffectV2,
- ]);
- }
- const pendingEffect = {
- id: `effect:${command.commandId}:provider-turn.start:${runId}`,
- commandId: command.commandId,
- threadId: command.threadId,
- request: { type: "provider-turn.start", runId },
- } satisfies PendingOrchestrationEffectV2;
- yield* Ref.update(effects, (existing) => [...existing, pendingEffect]);
- });
+ } satisfies PendingOrchestrationEffectV2,
+ ]);
+ }
+ const pendingEffect = {
+ id: `effect:${command.commandId}:provider-turn.start:${runId}`,
+ commandId: command.commandId,
+ threadId: command.threadId,
+ request: { type: "provider-turn.start", runId },
+ } satisfies PendingOrchestrationEffectV2;
+ yield* Ref.update(effects, (existing) => [...existing, pendingEffect]);
+ });
const dispatchDelegatedTaskRequest = Effect.fn("orchestrationV2.dispatch.delegatedTaskRequest")(
function* (
@@ -7481,12 +7472,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
);
- const dispatchRuntimeRequestRespond = (
- command: Extract<OrchestrationV2Command, { readonly type: "runtime-request.respond" }>,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
+ const dispatchRuntimeRequestRespond = Effect.fn("Orchestrator.dispatchRuntimeRequestRespond")(
+ function* (
+ command: Extract<OrchestrationV2Command, { readonly type: "runtime-request.respond" }>,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
+ ) {
const context = yield* projectionStore
.getRuntimeResponseContext(command.threadId, command.requestId)
.pipe(
@@ -7692,486 +7683,475 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
threadId: command.threadId,
messageId: MessageId.make(`async-answer:${command.requestId}`),
text: replies.join("\n\n"),
- attachments: [],
- createdBy: "user",
- creationSource: "server",
- dispatchMode,
- },
- events,
- effects,
- );
- }
- if (providerSessionId === null) return;
- yield* Ref.update(effects, (existing) => [
- ...existing,
- {
- id: `effect:${command.commandId}:runtime-request.respond:${command.requestId}`,
- commandId: command.commandId,
- threadId: command.threadId,
- request: {
- type: "runtime-request.respond",
- providerSessionId,
- requestId: command.requestId,
- ...(command.decision === undefined ? {} : { decision: command.decision }),
- ...(answers === undefined ? {} : { answers }),
- },
- } satisfies PendingOrchestrationEffectV2,
- ]);
- });
-
- const dispatchThreadUserInputDismiss = (
- command: Extract<OrchestrationV2Command, { readonly type: "thread.user-input.dismiss" }>,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
- const request = yield* projectionStore
- .getRuntimeRequest(command.threadId, command.requestId)
- .pipe(
- Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })),
- );
- if (request === undefined || request.status !== "pending") {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "This question has already been answered.",
- });
- }
- if (request.kind !== "user_input" || request.responseCapability.type !== "message") {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "This question needs an answer. Answer it or stop the turn.",
- });
- }
- yield* dispatchRuntimeRequestRespond(
- {
- type: "runtime-request.respond",
- commandId: command.commandId,
- threadId: command.threadId,
- requestId: command.requestId,
- decision: "cancel",
- },
- events,
- effects,
- );
- });
-
- const dispatchQueuedMessagePromoteToSteer = (
- command: Extract<OrchestrationV2Command, { readonly type: "queued-message.promote-to-steer" }>,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
- const projection = yield* projectionStore
- .getThreadRecords(
- command.threadId,
- [
- "runs",
- "nodes",
- "attempts",
- "messages",
- "providerThreads",
- "providerTurns",
- "providerSessions",
- "turnItems",
- "runtimeRequests",
- "subagents",
- ],
- { turnItemTypes: [], messageRoles: ["user"] },
- )
- .pipe(
- Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })),
- );
- if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Thread ${command.threadId} is not active.`,
- });
- }
- const queuedRun = projection.runs.find((candidate) => candidate.id === command.queuedRunId);
- if (queuedRun === undefined || queuedRun.status !== "queued") {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Queued run ${command.queuedRunId} is not queued.`,
- });
- }
- const queuedRootNode =
- queuedRun.rootNodeId === null
- ? undefined
- : projection.nodes.find((candidate) => candidate.id === queuedRun.rootNodeId);
- const queuedAttempt =
- queuedRun.activeAttemptId === null
- ? undefined
- : projection.attempts.find((candidate) => candidate.id === queuedRun.activeAttemptId);
- const queuedMessage = projection.messages.find(
- (candidate) => candidate.id === queuedRun.userMessageId,
- );
- if (
- queuedRootNode === undefined ||
- queuedAttempt === undefined ||
- queuedMessage === undefined
- ) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Queued run ${queuedRun.id} is missing message or execution state.`,
- });
- }
- if (
- queuedMessage.delegatedCompletion !== undefined ||
- queuedMessage.notification !== undefined
- ) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "Automatic completion deliveries cannot be promoted to Steer.",
- });
- }
-
- const now = yield* DateTime.now;
- const emitEvent = emit(events, command);
- yield* emitEvent({
- type: "run.updated",
- threadId: command.threadId,
- runId: queuedRun.id,
- nodeId: queuedRootNode.id,
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: {
- ...queuedRun,
- status: "cancelled",
- queuePosition: null,
- completedAt: now,
- },
- });
- yield* emitEvent({
- type: "run-attempt.updated",
- threadId: command.threadId,
- runId: queuedRun.id,
- nodeId: queuedRootNode.id,
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: {
- ...queuedAttempt,
- status: "cancelled",
- completedAt: now,
- },
- });
- yield* emitEvent({
- type: "node.updated",
- threadId: command.threadId,
- runId: queuedRun.id,
- nodeId: queuedRootNode.id,
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: {
- ...queuedRootNode,
- status: "cancelled",
- completedAt: now,
- },
- });
-
- yield* dispatchSteerIntoRun({
- command,
- events,
- effects,
- projection,
- modelSelection: projection.thread.modelSelection,
- targetRunId: command.targetRunId,
- messageId: queuedMessage.id,
- text: queuedMessage.text,
- attachments: queuedMessage.attachments,
- ...(queuedMessage.context ? { context: queuedMessage.context } : {}),
- createdBy: queuedMessage.createdBy,
- creationSource: queuedMessage.creationSource,
- ...(queuedMessage.scheduledTaskId === undefined
- ? {}
- : { scheduledTaskId: queuedMessage.scheduledTaskId }),
- ...(queuedMessage.senderThreadId === undefined
- ? {}
- : { senderThreadId: queuedMessage.senderThreadId }),
- forceRestart: false,
- });
- });
+ attachments: [],
+ createdBy: "user",
+ creationSource: "server",
+ dispatchMode,
+ },
+ events,
+ effects,
+ );
+ }
+ if (providerSessionId === null) return;
+ yield* Ref.update(effects, (existing) => [
+ ...existing,
+ {
+ id: `effect:${command.commandId}:runtime-request.respond:${command.requestId}`,
+ commandId: command.commandId,
+ threadId: command.threadId,
+ request: {
+ type: "runtime-request.respond",
+ providerSessionId,
+ requestId: command.requestId,
+ ...(command.decision === undefined ? {} : { decision: command.decision }),
+ ...(answers === undefined ? {} : { answers }),
+ },
+ } satisfies PendingOrchestrationEffectV2,
+ ]);
+ },
+ );
- const dispatchQueuedRunReorder = (
- command: Extract<OrchestrationV2Command, { readonly type: "queued-run.reorder" }>,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- ) =>
- Effect.gen(function* () {
- const projection = yield* projectionStore
- .getThreadRecords(command.threadId, ["runs", "messages"], { messageRoles: ["user"] })
+ const dispatchThreadUserInputDismiss = Effect.fn("Orchestrator.dispatchThreadUserInputDismiss")(
+ function* (
+ command: Extract<OrchestrationV2Command, { readonly type: "thread.user-input.dismiss" }>,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
+ ) {
+ const request = yield* projectionStore
+ .getRuntimeRequest(command.threadId, command.requestId)
.pipe(
Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })),
);
- const queuedRuns = queuedRunsInDeliveryOrder(projection);
- const moving = queuedRuns.find((run) => run.id === command.runId);
- if (moving === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Run ${command.runId} is not queued.`,
- });
- }
- const movingMessage = projection.messages.find(
- (candidate) => candidate.id === moving.userMessageId,
- );
- if (
- movingMessage?.delegatedCompletion !== undefined ||
- movingMessage?.notification !== undefined
- ) {
+ if (request === undefined || request.status !== "pending") {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
- cause: "Automatic completion deliveries cannot be reordered.",
+ cause: "This question has already been answered.",
});
}
- const automaticRuns = queuedRuns.filter((run) => isAutomaticCompletionRun(projection, run));
- if (
- command.beforeRunId !== null &&
- automaticRuns.some((run) => run.id === command.beforeRunId)
- ) {
+ if (request.kind !== "user_input" || request.responseCapability.type !== "message") {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
- cause: "Queued messages cannot be reordered ahead of automatic completion delivery.",
+ cause: "This question needs an answer. Answer it or stop the turn.",
});
}
- const reorderableRuns = queuedRuns.filter(
- (run) => !isAutomaticCompletionRun(projection, run),
- );
- const withoutMoving = reorderableRuns.filter((run) => run.id !== command.runId);
- const beforeIndex =
- command.beforeRunId === null
- ? withoutMoving.length
- : withoutMoving.findIndex((run) => run.id === command.beforeRunId);
- if (beforeIndex === -1) {
- return yield* new OrchestratorDispatchError({
+ yield* dispatchRuntimeRequestRespond(
+ {
+ type: "runtime-request.respond",
commandId: command.commandId,
- commandType: command.type,
- cause: `Queue target ${command.beforeRunId} is not queued.`,
- });
- }
- const reordered = [
- ...automaticRuns,
- ...withoutMoving.slice(0, beforeIndex),
- moving,
- ...withoutMoving.slice(beforeIndex),
- ];
- const now = yield* DateTime.now;
- const emitEvent = emit(events, command);
- yield* Effect.forEach(
- reordered,
- (run, index) =>
- Effect.gen(function* () {
- const queuePosition = index + 1;
- if (run.queuePosition === queuePosition) {
- return;
- }
- yield* emitEvent({
- type: "run.updated",
- threadId: command.threadId,
- runId: run.id,
- ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
- providerInstanceId: run.providerInstanceId,
- occurredAt: now,
- payload: {
- ...run,
- queuePosition,
- },
- });
- }),
- { concurrency: 1 },
+ threadId: command.threadId,
+ requestId: command.requestId,
+ decision: "cancel",
+ },
+ events,
+ effects,
);
+ },
+ );
+
+ const dispatchQueuedMessagePromoteToSteer = Effect.fn(
+ "Orchestrator.dispatchQueuedMessagePromoteToSteer",
+ )(function* (
+ command: Extract<OrchestrationV2Command, { readonly type: "queued-message.promote-to-steer" }>,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
+ ) {
+ const projection = yield* projectionStore
+ .getThreadRecords(
+ command.threadId,
+ [
+ "runs",
+ "nodes",
+ "attempts",
+ "messages",
+ "providerThreads",
+ "providerTurns",
+ "providerSessions",
+ "turnItems",
+ "runtimeRequests",
+ "subagents",
+ ],
+ { turnItemTypes: [], messageRoles: ["user"] },
+ )
+ .pipe(Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })));
+ if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Thread ${command.threadId} is not active.`,
+ });
+ }
+ const queuedRun = projection.runs.find((candidate) => candidate.id === command.queuedRunId);
+ if (queuedRun === undefined || queuedRun.status !== "queued") {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Queued run ${command.queuedRunId} is not queued.`,
+ });
+ }
+ const queuedRootNode =
+ queuedRun.rootNodeId === null
+ ? undefined
+ : projection.nodes.find((candidate) => candidate.id === queuedRun.rootNodeId);
+ const queuedAttempt =
+ queuedRun.activeAttemptId === null
+ ? undefined
+ : projection.attempts.find((candidate) => candidate.id === queuedRun.activeAttemptId);
+ const queuedMessage = projection.messages.find(
+ (candidate) => candidate.id === queuedRun.userMessageId,
+ );
+ if (
+ queuedRootNode === undefined ||
+ queuedAttempt === undefined ||
+ queuedMessage === undefined
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Queued run ${queuedRun.id} is missing message or execution state.`,
+ });
+ }
+ if (
+ queuedMessage.delegatedCompletion !== undefined ||
+ queuedMessage.notification !== undefined
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Automatic completion deliveries cannot be promoted to Steer.",
+ });
+ }
+
+ const now = yield* DateTime.now;
+ const emitEvent = emit(events, command);
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: command.threadId,
+ runId: queuedRun.id,
+ nodeId: queuedRootNode.id,
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...queuedRun,
+ status: "cancelled",
+ queuePosition: null,
+ completedAt: now,
+ },
+ });
+ yield* emitEvent({
+ type: "run-attempt.updated",
+ threadId: command.threadId,
+ runId: queuedRun.id,
+ nodeId: queuedRootNode.id,
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...queuedAttempt,
+ status: "cancelled",
+ completedAt: now,
+ },
+ });
+ yield* emitEvent({
+ type: "node.updated",
+ threadId: command.threadId,
+ runId: queuedRun.id,
+ nodeId: queuedRootNode.id,
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...queuedRootNode,
+ status: "cancelled",
+ completedAt: now,
+ },
});
- const dispatchQueuedRunCancel = (
- command: Extract<OrchestrationV2Command, { readonly type: "queued-run.cancel" }>,
+ yield* dispatchSteerIntoRun({
+ command,
+ events,
+ effects,
+ projection,
+ modelSelection: projection.thread.modelSelection,
+ targetRunId: command.targetRunId,
+ messageId: queuedMessage.id,
+ text: queuedMessage.text,
+ attachments: queuedMessage.attachments,
+ ...(queuedMessage.context ? { context: queuedMessage.context } : {}),
+ createdBy: queuedMessage.createdBy,
+ creationSource: queuedMessage.creationSource,
+ ...(queuedMessage.scheduledTaskId === undefined
+ ? {}
+ : { scheduledTaskId: queuedMessage.scheduledTaskId }),
+ ...(queuedMessage.senderThreadId === undefined
+ ? {}
+ : { senderThreadId: queuedMessage.senderThreadId }),
+ forceRestart: false,
+ });
+ });
+
+ const dispatchQueuedRunReorder = Effect.fn("Orchestrator.dispatchQueuedRunReorder")(function* (
+ command: Extract<OrchestrationV2Command, { readonly type: "queued-run.reorder" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- ) =>
- Effect.gen(function* () {
- const projection = yield* projectionStore
- .getThreadRecords(
- command.threadId,
- ["runs", "messages", "nodes", "attempts", "subagents", "turnItems"],
- { turnItemTypes: [], messageRoles: ["user"] },
- )
- .pipe(
- Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })),
- );
- const queuedRun = projection.runs.find((candidate) => candidate.id === command.runId);
- if (queuedRun === undefined || queuedRun.status !== "queued") {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Run ${command.runId} is not queued.`,
- });
- }
- const queuedMessage = projection.messages.find(
- (candidate) => candidate.id === queuedRun.userMessageId,
- );
- if (queuedMessage?.delegatedCompletion !== undefined) {
- const now = yield* DateTime.now;
- yield* disposeDelegatedCompletionCohort({
- command,
- events,
- projection,
- parentRunId: queuedMessage.delegatedCompletion.parentRunId,
- disposition: "disposed",
- now,
- });
- return;
- }
- const queuedRootNode =
- queuedRun.rootNodeId === null
- ? undefined
- : projection.nodes.find((candidate) => candidate.id === queuedRun.rootNodeId);
- const queuedAttempt =
- queuedRun.activeAttemptId === null
- ? undefined
- : projection.attempts.find((candidate) => candidate.id === queuedRun.activeAttemptId);
+ ) {
+ const projection = yield* projectionStore
+ .getThreadRecords(command.threadId, ["runs", "messages"], { messageRoles: ["user"] })
+ .pipe(Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })));
+ const queuedRuns = queuedRunsInDeliveryOrder(projection);
+ const moving = queuedRuns.find((run) => run.id === command.runId);
+ if (moving === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Run ${command.runId} is not queued.`,
+ });
+ }
+ const movingMessage = projection.messages.find(
+ (candidate) => candidate.id === moving.userMessageId,
+ );
+ if (
+ movingMessage?.delegatedCompletion !== undefined ||
+ movingMessage?.notification !== undefined
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Automatic completion deliveries cannot be reordered.",
+ });
+ }
+ const automaticRuns = queuedRuns.filter((run) => isAutomaticCompletionRun(projection, run));
+ if (
+ command.beforeRunId !== null &&
+ automaticRuns.some((run) => run.id === command.beforeRunId)
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Queued messages cannot be reordered ahead of automatic completion delivery.",
+ });
+ }
+ const reorderableRuns = queuedRuns.filter((run) => !isAutomaticCompletionRun(projection, run));
+ const withoutMoving = reorderableRuns.filter((run) => run.id !== command.runId);
+ const beforeIndex =
+ command.beforeRunId === null
+ ? withoutMoving.length
+ : withoutMoving.findIndex((run) => run.id === command.beforeRunId);
+ if (beforeIndex === -1) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Queue target ${command.beforeRunId} is not queued.`,
+ });
+ }
+ const reordered = [
+ ...automaticRuns,
+ ...withoutMoving.slice(0, beforeIndex),
+ moving,
+ ...withoutMoving.slice(beforeIndex),
+ ];
+ const now = yield* DateTime.now;
+ const emitEvent = emit(events, command);
+ yield* Effect.forEach(
+ reordered,
+ (run, index) =>
+ Effect.gen(function* () {
+ const queuePosition = index + 1;
+ if (run.queuePosition === queuePosition) {
+ return;
+ }
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: command.threadId,
+ runId: run.id,
+ ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...run,
+ queuePosition,
+ },
+ });
+ }),
+ { concurrency: 1 },
+ );
+ });
+ const dispatchQueuedRunCancel = Effect.fn("Orchestrator.dispatchQueuedRunCancel")(function* (
+ command: Extract<OrchestrationV2Command, { readonly type: "queued-run.cancel" }>,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ ) {
+ const projection = yield* projectionStore
+ .getThreadRecords(
+ command.threadId,
+ ["runs", "messages", "nodes", "attempts", "subagents", "turnItems"],
+ { turnItemTypes: [], messageRoles: ["user"] },
+ )
+ .pipe(Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })));
+ const queuedRun = projection.runs.find((candidate) => candidate.id === command.runId);
+ if (queuedRun === undefined || queuedRun.status !== "queued") {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Run ${command.runId} is not queued.`,
+ });
+ }
+ const queuedMessage = projection.messages.find(
+ (candidate) => candidate.id === queuedRun.userMessageId,
+ );
+ if (queuedMessage?.delegatedCompletion !== undefined) {
const now = yield* DateTime.now;
- const emitEvent = emit(events, command);
+ yield* disposeDelegatedCompletionCohort({
+ command,
+ events,
+ projection,
+ parentRunId: queuedMessage.delegatedCompletion.parentRunId,
+ disposition: "disposed",
+ now,
+ });
+ return;
+ }
+ const queuedRootNode =
+ queuedRun.rootNodeId === null
+ ? undefined
+ : projection.nodes.find((candidate) => candidate.id === queuedRun.rootNodeId);
+ const queuedAttempt =
+ queuedRun.activeAttemptId === null
+ ? undefined
+ : projection.attempts.find((candidate) => candidate.id === queuedRun.activeAttemptId);
+
+ const now = yield* DateTime.now;
+ const emitEvent = emit(events, command);
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: command.threadId,
+ runId: queuedRun.id,
+ ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...queuedRun,
+ status: "cancelled",
+ queuePosition: null,
+ completedAt: now,
+ },
+ });
+ if (queuedAttempt !== undefined && queuedRootNode !== undefined) {
yield* emitEvent({
- type: "run.updated",
+ type: "run-attempt.updated",
threadId: command.threadId,
runId: queuedRun.id,
- ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),
+ nodeId: queuedRootNode.id,
providerInstanceId: queuedRun.providerInstanceId,
occurredAt: now,
payload: {
- ...queuedRun,
+ ...queuedAttempt,
status: "cancelled",
- queuePosition: null,
completedAt: now,
},
});
- if (queuedAttempt !== undefined && queuedRootNode !== undefined) {
- yield* emitEvent({
- type: "run-attempt.updated",
- threadId: command.threadId,
- runId: queuedRun.id,
- nodeId: queuedRootNode.id,
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: {
- ...queuedAttempt,
- status: "cancelled",
- completedAt: now,
- },
- });
- }
- if (queuedRootNode !== undefined) {
- yield* emitEvent({
- type: "node.updated",
- threadId: command.threadId,
- runId: queuedRun.id,
- nodeId: queuedRootNode.id,
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: {
- ...queuedRootNode,
- status: "cancelled",
- completedAt: now,
- },
- });
- }
- });
+ }
+ if (queuedRootNode !== undefined) {
+ yield* emitEvent({
+ type: "node.updated",
+ threadId: command.threadId,
+ runId: queuedRun.id,
+ nodeId: queuedRootNode.id,
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...queuedRootNode,
+ status: "cancelled",
+ completedAt: now,
+ },
+ });
+ }
+ });
- const dispatchQueuedRunEdit = (
+ const dispatchQueuedRunEdit = Effect.fn("Orchestrator.dispatchQueuedRunEdit")(function* (
command: Extract<OrchestrationV2Command, { readonly type: "queued-run.edit" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- ) =>
- Effect.gen(function* () {
- if (command.text.trim().length === 0) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Queued run ${command.runId} cannot be edited to an empty message.`,
- });
- }
- const projection = yield* projectionStore
- .getThreadRecords(command.threadId, ["runs", "messages", "turnItems"], {
- turnItemTypes: ["user_message"],
- messageRoles: ["user"],
- })
- .pipe(
- Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })),
- );
- const queuedRun = projection.runs.find((candidate) => candidate.id === command.runId);
- if (queuedRun === undefined || queuedRun.status !== "queued") {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Run ${command.runId} is not queued.`,
- });
- }
- const queuedMessage = projection.messages.find(
- (candidate) => candidate.id === queuedRun.userMessageId,
- );
- if (queuedMessage === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Queued run ${queuedRun.id} has no user message.`,
- });
- }
- if (
- queuedMessage.delegatedCompletion !== undefined ||
- queuedMessage.notification !== undefined
- ) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "Automatic completion deliveries cannot be edited.",
- });
- }
- const queuedTurnItem = projection.turnItems.find(
- (candidate) =>
- candidate.type === "user_message" && candidate.messageId === queuedMessage.id,
- );
+ ) {
+ if (command.text.trim().length === 0) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Queued run ${command.runId} cannot be edited to an empty message.`,
+ });
+ }
+ const projection = yield* projectionStore
+ .getThreadRecords(command.threadId, ["runs", "messages", "turnItems"], {
+ turnItemTypes: ["user_message"],
+ messageRoles: ["user"],
+ })
+ .pipe(Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })));
+ const queuedRun = projection.runs.find((candidate) => candidate.id === command.runId);
+ if (queuedRun === undefined || queuedRun.status !== "queued") {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Run ${command.runId} is not queued.`,
+ });
+ }
+ const queuedMessage = projection.messages.find(
+ (candidate) => candidate.id === queuedRun.userMessageId,
+ );
+ if (queuedMessage === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Queued run ${queuedRun.id} has no user message.`,
+ });
+ }
+ if (
+ queuedMessage.delegatedCompletion !== undefined ||
+ queuedMessage.notification !== undefined
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Automatic completion deliveries cannot be edited.",
+ });
+ }
+ const queuedTurnItem = projection.turnItems.find(
+ (candidate) => candidate.type === "user_message" && candidate.messageId === queuedMessage.id,
+ );
- const now = yield* DateTime.now;
- const emitEvent = emit(events, command);
- const editedAttachments =
- command.attachments === undefined ? {} : { attachments: command.attachments };
+ const now = yield* DateTime.now;
+ const emitEvent = emit(events, command);
+ const editedAttachments =
+ command.attachments === undefined ? {} : { attachments: command.attachments };
+ yield* emitEvent({
+ type: "message.updated",
+ threadId: command.threadId,
+ runId: queuedRun.id,
+ ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),
+ providerInstanceId: queuedRun.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...queuedMessage,
+ text: command.text,
+ ...editedAttachments,
+ ...(command.context ? { context: command.context } : {}),
+ updatedAt: now,
+ },
+ });
+ if (queuedTurnItem !== undefined && queuedTurnItem.type === "user_message") {
yield* emitEvent({
- type: "message.updated",
+ type: "turn-item.updated",
threadId: command.threadId,
runId: queuedRun.id,
...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),
providerInstanceId: queuedRun.providerInstanceId,
occurredAt: now,
payload: {
- ...queuedMessage,
+ ...queuedTurnItem,
text: command.text,
...editedAttachments,
...(command.context ? { context: command.context } : {}),
updatedAt: now,
},
});
- if (queuedTurnItem !== undefined && queuedTurnItem.type === "user_message") {
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId: queuedRun.id,
- ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),
- providerInstanceId: queuedRun.providerInstanceId,
- occurredAt: now,
- payload: {
- ...queuedTurnItem,
- text: command.text,
- ...editedAttachments,
- ...(command.context ? { context: command.context } : {}),
- updatedAt: now,
- },
- });
- }
- });
+ }
+ });
const loadProjectionForCommand = <K extends ProjectionRecordField>(
command: OrchestrationV2Command,
@@ -8228,11 +8208,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return { run, attempt, rootNode, providerThread, preparationItem } as const;
};
- const dispatchPreparedRunProgress = (
- command: Extract<OrchestrationV2Command, { readonly type: "prepared-run.progress" }>,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- ) =>
- Effect.gen(function* () {
+ const dispatchPreparedRunProgress = Effect.fn("Orchestrator.dispatchPreparedRunProgress")(
+ function* (
+ command: Extract<OrchestrationV2Command, { readonly type: "prepared-run.progress" }>,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ ) {
const projection = yield* loadProjectionForCommand(
command,
["runs", "attempts", "nodes", "providerThreads", "turnItems"],
@@ -8263,14 +8243,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
updatedAt: now,
},
});
- });
+ },
+ );
- const dispatchPreparedRunRelease = (
- command: Extract<OrchestrationV2Command, { readonly type: "prepared-run.release" }>,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
+ const dispatchPreparedRunRelease = Effect.fn("Orchestrator.dispatchPreparedRunRelease")(
+ function* (
+ command: Extract<OrchestrationV2Command, { readonly type: "prepared-run.release" }>,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
+ ) {
const projection = yield* loadProjectionForCommand(
command,
["runs", "attempts", "nodes", "providerThreads", "turnItems"],
@@ -8352,200 +8333,199 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
request: { type: "provider-turn.start", runId: state.run.id },
} satisfies PendingOrchestrationEffectV2,
]);
- });
+ },
+ );
- const dispatchPreparedRunFail = (
+ const dispatchPreparedRunFail = Effect.fn("Orchestrator.dispatchPreparedRunFail")(function* (
command: Extract<OrchestrationV2Command, { readonly type: "prepared-run.fail" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- ) =>
- Effect.gen(function* () {
- const projection = yield* loadProjectionForCommand(
- command,
- ["runs", "attempts", "nodes", "providerThreads", "turnItems"],
- { turnItemTypes: ["command_execution"], turnItemRunId: command.runId },
- );
- const state = preparedRunState(command, projection);
- if (state === null) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Run ${command.runId} is not awaiting workspace preparation.`,
- });
- }
- const now = yield* DateTime.now;
- const emitEvent = emit(events, command);
- yield* emitEvent({
- type: "run-attempt.updated",
- threadId: command.threadId,
- runId: state.run.id,
- nodeId: state.rootNode.id,
- providerInstanceId: state.run.providerInstanceId,
- occurredAt: now,
- payload: { ...state.attempt, status: "failed", completedAt: now },
- });
- yield* emitEvent({
- type: "node.updated",
- threadId: command.threadId,
- runId: state.run.id,
- nodeId: state.rootNode.id,
- providerInstanceId: state.run.providerInstanceId,
- occurredAt: now,
- payload: { ...state.rootNode, status: "failed", completedAt: now },
- });
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId: state.run.id,
- nodeId: state.rootNode.id,
- providerInstanceId: state.run.providerInstanceId,
- occurredAt: now,
- payload: {
- ...state.preparationItem,
- status: "failed",
- title: "Workspace preparation failed",
- output: command.failure.message,
- exitCode: 1,
- completedAt: now,
- updatedAt: now,
- },
- });
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId: state.run.id,
- nodeId: state.rootNode.id,
- providerInstanceId: state.run.providerInstanceId,
- occurredAt: now,
- payload: {
- id: idAllocator.derive.turnItemFromProviderItem({
- driver: state.providerThread.driver,
- nativeItemId: `workspace-preparation-failure:${state.run.id}`,
- }),
- threadId: command.threadId,
- runId: state.run.id,
- nodeId: state.rootNode.id,
- providerThreadId: state.providerThread.id,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: yield* nextTurnItemOrdinal(projection),
- status: "failed",
- title: "Workspace preparation failed",
- startedAt: now,
- completedAt: now,
- updatedAt: now,
- type: "error",
- failure: {
- ...command.failure,
- code: ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
- },
- },
+ ) {
+ const projection = yield* loadProjectionForCommand(
+ command,
+ ["runs", "attempts", "nodes", "providerThreads", "turnItems"],
+ { turnItemTypes: ["command_execution"], turnItemRunId: command.runId },
+ );
+ const state = preparedRunState(command, projection);
+ if (state === null) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Run ${command.runId} is not awaiting workspace preparation.`,
});
- yield* emitEvent({
- type: "run.updated",
+ }
+ const now = yield* DateTime.now;
+ const emitEvent = emit(events, command);
+ yield* emitEvent({
+ type: "run-attempt.updated",
+ threadId: command.threadId,
+ runId: state.run.id,
+ nodeId: state.rootNode.id,
+ providerInstanceId: state.run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...state.attempt, status: "failed", completedAt: now },
+ });
+ yield* emitEvent({
+ type: "node.updated",
+ threadId: command.threadId,
+ runId: state.run.id,
+ nodeId: state.rootNode.id,
+ providerInstanceId: state.run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...state.rootNode, status: "failed", completedAt: now },
+ });
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ runId: state.run.id,
+ nodeId: state.rootNode.id,
+ providerInstanceId: state.run.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ ...state.preparationItem,
+ status: "failed",
+ title: "Workspace preparation failed",
+ output: command.failure.message,
+ exitCode: 1,
+ completedAt: now,
+ updatedAt: now,
+ },
+ });
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ runId: state.run.id,
+ nodeId: state.rootNode.id,
+ providerInstanceId: state.run.providerInstanceId,
+ occurredAt: now,
+ payload: {
+ id: idAllocator.derive.turnItemFromProviderItem({
+ driver: state.providerThread.driver,
+ nativeItemId: `workspace-preparation-failure:${state.run.id}`,
+ }),
threadId: command.threadId,
runId: state.run.id,
nodeId: state.rootNode.id,
- providerInstanceId: state.run.providerInstanceId,
- occurredAt: now,
- payload: { ...state.run, status: "failed", completedAt: now },
- });
+ providerThreadId: state.providerThread.id,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: yield* nextTurnItemOrdinal(projection),
+ status: "failed",
+ title: "Workspace preparation failed",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "error",
+ failure: {
+ ...command.failure,
+ code: ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
+ },
+ },
+ });
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: command.threadId,
+ runId: state.run.id,
+ nodeId: state.rootNode.id,
+ providerInstanceId: state.run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...state.run, status: "failed", completedAt: now },
});
+ });
- const dispatchPreparedRunRetry = (
+ const dispatchPreparedRunRetry = Effect.fn("Orchestrator.dispatchPreparedRunRetry")(function* (
command: Extract<OrchestrationV2Command, { readonly type: "prepared-run.retry" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- ) =>
- Effect.gen(function* () {
- const projection = yield* loadProjectionForCommand(
- command,
- ["runs", "attempts", "nodes", "providerThreads", "turnItems"],
- { turnItemTypes: ["command_execution", "error"], turnItemRunId: command.runId },
- );
- const state = preparedRunState(command, projection);
- const failureItem = projection.turnItems.find(
- (candidate): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "error" }> =>
- candidate.type === "error" &&
- candidate.status === "failed" &&
- candidate.failure.code === ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
- );
- if (
- state === null ||
- state.run.workspacePreparation === undefined ||
- failureItem === undefined ||
- projection.thread.archivedAt !== null ||
- projection.thread.deletedAt !== null
- ) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Run ${command.runId} has no failed workspace preparation to retry.`,
- });
- }
- if (projection.runs.some((run) => run.id !== state.run.id && isBlockingRun(run))) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "Another run is active on this thread.",
- });
- }
- const now = yield* DateTime.now;
- const emitEvent = emit(events, command);
- const scope = {
- threadId: command.threadId,
- runId: state.run.id,
- nodeId: state.rootNode.id,
- providerInstanceId: state.run.providerInstanceId,
- occurredAt: now,
- };
- yield* emitEvent({
- ...scope,
- type: "turn-item.updated",
- payload: { ...failureItem, status: "cancelled", updatedAt: now },
- });
- yield* emitEvent({
- ...scope,
- type: "turn-item.updated",
- payload: {
- ...withoutPreparationResult(state.preparationItem),
- status: "running",
- title: WORKSPACE_PREPARATION_INPUT,
- completedAt: null,
- updatedAt: now,
- },
- });
- yield* emitEvent({
- ...scope,
- type: "run-attempt.updated",
- payload: { ...state.attempt, status: "pending", completedAt: null },
+ ) {
+ const projection = yield* loadProjectionForCommand(
+ command,
+ ["runs", "attempts", "nodes", "providerThreads", "turnItems"],
+ { turnItemTypes: ["command_execution", "error"], turnItemRunId: command.runId },
+ );
+ const state = preparedRunState(command, projection);
+ const failureItem = projection.turnItems.find(
+ (candidate): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "error" }> =>
+ candidate.type === "error" &&
+ candidate.status === "failed" &&
+ candidate.failure.code === ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
+ );
+ if (
+ state === null ||
+ state.run.workspacePreparation === undefined ||
+ failureItem === undefined ||
+ projection.thread.archivedAt !== null ||
+ projection.thread.deletedAt !== null
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Run ${command.runId} has no failed workspace preparation to retry.`,
});
- yield* emitEvent({
- ...scope,
- type: "node.updated",
- payload: { ...state.rootNode, status: "pending", completedAt: null },
+ }
+ if (projection.runs.some((run) => run.id !== state.run.id && isBlockingRun(run))) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "Another run is active on this thread.",
});
+ }
+ const now = yield* DateTime.now;
+ const emitEvent = emit(events, command);
+ const scope = {
+ threadId: command.threadId,
+ runId: state.run.id,
+ nodeId: state.rootNode.id,
+ providerInstanceId: state.run.providerInstanceId,
+ occurredAt: now,
+ };
+ yield* emitEvent({
+ ...scope,
+ type: "turn-item.updated",
+ payload: { ...failureItem, status: "cancelled", updatedAt: now },
+ });
+ yield* emitEvent({
+ ...scope,
+ type: "turn-item.updated",
+ payload: {
+ ...withoutPreparationResult(state.preparationItem),
+ status: "running",
+ title: WORKSPACE_PREPARATION_INPUT,
+ completedAt: null,
+ updatedAt: now,
+ },
+ });
+ yield* emitEvent({
+ ...scope,
+ type: "run-attempt.updated",
+ payload: { ...state.attempt, status: "pending", completedAt: null },
+ });
+ yield* emitEvent({
+ ...scope,
+ type: "node.updated",
+ payload: { ...state.rootNode, status: "pending", completedAt: null },
+ });
+ yield* emitEvent({
+ ...scope,
+ type: "run.updated",
+ payload: { ...state.run, status: "preparing", completedAt: null },
+ });
+ // Messages held when this preparation failed follow the run again. A hold
+ // from a later run (a stop, say) is not this failure's to release.
+ const failureOwnsQueue = latestExecutedRun(projection.runs)?.id === state.run.id;
+ for (const run of projection.runs) {
+ if (!failureOwnsQueue || run.status !== "queued" || run.queueHeld !== true) continue;
yield* emitEvent({
- ...scope,
type: "run.updated",
- payload: { ...state.run, status: "preparing", completedAt: null },
+ threadId: command.threadId,
+ runId: run.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...run, queueHeld: false },
});
- // Messages held when this preparation failed follow the run again. A hold
- // from a later run (a stop, say) is not this failure's to release.
- const failureOwnsQueue = latestExecutedRun(projection.runs)?.id === state.run.id;
- for (const run of projection.runs) {
- if (!failureOwnsQueue || run.status !== "queued" || run.queueHeld !== true) continue;
- yield* emitEvent({
- type: "run.updated",
- threadId: command.threadId,
- runId: run.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: now,
- payload: { ...run, queueHeld: false },
- });
- }
- });
+ }
+ });
- const settleBackgroundWork = (input: {
+ const settleBackgroundWork = Effect.fn("Orchestrator.settleBackgroundWork")(function* (input: {
readonly command: Extract<
OrchestrationV2ServerCommand,
{ readonly type: "run.interrupt" | "thread.background-work.settle" }
@@ -8558,187 +8538,182 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly stoppedProviderThreadId: OrchestrationV2ProviderThread["id"] | null;
readonly throughRunOrdinal: number;
readonly now: DateTime.Utc;
- }) =>
- Effect.gen(function* () {
- const emitEvent = emit(input.events, input.command);
- const runOrdinals = new Map(input.projection.runs.map((run) => [run.id, run.ordinal]));
- const allocateEventId = () =>
- idAllocator.allocate.event({
- threadId: input.command.threadId,
- commandId: input.command.commandId,
- });
- const childThreadIds = new Set<ThreadId>();
- const liveness = new Map<string, boolean>();
- const hasLiveSession = (providerThreadId: OrchestrationV2ProviderThread["id"]) =>
- Effect.gen(function* () {
- const known = liveness.get(providerThreadId);
- if (known !== undefined) return known;
- const sessionId = input.projection.providerThreads.find(
- (candidate) => candidate.id === providerThreadId,
- )?.providerSessionId;
- const live =
- sessionId !== null &&
- sessionId !== undefined &&
- Option.isSome(
- yield* providerSessions
- .get(sessionId)
- .pipe(Effect.orElseSucceed(() => Option.none())),
- );
- liveness.set(providerThreadId, live);
- return live;
- });
- const stillReportsBackgroundWork = Effect.fnUntraced(function* (
- providerThread: OrchestrationV2ProviderThread,
+ }) {
+ const emitEvent = emit(input.events, input.command);
+ const runOrdinals = new Map(input.projection.runs.map((run) => [run.id, run.ordinal]));
+ const allocateEventId = () =>
+ idAllocator.allocate.event({
+ threadId: input.command.threadId,
+ commandId: input.command.commandId,
+ });
+ const childThreadIds = new Set<ThreadId>();
+ const liveness = new Map<string, boolean>();
+ const hasLiveSession = Effect.fn("Orchestrator.hasLiveSession")(function* (
+ providerThreadId: OrchestrationV2ProviderThread["id"],
+ ) {
+ const known = liveness.get(providerThreadId);
+ if (known !== undefined) return known;
+ const sessionId = input.projection.providerThreads.find(
+ (candidate) => candidate.id === providerThreadId,
+ )?.providerSessionId;
+ const live =
+ sessionId !== null &&
+ sessionId !== undefined &&
+ Option.isSome(
+ yield* providerSessions.get(sessionId).pipe(Effect.orElseSucceed(() => Option.none())),
+ );
+ liveness.set(providerThreadId, live);
+ return live;
+ });
+ const stillReportsBackgroundWork = Effect.fnUntraced(function* (
+ providerThread: OrchestrationV2ProviderThread,
+ ) {
+ if (providerThread.providerSessionId == null) return false;
+ const session = yield* providerSessions
+ .get(providerThread.providerSessionId)
+ .pipe(Effect.orElseSucceed(() => Option.none()));
+ if (Option.isNone(session) || session.value.hasPendingBackgroundWorkForThread === undefined) {
+ return false;
+ }
+ return yield* session.value
+ .hasPendingBackgroundWorkForThread(providerThread)
+ // A failed probe cannot confirm that the work ended.
+ .pipe(Effect.catchCause(() => Effect.succeed(true)));
+ });
+ for (const item of pendingBackgroundTurnItems({
+ turnItems: input.projection.turnItems,
+ runs: input.projection.runs,
+ })) {
+ const itemRunOrdinal = item.runId === null ? undefined : runOrdinals.get(item.runId);
+ if (itemRunOrdinal !== undefined && itemRunOrdinal > input.throughRunOrdinal) continue;
+ const providerThreadId = item.providerThreadId ?? null;
+ if (
+ providerThreadId !== null &&
+ providerThreadId !== input.stoppedProviderThreadId &&
+ (yield* hasLiveSession(providerThreadId))
) {
- if (providerThread.providerSessionId == null) return false;
- const session = yield* providerSessions
- .get(providerThread.providerSessionId)
- .pipe(Effect.orElseSucceed(() => Option.none()));
- if (
- Option.isNone(session) ||
- session.value.hasPendingBackgroundWorkForThread === undefined
- ) {
- return false;
- }
- return yield* session.value
- .hasPendingBackgroundWorkForThread(providerThread)
- // A failed probe cannot confirm that the work ended.
- .pipe(Effect.catchCause(() => Effect.succeed(true)));
+ continue;
+ }
+ const run = input.projection.runs.find((candidate) => candidate.id === item.runId);
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: input.command.threadId,
+ ...(item.runId === null ? {} : { runId: item.runId }),
+ ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
+ ...(run === undefined ? {} : { providerInstanceId: run.providerInstanceId }),
+ occurredAt: input.now,
+ payload: {
+ ...item,
+ status: "interrupted",
+ completedAt: input.now,
+ updatedAt: input.now,
+ },
});
- for (const item of pendingBackgroundTurnItems({
- turnItems: input.projection.turnItems,
- runs: input.projection.runs,
- })) {
- const itemRunOrdinal = item.runId === null ? undefined : runOrdinals.get(item.runId);
- if (itemRunOrdinal !== undefined && itemRunOrdinal > input.throughRunOrdinal) continue;
- const providerThreadId = item.providerThreadId ?? null;
+ if (item.type !== "subagent") continue;
+ // A native subagent died with the process too: end its record, its own
+ // thread's runless root turn, and the subagents it started there, which
+ // a provider can record on that thread rather than this one.
+ const dying: Array<{
+ readonly projection: Pick<
+ OrchestrationV2ThreadProjection,
+ "nodes" | "subagents" | "turnItems"
+ >;
+ readonly subagent: Pick<
+ Extract<OrchestrationV2TurnItem, { readonly type: "subagent" }>,
+ "subagentId" | "origin" | "childThreadId" | "providerInstanceId"
+ >;
+ }> = [{ projection: input.projection, subagent: item }];
+ for (const { projection, subagent } of dying) {
+ const ended = yield* endOrphanedNativeSubagent({
+ projection,
+ subagentId: subagent.subagentId,
+ status: "interrupted",
+ now: input.now,
+ emitted: yield* Ref.get(input.events),
+ allocateEventId,
+ }).pipe(mapDispatchError(input.command));
+ yield* Ref.update(input.events, (events) => [...events, ...ended]);
+ const childThreadId = subagent.childThreadId;
if (
- providerThreadId !== null &&
- providerThreadId !== input.stoppedProviderThreadId &&
- (yield* hasLiveSession(providerThreadId))
+ subagent.origin !== "provider_native" ||
+ childThreadId === null ||
+ childThreadIds.has(childThreadId)
) {
continue;
}
- const run = input.projection.runs.find((candidate) => candidate.id === item.runId);
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: input.command.threadId,
- ...(item.runId === null ? {} : { runId: item.runId }),
- ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
- ...(run === undefined ? {} : { providerInstanceId: run.providerInstanceId }),
- occurredAt: input.now,
- payload: {
- ...item,
- status: "interrupted",
- completedAt: input.now,
- updatedAt: input.now,
- },
- });
- if (item.type !== "subagent") continue;
- // A native subagent died with the process too: end its record, its own
- // thread's runless root turn, and the subagents it started there, which
- // a provider can record on that thread rather than this one.
- const dying: Array<{
- readonly projection: Pick<
- OrchestrationV2ThreadProjection,
- "nodes" | "subagents" | "turnItems"
- >;
- readonly subagent: Pick<
- Extract<OrchestrationV2TurnItem, { readonly type: "subagent" }>,
- "subagentId" | "origin" | "childThreadId" | "providerInstanceId"
- >;
- }> = [{ projection: input.projection, subagent: item }];
- for (const { projection, subagent } of dying) {
- const ended = yield* endOrphanedNativeSubagent({
- projection,
- subagentId: subagent.subagentId,
- status: "interrupted",
- now: input.now,
- emitted: yield* Ref.get(input.events),
- allocateEventId,
- }).pipe(mapDispatchError(input.command));
- yield* Ref.update(input.events, (events) => [...events, ...ended]);
- const childThreadId = subagent.childThreadId;
- if (
- subagent.origin !== "provider_native" ||
- childThreadId === null ||
- childThreadIds.has(childThreadId)
- ) {
- continue;
- }
- childThreadIds.add(childThreadId);
- const child = yield* projectionStore
- .getThreadRecords(childThreadId, ["nodes", "subagents", "turnItems"], {
- // Runless items are the subagent's; any run there is the user's own.
- turnItemRunIds: [null],
- turnItemStatuses: ["pending", "running", "waiting"],
- })
- .pipe(
- Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
- mapDispatchError(input.command),
- );
- if (child === null) continue;
- const childEnded = yield* endRunlessRootTurns({
- threadId: childThreadId,
- providerInstanceId: subagent.providerInstanceId,
- projection: child,
- status: "interrupted",
- now: input.now,
- emitted: yield* Ref.get(input.events),
- allocateEventId,
- }).pipe(mapDispatchError(input.command));
- yield* Ref.update(input.events, (events) => [...events, ...childEnded]);
- for (const nested of child.turnItems) {
- if (nested.type === "subagent") dying.push({ projection: child, subagent: nested });
- }
- for (const nested of child.subagents) {
- if (nested.origin === "provider_native" && nested.runId === null) {
- dying.push({
- projection: child,
- subagent: {
- subagentId: nested.id,
- origin: nested.origin,
- childThreadId: nested.childThreadId,
- providerInstanceId: nested.providerInstanceId,
- },
- });
- }
+ childThreadIds.add(childThreadId);
+ const child = yield* projectionStore
+ .getThreadRecords(childThreadId, ["nodes", "subagents", "turnItems"], {
+ // Runless items are the subagent's; any run there is the user's own.
+ turnItemRunIds: [null],
+ turnItemStatuses: ["pending", "running", "waiting"],
+ })
+ .pipe(
+ Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
+ mapDispatchError(input.command),
+ );
+ if (child === null) continue;
+ const childEnded = yield* endRunlessRootTurns({
+ threadId: childThreadId,
+ providerInstanceId: subagent.providerInstanceId,
+ projection: child,
+ status: "interrupted",
+ now: input.now,
+ emitted: yield* Ref.get(input.events),
+ allocateEventId,
+ }).pipe(mapDispatchError(input.command));
+ yield* Ref.update(input.events, (events) => [...events, ...childEnded]);
+ for (const nested of child.turnItems) {
+ if (nested.type === "subagent") dying.push({ projection: child, subagent: nested });
+ }
+ for (const nested of child.subagents) {
+ if (nested.origin === "provider_native" && nested.runId === null) {
+ dying.push({
+ projection: child,
+ subagent: {
+ subagentId: nested.id,
+ origin: nested.origin,
+ childThreadId: nested.childThreadId,
+ providerInstanceId: nested.providerInstanceId,
+ },
+ });
}
}
}
- for (const providerThread of input.projection.providerThreads) {
- if ((providerThread.pendingBackgroundTasks?.length ?? 0) === 0) continue;
- if (providerThread.id === input.stoppedProviderThreadId) {
- // A refused newer start can take ownership and reject the stopped
- // turn's roster clear. Reconcile it without hiding surviving work.
- if (yield* stillReportsBackgroundWork(providerThread)) continue;
- } else if (yield* hasLiveSession(providerThread.id)) {
- continue;
- }
- yield* emitEvent({
- type: "provider-thread.updated",
- threadId: input.command.threadId,
- driver: providerThread.driver,
- providerInstanceId: providerThread.providerInstanceId,
- occurredAt: input.now,
- payload: {
- ...providerThread,
- status:
- providerThread.status === "active" &&
- providerThread.lastRunOrdinal !== null &&
- providerThread.lastRunOrdinal <= input.throughRunOrdinal
- ? "idle"
- : providerThread.status,
- pendingBackgroundTasks: [],
- updatedAt: input.now,
- },
- });
+ }
+ for (const providerThread of input.projection.providerThreads) {
+ if ((providerThread.pendingBackgroundTasks?.length ?? 0) === 0) continue;
+ if (providerThread.id === input.stoppedProviderThreadId) {
+ // A refused newer start can take ownership and reject the stopped
+ // turn's roster clear. Reconcile it without hiding surviving work.
+ if (yield* stillReportsBackgroundWork(providerThread)) continue;
+ } else if (yield* hasLiveSession(providerThread.id)) {
+ continue;
}
- });
+ yield* emitEvent({
+ type: "provider-thread.updated",
+ threadId: input.command.threadId,
+ driver: providerThread.driver,
+ providerInstanceId: providerThread.providerInstanceId,
+ occurredAt: input.now,
+ payload: {
+ ...providerThread,
+ status:
+ providerThread.status === "active" &&
+ providerThread.lastRunOrdinal !== null &&
+ providerThread.lastRunOrdinal <= input.throughRunOrdinal
+ ? "idle"
+ : providerThread.status,
+ pendingBackgroundTasks: [],
+ updatedAt: input.now,
+ },
+ });
+ }
+ });
// A successful Stop may have no terminal event to ingest: the session or
// native turn already died, or its final write failed when storage filled.
- const settleInterruptedRun = (input: {
+ const settleInterruptedRun = Effect.fn("Orchestrator.settleInterruptedRun")(function* (input: {
readonly command: Extract<
OrchestrationV2ServerCommand,
{ readonly type: "run.interrupt" | "thread.background-work.settle" }
@@ -8746,180 +8721,177 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly projection: Pick<
OrchestrationV2ThreadProjection,
| "runs"
- | "attempts"
- | "nodes"
- | "subagents"
- | "runtimeRequests"
- | "messages"
- | "turnItems"
- | "providerThreads"
- >;
- readonly providerTurn: OrchestrationV2ProviderTurn;
- readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
- readonly effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>;
- readonly now: DateTime.Utc;
- }) =>
- Effect.gen(function* () {
- const attempt = input.projection.attempts.find(
- (candidate) => candidate.id === input.providerTurn.runAttemptId,
- );
- const run = input.projection.runs.find((candidate) => candidate.id === attempt?.runId);
- const rootNode = input.projection.nodes.find((candidate) => candidate.id === run?.rootNodeId);
- if (
- attempt === undefined ||
- run === undefined ||
- rootNode === undefined ||
- run.activeAttemptId !== attempt.id ||
- run.status !== "running" ||
- attempt.status !== "running"
- )
- return;
- const emitEvent = emit(input.events, input.command);
- const base = {
- threadId: input.command.threadId,
- runId: run.id,
- nodeId: rootNode.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: input.now,
- };
- if (input.providerTurn.status === "running") {
- yield* emitEvent({
- ...base,
- type: "provider-turn.updated",
- payload: {
- ...input.providerTurn,
- status: "interrupted",
- completedAt: input.now,
- },
- });
- }
+ | "attempts"
+ | "nodes"
+ | "subagents"
+ | "runtimeRequests"
+ | "messages"
+ | "turnItems"
+ | "providerThreads"
+ >;
+ readonly providerTurn: OrchestrationV2ProviderTurn;
+ readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
+ readonly effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>;
+ readonly now: DateTime.Utc;
+ }) {
+ const attempt = input.projection.attempts.find(
+ (candidate) => candidate.id === input.providerTurn.runAttemptId,
+ );
+ const run = input.projection.runs.find((candidate) => candidate.id === attempt?.runId);
+ const rootNode = input.projection.nodes.find((candidate) => candidate.id === run?.rootNodeId);
+ if (
+ attempt === undefined ||
+ run === undefined ||
+ rootNode === undefined ||
+ run.activeAttemptId !== attempt.id ||
+ run.status !== "running" ||
+ attempt.status !== "running"
+ )
+ return;
+ const emitEvent = emit(input.events, input.command);
+ const base = {
+ threadId: input.command.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: input.now,
+ };
+ if (input.providerTurn.status === "running") {
yield* emitEvent({
...base,
- type: "run-attempt.updated",
+ type: "provider-turn.updated",
payload: {
- ...attempt,
+ ...input.providerTurn,
status: "interrupted",
completedAt: input.now,
},
});
- const providerThread = input.projection.providerThreads.find(
- (candidate) => candidate.id === input.providerTurn.providerThreadId,
- );
- if (providerThread?.status === "active" && providerThread.lastRunOrdinal === run.ordinal) {
- yield* emitEvent({
- ...base,
- type: "provider-thread.updated",
- payload: { ...providerThread, status: "idle", updatedAt: input.now },
- });
- }
- for (const message of input.projection.messages) {
- if (message.runId !== run.id || !message.streaming) continue;
- yield* emitEvent({
- ...base,
- ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
- type: "message.updated",
- payload: { ...message, streaming: false, updatedAt: input.now },
- });
- }
- const delegatedNodeIds = new Set(
- input.projection.subagents
- .filter((subagent) => subagent.origin === "app_owned")
- .map((subagent) => subagent.id),
- );
- const cascaded = yield* RunExecutionService.cascadeTerminalizeRunOwnedSubagents({
- run,
+ }
+ yield* emitEvent({
+ ...base,
+ type: "run-attempt.updated",
+ payload: {
+ ...attempt,
status: "interrupted",
completedAt: input.now,
- allocateEventId: () =>
- idAllocator.allocate.event({
- threadId: input.command.threadId,
- commandId: input.command.commandId,
- }),
- open: {
- subagents: new Map(
- input.projection.subagents
- .filter((task) => task.runId === run.id && task.origin !== "app_owned")
- .map((task) => [task.id, task]),
- ),
- nodes: new Map(
- input.projection.nodes
- .filter((node) => node.runId === run.id && !delegatedNodeIds.has(node.id))
- .map((node) => [node.id, node]),
- ),
- turnItems: new Map(),
- childTurnItems: new Map(
- input.projection.turnItems
- .filter(
- (item) =>
- item.runId === run.id &&
- (item.type === "assistant_message" || item.type === "reasoning"),
- )
- .map((item) => [item.id, item]),
- ),
- linkedChildThreadIds: new Set([run.threadId]),
- },
- }).pipe(mapDispatchError(input.command));
- yield* Ref.update(input.events, (events) => [...events, ...cascaded]);
- for (const request of input.projection.runtimeRequests) {
- if (
- request.status !== "pending" ||
- !input.projection.nodes.some(
- (node) => node.id === request.nodeId && node.runId === run.id,
- )
- )
- continue;
- yield* emitEvent({
- ...base,
- nodeId: request.nodeId,
- type: "runtime-request.updated",
- payload: {
- ...request,
- status: "cancelled",
- resolvedAt: input.now,
- responseCapability: { type: "not_resumable", reason: "The run was interrupted." },
- },
- });
- }
- if (providerThread !== undefined) {
- yield* emitEvent({
- ...base,
- type: "turn-item.updated",
- payload: RunExecutionService.makeInterruptResultTurnItem({
- idAllocator,
- run,
- rootNode,
- providerThread,
- completedAt: input.now,
- }),
- });
- }
- const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
+ },
+ });
+ const providerThread = input.projection.providerThreads.find(
+ (candidate) => candidate.id === input.providerTurn.providerThreadId,
+ );
+ if (providerThread?.status === "active" && providerThread.lastRunOrdinal === run.ordinal) {
yield* emitEvent({
...base,
- type: "run.updated",
+ type: "provider-thread.updated",
+ payload: { ...providerThread, status: "idle", updatedAt: input.now },
+ });
+ }
+ for (const message of input.projection.messages) {
+ if (message.runId !== run.id || !message.streaming) continue;
+ yield* emitEvent({
+ ...base,
+ ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
+ type: "message.updated",
+ payload: { ...message, streaming: false, updatedAt: input.now },
+ });
+ }
+ const delegatedNodeIds = new Set(
+ input.projection.subagents
+ .filter((subagent) => subagent.origin === "app_owned")
+ .map((subagent) => subagent.id),
+ );
+ const cascaded = yield* RunExecutionService.cascadeTerminalizeRunOwnedSubagents({
+ run,
+ status: "interrupted",
+ completedAt: input.now,
+ allocateEventId: () =>
+ idAllocator.allocate.event({
+ threadId: input.command.threadId,
+ commandId: input.command.commandId,
+ }),
+ open: {
+ subagents: new Map(
+ input.projection.subagents
+ .filter((task) => task.runId === run.id && task.origin !== "app_owned")
+ .map((task) => [task.id, task]),
+ ),
+ nodes: new Map(
+ input.projection.nodes
+ .filter((node) => node.runId === run.id && !delegatedNodeIds.has(node.id))
+ .map((node) => [node.id, node]),
+ ),
+ turnItems: new Map(),
+ childTurnItems: new Map(
+ input.projection.turnItems
+ .filter(
+ (item) =>
+ item.runId === run.id &&
+ (item.type === "assistant_message" || item.type === "reasoning"),
+ )
+ .map((item) => [item.id, item]),
+ ),
+ linkedChildThreadIds: new Set([run.threadId]),
+ },
+ }).pipe(mapDispatchError(input.command));
+ yield* Ref.update(input.events, (events) => [...events, ...cascaded]);
+ for (const request of input.projection.runtimeRequests) {
+ if (
+ request.status !== "pending" ||
+ !input.projection.nodes.some((node) => node.id === request.nodeId && node.runId === run.id)
+ )
+ continue;
+ yield* emitEvent({
+ ...base,
+ nodeId: request.nodeId,
+ type: "runtime-request.updated",
payload: {
- ...runWithoutDelegatedCompletion,
- status: "interrupted",
- completedAt: input.now,
+ ...request,
+ status: "cancelled",
+ resolvedAt: input.now,
+ responseCapability: { type: "not_resumable", reason: "The run was interrupted." },
},
});
- const scopeId = rootNode.checkpointScopeId;
- if (scopeId !== null) {
- yield* Ref.update(input.effects, (effects) => [
- ...effects,
- {
- id: `effect:checkpoint.capture:${run.id}`,
- commandId: CommandId.make(`command:effect:checkpoint.capture:${run.id}`),
- threadId: input.command.threadId,
- request: {
- type: "checkpoint.capture",
- runId: run.id,
- scopeId,
- },
- } satisfies PendingOrchestrationEffectV2,
- ]);
- }
+ }
+ if (providerThread !== undefined) {
+ yield* emitEvent({
+ ...base,
+ type: "turn-item.updated",
+ payload: RunExecutionService.makeInterruptResultTurnItem({
+ idAllocator,
+ run,
+ rootNode,
+ providerThread,
+ completedAt: input.now,
+ }),
+ });
+ }
+ const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run;
+ yield* emitEvent({
+ ...base,
+ type: "run.updated",
+ payload: {
+ ...runWithoutDelegatedCompletion,
+ status: "interrupted",
+ completedAt: input.now,
+ },
});
+ const scopeId = rootNode.checkpointScopeId;
+ if (scopeId !== null) {
+ yield* Ref.update(input.effects, (effects) => [
+ ...effects,
+ {
+ id: `effect:checkpoint.capture:${run.id}`,
+ commandId: CommandId.make(`command:effect:checkpoint.capture:${run.id}`),
+ threadId: input.command.threadId,
+ request: {
+ type: "checkpoint.capture",
+ runId: run.id,
+ scopeId,
+ },
+ } satisfies PendingOrchestrationEffectV2,
+ ]);
+ }
+ });
/**
* Its agent can call tools
@@ -8993,7 +8965,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
});
- const holdStoppedThread = (input: {
+ const holdStoppedThread = Effect.fn("Orchestrator.holdStoppedThread")(function* (input: {
readonly command: Extract<
OrchestrationV2ServerCommand,
{ readonly type: "run.interrupt" | "thread.stop" }
@@ -9002,109 +8974,108 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly projection: Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "subagents">;
readonly cohortRunIds: ReadonlyArray<RunId>;
readonly now: DateTime.Utc;
- }) =>
- Effect.gen(function* () {
- const emitEvent = emit(input.events, input.command);
- const { thread, runs, subagents } = input.projection;
- const queuedRuns = runs.filter((run) => run.status === "queued");
- const queuedMessages =
- queuedRuns.length === 0
- ? []
- : (yield* projectionStore
- .getThreadRecords(thread.id, ["messages"], {
- messageIds: queuedRuns.map((run) => run.userMessageId),
- })
- .pipe(
- Effect.mapError(
- (cause) => new OrchestratorProjectionError({ threadId: thread.id, cause }),
- ),
- )).messages;
- const bufferedMessageIds = new Set(
- queuedMessages.filter(isBufferedProviderNotification).map((message) => message.id),
- );
- for (const run of runs) {
- // A resumed queue can have a lower ordinal than a pending continuation source.
- // Stop must reach those sources even when interrupting the resumed run succeeds.
- if (
- run.status === "cancelled" &&
- (yield* awaitsRestartContinuation(run).pipe(mapDispatchError(input.command)))
- ) {
- yield* markStoppedRun({ ...input, thread, run });
- }
- if (run.status !== "queued") continue;
- if (bufferedMessageIds.has(run.userMessageId)) {
- yield* dispatchQueuedRunCancel(
- {
- type: "queued-run.cancel",
- commandId: input.command.commandId,
- threadId: thread.id,
- runId: run.id,
- },
- input.events,
- );
- continue;
- }
- if (run.queueHeld === true) continue;
- yield* emitEvent({
- type: "run.updated",
- threadId: thread.id,
- runId: run.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: input.now,
- payload: { ...run, queueHeld: true },
- });
+ }) {
+ const emitEvent = emit(input.events, input.command);
+ const { thread, runs, subagents } = input.projection;
+ const queuedRuns = runs.filter((run) => run.status === "queued");
+ const queuedMessages =
+ queuedRuns.length === 0
+ ? []
+ : (yield* projectionStore
+ .getThreadRecords(thread.id, ["messages"], {
+ messageIds: queuedRuns.map((run) => run.userMessageId),
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) => new OrchestratorProjectionError({ threadId: thread.id, cause }),
+ ),
+ )).messages;
+ const bufferedMessageIds = new Set(
+ queuedMessages.filter(isBufferedProviderNotification).map((message) => message.id),
+ );
+ for (const run of runs) {
+ // A resumed queue can have a lower ordinal than a pending continuation source.
+ // Stop must reach those sources even when interrupting the resumed run succeeds.
+ if (
+ run.status === "cancelled" &&
+ (yield* awaitsRestartContinuation(run).pipe(mapDispatchError(input.command)))
+ ) {
+ yield* markStoppedRun({ ...input, thread, run });
}
- const pullRequests = thread.pullRequests ?? [];
- if (pullRequests.some((link) => link.watch !== undefined)) {
- yield* emitEvent({
- type: "thread.pull-request-synced",
- threadId: thread.id,
- providerInstanceId: thread.providerInstanceId,
- occurredAt: input.now,
- payload: {
- ...thread,
- pullRequests: pullRequests.map((link) => withPullRequestWatch(link, undefined)),
+ if (run.status !== "queued") continue;
+ if (bufferedMessageIds.has(run.userMessageId)) {
+ yield* dispatchQueuedRunCancel(
+ {
+ type: "queued-run.cancel",
+ commandId: input.command.commandId,
+ threadId: thread.id,
+ runId: run.id,
},
- });
- }
- const cohortRunIds = new Set(input.cohortRunIds);
- for (const run of runs) {
- if (run.delegatedCompletion?.delivery != null) cohortRunIds.add(run.id);
- }
- for (const task of subagents) {
- const delivery = task.completionDelivery?.state;
- if (
- task.origin === "app_owned" &&
- task.runId !== null &&
- delivery !== "acknowledged" &&
- delivery !== "delivered" &&
- delivery !== "disposed"
- ) {
- cohortRunIds.add(task.runId);
- }
+ input.events,
+ );
+ continue;
}
- // Each disposal reads the events the ones before it wrote.
- for (const parentRunId of cohortRunIds) {
- yield* disposeDelegatedCompletionCohort({
- command: input.command,
- events: input.events,
- projection: yield* getProjectionWithPendingEvents(thread.id, input.events),
- parentRunId,
- disposition: "stopped",
- now: input.now,
- });
+ if (run.queueHeld === true) continue;
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: thread.id,
+ runId: run.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: input.now,
+ payload: { ...run, queueHeld: true },
+ });
+ }
+ const pullRequests = thread.pullRequests ?? [];
+ if (pullRequests.some((link) => link.watch !== undefined)) {
+ yield* emitEvent({
+ type: "thread.pull-request-synced",
+ threadId: thread.id,
+ providerInstanceId: thread.providerInstanceId,
+ occurredAt: input.now,
+ payload: {
+ ...thread,
+ pullRequests: pullRequests.map((link) => withPullRequestWatch(link, undefined)),
+ },
+ });
+ }
+ const cohortRunIds = new Set(input.cohortRunIds);
+ for (const run of runs) {
+ if (run.delegatedCompletion?.delivery != null) cohortRunIds.add(run.id);
+ }
+ for (const task of subagents) {
+ const delivery = task.completionDelivery?.state;
+ if (
+ task.origin === "app_owned" &&
+ task.runId !== null &&
+ delivery !== "acknowledged" &&
+ delivery !== "delivered" &&
+ delivery !== "disposed"
+ ) {
+ cohortRunIds.add(task.runId);
}
- });
+ }
+ // Each disposal reads the events the ones before it wrote.
+ for (const parentRunId of cohortRunIds) {
+ yield* disposeDelegatedCompletionCohort({
+ command: input.command,
+ events: input.events,
+ projection: yield* getProjectionWithPendingEvents(thread.id, input.events),
+ parentRunId,
+ disposition: "stopped",
+ now: input.now,
+ });
+ }
+ });
- const dispatchBackgroundWorkSettle = (
- command: Extract<
- OrchestrationV2InternalCommand,
- { readonly type: "thread.background-work.settle" }
- >,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
+ const dispatchBackgroundWorkSettle = Effect.fn("Orchestrator.dispatchBackgroundWorkSettle")(
+ function* (
+ command: Extract<
+ OrchestrationV2InternalCommand,
+ { readonly type: "thread.background-work.settle" }
+ >,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
+ ) {
const [projection, stopped] = yield* Effect.all([
projectionStore.getThreadRecords(
command.threadId,
@@ -9224,417 +9195,333 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
(run) =>
run.id !== stoppedRun.id &&
(run.status === "preparing" || run.status === "starting" || run.status === "running"),
- )
- ) {
- return;
- }
- yield* settleBackgroundWork({
- command,
- events,
- projection,
- stoppedProviderThreadId: command.providerThreadId,
- throughRunOrdinal: stoppedRun.ordinal,
- now,
- });
- });
-
- const dispatchSubagentStop = (
- command: Extract<OrchestrationV2Command, { readonly type: "subagent.stop" }>,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
- const projection = yield* loadProjectionForCommand(command, [
- "runs",
- "subagents",
- "providerThreads",
- "providerTurns",
- ]);
- const run = projection.runs.find((candidate) => candidate.id === command.runId);
- const subagent = projection.subagents.find(
- (candidate) => candidate.id === command.subagentId,
- );
- if (
- subagent === undefined ||
- subagent.runId !== command.runId ||
- subagent.origin !== "provider_native" ||
- subagent.driver !== "claudeAgent" ||
- subagent.nativeTaskRef?.strength !== "strong" ||
- subagent.nativeTaskRef.nativeId === null
- ) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "The requested native subagent cannot be stopped on this run.",
- });
- }
- if (!["pending", "running", "waiting"].includes(subagent.status)) return;
- const providerThread = projection.providerThreads.find(
- (candidate) => candidate.id === run?.providerThreadId,
- );
- const providerTurn = projection.providerTurns.findLast(
- (candidate) => candidate.providerThreadId === providerThread?.id,
- );
- if (
- providerThread?.providerSessionId == null ||
- providerTurn === undefined ||
- providerThread.driver !== subagent.driver ||
- providerThread.providerInstanceId !== subagent.providerInstanceId
- ) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: "The requested native subagent has no owning provider session.",
- });
+ )
+ ) {
+ return;
}
- const providerSessionId = providerThread.providerSessionId;
- const nativeTaskId = subagent.nativeTaskRef.nativeId;
- const now = yield* DateTime.now;
- yield* emit(
- events,
+ yield* settleBackgroundWork({
command,
- )({
- type: "subagent.updated",
- threadId: command.threadId,
- runId: command.runId,
- nodeId: subagent.id,
- providerInstanceId: subagent.providerInstanceId,
- occurredAt: now,
- payload: { ...subagent, updatedAt: now },
+ events,
+ projection,
+ stoppedProviderThreadId: command.providerThreadId,
+ throughRunOrdinal: stoppedRun.ordinal,
+ now,
});
- yield* Ref.update(effects, (existing) => [
- ...existing,
- {
- id: `effect:${command.commandId}:subagent.stop:${subagent.id}`,
- commandId: command.commandId,
- threadId: command.threadId,
- request: {
- type: "provider-turn.interrupt",
- providerSessionId,
- providerThreadId: providerThread.id,
- providerTurnId: providerTurn.id,
- subagent: { id: subagent.id, nativeTaskId },
- },
- } satisfies PendingOrchestrationEffectV2,
- ]);
- return;
+ },
+ );
+
+ const dispatchSubagentStop = Effect.fn("Orchestrator.dispatchSubagentStop")(function* (
+ command: Extract<OrchestrationV2Command, { readonly type: "subagent.stop" }>,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
+ ) {
+ const projection = yield* loadProjectionForCommand(command, [
+ "runs",
+ "subagents",
+ "providerThreads",
+ "providerTurns",
+ ]);
+ const run = projection.runs.find((candidate) => candidate.id === command.runId);
+ const subagent = projection.subagents.find((candidate) => candidate.id === command.subagentId);
+ if (
+ subagent === undefined ||
+ subagent.runId !== command.runId ||
+ subagent.origin !== "provider_native" ||
+ subagent.driver !== "claudeAgent" ||
+ subagent.nativeTaskRef?.strength !== "strong" ||
+ subagent.nativeTaskRef.nativeId === null
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "The requested native subagent cannot be stopped on this run.",
+ });
+ }
+ if (!["pending", "running", "waiting"].includes(subagent.status)) return;
+ const providerThread = projection.providerThreads.find(
+ (candidate) => candidate.id === run?.providerThreadId,
+ );
+ const providerTurn = projection.providerTurns.findLast(
+ (candidate) => candidate.providerThreadId === providerThread?.id,
+ );
+ if (
+ providerThread?.providerSessionId == null ||
+ providerTurn === undefined ||
+ providerThread.driver !== subagent.driver ||
+ providerThread.providerInstanceId !== subagent.providerInstanceId
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "The requested native subagent has no owning provider session.",
+ });
+ }
+ const providerSessionId = providerThread.providerSessionId;
+ const nativeTaskId = subagent.nativeTaskRef.nativeId;
+ const now = yield* DateTime.now;
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "subagent.updated",
+ threadId: command.threadId,
+ runId: command.runId,
+ nodeId: subagent.id,
+ providerInstanceId: subagent.providerInstanceId,
+ occurredAt: now,
+ payload: { ...subagent, updatedAt: now },
});
+ yield* Ref.update(effects, (existing) => [
+ ...existing,
+ {
+ id: `effect:${command.commandId}:subagent.stop:${subagent.id}`,
+ commandId: command.commandId,
+ threadId: command.threadId,
+ request: {
+ type: "provider-turn.interrupt",
+ providerSessionId,
+ providerThreadId: providerThread.id,
+ providerTurnId: providerTurn.id,
+ subagent: { id: subagent.id, nativeTaskId },
+ },
+ } satisfies PendingOrchestrationEffectV2,
+ ]);
+ return;
+ });
- const dispatchRunInterrupt = (
+ const dispatchRunInterrupt = Effect.fn("Orchestrator.dispatchRunInterrupt")(function* (
command: Extract<OrchestrationV2Command, { readonly type: "run.interrupt" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
- const projection = yield* loadProjectionForCommand(
- command,
- [
- "runs",
- "nodes",
- "providerThreads",
- "providerTurns",
- "messages",
- "attempts",
- "turnItems",
- "subagents",
- "runtimeRequests",
+ ) {
+ const projection = yield* loadProjectionForCommand(
+ command,
+ [
+ "runs",
+ "nodes",
+ "providerThreads",
+ "providerTurns",
+ "messages",
+ "attempts",
+ "turnItems",
+ "subagents",
+ "runtimeRequests",
+ ],
+ // Thread-wide, like the Waiting strip: a settled thread's background
+ // work can belong to an earlier run than the one Stop targets.
+ {
+ turnItemTypes: [
+ "command_execution",
+ "dynamic_tool",
+ "subagent",
+ "assistant_message",
+ "reasoning",
],
- // Thread-wide, like the Waiting strip: a settled thread's background
- // work can belong to an earlier run than the one Stop targets.
- {
- turnItemTypes: [
- "command_execution",
- "dynamic_tool",
- "subagent",
- "assistant_message",
- "reasoning",
- ],
- turnItemStatuses: ["pending", "running", "waiting"],
- },
- );
- const run = projection.runs.find((candidate) => candidate.id === command.runId);
- const rootNode =
- run?.rootNodeId === null
- ? undefined
- : projection.nodes.find((candidate) => candidate.id === run?.rootNodeId);
- const providerThread =
- run?.providerThreadId === null
- ? undefined
- : projection.providerThreads.find((candidate) => candidate.id === run?.providerThreadId);
- const hasBackgroundWork =
- run?.id === projection.runs.findLast((candidate) => candidate.status !== "queued")?.id &&
- derivePendingBackgroundWork({
- latestRun: run,
- providerThreads: projection.providerThreads,
- turnItems: projection.turnItems,
- activeProviderThreadId: projection.thread.activeProviderThreadId,
- runs: projection.runs,
- }).length > 0;
- // A failed start has no provider turn. Background work still belongs
- // to the provider thread, so Stop reaches its latest accepted turn.
- const providerTurn =
- projection.providerTurns.findLast(
- (candidate) =>
- candidate.runAttemptId === run?.activeAttemptId &&
- (run?.status === "running" || candidate.status === "running" || hasBackgroundWork),
- ) ??
- (hasBackgroundWork
- ? projection.providerTurns.findLast(
- (candidate) => candidate.providerThreadId === run?.providerThreadId,
- )
- : undefined);
- if (run === undefined || rootNode === undefined || providerThread === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Run ${command.runId} is not interruptible.`,
- });
- }
- const now = yield* DateTime.now;
- const completionMessage = projection.messages.find(
- (candidate) => candidate.id === run.userMessageId,
- );
- const completionCohortRunId = completionMessage?.delegatedCompletion?.parentRunId ?? run.id;
- const stopRemainingWork = () =>
- command.holdQueue === true
- ? holdStoppedThread({
- command,
- events,
- projection,
- cohortRunIds: [completionCohortRunId],
- now,
- })
- : Effect.gen(function* () {
- for (const parentRunId of new Set([completionCohortRunId, run.id])) {
- yield* disposeDelegatedCompletionCohort({
- command,
- events,
- projection: yield* getProjectionWithPendingEvents(command.threadId, events),
- parentRunId,
- disposition: "stopped",
- now,
- });
- }
- });
+ turnItemStatuses: ["pending", "running", "waiting"],
+ },
+ );
+ const run = projection.runs.find((candidate) => candidate.id === command.runId);
+ const rootNode =
+ run?.rootNodeId === null
+ ? undefined
+ : projection.nodes.find((candidate) => candidate.id === run?.rootNodeId);
+ const providerThread =
+ run?.providerThreadId === null
+ ? undefined
+ : projection.providerThreads.find((candidate) => candidate.id === run?.providerThreadId);
+ const hasBackgroundWork =
+ run?.id === projection.runs.findLast((candidate) => candidate.status !== "queued")?.id &&
+ derivePendingBackgroundWork({
+ latestRun: run,
+ providerThreads: projection.providerThreads,
+ turnItems: projection.turnItems,
+ activeProviderThreadId: projection.thread.activeProviderThreadId,
+ runs: projection.runs,
+ }).length > 0;
+ // A failed start has no provider turn. Background work still belongs
+ // to the provider thread, so Stop reaches its latest accepted turn.
+ const providerTurn =
+ projection.providerTurns.findLast(
+ (candidate) =>
+ candidate.runAttemptId === run?.activeAttemptId &&
+ (run?.status === "running" || candidate.status === "running" || hasBackgroundWork),
+ ) ??
+ (hasBackgroundWork
+ ? projection.providerTurns.findLast(
+ (candidate) => candidate.providerThreadId === run?.providerThreadId,
+ )
+ : undefined);
+ if (run === undefined || rootNode === undefined || providerThread === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Run ${command.runId} is not interruptible.`,
+ });
+ }
+ const now = yield* DateTime.now;
+ const completionMessage = projection.messages.find(
+ (candidate) => candidate.id === run.userMessageId,
+ );
+ const completionCohortRunId = completionMessage?.delegatedCompletion?.parentRunId ?? run.id;
+ const stopRemainingWork = () =>
+ command.holdQueue === true
+ ? holdStoppedThread({
+ command,
+ events,
+ projection,
+ cohortRunIds: [completionCohortRunId],
+ now,
+ })
+ : Effect.gen(function* () {
+ for (const parentRunId of new Set([completionCohortRunId, run.id])) {
+ yield* disposeDelegatedCompletionCohort({
+ command,
+ events,
+ projection: yield* getProjectionWithPendingEvents(command.threadId, events),
+ parentRunId,
+ disposition: "stopped",
+ now,
+ });
+ }
+ });
- const emitEvent = emit(events, command);
- const interruptRequestItem: OrchestrationV2TurnItem = {
- id: idAllocator.derive.runSignalTurnItem({
- runId: run.id,
- signal: "interrupt-request",
- }),
- threadId: command.threadId,
+ const emitEvent = emit(events, command);
+ const interruptRequestItem: OrchestrationV2TurnItem = {
+ id: idAllocator.derive.runSignalTurnItem({
runId: run.id,
- nodeId: rootNode.id,
- providerThreadId: providerThread.id,
- providerTurnId: providerTurn?.id ?? null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: yield* nextTurnItemOrdinal(projection),
- status: "completed",
- title: "Interrupt requested",
- startedAt: now,
- completedAt: now,
- updatedAt: now,
- type: "run_interrupt_request",
- message: command.reason ?? "Interrupt requested",
- };
+ signal: "interrupt-request",
+ }),
+ threadId: command.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerThreadId: providerThread.id,
+ providerTurnId: providerTurn?.id ?? null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: yield* nextTurnItemOrdinal(projection),
+ status: "completed",
+ title: "Interrupt requested",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "run_interrupt_request",
+ message: command.reason ?? "Interrupt requested",
+ };
- const otherProviderInterrupts: Array<PendingOrchestrationEffectV2> = [];
- if (hasBackgroundWork || command.holdQueue === true) {
- const runOrdinals = new Map(
- projection.runs.map((candidate) => [candidate.id, candidate.ordinal]),
+ const otherProviderInterrupts: Array<PendingOrchestrationEffectV2> = [];
+ if (hasBackgroundWork || command.holdQueue === true) {
+ const runOrdinals = new Map(
+ projection.runs.map((candidate) => [candidate.id, candidate.ordinal]),
+ );
+ const runOrdinalOf = (item: (typeof projection.turnItems)[number]) =>
+ item.runId === null ? -1 : (runOrdinals.get(item.runId) ?? -1);
+ // Each provider thread is interrupted at its latest pending work: that
+ // turn's run bounds the settle follow-up, which must cover all of the
+ // thread's work. The target comes from the item's provider turn, since
+ // a native subagent item names its own provider thread but its
+ // parent's turn; interrupting the parent's turn reaches the subagent.
+ const latestTurnByProviderThread = new Map<
+ OrchestrationV2ProviderThread["id"],
+ { readonly turn: (typeof projection.providerTurns)[number]; readonly runOrdinal: number }
+ >();
+ for (const item of pendingBackgroundTurnItems({
+ turnItems: projection.turnItems,
+ runs: projection.runs,
+ })) {
+ const turn = projection.providerTurns.find(
+ (candidate) => candidate.id === item.providerTurnId,
);
- const runOrdinalOf = (item: (typeof projection.turnItems)[number]) =>
- item.runId === null ? -1 : (runOrdinals.get(item.runId) ?? -1);
- // Each provider thread is interrupted at its latest pending work: that
- // turn's run bounds the settle follow-up, which must cover all of the
- // thread's work. The target comes from the item's provider turn, since
- // a native subagent item names its own provider thread but its
- // parent's turn; interrupting the parent's turn reaches the subagent.
- const latestTurnByProviderThread = new Map<
- OrchestrationV2ProviderThread["id"],
- { readonly turn: (typeof projection.providerTurns)[number]; readonly runOrdinal: number }
- >();
- for (const item of pendingBackgroundTurnItems({
- turnItems: projection.turnItems,
- runs: projection.runs,
- })) {
- const turn = projection.providerTurns.find(
- (candidate) => candidate.id === item.providerTurnId,
- );
- if (turn === undefined || turn.providerThreadId === providerThread.id) continue;
- const runOrdinal = runOrdinalOf(item);
- const latest = latestTurnByProviderThread.get(turn.providerThreadId);
- if (latest === undefined || runOrdinal > latest.runOrdinal) {
- latestTurnByProviderThread.set(turn.providerThreadId, { turn, runOrdinal });
- }
- }
- for (const { turn } of latestTurnByProviderThread.values()) {
- const owner = projection.providerThreads.find(
- (candidate) => candidate.id === turn.providerThreadId,
- );
- if (owner === undefined || owner.providerSessionId === null) continue;
- const ownerSession = yield* providerSessions
- .get(owner.providerSessionId)
- .pipe(Effect.orElseSucceed(() => Option.none()));
- if (Option.isNone(ownerSession)) continue;
- otherProviderInterrupts.push({
- id: `effect:${command.commandId}:provider-turn.interrupt:${turn.id}`,
- commandId: command.commandId,
- threadId: command.threadId,
- request: {
- type: "provider-turn.interrupt",
- providerSessionId: owner.providerSessionId,
- providerThreadId: owner.id,
- providerTurnId: turn.id,
- },
- });
+ if (turn === undefined || turn.providerThreadId === providerThread.id) continue;
+ const runOrdinal = runOrdinalOf(item);
+ const latest = latestTurnByProviderThread.get(turn.providerThreadId);
+ if (latest === undefined || runOrdinal > latest.runOrdinal) {
+ latestTurnByProviderThread.set(turn.providerThreadId, { turn, runOrdinal });
}
}
-
- if (
- providerTurn === undefined &&
- (run.status === "preparing" || run.status === "starting" || run.status === "running")
- ) {
- const attempt = projection.attempts.find(
- (candidate) => candidate.id === run.activeAttemptId,
- );
- if (attempt === undefined) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Run ${command.runId} has no active attempt to interrupt.`,
- });
- }
- const interruptResultItem: OrchestrationV2TurnItem = {
- id: idAllocator.derive.runSignalTurnItem({
- runId: run.id,
- signal: "interrupt-result",
- }),
- threadId: command.threadId,
- runId: run.id,
- nodeId: rootNode.id,
- providerThreadId: providerThread.id,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: interruptRequestItem.id,
- ordinal: interruptRequestItem.ordinal + 1,
- status: "interrupted",
- title: "Interrupted",
- startedAt: now,
- completedAt: now,
- updatedAt: now,
- type: "run_interrupt_result",
- message: "Run interrupted before provider start",
- };
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId: run.id,
- nodeId: rootNode.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: now,
- payload: interruptRequestItem,
- });
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId: run.id,
- nodeId: rootNode.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: now,
- payload: interruptResultItem,
- });
- const preparationItem = projection.turnItems.find(
- (
- candidate,
- ): candidate is Extract<
- OrchestrationV2TurnItem,
- { readonly type: "command_execution" }
- > =>
- candidate.runId === run.id &&
- candidate.type === "command_execution" &&
- candidate.input === WORKSPACE_PREPARATION_INPUT &&
- candidate.status === "running",
+ for (const { turn } of latestTurnByProviderThread.values()) {
+ const owner = projection.providerThreads.find(
+ (candidate) => candidate.id === turn.providerThreadId,
);
- if (preparationItem !== undefined) {
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- runId: run.id,
- nodeId: rootNode.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: now,
- payload: {
- ...preparationItem,
- status: "interrupted",
- title: "Workspace preparation interrupted",
- output: command.reason ?? "Interrupted before provider start",
- completedAt: now,
- updatedAt: now,
- },
- });
- }
- yield* emitEvent({
- type: "run-attempt.updated",
- threadId: command.threadId,
- runId: run.id,
- nodeId: rootNode.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: now,
- payload: { ...attempt, status: "interrupted", completedAt: now },
- });
- yield* emitEvent({
- type: "node.updated",
- threadId: command.threadId,
- runId: run.id,
- nodeId: rootNode.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: now,
- payload: { ...rootNode, status: "interrupted", completedAt: now },
- });
- yield* emitEvent({
- type: "run.updated",
- threadId: command.threadId,
- runId: run.id,
- nodeId: rootNode.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: now,
- payload: { ...run, status: "interrupted", completedAt: now },
+ if (owner === undefined || owner.providerSessionId === null) continue;
+ const ownerSession = yield* providerSessions
+ .get(owner.providerSessionId)
+ .pipe(Effect.orElseSucceed(() => Option.none()));
+ if (Option.isNone(ownerSession)) continue;
+ otherProviderInterrupts.push({
+ id: `effect:${command.commandId}:provider-turn.interrupt:${turn.id}`,
+ commandId: command.commandId,
+ threadId: command.threadId,
+ request: {
+ type: "provider-turn.interrupt",
+ providerSessionId: owner.providerSessionId,
+ providerThreadId: owner.id,
+ providerTurnId: turn.id,
+ },
});
- yield* stopRemainingWork();
- yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]);
- return {
- effectTypes: ["provider-turn.start", "provider-turn.restart"],
- reason: `Run ${run.id} was interrupted before its provider turn started.`,
- } satisfies {
- readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
- readonly reason: string;
- };
}
+ }
- if (providerTurn === undefined) {
+ if (
+ providerTurn === undefined &&
+ (run.status === "preparing" || run.status === "starting" || run.status === "running")
+ ) {
+ const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
+ if (attempt === undefined) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
- cause: `Run ${command.runId} is not interruptible.`,
+ cause: `Run ${command.runId} has no active attempt to interrupt.`,
});
}
- const sessionOption =
- providerThread.providerSessionId === null
- ? Option.none()
- : yield* providerSessions.get(providerThread.providerSessionId).pipe(
- Effect.mapError(
- (cause) =>
- new OrchestratorProviderAdapterError({
- commandId: command.commandId,
- providerInstanceId: run.providerInstanceId,
- cause,
- }),
- ),
- );
- if (Option.isNone(sessionOption)) {
+ const interruptResultItem: OrchestrationV2TurnItem = {
+ id: idAllocator.derive.runSignalTurnItem({
+ runId: run.id,
+ signal: "interrupt-result",
+ }),
+ threadId: command.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerThreadId: providerThread.id,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: interruptRequestItem.id,
+ ordinal: interruptRequestItem.ordinal + 1,
+ status: "interrupted",
+ title: "Interrupted",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "run_interrupt_result",
+ message: "Run interrupted before provider start",
+ };
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: interruptRequestItem,
+ });
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: interruptResultItem,
+ });
+ const preparationItem = projection.turnItems.find(
+ (
+ candidate,
+ ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "command_execution" }> =>
+ candidate.runId === run.id &&
+ candidate.type === "command_execution" &&
+ candidate.input === WORKSPACE_PREPARATION_INPUT &&
+ candidate.status === "running",
+ );
+ if (preparationItem !== undefined) {
yield* emitEvent({
type: "turn-item.updated",
threadId: command.threadId,
@@ -9642,38 +9529,75 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
- payload: interruptRequestItem,
- });
- yield* stopRemainingWork();
- yield* settleInterruptedRun({ command, projection, providerTurn, events, effects, now });
- yield* settleBackgroundWork({
- command,
- events,
- projection,
- stoppedProviderThreadId: providerThread.id,
- throughRunOrdinal: run.ordinal,
- now,
- });
- yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]);
- return undefined;
- }
- if (providerThread.providerSessionId === null) {
- return yield* new OrchestratorDispatchError({
- commandId: command.commandId,
- commandType: command.type,
- cause: `Provider thread ${providerThread.id} has no active provider session.`,
+ payload: {
+ ...preparationItem,
+ status: "interrupted",
+ title: "Workspace preparation interrupted",
+ output: command.reason ?? "Interrupted before provider start",
+ completedAt: now,
+ updatedAt: now,
+ },
});
}
- const providerSessionId = providerThread.providerSessionId;
- yield* enforceCommandPolicy(command)(
- commandPolicy.ensureInterrupt({
- commandId: command.commandId,
- threadId: command.threadId,
- providerInstanceId: run.providerInstanceId,
- capabilities: sessionOption.value.providerSession.capabilities,
- }),
- );
+ yield* emitEvent({
+ type: "run-attempt.updated",
+ threadId: command.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...attempt, status: "interrupted", completedAt: now },
+ });
+ yield* emitEvent({
+ type: "node.updated",
+ threadId: command.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...rootNode, status: "interrupted", completedAt: now },
+ });
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: command.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...run, status: "interrupted", completedAt: now },
+ });
+ yield* stopRemainingWork();
+ yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]);
+ return {
+ effectTypes: ["provider-turn.start", "provider-turn.restart"],
+ reason: `Run ${run.id} was interrupted before its provider turn started.`,
+ } satisfies {
+ readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
+ readonly reason: string;
+ };
+ }
+ if (providerTurn === undefined) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Run ${command.runId} is not interruptible.`,
+ });
+ }
+ const sessionOption =
+ providerThread.providerSessionId === null
+ ? Option.none()
+ : yield* providerSessions.get(providerThread.providerSessionId).pipe(
+ Effect.mapError(
+ (cause) =>
+ new OrchestratorProviderAdapterError({
+ commandId: command.commandId,
+ providerInstanceId: run.providerInstanceId,
+ cause,
+ }),
+ ),
+ );
+ if (Option.isNone(sessionOption)) {
yield* emitEvent({
type: "turn-item.updated",
threadId: command.threadId,
@@ -9684,215 +9608,252 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
payload: interruptRequestItem,
});
yield* stopRemainingWork();
- yield* Ref.update(effects, (existing) => [
- ...existing,
- {
- id: `effect:${command.commandId}:provider-turn.interrupt:${providerTurn.id}`,
- commandId: command.commandId,
- threadId: command.threadId,
- request: {
- type: "provider-turn.interrupt",
- providerSessionId,
- providerThreadId: providerThread.id,
- providerTurnId: providerTurn.id,
- },
- } satisfies PendingOrchestrationEffectV2,
- ...otherProviderInterrupts,
- ]);
+ yield* settleInterruptedRun({ command, projection, providerTurn, events, effects, now });
+ yield* settleBackgroundWork({
+ command,
+ events,
+ projection,
+ stoppedProviderThreadId: providerThread.id,
+ throughRunOrdinal: run.ordinal,
+ now,
+ });
+ yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]);
return undefined;
+ }
+ if (providerThread.providerSessionId === null) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Provider thread ${providerThread.id} has no active provider session.`,
+ });
+ }
+ const providerSessionId = providerThread.providerSessionId;
+ yield* enforceCommandPolicy(command)(
+ commandPolicy.ensureInterrupt({
+ commandId: command.commandId,
+ threadId: command.threadId,
+ providerInstanceId: run.providerInstanceId,
+ capabilities: sessionOption.value.providerSession.capabilities,
+ }),
+ );
+
+ yield* emitEvent({
+ type: "turn-item.updated",
+ threadId: command.threadId,
+ runId: run.id,
+ nodeId: rootNode.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: interruptRequestItem,
});
+ yield* stopRemainingWork();
+ yield* Ref.update(effects, (existing) => [
+ ...existing,
+ {
+ id: `effect:${command.commandId}:provider-turn.interrupt:${providerTurn.id}`,
+ commandId: command.commandId,
+ threadId: command.threadId,
+ request: {
+ type: "provider-turn.interrupt",
+ providerSessionId,
+ providerThreadId: providerThread.id,
+ providerTurnId: providerTurn.id,
+ },
+ } satisfies PendingOrchestrationEffectV2,
+ ...otherProviderInterrupts,
+ ]);
+ return undefined;
+ });
- const dispatchThreadStop = (
+ const dispatchThreadStop = Effect.fn("Orchestrator.dispatchThreadStop")(function* (
command: Extract<OrchestrationV2ServerCommand, { readonly type: "thread.stop" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
- const projection = yield* projectionStore
- .getThreadRecords(command.threadId, ["runs", "providerThreads", "turnItems", "subagents"], {
- turnItemTypes: ["command_execution", "dynamic_tool", "subagent"],
- turnItemStatuses: ["pending", "running", "waiting"],
- })
- .pipe(
- Effect.mapError(
- (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
- ),
+ ) {
+ const projection = yield* projectionStore
+ .getThreadRecords(command.threadId, ["runs", "providerThreads", "turnItems", "subagents"], {
+ turnItemTypes: ["command_execution", "dynamic_tool", "subagent"],
+ turnItemStatuses: ["pending", "running", "waiting"],
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
+ ),
+ );
+ if (projection.thread.deletedAt !== null) return undefined;
+ const cancelIdleOrphans = Effect.gen(function* () {
+ const pending = yield* Ref.get(events);
+ const children = new Map<
+ ThreadId,
+ ProjectionRecords<"runs" | "providerThreads" | "runtimeRequests" | "turnItems"> | null
+ >();
+ const idleChildren = new Map<ThreadId, boolean>();
+ let nodes: ReadonlyArray<OrchestrationV2ExecutionNode> | undefined;
+ for (const recorded of projection.subagents) {
+ const updated = pending.findLast(
+ (event) => event.type === "subagent.updated" && event.payload.id === recorded.id,
);
- if (projection.thread.deletedAt !== null) return undefined;
- const cancelIdleOrphans = Effect.gen(function* () {
- const pending = yield* Ref.get(events);
- const children = new Map<
- ThreadId,
- ProjectionRecords<"runs" | "providerThreads" | "runtimeRequests" | "turnItems"> | null
- >();
- const idleChildren = new Map<ThreadId, boolean>();
- let nodes: ReadonlyArray<OrchestrationV2ExecutionNode> | undefined;
- for (const recorded of projection.subagents) {
- const updated = pending.findLast(
- (event) => event.type === "subagent.updated" && event.payload.id === recorded.id,
- );
- const task = updated?.type === "subagent.updated" ? updated.payload : recorded;
- if (
- task.origin !== "app_owned" ||
- task.childThreadId === null ||
- !isOrchestrationV2WorkActive(task.status)
- )
- continue;
- const childThreadId = task.childThreadId;
- const child = children.has(childThreadId)
- ? (children.get(childThreadId) ?? null)
- : yield* projectionStore
- .getThreadRecords(
- childThreadId,
- ["runs", "providerThreads", "runtimeRequests", "turnItems"],
- {
- turnItemTypes: ["command_execution", "dynamic_tool", "subagent"],
- turnItemStatuses: ["pending", "running", "waiting"],
- },
- )
- .pipe(
- Effect.catchTags({
- ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
- }),
- Effect.mapError(
- (cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }),
- ),
- );
- children.set(childThreadId, child);
- if (child === null) continue;
- if (
- child.thread.lineage.parentThreadId !== command.threadId ||
- child.thread.lineage.relationshipToParent !== "subagent" ||
- (child.thread.forkedFrom?.type === "node" &&
- child.thread.forkedFrom.nodeId === task.id) ||
- child.runs.some((run) => run.delegatedTaskId === task.id)
- )
- continue;
- const idle =
- idleChildren.get(task.childThreadId) ??
- (!child.runs.some((run) => run.status === "queued" || isBlockingRun(run)) &&
- !child.providerThreads.some(
- (thread) =>
- thread.status === "active" || (thread.pendingBackgroundTasks?.length ?? 0) > 0,
- ) &&
- !child.runtimeRequests.some((request) => request.status === "pending") &&
- child.turnItems.length === 0 &&
- Option.isNone(yield* Effect.findFirst(child.runs, awaitsRestartContinuation)));
- idleChildren.set(task.childThreadId, idle);
- if (!idle) continue;
- // Stop can cancel an idle orphan without guessing which completed run owned its result.
- const now = yield* DateTime.now;
- const emitEvent = emit(events, command);
+ const task = updated?.type === "subagent.updated" ? updated.payload : recorded;
+ if (
+ task.origin !== "app_owned" ||
+ task.childThreadId === null ||
+ !isOrchestrationV2WorkActive(task.status)
+ )
+ continue;
+ const childThreadId = task.childThreadId;
+ const child = children.has(childThreadId)
+ ? (children.get(childThreadId) ?? null)
+ : yield* projectionStore
+ .getThreadRecords(
+ childThreadId,
+ ["runs", "providerThreads", "runtimeRequests", "turnItems"],
+ {
+ turnItemTypes: ["command_execution", "dynamic_tool", "subagent"],
+ turnItemStatuses: ["pending", "running", "waiting"],
+ },
+ )
+ .pipe(
+ Effect.catchTags({
+ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
+ }),
+ Effect.mapError(
+ (cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }),
+ ),
+ );
+ children.set(childThreadId, child);
+ if (child === null) continue;
+ if (
+ child.thread.lineage.parentThreadId !== command.threadId ||
+ child.thread.lineage.relationshipToParent !== "subagent" ||
+ (child.thread.forkedFrom?.type === "node" &&
+ child.thread.forkedFrom.nodeId === task.id) ||
+ child.runs.some((run) => run.delegatedTaskId === task.id)
+ )
+ continue;
+ const idle =
+ idleChildren.get(task.childThreadId) ??
+ (!child.runs.some((run) => run.status === "queued" || isBlockingRun(run)) &&
+ !child.providerThreads.some(
+ (thread) =>
+ thread.status === "active" || (thread.pendingBackgroundTasks?.length ?? 0) > 0,
+ ) &&
+ !child.runtimeRequests.some((request) => request.status === "pending") &&
+ child.turnItems.length === 0 &&
+ Option.isNone(yield* Effect.findFirst(child.runs, awaitsRestartContinuation)));
+ idleChildren.set(task.childThreadId, idle);
+ if (!idle) continue;
+ // Stop can cancel an idle orphan without guessing which completed run owned its result.
+ const now = yield* DateTime.now;
+ const emitEvent = emit(events, command);
+ yield* emitEvent({
+ type: "subagent.updated",
+ threadId: command.threadId,
+ nodeId: task.id,
+ occurredAt: now,
+ payload: {
+ ...task,
+ status: "cancelled",
+ completedAt: now,
+ updatedAt: now,
+ completionDelivery: { state: "disposed", observedByRunId: null },
+ },
+ });
+ nodes ??= (yield* projectionStore.getThreadRecords(command.threadId, ["nodes"])).nodes;
+ const node = nodes.find((candidate) => candidate.id === task.id);
+ if (node !== undefined)
yield* emitEvent({
- type: "subagent.updated",
+ type: "node.updated",
+ threadId: command.threadId,
+ nodeId: node.id,
+ occurredAt: now,
+ payload: { ...node, status: "cancelled", completedAt: now },
+ });
+ for (const item of projection.turnItems) {
+ if (item.type !== "subagent" || item.subagentId !== task.id) continue;
+ yield* emitEvent({
+ type: "turn-item.updated",
threadId: command.threadId,
nodeId: task.id,
occurredAt: now,
- payload: {
- ...task,
- status: "cancelled",
- completedAt: now,
- updatedAt: now,
- completionDelivery: { state: "disposed", observedByRunId: null },
- },
+ payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
});
- nodes ??= (yield* projectionStore.getThreadRecords(command.threadId, ["nodes"])).nodes;
- const node = nodes.find((candidate) => candidate.id === task.id);
- if (node !== undefined)
- yield* emitEvent({
- type: "node.updated",
- threadId: command.threadId,
- nodeId: node.id,
- occurredAt: now,
- payload: { ...node, status: "cancelled", completedAt: now },
- });
- for (const item of projection.turnItems) {
- if (item.type !== "subagent" || item.subagentId !== task.id) continue;
- yield* emitEvent({
- type: "turn-item.updated",
- threadId: command.threadId,
- nodeId: task.id,
- occurredAt: now,
- payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
- });
- }
- }
- }).pipe(
- Effect.mapError((cause) =>
- Schema.is(OrchestratorProjectionError)(cause)
- ? cause
- : new OrchestratorProjectionError({ threadId: command.threadId, cause }),
- ),
- );
- const latestRun = projection.runs.findLast((run) => run.status !== "queued");
- const target =
- projection.runs.findLast(
- (run) =>
- run.status === "preparing" || run.status === "starting" || run.status === "running",
- ) ??
- (derivePendingBackgroundWork({
- latestRun,
- providerThreads: projection.providerThreads,
- turnItems: projection.turnItems,
- activeProviderThreadId: projection.thread.activeProviderThreadId,
- runs: projection.runs,
- }).length > 0
- ? latestRun
- : undefined);
- if (target !== undefined) {
- const interruptEvents = yield* Ref.make<Array<OrchestrationV2DomainEvent>>([]);
- const interruptEffects = yield* Ref.make<Array<PendingOrchestrationEffectV2>>([]);
- const interrupted = yield* Effect.exit(
- dispatchRunInterrupt(
- {
- type: "run.interrupt",
- commandId: command.commandId,
- threadId: command.threadId,
- runId: target.id,
- holdQueue: true,
- ...(command.reason === undefined ? {} : { reason: command.reason }),
- },
- interruptEvents,
- interruptEffects,
- ),
- );
- // A failed interrupt may have written part of its events, so they are kept apart.
- if (Exit.isSuccess(interrupted)) {
- const written = yield* Ref.get(interruptEvents);
- const enqueued = yield* Ref.get(interruptEffects);
- yield* Ref.update(events, (existing) => [...existing, ...written]);
- yield* Ref.update(effects, (existing) => [...existing, ...enqueued]);
- yield* cancelIdleOrphans;
- return interrupted.value;
}
- yield* Effect.logWarning("thread.stop could not interrupt the running turn", {
- threadId: command.threadId,
- runId: target.id,
- cause: interrupted.cause,
- });
}
- const now = yield* DateTime.now;
- // Record that Stop reached the turn it could not interrupt and the thread's last executed
- // run, so a late tool call from their agent starts nothing.
- const executed = latestExecutedRun(projection.runs);
- const reached = new Map<RunId, OrchestrationV2Run>();
- if (target !== undefined) reached.set(target.id, target);
- if (executed !== null && !hasLiveRun({ runs: [executed] }))
- reached.set(executed.id, executed);
- for (const run of reached.values()) {
- yield* markStoppedRun({ command, events, thread: projection.thread, run, now });
- }
- yield* holdStoppedThread({ command, events, projection, cohortRunIds: [], now });
- yield* cancelIdleOrphans;
- return undefined;
- });
+ }).pipe(
+ Effect.mapError((cause) =>
+ Schema.is(OrchestratorProjectionError)(cause)
+ ? cause
+ : new OrchestratorProjectionError({ threadId: command.threadId, cause }),
+ ),
+ );
+ const latestRun = projection.runs.findLast((run) => run.status !== "queued");
+ const target =
+ projection.runs.findLast(
+ (run) =>
+ run.status === "preparing" || run.status === "starting" || run.status === "running",
+ ) ??
+ (derivePendingBackgroundWork({
+ latestRun,
+ providerThreads: projection.providerThreads,
+ turnItems: projection.turnItems,
+ activeProviderThreadId: projection.thread.activeProviderThreadId,
+ runs: projection.runs,
+ }).length > 0
+ ? latestRun
+ : undefined);
+ if (target !== undefined) {
+ const interruptEvents = yield* Ref.make<Array<OrchestrationV2DomainEvent>>([]);
+ const interruptEffects = yield* Ref.make<Array<PendingOrchestrationEffectV2>>([]);
+ const interrupted = yield* Effect.exit(
+ dispatchRunInterrupt(
+ {
+ type: "run.interrupt",
+ commandId: command.commandId,
+ threadId: command.threadId,
+ runId: target.id,
+ holdQueue: true,
+ ...(command.reason === undefined ? {} : { reason: command.reason }),
+ },
+ interruptEvents,
+ interruptEffects,
+ ),
+ );
+ // A failed interrupt may have written part of its events, so they are kept apart.
+ if (Exit.isSuccess(interrupted)) {
+ const written = yield* Ref.get(interruptEvents);
+ const enqueued = yield* Ref.get(interruptEffects);
+ yield* Ref.update(events, (existing) => [...existing, ...written]);
+ yield* Ref.update(effects, (existing) => [...existing, ...enqueued]);
+ yield* cancelIdleOrphans;
+ return interrupted.value;
+ }
+ yield* Effect.logWarning("thread.stop could not interrupt the running turn", {
+ threadId: command.threadId,
+ runId: target.id,
+ cause: interrupted.cause,
+ });
+ }
+ const now = yield* DateTime.now;
+ // Record that Stop reached the turn it could not interrupt and the thread's last executed
+ // run, so a late tool call from their agent starts nothing.
+ const executed = latestExecutedRun(projection.runs);
+ const reached = new Map<RunId, OrchestrationV2Run>();
+ if (target !== undefined) reached.set(target.id, target);
+ if (executed !== null && !hasLiveRun({ runs: [executed] })) reached.set(executed.id, executed);
+ for (const run of reached.values()) {
+ yield* markStoppedRun({ command, events, thread: projection.thread, run, now });
+ }
+ yield* holdStoppedThread({ command, events, projection, cohortRunIds: [], now });
+ yield* cancelIdleOrphans;
+ return undefined;
+ });
- const dispatchCheckpointRollback = (
- command: Extract<OrchestrationV2Command, { readonly type: "checkpoint.rollback" }>,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
- ) =>
- Effect.gen(function* () {
+ const dispatchCheckpointRollback = Effect.fn("Orchestrator.dispatchCheckpointRollback")(
+ function* (
+ command: Extract<OrchestrationV2Command, { readonly type: "checkpoint.rollback" }>,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
+ ) {
const projection = yield* loadProjectionForCommand(
command,
["providerThreads", "checkpoints", "checkpointScopes", "runs", "providerTurns", "attempts"],
@@ -10061,13 +10022,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
} satisfies PendingOrchestrationEffectV2,
]);
- });
+ },
+ );
- const dispatchCheckpointRollbackFail = (
- command: Extract<OrchestrationV2InternalCommand, { readonly type: "checkpoint.rollback.fail" }>,
- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
- ) =>
- Effect.gen(function* () {
+ const dispatchCheckpointRollbackFail = Effect.fn("Orchestrator.dispatchCheckpointRollbackFail")(
+ function* (
+ command: Extract<
+ OrchestrationV2InternalCommand,
+ { readonly type: "checkpoint.rollback.fail" }
+ >,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ ) {
const thread = yield* projectionStore
.getThread(command.threadId)
.pipe(mapDispatchError(command));
@@ -10094,14 +10059,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
updatedAt: now,
},
});
- });
+ },
+ );
/**
* Thread lineage and fork origin are immutable, so this
* is safe to read without holding either thread's dispatch lock.
*/
- const appOwnedSubagentParentThreadId = (childThreadId: ThreadId) =>
- Effect.gen(function* () {
+ const appOwnedSubagentParentThreadId = Effect.fn("Orchestrator.appOwnedSubagentParentThreadId")(
+ function* (childThreadId: ThreadId) {
const childThread = yield* projectionStore.getThread(childThreadId);
const lineage = childThread.lineage;
return lineage.relationshipToParent === "subagent" &&
@@ -10109,7 +10075,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
childThread.forkedFrom?.type === "node"
? lineage.parentThreadId
: undefined;
- });
+ },
+ );
const awaitsRestartContinuation = (run: OrchestrationV2Run) =>
effectOutbox
@@ -10336,18 +10303,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
* other (stale policy on the terminal row, or a terminal row regressed to
* running).
*/
- const finalizeAppOwnedSubagentTask = (
- childControls: ProjectionRecords<
- "runs" | "messages" | "subagents" | "providerThreads" | "providerTurns" | "attempts"
- >,
- options: {
- readonly settledContinuationOf?: RunId;
- readonly syncRunId?: RunId;
- readonly task: OrchestrationV2Subagent;
- readonly resultRun?: OrchestrationV2Run;
- },
- ) =>
- Effect.gen(function* () {
+ const finalizeAppOwnedSubagentTask = Effect.fn("Orchestrator.finalizeAppOwnedSubagentTask")(
+ function* (
+ childControls: ProjectionRecords<
+ "runs" | "messages" | "subagents" | "providerThreads" | "providerTurns" | "attempts"
+ >,
+ options: {
+ readonly settledContinuationOf?: RunId;
+ readonly syncRunId?: RunId;
+ readonly task: OrchestrationV2Subagent;
+ readonly resultRun?: OrchestrationV2Run;
+ },
+ ) {
const childThreadId = childControls.thread.id;
const forkedFrom = childControls.thread.forkedFrom;
if (
@@ -10689,247 +10656,248 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
if (completionPlan.offer && completionPlan.parentRun !== undefined) {
yield* offerDelegatedCompletionDelivery(parentThreadId, completionPlan.parentRun.id);
}
- });
+ },
+ );
- const finalizeAppOwnedSubagent = (
+ const finalizeAppOwnedSubagent = Effect.fn("Orchestrator.finalizeAppOwnedSubagent")(function* (
childThreadId: ThreadId,
options?: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId },
- ) =>
- Effect.gen(function* () {
- const childControls = yield* projectionStore.getThreadRecords(
- childThreadId,
- ["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"],
- { messageRoles: ["user"] },
- );
- const parentThreadId = childControls.thread.lineage.parentThreadId;
+ ) {
+ const childControls = yield* projectionStore.getThreadRecords(
+ childThreadId,
+ ["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"],
+ { messageRoles: ["user"] },
+ );
+ const parentThreadId = childControls.thread.lineage.parentThreadId;
+ if (
+ childControls.thread.lineage.relationshipToParent !== "subagent" ||
+ parentThreadId === null ||
+ childControls.thread.forkedFrom?.type !== "node"
+ )
+ return;
+ const progress = delegatedTaskProgress(childControls);
+ const parent = yield* projectionStore.getThreadRecords(parentThreadId, [
+ "subagents",
+ "contextTransfers",
+ ]);
+ for (const task of parent.subagents) {
if (
- childControls.thread.lineage.relationshipToParent !== "subagent" ||
- parentThreadId === null ||
- childControls.thread.forkedFrom?.type !== "node"
+ task.origin !== "app_owned" ||
+ task.childThreadId !== childThreadId ||
+ (task.id === childControls.thread.forkedFrom.nodeId &&
+ progress.state !== "result_available") ||
+ (task.result !== null &&
+ parent.contextTransfers.some(
+ (transfer) =>
+ transfer.type === "subagent_result" && transfer.sourceThreadId === childThreadId,
+ ))
)
- return;
- const progress = delegatedTaskProgress(childControls);
- const parent = yield* projectionStore.getThreadRecords(parentThreadId, [
- "subagents",
- "contextTransfers",
- ]);
- for (const task of parent.subagents) {
- if (
- task.origin !== "app_owned" ||
- task.childThreadId !== childThreadId ||
- (task.id === childControls.thread.forkedFrom.nodeId &&
- progress.state !== "result_available") ||
- (task.result !== null &&
- parent.contextTransfers.some(
- (transfer) =>
- transfer.type === "subagent_result" && transfer.sourceThreadId === childThreadId,
- ))
- )
- continue;
- yield* finalizeAppOwnedSubagentTask(childControls, {
- ...options,
- task,
- ...(progress.resultRun === undefined ? {} : { resultRun: progress.resultRun }),
- });
- }
+ continue;
+ yield* finalizeAppOwnedSubagentTask(childControls, {
+ ...options,
+ task,
+ ...(progress.resultRun === undefined ? {} : { resultRun: progress.resultRun }),
+ });
+ }
- const { resultRun } = progress;
- if (progress.state !== "result_available" || resultRun === undefined) return;
- const status = delegatedTaskTerminalStatus(runOutcome(resultRun));
- if (status !== "cancelled" && status !== "interrupted") return;
+ const { resultRun } = progress;
+ if (progress.state !== "result_available" || resultRun === undefined) return;
+ const status = delegatedTaskTerminalStatus(runOutcome(resultRun));
+ if (status !== "cancelled" && status !== "interrupted") return;
+ if (
+ yield* childAwaitsRestartContinuation(
+ childControls.runs,
+ resultRun,
+ options?.settledContinuationOf,
+ )
+ )
+ return;
+ // Callers hold the parent lock; dismiss takes the child lock, as follow-up intake does.
+ const { runtimeRequests } = yield* projectionStore.getThreadRecords(childThreadId, [
+ "runtimeRequests",
+ ]);
+ const pendingQuestions = runtimeRequests.filter(
+ (request) =>
+ request.status === "pending" &&
+ request.kind === "user_input" &&
+ request.responseCapability.type === "message",
+ );
+ if (pendingQuestions.length === 0) return;
+ const { nodes } = yield* projectionStore.getThreadRecords(childThreadId, ["nodes"]);
+ const resultRunIds = new Set<RunId>();
+ let run: OrchestrationV2Run | undefined = resultRun;
+ while (run !== undefined && !resultRunIds.has(run.id)) {
+ resultRunIds.add(run.id);
+ const previousRunId: RunId | undefined = run.restartContinuationOfRunId;
+ run =
+ previousRunId === undefined
+ ? undefined
+ : childControls.runs.find((candidate) => candidate.id === previousRunId);
+ }
+ for (const request of pendingQuestions) {
if (
- yield* childAwaitsRestartContinuation(
- childControls.runs,
- resultRun,
- options?.settledContinuationOf,
+ nodes.some(
+ (node) =>
+ node.id === request.nodeId && node.runId !== null && resultRunIds.has(node.runId),
)
- )
- return;
- // Callers hold the parent lock; dismiss takes the child lock, as follow-up intake does.
- const { runtimeRequests } = yield* projectionStore.getThreadRecords(childThreadId, [
- "runtimeRequests",
- ]);
- const pendingQuestions = runtimeRequests.filter(
- (request) =>
- request.status === "pending" &&
- request.kind === "user_input" &&
- request.responseCapability.type === "message",
- );
- if (pendingQuestions.length === 0) return;
- const { nodes } = yield* projectionStore.getThreadRecords(childThreadId, ["nodes"]);
- const resultRunIds = new Set<RunId>();
- let run: OrchestrationV2Run | undefined = resultRun;
- while (run !== undefined && !resultRunIds.has(run.id)) {
- resultRunIds.add(run.id);
- const previousRunId: RunId | undefined = run.restartContinuationOfRunId;
- run =
- previousRunId === undefined
- ? undefined
- : childControls.runs.find((candidate) => candidate.id === previousRunId);
- }
- for (const request of pendingQuestions) {
- if (
- nodes.some(
- (node) =>
- node.id === request.nodeId && node.runId !== null && resultRunIds.has(node.runId),
- )
- ) {
- yield* dispatchWithReceipt({
- type: "thread.user-input.dismiss",
- commandId: CommandId.make(`command:system:delegated-task-question:${request.id}`),
- threadId: childThreadId,
- requestId: request.id,
- }).pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("Failed to dismiss task question", {
- requestId: request.id,
- cause,
- }),
- ),
- );
- }
+ ) {
+ yield* dispatchWithReceipt({
+ type: "thread.user-input.dismiss",
+ commandId: CommandId.make(`command:system:delegated-task-question:${request.id}`),
+ threadId: childThreadId,
+ requestId: request.id,
+ }).pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("Failed to dismiss task question", {
+ requestId: request.id,
+ cause,
+ }),
+ ),
+ );
}
- });
+ }
+ });
- const finalizeDelegatedCompletionDelivery = (threadId: ThreadId, runId: RunId) =>
- Effect.gen(function* () {
- // Ordinary turns do not own a delegated delivery. Read just their input
- // before loading the cohort state needed to settle an actual delivery.
- const message = yield* projectionStore.getRunMessage(threadId, runId);
- if (message?.delegatedCompletion === undefined) return;
- const projection = yield* projectionStore.getThreadRecords(
- threadId,
- ["runs", "messages", "subagents"],
- { messageRoles: ["user"] },
- );
- const deliveryRun = projection.runs.find((candidate) => candidate.id === runId);
- const deliveryMessage =
- deliveryRun === undefined
- ? undefined
- : projection.messages.find((candidate) => candidate.id === deliveryRun.userMessageId);
- const messageOwnership = deliveryMessage?.delegatedCompletion;
- if (deliveryRun === undefined || messageOwnership === undefined) {
- return;
- }
- const parentRun = projection.runs.find(
- (candidate) => candidate.id === messageOwnership.parentRunId,
- );
- const cohort = parentRun?.delegatedCompletion;
- const delivery = cohort?.delivery;
+ const finalizeDelegatedCompletionDelivery = Effect.fn(
+ "Orchestrator.finalizeDelegatedCompletionDelivery",
+ )(function* (threadId: ThreadId, runId: RunId) {
+ // Ordinary turns do not own a delegated delivery. Read just their input
+ // before loading the cohort state needed to settle an actual delivery.
+ const message = yield* projectionStore.getRunMessage(threadId, runId);
+ if (message?.delegatedCompletion === undefined) return;
+ const projection = yield* projectionStore.getThreadRecords(
+ threadId,
+ ["runs", "messages", "subagents"],
+ { messageRoles: ["user"] },
+ );
+ const deliveryRun = projection.runs.find((candidate) => candidate.id === runId);
+ const deliveryMessage =
+ deliveryRun === undefined
+ ? undefined
+ : projection.messages.find((candidate) => candidate.id === deliveryRun.userMessageId);
+ const messageOwnership = deliveryMessage?.delegatedCompletion;
+ if (deliveryRun === undefined || messageOwnership === undefined) {
+ return;
+ }
+ const parentRun = projection.runs.find(
+ (candidate) => candidate.id === messageOwnership.parentRunId,
+ );
+ const cohort = parentRun?.delegatedCompletion;
+ const delivery = cohort?.delivery;
+ if (
+ parentRun === undefined ||
+ cohort === undefined ||
+ delivery === null ||
+ delivery === undefined ||
+ delivery.messageId !== deliveryRun.userMessageId ||
+ delivery.generation !== messageOwnership.generation
+ ) {
+ return;
+ }
+
+ const now = yield* DateTime.now;
+ const nextTaskStates = new Map<
+ OrchestrationV2Subagent["id"],
+ OrchestrationV2Subagent["completionDelivery"]
+ >();
+ for (const task of projection.subagents) {
if (
- parentRun === undefined ||
- cohort === undefined ||
- delivery === null ||
- delivery === undefined ||
- delivery.messageId !== deliveryRun.userMessageId ||
- delivery.generation !== messageOwnership.generation
+ task.origin !== "app_owned" ||
+ task.runId !== parentRun.id ||
+ !delivery.taskIds.includes(task.id) ||
+ task.completionDelivery?.state !== "claimed"
) {
- return;
+ continue;
}
-
- const now = yield* DateTime.now;
- const nextTaskStates = new Map<
- OrchestrationV2Subagent["id"],
- OrchestrationV2Subagent["completionDelivery"]
- >();
- for (const task of projection.subagents) {
- if (
- task.origin !== "app_owned" ||
- task.runId !== parentRun.id ||
- !delivery.taskIds.includes(task.id) ||
- task.completionDelivery?.state !== "claimed"
- ) {
- continue;
+ nextTaskStates.set(task.id, {
+ state: deliveryRun.status === "cancelled" ? "pending" : "delivered",
+ observedByRunId: null,
+ });
+ }
+ const pendingTaskIds = projection.subagents
+ .filter(
+ (task) =>
+ task.origin === "app_owned" &&
+ task.runId === parentRun.id &&
+ isTerminalDelegatedTaskStatus(task.status) &&
+ (task.completionDelivery?.state === "pending" ||
+ nextTaskStates.get(task.id)?.state === "pending"),
+ )
+ .map((task) => task.id);
+ const canReserveFollowUp =
+ cohort.disposition === "open" &&
+ projection.thread.archivedAt === null &&
+ projection.thread.deletedAt === null &&
+ pendingTaskIds.length > 0;
+ const nextDelivery = canReserveFollowUp
+ ? {
+ generation: cohort.nextGeneration,
+ messageId: yield* mapDelegatedCompletionError(
+ idAllocator.allocate.message({
+ threadId,
+ ordinal:
+ (yield* mapDelegatedCompletionError(
+ projectionStore.getMessageCount(projection.thread.id),
+ )) + 1,
+ }),
+ ),
+ taskIds: pendingTaskIds,
}
- nextTaskStates.set(task.id, {
- state: deliveryRun.status === "cancelled" ? "pending" : "delivered",
+ : null;
+ if (nextDelivery !== null) {
+ for (const taskId of pendingTaskIds) {
+ nextTaskStates.set(taskId, {
+ state: "claimed",
observedByRunId: null,
});
}
- const pendingTaskIds = projection.subagents
- .filter(
- (task) =>
- task.origin === "app_owned" &&
- task.runId === parentRun.id &&
- isTerminalDelegatedTaskStatus(task.status) &&
- (task.completionDelivery?.state === "pending" ||
- nextTaskStates.get(task.id)?.state === "pending"),
- )
- .map((task) => task.id);
- const canReserveFollowUp =
- cohort.disposition === "open" &&
- projection.thread.archivedAt === null &&
- projection.thread.deletedAt === null &&
- pendingTaskIds.length > 0;
- const nextDelivery = canReserveFollowUp
- ? {
- generation: cohort.nextGeneration,
- messageId: yield* mapDelegatedCompletionError(
- idAllocator.allocate.message({
- threadId,
- ordinal:
- (yield* mapDelegatedCompletionError(
- projectionStore.getMessageCount(projection.thread.id),
- )) + 1,
- }),
- ),
- taskIds: pendingTaskIds,
- }
- : null;
- if (nextDelivery !== null) {
- for (const taskId of pendingTaskIds) {
- nextTaskStates.set(taskId, {
- state: "claimed",
- observedByRunId: null,
- });
- }
+ }
+ const updatedParentRun: OrchestrationV2Run = {
+ ...parentRun,
+ delegatedCompletion: {
+ ...cohort,
+ nextGeneration: nextDelivery === null ? cohort.nextGeneration : cohort.nextGeneration + 1,
+ delivery: nextDelivery,
+ },
+ };
+ const taskEvents = projection.subagents.flatMap((task) => {
+ const completionDelivery = nextTaskStates.get(task.id);
+ if (completionDelivery === undefined) {
+ return [];
}
- const updatedParentRun: OrchestrationV2Run = {
- ...parentRun,
- delegatedCompletion: {
- ...cohort,
- nextGeneration: nextDelivery === null ? cohort.nextGeneration : cohort.nextGeneration + 1,
- delivery: nextDelivery,
- },
- };
- const taskEvents = projection.subagents.flatMap((task) => {
- const completionDelivery = nextTaskStates.get(task.id);
- if (completionDelivery === undefined) {
- return [];
- }
- return [
- {
- type: "subagent.updated" as const,
- threadId,
- ...(task.runId === null ? {} : { runId: task.runId }),
- nodeId: task.id,
- driver: task.driver,
- providerInstanceId: task.providerInstanceId,
- occurredAt: now,
- payload: {
- ...task,
- completionDelivery,
- updatedAt: now,
- },
- },
- ];
- });
- yield* writeSystemEvents([
- ...taskEvents,
+ return [
{
- type: "run.updated",
+ type: "subagent.updated" as const,
threadId,
- runId: updatedParentRun.id,
- ...(updatedParentRun.rootNodeId === null ? {} : { nodeId: updatedParentRun.rootNodeId }),
- providerInstanceId: updatedParentRun.providerInstanceId,
+ ...(task.runId === null ? {} : { runId: task.runId }),
+ nodeId: task.id,
+ driver: task.driver,
+ providerInstanceId: task.providerInstanceId,
occurredAt: now,
- payload: updatedParentRun,
+ payload: {
+ ...task,
+ completionDelivery,
+ updatedAt: now,
+ },
},
- ]);
- if (nextDelivery !== null) {
- yield* offerDelegatedCompletionDelivery(threadId, parentRun.id);
- }
+ ];
});
+ yield* writeSystemEvents([
+ ...taskEvents,
+ {
+ type: "run.updated",
+ threadId,
+ runId: updatedParentRun.id,
+ ...(updatedParentRun.rootNodeId === null ? {} : { nodeId: updatedParentRun.rootNodeId }),
+ providerInstanceId: updatedParentRun.providerInstanceId,
+ occurredAt: now,
+ payload: updatedParentRun,
+ },
+ ]);
+ if (nextDelivery !== null) {
+ yield* offerDelegatedCompletionDelivery(threadId, parentRun.id);
+ }
+ });
const dispatchNotificationAccepted = Effect.fn("orchestrationV2.notificationAccepted")(function* (
command: Extract<OrchestrationV2Command, { type: "notification.delivery.accept" }>,
@@ -11534,30 +11502,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
} satisfies OrchestratorV2DispatchResult;
});
- const dispatchWithReceipt = (command: OrchestrationV2ServerCommand) =>
- Effect.gen(function* () {
- const dispatch = threadDispatch.withLock(
- commandThreadId(command),
- dispatchWithReceiptEffect(command),
- );
- if (
- command.type !== "message.dispatch" ||
- (command.createdBy !== "user" && command.creationSource !== "mcp")
- )
- return yield* dispatch;
- const parentThreadId = yield* appOwnedSubagentParentThreadId(command.threadId).pipe(
- Effect.mapError(
- (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
- ),
- );
- // Follow-up intake and Stop serialize on the parent before taking the child lock.
- return yield* parentThreadId === undefined
- ? dispatch
- : threadDispatch.withLock(parentThreadId, dispatch);
- });
+ // dispatchWithReceiptEffect owns the dispatch span; this wrapper selects the thread locks.
+ const dispatchWithReceipt = Effect.fnUntraced(function* (command: OrchestrationV2ServerCommand) {
+ const dispatch = threadDispatch.withLock(
+ commandThreadId(command),
+ dispatchWithReceiptEffect(command),
+ );
+ if (
+ command.type !== "message.dispatch" ||
+ (command.createdBy !== "user" && command.creationSource !== "mcp")
+ )
+ return yield* dispatch;
+ const parentThreadId = yield* appOwnedSubagentParentThreadId(command.threadId).pipe(
+ Effect.mapError(
+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
+ ),
+ );
+ // Follow-up intake and Stop serialize on the parent before taking the child lock.
+ return yield* parentThreadId === undefined
+ ? dispatch
+ : threadDispatch.withLock(parentThreadId, dispatch);
+ });
- const handleRunUpdate = (stored: OrchestrationV2StoredEvent) =>
- Effect.gen(function* () {
+ const handleRunUpdate = Effect.fn("Orchestrator.handleRunUpdate")(
+ function* (stored: OrchestrationV2StoredEvent) {
if (stored.event.type !== "run.updated") return;
const threadId = stored.event.threadId;
const run = stored.event.payload;
@@ -11593,15 +11561,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
finalizeAppOwnedSubagent(threadId, { syncRunId: run.id }),
);
}
- }).pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("Failed to react to V2 run update", {
- threadId: stored.event.threadId,
- sequence: stored.sequence,
- cause,
- }),
+ },
+ (effect, stored) =>
+ effect.pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("Failed to react to V2 run update", {
+ threadId: stored.event.threadId,
+ sequence: stored.sequence,
+ cause,
+ }),
+ ),
),
- );
+ );
// Historical terminal events are already represented by the projections
// below. Replaying the full event table on every server start delays live
@@ -11727,8 +11698,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
);
});
- const delegatedTaskResultPending = (childThreadId: ThreadId, taskId?: NodeId) =>
- Effect.gen(function* () {
+ const delegatedTaskResultPending = Effect.fn("Orchestrator.delegatedTaskResultPending")(
+ function* (childThreadId: ThreadId, taskId?: NodeId) {
const child = yield* projectionStore.getThreadRecords(
childThreadId,
["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"],
@@ -11744,28 +11715,34 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
if (progress.state !== "result_available") return true;
if (progress.resultRun === undefined) return false;
return yield* childAwaitsRestartContinuation(child.runs, progress.resultRun);
- }).pipe(
- Effect.mapError(
- (cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }),
+ },
+ (effect, childThreadId, _taskId?) =>
+ effect.pipe(
+ Effect.mapError(
+ (cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }),
+ ),
),
- );
+ );
- const recoverDelegatedTask = (threadId: ThreadId, sourceRunId: RunId) =>
- Effect.gen(function* () {
+ const recoverDelegatedTask = Effect.fn("Orchestrator.recoverDelegatedTask")(
+ function* (threadId: ThreadId, sourceRunId: RunId) {
const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId);
if (parentThreadId === undefined) return;
yield* threadDispatch.withLock(
parentThreadId,
finalizeAppOwnedSubagent(threadId, { settledContinuationOf: sourceRunId }),
);
- }).pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("Failed to recover delegated task after restart", {
- childThreadId: threadId,
- cause,
- }),
+ },
+ (effect, threadId, _sourceRunId) =>
+ effect.pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("Failed to recover delegated task after restart", {
+ childThreadId: threadId,
+ cause,
+ }),
+ ),
),
- );
+ );
const shellProjectionError = (cause: unknown) =>
new OrchestratorProjectionError({ threadId: ThreadId.make("thread:shell"), cause });
diff --git a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts
index 58609d18ce2..4d63447fc04 100644
--- a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts
+++ b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts
@@ -136,26 +136,25 @@ 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,
- };
- }),
+ getMetadata: Effect.fn("ProviderAdapterRegistry.getMetadata")(function* (instanceId) {
+ 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,
+ };
+ }),
});
}),
);
@@ -167,14 +166,13 @@ function makeRegistry(
adapters: ReadonlyArray<ProviderAdapter.ProviderAdapterV2["Service"]>,
): ProviderAdapterRegistryV2Shape {
return {
- get: (instanceId) =>
- Effect.gen(function* () {
- const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
- if (!adapter) {
- return yield* new ProviderAdapterRegistryLookupError({ instanceId });
- }
- return adapter;
- }),
+ get: Effect.fn("ProviderAdapterRegistry.get")(function* (instanceId) {
+ const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
+ if (!adapter) {
+ return yield* new ProviderAdapterRegistryLookupError({ instanceId });
+ }
+ return adapter;
+ }),
list: () => Effect.succeed(adapters.map((adapter) => adapter.instanceId)),
};
}
@@ -318,20 +316,20 @@ const buildAdaptersFromConfigMap = Effect.fn("ProviderAdapterRegistry.buildAdapt
},
);
-export function makeRegistryFromConfigMap<R>(input: {
+export const makeRegistryFromConfigMap = Effect.fn(
+ "ProviderAdapterRegistry.makeRegistryFromConfigMap",
+)(function* <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
-}): Effect.Effect<
+}): Effect.fn.Return<
ProviderAdapterRegistryV2Shape,
ProviderAdapterRegistryBuildError,
R | Scope.Scope
> {
- return Effect.gen(function* () {
- const parentScope = yield* Effect.scope;
- const entries = yield* buildAdaptersFromConfigMap({ ...input, parentScope });
- return makeRegistry(Array.from(entries.values()).map((entry) => entry.adapter));
- });
-}
+ const parentScope = yield* Effect.scope;
+ const entries = yield* buildAdaptersFromConfigMap({ ...input, parentScope });
+ return makeRegistry(Array.from(entries.values()).map((entry) => entry.adapter));
+});
export function layerFromDrivers<R>(input: {
readonly drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>;
diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
index 32de3b9d6a4..a3c41fed25f 100644
--- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
+++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
@@ -696,62 +696,61 @@ export const make = Effect.gen(function* () {
},
);
- const reconcile = (trigger: "startup" | "shutdown") =>
- Effect.gen(function* () {
- const continueAfterRestart = yield* settings.getSettings.pipe(
- Effect.orElseSucceed(() => null),
+ const reconcile = Effect.fn("ProviderRuntimeRecoveryService.reconcile")(function* (
+ trigger: "startup" | "shutdown",
+ ) {
+ const continueAfterRestart = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
+ const threadIds = yield* projections
+ .getRecoveryThreadIds("runtime")
+ .pipe(
+ Effect.mapError(
+ (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
+ ),
);
- const threadIds = yield* projections
- .getRecoveryThreadIds("runtime")
- .pipe(
- Effect.mapError(
- (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
- ),
- );
- let terminalizedRuns = 0;
- let stoppedSessions = 0;
- let closedRequests = 0;
- let retiredEffects = 0;
- const stoppedThisPass = new Map<string, RecoverySession>();
- for (const threadId of threadIds) {
- const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
- Effect.mapError(
- (cause) =>
- new ProviderRuntimeRecoveryError({
- operation: "read-projections",
- threadId,
- cause,
- }),
- ),
- );
- const enabled =
- continueAfterRestart !== null &&
- resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
- .continueThreadsAfterServerUpdate;
- const result = yield* reconcileProjection(projection, trigger, enabled, stoppedThisPass);
- for (const session of projection.providerSessions) {
- if (session.status !== "stopped" && session.status !== "error") {
- stoppedThisPass.set(session.id, session);
- }
- }
- terminalizedRuns += result.terminalizedRuns;
- stoppedSessions += result.stoppedSessions;
- closedRequests += result.closedRequests;
- retiredEffects += result.retiredEffects;
- }
- const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
+ let terminalizedRuns = 0;
+ let stoppedSessions = 0;
+ let closedRequests = 0;
+ let retiredEffects = 0;
+ const stoppedThisPass = new Map<string, RecoverySession>();
+ for (const threadId of threadIds) {
+ const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
Effect.mapError(
- (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
+ (cause) =>
+ new ProviderRuntimeRecoveryError({
+ operation: "read-projections",
+ threadId,
+ cause,
+ }),
),
);
- return {
- terminalizedRuns,
- stoppedSessions,
- closedRequests,
- retiredEffects: retiredEffects + outboxReconciliation.cancelled,
- requeuedEffects: outboxReconciliation.requeued,
- } satisfies ProviderRuntimeReconciliationSummary;
- });
+ const enabled =
+ continueAfterRestart !== null &&
+ resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
+ .continueThreadsAfterServerUpdate;
+ const result = yield* reconcileProjection(projection, trigger, enabled, stoppedThisPass);
+ for (const session of projection.providerSessions) {
+ if (session.status !== "stopped" && session.status !== "error") {
+ stoppedThisPass.set(session.id, session);
+ }
+ }
+ terminalizedRuns += result.terminalizedRuns;
+ stoppedSessions += result.stoppedSessions;
+ closedRequests += result.closedRequests;
+ retiredEffects += result.retiredEffects;
+ }
+ const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
+ Effect.mapError(
+ (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
+ ),
+ );
+ return {
+ terminalizedRuns,
+ stoppedSessions,
+ closedRequests,
+ retiredEffects: retiredEffects + outboxReconciliation.cancelled,
+ requeuedEffects: outboxReconciliation.requeued,
+ } satisfies ProviderRuntimeReconciliationSummary;
+ });
const prepareForShutdown = Effect.gen(function* () {
const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts
index edcaecfa884..3164186c9fc 100644
--- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts
+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts
@@ -525,220 +525,227 @@ export const layerWithOptions = (
),
);
- const failSubscribers = (entry: LiveSessionEntry, detail: string) =>
- Effect.gen(function* () {
- const error = new ProviderAdapter.ProviderAdapterEventStreamError({
- driver: entry.runtime.driver,
- providerSessionId: entry.runtime.providerSessionId,
- cause: detail,
- });
- const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
- yield* Effect.forEach(
- subscribers.values(),
- (queue) =>
- Queue.offer(queue, {
- type: "failure",
- cause: Cause.fail(error),
- }),
- { discard: true },
- );
+ const failSubscribers = Effect.fn("ProviderSessionManager.failSubscribers")(function* (
+ entry: LiveSessionEntry,
+ detail: string,
+ ) {
+ const error = new ProviderAdapter.ProviderAdapterEventStreamError({
+ driver: entry.runtime.driver,
+ providerSessionId: entry.runtime.providerSessionId,
+ cause: detail,
});
+ const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
+ yield* Effect.forEach(
+ subscribers.values(),
+ (queue) =>
+ Queue.offer(queue, {
+ type: "failure",
+ cause: Cause.fail(error),
+ }),
+ { discard: true },
+ );
+ });
// Server shutdown interrupts subscribers rather than ending them: a
// cleanly ended stream without a terminal fails its run, while an
// interrupted one leaves run settlement to restart recovery.
- const interruptSubscribers = (entry: LiveSessionEntry) =>
- Effect.gen(function* () {
+ const interruptSubscribers = Effect.fn("ProviderSessionManager.interruptSubscribers")(
+ function* (entry: LiveSessionEntry) {
const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
yield* Effect.forEach(
subscribers.values(),
(queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.interrupt(queue))),
{ discard: true },
);
- });
+ },
+ );
// Server shutdown intentionally clears them; a provider-announced Stop
// must let consumers drain them before the stream completes.
- const endSubscribers = (entry: LiveSessionEntry) =>
- Effect.gen(function* () {
- const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
- yield* Effect.forEach(subscribers.values(), (queue) => Queue.end(queue), {
- discard: true,
- });
+ const endSubscribers = Effect.fn("ProviderSessionManager.endSubscribers")(function* (
+ entry: LiveSessionEntry,
+ ) {
+ const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
+ yield* Effect.forEach(subscribers.values(), (queue) => Queue.end(queue), {
+ discard: true,
});
+ });
const cancelIdleFiber = (fiber: Fiber.Fiber<void, never> | null) =>
fiber === null ? Effect.void : Fiber.interrupt(fiber).pipe(Effect.ignore);
- const writeProviderSessionEvents = (input: {
+ const writeProviderSessionEvents = Effect.fn(
+ "ProviderSessionManager.writeProviderSessionEvents",
+ )(function* (input: {
readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime;
readonly threadIds: Iterable<ThreadId>;
readonly type: "provider-session.attached" | "provider-session.updated";
readonly payload: OrchestrationV2ProviderSession;
- }) =>
- Effect.gen(function* () {
- const now = yield* DateTime.now;
- const events = yield* Effect.forEach(input.threadIds, (threadId) =>
- Effect.gen(function* () {
- return {
- id: yield* idAllocator.allocate.event({
- threadId,
- providerSessionId: input.runtime.providerSessionId,
- }),
- type: input.type,
+ }) {
+ const now = yield* DateTime.now;
+ const events = yield* Effect.forEach(input.threadIds, (threadId) =>
+ Effect.gen(function* () {
+ return {
+ id: yield* idAllocator.allocate.event({
threadId,
- driver: input.runtime.driver,
- providerInstanceId: input.runtime.instanceId,
- occurredAt: now,
- payload: input.payload,
- } satisfies OrchestrationV2DomainEvent;
- }),
- );
- if (events.length > 0) {
- yield* eventSink.write({ events });
- }
- });
+ providerSessionId: input.runtime.providerSessionId,
+ }),
+ type: input.type,
+ threadId,
+ driver: input.runtime.driver,
+ providerInstanceId: input.runtime.instanceId,
+ occurredAt: now,
+ payload: input.payload,
+ } satisfies OrchestrationV2DomainEvent;
+ }),
+ );
+ if (events.length > 0) {
+ yield* eventSink.write({ events });
+ }
+ });
- const writeReleasedSessionEvents = (input: {
+ const writeReleasedSessionEvents = Effect.fn(
+ "ProviderSessionManager.writeReleasedSessionEvents",
+ )(function* (input: {
readonly entry: LiveSessionEntry;
readonly reason: ProviderSessionReleaseReason;
readonly detail?: string;
- }) =>
- Effect.gen(function* () {
- const now = yield* DateTime.now;
- const payload: OrchestrationV2ProviderSession = {
- ...input.entry.runtime.providerSession,
- status: releaseStatusFor(input.reason),
- updatedAt: now,
- lastError:
- input.reason === "runtime_error"
- ? (input.detail ?? "Provider runtime failed.")
- : null,
- };
- yield* writeProviderSessionEvents({
- runtime: input.entry.runtime,
- threadIds: input.entry.attachedThreadIds,
- type: "provider-session.updated",
- payload,
- });
+ }) {
+ const now = yield* DateTime.now;
+ const payload: OrchestrationV2ProviderSession = {
+ ...input.entry.runtime.providerSession,
+ status: releaseStatusFor(input.reason),
+ updatedAt: now,
+ lastError:
+ input.reason === "runtime_error" ? (input.detail ?? "Provider runtime failed.") : null,
+ };
+ yield* writeProviderSessionEvents({
+ runtime: input.entry.runtime,
+ threadIds: input.entry.attachedThreadIds,
+ type: "provider-session.updated",
+ payload,
});
+ });
- const writeReleasedRuntimeRequestEvents = (input: {
+ const writeReleasedRuntimeRequestEvents = Effect.fn(
+ "ProviderSessionManager.writeReleasedRuntimeRequestEvents",
+ )(function* (input: {
readonly entry: LiveSessionEntry;
readonly reason: ProviderSessionReleaseReason;
readonly releasedAt: DateTime.Utc;
- }) =>
- Effect.gen(function* () {
- const providerSessionId = input.entry.runtime.providerSessionId;
- const now = yield* DateTime.now;
- const status = releasedRuntimeRequestStatusFor(input.reason);
- const reason =
- input.reason === "runtime_error"
- ? "Provider session failed before this runtime request was resolved."
- : "Provider session was closed before this runtime request was resolved.";
-
- const events: Array<OrchestrationV2DomainEvent> = [];
- for (const threadId of input.entry.attachedThreadIds) {
- const projection = yield* projectionStore.getThreadRecords(
+ }) {
+ const providerSessionId = input.entry.runtime.providerSessionId;
+ const now = yield* DateTime.now;
+ const status = releasedRuntimeRequestStatusFor(input.reason);
+ const reason =
+ input.reason === "runtime_error"
+ ? "Provider session failed before this runtime request was resolved."
+ : "Provider session was closed before this runtime request was resolved.";
+
+ const events: Array<OrchestrationV2DomainEvent> = [];
+ for (const threadId of input.entry.attachedThreadIds) {
+ const projection = yield* projectionStore.getThreadRecords(
+ threadId,
+ ["runtimeRequests", "nodes", "turnItems"],
+ { turnItemTypes: ["approval_request", "user_input_request"] },
+ );
+ const releasedRequests = projection.runtimeRequests.filter(
+ (request) =>
+ request.status === "pending" &&
+ request.responseCapability.type === "live" &&
+ request.responseCapability.providerSessionId === providerSessionId &&
+ DateTime.isLessThanOrEqualTo(request.createdAt, input.releasedAt),
+ );
+
+ for (const request of releasedRequests) {
+ events.push({
+ id: yield* idAllocator.allocate.event({
+ threadId,
+ providerSessionId,
+ }),
+ type: "runtime-request.updated",
threadId,
- ["runtimeRequests", "nodes", "turnItems"],
- { turnItemTypes: ["approval_request", "user_input_request"] },
- );
- const releasedRequests = projection.runtimeRequests.filter(
- (request) =>
- request.status === "pending" &&
- request.responseCapability.type === "live" &&
- request.responseCapability.providerSessionId === providerSessionId &&
- DateTime.isLessThanOrEqualTo(request.createdAt, input.releasedAt),
- );
+ nodeId: request.nodeId,
+ driver: input.entry.runtime.driver,
+ occurredAt: now,
+ payload: {
+ ...request,
+ status,
+ responseCapability: {
+ type: "not_resumable",
+ reason,
+ },
+ resolvedAt: now,
+ },
+ });
- for (const request of releasedRequests) {
+ const requestNode = projection.nodes.find((node) => node.id === request.nodeId);
+ if (requestNode !== undefined) {
events.push({
id: yield* idAllocator.allocate.event({
threadId,
providerSessionId,
}),
- type: "runtime-request.updated",
+ type: "node.updated",
threadId,
- nodeId: request.nodeId,
+ ...(requestNode.runId === null ? {} : { runId: requestNode.runId }),
+ nodeId: requestNode.id,
driver: input.entry.runtime.driver,
occurredAt: now,
payload: {
- ...request,
- status,
- responseCapability: {
- type: "not_resumable",
- reason,
- },
- resolvedAt: now,
+ ...requestNode,
+ status: input.reason === "runtime_error" ? "failed" : "cancelled",
+ completedAt: now,
},
});
+ }
- const requestNode = projection.nodes.find((node) => node.id === request.nodeId);
- if (requestNode !== undefined) {
- events.push({
- id: yield* idAllocator.allocate.event({
- threadId,
- providerSessionId,
- }),
- type: "node.updated",
- threadId,
- ...(requestNode.runId === null ? {} : { runId: requestNode.runId }),
- nodeId: requestNode.id,
- driver: input.entry.runtime.driver,
- occurredAt: now,
- payload: {
- ...requestNode,
- status: input.reason === "runtime_error" ? "failed" : "cancelled",
- completedAt: now,
- },
- });
- }
-
- const turnItem = projection.turnItems.find(
- (item) =>
- (item.type === "approval_request" || item.type === "user_input_request") &&
- item.requestId === request.id,
- );
- if (turnItem !== undefined) {
- events.push({
- id: yield* idAllocator.allocate.event({
- threadId,
- providerSessionId,
- }),
- type: "turn-item.updated",
+ const turnItem = projection.turnItems.find(
+ (item) =>
+ (item.type === "approval_request" || item.type === "user_input_request") &&
+ item.requestId === request.id,
+ );
+ if (turnItem !== undefined) {
+ events.push({
+ id: yield* idAllocator.allocate.event({
threadId,
- ...(turnItem.runId === null ? {} : { runId: turnItem.runId }),
- ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
- driver: input.entry.runtime.driver,
- occurredAt: now,
- payload: {
- ...turnItem,
- status: input.reason === "runtime_error" ? "failed" : "cancelled",
- completedAt: now,
- updatedAt: now,
- },
- });
- }
+ providerSessionId,
+ }),
+ type: "turn-item.updated",
+ threadId,
+ ...(turnItem.runId === null ? {} : { runId: turnItem.runId }),
+ ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
+ driver: input.entry.runtime.driver,
+ occurredAt: now,
+ payload: {
+ ...turnItem,
+ status: input.reason === "runtime_error" ? "failed" : "cancelled",
+ completedAt: now,
+ updatedAt: now,
+ },
+ });
}
}
+ }
- if (events.length > 0) {
- yield* eventSink.write({ events });
- }
- });
+ if (events.length > 0) {
+ yield* eventSink.write({ events });
+ }
+ });
// Read as soon as the session leaves the live map: after that, a
// replacement session with the same id can open and report tasks of its
// own on the same provider threads. OpenCode's background subagents run
// on a server shared by its sessions and can outlive this one, so their
// roster stays.
- const readReleasedBackgroundTasks = (input: {
- readonly entry: LiveSessionEntry;
- readonly reason: ProviderSessionReleaseReason;
- readonly detachedThreadId?: ThreadId;
- }) =>
- Effect.gen(function* () {
+ const readReleasedBackgroundTasks = Effect.fn(
+ "ProviderSessionManager.readReleasedBackgroundTasks",
+ )(
+ function* (input: {
+ readonly entry: LiveSessionEntry;
+ readonly reason: ProviderSessionReleaseReason;
+ readonly detachedThreadId?: ThreadId;
+ }) {
if (
input.reason === "server_shutdown" ||
input.entry.runtime.backgroundTasksEndWithProcess !== true
@@ -767,14 +774,17 @@ export const layerWithOptions = (
}
}
return released;
- }).pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("orchestration-v2.provider-session-release-roster-read-failed", {
- providerSessionId: input.entry.runtime.providerSessionId,
- cause,
- }).pipe(Effect.as([])),
+ },
+ (effect, input) =>
+ effect.pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("orchestration-v2.provider-session-release-roster-read-failed", {
+ providerSessionId: input.entry.runtime.providerSessionId,
+ cause,
+ }).pipe(Effect.as([])),
+ ),
),
- );
+ );
type ReleasedBackgroundTasks = Effect.Success<
ReturnType<typeof readReleasedBackgroundTasks>
>[number];
@@ -907,11 +917,11 @@ export const layerWithOptions = (
// A request the event pump is persisting for this runtime lands before
// the cutoff, and once the entry is gone the pump persists no more for
// it.
- const removeLiveEntry = (input: {
- readonly providerSessionId: ProviderSessionId;
- readonly onlyIfIdleGeneration?: number;
- }): Effect.Effect<readonly [Option.Option<LiveSessionEntry>, DateTime.Utc]> =>
- Effect.gen(function* () {
+ const removeLiveEntry = Effect.fn("ProviderSessionManager.removeLiveEntry")(
+ function* (input: {
+ readonly providerSessionId: ProviderSessionId;
+ readonly onlyIfIdleGeneration?: number;
+ }): Effect.fn.Return<readonly [Option.Option<LiveSessionEntry>, DateTime.Utc]> {
const key = sessionKey(input.providerSessionId);
const candidate = (yield* Ref.get(sessions)).get(key);
if (candidate === undefined) {
@@ -942,44 +952,44 @@ export const layerWithOptions = (
outcome === "removed" ? Option.some(candidate) : Option.none<LiveSessionEntry>(),
releasedAt,
] as const;
- });
+ },
+ );
// Scope close can wedge on a misbehaving adapter finalizer (e.g. a
// provider process that never yields its message stream).
- const closeScopeWithin = (
+ const closeScopeWithin = Effect.fn("ProviderSessionManager.closeScopeWithin")(function* (
scope: Scope.Closeable,
annotations: { readonly providerSessionId?: ProviderSessionId; readonly reason: string },
- ) =>
- Effect.gen(function* () {
- const closeFiber = yield* Scope.close(scope, Exit.void).pipe(
- Effect.exit,
- Effect.forkDetach({ startImmediately: true }),
- );
- const closeExit = yield* Fiber.join(closeFiber).pipe(
- Effect.timeoutOption(RELEASE_SCOPE_CLOSE_TIMEOUT_MS),
+ ) {
+ const closeFiber = yield* Scope.close(scope, Exit.void).pipe(
+ Effect.exit,
+ Effect.forkDetach({ startImmediately: true }),
+ );
+ const closeExit = yield* Fiber.join(closeFiber).pipe(
+ Effect.timeoutOption(RELEASE_SCOPE_CLOSE_TIMEOUT_MS),
+ );
+ if (Option.isNone(closeExit)) {
+ yield* Effect.logWarning("orchestration-v2.provider-session-scope-close-timeout", {
+ ...annotations,
+ timeoutMs: RELEASE_SCOPE_CLOSE_TIMEOUT_MS,
+ });
+ yield* Fiber.join(closeFiber).pipe(
+ Effect.flatMap((exit) =>
+ Exit.isFailure(exit)
+ ? Effect.logWarning("orchestration-v2.provider-session-scope-close-failed", {
+ ...annotations,
+ cause: exit.cause,
+ })
+ : Effect.logInfo(
+ "orchestration-v2.provider-session-scope-close-completed-late",
+ annotations,
+ ),
+ ),
+ Effect.forkDetach,
);
- if (Option.isNone(closeExit)) {
- yield* Effect.logWarning("orchestration-v2.provider-session-scope-close-timeout", {
- ...annotations,
- timeoutMs: RELEASE_SCOPE_CLOSE_TIMEOUT_MS,
- });
- yield* Fiber.join(closeFiber).pipe(
- Effect.flatMap((exit) =>
- Exit.isFailure(exit)
- ? Effect.logWarning("orchestration-v2.provider-session-scope-close-failed", {
- ...annotations,
- cause: exit.cause,
- })
- : Effect.logInfo(
- "orchestration-v2.provider-session-scope-close-completed-late",
- annotations,
- ),
- ),
- Effect.forkDetach,
- );
- }
- return closeExit;
- });
+ }
+ return closeExit;
+ });
const releaseEntry = (input: {
readonly providerSessionId: ProviderSessionId;
@@ -1096,11 +1106,11 @@ export const layerWithOptions = (
),
);
- const releaseIfStillIdle = (input: {
- readonly providerSessionId: ProviderSessionId;
- readonly generation: number;
- }): Effect.Effect<void> =>
- Effect.gen(function* () {
+ const releaseIfStillIdle = Effect.fn("ProviderSessionManager.releaseIfStillIdle")(
+ function* (input: {
+ readonly providerSessionId: ProviderSessionId;
+ readonly generation: number;
+ }): Effect.fn.Return<void> {
const current = yield* Ref.get(sessions);
const key = sessionKey(input.providerSessionId);
const entry = current.get(key);
@@ -1173,7 +1183,8 @@ export const layerWithOptions = (
}),
),
);
- });
+ },
+ );
const withActivityError = <A, E, R>(
providerSessionId: ProviderSessionId,
@@ -1192,42 +1203,42 @@ export const layerWithOptions = (
// Provider activity restarts the pin budget, so background work that keeps
// reporting progress (a long Claude workflow) is never cut off; only work
- // that went silent for maxIdlePinMs is released.
- const scheduleIdleReleaseInternal = (
+ // that went silent for maxIdlePinMs is released. This runs for every
+ // provider event, so keep it untraced.
+ const scheduleIdleReleaseInternal = Effect.fnUntraced(function* (
providerSessionId: ProviderSessionId,
options?: { readonly providerActivity?: boolean },
- ) =>
- Effect.gen(function* () {
- const key = sessionKey(providerSessionId);
- const current = yield* Ref.get(sessions);
- const entry = current.get(key);
- if (entry === undefined || entry.busyTurns.size > 0) {
- return;
- }
+ ) {
+ const key = sessionKey(providerSessionId);
+ const current = yield* Ref.get(sessions);
+ const entry = current.get(key);
+ if (entry === undefined || entry.busyTurns.size > 0) {
+ return;
+ }
- yield* cancelIdleFiber(entry.idleFiber);
- const generation = entry.idleGeneration + 1;
- const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe(
- Effect.andThen(releaseIfStillIdle({ providerSessionId, generation })),
- Effect.forkIn(layerScope),
- );
- const lastActivityAtMs = yield* Clock.currentTimeMillis;
- yield* Ref.update(sessions, (latest) => {
- const latestEntry = latest.get(key);
- if (latestEntry === undefined || latestEntry.busyTurns.size > 0) {
- return latest;
- }
- const updated = new Map(latest);
- updated.set(key, {
- ...latestEntry,
- idleGeneration: generation,
- idleFiber,
- lastActivityAtMs,
- ...(options?.providerActivity === true ? { pinnedSinceMs: null } : {}),
- });
- return updated;
+ yield* cancelIdleFiber(entry.idleFiber);
+ const generation = entry.idleGeneration + 1;
+ const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe(
+ Effect.andThen(releaseIfStillIdle({ providerSessionId, generation })),
+ Effect.forkIn(layerScope),
+ );
+ const lastActivityAtMs = yield* Clock.currentTimeMillis;
+ yield* Ref.update(sessions, (latest) => {
+ const latestEntry = latest.get(key);
+ if (latestEntry === undefined || latestEntry.busyTurns.size > 0) {
+ return latest;
+ }
+ const updated = new Map(latest);
+ updated.set(key, {
+ ...latestEntry,
+ idleGeneration: generation,
+ idleFiber,
+ lastActivityAtMs,
+ ...(options?.providerActivity === true ? { pinnedSinceMs: null } : {}),
});
+ return updated;
});
+ });
const scheduleIdleRelease = (providerSessionId: ProviderSessionId) =>
withActivityError(providerSessionId, scheduleIdleReleaseInternal(providerSessionId));
@@ -1518,12 +1529,12 @@ export const layerWithOptions = (
* cannot land between a resume that found the thread loaded and the turn
* that relies on it.
*/
- const holdThreadLoaded = (input: {
- readonly providerSessionId: ProviderSessionId;
- readonly threadId: ThreadId;
- readonly providerThread: OrchestrationV2ProviderThread;
- }) =>
- Effect.gen(function* () {
+ const holdThreadLoaded = Effect.fn("ProviderSessionManager.holdThreadLoaded")(
+ function* (input: {
+ readonly providerSessionId: ProviderSessionId;
+ readonly threadId: ThreadId;
+ readonly providerThread: OrchestrationV2ProviderThread;
+ }) {
const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId));
if (
entry === undefined ||
@@ -1543,13 +1554,11 @@ export const layerWithOptions = (
}),
);
yield* cancelIdleFiber(previous?.fiber ?? null);
- });
+ },
+ );
- const scheduleThreadUnload = (
- providerSessionId: ProviderSessionId,
- providerThreadId: ProviderThreadId,
- ) =>
- Effect.gen(function* () {
+ const scheduleThreadUnload = Effect.fn("ProviderSessionManager.scheduleThreadUnload")(
+ function* (providerSessionId: ProviderSessionId, providerThreadId: ProviderThreadId) {
const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId));
if (entry === undefined || hasBusyTurn(entry, providerThreadId)) return;
const tracked = Array.from(entry.idleThreadUnloads).find(
@@ -1570,14 +1579,15 @@ export const layerWithOptions = (
yield* cancelIdleFiber(
previous?.generation === pending.generation ? previous.fiber : fiber,
);
- });
+ },
+ );
- const unloadIdleThread = (input: {
- readonly providerSessionId: ProviderSessionId;
- readonly threadId: ThreadId;
- readonly generation: number;
- }): Effect.Effect<void> =>
- Effect.gen(function* () {
+ const unloadIdleThread = Effect.fn("ProviderSessionManager.unloadIdleThread")(
+ function* (input: {
+ readonly providerSessionId: ProviderSessionId;
+ readonly threadId: ThreadId;
+ readonly generation: number;
+ }): Effect.fn.Return<void> {
const outcome = yield* threadAttachment.withLock(
threadAttachmentKey(input),
Effect.gen(function* () {
@@ -1647,7 +1657,8 @@ export const layerWithOptions = (
yield* Effect.sleep(Duration.millis(idleTimeoutMs));
return yield* unloadIdleThread(input);
}
- });
+ },
+ );
const observeActivity = (
providerSessionId: ProviderSessionId,
@@ -1662,12 +1673,12 @@ export const layerWithOptions = (
),
);
- const makeEventSubscription = (
- subscribers: Ref.Ref<
- ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
- >,
- ): Effect.Effect<ProviderAdapter.ProviderAdapterV2EventSubscription> =>
- Effect.gen(function* () {
+ const makeEventSubscription = Effect.fn("ProviderSessionManager.makeEventSubscription")(
+ function* (
+ subscribers: Ref.Ref<
+ ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
+ >,
+ ): Effect.fn.Return<ProviderAdapter.ProviderAdapterV2EventSubscription> {
const queue = yield* Queue.unbounded<ProviderSessionEventSignal, Cause.Done>();
const subscriberId = yield* Ref.getAndUpdate(nextSubscriberId, (value) => value + 1);
yield* Ref.update(subscribers, (current) => {
@@ -1698,7 +1709,8 @@ export const layerWithOptions = (
Stream.ensuring(close),
);
return { events, close } satisfies ProviderAdapter.ProviderAdapterV2EventSubscription;
- });
+ },
+ );
const decorateRuntime = (
runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
@@ -1880,14 +1892,16 @@ export const layerWithOptions = (
};
};
- const persistProviderSessionUpdate = (
- entry: LiveSessionEntry,
- event: Extract<
- ProviderAdapter.ProviderAdapterV2Event,
- { readonly type: "provider_session.updated" }
- >,
- ) =>
- Effect.gen(function* () {
+ const persistProviderSessionUpdate = Effect.fn(
+ "ProviderSessionManager.persistProviderSessionUpdate",
+ )(
+ function* (
+ entry: LiveSessionEntry,
+ event: Extract<
+ ProviderAdapter.ProviderAdapterV2Event,
+ { readonly type: "provider_session.updated" }
+ >,
+ ) {
const current = (yield* Ref.get(sessions)).get(
sessionKey(entry.runtime.providerSessionId),
);
@@ -1900,14 +1914,17 @@ export const layerWithOptions = (
type: "provider-session.updated",
payload: event.providerSession,
});
- }).pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("orchestration-v2.driver-session.status-persist-failed", {
- providerSessionId: entry.runtime.providerSessionId,
- cause,
- }),
+ },
+ (effect, entry, _event) =>
+ effect.pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("orchestration-v2.driver-session.status-persist-failed", {
+ providerSessionId: entry.runtime.providerSessionId,
+ cause,
+ }),
+ ),
),
- );
+ );
const startEventPump = (entry: LiveSessionEntry) => {
let stoppedByProvider = false;
@@ -2248,23 +2265,26 @@ export const layerWithOptions = (
Ref.get(sessions).pipe(
Effect.map((current) => current.has(sessionKey(providerSessionId))),
),
- get: (providerSessionId) =>
- Effect.gen(function* () {
+ get: Effect.fn("ProviderSessionManager.get")(
+ function* (providerSessionId) {
const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId));
if (entry === undefined) {
return Option.none<ProviderAdapter.ProviderAdapterV2SessionRuntime>();
}
yield* touchActivity(providerSessionId);
return Option.some(entry.exposedRuntime);
- }).pipe(
- Effect.mapError(
- (cause) =>
- new ProviderSessionLookupError({
- providerSessionId,
- cause,
- }),
+ },
+ (effect, providerSessionId) =>
+ effect.pipe(
+ Effect.mapError(
+ (cause) =>
+ new ProviderSessionLookupError({
+ providerSessionId,
+ cause,
+ }),
+ ),
),
- ),
+ ),
close: (providerSessionId) =>
releaseEntry({ providerSessionId, reason: "manual_shutdown" }).pipe(
Effect.mapError(
@@ -2275,8 +2295,8 @@ export const layerWithOptions = (
}),
),
),
- closeInstance: (instanceId) =>
- Effect.gen(function* () {
+ closeInstance: Effect.fn("ProviderSessionManager.closeInstance")(
+ function* (instanceId) {
const active = [...(yield* Ref.get(sessions)).values()].filter(
(entry) => entry.runtime.instanceId === instanceId,
);
@@ -2294,20 +2314,23 @@ export const layerWithOptions = (
if (failure !== undefined && Exit.isFailure(failure)) {
return yield* Effect.failCause(failure.cause);
}
- }).pipe(
- Effect.mapError(
- (cause) =>
- new ProviderSessionCloseError({
- providerSessionId: ProviderSessionId.make(
- `provider-session:provider-instance:${instanceId}`,
- ),
- cause,
- }),
+ },
+ (effect, instanceId) =>
+ effect.pipe(
+ Effect.mapError(
+ (cause) =>
+ new ProviderSessionCloseError({
+ providerSessionId: ProviderSessionId.make(
+ `provider-session:provider-instance:${instanceId}`,
+ ),
+ cause,
+ }),
+ ),
),
- ),
+ ),
release: releaseEntry,
- detach: (input) =>
- Effect.gen(function* () {
+ detach: Effect.fn("ProviderSessionManager.detach")(
+ function* (input) {
const key = sessionKey(input.providerSessionId);
const currentEntry = (yield* Ref.get(sessions)).get(key);
let detachedProviderThreads: ReadonlyArray<OrchestrationV2ProviderThread> = [];
@@ -2461,17 +2484,20 @@ export const layerWithOptions = (
);
}
yield* scheduleIdleRelease(input.providerSessionId);
- }).pipe(
- Effect.catchCause((cause) =>
- Effect.fail(
- new ProviderSessionReleaseError({
- providerSessionId: input.providerSessionId,
- reason: "manual_shutdown",
- cause,
- }),
+ },
+ (effect, input) =>
+ effect.pipe(
+ Effect.catchCause((cause) =>
+ Effect.fail(
+ new ProviderSessionReleaseError({
+ providerSessionId: input.providerSessionId,
+ reason: "manual_shutdown",
+ cause,
+ }),
+ ),
),
),
- ),
+ ),
} satisfies ProviderSessionManagerV2Shape);
}),
);
diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.ts
index b27bb39bcdf..ed343e13e7f 100644
--- a/apps/server/src/orchestration-v2/ProviderSwitchService.ts
+++ b/apps/server/src/orchestration-v2/ProviderSwitchService.ts
@@ -64,8 +64,8 @@ export const layer: Layer.Layer<
Effect.gen(function* () {
const adapters = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
return ProviderSwitchServiceV2.of({
- plan: ({ projection, targetModelSelection }) =>
- Effect.gen(function* () {
+ plan: Effect.fn("ProviderSwitchService.plan")(
+ function* ({ projection, targetModelSelection }) {
const current = projection.thread.modelSelection;
const instanceChanged = current.instanceId !== targetModelSelection.instanceId;
const modelChanged = current.model !== targetModelSelection.model;
@@ -198,16 +198,19 @@ export const layer: Layer.Layer<
releaseProviderSessionIds,
transition,
};
- }).pipe(
- Effect.mapError(
- (cause) =>
- new ProviderSwitchPlanError({
- threadId: projection.thread.id,
- targetProviderInstanceId: targetModelSelection.instanceId,
- cause,
- }),
+ },
+ (effect, { projection, targetModelSelection }) =>
+ effect.pipe(
+ Effect.mapError(
+ (cause) =>
+ new ProviderSwitchPlanError({
+ threadId: projection.thread.id,
+ targetProviderInstanceId: targetModelSelection.instanceId,
+ cause,
+ }),
+ ),
),
- ),
+ ),
});
}),
);
diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts
index de03594916a..56bbae37dd9 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts
@@ -91,7 +91,7 @@ export const layer: Layer.Layer<
const projections = yield* ProjectionStore.ProjectionStoreV2;
const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
- const load = (input: {
+ const load = Effect.fn("ProviderTurnControlService.load")(function* (input: {
readonly threadId: ThreadId;
readonly providerSessionId: ProviderSessionId;
readonly replacementProviderSessionId?: ProviderSessionId;
@@ -99,46 +99,68 @@ export const layer: Layer.Layer<
readonly providerTurnId: ProviderTurnId;
readonly operation: "interrupt" | "restart" | "steer";
readonly messageId?: MessageId;
- }) =>
- Effect.gen(function* () {
- const context = yield* projections.getProviderControlContext(input.threadId, input);
- const { providerThread, providerTurn } = context;
- const targetsRecordedSession =
- providerThread?.providerSessionId === input.providerSessionId;
- const targetsCommittedReplacement =
- input.operation === "restart" &&
- input.replacementProviderSessionId !== undefined &&
- providerThread?.providerSessionId === input.replacementProviderSessionId;
- if (
- providerThread === undefined ||
- providerTurn === undefined ||
- (!targetsRecordedSession && !targetsCommittedReplacement) ||
- providerTurn.providerThreadId !== providerThread.id
- ) {
+ }) {
+ const context = yield* projections.getProviderControlContext(input.threadId, input);
+ const { providerThread, providerTurn } = context;
+ const targetsRecordedSession = providerThread?.providerSessionId === input.providerSessionId;
+ const targetsCommittedReplacement =
+ input.operation === "restart" &&
+ input.replacementProviderSessionId !== undefined &&
+ providerThread?.providerSessionId === input.replacementProviderSessionId;
+ if (
+ providerThread === undefined ||
+ providerTurn === undefined ||
+ (!targetsRecordedSession && !targetsCommittedReplacement) ||
+ providerTurn.providerThreadId !== providerThread.id
+ ) {
+ return yield* new ProviderTurnControlError({
+ threadId: input.threadId,
+ operation: input.operation,
+ providerTurnId: input.providerTurnId,
+ cause: "The recorded provider execution target is no longer valid.",
+ });
+ }
+ // A restart-session command commits the replacement binding before its
+ // process-bound effect runs. The old live runtime must still receive
+ // the interrupt, but only when the projection matches the exact
+ // replacement captured by that same durable effect.
+ const interruptProviderThread = targetsRecordedSession
+ ? providerThread
+ : { ...providerThread, providerSessionId: input.providerSessionId };
+ if (providerTurn.status !== "running") {
+ if (input.operation === "steer") {
return yield* new ProviderTurnControlError({
threadId: input.threadId,
- operation: input.operation,
+ operation: "steer",
providerTurnId: input.providerTurnId,
- cause: "The recorded provider execution target is no longer valid.",
+ turnCompleted: providerTurn.status === "completed",
+ cause: "The provider turn ended before the steering message was delivered.",
});
}
- // A restart-session command commits the replacement binding before its
- // process-bound effect runs. The old live runtime must still receive
- // the interrupt, but only when the projection matches the exact
- // replacement captured by that same durable effect.
- const interruptProviderThread = targetsRecordedSession
- ? providerThread
- : { ...providerThread, providerSessionId: input.providerSessionId };
- if (providerTurn.status !== "running") {
- if (input.operation === "steer") {
- return yield* new ProviderTurnControlError({
+ return {
+ context,
+ providerThread: interruptProviderThread,
+ providerTurn,
+ session: Option.none(),
+ };
+ }
+ const session = yield* sessions.get(input.providerSessionId);
+ if (Option.isNone(session)) {
+ // Interrupt/restart against a already-released session must not fail
+ // the durable effect (and retry 5x). The turn may still look running
+ // in projection until recovery/finalization; there is no live adapter
+ // to interrupt.
+ if (input.operation === "interrupt" || input.operation === "restart") {
+ yield* Effect.logWarning(
+ "Provider interrupt/restart found no live session; treating as already stopped",
+ {
threadId: input.threadId,
- operation: "steer",
+ operation: input.operation,
+ providerSessionId: input.providerSessionId,
providerTurnId: input.providerTurnId,
- turnCompleted: providerTurn.status === "completed",
- cause: "The provider turn ended before the steering message was delivered.",
- });
- }
+ providerTurnStatus: providerTurn.status,
+ },
+ );
return {
context,
providerThread: interruptProviderThread,
@@ -146,43 +168,19 @@ export const layer: Layer.Layer<
session: Option.none(),
};
}
- const session = yield* sessions.get(input.providerSessionId);
- if (Option.isNone(session)) {
- // Interrupt/restart against a already-released session must not fail
- // the durable effect (and retry 5x). The turn may still look running
- // in projection until recovery/finalization; there is no live adapter
- // to interrupt.
- if (input.operation === "interrupt" || input.operation === "restart") {
- yield* Effect.logWarning(
- "Provider interrupt/restart found no live session; treating as already stopped",
- {
- threadId: input.threadId,
- operation: input.operation,
- providerSessionId: input.providerSessionId,
- providerTurnId: input.providerTurnId,
- providerTurnStatus: providerTurn.status,
- },
- );
- return {
- context,
- providerThread: interruptProviderThread,
- providerTurn,
- session: Option.none(),
- };
- }
- return yield* new ProviderTurnControlError({
- threadId: input.threadId,
- operation: input.operation,
- providerTurnId: input.providerTurnId,
- cause: `Provider session ${input.providerSessionId} is not active.`,
- });
- }
- return { context, providerThread: interruptProviderThread, providerTurn, session };
- });
+ return yield* new ProviderTurnControlError({
+ threadId: input.threadId,
+ operation: input.operation,
+ providerTurnId: input.providerTurnId,
+ cause: `Provider session ${input.providerSessionId} is not active.`,
+ });
+ }
+ return { context, providerThread: interruptProviderThread, providerTurn, session };
+ });
return ProviderTurnControlServiceV2.of({
- interrupt: (input) =>
- Effect.gen(function* () {
+ interrupt: Effect.fn("ProviderTurnControlService.interrupt")(
+ function* (input) {
const loaded = yield* load({ ...input, operation: "interrupt" });
const session = Option.isSome(loaded.session)
? loaded.session
@@ -241,20 +239,23 @@ export const layer: Layer.Layer<
yield* Effect.sleep("10 millis");
}
}).pipe(Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()));
- }).pipe(
- Effect.mapError((cause) =>
- isProviderTurnControlError(cause)
- ? cause
- : new ProviderTurnControlError({
- threadId: input.threadId,
- operation: "interrupt",
- providerTurnId: input.providerTurnId,
- cause,
- }),
+ },
+ (effect, input) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ isProviderTurnControlError(cause)
+ ? cause
+ : new ProviderTurnControlError({
+ threadId: input.threadId,
+ operation: "interrupt",
+ providerTurnId: input.providerTurnId,
+ cause,
+ }),
+ ),
),
- ),
- interruptAndAwaitTerminal: (input) =>
- Effect.gen(function* () {
+ ),
+ interruptAndAwaitTerminal: Effect.fn("ProviderTurnControlService.interruptAndAwaitTerminal")(
+ function* (input) {
const loaded = yield* load({ ...input, operation: "restart" });
if (Option.isNone(loaded.session)) {
// No live adapter: nothing can emit a terminal provider-turn update
@@ -307,20 +308,23 @@ export const layer: Layer.Layer<
providerTurnId: input.providerTurnId,
cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
});
- }).pipe(
- Effect.mapError((cause) =>
- isProviderTurnControlError(cause)
- ? cause
- : new ProviderTurnControlError({
- threadId: input.threadId,
- operation: "restart",
- providerTurnId: input.providerTurnId,
- cause,
- }),
+ },
+ (effect, input) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ isProviderTurnControlError(cause)
+ ? cause
+ : new ProviderTurnControlError({
+ threadId: input.threadId,
+ operation: "restart",
+ providerTurnId: input.providerTurnId,
+ cause,
+ }),
+ ),
),
- ),
- steer: (input) =>
- Effect.gen(function* () {
+ ),
+ steer: Effect.fn("ProviderTurnControlService.steer")(
+ function* (input) {
const context = yield* projections.getProviderControlContext(input.threadId, input);
const ownership = context.message?.delegatedCompletion;
if (ownership !== undefined) {
@@ -389,18 +393,21 @@ export const layer: Layer.Layer<
}),
),
);
- }).pipe(
- Effect.mapError((cause) =>
- isProviderTurnControlError(cause)
- ? cause
- : new ProviderTurnControlError({
- threadId: input.threadId,
- operation: "steer",
- providerTurnId: input.providerTurnId,
- cause,
- }),
+ },
+ (effect, input) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ isProviderTurnControlError(cause)
+ ? cause
+ : new ProviderTurnControlError({
+ threadId: input.threadId,
+ operation: "steer",
+ providerTurnId: input.providerTurnId,
+ cause,
+ }),
+ ),
),
- ),
+ ),
});
}),
);
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
index a9e0e35e696..1f57b2a8a40 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
@@ -541,12 +541,12 @@ export const layer: Layer.Layer<
}),
}),
);
- const settleStartFailure = (failed: {
- readonly signal: string;
- readonly title: string;
- readonly error: Error;
- }) =>
- Effect.gen(function* () {
+ const settleStartFailure = Effect.fn("ProviderTurnStartService.settleStartFailure")(
+ function* (failed: {
+ readonly signal: string;
+ readonly title: string;
+ readonly error: Error;
+ }) {
const nestedCause = "cause" in failed.error ? failed.error.cause : undefined;
yield* settleRunBeforeStart({
signal: failed.signal,
@@ -569,7 +569,8 @@ export const layer: Layer.Layer<
}),
},
});
- });
+ },
+ );
if (sessionResult._tag === "Failure") {
if (input.willRetry === true) return yield* sessionResult.failure;
yield* settleStartFailure({
@@ -581,20 +582,19 @@ export const layer: Layer.Layer<
}
const session = sessionResult.success;
if (!(yield* isCurrentAttemptInStatus("starting"))) return;
- const loadFromProvider = (
+ const loadFromProvider = Effect.fn("ProviderTurnStartService.loadFromProvider")(function* (
load: Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapter.ProviderAdapterV2Error>,
- ) =>
- Effect.gen(function* () {
- const loaded = yield* Effect.result(load);
- if (loaded._tag === "Success") return loaded.success;
- if (input.willRetry === true) return yield* loaded.failure;
- yield* settleStartFailure({
- signal: "provider-thread-load-failure",
- title: "Provider turn failed to start",
- error: loaded.failure,
- });
- return undefined;
+ ) {
+ const loaded = yield* Effect.result(load);
+ if (loaded._tag === "Success") return loaded.success;
+ if (input.willRetry === true) return yield* loaded.failure;
+ yield* settleStartFailure({
+ signal: "provider-thread-load-failure",
+ title: "Provider turn failed to start",
+ error: loaded.failure,
});
+ return undefined;
+ });
let effectiveHandoffs = handoffs;
const loadedProviderThread = yield* Effect.gen(function* () {
if (nativeForkTransfer !== undefined) {
@@ -1073,11 +1073,8 @@ export const layer: Layer.Layer<
!coveredItemIds.has(item.id) &&
historicalMessage(item) !== null,
);
- const startWithHandoffs = (
- turnInput: Parameters<typeof session.startTurn>[0],
- compact = false,
- ) =>
- Effect.gen(function* () {
+ const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")(
+ function* (turnInput: Parameters<typeof session.startTurn>[0], compact = false) {
const retryHandoff =
missedItems.length === 0
? []
@@ -1127,25 +1124,24 @@ export const layer: Layer.Layer<
...history,
}),
}),
- persist: (handoff) =>
- Effect.gen(function* () {
- const updatedAt = yield* DateTime.now;
- yield* eventSink.write({
- events: [
- {
- id: yield* idAllocator.allocate.event({
- threadId: projection.thread.id,
- }),
- type: "context-handoff.updated",
+ persist: Effect.fn("ProviderTurnStartService.persist")(function* (handoff) {
+ const updatedAt = yield* DateTime.now;
+ yield* eventSink.write({
+ events: [
+ {
+ id: yield* idAllocator.allocate.event({
threadId: projection.thread.id,
- runId: run.id,
- providerInstanceId: run.providerInstanceId,
- occurredAt: updatedAt,
- payload: { ...handoff, updatedAt },
- },
- ],
- });
- }),
+ }),
+ type: "context-handoff.updated",
+ threadId: projection.thread.id,
+ runId: run.id,
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: updatedAt,
+ payload: { ...handoff, updatedAt },
+ },
+ ],
+ });
+ }),
});
if (!(yield* isCurrentAttemptInStatus("running"))) return;
const start = compact ? session.compactThread! : session.startTurn;
@@ -1184,19 +1180,19 @@ export const layer: Layer.Layer<
}),
),
);
- }).pipe(
- Effect.mapError((cause) =>
- cause._tag === "ProviderAdapterTurnStartError"
- ? cause
- : new ProviderAdapter.ProviderAdapterTurnStartError({
- driver: session.driver,
- threadId: projection.thread.id,
- providerThreadId: providerThread.id,
- runId: run.id,
- cause,
- }),
- ),
- );
+ },
+ Effect.mapError((cause) =>
+ cause._tag === "ProviderAdapterTurnStartError"
+ ? cause
+ : new ProviderAdapter.ProviderAdapterTurnStartError({
+ driver: session.driver,
+ threadId: projection.thread.id,
+ providerThreadId: providerThread.id,
+ runId: run.id,
+ cause,
+ }),
+ ),
+ );
const deliverySession =
effectiveHandoffs.length === 0 &&
missedItems.length === 0 &&
@@ -1256,8 +1252,8 @@ export const layer: Layer.Layer<
});
return ProviderTurnStartServiceV2.of({
- start: (input) =>
- Effect.gen(function* () {
+ start: Effect.fn("ProviderTurnStartService.start")(
+ function* (input) {
// Storage cleanup removes worktrees under the same lease. Only startup
// holds it; the provider turn runs after it is released.
const { thread } = yield* projectionStore.getThreadRecords(input.threadId, []);
@@ -1265,13 +1261,16 @@ export const layer: Layer.Layer<
? start(input)
: withWorkspaceLease(path.resolve(thread.worktreePath), start(input));
if (providerTurn !== undefined) yield* providerTurn;
- }).pipe(
- Effect.mapError((cause) =>
- isProviderTurnStartError(cause)
- ? cause
- : new ProviderTurnStartError({ runId: input.runId, cause }),
+ },
+ (effect, input) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ isProviderTurnStartError(cause)
+ ? cause
+ : new ProviderTurnStartError({ runId: input.runId, cause }),
+ ),
),
- ),
+ ),
});
}),
);
diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
index 165e08407e1..6589d51d56d 100644
--- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
+++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
@@ -218,23 +218,26 @@ export const make = Effect.gen(function* () {
lives.set(lifeKey(target), { ...life, wakes: life.wakes + 1 });
});
- const reportEnd = (key: string, life: WatchLife, reason: WatchEndReason) =>
- Effect.gen(function* () {
- lives.delete(key);
- const now = yield* Clock.currentTimeMillis;
- const quietMs = now - life.pushedAt;
- yield* Effect.logInfo("pull request watch ended", {
- threadId: life.threadId,
- pullRequest: life.pullRequest,
- reason,
- minutes: minutes(now - life.startedAt),
- quietMinutes: minutes(quietMs),
- longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
- wakes: life.wakes,
- reads: life.reads,
- partial: life.startedAt < bootedAt,
- });
+ const reportEnd = Effect.fn("PullRequestWatchReactor.reportEnd")(function* (
+ key: string,
+ life: WatchLife,
+ reason: WatchEndReason,
+ ) {
+ lives.delete(key);
+ const now = yield* Clock.currentTimeMillis;
+ const quietMs = now - life.pushedAt;
+ yield* Effect.logInfo("pull request watch ended", {
+ threadId: life.threadId,
+ pullRequest: life.pullRequest,
+ reason,
+ minutes: minutes(now - life.startedAt),
+ quietMinutes: minutes(quietMs),
+ longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
+ wakes: life.wakes,
+ reads: life.reads,
+ partial: life.startedAt < bootedAt,
});
+ });
const ended = (target: WatchTarget, reason: WatchEndReason) =>
Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason));
@@ -255,27 +258,26 @@ export const make = Effect.gen(function* () {
* The orchestrator applies this only while the same watch is on, so a stop or restart
* that lands during the host read wins.
*/
- const record = (
+ const record = Effect.fn("PullRequestWatchReactor.record")(function* (
target: WatchTarget,
next: ThreadPullRequestWatch | null,
wake?: { readonly text: string; readonly notification: OrchestrationV2Notification },
endedWatch?: ThreadPullRequestWatch,
- ) =>
- Effect.gen(function* () {
- const uuid = yield* crypto.randomUUIDv4();
- yield* engine.dispatch({
- type: "thread.pull-request-watch.sync",
- commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
- threadId: target.thread.id,
- ...identityOf(target.link),
- startedAt: target.watch.startedAt,
- watch: next,
- ...(endedWatch === undefined ? {} : { endedWatch }),
- ...(wake === undefined
- ? {}
- : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
- });
+ ) {
+ const uuid = yield* crypto.randomUUIDv4();
+ yield* engine.dispatch({
+ type: "thread.pull-request-watch.sync",
+ commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
+ threadId: target.thread.id,
+ ...identityOf(target.link),
+ startedAt: target.watch.startedAt,
+ watch: next,
+ ...(endedWatch === undefined ? {} : { endedWatch }),
+ ...(wake === undefined
+ ? {}
+ : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
});
+ });
const giveUp = (target: WatchTarget) =>
record(target, null, {
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts
index 9abe812c3d1..74916428333 100644
--- a/apps/server/src/orchestration-v2/RunExecutionService.ts
+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts
@@ -201,120 +201,120 @@ function withLinkedChildThreadId(
return { ...current, linkedChildThreadIds };
}
-export function cascadeTerminalizeRunOwnedSubagents(input: {
+export const cascadeTerminalizeRunOwnedSubagents = Effect.fn(
+ "RunExecutionService.cascadeTerminalizeRunOwnedSubagents",
+)(function* (input: {
readonly run: OrchestrationV2Run;
readonly open: OpenRunOwnedSubagentProjection;
readonly status: RunOwnedSubagentTerminalStatus;
readonly completedAt: DateTime.Utc;
readonly allocateEventId: () => Effect.Effect<EventId, IdAllocator.IdAllocatorV2AllocationError>;
-}): Effect.Effect<
+}): Effect.fn.Return<
ReadonlyArray<OrchestrationV2DomainEvent>,
IdAllocator.IdAllocatorV2AllocationError
> {
- return Effect.gen(function* () {
- const events: Array<OrchestrationV2DomainEvent> = [];
- // Prefer lifetime linkage over currently-open rows: subagent/turn-item
- // snapshots may terminalize before the linked child-thread node settles.
- const childThreadIds = new Set(input.open.linkedChildThreadIds);
- for (const item of [...input.open.subagents.values(), ...input.open.turnItems.values()]) {
- if (item.childThreadId !== null) {
- childThreadIds.add(item.childThreadId);
- }
+ const events: Array<OrchestrationV2DomainEvent> = [];
+ // Prefer lifetime linkage over currently-open rows: subagent/turn-item
+ // snapshots may terminalize before the linked child-thread node settles.
+ const childThreadIds = new Set(input.open.linkedChildThreadIds);
+ for (const item of [...input.open.subagents.values(), ...input.open.turnItems.values()]) {
+ if (item.childThreadId !== null) {
+ childThreadIds.add(item.childThreadId);
}
- const keys = new Set<NodeId>([
- ...input.open.subagents.keys(),
- ...input.open.turnItems.keys(),
- ...input.open.nodes.keys(),
- ]);
- for (const key of keys) {
- const subagent = input.open.subagents.get(key);
- if (subagent !== undefined && !isSettledSubagentStatus(subagent.status)) {
- events.push({
- id: yield* input.allocateEventId(),
- type: "subagent.updated",
- threadId: subagent.threadId,
- runId: input.run.id,
- nodeId: subagent.id,
- driver: subagent.driver,
- providerInstanceId: subagent.providerInstanceId,
- occurredAt: input.completedAt,
- payload: {
- ...subagent,
- status: input.status,
- completedAt: input.completedAt,
- updatedAt: input.completedAt,
- },
- });
- }
- const node = input.open.nodes.get(key);
- if (
- node !== undefined &&
- ((node.threadId === input.run.threadId && node.runId === input.run.id) ||
- childThreadIds.has(node.threadId)) &&
- isOpenExecutionNodeStatus(node.status)
- ) {
- events.push({
- id: yield* input.allocateEventId(),
- type: "node.updated",
- threadId: node.threadId,
- runId: node.runId ?? input.run.id,
- nodeId: node.id,
- providerInstanceId: input.run.providerInstanceId,
- occurredAt: input.completedAt,
- payload: {
- ...node,
- status: input.status,
- completedAt: input.completedAt,
- },
- });
- }
- const turnItem = input.open.turnItems.get(key);
- if (
- turnItem !== undefined &&
- turnItem.runId === input.run.id &&
- !isSettledTurnItemStatus(turnItem.status)
- ) {
- events.push({
- id: yield* input.allocateEventId(),
- type: "turn-item.updated",
- threadId: turnItem.threadId,
- runId: input.run.id,
- ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
- providerInstanceId: input.run.providerInstanceId,
- occurredAt: input.completedAt,
- payload: {
- ...turnItem,
- status: input.status,
- completedAt: input.completedAt,
- updatedAt: input.completedAt,
- },
- });
- }
+ }
+ const keys = new Set<NodeId>([
+ ...input.open.subagents.keys(),
+ ...input.open.turnItems.keys(),
+ ...input.open.nodes.keys(),
+ ]);
+ for (const key of keys) {
+ const subagent = input.open.subagents.get(key);
+ if (subagent !== undefined && !isSettledSubagentStatus(subagent.status)) {
+ events.push({
+ id: yield* input.allocateEventId(),
+ type: "subagent.updated",
+ threadId: subagent.threadId,
+ runId: input.run.id,
+ nodeId: subagent.id,
+ driver: subagent.driver,
+ providerInstanceId: subagent.providerInstanceId,
+ occurredAt: input.completedAt,
+ payload: {
+ ...subagent,
+ status: input.status,
+ completedAt: input.completedAt,
+ updatedAt: input.completedAt,
+ },
+ });
}
- for (const turnItem of input.open.childTurnItems.values()) {
- if (!childThreadIds.has(turnItem.threadId) || isSettledTurnItemStatus(turnItem.status)) {
- continue;
- }
+ const node = input.open.nodes.get(key);
+ if (
+ node !== undefined &&
+ ((node.threadId === input.run.threadId && node.runId === input.run.id) ||
+ childThreadIds.has(node.threadId)) &&
+ isOpenExecutionNodeStatus(node.status)
+ ) {
+ events.push({
+ id: yield* input.allocateEventId(),
+ type: "node.updated",
+ threadId: node.threadId,
+ runId: node.runId ?? input.run.id,
+ nodeId: node.id,
+ providerInstanceId: input.run.providerInstanceId,
+ occurredAt: input.completedAt,
+ payload: {
+ ...node,
+ status: input.status,
+ completedAt: input.completedAt,
+ },
+ });
+ }
+ const turnItem = input.open.turnItems.get(key);
+ if (
+ turnItem !== undefined &&
+ turnItem.runId === input.run.id &&
+ !isSettledTurnItemStatus(turnItem.status)
+ ) {
events.push({
id: yield* input.allocateEventId(),
type: "turn-item.updated",
threadId: turnItem.threadId,
- runId: turnItem.runId ?? input.run.id,
+ runId: input.run.id,
...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
providerInstanceId: input.run.providerInstanceId,
occurredAt: input.completedAt,
payload: {
...turnItem,
- ...("streaming" in turnItem ? { streaming: false } : {}),
status: input.status,
completedAt: input.completedAt,
updatedAt: input.completedAt,
},
});
}
- return events;
- });
-}
+ }
+ for (const turnItem of input.open.childTurnItems.values()) {
+ if (!childThreadIds.has(turnItem.threadId) || isSettledTurnItemStatus(turnItem.status)) {
+ continue;
+ }
+ events.push({
+ id: yield* input.allocateEventId(),
+ type: "turn-item.updated",
+ threadId: turnItem.threadId,
+ runId: turnItem.runId ?? input.run.id,
+ ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
+ providerInstanceId: input.run.providerInstanceId,
+ occurredAt: input.completedAt,
+ payload: {
+ ...turnItem,
+ ...("streaming" in turnItem ? { streaming: false } : {}),
+ status: input.status,
+ completedAt: input.completedAt,
+ updatedAt: input.completedAt,
+ },
+ });
+ }
+ return events;
+});
export function finalProviderThreadStatus(
disposition: ProviderTerminalEvent["threadDisposition"],
@@ -582,24 +582,24 @@ export const layer: Layer.Layer<
const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
const finalizationObserver = yield* RunFinalizationService.RunFinalizationObserver;
- const writeFinalRunEvents = (input: {
- readonly run: OrchestrationV2Run;
- readonly rootNode: OrchestrationV2ExecutionNode;
- readonly checkpointScope: OrchestrationV2CheckpointScope;
- readonly providerThread: OrchestrationV2ProviderThread;
- readonly attempt: OrchestrationV2RunAttempt;
- readonly shouldFinalizeRun?: () => Effect.Effect<boolean, ProjectionStoreV2Error>;
- readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
- readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;
- readonly terminal: ProviderTerminalEvent;
- readonly failureItemPersisted: boolean;
- readonly refreshAfterTurn: Effect.Effect<void>;
- readonly writeIfRunCurrent?: {
- readonly activeAttemptId: RunAttemptId;
- readonly expectedStatus: OrchestrationV2Run["status"];
- };
- }) =>
- Effect.gen(function* () {
+ const writeFinalRunEvents = Effect.fn("RunExecutionService.writeFinalRunEvents")(
+ function* (input: {
+ readonly run: OrchestrationV2Run;
+ readonly rootNode: OrchestrationV2ExecutionNode;
+ readonly checkpointScope: OrchestrationV2CheckpointScope;
+ readonly providerThread: OrchestrationV2ProviderThread;
+ readonly attempt: OrchestrationV2RunAttempt;
+ readonly shouldFinalizeRun?: () => Effect.Effect<boolean, ProjectionStoreV2Error>;
+ readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
+ readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;
+ readonly terminal: ProviderTerminalEvent;
+ readonly failureItemPersisted: boolean;
+ readonly refreshAfterTurn: Effect.Effect<void>;
+ readonly writeIfRunCurrent?: {
+ readonly activeAttemptId: RunAttemptId;
+ readonly expectedStatus: OrchestrationV2Run["status"];
+ };
+ }) {
const completedAt = yield* DateTime.now;
const finalizedAttempt: OrchestrationV2RunAttempt | null = {
...input.attempt,
@@ -816,697 +816,690 @@ export const layer: Layer.Layer<
yield* eventSink.writeWithEffects(finalization);
}
yield* input.refreshAfterTurn;
- });
+ },
+ );
return RunExecutionServiceV2.of({
- startRootRun: (input) =>
- Effect.gen(function* () {
- // Startup failure and stream shutdown can report the same attempt.
- const refreshAfterTurn = yield* Effect.cached(
- finalizationObserver.refreshAfterTurn(input.appThread.projectId).pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("failed to refresh pull requests after run termination", {
- threadId: input.run.threadId,
- runId: input.run.id,
- cause,
- }),
- ),
- ),
- );
- const makeFailedTerminalEvent = (
- failure: OrchestrationV2ProviderFailure,
- failureItemOrdinal: number,
- ): ProviderTerminalEvent => ({
- type: "turn.terminal",
- driver: input.providerThread.driver,
- providerThreadId: input.providerThread.id,
- providerTurnId:
- input.attempt.providerTurnId ??
- idAllocator.derive.providerTurn({
- driver: input.providerThread.driver,
- nativeTurnId: `failed:${input.attempt.id}`,
- }),
- runOrdinal: input.run.ordinal,
- failureItemOrdinal,
- status: "failed",
- failure,
- threadDisposition: "reusable",
- });
- const responseStreamingMode = yield* Effect.gen(function* () {
- const responseStreamingMode = yield* serverSettings.getSettings.pipe(
- Effect.map(
- (settings) =>
- resolveProjectSettings(settings, input.appThread.projectId).settings
- .responseStreamingMode,
- ),
- );
- yield* checkpointService
- .captureBaseline({
- scope: input.checkpointScope,
- ordinalWithinScope: Math.max(0, input.run.ordinal - 1),
- })
- .pipe(
- Effect.catchCause((cause) =>
- Cause.hasInterruptsOnly(cause)
- ? Effect.failCause(cause)
- : Effect.logWarning(
- "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline",
- { runId: input.run.id },
- ),
- ),
- );
- if (
- input.shouldStartProviderTurn !== undefined &&
- !(yield* input.shouldStartProviderTurn())
- ) {
- return null;
- }
- return responseStreamingMode;
- }).pipe(
+ startRootRun: Effect.fn("RunExecutionService.startRootRun")(function* (input) {
+ // Startup failure and stream shutdown can report the same attempt.
+ const refreshAfterTurn = yield* Effect.cached(
+ finalizationObserver.refreshAfterTurn(input.appThread.projectId).pipe(
Effect.catchCause((cause) =>
- Effect.gen(function* () {
- if (Cause.hasInterruptsOnly(cause)) {
- return yield* Effect.failCause(cause);
- }
- yield* Effect.logError("orchestration V2 run preparation failed", {
- runId: input.run.id,
- cause,
- });
- yield* writeFinalRunEvents({
- run: input.run,
- rootNode: input.rootNode,
- checkpointScope: input.checkpointScope,
- providerThread: input.providerThread,
- attempt: input.attempt,
- terminal: makeFailedTerminalEvent(
- makeProviderFailure({
- cause: Cause.squash(cause),
- message: "Run preparation failed.",
- class: "unknown",
- }),
- input.providerTurnOrdinal * 100 + 1,
- ),
- failureItemPersisted: false,
- refreshAfterTurn,
- writeIfRunCurrent: {
- activeAttemptId: input.attemptId,
- expectedStatus: "running",
- },
- });
- return null;
+ Effect.logWarning("failed to refresh pull requests after run termination", {
+ threadId: input.run.threadId,
+ runId: input.run.id,
+ cause,
}),
),
- Effect.mapError(
- (cause) =>
- new RunExecutionStartError({
- commandId: input.commandId,
- runId: input.run.id,
- cause,
- }),
+ ),
+ );
+ const makeFailedTerminalEvent = (
+ failure: OrchestrationV2ProviderFailure,
+ failureItemOrdinal: number,
+ ): ProviderTerminalEvent => ({
+ type: "turn.terminal",
+ driver: input.providerThread.driver,
+ providerThreadId: input.providerThread.id,
+ providerTurnId:
+ input.attempt.providerTurnId ??
+ idAllocator.derive.providerTurn({
+ driver: input.providerThread.driver,
+ nativeTurnId: `failed:${input.attempt.id}`,
+ }),
+ runOrdinal: input.run.ordinal,
+ failureItemOrdinal,
+ status: "failed",
+ failure,
+ threadDisposition: "reusable",
+ });
+ const responseStreamingMode = yield* Effect.gen(function* () {
+ const responseStreamingMode = yield* serverSettings.getSettings.pipe(
+ Effect.map(
+ (settings) =>
+ resolveProjectSettings(settings, input.appThread.projectId).settings
+ .responseStreamingMode,
),
);
- if (responseStreamingMode === null) {
- return;
+ yield* checkpointService
+ .captureBaseline({
+ scope: input.checkpointScope,
+ ordinalWithinScope: Math.max(0, input.run.ordinal - 1),
+ })
+ .pipe(
+ Effect.catchCause((cause) =>
+ Cause.hasInterruptsOnly(cause)
+ ? Effect.failCause(cause)
+ : Effect.logWarning(
+ "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline",
+ { runId: input.run.id },
+ ),
+ ),
+ );
+ if (
+ input.shouldStartProviderTurn !== undefined &&
+ !(yield* input.shouldStartProviderTurn())
+ ) {
+ return null;
}
- const terminalEvent = yield* Ref.make<ProviderTerminalEvent | null>(null);
- const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);
- const latestProviderThread = yield* Ref.make(input.providerThread);
- const routeIdentity: ProviderEventRouteIdentity = {
- threadId: input.run.threadId,
- runId: input.run.id,
- attemptId: input.attempt.id,
- providerThreadId: input.providerThread.id,
- };
- const eventSubscription =
- input.session.subscribeEvents === undefined
- ? { events: input.session.events, close: Effect.void }
- : yield* input.session.subscribeEvents;
- const inheritedBackgroundTurnItems = yield* (
- input.loadInheritedBackgroundTurnItems?.() ?? Effect.succeed([])
- ).pipe(
- Effect.onError(() => eventSubscription.close),
- Effect.mapError(
- (cause) =>
- new RunExecutionStartError({
- commandId: input.commandId,
- runId: input.run.id,
- cause,
- }),
- ),
- );
- const inheritedBackgroundTurnItemsById = new Map(
- inheritedBackgroundTurnItems.map((item) => [item.id, item.runId]),
- );
- const eventRouting = yield* Ref.make<ProviderEventRoutingState>(
- makeProviderEventRoutingState({
- identity: routeIdentity,
- inheritedBackgroundTurnItems,
- providerTurnId: input.attempt.providerTurnId,
- ...(input.relatedThreadIds === undefined
- ? {}
- : { relatedThreadIds: input.relatedThreadIds }),
- ...(input.relatedProviderThreadIds === undefined
- ? {}
- : { relatedProviderThreadIds: input.relatedProviderThreadIds }),
- }),
- );
- const rootTerminalSeen = yield* Ref.make(false);
- const rootRunFinalized = yield* Ref.make(false);
- const providerThreadOwnerLost = yield* Ref.make(false);
- const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
- const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
- const activeBackgroundTurnItems = yield* Ref.make<
- ReadonlySet<OrchestrationV2TurnItem["id"]>
- >(new Set(inheritedBackgroundTurnItemsById.keys()));
- const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection());
- const finalizeRootRun = (terminal: ProviderTerminalEvent) =>
+ return responseStreamingMode;
+ }).pipe(
+ Effect.catchCause((cause) =>
Effect.gen(function* () {
- if (yield* Ref.get(rootRunFinalized)) {
- return;
+ if (Cause.hasInterruptsOnly(cause)) {
+ return yield* Effect.failCause(cause);
}
- const providerThread = yield* Ref.get(latestProviderThread);
- const openSubagents = yield* Ref.get(openRunOwnedSubagents);
+ yield* Effect.logError("orchestration V2 run preparation failed", {
+ runId: input.run.id,
+ cause,
+ });
yield* writeFinalRunEvents({
run: input.run,
rootNode: input.rootNode,
checkpointScope: input.checkpointScope,
- providerThread,
+ providerThread: input.providerThread,
attempt: input.attempt,
- ...(input.shouldFinalizeRun === undefined
- ? {}
- : {
- shouldFinalizeRun: input.shouldFinalizeRun,
- // Stop may commit between the ownership read and this
- // terminal write. Gate the events and checkpoint together.
- writeIfRunCurrent: {
- activeAttemptId: input.attempt.id,
- expectedStatus: "running" as const,
- },
- }),
- ...(input.hasUnpairedRunInterruptRequest === undefined
- ? {}
- : {
- hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
- }),
- openRunOwnedSubagents: openSubagents,
- terminal,
- failureItemPersisted: terminal.status === "failed",
- refreshAfterTurn,
- }).pipe(
- Effect.mapError(
- (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
+ terminal: makeFailedTerminalEvent(
+ makeProviderFailure({
+ cause: Cause.squash(cause),
+ message: "Run preparation failed.",
+ class: "unknown",
+ }),
+ input.providerTurnOrdinal * 100 + 1,
),
- );
- if (
- isRunOwnedSubagentTerminalStatus(terminal.status) &&
- !childTurnsContinue(terminal)
- ) {
- yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());
- }
- yield* Ref.set(rootRunFinalized, true);
- });
- const trackChildLifecycle = (
- event: ProviderAdapter.ProviderAdapterV2Event,
- deliverable: boolean,
- ) =>
- Effect.gen(function* () {
- const routing = yield* Ref.get(eventRouting);
- if (event.type === "provider_turn.updated") {
- const isRoot =
- event.providerTurn.runAttemptId === input.attempt.id ||
- event.providerTurn.id === routing.rootProviderTurnId;
- if (!isRoot) {
- yield* Ref.update(activeChildProviderTurns, (current) => {
- const next = new Set(current);
- if (isTerminalProviderTurnStatus(event.providerTurn.status)) {
- next.delete(event.providerTurn.id);
- } else {
- next.add(event.providerTurn.id);
- }
- return next;
- });
- }
- }
- if (event.type === "subagent.updated") {
- const belongsToRootRun = event.subagent.runId === input.run.id;
- const belongsToOwnedChildThread =
- event.subagent.threadId !== input.run.threadId &&
- routing.ownedThreadIds.has(event.subagent.threadId);
- if (belongsToRootRun || belongsToOwnedChildThread) {
- yield* Ref.update(activeChildSubagents, (current) => {
- const next = new Set(current);
- if (isSettledSubagentStatus(event.subagent.status)) {
- next.delete(event.subagent.id);
- } else {
- next.add(event.subagent.id);
- }
- return next;
- });
- }
- // Preserve childThreadId linkage for the root-run lifetime even after the subagent
- // row terminalizes, so open child-thread nodes can still be proven linked on a
- // later root interrupt. A provider records nested native subagents on the child
- // thread, runless; they die with this run too.
- if (
- belongsToRootRun ||
- (belongsToOwnedChildThread &&
- event.subagent.runId === null &&
- event.subagent.origin === "provider_native")
- ) {
- yield* Ref.update(openRunOwnedSubagents, (current) => {
- const withLink = withLinkedChildThreadId(current, event.subagent.childThreadId);
- const subagents = new Map(withLink.subagents);
- if (isSettledSubagentStatus(event.subagent.status)) {
- subagents.delete(event.subagent.id);
- } else {
- subagents.set(event.subagent.id, event.subagent);
- }
- return { ...withLink, subagents };
- });
- }
- }
- if (event.type === "node.updated") {
- const belongsToRootSubagent =
- event.node.kind === "subagent" && event.node.runId === input.run.id;
- const belongsToOwnedChildThread =
- event.node.threadId !== input.run.threadId &&
- routing.ownedThreadIds.has(event.node.threadId);
- if (
- !belongsToRootSubagent &&
- !(
- belongsToOwnedChildThread &&
- (event.node.runId === null || event.node.runId === input.run.id)
- )
- ) {
- return;
- }
- yield* Ref.update(openRunOwnedSubagents, (current) => {
- const nodes = new Map(current.nodes);
- if (isOpenExecutionNodeStatus(event.node.status)) {
- nodes.set(event.node.id, event.node);
- } else {
- nodes.delete(event.node.id);
- }
- return { ...current, nodes };
- });
- }
- if (event.type === "turn_item.updated") {
- const belongsToRootRun = event.turnItem.runId === input.run.id;
- const belongsToOwnedChildThread =
- event.turnItem.threadId !== input.run.threadId &&
- routing.ownedThreadIds.has(event.turnItem.threadId);
- const belongsToInheritedBackgroundItem =
- event.turnItem.threadId === input.run.threadId &&
- event.turnItem.runId !== null &&
- inheritedBackgroundTurnItemsById.get(event.turnItem.id) === event.turnItem.runId;
- if (
- backgroundCapableTurnItemTypes.has(event.turnItem.type) &&
- (belongsToRootRun ||
- belongsToOwnedChildThread ||
- belongsToInheritedBackgroundItem)
- ) {
- yield* Ref.update(activeBackgroundTurnItems, (current) => {
- const next = new Set(current);
- if (isSettledTurnItemStatus(event.turnItem.status)) {
- next.delete(event.turnItem.id);
- } else {
- next.add(event.turnItem.id);
- }
- return next;
- });
+ failureItemPersisted: false,
+ refreshAfterTurn,
+ writeIfRunCurrent: {
+ activeAttemptId: input.attemptId,
+ expectedStatus: "running",
+ },
+ });
+ return null;
+ }),
+ ),
+ Effect.mapError(
+ (cause) =>
+ new RunExecutionStartError({
+ commandId: input.commandId,
+ runId: input.run.id,
+ cause,
+ }),
+ ),
+ );
+ if (responseStreamingMode === null) {
+ return;
+ }
+ const terminalEvent = yield* Ref.make<ProviderTerminalEvent | null>(null);
+ const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);
+ const latestProviderThread = yield* Ref.make(input.providerThread);
+ const routeIdentity: ProviderEventRouteIdentity = {
+ threadId: input.run.threadId,
+ runId: input.run.id,
+ attemptId: input.attempt.id,
+ providerThreadId: input.providerThread.id,
+ };
+ const eventSubscription =
+ input.session.subscribeEvents === undefined
+ ? { events: input.session.events, close: Effect.void }
+ : yield* input.session.subscribeEvents;
+ const inheritedBackgroundTurnItems = yield* (
+ input.loadInheritedBackgroundTurnItems?.() ?? Effect.succeed([])
+ ).pipe(
+ Effect.onError(() => eventSubscription.close),
+ Effect.mapError(
+ (cause) =>
+ new RunExecutionStartError({
+ commandId: input.commandId,
+ runId: input.run.id,
+ cause,
+ }),
+ ),
+ );
+ const inheritedBackgroundTurnItemsById = new Map(
+ inheritedBackgroundTurnItems.map((item) => [item.id, item.runId]),
+ );
+ const eventRouting = yield* Ref.make<ProviderEventRoutingState>(
+ makeProviderEventRoutingState({
+ identity: routeIdentity,
+ inheritedBackgroundTurnItems,
+ providerTurnId: input.attempt.providerTurnId,
+ ...(input.relatedThreadIds === undefined
+ ? {}
+ : { relatedThreadIds: input.relatedThreadIds }),
+ ...(input.relatedProviderThreadIds === undefined
+ ? {}
+ : { relatedProviderThreadIds: input.relatedProviderThreadIds }),
+ }),
+ );
+ const rootTerminalSeen = yield* Ref.make(false);
+ const rootRunFinalized = yield* Ref.make(false);
+ const providerThreadOwnerLost = yield* Ref.make(false);
+ const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
+ const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
+ const activeBackgroundTurnItems = yield* Ref.make<
+ ReadonlySet<OrchestrationV2TurnItem["id"]>
+ >(new Set(inheritedBackgroundTurnItemsById.keys()));
+ const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection());
+ const finalizeRootRun = Effect.fn("RunExecutionService.finalizeRootRun")(function* (
+ terminal: ProviderTerminalEvent,
+ ) {
+ if (yield* Ref.get(rootRunFinalized)) {
+ return;
+ }
+ const providerThread = yield* Ref.get(latestProviderThread);
+ const openSubagents = yield* Ref.get(openRunOwnedSubagents);
+ yield* writeFinalRunEvents({
+ run: input.run,
+ rootNode: input.rootNode,
+ checkpointScope: input.checkpointScope,
+ providerThread,
+ attempt: input.attempt,
+ ...(input.shouldFinalizeRun === undefined
+ ? {}
+ : {
+ shouldFinalizeRun: input.shouldFinalizeRun,
+ // Stop may commit between the ownership read and this
+ // terminal write. Gate the events and checkpoint together.
+ writeIfRunCurrent: {
+ activeAttemptId: input.attempt.id,
+ expectedStatus: "running" as const,
+ },
+ }),
+ ...(input.hasUnpairedRunInterruptRequest === undefined
+ ? {}
+ : {
+ hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
+ }),
+ openRunOwnedSubagents: openSubagents,
+ terminal,
+ failureItemPersisted: terminal.status === "failed",
+ refreshAfterTurn,
+ }).pipe(
+ Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
+ );
+ if (isRunOwnedSubagentTerminalStatus(terminal.status) && !childTurnsContinue(terminal)) {
+ yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());
+ }
+ yield* Ref.set(rootRunFinalized, true);
+ });
+ // Runs for every provider event, including streamed text updates; avoid a per-event span.
+ const trackChildLifecycle = Effect.fnUntraced(function* (
+ event: ProviderAdapter.ProviderAdapterV2Event,
+ deliverable: boolean,
+ ) {
+ const routing = yield* Ref.get(eventRouting);
+ if (event.type === "provider_turn.updated") {
+ const isRoot =
+ event.providerTurn.runAttemptId === input.attempt.id ||
+ event.providerTurn.id === routing.rootProviderTurnId;
+ if (!isRoot) {
+ yield* Ref.update(activeChildProviderTurns, (current) => {
+ const next = new Set(current);
+ if (isTerminalProviderTurnStatus(event.providerTurn.status)) {
+ next.delete(event.providerTurn.id);
+ } else {
+ next.add(event.providerTurn.id);
}
- if (
- belongsToOwnedChildThread &&
- (event.turnItem.runId === null || belongsToRootRun) &&
- deliverable
- ) {
- yield* Ref.update(openRunOwnedSubagents, (current) => {
- const childTurnItems = new Map(current.childTurnItems);
- if (isSettledTurnItemStatus(event.turnItem.status)) {
- childTurnItems.delete(event.turnItem.id);
- } else {
- childTurnItems.set(event.turnItem.id, event.turnItem);
- }
- return { ...current, childTurnItems };
- });
+ return next;
+ });
+ }
+ }
+ if (event.type === "subagent.updated") {
+ const belongsToRootRun = event.subagent.runId === input.run.id;
+ const belongsToOwnedChildThread =
+ event.subagent.threadId !== input.run.threadId &&
+ routing.ownedThreadIds.has(event.subagent.threadId);
+ if (belongsToRootRun || belongsToOwnedChildThread) {
+ yield* Ref.update(activeChildSubagents, (current) => {
+ const next = new Set(current);
+ if (isSettledSubagentStatus(event.subagent.status)) {
+ next.delete(event.subagent.id);
+ } else {
+ next.add(event.subagent.id);
}
- if (belongsToRootRun && event.turnItem.type === "subagent") {
- const subagentItem = event.turnItem;
- yield* Ref.update(openRunOwnedSubagents, (current) => {
- const withLink = withLinkedChildThreadId(current, subagentItem.childThreadId);
- const turnItems = new Map(withLink.turnItems);
- if (isSettledTurnItemStatus(subagentItem.status)) {
- turnItems.delete(subagentItem.subagentId);
- } else {
- turnItems.set(subagentItem.subagentId, subagentItem);
- }
- return { ...withLink, turnItems };
- });
+ return next;
+ });
+ }
+ // Preserve childThreadId linkage for the root-run lifetime even after the subagent
+ // row terminalizes, so open child-thread nodes can still be proven linked on a
+ // later root interrupt. A provider records nested native subagents on the child
+ // thread, runless; they die with this run too.
+ if (
+ belongsToRootRun ||
+ (belongsToOwnedChildThread &&
+ event.subagent.runId === null &&
+ event.subagent.origin === "provider_native")
+ ) {
+ yield* Ref.update(openRunOwnedSubagents, (current) => {
+ const withLink = withLinkedChildThreadId(current, event.subagent.childThreadId);
+ const subagents = new Map(withLink.subagents);
+ if (isSettledSubagentStatus(event.subagent.status)) {
+ subagents.delete(event.subagent.id);
+ } else {
+ subagents.set(event.subagent.id, event.subagent);
}
+ return { ...withLink, subagents };
+ });
+ }
+ }
+ if (event.type === "node.updated") {
+ const belongsToRootSubagent =
+ event.node.kind === "subagent" && event.node.runId === input.run.id;
+ const belongsToOwnedChildThread =
+ event.node.threadId !== input.run.threadId &&
+ routing.ownedThreadIds.has(event.node.threadId);
+ if (
+ !belongsToRootSubagent &&
+ !(
+ belongsToOwnedChildThread &&
+ (event.node.runId === null || event.node.runId === input.run.id)
+ )
+ ) {
+ return;
+ }
+ yield* Ref.update(openRunOwnedSubagents, (current) => {
+ const nodes = new Map(current.nodes);
+ if (isOpenExecutionNodeStatus(event.node.status)) {
+ nodes.set(event.node.id, event.node);
+ } else {
+ nodes.delete(event.node.id);
}
+ return { ...current, nodes };
});
- const shouldStopProviderEventIngestion = Effect.gen(function* () {
- if (!(yield* Ref.get(rootTerminalSeen))) {
- return false;
- }
- const terminal = yield* Ref.get(terminalEvent);
+ }
+ if (event.type === "turn_item.updated") {
+ const belongsToRootRun = event.turnItem.runId === input.run.id;
+ const belongsToOwnedChildThread =
+ event.turnItem.threadId !== input.run.threadId &&
+ routing.ownedThreadIds.has(event.turnItem.threadId);
+ const belongsToInheritedBackgroundItem =
+ event.turnItem.threadId === input.run.threadId &&
+ event.turnItem.runId !== null &&
+ inheritedBackgroundTurnItemsById.get(event.turnItem.id) === event.turnItem.runId;
if (
- terminal !== null &&
- terminal.status !== "completed" &&
- !childTurnsContinue(terminal)
+ backgroundCapableTurnItemTypes.has(event.turnItem.type) &&
+ (belongsToRootRun || belongsToOwnedChildThread || belongsToInheritedBackgroundItem)
) {
- return true;
+ yield* Ref.update(activeBackgroundTurnItems, (current) => {
+ const next = new Set(current);
+ if (isSettledTurnItemStatus(event.turnItem.status)) {
+ next.delete(event.turnItem.id);
+ } else {
+ next.add(event.turnItem.id);
+ }
+ return next;
+ });
}
- const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
- if (childProviderTurns.size > 0) {
- return false;
+ if (
+ belongsToOwnedChildThread &&
+ (event.turnItem.runId === null || belongsToRootRun) &&
+ deliverable
+ ) {
+ yield* Ref.update(openRunOwnedSubagents, (current) => {
+ const childTurnItems = new Map(current.childTurnItems);
+ if (isSettledTurnItemStatus(event.turnItem.status)) {
+ childTurnItems.delete(event.turnItem.id);
+ } else {
+ childTurnItems.set(event.turnItem.id, event.turnItem);
+ }
+ return { ...current, childTurnItems };
+ });
}
- const childSubagents = yield* Ref.get(activeChildSubagents);
- if (childSubagents.size > 0) {
- return false;
+ if (belongsToRootRun && event.turnItem.type === "subagent") {
+ const subagentItem = event.turnItem;
+ yield* Ref.update(openRunOwnedSubagents, (current) => {
+ const withLink = withLinkedChildThreadId(current, subagentItem.childThreadId);
+ const turnItems = new Map(withLink.turnItems);
+ if (isSettledTurnItemStatus(subagentItem.status)) {
+ turnItems.delete(subagentItem.subagentId);
+ } else {
+ turnItems.set(subagentItem.subagentId, subagentItem);
+ }
+ return { ...withLink, turnItems };
+ });
}
- // Newly owned items depend on adapters emitting a non-terminal event before the root
- // terminal. Owner loss (a newer run claimed lastRunOrdinal) must not close this stream
- // while these sets are non-empty: turn_item.updated writes are not ownership-gated, so
- // late completions still land.
- const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
- if (backgroundItems.size > 0) {
+ }
+ });
+ const shouldStopProviderEventIngestion = Effect.gen(function* () {
+ if (!(yield* Ref.get(rootTerminalSeen))) {
+ return false;
+ }
+ const terminal = yield* Ref.get(terminalEvent);
+ if (
+ terminal !== null &&
+ terminal.status !== "completed" &&
+ !childTurnsContinue(terminal)
+ ) {
+ return true;
+ }
+ const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
+ if (childProviderTurns.size > 0) {
+ return false;
+ }
+ const childSubagents = yield* Ref.get(activeChildSubagents);
+ if (childSubagents.size > 0) {
+ return false;
+ }
+ // Newly owned items depend on adapters emitting a non-terminal event before the root
+ // terminal. Owner loss (a newer run claimed lastRunOrdinal) must not close this stream
+ // while these sets are non-empty: turn_item.updated writes are not ownership-gated, so
+ // late completions still land.
+ const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
+ if (backgroundItems.size > 0) {
+ return false;
+ }
+ if (yield* Ref.get(providerThreadOwnerLost)) {
+ return true;
+ }
+ // Claude background Bash has no turn-item projection. Use only the
+ // thread-scoped probe: session-wide pending work (siblings, wake
+ // buffers, session subagents) must not pin this root subscription.
+ const latestProviderThreadSnapshot = yield* Ref.get(latestProviderThread);
+ if (input.session.hasPendingBackgroundWorkForThread !== undefined) {
+ const hasPendingWork = yield* input.session
+ .hasPendingBackgroundWorkForThread(latestProviderThreadSnapshot)
+ .pipe(Effect.catchCause(() => Effect.succeed(false)));
+ if (hasPendingWork) {
return false;
}
- if (yield* Ref.get(providerThreadOwnerLost)) {
- return true;
- }
- // Claude background Bash has no turn-item projection. Use only the
- // thread-scoped probe: session-wide pending work (siblings, wake
- // buffers, session subagents) must not pin this root subscription.
- const latestProviderThreadSnapshot = yield* Ref.get(latestProviderThread);
- if (input.session.hasPendingBackgroundWorkForThread !== undefined) {
- const hasPendingWork = yield* input.session
- .hasPendingBackgroundWorkForThread(latestProviderThreadSnapshot)
- .pipe(Effect.catchCause(() => Effect.succeed(false)));
- if (hasPendingWork) {
- return false;
- }
- }
- return true;
- });
- const filterAssistantEvent = makeAssistantStreamingFilter(responseStreamingMode);
- // Held text writes nothing, so its item would take a position only
- // when finally written, behind every item that began after it.
- const reservedHeldTurnItemIds = new Set<TurnItemId>();
- const providerEventFiber = yield* eventSubscription.events.pipe(
- Stream.filterEffect((event) =>
- Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
- ),
- Stream.tap((event) =>
- Effect.gen(function* () {
- let storedEventCount = 0;
- const deliveredEvent = filterAssistantEvent(
- event,
- DateTime.toEpochMillis(yield* DateTime.now),
- );
- if (deliveredEvent) {
- const rootTerminalAlreadySeen = yield* Ref.get(rootTerminalSeen);
- const isRootProviderThreadUpdate =
- event.type === "provider_thread.updated" &&
- event.providerThread.id === input.providerThread.id;
- const storedEvents = yield* providerEventIngestor.ingestNormalized({
- analyticsContext: {
- modelSelection: input.modelSelection,
- runtimeMode: input.runtimePolicy.runtimeMode,
- interactionMode: input.runtimePolicy.interactionMode,
- },
- providerSessionId: input.providerSessionId,
- providerInstanceId: input.run.providerInstanceId,
- threadId: input.run.threadId,
- runId: input.run.id,
- nodeId: input.rootNode.id,
- event: deliveredEvent,
- ...(isRootProviderThreadUpdate
- ? rootTerminalAlreadySeen
- ? {
- writeIfProviderThreadOwner: {
- providerThreadId: input.providerThread.id,
- runId: input.run.id,
- activeAttemptId: input.attempt.id,
- expectedLastRunOrdinal: input.run.ordinal,
- },
- }
- : {
- writeIfRunCurrent: {
- runId: input.run.id,
- activeAttemptId: input.attempt.id,
- expectedStatus: "running" as const,
- },
- }
- : {}),
- });
- storedEventCount = storedEvents.length;
- if (
- isRootProviderThreadUpdate &&
- rootTerminalAlreadySeen &&
- storedEventCount === 0
- ) {
- yield* Ref.set(providerThreadOwnerLost, true);
- }
- } else if (
- event.type === "turn_item.updated" &&
- (event.turnItem.type === "assistant_message" ||
- event.turnItem.type === "reasoning") &&
- event.turnItem.streaming &&
- !reservedHeldTurnItemIds.has(event.turnItem.id)
- ) {
- yield* turnItemPositions.allocate({
- threadId: event.turnItem.threadId,
- turnItemId: event.turnItem.id,
- runId: event.turnItem.runId,
- });
- reservedHeldTurnItemIds.add(event.turnItem.id);
- }
- if (event.type === "provider_thread.updated") {
- if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
- yield* Ref.set(latestProviderThread, event.providerThread);
- }
- }
+ }
+ return true;
+ });
+ const filterAssistantEvent = makeAssistantStreamingFilter(responseStreamingMode);
+ // Held text writes nothing, so its item would take a position only
+ // when finally written, behind every item that began after it.
+ const reservedHeldTurnItemIds = new Set<TurnItemId>();
+ const providerEventFiber = yield* eventSubscription.events.pipe(
+ Stream.filterEffect((event) =>
+ Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
+ ),
+ Stream.tap((event) =>
+ Effect.gen(function* () {
+ let storedEventCount = 0;
+ const deliveredEvent = filterAssistantEvent(
+ event,
+ DateTime.toEpochMillis(yield* DateTime.now),
+ );
+ if (deliveredEvent) {
+ const rootTerminalAlreadySeen = yield* Ref.get(rootTerminalSeen);
+ const isRootProviderThreadUpdate =
+ event.type === "provider_thread.updated" &&
+ event.providerThread.id === input.providerThread.id;
+ const storedEvents = yield* providerEventIngestor.ingestNormalized({
+ analyticsContext: {
+ modelSelection: input.modelSelection,
+ runtimeMode: input.runtimePolicy.runtimeMode,
+ interactionMode: input.runtimePolicy.interactionMode,
+ },
+ providerSessionId: input.providerSessionId,
+ providerInstanceId: input.run.providerInstanceId,
+ threadId: input.run.threadId,
+ runId: input.run.id,
+ nodeId: input.rootNode.id,
+ event: deliveredEvent,
+ ...(isRootProviderThreadUpdate
+ ? rootTerminalAlreadySeen
+ ? {
+ writeIfProviderThreadOwner: {
+ providerThreadId: input.providerThread.id,
+ runId: input.run.id,
+ activeAttemptId: input.attempt.id,
+ expectedLastRunOrdinal: input.run.ordinal,
+ },
+ }
+ : {
+ writeIfRunCurrent: {
+ runId: input.run.id,
+ activeAttemptId: input.attempt.id,
+ expectedStatus: "running" as const,
+ },
+ }
+ : {}),
+ });
+ storedEventCount = storedEvents.length;
if (
- event.type === "turn_item.updated" &&
- event.turnItem.providerTurnId ===
- (yield* Ref.get(eventRouting)).rootProviderTurnId
+ isRootProviderThreadUpdate &&
+ rootTerminalAlreadySeen &&
+ storedEventCount === 0
) {
- yield* Ref.update(latestTurnItemOrdinal, (current) =>
- Math.max(current, event.turnItem.ordinal),
- );
+ yield* Ref.set(providerThreadOwnerLost, true);
}
- if (event.type === "turn.terminal") {
- yield* Ref.set(terminalEvent, event);
- yield* Ref.set(rootTerminalSeen, true);
- yield* finalizeRootRun(event);
+ } else if (
+ event.type === "turn_item.updated" &&
+ (event.turnItem.type === "assistant_message" ||
+ event.turnItem.type === "reasoning") &&
+ event.turnItem.streaming &&
+ !reservedHeldTurnItemIds.has(event.turnItem.id)
+ ) {
+ yield* turnItemPositions.allocate({
+ threadId: event.turnItem.threadId,
+ turnItemId: event.turnItem.id,
+ runId: event.turnItem.runId,
+ });
+ reservedHeldTurnItemIds.add(event.turnItem.id);
+ }
+ if (event.type === "provider_thread.updated") {
+ if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
+ yield* Ref.set(latestProviderThread, event.providerThread);
}
- yield* trackChildLifecycle(event, deliveredEvent !== null);
- }),
- ),
- Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
- Stream.runDrain,
- Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
- Effect.flatMap(() =>
- Effect.gen(function* () {
- const terminal = yield* Ref.get(terminalEvent);
- if (terminal === null) {
- // A session release interrupts or fails the stream; a clean
- // end without a terminal means the run would never settle.
- return yield* new RunExecutionIngestError({
+ }
+ if (
+ event.type === "turn_item.updated" &&
+ event.turnItem.providerTurnId === (yield* Ref.get(eventRouting)).rootProviderTurnId
+ ) {
+ yield* Ref.update(latestTurnItemOrdinal, (current) =>
+ Math.max(current, event.turnItem.ordinal),
+ );
+ }
+ if (event.type === "turn.terminal") {
+ yield* Ref.set(terminalEvent, event);
+ yield* Ref.set(rootTerminalSeen, true);
+ yield* finalizeRootRun(event);
+ }
+ yield* trackChildLifecycle(event, deliveredEvent !== null);
+ }),
+ ),
+ Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
+ Stream.runDrain,
+ Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
+ Effect.flatMap(() =>
+ Effect.gen(function* () {
+ const terminal = yield* Ref.get(terminalEvent);
+ if (terminal === null) {
+ // A session release interrupts or fails the stream; a clean
+ // end without a terminal means the run would never settle.
+ return yield* new RunExecutionIngestError({
+ runId: input.run.id,
+ cause: new ProviderAdapter.ProviderAdapterEventStreamError({
+ driver: input.providerThread.driver,
+ providerSessionId: input.providerSessionId,
+ cause: "Provider event stream ended without a root terminal.",
+ }),
+ });
+ }
+ yield* finalizeRootRun(terminal);
+ }),
+ ),
+ // Server shutdown interrupts the subscription and leaves the run to
+ // restart recovery; every other failure fails the run.
+ Effect.catchCauseIf(
+ (cause) => !Cause.hasInterruptsOnly(cause),
+ (cause) =>
+ Ref.get(rootRunFinalized).pipe(
+ Effect.flatMap((finalized) =>
+ Effect.logWarning("orchestration V2 provider event ingestion failed", {
runId: input.run.id,
- cause: new ProviderAdapter.ProviderAdapterEventStreamError({
- driver: input.providerThread.driver,
- providerSessionId: input.providerSessionId,
- cause: "Provider event stream ended without a root terminal.",
- }),
- });
- }
- yield* finalizeRootRun(terminal);
- }),
- ),
- // Server shutdown interrupts the subscription and leaves the run to
- // restart recovery; every other failure fails the run.
- Effect.catchCauseIf(
- (cause) => !Cause.hasInterruptsOnly(cause),
- (cause) =>
- Ref.get(rootRunFinalized).pipe(
- Effect.flatMap((finalized) =>
- Effect.logWarning("orchestration V2 provider event ingestion failed", {
- runId: input.run.id,
- cause,
- }).pipe(
- Effect.andThen(
- finalized
- ? Effect.void
- : Ref.get(latestProviderThread).pipe(
- Effect.flatMap((providerThread) =>
- Ref.get(latestTurnItemOrdinal).pipe(
- Effect.flatMap((latestItemOrdinal) =>
- Ref.get(openRunOwnedSubagents).pipe(
- Effect.flatMap((openSubagents) =>
- writeFinalRunEvents({
- run: input.run,
- rootNode: input.rootNode,
- checkpointScope: input.checkpointScope,
- providerThread,
- attempt: input.attempt,
- writeIfRunCurrent: {
- activeAttemptId: input.attempt.id,
- expectedStatus: "running",
- },
- openRunOwnedSubagents: openSubagents,
- terminal: makeFailedTerminalEvent(
- makeProviderFailure({
- cause: Cause.squash(cause),
- class: "unknown",
- }),
- latestItemOrdinal + 1,
- ),
- failureItemPersisted: false,
- refreshAfterTurn,
- }),
- ),
+ cause,
+ }).pipe(
+ Effect.andThen(
+ finalized
+ ? Effect.void
+ : Ref.get(latestProviderThread).pipe(
+ Effect.flatMap((providerThread) =>
+ Ref.get(latestTurnItemOrdinal).pipe(
+ Effect.flatMap((latestItemOrdinal) =>
+ Ref.get(openRunOwnedSubagents).pipe(
+ Effect.flatMap((openSubagents) =>
+ writeFinalRunEvents({
+ run: input.run,
+ rootNode: input.rootNode,
+ checkpointScope: input.checkpointScope,
+ providerThread,
+ attempt: input.attempt,
+ writeIfRunCurrent: {
+ activeAttemptId: input.attempt.id,
+ expectedStatus: "running",
+ },
+ openRunOwnedSubagents: openSubagents,
+ terminal: makeFailedTerminalEvent(
+ makeProviderFailure({
+ cause: Cause.squash(cause),
+ class: "unknown",
+ }),
+ latestItemOrdinal + 1,
+ ),
+ failureItemPersisted: false,
+ refreshAfterTurn,
+ }),
),
),
),
),
),
- ),
- Effect.mapError(
- (writeCause) =>
- new RunExecutionIngestError({
- runId: input.run.id,
- cause: { ingest: cause, write: writeCause },
- }),
- ),
+ ),
+ ),
+ Effect.mapError(
+ (writeCause) =>
+ new RunExecutionIngestError({
+ runId: input.run.id,
+ cause: { ingest: cause, write: writeCause },
+ }),
),
),
),
- ),
- Effect.ensuring(eventSubscription.close),
- Effect.forkDetach,
- );
+ ),
+ ),
+ Effect.ensuring(eventSubscription.close),
+ Effect.forkDetach,
+ );
- // A provider turn is a sign that the session is still alive. Keep
- // its already-issued MCP credential valid even when the agent goes
- // a long time between browser-tool calls.
- yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId);
- const appContext = (yield* mcpAppModelContext
- .forThread(input.run.threadId)
- .pipe(
- Effect.catch((cause) =>
- Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe(
- Effect.as([]),
- ),
+ // A provider turn is a sign that the session is still alive. Keep
+ // its already-issued MCP credential valid even when the agent goes
+ // a long time between browser-tool calls.
+ yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId);
+ const appContext = (yield* mcpAppModelContext
+ .forThread(input.run.threadId)
+ .pipe(
+ Effect.catch((cause) =>
+ Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe(
+ Effect.as([]),
),
- )).map((entry) => ({
- // The item id alone is unique and needs no escaping; server and
- // tool names are free text that would break the tag Codex wraps
- // the context in.
- key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`,
- text: entry.text,
- }));
- const turnInput = {
- appThread: input.appThread,
- threadId: input.run.threadId,
- runId: input.run.id,
- runOrdinal: input.run.ordinal,
- providerTurnOrdinal: input.providerTurnOrdinal,
- ...(input.nativeThreadHasTurns === undefined
- ? {}
- : { nativeThreadHasTurns: input.nativeThreadHasTurns }),
- ...(input.run.restartContinuationOfRunId === undefined
- ? {}
- : {
- restartContinuationOfRunId: input.run.restartContinuationOfRunId,
- }),
- attemptId: input.attemptId,
- rootNodeId: input.rootNode.id,
- providerThread: input.providerThread,
- message: input.message,
- modelSelection: input.modelSelection,
- runtimePolicy: input.runtimePolicy,
- ...(appContext.length === 0 ? {} : { appContext }),
- };
- // Check after the context read: ingestion can settle the run while
- // it awaits. A failed ownership read fails the start below.
- const shouldStart =
- input.shouldStartProviderTurn === undefined
- ? Exit.succeed(true)
- : yield* Effect.exit(input.shouldStartProviderTurn());
- if (Exit.isSuccess(shouldStart) && !shouldStart.value) {
- yield* Fiber.interrupt(providerEventFiber);
- return;
- }
+ ),
+ )).map((entry) => ({
+ // The item id alone is unique and needs no escaping; server and
+ // tool names are free text that would break the tag Codex wraps
+ // the context in.
+ key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`,
+ text: entry.text,
+ }));
+ const turnInput = {
+ appThread: input.appThread,
+ threadId: input.run.threadId,
+ runId: input.run.id,
+ runOrdinal: input.run.ordinal,
+ providerTurnOrdinal: input.providerTurnOrdinal,
+ ...(input.nativeThreadHasTurns === undefined
+ ? {}
+ : { nativeThreadHasTurns: input.nativeThreadHasTurns }),
+ ...(input.run.restartContinuationOfRunId === undefined
+ ? {}
+ : {
+ restartContinuationOfRunId: input.run.restartContinuationOfRunId,
+ }),
+ attemptId: input.attemptId,
+ rootNodeId: input.rootNode.id,
+ providerThread: input.providerThread,
+ message: input.message,
+ modelSelection: input.modelSelection,
+ runtimePolicy: input.runtimePolicy,
+ ...(appContext.length === 0 ? {} : { appContext }),
+ };
+ // Check after the context read: ingestion can settle the run while
+ // it awaits. A failed ownership read fails the start below.
+ const shouldStart =
+ input.shouldStartProviderTurn === undefined
+ ? Exit.succeed(true)
+ : yield* Effect.exit(input.shouldStartProviderTurn());
+ if (Exit.isSuccess(shouldStart) && !shouldStart.value) {
+ yield* Fiber.interrupt(providerEventFiber);
+ return;
+ }
- const compact =
- input.message.attachments.length === 0 &&
- input.message.text.trim().toLowerCase() === "/compact";
- const startTurn = compact
- ? (input.session.compactThread?.(turnInput) ??
- Effect.fail(
- new ProviderAdapter.ProviderAdapterTurnStartError({
- driver: input.session.driver,
- threadId: input.run.threadId,
- providerThreadId: input.providerThread.id,
- runId: input.run.id,
- cause: "This provider does not support context compaction.",
- }),
- ))
- : input.session.startTurn(turnInput);
- yield* Effect.andThen(shouldStart, startTurn).pipe(
- Effect.catchCause((cause) =>
- Effect.logError("orchestration V2 provider turn start failed", {
+ const compact =
+ input.message.attachments.length === 0 &&
+ input.message.text.trim().toLowerCase() === "/compact";
+ const startTurn = compact
+ ? (input.session.compactThread?.(turnInput) ??
+ Effect.fail(
+ new ProviderAdapter.ProviderAdapterTurnStartError({
+ driver: input.session.driver,
+ threadId: input.run.threadId,
+ providerThreadId: input.providerThread.id,
runId: input.run.id,
- cause,
- }).pipe(
- Effect.andThen(Fiber.interrupt(providerEventFiber)),
- Effect.andThen(Ref.get(latestProviderThread)),
- Effect.flatMap((providerThread) =>
- Ref.get(latestTurnItemOrdinal).pipe(
- Effect.flatMap((latestItemOrdinal) =>
- Ref.get(openRunOwnedSubagents).pipe(
- Effect.flatMap((openSubagents) =>
- writeFinalRunEvents({
- run: input.run,
- rootNode: input.rootNode,
- checkpointScope: input.checkpointScope,
- providerThread,
- attempt: input.attempt,
- writeIfRunCurrent: {
- activeAttemptId: input.attempt.id,
- expectedStatus: "running",
- },
- openRunOwnedSubagents: openSubagents,
- terminal: makeFailedTerminalEvent(
- makeProviderFailure({
- cause: Cause.squash(cause),
- class: Exit.isFailure(shouldStart) ? "unknown" : "provider_error",
- }),
- latestItemOrdinal + 1,
- ),
- failureItemPersisted: false,
- refreshAfterTurn,
- }),
- ),
+ cause: "This provider does not support context compaction.",
+ }),
+ ))
+ : input.session.startTurn(turnInput);
+ yield* Effect.andThen(shouldStart, startTurn).pipe(
+ Effect.catchCause((cause) =>
+ Effect.logError("orchestration V2 provider turn start failed", {
+ runId: input.run.id,
+ cause,
+ }).pipe(
+ Effect.andThen(Fiber.interrupt(providerEventFiber)),
+ Effect.andThen(Ref.get(latestProviderThread)),
+ Effect.flatMap((providerThread) =>
+ Ref.get(latestTurnItemOrdinal).pipe(
+ Effect.flatMap((latestItemOrdinal) =>
+ Ref.get(openRunOwnedSubagents).pipe(
+ Effect.flatMap((openSubagents) =>
+ writeFinalRunEvents({
+ run: input.run,
+ rootNode: input.rootNode,
+ checkpointScope: input.checkpointScope,
+ providerThread,
+ attempt: input.attempt,
+ writeIfRunCurrent: {
+ activeAttemptId: input.attempt.id,
+ expectedStatus: "running",
+ },
+ openRunOwnedSubagents: openSubagents,
+ terminal: makeFailedTerminalEvent(
+ makeProviderFailure({
+ cause: Cause.squash(cause),
+ class: Exit.isFailure(shouldStart) ? "unknown" : "provider_error",
+ }),
+ latestItemOrdinal + 1,
+ ),
+ failureItemPersisted: false,
+ refreshAfterTurn,
+ }),
),
),
),
),
- Effect.mapError(
- (writeCause) =>
- new RunExecutionStartError({
- commandId: input.commandId,
- runId: input.run.id,
- cause: { start: cause, write: writeCause },
- }),
- ),
+ ),
+ Effect.mapError(
+ (writeCause) =>
+ new RunExecutionStartError({
+ commandId: input.commandId,
+ runId: input.run.id,
+ cause: { start: cause, write: writeCause },
+ }),
),
),
- );
- }),
+ ),
+ );
+ }),
} satisfies RunExecutionServiceV2Shape);
}),
);
diff --git a/apps/server/src/orchestration-v2/RunFinalizationService.ts b/apps/server/src/orchestration-v2/RunFinalizationService.ts
index b1136f6f8b0..40882033ba5 100644
--- a/apps/server/src/orchestration-v2/RunFinalizationService.ts
+++ b/apps/server/src/orchestration-v2/RunFinalizationService.ts
@@ -98,8 +98,8 @@ export const layerObserver = Layer.effect(
const pullRequests = yield* PullRequestService.PullRequestService;
return {
refreshAfterTurn: pullRequests.refreshAfterTurn,
- refresh: ({ cwd, threadId, runId }) =>
- Effect.gen(function* () {
+ refresh: Effect.fn("RunFinalizationService.refresh")(
+ function* ({ cwd, threadId, runId }) {
const [, local] = yield* Effect.all(
[workspaceEntries.refresh(cwd), vcsStatus.refreshLocalStatus(cwd)],
{ concurrency: "unbounded" },
@@ -117,7 +117,10 @@ export const layerObserver = Layer.effect(
}),
),
);
- }).pipe(Effect.mapError((cause) => new RunFinalizationRefreshError({ cwd, cause }))),
+ },
+ (effect, { cwd }) =>
+ effect.pipe(Effect.mapError((cause) => new RunFinalizationRefreshError({ cwd, cause }))),
+ ),
};
}),
);
diff --git a/apps/server/src/orchestration-v2/RuntimeRequestService.ts b/apps/server/src/orchestration-v2/RuntimeRequestService.ts
index 61976853271..9c96ea5d6b4 100644
--- a/apps/server/src/orchestration-v2/RuntimeRequestService.ts
+++ b/apps/server/src/orchestration-v2/RuntimeRequestService.ts
@@ -74,8 +74,8 @@ export const layer: Layer.Layer<
const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
return RuntimeRequestServiceV2.of({
- respond: (input) =>
- Effect.gen(function* () {
+ respond: Effect.fn("RuntimeRequestService.respond")(
+ function* (input) {
const request = yield* projections.getRuntimeRequest(input.threadId, input.requestId);
if (request === undefined) {
return yield* new RuntimeRequestResponseExecutionError({
@@ -120,19 +120,22 @@ export const layer: Layer.Layer<
...(input.decision === undefined ? {} : { decision: input.decision }),
...(input.answers === undefined ? {} : { answers: input.answers }),
});
- }).pipe(
- Effect.mapError((cause) =>
- isRuntimeRequestResponseExecutionError(cause)
- ? cause
- : new RuntimeRequestResponseExecutionError({
- reason: "unexpected-failure",
- threadId: input.threadId,
- providerSessionId: input.providerSessionId,
- requestId: input.requestId,
- cause,
- }),
+ },
+ (effect, input) =>
+ effect.pipe(
+ Effect.mapError((cause) =>
+ isRuntimeRequestResponseExecutionError(cause)
+ ? cause
+ : new RuntimeRequestResponseExecutionError({
+ reason: "unexpected-failure",
+ threadId: input.threadId,
+ providerSessionId: input.providerSessionId,
+ requestId: input.requestId,
+ cause,
+ }),
+ ),
),
- ),
+ ),
});
}),
);
diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.ts
index b652ea1b14b..b3b798d57de 100644
--- a/apps/server/src/orchestration-v2/ThreadForkService.ts
+++ b/apps/server/src/orchestration-v2/ThreadForkService.ts
@@ -72,68 +72,67 @@ export class ThreadForkServiceV2 extends Context.Service<
export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
ThreadForkServiceV2,
ThreadForkServiceV2.of({
- plan: (input) =>
- Effect.gen(function* () {
- if (!isForkableSourceRunStatus(input.sourceRun.status)) {
- return yield* new ThreadForkPlanError({
- sourceThreadId: input.sourceProjection.thread.id,
- targetThreadId: input.targetThreadId,
- cause: forkableSourceRunStatusError(input.sourceRun),
- });
- }
- const targetThread: OrchestrationV2AppThread = {
- ...input.sourceProjection.thread,
- // PR context follows the conversation; watching remains the source thread's responsibility.
- pullRequests: input.sourceProjection.thread.pullRequests?.map(
- ({ watch: _watch, ...link }) => link,
- ),
- createdBy: input.createdBy,
- creationSource: input.creationSource,
- id: input.targetThreadId,
- title: input.title ?? `${input.sourceProjection.thread.title} fork`,
- activeProviderThreadId: null,
- lineage: {
- parentThreadId: input.sourceProjection.thread.id,
- relationshipToParent: "fork",
- rootThreadId: input.sourceProjection.thread.lineage.rootThreadId,
- },
- forkedFrom: {
- type: "run",
- threadId: input.sourceProjection.thread.id,
- runId: input.sourceRun.id,
- },
- createdAt: input.createdAt,
- updatedAt: input.createdAt,
- archivedAt: null,
- settledOverride: null,
- settledAt: null,
- snoozedUntil: null,
- snoozedAt: null,
- lastVisitedAt: null,
- deletedAt: null,
- };
- const transfer: OrchestrationV2ContextTransfer = {
- id: input.transferId,
- type: "fork",
+ plan: Effect.fn("ThreadForkService.plan")(function* (input) {
+ if (!isForkableSourceRunStatus(input.sourceRun.status)) {
+ return yield* new ThreadForkPlanError({
sourceThreadId: input.sourceProjection.thread.id,
targetThreadId: input.targetThreadId,
- sourcePoint: input.canonicalSourcePoint,
- basePoint: null,
- sourceProviderInstanceId: input.sourceRun.providerInstanceId,
- targetProviderInstanceId: null,
- targetRunId: null,
- status: "pending",
- resolution: null,
- createdBy: input.createdBy,
- error:
- input.sourceProviderThread?.nativeThreadRef?.strength === "strong"
- ? null
- : "Source provider thread does not expose a strong native thread ref.",
- createdAt: input.createdAt,
- updatedAt: input.createdAt,
- consumedAt: null,
- };
- return { targetThread, transfer };
- }),
+ cause: forkableSourceRunStatusError(input.sourceRun),
+ });
+ }
+ const targetThread: OrchestrationV2AppThread = {
+ ...input.sourceProjection.thread,
+ // PR context follows the conversation; watching remains the source thread's responsibility.
+ pullRequests: input.sourceProjection.thread.pullRequests?.map(
+ ({ watch: _watch, ...link }) => link,
+ ),
+ createdBy: input.createdBy,
+ creationSource: input.creationSource,
+ id: input.targetThreadId,
+ title: input.title ?? `${input.sourceProjection.thread.title} fork`,
+ activeProviderThreadId: null,
+ lineage: {
+ parentThreadId: input.sourceProjection.thread.id,
+ relationshipToParent: "fork",
+ rootThreadId: input.sourceProjection.thread.lineage.rootThreadId,
+ },
+ forkedFrom: {
+ type: "run",
+ threadId: input.sourceProjection.thread.id,
+ runId: input.sourceRun.id,
+ },
+ createdAt: input.createdAt,
+ updatedAt: input.createdAt,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ snoozedUntil: null,
+ snoozedAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ };
+ const transfer: OrchestrationV2ContextTransfer = {
+ id: input.transferId,
+ type: "fork",
+ sourceThreadId: input.sourceProjection.thread.id,
+ targetThreadId: input.targetThreadId,
+ sourcePoint: input.canonicalSourcePoint,
+ basePoint: null,
+ sourceProviderInstanceId: input.sourceRun.providerInstanceId,
+ targetProviderInstanceId: null,
+ targetRunId: null,
+ status: "pending",
+ resolution: null,
+ createdBy: input.createdBy,
+ error:
+ input.sourceProviderThread?.nativeThreadRef?.strength === "strong"
+ ? null
+ : "Source provider thread does not expose a strong native thread ref.",
+ createdAt: input.createdAt,
+ updatedAt: input.createdAt,
+ consumedAt: null,
+ };
+ return { targetThread, transfer };
+ }),
}),
);
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts
index 4390bc48d1f..f1c3d432a10 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts
@@ -330,8 +330,8 @@ const make = Effect.gen(function* () {
}
yield* Effect.gen(function* () {
const initialMessage = input.initialMessage;
- const generateBranchNameFor = (cwd: string, message: ThreadLaunchInitialMessage) =>
- Effect.gen(function* () {
+ const generateBranchNameFor = Effect.fn("ThreadLaunchService.generateBranchNameFor")(
+ function* (cwd: string, message: ThreadLaunchInitialMessage) {
const settings = resolveProjectSettings(
yield* serverSettings.getSettings,
input.projectId,
@@ -363,7 +363,8 @@ const make = Effect.gen(function* () {
exactName: settings.branchNamingMode === "custom",
})),
);
- });
+ },
+ );
const requestedBranch = input.workspaceStrategy.branch;
let branch: string | null;
diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts
index e85f33d259a..af44e898021 100644
--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts
+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts
@@ -748,184 +748,185 @@ const make = Effect.gen(function* () {
),
);
- const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
- Effect.gen(function* () {
- const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
- if (target.thread.archivedAt !== null) {
- return yield* new ThreadManagementThreadArchivedError({
+ const sendToThread: ThreadManagementServiceShape["sendToThread"] = Effect.fn(
+ "ThreadManagementService.sendToThread",
+ )(function* (input) {
+ const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
+ if (target.thread.archivedAt !== null) {
+ return yield* new ThreadManagementThreadArchivedError({
+ threadId: input.threadId,
+ });
+ }
+ const steerableRun = latestSteerableRun(target);
+ let dispatchMode: Extract<
+ OrchestrationV2Command,
+ { readonly type: "message.dispatch" }
+ >["dispatchMode"];
+ if (input.mode === "steer" || input.mode === "restart") {
+ if (steerableRun === undefined) {
+ return yield* new ThreadManagementNoSteerableRunError({
threadId: input.threadId,
+ mode: input.mode,
});
}
- const steerableRun = latestSteerableRun(target);
- let dispatchMode: Extract<
- OrchestrationV2Command,
- { readonly type: "message.dispatch" }
- >["dispatchMode"];
- if (input.mode === "steer" || input.mode === "restart") {
- if (steerableRun === undefined) {
- return yield* new ThreadManagementNoSteerableRunError({
- threadId: input.threadId,
- mode: input.mode,
- });
- }
- dispatchMode = {
- type: input.mode === "steer" ? "steer_active" : "restart_active",
- targetRunId: steerableRun.id,
- };
- } else if (input.mode === "auto" && steerableRun !== undefined) {
- dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
- } else {
- dispatchMode = {
- type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
- };
- }
+ dispatchMode = {
+ type: input.mode === "steer" ? "steer_active" : "restart_active",
+ targetRunId: steerableRun.id,
+ };
+ } else if (input.mode === "auto" && steerableRun !== undefined) {
+ dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
+ } else {
+ dispatchMode = {
+ type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
+ };
+ }
- const dispatched = yield* dispatch({
- type: "message.dispatch",
- commandId: input.commandId,
+ const dispatched = yield* dispatch({
+ type: "message.dispatch",
+ commandId: input.commandId,
+ threadId: input.threadId,
+ messageId: input.messageId,
+ ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
+ ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
+ text: input.text,
+ attachments: input.attachments,
+ ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
+ dispatchMode,
+ createdBy: input.createdBy,
+ creationSource: input.creationSource,
+ });
+ const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
+ messageIds: [input.messageId],
+ turnItemTypes: ["user_message"],
+ });
+ const message = projection.messages.find((candidate) => candidate.id === input.messageId);
+ const run =
+ message?.runId === null || message?.runId === undefined
+ ? undefined
+ : projection.runs.find((candidate) => candidate.id === message.runId);
+ const turnItem =
+ projection.turnItems.find(
+ (
+ candidate,
+ ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
+ candidate.type === "user_message" && candidate.messageId === input.messageId,
+ ) ?? null;
+ if (
+ message === undefined ||
+ run === undefined ||
+ (turnItem === null && run.status !== "queued")
+ ) {
+ return yield* new ThreadManagementDurableRunProjectionError({
threadId: input.threadId,
messageId: input.messageId,
- ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
- ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
- text: input.text,
- attachments: input.attachments,
- ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
- dispatchMode,
- createdBy: input.createdBy,
- creationSource: input.creationSource,
});
- const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
- messageIds: [input.messageId],
- turnItemTypes: ["user_message"],
+ }
+ const delivery: ThreadManagementSendResult["delivery"] =
+ turnItem === null || turnItem.inputIntent === "queued_turn"
+ ? "queued"
+ : turnItem.inputIntent === "turn_start"
+ ? "started"
+ : input.mode === "restart"
+ ? "restarted"
+ : "steered";
+ return { dispatch: dispatched, projection, message, run, turnItem, delivery };
+ });
+
+ const waitForThread: ThreadManagementServiceShape["waitForThread"] = Effect.fn(
+ "ThreadManagementService.waitForThread",
+ )(function* (input) {
+ const loadError = (cause: unknown) =>
+ new ThreadManagementProjectionLoadError({
+ projectId: input.projectId,
+ threadId: input.threadId,
+ cause,
+ });
+ // Taken before the first read, so a run update between that read and
+ // the subscription below still replays.
+ const afterSequence = yield* orchestrator
+ .getThreadEventSequence(input.threadId)
+ .pipe(Effect.mapError(loadError));
+ const target = yield* getProjectThreadRecords(input, ["runs"]);
+ const selectedRun =
+ input.runId === undefined
+ ? latestRun(target)
+ : target.runs.find((candidate) => candidate.id === input.runId);
+ if (input.runId !== undefined && selectedRun === undefined) {
+ return yield* new ThreadManagementRunNotFoundError({
+ threadId: input.threadId,
+ runId: input.runId,
});
- const message = projection.messages.find((candidate) => candidate.id === input.messageId);
- const run =
- message?.runId === null || message?.runId === undefined
- ? undefined
- : projection.runs.find((candidate) => candidate.id === message.runId);
- const turnItem =
- projection.turnItems.find(
- (
- candidate,
- ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
- candidate.type === "user_message" && candidate.messageId === input.messageId,
- ) ?? null;
- if (
- message === undefined ||
- run === undefined ||
- (turnItem === null && run.status !== "queued")
- ) {
- return yield* new ThreadManagementDurableRunProjectionError({
+ }
+ if (selectedRun === undefined) {
+ return { threadId: input.threadId, run: null, timedOut: false };
+ }
+ // A restart cuts a run and continues it as a new run. Follow that chain,
+ // so a cut run is not the answer while its continuation is pending.
+ // Runs per matching event and is already covered by the waitForThread span.
+ const outcome = Effect.fnUntraced(function* (runs: ReadonlyArray<OrchestrationV2Run>) {
+ const current = runs.find((candidate) => candidate.id === selectedRun.id);
+ if (current === undefined) {
+ return yield* new ThreadManagementRunNotFoundError({
threadId: input.threadId,
- messageId: input.messageId,
+ runId: selectedRun.id,
});
}
- const delivery: ThreadManagementSendResult["delivery"] =
- turnItem === null || turnItem.inputIntent === "queued_turn"
- ? "queued"
- : turnItem.inputIntent === "turn_start"
- ? "started"
- : input.mode === "restart"
- ? "restarted"
- : "steered";
- return { dispatch: dispatched, projection, message, run, turnItem, delivery };
+ const run = latestRestartContinuation(runs, current);
+ const pending =
+ isTerminalRunStatus(run.status) && (yield* orchestrator.restartContinuationPending(run));
+ return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };
});
+ const initial = yield* outcome(target.runs);
+ if (initial.settled) {
+ return { threadId: input.threadId, run: initial.run, timedOut: false };
+ }
- const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
- Effect.gen(function* () {
- const loadError = (cause: unknown) =>
- new ThreadManagementProjectionLoadError({
- projectId: input.projectId,
+ // A declined continuation records no event, so its effect settling wakes
+ // the wait too.
+ const wait = Stream.merge(
+ Stream.merge(
+ orchestrator.streamStoredEventsFrom({
threadId: input.threadId,
- cause,
- });
- // Taken before the first read, so a run update between that read and
- // the subscription below still replays.
- const afterSequence = yield* orchestrator
- .getThreadEventSequence(input.threadId)
- .pipe(Effect.mapError(loadError));
- const target = yield* getProjectThreadRecords(input, ["runs"]);
- const selectedRun =
- input.runId === undefined
- ? latestRun(target)
- : target.runs.find((candidate) => candidate.id === input.runId);
- if (input.runId !== undefined && selectedRun === undefined) {
- return yield* new ThreadManagementRunNotFoundError({
+ afterSequence,
+ eventType: "run.updated",
+ }),
+ orchestrator.streamStoredEventsFrom({
threadId: input.threadId,
- runId: input.runId,
- });
- }
- if (selectedRun === undefined) {
- return { threadId: input.threadId, run: null, timedOut: false };
- }
- // A restart cuts a run and continues it as a new run. Follow that chain,
- // so a cut run is not the answer while its continuation is pending.
- const outcome = (runs: ReadonlyArray<OrchestrationV2Run>) =>
- Effect.gen(function* () {
- const current = runs.find((candidate) => candidate.id === selectedRun.id);
- if (current === undefined) {
- return yield* new ThreadManagementRunNotFoundError({
- threadId: input.threadId,
- runId: selectedRun.id,
- });
- }
- const run = latestRestartContinuation(runs, current);
- const pending =
- isTerminalRunStatus(run.status) &&
- (yield* orchestrator.restartContinuationPending(run));
- return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };
- });
- const initial = yield* outcome(target.runs);
- if (initial.settled) {
- return { threadId: input.threadId, run: initial.run, timedOut: false };
- }
-
- // A declined continuation records no event, so its effect settling wakes
- // the wait too.
- const wait = Stream.merge(
- Stream.merge(
- orchestrator.streamStoredEventsFrom({
- threadId: input.threadId,
- afterSequence,
- eventType: "run.updated",
- }),
- orchestrator.streamStoredEventsFrom({
- threadId: input.threadId,
- afterSequence,
- eventType: "thread.deleted",
- }),
- ).pipe(
- Stream.mapError(loadError),
- Stream.filter(
- (stored) =>
- stored.event.type !== "run.updated" ||
- stored.event.payload.id === selectedRun.id ||
- stored.event.payload.restartContinuationOfRunId !== undefined,
- ),
- ),
- initial.pending
- ? Stream.fromEffect(orchestrator.awaitRestartContinuation(initial.run))
- : Stream.empty,
+ afterSequence,
+ eventType: "thread.deleted",
+ }),
).pipe(
- Stream.mapEffect(() =>
- getProjectThreadRecords(input, ["runs"]).pipe(
- Effect.flatMap((current) => outcome(current.runs)),
- ),
+ Stream.mapError(loadError),
+ Stream.filter(
+ (stored) =>
+ stored.event.type !== "run.updated" ||
+ stored.event.payload.id === selectedRun.id ||
+ stored.event.payload.restartContinuationOfRunId !== undefined,
),
- Stream.filter((current) => current.settled),
- Stream.runHead,
- Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
- );
- const waited = Option.flatten(yield* wait);
- if (Option.isSome(waited)) {
- return { threadId: input.threadId, run: waited.value.run, timedOut: false };
- }
- // The run may have reached a terminal status while the timeout was
- // winning the race; the final projection read decides what actually
- // happened, so only a still-active run counts as timed out.
- const final = yield* outcome((yield* getProjectThreadRecords(input, ["runs"])).runs);
- return { threadId: input.threadId, run: final.run, timedOut: !final.settled };
- });
+ ),
+ initial.pending
+ ? Stream.fromEffect(orchestrator.awaitRestartContinuation(initial.run))
+ : Stream.empty,
+ ).pipe(
+ Stream.mapEffect(() =>
+ getProjectThreadRecords(input, ["runs"]).pipe(
+ Effect.flatMap((current) => outcome(current.runs)),
+ ),
+ ),
+ Stream.filter((current) => current.settled),
+ Stream.runHead,
+ Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
+ );
+ const waited = Option.flatten(yield* wait);
+ if (Option.isSome(waited)) {
+ return { threadId: input.threadId, run: waited.value.run, timedOut: false };
+ }
+ // The run may have reached a terminal status while the timeout was
+ // winning the race; the final projection read decides what actually
+ // happened, so only a still-active run counts as timed out.
+ const final = yield* outcome((yield* getProjectThreadRecords(input, ["runs"])).runs);
+ return { threadId: input.threadId, run: final.run, timedOut: !final.settled };
+ });
const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
"orchestrationV2.threadManagement.settleAfterRun",
@@ -959,55 +960,58 @@ const make = Effect.gen(function* () {
return { sequence: result.sequence };
});
- const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
- Effect.gen(function* () {
- const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
- const explicitRun =
- input.runId === undefined
- ? undefined
- : target.runs.find((candidate) => candidate.id === input.runId);
- if (input.runId !== undefined && explicitRun === undefined) {
- return yield* new ThreadManagementRunNotFoundError({
- threadId: input.threadId,
- runId: input.runId,
- });
- }
- if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
- return {
- type: "already_terminal",
- run: explicitRun as OrchestrationV2Run & {
- readonly status: ThreadManagementTerminalRunStatus;
- },
- } as const;
- }
- const interruptibleRun = latestActiveRun(target);
- if (interruptibleRun === undefined) {
- if (input.runId === undefined) {
- return { type: "no_active_run" } as const;
- }
- return yield* new ThreadManagementThreadNotInterruptibleError({
- threadId: input.threadId,
- runId: input.runId,
- });
- }
- if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
- return yield* new ThreadManagementThreadNotInterruptibleError({
- threadId: input.threadId,
- runId: input.runId,
- });
+ const interruptThread: ThreadManagementServiceShape["interruptThread"] = Effect.fn(
+ "ThreadManagementService.interruptThread",
+ )(function* (input) {
+ const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
+ const explicitRun =
+ input.runId === undefined
+ ? undefined
+ : target.runs.find((candidate) => candidate.id === input.runId);
+ if (input.runId !== undefined && explicitRun === undefined) {
+ return yield* new ThreadManagementRunNotFoundError({
+ threadId: input.threadId,
+ runId: input.runId,
+ });
+ }
+ if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
+ return {
+ type: "already_terminal",
+ run: explicitRun as OrchestrationV2Run & {
+ readonly status: ThreadManagementTerminalRunStatus;
+ },
+ } as const;
+ }
+ const interruptibleRun = latestActiveRun(target);
+ if (interruptibleRun === undefined) {
+ if (input.runId === undefined) {
+ return { type: "no_active_run" } as const;
}
- const dispatch = yield* orchestrator.dispatch({
- type: "run.interrupt",
- commandId: input.commandId,
+ return yield* new ThreadManagementThreadNotInterruptibleError({
threadId: input.threadId,
- runId: interruptibleRun.id,
- ...(input.reason === undefined ? {} : { reason: input.reason }),
+ runId: input.runId,
+ });
+ }
+ if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
+ return yield* new ThreadManagementThreadNotInterruptibleError({
+ threadId: input.threadId,
+ runId: input.runId,
});
- return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
+ }
+ const dispatch = yield* orchestrator.dispatch({
+ type: "run.interrupt",
+ commandId: input.commandId,
+ threadId: input.threadId,
+ runId: interruptibleRun.id,
+ ...(input.reason === undefined ? {} : { reason: input.reason }),
});
+ return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
+ });
- const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = (input) =>
- Effect.gen(function* () {
+ const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = Effect.fn(
+ "ThreadManagementService.stopWorkflow",
+ )(
+ function* (input) {
const records = yield* orchestrator
.getThreadRecords(input.threadId, ["subagents", "runs", "providerThreads"])
.pipe(
@@ -1088,39 +1092,42 @@ const make = Effect.gen(function* () {
}),
),
);
- }).pipe((effect) => threadDispatch.withLock(input.threadId, effect));
+ },
+ (effect, input) => effect.pipe((effect) => threadDispatch.withLock(input.threadId, effect)),
+ );
- const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = (input) =>
- Effect.gen(function* () {
- const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
- const failures: Array<
- Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
- > = [];
- const stoppedChildThreadIds = new Set<ThreadId>();
- for (const task of subagents) {
- if (task.origin !== "app_owned" || task.childThreadId === null) continue;
- const threadId = task.childThreadId;
- // Follow-up tasks reuse a child thread; walk its subtree only once.
- if (stoppedChildThreadIds.has(threadId)) continue;
- stoppedChildThreadIds.add(threadId);
- yield* dispatch({
- type: "thread.stop",
- commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
- threadId,
- ...(input.reason === undefined ? {} : { reason: input.reason }),
- }).pipe(
- Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
- Effect.catch((error) =>
- Effect.logWarning("Unable to stop a delegated task", {
- parentThreadId: input.threadId,
- threadId,
- error,
- }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
- ),
- );
- }
- if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
- });
+ const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn(
+ "ThreadManagementService.stopDelegatedTasks",
+ )(function* (input) {
+ const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
+ const failures: Array<
+ Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
+ > = [];
+ const stoppedChildThreadIds = new Set<ThreadId>();
+ for (const task of subagents) {
+ if (task.origin !== "app_owned" || task.childThreadId === null) continue;
+ const threadId = task.childThreadId;
+ // Follow-up tasks reuse a child thread; walk its subtree only once.
+ if (stoppedChildThreadIds.has(threadId)) continue;
+ stoppedChildThreadIds.add(threadId);
+ yield* dispatch({
+ type: "thread.stop",
+ commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
+ threadId,
+ ...(input.reason === undefined ? {} : { reason: input.reason }),
+ }).pipe(
+ Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
+ Effect.catch((error) =>
+ Effect.logWarning("Unable to stop a delegated task", {
+ parentThreadId: input.threadId,
+ threadId,
+ error,
+ }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
+ ),
+ );
+ }
+ if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
+ });
return ThreadManagementService.of({
ensureLegacyTranscript,
diff --git a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
index c07eca4048b..9f5b3ab38c9 100644
--- a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
+++ b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
@@ -361,9 +361,10 @@ const make = Effect.gen(function* () {
ORDER BY created_at ASC, message_id ASC
`;
- const listShellMessages = (threadId: ThreadId) =>
- Effect.gen(function* () {
- const latest = yield* sql<LegacyMessageRow>`
+ const listShellMessages = Effect.fn("LegacyV1ThreadImporter.listShellMessages")(function* (
+ threadId: ThreadId,
+ ) {
+ const latest = yield* sql<LegacyMessageRow>`
SELECT
message.message_id,
message.thread_id,
@@ -393,7 +394,7 @@ const make = Effect.gen(function* () {
ORDER BY message.created_at DESC, message.message_id DESC
LIMIT 1
`;
- const latestUser = yield* sql<LegacyMessageRow>`
+ const latestUser = yield* sql<LegacyMessageRow>`
SELECT
message.message_id,
message.thread_id,
@@ -423,12 +424,12 @@ const make = Effect.gen(function* () {
ORDER BY message.created_at DESC, message.message_id DESC
LIMIT 1
`;
- return [latestUser[0], latest[0]].filter(
- (message, index, selected): message is LegacyMessageRow =>
- message !== undefined &&
- selected.findIndex((candidate) => candidate?.message_id === message.message_id) === index,
- );
- });
+ return [latestUser[0], latest[0]].filter(
+ (message, index, selected): message is LegacyMessageRow =>
+ message !== undefined &&
+ selected.findIndex((candidate) => candidate?.message_id === message.message_id) === index,
+ );
+ });
const reconcileShellsBase = Effect.gen(function* () {
const now = DateTime.formatIso(yield* DateTime.now);