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