@devries-cameron20 / t3code-1 / commits / c911f654b9
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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

Julius Marminge committed Oct 19, 2026 at 18:30 UTC c911f654b9fb604e93808c4cb216eb0e99825878
19 files changed +6597 -6570
apps/server/src/orchestration-v2/CheckpointRollbackService.ts
+18 -14
@@ -355,26 +355,30 @@ export const layer: Layer.Layer<
355 });
356
357 return CheckpointRollbackServiceV2.of({
358 - execute: (input) =>
359 - Effect.gen(function* () {
358 + // The inner execute owns the rollback span; this wrapper selects the workspace lease.
359 + execute: Effect.fnUntraced(
360 + function* (input) {
361 // Storage cleanup removes worktrees under the same lease.
362 const thread = yield* projections.getThread(input.threadId);
363 yield* thread.worktreePath === null
364 ? execute(input)
365 : withWorkspaceLease(path.resolve(thread.worktreePath), execute(input));
365 - }).pipe(
366 - Effect.mapError((cause) =>
367 - isCheckpointRollbackExecutionError(cause)
368 - ? cause
369 - : new CheckpointRollbackExecutionError({
370 - reason: "unexpected-failure",
371 - threadId: input.threadId,
372 - providerThreadId: input.providerThreadId,
373 - checkpointId: input.checkpointId,
374 - cause,
375 - }),
366 + },
367 + (effect, input) =>
368 + effect.pipe(
369 + Effect.mapError((cause) =>
370 + isCheckpointRollbackExecutionError(cause)
371 + ? cause
372 + : new CheckpointRollbackExecutionError({
373 + reason: "unexpected-failure",
374 + threadId: input.threadId,
375 + providerThreadId: input.providerThreadId,
376 + checkpointId: input.checkpointId,
377 + cause,
378 + }),
379 + ),
380 ),
377 - ),
381 + ),
382 });
383 }),
384 );
apps/server/src/orchestration-v2/CheckpointService.ts
+18 -20
@@ -184,7 +184,7 @@ function checkpointIdForScopeOrdinal(
184 });
185 }
186
187 -function makeRootRunScope(input: {
187 +const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(function* (input: {
188 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
189 readonly threadId: ThreadId;
190 readonly runId: RunId;
@@ -193,26 +193,24 @@ function makeRootRunScope(input: {
193 readonly cwd: string;
194 readonly createdAt: DateTime.Utc;
195 }) {
196 - return Effect.gen(function* () {
197 - const scopeId = yield* input.idAllocator.allocate.checkpointScope({
198 - threadId: input.threadId,
199 - name: ROOT_CHECKPOINT_SCOPE_NAME,
200 - });
201 - return {
202 - id: scopeId,
203 - threadId: input.threadId,
204 - runId: input.runId,
205 - nodeId: input.rootNodeId,
206 - parentScopeId: null,
207 - providerThreadId: input.providerThreadId,
208 - kind: "root_run",
209 - ordinalWithinParent: 0,
210 - advancesAppRunCount: true,
211 - cwd: input.cwd,
212 - createdAt: input.createdAt,
213 - } satisfies OrchestrationV2CheckpointScope;
196 + const scopeId = yield* input.idAllocator.allocate.checkpointScope({
197 + threadId: input.threadId,
198 + name: ROOT_CHECKPOINT_SCOPE_NAME,
199 });
215 -}
200 + return {
201 + id: scopeId,
202 + threadId: input.threadId,
203 + runId: input.runId,
204 + nodeId: input.rootNodeId,
205 + parentScopeId: null,
206 + providerThreadId: input.providerThreadId,
207 + kind: "root_run",
208 + ordinalWithinParent: 0,
209 + advancesAppRunCount: true,
210 + cwd: input.cwd,
211 + createdAt: input.createdAt,
212 + } satisfies OrchestrationV2CheckpointScope;
213 +});
214
215 function makeCheckpoint(input: {
216 readonly id: CheckpointId;
apps/server/src/orchestration-v2/DelegatedTaskQuestionReactor.ts
+13 -9
@@ -58,8 +58,9 @@ const make = Effect.gen(function* () {
58 });
59 });
60
61 - const handle: DelegatedTaskQuestionReactor["Service"]["handle"] = (event) =>
62 - Effect.gen(function* () {
61 + // Runs for every domain event; most events return before any work is needed.
62 + const handle: DelegatedTaskQuestionReactor["Service"]["handle"] = Effect.fnUntraced(
63 + function* (event) {
64 if (event.type === "run.updated") {
65 if (!["completed", "failed", "waiting"].includes(event.payload.status)) return;
66 const parent = yield* projections.getThreadRecords(event.threadId, ["subagents"]);
@@ -154,14 +155,17 @@ const make = Effect.gen(function* () {
155 return;
156 }
157 yield* wakeParent(task, request);
157 - }).pipe(
158 - Effect.catchCause((cause) =>
159 - Effect.logWarning("waking the parent of a delegated task question failed", {
160 - threadId: event.threadId,
161 - cause,
162 - }),
158 + },
159 + (effect, event) =>
160 + effect.pipe(
161 + Effect.catchCause((cause) =>
162 + Effect.logWarning("waking the parent of a delegated task question failed", {
163 + threadId: event.threadId,
164 + cause,
165 + }),
166 + ),
167 ),
164 - );
168 + );
169
170 const start: DelegatedTaskQuestionReactor["Service"]["start"] = () =>
171 forkParked(
apps/server/src/orchestration-v2/EffectWorker.ts
+19 -16
@@ -673,8 +673,9 @@ export const layerWithOptions = (
673 ? requeueClaim(effect, cause)
674 : terminalizeClaim(effect, cause);
675
676 - const runOnce = (excludeRestartContinuations = false) =>
677 - Effect.gen(function* () {
676 + // The worker probes for work repeatedly, including when the outbox is empty.
677 + const runOnce = Effect.fnUntraced(
678 + function* (excludeRestartContinuations = false) {
679 const claimExit = yield* Effect.exit(
680 outbox.claimNext({ workerId, leaseDurationMs, excludeRestartContinuations }),
681 );
@@ -781,13 +782,16 @@ export const layerWithOptions = (
782 });
783 }
784 return true;
784 - }).pipe(
785 - Effect.mapError((cause) =>
786 - isOrchestrationEffectWorkerError(cause)
787 - ? cause
788 - : new OrchestrationEffectWorkerError({ operation: "run", cause }),
785 + },
786 + (effect, _excludeRestartContinuations?: boolean) =>
787 + effect.pipe(
788 + Effect.mapError((cause) =>
789 + isOrchestrationEffectWorkerError(cause)
790 + ? cause
791 + : new OrchestrationEffectWorkerError({ operation: "run", cause }),
792 + ),
793 ),
790 - );
794 + );
795
796 return OrchestrationEffectWorkerV2.of({
797 awaitWork: outbox.awaitAvailable,
@@ -802,14 +806,13 @@ export const layerWithOptions = (
806 }),
807 ),
808 ),
805 - drain: (maxEffects = Number.MAX_SAFE_INTEGER) =>
806 - Effect.gen(function* () {
807 - let completed = 0;
808 - while (completed < maxEffects && (yield* runOnce())) {
809 - completed += 1;
810 - }
811 - return completed;
812 - }),
809 + drain: Effect.fn("EffectWorker.drain")(function* (maxEffects = Number.MAX_SAFE_INTEGER) {
810 + let completed = 0;
811 + while (completed < maxEffects && (yield* runOnce())) {
812 + completed += 1;
813 + }
814 + return completed;
815 + }),
816 });
817 }),
818 );
apps/server/src/orchestration-v2/Orchestrator.ts
+4800 -4823
@@ -917,11 +917,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
917 ),
918 );
919
920 - const makeEvent = <Event extends OrchestrationV2DomainEvent>(
921 - command: OrchestrationV2ServerCommand,
922 - event: Omit<Event, "id">,
923 - ) =>
924 - Effect.gen(function* () {
920 + const makeEvent =
921 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
922 + Effect.fnUntraced(function* <Event extends OrchestrationV2DomainEvent>(
923 + command: OrchestrationV2ServerCommand,
924 + event: Omit<Event, "id">,
925 + ) {
926 const eventId = yield* mapDispatchError(command)(
927 idAllocator.allocate.event({
928 threadId: event.threadId,
@@ -993,11 +994,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
994 Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
995 );
996
996 - const getProjectionWithPendingEvents = (
997 - threadId: ThreadId,
998 - events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
999 - ) =>
1000 - Effect.gen(function* () {
997 + const getProjectionWithPendingEvents =
998 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
999 + Effect.fnUntraced(function* (
1000 + threadId: ThreadId,
1001 + events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
1002 + ) {
1003 const pending = (yield* Ref.get(events)).filter((event) => event.threadId === threadId);
1004 const stored = yield* Effect.option(readCommandProjection(threadId));
1005 let projection: OrchestrationV2ThreadProjection;
@@ -1026,8 +1028,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1028 return projection;
1029 });
1030
1029 - const makeSystemEvent = <Event extends OrchestrationV2DomainEvent>(event: Omit<Event, "id">) =>
1030 - Effect.gen(function* () {
1031 + const makeSystemEvent =
1032 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
1033 + Effect.fnUntraced(function* <Event extends OrchestrationV2DomainEvent>(
1034 + event: Omit<Event, "id">,
1035 + ) {
1036 const eventId = yield* idAllocator.allocate.event({
1037 threadId: event.threadId,
1038 });
@@ -1037,11 +1042,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1042 } as Event;
1043 });
1044
1040 - const writeSystemEvents = (
1041 - events: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">>,
1042 - effects: ReadonlyArray<PendingOrchestrationEffectV2> = [],
1043 - ) =>
1044 - Effect.gen(function* () {
1045 + const writeSystemEvents =
1046 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
1047 + Effect.fnUntraced(function* (
1048 + events: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">>,
1049 + effects: ReadonlyArray<PendingOrchestrationEffectV2> = [],
1050 + ) {
1051 const withIds = yield* Effect.forEach(events, (event) =>
1052 makeSystemEvent(event as Omit<OrchestrationV2DomainEvent, "id">),
1053 );
@@ -1065,8 +1071,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1071 ? undefined
1072 : projection.messages.find((candidate) => candidate.id === delivery.messageId);
1073
1068 - const offerDelegatedCompletionDelivery = (threadId: ThreadId, parentRunId: RunId) =>
1069 - Effect.gen(function* () {
1074 + const offerDelegatedCompletionDelivery =
1075 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
1076 + Effect.fnUntraced(function* (threadId: ThreadId, parentRunId: RunId) {
1077 const projection = yield* projectionStore.getThreadRecords(
1078 threadId,
1079 ["runs", "messages", "providerTurns", "providerThreads"],
@@ -1111,8 +1118,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1118 });
1119 });
1120
1114 - const offerDelegatedCompletionDeliveries = (threadId: ThreadId) =>
1115 - Effect.gen(function* () {
1121 + const offerDelegatedCompletionDeliveries =
1122 + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
1123 + Effect.fnUntraced(function* (threadId: ThreadId) {
1124 const projection = yield* projectionStore.getThreadRecords(threadId, ["runs"]);
1125 for (const run of projection.runs) {
1126 if (
@@ -1124,14 +1132,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1132 }
1133 });
1134
1127 - const emitQueuedRunCancellation = (input: {
1128 - readonly command: OrchestrationV2ServerCommand;
1129 - readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
1130 - readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">;
1131 - readonly run: OrchestrationV2Run;
1132 - readonly now: DateTime.Utc;
1133 - }) =>
1134 - Effect.gen(function* () {
1135 + const emitQueuedRunCancellation = Effect.fn("Orchestrator.emitQueuedRunCancellation")(
1136 + function* (input: {
1137 + readonly command: OrchestrationV2ServerCommand;
1138 + readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
1139 + readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">;
1140 + readonly run: OrchestrationV2Run;
1141 + readonly now: DateTime.Utc;
1142 + }) {
1143 const rootNode =
1144 input.run.rootNodeId === null
1145 ? undefined
@@ -1187,118 +1195,121 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1195 },
1196 });
1197 }
1190 - });
1198 + },
1199 + );
1200
1192 - const failQueuedRunStart = (threadId: ThreadId, cause: unknown) =>
1193 - Effect.gen(function* () {
1194 - const projection = yield* projectionStore.getThreadRecords(
1195 - threadId,
1196 - ["runs", "nodes", "attempts", "providerThreads", "turnItems", "messages"],
1197 - { turnItemTypes: [], messageRoles: ["user"] },
1198 - );
1199 - const queuedRun = nextQueuedRun(projection);
1200 - if (queuedRun === undefined) return;
1201 - const now = yield* DateTime.now;
1202 - const rootNode = projection.nodes.find((node) => node.id === queuedRun.rootNodeId);
1203 - const attempt = projection.attempts.find((entry) => entry.id === queuedRun.activeAttemptId);
1204 - const providerThread = projection.providerThreads.find(
1205 - (entry) => entry.id === queuedRun.providerThreadId,
1206 - );
1207 - const handoffUnsupported =
1208 - typeof cause === "object" &&
1209 - cause !== null &&
1210 - "_tag" in cause &&
1211 - cause._tag === "CommandPolicyCapabilityUnsupportedError";
1212 - const failureCause =
1213 - typeof cause === "object" &&
1214 - cause !== null &&
1215 - "_tag" in cause &&
1216 - cause._tag === "OrchestratorDispatchError" &&
1217 - "cause" in cause
1218 - ? cause.cause
1219 - : cause;
1220 - const failure = makeProviderFailure({
1221 - cause: failureCause,
1222 - code: handoffUnsupported ? "context_handoff_unsupported" : "queued_start_failed",
1223 - class: handoffUnsupported ? "validation_error" : "unknown",
1224 - });
1225 - yield* writeSystemEvents([
1226 - ...(attempt !== undefined && rootNode !== undefined
1227 - ? [
1228 - {
1229 - type: "run-attempt.updated" as const,
1230 - threadId,
1231 - runId: queuedRun.id,
1232 - nodeId: rootNode.id,
1233 - providerInstanceId: queuedRun.providerInstanceId,
1234 - occurredAt: now,
1235 - payload: { ...attempt, status: "failed" as const, completedAt: now },
1236 - },
1237 - ]
1238 - : []),
1239 - ...(rootNode === undefined
1240 - ? []
1241 - : [
1242 - {
1243 - type: "node.updated" as const,
1244 - threadId,
1245 - runId: queuedRun.id,
1246 - nodeId: rootNode.id,
1247 - providerInstanceId: queuedRun.providerInstanceId,
1248 - occurredAt: now,
1249 - payload: { ...rootNode, status: "failed" as const, completedAt: now },
1250 - },
1251 - ]),
1252 - ...(rootNode === undefined || providerThread === undefined
1253 - ? []
1254 - : [
1255 - {
1256 - type: "turn-item.updated" as const,
1201 + const failQueuedRunStart = Effect.fn("Orchestrator.failQueuedRunStart")(function* (
1202 + threadId: ThreadId,
1203 + cause: unknown,
1204 + ) {
1205 + const projection = yield* projectionStore.getThreadRecords(
1206 + threadId,
1207 + ["runs", "nodes", "attempts", "providerThreads", "turnItems", "messages"],
1208 + { turnItemTypes: [], messageRoles: ["user"] },
1209 + );
1210 + const queuedRun = nextQueuedRun(projection);
1211 + if (queuedRun === undefined) return;
1212 + const now = yield* DateTime.now;
1213 + const rootNode = projection.nodes.find((node) => node.id === queuedRun.rootNodeId);
1214 + const attempt = projection.attempts.find((entry) => entry.id === queuedRun.activeAttemptId);
1215 + const providerThread = projection.providerThreads.find(
1216 + (entry) => entry.id === queuedRun.providerThreadId,
1217 + );
1218 + const handoffUnsupported =
1219 + typeof cause === "object" &&
1220 + cause !== null &&
1221 + "_tag" in cause &&
1222 + cause._tag === "CommandPolicyCapabilityUnsupportedError";
1223 + const failureCause =
1224 + typeof cause === "object" &&
1225 + cause !== null &&
1226 + "_tag" in cause &&
1227 + cause._tag === "OrchestratorDispatchError" &&
1228 + "cause" in cause
1229 + ? cause.cause
1230 + : cause;
1231 + const failure = makeProviderFailure({
1232 + cause: failureCause,
1233 + code: handoffUnsupported ? "context_handoff_unsupported" : "queued_start_failed",
1234 + class: handoffUnsupported ? "validation_error" : "unknown",
1235 + });
1236 + yield* writeSystemEvents([
1237 + ...(attempt !== undefined && rootNode !== undefined
1238 + ? [
1239 + {
1240 + type: "run-attempt.updated" as const,
1241 + threadId,
1242 + runId: queuedRun.id,
1243 + nodeId: rootNode.id,
1244 + providerInstanceId: queuedRun.providerInstanceId,
1245 + occurredAt: now,
1246 + payload: { ...attempt, status: "failed" as const, completedAt: now },
1247 + },
1248 + ]
1249 + : []),
1250 + ...(rootNode === undefined
1251 + ? []
1252 + : [
1253 + {
1254 + type: "node.updated" as const,
1255 + threadId,
1256 + runId: queuedRun.id,
1257 + nodeId: rootNode.id,
1258 + providerInstanceId: queuedRun.providerInstanceId,
1259 + occurredAt: now,
1260 + payload: { ...rootNode, status: "failed" as const, completedAt: now },
1261 + },
1262 + ]),
1263 + ...(rootNode === undefined || providerThread === undefined
1264 + ? []
1265 + : [
1266 + {
1267 + type: "turn-item.updated" as const,
1268 + threadId,
1269 + runId: queuedRun.id,
1270 + nodeId: rootNode.id,
1271 + providerInstanceId: queuedRun.providerInstanceId,
1272 + occurredAt: now,
1273 + payload: {
1274 + id: idAllocator.derive.turnItemFromProviderItem({
1275 + driver: providerThread.driver,
1276 + nativeItemId: `queued-start-failure:${queuedRun.id}`,
1277 + }),
1278 threadId,
1279 runId: queuedRun.id,
1280 nodeId: rootNode.id,
1260 - providerInstanceId: queuedRun.providerInstanceId,
1261 - occurredAt: now,
1262 - payload: {
1263 - id: idAllocator.derive.turnItemFromProviderItem({
1264 - driver: providerThread.driver,
1265 - nativeItemId: `queued-start-failure:${queuedRun.id}`,
1266 - }),
1267 - threadId,
1268 - runId: queuedRun.id,
1269 - nodeId: rootNode.id,
1270 - providerThreadId: providerThread.id,
1271 - providerTurnId: null,
1272 - nativeItemRef: null,
1273 - parentItemId: null,
1274 - ordinal: yield* nextTurnItemOrdinal(projection),
1275 - status: "failed" as const,
1276 - title: "Queued provider could not start",
1277 - startedAt: now,
1278 - completedAt: now,
1279 - updatedAt: now,
1280 - type: "error" as const,
1281 - failure,
1282 - },
1281 + providerThreadId: providerThread.id,
1282 + providerTurnId: null,
1283 + nativeItemRef: null,
1284 + parentItemId: null,
1285 + ordinal: yield* nextTurnItemOrdinal(projection),
1286 + status: "failed" as const,
1287 + title: "Queued provider could not start",
1288 + startedAt: now,
1289 + completedAt: now,
1290 + updatedAt: now,
1291 + type: "error" as const,
1292 + failure,
1293 },
1284 - ]),
1285 - {
1286 - type: "run.updated",
1287 - threadId,
1288 - runId: queuedRun.id,
1289 - ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
1290 - providerInstanceId: queuedRun.providerInstanceId,
1291 - occurredAt: now,
1292 - payload: { ...queuedRun, status: "failed", queuePosition: null, completedAt: now },
1293 - },
1294 - ]);
1295 - });
1294 + },
1295 + ]),
1296 + {
1297 + type: "run.updated",
1298 + threadId,
1299 + runId: queuedRun.id,
1300 + ...(rootNode === undefined ? {} : { nodeId: rootNode.id }),
1301 + providerInstanceId: queuedRun.providerInstanceId,
1302 + occurredAt: now,
1303 + payload: { ...queuedRun, status: "failed", queuePosition: null, completedAt: now },
1304 + },
1305 + ]);
1306 + });
1307
1297 - const startNextQueuedRun = (
1298 - threadId: ThreadId,
1299 - options?: { readonly failedRunId?: RunId; readonly endedRunId?: RunId },
1300 - ) =>
1301 - Effect.gen(function* () {
1308 + const startNextQueuedRun = Effect.fn("Orchestrator.startNextQueuedRun")(
1309 + function* (
1310 + threadId: ThreadId,
1311 + options?: { readonly failedRunId?: RunId; readonly endedRunId?: RunId },
1312 + ) {
1313 if (!(yield* projectionStore.canStartQueuedRun(threadId))) return;
1314 const projection = yield* readCommandProjection(threadId);
1315 if (
@@ -1934,7 +1945,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1945 },
1946 ],
1947 );
1937 - }).pipe(Effect.catch((cause) => failQueuedRunStart(threadId, cause)));
1948 + },
1949 + (effect, threadId, _options?) =>
1950 + effect.pipe(Effect.catch((cause) => failQueuedRunStart(threadId, cause))),
1951 + );
1952
1953 const resumeQueuedRuns = Effect.gen(function* () {
1954 const threadIds = yield* projectionStore.getRecoveryThreadIds("queued-runs");
@@ -1968,7 +1982,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1982 ),
1983 );
1984
1971 - const dispatchDelegatedTaskCompletionDeliveryResolution = (
1985 + const dispatchDelegatedTaskCompletionDeliveryResolution = Effect.fn(
1986 + "Orchestrator.dispatchDelegatedTaskCompletionDeliveryResolution",
1987 + )(function* (
1988 command: Extract<
1989 OrchestrationV2Command,
1990 {
@@ -1978,71 +1994,47 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1994 }
1995 >,
1996 events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
1981 - ) =>
1982 - Effect.gen(function* () {
1983 - const projection = yield* projectionStore
1984 - .getThreadRecords(
1985 - command.parentThreadId,
1986 - ["subagents", "runs", "messages", "nodes", "attempts", "turnItems"],
1987 - { turnItemTypes: [], messageRoles: ["user"] },
1988 - )
1989 - .pipe(
1990 - Effect.mapError(
1991 - (cause) =>
1992 - new OrchestratorProjectionError({
1993 - threadId: command.parentThreadId,
1994 - cause,
1995 - }),
1996 - ),
1997 - );
1998 - const task = projection.subagents.find(
1999 - (candidate) => candidate.id === command.taskId && candidate.origin === "app_owned",
1997 + ) {
1998 + const projection = yield* projectionStore
1999 + .getThreadRecords(
2000 + command.parentThreadId,
2001 + ["subagents", "runs", "messages", "nodes", "attempts", "turnItems"],
2002 + { turnItemTypes: [], messageRoles: ["user"] },
2003 + )
2004 + .pipe(
2005 + Effect.mapError(
2006 + (cause) =>
2007 + new OrchestratorProjectionError({
2008 + threadId: command.parentThreadId,
2009 + cause,
2010 + }),
2011 + ),
2012 );
2001 - if (task === undefined) {
2002 - return yield* new OrchestratorDispatchError({
2003 - commandId: command.commandId,
2004 - commandType: command.type,
2005 - cause: `Delegated task ${command.taskId} is not an app-owned task of thread ${command.parentThreadId}.`,
2006 - });
2007 - }
2008 - const state =
2009 - command.type === "delegated_task.completion-delivery.acknowledge"
2010 - ? "acknowledged"
2011 - : "disposed";
2012 - const now = yield* DateTime.now;
2013 - const emitEvent = emit(events, command);
2014 - // task_status and t3_thread_read use distinct command IDs, so two
2015 - // valid observations can race after their read preflight. Re-emit the
2016 - // existing task row so the second dispatch is a successful idempotent
2017 - // no-op rather than "already acknowledged/disposed" or empty-events.
2018 - if (
2019 - task.completionDelivery?.state === state ||
2020 - (command.type === "delegated_task.completion-delivery.acknowledge" &&
2021 - task.completionDelivery?.state === "disposed")
2022 - ) {
2023 - yield* emitEvent({
2024 - type: "subagent.updated",
2025 - threadId: command.parentThreadId,
2026 - ...(task.runId === null ? {} : { runId: task.runId }),
2027 - nodeId: task.id,
2028 - driver: task.driver,
2029 - providerInstanceId: task.providerInstanceId,
2030 - occurredAt: now,
2031 - payload: task,
2032 - });
2033 - return;
2034 - }
2035 - const updatedTask: OrchestrationV2Subagent = {
2036 - ...task,
2037 - completionDelivery: {
2038 - state,
2039 - observedByRunId:
2040 - command.type === "delegated_task.completion-delivery.acknowledge"
2041 - ? command.observedByRunId
2042 - : null,
2043 - },
2044 - updatedAt: now,
2045 - };
2013 + const task = projection.subagents.find(
2014 + (candidate) => candidate.id === command.taskId && candidate.origin === "app_owned",
2015 + );
2016 + if (task === undefined) {
2017 + return yield* new OrchestratorDispatchError({
2018 + commandId: command.commandId,
2019 + commandType: command.type,
2020 + cause: `Delegated task ${command.taskId} is not an app-owned task of thread ${command.parentThreadId}.`,
2021 + });
2022 + }
2023 + const state =
2024 + command.type === "delegated_task.completion-delivery.acknowledge"
2025 + ? "acknowledged"
2026 + : "disposed";
2027 + const now = yield* DateTime.now;
2028 + const emitEvent = emit(events, command);
2029 + // task_status and t3_thread_read use distinct command IDs, so two
2030 + // valid observations can race after their read preflight. Re-emit the
2031 + // existing task row so the second dispatch is a successful idempotent
2032 + // no-op rather than "already acknowledged/disposed" or empty-events.
2033 + if (
2034 + task.completionDelivery?.state === state ||
2035 + (command.type === "delegated_task.completion-delivery.acknowledge" &&
2036 + task.completionDelivery?.state === "disposed")
2037 + ) {
2038 yield* emitEvent({
2039 type: "subagent.updated",
2040 threadId: command.parentThreadId,
@@ -2051,90 +2043,115 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2043 driver: task.driver,
2044 providerInstanceId: task.providerInstanceId,
2045 occurredAt: now,
2054 - payload: updatedTask,
2046 + payload: task,
2047 });
2048 + return;
2049 + }
2050 + const updatedTask: OrchestrationV2Subagent = {
2051 + ...task,
2052 + completionDelivery: {
2053 + state,
2054 + observedByRunId:
2055 + command.type === "delegated_task.completion-delivery.acknowledge"
2056 + ? command.observedByRunId
2057 + : null,
2058 + },
2059 + updatedAt: now,
2060 + };
2061 + yield* emitEvent({
2062 + type: "subagent.updated",
2063 + threadId: command.parentThreadId,
2064 + ...(task.runId === null ? {} : { runId: task.runId }),
2065 + nodeId: task.id,
2066 + driver: task.driver,
2067 + providerInstanceId: task.providerInstanceId,
2068 + occurredAt: now,
2069 + payload: updatedTask,
2070 + });
2071
2057 - const parentRun =
2058 - task.runId === null
2059 - ? undefined
2060 - : projection.runs.find((candidate) => candidate.id === task.runId);
2061 - const cohort = parentRun?.delegatedCompletion;
2062 - const delivery = cohort?.delivery;
2063 - if (
2064 - parentRun === undefined ||
2065 - cohort === undefined ||
2066 - delivery === null ||
2067 - delivery === undefined
2068 - ) {
2072 + const parentRun =
2073 + task.runId === null
2074 + ? undefined
2075 + : projection.runs.find((candidate) => candidate.id === task.runId);
2076 + const cohort = parentRun?.delegatedCompletion;
2077 + const delivery = cohort?.delivery;
2078 + if (
2079 + parentRun === undefined ||
2080 + cohort === undefined ||
2081 + delivery === null ||
2082 + delivery === undefined
2083 + ) {
2084 + return;
2085 + }
2086 + if (!delivery.taskIds.includes(task.id)) {
2087 + return;
2088 + }
2089 +
2090 + const remainingTaskIds = delivery.taskIds.filter((taskId) => taskId !== task.id);
2091 + const deliveryRun = completionDeliveryRun(projection, delivery);
2092 + const clearDelivery =
2093 + remainingTaskIds.length === 0 &&
2094 + (deliveryRun === undefined || deliveryRun.status === "queued");
2095 + const updatedCohort: OrchestrationV2DelegatedCompletionCohort = {
2096 + ...cohort,
2097 + delivery: clearDelivery
2098 + ? null
2099 + : {
2100 + ...delivery,
2101 + taskIds: remainingTaskIds,
2102 + },
2103 + };
2104 + yield* emitEvent({
2105 + type: "run.updated",
2106 + threadId: command.parentThreadId,
2107 + runId: parentRun.id,
2108 + ...(parentRun.rootNodeId === null ? {} : { nodeId: parentRun.rootNodeId }),
2109 + providerInstanceId: parentRun.providerInstanceId,
2110 + occurredAt: now,
2111 + payload: {
2112 + ...parentRun,
2113 + delegatedCompletion: updatedCohort,
2114 + },
2115 + });
2116 +
2117 + if (deliveryRun?.status === "queued") {
2118 + if (remainingTaskIds.length === 0) {
2119 + yield* emitQueuedRunCancellation({
2120 + command,
2121 + events,
2122 + projection,
2123 + run: deliveryRun,
2124 + now,
2125 + });
2126 return;
2127 }
2071 - if (!delivery.taskIds.includes(task.id)) {
2072 - return;
2073 - }
2074 -
2075 - const remainingTaskIds = delivery.taskIds.filter((taskId) => taskId !== task.id);
2076 - const deliveryRun = completionDeliveryRun(projection, delivery);
2077 - const clearDelivery =
2078 - remainingTaskIds.length === 0 &&
2079 - (deliveryRun === undefined || deliveryRun.status === "queued");
2080 - const updatedCohort: OrchestrationV2DelegatedCompletionCohort = {
2081 - ...cohort,
2082 - delivery: clearDelivery
2083 - ? null
2084 - : {
2085 - ...delivery,
2128 + const message = completionDeliveryMessage(projection, delivery);
2129 + if (message !== undefined) {
2130 + yield* emitEvent({
2131 + type: "message.updated",
2132 + threadId: command.parentThreadId,
2133 + runId: deliveryRun.id,
2134 + ...(deliveryRun.rootNodeId === null ? {} : { nodeId: deliveryRun.rootNodeId }),
2135 + providerInstanceId: deliveryRun.providerInstanceId,
2136 + occurredAt: now,
2137 + payload: {
2138 + ...message,
2139 + text: delegatedCompletionWakeDetail(remainingTaskIds),
2140 + delegatedCompletion: {
2141 + parentRunId: parentRun.id,
2142 + generation: delivery.generation,
2143 taskIds: remainingTaskIds,
2144 },
2088 - };
2089 - yield* emitEvent({
2090 - type: "run.updated",
2091 - threadId: command.parentThreadId,
2092 - runId: parentRun.id,
2093 - ...(parentRun.rootNodeId === null ? {} : { nodeId: parentRun.rootNodeId }),
2094 - providerInstanceId: parentRun.providerInstanceId,
2095 - occurredAt: now,
2096 - payload: {
2097 - ...parentRun,
2098 - delegatedCompletion: updatedCohort,
2099 - },
2100 - });
2101 -
2102 - if (deliveryRun?.status === "queued") {
2103 - if (remainingTaskIds.length === 0) {
2104 - yield* emitQueuedRunCancellation({
2105 - command,
2106 - events,
2107 - projection,
2108 - run: deliveryRun,
2109 - now,
2110 - });
2111 - return;
2112 - }
2113 - const message = completionDeliveryMessage(projection, delivery);
2114 - if (message !== undefined) {
2115 - yield* emitEvent({
2116 - type: "message.updated",
2117 - threadId: command.parentThreadId,
2118 - runId: deliveryRun.id,
2119 - ...(deliveryRun.rootNodeId === null ? {} : { nodeId: deliveryRun.rootNodeId }),
2120 - providerInstanceId: deliveryRun.providerInstanceId,
2121 - occurredAt: now,
2122 - payload: {
2123 - ...message,
2124 - text: delegatedCompletionWakeDetail(remainingTaskIds),
2125 - delegatedCompletion: {
2126 - parentRunId: parentRun.id,
2127 - generation: delivery.generation,
2128 - taskIds: remainingTaskIds,
2129 - },
2130 - updatedAt: now,
2131 - },
2132 - });
2133 - }
2145 + updatedAt: now,
2146 + },
2147 + });
2148 }
2135 - });
2149 + }
2150 + });
2151
2137 - const disposeDelegatedCompletionCohort = (input: {
2152 + const disposeDelegatedCompletionCohort = Effect.fn(
2153 + "Orchestrator.disposeDelegatedCompletionCohort",
2154 + )(function* (input: {
2155 readonly command: OrchestrationV2ServerCommand;
2156 readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
2157 readonly projection: Pick<
@@ -2145,77 +2162,74 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2162 readonly disposition: "stopped" | "disposed";
2163 readonly now: DateTime.Utc;
2164 readonly cancelQueuedDelivery?: boolean;
2148 - }) =>
2149 - Effect.gen(function* () {
2150 - const parentRun = input.projection.runs.find(
2151 - (candidate) => candidate.id === input.parentRunId,
2152 - );
2153 - if (parentRun === undefined) {
2154 - return;
2155 - }
2156 - const cohort = parentRun.delegatedCompletion;
2157 - const tasks = input.projection.subagents.filter(
2158 - (candidate) => candidate.origin === "app_owned" && candidate.runId === input.parentRunId,
2159 - );
2160 - if (cohort === undefined && tasks.length === 0) {
2161 - return;
2165 + }) {
2166 + const parentRun = input.projection.runs.find((candidate) => candidate.id === input.parentRunId);
2167 + if (parentRun === undefined) {
2168 + return;
2169 + }
2170 + const cohort = parentRun.delegatedCompletion;
2171 + const tasks = input.projection.subagents.filter(
2172 + (candidate) => candidate.origin === "app_owned" && candidate.runId === input.parentRunId,
2173 + );
2174 + if (cohort === undefined && tasks.length === 0) {
2175 + return;
2176 + }
2177 + const emitEvent = emit(input.events, input.command);
2178 + const nextDisposition = cohort?.disposition === "disposed" ? "disposed" : input.disposition;
2179 + const nextCohort = {
2180 + disposition: nextDisposition,
2181 + nextGeneration: cohort?.nextGeneration ?? 1,
2182 + delivery: null,
2183 + } as const;
2184 + yield* emitEvent({
2185 + type: "run.updated",
2186 + threadId: parentRun.threadId,
2187 + runId: parentRun.id,
2188 + ...(parentRun.rootNodeId === null ? {} : { nodeId: parentRun.rootNodeId }),
2189 + providerInstanceId: parentRun.providerInstanceId,
2190 + occurredAt: input.now,
2191 + payload: {
2192 + ...parentRun,
2193 + delegatedCompletion: nextCohort,
2194 + },
2195 + });
2196 + for (const task of tasks) {
2197 + if (
2198 + task.completionDelivery?.state === "acknowledged" ||
2199 + task.completionDelivery?.state === "delivered" ||
2200 + task.completionDelivery?.state === "disposed"
2201 + ) {
2202 + continue;
2203 }
2163 - const emitEvent = emit(input.events, input.command);
2164 - const nextDisposition = cohort?.disposition === "disposed" ? "disposed" : input.disposition;
2165 - const nextCohort = {
2166 - disposition: nextDisposition,
2167 - nextGeneration: cohort?.nextGeneration ?? 1,
2168 - delivery: null,
2169 - } as const;
2204 yield* emitEvent({
2171 - type: "run.updated",
2205 + type: "subagent.updated",
2206 threadId: parentRun.threadId,
2173 - runId: parentRun.id,
2174 - ...(parentRun.rootNodeId === null ? {} : { nodeId: parentRun.rootNodeId }),
2175 - providerInstanceId: parentRun.providerInstanceId,
2207 + ...(task.runId === null ? {} : { runId: task.runId }),
2208 + nodeId: task.id,
2209 + driver: task.driver,
2210 + providerInstanceId: task.providerInstanceId,
2211 occurredAt: input.now,
2212 payload: {
2178 - ...parentRun,
2179 - delegatedCompletion: nextCohort,
2213 + ...task,
2214 + completionDelivery: {
2215 + state: "disposed",
2216 + observedByRunId: null,
2217 + },
2218 + updatedAt: input.now,
2219 },
2220 });
2182 - for (const task of tasks) {
2183 - if (
2184 - task.completionDelivery?.state === "acknowledged" ||
2185 - task.completionDelivery?.state === "delivered" ||
2186 - task.completionDelivery?.state === "disposed"
2187 - ) {
2188 - continue;
2189 - }
2190 - yield* emitEvent({
2191 - type: "subagent.updated",
2192 - threadId: parentRun.threadId,
2193 - ...(task.runId === null ? {} : { runId: task.runId }),
2194 - nodeId: task.id,
2195 - driver: task.driver,
2196 - providerInstanceId: task.providerInstanceId,
2197 - occurredAt: input.now,
2198 - payload: {
2199 - ...task,
2200 - completionDelivery: {
2201 - state: "disposed",
2202 - observedByRunId: null,
2203 - },
2204 - updatedAt: input.now,
2205 - },
2206 - });
2207 - }
2208 - const deliveryRun = completionDeliveryRun(input.projection, cohort?.delivery ?? null);
2209 - if (input.cancelQueuedDelivery !== false && deliveryRun?.status === "queued") {
2210 - yield* emitQueuedRunCancellation({
2211 - command: input.command,
2212 - events: input.events,
2213 - projection: input.projection,
2214 - run: deliveryRun,
2215 - now: input.now,
2216 - });
2217 - }
2218 - });
2221 + }
2222 + const deliveryRun = completionDeliveryRun(input.projection, cohort?.delivery ?? null);
2223 + if (input.cancelQueuedDelivery !== false && deliveryRun?.status === "queued") {
2224 + yield* emitQueuedRunCancellation({
2225 + command: input.command,
2226 + events: input.events,
2227 + projection: input.projection,
2228 + run: deliveryRun,
2229 + now: input.now,
2230 + });
2231 + }
2232 + });
2233
2234 const disposeAllDelegatedCompletionCohorts = (input: {
2235 readonly command: OrchestrationV2Command;
@@ -3903,7 +3917,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3917 });
3918 });
3919
3906 - const dispatchSteerIntoRun = (input: {
3920 + const dispatchSteerIntoRun = Effect.fn("Orchestrator.dispatchSteerIntoRun")(function* (input: {
3921 readonly command: Extract<
3922 OrchestrationV2Command,
3923 { readonly type: "message.dispatch" | "queued-message.promote-to-steer" }
@@ -3935,593 +3949,251 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3949 readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"];
3950 readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"];
3951 readonly forceRestart: boolean;
3938 - }) =>
3939 - Effect.gen(function* () {
3940 - const targetRun = input.projection.runs.find(
3941 - (candidate) => candidate.id === input.targetRunId,
3942 - );
3943 - if (targetRun === undefined) {
3944 - return yield* new OrchestratorDispatchError({
3945 - commandId: input.command.commandId,
3946 - commandType: input.command.type,
3947 - cause: `Target run ${input.targetRunId} was not found.`,
3948 - });
3949 - }
3950 - if (isNativeMaintenanceCommand(input)) {
3951 - return yield* new OrchestratorDispatchError({
3952 - commandId: input.command.commandId,
3953 - commandType: input.command.type,
3954 - cause:
3955 - input.text.trim().toLowerCase() === "/compact"
3956 - ? "Context compaction must run as a separate turn. Queue it or wait for the active turn to finish."
3957 - : "Signing out must run as a separate turn. Queue it or wait for the active turn to finish.",
3958 - });
3959 - }
3960 - if (isGoalCommand(input)) {
3961 - return yield* new OrchestratorDispatchError({
3962 - commandId: input.command.commandId,
3963 - commandType: input.command.type,
3964 - cause:
3965 - "Goal commands must run as a separate turn. Queue it or wait for the active turn to finish.",
3966 - });
3967 - }
3968 - const targetMessage = input.projection.messages.find(
3969 - (message) => message.id === targetRun.userMessageId,
3970 - );
3971 - if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) {
3972 - return yield* new OrchestratorDispatchError({
3973 - commandId: input.command.commandId,
3974 - commandType: input.command.type,
3975 - cause:
3976 - targetMessage.text.trim().toLowerCase() === "/compact"
3977 - ? "Wait for context compaction to finish before steering the thread."
3978 - : "Wait for sign-out to finish before steering the thread.",
3979 - });
3980 - }
3981 - const rootNodeId = targetRun.rootNodeId;
3982 - if (rootNodeId === null) {
3983 - return yield* new OrchestratorDispatchError({
3984 - commandId: input.command.commandId,
3985 - commandType: input.command.type,
3986 - cause: `Target run ${targetRun.id} has no root node.`,
3987 - });
3988 - }
3989 - if (targetRun.status !== "running") {
3990 - return yield* new OrchestratorDispatchError({
3991 - commandId: input.command.commandId,
3992 - commandType: input.command.type,
3993 - cause: `Target run ${targetRun.id} is ${targetRun.status} and cannot be steered.`,
3994 - });
3995 - }
3996 - // The run reads as running until its provider stops, but a steer accepted
3997 - // after Stop never reaches the agent.
3998 - if (yield* stopReachedRun(input.command, input.command.threadId, targetRun.id)) {
3999 - return yield* new OrchestratorDispatchError({
4000 - commandId: input.command.commandId,
4001 - commandType: input.command.type,
4002 - cause: `Target run ${targetRun.id} is stopping and cannot be steered.`,
4003 - });
4004 - }
4005 - const providerThread = input.projection.providerThreads.find(
4006 - (candidate) => candidate.id === targetRun.providerThreadId,
4007 - );
4008 - if (providerThread === undefined || providerThread.providerSessionId === null) {
4009 - return yield* new OrchestratorDispatchError({
4010 - commandId: input.command.commandId,
4011 - commandType: input.command.type,
4012 - cause: `Provider thread ${targetRun.providerThreadId} has no active provider session for steering.`,
4013 - });
4014 - }
4015 - const providerSessionId = providerThread.providerSessionId;
4016 - const providerTurn = input.projection.providerTurns.find(
4017 - (candidate) =>
4018 - candidate.runAttemptId === targetRun.activeAttemptId && candidate.status === "running",
4019 - );
4020 - if (providerTurn === undefined) {
4021 - return yield* new OrchestratorDispatchError({
4022 - commandId: input.command.commandId,
4023 - commandType: input.command.type,
4024 - cause: `No running provider turn found for active run ${targetRun.id}.`,
4025 - });
4026 - }
4027 - const sessionOption = yield* providerSessions.get(providerSessionId).pipe(
4028 - Effect.mapError(
4029 - (cause) =>
4030 - new OrchestratorDispatchError({
4031 - commandId: input.command.commandId,
4032 - commandType: input.command.type,
4033 - cause,
4034 - }),
4035 - ),
4036 - );
4037 - if (Option.isNone(sessionOption)) {
4038 - return yield* new OrchestratorDispatchError({
4039 - commandId: input.command.commandId,
4040 - commandType: input.command.type,
4041 - cause: `Provider session ${providerThread.providerSessionId} is not active.`,
4042 - });
4043 - }
3952 + }) {
3953 + const targetRun = input.projection.runs.find((candidate) => candidate.id === input.targetRunId);
3954 + if (targetRun === undefined) {
3955 + return yield* new OrchestratorDispatchError({
3956 + commandId: input.command.commandId,
3957 + commandType: input.command.type,
3958 + cause: `Target run ${input.targetRunId} was not found.`,
3959 + });
3960 + }
3961 + if (isNativeMaintenanceCommand(input)) {
3962 + return yield* new OrchestratorDispatchError({
3963 + commandId: input.command.commandId,
3964 + commandType: input.command.type,
3965 + cause:
3966 + input.text.trim().toLowerCase() === "/compact"
3967 + ? "Context compaction must run as a separate turn. Queue it or wait for the active turn to finish."
3968 + : "Signing out must run as a separate turn. Queue it or wait for the active turn to finish.",
3969 + });
3970 + }
3971 + if (isGoalCommand(input)) {
3972 + return yield* new OrchestratorDispatchError({
3973 + commandId: input.command.commandId,
3974 + commandType: input.command.type,
3975 + cause:
3976 + "Goal commands must run as a separate turn. Queue it or wait for the active turn to finish.",
3977 + });
3978 + }
3979 + const targetMessage = input.projection.messages.find(
3980 + (message) => message.id === targetRun.userMessageId,
3981 + );
3982 + if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) {
3983 + return yield* new OrchestratorDispatchError({
3984 + commandId: input.command.commandId,
3985 + commandType: input.command.type,
3986 + cause:
3987 + targetMessage.text.trim().toLowerCase() === "/compact"
3988 + ? "Wait for context compaction to finish before steering the thread."
3989 + : "Wait for sign-out to finish before steering the thread.",
3990 + });
3991 + }
3992 + const rootNodeId = targetRun.rootNodeId;
3993 + if (rootNodeId === null) {
3994 + return yield* new OrchestratorDispatchError({
3995 + commandId: input.command.commandId,
3996 + commandType: input.command.type,
3997 + cause: `Target run ${targetRun.id} has no root node.`,
3998 + });
3999 + }
4000 + if (targetRun.status !== "running") {
4001 + return yield* new OrchestratorDispatchError({
4002 + commandId: input.command.commandId,
4003 + commandType: input.command.type,
4004 + cause: `Target run ${targetRun.id} is ${targetRun.status} and cannot be steered.`,
4005 + });
4006 + }
4007 + // The run reads as running until its provider stops, but a steer accepted
4008 + // after Stop never reaches the agent.
4009 + if (yield* stopReachedRun(input.command, input.command.threadId, targetRun.id)) {
4010 + return yield* new OrchestratorDispatchError({
4011 + commandId: input.command.commandId,
4012 + commandType: input.command.type,
4013 + cause: `Target run ${targetRun.id} is stopping and cannot be steered.`,
4014 + });
4015 + }
4016 + const providerThread = input.projection.providerThreads.find(
4017 + (candidate) => candidate.id === targetRun.providerThreadId,
4018 + );
4019 + if (providerThread === undefined || providerThread.providerSessionId === null) {
4020 + return yield* new OrchestratorDispatchError({
4021 + commandId: input.command.commandId,
4022 + commandType: input.command.type,
4023 + cause: `Provider thread ${targetRun.providerThreadId} has no active provider session for steering.`,
4024 + });
4025 + }
4026 + const providerSessionId = providerThread.providerSessionId;
4027 + const providerTurn = input.projection.providerTurns.find(
4028 + (candidate) =>
4029 + candidate.runAttemptId === targetRun.activeAttemptId && candidate.status === "running",
4030 + );
4031 + if (providerTurn === undefined) {
4032 + return yield* new OrchestratorDispatchError({
4033 + commandId: input.command.commandId,
4034 + commandType: input.command.type,
4035 + cause: `No running provider turn found for active run ${targetRun.id}.`,
4036 + });
4037 + }
4038 + const sessionOption = yield* providerSessions.get(providerSessionId).pipe(
4039 + Effect.mapError(
4040 + (cause) =>
4041 + new OrchestratorDispatchError({
4042 + commandId: input.command.commandId,
4043 + commandType: input.command.type,
4044 + cause,
4045 + }),
4046 + ),
4047 + );
4048 + if (Option.isNone(sessionOption)) {
4049 + return yield* new OrchestratorDispatchError({
4050 + commandId: input.command.commandId,
4051 + commandType: input.command.type,
4052 + cause: `Provider session ${providerThread.providerSessionId} is not active.`,
4053 + });
4054 + }
4055
4045 - const session = sessionOption.value;
4046 - const now = yield* DateTime.now;
4047 - const emitEvent = emit(input.events, input.command);
4048 - const selectionChanged = !modelSelectionsEqual(
4049 - targetRun.modelSelection,
4050 - input.modelSelection,
4051 - );
4052 - const providerInstanceChanged =
4053 - targetRun.providerInstanceId !== input.modelSelection.instanceId;
4054 - const selectionTransition =
4055 - selectionChanged && !providerInstanceChanged
4056 - ? yield* providerAdapters.get(targetRun.providerInstanceId).pipe(
4057 - Effect.flatMap((adapter) =>
4058 - adapter.planSelectionTransition({
4059 - current: targetRun.modelSelection,
4060 - target: input.modelSelection,
4061 - sessionCapabilities: session.providerSession.capabilities,
4056 + const session = sessionOption.value;
4057 + const now = yield* DateTime.now;
4058 + const emitEvent = emit(input.events, input.command);
4059 + const selectionChanged = !modelSelectionsEqual(targetRun.modelSelection, input.modelSelection);
4060 + const providerInstanceChanged =
4061 + targetRun.providerInstanceId !== input.modelSelection.instanceId;
4062 + const selectionTransition =
4063 + selectionChanged && !providerInstanceChanged
4064 + ? yield* providerAdapters.get(targetRun.providerInstanceId).pipe(
4065 + Effect.flatMap((adapter) =>
4066 + adapter.planSelectionTransition({
4067 + current: targetRun.modelSelection,
4068 + target: input.modelSelection,
4069 + sessionCapabilities: session.providerSession.capabilities,
4070 + }),
4071 + ),
4072 + Effect.mapError(
4073 + (cause) =>
4074 + new OrchestratorProviderAdapterError({
4075 + commandId: input.command.commandId,
4076 + providerInstanceId: targetRun.providerInstanceId,
4077 + cause,
4078 }),
4063 - ),
4064 - Effect.mapError(
4065 - (cause) =>
4066 - new OrchestratorProviderAdapterError({
4067 - commandId: input.command.commandId,
4068 - providerInstanceId: targetRun.providerInstanceId,
4069 - cause,
4070 - }),
4071 - ),
4072 - )
4073 - : null;
4074 - if (selectionTransition?.type === "reject") {
4075 - return yield* new OrchestratorDispatchError({
4076 - commandId: input.command.commandId,
4077 - commandType: input.command.type,
4078 - cause: selectionTransition.reason,
4079 - });
4080 - }
4081 - const appendSteeringMessage = (messageInput: {
4079 + ),
4080 + )
4081 + : null;
4082 + if (selectionTransition?.type === "reject") {
4083 + return yield* new OrchestratorDispatchError({
4084 + commandId: input.command.commandId,
4085 + commandType: input.command.type,
4086 + cause: selectionTransition.reason,
4087 + });
4088 + }
4089 + const appendSteeringMessage = Effect.fn("Orchestrator.appendSteeringMessage")(
4090 + function* (messageInput: {
4091 readonly runId: OrchestrationV2Run["id"];
4092 readonly nodeId: OrchestrationV2ExecutionNode["id"];
4093 readonly providerTurnId: typeof providerTurn.id | null;
4094 readonly providerThreadId: OrchestrationV2ProviderThread["id"];
4095 readonly providerInstanceId: ProviderInstanceId;
4087 - }) =>
4088 - Effect.gen(function* () {
4089 - const message: OrchestrationV2ConversationMessage = {
4090 - createdBy: input.createdBy,
4091 - creationSource: input.creationSource,
4092 - ...(input.delegatedCompletion === undefined
4093 - ? {}
4094 - : { delegatedCompletion: input.delegatedCompletion }),
4095 - ...(input.scheduledTaskId === undefined
4096 - ? {}
4097 - : { scheduledTaskId: input.scheduledTaskId }),
4098 - ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
4099 - id: input.messageId,
4100 - threadId: input.command.threadId,
4101 - runId: messageInput.runId,
4102 - nodeId: messageInput.nodeId,
4103 - role: "user",
4104 - text: input.text,
4105 - attachments: input.attachments,
4106 - ...(input.context ? { context: input.context } : {}),
4107 - streaming: false,
4108 - createdAt: now,
4109 - updatedAt: now,
4110 - };
4111 - const turnItem: OrchestrationV2TurnItem = {
4112 - createdBy: input.createdBy,
4113 - creationSource: input.creationSource,
4114 - ...(input.scheduledTaskId === undefined
4115 - ? {}
4116 - : { scheduledTaskId: input.scheduledTaskId }),
4117 - ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
4118 - id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
4119 - threadId: input.command.threadId,
4120 - runId: messageInput.runId,
4121 - nodeId: messageInput.nodeId,
4122 - providerThreadId: messageInput.providerThreadId,
4123 - providerTurnId: messageInput.providerTurnId,
4124 - nativeItemRef: null,
4125 - parentItemId: null,
4126 - ordinal: yield* nextTurnItemOrdinal(input.projection),
4127 - status: "completed",
4128 - title: null,
4129 - startedAt: now,
4130 - completedAt: now,
4131 - updatedAt: now,
4132 - type: "user_message",
4133 - messageId: input.messageId,
4134 - inputIntent:
4135 - input.command.type === "queued-message.promote-to-steer"
4136 - ? "promoted_queued_to_steer"
4137 - : "steer",
4138 - text: input.text,
4139 - attachments: input.attachments,
4140 - ...(input.context ? { context: input.context } : {}),
4141 - };
4142 - yield* emitEvent({
4143 - type: "message.updated",
4144 - threadId: input.command.threadId,
4145 - runId: messageInput.runId,
4146 - nodeId: messageInput.nodeId,
4147 - providerInstanceId: messageInput.providerInstanceId,
4148 - occurredAt: now,
4149 - payload: message,
4150 - });
4151 - yield* emitEvent({
4152 - type: "turn-item.updated",
4153 - threadId: input.command.threadId,
4154 - runId: messageInput.runId,
4155 - nodeId: messageInput.nodeId,
4156 - providerInstanceId: messageInput.providerInstanceId,
4157 - occurredAt: now,
4158 - payload: notificationTurnItem(turnItem, message, input.projection.subagents),
4159 - });
4160 - });
4161 -
4162 - // A selection the provider applies on its next turn joins the running
4163 - // turn as a steer and waits for the next turn. Restarting the turn for it
4164 - // would end the turn's native subagents, which a steer must never do.
4165 - const selectionMustApplyNow =
4166 - selectionChanged &&
4167 - (providerInstanceChanged || selectionTransition?.type !== "apply_on_next_turn");
4168 - const steeringPolicy = yield* enforceCommandPolicy(input.command)(
4169 - commandPolicy.decideSteeringExecution({
4170 - commandId: input.command.commandId,
4171 - threadId: input.command.threadId,
4172 - providerInstanceId: targetRun.providerInstanceId,
4173 - capabilities: session.providerSession.capabilities,
4174 - forceRestart: input.forceRestart || selectionMustApplyNow,
4175 - }),
4176 - );
4177 -
4178 - if (steeringPolicy === "active_steering") {
4179 - const instanceChanged =
4180 - input.projection.thread.providerInstanceId !== input.modelSelection.instanceId;
4181 - if (
4182 - input.delegatedCompletion === undefined &&
4183 - (instanceChanged ||
4184 - !modelSelectionsEqual(input.projection.thread.modelSelection, input.modelSelection))
4185 - ) {
4186 - yield* emitEvent({
4187 - type: instanceChanged ? "thread.provider-switched" : "thread.model-selection-updated",
4188 - threadId: input.command.threadId,
4189 - providerInstanceId: input.modelSelection.instanceId,
4190 - occurredAt: now,
4191 - payload: {
4192 - ...input.projection.thread,
4193 - providerInstanceId: input.modelSelection.instanceId,
4194 - modelSelection: input.modelSelection,
4195 - updatedAt: now,
4196 - },
4197 - });
4198 - }
4199 - yield* appendSteeringMessage({
4200 - runId: targetRun.id,
4201 - nodeId: rootNodeId,
4202 - providerTurnId: providerTurn.id,
4203 - providerThreadId: providerThread.id,
4204 - providerInstanceId: targetRun.providerInstanceId,
4205 - });
4206 - yield* Ref.update(input.effects, (existing) => [
4207 - ...existing,
4208 - {
4209 - id: `effect:${input.command.commandId}:provider-turn.steer:${providerTurn.id}`,
4210 - commandId: input.command.commandId,
4211 - threadId: input.command.threadId,
4212 - request: {
4213 - type: "provider-turn.steer",
4214 - providerSessionId,
4215 - providerThreadId: providerThread.id,
4216 - providerTurnId: providerTurn.id,
4217 - messageId: input.messageId,
4218 - },
4219 - } satisfies PendingOrchestrationEffectV2,
4220 - ]);
4221 - return;
4222 - }
4223 -
4224 - const currentAttempt = input.projection.attempts.find(
4225 - (candidate) => candidate.id === targetRun.activeAttemptId,
4226 - );
4227 - const currentRootNode = input.projection.nodes.find(
4228 - (candidate) => candidate.id === rootNodeId,
4229 - );
4230 - const attemptOrdinal =
4231 - Math.max(
4232 - 0,
4233 - ...input.projection.attempts
4234 - .filter((candidate) => candidate.runId === targetRun.id)
4235 - .map((candidate) => candidate.attemptOrdinal),
4236 - ) + 1;
4237 - const nextAttemptId = idAllocator.derive.runAttempt({
4238 - runId: targetRun.id,
4239 - attemptOrdinal,
4240 - });
4241 - const nextRootNodeId = idAllocator.derive.rootNodeAttempt({
4242 - runId: targetRun.id,
4243 - attemptOrdinal,
4244 - });
4245 - let restartProviderThread = providerThread;
4246 - let restartSessionTransition:
4247 - | {
4248 - readonly type: "replace";
4249 - readonly replacementProviderSessionId: ProviderSessionId;
4250 - }
4251 - | { readonly type: "detach" }
4252 - | null = null;
4253 - let restartHandoff: OrchestrationV2ContextHandoff | null = null;
4254 - let restartTransfer: OrchestrationV2ContextTransfer | null = null;
4255 - const canResumeAcrossInstances =
4256 - providerInstanceChanged &&
4257 - providerThread.nativeThreadRef !== null &&
4258 - (yield* providerSwitchService
4259 - .plan({
4260 - projection: {
4261 - ...input.projection,
4262 - thread: { ...input.projection.thread, modelSelection: targetRun.modelSelection },
4263 - },
4264 - targetModelSelection: input.modelSelection,
4265 - })
4266 - .pipe(mapDispatchError(input.command))).transition.type === "restart_and_resume";
4267 - const requiresProviderThreadHandoff =
4268 - (providerInstanceChanged && !canResumeAcrossInstances) ||
4269 - selectionTransition?.type === "create_with_handoff";
4270 - const requiresProviderSessionRestart =
4271 - canResumeAcrossInstances || selectionTransition?.type === "restart_session";
4272 - if (requiresProviderThreadHandoff) {
4273 - const targetAdapter = yield* providerAdapters.get(input.modelSelection.instanceId).pipe(
4274 - Effect.mapError(
4275 - (cause) =>
4276 - new OrchestratorProviderAdapterError({
4277 - commandId: input.command.commandId,
4278 - providerInstanceId: input.modelSelection.instanceId,
4279 - cause,
4280 - }),
4281 - ),
4282 - );
4283 - const targetCapabilities = yield* targetAdapter.getCapabilities().pipe(
4284 - Effect.mapError(
4285 - (cause) =>
4286 - new OrchestratorProviderAdapterError({
4287 - commandId: input.command.commandId,
4288 - providerInstanceId: input.modelSelection.instanceId,
4289 - cause,
4290 - }),
4291 - ),
4292 - );
4293 - yield* enforceCommandPolicy(input.command)(
4294 - commandPolicy.ensureContextHandoff({
4295 - commandId: input.command.commandId,
4296 - threadId: input.command.threadId,
4297 - providerInstanceId: input.modelSelection.instanceId,
4298 - capabilities: targetCapabilities,
4299 - strategy: "full_thread_summary",
4300 - }),
4301 - );
4302 - const existingTargetProviderThread = rootProviderThreadsForProvider(
4303 - input.projection,
4304 - input.modelSelection.instanceId,
4305 - ).find((candidate) => candidate.id !== providerThread.id);
4306 - const targetProviderSessionId =
4307 - existingTargetProviderThread?.providerSessionId ??
4308 - (yield* mapDispatchError(input.command)(
4309 - providerSessionIdFor({
4310 - adapter: targetAdapter,
4311 - providerInstanceId: input.modelSelection.instanceId,
4312 - threadId: input.command.threadId,
4313 - }),
4314 - ));
4315 - const targetProviderThreadBase: OrchestrationV2ProviderThread =
4316 - existingTargetProviderThread === undefined
4317 - ? {
4318 - id: idAllocator.derive.providerThread({
4319 - driver: targetAdapter.driver,
4320 - nativeThreadId: `pending:${targetRun.id}:attempt:${attemptOrdinal}`,
4321 - }),
4322 - driver: targetAdapter.driver,
4323 - providerInstanceId: input.modelSelection.instanceId,
4324 - providerSessionId: targetProviderSessionId,
4325 - appThreadId: input.command.threadId,
4326 - ownerNodeId: null,
4327 - nativeThreadRef: null,
4328 - nativeConversationHeadRef: null,
4329 - status: "not_loaded",
4330 - firstRunOrdinal: targetRun.ordinal,
4331 - lastRunOrdinal: targetRun.ordinal,
4332 - handoffIds: [],
4333 - forkedFrom: null,
4334 - createdAt: now,
4335 - updatedAt: now,
4336 - }
4337 - : {
4338 - ...existingTargetProviderThread,
4339 - providerSessionId: targetProviderSessionId,
4340 - lastRunOrdinal: targetRun.ordinal,
4341 - updatedAt: now,
4342 - };
4343 - const transferId = yield* mapDispatchError(input.command)(
4344 - idAllocator.allocate.contextTransfer({
4345 - sourceThreadId: input.command.threadId,
4346 - targetThreadId: input.command.threadId,
4347 - type: "provider_handoff",
4348 - }),
4349 - );
4350 - restartHandoff = yield* contextHandoffService
4351 - .prepareProviderHandoff({
4352 - threadId: input.command.threadId,
4353 - targetRunId: targetRun.id,
4354 - transferId,
4355 - fromProviderThreadIds: [providerThread.id],
4356 - toProviderThreadId: targetProviderThreadBase.id,
4357 - fromProviderInstanceId: targetRun.providerInstanceId,
4358 - toProviderInstanceId: input.modelSelection.instanceId,
4359 - coveredRunOrdinals: { from: 1, to: targetRun.ordinal },
4360 - strategy: "full_thread_summary",
4361 - items: yield* readHandoffItems(input.command.threadId),
4362 - runs: input.projection.runs,
4363 - createdAt: now,
4364 - })
4365 - .pipe(mapDispatchError(input.command));
4366 - restartProviderThread = {
4367 - ...targetProviderThreadBase,
4368 - handoffIds: Array.from(
4369 - new Set([...targetProviderThreadBase.handoffIds, restartHandoff.id]),
4370 - ),
4371 - };
4372 - restartTransfer = {
4373 - id: transferId,
4374 - type: "provider_handoff",
4375 - sourceThreadId: input.command.threadId,
4376 - targetThreadId: input.command.threadId,
4377 - sourcePoint: contextSourcePointForRun(input.projection, targetRun),
4378 - basePoint: null,
4379 - sourceProviderInstanceId: targetRun.providerInstanceId,
4380 - targetProviderInstanceId: input.modelSelection.instanceId,
4381 - targetRunId: targetRun.id,
4382 - status: "consumed",
4383 - resolution: {
4384 - strategy: "portable_context",
4385 - contextHandoffId: restartHandoff.id,
4386 - },
4096 + }) {
4097 + const message: OrchestrationV2ConversationMessage = {
4098 createdBy: input.createdBy,
4388 - error: null,
4099 + creationSource: input.creationSource,
4100 + ...(input.delegatedCompletion === undefined
4101 + ? {}
4102 + : { delegatedCompletion: input.delegatedCompletion }),
4103 + ...(input.scheduledTaskId === undefined
4104 + ? {}
4105 + : { scheduledTaskId: input.scheduledTaskId }),
4106 + ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
4107 + id: input.messageId,
4108 + threadId: input.command.threadId,
4109 + runId: messageInput.runId,
4110 + nodeId: messageInput.nodeId,
4111 + role: "user",
4112 + text: input.text,
4113 + attachments: input.attachments,
4114 + ...(input.context ? { context: input.context } : {}),
4115 + streaming: false,
4116 createdAt: now,
4117 updatedAt: now,
4391 - consumedAt: now,
4118 };
4393 - restartSessionTransition = { type: "detach" };
4394 - } else if (requiresProviderSessionRestart) {
4395 - const nextProviderSessionId = yield* mapDispatchError(input.command)(
4396 - idAllocator.allocate.providerSession({
4397 - providerInstanceId: input.modelSelection.instanceId,
4398 - threadId: input.command.threadId,
4399 - }),
4400 - );
4401 - restartProviderThread = {
4402 - ...providerThread,
4403 - providerInstanceId: input.modelSelection.instanceId,
4404 - providerSessionId: nextProviderSessionId,
4405 - status: "not_loaded",
4119 + const turnItem: OrchestrationV2TurnItem = {
4120 + createdBy: input.createdBy,
4121 + creationSource: input.creationSource,
4122 + ...(input.scheduledTaskId === undefined
4123 + ? {}
4124 + : { scheduledTaskId: input.scheduledTaskId }),
4125 + ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
4126 + id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
4127 + threadId: input.command.threadId,
4128 + runId: messageInput.runId,
4129 + nodeId: messageInput.nodeId,
4130 + providerThreadId: messageInput.providerThreadId,
4131 + providerTurnId: messageInput.providerTurnId,
4132 + nativeItemRef: null,
4133 + parentItemId: null,
4134 + ordinal: yield* nextTurnItemOrdinal(input.projection),
4135 + status: "completed",
4136 + title: null,
4137 + startedAt: now,
4138 + completedAt: now,
4139 updatedAt: now,
4140 + type: "user_message",
4141 + messageId: input.messageId,
4142 + inputIntent:
4143 + input.command.type === "queued-message.promote-to-steer"
4144 + ? "promoted_queued_to_steer"
4145 + : "steer",
4146 + text: input.text,
4147 + attachments: input.attachments,
4148 + ...(input.context ? { context: input.context } : {}),
4149 };
4408 - restartSessionTransition = {
4409 - type: "replace",
4410 - replacementProviderSessionId: nextProviderSessionId,
4411 - };
4412 - }
4413 - const resolvedRuntimePolicy = yield* runtimePolicy
4414 - .resolve({ thread: input.projection.thread, modelSelection: input.modelSelection })
4415 - .pipe(
4416 - Effect.mapError(
4417 - (cause) =>
4418 - new OrchestratorDispatchError({
4419 - commandId: input.command.commandId,
4420 - commandType: input.command.type,
4421 - cause,
4422 - }),
4423 - ),
4424 - );
4425 - const checkpointScope = yield* checkpointService
4426 - .prepareRootRunScope({
4427 - threadId: input.command.threadId,
4428 - runId: targetRun.id,
4429 - rootNodeId: nextRootNodeId,
4430 - providerThreadId: restartProviderThread.id,
4431 - cwd:
4432 - resolvedRuntimePolicy.cwd ??
4433 - input.projection.thread.worktreePath ??
4434 - session.providerSession.cwd,
4435 - createdAt: now,
4436 - })
4437 - .pipe(
4438 - Effect.mapError(
4439 - (cause) =>
4440 - new OrchestratorDispatchError({
4441 - commandId: input.command.commandId,
4442 - commandType: input.command.type,
4443 - cause,
4444 - }),
4445 - ),
4446 - );
4447 - const ensuredCheckpointScope = yield* checkpointService.ensureScope(checkpointScope).pipe(
4448 - Effect.mapError(
4449 - (cause) =>
4450 - new OrchestratorDispatchError({
4451 - commandId: input.command.commandId,
4452 - commandType: input.command.type,
4453 - cause,
4454 - }),
4455 - ),
4456 - );
4457 - const restartedRun: OrchestrationV2Run = {
4458 - ...targetRun,
4459 - providerInstanceId: input.modelSelection.instanceId,
4460 - modelSelection: input.modelSelection,
4461 - providerThreadId: restartProviderThread.id,
4462 - rootNodeId: nextRootNodeId,
4463 - activeAttemptId: nextAttemptId,
4464 - userMessageId: input.messageId,
4465 - status: "starting",
4466 - contextHandoffId: restartHandoff?.id ?? targetRun.contextHandoffId,
4467 - };
4468 - const nextAttempt: OrchestrationV2RunAttempt = {
4469 - id: nextAttemptId,
4470 - runId: targetRun.id,
4471 - attemptOrdinal,
4472 - rootNodeId: nextRootNodeId,
4473 - providerInstanceId: input.modelSelection.instanceId,
4474 - providerThreadId: restartProviderThread.id,
4475 - providerTurnId: null,
4476 - reason: "steering_restart",
4477 - status: "pending",
4478 - startedAt: null,
4479 - completedAt: null,
4480 - };
4481 - const nextRootNode: OrchestrationV2ExecutionNode = {
4482 - id: nextRootNodeId,
4483 - threadId: input.command.threadId,
4484 - runId: targetRun.id,
4485 - parentNodeId: null,
4486 - rootNodeId: nextRootNodeId,
4487 - kind: "root_turn",
4488 - status: "pending",
4489 - countsForRun: true,
4490 - providerThreadId: restartProviderThread.id,
4491 - providerTurnId: null,
4492 - nativeItemRef: null,
4493 - runtimeRequestId: null,
4494 - checkpointScopeId: ensuredCheckpointScope.id,
4495 - startedAt: null,
4496 - completedAt: null,
4497 - };
4498 - if (currentAttempt !== undefined) {
4150 yield* emitEvent({
4500 - type: "run-attempt.updated",
4151 + type: "message.updated",
4152 threadId: input.command.threadId,
4502 - runId: targetRun.id,
4503 - nodeId: rootNodeId,
4504 - providerInstanceId: targetRun.providerInstanceId,
4153 + runId: messageInput.runId,
4154 + nodeId: messageInput.nodeId,
4155 + providerInstanceId: messageInput.providerInstanceId,
4156 occurredAt: now,
4506 - payload: { ...currentAttempt, status: "superseded", completedAt: now },
4157 + payload: message,
4158 });
4508 - }
4509 - if (currentRootNode !== undefined) {
4159 yield* emitEvent({
4511 - type: "node.updated",
4160 + type: "turn-item.updated",
4161 threadId: input.command.threadId,
4513 - runId: targetRun.id,
4514 - nodeId: rootNodeId,
4515 - providerInstanceId: targetRun.providerInstanceId,
4162 + runId: messageInput.runId,
4163 + nodeId: messageInput.nodeId,
4164 + providerInstanceId: messageInput.providerInstanceId,
4165 occurredAt: now,
4517 - payload: { ...currentRootNode, status: "interrupted", completedAt: now },
4166 + payload: notificationTurnItem(turnItem, message, input.projection.subagents),
4167 });
4519 - }
4520 - if (selectionChanged) {
4168 + },
4169 + );
4170 +
4171 + // A selection the provider applies on its next turn joins the running
4172 + // turn as a steer and waits for the next turn. Restarting the turn for it
4173 + // would end the turn's native subagents, which a steer must never do.
4174 + const selectionMustApplyNow =
4175 + selectionChanged &&
4176 + (providerInstanceChanged || selectionTransition?.type !== "apply_on_next_turn");
4177 + const steeringPolicy = yield* enforceCommandPolicy(input.command)(
4178 + commandPolicy.decideSteeringExecution({
4179 + commandId: input.command.commandId,
4180 + threadId: input.command.threadId,
4181 + providerInstanceId: targetRun.providerInstanceId,
4182 + capabilities: session.providerSession.capabilities,
4183 + forceRestart: input.forceRestart || selectionMustApplyNow,
4184 + }),
4185 + );
4186 +
4187 + if (steeringPolicy === "active_steering") {
4188 + const instanceChanged =
4189 + input.projection.thread.providerInstanceId !== input.modelSelection.instanceId;
4190 + if (
4191 + input.delegatedCompletion === undefined &&
4192 + (instanceChanged ||
4193 + !modelSelectionsEqual(input.projection.thread.modelSelection, input.modelSelection))
4194 + ) {
4195 yield* emitEvent({
4522 - type: providerInstanceChanged
4523 - ? "thread.provider-switched"
4524 - : "thread.model-selection-updated",
4196 + type: instanceChanged ? "thread.provider-switched" : "thread.model-selection-updated",
4197 threadId: input.command.threadId,
4198 providerInstanceId: input.modelSelection.instanceId,
4199 occurredAt: now,
@@ -4533,823 +4205,1008 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4205 },
4206 });
4207 }
4536 - if (requiresProviderThreadHandoff || requiresProviderSessionRestart) {
4537 - yield* emitEvent({
4538 - type: "provider-thread.updated",
4539 - threadId: input.command.threadId,
4540 - driver: restartProviderThread.driver,
4541 - providerInstanceId: input.modelSelection.instanceId,
4542 - occurredAt: now,
4543 - payload: restartProviderThread,
4544 - });
4545 - }
4546 - if (restartHandoff !== null) {
4547 - yield* emitEvent({
4548 - type: "context-handoff.updated",
4549 - threadId: input.command.threadId,
4550 - runId: targetRun.id,
4551 - providerInstanceId: input.modelSelection.instanceId,
4552 - occurredAt: now,
4553 - payload: restartHandoff,
4554 - });
4555 - }
4556 - if (restartTransfer !== null) {
4557 - yield* emitEvent({
4558 - type: "context-transfer.created",
4559 - threadId: input.command.threadId,
4560 - runId: targetRun.id,
4561 - providerInstanceId: input.modelSelection.instanceId,
4562 - occurredAt: now,
4563 - payload: restartTransfer,
4564 - });
4565 - }
4566 - yield* emitEvent({
4567 - type: "run.updated",
4568 - threadId: input.command.threadId,
4569 - runId: targetRun.id,
4570 - nodeId: nextRootNodeId,
4571 - providerInstanceId: input.modelSelection.instanceId,
4572 - occurredAt: now,
4573 - payload: restartedRun,
4574 - });
4575 - yield* emitEvent({
4576 - type: "run-attempt.created",
4577 - threadId: input.command.threadId,
4578 - runId: targetRun.id,
4579 - nodeId: nextRootNodeId,
4580 - providerInstanceId: input.modelSelection.instanceId,
4581 - occurredAt: now,
4582 - payload: nextAttempt,
4583 - });
4584 - yield* emitEvent({
4585 - type: "node.updated",
4586 - threadId: input.command.threadId,
4587 - runId: targetRun.id,
4588 - nodeId: nextRootNodeId,
4589 - providerInstanceId: input.modelSelection.instanceId,
4590 - occurredAt: now,
4591 - payload: nextRootNode,
4592 - });
4593 - yield* emitEvent({
4594 - type: "checkpoint-scope.created",
4595 - threadId: input.command.threadId,
4596 - runId: targetRun.id,
4597 - nodeId: nextRootNodeId,
4598 - providerInstanceId: input.modelSelection.instanceId,
4599 - occurredAt: now,
4600 - payload: ensuredCheckpointScope,
4601 - });
4208 yield* appendSteeringMessage({
4209 runId: targetRun.id,
4604 - nodeId: nextRootNodeId,
4605 - providerTurnId: null,
4606 - providerThreadId: restartProviderThread.id,
4607 - providerInstanceId: input.modelSelection.instanceId,
4608 - });
4609 - const interruptedAttemptId = targetRun.activeAttemptId;
4610 - if (interruptedAttemptId === null) {
4611 - return yield* new OrchestratorDispatchError({
4612 - commandId: input.command.commandId,
4613 - commandType: input.command.type,
4614 - cause: `Active run ${targetRun.id} has no attempt to interrupt.`,
4615 - });
4616 - }
4210 + nodeId: rootNodeId,
4211 + providerTurnId: providerTurn.id,
4212 + providerThreadId: providerThread.id,
4213 + providerInstanceId: targetRun.providerInstanceId,
4214 + });
4215 yield* Ref.update(input.effects, (existing) => [
4216 ...existing,
4217 {
4620 - id: `effect:${input.command.commandId}:provider-turn.restart:${providerTurn.id}`,
4218 + id: `effect:${input.command.commandId}:provider-turn.steer:${providerTurn.id}`,
4219 commandId: input.command.commandId,
4220 threadId: input.command.threadId,
4221 request: {
4624 - type: "provider-turn.restart",
4222 + type: "provider-turn.steer",
4223 providerSessionId,
4224 providerThreadId: providerThread.id,
4225 providerTurnId: providerTurn.id,
4628 - interruptedAttemptId,
4629 - runId: targetRun.id,
4630 - ...(restartSessionTransition === null
4631 - ? {}
4632 - : { sessionTransition: restartSessionTransition }),
4226 + messageId: input.messageId,
4227 },
4228 } satisfies PendingOrchestrationEffectV2,
4229 ]);
4230 + return;
4231 + }
4232 +
4233 + const currentAttempt = input.projection.attempts.find(
4234 + (candidate) => candidate.id === targetRun.activeAttemptId,
4235 + );
4236 + const currentRootNode = input.projection.nodes.find((candidate) => candidate.id === rootNodeId);
4237 + const attemptOrdinal =
4238 + Math.max(
4239 + 0,
4240 + ...input.projection.attempts
4241 + .filter((candidate) => candidate.runId === targetRun.id)
4242 + .map((candidate) => candidate.attemptOrdinal),
4243 + ) + 1;
4244 + const nextAttemptId = idAllocator.derive.runAttempt({
4245 + runId: targetRun.id,
4246 + attemptOrdinal,
4247 + });
4248 + const nextRootNodeId = idAllocator.derive.rootNodeAttempt({
4249 + runId: targetRun.id,
4250 + attemptOrdinal,
4251 + });
4252 + let restartProviderThread = providerThread;
4253 + let restartSessionTransition:
4254 + | {
4255 + readonly type: "replace";
4256 + readonly replacementProviderSessionId: ProviderSessionId;
4257 + }
4258 + | { readonly type: "detach" }
4259 + | null = null;
4260 + let restartHandoff: OrchestrationV2ContextHandoff | null = null;
4261 + let restartTransfer: OrchestrationV2ContextTransfer | null = null;
4262 + const canResumeAcrossInstances =
4263 + providerInstanceChanged &&
4264 + providerThread.nativeThreadRef !== null &&
4265 + (yield* providerSwitchService
4266 + .plan({
4267 + projection: {
4268 + ...input.projection,
4269 + thread: { ...input.projection.thread, modelSelection: targetRun.modelSelection },
4270 + },
4271 + targetModelSelection: input.modelSelection,
4272 + })
4273 + .pipe(mapDispatchError(input.command))).transition.type === "restart_and_resume";
4274 + const requiresProviderThreadHandoff =
4275 + (providerInstanceChanged && !canResumeAcrossInstances) ||
4276 + selectionTransition?.type === "create_with_handoff";
4277 + const requiresProviderSessionRestart =
4278 + canResumeAcrossInstances || selectionTransition?.type === "restart_session";
4279 + if (requiresProviderThreadHandoff) {
4280 + const targetAdapter = yield* providerAdapters.get(input.modelSelection.instanceId).pipe(
4281 + Effect.mapError(
4282 + (cause) =>
4283 + new OrchestratorProviderAdapterError({
4284 + commandId: input.command.commandId,
4285 + providerInstanceId: input.modelSelection.instanceId,
4286 + cause,
4287 + }),
4288 + ),
4289 + );
4290 + const targetCapabilities = yield* targetAdapter.getCapabilities().pipe(
4291 + Effect.mapError(
4292 + (cause) =>
4293 + new OrchestratorProviderAdapterError({
4294 + commandId: input.command.commandId,
4295 + providerInstanceId: input.modelSelection.instanceId,
4296 + cause,
4297 + }),
4298 + ),
4299 + );
4300 + yield* enforceCommandPolicy(input.command)(
4301 + commandPolicy.ensureContextHandoff({
4302 + commandId: input.command.commandId,
4303 + threadId: input.command.threadId,
4304 + providerInstanceId: input.modelSelection.instanceId,
4305 + capabilities: targetCapabilities,
4306 + strategy: "full_thread_summary",
4307 + }),
4308 + );
4309 + const existingTargetProviderThread = rootProviderThreadsForProvider(
4310 + input.projection,
4311 + input.modelSelection.instanceId,
4312 + ).find((candidate) => candidate.id !== providerThread.id);
4313 + const targetProviderSessionId =
4314 + existingTargetProviderThread?.providerSessionId ??
4315 + (yield* mapDispatchError(input.command)(
4316 + providerSessionIdFor({
4317 + adapter: targetAdapter,
4318 + providerInstanceId: input.modelSelection.instanceId,
4319 + threadId: input.command.threadId,
4320 + }),
4321 + ));
4322 + const targetProviderThreadBase: OrchestrationV2ProviderThread =
4323 + existingTargetProviderThread === undefined
4324 + ? {
4325 + id: idAllocator.derive.providerThread({
4326 + driver: targetAdapter.driver,
4327 + nativeThreadId: `pending:${targetRun.id}:attempt:${attemptOrdinal}`,
4328 + }),
4329 + driver: targetAdapter.driver,
4330 + providerInstanceId: input.modelSelection.instanceId,
4331 + providerSessionId: targetProviderSessionId,
4332 + appThreadId: input.command.threadId,
4333 + ownerNodeId: null,
4334 + nativeThreadRef: null,
4335 + nativeConversationHeadRef: null,
4336 + status: "not_loaded",
4337 + firstRunOrdinal: targetRun.ordinal,
4338 + lastRunOrdinal: targetRun.ordinal,
4339 + handoffIds: [],
4340 + forkedFrom: null,
4341 + createdAt: now,
4342 + updatedAt: now,
4343 + }
4344 + : {
4345 + ...existingTargetProviderThread,
4346 + providerSessionId: targetProviderSessionId,
4347 + lastRunOrdinal: targetRun.ordinal,
4348 + updatedAt: now,
4349 + };
4350 + const transferId = yield* mapDispatchError(input.command)(
4351 + idAllocator.allocate.contextTransfer({
4352 + sourceThreadId: input.command.threadId,
4353 + targetThreadId: input.command.threadId,
4354 + type: "provider_handoff",
4355 + }),
4356 + );
4357 + restartHandoff = yield* contextHandoffService
4358 + .prepareProviderHandoff({
4359 + threadId: input.command.threadId,
4360 + targetRunId: targetRun.id,
4361 + transferId,
4362 + fromProviderThreadIds: [providerThread.id],
4363 + toProviderThreadId: targetProviderThreadBase.id,
4364 + fromProviderInstanceId: targetRun.providerInstanceId,
4365 + toProviderInstanceId: input.modelSelection.instanceId,
4366 + coveredRunOrdinals: { from: 1, to: targetRun.ordinal },
4367 + strategy: "full_thread_summary",
4368 + items: yield* readHandoffItems(input.command.threadId),
4369 + runs: input.projection.runs,
4370 + createdAt: now,
4371 + })
4372 + .pipe(mapDispatchError(input.command));
4373 + restartProviderThread = {
4374 + ...targetProviderThreadBase,
4375 + handoffIds: Array.from(
4376 + new Set([...targetProviderThreadBase.handoffIds, restartHandoff.id]),
4377 + ),
4378 + };
4379 + restartTransfer = {
4380 + id: transferId,
4381 + type: "provider_handoff",
4382 + sourceThreadId: input.command.threadId,
4383 + targetThreadId: input.command.threadId,
4384 + sourcePoint: contextSourcePointForRun(input.projection, targetRun),
4385 + basePoint: null,
4386 + sourceProviderInstanceId: targetRun.providerInstanceId,
4387 + targetProviderInstanceId: input.modelSelection.instanceId,
4388 + targetRunId: targetRun.id,
4389 + status: "consumed",
4390 + resolution: {
4391 + strategy: "portable_context",
4392 + contextHandoffId: restartHandoff.id,
4393 + },
4394 + createdBy: input.createdBy,
4395 + error: null,
4396 + createdAt: now,
4397 + updatedAt: now,
4398 + consumedAt: now,
4399 + };
4400 + restartSessionTransition = { type: "detach" };
4401 + } else if (requiresProviderSessionRestart) {
4402 + const nextProviderSessionId = yield* mapDispatchError(input.command)(
4403 + idAllocator.allocate.providerSession({
4404 + providerInstanceId: input.modelSelection.instanceId,
4405 + threadId: input.command.threadId,
4406 + }),
4407 + );
4408 + restartProviderThread = {
4409 + ...providerThread,
4410 + providerInstanceId: input.modelSelection.instanceId,
4411 + providerSessionId: nextProviderSessionId,
4412 + status: "not_loaded",
4413 + updatedAt: now,
4414 + };
4415 + restartSessionTransition = {
4416 + type: "replace",
4417 + replacementProviderSessionId: nextProviderSessionId,
4418 + };
4419 + }
4420 + const resolvedRuntimePolicy = yield* runtimePolicy
4421 + .resolve({ thread: input.projection.thread, modelSelection: input.modelSelection })
4422 + .pipe(
4423 + Effect.mapError(
4424 + (cause) =>
4425 + new OrchestratorDispatchError({
4426 + commandId: input.command.commandId,
4427 + commandType: input.command.type,
4428 + cause,
4429 + }),
4430 + ),
4431 + );
4432 + const checkpointScope = yield* checkpointService
4433 + .prepareRootRunScope({
4434 + threadId: input.command.threadId,
4435 + runId: targetRun.id,
4436 + rootNodeId: nextRootNodeId,
4437 + providerThreadId: restartProviderThread.id,
4438 + cwd:
4439 + resolvedRuntimePolicy.cwd ??
4440 + input.projection.thread.worktreePath ??
4441 + session.providerSession.cwd,
4442 + createdAt: now,
4443 + })
4444 + .pipe(
4445 + Effect.mapError(
4446 + (cause) =>
4447 + new OrchestratorDispatchError({
4448 + commandId: input.command.commandId,
4449 + commandType: input.command.type,
4450 + cause,
4451 + }),
4452 + ),
4453 + );
4454 + const ensuredCheckpointScope = yield* checkpointService.ensureScope(checkpointScope).pipe(
4455 + Effect.mapError(
4456 + (cause) =>
4457 + new OrchestratorDispatchError({
4458 + commandId: input.command.commandId,
4459 + commandType: input.command.type,
4460 + cause,
4461 + }),
4462 + ),
4463 + );
4464 + const restartedRun: OrchestrationV2Run = {
4465 + ...targetRun,
4466 + providerInstanceId: input.modelSelection.instanceId,
4467 + modelSelection: input.modelSelection,
4468 + providerThreadId: restartProviderThread.id,
4469 + rootNodeId: nextRootNodeId,
4470 + activeAttemptId: nextAttemptId,
4471 + userMessageId: input.messageId,
4472 + status: "starting",
4473 + contextHandoffId: restartHandoff?.id ?? targetRun.contextHandoffId,
4474 + };
4475 + const nextAttempt: OrchestrationV2RunAttempt = {
4476 + id: nextAttemptId,
4477 + runId: targetRun.id,
4478 + attemptOrdinal,
4479 + rootNodeId: nextRootNodeId,
4480 + providerInstanceId: input.modelSelection.instanceId,
4481 + providerThreadId: restartProviderThread.id,
4482 + providerTurnId: null,
4483 + reason: "steering_restart",
4484 + status: "pending",
4485 + startedAt: null,
4486 + completedAt: null,
4487 + };
4488 + const nextRootNode: OrchestrationV2ExecutionNode = {
4489 + id: nextRootNodeId,
4490 + threadId: input.command.threadId,
4491 + runId: targetRun.id,
4492 + parentNodeId: null,
4493 + rootNodeId: nextRootNodeId,
4494 + kind: "root_turn",
4495 + status: "pending",
4496 + countsForRun: true,
4497 + providerThreadId: restartProviderThread.id,
4498 + providerTurnId: null,
4499 + nativeItemRef: null,
4500 + runtimeRequestId: null,
4501 + checkpointScopeId: ensuredCheckpointScope.id,
4502 + startedAt: null,
4503 + completedAt: null,
4504 + };
4505 + if (currentAttempt !== undefined) {
4506 + yield* emitEvent({
4507 + type: "run-attempt.updated",
4508 + threadId: input.command.threadId,
4509 + runId: targetRun.id,
4510 + nodeId: rootNodeId,
4511 + providerInstanceId: targetRun.providerInstanceId,
4512 + occurredAt: now,
4513 + payload: { ...currentAttempt, status: "superseded", completedAt: now },
4514 + });
4515 + }
4516 + if (currentRootNode !== undefined) {
4517 + yield* emitEvent({
4518 + type: "node.updated",
4519 + threadId: input.command.threadId,
4520 + runId: targetRun.id,
4521 + nodeId: rootNodeId,
4522 + providerInstanceId: targetRun.providerInstanceId,
4523 + occurredAt: now,
4524 + payload: { ...currentRootNode, status: "interrupted", completedAt: now },
4525 + });
4526 + }
4527 + if (selectionChanged) {
4528 + yield* emitEvent({
4529 + type: providerInstanceChanged
4530 + ? "thread.provider-switched"
4531 + : "thread.model-selection-updated",
4532 + threadId: input.command.threadId,
4533 + providerInstanceId: input.modelSelection.instanceId,
4534 + occurredAt: now,
4535 + payload: {
4536 + ...input.projection.thread,
4537 + providerInstanceId: input.modelSelection.instanceId,
4538 + modelSelection: input.modelSelection,
4539 + updatedAt: now,
4540 + },
4541 + });
4542 + }
4543 + if (requiresProviderThreadHandoff || requiresProviderSessionRestart) {
4544 + yield* emitEvent({
4545 + type: "provider-thread.updated",
4546 + threadId: input.command.threadId,
4547 + driver: restartProviderThread.driver,
4548 + providerInstanceId: input.modelSelection.instanceId,
4549 + occurredAt: now,
4550 + payload: restartProviderThread,
4551 + });
4552 + }
4553 + if (restartHandoff !== null) {
4554 + yield* emitEvent({
4555 + type: "context-handoff.updated",
4556 + threadId: input.command.threadId,
4557 + runId: targetRun.id,
4558 + providerInstanceId: input.modelSelection.instanceId,
4559 + occurredAt: now,
4560 + payload: restartHandoff,
4561 + });
4562 + }
4563 + if (restartTransfer !== null) {
4564 + yield* emitEvent({
4565 + type: "context-transfer.created",
4566 + threadId: input.command.threadId,
4567 + runId: targetRun.id,
4568 + providerInstanceId: input.modelSelection.instanceId,
4569 + occurredAt: now,
4570 + payload: restartTransfer,
4571 + });
4572 + }
4573 + yield* emitEvent({
4574 + type: "run.updated",
4575 + threadId: input.command.threadId,
4576 + runId: targetRun.id,
4577 + nodeId: nextRootNodeId,
4578 + providerInstanceId: input.modelSelection.instanceId,
4579 + occurredAt: now,
4580 + payload: restartedRun,
4581 + });
4582 + yield* emitEvent({
4583 + type: "run-attempt.created",
4584 + threadId: input.command.threadId,
4585 + runId: targetRun.id,
4586 + nodeId: nextRootNodeId,
4587 + providerInstanceId: input.modelSelection.instanceId,
4588 + occurredAt: now,
4589 + payload: nextAttempt,
4590 + });
4591 + yield* emitEvent({
4592 + type: "node.updated",
4593 + threadId: input.command.threadId,
4594 + runId: targetRun.id,
4595 + nodeId: nextRootNodeId,
4596 + providerInstanceId: input.modelSelection.instanceId,
4597 + occurredAt: now,
4598 + payload: nextRootNode,
4599 + });
4600 + yield* emitEvent({
4601 + type: "checkpoint-scope.created",
4602 + threadId: input.command.threadId,
4603 + runId: targetRun.id,
4604 + nodeId: nextRootNodeId,
4605 + providerInstanceId: input.modelSelection.instanceId,
4606 + occurredAt: now,
4607 + payload: ensuredCheckpointScope,
4608 + });
4609 + yield* appendSteeringMessage({
4610 + runId: targetRun.id,
4611 + nodeId: nextRootNodeId,
4612 + providerTurnId: null,
4613 + providerThreadId: restartProviderThread.id,
4614 + providerInstanceId: input.modelSelection.instanceId,
4615 });
4616 + const interruptedAttemptId = targetRun.activeAttemptId;
4617 + if (interruptedAttemptId === null) {
4618 + return yield* new OrchestratorDispatchError({
4619 + commandId: input.command.commandId,
4620 + commandType: input.command.type,
4621 + cause: `Active run ${targetRun.id} has no attempt to interrupt.`,
4622 + });
4623 + }
4624 + yield* Ref.update(input.effects, (existing) => [
4625 + ...existing,
4626 + {
4627 + id: `effect:${input.command.commandId}:provider-turn.restart:${providerTurn.id}`,
4628 + commandId: input.command.commandId,
4629 + threadId: input.command.threadId,
4630 + request: {
4631 + type: "provider-turn.restart",
4632 + providerSessionId,
4633 + providerThreadId: providerThread.id,
4634 + providerTurnId: providerTurn.id,
4635 + interruptedAttemptId,
4636 + runId: targetRun.id,
4637 + ...(restartSessionTransition === null
4638 + ? {}
4639 + : { sessionTransition: restartSessionTransition }),
4640 + },
4641 + } satisfies PendingOrchestrationEffectV2,
4642 + ]);
4643 + });
4644
4638 - const dispatchMessage = (
4645 + const dispatchMessage = Effect.fn("Orchestrator.dispatchMessage")(function* (
4646 command: Extract<OrchestrationV2Command, { readonly type: "message.dispatch" }>,
4647 events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
4648 effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
4642 - ) =>
4643 - Effect.gen(function* () {
4644 - let projection = yield* getProjectionWithPendingEvents(command.threadId, events);
4645 - if (command.manualContinuationOfRunId !== undefined) {
4646 - const source = projection.runs.find((run) => run.id === command.manualContinuationOfRunId);
4647 - const limited = latestRootProviderFailure(source ?? null, projection.turnItems);
4648 - if (
4649 - command.dispatchMode.type !== "start_immediately" ||
4650 - source === undefined ||
4651 - (source.status !== "interrupted" &&
4652 - !(source.status === "failed" && limited?.class === "usage_limit")) ||
4653 - latestExecutedRun(projection.runs)?.id !== source.id ||
4654 - projection.thread.archivedAt !== null ||
4655 - projection.thread.deletedAt !== null ||
4656 - projection.runtimeRequests.some((request) => request.status === "pending")
4657 - ) {
4658 - return yield* new OrchestratorDispatchError({
4659 - commandId: command.commandId,
4660 - commandType: command.type,
4661 - cause: "This thread can no longer be resumed from that run.",
4662 - });
4663 - }
4664 - }
4665 - if (command.usageLimitContinuationOfRunId !== undefined) {
4666 - const run = usageLimitBlockedRun(projection.runs, projection.turnItems, null);
4667 - const failure = latestRootProviderFailure(run, projection.turnItems);
4668 - const recovery = projection.thread.limitRecovery;
4669 - const now = yield* DateTime.now;
4670 - if (
4671 - run?.id !== command.usageLimitContinuationOfRunId ||
4672 - failure?.class !== "usage_limit" ||
4673 - threadShellFromProjection(projection).lastErrorClass !== "usage_limit" ||
4674 - !recovery?.autoResume ||
4675 - recovery.requestId !== command.usageLimitRecoveryRequestId ||
4676 - recovery.runId !== run.id ||
4677 - recovery.resetAt !== failure.resetAt ||
4678 - Date.parse(recovery.resetAt) > DateTime.toEpochMillis(now) ||
4679 - projection.thread.archivedAt !== null ||
4680 - projection.thread.deletedAt !== null ||
4681 - projection.thread.settledOverride === "settled" ||
4682 - projection.thread.providerInstanceId !== run.providerInstanceId ||
4683 - projection.runtimeRequests.some((request) => request.status === "pending") ||
4684 - (projection.thread.snoozedUntil != null &&
4685 - DateTime.toEpochMillis(projection.thread.snoozedUntil) > DateTime.toEpochMillis(now))
4686 - ) {
4687 - yield* emit(
4688 - events,
4689 - command,
4690 - )({
4691 - type: "thread.metadata-updated",
4692 - threadId: command.threadId,
4693 - occurredAt: now,
4694 - payload: {
4695 - ...projection.thread,
4696 - ...(recovery?.autoResume &&
4697 - recovery.requestId === command.usageLimitRecoveryRequestId &&
4698 - recovery.runId === command.usageLimitContinuationOfRunId &&
4699 - projection.thread.snoozedUntil != null &&
4700 - DateTime.toEpochMillis(projection.thread.snoozedUntil) > DateTime.toEpochMillis(now)
4701 - ? { limitRecovery: { ...recovery, requestId: command.commandId } }
4702 - : {}),
4703 - },
4704 - });
4705 - return;
4706 - }
4649 + ) {
4650 + let projection = yield* getProjectionWithPendingEvents(command.threadId, events);
4651 + if (command.manualContinuationOfRunId !== undefined) {
4652 + const source = projection.runs.find((run) => run.id === command.manualContinuationOfRunId);
4653 + const limited = latestRootProviderFailure(source ?? null, projection.turnItems);
4654 + if (
4655 + command.dispatchMode.type !== "start_immediately" ||
4656 + source === undefined ||
4657 + (source.status !== "interrupted" &&
4658 + !(source.status === "failed" && limited?.class === "usage_limit")) ||
4659 + latestExecutedRun(projection.runs)?.id !== source.id ||
4660 + projection.thread.archivedAt !== null ||
4661 + projection.thread.deletedAt !== null ||
4662 + projection.runtimeRequests.some((request) => request.status === "pending")
4663 + ) {
4664 + return yield* new OrchestratorDispatchError({
4665 + commandId: command.commandId,
4666 + commandType: command.type,
4667 + cause: "This thread can no longer be resumed from that run.",
4668 + });
4669 }
4708 -
4709 - if (command.restartContinuationOfRunId !== undefined) {
4710 - const source = projection.runs.find((run) => run.id === command.restartContinuationOfRunId);
4711 - if (
4712 - !source ||
4713 - !isRestartContinuationSource(source, projection.providerTurns) ||
4714 - projection.thread.archivedAt !== null ||
4715 - projection.thread.deletedAt !== null ||
4716 - projection.thread.providerInstanceId !== source.providerInstanceId ||
4717 - projection.runs.some(
4718 - (run) =>
4719 - run.id !== source.id &&
4720 - run.status !== "queued" &&
4721 - !cancelledBeforeStart(run) &&
4722 - runRanAfter(run, source),
4723 - ) ||
4724 - (yield* stopReachedRun(command, command.threadId, source.id))
4725 - ) {
4726 - // Preserve the current row so stale automatic deliveries receive an
4727 - // accepted receipt without changing work or repeatedly retrying.
4728 - yield* emit(
4729 - events,
4730 - command,
4731 - )({
4732 - type: "thread.metadata-updated",
4733 - threadId: command.threadId,
4734 - occurredAt: yield* DateTime.now,
4735 - payload: projection.thread,
4736 - });
4737 - return;
4738 - }
4739 - }
4740 -
4741 - if (projection.thread.lastVisitedAt === null && !isNativeMaintenanceCommand(command)) {
4742 - const now = yield* DateTime.now;
4743 - // Null keeps imported history read. The first fresh dispatch establishes
4744 - // a read watermark so its completion can be unread on every client.
4745 - // Offset it so a completion in the same millisecond is still unread.
4746 - const event = yield* emit(
4670 + }
4671 + if (command.usageLimitContinuationOfRunId !== undefined) {
4672 + const run = usageLimitBlockedRun(projection.runs, projection.turnItems, null);
4673 + const failure = latestRootProviderFailure(run, projection.turnItems);
4674 + const recovery = projection.thread.limitRecovery;
4675 + const now = yield* DateTime.now;
4676 + if (
4677 + run?.id !== command.usageLimitContinuationOfRunId ||
4678 + failure?.class !== "usage_limit" ||
4679 + threadShellFromProjection(projection).lastErrorClass !== "usage_limit" ||
4680 + !recovery?.autoResume ||
4681 + recovery.requestId !== command.usageLimitRecoveryRequestId ||
4682 + recovery.runId !== run.id ||
4683 + recovery.resetAt !== failure.resetAt ||
4684 + Date.parse(recovery.resetAt) > DateTime.toEpochMillis(now) ||
4685 + projection.thread.archivedAt !== null ||
4686 + projection.thread.deletedAt !== null ||
4687 + projection.thread.settledOverride === "settled" ||
4688 + projection.thread.providerInstanceId !== run.providerInstanceId ||
4689 + projection.runtimeRequests.some((request) => request.status === "pending") ||
4690 + (projection.thread.snoozedUntil != null &&
4691 + DateTime.toEpochMillis(projection.thread.snoozedUntil) > DateTime.toEpochMillis(now))
4692 + ) {
4693 + yield* emit(
4694 events,
4695 command,
4696 )({
4697 type: "thread.metadata-updated",
4698 threadId: command.threadId,
4752 - providerInstanceId: projection.thread.providerInstanceId,
4699 occurredAt: now,
4700 payload: {
4701 ...projection.thread,
4756 - lastVisitedAt: DateTime.subtract(now, { milliseconds: 1 }),
4702 + ...(recovery?.autoResume &&
4703 + recovery.requestId === command.usageLimitRecoveryRequestId &&
4704 + recovery.runId === command.usageLimitContinuationOfRunId &&
4705 + projection.thread.snoozedUntil != null &&
4706 + DateTime.toEpochMillis(projection.thread.snoozedUntil) > DateTime.toEpochMillis(now)
4707 + ? { limitRecovery: { ...recovery, requestId: command.commandId } }
4708 + : {}),
4709 },
4710 });
4759 - projection = applyToProjection(projection, event);
4711 + return;
4712 }
4713 + }
4714
4762 - const continuedTaskId = projection.runs.find(
4763 - (run) => run.id === command.restartContinuationOfRunId,
4764 - )?.delegatedTaskId;
4765 -
4766 - if (projection.thread.settledOverride !== null) {
4767 - const now = yield* DateTime.now;
4768 - const thread: OrchestrationV2AppThread = {
4769 - ...projection.thread,
4770 - settledOverride: null,
4771 - settledAt: null,
4772 - unsettledAt:
4773 - projection.thread.settledOverride === "active"
4774 - ? (projection.thread.unsettledAt ?? null)
4775 - : now,
4776 - updatedAt: now,
4777 - };
4778 - yield* emit(
4779 - events,
4780 - command,
4781 - )({
4782 - type: "thread.unsettled",
4783 - threadId: command.threadId,
4784 - providerInstanceId: thread.providerInstanceId,
4785 - occurredAt: now,
4786 - payload: thread,
4787 - });
4788 - projection = yield* getProjectionWithPendingEvents(command.threadId, events);
4789 - }
4790 - if (projection.thread.snoozedUntil != null) {
4791 - const now = yield* DateTime.now;
4792 - const thread: OrchestrationV2AppThread = {
4793 - ...projection.thread,
4794 - snoozedUntil: null,
4795 - snoozedAt: null,
4796 - updatedAt: now,
4797 - };
4798 - yield* emit(
4799 - events,
4800 - command,
4801 - )({
4802 - type: "thread.unsnoozed",
4803 - threadId: command.threadId,
4804 - providerInstanceId: thread.providerInstanceId,
4805 - occurredAt: now,
4806 - payload: thread,
4807 - });
4808 - projection = yield* getProjectionWithPendingEvents(command.threadId, events);
4809 - }
4810 - const userMessages = projection.messages.filter((message) => message.role === "user");
4811 - const onlyMaintenanceHistory =
4812 - userMessages.length > 0 && userMessages.every(isNativeMaintenanceCommand);
4715 + if (command.restartContinuationOfRunId !== undefined) {
4716 + const source = projection.runs.find((run) => run.id === command.restartContinuationOfRunId);
4717 if (
4814 - !isNativeMaintenanceCommand(command) &&
4815 - ((command.titleSeed !== undefined &&
4816 - (yield* projectionStore
4817 - .getMessageCount(command.threadId)
4818 - .pipe(mapDispatchError(command))) === 0) ||
4819 - (command.createdBy === "user" && onlyMaintenanceHistory))
4718 + !source ||
4719 + !isRestartContinuationSource(source, projection.providerTurns) ||
4720 + projection.thread.archivedAt !== null ||
4721 + projection.thread.deletedAt !== null ||
4722 + projection.thread.providerInstanceId !== source.providerInstanceId ||
4723 + projection.runs.some(
4724 + (run) =>
4725 + run.id !== source.id &&
4726 + run.status !== "queued" &&
4727 + !cancelledBeforeStart(run) &&
4728 + runRanAfter(run, source),
4729 + ) ||
4730 + (yield* stopReachedRun(command, command.threadId, source.id))
4731 ) {
4821 - const now = yield* DateTime.now;
4822 - const thread: OrchestrationV2AppThread = {
4823 - ...projection.thread,
4824 - title: command.titleSeed ?? projection.thread.title,
4825 - titleRegeneration: { requestId: command.commandId, startedAt: now },
4826 - updatedAt: now,
4827 - };
4732 + // Preserve the current row so stale automatic deliveries receive an
4733 + // accepted receipt without changing work or repeatedly retrying.
4734 yield* emit(
4735 events,
4736 command,
4737 )({
4738 type: "thread.metadata-updated",
4739 threadId: command.threadId,
4834 - providerInstanceId: thread.providerInstanceId,
4835 - occurredAt: now,
4836 - payload: thread,
4740 + occurredAt: yield* DateTime.now,
4741 + payload: projection.thread,
4742 });
4838 - yield* Ref.update(effects, (existing) => [
4839 - ...existing,
4840 - pendingThreadTitleGenerationEffect(command.commandId, command.threadId, {
4841 - type: "initial",
4842 - messageId: command.messageId,
4843 - }),
4844 - ]);
4845 - projection = yield* getProjectionWithPendingEvents(command.threadId, events);
4743 + return;
4744 }
4847 - const modelSelection = command.modelSelection ?? projection.thread.modelSelection;
4848 - let dispatchMode = resolveMessageDispatchIntent(
4849 - projection,
4850 - command.dispatchMode,
4851 - command.deliveryIntent,
4745 + }
4746 +
4747 + if (projection.thread.lastVisitedAt === null && !isNativeMaintenanceCommand(command)) {
4748 + const now = yield* DateTime.now;
4749 + // Null keeps imported history read. The first fresh dispatch establishes
4750 + // a read watermark so its completion can be unread on every client.
4751 + // Offset it so a completion in the same millisecond is still unread.
4752 + const event = yield* emit(
4753 + events,
4754 + command,
4755 + )({
4756 + type: "thread.metadata-updated",
4757 + threadId: command.threadId,
4758 + providerInstanceId: projection.thread.providerInstanceId,
4759 + occurredAt: now,
4760 + payload: {
4761 + ...projection.thread,
4762 + lastVisitedAt: DateTime.subtract(now, { milliseconds: 1 }),
4763 + },
4764 + });
4765 + projection = applyToProjection(projection, event);
4766 + }
4767 +
4768 + const continuedTaskId = projection.runs.find(
4769 + (run) => run.id === command.restartContinuationOfRunId,
4770 + )?.delegatedTaskId;
4771 +
4772 + if (projection.thread.settledOverride !== null) {
4773 + const now = yield* DateTime.now;
4774 + const thread: OrchestrationV2AppThread = {
4775 + ...projection.thread,
4776 + settledOverride: null,
4777 + settledAt: null,
4778 + unsettledAt:
4779 + projection.thread.settledOverride === "active"
4780 + ? (projection.thread.unsettledAt ?? null)
4781 + : now,
4782 + updatedAt: now,
4783 + };
4784 + yield* emit(
4785 + events,
4786 + command,
4787 + )({
4788 + type: "thread.unsettled",
4789 + threadId: command.threadId,
4790 + providerInstanceId: thread.providerInstanceId,
4791 + occurredAt: now,
4792 + payload: thread,
4793 + });
4794 + projection = yield* getProjectionWithPendingEvents(command.threadId, events);
4795 + }
4796 + if (projection.thread.snoozedUntil != null) {
4797 + const now = yield* DateTime.now;
4798 + const thread: OrchestrationV2AppThread = {
4799 + ...projection.thread,
4800 + snoozedUntil: null,
4801 + snoozedAt: null,
4802 + updatedAt: now,
4803 + };
4804 + yield* emit(
4805 + events,
4806 + command,
4807 + )({
4808 + type: "thread.unsnoozed",
4809 + threadId: command.threadId,
4810 + providerInstanceId: thread.providerInstanceId,
4811 + occurredAt: now,
4812 + payload: thread,
4813 + });
4814 + projection = yield* getProjectionWithPendingEvents(command.threadId, events);
4815 + }
4816 + const userMessages = projection.messages.filter((message) => message.role === "user");
4817 + const onlyMaintenanceHistory =
4818 + userMessages.length > 0 && userMessages.every(isNativeMaintenanceCommand);
4819 + if (
4820 + !isNativeMaintenanceCommand(command) &&
4821 + ((command.titleSeed !== undefined &&
4822 + (yield* projectionStore
4823 + .getMessageCount(command.threadId)
4824 + .pipe(mapDispatchError(command))) === 0) ||
4825 + (command.createdBy === "user" && onlyMaintenanceHistory))
4826 + ) {
4827 + const now = yield* DateTime.now;
4828 + const thread: OrchestrationV2AppThread = {
4829 + ...projection.thread,
4830 + title: command.titleSeed ?? projection.thread.title,
4831 + titleRegeneration: { requestId: command.commandId, startedAt: now },
4832 + updatedAt: now,
4833 + };
4834 + yield* emit(
4835 + events,
4836 + command,
4837 + )({
4838 + type: "thread.metadata-updated",
4839 + threadId: command.threadId,
4840 + providerInstanceId: thread.providerInstanceId,
4841 + occurredAt: now,
4842 + payload: thread,
4843 + });
4844 + yield* Ref.update(effects, (existing) => [
4845 + ...existing,
4846 + pendingThreadTitleGenerationEffect(command.commandId, command.threadId, {
4847 + type: "initial",
4848 + messageId: command.messageId,
4849 + }),
4850 + ]);
4851 + projection = yield* getProjectionWithPendingEvents(command.threadId, events);
4852 + }
4853 + const modelSelection = command.modelSelection ?? projection.thread.modelSelection;
4854 + let dispatchMode = resolveMessageDispatchIntent(
4855 + projection,
4856 + command.dispatchMode,
4857 + command.deliveryIntent,
4858 + );
4859 + if (dispatchMode.type === "steer_active") {
4860 + const targetRunId = dispatchMode.targetRunId;
4861 + const target = projection.runs.find((run) => run.id === targetRunId);
4862 + const turn = latestProviderTurnForAttempt(
4863 + projection.providerTurns.filter((candidate) => candidate.nodeId === target?.rootNodeId),
4864 + target?.activeAttemptId,
4865 );
4853 - if (dispatchMode.type === "steer_active") {
4854 - const targetRunId = dispatchMode.targetRunId;
4855 - const target = projection.runs.find((run) => run.id === targetRunId);
4856 - const turn = latestProviderTurnForAttempt(
4857 - projection.providerTurns.filter((candidate) => candidate.nodeId === target?.rootNodeId),
4858 - target?.activeAttemptId,
4859 - );
4860 - // The client may still show a running turn while its completion is being
4861 - // projected. Preserve the submission as a new turn when steering is too late.
4862 - if (
4863 - target !== undefined &&
4864 - (target.status === "completed" ||
4865 - ((target.status === "running" || target.status === "waiting") &&
4866 - turn !== undefined &&
4867 - turn.status === "completed"))
4868 - ) {
4869 - dispatchMode = { type: "start_immediately" };
4870 - }
4871 - }
4872 - // Stop leaves the run reading as running until its provider stops. A plain
4873 - // send in that window queues behind the stopped queue instead of steering
4874 - // text the agent never receives, and like any user send it releases the
4875 - // hold; an explicit steer or restart still fails below.
4866 + // The client may still show a running turn while its completion is being
4867 + // projected. Preserve the submission as a new turn when steering is too late.
4868 if (
4877 - command.deliveryIntent === "auto" &&
4878 - (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") &&
4879 - (yield* stopReachedRun(command, command.threadId, dispatchMode.targetRunId))
4869 + target !== undefined &&
4870 + (target.status === "completed" ||
4871 + ((target.status === "running" || target.status === "waiting") &&
4872 + turn !== undefined &&
4873 + turn.status === "completed"))
4874 ) {
4881 - dispatchMode = { type: "queue_after_active" };
4875 + dispatchMode = { type: "start_immediately" };
4876 }
4877 + }
4878 + // Stop leaves the run reading as running until its provider stops. A plain
4879 + // send in that window queues behind the stopped queue instead of steering
4880 + // text the agent never receives, and like any user send it releases the
4881 + // hold; an explicit steer or restart still fails below.
4882 + if (
4883 + command.deliveryIntent === "auto" &&
4884 + (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") &&
4885 + (yield* stopReachedRun(command, command.threadId, dispatchMode.targetRunId))
4886 + ) {
4887 + dispatchMode = { type: "queue_after_active" };
4888 + }
4889 + if (
4890 + command.notification !== undefined &&
4891 + (command.createdBy !== "agent" ||
4892 + (command.creationSource !== "server" && command.creationSource !== "provider") ||
4893 + (dispatchMode.type !== "queue_after_active" &&
4894 + !(
4895 + command.restartContinuationOfRunId !== undefined &&
4896 + dispatchMode.type === "start_immediately"
4897 + )))
4898 + ) {
4899 + return yield* new OrchestratorDispatchError({
4900 + commandId: command.commandId,
4901 + commandType: command.type,
4902 + cause: "Notifications must be server- or provider-created queued messages.",
4903 + });
4904 + }
4905 + let delegatedCompletion: OrchestrationV2ConversationMessage["delegatedCompletion"] | undefined;
4906 + if (command.delegatedCompletion !== undefined) {
4907 + const requestedCompletion = command.delegatedCompletion;
4908 if (
4884 - command.notification !== undefined &&
4885 - (command.createdBy !== "agent" ||
4886 - (command.creationSource !== "server" && command.creationSource !== "provider") ||
4887 - (dispatchMode.type !== "queue_after_active" &&
4888 - !(
4889 - command.restartContinuationOfRunId !== undefined &&
4890 - dispatchMode.type === "start_immediately"
4891 - )))
4909 + command.createdBy !== "agent" ||
4910 + command.creationSource !== "server" ||
4911 + dispatchMode.type !== "queue_after_active"
4912 ) {
4913 return yield* new OrchestratorDispatchError({
4914 commandId: command.commandId,
4915 commandType: command.type,
4896 - cause: "Notifications must be server- or provider-created queued messages.",
4916 + cause: "Delegated completion delivery must be a server-created queued message.",
4917 });
4918 }
4899 - let delegatedCompletion:
4900 - | OrchestrationV2ConversationMessage["delegatedCompletion"]
4901 - | undefined;
4902 - if (command.delegatedCompletion !== undefined) {
4903 - const requestedCompletion = command.delegatedCompletion;
4904 - if (
4905 - command.createdBy !== "agent" ||
4906 - command.creationSource !== "server" ||
4907 - dispatchMode.type !== "queue_after_active"
4908 - ) {
4909 - return yield* new OrchestratorDispatchError({
4910 - commandId: command.commandId,
4911 - commandType: command.type,
4912 - cause: "Delegated completion delivery must be a server-created queued message.",
4913 - });
4914 - }
4915 - const parentRun = projection.runs.find(
4916 - (candidate) => candidate.id === requestedCompletion.parentRunId,
4917 - );
4918 - const delivery = parentRun?.delegatedCompletion?.delivery;
4919 - if (
4920 - parentRun?.delegatedCompletion?.disposition !== "open" ||
4921 - delivery === null ||
4922 - delivery === undefined ||
4923 - delivery.generation !== requestedCompletion.generation ||
4924 - delivery.messageId !== command.messageId ||
4925 - (projection.messages.some((candidate) => candidate.id === command.messageId) &&
4926 - !isUndeliveredMailboxSteer(projection, command.messageId))
4927 - ) {
4928 - return yield* new OrchestratorDispatchError({
4929 - commandId: command.commandId,
4930 - commandType: command.type,
4931 - cause: "Delegated completion delivery is no longer dispatchable.",
4932 - });
4933 - }
4934 - delegatedCompletion = {
4935 - parentRunId: requestedCompletion.parentRunId,
4936 - generation: delivery.generation,
4937 - taskIds: delivery.taskIds,
4938 - };
4939 - }
4940 - // Route durable mailbox deliveries under the thread lock, using the live
4941 - // session's capabilities. Never interrupt/restart a turn for a notification.
4919 + const parentRun = projection.runs.find(
4920 + (candidate) => candidate.id === requestedCompletion.parentRunId,
4921 + );
4922 + const delivery = parentRun?.delegatedCompletion?.delivery;
4923 if (
4943 - delegatedCompletion !== undefined &&
4944 - delegatedCompletion.taskIds.every(
4945 - (id) => projection.subagents.find((task) => task.id === id)?.completionWake === "always",
4946 - )
4924 + parentRun?.delegatedCompletion?.disposition !== "open" ||
4925 + delivery === null ||
4926 + delivery === undefined ||
4927 + delivery.generation !== requestedCompletion.generation ||
4928 + delivery.messageId !== command.messageId ||
4929 + (projection.messages.some((candidate) => candidate.id === command.messageId) &&
4930 + !isUndeliveredMailboxSteer(projection, command.messageId))
4931 ) {
4948 - const active = projection.runs.find((run) => run.status === "running");
4949 - const providerThread = projection.providerThreads.find(
4950 - (row) => row.id === active?.providerThreadId,
4951 - );
4952 - const activeTurn = projection.providerTurns.find(
4953 - (turn) => turn.runAttemptId === active?.activeAttemptId && turn.status === "running",
4954 - );
4955 - const activeMessage = projection.messages.find(
4956 - (message) => message.id === active?.userMessageId,
4957 - );
4958 - if (
4959 - active !== undefined &&
4960 - activeTurn !== undefined &&
4961 - providerThread?.providerSessionId != null &&
4962 - (activeMessage === undefined || !isNativeMaintenanceCommand(activeMessage))
4963 - ) {
4964 - const session = yield* providerSessions
4965 - .get(providerThread.providerSessionId)
4966 - .pipe(Effect.orElseSucceed(() => Option.none()));
4967 - if (
4968 - Option.isSome(session) &&
4969 - session.value.providerSession.capabilities.turns.supportsActiveSteering &&
4970 - session.value.providerSession.capabilities.turns.activeSteeringInterruptsTools !== true
4971 - ) {
4972 - dispatchMode = { type: "steer_active", targetRunId: active.id };
4973 - }
4974 - }
4975 - }
4976 - const dispatchText =
4977 - delegatedCompletion === undefined
4978 - ? command.text
4979 - : delegatedCompletionWakeDetail(delegatedCompletion.taskIds);
4980 - const sourcePlanProjection =
4981 - command.sourcePlanRef === undefined
4982 - ? null
4983 - : yield* getProjectionWithPendingEvents(command.sourcePlanRef.threadId, events);
4984 - const sourcePlanArtifact =
4985 - command.sourcePlanRef === undefined
4986 - ? undefined
4987 - : yield* projectionStore
4988 - .getPlan(command.sourcePlanRef.threadId, command.sourcePlanRef.planId)
4989 - .pipe(mapDispatchError(command));
4990 - const sourcePlan = sourcePlanArtifact?.kind === "proposed_plan" ? sourcePlanArtifact : null;
4991 - if (command.sourcePlanRef !== undefined && sourcePlan === null) {
4932 return yield* new OrchestratorDispatchError({
4933 commandId: command.commandId,
4934 commandType: command.type,
4995 - cause: `Proposed plan ${command.sourcePlanRef.planId} does not exist on thread ${command.sourcePlanRef.threadId}.`,
4935 + cause: "Delegated completion delivery is no longer dispatchable.",
4936 });
4937 }
4938 + delegatedCompletion = {
4939 + parentRunId: requestedCompletion.parentRunId,
4940 + generation: delivery.generation,
4941 + taskIds: delivery.taskIds,
4942 + };
4943 + }
4944 + // Route durable mailbox deliveries under the thread lock, using the live
4945 + // session's capabilities. Never interrupt/restart a turn for a notification.
4946 + if (
4947 + delegatedCompletion !== undefined &&
4948 + delegatedCompletion.taskIds.every(
4949 + (id) => projection.subagents.find((task) => task.id === id)?.completionWake === "always",
4950 + )
4951 + ) {
4952 + const active = projection.runs.find((run) => run.status === "running");
4953 + const providerThread = projection.providerThreads.find(
4954 + (row) => row.id === active?.providerThreadId,
4955 + );
4956 + const activeTurn = projection.providerTurns.find(
4957 + (turn) => turn.runAttemptId === active?.activeAttemptId && turn.status === "running",
4958 + );
4959 + const activeMessage = projection.messages.find(
4960 + (message) => message.id === active?.userMessageId,
4961 + );
4962 if (
4999 - sourcePlanProjection !== null &&
5000 - sourcePlanProjection.thread.projectId !== projection.thread.projectId
4963 + active !== undefined &&
4964 + activeTurn !== undefined &&
4965 + providerThread?.providerSessionId != null &&
4966 + (activeMessage === undefined || !isNativeMaintenanceCommand(activeMessage))
4967 ) {
4968 + const session = yield* providerSessions
4969 + .get(providerThread.providerSessionId)
4970 + .pipe(Effect.orElseSucceed(() => Option.none()));
4971 + if (
4972 + Option.isSome(session) &&
4973 + session.value.providerSession.capabilities.turns.supportsActiveSteering &&
4974 + session.value.providerSession.capabilities.turns.activeSteeringInterruptsTools !== true
4975 + ) {
4976 + dispatchMode = { type: "steer_active", targetRunId: active.id };
4977 + }
4978 + }
4979 + }
4980 + const dispatchText =
4981 + delegatedCompletion === undefined
4982 + ? command.text
4983 + : delegatedCompletionWakeDetail(delegatedCompletion.taskIds);
4984 + const sourcePlanProjection =
4985 + command.sourcePlanRef === undefined
4986 + ? null
4987 + : yield* getProjectionWithPendingEvents(command.sourcePlanRef.threadId, events);
4988 + const sourcePlanArtifact =
4989 + command.sourcePlanRef === undefined
4990 + ? undefined
4991 + : yield* projectionStore
4992 + .getPlan(command.sourcePlanRef.threadId, command.sourcePlanRef.planId)
4993 + .pipe(mapDispatchError(command));
4994 + const sourcePlan = sourcePlanArtifact?.kind === "proposed_plan" ? sourcePlanArtifact : null;
4995 + if (command.sourcePlanRef !== undefined && sourcePlan === null) {
4996 + return yield* new OrchestratorDispatchError({
4997 + commandId: command.commandId,
4998 + commandType: command.type,
4999 + cause: `Proposed plan ${command.sourcePlanRef.planId} does not exist on thread ${command.sourcePlanRef.threadId}.`,
5000 + });
5001 + }
5002 + if (
5003 + sourcePlanProjection !== null &&
5004 + sourcePlanProjection.thread.projectId !== projection.thread.projectId
5005 + ) {
5006 + return yield* new OrchestratorDispatchError({
5007 + commandId: command.commandId,
5008 + commandType: command.type,
5009 + cause: `Proposed plan ${command.sourcePlanRef?.planId} belongs to a different project.`,
5010 + });
5011 + }
5012 + if (sourcePlan !== null && sourcePlan.status !== "active") {
5013 + return yield* new OrchestratorDispatchError({
5014 + commandId: command.commandId,
5015 + commandType: command.type,
5016 + cause: `Proposed plan ${sourcePlan.id} is not active.`,
5017 + });
5018 + }
5019 + const completeSourcePlan = (occurredAt: DateTime.Utc) =>
5020 + sourcePlan === null
5021 + ? Effect.void
5022 + : emit(
5023 + events,
5024 + command,
5025 + )({
5026 + type: "plan.updated",
5027 + threadId: sourcePlan.threadId,
5028 + ...(sourcePlan.runId === null ? {} : { runId: sourcePlan.runId }),
5029 + nodeId: sourcePlan.nodeId,
5030 + occurredAt,
5031 + payload: { ...sourcePlan, status: "completed" },
5032 + });
5033 +
5034 + if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") {
5035 + yield* dispatchSteerIntoRun({
5036 + command,
5037 + events,
5038 + effects,
5039 + projection,
5040 + modelSelection:
5041 + delegatedCompletion === undefined
5042 + ? modelSelection
5043 + : (projection.runs.find((run) => run.id === dispatchMode.targetRunId)?.modelSelection ??
5044 + modelSelection),
5045 + delegatedCompletion,
5046 + targetRunId: dispatchMode.targetRunId,
5047 + messageId: command.messageId,
5048 + text: dispatchText,
5049 + ...(command.context ? { context: command.context } : {}),
5050 + attachments: command.attachments,
5051 + createdBy: command.createdBy,
5052 + creationSource: command.creationSource,
5053 + ...(command.scheduledTaskId === undefined
5054 + ? {}
5055 + : { scheduledTaskId: command.scheduledTaskId }),
5056 + ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5057 + forceRestart: dispatchMode.type === "restart_active",
5058 + });
5059 + return;
5060 + }
5061 +
5062 + const activeProviderThread = projection.providerThreads.find(
5063 + (candidate) => candidate.id === projection.thread.activeProviderThreadId,
5064 + );
5065 + const activeRun = projection.runs.find(isBlockingRun);
5066 + // A message queued during worktree setup can arrive after that setup failed
5067 + // without a worktree. It waits, held, like the messages queued before the
5068 + // failure, instead of starting in the project checkout.
5069 + const latestRun = latestExecutedRun(projection.runs);
5070 + const worktreeMissingRun =
5071 + activeRun === undefined &&
5072 + dispatchMode.type === "queue_after_active" &&
5073 + (latestRun?.status === "failed" || latestRun?.status === "interrupted") &&
5074 + latestRun.workspacePreparation?.type === "worktree" &&
5075 + projection.thread.worktreePath === null
5076 + ? latestRun
5077 + : undefined;
5078 + const queueBehindRun = activeRun ?? worktreeMissingRun;
5079 + const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection);
5080 + const startsOrQueuesRun =
5081 + dispatchMode.type === "defer_start" ||
5082 + dispatchMode.type === "start_immediately" ||
5083 + dispatchMode.type === "queue_after_active";
5084 + const shouldQueue = queueBehindRun !== undefined && startsOrQueuesRun;
5085 + // A message the user sends from a client means they are back, so the
5086 + // queue a stop or a restart held runs again, in its order, rather than
5087 + // waiting for a Resume.
5088 + // Continuations and scheduled tasks the server sends for them are not
5089 + // them coming back. Starting the queue still re-holds it for a failed
5090 + // provider or a usage limit; a queue held after worktree setup failed
5091 + // keeps its hold until a worktree exists, even once later messages have
5092 + // run, since its messages would start in the project checkout.
5093 + const worktreeSetupUnresolved =
5094 + projection.thread.worktreePath === null &&
5095 + projection.runs.some(
5096 + (run) =>
5097 + (run.status === "failed" || run.status === "interrupted") &&
5098 + run.workspacePreparation?.type === "worktree",
5099 + );
5100 + const sentByUserFromClient =
5101 + command.createdBy === "user" &&
5102 + (command.creationSource === "web" || command.creationSource === "mobile") &&
5103 + command.scheduledTaskId === undefined;
5104 + const heldRunsToRelease =
5105 + sentByUserFromClient && startsOrQueuesRun && !worktreeSetupUnresolved
5106 + ? projection.runs.filter((run) => run.status === "queued" && run.queueHeld === true)
5107 + : [];
5108 + const releasedAt = yield* DateTime.now;
5109 + for (const held of heldRunsToRelease) {
5110 + yield* emit(
5111 + events,
5112 + command,
5113 + )({
5114 + type: "run.updated",
5115 + threadId: command.threadId,
5116 + runId: held.id,
5117 + providerInstanceId: held.providerInstanceId,
5118 + occurredAt: releasedAt,
5119 + payload: { ...held, queueHeld: false },
5120 + });
5121 + }
5122 + if (shouldQueue) {
5123 + if (pendingMergeBackTransfers.length > 0) {
5124 return yield* new OrchestratorDispatchError({
5125 commandId: command.commandId,
5126 commandType: command.type,
5005 - cause: `Proposed plan ${command.sourcePlanRef?.planId} belongs to a different project.`,
5127 + cause: `Thread ${command.threadId} has a pending merge-back transfer; queued merge-back consumption is not implemented yet.`,
5128 });
5129 }
5008 - if (sourcePlan !== null && sourcePlan.status !== "active") {
5130 + const queueProviderThread =
5131 + activeProviderThread ??
5132 + projection.providerThreads.find(
5133 + (candidate) => candidate.id === queueBehindRun.providerThreadId,
5134 + );
5135 + if (queueProviderThread === undefined) {
5136 return yield* new OrchestratorDispatchError({
5137 commandId: command.commandId,
5138 commandType: command.type,
5012 - cause: `Proposed plan ${sourcePlan.id} is not active.`,
5139 + cause: `Active run ${queueBehindRun.id} has no provider thread for queued dispatch.`,
5140 });
5141 }
5015 - const completeSourcePlan = (occurredAt: DateTime.Utc) =>
5016 - sourcePlan === null
5017 - ? Effect.void
5018 - : emit(
5019 - events,
5020 - command,
5021 - )({
5022 - type: "plan.updated",
5023 - threadId: sourcePlan.threadId,
5024 - ...(sourcePlan.runId === null ? {} : { runId: sourcePlan.runId }),
5025 - nodeId: sourcePlan.nodeId,
5026 - occurredAt,
5027 - payload: { ...sourcePlan, status: "completed" },
5028 - });
5029 -
5030 - if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") {
5031 - yield* dispatchSteerIntoRun({
5032 - command,
5033 - events,
5034 - effects,
5035 - projection,
5036 - modelSelection:
5037 - delegatedCompletion === undefined
5038 - ? modelSelection
5039 - : (projection.runs.find((run) => run.id === dispatchMode.targetRunId)
5040 - ?.modelSelection ?? modelSelection),
5041 - delegatedCompletion,
5042 - targetRunId: dispatchMode.targetRunId,
5043 - messageId: command.messageId,
5044 - text: dispatchText,
5045 - ...(command.context ? { context: command.context } : {}),
5046 - attachments: command.attachments,
5047 - createdBy: command.createdBy,
5048 - creationSource: command.creationSource,
5049 - ...(command.scheduledTaskId === undefined
5050 - ? {}
5051 - : { scheduledTaskId: command.scheduledTaskId }),
5052 - ...(command.senderThreadId === undefined
5053 - ? {}
5054 - : { senderThreadId: command.senderThreadId }),
5055 - forceRestart: dispatchMode.type === "restart_active",
5056 - });
5057 - return;
5058 - }
5059 -
5060 - const activeProviderThread = projection.providerThreads.find(
5061 - (candidate) => candidate.id === projection.thread.activeProviderThreadId,
5062 - );
5063 - const activeRun = projection.runs.find(isBlockingRun);
5064 - // A message queued during worktree setup can arrive after that setup failed
5065 - // without a worktree. It waits, held, like the messages queued before the
5066 - // failure, instead of starting in the project checkout.
5067 - const latestRun = latestExecutedRun(projection.runs);
5068 - const worktreeMissingRun =
5069 - activeRun === undefined &&
5070 - dispatchMode.type === "queue_after_active" &&
5071 - (latestRun?.status === "failed" || latestRun?.status === "interrupted") &&
5072 - latestRun.workspacePreparation?.type === "worktree" &&
5073 - projection.thread.worktreePath === null
5074 - ? latestRun
5075 - : undefined;
5076 - const queueBehindRun = activeRun ?? worktreeMissingRun;
5077 - const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection);
5078 - const startsOrQueuesRun =
5079 - dispatchMode.type === "defer_start" ||
5080 - dispatchMode.type === "start_immediately" ||
5081 - dispatchMode.type === "queue_after_active";
5082 - const shouldQueue = queueBehindRun !== undefined && startsOrQueuesRun;
5083 - // A message the user sends from a client means they are back, so the
5084 - // queue a stop or a restart held runs again, in its order, rather than
5085 - // waiting for a Resume.
5086 - // Continuations and scheduled tasks the server sends for them are not
5087 - // them coming back. Starting the queue still re-holds it for a failed
5088 - // provider or a usage limit; a queue held after worktree setup failed
5089 - // keeps its hold until a worktree exists, even once later messages have
5090 - // run, since its messages would start in the project checkout.
5091 - const worktreeSetupUnresolved =
5092 - projection.thread.worktreePath === null &&
5093 - projection.runs.some(
5094 - (run) =>
5095 - (run.status === "failed" || run.status === "interrupted") &&
5096 - run.workspacePreparation?.type === "worktree",
5097 - );
5098 - const sentByUserFromClient =
5099 - command.createdBy === "user" &&
5100 - (command.creationSource === "web" || command.creationSource === "mobile") &&
5101 - command.scheduledTaskId === undefined;
5102 - const heldRunsToRelease =
5103 - sentByUserFromClient && startsOrQueuesRun && !worktreeSetupUnresolved
5104 - ? projection.runs.filter((run) => run.status === "queued" && run.queueHeld === true)
5105 - : [];
5106 - const releasedAt = yield* DateTime.now;
5107 - for (const held of heldRunsToRelease) {
5108 - yield* emit(
5109 - events,
5110 - command,
5111 - )({
5112 - type: "run.updated",
5113 - threadId: command.threadId,
5114 - runId: held.id,
5115 - providerInstanceId: held.providerInstanceId,
5116 - occurredAt: releasedAt,
5117 - payload: { ...held, queueHeld: false },
5118 - });
5119 - }
5120 - if (shouldQueue) {
5121 - if (pendingMergeBackTransfers.length > 0) {
5122 - return yield* new OrchestratorDispatchError({
5123 - commandId: command.commandId,
5124 - commandType: command.type,
5125 - cause: `Thread ${command.threadId} has a pending merge-back transfer; queued merge-back consumption is not implemented yet.`,
5126 - });
5127 - }
5128 - const queueProviderThread =
5129 - activeProviderThread ??
5130 - projection.providerThreads.find(
5131 - (candidate) => candidate.id === queueBehindRun.providerThreadId,
5132 - );
5133 - if (queueProviderThread === undefined) {
5134 - return yield* new OrchestratorDispatchError({
5135 - commandId: command.commandId,
5136 - commandType: command.type,
5137 - cause: `Active run ${queueBehindRun.id} has no provider thread for queued dispatch.`,
5138 - });
5139 - }
5140 - const now = yield* DateTime.now;
5141 - const ordinal = nextRunOrdinal(projection);
5142 - const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
5143 - const targetProviderThread =
5144 - modelSelection.instanceId === queueProviderThread.providerInstanceId
5145 - ? queueProviderThread
5146 - : rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0];
5147 - const queuedAdapter = yield* providerAdapters
5148 - .get(modelSelection.instanceId)
5149 - .pipe(mapDispatchError(command));
5150 - const selectedProviderSession =
5151 - targetProviderThread?.providerSessionId === null ||
5152 - targetProviderThread?.providerSessionId === undefined
5153 - ? undefined
5154 - : projection.providerSessions.find(
5155 - (candidate) => candidate.id === targetProviderThread.providerSessionId,
5156 - );
5157 - const queuedCapabilities =
5158 - selectedProviderSession?.capabilities ??
5159 - (yield* queuedAdapter.getCapabilities().pipe(mapDispatchError(command)));
5160 - yield* enforceCommandPolicy(command)(
5161 - commandPolicy.ensureQueuedMessages({
5162 - commandId: command.commandId,
5163 - threadId: command.threadId,
5164 - providerInstanceId: modelSelection.instanceId,
5165 - capabilities: queuedCapabilities,
5166 - }),
5167 - );
5168 - const queuedProviderThread: OrchestrationV2ProviderThread = targetProviderThread ?? {
5169 - id: idAllocator.derive.providerThread({
5170 - driver: queuedAdapter.driver,
5171 - nativeThreadId: `pending:${runId}`,
5172 - }),
5173 - driver: queuedAdapter.driver,
5174 - providerInstanceId: modelSelection.instanceId,
5175 - providerSessionId: null,
5176 - appThreadId: command.threadId,
5177 - ownerNodeId: null,
5178 - nativeThreadRef: null,
5179 - nativeConversationHeadRef: null,
5180 - status: "not_loaded",
5181 - firstRunOrdinal: null,
5182 - lastRunOrdinal: null,
5183 - handoffIds: [],
5184 - forkedFrom: null,
5185 - createdAt: now,
5186 - updatedAt: now,
5187 - };
5188 - const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
5189 - const rootNodeId = idAllocator.derive.rootNode({ runId });
5190 - const checkpointScope =
5191 - queueBehindRun.status === "preparing" || worktreeMissingRun !== undefined
5192 - ? null
5193 - : yield* runtimePolicy.resolve({ thread: projection.thread, modelSelection }).pipe(
5194 - Effect.flatMap((resolvedRuntimePolicy) =>
5195 - checkpointService.prepareRootRunScope({
5196 - threadId: command.threadId,
5197 - runId,
5198 - rootNodeId,
5199 - providerThreadId: queuedProviderThread.id,
5200 - cwd:
5201 - resolvedRuntimePolicy.cwd ??
5202 - selectedProviderSession?.cwd ??
5203 - projection.thread.worktreePath ??
5204 - process.cwd(),
5205 - createdAt: now,
5206 - }),
5207 - ),
5208 - Effect.mapError(
5209 - (cause) =>
5210 - new OrchestratorDispatchError({
5211 - commandId: command.commandId,
5212 - commandType: command.type,
5213 - cause,
5214 - }),
5215 - ),
5216 - );
5217 - const run: OrchestrationV2Run = {
5218 - id: runId,
5219 - threadId: command.threadId,
5220 - ordinal,
5221 - providerInstanceId: modelSelection.instanceId,
5222 - modelSelection,
5223 - providerThreadId: queuedProviderThread.id,
5224 - userMessageId: command.messageId,
5225 - rootNodeId,
5226 - activeAttemptId: attemptId,
5227 - status: "queued",
5228 - ...(worktreeMissingRun !== undefined ||
5229 - (heldRunsToRelease.length === 0 &&
5230 - projection.runs.some(
5231 - (candidate) => candidate.status === "queued" && candidate.queueHeld === true,
5232 - ))
5233 - ? { queueHeld: true }
5234 - : {}),
5235 - queuePosition:
5236 - Math.max(
5237 - 0,
5238 - ...projection.runs
5239 - .filter((candidate) => candidate.status === "queued")
5240 - .map((candidate) => candidate.queuePosition ?? candidate.ordinal),
5241 - ) + 1,
5242 - requestedAt: now,
5243 - startedAt: null,
5244 - completedAt: null,
5245 - checkpointId: null,
5246 - contextHandoffId: null,
5247 - ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
5248 - ...(command.restartContinuationOfRunId === undefined
5249 - ? {}
5250 - : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
5251 - ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
5252 - };
5253 - const attempt: OrchestrationV2RunAttempt = {
5254 - id: attemptId,
5255 - runId,
5256 - attemptOrdinal: 1,
5257 - rootNodeId,
5258 - providerInstanceId: modelSelection.instanceId,
5259 - providerThreadId: queuedProviderThread.id,
5260 - providerTurnId: null,
5261 - reason: "initial",
5262 - status: "pending",
5263 - startedAt: null,
5264 - completedAt: null,
5265 - };
5266 - const rootNode: OrchestrationV2ExecutionNode = {
5267 - id: rootNodeId,
5268 - threadId: command.threadId,
5269 - runId,
5270 - parentNodeId: null,
5271 - rootNodeId,
5272 - kind: "root_turn",
5273 - status: "pending",
5274 - countsForRun: true,
5275 - providerThreadId: queuedProviderThread.id,
5276 - providerTurnId: null,
5277 - nativeItemRef: null,
5278 - runtimeRequestId: null,
5279 - checkpointScopeId: checkpointScope?.id ?? null,
5280 - startedAt: null,
5281 - completedAt: null,
5282 - };
5283 - const message: OrchestrationV2ConversationMessage = {
5284 - createdBy: command.createdBy,
5285 - creationSource: command.creationSource,
5286 - ...(command.scheduledTaskId === undefined
5287 - ? {}
5288 - : { scheduledTaskId: command.scheduledTaskId }),
5289 - ...(command.senderThreadId === undefined
5290 - ? {}
5291 - : { senderThreadId: command.senderThreadId }),
5292 - id: command.messageId,
5293 - threadId: command.threadId,
5294 - runId,
5295 - nodeId: rootNodeId,
5296 - role: "user",
5297 - text: dispatchText,
5298 - ...(command.context ? { context: command.context } : {}),
5299 - attachments: command.attachments,
5300 - streaming: false,
5301 - createdAt: now,
5302 - updatedAt: now,
5303 - ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
5304 - ...(command.notification === undefined ? {} : { notification: command.notification }),
5305 - };
5306 - const emitEvent = emit(events, command);
5307 - if (targetProviderThread === undefined) {
5308 - yield* emitEvent({
5309 - type: "provider-thread.updated",
5310 - threadId: command.threadId,
5311 - providerInstanceId: modelSelection.instanceId,
5312 - occurredAt: now,
5313 - payload: queuedProviderThread,
5314 - });
5315 - }
5316 - yield* emitEvent({
5317 - type: "run.created",
5318 - threadId: command.threadId,
5319 - runId,
5320 - nodeId: rootNodeId,
5321 - providerInstanceId: modelSelection.instanceId,
5322 - occurredAt: now,
5323 - payload: run,
5324 - });
5325 - yield* completeSourcePlan(now);
5326 - yield* emitEvent({
5327 - type: "run-attempt.created",
5328 - threadId: command.threadId,
5329 - runId,
5330 - nodeId: rootNodeId,
5331 - providerInstanceId: modelSelection.instanceId,
5332 - occurredAt: now,
5333 - payload: attempt,
5334 - });
5335 - yield* emitEvent({
5336 - type: "node.updated",
5142 + const now = yield* DateTime.now;
5143 + const ordinal = nextRunOrdinal(projection);
5144 + const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
5145 + const targetProviderThread =
5146 + modelSelection.instanceId === queueProviderThread.providerInstanceId
5147 + ? queueProviderThread
5148 + : rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0];
5149 + const queuedAdapter = yield* providerAdapters
5150 + .get(modelSelection.instanceId)
5151 + .pipe(mapDispatchError(command));
5152 + const selectedProviderSession =
5153 + targetProviderThread?.providerSessionId === null ||
5154 + targetProviderThread?.providerSessionId === undefined
5155 + ? undefined
5156 + : projection.providerSessions.find(
5157 + (candidate) => candidate.id === targetProviderThread.providerSessionId,
5158 + );
5159 + const queuedCapabilities =
5160 + selectedProviderSession?.capabilities ??
5161 + (yield* queuedAdapter.getCapabilities().pipe(mapDispatchError(command)));
5162 + yield* enforceCommandPolicy(command)(
5163 + commandPolicy.ensureQueuedMessages({
5164 + commandId: command.commandId,
5165 threadId: command.threadId,
5338 - runId,
5339 - nodeId: rootNodeId,
5166 providerInstanceId: modelSelection.instanceId,
5341 - occurredAt: now,
5342 - payload: rootNode,
5343 - });
5344 - if (checkpointScope !== null) {
5345 - yield* emitEvent({
5346 - type: "checkpoint-scope.created",
5347 - threadId: command.threadId,
5348 - runId,
5349 - nodeId: rootNodeId,
5350 - providerInstanceId: modelSelection.instanceId,
5351 - occurredAt: now,
5352 - payload: yield* checkpointService.ensureScope(checkpointScope).pipe(
5167 + capabilities: queuedCapabilities,
5168 + }),
5169 + );
5170 + const queuedProviderThread: OrchestrationV2ProviderThread = targetProviderThread ?? {
5171 + id: idAllocator.derive.providerThread({
5172 + driver: queuedAdapter.driver,
5173 + nativeThreadId: `pending:${runId}`,
5174 + }),
5175 + driver: queuedAdapter.driver,
5176 + providerInstanceId: modelSelection.instanceId,
5177 + providerSessionId: null,
5178 + appThreadId: command.threadId,
5179 + ownerNodeId: null,
5180 + nativeThreadRef: null,
5181 + nativeConversationHeadRef: null,
5182 + status: "not_loaded",
5183 + firstRunOrdinal: null,
5184 + lastRunOrdinal: null,
5185 + handoffIds: [],
5186 + forkedFrom: null,
5187 + createdAt: now,
5188 + updatedAt: now,
5189 + };
5190 + const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
5191 + const rootNodeId = idAllocator.derive.rootNode({ runId });
5192 + const checkpointScope =
5193 + queueBehindRun.status === "preparing" || worktreeMissingRun !== undefined
5194 + ? null
5195 + : yield* runtimePolicy.resolve({ thread: projection.thread, modelSelection }).pipe(
5196 + Effect.flatMap((resolvedRuntimePolicy) =>
5197 + checkpointService.prepareRootRunScope({
5198 + threadId: command.threadId,
5199 + runId,
5200 + rootNodeId,
5201 + providerThreadId: queuedProviderThread.id,
5202 + cwd:
5203 + resolvedRuntimePolicy.cwd ??
5204 + selectedProviderSession?.cwd ??
5205 + projection.thread.worktreePath ??
5206 + process.cwd(),
5207 + createdAt: now,
5208 + }),
5209 + ),
5210 Effect.mapError(
5211 (cause) =>
5212 new OrchestratorDispatchError({
@@ -5358,589 +5215,306 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5215 cause,
5216 }),
5217 ),
5361 - ),
5362 - });
5363 - }
5218 + );
5219 + const run: OrchestrationV2Run = {
5220 + id: runId,
5221 + threadId: command.threadId,
5222 + ordinal,
5223 + providerInstanceId: modelSelection.instanceId,
5224 + modelSelection,
5225 + providerThreadId: queuedProviderThread.id,
5226 + userMessageId: command.messageId,
5227 + rootNodeId,
5228 + activeAttemptId: attemptId,
5229 + status: "queued",
5230 + ...(worktreeMissingRun !== undefined ||
5231 + (heldRunsToRelease.length === 0 &&
5232 + projection.runs.some(
5233 + (candidate) => candidate.status === "queued" && candidate.queueHeld === true,
5234 + ))
5235 + ? { queueHeld: true }
5236 + : {}),
5237 + queuePosition:
5238 + Math.max(
5239 + 0,
5240 + ...projection.runs
5241 + .filter((candidate) => candidate.status === "queued")
5242 + .map((candidate) => candidate.queuePosition ?? candidate.ordinal),
5243 + ) + 1,
5244 + requestedAt: now,
5245 + startedAt: null,
5246 + completedAt: null,
5247 + checkpointId: null,
5248 + contextHandoffId: null,
5249 + ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
5250 + ...(command.restartContinuationOfRunId === undefined
5251 + ? {}
5252 + : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
5253 + ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
5254 + };
5255 + const attempt: OrchestrationV2RunAttempt = {
5256 + id: attemptId,
5257 + runId,
5258 + attemptOrdinal: 1,
5259 + rootNodeId,
5260 + providerInstanceId: modelSelection.instanceId,
5261 + providerThreadId: queuedProviderThread.id,
5262 + providerTurnId: null,
5263 + reason: "initial",
5264 + status: "pending",
5265 + startedAt: null,
5266 + completedAt: null,
5267 + };
5268 + const rootNode: OrchestrationV2ExecutionNode = {
5269 + id: rootNodeId,
5270 + threadId: command.threadId,
5271 + runId,
5272 + parentNodeId: null,
5273 + rootNodeId,
5274 + kind: "root_turn",
5275 + status: "pending",
5276 + countsForRun: true,
5277 + providerThreadId: queuedProviderThread.id,
5278 + providerTurnId: null,
5279 + nativeItemRef: null,
5280 + runtimeRequestId: null,
5281 + checkpointScopeId: checkpointScope?.id ?? null,
5282 + startedAt: null,
5283 + completedAt: null,
5284 + };
5285 + const message: OrchestrationV2ConversationMessage = {
5286 + createdBy: command.createdBy,
5287 + creationSource: command.creationSource,
5288 + ...(command.scheduledTaskId === undefined
5289 + ? {}
5290 + : { scheduledTaskId: command.scheduledTaskId }),
5291 + ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5292 + id: command.messageId,
5293 + threadId: command.threadId,
5294 + runId,
5295 + nodeId: rootNodeId,
5296 + role: "user",
5297 + text: dispatchText,
5298 + ...(command.context ? { context: command.context } : {}),
5299 + attachments: command.attachments,
5300 + streaming: false,
5301 + createdAt: now,
5302 + updatedAt: now,
5303 + ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
5304 + ...(command.notification === undefined ? {} : { notification: command.notification }),
5305 + };
5306 + const emitEvent = emit(events, command);
5307 + if (targetProviderThread === undefined) {
5308 yield* emitEvent({
5365 - type: "message.updated",
5309 + type: "provider-thread.updated",
5310 threadId: command.threadId,
5367 - runId,
5368 - nodeId: rootNodeId,
5311 providerInstanceId: modelSelection.instanceId,
5312 occurredAt: now,
5371 - payload: message,
5313 + payload: queuedProviderThread,
5314 });
5373 - const existingItem = projection.turnItems.find(
5374 - (item) => item.type === "user_message" && item.messageId === command.messageId,
5375 - );
5376 - if (existingItem?.type === "user_message") {
5377 - yield* emitEvent({
5378 - type: "turn-item.updated",
5379 - threadId: command.threadId,
5380 - runId,
5381 - nodeId: rootNodeId,
5382 - providerInstanceId: modelSelection.instanceId,
5383 - occurredAt: now,
5384 - payload: {
5385 - ...existingItem,
5386 - runId,
5387 - nodeId: rootNodeId,
5388 - providerThreadId: queuedProviderThread.id,
5389 - providerTurnId: null,
5390 - inputIntent: "queued_turn",
5391 - updatedAt: now,
5392 - },
5393 - });
5394 - }
5395 - return;
5315 }
5397 - const pendingForkTransfer = pendingForkTransferForThread(projection);
5398 - const pendingMergeBackSourceThreadIds = new Set(
5399 - pendingMergeBackTransfers.map((transfer) => transfer.sourceThreadId),
5400 - );
5401 - if (pendingMergeBackSourceThreadIds.size > 1) {
5402 - return yield* new OrchestratorDispatchError({
5403 - commandId: command.commandId,
5404 - commandType: command.type,
5405 - cause: `Thread ${command.threadId} has pending merge-back transfers from multiple forks.`,
5316 + yield* emitEvent({
5317 + type: "run.created",
5318 + threadId: command.threadId,
5319 + runId,
5320 + nodeId: rootNodeId,
5321 + providerInstanceId: modelSelection.instanceId,
5322 + occurredAt: now,
5323 + payload: run,
5324 + });
5325 + yield* completeSourcePlan(now);
5326 + yield* emitEvent({
5327 + type: "run-attempt.created",
5328 + threadId: command.threadId,
5329 + runId,
5330 + nodeId: rootNodeId,
5331 + providerInstanceId: modelSelection.instanceId,
5332 + occurredAt: now,
5333 + payload: attempt,
5334 + });
5335 + yield* emitEvent({
5336 + type: "node.updated",
5337 + threadId: command.threadId,
5338 + runId,
5339 + nodeId: rootNodeId,
5340 + providerInstanceId: modelSelection.instanceId,
5341 + occurredAt: now,
5342 + payload: rootNode,
5343 + });
5344 + if (checkpointScope !== null) {
5345 + yield* emitEvent({
5346 + type: "checkpoint-scope.created",
5347 + threadId: command.threadId,
5348 + runId,
5349 + nodeId: rootNodeId,
5350 + providerInstanceId: modelSelection.instanceId,
5351 + occurredAt: now,
5352 + payload: yield* checkpointService.ensureScope(checkpointScope).pipe(
5353 + Effect.mapError(
5354 + (cause) =>
5355 + new OrchestratorDispatchError({
5356 + commandId: command.commandId,
5357 + commandType: command.type,
5358 + cause,
5359 + }),
5360 + ),
5361 + ),
5362 });
5363 }
5408 - const pendingMergeBackTransfer = latestContextTransfer(pendingMergeBackTransfers);
5409 - const supersededMergeBackTransfers = pendingMergeBackTransfers.filter(
5410 - (transfer) => transfer.id !== pendingMergeBackTransfer?.id,
5364 + yield* emitEvent({
5365 + type: "message.updated",
5366 + threadId: command.threadId,
5367 + runId,
5368 + nodeId: rootNodeId,
5369 + providerInstanceId: modelSelection.instanceId,
5370 + occurredAt: now,
5371 + payload: message,
5372 + });
5373 + const existingItem = projection.turnItems.find(
5374 + (item) => item.type === "user_message" && item.messageId === command.messageId,
5375 );
5412 - const now = yield* DateTime.now;
5413 - if (
5414 - !modelSelectionsEqual(projection.thread.modelSelection, modelSelection) ||
5415 - projection.thread.providerInstanceId !== modelSelection.instanceId
5416 - ) {
5417 - yield* emit(
5418 - events,
5419 - command,
5420 - )({
5421 - type:
5422 - projection.thread.providerInstanceId === modelSelection.instanceId
5423 - ? "thread.model-selection-updated"
5424 - : "thread.provider-switched",
5376 + if (existingItem?.type === "user_message") {
5377 + yield* emitEvent({
5378 + type: "turn-item.updated",
5379 threadId: command.threadId,
5380 + runId,
5381 + nodeId: rootNodeId,
5382 providerInstanceId: modelSelection.instanceId,
5383 occurredAt: now,
5384 payload: {
5429 - ...projection.thread,
5430 - providerInstanceId: modelSelection.instanceId,
5431 - modelSelection,
5385 + ...existingItem,
5386 + runId,
5387 + nodeId: rootNodeId,
5388 + providerThreadId: queuedProviderThread.id,
5389 + providerTurnId: null,
5390 + inputIntent: "queued_turn",
5391 updatedAt: now,
5392 },
5393 });
5394 }
5436 - const ordinal = nextRunOrdinal(projection);
5437 - const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
5438 - const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed");
5439 - const latestHandoffRun = projection.runs.findLast(isHandoffSourceRun);
5440 - const legacyImportItems =
5441 - projection.thread.historyOrigin === "v1_import"
5442 - ? yield* readHandoffItems(command.threadId, [null])
5443 - : [];
5444 - const isProviderSwitch =
5445 - activeProviderThread !== undefined &&
5446 - activeProviderThread.providerInstanceId !== modelSelection.instanceId;
5447 - // Account overlays share native history. Selection commands may already
5448 - // have updated the app thread, so classify against the native thread's owner.
5449 - const canResumeAcrossInstances =
5450 - isProviderSwitch &&
5451 - activeProviderThread.nativeThreadRef !== null &&
5452 - (yield* providerSwitchService
5453 - .plan({
5454 - projection: {
5455 - ...projection,
5456 - thread: {
5457 - ...projection.thread,
5458 - modelSelection: {
5459 - ...projection.thread.modelSelection,
5460 - instanceId: activeProviderThread.providerInstanceId,
5461 - },
5395 + return;
5396 + }
5397 + const pendingForkTransfer = pendingForkTransferForThread(projection);
5398 + const pendingMergeBackSourceThreadIds = new Set(
5399 + pendingMergeBackTransfers.map((transfer) => transfer.sourceThreadId),
5400 + );
5401 + if (pendingMergeBackSourceThreadIds.size > 1) {
5402 + return yield* new OrchestratorDispatchError({
5403 + commandId: command.commandId,
5404 + commandType: command.type,
5405 + cause: `Thread ${command.threadId} has pending merge-back transfers from multiple forks.`,
5406 + });
5407 + }
5408 + const pendingMergeBackTransfer = latestContextTransfer(pendingMergeBackTransfers);
5409 + const supersededMergeBackTransfers = pendingMergeBackTransfers.filter(
5410 + (transfer) => transfer.id !== pendingMergeBackTransfer?.id,
5411 + );
5412 + const now = yield* DateTime.now;
5413 + if (
5414 + !modelSelectionsEqual(projection.thread.modelSelection, modelSelection) ||
5415 + projection.thread.providerInstanceId !== modelSelection.instanceId
5416 + ) {
5417 + yield* emit(
5418 + events,
5419 + command,
5420 + )({
5421 + type:
5422 + projection.thread.providerInstanceId === modelSelection.instanceId
5423 + ? "thread.model-selection-updated"
5424 + : "thread.provider-switched",
5425 + threadId: command.threadId,
5426 + providerInstanceId: modelSelection.instanceId,
5427 + occurredAt: now,
5428 + payload: {
5429 + ...projection.thread,
5430 + providerInstanceId: modelSelection.instanceId,
5431 + modelSelection,
5432 + updatedAt: now,
5433 + },
5434 + });
5435 + }
5436 + const ordinal = nextRunOrdinal(projection);
5437 + const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal });
5438 + const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed");
5439 + const latestHandoffRun = projection.runs.findLast(isHandoffSourceRun);
5440 + const legacyImportItems =
5441 + projection.thread.historyOrigin === "v1_import"
5442 + ? yield* readHandoffItems(command.threadId, [null])
5443 + : [];
5444 + const isProviderSwitch =
5445 + activeProviderThread !== undefined &&
5446 + activeProviderThread.providerInstanceId !== modelSelection.instanceId;
5447 + // Account overlays share native history. Selection commands may already
5448 + // have updated the app thread, so classify against the native thread's owner.
5449 + const canResumeAcrossInstances =
5450 + isProviderSwitch &&
5451 + activeProviderThread.nativeThreadRef !== null &&
5452 + (yield* providerSwitchService
5453 + .plan({
5454 + projection: {
5455 + ...projection,
5456 + thread: {
5457 + ...projection.thread,
5458 + modelSelection: {
5459 + ...projection.thread.modelSelection,
5460 + instanceId: activeProviderThread.providerInstanceId,
5461 },
5462 },
5464 - targetModelSelection: modelSelection,
5465 - })
5466 - .pipe(mapDispatchError(command))).transition.type === "restart_and_resume";
5463 + },
5464 + targetModelSelection: modelSelection,
5465 + })
5466 + .pipe(mapDispatchError(command))).transition.type === "restart_and_resume";
5467
5468 - if (
5469 - pendingForkTransfer === undefined &&
5470 - pendingMergeBackTransfer === undefined &&
5471 - !isProviderSwitch
5472 - ) {
5473 - const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe(
5474 - Effect.mapError(
5475 - (cause) =>
5476 - new OrchestratorProviderAdapterError({
5477 - commandId: command.commandId,
5478 - providerInstanceId: modelSelection.instanceId,
5479 - cause,
5480 - }),
5481 - ),
5482 - );
5483 - const providerSessionId =
5484 - activeProviderThread?.providerSessionId ??
5485 - (yield* mapDispatchError(command)(
5486 - providerSessionIdFor({
5487 - adapter,
5468 + if (
5469 + pendingForkTransfer === undefined &&
5470 + pendingMergeBackTransfer === undefined &&
5471 + !isProviderSwitch
5472 + ) {
5473 + const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe(
5474 + Effect.mapError(
5475 + (cause) =>
5476 + new OrchestratorProviderAdapterError({
5477 + commandId: command.commandId,
5478 providerInstanceId: modelSelection.instanceId,
5489 - threadId: command.threadId,
5479 + cause,
5480 }),
5491 - ));
5492 - const providerThreadId =
5493 - activeProviderThread?.id ??
5494 - idAllocator.derive.providerThread({
5495 - driver: adapter.driver,
5496 - nativeThreadId: `pending:${runId}`,
5497 - });
5498 - const legacyImportHandoff = shouldPrepareLegacyImportHandoff({
5499 - historyOrigin: projection.thread.historyOrigin,
5500 - hasCompletedRun: latestCompletedRun !== undefined,
5501 - legacyImportItemCount: legacyImportItems.length,
5502 - })
5503 - ? yield* contextHandoffService
5504 - .prepareLegacyImport({
5505 - threadId: command.threadId,
5506 - targetRunId: runId,
5507 - toProviderThreadId: providerThreadId,
5508 - toProviderInstanceId: modelSelection.instanceId,
5509 - items: legacyImportItems,
5510 - createdAt: now,
5511 - })
5512 - .pipe(mapDispatchError(command))
5513 - : null;
5514 - const providerThread: OrchestrationV2ProviderThread =
5515 - activeProviderThread === undefined
5516 - ? {
5517 - id: providerThreadId,
5518 - driver: adapter.driver,
5519 - providerInstanceId: modelSelection.instanceId,
5520 - providerSessionId,
5521 - appThreadId: command.threadId,
5522 - ownerNodeId: null,
5523 - nativeThreadRef: null,
5524 - nativeConversationHeadRef: null,
5525 - status: "not_loaded",
5526 - firstRunOrdinal: ordinal,
5527 - lastRunOrdinal: ordinal,
5528 - handoffIds: legacyImportHandoff === null ? [] : [legacyImportHandoff.id],
5529 - forkedFrom: null,
5530 - createdAt: now,
5531 - updatedAt: now,
5532 - }
5533 - : {
5534 - ...activeProviderThread,
5535 - providerSessionId,
5536 - lastRunOrdinal: ordinal,
5537 - handoffIds: appendContextHandoffId(
5538 - activeProviderThread.handoffIds,
5539 - legacyImportHandoff?.id ?? null,
5540 - ),
5541 - updatedAt: now,
5542 - };
5543 - const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
5544 - const rootNodeId = idAllocator.derive.rootNode({ runId });
5545 - const checkpointScope =
5546 - dispatchMode.type === "defer_start"
5547 - ? null
5548 - : yield* runtimePolicy
5549 - .resolve({
5550 - thread: projection.thread,
5551 - modelSelection,
5552 - })
5553 - .pipe(
5554 - mapDispatchError(command),
5555 - Effect.flatMap((resolvedRuntimePolicy) =>
5556 - checkpointService.prepareRootRunScope({
5557 - threadId: command.threadId,
5558 - runId,
5559 - rootNodeId,
5560 - providerThreadId,
5561 - cwd:
5562 - resolvedRuntimePolicy.cwd ??
5563 - projection.thread.worktreePath ??
5564 - process.cwd(),
5565 - createdAt: now,
5566 - }),
5567 - ),
5568 - mapDispatchError(command),
5569 - );
5570 - const run: OrchestrationV2Run = {
5571 - id: runId,
5572 - threadId: command.threadId,
5573 - ordinal,
5574 - providerInstanceId: modelSelection.instanceId,
5575 - modelSelection,
5576 - providerThreadId,
5577 - userMessageId: command.messageId,
5578 - rootNodeId,
5579 - activeAttemptId: attemptId,
5580 - status: dispatchMode.type === "defer_start" ? "preparing" : "starting",
5581 - queuePosition: null,
5582 - requestedAt: now,
5583 - startedAt: null,
5584 - completedAt: null,
5585 - checkpointId: null,
5586 - contextHandoffId: legacyImportHandoff?.id ?? null,
5587 - ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
5588 - ...(command.restartContinuationOfRunId === undefined
5589 - ? {}
5590 - : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
5591 - ...(dispatchMode.type === "defer_start" && dispatchMode.workspaceStrategy !== undefined
5592 - ? { workspacePreparation: dispatchMode.workspaceStrategy }
5593 - : {}),
5594 - ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
5595 - ...wakeWorkStartedAt(projection.runs, command),
5596 - };
5597 - const attempt: OrchestrationV2RunAttempt = {
5598 - id: attemptId,
5599 - runId,
5600 - attemptOrdinal: 1,
5601 - rootNodeId,
5602 - providerInstanceId: modelSelection.instanceId,
5603 - providerThreadId,
5604 - providerTurnId: null,
5605 - reason: "initial",
5606 - status: "pending",
5607 - startedAt: null,
5608 - completedAt: null,
5609 - };
5610 - const rootNode: OrchestrationV2ExecutionNode = {
5611 - id: rootNodeId,
5612 - threadId: command.threadId,
5613 - runId,
5614 - parentNodeId: null,
5615 - rootNodeId,
5616 - kind: "root_turn",
5617 - status: "pending",
5618 - countsForRun: true,
5619 - providerThreadId,
5620 - providerTurnId: null,
5621 - nativeItemRef: null,
5622 - runtimeRequestId: null,
5623 - checkpointScopeId: checkpointScope?.id ?? null,
5624 - startedAt: null,
5625 - completedAt: null,
5626 - };
5627 - const message: OrchestrationV2ConversationMessage = {
5628 - createdBy: command.createdBy,
5629 - creationSource: command.creationSource,
5630 - ...(command.scheduledTaskId === undefined
5631 - ? {}
5632 - : { scheduledTaskId: command.scheduledTaskId }),
5633 - ...(command.senderThreadId === undefined
5634 - ? {}
5635 - : { senderThreadId: command.senderThreadId }),
5636 - id: command.messageId,
5637 - threadId: command.threadId,
5638 - runId,
5639 - nodeId: rootNodeId,
5640 - role: "user",
5641 - text: dispatchText,
5642 - ...(command.context ? { context: command.context } : {}),
5643 - attachments: command.attachments,
5644 - streaming: false,
5645 - createdAt: now,
5646 - updatedAt: now,
5647 - ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
5648 - ...(command.notification === undefined ? {} : { notification: command.notification }),
5649 - };
5650 - const turnItem: OrchestrationV2TurnItem = {
5651 - createdBy: command.createdBy,
5652 - creationSource: command.creationSource,
5653 - ...(command.scheduledTaskId === undefined
5654 - ? {}
5655 - : { scheduledTaskId: command.scheduledTaskId }),
5656 - ...(command.senderThreadId === undefined
5657 - ? {}
5658 - : { senderThreadId: command.senderThreadId }),
5659 - id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
5660 - threadId: command.threadId,
5661 - runId,
5662 - nodeId: rootNodeId,
5663 - providerThreadId,
5664 - providerTurnId: null,
5665 - nativeItemRef: null,
5666 - parentItemId: null,
5667 - ordinal: yield* nextTurnItemOrdinal(projection),
5668 - status: "completed",
5669 - title: null,
5670 - startedAt: now,
5671 - completedAt: now,
5672 - updatedAt: now,
5673 - type: "user_message",
5674 - messageId: command.messageId,
5675 - inputIntent: "turn_start",
5676 - text: dispatchText,
5677 - ...(command.context ? { context: command.context } : {}),
5678 - attachments: command.attachments,
5679 - };
5680 - const preparationTurnItem: OrchestrationV2TurnItem | null =
5681 - dispatchMode.type === "defer_start"
5682 - ? {
5683 - id: idAllocator.derive.turnItemFromProviderItem({
5684 - driver: adapter.driver,
5685 - nativeItemId: `workspace-preparation:${runId}`,
5686 - }),
5687 - threadId: command.threadId,
5688 - runId,
5689 - nodeId: rootNodeId,
5690 - providerThreadId,
5691 - providerTurnId: null,
5692 - nativeItemRef: null,
5693 - parentItemId: null,
5694 - ordinal: turnItem.ordinal + 1,
5695 - status: "running",
5696 - title: WORKSPACE_PREPARATION_INPUT,
5697 - startedAt: now,
5698 - completedAt: null,
5699 - updatedAt: now,
5700 - type: "command_execution",
5701 - input: WORKSPACE_PREPARATION_INPUT,
5702 - }
5703 - : null;
5704 - const emitEvent = emit(events, command);
5705 - yield* emitEvent({
5706 - type: "provider-thread.updated",
5707 - threadId: command.threadId,
5481 + ),
5482 + );
5483 + const providerSessionId =
5484 + activeProviderThread?.providerSessionId ??
5485 + (yield* mapDispatchError(command)(
5486 + providerSessionIdFor({
5487 + adapter,
5488 + providerInstanceId: modelSelection.instanceId,
5489 + threadId: command.threadId,
5490 + }),
5491 + ));
5492 + const providerThreadId =
5493 + activeProviderThread?.id ??
5494 + idAllocator.derive.providerThread({
5495 driver: adapter.driver,
5709 - providerInstanceId: modelSelection.instanceId,
5710 - occurredAt: now,
5711 - payload: providerThread,
5496 + nativeThreadId: `pending:${runId}`,
5497 });
5713 - if (legacyImportHandoff !== null) {
5714 - yield* emitEvent({
5715 - type: "context-handoff.updated",
5716 - threadId: command.threadId,
5717 - runId,
5718 - providerInstanceId: modelSelection.instanceId,
5719 - occurredAt: now,
5720 - payload: legacyImportHandoff,
5721 - });
5722 - }
5723 - yield* emitEvent({
5724 - type: "run.created",
5725 - threadId: command.threadId,
5726 - runId,
5727 - nodeId: rootNodeId,
5728 - providerInstanceId: modelSelection.instanceId,
5729 - occurredAt: now,
5730 - payload: run,
5731 - });
5732 - yield* completeSourcePlan(now);
5733 - yield* emitEvent({
5734 - type: "run-attempt.created",
5735 - threadId: command.threadId,
5736 - runId,
5737 - nodeId: rootNodeId,
5738 - providerInstanceId: modelSelection.instanceId,
5739 - occurredAt: now,
5740 - payload: attempt,
5741 - });
5742 - yield* emitEvent({
5743 - type: "node.updated",
5744 - threadId: command.threadId,
5745 - runId,
5746 - nodeId: rootNodeId,
5747 - providerInstanceId: modelSelection.instanceId,
5748 - occurredAt: now,
5749 - payload: rootNode,
5750 - });
5751 - if (checkpointScope !== null) {
5752 - yield* emitEvent({
5753 - type: "checkpoint-scope.created",
5754 - threadId: command.threadId,
5755 - runId,
5756 - nodeId: rootNodeId,
5757 - providerInstanceId: modelSelection.instanceId,
5758 - occurredAt: now,
5759 - payload: checkpointScope,
5760 - });
5761 - }
5762 - yield* emitEvent({
5763 - type: "message.updated",
5764 - threadId: command.threadId,
5765 - runId,
5766 - nodeId: rootNodeId,
5767 - providerInstanceId: modelSelection.instanceId,
5768 - occurredAt: now,
5769 - payload: message,
5770 - });
5771 - yield* emitEvent({
5772 - type: "turn-item.updated",
5773 - threadId: command.threadId,
5774 - runId,
5775 - nodeId: rootNodeId,
5776 - providerInstanceId: modelSelection.instanceId,
5777 - occurredAt: now,
5778 - payload: notificationTurnItem(turnItem, message, projection.subagents),
5779 - });
5780 - if (preparationTurnItem !== null) {
5781 - yield* emitEvent({
5782 - type: "turn-item.updated",
5783 - threadId: command.threadId,
5784 - runId,
5785 - nodeId: rootNodeId,
5786 - providerInstanceId: modelSelection.instanceId,
5787 - occurredAt: now,
5788 - payload: preparationTurnItem,
5789 - });
5790 - }
5791 - const pendingEffect = {
5792 - id: `effect:${command.commandId}:provider-turn.start:${runId}`,
5793 - commandId: command.commandId,
5794 - threadId: command.threadId,
5795 - request: { type: "provider-turn.start", runId },
5796 - } satisfies PendingOrchestrationEffectV2;
5797 - if (dispatchMode.type !== "defer_start") {
5798 - yield* Ref.update(effects, (existing) => [...existing, pendingEffect]);
5799 - }
5800 - return;
5801 - }
5802 - const sourceProjection =
5803 - pendingForkTransfer === undefined
5804 - ? null
5805 - : yield* projectionStore
5806 - .getThreadRecords(pendingForkTransfer.sourceThreadId, [
5807 - "runs",
5808 - "attempts",
5809 - "providerThreads",
5810 - "providerTurns",
5811 - ])
5812 - .pipe(
5813 - Effect.mapError(
5814 - (cause) =>
5815 - new OrchestratorProjectionError({
5816 - threadId: pendingForkTransfer.sourceThreadId,
5817 - cause,
5818 - }),
5819 - ),
5820 - );
5821 - const sourceRun =
5822 - pendingForkTransfer?.sourcePoint.runId === undefined || sourceProjection === null
5823 - ? null
5824 - : (sourceProjection.runs.find(
5825 - (candidate) => candidate.id === pendingForkTransfer.sourcePoint.runId,
5826 - ) ?? null);
5827 - const sourceProviderThread =
5828 - sourceProjection === null || sourceRun === null
5829 - ? undefined
5830 - : providerThreadForRun(sourceProjection, sourceRun);
5831 - const sourceProviderTurnId =
5832 - sourceProjection === null || sourceRun === null || sourceRun.activeAttemptId === null
5833 - ? undefined
5834 - : (latestProviderTurnForAttempt(sourceProjection.providerTurns, sourceRun.activeAttemptId)
5835 - ?.id ??
5836 - sourceProjection.attempts.find(
5837 - (candidate) => candidate.id === sourceRun.activeAttemptId,
5838 - )?.providerTurnId ??
5839 - undefined);
5840 - if (pendingForkTransfer !== undefined) {
5841 - if (sourceRun === null || sourceProviderThread === undefined) {
5842 - return yield* new OrchestratorDispatchError({
5843 - commandId: command.commandId,
5844 - commandType: command.type,
5845 - cause: `Pending fork transfer ${pendingForkTransfer.id} has no resolvable source provider thread.`,
5846 - });
5847 - }
5848 - if (pendingForkTransfer.sourceProviderInstanceId === null) {
5849 - return yield* new OrchestratorDispatchError({
5850 - commandId: command.commandId,
5851 - commandType: command.type,
5852 - cause: `Pending fork transfer ${pendingForkTransfer.id} has no source provider.`,
5853 - });
5854 - }
5855 - }
5856 -
5857 - const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe(
5858 - Effect.mapError(
5859 - (cause) =>
5860 - new OrchestratorProviderAdapterError({
5861 - commandId: command.commandId,
5862 - providerInstanceId: modelSelection.instanceId,
5863 - cause,
5864 - }),
5865 - ),
5866 - );
5867 - const targetProviderThread =
5868 - isProviderSwitch && !canResumeAcrossInstances
5869 - ? rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0]
5870 - : activeProviderThread;
5871 - const providerSessionId =
5872 - (canResumeAcrossInstances ? undefined : targetProviderThread?.providerSessionId) ??
5873 - (yield* mapDispatchError(command)(
5874 - providerSessionIdFor({
5875 - adapter,
5876 - providerInstanceId: modelSelection.instanceId,
5877 - threadId: command.threadId,
5878 - }),
5879 - ));
5880 - const existingProviderSession = projection.providerSessions.find(
5881 - (candidate) => candidate.id === providerSessionId,
5882 - );
5883 - const resolvedRuntimePolicy = yield* runtimePolicy
5884 - .resolve({ thread: projection.thread, modelSelection })
5885 - .pipe(
5886 - Effect.mapError(
5887 - (cause) =>
5888 - new OrchestratorDispatchError({
5889 - commandId: command.commandId,
5890 - commandType: command.type,
5891 - cause,
5892 - }),
5893 - ),
5894 - );
5895 -
5896 - const capabilities = yield* adapter.getCapabilities().pipe(
5897 - Effect.mapError(
5898 - (cause) =>
5899 - new OrchestratorProviderAdapterError({
5900 - commandId: command.commandId,
5901 - providerInstanceId: modelSelection.instanceId,
5902 - cause,
5903 - }),
5904 - ),
5905 - );
5906 - const forkExecution =
5907 - pendingForkTransfer === undefined || sourceRun === null
5908 - ? null
5909 - : yield* enforceCommandPolicy(command)(
5910 - commandPolicy.decideForkExecution({
5911 - commandId: command.commandId,
5912 - threadId: command.threadId,
5913 - providerInstanceId: modelSelection.instanceId,
5914 - capabilities,
5915 - sameProvider:
5916 - pendingForkTransfer.sourceProviderInstanceId === modelSelection.instanceId,
5917 - hasStrongNativeSource: sourceProviderThread?.nativeThreadRef?.strength === "strong",
5918 - sourceRunStatus: sourceRun.status,
5919 - fromSpecificTurn: sourceRun !== null,
5920 - }),
5921 - );
5922 - const canResolveForkNatively = forkExecution === "native_fork";
5923 - const requiresPortableFork = forkExecution === "portable_context";
5924 -
5925 - if (canResolveForkNatively) {
5926 - yield* enforceCommandPolicy(command)(
5927 - commandPolicy.ensureNativeFork({
5928 - commandId: command.commandId,
5929 - threadId: command.threadId,
5930 - providerInstanceId: modelSelection.instanceId,
5931 - capabilities,
5932 - fromSpecificTurn: sourceRun !== null,
5933 - }),
5934 - );
5935 - }
5936 -
5937 - const ensuredProviderThread: OrchestrationV2ProviderThread =
5938 - targetProviderThread === undefined
5498 + const legacyImportHandoff = shouldPrepareLegacyImportHandoff({
5499 + historyOrigin: projection.thread.historyOrigin,
5500 + hasCompletedRun: latestCompletedRun !== undefined,
5501 + legacyImportItemCount: legacyImportItems.length,
5502 + })
5503 + ? yield* contextHandoffService
5504 + .prepareLegacyImport({
5505 + threadId: command.threadId,
5506 + targetRunId: runId,
5507 + toProviderThreadId: providerThreadId,
5508 + toProviderInstanceId: modelSelection.instanceId,
5509 + items: legacyImportItems,
5510 + createdAt: now,
5511 + })
5512 + .pipe(mapDispatchError(command))
5513 + : null;
5514 + const providerThread: OrchestrationV2ProviderThread =
5515 + activeProviderThread === undefined
5516 ? {
5940 - id: idAllocator.derive.providerThread({
5941 - driver: adapter.driver,
5942 - nativeThreadId: `pending:${runId}`,
5943 - }),
5517 + id: providerThreadId,
5518 driver: adapter.driver,
5519 providerInstanceId: modelSelection.instanceId,
5520 providerSessionId,
@@ -5951,340 +5525,70 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5525 status: "not_loaded",
5526 firstRunOrdinal: ordinal,
5527 lastRunOrdinal: ordinal,
5954 - handoffIds: [],
5955 - forkedFrom:
5956 - canResolveForkNatively && sourceProviderThread !== undefined
5957 - ? {
5958 - providerThreadId: sourceProviderThread.id,
5959 - ...(sourceProviderTurnId === undefined
5960 - ? {}
5961 - : { providerTurnId: sourceProviderTurnId }),
5962 - }
5963 - : null,
5528 + handoffIds: legacyImportHandoff === null ? [] : [legacyImportHandoff.id],
5529 + forkedFrom: null,
5530 createdAt: now,
5531 updatedAt: now,
5532 }
5533 : {
5968 - ...targetProviderThread,
5969 - providerInstanceId: modelSelection.instanceId,
5534 + ...activeProviderThread,
5535 providerSessionId,
5536 + lastRunOrdinal: ordinal,
5537 + handoffIds: appendContextHandoffId(
5538 + activeProviderThread.handoffIds,
5539 + legacyImportHandoff?.id ?? null,
5540 + ),
5541 updatedAt: now,
5542 };
5973 - const portableForkItems =
5974 - !requiresPortableFork || sourceProjection === null || sourceRun === null
5975 - ? []
5976 - : yield* readHandoffItems(sourceProjection.thread.id, [
5977 - ...sourceProjection.runs
5978 - .filter((run) => run.ordinal <= sourceRun.ordinal)
5979 - .map((run) => run.id),
5980 - ...(sourceProjection.thread.historyOrigin === "v1_import" ? [null] : []),
5981 - ]);
5982 - const portableForkHandoff =
5983 - !requiresPortableFork ||
5984 - pendingForkTransfer === undefined ||
5985 - sourceProjection === null ||
5986 - sourceRun === null
5987 - ? null
5988 - : yield* contextHandoffService
5989 - .prepareProviderHandoff({
5990 - threadId: command.threadId,
5991 - targetRunId: runId,
5992 - transferId: pendingForkTransfer.id,
5993 - fromProviderThreadIds:
5994 - sourceProviderThread === undefined ? [] : [sourceProviderThread.id],
5995 - toProviderThreadId: ensuredProviderThread.id,
5996 - fromProviderInstanceId: sourceRun.providerInstanceId,
5997 - toProviderInstanceId: modelSelection.instanceId,
5998 - coveredRunOrdinals: visibleDeltaRunOrdinals(sourceProjection, portableForkItems),
5999 - strategy: "full_thread_summary",
6000 - items: portableForkItems,
6001 - runs: sourceProjection.runs,
6002 - createdAt: now,
6003 - })
6004 - .pipe(
6005 - Effect.mapError(
6006 - (cause) =>
6007 - new OrchestratorDispatchError({
6008 - commandId: command.commandId,
6009 - commandType: command.type,
6010 - cause,
6011 - }),
6012 - ),
6013 - );
6014 - const requiresFullProviderSwitchContext =
6015 - isProviderSwitch && pendingMergeBackTransfer !== undefined;
6016 - const targetLastCompletedRun =
6017 - targetProviderThread === undefined
6018 - ? undefined
6019 - : lastDeliveredRunForProviderThread(projection, targetProviderThread.id);
6020 - const providerSwitchCoveredRuns =
6021 - !isProviderSwitch || canResumeAcrossInstances || latestHandoffRun === undefined
6022 - ? []
6023 - : projection.runs.filter(
6024 - (run) =>
6025 - isHandoffSourceRun(run) &&
6026 - run.ordinal >
6027 - (requiresFullProviderSwitchContext
6028 - ? 0
6029 - : (targetLastCompletedRun?.ordinal ?? 0)) &&
6030 - run.ordinal <= latestHandoffRun.ordinal,
6031 - );
6032 - const providerSwitchItems =
6033 - providerSwitchCoveredRuns.length === 0
6034 - ? []
6035 - : [
6036 - ...(latestCompletedRun !== undefined &&
6037 - (targetProviderThread === undefined || requiresFullProviderSwitchContext)
6038 - ? legacyImportItems
6039 - : []),
6040 - ...(yield* readHandoffItems(
6041 - command.threadId,
6042 - providerSwitchCoveredRuns.map((run) => run.id),
6043 - )),
6044 - ];
6045 - const providerSwitchTransferId =
6046 - providerSwitchCoveredRuns.length === 0 || latestHandoffRun === undefined
6047 - ? null
6048 - : yield* mapDispatchError(command)(
6049 - idAllocator.allocate.contextTransfer({
6050 - sourceThreadId: command.threadId,
6051 - targetThreadId: command.threadId,
6052 - type: "provider_handoff",
6053 - }),
6054 - );
6055 - if (providerSwitchTransferId !== null) {
6056 - yield* enforceCommandPolicy(command)(
6057 - commandPolicy.ensureContextHandoff({
6058 - commandId: command.commandId,
6059 - threadId: command.threadId,
6060 - providerInstanceId: modelSelection.instanceId,
6061 - capabilities,
6062 - strategy:
6063 - targetProviderThread === undefined || requiresFullProviderSwitchContext
6064 - ? "full_thread_summary"
6065 - : "delta_context",
6066 - }),
6067 - );
6068 - }
6069 - const providerSwitchHandoff =
6070 - providerSwitchTransferId === null || latestHandoffRun === undefined
6071 - ? null
6072 - : yield* contextHandoffService
6073 - .prepareProviderHandoff({
6074 - threadId: command.threadId,
6075 - targetRunId: runId,
6076 - transferId: providerSwitchTransferId,
6077 - fromProviderThreadIds: Array.from(
6078 - new Set(
6079 - providerSwitchCoveredRuns.flatMap((run) =>
6080 - run.providerThreadId === null ? [] : [run.providerThreadId],
6081 - ),
6082 - ),
6083 - ),
6084 - toProviderThreadId: ensuredProviderThread.id,
6085 - fromProviderInstanceId: latestHandoffRun.providerInstanceId,
6086 - toProviderInstanceId: modelSelection.instanceId,
6087 - coveredRunOrdinals: {
6088 - from: providerSwitchCoveredRuns[0]!.ordinal,
6089 - to: providerSwitchCoveredRuns.at(-1)!.ordinal,
6090 - },
6091 - strategy:
6092 - targetProviderThread === undefined || requiresFullProviderSwitchContext
6093 - ? "full_thread_summary"
6094 - : "delta_since_target_last_seen",
6095 - items: providerSwitchItems,
6096 - runs: projection.runs,
6097 - createdAt: now,
6098 - })
6099 - .pipe(
6100 - Effect.mapError(
6101 - (cause) =>
6102 - new OrchestratorDispatchError({
6103 - commandId: command.commandId,
6104 - commandType: command.type,
6105 - cause,
6106 - }),
6107 - ),
6108 - );
6109 - const legacyImportRecoveryHandoff =
6110 - isProviderSwitch &&
6111 - !canResumeAcrossInstances &&
6112 - latestCompletedRun === undefined &&
6113 - legacyImportItems.length > 0
6114 - ? yield* contextHandoffService
6115 - .prepareLegacyImport({
6116 - threadId: command.threadId,
6117 - targetRunId: runId,
6118 - toProviderThreadId: ensuredProviderThread.id,
6119 - toProviderInstanceId: modelSelection.instanceId,
6120 - items: legacyImportItems,
6121 - createdAt: now,
6122 - })
6123 - .pipe(mapDispatchError(command))
6124 - : null;
6125 - const providerThread: OrchestrationV2ProviderThread = {
6126 - ...ensuredProviderThread,
6127 - status: "active",
6128 - firstRunOrdinal: ensuredProviderThread.firstRunOrdinal ?? ordinal,
6129 - lastRunOrdinal: ordinal,
6130 - handoffIds: [
6131 - ...ensuredProviderThread.handoffIds,
6132 - ...[portableForkHandoff, providerSwitchHandoff, legacyImportRecoveryHandoff].flatMap(
6133 - (handoff) => (handoff === null ? [] : [handoff.id]),
6134 - ),
6135 - ],
6136 - updatedAt: now,
6137 - };
6138 -
5543 const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 });
5544 const rootNodeId = idAllocator.derive.rootNode({ runId });
6141 - const emitEvent = emit(events, command);
6142 - const mergeBackSourceProjection =
6143 - pendingMergeBackTransfer === undefined
5545 + const checkpointScope =
5546 + dispatchMode.type === "defer_start"
5547 ? null
6145 - : yield* projectionStore
6146 - .getThreadRecords(pendingMergeBackTransfer.sourceThreadId, [
6147 - "runs",
6148 - "attempts",
6149 - "providerThreads",
6150 - "providerTurns",
6151 - ])
5548 + : yield* runtimePolicy
5549 + .resolve({
5550 + thread: projection.thread,
5551 + modelSelection,
5552 + })
5553 .pipe(
6153 - Effect.mapError(
6154 - (cause) =>
6155 - new OrchestratorProjectionError({
6156 - threadId: pendingMergeBackTransfer.sourceThreadId,
6157 - cause,
6158 - }),
5554 + mapDispatchError(command),
5555 + Effect.flatMap((resolvedRuntimePolicy) =>
5556 + checkpointService.prepareRootRunScope({
5557 + threadId: command.threadId,
5558 + runId,
5559 + rootNodeId,
5560 + providerThreadId,
5561 + cwd:
5562 + resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(),
5563 + createdAt: now,
5564 + }),
5565 ),
5566 + mapDispatchError(command),
5567 );
6161 - const mergeBackSourceRun =
6162 - pendingMergeBackTransfer?.sourcePoint.runId === undefined ||
6163 - mergeBackSourceProjection === null
6164 - ? null
6165 - : (mergeBackSourceProjection.runs.find(
6166 - (candidate) => candidate.id === pendingMergeBackTransfer.sourcePoint.runId,
6167 - ) ?? null);
6168 - if (pendingMergeBackTransfer !== undefined && mergeBackSourceRun === null) {
6169 - return yield* new OrchestratorDispatchError({
6170 - commandId: command.commandId,
6171 - commandType: command.type,
6172 - cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source run.`,
6173 - });
6174 - }
6175 - const mergeBackSourceProviderThread =
6176 - mergeBackSourceProjection === null || mergeBackSourceRun === null
6177 - ? undefined
6178 - : providerThreadForRun(mergeBackSourceProjection, mergeBackSourceRun);
6179 - if (pendingMergeBackTransfer !== undefined && mergeBackSourceProviderThread === undefined) {
6180 - return yield* new OrchestratorDispatchError({
6181 - commandId: command.commandId,
6182 - commandType: command.type,
6183 - cause: `Pending merge-back transfer ${pendingMergeBackTransfer.id} has no resolvable source provider thread.`,
6184 - });
6185 - }
6186 - if (pendingMergeBackTransfer !== undefined) {
6187 - yield* enforceCommandPolicy(command)(
6188 - commandPolicy.ensureContextHandoff({
6189 - commandId: command.commandId,
6190 - threadId: command.threadId,
6191 - providerInstanceId: modelSelection.instanceId,
6192 - capabilities,
6193 - strategy: "fork_delta_context",
6194 - }),
6195 - );
6196 - }
6197 - const mergeBackDeltaItems =
6198 - mergeBackSourceProjection === null || mergeBackSourceRun === null
6199 - ? []
6200 - : yield* readHandoffItems(
6201 - mergeBackSourceProjection.thread.id,
6202 - mergeBackSourceProjection.runs
6203 - .filter((run) => run.ordinal <= mergeBackSourceRun.ordinal)
6204 - .map((run) => run.id),
6205 - );
6206 - const mergeBackHandoff =
6207 - pendingMergeBackTransfer === undefined ||
6208 - mergeBackSourceProjection === null ||
6209 - mergeBackSourceRun === null ||
6210 - mergeBackSourceProviderThread === undefined
6211 - ? null
6212 - : yield* contextHandoffService
6213 - .prepareForkDelta({
6214 - sourceThreadId: pendingMergeBackTransfer.sourceThreadId,
6215 - targetThreadId: command.threadId,
6216 - targetRunId: runId,
6217 - transferId: pendingMergeBackTransfer.id,
6218 - fromProviderThreadIds: [mergeBackSourceProviderThread.id],
6219 - toProviderThreadId: providerThread.id,
6220 - fromProviderInstanceId: mergeBackSourceRun.providerInstanceId,
6221 - toProviderInstanceId: modelSelection.instanceId,
6222 - coveredRunOrdinals: visibleDeltaRunOrdinals(
6223 - mergeBackSourceProjection,
6224 - mergeBackDeltaItems,
6225 - ),
6226 - deltaItems: mergeBackDeltaItems,
6227 - createdAt: now,
6228 - })
6229 - .pipe(
6230 - Effect.mapError(
6231 - (cause) =>
6232 - new OrchestratorDispatchError({
6233 - commandId: command.commandId,
6234 - commandType: command.type,
6235 - cause,
6236 - }),
6237 - ),
6238 - );
6239 - const checkpointScope = yield* checkpointService
6240 - .prepareRootRunScope({
6241 - threadId: command.threadId,
6242 - runId,
6243 - rootNodeId,
6244 - providerThreadId: providerThread.id,
6245 - cwd:
6246 - resolvedRuntimePolicy.cwd ??
6247 - existingProviderSession?.cwd ??
6248 - projection.thread.worktreePath ??
6249 - process.cwd(),
6250 - createdAt: now,
6251 - })
6252 - .pipe(
6253 - Effect.mapError(
6254 - (cause) =>
6255 - new OrchestratorDispatchError({
6256 - commandId: command.commandId,
6257 - commandType: command.type,
6258 - cause,
6259 - }),
6260 - ),
6261 - );
5568 const run: OrchestrationV2Run = {
5569 id: runId,
5570 threadId: command.threadId,
5571 ordinal,
5572 providerInstanceId: modelSelection.instanceId,
5573 modelSelection,
6268 - providerThreadId: providerThread.id,
5574 + providerThreadId,
5575 userMessageId: command.messageId,
5576 rootNodeId,
5577 activeAttemptId: attemptId,
6272 - status: "starting",
5578 + status: dispatchMode.type === "defer_start" ? "preparing" : "starting",
5579 queuePosition: null,
5580 requestedAt: now,
5581 startedAt: null,
5582 completedAt: null,
5583 checkpointId: null,
6278 - contextHandoffId:
6279 - portableForkHandoff?.id ??
6280 - providerSwitchHandoff?.id ??
6281 - mergeBackHandoff?.id ??
6282 - legacyImportRecoveryHandoff?.id ??
6283 - null,
5584 + contextHandoffId: legacyImportHandoff?.id ?? null,
5585 ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }),
5586 ...(command.restartContinuationOfRunId === undefined
5587 ? {}
5588 : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
5589 + ...(dispatchMode.type === "defer_start" && dispatchMode.workspaceStrategy !== undefined
5590 + ? { workspacePreparation: dispatchMode.workspaceStrategy }
5591 + : {}),
5592 ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
5593 ...wakeWorkStartedAt(projection.runs, command),
5594 };
@@ -6294,7 +5598,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5598 attemptOrdinal: 1,
5599 rootNodeId,
5600 providerInstanceId: modelSelection.instanceId,
6297 - providerThreadId: providerThread.id,
5601 + providerThreadId,
5602 providerTurnId: null,
5603 reason: "initial",
5604 status: "pending",
@@ -6310,11 +5614,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5614 kind: "root_turn",
5615 status: "pending",
5616 countsForRun: true,
6313 - providerThreadId: providerThread.id,
5617 + providerThreadId,
5618 providerTurnId: null,
5619 nativeItemRef: null,
5620 runtimeRequestId: null,
6317 - checkpointScopeId: checkpointScope.id,
5621 + checkpointScopeId: checkpointScope?.id ?? null,
5622 startedAt: null,
5623 completedAt: null,
5624 };
@@ -6328,416 +5632,1103 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5632 id: command.messageId,
5633 threadId: command.threadId,
5634 runId,
6331 - nodeId: rootNodeId,
6332 - role: "user",
6333 - text: dispatchText,
6334 - ...(command.context ? { context: command.context } : {}),
6335 - attachments: command.attachments,
6336 - streaming: false,
6337 - createdAt: now,
6338 - updatedAt: now,
6339 - ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
6340 - ...(command.notification === undefined ? {} : { notification: command.notification }),
6341 - };
6342 - const turnItem: OrchestrationV2TurnItem = {
6343 - createdBy: command.createdBy,
6344 - creationSource: command.creationSource,
6345 - ...(command.scheduledTaskId === undefined
6346 - ? {}
6347 - : { scheduledTaskId: command.scheduledTaskId }),
6348 - ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
6349 - id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
5635 + nodeId: rootNodeId,
5636 + role: "user",
5637 + text: dispatchText,
5638 + ...(command.context ? { context: command.context } : {}),
5639 + attachments: command.attachments,
5640 + streaming: false,
5641 + createdAt: now,
5642 + updatedAt: now,
5643 + ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
5644 + ...(command.notification === undefined ? {} : { notification: command.notification }),
5645 + };
5646 + const turnItem: OrchestrationV2TurnItem = {
5647 + createdBy: command.createdBy,
5648 + creationSource: command.creationSource,
5649 + ...(command.scheduledTaskId === undefined
5650 + ? {}
5651 + : { scheduledTaskId: command.scheduledTaskId }),
5652 + ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5653 + id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
5654 + threadId: command.threadId,
5655 + runId,
5656 + nodeId: rootNodeId,
5657 + providerThreadId,
5658 + providerTurnId: null,
5659 + nativeItemRef: null,
5660 + parentItemId: null,
5661 + ordinal: yield* nextTurnItemOrdinal(projection),
5662 + status: "completed",
5663 + title: null,
5664 + startedAt: now,
5665 + completedAt: now,
5666 + updatedAt: now,
5667 + type: "user_message",
5668 + messageId: command.messageId,
5669 + inputIntent: "turn_start",
5670 + text: dispatchText,
5671 + ...(command.context ? { context: command.context } : {}),
5672 + attachments: command.attachments,
5673 + };
5674 + const preparationTurnItem: OrchestrationV2TurnItem | null =
5675 + dispatchMode.type === "defer_start"
5676 + ? {
5677 + id: idAllocator.derive.turnItemFromProviderItem({
5678 + driver: adapter.driver,
5679 + nativeItemId: `workspace-preparation:${runId}`,
5680 + }),
5681 + threadId: command.threadId,
5682 + runId,
5683 + nodeId: rootNodeId,
5684 + providerThreadId,
5685 + providerTurnId: null,
5686 + nativeItemRef: null,
5687 + parentItemId: null,
5688 + ordinal: turnItem.ordinal + 1,
5689 + status: "running",
5690 + title: WORKSPACE_PREPARATION_INPUT,
5691 + startedAt: now,
5692 + completedAt: null,
5693 + updatedAt: now,
5694 + type: "command_execution",
5695 + input: WORKSPACE_PREPARATION_INPUT,
5696 + }
5697 + : null;
5698 + const emitEvent = emit(events, command);
5699 + yield* emitEvent({
5700 + type: "provider-thread.updated",
5701 + threadId: command.threadId,
5702 + driver: adapter.driver,
5703 + providerInstanceId: modelSelection.instanceId,
5704 + occurredAt: now,
5705 + payload: providerThread,
5706 + });
5707 + if (legacyImportHandoff !== null) {
5708 + yield* emitEvent({
5709 + type: "context-handoff.updated",
5710 + threadId: command.threadId,
5711 + runId,
5712 + providerInstanceId: modelSelection.instanceId,
5713 + occurredAt: now,
5714 + payload: legacyImportHandoff,
5715 + });
5716 + }
5717 + yield* emitEvent({
5718 + type: "run.created",
5719 + threadId: command.threadId,
5720 + runId,
5721 + nodeId: rootNodeId,
5722 + providerInstanceId: modelSelection.instanceId,
5723 + occurredAt: now,
5724 + payload: run,
5725 + });
5726 + yield* completeSourcePlan(now);
5727 + yield* emitEvent({
5728 + type: "run-attempt.created",
5729 + threadId: command.threadId,
5730 + runId,
5731 + nodeId: rootNodeId,
5732 + providerInstanceId: modelSelection.instanceId,
5733 + occurredAt: now,
5734 + payload: attempt,
5735 + });
5736 + yield* emitEvent({
5737 + type: "node.updated",
5738 + threadId: command.threadId,
5739 + runId,
5740 + nodeId: rootNodeId,
5741 + providerInstanceId: modelSelection.instanceId,
5742 + occurredAt: now,
5743 + payload: rootNode,
5744 + });
5745 + if (checkpointScope !== null) {
5746 + yield* emitEvent({
5747 + type: "checkpoint-scope.created",
5748 + threadId: command.threadId,
5749 + runId,
5750 + nodeId: rootNodeId,
5751 + providerInstanceId: modelSelection.instanceId,
5752 + occurredAt: now,
5753 + payload: checkpointScope,
5754 + });
5755 + }
5756 + yield* emitEvent({
5757 + type: "message.updated",
5758 + threadId: command.threadId,
5759 + runId,
5760 + nodeId: rootNodeId,
5761 + providerInstanceId: modelSelection.instanceId,
5762 + occurredAt: now,
5763 + payload: message,
5764 + });
5765 + yield* emitEvent({
5766 + type: "turn-item.updated",
5767 + threadId: command.threadId,
5768 + runId,
5769 + nodeId: rootNodeId,
5770 + providerInstanceId: modelSelection.instanceId,
5771 + occurredAt: now,
5772 + payload: notificationTurnItem(turnItem, message, projection.subagents),
5773 + });
5774 + if (preparationTurnItem !== null) {
5775 + yield* emitEvent({
5776 + type: "turn-item.updated",
5777 + threadId: command.threadId,
5778 + runId,
5779 + nodeId: rootNodeId,
5780 + providerInstanceId: modelSelection.instanceId,
5781 + occurredAt: now,
5782 + payload: preparationTurnItem,
5783 + });
5784 + }
5785 + const pendingEffect = {
5786 + id: `effect:${command.commandId}:provider-turn.start:${runId}`,
5787 + commandId: command.commandId,
5788 + threadId: command.threadId,
5789 + request: { type: "provider-turn.start", runId },
5790 + } satisfies PendingOrchestrationEffectV2;
5791 + if (dispatchMode.type !== "defer_start") {
5792 + yield* Ref.update(effects, (existing) => [...existing, pendingEffect]);
5793 + }
5794 + return;
5795 + }
5796 + const sourceProjection =
5797 + pendingForkTransfer === undefined
5798 + ? null
5799 + : yield* projectionStore
5800 + .getThreadRecords(pendingForkTransfer.sourceThreadId, [
5801 + "runs",
5802 + "attempts",
5803 + "providerThreads",
5804 + "providerTurns",
5805 + ])
5806 + .pipe(
5807 + Effect.mapError(
5808 + (cause) =>
5809 + new OrchestratorProjectionError({
5810 + threadId: pendingForkTransfer.sourceThreadId,
5811 + cause,
5812 + }),
5813 + ),
5814 + );
5815 + const sourceRun =
5816 + pendingForkTransfer?.sourcePoint.runId === undefined || sourceProjection === null
5817 + ? null
5818 + : (sourceProjection.runs.find(
5819 + (candidate) => candidate.id === pendingForkTransfer.sourcePoint.runId,
5820 + ) ?? null);
5821 + const sourceProviderThread =
5822 + sourceProjection === null || sourceRun === null
5823 + ? undefined
5824 + : providerThreadForRun(sourceProjection, sourceRun);
5825 + const sourceProviderTurnId =
5826 + sourceProjection === null || sourceRun === null || sourceRun.activeAttemptId === null
5827 + ? undefined
5828 + : (latestProviderTurnForAttempt(sourceProjection.providerTurns, sourceRun.activeAttemptId)
5829 + ?.id ??
5830 + sourceProjection.attempts.find((candidate) => candidate.id === sourceRun.activeAttemptId)
5831 + ?.providerTurnId ??
5832 + undefined);
5833 + if (pendingForkTransfer !== undefined) {
5834 + if (sourceRun === null || sourceProviderThread === undefined) {
5835 + return yield* new OrchestratorDispatchError({
5836 + commandId: command.commandId,
5837 + commandType: command.type,
5838 + cause: `Pending fork transfer ${pendingForkTransfer.id} has no resolvable source provider thread.`,
5839 + });
5840 + }
5841 + if (pendingForkTransfer.sourceProviderInstanceId === null) {
5842 + return yield* new OrchestratorDispatchError({
5843 + commandId: command.commandId,
5844 + commandType: command.type,
5845 + cause: `Pending fork transfer ${pendingForkTransfer.id} has no source provider.`,
5846 + });
5847 + }
5848 + }
5849 +
5850 + const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe(
5851 + Effect.mapError(
5852 + (cause) =>
5853 + new OrchestratorProviderAdapterError({
5854 + commandId: command.commandId,
5855 + providerInstanceId: modelSelection.instanceId,
5856 + cause,
5857 + }),
5858 + ),
5859 + );
5860 + const targetProviderThread =
5861 + isProviderSwitch && !canResumeAcrossInstances
5862 + ? rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0]
5863 + : activeProviderThread;
5864 + const providerSessionId =
5865 + (canResumeAcrossInstances ? undefined : targetProviderThread?.providerSessionId) ??
5866 + (yield* mapDispatchError(command)(
5867 + providerSessionIdFor({
5868 + adapter,
5869 + providerInstanceId: modelSelection.instanceId,
5870 + threadId: command.threadId,
5871 + }),
5872 + ));
5873 + const existingProviderSession = projection.providerSessions.find(
5874 + (candidate) => candidate.id === providerSessionId,
5875 + );
5876 + const resolvedRuntimePolicy = yield* runtimePolicy
5877 + .resolve({ thread: projection.thread, modelSelection })
5878 + .pipe(
5879 + Effect.mapError(
5880 + (cause) =>
5881 + new OrchestratorDispatchError({
5882 + commandId: command.commandId,
5883 + commandType: command.type,
5884 + cause,
5885 + }),
5886 + ),
5887 + );
5888 +
5889 + const capabilities = yield* adapter.getCapabilities().pipe(
5890 + Effect.mapError(
5891 + (cause) =>
5892 + new OrchestratorProviderAdapterError({
5893 + commandId: command.commandId,
5894 + providerInstanceId: modelSelection.instanceId,
5895 + cause,
5896 + }),
5897 + ),
5898 + );
5899 + const forkExecution =
5900 + pendingForkTransfer === undefined || sourceRun === null
5901 + ? null
5902 + : yield* enforceCommandPolicy(command)(
5903 + commandPolicy.decideForkExecution({
5904 + commandId: command.commandId,
5905 + threadId: command.threadId,
5906 + providerInstanceId: modelSelection.instanceId,
5907 + capabilities,
5908 + sameProvider:
5909 + pendingForkTransfer.sourceProviderInstanceId === modelSelection.instanceId,
5910 + hasStrongNativeSource: sourceProviderThread?.nativeThreadRef?.strength === "strong",
5911 + sourceRunStatus: sourceRun.status,
5912 + fromSpecificTurn: sourceRun !== null,
5913 + }),
5914 + );
5915 + const canResolveForkNatively = forkExecution === "native_fork";
5916 + const requiresPortableFork = forkExecution === "portable_context";
5917 +
5918 + if (canResolveForkNatively) {
5919 + yield* enforceCommandPolicy(command)(
5920 + commandPolicy.ensureNativeFork({
5921 + commandId: command.commandId,
5922 + threadId: command.threadId,
5923 + providerInstanceId: modelSelection.instanceId,
5924 + capabilities,
5925 + fromSpecificTurn: sourceRun !== null,
5926 + }),
5927 + );
5928 + }
5929 +
5930 + const ensuredProviderThread: OrchestrationV2ProviderThread =
5931 + targetProviderThread === undefined
5932 + ? {
5933 + id: idAllocator.derive.providerThread({
5934 + driver: adapter.driver,
5935 + nativeThreadId: `pending:${runId}`,
5936 + }),
5937 + driver: adapter.driver,
5938 + providerInstanceId: modelSelection.instanceId,
5939 + providerSessionId,
5940 + appThreadId: command.threadId,
5941 + ownerNodeId: null,
5942 + nativeThreadRef: null,
5943 + nativeConversationHeadRef: null,
5944 + status: "not_loaded",
5945 + firstRunOrdinal: ordinal,
5946 + lastRunOrdinal: ordinal,
5947 + handoffIds: [],
5948 + forkedFrom:
5949 + canResolveForkNatively && sourceProviderThread !== undefined
5950 + ? {
5951 + providerThreadId: sourceProviderThread.id,
5952 + ...(sourceProviderTurnId === undefined
5953 + ? {}
5954 + : { providerTurnId: sourceProviderTurnId }),
5955 + }
5956 + : null,
5957 + createdAt: now,
5958 + updatedAt: now,
5959 + }
5960 + : {
5961 + ...targetProviderThread,
5962 + providerInstanceId: modelSelection.instanceId,

This file is too large to show in full.

apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts
+34 -36
@@ -136,26 +136,25 @@ export const layerFromProviderInstanceRegistry: Layer.Layer<
136 instances.listInstances.pipe(
137 Effect.map((available) => available.map((instance) => instance.instanceId)),
138 ),
139 - getMetadata: (instanceId) =>
140 - Effect.gen(function* () {
141 - const instance = yield* instances.getInstance(instanceId);
142 - if (instance === undefined) {
143 - return yield* new ProviderAdapterRegistryLookupError({ instanceId });
144 - }
145 - const capabilities = yield* instance.orchestrationAdapter
146 - .getCapabilities()
147 - .pipe(
148 - Effect.mapError(
149 - (cause) => new ProviderAdapterRegistryMetadataError({ instanceId, cause }),
150 - ),
151 - );
152 - return {
153 - driver: instance.driverKind,
154 - continuationKey: instance.continuationIdentity.continuationKey,
155 - enabled: instance.enabled,
156 - capabilities,
157 - };
158 - }),
139 + getMetadata: Effect.fn("ProviderAdapterRegistry.getMetadata")(function* (instanceId) {
140 + const instance = yield* instances.getInstance(instanceId);
141 + if (instance === undefined) {
142 + return yield* new ProviderAdapterRegistryLookupError({ instanceId });
143 + }
144 + const capabilities = yield* instance.orchestrationAdapter
145 + .getCapabilities()
146 + .pipe(
147 + Effect.mapError(
148 + (cause) => new ProviderAdapterRegistryMetadataError({ instanceId, cause }),
149 + ),
150 + );
151 + return {
152 + driver: instance.driverKind,
153 + continuationKey: instance.continuationIdentity.continuationKey,
154 + enabled: instance.enabled,
155 + capabilities,
156 + };
157 + }),
158 });
159 }),
160 );
@@ -167,14 +166,13 @@ function makeRegistry(
166 adapters: ReadonlyArray<ProviderAdapter.ProviderAdapterV2["Service"]>,
167 ): ProviderAdapterRegistryV2Shape {
168 return {
170 - get: (instanceId) =>
171 - Effect.gen(function* () {
172 - const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
173 - if (!adapter) {
174 - return yield* new ProviderAdapterRegistryLookupError({ instanceId });
175 - }
176 - return adapter;
177 - }),
169 + get: Effect.fn("ProviderAdapterRegistry.get")(function* (instanceId) {
170 + const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
171 + if (!adapter) {
172 + return yield* new ProviderAdapterRegistryLookupError({ instanceId });
173 + }
174 + return adapter;
175 + }),
176 list: () => Effect.succeed(adapters.map((adapter) => adapter.instanceId)),
177 };
178 }
@@ -318,20 +316,20 @@ const buildAdaptersFromConfigMap = Effect.fn("ProviderAdapterRegistry.buildAdapt
316 },
317 );
318
321 -export function makeRegistryFromConfigMap<R>(input: {
319 +export const makeRegistryFromConfigMap = Effect.fn(
320 + "ProviderAdapterRegistry.makeRegistryFromConfigMap",
321 +)(function* <R>(input: {
322 readonly drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>;
323 readonly configMap: ProviderInstanceConfigMap;
324 -}): Effect.Effect<
324 +}): Effect.fn.Return<
325 ProviderAdapterRegistryV2Shape,
326 ProviderAdapterRegistryBuildError,
327 R | Scope.Scope
328 > {
329 - return Effect.gen(function* () {
330 - const parentScope = yield* Effect.scope;
331 - const entries = yield* buildAdaptersFromConfigMap({ ...input, parentScope });
332 - return makeRegistry(Array.from(entries.values()).map((entry) => entry.adapter));
333 - });
334 -}
329 + const parentScope = yield* Effect.scope;
330 + const entries = yield* buildAdaptersFromConfigMap({ ...input, parentScope });
331 + return makeRegistry(Array.from(entries.values()).map((entry) => entry.adapter));
332 +});
333
334 export function layerFromDrivers<R>(input: {
335 readonly drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>;
apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
+51 -52
@@ -696,62 +696,61 @@ export const make = Effect.gen(function* () {
696 },
697 );
698
699 - const reconcile = (trigger: "startup" | "shutdown") =>
700 - Effect.gen(function* () {
701 - const continueAfterRestart = yield* settings.getSettings.pipe(
702 - Effect.orElseSucceed(() => null),
699 + const reconcile = Effect.fn("ProviderRuntimeRecoveryService.reconcile")(function* (
700 + trigger: "startup" | "shutdown",
701 + ) {
702 + const continueAfterRestart = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
703 + const threadIds = yield* projections
704 + .getRecoveryThreadIds("runtime")
705 + .pipe(
706 + Effect.mapError(
707 + (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
708 + ),
709 );
704 - const threadIds = yield* projections
705 - .getRecoveryThreadIds("runtime")
706 - .pipe(
707 - Effect.mapError(
708 - (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
709 - ),
710 - );
711 - let terminalizedRuns = 0;
712 - let stoppedSessions = 0;
713 - let closedRequests = 0;
714 - let retiredEffects = 0;
715 - const stoppedThisPass = new Map<string, RecoverySession>();
716 - for (const threadId of threadIds) {
717 - const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
718 - Effect.mapError(
719 - (cause) =>
720 - new ProviderRuntimeRecoveryError({
721 - operation: "read-projections",
722 - threadId,
723 - cause,
724 - }),
725 - ),
726 - );
727 - const enabled =
728 - continueAfterRestart !== null &&
729 - resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
730 - .continueThreadsAfterServerUpdate;
731 - const result = yield* reconcileProjection(projection, trigger, enabled, stoppedThisPass);
732 - for (const session of projection.providerSessions) {
733 - if (session.status !== "stopped" && session.status !== "error") {
734 - stoppedThisPass.set(session.id, session);
735 - }
736 - }
737 - terminalizedRuns += result.terminalizedRuns;
738 - stoppedSessions += result.stoppedSessions;
739 - closedRequests += result.closedRequests;
740 - retiredEffects += result.retiredEffects;
741 - }
742 - const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
710 + let terminalizedRuns = 0;
711 + let stoppedSessions = 0;
712 + let closedRequests = 0;
713 + let retiredEffects = 0;
714 + const stoppedThisPass = new Map<string, RecoverySession>();
715 + for (const threadId of threadIds) {
716 + const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
717 Effect.mapError(
744 - (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
718 + (cause) =>
719 + new ProviderRuntimeRecoveryError({
720 + operation: "read-projections",
721 + threadId,
722 + cause,
723 + }),
724 ),
725 );
747 - return {
748 - terminalizedRuns,
749 - stoppedSessions,
750 - closedRequests,
751 - retiredEffects: retiredEffects + outboxReconciliation.cancelled,
752 - requeuedEffects: outboxReconciliation.requeued,
753 - } satisfies ProviderRuntimeReconciliationSummary;
754 - });
726 + const enabled =
727 + continueAfterRestart !== null &&
728 + resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
729 + .continueThreadsAfterServerUpdate;
730 + const result = yield* reconcileProjection(projection, trigger, enabled, stoppedThisPass);
731 + for (const session of projection.providerSessions) {
732 + if (session.status !== "stopped" && session.status !== "error") {
733 + stoppedThisPass.set(session.id, session);
734 + }
735 + }
736 + terminalizedRuns += result.terminalizedRuns;
737 + stoppedSessions += result.stoppedSessions;
738 + closedRequests += result.closedRequests;
739 + retiredEffects += result.retiredEffects;
740 + }
741 + const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
742 + Effect.mapError(
743 + (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
744 + ),
745 + );
746 + return {
747 + terminalizedRuns,
748 + stoppedSessions,
749 + closedRequests,
750 + retiredEffects: retiredEffects + outboxReconciliation.cancelled,
751 + requeuedEffects: outboxReconciliation.requeued,
752 + } satisfies ProviderRuntimeReconciliationSummary;
753 + });
754
755 const prepareForShutdown = Effect.gen(function* () {
756 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+339 -313
@@ -525,220 +525,227 @@ export const layerWithOptions = (
525 ),
526 );
527
528 - const failSubscribers = (entry: LiveSessionEntry, detail: string) =>
529 - Effect.gen(function* () {
530 - const error = new ProviderAdapter.ProviderAdapterEventStreamError({
531 - driver: entry.runtime.driver,
532 - providerSessionId: entry.runtime.providerSessionId,
533 - cause: detail,
534 - });
535 - const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
536 - yield* Effect.forEach(
537 - subscribers.values(),
538 - (queue) =>
539 - Queue.offer(queue, {
540 - type: "failure",
541 - cause: Cause.fail(error),
542 - }),
543 - { discard: true },
544 - );
528 + const failSubscribers = Effect.fn("ProviderSessionManager.failSubscribers")(function* (
529 + entry: LiveSessionEntry,
530 + detail: string,
531 + ) {
532 + const error = new ProviderAdapter.ProviderAdapterEventStreamError({
533 + driver: entry.runtime.driver,
534 + providerSessionId: entry.runtime.providerSessionId,
535 + cause: detail,
536 });
537 + const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
538 + yield* Effect.forEach(
539 + subscribers.values(),
540 + (queue) =>
541 + Queue.offer(queue, {
542 + type: "failure",
543 + cause: Cause.fail(error),
544 + }),
545 + { discard: true },
546 + );
547 + });
548
549 // Server shutdown interrupts subscribers rather than ending them: a
550 // cleanly ended stream without a terminal fails its run, while an
551 // interrupted one leaves run settlement to restart recovery.
550 - const interruptSubscribers = (entry: LiveSessionEntry) =>
551 - Effect.gen(function* () {
552 + const interruptSubscribers = Effect.fn("ProviderSessionManager.interruptSubscribers")(
553 + function* (entry: LiveSessionEntry) {
554 const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
555 yield* Effect.forEach(
556 subscribers.values(),
557 (queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.interrupt(queue))),
558 { discard: true },
559 );
558 - });
560 + },
561 + );
562
563 // Server shutdown intentionally clears them; a provider-announced Stop
564 // must let consumers drain them before the stream completes.
562 - const endSubscribers = (entry: LiveSessionEntry) =>
563 - Effect.gen(function* () {
564 - const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
565 - yield* Effect.forEach(subscribers.values(), (queue) => Queue.end(queue), {
566 - discard: true,
567 - });
565 + const endSubscribers = Effect.fn("ProviderSessionManager.endSubscribers")(function* (
566 + entry: LiveSessionEntry,
567 + ) {
568 + const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map());
569 + yield* Effect.forEach(subscribers.values(), (queue) => Queue.end(queue), {
570 + discard: true,
571 });
572 + });
573
574 const cancelIdleFiber = (fiber: Fiber.Fiber<void, never> | null) =>
575 fiber === null ? Effect.void : Fiber.interrupt(fiber).pipe(Effect.ignore);
576
573 - const writeProviderSessionEvents = (input: {
577 + const writeProviderSessionEvents = Effect.fn(
578 + "ProviderSessionManager.writeProviderSessionEvents",
579 + )(function* (input: {
580 readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime;
581 readonly threadIds: Iterable<ThreadId>;
582 readonly type: "provider-session.attached" | "provider-session.updated";
583 readonly payload: OrchestrationV2ProviderSession;
578 - }) =>
579 - Effect.gen(function* () {
580 - const now = yield* DateTime.now;
581 - const events = yield* Effect.forEach(input.threadIds, (threadId) =>
582 - Effect.gen(function* () {
583 - return {
584 - id: yield* idAllocator.allocate.event({
585 - threadId,
586 - providerSessionId: input.runtime.providerSessionId,
587 - }),
588 - type: input.type,
584 + }) {
585 + const now = yield* DateTime.now;
586 + const events = yield* Effect.forEach(input.threadIds, (threadId) =>
587 + Effect.gen(function* () {
588 + return {
589 + id: yield* idAllocator.allocate.event({
590 threadId,
590 - driver: input.runtime.driver,
591 - providerInstanceId: input.runtime.instanceId,
592 - occurredAt: now,
593 - payload: input.payload,
594 - } satisfies OrchestrationV2DomainEvent;
595 - }),
596 - );
597 - if (events.length > 0) {
598 - yield* eventSink.write({ events });
599 - }
600 - });
591 + providerSessionId: input.runtime.providerSessionId,
592 + }),
593 + type: input.type,
594 + threadId,
595 + driver: input.runtime.driver,
596 + providerInstanceId: input.runtime.instanceId,
597 + occurredAt: now,
598 + payload: input.payload,
599 + } satisfies OrchestrationV2DomainEvent;
600 + }),
601 + );
602 + if (events.length > 0) {
603 + yield* eventSink.write({ events });
604 + }
605 + });
606
602 - const writeReleasedSessionEvents = (input: {
607 + const writeReleasedSessionEvents = Effect.fn(
608 + "ProviderSessionManager.writeReleasedSessionEvents",
609 + )(function* (input: {
610 readonly entry: LiveSessionEntry;
611 readonly reason: ProviderSessionReleaseReason;
612 readonly detail?: string;
606 - }) =>
607 - Effect.gen(function* () {
608 - const now = yield* DateTime.now;
609 - const payload: OrchestrationV2ProviderSession = {
610 - ...input.entry.runtime.providerSession,
611 - status: releaseStatusFor(input.reason),
612 - updatedAt: now,
613 - lastError:
614 - input.reason === "runtime_error"
615 - ? (input.detail ?? "Provider runtime failed.")
616 - : null,
617 - };
618 - yield* writeProviderSessionEvents({
619 - runtime: input.entry.runtime,
620 - threadIds: input.entry.attachedThreadIds,
621 - type: "provider-session.updated",
622 - payload,
623 - });
613 + }) {
614 + const now = yield* DateTime.now;
615 + const payload: OrchestrationV2ProviderSession = {
616 + ...input.entry.runtime.providerSession,
617 + status: releaseStatusFor(input.reason),
618 + updatedAt: now,
619 + lastError:
620 + input.reason === "runtime_error" ? (input.detail ?? "Provider runtime failed.") : null,
621 + };
622 + yield* writeProviderSessionEvents({
623 + runtime: input.entry.runtime,
624 + threadIds: input.entry.attachedThreadIds,
625 + type: "provider-session.updated",
626 + payload,
627 });
628 + });
629
626 - const writeReleasedRuntimeRequestEvents = (input: {
630 + const writeReleasedRuntimeRequestEvents = Effect.fn(
631 + "ProviderSessionManager.writeReleasedRuntimeRequestEvents",
632 + )(function* (input: {
633 readonly entry: LiveSessionEntry;
634 readonly reason: ProviderSessionReleaseReason;
635 readonly releasedAt: DateTime.Utc;
630 - }) =>
631 - Effect.gen(function* () {
632 - const providerSessionId = input.entry.runtime.providerSessionId;
633 - const now = yield* DateTime.now;
634 - const status = releasedRuntimeRequestStatusFor(input.reason);
635 - const reason =
636 - input.reason === "runtime_error"
637 - ? "Provider session failed before this runtime request was resolved."
638 - : "Provider session was closed before this runtime request was resolved.";
639 -
640 - const events: Array<OrchestrationV2DomainEvent> = [];
641 - for (const threadId of input.entry.attachedThreadIds) {
642 - const projection = yield* projectionStore.getThreadRecords(
636 + }) {
637 + const providerSessionId = input.entry.runtime.providerSessionId;
638 + const now = yield* DateTime.now;
639 + const status = releasedRuntimeRequestStatusFor(input.reason);
640 + const reason =
641 + input.reason === "runtime_error"
642 + ? "Provider session failed before this runtime request was resolved."
643 + : "Provider session was closed before this runtime request was resolved.";
644 +
645 + const events: Array<OrchestrationV2DomainEvent> = [];
646 + for (const threadId of input.entry.attachedThreadIds) {
647 + const projection = yield* projectionStore.getThreadRecords(
648 + threadId,
649 + ["runtimeRequests", "nodes", "turnItems"],
650 + { turnItemTypes: ["approval_request", "user_input_request"] },
651 + );
652 + const releasedRequests = projection.runtimeRequests.filter(
653 + (request) =>
654 + request.status === "pending" &&
655 + request.responseCapability.type === "live" &&
656 + request.responseCapability.providerSessionId === providerSessionId &&
657 + DateTime.isLessThanOrEqualTo(request.createdAt, input.releasedAt),
658 + );
659 +
660 + for (const request of releasedRequests) {
661 + events.push({
662 + id: yield* idAllocator.allocate.event({
663 + threadId,
664 + providerSessionId,
665 + }),
666 + type: "runtime-request.updated",
667 threadId,
644 - ["runtimeRequests", "nodes", "turnItems"],
645 - { turnItemTypes: ["approval_request", "user_input_request"] },
646 - );
647 - const releasedRequests = projection.runtimeRequests.filter(
648 - (request) =>
649 - request.status === "pending" &&
650 - request.responseCapability.type === "live" &&
651 - request.responseCapability.providerSessionId === providerSessionId &&
652 - DateTime.isLessThanOrEqualTo(request.createdAt, input.releasedAt),
653 - );
668 + nodeId: request.nodeId,
669 + driver: input.entry.runtime.driver,
670 + occurredAt: now,
671 + payload: {
672 + ...request,
673 + status,
674 + responseCapability: {
675 + type: "not_resumable",
676 + reason,
677 + },
678 + resolvedAt: now,
679 + },
680 + });
681
655 - for (const request of releasedRequests) {
682 + const requestNode = projection.nodes.find((node) => node.id === request.nodeId);
683 + if (requestNode !== undefined) {
684 events.push({
685 id: yield* idAllocator.allocate.event({
686 threadId,
687 providerSessionId,
688 }),
661 - type: "runtime-request.updated",
689 + type: "node.updated",
690 threadId,
663 - nodeId: request.nodeId,
691 + ...(requestNode.runId === null ? {} : { runId: requestNode.runId }),
692 + nodeId: requestNode.id,
693 driver: input.entry.runtime.driver,
694 occurredAt: now,
695 payload: {
667 - ...request,
668 - status,
669 - responseCapability: {
670 - type: "not_resumable",
671 - reason,
672 - },
673 - resolvedAt: now,
696 + ...requestNode,
697 + status: input.reason === "runtime_error" ? "failed" : "cancelled",
698 + completedAt: now,
699 },
700 });
701 + }
702
677 - const requestNode = projection.nodes.find((node) => node.id === request.nodeId);
678 - if (requestNode !== undefined) {
679 - events.push({
680 - id: yield* idAllocator.allocate.event({
681 - threadId,
682 - providerSessionId,
683 - }),
684 - type: "node.updated",
685 - threadId,
686 - ...(requestNode.runId === null ? {} : { runId: requestNode.runId }),
687 - nodeId: requestNode.id,
688 - driver: input.entry.runtime.driver,
689 - occurredAt: now,
690 - payload: {
691 - ...requestNode,
692 - status: input.reason === "runtime_error" ? "failed" : "cancelled",
693 - completedAt: now,
694 - },
695 - });
696 - }
697 -
698 - const turnItem = projection.turnItems.find(
699 - (item) =>
700 - (item.type === "approval_request" || item.type === "user_input_request") &&
701 - item.requestId === request.id,
702 - );
703 - if (turnItem !== undefined) {
704 - events.push({
705 - id: yield* idAllocator.allocate.event({
706 - threadId,
707 - providerSessionId,
708 - }),
709 - type: "turn-item.updated",
703 + const turnItem = projection.turnItems.find(
704 + (item) =>
705 + (item.type === "approval_request" || item.type === "user_input_request") &&
706 + item.requestId === request.id,
707 + );
708 + if (turnItem !== undefined) {
709 + events.push({
710 + id: yield* idAllocator.allocate.event({
711 threadId,
711 - ...(turnItem.runId === null ? {} : { runId: turnItem.runId }),
712 - ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
713 - driver: input.entry.runtime.driver,
714 - occurredAt: now,
715 - payload: {
716 - ...turnItem,
717 - status: input.reason === "runtime_error" ? "failed" : "cancelled",
718 - completedAt: now,
719 - updatedAt: now,
720 - },
721 - });
722 - }
712 + providerSessionId,
713 + }),
714 + type: "turn-item.updated",
715 + threadId,
716 + ...(turnItem.runId === null ? {} : { runId: turnItem.runId }),
717 + ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
718 + driver: input.entry.runtime.driver,
719 + occurredAt: now,
720 + payload: {
721 + ...turnItem,
722 + status: input.reason === "runtime_error" ? "failed" : "cancelled",
723 + completedAt: now,
724 + updatedAt: now,
725 + },
726 + });
727 }
728 }
729 + }
730
726 - if (events.length > 0) {
727 - yield* eventSink.write({ events });
728 - }
729 - });
731 + if (events.length > 0) {
732 + yield* eventSink.write({ events });
733 + }
734 + });
735
736 // Read as soon as the session leaves the live map: after that, a
737 // replacement session with the same id can open and report tasks of its
738 // own on the same provider threads. OpenCode's background subagents run
739 // on a server shared by its sessions and can outlive this one, so their
740 // roster stays.
736 - const readReleasedBackgroundTasks = (input: {
737 - readonly entry: LiveSessionEntry;
738 - readonly reason: ProviderSessionReleaseReason;
739 - readonly detachedThreadId?: ThreadId;
740 - }) =>
741 - Effect.gen(function* () {
741 + const readReleasedBackgroundTasks = Effect.fn(
742 + "ProviderSessionManager.readReleasedBackgroundTasks",
743 + )(
744 + function* (input: {
745 + readonly entry: LiveSessionEntry;
746 + readonly reason: ProviderSessionReleaseReason;
747 + readonly detachedThreadId?: ThreadId;
748 + }) {
749 if (
750 input.reason === "server_shutdown" ||
751 input.entry.runtime.backgroundTasksEndWithProcess !== true
@@ -767,14 +774,17 @@ export const layerWithOptions = (
774 }
775 }
776 return released;
770 - }).pipe(
771 - Effect.catchCause((cause) =>
772 - Effect.logWarning("orchestration-v2.provider-session-release-roster-read-failed", {
773 - providerSessionId: input.entry.runtime.providerSessionId,
774 - cause,
775 - }).pipe(Effect.as([])),
777 + },
778 + (effect, input) =>
779 + effect.pipe(
780 + Effect.catchCause((cause) =>
781 + Effect.logWarning("orchestration-v2.provider-session-release-roster-read-failed", {
782 + providerSessionId: input.entry.runtime.providerSessionId,
783 + cause,
784 + }).pipe(Effect.as([])),
785 + ),
786 ),
777 - );
787 + );
788 type ReleasedBackgroundTasks = Effect.Success<
789 ReturnType<typeof readReleasedBackgroundTasks>
790 >[number];
@@ -907,11 +917,11 @@ export const layerWithOptions = (
917 // A request the event pump is persisting for this runtime lands before
918 // the cutoff, and once the entry is gone the pump persists no more for
919 // it.
910 - const removeLiveEntry = (input: {
911 - readonly providerSessionId: ProviderSessionId;
912 - readonly onlyIfIdleGeneration?: number;
913 - }): Effect.Effect<readonly [Option.Option<LiveSessionEntry>, DateTime.Utc]> =>
914 - Effect.gen(function* () {
920 + const removeLiveEntry = Effect.fn("ProviderSessionManager.removeLiveEntry")(
921 + function* (input: {
922 + readonly providerSessionId: ProviderSessionId;
923 + readonly onlyIfIdleGeneration?: number;
924 + }): Effect.fn.Return<readonly [Option.Option<LiveSessionEntry>, DateTime.Utc]> {
925 const key = sessionKey(input.providerSessionId);
926 const candidate = (yield* Ref.get(sessions)).get(key);
927 if (candidate === undefined) {
@@ -942,44 +952,44 @@ export const layerWithOptions = (
952 outcome === "removed" ? Option.some(candidate) : Option.none<LiveSessionEntry>(),
953 releasedAt,
954 ] as const;
945 - });
955 + },
956 + );
957
958 // Scope close can wedge on a misbehaving adapter finalizer (e.g. a
959 // provider process that never yields its message stream).
949 - const closeScopeWithin = (
960 + const closeScopeWithin = Effect.fn("ProviderSessionManager.closeScopeWithin")(function* (
961 scope: Scope.Closeable,
962 annotations: { readonly providerSessionId?: ProviderSessionId; readonly reason: string },
952 - ) =>
953 - Effect.gen(function* () {
954 - const closeFiber = yield* Scope.close(scope, Exit.void).pipe(
955 - Effect.exit,
956 - Effect.forkDetach({ startImmediately: true }),
957 - );
958 - const closeExit = yield* Fiber.join(closeFiber).pipe(
959 - Effect.timeoutOption(RELEASE_SCOPE_CLOSE_TIMEOUT_MS),
963 + ) {
964 + const closeFiber = yield* Scope.close(scope, Exit.void).pipe(
965 + Effect.exit,
966 + Effect.forkDetach({ startImmediately: true }),
967 + );
968 + const closeExit = yield* Fiber.join(closeFiber).pipe(
969 + Effect.timeoutOption(RELEASE_SCOPE_CLOSE_TIMEOUT_MS),
970 + );
971 + if (Option.isNone(closeExit)) {
972 + yield* Effect.logWarning("orchestration-v2.provider-session-scope-close-timeout", {
973 + ...annotations,
974 + timeoutMs: RELEASE_SCOPE_CLOSE_TIMEOUT_MS,
975 + });
976 + yield* Fiber.join(closeFiber).pipe(
977 + Effect.flatMap((exit) =>
978 + Exit.isFailure(exit)
979 + ? Effect.logWarning("orchestration-v2.provider-session-scope-close-failed", {
980 + ...annotations,
981 + cause: exit.cause,
982 + })
983 + : Effect.logInfo(
984 + "orchestration-v2.provider-session-scope-close-completed-late",
985 + annotations,
986 + ),
987 + ),
988 + Effect.forkDetach,
989 );
961 - if (Option.isNone(closeExit)) {
962 - yield* Effect.logWarning("orchestration-v2.provider-session-scope-close-timeout", {
963 - ...annotations,
964 - timeoutMs: RELEASE_SCOPE_CLOSE_TIMEOUT_MS,
965 - });
966 - yield* Fiber.join(closeFiber).pipe(
967 - Effect.flatMap((exit) =>
968 - Exit.isFailure(exit)
969 - ? Effect.logWarning("orchestration-v2.provider-session-scope-close-failed", {
970 - ...annotations,
971 - cause: exit.cause,
972 - })
973 - : Effect.logInfo(
974 - "orchestration-v2.provider-session-scope-close-completed-late",
975 - annotations,
976 - ),
977 - ),
978 - Effect.forkDetach,
979 - );
980 - }
981 - return closeExit;
982 - });
990 + }
991 + return closeExit;
992 + });
993
994 const releaseEntry = (input: {
995 readonly providerSessionId: ProviderSessionId;
@@ -1096,11 +1106,11 @@ export const layerWithOptions = (
1106 ),
1107 );
1108
1099 - const releaseIfStillIdle = (input: {
1100 - readonly providerSessionId: ProviderSessionId;
1101 - readonly generation: number;
1102 - }): Effect.Effect<void> =>
1103 - Effect.gen(function* () {
1109 + const releaseIfStillIdle = Effect.fn("ProviderSessionManager.releaseIfStillIdle")(
1110 + function* (input: {
1111 + readonly providerSessionId: ProviderSessionId;
1112 + readonly generation: number;
1113 + }): Effect.fn.Return<void> {
1114 const current = yield* Ref.get(sessions);
1115 const key = sessionKey(input.providerSessionId);
1116 const entry = current.get(key);
@@ -1173,7 +1183,8 @@ export const layerWithOptions = (
1183 }),
1184 ),
1185 );
1176 - });
1186 + },
1187 + );
1188
1189 const withActivityError = <A, E, R>(
1190 providerSessionId: ProviderSessionId,
@@ -1192,42 +1203,42 @@ export const layerWithOptions = (
1203
1204 // Provider activity restarts the pin budget, so background work that keeps
1205 // reporting progress (a long Claude workflow) is never cut off; only work
1195 - // that went silent for maxIdlePinMs is released.
1196 - const scheduleIdleReleaseInternal = (
1206 + // that went silent for maxIdlePinMs is released. This runs for every
1207 + // provider event, so keep it untraced.
1208 + const scheduleIdleReleaseInternal = Effect.fnUntraced(function* (
1209 providerSessionId: ProviderSessionId,
1210 options?: { readonly providerActivity?: boolean },
1199 - ) =>
1200 - Effect.gen(function* () {
1201 - const key = sessionKey(providerSessionId);
1202 - const current = yield* Ref.get(sessions);
1203 - const entry = current.get(key);
1204 - if (entry === undefined || entry.busyTurns.size > 0) {
1205 - return;
1206 - }
1211 + ) {
1212 + const key = sessionKey(providerSessionId);
1213 + const current = yield* Ref.get(sessions);
1214 + const entry = current.get(key);
1215 + if (entry === undefined || entry.busyTurns.size > 0) {
1216 + return;
1217 + }
1218
1208 - yield* cancelIdleFiber(entry.idleFiber);
1209 - const generation = entry.idleGeneration + 1;
1210 - const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe(
1211 - Effect.andThen(releaseIfStillIdle({ providerSessionId, generation })),
1212 - Effect.forkIn(layerScope),
1213 - );
1214 - const lastActivityAtMs = yield* Clock.currentTimeMillis;
1215 - yield* Ref.update(sessions, (latest) => {
1216 - const latestEntry = latest.get(key);
1217 - if (latestEntry === undefined || latestEntry.busyTurns.size > 0) {
1218 - return latest;
1219 - }
1220 - const updated = new Map(latest);
1221 - updated.set(key, {
1222 - ...latestEntry,
1223 - idleGeneration: generation,
1224 - idleFiber,
1225 - lastActivityAtMs,
1226 - ...(options?.providerActivity === true ? { pinnedSinceMs: null } : {}),
1227 - });
1228 - return updated;
1219 + yield* cancelIdleFiber(entry.idleFiber);
1220 + const generation = entry.idleGeneration + 1;
1221 + const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe(
1222 + Effect.andThen(releaseIfStillIdle({ providerSessionId, generation })),
1223 + Effect.forkIn(layerScope),
1224 + );
1225 + const lastActivityAtMs = yield* Clock.currentTimeMillis;
1226 + yield* Ref.update(sessions, (latest) => {
1227 + const latestEntry = latest.get(key);
1228 + if (latestEntry === undefined || latestEntry.busyTurns.size > 0) {
1229 + return latest;
1230 + }
1231 + const updated = new Map(latest);
1232 + updated.set(key, {
1233 + ...latestEntry,
1234 + idleGeneration: generation,
1235 + idleFiber,
1236 + lastActivityAtMs,
1237 + ...(options?.providerActivity === true ? { pinnedSinceMs: null } : {}),
1238 });
1239 + return updated;
1240 });
1241 + });
1242
1243 const scheduleIdleRelease = (providerSessionId: ProviderSessionId) =>
1244 withActivityError(providerSessionId, scheduleIdleReleaseInternal(providerSessionId));
@@ -1518,12 +1529,12 @@ export const layerWithOptions = (
1529 * cannot land between a resume that found the thread loaded and the turn
1530 * that relies on it.
1531 */
1521 - const holdThreadLoaded = (input: {
1522 - readonly providerSessionId: ProviderSessionId;
1523 - readonly threadId: ThreadId;
1524 - readonly providerThread: OrchestrationV2ProviderThread;
1525 - }) =>
1526 - Effect.gen(function* () {
1532 + const holdThreadLoaded = Effect.fn("ProviderSessionManager.holdThreadLoaded")(
1533 + function* (input: {
1534 + readonly providerSessionId: ProviderSessionId;
1535 + readonly threadId: ThreadId;
1536 + readonly providerThread: OrchestrationV2ProviderThread;
1537 + }) {
1538 const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId));
1539 if (
1540 entry === undefined ||
@@ -1543,13 +1554,11 @@ export const layerWithOptions = (
1554 }),
1555 );
1556 yield* cancelIdleFiber(previous?.fiber ?? null);
1546 - });
1557 + },
1558 + );
1559
1548 - const scheduleThreadUnload = (
1549 - providerSessionId: ProviderSessionId,
1550 - providerThreadId: ProviderThreadId,
1551 - ) =>
1552 - Effect.gen(function* () {
1560 + const scheduleThreadUnload = Effect.fn("ProviderSessionManager.scheduleThreadUnload")(
1561 + function* (providerSessionId: ProviderSessionId, providerThreadId: ProviderThreadId) {
1562 const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId));
1563 if (entry === undefined || hasBusyTurn(entry, providerThreadId)) return;
1564 const tracked = Array.from(entry.idleThreadUnloads).find(
@@ -1570,14 +1579,15 @@ export const layerWithOptions = (
1579 yield* cancelIdleFiber(
1580 previous?.generation === pending.generation ? previous.fiber : fiber,
1581 );
1573 - });
1582 + },
1583 + );
1584
1575 - const unloadIdleThread = (input: {
1576 - readonly providerSessionId: ProviderSessionId;
1577 - readonly threadId: ThreadId;
1578 - readonly generation: number;
1579 - }): Effect.Effect<void> =>
1580 - Effect.gen(function* () {
1585 + const unloadIdleThread = Effect.fn("ProviderSessionManager.unloadIdleThread")(
1586 + function* (input: {
1587 + readonly providerSessionId: ProviderSessionId;
1588 + readonly threadId: ThreadId;
1589 + readonly generation: number;
1590 + }): Effect.fn.Return<void> {
1591 const outcome = yield* threadAttachment.withLock(
1592 threadAttachmentKey(input),
1593 Effect.gen(function* () {
@@ -1647,7 +1657,8 @@ export const layerWithOptions = (
1657 yield* Effect.sleep(Duration.millis(idleTimeoutMs));
1658 return yield* unloadIdleThread(input);
1659 }
1650 - });
1660 + },
1661 + );
1662
1663 const observeActivity = (
1664 providerSessionId: ProviderSessionId,
@@ -1662,12 +1673,12 @@ export const layerWithOptions = (
1673 ),
1674 );
1675
1665 - const makeEventSubscription = (
1666 - subscribers: Ref.Ref<
1667 - ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
1668 - >,
1669 - ): Effect.Effect<ProviderAdapter.ProviderAdapterV2EventSubscription> =>
1670 - Effect.gen(function* () {
1676 + const makeEventSubscription = Effect.fn("ProviderSessionManager.makeEventSubscription")(
1677 + function* (
1678 + subscribers: Ref.Ref<
1679 + ReadonlyMap<number, Queue.Queue<ProviderSessionEventSignal, Cause.Done>>
1680 + >,
1681 + ): Effect.fn.Return<ProviderAdapter.ProviderAdapterV2EventSubscription> {
1682 const queue = yield* Queue.unbounded<ProviderSessionEventSignal, Cause.Done>();
1683 const subscriberId = yield* Ref.getAndUpdate(nextSubscriberId, (value) => value + 1);
1684 yield* Ref.update(subscribers, (current) => {
@@ -1698,7 +1709,8 @@ export const layerWithOptions = (
1709 Stream.ensuring(close),
1710 );
1711 return { events, close } satisfies ProviderAdapter.ProviderAdapterV2EventSubscription;
1701 - });
1712 + },
1713 + );
1714
1715 const decorateRuntime = (
1716 runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
@@ -1880,14 +1892,16 @@ export const layerWithOptions = (
1892 };
1893 };
1894
1883 - const persistProviderSessionUpdate = (
1884 - entry: LiveSessionEntry,
1885 - event: Extract<
1886 - ProviderAdapter.ProviderAdapterV2Event,
1887 - { readonly type: "provider_session.updated" }
1888 - >,
1889 - ) =>
1890 - Effect.gen(function* () {
1895 + const persistProviderSessionUpdate = Effect.fn(
1896 + "ProviderSessionManager.persistProviderSessionUpdate",
1897 + )(
1898 + function* (
1899 + entry: LiveSessionEntry,
1900 + event: Extract<
1901 + ProviderAdapter.ProviderAdapterV2Event,
1902 + { readonly type: "provider_session.updated" }
1903 + >,
1904 + ) {
1905 const current = (yield* Ref.get(sessions)).get(
1906 sessionKey(entry.runtime.providerSessionId),
1907 );
@@ -1900,14 +1914,17 @@ export const layerWithOptions = (
1914 type: "provider-session.updated",
1915 payload: event.providerSession,
1916 });
1903 - }).pipe(
1904 - Effect.catchCause((cause) =>
1905 - Effect.logWarning("orchestration-v2.driver-session.status-persist-failed", {
1906 - providerSessionId: entry.runtime.providerSessionId,
1907 - cause,
1908 - }),
1917 + },
1918 + (effect, entry, _event) =>
1919 + effect.pipe(
1920 + Effect.catchCause((cause) =>
1921 + Effect.logWarning("orchestration-v2.driver-session.status-persist-failed", {
1922 + providerSessionId: entry.runtime.providerSessionId,
1923 + cause,
1924 + }),
1925 + ),
1926 ),
1910 - );
1927 + );
1928
1929 const startEventPump = (entry: LiveSessionEntry) => {
1930 let stoppedByProvider = false;
@@ -2248,23 +2265,26 @@ export const layerWithOptions = (
2265 Ref.get(sessions).pipe(
2266 Effect.map((current) => current.has(sessionKey(providerSessionId))),
2267 ),
2251 - get: (providerSessionId) =>
2252 - Effect.gen(function* () {
2268 + get: Effect.fn("ProviderSessionManager.get")(
2269 + function* (providerSessionId) {
2270 const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId));
2271 if (entry === undefined) {
2272 return Option.none<ProviderAdapter.ProviderAdapterV2SessionRuntime>();
2273 }
2274 yield* touchActivity(providerSessionId);
2275 return Option.some(entry.exposedRuntime);
2259 - }).pipe(
2260 - Effect.mapError(
2261 - (cause) =>
2262 - new ProviderSessionLookupError({
2263 - providerSessionId,
2264 - cause,
2265 - }),
2276 + },
2277 + (effect, providerSessionId) =>
2278 + effect.pipe(
2279 + Effect.mapError(
2280 + (cause) =>
2281 + new ProviderSessionLookupError({
2282 + providerSessionId,
2283 + cause,
2284 + }),
2285 + ),
2286 ),
2267 - ),
2287 + ),
2288 close: (providerSessionId) =>
2289 releaseEntry({ providerSessionId, reason: "manual_shutdown" }).pipe(
2290 Effect.mapError(
@@ -2275,8 +2295,8 @@ export const layerWithOptions = (
2295 }),
2296 ),
2297 ),
2278 - closeInstance: (instanceId) =>
2279 - Effect.gen(function* () {
2298 + closeInstance: Effect.fn("ProviderSessionManager.closeInstance")(
2299 + function* (instanceId) {
2300 const active = [...(yield* Ref.get(sessions)).values()].filter(
2301 (entry) => entry.runtime.instanceId === instanceId,
2302 );
@@ -2294,20 +2314,23 @@ export const layerWithOptions = (
2314 if (failure !== undefined && Exit.isFailure(failure)) {
2315 return yield* Effect.failCause(failure.cause);
2316 }
2297 - }).pipe(
2298 - Effect.mapError(
2299 - (cause) =>
2300 - new ProviderSessionCloseError({
2301 - providerSessionId: ProviderSessionId.make(
2302 - `provider-session:provider-instance:${instanceId}`,
2303 - ),
2304 - cause,
2305 - }),
2317 + },
2318 + (effect, instanceId) =>
2319 + effect.pipe(
2320 + Effect.mapError(
2321 + (cause) =>
2322 + new ProviderSessionCloseError({
2323 + providerSessionId: ProviderSessionId.make(
2324 + `provider-session:provider-instance:${instanceId}`,
2325 + ),
2326 + cause,
2327 + }),
2328 + ),
2329 ),
2307 - ),
2330 + ),
2331 release: releaseEntry,
2309 - detach: (input) =>
2310 - Effect.gen(function* () {
2332 + detach: Effect.fn("ProviderSessionManager.detach")(
2333 + function* (input) {
2334 const key = sessionKey(input.providerSessionId);
2335 const currentEntry = (yield* Ref.get(sessions)).get(key);
2336 let detachedProviderThreads: ReadonlyArray<OrchestrationV2ProviderThread> = [];
@@ -2461,17 +2484,20 @@ export const layerWithOptions = (
2484 );
2485 }
2486 yield* scheduleIdleRelease(input.providerSessionId);
2464 - }).pipe(
2465 - Effect.catchCause((cause) =>
2466 - Effect.fail(
2467 - new ProviderSessionReleaseError({
2468 - providerSessionId: input.providerSessionId,
2469 - reason: "manual_shutdown",
2470 - cause,
2471 - }),
2487 + },
2488 + (effect, input) =>
2489 + effect.pipe(
2490 + Effect.catchCause((cause) =>
2491 + Effect.fail(
2492 + new ProviderSessionReleaseError({
2493 + providerSessionId: input.providerSessionId,
2494 + reason: "manual_shutdown",
2495 + cause,
2496 + }),
2497 + ),
2498 ),
2499 ),
2474 - ),
2500 + ),
2501 } satisfies ProviderSessionManagerV2Shape);
2502 }),
2503 );
apps/server/src/orchestration-v2/ProviderSwitchService.ts
+14 -11
@@ -64,8 +64,8 @@ export const layer: Layer.Layer<
64 Effect.gen(function* () {
65 const adapters = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
66 return ProviderSwitchServiceV2.of({
67 - plan: ({ projection, targetModelSelection }) =>
68 - Effect.gen(function* () {
67 + plan: Effect.fn("ProviderSwitchService.plan")(
68 + function* ({ projection, targetModelSelection }) {
69 const current = projection.thread.modelSelection;
70 const instanceChanged = current.instanceId !== targetModelSelection.instanceId;
71 const modelChanged = current.model !== targetModelSelection.model;
@@ -198,16 +198,19 @@ export const layer: Layer.Layer<
198 releaseProviderSessionIds,
199 transition,
200 };
201 - }).pipe(
202 - Effect.mapError(
203 - (cause) =>
204 - new ProviderSwitchPlanError({
205 - threadId: projection.thread.id,
206 - targetProviderInstanceId: targetModelSelection.instanceId,
207 - cause,
208 - }),
201 + },
202 + (effect, { projection, targetModelSelection }) =>
203 + effect.pipe(
204 + Effect.mapError(
205 + (cause) =>
206 + new ProviderSwitchPlanError({
207 + threadId: projection.thread.id,
208 + targetProviderInstanceId: targetModelSelection.instanceId,
209 + cause,
210 + }),
211 + ),
212 ),
210 - ),
213 + ),
214 });
215 }),
216 );
apps/server/src/orchestration-v2/ProviderTurnControlService.ts
+113 -106
@@ -91,7 +91,7 @@ export const layer: Layer.Layer<
91 const projections = yield* ProjectionStore.ProjectionStoreV2;
92 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
93
94 - const load = (input: {
94 + const load = Effect.fn("ProviderTurnControlService.load")(function* (input: {
95 readonly threadId: ThreadId;
96 readonly providerSessionId: ProviderSessionId;
97 readonly replacementProviderSessionId?: ProviderSessionId;
@@ -99,46 +99,68 @@ export const layer: Layer.Layer<
99 readonly providerTurnId: ProviderTurnId;
100 readonly operation: "interrupt" | "restart" | "steer";
101 readonly messageId?: MessageId;
102 - }) =>
103 - Effect.gen(function* () {
104 - const context = yield* projections.getProviderControlContext(input.threadId, input);
105 - const { providerThread, providerTurn } = context;
106 - const targetsRecordedSession =
107 - providerThread?.providerSessionId === input.providerSessionId;
108 - const targetsCommittedReplacement =
109 - input.operation === "restart" &&
110 - input.replacementProviderSessionId !== undefined &&
111 - providerThread?.providerSessionId === input.replacementProviderSessionId;
112 - if (
113 - providerThread === undefined ||
114 - providerTurn === undefined ||
115 - (!targetsRecordedSession && !targetsCommittedReplacement) ||
116 - providerTurn.providerThreadId !== providerThread.id
117 - ) {
102 + }) {
103 + const context = yield* projections.getProviderControlContext(input.threadId, input);
104 + const { providerThread, providerTurn } = context;
105 + const targetsRecordedSession = providerThread?.providerSessionId === input.providerSessionId;
106 + const targetsCommittedReplacement =
107 + input.operation === "restart" &&
108 + input.replacementProviderSessionId !== undefined &&
109 + providerThread?.providerSessionId === input.replacementProviderSessionId;
110 + if (
111 + providerThread === undefined ||
112 + providerTurn === undefined ||
113 + (!targetsRecordedSession && !targetsCommittedReplacement) ||
114 + providerTurn.providerThreadId !== providerThread.id
115 + ) {
116 + return yield* new ProviderTurnControlError({
117 + threadId: input.threadId,
118 + operation: input.operation,
119 + providerTurnId: input.providerTurnId,
120 + cause: "The recorded provider execution target is no longer valid.",
121 + });
122 + }
123 + // A restart-session command commits the replacement binding before its
124 + // process-bound effect runs. The old live runtime must still receive
125 + // the interrupt, but only when the projection matches the exact
126 + // replacement captured by that same durable effect.
127 + const interruptProviderThread = targetsRecordedSession
128 + ? providerThread
129 + : { ...providerThread, providerSessionId: input.providerSessionId };
130 + if (providerTurn.status !== "running") {
131 + if (input.operation === "steer") {
132 return yield* new ProviderTurnControlError({
133 threadId: input.threadId,
120 - operation: input.operation,
134 + operation: "steer",
135 providerTurnId: input.providerTurnId,
122 - cause: "The recorded provider execution target is no longer valid.",
136 + turnCompleted: providerTurn.status === "completed",
137 + cause: "The provider turn ended before the steering message was delivered.",
138 });
139 }
125 - // A restart-session command commits the replacement binding before its
126 - // process-bound effect runs. The old live runtime must still receive
127 - // the interrupt, but only when the projection matches the exact
128 - // replacement captured by that same durable effect.
129 - const interruptProviderThread = targetsRecordedSession
130 - ? providerThread
131 - : { ...providerThread, providerSessionId: input.providerSessionId };
132 - if (providerTurn.status !== "running") {
133 - if (input.operation === "steer") {
134 - return yield* new ProviderTurnControlError({
140 + return {
141 + context,
142 + providerThread: interruptProviderThread,
143 + providerTurn,
144 + session: Option.none(),
145 + };
146 + }
147 + const session = yield* sessions.get(input.providerSessionId);
148 + if (Option.isNone(session)) {
149 + // Interrupt/restart against a already-released session must not fail
150 + // the durable effect (and retry 5x). The turn may still look running
151 + // in projection until recovery/finalization; there is no live adapter
152 + // to interrupt.
153 + if (input.operation === "interrupt" || input.operation === "restart") {
154 + yield* Effect.logWarning(
155 + "Provider interrupt/restart found no live session; treating as already stopped",
156 + {
157 threadId: input.threadId,
136 - operation: "steer",
158 + operation: input.operation,
159 + providerSessionId: input.providerSessionId,
160 providerTurnId: input.providerTurnId,
138 - turnCompleted: providerTurn.status === "completed",
139 - cause: "The provider turn ended before the steering message was delivered.",
140 - });
141 - }
161 + providerTurnStatus: providerTurn.status,
162 + },
163 + );
164 return {
165 context,
166 providerThread: interruptProviderThread,
@@ -146,43 +168,19 @@ export const layer: Layer.Layer<
168 session: Option.none(),
169 };
170 }
149 - const session = yield* sessions.get(input.providerSessionId);
150 - if (Option.isNone(session)) {
151 - // Interrupt/restart against a already-released session must not fail
152 - // the durable effect (and retry 5x). The turn may still look running
153 - // in projection until recovery/finalization; there is no live adapter
154 - // to interrupt.
155 - if (input.operation === "interrupt" || input.operation === "restart") {
156 - yield* Effect.logWarning(
157 - "Provider interrupt/restart found no live session; treating as already stopped",
158 - {
159 - threadId: input.threadId,
160 - operation: input.operation,
161 - providerSessionId: input.providerSessionId,
162 - providerTurnId: input.providerTurnId,
163 - providerTurnStatus: providerTurn.status,
164 - },
165 - );
166 - return {
167 - context,
168 - providerThread: interruptProviderThread,
169 - providerTurn,
170 - session: Option.none(),
171 - };
172 - }
173 - return yield* new ProviderTurnControlError({
174 - threadId: input.threadId,
175 - operation: input.operation,
176 - providerTurnId: input.providerTurnId,
177 - cause: `Provider session ${input.providerSessionId} is not active.`,
178 - });
179 - }
180 - return { context, providerThread: interruptProviderThread, providerTurn, session };
181 - });
171 + return yield* new ProviderTurnControlError({
172 + threadId: input.threadId,
173 + operation: input.operation,
174 + providerTurnId: input.providerTurnId,
175 + cause: `Provider session ${input.providerSessionId} is not active.`,
176 + });
177 + }
178 + return { context, providerThread: interruptProviderThread, providerTurn, session };
179 + });
180
181 return ProviderTurnControlServiceV2.of({
184 - interrupt: (input) =>
185 - Effect.gen(function* () {
182 + interrupt: Effect.fn("ProviderTurnControlService.interrupt")(
183 + function* (input) {
184 const loaded = yield* load({ ...input, operation: "interrupt" });
185 const session = Option.isSome(loaded.session)
186 ? loaded.session
@@ -241,20 +239,23 @@ export const layer: Layer.Layer<
239 yield* Effect.sleep("10 millis");
240 }
241 }).pipe(Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()));
244 - }).pipe(
245 - Effect.mapError((cause) =>
246 - isProviderTurnControlError(cause)
247 - ? cause
248 - : new ProviderTurnControlError({
249 - threadId: input.threadId,
250 - operation: "interrupt",
251 - providerTurnId: input.providerTurnId,
252 - cause,
253 - }),
242 + },
243 + (effect, input) =>
244 + effect.pipe(
245 + Effect.mapError((cause) =>
246 + isProviderTurnControlError(cause)
247 + ? cause
248 + : new ProviderTurnControlError({
249 + threadId: input.threadId,
250 + operation: "interrupt",
251 + providerTurnId: input.providerTurnId,
252 + cause,
253 + }),
254 + ),
255 ),
255 - ),
256 - interruptAndAwaitTerminal: (input) =>
257 - Effect.gen(function* () {
256 + ),
257 + interruptAndAwaitTerminal: Effect.fn("ProviderTurnControlService.interruptAndAwaitTerminal")(
258 + function* (input) {
259 const loaded = yield* load({ ...input, operation: "restart" });
260 if (Option.isNone(loaded.session)) {
261 // No live adapter: nothing can emit a terminal provider-turn update
@@ -307,20 +308,23 @@ export const layer: Layer.Layer<
308 providerTurnId: input.providerTurnId,
309 cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`,
310 });
310 - }).pipe(
311 - Effect.mapError((cause) =>
312 - isProviderTurnControlError(cause)
313 - ? cause
314 - : new ProviderTurnControlError({
315 - threadId: input.threadId,
316 - operation: "restart",
317 - providerTurnId: input.providerTurnId,
318 - cause,
319 - }),
311 + },
312 + (effect, input) =>
313 + effect.pipe(
314 + Effect.mapError((cause) =>
315 + isProviderTurnControlError(cause)
316 + ? cause
317 + : new ProviderTurnControlError({
318 + threadId: input.threadId,
319 + operation: "restart",
320 + providerTurnId: input.providerTurnId,
321 + cause,
322 + }),
323 + ),
324 ),
321 - ),
322 - steer: (input) =>
323 - Effect.gen(function* () {
325 + ),
326 + steer: Effect.fn("ProviderTurnControlService.steer")(
327 + function* (input) {
328 const context = yield* projections.getProviderControlContext(input.threadId, input);
329 const ownership = context.message?.delegatedCompletion;
330 if (ownership !== undefined) {
@@ -389,18 +393,21 @@ export const layer: Layer.Layer<
393 }),
394 ),
395 );
392 - }).pipe(
393 - Effect.mapError((cause) =>
394 - isProviderTurnControlError(cause)
395 - ? cause
396 - : new ProviderTurnControlError({
397 - threadId: input.threadId,
398 - operation: "steer",
399 - providerTurnId: input.providerTurnId,
400 - cause,
401 - }),
396 + },
397 + (effect, input) =>
398 + effect.pipe(
399 + Effect.mapError((cause) =>
400 + isProviderTurnControlError(cause)
401 + ? cause
402 + : new ProviderTurnControlError({
403 + threadId: input.threadId,
404 + operation: "steer",
405 + providerTurnId: input.providerTurnId,
406 + cause,
407 + }),
408 + ),
409 ),
403 - ),
410 + ),
411 });
412 }),
413 );
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+62 -63
@@ -541,12 +541,12 @@ export const layer: Layer.Layer<
541 }),
542 }),
543 );
544 - const settleStartFailure = (failed: {
545 - readonly signal: string;
546 - readonly title: string;
547 - readonly error: Error;
548 - }) =>
549 - Effect.gen(function* () {
544 + const settleStartFailure = Effect.fn("ProviderTurnStartService.settleStartFailure")(
545 + function* (failed: {
546 + readonly signal: string;
547 + readonly title: string;
548 + readonly error: Error;
549 + }) {
550 const nestedCause = "cause" in failed.error ? failed.error.cause : undefined;
551 yield* settleRunBeforeStart({
552 signal: failed.signal,
@@ -569,7 +569,8 @@ export const layer: Layer.Layer<
569 }),
570 },
571 });
572 - });
572 + },
573 + );
574 if (sessionResult._tag === "Failure") {
575 if (input.willRetry === true) return yield* sessionResult.failure;
576 yield* settleStartFailure({
@@ -581,20 +582,19 @@ export const layer: Layer.Layer<
582 }
583 const session = sessionResult.success;
584 if (!(yield* isCurrentAttemptInStatus("starting"))) return;
584 - const loadFromProvider = (
585 + const loadFromProvider = Effect.fn("ProviderTurnStartService.loadFromProvider")(function* (
586 load: Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapter.ProviderAdapterV2Error>,
586 - ) =>
587 - Effect.gen(function* () {
588 - const loaded = yield* Effect.result(load);
589 - if (loaded._tag === "Success") return loaded.success;
590 - if (input.willRetry === true) return yield* loaded.failure;
591 - yield* settleStartFailure({
592 - signal: "provider-thread-load-failure",
593 - title: "Provider turn failed to start",
594 - error: loaded.failure,
595 - });
596 - return undefined;
587 + ) {
588 + const loaded = yield* Effect.result(load);
589 + if (loaded._tag === "Success") return loaded.success;
590 + if (input.willRetry === true) return yield* loaded.failure;
591 + yield* settleStartFailure({
592 + signal: "provider-thread-load-failure",
593 + title: "Provider turn failed to start",
594 + error: loaded.failure,
595 });
596 + return undefined;
597 + });
598 let effectiveHandoffs = handoffs;
599 const loadedProviderThread = yield* Effect.gen(function* () {
600 if (nativeForkTransfer !== undefined) {
@@ -1073,11 +1073,8 @@ export const layer: Layer.Layer<
1073 !coveredItemIds.has(item.id) &&
1074 historicalMessage(item) !== null,
1075 );
1076 - const startWithHandoffs = (
1077 - turnInput: Parameters<typeof session.startTurn>[0],
1078 - compact = false,
1079 - ) =>
1080 - Effect.gen(function* () {
1076 + const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")(
1077 + function* (turnInput: Parameters<typeof session.startTurn>[0], compact = false) {
1078 const retryHandoff =
1079 missedItems.length === 0
1080 ? []
@@ -1127,25 +1124,24 @@ export const layer: Layer.Layer<
1124 ...history,
1125 }),
1126 }),
1130 - persist: (handoff) =>
1131 - Effect.gen(function* () {
1132 - const updatedAt = yield* DateTime.now;
1133 - yield* eventSink.write({
1134 - events: [
1135 - {
1136 - id: yield* idAllocator.allocate.event({
1137 - threadId: projection.thread.id,
1138 - }),
1139 - type: "context-handoff.updated",
1127 + persist: Effect.fn("ProviderTurnStartService.persist")(function* (handoff) {
1128 + const updatedAt = yield* DateTime.now;
1129 + yield* eventSink.write({
1130 + events: [
1131 + {
1132 + id: yield* idAllocator.allocate.event({
1133 threadId: projection.thread.id,
1141 - runId: run.id,
1142 - providerInstanceId: run.providerInstanceId,
1143 - occurredAt: updatedAt,
1144 - payload: { ...handoff, updatedAt },
1145 - },
1146 - ],
1147 - });
1148 - }),
1134 + }),
1135 + type: "context-handoff.updated",
1136 + threadId: projection.thread.id,
1137 + runId: run.id,
1138 + providerInstanceId: run.providerInstanceId,
1139 + occurredAt: updatedAt,
1140 + payload: { ...handoff, updatedAt },
1141 + },
1142 + ],
1143 + });
1144 + }),
1145 });
1146 if (!(yield* isCurrentAttemptInStatus("running"))) return;
1147 const start = compact ? session.compactThread! : session.startTurn;
@@ -1184,19 +1180,19 @@ export const layer: Layer.Layer<
1180 }),
1181 ),
1182 );
1187 - }).pipe(
1188 - Effect.mapError((cause) =>
1189 - cause._tag === "ProviderAdapterTurnStartError"
1190 - ? cause
1191 - : new ProviderAdapter.ProviderAdapterTurnStartError({
1192 - driver: session.driver,
1193 - threadId: projection.thread.id,
1194 - providerThreadId: providerThread.id,
1195 - runId: run.id,
1196 - cause,
1197 - }),
1198 - ),
1199 - );
1183 + },
1184 + Effect.mapError((cause) =>
1185 + cause._tag === "ProviderAdapterTurnStartError"
1186 + ? cause
1187 + : new ProviderAdapter.ProviderAdapterTurnStartError({
1188 + driver: session.driver,
1189 + threadId: projection.thread.id,
1190 + providerThreadId: providerThread.id,
1191 + runId: run.id,
1192 + cause,
1193 + }),
1194 + ),
1195 + );
1196 const deliverySession =
1197 effectiveHandoffs.length === 0 &&
1198 missedItems.length === 0 &&
@@ -1256,8 +1252,8 @@ export const layer: Layer.Layer<
1252 });
1253
1254 return ProviderTurnStartServiceV2.of({
1259 - start: (input) =>
1260 - Effect.gen(function* () {
1255 + start: Effect.fn("ProviderTurnStartService.start")(
1256 + function* (input) {
1257 // Storage cleanup removes worktrees under the same lease. Only startup
1258 // holds it; the provider turn runs after it is released.
1259 const { thread } = yield* projectionStore.getThreadRecords(input.threadId, []);
@@ -1265,13 +1261,16 @@ export const layer: Layer.Layer<
1261 ? start(input)
1262 : withWorkspaceLease(path.resolve(thread.worktreePath), start(input));
1263 if (providerTurn !== undefined) yield* providerTurn;
1268 - }).pipe(
1269 - Effect.mapError((cause) =>
1270 - isProviderTurnStartError(cause)
1271 - ? cause
1272 - : new ProviderTurnStartError({ runId: input.runId, cause }),
1264 + },
1265 + (effect, input) =>
1266 + effect.pipe(
1267 + Effect.mapError((cause) =>
1268 + isProviderTurnStartError(cause)
1269 + ? cause
1270 + : new ProviderTurnStartError({ runId: input.runId, cause }),
1271 + ),
1272 ),
1274 - ),
1273 + ),
1274 });
1275 }),
1276 );
apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
+34 -32
@@ -218,23 +218,26 @@ export const make = Effect.gen(function* () {
218 lives.set(lifeKey(target), { ...life, wakes: life.wakes + 1 });
219 });
220
221 - const reportEnd = (key: string, life: WatchLife, reason: WatchEndReason) =>
222 - Effect.gen(function* () {
223 - lives.delete(key);
224 - const now = yield* Clock.currentTimeMillis;
225 - const quietMs = now - life.pushedAt;
226 - yield* Effect.logInfo("pull request watch ended", {
227 - threadId: life.threadId,
228 - pullRequest: life.pullRequest,
229 - reason,
230 - minutes: minutes(now - life.startedAt),
231 - quietMinutes: minutes(quietMs),
232 - longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
233 - wakes: life.wakes,
234 - reads: life.reads,
235 - partial: life.startedAt < bootedAt,
236 - });
221 + const reportEnd = Effect.fn("PullRequestWatchReactor.reportEnd")(function* (
222 + key: string,
223 + life: WatchLife,
224 + reason: WatchEndReason,
225 + ) {
226 + lives.delete(key);
227 + const now = yield* Clock.currentTimeMillis;
228 + const quietMs = now - life.pushedAt;
229 + yield* Effect.logInfo("pull request watch ended", {
230 + threadId: life.threadId,
231 + pullRequest: life.pullRequest,
232 + reason,
233 + minutes: minutes(now - life.startedAt),
234 + quietMinutes: minutes(quietMs),
235 + longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
236 + wakes: life.wakes,
237 + reads: life.reads,
238 + partial: life.startedAt < bootedAt,
239 });
240 + });
241 const ended = (target: WatchTarget, reason: WatchEndReason) =>
242 Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason));
243
@@ -255,27 +258,26 @@ export const make = Effect.gen(function* () {
258 * The orchestrator applies this only while the same watch is on, so a stop or restart
259 * that lands during the host read wins.
260 */
258 - const record = (
261 + const record = Effect.fn("PullRequestWatchReactor.record")(function* (
262 target: WatchTarget,
263 next: ThreadPullRequestWatch | null,
264 wake?: { readonly text: string; readonly notification: OrchestrationV2Notification },
265 endedWatch?: ThreadPullRequestWatch,
263 - ) =>
264 - Effect.gen(function* () {
265 - const uuid = yield* crypto.randomUUIDv4();
266 - yield* engine.dispatch({
267 - type: "thread.pull-request-watch.sync",
268 - commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
269 - threadId: target.thread.id,
270 - ...identityOf(target.link),
271 - startedAt: target.watch.startedAt,
272 - watch: next,
273 - ...(endedWatch === undefined ? {} : { endedWatch }),
274 - ...(wake === undefined
275 - ? {}
276 - : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
277 - });
266 + ) {
267 + const uuid = yield* crypto.randomUUIDv4();
268 + yield* engine.dispatch({
269 + type: "thread.pull-request-watch.sync",
270 + commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
271 + threadId: target.thread.id,
272 + ...identityOf(target.link),
273 + startedAt: target.watch.startedAt,
274 + watch: next,
275 + ...(endedWatch === undefined ? {} : { endedWatch }),
276 + ...(wake === undefined
277 + ? {}
278 + : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
279 });
280 + });
281
282 const giveUp = (target: WatchTarget) =>
283 record(target, null, {
apps/server/src/orchestration-v2/RunExecutionService.ts
+740 -747
@@ -201,120 +201,120 @@ function withLinkedChildThreadId(
201 return { ...current, linkedChildThreadIds };
202 }
203
204 -export function cascadeTerminalizeRunOwnedSubagents(input: {
204 +export const cascadeTerminalizeRunOwnedSubagents = Effect.fn(
205 + "RunExecutionService.cascadeTerminalizeRunOwnedSubagents",
206 +)(function* (input: {
207 readonly run: OrchestrationV2Run;
208 readonly open: OpenRunOwnedSubagentProjection;
209 readonly status: RunOwnedSubagentTerminalStatus;
210 readonly completedAt: DateTime.Utc;
211 readonly allocateEventId: () => Effect.Effect<EventId, IdAllocator.IdAllocatorV2AllocationError>;
210 -}): Effect.Effect<
212 +}): Effect.fn.Return<
213 ReadonlyArray<OrchestrationV2DomainEvent>,
214 IdAllocator.IdAllocatorV2AllocationError
215 > {
214 - return Effect.gen(function* () {
215 - const events: Array<OrchestrationV2DomainEvent> = [];
216 - // Prefer lifetime linkage over currently-open rows: subagent/turn-item
217 - // snapshots may terminalize before the linked child-thread node settles.
218 - const childThreadIds = new Set(input.open.linkedChildThreadIds);
219 - for (const item of [...input.open.subagents.values(), ...input.open.turnItems.values()]) {
220 - if (item.childThreadId !== null) {
221 - childThreadIds.add(item.childThreadId);
222 - }
216 + const events: Array<OrchestrationV2DomainEvent> = [];
217 + // Prefer lifetime linkage over currently-open rows: subagent/turn-item
218 + // snapshots may terminalize before the linked child-thread node settles.
219 + const childThreadIds = new Set(input.open.linkedChildThreadIds);
220 + for (const item of [...input.open.subagents.values(), ...input.open.turnItems.values()]) {
221 + if (item.childThreadId !== null) {
222 + childThreadIds.add(item.childThreadId);
223 }
224 - const keys = new Set<NodeId>([
225 - ...input.open.subagents.keys(),
226 - ...input.open.turnItems.keys(),
227 - ...input.open.nodes.keys(),
228 - ]);
229 - for (const key of keys) {
230 - const subagent = input.open.subagents.get(key);
231 - if (subagent !== undefined && !isSettledSubagentStatus(subagent.status)) {
232 - events.push({
233 - id: yield* input.allocateEventId(),
234 - type: "subagent.updated",
235 - threadId: subagent.threadId,
236 - runId: input.run.id,
237 - nodeId: subagent.id,
238 - driver: subagent.driver,
239 - providerInstanceId: subagent.providerInstanceId,
240 - occurredAt: input.completedAt,
241 - payload: {
242 - ...subagent,
243 - status: input.status,
244 - completedAt: input.completedAt,
245 - updatedAt: input.completedAt,
246 - },
247 - });
248 - }
249 - const node = input.open.nodes.get(key);
250 - if (
251 - node !== undefined &&
252 - ((node.threadId === input.run.threadId && node.runId === input.run.id) ||
253 - childThreadIds.has(node.threadId)) &&
254 - isOpenExecutionNodeStatus(node.status)
255 - ) {
256 - events.push({
257 - id: yield* input.allocateEventId(),
258 - type: "node.updated",
259 - threadId: node.threadId,
260 - runId: node.runId ?? input.run.id,
261 - nodeId: node.id,
262 - providerInstanceId: input.run.providerInstanceId,
263 - occurredAt: input.completedAt,
264 - payload: {
265 - ...node,
266 - status: input.status,
267 - completedAt: input.completedAt,
268 - },
269 - });
270 - }
271 - const turnItem = input.open.turnItems.get(key);
272 - if (
273 - turnItem !== undefined &&
274 - turnItem.runId === input.run.id &&
275 - !isSettledTurnItemStatus(turnItem.status)
276 - ) {
277 - events.push({
278 - id: yield* input.allocateEventId(),
279 - type: "turn-item.updated",
280 - threadId: turnItem.threadId,
281 - runId: input.run.id,
282 - ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
283 - providerInstanceId: input.run.providerInstanceId,
284 - occurredAt: input.completedAt,
285 - payload: {
286 - ...turnItem,
287 - status: input.status,
288 - completedAt: input.completedAt,
289 - updatedAt: input.completedAt,
290 - },
291 - });
292 - }
224 + }
225 + const keys = new Set<NodeId>([
226 + ...input.open.subagents.keys(),
227 + ...input.open.turnItems.keys(),
228 + ...input.open.nodes.keys(),
229 + ]);
230 + for (const key of keys) {
231 + const subagent = input.open.subagents.get(key);
232 + if (subagent !== undefined && !isSettledSubagentStatus(subagent.status)) {
233 + events.push({
234 + id: yield* input.allocateEventId(),
235 + type: "subagent.updated",
236 + threadId: subagent.threadId,
237 + runId: input.run.id,
238 + nodeId: subagent.id,
239 + driver: subagent.driver,
240 + providerInstanceId: subagent.providerInstanceId,
241 + occurredAt: input.completedAt,
242 + payload: {
243 + ...subagent,
244 + status: input.status,
245 + completedAt: input.completedAt,
246 + updatedAt: input.completedAt,
247 + },
248 + });
249 }
294 - for (const turnItem of input.open.childTurnItems.values()) {
295 - if (!childThreadIds.has(turnItem.threadId) || isSettledTurnItemStatus(turnItem.status)) {
296 - continue;
297 - }
250 + const node = input.open.nodes.get(key);
251 + if (
252 + node !== undefined &&
253 + ((node.threadId === input.run.threadId && node.runId === input.run.id) ||
254 + childThreadIds.has(node.threadId)) &&
255 + isOpenExecutionNodeStatus(node.status)
256 + ) {
257 + events.push({
258 + id: yield* input.allocateEventId(),
259 + type: "node.updated",
260 + threadId: node.threadId,
261 + runId: node.runId ?? input.run.id,
262 + nodeId: node.id,
263 + providerInstanceId: input.run.providerInstanceId,
264 + occurredAt: input.completedAt,
265 + payload: {
266 + ...node,
267 + status: input.status,
268 + completedAt: input.completedAt,
269 + },
270 + });
271 + }
272 + const turnItem = input.open.turnItems.get(key);
273 + if (
274 + turnItem !== undefined &&
275 + turnItem.runId === input.run.id &&
276 + !isSettledTurnItemStatus(turnItem.status)
277 + ) {
278 events.push({
279 id: yield* input.allocateEventId(),
280 type: "turn-item.updated",
281 threadId: turnItem.threadId,
302 - runId: turnItem.runId ?? input.run.id,
282 + runId: input.run.id,
283 ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
284 providerInstanceId: input.run.providerInstanceId,
285 occurredAt: input.completedAt,
286 payload: {
287 ...turnItem,
308 - ...("streaming" in turnItem ? { streaming: false } : {}),
288 status: input.status,
289 completedAt: input.completedAt,
290 updatedAt: input.completedAt,
291 },
292 });
293 }
315 - return events;
316 - });
317 -}
294 + }
295 + for (const turnItem of input.open.childTurnItems.values()) {
296 + if (!childThreadIds.has(turnItem.threadId) || isSettledTurnItemStatus(turnItem.status)) {
297 + continue;
298 + }
299 + events.push({
300 + id: yield* input.allocateEventId(),
301 + type: "turn-item.updated",
302 + threadId: turnItem.threadId,
303 + runId: turnItem.runId ?? input.run.id,
304 + ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
305 + providerInstanceId: input.run.providerInstanceId,
306 + occurredAt: input.completedAt,
307 + payload: {
308 + ...turnItem,
309 + ...("streaming" in turnItem ? { streaming: false } : {}),
310 + status: input.status,
311 + completedAt: input.completedAt,
312 + updatedAt: input.completedAt,
313 + },
314 + });
315 + }
316 + return events;
317 +});
318
319 export function finalProviderThreadStatus(
320 disposition: ProviderTerminalEvent["threadDisposition"],
@@ -582,24 +582,24 @@ export const layer: Layer.Layer<
582 const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
583 const finalizationObserver = yield* RunFinalizationService.RunFinalizationObserver;
584
585 - const writeFinalRunEvents = (input: {
586 - readonly run: OrchestrationV2Run;
587 - readonly rootNode: OrchestrationV2ExecutionNode;
588 - readonly checkpointScope: OrchestrationV2CheckpointScope;
589 - readonly providerThread: OrchestrationV2ProviderThread;
590 - readonly attempt: OrchestrationV2RunAttempt;
591 - readonly shouldFinalizeRun?: () => Effect.Effect<boolean, ProjectionStoreV2Error>;
592 - readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
593 - readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;
594 - readonly terminal: ProviderTerminalEvent;
595 - readonly failureItemPersisted: boolean;
596 - readonly refreshAfterTurn: Effect.Effect<void>;
597 - readonly writeIfRunCurrent?: {
598 - readonly activeAttemptId: RunAttemptId;
599 - readonly expectedStatus: OrchestrationV2Run["status"];
600 - };
601 - }) =>
602 - Effect.gen(function* () {
585 + const writeFinalRunEvents = Effect.fn("RunExecutionService.writeFinalRunEvents")(
586 + function* (input: {
587 + readonly run: OrchestrationV2Run;
588 + readonly rootNode: OrchestrationV2ExecutionNode;
589 + readonly checkpointScope: OrchestrationV2CheckpointScope;
590 + readonly providerThread: OrchestrationV2ProviderThread;
591 + readonly attempt: OrchestrationV2RunAttempt;
592 + readonly shouldFinalizeRun?: () => Effect.Effect<boolean, ProjectionStoreV2Error>;
593 + readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
594 + readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;
595 + readonly terminal: ProviderTerminalEvent;
596 + readonly failureItemPersisted: boolean;
597 + readonly refreshAfterTurn: Effect.Effect<void>;
598 + readonly writeIfRunCurrent?: {
599 + readonly activeAttemptId: RunAttemptId;
600 + readonly expectedStatus: OrchestrationV2Run["status"];
601 + };
602 + }) {
603 const completedAt = yield* DateTime.now;
604 const finalizedAttempt: OrchestrationV2RunAttempt | null = {
605 ...input.attempt,
@@ -816,697 +816,690 @@ export const layer: Layer.Layer<
816 yield* eventSink.writeWithEffects(finalization);
817 }
818 yield* input.refreshAfterTurn;
819 - });
819 + },
820 + );
821
822 return RunExecutionServiceV2.of({
822 - startRootRun: (input) =>
823 - Effect.gen(function* () {
824 - // Startup failure and stream shutdown can report the same attempt.
825 - const refreshAfterTurn = yield* Effect.cached(
826 - finalizationObserver.refreshAfterTurn(input.appThread.projectId).pipe(
827 - Effect.catchCause((cause) =>
828 - Effect.logWarning("failed to refresh pull requests after run termination", {
829 - threadId: input.run.threadId,
830 - runId: input.run.id,
831 - cause,
832 - }),
833 - ),
834 - ),
835 - );
836 - const makeFailedTerminalEvent = (
837 - failure: OrchestrationV2ProviderFailure,
838 - failureItemOrdinal: number,
839 - ): ProviderTerminalEvent => ({
840 - type: "turn.terminal",
841 - driver: input.providerThread.driver,
842 - providerThreadId: input.providerThread.id,
843 - providerTurnId:
844 - input.attempt.providerTurnId ??
845 - idAllocator.derive.providerTurn({
846 - driver: input.providerThread.driver,
847 - nativeTurnId: `failed:${input.attempt.id}`,
848 - }),
849 - runOrdinal: input.run.ordinal,
850 - failureItemOrdinal,
851 - status: "failed",
852 - failure,
853 - threadDisposition: "reusable",
854 - });
855 - const responseStreamingMode = yield* Effect.gen(function* () {
856 - const responseStreamingMode = yield* serverSettings.getSettings.pipe(
857 - Effect.map(
858 - (settings) =>
859 - resolveProjectSettings(settings, input.appThread.projectId).settings
860 - .responseStreamingMode,
861 - ),
862 - );
863 - yield* checkpointService
864 - .captureBaseline({
865 - scope: input.checkpointScope,
866 - ordinalWithinScope: Math.max(0, input.run.ordinal - 1),
867 - })
868 - .pipe(
869 - Effect.catchCause((cause) =>
870 - Cause.hasInterruptsOnly(cause)
871 - ? Effect.failCause(cause)
872 - : Effect.logWarning(
873 - "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline",
874 - { runId: input.run.id },
875 - ),
876 - ),
877 - );
878 - if (
879 - input.shouldStartProviderTurn !== undefined &&
880 - !(yield* input.shouldStartProviderTurn())
881 - ) {
882 - return null;
883 - }
884 - return responseStreamingMode;
885 - }).pipe(
823 + startRootRun: Effect.fn("RunExecutionService.startRootRun")(function* (input) {
824 + // Startup failure and stream shutdown can report the same attempt.
825 + const refreshAfterTurn = yield* Effect.cached(
826 + finalizationObserver.refreshAfterTurn(input.appThread.projectId).pipe(
827 Effect.catchCause((cause) =>
887 - Effect.gen(function* () {
888 - if (Cause.hasInterruptsOnly(cause)) {
889 - return yield* Effect.failCause(cause);
890 - }
891 - yield* Effect.logError("orchestration V2 run preparation failed", {
892 - runId: input.run.id,
893 - cause,
894 - });
895 - yield* writeFinalRunEvents({
896 - run: input.run,
897 - rootNode: input.rootNode,
898 - checkpointScope: input.checkpointScope,
899 - providerThread: input.providerThread,
900 - attempt: input.attempt,
901 - terminal: makeFailedTerminalEvent(
902 - makeProviderFailure({
903 - cause: Cause.squash(cause),
904 - message: "Run preparation failed.",
905 - class: "unknown",
906 - }),
907 - input.providerTurnOrdinal * 100 + 1,
908 - ),
909 - failureItemPersisted: false,
910 - refreshAfterTurn,
911 - writeIfRunCurrent: {
912 - activeAttemptId: input.attemptId,
913 - expectedStatus: "running",
914 - },
915 - });
916 - return null;
828 + Effect.logWarning("failed to refresh pull requests after run termination", {
829 + threadId: input.run.threadId,
830 + runId: input.run.id,
831 + cause,
832 }),
833 ),
919 - Effect.mapError(
920 - (cause) =>
921 - new RunExecutionStartError({
922 - commandId: input.commandId,
923 - runId: input.run.id,
924 - cause,
925 - }),
834 + ),
835 + );
836 + const makeFailedTerminalEvent = (
837 + failure: OrchestrationV2ProviderFailure,
838 + failureItemOrdinal: number,
839 + ): ProviderTerminalEvent => ({
840 + type: "turn.terminal",
841 + driver: input.providerThread.driver,
842 + providerThreadId: input.providerThread.id,
843 + providerTurnId:
844 + input.attempt.providerTurnId ??
845 + idAllocator.derive.providerTurn({
846 + driver: input.providerThread.driver,
847 + nativeTurnId: `failed:${input.attempt.id}`,
848 + }),
849 + runOrdinal: input.run.ordinal,
850 + failureItemOrdinal,
851 + status: "failed",
852 + failure,
853 + threadDisposition: "reusable",
854 + });
855 + const responseStreamingMode = yield* Effect.gen(function* () {
856 + const responseStreamingMode = yield* serverSettings.getSettings.pipe(
857 + Effect.map(
858 + (settings) =>
859 + resolveProjectSettings(settings, input.appThread.projectId).settings
860 + .responseStreamingMode,
861 ),
862 );
928 - if (responseStreamingMode === null) {
929 - return;
863 + yield* checkpointService
864 + .captureBaseline({
865 + scope: input.checkpointScope,
866 + ordinalWithinScope: Math.max(0, input.run.ordinal - 1),
867 + })
868 + .pipe(
869 + Effect.catchCause((cause) =>
870 + Cause.hasInterruptsOnly(cause)
871 + ? Effect.failCause(cause)
872 + : Effect.logWarning(
873 + "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline",
874 + { runId: input.run.id },
875 + ),
876 + ),
877 + );
878 + if (
879 + input.shouldStartProviderTurn !== undefined &&
880 + !(yield* input.shouldStartProviderTurn())
881 + ) {
882 + return null;
883 }
931 - const terminalEvent = yield* Ref.make<ProviderTerminalEvent | null>(null);
932 - const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);
933 - const latestProviderThread = yield* Ref.make(input.providerThread);
934 - const routeIdentity: ProviderEventRouteIdentity = {
935 - threadId: input.run.threadId,
936 - runId: input.run.id,
937 - attemptId: input.attempt.id,
938 - providerThreadId: input.providerThread.id,
939 - };
940 - const eventSubscription =
941 - input.session.subscribeEvents === undefined
942 - ? { events: input.session.events, close: Effect.void }
943 - : yield* input.session.subscribeEvents;
944 - const inheritedBackgroundTurnItems = yield* (
945 - input.loadInheritedBackgroundTurnItems?.() ?? Effect.succeed([])
946 - ).pipe(
947 - Effect.onError(() => eventSubscription.close),
948 - Effect.mapError(
949 - (cause) =>
950 - new RunExecutionStartError({
951 - commandId: input.commandId,
952 - runId: input.run.id,
953 - cause,
954 - }),
955 - ),
956 - );
957 - const inheritedBackgroundTurnItemsById = new Map(
958 - inheritedBackgroundTurnItems.map((item) => [item.id, item.runId]),
959 - );
960 - const eventRouting = yield* Ref.make<ProviderEventRoutingState>(
961 - makeProviderEventRoutingState({
962 - identity: routeIdentity,
963 - inheritedBackgroundTurnItems,
964 - providerTurnId: input.attempt.providerTurnId,
965 - ...(input.relatedThreadIds === undefined
966 - ? {}
967 - : { relatedThreadIds: input.relatedThreadIds }),
968 - ...(input.relatedProviderThreadIds === undefined
969 - ? {}
970 - : { relatedProviderThreadIds: input.relatedProviderThreadIds }),
971 - }),
972 - );
973 - const rootTerminalSeen = yield* Ref.make(false);
974 - const rootRunFinalized = yield* Ref.make(false);
975 - const providerThreadOwnerLost = yield* Ref.make(false);
976 - const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
977 - const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
978 - const activeBackgroundTurnItems = yield* Ref.make<
979 - ReadonlySet<OrchestrationV2TurnItem["id"]>
980 - >(new Set(inheritedBackgroundTurnItemsById.keys()));
981 - const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection());
982 - const finalizeRootRun = (terminal: ProviderTerminalEvent) =>
884 + return responseStreamingMode;
885 + }).pipe(
886 + Effect.catchCause((cause) =>
887 Effect.gen(function* () {
984 - if (yield* Ref.get(rootRunFinalized)) {
985 - return;
888 + if (Cause.hasInterruptsOnly(cause)) {
889 + return yield* Effect.failCause(cause);
890 }
987 - const providerThread = yield* Ref.get(latestProviderThread);
988 - const openSubagents = yield* Ref.get(openRunOwnedSubagents);
891 + yield* Effect.logError("orchestration V2 run preparation failed", {
892 + runId: input.run.id,
893 + cause,
894 + });
895 yield* writeFinalRunEvents({
896 run: input.run,
897 rootNode: input.rootNode,
898 checkpointScope: input.checkpointScope,
993 - providerThread,
899 + providerThread: input.providerThread,
900 attempt: input.attempt,
995 - ...(input.shouldFinalizeRun === undefined
996 - ? {}
997 - : {
998 - shouldFinalizeRun: input.shouldFinalizeRun,
999 - // Stop may commit between the ownership read and this
1000 - // terminal write. Gate the events and checkpoint together.
1001 - writeIfRunCurrent: {
1002 - activeAttemptId: input.attempt.id,
1003 - expectedStatus: "running" as const,
1004 - },
1005 - }),
1006 - ...(input.hasUnpairedRunInterruptRequest === undefined
1007 - ? {}
1008 - : {
1009 - hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
1010 - }),
1011 - openRunOwnedSubagents: openSubagents,
1012 - terminal,
1013 - failureItemPersisted: terminal.status === "failed",
1014 - refreshAfterTurn,
1015 - }).pipe(
1016 - Effect.mapError(
1017 - (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
901 + terminal: makeFailedTerminalEvent(
902 + makeProviderFailure({
903 + cause: Cause.squash(cause),
904 + message: "Run preparation failed.",
905 + class: "unknown",
906 + }),
907 + input.providerTurnOrdinal * 100 + 1,
908 ),
1019 - );
1020 - if (
1021 - isRunOwnedSubagentTerminalStatus(terminal.status) &&
1022 - !childTurnsContinue(terminal)
1023 - ) {
1024 - yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());
1025 - }
1026 - yield* Ref.set(rootRunFinalized, true);
1027 - });
1028 - const trackChildLifecycle = (
1029 - event: ProviderAdapter.ProviderAdapterV2Event,
1030 - deliverable: boolean,
1031 - ) =>
1032 - Effect.gen(function* () {
1033 - const routing = yield* Ref.get(eventRouting);
1034 - if (event.type === "provider_turn.updated") {
1035 - const isRoot =
1036 - event.providerTurn.runAttemptId === input.attempt.id ||
1037 - event.providerTurn.id === routing.rootProviderTurnId;
1038 - if (!isRoot) {
1039 - yield* Ref.update(activeChildProviderTurns, (current) => {
1040 - const next = new Set(current);
1041 - if (isTerminalProviderTurnStatus(event.providerTurn.status)) {
1042 - next.delete(event.providerTurn.id);
1043 - } else {
1044 - next.add(event.providerTurn.id);
1045 - }
1046 - return next;
1047 - });
1048 - }
1049 - }
1050 - if (event.type === "subagent.updated") {
1051 - const belongsToRootRun = event.subagent.runId === input.run.id;
1052 - const belongsToOwnedChildThread =
1053 - event.subagent.threadId !== input.run.threadId &&
1054 - routing.ownedThreadIds.has(event.subagent.threadId);
1055 - if (belongsToRootRun || belongsToOwnedChildThread) {
1056 - yield* Ref.update(activeChildSubagents, (current) => {
1057 - const next = new Set(current);
1058 - if (isSettledSubagentStatus(event.subagent.status)) {
1059 - next.delete(event.subagent.id);
1060 - } else {
1061 - next.add(event.subagent.id);
1062 - }
1063 - return next;
1064 - });
1065 - }
1066 - // Preserve childThreadId linkage for the root-run lifetime even after the subagent
1067 - // row terminalizes, so open child-thread nodes can still be proven linked on a
1068 - // later root interrupt. A provider records nested native subagents on the child
1069 - // thread, runless; they die with this run too.
1070 - if (
1071 - belongsToRootRun ||
1072 - (belongsToOwnedChildThread &&
1073 - event.subagent.runId === null &&
1074 - event.subagent.origin === "provider_native")
1075 - ) {
1076 - yield* Ref.update(openRunOwnedSubagents, (current) => {
1077 - const withLink = withLinkedChildThreadId(current, event.subagent.childThreadId);
1078 - const subagents = new Map(withLink.subagents);
1079 - if (isSettledSubagentStatus(event.subagent.status)) {
1080 - subagents.delete(event.subagent.id);
1081 - } else {
1082 - subagents.set(event.subagent.id, event.subagent);
1083 - }
1084 - return { ...withLink, subagents };
1085 - });
1086 - }
1087 - }
1088 - if (event.type === "node.updated") {
1089 - const belongsToRootSubagent =
1090 - event.node.kind === "subagent" && event.node.runId === input.run.id;
1091 - const belongsToOwnedChildThread =
1092 - event.node.threadId !== input.run.threadId &&
1093 - routing.ownedThreadIds.has(event.node.threadId);
1094 - if (
1095 - !belongsToRootSubagent &&
1096 - !(
1097 - belongsToOwnedChildThread &&
1098 - (event.node.runId === null || event.node.runId === input.run.id)
1099 - )
1100 - ) {
1101 - return;
1102 - }
1103 - yield* Ref.update(openRunOwnedSubagents, (current) => {
1104 - const nodes = new Map(current.nodes);
1105 - if (isOpenExecutionNodeStatus(event.node.status)) {
1106 - nodes.set(event.node.id, event.node);
1107 - } else {
1108 - nodes.delete(event.node.id);
1109 - }
1110 - return { ...current, nodes };
1111 - });
1112 - }
1113 - if (event.type === "turn_item.updated") {
1114 - const belongsToRootRun = event.turnItem.runId === input.run.id;
1115 - const belongsToOwnedChildThread =
1116 - event.turnItem.threadId !== input.run.threadId &&
1117 - routing.ownedThreadIds.has(event.turnItem.threadId);
1118 - const belongsToInheritedBackgroundItem =
1119 - event.turnItem.threadId === input.run.threadId &&
1120 - event.turnItem.runId !== null &&
1121 - inheritedBackgroundTurnItemsById.get(event.turnItem.id) === event.turnItem.runId;
1122 - if (
1123 - backgroundCapableTurnItemTypes.has(event.turnItem.type) &&
1124 - (belongsToRootRun ||
1125 - belongsToOwnedChildThread ||
1126 - belongsToInheritedBackgroundItem)
1127 - ) {
1128 - yield* Ref.update(activeBackgroundTurnItems, (current) => {
1129 - const next = new Set(current);
1130 - if (isSettledTurnItemStatus(event.turnItem.status)) {
1131 - next.delete(event.turnItem.id);
1132 - } else {
1133 - next.add(event.turnItem.id);
1134 - }
1135 - return next;
1136 - });
909 + failureItemPersisted: false,
910 + refreshAfterTurn,
911 + writeIfRunCurrent: {
912 + activeAttemptId: input.attemptId,
913 + expectedStatus: "running",
914 + },
915 + });
916 + return null;
917 + }),
918 + ),
919 + Effect.mapError(
920 + (cause) =>
921 + new RunExecutionStartError({
922 + commandId: input.commandId,
923 + runId: input.run.id,
924 + cause,
925 + }),
926 + ),
927 + );
928 + if (responseStreamingMode === null) {
929 + return;
930 + }
931 + const terminalEvent = yield* Ref.make<ProviderTerminalEvent | null>(null);
932 + const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);
933 + const latestProviderThread = yield* Ref.make(input.providerThread);
934 + const routeIdentity: ProviderEventRouteIdentity = {
935 + threadId: input.run.threadId,
936 + runId: input.run.id,
937 + attemptId: input.attempt.id,
938 + providerThreadId: input.providerThread.id,
939 + };
940 + const eventSubscription =
941 + input.session.subscribeEvents === undefined
942 + ? { events: input.session.events, close: Effect.void }
943 + : yield* input.session.subscribeEvents;
944 + const inheritedBackgroundTurnItems = yield* (
945 + input.loadInheritedBackgroundTurnItems?.() ?? Effect.succeed([])
946 + ).pipe(
947 + Effect.onError(() => eventSubscription.close),
948 + Effect.mapError(
949 + (cause) =>
950 + new RunExecutionStartError({
951 + commandId: input.commandId,
952 + runId: input.run.id,
953 + cause,
954 + }),
955 + ),
956 + );
957 + const inheritedBackgroundTurnItemsById = new Map(
958 + inheritedBackgroundTurnItems.map((item) => [item.id, item.runId]),
959 + );
960 + const eventRouting = yield* Ref.make<ProviderEventRoutingState>(
961 + makeProviderEventRoutingState({
962 + identity: routeIdentity,
963 + inheritedBackgroundTurnItems,
964 + providerTurnId: input.attempt.providerTurnId,
965 + ...(input.relatedThreadIds === undefined
966 + ? {}
967 + : { relatedThreadIds: input.relatedThreadIds }),
968 + ...(input.relatedProviderThreadIds === undefined
969 + ? {}
970 + : { relatedProviderThreadIds: input.relatedProviderThreadIds }),
971 + }),
972 + );
973 + const rootTerminalSeen = yield* Ref.make(false);
974 + const rootRunFinalized = yield* Ref.make(false);
975 + const providerThreadOwnerLost = yield* Ref.make(false);
976 + const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
977 + const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
978 + const activeBackgroundTurnItems = yield* Ref.make<
979 + ReadonlySet<OrchestrationV2TurnItem["id"]>
980 + >(new Set(inheritedBackgroundTurnItemsById.keys()));
981 + const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection());
982 + const finalizeRootRun = Effect.fn("RunExecutionService.finalizeRootRun")(function* (
983 + terminal: ProviderTerminalEvent,
984 + ) {
985 + if (yield* Ref.get(rootRunFinalized)) {
986 + return;
987 + }
988 + const providerThread = yield* Ref.get(latestProviderThread);
989 + const openSubagents = yield* Ref.get(openRunOwnedSubagents);
990 + yield* writeFinalRunEvents({
991 + run: input.run,
992 + rootNode: input.rootNode,
993 + checkpointScope: input.checkpointScope,
994 + providerThread,
995 + attempt: input.attempt,
996 + ...(input.shouldFinalizeRun === undefined
997 + ? {}
998 + : {
999 + shouldFinalizeRun: input.shouldFinalizeRun,
1000 + // Stop may commit between the ownership read and this
1001 + // terminal write. Gate the events and checkpoint together.
1002 + writeIfRunCurrent: {
1003 + activeAttemptId: input.attempt.id,
1004 + expectedStatus: "running" as const,
1005 + },
1006 + }),
1007 + ...(input.hasUnpairedRunInterruptRequest === undefined
1008 + ? {}
1009 + : {
1010 + hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
1011 + }),
1012 + openRunOwnedSubagents: openSubagents,
1013 + terminal,
1014 + failureItemPersisted: terminal.status === "failed",
1015 + refreshAfterTurn,
1016 + }).pipe(
1017 + Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
1018 + );
1019 + if (isRunOwnedSubagentTerminalStatus(terminal.status) && !childTurnsContinue(terminal)) {
1020 + yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());
1021 + }
1022 + yield* Ref.set(rootRunFinalized, true);
1023 + });
1024 + // Runs for every provider event, including streamed text updates; avoid a per-event span.
1025 + const trackChildLifecycle = Effect.fnUntraced(function* (
1026 + event: ProviderAdapter.ProviderAdapterV2Event,
1027 + deliverable: boolean,
1028 + ) {
1029 + const routing = yield* Ref.get(eventRouting);
1030 + if (event.type === "provider_turn.updated") {
1031 + const isRoot =
1032 + event.providerTurn.runAttemptId === input.attempt.id ||
1033 + event.providerTurn.id === routing.rootProviderTurnId;
1034 + if (!isRoot) {
1035 + yield* Ref.update(activeChildProviderTurns, (current) => {
1036 + const next = new Set(current);
1037 + if (isTerminalProviderTurnStatus(event.providerTurn.status)) {
1038 + next.delete(event.providerTurn.id);
1039 + } else {
1040 + next.add(event.providerTurn.id);
1041 }
1138 - if (
1139 - belongsToOwnedChildThread &&
1140 - (event.turnItem.runId === null || belongsToRootRun) &&
1141 - deliverable
1142 - ) {
1143 - yield* Ref.update(openRunOwnedSubagents, (current) => {
1144 - const childTurnItems = new Map(current.childTurnItems);
1145 - if (isSettledTurnItemStatus(event.turnItem.status)) {
1146 - childTurnItems.delete(event.turnItem.id);
1147 - } else {
1148 - childTurnItems.set(event.turnItem.id, event.turnItem);
1149 - }
1150 - return { ...current, childTurnItems };
1151 - });
1042 + return next;
1043 + });
1044 + }
1045 + }
1046 + if (event.type === "subagent.updated") {
1047 + const belongsToRootRun = event.subagent.runId === input.run.id;
1048 + const belongsToOwnedChildThread =
1049 + event.subagent.threadId !== input.run.threadId &&
1050 + routing.ownedThreadIds.has(event.subagent.threadId);
1051 + if (belongsToRootRun || belongsToOwnedChildThread) {
1052 + yield* Ref.update(activeChildSubagents, (current) => {
1053 + const next = new Set(current);
1054 + if (isSettledSubagentStatus(event.subagent.status)) {
1055 + next.delete(event.subagent.id);
1056 + } else {
1057 + next.add(event.subagent.id);
1058 }
1153 - if (belongsToRootRun && event.turnItem.type === "subagent") {
1154 - const subagentItem = event.turnItem;
1155 - yield* Ref.update(openRunOwnedSubagents, (current) => {
1156 - const withLink = withLinkedChildThreadId(current, subagentItem.childThreadId);
1157 - const turnItems = new Map(withLink.turnItems);
1158 - if (isSettledTurnItemStatus(subagentItem.status)) {
1159 - turnItems.delete(subagentItem.subagentId);
1160 - } else {
1161 - turnItems.set(subagentItem.subagentId, subagentItem);
1162 - }
1163 - return { ...withLink, turnItems };
1164 - });
1059 + return next;
1060 + });
1061 + }
1062 + // Preserve childThreadId linkage for the root-run lifetime even after the subagent
1063 + // row terminalizes, so open child-thread nodes can still be proven linked on a
1064 + // later root interrupt. A provider records nested native subagents on the child
1065 + // thread, runless; they die with this run too.
1066 + if (
1067 + belongsToRootRun ||
1068 + (belongsToOwnedChildThread &&
1069 + event.subagent.runId === null &&
1070 + event.subagent.origin === "provider_native")
1071 + ) {
1072 + yield* Ref.update(openRunOwnedSubagents, (current) => {
1073 + const withLink = withLinkedChildThreadId(current, event.subagent.childThreadId);
1074 + const subagents = new Map(withLink.subagents);
1075 + if (isSettledSubagentStatus(event.subagent.status)) {
1076 + subagents.delete(event.subagent.id);
1077 + } else {
1078 + subagents.set(event.subagent.id, event.subagent);
1079 }
1080 + return { ...withLink, subagents };
1081 + });
1082 + }
1083 + }
1084 + if (event.type === "node.updated") {
1085 + const belongsToRootSubagent =
1086 + event.node.kind === "subagent" && event.node.runId === input.run.id;
1087 + const belongsToOwnedChildThread =
1088 + event.node.threadId !== input.run.threadId &&
1089 + routing.ownedThreadIds.has(event.node.threadId);
1090 + if (
1091 + !belongsToRootSubagent &&
1092 + !(
1093 + belongsToOwnedChildThread &&
1094 + (event.node.runId === null || event.node.runId === input.run.id)
1095 + )
1096 + ) {
1097 + return;
1098 + }
1099 + yield* Ref.update(openRunOwnedSubagents, (current) => {
1100 + const nodes = new Map(current.nodes);
1101 + if (isOpenExecutionNodeStatus(event.node.status)) {
1102 + nodes.set(event.node.id, event.node);
1103 + } else {
1104 + nodes.delete(event.node.id);
1105 }
1106 + return { ...current, nodes };
1107 });
1168 - const shouldStopProviderEventIngestion = Effect.gen(function* () {
1169 - if (!(yield* Ref.get(rootTerminalSeen))) {
1170 - return false;
1171 - }
1172 - const terminal = yield* Ref.get(terminalEvent);
1108 + }
1109 + if (event.type === "turn_item.updated") {
1110 + const belongsToRootRun = event.turnItem.runId === input.run.id;
1111 + const belongsToOwnedChildThread =
1112 + event.turnItem.threadId !== input.run.threadId &&
1113 + routing.ownedThreadIds.has(event.turnItem.threadId);
1114 + const belongsToInheritedBackgroundItem =
1115 + event.turnItem.threadId === input.run.threadId &&
1116 + event.turnItem.runId !== null &&
1117 + inheritedBackgroundTurnItemsById.get(event.turnItem.id) === event.turnItem.runId;
1118 if (
1174 - terminal !== null &&
1175 - terminal.status !== "completed" &&
1176 - !childTurnsContinue(terminal)
1119 + backgroundCapableTurnItemTypes.has(event.turnItem.type) &&
1120 + (belongsToRootRun || belongsToOwnedChildThread || belongsToInheritedBackgroundItem)
1121 ) {
1178 - return true;
1122 + yield* Ref.update(activeBackgroundTurnItems, (current) => {
1123 + const next = new Set(current);
1124 + if (isSettledTurnItemStatus(event.turnItem.status)) {
1125 + next.delete(event.turnItem.id);
1126 + } else {
1127 + next.add(event.turnItem.id);
1128 + }
1129 + return next;
1130 + });
1131 }
1180 - const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
1181 - if (childProviderTurns.size > 0) {
1182 - return false;
1132 + if (
1133 + belongsToOwnedChildThread &&
1134 + (event.turnItem.runId === null || belongsToRootRun) &&
1135 + deliverable
1136 + ) {
1137 + yield* Ref.update(openRunOwnedSubagents, (current) => {
1138 + const childTurnItems = new Map(current.childTurnItems);
1139 + if (isSettledTurnItemStatus(event.turnItem.status)) {
1140 + childTurnItems.delete(event.turnItem.id);
1141 + } else {
1142 + childTurnItems.set(event.turnItem.id, event.turnItem);
1143 + }
1144 + return { ...current, childTurnItems };
1145 + });
1146 }
1184 - const childSubagents = yield* Ref.get(activeChildSubagents);
1185 - if (childSubagents.size > 0) {
1186 - return false;
1147 + if (belongsToRootRun && event.turnItem.type === "subagent") {
1148 + const subagentItem = event.turnItem;
1149 + yield* Ref.update(openRunOwnedSubagents, (current) => {
1150 + const withLink = withLinkedChildThreadId(current, subagentItem.childThreadId);
1151 + const turnItems = new Map(withLink.turnItems);
1152 + if (isSettledTurnItemStatus(subagentItem.status)) {
1153 + turnItems.delete(subagentItem.subagentId);
1154 + } else {
1155 + turnItems.set(subagentItem.subagentId, subagentItem);
1156 + }
1157 + return { ...withLink, turnItems };
1158 + });
1159 }
1188 - // Newly owned items depend on adapters emitting a non-terminal event before the root
1189 - // terminal. Owner loss (a newer run claimed lastRunOrdinal) must not close this stream
1190 - // while these sets are non-empty: turn_item.updated writes are not ownership-gated, so
1191 - // late completions still land.
1192 - const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
1193 - if (backgroundItems.size > 0) {
1160 + }
1161 + });
1162 + const shouldStopProviderEventIngestion = Effect.gen(function* () {
1163 + if (!(yield* Ref.get(rootTerminalSeen))) {
1164 + return false;
1165 + }
1166 + const terminal = yield* Ref.get(terminalEvent);
1167 + if (
1168 + terminal !== null &&
1169 + terminal.status !== "completed" &&
1170 + !childTurnsContinue(terminal)
1171 + ) {
1172 + return true;
1173 + }
1174 + const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
1175 + if (childProviderTurns.size > 0) {
1176 + return false;
1177 + }
1178 + const childSubagents = yield* Ref.get(activeChildSubagents);
1179 + if (childSubagents.size > 0) {
1180 + return false;
1181 + }
1182 + // Newly owned items depend on adapters emitting a non-terminal event before the root
1183 + // terminal. Owner loss (a newer run claimed lastRunOrdinal) must not close this stream
1184 + // while these sets are non-empty: turn_item.updated writes are not ownership-gated, so
1185 + // late completions still land.
1186 + const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
1187 + if (backgroundItems.size > 0) {
1188 + return false;
1189 + }
1190 + if (yield* Ref.get(providerThreadOwnerLost)) {
1191 + return true;
1192 + }
1193 + // Claude background Bash has no turn-item projection. Use only the
1194 + // thread-scoped probe: session-wide pending work (siblings, wake
1195 + // buffers, session subagents) must not pin this root subscription.
1196 + const latestProviderThreadSnapshot = yield* Ref.get(latestProviderThread);
1197 + if (input.session.hasPendingBackgroundWorkForThread !== undefined) {
1198 + const hasPendingWork = yield* input.session
1199 + .hasPendingBackgroundWorkForThread(latestProviderThreadSnapshot)
1200 + .pipe(Effect.catchCause(() => Effect.succeed(false)));
1201 + if (hasPendingWork) {
1202 return false;
1203 }
1196 - if (yield* Ref.get(providerThreadOwnerLost)) {
1197 - return true;
1198 - }
1199 - // Claude background Bash has no turn-item projection. Use only the
1200 - // thread-scoped probe: session-wide pending work (siblings, wake
1201 - // buffers, session subagents) must not pin this root subscription.
1202 - const latestProviderThreadSnapshot = yield* Ref.get(latestProviderThread);
1203 - if (input.session.hasPendingBackgroundWorkForThread !== undefined) {
1204 - const hasPendingWork = yield* input.session
1205 - .hasPendingBackgroundWorkForThread(latestProviderThreadSnapshot)
1206 - .pipe(Effect.catchCause(() => Effect.succeed(false)));
1207 - if (hasPendingWork) {
1208 - return false;
1209 - }
1210 - }
1211 - return true;
1212 - });
1213 - const filterAssistantEvent = makeAssistantStreamingFilter(responseStreamingMode);
1214 - // Held text writes nothing, so its item would take a position only
1215 - // when finally written, behind every item that began after it.
1216 - const reservedHeldTurnItemIds = new Set<TurnItemId>();
1217 - const providerEventFiber = yield* eventSubscription.events.pipe(
1218 - Stream.filterEffect((event) =>
1219 - Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
1220 - ),
1221 - Stream.tap((event) =>
1222 - Effect.gen(function* () {
1223 - let storedEventCount = 0;
1224 - const deliveredEvent = filterAssistantEvent(
1225 - event,
1226 - DateTime.toEpochMillis(yield* DateTime.now),
1227 - );
1228 - if (deliveredEvent) {
1229 - const rootTerminalAlreadySeen = yield* Ref.get(rootTerminalSeen);
1230 - const isRootProviderThreadUpdate =
1231 - event.type === "provider_thread.updated" &&
1232 - event.providerThread.id === input.providerThread.id;
1233 - const storedEvents = yield* providerEventIngestor.ingestNormalized({
1234 - analyticsContext: {
1235 - modelSelection: input.modelSelection,
1236 - runtimeMode: input.runtimePolicy.runtimeMode,
1237 - interactionMode: input.runtimePolicy.interactionMode,
1238 - },
1239 - providerSessionId: input.providerSessionId,
1240 - providerInstanceId: input.run.providerInstanceId,
1241 - threadId: input.run.threadId,
1242 - runId: input.run.id,
1243 - nodeId: input.rootNode.id,
1244 - event: deliveredEvent,
1245 - ...(isRootProviderThreadUpdate
1246 - ? rootTerminalAlreadySeen
1247 - ? {
1248 - writeIfProviderThreadOwner: {
1249 - providerThreadId: input.providerThread.id,
1250 - runId: input.run.id,
1251 - activeAttemptId: input.attempt.id,
1252 - expectedLastRunOrdinal: input.run.ordinal,
1253 - },
1254 - }
1255 - : {
1256 - writeIfRunCurrent: {
1257 - runId: input.run.id,
1258 - activeAttemptId: input.attempt.id,
1259 - expectedStatus: "running" as const,
1260 - },
1261 - }
1262 - : {}),
1263 - });
1264 - storedEventCount = storedEvents.length;
1265 - if (
1266 - isRootProviderThreadUpdate &&
1267 - rootTerminalAlreadySeen &&
1268 - storedEventCount === 0
1269 - ) {
1270 - yield* Ref.set(providerThreadOwnerLost, true);
1271 - }
1272 - } else if (
1273 - event.type === "turn_item.updated" &&
1274 - (event.turnItem.type === "assistant_message" ||
1275 - event.turnItem.type === "reasoning") &&
1276 - event.turnItem.streaming &&
1277 - !reservedHeldTurnItemIds.has(event.turnItem.id)
1278 - ) {
1279 - yield* turnItemPositions.allocate({
1280 - threadId: event.turnItem.threadId,
1281 - turnItemId: event.turnItem.id,
1282 - runId: event.turnItem.runId,
1283 - });
1284 - reservedHeldTurnItemIds.add(event.turnItem.id);
1285 - }
1286 - if (event.type === "provider_thread.updated") {
1287 - if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
1288 - yield* Ref.set(latestProviderThread, event.providerThread);
1289 - }
1290 - }
1204 + }
1205 + return true;
1206 + });
1207 + const filterAssistantEvent = makeAssistantStreamingFilter(responseStreamingMode);
1208 + // Held text writes nothing, so its item would take a position only
1209 + // when finally written, behind every item that began after it.
1210 + const reservedHeldTurnItemIds = new Set<TurnItemId>();
1211 + const providerEventFiber = yield* eventSubscription.events.pipe(
1212 + Stream.filterEffect((event) =>
1213 + Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
1214 + ),
1215 + Stream.tap((event) =>
1216 + Effect.gen(function* () {
1217 + let storedEventCount = 0;
1218 + const deliveredEvent = filterAssistantEvent(
1219 + event,
1220 + DateTime.toEpochMillis(yield* DateTime.now),
1221 + );
1222 + if (deliveredEvent) {
1223 + const rootTerminalAlreadySeen = yield* Ref.get(rootTerminalSeen);
1224 + const isRootProviderThreadUpdate =
1225 + event.type === "provider_thread.updated" &&
1226 + event.providerThread.id === input.providerThread.id;
1227 + const storedEvents = yield* providerEventIngestor.ingestNormalized({
1228 + analyticsContext: {
1229 + modelSelection: input.modelSelection,
1230 + runtimeMode: input.runtimePolicy.runtimeMode,
1231 + interactionMode: input.runtimePolicy.interactionMode,
1232 + },
1233 + providerSessionId: input.providerSessionId,
1234 + providerInstanceId: input.run.providerInstanceId,
1235 + threadId: input.run.threadId,
1236 + runId: input.run.id,
1237 + nodeId: input.rootNode.id,
1238 + event: deliveredEvent,
1239 + ...(isRootProviderThreadUpdate
1240 + ? rootTerminalAlreadySeen
1241 + ? {
1242 + writeIfProviderThreadOwner: {
1243 + providerThreadId: input.providerThread.id,
1244 + runId: input.run.id,
1245 + activeAttemptId: input.attempt.id,
1246 + expectedLastRunOrdinal: input.run.ordinal,
1247 + },
1248 + }
1249 + : {
1250 + writeIfRunCurrent: {
1251 + runId: input.run.id,
1252 + activeAttemptId: input.attempt.id,
1253 + expectedStatus: "running" as const,
1254 + },
1255 + }
1256 + : {}),
1257 + });
1258 + storedEventCount = storedEvents.length;
1259 if (
1292 - event.type === "turn_item.updated" &&
1293 - event.turnItem.providerTurnId ===
1294 - (yield* Ref.get(eventRouting)).rootProviderTurnId
1260 + isRootProviderThreadUpdate &&
1261 + rootTerminalAlreadySeen &&
1262 + storedEventCount === 0
1263 ) {
1296 - yield* Ref.update(latestTurnItemOrdinal, (current) =>
1297 - Math.max(current, event.turnItem.ordinal),
1298 - );
1264 + yield* Ref.set(providerThreadOwnerLost, true);
1265 }
1300 - if (event.type === "turn.terminal") {
1301 - yield* Ref.set(terminalEvent, event);
1302 - yield* Ref.set(rootTerminalSeen, true);
1303 - yield* finalizeRootRun(event);
1266 + } else if (
1267 + event.type === "turn_item.updated" &&
1268 + (event.turnItem.type === "assistant_message" ||
1269 + event.turnItem.type === "reasoning") &&
1270 + event.turnItem.streaming &&
1271 + !reservedHeldTurnItemIds.has(event.turnItem.id)
1272 + ) {
1273 + yield* turnItemPositions.allocate({
1274 + threadId: event.turnItem.threadId,
1275 + turnItemId: event.turnItem.id,
1276 + runId: event.turnItem.runId,
1277 + });
1278 + reservedHeldTurnItemIds.add(event.turnItem.id);
1279 + }
1280 + if (event.type === "provider_thread.updated") {
1281 + if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
1282 + yield* Ref.set(latestProviderThread, event.providerThread);
1283 }
1305 - yield* trackChildLifecycle(event, deliveredEvent !== null);
1306 - }),
1307 - ),
1308 - Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
1309 - Stream.runDrain,
1310 - Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
1311 - Effect.flatMap(() =>
1312 - Effect.gen(function* () {
1313 - const terminal = yield* Ref.get(terminalEvent);
1314 - if (terminal === null) {
1315 - // A session release interrupts or fails the stream; a clean
1316 - // end without a terminal means the run would never settle.
1317 - return yield* new RunExecutionIngestError({
1284 + }
1285 + if (
1286 + event.type === "turn_item.updated" &&
1287 + event.turnItem.providerTurnId === (yield* Ref.get(eventRouting)).rootProviderTurnId
1288 + ) {
1289 + yield* Ref.update(latestTurnItemOrdinal, (current) =>
1290 + Math.max(current, event.turnItem.ordinal),
1291 + );
1292 + }
1293 + if (event.type === "turn.terminal") {
1294 + yield* Ref.set(terminalEvent, event);
1295 + yield* Ref.set(rootTerminalSeen, true);
1296 + yield* finalizeRootRun(event);
1297 + }
1298 + yield* trackChildLifecycle(event, deliveredEvent !== null);
1299 + }),
1300 + ),
1301 + Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
1302 + Stream.runDrain,
1303 + Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
1304 + Effect.flatMap(() =>
1305 + Effect.gen(function* () {
1306 + const terminal = yield* Ref.get(terminalEvent);
1307 + if (terminal === null) {
1308 + // A session release interrupts or fails the stream; a clean
1309 + // end without a terminal means the run would never settle.
1310 + return yield* new RunExecutionIngestError({
1311 + runId: input.run.id,
1312 + cause: new ProviderAdapter.ProviderAdapterEventStreamError({
1313 + driver: input.providerThread.driver,
1314 + providerSessionId: input.providerSessionId,
1315 + cause: "Provider event stream ended without a root terminal.",
1316 + }),
1317 + });
1318 + }
1319 + yield* finalizeRootRun(terminal);
1320 + }),
1321 + ),
1322 + // Server shutdown interrupts the subscription and leaves the run to
1323 + // restart recovery; every other failure fails the run.
1324 + Effect.catchCauseIf(
1325 + (cause) => !Cause.hasInterruptsOnly(cause),
1326 + (cause) =>
1327 + Ref.get(rootRunFinalized).pipe(
1328 + Effect.flatMap((finalized) =>
1329 + Effect.logWarning("orchestration V2 provider event ingestion failed", {
1330 runId: input.run.id,
1319 - cause: new ProviderAdapter.ProviderAdapterEventStreamError({
1320 - driver: input.providerThread.driver,
1321 - providerSessionId: input.providerSessionId,
1322 - cause: "Provider event stream ended without a root terminal.",
1323 - }),
1324 - });
1325 - }
1326 - yield* finalizeRootRun(terminal);
1327 - }),
1328 - ),
1329 - // Server shutdown interrupts the subscription and leaves the run to
1330 - // restart recovery; every other failure fails the run.
1331 - Effect.catchCauseIf(
1332 - (cause) => !Cause.hasInterruptsOnly(cause),
1333 - (cause) =>
1334 - Ref.get(rootRunFinalized).pipe(
1335 - Effect.flatMap((finalized) =>
1336 - Effect.logWarning("orchestration V2 provider event ingestion failed", {
1337 - runId: input.run.id,
1338 - cause,
1339 - }).pipe(
1340 - Effect.andThen(
1341 - finalized
1342 - ? Effect.void
1343 - : Ref.get(latestProviderThread).pipe(
1344 - Effect.flatMap((providerThread) =>
1345 - Ref.get(latestTurnItemOrdinal).pipe(
1346 - Effect.flatMap((latestItemOrdinal) =>
1347 - Ref.get(openRunOwnedSubagents).pipe(
1348 - Effect.flatMap((openSubagents) =>
1349 - writeFinalRunEvents({
1350 - run: input.run,
1351 - rootNode: input.rootNode,
1352 - checkpointScope: input.checkpointScope,
1353 - providerThread,
1354 - attempt: input.attempt,
1355 - writeIfRunCurrent: {
1356 - activeAttemptId: input.attempt.id,
1357 - expectedStatus: "running",
1358 - },
1359 - openRunOwnedSubagents: openSubagents,
1360 - terminal: makeFailedTerminalEvent(
1361 - makeProviderFailure({
1362 - cause: Cause.squash(cause),
1363 - class: "unknown",
1364 - }),
1365 - latestItemOrdinal + 1,
1366 - ),
1367 - failureItemPersisted: false,
1368 - refreshAfterTurn,
1369 - }),
1370 - ),
1331 + cause,
1332 + }).pipe(
1333 + Effect.andThen(
1334 + finalized
1335 + ? Effect.void
1336 + : Ref.get(latestProviderThread).pipe(
1337 + Effect.flatMap((providerThread) =>
1338 + Ref.get(latestTurnItemOrdinal).pipe(
1339 + Effect.flatMap((latestItemOrdinal) =>
1340 + Ref.get(openRunOwnedSubagents).pipe(
1341 + Effect.flatMap((openSubagents) =>
1342 + writeFinalRunEvents({
1343 + run: input.run,
1344 + rootNode: input.rootNode,
1345 + checkpointScope: input.checkpointScope,
1346 + providerThread,
1347 + attempt: input.attempt,
1348 + writeIfRunCurrent: {
1349 + activeAttemptId: input.attempt.id,
1350 + expectedStatus: "running",
1351 + },
1352 + openRunOwnedSubagents: openSubagents,
1353 + terminal: makeFailedTerminalEvent(
1354 + makeProviderFailure({
1355 + cause: Cause.squash(cause),
1356 + class: "unknown",
1357 + }),
1358 + latestItemOrdinal + 1,
1359 + ),
1360 + failureItemPersisted: false,
1361 + refreshAfterTurn,
1362 + }),
1363 ),
1364 ),
1365 ),
1366 ),
1367 ),
1376 - ),
1377 - Effect.mapError(
1378 - (writeCause) =>
1379 - new RunExecutionIngestError({
1380 - runId: input.run.id,
1381 - cause: { ingest: cause, write: writeCause },
1382 - }),
1383 - ),
1368 + ),
1369 + ),
1370 + Effect.mapError(
1371 + (writeCause) =>
1372 + new RunExecutionIngestError({
1373 + runId: input.run.id,
1374 + cause: { ingest: cause, write: writeCause },
1375 + }),
1376 ),
1377 ),
1378 ),
1387 - ),
1388 - Effect.ensuring(eventSubscription.close),
1389 - Effect.forkDetach,
1390 - );
1379 + ),
1380 + ),
1381 + Effect.ensuring(eventSubscription.close),
1382 + Effect.forkDetach,
1383 + );
1384
1392 - // A provider turn is a sign that the session is still alive. Keep
1393 - // its already-issued MCP credential valid even when the agent goes
1394 - // a long time between browser-tool calls.
1395 - yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId);
1396 - const appContext = (yield* mcpAppModelContext
1397 - .forThread(input.run.threadId)
1398 - .pipe(
1399 - Effect.catch((cause) =>
1400 - Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe(
1401 - Effect.as([]),
1402 - ),
1385 + // A provider turn is a sign that the session is still alive. Keep
1386 + // its already-issued MCP credential valid even when the agent goes
1387 + // a long time between browser-tool calls.
1388 + yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId);
1389 + const appContext = (yield* mcpAppModelContext
1390 + .forThread(input.run.threadId)
1391 + .pipe(
1392 + Effect.catch((cause) =>
1393 + Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe(
1394 + Effect.as([]),
1395 ),
1404 - )).map((entry) => ({
1405 - // The item id alone is unique and needs no escaping; server and
1406 - // tool names are free text that would break the tag Codex wraps
1407 - // the context in.
1408 - key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`,
1409 - text: entry.text,
1410 - }));
1411 - const turnInput = {
1412 - appThread: input.appThread,
1413 - threadId: input.run.threadId,
1414 - runId: input.run.id,
1415 - runOrdinal: input.run.ordinal,
1416 - providerTurnOrdinal: input.providerTurnOrdinal,
1417 - ...(input.nativeThreadHasTurns === undefined
1418 - ? {}
1419 - : { nativeThreadHasTurns: input.nativeThreadHasTurns }),
1420 - ...(input.run.restartContinuationOfRunId === undefined
1421 - ? {}
1422 - : {
1423 - restartContinuationOfRunId: input.run.restartContinuationOfRunId,
1424 - }),
1425 - attemptId: input.attemptId,
1426 - rootNodeId: input.rootNode.id,
1427 - providerThread: input.providerThread,
1428 - message: input.message,
1429 - modelSelection: input.modelSelection,
1430 - runtimePolicy: input.runtimePolicy,
1431 - ...(appContext.length === 0 ? {} : { appContext }),
1432 - };
1433 - // Check after the context read: ingestion can settle the run while
1434 - // it awaits. A failed ownership read fails the start below.
1435 - const shouldStart =
1436 - input.shouldStartProviderTurn === undefined
1437 - ? Exit.succeed(true)
1438 - : yield* Effect.exit(input.shouldStartProviderTurn());
1439 - if (Exit.isSuccess(shouldStart) && !shouldStart.value) {
1440 - yield* Fiber.interrupt(providerEventFiber);
1441 - return;
1442 - }
1396 + ),
1397 + )).map((entry) => ({
1398 + // The item id alone is unique and needs no escaping; server and
1399 + // tool names are free text that would break the tag Codex wraps
1400 + // the context in.
1401 + key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`,
1402 + text: entry.text,
1403 + }));
1404 + const turnInput = {
1405 + appThread: input.appThread,
1406 + threadId: input.run.threadId,
1407 + runId: input.run.id,
1408 + runOrdinal: input.run.ordinal,
1409 + providerTurnOrdinal: input.providerTurnOrdinal,
1410 + ...(input.nativeThreadHasTurns === undefined
1411 + ? {}
1412 + : { nativeThreadHasTurns: input.nativeThreadHasTurns }),
1413 + ...(input.run.restartContinuationOfRunId === undefined
1414 + ? {}
1415 + : {
1416 + restartContinuationOfRunId: input.run.restartContinuationOfRunId,
1417 + }),
1418 + attemptId: input.attemptId,
1419 + rootNodeId: input.rootNode.id,
1420 + providerThread: input.providerThread,
1421 + message: input.message,
1422 + modelSelection: input.modelSelection,
1423 + runtimePolicy: input.runtimePolicy,
1424 + ...(appContext.length === 0 ? {} : { appContext }),
1425 + };
1426 + // Check after the context read: ingestion can settle the run while
1427 + // it awaits. A failed ownership read fails the start below.
1428 + const shouldStart =
1429 + input.shouldStartProviderTurn === undefined
1430 + ? Exit.succeed(true)
1431 + : yield* Effect.exit(input.shouldStartProviderTurn());
1432 + if (Exit.isSuccess(shouldStart) && !shouldStart.value) {
1433 + yield* Fiber.interrupt(providerEventFiber);
1434 + return;
1435 + }
1436
1444 - const compact =
1445 - input.message.attachments.length === 0 &&
1446 - input.message.text.trim().toLowerCase() === "/compact";
1447 - const startTurn = compact
1448 - ? (input.session.compactThread?.(turnInput) ??
1449 - Effect.fail(
1450 - new ProviderAdapter.ProviderAdapterTurnStartError({
1451 - driver: input.session.driver,
1452 - threadId: input.run.threadId,
1453 - providerThreadId: input.providerThread.id,
1454 - runId: input.run.id,
1455 - cause: "This provider does not support context compaction.",
1456 - }),
1457 - ))
1458 - : input.session.startTurn(turnInput);
1459 - yield* Effect.andThen(shouldStart, startTurn).pipe(
1460 - Effect.catchCause((cause) =>
1461 - Effect.logError("orchestration V2 provider turn start failed", {
1437 + const compact =
1438 + input.message.attachments.length === 0 &&
1439 + input.message.text.trim().toLowerCase() === "/compact";
1440 + const startTurn = compact
1441 + ? (input.session.compactThread?.(turnInput) ??
1442 + Effect.fail(
1443 + new ProviderAdapter.ProviderAdapterTurnStartError({
1444 + driver: input.session.driver,
1445 + threadId: input.run.threadId,
1446 + providerThreadId: input.providerThread.id,
1447 runId: input.run.id,
1463 - cause,
1464 - }).pipe(
1465 - Effect.andThen(Fiber.interrupt(providerEventFiber)),
1466 - Effect.andThen(Ref.get(latestProviderThread)),
1467 - Effect.flatMap((providerThread) =>
1468 - Ref.get(latestTurnItemOrdinal).pipe(
1469 - Effect.flatMap((latestItemOrdinal) =>
1470 - Ref.get(openRunOwnedSubagents).pipe(
1471 - Effect.flatMap((openSubagents) =>
1472 - writeFinalRunEvents({
1473 - run: input.run,
1474 - rootNode: input.rootNode,
1475 - checkpointScope: input.checkpointScope,
1476 - providerThread,
1477 - attempt: input.attempt,
1478 - writeIfRunCurrent: {
1479 - activeAttemptId: input.attempt.id,
1480 - expectedStatus: "running",
1481 - },
1482 - openRunOwnedSubagents: openSubagents,
1483 - terminal: makeFailedTerminalEvent(
1484 - makeProviderFailure({
1485 - cause: Cause.squash(cause),
1486 - class: Exit.isFailure(shouldStart) ? "unknown" : "provider_error",
1487 - }),
1488 - latestItemOrdinal + 1,
1489 - ),
1490 - failureItemPersisted: false,
1491 - refreshAfterTurn,
1492 - }),
1493 - ),
1448 + cause: "This provider does not support context compaction.",
1449 + }),
1450 + ))
1451 + : input.session.startTurn(turnInput);
1452 + yield* Effect.andThen(shouldStart, startTurn).pipe(
1453 + Effect.catchCause((cause) =>
1454 + Effect.logError("orchestration V2 provider turn start failed", {
1455 + runId: input.run.id,
1456 + cause,
1457 + }).pipe(
1458 + Effect.andThen(Fiber.interrupt(providerEventFiber)),
1459 + Effect.andThen(Ref.get(latestProviderThread)),
1460 + Effect.flatMap((providerThread) =>
1461 + Ref.get(latestTurnItemOrdinal).pipe(
1462 + Effect.flatMap((latestItemOrdinal) =>
1463 + Ref.get(openRunOwnedSubagents).pipe(
1464 + Effect.flatMap((openSubagents) =>
1465 + writeFinalRunEvents({
1466 + run: input.run,
1467 + rootNode: input.rootNode,
1468 + checkpointScope: input.checkpointScope,
1469 + providerThread,
1470 + attempt: input.attempt,
1471 + writeIfRunCurrent: {
1472 + activeAttemptId: input.attempt.id,
1473 + expectedStatus: "running",
1474 + },
1475 + openRunOwnedSubagents: openSubagents,
1476 + terminal: makeFailedTerminalEvent(
1477 + makeProviderFailure({
1478 + cause: Cause.squash(cause),
1479 + class: Exit.isFailure(shouldStart) ? "unknown" : "provider_error",
1480 + }),
1481 + latestItemOrdinal + 1,
1482 + ),
1483 + failureItemPersisted: false,
1484 + refreshAfterTurn,
1485 + }),
1486 ),
1487 ),
1488 ),
1489 ),
1498 - Effect.mapError(
1499 - (writeCause) =>
1500 - new RunExecutionStartError({
1501 - commandId: input.commandId,
1502 - runId: input.run.id,
1503 - cause: { start: cause, write: writeCause },
1504 - }),
1505 - ),
1490 + ),
1491 + Effect.mapError(
1492 + (writeCause) =>
1493 + new RunExecutionStartError({
1494 + commandId: input.commandId,
1495 + runId: input.run.id,
1496 + cause: { start: cause, write: writeCause },
1497 + }),
1498 ),
1499 ),
1508 - );
1509 - }),
1500 + ),
1501 + );
1502 + }),
1503 } satisfies RunExecutionServiceV2Shape);
1504 }),
1505 );
apps/server/src/orchestration-v2/RunFinalizationService.ts
+6 -3
@@ -98,8 +98,8 @@ export const layerObserver = Layer.effect(
98 const pullRequests = yield* PullRequestService.PullRequestService;
99 return {
100 refreshAfterTurn: pullRequests.refreshAfterTurn,
101 - refresh: ({ cwd, threadId, runId }) =>
102 - Effect.gen(function* () {
101 + refresh: Effect.fn("RunFinalizationService.refresh")(
102 + function* ({ cwd, threadId, runId }) {
103 const [, local] = yield* Effect.all(
104 [workspaceEntries.refresh(cwd), vcsStatus.refreshLocalStatus(cwd)],
105 { concurrency: "unbounded" },
@@ -117,7 +117,10 @@ export const layerObserver = Layer.effect(
117 }),
118 ),
119 );
120 - }).pipe(Effect.mapError((cause) => new RunFinalizationRefreshError({ cwd, cause }))),
120 + },
121 + (effect, { cwd }) =>
122 + effect.pipe(Effect.mapError((cause) => new RunFinalizationRefreshError({ cwd, cause }))),
123 + ),
124 };
125 }),
126 );
apps/server/src/orchestration-v2/RuntimeRequestService.ts
+17 -14
@@ -74,8 +74,8 @@ export const layer: Layer.Layer<
74 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
75
76 return RuntimeRequestServiceV2.of({
77 - respond: (input) =>
78 - Effect.gen(function* () {
77 + respond: Effect.fn("RuntimeRequestService.respond")(
78 + function* (input) {
79 const request = yield* projections.getRuntimeRequest(input.threadId, input.requestId);
80 if (request === undefined) {
81 return yield* new RuntimeRequestResponseExecutionError({
@@ -120,19 +120,22 @@ export const layer: Layer.Layer<
120 ...(input.decision === undefined ? {} : { decision: input.decision }),
121 ...(input.answers === undefined ? {} : { answers: input.answers }),
122 });
123 - }).pipe(
124 - Effect.mapError((cause) =>
125 - isRuntimeRequestResponseExecutionError(cause)
126 - ? cause
127 - : new RuntimeRequestResponseExecutionError({
128 - reason: "unexpected-failure",
129 - threadId: input.threadId,
130 - providerSessionId: input.providerSessionId,
131 - requestId: input.requestId,
132 - cause,
133 - }),
123 + },
124 + (effect, input) =>
125 + effect.pipe(
126 + Effect.mapError((cause) =>
127 + isRuntimeRequestResponseExecutionError(cause)
128 + ? cause
129 + : new RuntimeRequestResponseExecutionError({
130 + reason: "unexpected-failure",
131 + threadId: input.threadId,
132 + providerSessionId: input.providerSessionId,
133 + requestId: input.requestId,
134 + cause,
135 + }),
136 + ),
137 ),
135 - ),
138 + ),
139 });
140 }),
141 );
apps/server/src/orchestration-v2/ThreadForkService.ts
+60 -61
@@ -72,68 +72,67 @@ export class ThreadForkServiceV2 extends Context.Service<
72 export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
73 ThreadForkServiceV2,
74 ThreadForkServiceV2.of({
75 - plan: (input) =>
76 - Effect.gen(function* () {
77 - if (!isForkableSourceRunStatus(input.sourceRun.status)) {
78 - return yield* new ThreadForkPlanError({
79 - sourceThreadId: input.sourceProjection.thread.id,
80 - targetThreadId: input.targetThreadId,
81 - cause: forkableSourceRunStatusError(input.sourceRun),
82 - });
83 - }
84 - const targetThread: OrchestrationV2AppThread = {
85 - ...input.sourceProjection.thread,
86 - // PR context follows the conversation; watching remains the source thread's responsibility.
87 - pullRequests: input.sourceProjection.thread.pullRequests?.map(
88 - ({ watch: _watch, ...link }) => link,
89 - ),
90 - createdBy: input.createdBy,
91 - creationSource: input.creationSource,
92 - id: input.targetThreadId,
93 - title: input.title ?? `${input.sourceProjection.thread.title} fork`,
94 - activeProviderThreadId: null,
95 - lineage: {
96 - parentThreadId: input.sourceProjection.thread.id,
97 - relationshipToParent: "fork",
98 - rootThreadId: input.sourceProjection.thread.lineage.rootThreadId,
99 - },
100 - forkedFrom: {
101 - type: "run",
102 - threadId: input.sourceProjection.thread.id,
103 - runId: input.sourceRun.id,
104 - },
105 - createdAt: input.createdAt,
106 - updatedAt: input.createdAt,
107 - archivedAt: null,
108 - settledOverride: null,
109 - settledAt: null,
110 - snoozedUntil: null,
111 - snoozedAt: null,
112 - lastVisitedAt: null,
113 - deletedAt: null,
114 - };
115 - const transfer: OrchestrationV2ContextTransfer = {
116 - id: input.transferId,
117 - type: "fork",
75 + plan: Effect.fn("ThreadForkService.plan")(function* (input) {
76 + if (!isForkableSourceRunStatus(input.sourceRun.status)) {
77 + return yield* new ThreadForkPlanError({
78 sourceThreadId: input.sourceProjection.thread.id,
79 targetThreadId: input.targetThreadId,
120 - sourcePoint: input.canonicalSourcePoint,
121 - basePoint: null,
122 - sourceProviderInstanceId: input.sourceRun.providerInstanceId,
123 - targetProviderInstanceId: null,
124 - targetRunId: null,
125 - status: "pending",
126 - resolution: null,
127 - createdBy: input.createdBy,
128 - error:
129 - input.sourceProviderThread?.nativeThreadRef?.strength === "strong"
130 - ? null
131 - : "Source provider thread does not expose a strong native thread ref.",
132 - createdAt: input.createdAt,
133 - updatedAt: input.createdAt,
134 - consumedAt: null,
135 - };
136 - return { targetThread, transfer };
137 - }),
80 + cause: forkableSourceRunStatusError(input.sourceRun),
81 + });
82 + }
83 + const targetThread: OrchestrationV2AppThread = {
84 + ...input.sourceProjection.thread,
85 + // PR context follows the conversation; watching remains the source thread's responsibility.
86 + pullRequests: input.sourceProjection.thread.pullRequests?.map(
87 + ({ watch: _watch, ...link }) => link,
88 + ),
89 + createdBy: input.createdBy,
90 + creationSource: input.creationSource,
91 + id: input.targetThreadId,
92 + title: input.title ?? `${input.sourceProjection.thread.title} fork`,
93 + activeProviderThreadId: null,
94 + lineage: {
95 + parentThreadId: input.sourceProjection.thread.id,
96 + relationshipToParent: "fork",
97 + rootThreadId: input.sourceProjection.thread.lineage.rootThreadId,
98 + },
99 + forkedFrom: {
100 + type: "run",
101 + threadId: input.sourceProjection.thread.id,
102 + runId: input.sourceRun.id,
103 + },
104 + createdAt: input.createdAt,
105 + updatedAt: input.createdAt,
106 + archivedAt: null,
107 + settledOverride: null,
108 + settledAt: null,
109 + snoozedUntil: null,
110 + snoozedAt: null,
111 + lastVisitedAt: null,
112 + deletedAt: null,
113 + };
114 + const transfer: OrchestrationV2ContextTransfer = {
115 + id: input.transferId,
116 + type: "fork",
117 + sourceThreadId: input.sourceProjection.thread.id,
118 + targetThreadId: input.targetThreadId,
119 + sourcePoint: input.canonicalSourcePoint,
120 + basePoint: null,
121 + sourceProviderInstanceId: input.sourceRun.providerInstanceId,
122 + targetProviderInstanceId: null,
123 + targetRunId: null,
124 + status: "pending",
125 + resolution: null,
126 + createdBy: input.createdBy,
127 + error:
128 + input.sourceProviderThread?.nativeThreadRef?.strength === "strong"
129 + ? null
130 + : "Source provider thread does not expose a strong native thread ref.",
131 + createdAt: input.createdAt,
132 + updatedAt: input.createdAt,
133 + consumedAt: null,
134 + };
135 + return { targetThread, transfer };
136 + }),
137 }),
138 );
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+4 -3
@@ -330,8 +330,8 @@ const make = Effect.gen(function* () {
330 }
331 yield* Effect.gen(function* () {
332 const initialMessage = input.initialMessage;
333 - const generateBranchNameFor = (cwd: string, message: ThreadLaunchInitialMessage) =>
334 - Effect.gen(function* () {
333 + const generateBranchNameFor = Effect.fn("ThreadLaunchService.generateBranchNameFor")(
334 + function* (cwd: string, message: ThreadLaunchInitialMessage) {
335 const settings = resolveProjectSettings(
336 yield* serverSettings.getSettings,
337 input.projectId,
@@ -363,7 +363,8 @@ const make = Effect.gen(function* () {
363 exactName: settings.branchNamingMode === "custom",
364 })),
365 );
366 - });
366 + },
367 + );
368
369 const requestedBranch = input.workspaceStrategy.branch;
370 let branch: string | null;
apps/server/src/orchestration-v2/ThreadManagementService.ts
+244 -237
@@ -748,184 +748,185 @@ const make = Effect.gen(function* () {
748 ),
749 );
750
751 - const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) =>
752 - Effect.gen(function* () {
753 - const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
754 - if (target.thread.archivedAt !== null) {
755 - return yield* new ThreadManagementThreadArchivedError({
751 + const sendToThread: ThreadManagementServiceShape["sendToThread"] = Effect.fn(
752 + "ThreadManagementService.sendToThread",
753 + )(function* (input) {
754 + const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
755 + if (target.thread.archivedAt !== null) {
756 + return yield* new ThreadManagementThreadArchivedError({
757 + threadId: input.threadId,
758 + });
759 + }
760 + const steerableRun = latestSteerableRun(target);
761 + let dispatchMode: Extract<
762 + OrchestrationV2Command,
763 + { readonly type: "message.dispatch" }
764 + >["dispatchMode"];
765 + if (input.mode === "steer" || input.mode === "restart") {
766 + if (steerableRun === undefined) {
767 + return yield* new ThreadManagementNoSteerableRunError({
768 threadId: input.threadId,
769 + mode: input.mode,
770 });
771 }
759 - const steerableRun = latestSteerableRun(target);
760 - let dispatchMode: Extract<
761 - OrchestrationV2Command,
762 - { readonly type: "message.dispatch" }
763 - >["dispatchMode"];
764 - if (input.mode === "steer" || input.mode === "restart") {
765 - if (steerableRun === undefined) {
766 - return yield* new ThreadManagementNoSteerableRunError({
767 - threadId: input.threadId,
768 - mode: input.mode,
769 - });
770 - }
771 - dispatchMode = {
772 - type: input.mode === "steer" ? "steer_active" : "restart_active",
773 - targetRunId: steerableRun.id,
774 - };
775 - } else if (input.mode === "auto" && steerableRun !== undefined) {
776 - dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
777 - } else {
778 - dispatchMode = {
779 - type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
780 - };
781 - }
772 + dispatchMode = {
773 + type: input.mode === "steer" ? "steer_active" : "restart_active",
774 + targetRunId: steerableRun.id,
775 + };
776 + } else if (input.mode === "auto" && steerableRun !== undefined) {
777 + dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
778 + } else {
779 + dispatchMode = {
780 + type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
781 + };
782 + }
783
783 - const dispatched = yield* dispatch({
784 - type: "message.dispatch",
785 - commandId: input.commandId,
784 + const dispatched = yield* dispatch({
785 + type: "message.dispatch",
786 + commandId: input.commandId,
787 + threadId: input.threadId,
788 + messageId: input.messageId,
789 + ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
790 + ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
791 + text: input.text,
792 + attachments: input.attachments,
793 + ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
794 + dispatchMode,
795 + createdBy: input.createdBy,
796 + creationSource: input.creationSource,
797 + });
798 + const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
799 + messageIds: [input.messageId],
800 + turnItemTypes: ["user_message"],
801 + });
802 + const message = projection.messages.find((candidate) => candidate.id === input.messageId);
803 + const run =
804 + message?.runId === null || message?.runId === undefined
805 + ? undefined
806 + : projection.runs.find((candidate) => candidate.id === message.runId);
807 + const turnItem =
808 + projection.turnItems.find(
809 + (
810 + candidate,
811 + ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
812 + candidate.type === "user_message" && candidate.messageId === input.messageId,
813 + ) ?? null;
814 + if (
815 + message === undefined ||
816 + run === undefined ||
817 + (turnItem === null && run.status !== "queued")
818 + ) {
819 + return yield* new ThreadManagementDurableRunProjectionError({
820 threadId: input.threadId,
821 messageId: input.messageId,
788 - ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
789 - ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
790 - text: input.text,
791 - attachments: input.attachments,
792 - ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
793 - dispatchMode,
794 - createdBy: input.createdBy,
795 - creationSource: input.creationSource,
822 });
797 - const projection = yield* getProjectThreadRecords(input, ["runs", "messages", "turnItems"], {
798 - messageIds: [input.messageId],
799 - turnItemTypes: ["user_message"],
823 + }
824 + const delivery: ThreadManagementSendResult["delivery"] =
825 + turnItem === null || turnItem.inputIntent === "queued_turn"
826 + ? "queued"
827 + : turnItem.inputIntent === "turn_start"
828 + ? "started"
829 + : input.mode === "restart"
830 + ? "restarted"
831 + : "steered";
832 + return { dispatch: dispatched, projection, message, run, turnItem, delivery };
833 + });
834 +
835 + const waitForThread: ThreadManagementServiceShape["waitForThread"] = Effect.fn(
836 + "ThreadManagementService.waitForThread",
837 + )(function* (input) {
838 + const loadError = (cause: unknown) =>
839 + new ThreadManagementProjectionLoadError({
840 + projectId: input.projectId,
841 + threadId: input.threadId,
842 + cause,
843 + });
844 + // Taken before the first read, so a run update between that read and
845 + // the subscription below still replays.
846 + const afterSequence = yield* orchestrator
847 + .getThreadEventSequence(input.threadId)
848 + .pipe(Effect.mapError(loadError));
849 + const target = yield* getProjectThreadRecords(input, ["runs"]);
850 + const selectedRun =
851 + input.runId === undefined
852 + ? latestRun(target)
853 + : target.runs.find((candidate) => candidate.id === input.runId);
854 + if (input.runId !== undefined && selectedRun === undefined) {
855 + return yield* new ThreadManagementRunNotFoundError({
856 + threadId: input.threadId,
857 + runId: input.runId,
858 });
801 - const message = projection.messages.find((candidate) => candidate.id === input.messageId);
802 - const run =
803 - message?.runId === null || message?.runId === undefined
804 - ? undefined
805 - : projection.runs.find((candidate) => candidate.id === message.runId);
806 - const turnItem =
807 - projection.turnItems.find(
808 - (
809 - candidate,
810 - ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
811 - candidate.type === "user_message" && candidate.messageId === input.messageId,
812 - ) ?? null;
813 - if (
814 - message === undefined ||
815 - run === undefined ||
816 - (turnItem === null && run.status !== "queued")
817 - ) {
818 - return yield* new ThreadManagementDurableRunProjectionError({
859 + }
860 + if (selectedRun === undefined) {
861 + return { threadId: input.threadId, run: null, timedOut: false };
862 + }
863 + // A restart cuts a run and continues it as a new run. Follow that chain,
864 + // so a cut run is not the answer while its continuation is pending.
865 + // Runs per matching event and is already covered by the waitForThread span.
866 + const outcome = Effect.fnUntraced(function* (runs: ReadonlyArray<OrchestrationV2Run>) {
867 + const current = runs.find((candidate) => candidate.id === selectedRun.id);
868 + if (current === undefined) {
869 + return yield* new ThreadManagementRunNotFoundError({
870 threadId: input.threadId,
820 - messageId: input.messageId,
871 + runId: selectedRun.id,
872 });
873 }
823 - const delivery: ThreadManagementSendResult["delivery"] =
824 - turnItem === null || turnItem.inputIntent === "queued_turn"
825 - ? "queued"
826 - : turnItem.inputIntent === "turn_start"
827 - ? "started"
828 - : input.mode === "restart"
829 - ? "restarted"
830 - : "steered";
831 - return { dispatch: dispatched, projection, message, run, turnItem, delivery };
874 + const run = latestRestartContinuation(runs, current);
875 + const pending =
876 + isTerminalRunStatus(run.status) && (yield* orchestrator.restartContinuationPending(run));
877 + return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };
878 });
879 + const initial = yield* outcome(target.runs);
880 + if (initial.settled) {
881 + return { threadId: input.threadId, run: initial.run, timedOut: false };
882 + }
883
834 - const waitForThread: ThreadManagementServiceShape["waitForThread"] = (input) =>
835 - Effect.gen(function* () {
836 - const loadError = (cause: unknown) =>
837 - new ThreadManagementProjectionLoadError({
838 - projectId: input.projectId,
884 + // A declined continuation records no event, so its effect settling wakes
885 + // the wait too.
886 + const wait = Stream.merge(
887 + Stream.merge(
888 + orchestrator.streamStoredEventsFrom({
889 threadId: input.threadId,
840 - cause,
841 - });
842 - // Taken before the first read, so a run update between that read and
843 - // the subscription below still replays.
844 - const afterSequence = yield* orchestrator
845 - .getThreadEventSequence(input.threadId)
846 - .pipe(Effect.mapError(loadError));
847 - const target = yield* getProjectThreadRecords(input, ["runs"]);
848 - const selectedRun =
849 - input.runId === undefined
850 - ? latestRun(target)
851 - : target.runs.find((candidate) => candidate.id === input.runId);
852 - if (input.runId !== undefined && selectedRun === undefined) {
853 - return yield* new ThreadManagementRunNotFoundError({
890 + afterSequence,
891 + eventType: "run.updated",
892 + }),
893 + orchestrator.streamStoredEventsFrom({
894 threadId: input.threadId,
855 - runId: input.runId,
856 - });
857 - }
858 - if (selectedRun === undefined) {
859 - return { threadId: input.threadId, run: null, timedOut: false };
860 - }
861 - // A restart cuts a run and continues it as a new run. Follow that chain,
862 - // so a cut run is not the answer while its continuation is pending.
863 - const outcome = (runs: ReadonlyArray<OrchestrationV2Run>) =>
864 - Effect.gen(function* () {
865 - const current = runs.find((candidate) => candidate.id === selectedRun.id);
866 - if (current === undefined) {
867 - return yield* new ThreadManagementRunNotFoundError({
868 - threadId: input.threadId,
869 - runId: selectedRun.id,
870 - });
871 - }
872 - const run = latestRestartContinuation(runs, current);
873 - const pending =
874 - isTerminalRunStatus(run.status) &&
875 - (yield* orchestrator.restartContinuationPending(run));
876 - return { run, pending, settled: isTerminalRunStatus(run.status) && !pending };
877 - });
878 - const initial = yield* outcome(target.runs);
879 - if (initial.settled) {
880 - return { threadId: input.threadId, run: initial.run, timedOut: false };
881 - }
882 -
883 - // A declined continuation records no event, so its effect settling wakes
884 - // the wait too.
885 - const wait = Stream.merge(
886 - Stream.merge(
887 - orchestrator.streamStoredEventsFrom({
888 - threadId: input.threadId,
889 - afterSequence,
890 - eventType: "run.updated",
891 - }),
892 - orchestrator.streamStoredEventsFrom({
893 - threadId: input.threadId,
894 - afterSequence,
895 - eventType: "thread.deleted",
896 - }),
897 - ).pipe(
898 - Stream.mapError(loadError),
899 - Stream.filter(
900 - (stored) =>
901 - stored.event.type !== "run.updated" ||
902 - stored.event.payload.id === selectedRun.id ||
903 - stored.event.payload.restartContinuationOfRunId !== undefined,
904 - ),
905 - ),
906 - initial.pending
907 - ? Stream.fromEffect(orchestrator.awaitRestartContinuation(initial.run))
908 - : Stream.empty,
895 + afterSequence,
896 + eventType: "thread.deleted",
897 + }),
898 ).pipe(
910 - Stream.mapEffect(() =>
911 - getProjectThreadRecords(input, ["runs"]).pipe(
912 - Effect.flatMap((current) => outcome(current.runs)),
913 - ),
899 + Stream.mapError(loadError),
900 + Stream.filter(
901 + (stored) =>
902 + stored.event.type !== "run.updated" ||
903 + stored.event.payload.id === selectedRun.id ||
904 + stored.event.payload.restartContinuationOfRunId !== undefined,
905 ),
915 - Stream.filter((current) => current.settled),
916 - Stream.runHead,
917 - Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
918 - );
919 - const waited = Option.flatten(yield* wait);
920 - if (Option.isSome(waited)) {
921 - return { threadId: input.threadId, run: waited.value.run, timedOut: false };
922 - }
923 - // The run may have reached a terminal status while the timeout was
924 - // winning the race; the final projection read decides what actually
925 - // happened, so only a still-active run counts as timed out.
926 - const final = yield* outcome((yield* getProjectThreadRecords(input, ["runs"])).runs);
927 - return { threadId: input.threadId, run: final.run, timedOut: !final.settled };
928 - });
906 + ),
907 + initial.pending
908 + ? Stream.fromEffect(orchestrator.awaitRestartContinuation(initial.run))
909 + : Stream.empty,
910 + ).pipe(
911 + Stream.mapEffect(() =>
912 + getProjectThreadRecords(input, ["runs"]).pipe(
913 + Effect.flatMap((current) => outcome(current.runs)),
914 + ),
915 + ),
916 + Stream.filter((current) => current.settled),
917 + Stream.runHead,
918 + Effect.timeoutOption(Duration.millis(Math.max(1, input.timeoutMs))),
919 + );
920 + const waited = Option.flatten(yield* wait);
921 + if (Option.isSome(waited)) {
922 + return { threadId: input.threadId, run: waited.value.run, timedOut: false };
923 + }
924 + // The run may have reached a terminal status while the timeout was
925 + // winning the race; the final projection read decides what actually
926 + // happened, so only a still-active run counts as timed out.
927 + const final = yield* outcome((yield* getProjectThreadRecords(input, ["runs"])).runs);
928 + return { threadId: input.threadId, run: final.run, timedOut: !final.settled };
929 + });
930
931 const settleAfterRun: ThreadManagementServiceShape["settleAfterRun"] = Effect.fn(
932 "orchestrationV2.threadManagement.settleAfterRun",
@@ -959,55 +960,58 @@ const make = Effect.gen(function* () {
960 return { sequence: result.sequence };
961 });
962
962 - const interruptThread: ThreadManagementServiceShape["interruptThread"] = (input) =>
963 - Effect.gen(function* () {
964 - const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
965 - const explicitRun =
966 - input.runId === undefined
967 - ? undefined
968 - : target.runs.find((candidate) => candidate.id === input.runId);
969 - if (input.runId !== undefined && explicitRun === undefined) {
970 - return yield* new ThreadManagementRunNotFoundError({
971 - threadId: input.threadId,
972 - runId: input.runId,
973 - });
974 - }
975 - if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
976 - return {
977 - type: "already_terminal",
978 - run: explicitRun as OrchestrationV2Run & {
979 - readonly status: ThreadManagementTerminalRunStatus;
980 - },
981 - } as const;
982 - }
983 - const interruptibleRun = latestActiveRun(target);
984 - if (interruptibleRun === undefined) {
985 - if (input.runId === undefined) {
986 - return { type: "no_active_run" } as const;
987 - }
988 - return yield* new ThreadManagementThreadNotInterruptibleError({
989 - threadId: input.threadId,
990 - runId: input.runId,
991 - });
992 - }
993 - if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
994 - return yield* new ThreadManagementThreadNotInterruptibleError({
995 - threadId: input.threadId,
996 - runId: input.runId,
997 - });
963 + const interruptThread: ThreadManagementServiceShape["interruptThread"] = Effect.fn(
964 + "ThreadManagementService.interruptThread",
965 + )(function* (input) {
966 + const target = yield* getProjectThreadRecords(input, ["runs", "providerTurns"]);
967 + const explicitRun =
968 + input.runId === undefined
969 + ? undefined
970 + : target.runs.find((candidate) => candidate.id === input.runId);
971 + if (input.runId !== undefined && explicitRun === undefined) {
972 + return yield* new ThreadManagementRunNotFoundError({
973 + threadId: input.threadId,
974 + runId: input.runId,
975 + });
976 + }
977 + if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
978 + return {
979 + type: "already_terminal",
980 + run: explicitRun as OrchestrationV2Run & {
981 + readonly status: ThreadManagementTerminalRunStatus;
982 + },
983 + } as const;
984 + }
985 + const interruptibleRun = latestActiveRun(target);
986 + if (interruptibleRun === undefined) {
987 + if (input.runId === undefined) {
988 + return { type: "no_active_run" } as const;
989 }
999 - const dispatch = yield* orchestrator.dispatch({
1000 - type: "run.interrupt",
1001 - commandId: input.commandId,
990 + return yield* new ThreadManagementThreadNotInterruptibleError({
991 threadId: input.threadId,
1003 - runId: interruptibleRun.id,
1004 - ...(input.reason === undefined ? {} : { reason: input.reason }),
992 + runId: input.runId,
993 + });
994 + }
995 + if (input.runId !== undefined && interruptibleRun.id !== input.runId) {
996 + return yield* new ThreadManagementThreadNotInterruptibleError({
997 + threadId: input.threadId,
998 + runId: input.runId,
999 });
1006 - return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
1000 + }
1001 + const dispatch = yield* orchestrator.dispatch({
1002 + type: "run.interrupt",
1003 + commandId: input.commandId,
1004 + threadId: input.threadId,
1005 + runId: interruptibleRun.id,
1006 + ...(input.reason === undefined ? {} : { reason: input.reason }),
1007 });
1008 + return { type: "interrupt_requested", run: interruptibleRun, dispatch } as const;
1009 + });
1010
1009 - const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = (input) =>
1010 - Effect.gen(function* () {
1011 + const stopWorkflow: ThreadManagementServiceShape["stopWorkflow"] = Effect.fn(
1012 + "ThreadManagementService.stopWorkflow",
1013 + )(
1014 + function* (input) {
1015 const records = yield* orchestrator
1016 .getThreadRecords(input.threadId, ["subagents", "runs", "providerThreads"])
1017 .pipe(
@@ -1088,39 +1092,42 @@ const make = Effect.gen(function* () {
1092 }),
1093 ),
1094 );
1091 - }).pipe((effect) => threadDispatch.withLock(input.threadId, effect));
1095 + },
1096 + (effect, input) => effect.pipe((effect) => threadDispatch.withLock(input.threadId, effect)),
1097 + );
1098
1093 - const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = (input) =>
1094 - Effect.gen(function* () {
1095 - const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
1096 - const failures: Array<
1097 - Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
1098 - > = [];
1099 - const stoppedChildThreadIds = new Set<ThreadId>();
1100 - for (const task of subagents) {
1101 - if (task.origin !== "app_owned" || task.childThreadId === null) continue;
1102 - const threadId = task.childThreadId;
1103 - // Follow-up tasks reuse a child thread; walk its subtree only once.
1104 - if (stoppedChildThreadIds.has(threadId)) continue;
1105 - stoppedChildThreadIds.add(threadId);
1106 - yield* dispatch({
1107 - type: "thread.stop",
1108 - commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
1109 - threadId,
1110 - ...(input.reason === undefined ? {} : { reason: input.reason }),
1111 - }).pipe(
1112 - Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
1113 - Effect.catch((error) =>
1114 - Effect.logWarning("Unable to stop a delegated task", {
1115 - parentThreadId: input.threadId,
1116 - threadId,
1117 - error,
1118 - }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1119 - ),
1120 - );
1121 - }
1122 - if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
1123 - });
1099 + const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn(
1100 + "ThreadManagementService.stopDelegatedTasks",
1101 + )(function* (input) {
1102 + const { subagents } = yield* orchestrator.getThreadRecords(input.threadId, ["subagents"]);
1103 + const failures: Array<
1104 + Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError
1105 + > = [];
1106 + const stoppedChildThreadIds = new Set<ThreadId>();
1107 + for (const task of subagents) {
1108 + if (task.origin !== "app_owned" || task.childThreadId === null) continue;
1109 + const threadId = task.childThreadId;
1110 + // Follow-up tasks reuse a child thread; walk its subtree only once.
1111 + if (stoppedChildThreadIds.has(threadId)) continue;
1112 + stoppedChildThreadIds.add(threadId);
1113 + yield* dispatch({
1114 + type: "thread.stop",
1115 + commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
1116 + threadId,
1117 + ...(input.reason === undefined ? {} : { reason: input.reason }),
1118 + }).pipe(
1119 + Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
1120 + Effect.catch((error) =>
1121 + Effect.logWarning("Unable to stop a delegated task", {
1122 + parentThreadId: input.threadId,
1123 + threadId,
1124 + error,
1125 + }).pipe(Effect.andThen(Effect.sync(() => failures.push(error)))),
1126 + ),
1127 + );
1128 + }
1129 + if (failures[0] !== undefined) return yield* Effect.fail(failures[0]);
1130 + });
1131
1132 return ThreadManagementService.of({
1133 ensureLegacyTranscript,
apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
+11 -10
@@ -361,9 +361,10 @@ const make = Effect.gen(function* () {
361 ORDER BY created_at ASC, message_id ASC
362 `;
363
364 - const listShellMessages = (threadId: ThreadId) =>
365 - Effect.gen(function* () {
366 - const latest = yield* sql<LegacyMessageRow>`
364 + const listShellMessages = Effect.fn("LegacyV1ThreadImporter.listShellMessages")(function* (
365 + threadId: ThreadId,
366 + ) {
367 + const latest = yield* sql<LegacyMessageRow>`
368 SELECT
369 message.message_id,
370 message.thread_id,
@@ -393,7 +394,7 @@ const make = Effect.gen(function* () {
394 ORDER BY message.created_at DESC, message.message_id DESC
395 LIMIT 1
396 `;
396 - const latestUser = yield* sql<LegacyMessageRow>`
397 + const latestUser = yield* sql<LegacyMessageRow>`
398 SELECT
399 message.message_id,
400 message.thread_id,
@@ -423,12 +424,12 @@ const make = Effect.gen(function* () {
424 ORDER BY message.created_at DESC, message.message_id DESC
425 LIMIT 1
426 `;
426 - return [latestUser[0], latest[0]].filter(
427 - (message, index, selected): message is LegacyMessageRow =>
428 - message !== undefined &&
429 - selected.findIndex((candidate) => candidate?.message_id === message.message_id) === index,
430 - );
431 - });
427 + return [latestUser[0], latest[0]].filter(
428 + (message, index, selected): message is LegacyMessageRow =>
429 + message !== undefined &&
430 + selected.findIndex((candidate) => candidate?.message_id === message.message_id) === index,
431 + );
432 + });
433
434 const reconcileShellsBase = Effect.gen(function* () {
435 const now = DateTime.formatIso(yield* DateTime.now);