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