Open History to see the last commit
1import type {
2 OrchestrationV2ConversationMessage,
3 OrchestrationV2Notification,
4 OrchestrationV2NotificationSource,
5 OrchestrationV2Subagent,
6 OrchestrationV2TurnItem,
7 ThreadId,
8} from "@t3tools/contracts";
9
10type NotificationOutcome = OrchestrationV2Notification["outcome"];
11
12export type BackgroundWork = {
13 readonly label?: string | undefined;
14} & (
15 | { readonly kind: "subagent"; readonly childThreadId?: ThreadId | undefined }
16 | { readonly kind: "command"; readonly exitCode?: number | undefined }
17 | { readonly kind: "monitor" }
18 | { readonly kind: "background_task" }
19);
20
21export type BackgroundWorkReport = BackgroundWork & { readonly outcome: NotificationOutcome };
22
23const LABEL_MAX_LENGTH = 80;
24
25export function reportLabel(label: string | undefined): string | undefined {
26 const firstLine = label?.trim().split("\n")[0]?.trim();
27 if (firstLine === undefined || firstLine.length === 0) return undefined;
28 return firstLine.length > LABEL_MAX_LENGTH
29 ? `${firstLine.slice(0, LABEL_MAX_LENGTH - 1)}…`
30 : firstLine;
31}
32
33const KIND_NOUN: Record<BackgroundWork["kind"], readonly [string, string]> = {
34 subagent: ["Subagent", "subagents"],
35 command: ["Command", "commands"],
36 monitor: ["Monitor", "monitors"],
37 background_task: ["Background task", "background tasks"],
38};
39
40function outcomeVerb(kind: BackgroundWork["kind"], outcome: NotificationOutcome) {
41 switch (outcome) {
42 case "failed":
43 return "failed";
44 case "cancelled":
45 return "was stopped";
46 case "updated":
47 return kind === "monitor" ? "reported new output" : "updated";
48 case "completed":
49 case "unknown":
50 return "finished";
51 }
52}
53
54function combinedOutcome(outcomes: ReadonlyArray<NotificationOutcome>): NotificationOutcome {
55 if (outcomes.includes("failed")) return "failed";
56 if (outcomes.includes("cancelled")) return "cancelled";
57 if (outcomes.length > 0 && outcomes.every((outcome) => outcome === "completed")) {
58 return "completed";
59 }
60 return outcomes.includes("updated") ? "updated" : "unknown";
61}
62
63function exitSuffix(report: BackgroundWorkReport): string {
64 return report.kind === "command" && report.exitCode !== undefined
65 ? ` (exit ${report.exitCode})`
66 : "";
67}
68
69function namedReport(report: BackgroundWorkReport, capitalize: boolean): string {
70 const noun = KIND_NOUN[report.kind][0];
71 const label = reportLabel(report.label);
72 const named = `${capitalize ? noun : noun.toLowerCase()}${label === undefined ? "" : ` "${label}"`}`;
73 return `${named}${exitSuffix(report)}`;
74}
75
76function joinNames(names: ReadonlyArray<string>): string {
77 if (names.length <= 1) return names.join("");
78 return `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
79}
80
81function reportsSummary(
82 reports: readonly [BackgroundWorkReport, ...ReadonlyArray<BackgroundWorkReport>],
83 outcome: NotificationOutcome,
84): string {
85 const [first] = reports;
86 if (reports.length === 1) {
87 const label = reportLabel(first.label);
88 const noun = KIND_NOUN[first.kind][0];
89 return `${noun}${label === undefined ? "" : ` "${label}"`} ${outcomeVerb(first.kind, first.outcome)}${exitSuffix(first)}`;
90 }
91 const verb =
92 outcome === "failed"
93 ? "failed"
94 : outcome === "cancelled"
95 ? "were stopped"
96 : outcome === "updated"
97 ? "updated"
98 : "finished";
99 if (reports.length > 3 || reports.every((report) => reportLabel(report.label) === undefined)) {
100 const kinds = new Set(reports.map((report) => report.kind));
101 const noun = kinds.size === 1 ? KIND_NOUN[first.kind][1] : "background tasks";
102 return `${reports.length} ${noun} ${verb}`;
103 }
104 return `${joinNames(reports.map((report, index) => namedReport(report, index === 0)))} ${verb}`;
105}
106
107function reportsSource(
108 reports: readonly [BackgroundWorkReport, ...ReadonlyArray<BackgroundWorkReport>],
109): OrchestrationV2NotificationSource {
110 const [first, ...rest] = reports;
111 if (rest.some((report) => report.kind !== first.kind)) return { kind: "background_task" };
112 switch (first.kind) {
113 case "subagent":
114 return rest.length === 0 && first.childThreadId !== undefined
115 ? { kind: "subagent", childThreadId: first.childThreadId }
116 : { kind: "subagent" };
117 case "command":
118 case "monitor":
119 case "background_task":
120 return { kind: first.kind };
121 }
122}
123
124export function backgroundWorkNotification(
125 reports: readonly [BackgroundWorkReport, ...ReadonlyArray<BackgroundWorkReport>],
126): OrchestrationV2Notification;
127export function backgroundWorkNotification(
128 reports: ReadonlyArray<BackgroundWorkReport>,
129): OrchestrationV2Notification | null;
130export function backgroundWorkNotification(
131 reports: ReadonlyArray<BackgroundWorkReport>,
132): OrchestrationV2Notification | null {
133 const [first, ...rest] = reports;
134 if (first === undefined) return null;
135 const outcome = combinedOutcome(reports.map((report) => report.outcome));
136 return {
137 source: reportsSource([first, ...rest]),
138 outcome,
139 summary: reportsSummary([first, ...rest], outcome),
140 };
141}
142
143function delegatedTaskReport(
144 task: OrchestrationV2Subagent | undefined,
145): Extract<BackgroundWorkReport, { readonly kind: "subagent" }> {
146 const outcome: NotificationOutcome =
147 task?.status === "failed"
148 ? "failed"
149 : task?.status === "cancelled" || task?.status === "interrupted"
150 ? "cancelled"
151 : task?.status === "completed"
152 ? "completed"
153 : "unknown";
154 return {
155 kind: "subagent",
156 label: task?.title?.trim() || task?.prompt,
157 outcome,
158 ...(task?.childThreadId == null ? {} : { childThreadId: task.childThreadId }),
159 };
160}
161
162function delegatedCompletionNotification(
163 completion: NonNullable<OrchestrationV2ConversationMessage["delegatedCompletion"]>,
164 tasks: ReadonlyArray<OrchestrationV2Subagent>,
165): OrchestrationV2Notification {
166 const taskIds = completion.taskIds;
167 const reports = taskIds.map((taskId) =>
168 delegatedTaskReport(tasks.find((task) => task.id === taskId)),
169 );
170 const delegatedByRun = tasks.filter(
171 (task) => task.origin === "app_owned" && task.runId === completion.parentRunId,
172 ).length;
173 const outcome = combinedOutcome(reports.map((report) => report.outcome));
174 const verb = outcome === "failed" ? "failed" : outcome === "cancelled" ? "stopped" : "finished";
175 const [only] = reports;
176 if (reports.length === 1 && only !== undefined) {
177 const label = reportLabel(only.label);
178 return {
179 source: {
180 kind: "delegated_task",
181 taskIds,
182 ...(only.childThreadId === undefined ? {} : { childThreadId: only.childThreadId }),
183 },
184 outcome,
185 summary: `Delegated task${label === undefined ? "" : ` "${label}"`} ${verb}`,
186 };
187 }
188 const labels = reports.flatMap((report) => reportLabel(report.label) ?? []);
189 const count =
190 delegatedByRun > taskIds.length
191 ? `${taskIds.length} of ${delegatedByRun}`
192 : `${taskIds.length}`;
193 return {
194 source: { kind: "delegated_task", taskIds },
195 outcome,
196 summary: `${count} delegated tasks ${verb}${labels.length === 0 ? "" : `: ${labels.join(", ")}`}`,
197 };
198}
199
200export function notificationTurnItem(
201 item: OrchestrationV2TurnItem,
202 message: Pick<OrchestrationV2ConversationMessage, "notification" | "delegatedCompletion">,
203 tasks: ReadonlyArray<OrchestrationV2Subagent>,
204): OrchestrationV2TurnItem {
205 if (item.type !== "user_message") return item;
206 const notification =
207 message.delegatedCompletion === undefined
208 ? message.notification
209 : delegatedCompletionNotification(message.delegatedCompletion, tasks);
210 if (notification === undefined) return item;
211 const {
212 type: _type,
213 messageId: _messageId,
214 inputIntent: _inputIntent,
215 text: _text,
216 attachments: _attachments,
217 createdBy: _createdBy,
218 creationSource: _creationSource,
219 scheduledTaskId: _scheduledTaskId,
220 ...base
221 } = item;
222 return { ...base, type: "notification", ...notification };
223}