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