Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RestartBackgroundNote.ts

625 lines24.0 KB

1import {
2 isDeliveredProviderTurn,
3 type NodeId,
4 type OrchestrationV2ConversationMessage,
5 type OrchestrationV2PendingBackgroundTask,
6 type OrchestrationV2ProviderThread,
7 type OrchestrationV2ProviderTurn,
8 type OrchestrationV2RestartCancelledBackgroundWork,
9 type OrchestrationV2Run,
10 type OrchestrationV2RunAttempt,
11 type OrchestrationV2Subagent,
12 type OrchestrationV2TurnItem,
13} from "@t3tools/contracts";
14import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection";
15import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
16import * as DateTime from "effect/DateTime";
17import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
18​
19type Work = OrchestrationV2RestartCancelledBackgroundWork;
20type Attempt = Pick<OrchestrationV2RunAttempt, "id" | "runId">;
21​
22const MAX_LABEL_LENGTH = 160;
23​
24function compactLabel(value: unknown, maxLength = MAX_LABEL_LENGTH): string | undefined {
25 if (typeof value !== "string") return undefined;
26 const text = value.replaceAll(/\s+/g, " ").trim();
27 if (text.length === 0) return undefined;
28 if (text.length <= maxLength) return text;
29 // Half an emoji serializes to a lone surrogate escape, which provider JSON parsers reject.
30 const last = text.charCodeAt(maxLength - 2);
31 const end = last >= 0xd800 && last <= 0xdbff ? maxLength - 2 : maxLength - 1;
32 return `${text.slice(0, end)}…`;
34​
35/** A bounded label that keeps its id suffix whole whenever it fits. */
36function labelWithId(name: unknown, fallback: string, suffix: string): string {
37 const budget = MAX_LABEL_LENGTH - suffix.length;
38 if (budget < 2) return compactLabel(`${fallback}${suffix}`) ?? fallback;
39 return `${compactLabel(name, budget) ?? compactLabel(fallback, budget)}${suffix}`;
41​
42/** resumeId overrides the item id for native resume, such as Codex's child provider-thread id. */
43export function cancelledTurnItemWork(
44 item: OrchestrationV2TurnItem,
45 resumeId?: string,
46): Work | undefined {
47 switch (item.type) {
48 case "subagent": {
49 const nativeId =
50 item.origin === "provider_native" ? (resumeId ?? item.nativeItemRef?.nativeId) : undefined;
51 return {
52 kind: "subagent",
53 label: labelWithId(
54 compactLabel(item.title) === undefined ? item.prompt : item.title,
55 "subagent",
56 nativeId == null
57 ? ""
58 : item.nativeItemRef?.driver === "claudeAgent"
59 ? ` (id ${nativeId}; resume it with SendMessage to '${nativeId}')`
60 : ` (id ${nativeId})`,
61 ),
62 id: item.id,
63 };
64 }
65 case "command_execution":
66 return {
67 kind: item.monitor === true ? "monitor" : "shell",
68 label: compactLabel(item.input) ?? compactLabel(item.title) ?? "background command",
69 id: item.id,
70 ...(item.completionWake === "always" ? { awaited: true as const } : {}),
71 };
72 case "dynamic_tool": {
73 const monitor =
74 item.input !== null &&
75 typeof item.input === "object" &&
76 Reflect.get(item.input, "persistent") === true;
77 return {
78 kind: monitor ? "monitor" : "task",
79 label: compactLabel(item.title) ?? compactLabel(item.toolName) ?? "background tool",
80 id: item.id,
81 };
82 }
83 default:
84 return undefined;
85 }
87​
88/** Returns the awaiting provider thread; native subagents can run on children while their launching turn awaits them. */
89export function awaitingProviderThreadId(
90 item: OrchestrationV2TurnItem,
91 runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "providerThreadId">>,
92): OrchestrationV2Run["providerThreadId"] | undefined {
93 const runProviderThreadId = runs.find((run) => run.id === item.runId)?.providerThreadId;
94 return item.type === "subagent" && item.origin === "provider_native"
95 ? (runProviderThreadId ?? item.providerThreadId)
96 : (item.providerThreadId ?? runProviderThreadId);
98​
99function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind"] {
100 switch (task.kind) {
101 case "command":
102 return "shell";
103 case "subagent":
104 return "subagent";
105 case "monitor":
106 return "monitor";
107 case "background_task":
108 return "task";
109 default:
110 task satisfies never;
111 return "task";
112 }
114​
115export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTask): Work {
116 if (task.parentTaskId !== undefined) {
117 return {
118 kind: "subagent",
119 label: labelWithId(task.description, "background task", ` (subagent ${task.parentTaskId})`),
120 id: task.parentTaskId,
121 };
122 }
123 const kind = restartWorkKind(task);
124 const description = compactLabel(task.description);
125 return {
126 kind,
127 label:
128 compactLabel(
129 description === undefined ? task.taskId : `${description} (id ${task.taskId})`,
130 ) ?? "background task",
131 id: task.taskId,
132 ...(task.awaited === true ? { awaited: true as const } : {}),
133 };
135​
136const MAX_NOTE_ENTRIES = 10;
137​
138/** Why background work stopped: a T3 server restart, or the provider process exiting under a live server. */
139export type BackgroundWorkLossCause = "server_restart" | "provider_exit";
140​
141/** Bounds entries and labels to protect the context budget. */
142export function restartCancelledBackgroundWorkNote(
143 work: ReadonlyArray<Work>,
144 cause: BackgroundWorkLossCause = "server_restart",
145): string {
146 const omitted = work.length - MAX_NOTE_ENTRIES;
147 return [
148 `Note: ${cause === "provider_exit" ? "the agent runtime process exited" : "the T3 server restarted"}, and this background work was cancelled before it finished. It will not report back on its own, so resume or restart what you still need and wait for its result:`,
149 ...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`),
150 ...(omitted > 0 ? [`- and ${omitted} more`] : []),
151 ].join("\n");
153​
154/** The run's delegated tasks may include ones a Stop interrupted. */
155export function cohortWasStopped(run: Pick<OrchestrationV2Run, "delegatedCompletion">): boolean {
156 return (
157 run.delegatedCompletion?.disposition === "stopped" ||
158 run.delegatedCompletion?.reopenedAfterStop === true
159 );
161​
162/**
163 * Delegated tasks a Stop on this provider thread interrupted, until a turn requested after they
164 * ended completes. A run's turn start reads tasks after its request, but can record startedAt
165 * later. A fresh context starts a new provider thread, so it never inherits the note.
166 */
167export function pendingStoppedDelegatedTasks(input: {
168 readonly providerThreadId: OrchestrationV2Run["providerThreadId"];
169 readonly runs: ReadonlyArray<OrchestrationV2Run>;
170 readonly providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>;
171 readonly attempts: ReadonlyArray<Attempt>;
172 readonly subagents: ReadonlyArray<OrchestrationV2Subagent>;
173 readonly compactionMessageIds: ReadonlySet<string>;
174}): ReadonlyArray<OrchestrationV2Subagent> {
175 const stoppedRunIds = new Set(
176 input.runs
177 .filter((run) => run.providerThreadId === input.providerThreadId && cohortWasStopped(run))
178 .map((run) => run.id),
179 );
180 if (stoppedRunIds.size === 0) return [];
181 const completedAttemptIds = new Set(
182 input.providerTurns
183 .filter((turn) => turn.status === "completed")
184 .map((turn) => turn.runAttemptId),
185 );
186 const completedRunIds = new Set<OrchestrationV2Run["id"]>();
187 for (const attempt of input.attempts) {
188 if (completedAttemptIds.has(attempt.id)) completedRunIds.add(attempt.runId);
189 }
190 let lastToldRequest = Number.NEGATIVE_INFINITY;
191 for (const run of input.runs) {
192 if (
193 run.providerThreadId === input.providerThreadId &&
194 !input.compactionMessageIds.has(run.userMessageId) &&
195 completedRunIds.has(run.id)
196 ) {
197 lastToldRequest = Math.max(lastToldRequest, DateTime.toEpochMillis(run.requestedAt));
198 }
199 }
200 return input.subagents.filter(
201 (task) =>
202 task.origin === "app_owned" &&
203 task.runId !== null &&
204 stoppedRunIds.has(task.runId) &&
205 task.status === "interrupted" &&
206 task.cancelledRunId === undefined &&
207 task.completionDelivery?.state === "disposed" &&
208 task.completedAt !== null &&
209 lastToldRequest <= DateTime.toEpochMillis(task.completedAt),
210 );
212​
213export function stoppedDelegatedTasksNote(tasks: ReadonlyArray<OrchestrationV2Subagent>): string {
214 const omitted = tasks.length - MAX_NOTE_ENTRIES;
215 return [
216 "Note: Stop on this thread also stopped these delegated tasks before they finished. They will not report back on their own, so check them with task_status and start again what you still need:",
217 ...tasks
218 .slice(0, MAX_NOTE_ENTRIES)
219 .map(
220 (task) =>
221 `- ${labelWithId(
222 compactLabel(task.title) === undefined ? task.prompt : task.title,
223 "delegated task",
224 ` (task ${task.id})`,
225 )}`,
226 ),
227 ...(omitted > 0 ? [`- and ${omitted} more`] : []),
228 ].join("\n");
230​
231type ProviderTurnState = Pick<
232 OrchestrationV2ProviderTurn,
233 "runAttemptId" | "providerThreadId" | "status" | "promptDropped"
234>;
235​
236export function isRestartNoteSource(
237 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
238 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
239): boolean {
240 return isNoteSource(source, (attemptId) =>
241 providerTurns.some((turn) => turn.runAttemptId === attemptId && turn.status === "cancelled"),
242 );
244​
245function isNoteSource(
246 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
247 attemptCancelled: (attemptId: OrchestrationV2Run["activeAttemptId"]) => boolean,
248): boolean {
249 return (
250 // Failed and interrupted turns never continue; recovery-cancelled waiting runs still qualify.
251 (source.status === "completed" ||
252 source.status === "waiting" ||
253 source.status === "cancelled") &&
254 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
255 !attemptCancelled(source.activeAttemptId)
256 );
258​
259/**
260 * Matches the Working-section hold: a shell or monitor wakes it only when the agent said it
261 * waits on it. Most are dev servers and their watchdogs, so their note waits for the next
262 * user message.
263 */
264export function isAwaitedWork(work: Pick<Work, "kind" | "awaited">): boolean {
265 return work.awaited === true || (work.kind !== "shell" && work.kind !== "monitor");
267​
268export function runOutcome(
269 run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork">,
270): OrchestrationV2Run["status"] {
271 return (run.status === "completed" || run.status === "cancelled") &&
272 (run.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
273 ? "interrupted"
274 : run.status;
276​
277/** The run whose continuation carries a provider thread's lost background work. */
278export function latestStartedRun(
279 runs: ReadonlyArray<OrchestrationV2Run>,
280 providerThreadId: OrchestrationV2Run["providerThreadId"],
281): OrchestrationV2Run | undefined {
282 return runs.reduce<OrchestrationV2Run | undefined>(
283 (latest, run) =>
284 run.providerThreadId === providerThreadId &&
285 run.status !== "queued" &&
286 run.status !== "rolled_back" &&
287 !neverStarted(run) &&
288 (latest === undefined || runRanAfter(run, latest))
289 ? run
290 : latest,
291 undefined,
292 );
294​
295/** Unstarted runs have no lost work to continue, except prepared continuations carrying a source run. */
296export function neverStarted(
297 run: Pick<OrchestrationV2Run, "startedAt" | "restartContinuationOfRunId">,
298): boolean {
299 return run.startedAt === null && run.restartContinuationOfRunId === undefined;
301​
302/** Restart-cancelled unstarted runs supersede nothing; user-stopped unstarted runs do. */
303export function cancelledBeforeStart(
304 run: Pick<OrchestrationV2Run, "status" | "startedAt" | "restartContinuationOfRunId">,
305): boolean {
306 return run.status === "cancelled" && neverStarted(run);
308​
309/** A follow-up task's runs: those tagged with it, and the untagged wakes for subagents they started. */
310export function delegatedTaskRuns(
311 projection: {
312 readonly runs: ReadonlyArray<OrchestrationV2Run>;
313 readonly messages: ReadonlyArray<
314 Pick<OrchestrationV2ConversationMessage, "runId" | "delegatedCompletion">
315 >;
316 },
317 taskId: NodeId,
318): ReadonlyArray<OrchestrationV2Run> {
319 const owned = new Set(
320 projection.runs.filter((run) => run.delegatedTaskId === taskId).map((run) => run.id),
321 );
322 const untagged = new Set(
323 projection.runs.filter((run) => run.delegatedTaskId === undefined).map((run) => run.id),
324 );
325 for (let grew = owned.size > 0; grew;) {
326 grew = false;
327 for (const { runId, delegatedCompletion } of projection.messages) {
328 if (
329 runId === null ||
330 !untagged.has(runId) ||
331 owned.has(runId) ||
332 delegatedCompletion === undefined ||
333 !owned.has(delegatedCompletion.parentRunId)
334 )
335 continue;
336 owned.add(runId);
337 grew = true;
338 }
339 }
340 return projection.runs.filter((run) => owned.has(run.id));
342​
343/**
344 * A follow-up task's runs still owe a subagent they started its result, or still await
345 * background work they started, as the original task waits on both.
346 */
347export function delegatedTaskAwaitsWork(
348 runs: ReadonlyArray<OrchestrationV2Run>,
349 child: {
350 readonly subagents: ReadonlyArray<
351 Pick<OrchestrationV2Subagent, "runId" | "status" | "completionDelivery">
352 >;
353 readonly providerThreads: ReadonlyArray<
354 Pick<OrchestrationV2ProviderThread, "pendingBackgroundTasks">
355 >;
356 },
357): boolean {
358 const runIds = new Set<string | null>(runs.map((run) => run.id));
359 return (
360 child.subagents.some((task) => runIds.has(task.runId) && subagentHoldsCompletion(task)) ||
361 child.providerThreads.some((thread) =>
362 backgroundWorkHoldsCompletion(
363 (thread.pendingBackgroundTasks ?? []).filter(
364 (task) => task.runId !== undefined && runIds.has(task.runId),
365 ),
366 ),
367 )
368 );
370​
371/** A follow-up task's latest run, passing over queued work it no longer waits on, as the original task does. */
372export function delegatedTaskResultRun(
373 runs: ReadonlyArray<OrchestrationV2Run>,
374): OrchestrationV2Run | undefined {
375 const taskRuns = runs.toSorted((a, b) => b.ordinal - a.ordinal);
376 const awaited = taskRuns.filter(
377 (run) => !cancelledBeforeStart(run) && !(run.status === "queued" && run.queueHeld === true),
378 );
379 // Executing work reports the task's state; a reordered queue can finish a newer run before an older one.
380 const executing = awaited.find((run) =>
381 ["preparing", "starting", "running", "waiting"].includes(run.status),
382 );
383 return executing ?? awaited.find((run) => run.status === "queued") ?? awaited[0] ?? taskRuns[0];
385​
386/** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */
387export function continuationFailedBeforePrompt(
388 run: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartContinuationOfRunId">,
389 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "promptDropped">>,
390): boolean {
391 return (
392 run.status === "failed" &&
393 run.restartContinuationOfRunId !== undefined &&
394 !providerTurns.some(
395 (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn),
396 )
397 );
399​
400const CONTINUATION_START_RETRY_DELAYS_MS = [60_000, 180_000];
401​
402/** Backoff before restarting a continuation that failed to start, or undefined to let it fail. */
403export function continuationStartRetryDelayMs(
404 run: OrchestrationV2Run,
405 projection: {
406 readonly runs: ReadonlyArray<OrchestrationV2Run>;
407 readonly providerTurns: ReadonlyArray<
408 Pick<ProviderTurnState, "runAttemptId" | "promptDropped">
409 >;
410 readonly turnItems: Parameters<typeof latestRootProviderFailure>[1];
411 },
412): number | undefined {
413 if (!continuationFailedBeforePrompt(run, projection.providerTurns)) return;
414 // These fail the same way however often they start.
415 const failureClass = latestRootProviderFailure(run, projection.turnItems)?.class;
416 if (
417 failureClass === "usage_limit" ||
418 failureClass === "permission_error" ||
419 failureClass === "validation_error"
420 )
421 return;
422 let failedStarts = 0;
423 for (
424 let current: OrchestrationV2Run | undefined = run;
425 current !== undefined && continuationFailedBeforePrompt(current, projection.providerTurns);
426 current = projection.runs.find(
427 (candidate) => candidate.id === current?.restartContinuationOfRunId,
428 )
429 )
430 failedStarts += 1;
431 return CONTINUATION_START_RETRY_DELAYS_MS[failedStarts - 1];
433​
434export function latestRestartContinuation(
435 runs: ReadonlyArray<OrchestrationV2Run>,
436 run: OrchestrationV2Run,
437): OrchestrationV2Run {
438 let current = run;
439 for (let hops = 0; hops < runs.length; hops++) {
440 const next = runs.find((candidate) => candidate.restartContinuationOfRunId === current.id);
441 if (next === undefined) break;
442 current = next;
443 }
444 return current;
446​
447export function isRestartContinuationSource(
448 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
449 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
450): boolean {
451 return isRestartNoteSource(source, providerTurns)
452 ? (source.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
453 : source.status === "cancelled";
455​
456/** Built once per call so long threads are read a bounded number of times, not once per run. */
457function continuationLookup(
458 runs: ReadonlyArray<OrchestrationV2Run>,
459 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
460 attempts: ReadonlyArray<Attempt>,
461) {
462 const runsById = new Map<string, OrchestrationV2Run>();
463 for (const run of runs) if (!runsById.has(run.id)) runsById.set(run.id, run);
464 const completedAttempts = new Set<string | null>();
465 const cancelledAttempts = new Set<string | null>();
466 for (const turn of providerTurns) {
467 if (turn.status === "completed") completedAttempts.add(turn.runAttemptId);
468 else if (turn.status === "cancelled") cancelledAttempts.add(turn.runAttemptId);
469 }
470 const completedRuns = new Set<string>();
471 for (const attempt of attempts)
472 if (completedAttempts.has(attempt.id)) completedRuns.add(attempt.runId);
473 return { runsById, completedAttempts, cancelledAttempts, completedRuns };
475​
476type ContinuationLookup = ReturnType<typeof continuationLookup>;
477​
478/** Running does not prove prompt acceptance; carry continuation notes until a completed turn proves delivery. */
479export function restartContinuationNote(
480 source: OrchestrationV2Run,
481 runs: ReadonlyArray<OrchestrationV2Run>,
482 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
483 attempts: ReadonlyArray<Attempt>,
484): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
485 return continuationNote(source, continuationLookup(runs, providerTurns, attempts));
487​
488function continuationNote(
489 source: OrchestrationV2Run,
490 { runsById, completedAttempts, cancelledAttempts, completedRuns }: ContinuationLookup,
491): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
492 let current = source;
493 let work = current.restartCancelledBackgroundWork ?? [];
494 const visited = new Set([current.id]);
495 while (
496 current.restartContinuationOfRunId !== undefined &&
497 !completedRuns.has(current.id) &&
498 !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId))
499 ) {
500 const previous = runsById.get(current.restartContinuationOfRunId);
501 if (previous === undefined || visited.has(previous.id)) break;
502 visited.add(previous.id);
503 current = previous;
504 work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work);
505 }
506 return {
507 work,
508 settled: isNoteSource(current, (attemptId) => cancelledAttempts.has(attemptId)),
509 };
511​
512export function isRestartNoteContinuation(
513 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
514 runs: ReadonlyArray<OrchestrationV2Run>,
515 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
516 attempts: ReadonlyArray<Attempt>,
517): boolean {
518 return (
519 run.restartContinuationOfRunId !== undefined &&
520 isNoteContinuation(run, continuationLookup(runs, providerTurns, attempts))
521 );
523​
524function isNoteContinuation(
525 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
526 lookup: ContinuationLookup,
527): boolean {
528 const source =
529 run.restartContinuationOfRunId === undefined
530 ? undefined
531 : lookup.runsById.get(run.restartContinuationOfRunId);
532 return source !== undefined && continuationNote(source, lookup).work.length > 0;
534​
535/** Derive delivery from later completed turns on the same provider thread, excluding compactions, resumes, and rolled-back runs. */
536export function pendingRestartCancelledBackgroundWork(input: {
537 readonly runs: ReadonlyArray<OrchestrationV2Run>;
538 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
539 /** Called only when an earlier run on the provider thread carries restart-note work. */
540 readonly compactionMessageIds: () => ReadonlySet<string>;
541 readonly run: Pick<
542 OrchestrationV2Run,
543 | "id"
544 | "ordinal"
545 | "completedAt"
546 | "userMessageId"
547 | "providerThreadId"
548 | "restartContinuationOfRunId"
549 | "activeAttemptId"
550 >;
551​
552 readonly attempts: ReadonlyArray<Attempt>;
553}): ReadonlyArray<Work> {
554 if (input.run.providerThreadId === null || input.run.restartContinuationOfRunId !== undefined)
555 return [];
556 const providerThreadId = input.run.providerThreadId;
557 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
558 const sources = sameThread.filter(
559 (source) =>
560 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 && runRanAfter(input.run, source),
561 );
562 // Threads whose server never restarted carry no notes; skip every other lookup for them.
563 if (sources.length === 0) return [];
564 const compactionMessageIds = input.compactionMessageIds();
565 const isCompaction = (run: typeof input.run) => compactionMessageIds.has(run.userMessageId);
566 if (isCompaction(input.run)) return [];
567 const deliveredAttemptIds = new Set(
568 input.providerTurns
569 .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed")
570 .map((turn) => turn.runAttemptId),
571 );
572 // Earlier attempts may already have delivered the note; a steer's replacement attempt must not repeat it.
573 const alreadyDelivered = input.attempts.some(
574 (attempt) =>
575 attempt.runId === input.run.id &&
576 attempt.id !== input.run.activeAttemptId &&
577 deliveredAttemptIds.has(attempt.id),
578 );
579 if (alreadyDelivered) return [];
580 const deliveredRunIds = new Set<string>();
581 for (const attempt of input.attempts)
582 if (deliveredAttemptIds.has(attempt.id)) deliveredRunIds.add(attempt.runId);
583 let lookup: ContinuationLookup | undefined;
584 // runRanAfter is a total order, so a source precedes some prompted run iff it precedes the latest one.
585 let latestPrompted: OrchestrationV2Run | undefined;
586 for (const candidate of sameThread) {
587 if (
588 candidate.id !== input.run.id &&
589 candidate.activeAttemptId !== null &&
590 candidate.status !== "rolled_back" &&
591 (deliveredAttemptIds.has(candidate.activeAttemptId) || deliveredRunIds.has(candidate.id)) &&
592 !isCompaction(candidate) &&
593 (candidate.restartContinuationOfRunId === undefined ||
594 isNoteContinuation(
595 candidate,
596 (lookup ??= continuationLookup(input.runs, input.providerTurns, input.attempts)),
597 )) &&
598 (latestPrompted === undefined || runRanAfter(candidate, latestPrompted))
599 )
600 latestPrompted = candidate;
601 }
602 return sources
603 .filter((source) => latestPrompted === undefined || !runRanAfter(latestPrompted, source))
604 .reduce<ReadonlyArray<Work>>(
605 (work, source) =>
606 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
607 [],
608 );
610​
611export function mergeRestartCancelledBackgroundWork(
612 current: ReadonlyArray<Work>,
613 added: ReadonlyArray<Work>,
614): ReadonlyArray<Work> {
615 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
616 const seen = new Set(current.map(identity));
617 const merged = [...current];
618 for (const entry of added) {
619 const key = identity(entry);
620 if (seen.has(key)) continue;
621 seen.add(key);
622 merged.push(entry);
623 }
624 return merged;