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

RestartBackgroundNote.ts

606 lines23.2 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/**
155 * Delegated tasks a Stop on this provider thread interrupted, until a turn requested after they
156 * ended completes. A run's turn start reads tasks after its request, but can record startedAt
157 * later. A fresh context starts a new provider thread, so it never inherits the note.
158 */
159export function pendingStoppedDelegatedTasks(input: {
160 readonly providerThreadId: OrchestrationV2Run["providerThreadId"];
161 readonly runs: ReadonlyArray<OrchestrationV2Run>;
162 readonly providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>;
163 readonly attempts: ReadonlyArray<Attempt>;
164 readonly subagents: ReadonlyArray<OrchestrationV2Subagent>;
165 readonly compactionMessageIds: ReadonlySet<string>;
166}): ReadonlyArray<OrchestrationV2Subagent> {
167 const stoppedRunIds = new Set(
168 input.runs
169 .filter(
170 (run) =>
171 run.providerThreadId === input.providerThreadId &&
172 run.delegatedCompletion?.disposition === "stopped",
173 )
174 .map((run) => run.id),
175 );
176 if (stoppedRunIds.size === 0) return [];
177 const completedAttemptIds = new Set(
178 input.providerTurns
179 .filter((turn) => turn.status === "completed")
180 .map((turn) => turn.runAttemptId),
181 );
182 const toldRunRequests = input.runs
183 .filter(
184 (run) =>
185 run.providerThreadId === input.providerThreadId &&
186 !input.compactionMessageIds.has(run.userMessageId) &&
187 input.attempts.some(
188 (attempt) => attempt.runId === run.id && completedAttemptIds.has(attempt.id),
189 ),
190 )
191 .map((run) => DateTime.toEpochMillis(run.requestedAt));
192 return input.subagents.filter(
193 (task) =>
194 task.origin === "app_owned" &&
195 task.runId !== null &&
196 stoppedRunIds.has(task.runId) &&
197 task.status === "interrupted" &&
198 task.cancelledRunId === undefined &&
199 task.completionDelivery?.state === "disposed" &&
200 task.completedAt !== null &&
201 !toldRunRequests.some(
202 (requestedAt) => requestedAt > DateTime.toEpochMillis(task.completedAt!),
203 ),
204 );
206​
207export function stoppedDelegatedTasksNote(tasks: ReadonlyArray<OrchestrationV2Subagent>): string {
208 const omitted = tasks.length - MAX_NOTE_ENTRIES;
209 return [
210 "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:",
211 ...tasks
212 .slice(0, MAX_NOTE_ENTRIES)
213 .map(
214 (task) =>
215 `- ${labelWithId(
216 compactLabel(task.title) === undefined ? task.prompt : task.title,
217 "delegated task",
218 ` (task ${task.id})`,
219 )}`,
220 ),
221 ...(omitted > 0 ? [`- and ${omitted} more`] : []),
222 ].join("\n");
224​
225type ProviderTurnState = Pick<
226 OrchestrationV2ProviderTurn,
227 "runAttemptId" | "providerThreadId" | "status" | "promptDropped"
228>;
229​
230export function isRestartNoteSource(
231 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
232 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
233): boolean {
234 return isNoteSource(source, (attemptId) =>
235 providerTurns.some((turn) => turn.runAttemptId === attemptId && turn.status === "cancelled"),
236 );
238​
239function isNoteSource(
240 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
241 attemptCancelled: (attemptId: OrchestrationV2Run["activeAttemptId"]) => boolean,
242): boolean {
243 return (
244 // Failed and interrupted turns never continue; recovery-cancelled waiting runs still qualify.
245 (source.status === "completed" ||
246 source.status === "waiting" ||
247 source.status === "cancelled") &&
248 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 &&
249 !attemptCancelled(source.activeAttemptId)
250 );
252​
253/**
254 * Matches the Working-section hold: a shell or monitor wakes it only when the agent said it
255 * waits on it. Most are dev servers and their watchdogs, so their note waits for the next
256 * user message.
257 */
258export function isAwaitedWork(work: Pick<Work, "kind" | "awaited">): boolean {
259 return work.awaited === true || (work.kind !== "shell" && work.kind !== "monitor");
261​
262export function runOutcome(
263 run: Pick<OrchestrationV2Run, "status" | "restartCancelledBackgroundWork">,
264): OrchestrationV2Run["status"] {
265 return (run.status === "completed" || run.status === "cancelled") &&
266 (run.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
267 ? "interrupted"
268 : run.status;
270​
271/** The run whose continuation carries a provider thread's lost background work. */
272export function latestStartedRun(
273 runs: ReadonlyArray<OrchestrationV2Run>,
274 providerThreadId: OrchestrationV2Run["providerThreadId"],
275): OrchestrationV2Run | undefined {
276 return runs.reduce<OrchestrationV2Run | undefined>(
277 (latest, run) =>
278 run.providerThreadId === providerThreadId &&
279 run.status !== "queued" &&
280 run.status !== "rolled_back" &&
281 !neverStarted(run) &&
282 (latest === undefined || runRanAfter(run, latest))
283 ? run
284 : latest,
285 undefined,
286 );
288​
289/** Unstarted runs have no lost work to continue, except prepared continuations carrying a source run. */
290export function neverStarted(
291 run: Pick<OrchestrationV2Run, "startedAt" | "restartContinuationOfRunId">,
292): boolean {
293 return run.startedAt === null && run.restartContinuationOfRunId === undefined;
295​
296/** Restart-cancelled unstarted runs supersede nothing; user-stopped unstarted runs do. */
297export function cancelledBeforeStart(
298 run: Pick<OrchestrationV2Run, "status" | "startedAt" | "restartContinuationOfRunId">,
299): boolean {
300 return run.status === "cancelled" && neverStarted(run);
302​
303/** A follow-up task's runs: those tagged with it, and the untagged wakes for subagents they started. */
304export function delegatedTaskRuns(
305 projection: {
306 readonly runs: ReadonlyArray<OrchestrationV2Run>;
307 readonly messages: ReadonlyArray<
308 Pick<OrchestrationV2ConversationMessage, "runId" | "delegatedCompletion">
309 >;
310 },
311 taskId: NodeId,
312): ReadonlyArray<OrchestrationV2Run> {
313 const owned = new Set(
314 projection.runs.filter((run) => run.delegatedTaskId === taskId).map((run) => run.id),
315 );
316 const untagged = new Set(
317 projection.runs.filter((run) => run.delegatedTaskId === undefined).map((run) => run.id),
318 );
319 for (let grew = owned.size > 0; grew;) {
320 grew = false;
321 for (const { runId, delegatedCompletion } of projection.messages) {
322 if (
323 runId === null ||
324 !untagged.has(runId) ||
325 owned.has(runId) ||
326 delegatedCompletion === undefined ||
327 !owned.has(delegatedCompletion.parentRunId)
328 )
329 continue;
330 owned.add(runId);
331 grew = true;
332 }
333 }
334 return projection.runs.filter((run) => owned.has(run.id));
336​
337/**
338 * A follow-up task's runs still owe a subagent they started its result, or still await
339 * background work they started, as the original task waits on both.
340 */
341export function delegatedTaskAwaitsWork(
342 runs: ReadonlyArray<OrchestrationV2Run>,
343 child: {
344 readonly subagents: ReadonlyArray<
345 Pick<OrchestrationV2Subagent, "runId" | "status" | "completionDelivery">
346 >;
347 readonly providerThreads: ReadonlyArray<
348 Pick<OrchestrationV2ProviderThread, "pendingBackgroundTasks">
349 >;
350 },
351): boolean {
352 const runIds = new Set<string | null>(runs.map((run) => run.id));
353 return (
354 child.subagents.some((task) => runIds.has(task.runId) && subagentHoldsCompletion(task)) ||
355 child.providerThreads.some((thread) =>
356 backgroundWorkHoldsCompletion(
357 (thread.pendingBackgroundTasks ?? []).filter(
358 (task) => task.runId !== undefined && runIds.has(task.runId),
359 ),
360 ),
361 )
362 );
364​
365/** A follow-up task's latest run, passing over queued work it no longer waits on, as the original task does. */
366export function delegatedTaskResultRun(
367 runs: ReadonlyArray<OrchestrationV2Run>,
368): OrchestrationV2Run | undefined {
369 const taskRuns = runs.toSorted((a, b) => b.ordinal - a.ordinal);
370 const awaited = taskRuns.filter(
371 (run) => !cancelledBeforeStart(run) && !(run.status === "queued" && run.queueHeld === true),
372 );
373 // Executing work reports the task's state; a reordered queue can finish a newer run before an older one.
374 const executing = awaited.find((run) =>
375 ["preparing", "starting", "running", "waiting"].includes(run.status),
376 );
377 return executing ?? awaited.find((run) => run.status === "queued") ?? awaited[0] ?? taskRuns[0];
379​
380/** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */
381export function continuationFailedBeforePrompt(
382 run: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartContinuationOfRunId">,
383 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "promptDropped">>,
384): boolean {
385 return (
386 run.status === "failed" &&
387 run.restartContinuationOfRunId !== undefined &&
388 !providerTurns.some(
389 (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn),
390 )
391 );
393​
394const CONTINUATION_START_RETRY_DELAYS_MS = [60_000, 180_000];
395​
396/** Backoff before restarting a continuation that failed to start, or undefined to let it fail. */
397export function continuationStartRetryDelayMs(
398 run: OrchestrationV2Run,
399 projection: {
400 readonly runs: ReadonlyArray<OrchestrationV2Run>;
401 readonly providerTurns: ReadonlyArray<
402 Pick<ProviderTurnState, "runAttemptId" | "promptDropped">
403 >;
404 readonly turnItems: Parameters<typeof latestRootProviderFailure>[1];
405 },
406): number | undefined {
407 if (!continuationFailedBeforePrompt(run, projection.providerTurns)) return;
408 // These fail the same way however often they start.
409 const failureClass = latestRootProviderFailure(run, projection.turnItems)?.class;
410 if (
411 failureClass === "usage_limit" ||
412 failureClass === "permission_error" ||
413 failureClass === "validation_error"
414 )
415 return;
416 let failedStarts = 0;
417 for (
418 let current: OrchestrationV2Run | undefined = run;
419 current !== undefined && continuationFailedBeforePrompt(current, projection.providerTurns);
420 current = projection.runs.find(
421 (candidate) => candidate.id === current?.restartContinuationOfRunId,
422 )
423 )
424 failedStarts += 1;
425 return CONTINUATION_START_RETRY_DELAYS_MS[failedStarts - 1];
427​
428export function isRestartContinuationSource(
429 source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
430 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
431): boolean {
432 return isRestartNoteSource(source, providerTurns)
433 ? (source.restartCancelledBackgroundWork ?? []).some(isAwaitedWork)
434 : source.status === "cancelled";
436​
437/** Built once per call so long threads are read a bounded number of times, not once per run. */
438function continuationLookup(
439 runs: ReadonlyArray<OrchestrationV2Run>,
440 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
441 attempts: ReadonlyArray<Attempt>,
442) {
443 const runsById = new Map<string, OrchestrationV2Run>();
444 for (const run of runs) if (!runsById.has(run.id)) runsById.set(run.id, run);
445 const completedAttempts = new Set<string | null>();
446 const cancelledAttempts = new Set<string | null>();
447 for (const turn of providerTurns) {
448 if (turn.status === "completed") completedAttempts.add(turn.runAttemptId);
449 else if (turn.status === "cancelled") cancelledAttempts.add(turn.runAttemptId);
450 }
451 const completedRuns = new Set<string>();
452 for (const attempt of attempts)
453 if (completedAttempts.has(attempt.id)) completedRuns.add(attempt.runId);
454 return { runsById, completedAttempts, cancelledAttempts, completedRuns };
456​
457type ContinuationLookup = ReturnType<typeof continuationLookup>;
458​
459/** Running does not prove prompt acceptance; carry continuation notes until a completed turn proves delivery. */
460export function restartContinuationNote(
461 source: OrchestrationV2Run,
462 runs: ReadonlyArray<OrchestrationV2Run>,
463 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
464 attempts: ReadonlyArray<Attempt>,
465): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
466 return continuationNote(source, continuationLookup(runs, providerTurns, attempts));
468​
469function continuationNote(
470 source: OrchestrationV2Run,
471 { runsById, completedAttempts, cancelledAttempts, completedRuns }: ContinuationLookup,
472): { readonly work: ReadonlyArray<Work>; readonly settled: boolean } {
473 let current = source;
474 let work = current.restartCancelledBackgroundWork ?? [];
475 const visited = new Set([current.id]);
476 while (
477 current.restartContinuationOfRunId !== undefined &&
478 !completedRuns.has(current.id) &&
479 !(current.activeAttemptId !== null && completedAttempts.has(current.activeAttemptId))
480 ) {
481 const previous = runsById.get(current.restartContinuationOfRunId);
482 if (previous === undefined || visited.has(previous.id)) break;
483 visited.add(previous.id);
484 current = previous;
485 work = mergeRestartCancelledBackgroundWork(current.restartCancelledBackgroundWork ?? [], work);
486 }
487 return {
488 work,
489 settled: isNoteSource(current, (attemptId) => cancelledAttempts.has(attemptId)),
490 };
492​
493export function isRestartNoteContinuation(
494 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
495 runs: ReadonlyArray<OrchestrationV2Run>,
496 providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
497 attempts: ReadonlyArray<Attempt>,
498): boolean {
499 return (
500 run.restartContinuationOfRunId !== undefined &&
501 isNoteContinuation(run, continuationLookup(runs, providerTurns, attempts))
502 );
504​
505function isNoteContinuation(
506 run: Pick<OrchestrationV2Run, "restartContinuationOfRunId">,
507 lookup: ContinuationLookup,
508): boolean {
509 const source =
510 run.restartContinuationOfRunId === undefined
511 ? undefined
512 : lookup.runsById.get(run.restartContinuationOfRunId);
513 return source !== undefined && continuationNote(source, lookup).work.length > 0;
515​
516/** Derive delivery from later completed turns on the same provider thread, excluding compactions, resumes, and rolled-back runs. */
517export function pendingRestartCancelledBackgroundWork(input: {
518 readonly runs: ReadonlyArray<OrchestrationV2Run>;
519 readonly providerTurns: ReadonlyArray<ProviderTurnState>;
520 /** Called only when an earlier run on the provider thread carries restart-note work. */
521 readonly compactionMessageIds: () => ReadonlySet<string>;
522 readonly run: Pick<
523 OrchestrationV2Run,
524 | "id"
525 | "ordinal"
526 | "completedAt"
527 | "userMessageId"
528 | "providerThreadId"
529 | "restartContinuationOfRunId"
530 | "activeAttemptId"
531 >;
532​
533 readonly attempts: ReadonlyArray<Attempt>;
534}): ReadonlyArray<Work> {
535 if (input.run.providerThreadId === null || input.run.restartContinuationOfRunId !== undefined)
536 return [];
537 const providerThreadId = input.run.providerThreadId;
538 const sameThread = input.runs.filter((run) => run.providerThreadId === providerThreadId);
539 const sources = sameThread.filter(
540 (source) =>
541 (source.restartCancelledBackgroundWork?.length ?? 0) > 0 && runRanAfter(input.run, source),
542 );
543 // Threads whose server never restarted carry no notes; skip every other lookup for them.
544 if (sources.length === 0) return [];
545 const compactionMessageIds = input.compactionMessageIds();
546 const isCompaction = (run: typeof input.run) => compactionMessageIds.has(run.userMessageId);
547 if (isCompaction(input.run)) return [];
548 const deliveredAttemptIds = new Set(
549 input.providerTurns
550 .filter((turn) => turn.providerThreadId === providerThreadId && turn.status === "completed")
551 .map((turn) => turn.runAttemptId),
552 );
553 // Earlier attempts may already have delivered the note; a steer's replacement attempt must not repeat it.
554 const alreadyDelivered = input.attempts.some(
555 (attempt) =>
556 attempt.runId === input.run.id &&
557 attempt.id !== input.run.activeAttemptId &&
558 deliveredAttemptIds.has(attempt.id),
559 );
560 if (alreadyDelivered) return [];
561 const deliveredRunIds = new Set<string>();
562 for (const attempt of input.attempts)
563 if (deliveredAttemptIds.has(attempt.id)) deliveredRunIds.add(attempt.runId);
564 let lookup: ContinuationLookup | undefined;
565 // runRanAfter is a total order, so a source precedes some prompted run iff it precedes the latest one.
566 let latestPrompted: OrchestrationV2Run | undefined;
567 for (const candidate of sameThread) {
568 if (
569 candidate.id !== input.run.id &&
570 candidate.activeAttemptId !== null &&
571 candidate.status !== "rolled_back" &&
572 (deliveredAttemptIds.has(candidate.activeAttemptId) || deliveredRunIds.has(candidate.id)) &&
573 !isCompaction(candidate) &&
574 (candidate.restartContinuationOfRunId === undefined ||
575 isNoteContinuation(
576 candidate,
577 (lookup ??= continuationLookup(input.runs, input.providerTurns, input.attempts)),
578 )) &&
579 (latestPrompted === undefined || runRanAfter(candidate, latestPrompted))
580 )
581 latestPrompted = candidate;
582 }
583 return sources
584 .filter((source) => latestPrompted === undefined || !runRanAfter(latestPrompted, source))
585 .reduce<ReadonlyArray<Work>>(
586 (work, source) =>
587 mergeRestartCancelledBackgroundWork(work, source.restartCancelledBackgroundWork ?? []),
588 [],
589 );
591​
592export function mergeRestartCancelledBackgroundWork(
593 current: ReadonlyArray<Work>,
594 added: ReadonlyArray<Work>,
595): ReadonlyArray<Work> {
596 const identity = (entry: Work) => entry.id ?? `${entry.kind}\u0000${entry.label}`;
597 const seen = new Set(current.map(identity));
598 const merged = [...current];
599 for (const entry of added) {
600 const key = identity(entry);
601 if (seen.has(key)) continue;
602 seen.add(key);
603 merged.push(entry);
604 }
605 return merged;