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: OrchestrationV2ThreadProjection,
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.getThreadProjection(request.threadId);
85 if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) {
86 yield* Effect.logInfo("orchestration-v2.provider-continuation.thread-archived", {
87 threadId: request.threadId,
88 providerThreadId: request.providerThreadId,
89 });
90 if (request.delegatedCompletion !== undefined) {
91 yield* clearRetryAttempt(
92 delegatedCompletionRetryKey(request, request.delegatedCompletion),
93 );
94 }
95 // No continuation turn will start to clear the adapter's sticky offer.
96 if (request.clearIfCurrent !== undefined) {
97 yield* request.clearIfCurrent();
98 } else if (request.dispatchIfCurrent !== undefined) {
99 // Backward compatibility for request producers without an explicit
100 // drop callback.
101 yield* request.dispatchIfCurrent(Effect.void);
102 }
103 return;
104 }
105 if (request.delegatedCompletion !== undefined) {
106 const retryKey = delegatedCompletionRetryKey(request, request.delegatedCompletion);
107 const delivery = currentDelegatedCompletionDelivery(
108 projection,
109 request.delegatedCompletion,
110 );
111 if (delivery === undefined) {
112 yield* clearRetryAttempt(retryKey);
113 return;
114 }
115 const commandId = yield* ids.allocate.command({
116 fixtureName: "delegated-completion",
117 commandName: "dispatch",
118 });
119 yield* threads.dispatch({
120 type: "message.dispatch",
121 commandId,
122 threadId: request.threadId,
123 messageId: delivery.messageId,
124 text: delegatedCompletionText(delivery.taskIds),
125 attachments: [],
126 dispatchMode: { type: "queue_after_active" },
127 createdBy: "agent",
128 creationSource: "server",
129 delegatedCompletion: {
130 parentRunId: request.delegatedCompletion.parentRunId,
131 generation: delivery.generation,
132 taskIds: delivery.taskIds,
133 },
134 });
135 yield* clearRetryAttempt(retryKey);
136 return;
137 }
138 // The ordinal is display metadata only: allocate.message appends a
139 // random UUID, so a stale projection read here cannot collide ids.
140 const messageId = yield* ids.allocate.message({
141 threadId: request.threadId,
142 ordinal: projection.messages.length + 1,
143 });
144 const commandId = CommandId.make(`provider-continuation:${messageId}`);
145 const dispatch = threads.dispatch({
146 type: "message.dispatch",
147 commandId,
148 threadId: request.threadId,
149 messageId,
150 text: request.detail ?? CONTINUATION_MESSAGE_TEXT,
151 notification: request.notification ?? {
152 source: { kind: "background_task" },
153 outcome: "updated",
154 summary: "Background activity updated",
155 },
156 attachments: [],
157 dispatchMode: { type: "queue_after_active" },
158 createdBy: "agent",
159 // "provider" marks an adapter-buffered wake, which ClaudeAdapterV2
160 // detects to attach the buffered CLI output and drop this text. A
161 // message_text wake has no buffered output, so it must not carry that
162 // marker or the turn settles immediately having prompted nothing.
163 creationSource: request.delivery === "message_text" ? "server" : "provider",
164 });
165 if (request.dispatchIfCurrent === undefined) {
166 yield* dispatch;
167 return;
168 }
169 yield* request.dispatchIfCurrent(dispatch);
170 },
171 );
172
173 yield* requests.take.pipe(
174 Effect.flatMap((request) =>
175 dispatchContinuation(request).pipe(
176 Effect.catchCause((cause) =>
177 Effect.gen(function* () {
178 yield* Effect.logWarning("orchestration-v2.provider-continuation.dispatch-failed", {
179 threadId: request.threadId,
180 providerThreadId: request.providerThreadId,
181 cause,
182 });
183 if (request.delegatedCompletion !== undefined) {
184 const completion = request.delegatedCompletion;
185 const retryKey = delegatedCompletionRetryKey(request, completion);
186 const retryDelay = yield* nextRetryDelay(retryKey);
187 yield* Effect.gen(function* () {
188 yield* Effect.sleep(`${retryDelay} millis`);
189 const projection = yield* threads.getThreadProjection(request.threadId);
190 if (currentDelegatedCompletionDelivery(projection, completion) !== undefined) {
191 yield* requests.offer(request);
192 } else {
193 yield* clearRetryAttempt(retryKey);
194 }
195 }).pipe(
196 Effect.catchCause((retryCause) =>
197 Effect.logWarning("orchestration-v2.provider-continuation.retry-check-failed", {
198 threadId: request.threadId,
199 providerThreadId: request.providerThreadId,
200 cause: retryCause,
201 }).pipe(Effect.andThen(requests.offer(request))),
202 ),
203 Effect.forkScoped,
204 );
205 }
206 }),
207 ),
208 ),
209 ),
210 Effect.forever,
211 Effect.forkScoped,
212 );
213 }),
214);