Open History to see the last commit
1import { CommandId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Ref from "effect/Ref";
5
6import { IdAllocatorV2 } from "./IdAllocator.ts";
7import {
8 type ProviderContinuationRequest,
9 ProviderContinuationRequests,
10} from "./ProviderContinuationRequests.ts";
11import { ThreadManagementService } from "./ThreadManagementService.ts";
12import { isUndeliveredMailboxSteer } from "./NotificationMailbox.ts";
13
14const CONTINUATION_MESSAGE_TEXT = "Background task completed.";
15
16function delegatedCompletionText(taskIds: ReadonlyArray<string>): string {
17 const taskList = taskIds.join(", ");
18 return taskIds.length === 1
19 ? `Delegated task ${taskList} reached a terminal state. Use task_status with taskId ${taskList} to read the result.`
20 : `Delegated tasks ${taskList} reached terminal states. Use task_status with each taskId to read the results.`;
21}
22
23function currentDelegatedCompletionDelivery(
24 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "runs" | "providerTurns">,
25 completion: NonNullable<ProviderContinuationRequest["delegatedCompletion"]>,
26) {
27 const sourceRun = projection.runs.find((candidate) => candidate.id === completion.parentRunId);
28 const delivery = sourceRun?.delegatedCompletion?.delivery;
29 const alreadyDispatched = projection.messages.some(
30 (message) => message.id === completion.messageId,
31 );
32 if (
33 sourceRun?.delegatedCompletion?.disposition !== "open" ||
34 delivery === null ||
35 delivery === undefined ||
36 delivery.generation !== completion.generation ||
37 delivery.messageId !== completion.messageId ||
38 (alreadyDispatched && !isUndeliveredMailboxSteer(projection, completion.messageId))
39 ) {
40 return undefined;
41 }
42 return delivery;
43}
44
45function delegatedCompletionRetryKey(
46 request: ProviderContinuationRequest,
47 completion: NonNullable<ProviderContinuationRequest["delegatedCompletion"]>,
48): string {
49 return `${request.threadId}:${completion.parentRunId}:${completion.generation}:${completion.messageId}`;
50}
51
52/**
53 * Drains ProviderContinuationRequests and dispatches an internal
54 * message.dispatch per request so the wake turn buffered by the adapter is
55 * ingested as a normal run. Delegated completions are durable mailbox offers:
56 * the orchestrator selects native steering or queued delivery under its thread
57 * lock. Adapter-buffered continuations still queue behind active work.
58 */
59export const workerLive = Layer.effectDiscard(
60 Effect.gen(function* () {
61 const ids = yield* IdAllocatorV2;
62 const requests = yield* ProviderContinuationRequests;
63 const threads = yield* ThreadManagementService;
64 const retryAttempts = yield* Ref.make(new Map<string, number>());
65
66 const clearRetryAttempt = (key: string) =>
67 Ref.update(retryAttempts, (current) => {
68 if (!current.has(key)) return current;
69 const updated = new Map(current);
70 updated.delete(key);
71 return updated;
72 });
73
74 const nextRetryDelay = (key: string) =>
75 Ref.modify(retryAttempts, (current) => {
76 const attempt = current.get(key) ?? 0;
77 const updated = new Map(current);
78 updated.set(key, attempt + 1);
79 return [Math.min(100 * 2 ** Math.min(attempt, 6), 5_000), updated] as const;
80 });
81
82 const dispatchContinuation = Effect.fn("ProviderContinuationService.dispatchContinuation")(
83 function* (request: ProviderContinuationRequest) {
84 const projection = yield* threads.getThreadRecords(
85 request.threadId,
86 ["messages", "runs", "providerTurns"],
87 {
88 messageIds:
89 request.delegatedCompletion === undefined
90 ? []
91 : [request.delegatedCompletion.messageId],
92 },
93 );
94 if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) {
95 yield* Effect.logInfo("orchestration-v2.provider-continuation.thread-archived", {
96 threadId: request.threadId,
97 providerThreadId: request.providerThreadId,
98 });
99 if (request.delegatedCompletion !== undefined) {
100 yield* clearRetryAttempt(
101 delegatedCompletionRetryKey(request, request.delegatedCompletion),
102 );
103 }
104 // No continuation turn will start to clear the adapter's sticky offer.
105 if (request.clearIfCurrent !== undefined) {
106 yield* request.clearIfCurrent();
107 } else if (request.dispatchIfCurrent !== undefined) {
108 // Backward compatibility for request producers without an explicit
109 // drop callback.
110 yield* request.dispatchIfCurrent(Effect.void);
111 }
112 return;
113 }
114 if (request.delegatedCompletion !== undefined) {
115 const retryKey = delegatedCompletionRetryKey(request, request.delegatedCompletion);
116 const delivery = currentDelegatedCompletionDelivery(
117 projection,
118 request.delegatedCompletion,
119 );
120 if (delivery === undefined) {
121 yield* clearRetryAttempt(retryKey);
122 return;
123 }
124 const commandId = yield* ids.allocate.command({
125 fixtureName: "delegated-completion",
126 commandName: "dispatch",
127 });
128 yield* threads.dispatch({
129 type: "message.dispatch",
130 commandId,
131 threadId: request.threadId,
132 messageId: delivery.messageId,
133 text: delegatedCompletionText(delivery.taskIds),
134 attachments: [],
135 dispatchMode: { type: "queue_after_active" },
136 createdBy: "agent",
137 creationSource: "server",
138 delegatedCompletion: {
139 parentRunId: request.delegatedCompletion.parentRunId,
140 generation: delivery.generation,
141 taskIds: delivery.taskIds,
142 },
143 });
144 yield* clearRetryAttempt(retryKey);
145 return;
146 }
147 // The ordinal is display metadata only: allocate.message appends a
148 // random UUID, so a stale projection read here cannot collide ids.
149 const messageId = yield* ids.allocate.message({
150 threadId: request.threadId,
151 ordinal: projection.messages.length + 1,
152 });
153 const commandId = CommandId.make(`provider-continuation:${messageId}`);
154 const dispatch = threads.dispatch({
155 type: "message.dispatch",
156 commandId,
157 threadId: request.threadId,
158 messageId,
159 text: request.detail ?? CONTINUATION_MESSAGE_TEXT,
160 notification: request.notification ?? {
161 source: { kind: "background_task" },
162 outcome: "updated",
163 summary: "Background activity updated",
164 },
165 attachments: [],
166 dispatchMode: { type: "queue_after_active" },
167 createdBy: "agent",
168 // "provider" marks an adapter-buffered wake, which ClaudeAdapterV2
169 // detects to attach the buffered CLI output and drop this text. A
170 // message_text wake has no buffered output, so it must not carry that
171 // marker or the turn settles immediately having prompted nothing.
172 creationSource: request.delivery === "message_text" ? "server" : "provider",
173 });
174 if (request.dispatchIfCurrent === undefined) {
175 yield* dispatch;
176 return;
177 }
178 yield* request.dispatchIfCurrent(dispatch);
179 },
180 );
181
182 yield* requests.take.pipe(
183 Effect.flatMap((request) =>
184 dispatchContinuation(request).pipe(
185 Effect.catchCause((cause) =>
186 Effect.gen(function* () {
187 yield* Effect.logWarning("orchestration-v2.provider-continuation.dispatch-failed", {
188 threadId: request.threadId,
189 providerThreadId: request.providerThreadId,
190 cause,
191 });
192 if (request.delegatedCompletion !== undefined) {
193 const completion = request.delegatedCompletion;
194 const retryKey = delegatedCompletionRetryKey(request, completion);
195 const retryDelay = yield* nextRetryDelay(retryKey);
196 yield* Effect.gen(function* () {
197 yield* Effect.sleep(`${retryDelay} millis`);
198 const projection = yield* threads.getThreadRecords(
199 request.threadId,
200 ["messages", "runs", "providerTurns"],
201 {
202 messageIds:
203 request.delegatedCompletion === undefined
204 ? []
205 : [request.delegatedCompletion.messageId],
206 },
207 );
208 if (currentDelegatedCompletionDelivery(projection, completion) !== undefined) {
209 yield* requests.offer(request);
210 } else {
211 yield* clearRetryAttempt(retryKey);
212 }
213 }).pipe(
214 Effect.catchCause((retryCause) =>
215 Effect.logWarning("orchestration-v2.provider-continuation.retry-check-failed", {
216 threadId: request.threadId,
217 providerThreadId: request.providerThreadId,
218 cause: retryCause,
219 }).pipe(Effect.andThen(requests.offer(request))),
220 ),
221 Effect.forkScoped,
222 );
223 }
224 }),
225 ),
226 ),
227 ),
228 Effect.forever,
229 Effect.forkScoped,
230 );
231 }),
232);