Open History to see the last commit
1import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
2import type {
3 CommandId,
4 EnvironmentId,
5 MessageId,
6 OrchestrationThread,
7 OrchestrationThreadActivity,
8 TurnId,
9 ToolLifecycleItemType,
10 ThreadId,
11 UserInputQuestion,
12} from "@t3tools/contracts";
13
14import type { DraftComposerImageAttachment } from "./composerImages";
15import * as Arr from "effect/Array";
16import * as Order from "effect/Order";
17
18export interface PendingApproval {
19 readonly requestId: ApprovalRequestId;
20 readonly requestKind: "command" | "file-read" | "file-change";
21 readonly createdAt: string;
22 readonly detail?: string;
23}
24
25export interface PendingUserInput {
26 readonly requestId: ApprovalRequestId;
27 readonly createdAt: string;
28 readonly questions: ReadonlyArray<UserInputQuestion>;
29}
30
31export interface PendingUserInputDraftAnswer {
32 readonly selectedOptionLabel?: string;
33 readonly customAnswer?: string;
34}
35
36export interface QueuedThreadMessage {
37 readonly environmentId: EnvironmentId;
38 readonly threadId: ThreadId;
39 readonly messageId: MessageId;
40 readonly commandId: CommandId;
41 readonly text: string;
42 readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
43 readonly createdAt: string;
44}
45
46export interface ThreadFeedActivity {
47 readonly id: string;
48 readonly createdAt: string;
49 readonly summary: string;
50 readonly detail: string | null;
51 readonly status: string | null;
52}
53
54interface WorkLogEntry {
55 id: string;
56 createdAt: string;
57 label: string;
58 detail?: string;
59 command?: string;
60 rawCommand?: string;
61 changedFiles?: ReadonlyArray<string>;
62 tone: "thinking" | "tool" | "info" | "error";
63 toolTitle?: string;
64 itemType?: ToolLifecycleItemType;
65 requestKind?: PendingApproval["requestKind"];
66}
67
68interface DerivedWorkLogEntry extends WorkLogEntry {
69 activityKind: OrchestrationThreadActivity["kind"];
70 collapseKey?: string;
71}
72
73type RawThreadFeedEntry =
74 | {
75 readonly type: "message";
76 readonly id: string;
77 readonly createdAt: string;
78 readonly message: OrchestrationThread["messages"][number];
79 }
80 | {
81 readonly type: "queued-message";
82 readonly id: string;
83 readonly createdAt: string;
84 readonly queuedMessage: QueuedThreadMessage;
85 readonly sending: boolean;
86 }
87 | {
88 readonly type: "activity";
89 readonly id: string;
90 readonly createdAt: string;
91 readonly activity: ThreadFeedActivity;
92 };
93
94export type ThreadFeedEntry =
95 | Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
96 | {
97 readonly type: "activity-group";
98 readonly id: string;
99 readonly createdAt: string;
100 readonly activities: ReadonlyArray<ThreadFeedActivity>;
101 };
102
103function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
104 switch (requestType) {
105 case "command_execution_approval":
106 case "exec_command_approval":
107 return "command";
108 case "file_read_approval":
109 return "file-read";
110 case "file_change_approval":
111 case "apply_patch_approval":
112 return "file-change";
113 default:
114 return null;
115 }
116}
117
118function isStalePendingRequestFailureDetail(detail: string | undefined): boolean {
119 const normalized = detail?.toLowerCase();
120 if (!normalized) {
121 return false;
122 }
123 return (
124 normalized.includes("stale pending approval request") ||
125 normalized.includes("stale pending user-input request") ||
126 normalized.includes("unknown pending approval request") ||
127 normalized.includes("unknown pending permission request") ||
128 normalized.includes("unknown pending user-input request")
129 );
130}
131
132function parseApprovalRequestId(value: unknown): ApprovalRequestId | null {
133 return typeof value === "string" && value.length > 0 ? ApprovalRequestId.make(value) : null;
134}
135
136function parseUserInputQuestions(
137 payload: Record<string, unknown> | null,
138): ReadonlyArray<UserInputQuestion> | null {
139 const questions = payload?.questions;
140 if (!Array.isArray(questions)) {
141 return null;
142 }
143
144 const parsed = questions
145 .map<UserInputQuestion | null>((entry) => {
146 if (!entry || typeof entry !== "object") return null;
147 const question = entry as Record<string, unknown>;
148 if (
149 typeof question.id !== "string" ||
150 typeof question.header !== "string" ||
151 typeof question.question !== "string" ||
152 !Array.isArray(question.options)
153 ) {
154 return null;
155 }
156 const options = question.options
157 .map<UserInputQuestion["options"][number] | null>((option) => {
158 if (!option || typeof option !== "object") return null;
159 const record = option as Record<string, unknown>;
160 if (typeof record.label !== "string" || typeof record.description !== "string") {
161 return null;
162 }
163 return {
164 label: record.label,
165 description: record.description,
166 };
167 })
168 .filter((option): option is UserInputQuestion["options"][number] => option !== null);
169 if (options.length === 0) {
170 return null;
171 }
172 return {
173 id: question.id,
174 header: question.header,
175 question: question.question,
176 options,
177 multiSelect: question.multiSelect === true,
178 };
179 })
180 .filter((question): question is UserInputQuestion => question !== null);
181
182 return parsed.length > 0 ? parsed : null;
183}
184
185function normalizeDraftAnswer(value: string | undefined): string | null {
186 if (typeof value !== "string") {
187 return null;
188 }
189 const trimmed = value.trim();
190 return trimmed.length > 0 ? trimmed : null;
191}
192
193function resolvePendingUserInputAnswer(
194 draft: PendingUserInputDraftAnswer | undefined,
195): string | null {
196 const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
197 if (customAnswer) {
198 return customAnswer;
199 }
200 return normalizeDraftAnswer(draft?.selectedOptionLabel);
201}
202
203function deriveWorkLogEntries(
204 activities: ReadonlyArray<OrchestrationThreadActivity>,
205 latestTurnId: TurnId | undefined,
206): WorkLogEntry[] {
207 const ordered = Arr.sort(activities, activityOrder);
208 const entries: DerivedWorkLogEntry[] = [];
209 for (const activity of ordered) {
210 if (latestTurnId && activity.turnId !== latestTurnId) continue;
211 if (activity.kind === "tool.started") continue;
212 if (activity.kind === "task.started" || activity.kind === "task.completed") continue;
213 if (activity.kind === "context-window.updated") continue;
214 if (activity.summary === "Checkpoint captured") continue;
215 if (isPlanBoundaryToolActivity(activity)) continue;
216 entries.push(toDerivedWorkLogEntry(activity));
217 }
218 return collapseDerivedWorkLogEntries(entries).map(
219 ({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
220 );
221}
222
223function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
224 if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") {
225 return false;
226 }
227
228 const payload =
229 activity.payload && typeof activity.payload === "object"
230 ? (activity.payload as Record<string, unknown>)
231 : null;
232 return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
233}
234
235function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
236 const payload =
237 activity.payload && typeof activity.payload === "object"
238 ? (activity.payload as Record<string, unknown>)
239 : null;
240 const commandPreview = extractToolCommand(payload);
241 const changedFiles = extractChangedFiles(payload);
242 const title = extractToolTitle(payload);
243 const entry: DerivedWorkLogEntry = {
244 id: activity.id,
245 createdAt: activity.createdAt,
246 label: activity.summary,
247 tone: activity.tone === "approval" ? "info" : activity.tone,
248 activityKind: activity.kind,
249 };
250 const itemType = extractWorkLogItemType(payload);
251 const requestKind = extractWorkLogRequestKind(payload);
252 if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
253 const detail = stripTrailingExitCode(payload.detail).output;
254 if (detail) {
255 entry.detail = detail;
256 }
257 }
258 if (commandPreview.command) {
259 entry.command = commandPreview.command;
260 }
261 if (commandPreview.rawCommand) {
262 entry.rawCommand = commandPreview.rawCommand;
263 }
264 if (changedFiles.length > 0) {
265 entry.changedFiles = changedFiles;
266 }
267 if (title) {
268 entry.toolTitle = title;
269 }
270 if (itemType) {
271 entry.itemType = itemType;
272 }
273 if (requestKind) {
274 entry.requestKind = requestKind;
275 }
276 const collapseKey = deriveToolLifecycleCollapseKey(entry);
277 if (collapseKey) {
278 entry.collapseKey = collapseKey;
279 }
280 return entry;
281}
282
283function collapseDerivedWorkLogEntries(
284 entries: ReadonlyArray<DerivedWorkLogEntry>,
285): DerivedWorkLogEntry[] {
286 const collapsed: DerivedWorkLogEntry[] = [];
287 for (const entry of entries) {
288 const previous = collapsed.at(-1);
289 if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
290 collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
291 continue;
292 }
293 collapsed.push(entry);
294 }
295 return collapsed;
296}
297
298function shouldCollapseToolLifecycleEntries(
299 previous: DerivedWorkLogEntry,
300 next: DerivedWorkLogEntry,
301): boolean {
302 if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") {
303 return false;
304 }
305 if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") {
306 return false;
307 }
308 if (previous.activityKind === "tool.completed") {
309 return false;
310 }
311 return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey;
312}
313
314function mergeDerivedWorkLogEntries(
315 previous: DerivedWorkLogEntry,
316 next: DerivedWorkLogEntry,
317): DerivedWorkLogEntry {
318 const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);
319 const detail = next.detail ?? previous.detail;
320 const command = next.command ?? previous.command;
321 const rawCommand = next.rawCommand ?? previous.rawCommand;
322 const toolTitle = next.toolTitle ?? previous.toolTitle;
323 const itemType = next.itemType ?? previous.itemType;
324 const requestKind = next.requestKind ?? previous.requestKind;
325 const collapseKey = next.collapseKey ?? previous.collapseKey;
326 return {
327 ...previous,
328 ...next,
329 ...(detail ? { detail } : {}),
330 ...(command ? { command } : {}),
331 ...(rawCommand ? { rawCommand } : {}),
332 ...(changedFiles.length > 0 ? { changedFiles } : {}),
333 ...(toolTitle ? { toolTitle } : {}),
334 ...(itemType ? { itemType } : {}),
335 ...(requestKind ? { requestKind } : {}),
336 ...(collapseKey ? { collapseKey } : {}),
337 };
338}
339
340function mergeChangedFiles(
341 previous: ReadonlyArray<string> | undefined,
342 next: ReadonlyArray<string> | undefined,
343): string[] {
344 const merged = [...(previous ?? []), ...(next ?? [])];
345 if (merged.length === 0) {
346 return [];
347 }
348 return [...new Set(merged)];
349}
350
351function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined {
352 if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {
353 return undefined;
354 }
355 const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label);
356 const detail = entry.detail?.trim() ?? "";
357 const itemType = entry.itemType ?? "";
358 if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) {
359 return undefined;
360 }
361 return [itemType, normalizedLabel, detail].join("\u001f");
362}
363
364function normalizeCompactToolLabel(value: string): string {
365 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
366}
367
368function workEntryPreview(
369 workEntry: Pick<WorkLogEntry, "detail" | "command" | "changedFiles">,
370): string | null {
371 if (workEntry.command) return workEntry.command;
372 if (workEntry.detail) return workEntry.detail;
373 if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
374 const [firstPath] = workEntry.changedFiles ?? [];
375 if (!firstPath) return null;
376 return workEntry.changedFiles!.length === 1
377 ? firstPath
378 : `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
379}
380
381function capitalizePhrase(value: string): string {
382 const trimmed = value.trim();
383 if (trimmed.length === 0) {
384 return value;
385 }
386 return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
387}
388
389function workEntryHeading(workEntry: WorkLogEntry): string {
390 if (!workEntry.toolTitle) {
391 return capitalizePhrase(normalizeCompactToolLabel(workEntry.label));
392 }
393 return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle));
394}
395
396function asRecord(value: unknown): Record<string, unknown> | null {
397 return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
398}
399
400function asTrimmedString(value: unknown): string | null {
401 if (typeof value !== "string") {
402 return null;
403 }
404 const trimmed = value.trim();
405 return trimmed.length > 0 ? trimmed : null;
406}
407
408function trimMatchingOuterQuotes(value: string): string {
409 const trimmed = value.trim();
410 if (
411 (trimmed.startsWith("'") && trimmed.endsWith("'")) ||
412 (trimmed.startsWith('"') && trimmed.endsWith('"'))
413 ) {
414 const unquoted = trimmed.slice(1, -1).trim();
415 return unquoted.length > 0 ? unquoted : trimmed;
416 }
417 return trimmed;
418}
419
420function executableBasename(value: string): string | null {
421 const trimmed = trimMatchingOuterQuotes(value);
422 if (trimmed.length === 0) {
423 return null;
424 }
425 const normalized = trimmed.replace(/\\/g, "/");
426 const segments = normalized.split("/");
427 const last = segments.at(-1)?.trim() ?? "";
428 return last.length > 0 ? last.toLowerCase() : null;
429}
430
431function splitExecutableAndRest(value: string): { executable: string; rest: string } | null {
432 const trimmed = value.trim();
433 if (trimmed.length === 0) {
434 return null;
435 }
436
437 if (trimmed.startsWith('"') || trimmed.startsWith("'")) {
438 const quote = trimmed.charAt(0);
439 const closeIndex = trimmed.indexOf(quote, 1);
440 if (closeIndex <= 0) {
441 return null;
442 }
443 return {
444 executable: trimmed.slice(0, closeIndex + 1),
445 rest: trimmed.slice(closeIndex + 1).trim(),
446 };
447 }
448
449 const firstWhitespace = trimmed.search(/\s/);
450 if (firstWhitespace < 0) {
451 return {
452 executable: trimmed,
453 rest: "",
454 };
455 }
456
457 return {
458 executable: trimmed.slice(0, firstWhitespace),
459 rest: trimmed.slice(firstWhitespace).trim(),
460 };
461}
462
463const SHELL_WRAPPER_SPECS = [
464 {
465 executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"],
466 wrapperFlagPattern: /(?:^|\s)-command\s+/i,
467 },
468 {
469 executables: ["cmd", "cmd.exe"],
470 wrapperFlagPattern: /(?:^|\s)\/c\s+/i,
471 },
472 {
473 executables: ["bash", "sh", "zsh"],
474 wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i,
475 },
476] as const;
477
478function findShellWrapperSpec(shell: string) {
479 return SHELL_WRAPPER_SPECS.find((spec) =>
480 (spec.executables as ReadonlyArray<string>).includes(shell),
481 );
482}
483
484function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null {
485 const match = wrapperFlagPattern.exec(value);
486 if (!match) {
487 return null;
488 }
489
490 const command = value.slice(match.index + match[0].length).trim();
491 if (command.length === 0) {
492 return null;
493 }
494
495 const unwrapped = trimMatchingOuterQuotes(command);
496 return unwrapped.length > 0 ? unwrapped : null;
497}
498
499function unwrapKnownShellCommandWrapper(value: string): string {
500 const split = splitExecutableAndRest(value);
501 if (!split || split.rest.length === 0) {
502 return value;
503 }
504
505 const shell = executableBasename(split.executable);
506 if (!shell) {
507 return value;
508 }
509
510 const spec = findShellWrapperSpec(shell);
511 if (!spec) {
512 return value;
513 }
514
515 return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value;
516}
517
518function formatCommandArrayPart(value: string): string {
519 return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;
520}
521
522function formatCommandValue(value: unknown): string | null {
523 const direct = asTrimmedString(value);
524 if (direct) {
525 return direct;
526 }
527 if (!Array.isArray(value)) {
528 return null;
529 }
530 const parts: Array<string> = [];
531 for (const entry of value) {
532 const part = asTrimmedString(entry);
533 if (part !== null) {
534 parts.push(part);
535 }
536 }
537 if (parts.length === 0) {
538 return null;
539 }
540 return parts.map((part) => formatCommandArrayPart(part)).join(" ");
541}
542
543function normalizeCommandValue(value: unknown): string | null {
544 const formatted = formatCommandValue(value);
545 return formatted ? unwrapKnownShellCommandWrapper(formatted) : null;
546}
547
548function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null {
549 const formatted = formatCommandValue(value);
550 if (!formatted || normalizedCommand === null) {
551 return null;
552 }
553 return formatted === normalizedCommand ? null : formatted;
554}
555
556function extractToolCommand(payload: Record<string, unknown> | null): {
557 command: string | null;
558 rawCommand: string | null;
559} {
560 const data = asRecord(payload?.data);
561 const item = asRecord(data?.item);
562 const itemResult = asRecord(item?.result);
563 const itemInput = asRecord(item?.input);
564 const itemType = asTrimmedString(payload?.itemType);
565 const detail = asTrimmedString(payload?.detail);
566 const candidates: unknown[] = [
567 item?.command,
568 itemInput?.command,
569 itemResult?.command,
570 data?.command,
571 itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null,
572 ];
573
574 for (const candidate of candidates) {
575 const command = normalizeCommandValue(candidate);
576 if (!command) {
577 continue;
578 }
579 return {
580 command,
581 rawCommand: toRawToolCommand(candidate, command),
582 };
583 }
584
585 return {
586 command: null,
587 rawCommand: null,
588 };
589}
590
591function extractToolTitle(payload: Record<string, unknown> | null): string | null {
592 return asTrimmedString(payload?.title);
593}
594
595function stripTrailingExitCode(value: string): {
596 output: string | null;
597 exitCode?: number | undefined;
598} {
599 const trimmed = value.trim();
600 const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code (?<code>\d+)>)\s*$/i.exec(
601 trimmed,
602 );
603 if (!match?.groups) {
604 return {
605 output: trimmed.length > 0 ? trimmed : null,
606 };
607 }
608 const exitCode = Number.parseInt(match.groups.code ?? "", 10);
609 const normalizedOutput = match.groups.output?.trim() ?? "";
610 return {
611 output: normalizedOutput.length > 0 ? normalizedOutput : null,
612 ...(Number.isInteger(exitCode) ? { exitCode } : {}),
613 };
614}
615
616function extractWorkLogItemType(
617 payload: Record<string, unknown> | null,
618): WorkLogEntry["itemType"] | undefined {
619 if (typeof payload?.itemType === "string" && isToolLifecycleItemType(payload.itemType)) {
620 return payload.itemType;
621 }
622 return undefined;
623}
624
625function extractWorkLogRequestKind(
626 payload: Record<string, unknown> | null,
627): WorkLogEntry["requestKind"] | undefined {
628 if (
629 payload?.requestKind === "command" ||
630 payload?.requestKind === "file-read" ||
631 payload?.requestKind === "file-change"
632 ) {
633 return payload.requestKind;
634 }
635 return requestKindFromRequestType(payload?.requestType) ?? undefined;
636}
637
638function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
639 const normalized = asTrimmedString(value);
640 if (!normalized || seen.has(normalized)) {
641 return;
642 }
643 seen.add(normalized);
644 target.push(normalized);
645}
646
647function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {
648 if (depth > 4 || target.length >= 12) {
649 return;
650 }
651 if (Array.isArray(value)) {
652 for (const entry of value) {
653 collectChangedFiles(entry, target, seen, depth + 1);
654 if (target.length >= 12) {
655 return;
656 }
657 }
658 return;
659 }
660
661 const record = asRecord(value);
662 if (!record) {
663 return;
664 }
665
666 pushChangedFile(target, seen, record.path);
667 pushChangedFile(target, seen, record.filePath);
668 pushChangedFile(target, seen, record.relativePath);
669 pushChangedFile(target, seen, record.filename);
670 pushChangedFile(target, seen, record.newPath);
671 pushChangedFile(target, seen, record.oldPath);
672
673 for (const nestedKey of [
674 "item",
675 "result",
676 "input",
677 "data",
678 "changes",
679 "files",
680 "edits",
681 "patch",
682 "patches",
683 "operations",
684 ]) {
685 if (!(nestedKey in record)) {
686 continue;
687 }
688 collectChangedFiles(record[nestedKey], target, seen, depth + 1);
689 if (target.length >= 12) {
690 return;
691 }
692 }
693}
694
695function extractChangedFiles(payload: Record<string, unknown> | null): string[] {
696 const changedFiles: string[] = [];
697 const seen = new Set<string>();
698 collectChangedFiles(asRecord(payload?.data), changedFiles, seen, 0);
699 return changedFiles;
700}
701
702function compareActivityLifecycleRank(kind: string): number {
703 if (kind.endsWith(".started") || kind === "tool.started") {
704 return 0;
705 }
706 if (kind.endsWith(".progress") || kind.endsWith(".updated")) {
707 return 1;
708 }
709 if (kind.endsWith(".completed") || kind.endsWith(".resolved")) {
710 return 2;
711 }
712 return 1;
713}
714
715const activityOrder = Order.combineAll<OrchestrationThreadActivity>([
716 Order.mapInput(Order.Number, (activity) => activity.sequence ?? Number.MAX_SAFE_INTEGER),
717 Order.mapInput(Order.String, (activity) => activity.createdAt),
718 Order.mapInput(Order.Number, (activity) => compareActivityLifecycleRank(activity.kind)),
719 Order.mapInput(Order.String, (activity) => activity.id),
720]);
721
722function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
723 if (entry.type !== "message") {
724 return false;
725 }
726 const hasText = entry.message.text.trim().length > 0;
727 const hasAttachments = (entry.message.attachments ?? []).length > 0;
728 return !hasText && !hasAttachments;
729}
730
731function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
732 const grouped: ThreadFeedEntry[] = [];
733
734 for (const entry of entries) {
735 // Skip empty messages so they don't break activity grouping.
736 if (isEmptyMessage(entry)) {
737 continue;
738 }
739
740 if (entry.type !== "activity") {
741 grouped.push(entry);
742 continue;
743 }
744
745 const previous = grouped.at(-1);
746 if (previous?.type === "activity-group") {
747 grouped[grouped.length - 1] = {
748 ...previous,
749 activities: [...previous.activities, entry.activity],
750 };
751 continue;
752 }
753
754 grouped.push({
755 type: "activity-group",
756 id: entry.id,
757 createdAt: entry.createdAt,
758 activities: [entry.activity],
759 });
760 }
761
762 return grouped;
763}
764
765export function derivePendingApprovals(
766 activities: ReadonlyArray<OrchestrationThreadActivity>,
767): PendingApproval[] {
768 const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
769 const ordered = Arr.sort(activities, activityOrder);
770
771 for (const activity of ordered) {
772 const payload =
773 activity.payload && typeof activity.payload === "object"
774 ? (activity.payload as Record<string, unknown>)
775 : null;
776 const requestId = parseApprovalRequestId(payload?.requestId);
777 const requestKind =
778 payload?.requestKind === "command" ||
779 payload?.requestKind === "file-read" ||
780 payload?.requestKind === "file-change"
781 ? payload.requestKind
782 : requestKindFromRequestType(payload?.requestType);
783 const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
784
785 if (activity.kind === "approval.requested" && requestId && requestKind) {
786 openByRequestId.set(requestId, {
787 requestId,
788 requestKind,
789 createdAt: activity.createdAt,
790 ...(detail ? { detail } : {}),
791 });
792 continue;
793 }
794
795 if (activity.kind === "approval.resolved" && requestId) {
796 openByRequestId.delete(requestId);
797 continue;
798 }
799
800 if (
801 activity.kind === "provider.approval.respond.failed" &&
802 requestId &&
803 isStalePendingRequestFailureDetail(detail)
804 ) {
805 openByRequestId.delete(requestId);
806 }
807 }
808
809 return Arr.sortWith([...openByRequestId.values()], (s) => new Date(s.createdAt), Order.Date);
810}
811
812export function derivePendingUserInputs(
813 activities: ReadonlyArray<OrchestrationThreadActivity>,
814): PendingUserInput[] {
815 const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
816 const ordered = Arr.sort(activities, activityOrder);
817
818 for (const activity of ordered) {
819 const payload =
820 activity.payload && typeof activity.payload === "object"
821 ? (activity.payload as Record<string, unknown>)
822 : null;
823 const requestId = parseApprovalRequestId(payload?.requestId);
824 const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
825
826 if (activity.kind === "user-input.requested" && requestId) {
827 const questions = parseUserInputQuestions(payload);
828 if (!questions) {
829 continue;
830 }
831 openByRequestId.set(requestId, {
832 requestId,
833 createdAt: activity.createdAt,
834 questions,
835 });
836 continue;
837 }
838
839 if (activity.kind === "user-input.resolved" && requestId) {
840 openByRequestId.delete(requestId);
841 continue;
842 }
843
844 if (
845 activity.kind === "provider.user-input.respond.failed" &&
846 requestId &&
847 isStalePendingRequestFailureDetail(detail)
848 ) {
849 openByRequestId.delete(requestId);
850 }
851 }
852
853 return Arr.sortWith(openByRequestId.values(), (s) => new Date(s.createdAt), Order.Date);
854}
855
856export function setPendingUserInputCustomAnswer(
857 draft: PendingUserInputDraftAnswer | undefined,
858 customAnswer: string,
859): PendingUserInputDraftAnswer {
860 const selectedOptionLabel =
861 customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
862 return {
863 customAnswer,
864 ...(selectedOptionLabel ? { selectedOptionLabel } : {}),
865 };
866}
867
868export function buildPendingUserInputAnswers(
869 questions: ReadonlyArray<UserInputQuestion>,
870 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
871): Record<string, string> | null {
872 const answers: Record<string, string> = {};
873
874 for (const question of questions) {
875 const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
876 if (!answer) {
877 return null;
878 }
879 answers[question.id] = answer;
880 }
881
882 return answers;
883}
884
885export function buildThreadFeed(
886 thread: OrchestrationThread,
887 queuedMessages: ReadonlyArray<QueuedThreadMessage>,
888 dispatchingQueuedMessageId: MessageId | null,
889 options?: {
890 readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
891 },
892): ThreadFeedEntry[] {
893 const loadedMessages = options?.loadedMessages ?? thread.messages;
894 const oldestLoadedMessageCreatedAt =
895 options?.loadedMessages !== undefined ? (loadedMessages[0]?.createdAt ?? null) : null;
896 const workLogEntries = deriveWorkLogEntries(
897 thread.activities,
898 thread.latestTurn?.turnId ?? undefined,
899 );
900 const entries = Arr.sortWith(
901 [
902 ...loadedMessages.map<RawThreadFeedEntry>((message) => ({
903 type: "message",
904 id: message.id,
905 createdAt: message.createdAt,
906 message,
907 })),
908 ...queuedMessages.map<RawThreadFeedEntry>((queuedMessage) => ({
909 type: "queued-message",
910 id: queuedMessage.messageId,
911 createdAt: queuedMessage.createdAt,
912 queuedMessage,
913 sending: queuedMessage.messageId === dispatchingQueuedMessageId,
914 })),
915 ...workLogEntries
916 .filter((entry) => {
917 if (options?.loadedMessages === undefined) {
918 return true;
919 }
920 return (
921 oldestLoadedMessageCreatedAt === null || entry.createdAt >= oldestLoadedMessageCreatedAt
922 );
923 })
924 .map<RawThreadFeedEntry>((entry) => ({
925 type: "activity",
926 id: entry.id,
927 createdAt: entry.createdAt,
928 activity: {
929 id: entry.id,
930 createdAt: entry.createdAt,
931 summary: workEntryHeading(entry),
932 detail: workEntryPreview(entry),
933 status: null,
934 },
935 })),
936 ],
937 (s) => new Date(s.createdAt),
938 Order.Date,
939 );
940
941 return groupAdjacentActivities(entries);
942}