Open History to see the last commit
1import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
2import type {
3 OrchestrationLatestTurn,
4 OrchestrationThread,
5 OrchestrationThreadActivity,
6 ToolLifecycleItemType,
7 TurnId,
8 UserInputQuestion,
9} from "@t3tools/contracts";
10import { formatDuration } from "@t3tools/shared/orchestrationTiming";
11
12import * as Arr from "effect/Array";
13import * as Order from "effect/Order";
14
15export interface PendingApproval {
16 readonly requestId: ApprovalRequestId;
17 readonly requestKind: "command" | "file-read" | "file-change";
18 readonly createdAt: string;
19 readonly detail?: string;
20}
21
22export interface PendingUserInput {
23 readonly requestId: ApprovalRequestId;
24 readonly createdAt: string;
25 readonly questions: ReadonlyArray<UserInputQuestion>;
26}
27
28export interface PendingUserInputDraftAnswer {
29 readonly selectedOptionLabel?: string;
30 readonly customAnswer?: string;
31}
32
33export interface ThreadFeedActivity {
34 readonly id: string;
35 readonly createdAt: string;
36 readonly turnId: TurnId | null;
37 readonly summary: string;
38 readonly detail: string | null;
39 readonly canExpand: boolean;
40 readonly getFullDetail: () => string | null;
41 readonly getCopyText: () => string;
42 readonly icon:
43 | "agent"
44 | "alert"
45 | "check"
46 | "command"
47 | "edit"
48 | "eye"
49 | "globe"
50 | "hammer"
51 | "message"
52 | "warning"
53 | "wrench"
54 | "zap";
55 readonly toolLike: boolean;
56 readonly status: "success" | "failure" | "neutral" | null;
57}
58
59const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
60
61type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
62
63interface WorkLogEntry {
64 id: string;
65 createdAt: string;
66 turnId: TurnId | null;
67 label: string;
68 detail?: string;
69 command?: string;
70 rawCommand?: string;
71 changedFiles?: ReadonlyArray<string>;
72 tone: "thinking" | "tool" | "info" | "error";
73 toolTitle?: string;
74 itemType?: ToolLifecycleItemType;
75 requestKind?: PendingApproval["requestKind"];
76 toolLifecycleStatus?: WorkLogToolLifecycleStatus;
77 toolData?: unknown;
78}
79
80interface DerivedWorkLogEntry extends WorkLogEntry {
81 activityKind: OrchestrationThreadActivity["kind"];
82 collapseKey?: string;
83}
84
85type RawThreadFeedEntry =
86 | {
87 readonly type: "message";
88 readonly id: string;
89 readonly createdAt: string;
90 readonly message: OrchestrationThread["messages"][number];
91 }
92 | {
93 readonly type: "activity";
94 readonly id: string;
95 readonly createdAt: string;
96 readonly turnId: TurnId | null;
97 readonly activity: ThreadFeedActivity;
98 };
99
100export type ThreadFeedEntry =
101 | Extract<RawThreadFeedEntry, { type: "message" }>
102 | {
103 readonly type: "working";
104 readonly id: string;
105 readonly createdAt: string;
106 }
107 | {
108 readonly type: "activity-group";
109 readonly id: string;
110 readonly createdAt: string;
111 readonly turnId: TurnId | null;
112 readonly activities: ReadonlyArray<ThreadFeedActivity>;
113 }
114 | {
115 readonly type: "work-toggle";
116 readonly id: string;
117 readonly createdAt: string;
118 readonly turnId: TurnId | null;
119 readonly groupId: string;
120 readonly hiddenCount: number;
121 readonly expanded: boolean;
122 readonly onlyToolActivities: boolean;
123 }
124 | {
125 readonly type: "turn-fold";
126 readonly id: string;
127 readonly createdAt: string;
128 readonly turnId: TurnId;
129 readonly label: string;
130 readonly expanded: boolean;
131 };
132
133export type ThreadFeedLatestTurn = Pick<
134 OrchestrationLatestTurn,
135 "turnId" | "state" | "startedAt" | "completedAt"
136>;
137
138function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
139 switch (requestType) {
140 case "command_execution_approval":
141 case "exec_command_approval":
142 return "command";
143 case "file_read_approval":
144 return "file-read";
145 case "file_change_approval":
146 case "apply_patch_approval":
147 return "file-change";
148 default:
149 return null;
150 }
151}
152
153function isStalePendingRequestFailureDetail(detail: string | undefined): boolean {
154 const normalized = detail?.toLowerCase();
155 if (!normalized) {
156 return false;
157 }
158 return (
159 normalized.includes("stale pending approval request") ||
160 normalized.includes("stale pending user-input request") ||
161 normalized.includes("unknown pending approval request") ||
162 normalized.includes("unknown pending permission request") ||
163 normalized.includes("unknown pending user-input request")
164 );
165}
166
167function parseApprovalRequestId(value: unknown): ApprovalRequestId | null {
168 return typeof value === "string" && value.length > 0 ? ApprovalRequestId.make(value) : null;
169}
170
171function parseUserInputQuestions(
172 payload: Record<string, unknown> | null,
173): ReadonlyArray<UserInputQuestion> | null {
174 const questions = payload?.questions;
175 if (!Array.isArray(questions)) {
176 return null;
177 }
178
179 const parsed = questions
180 .map<UserInputQuestion | null>((entry) => {
181 if (!entry || typeof entry !== "object") return null;
182 const question = entry as Record<string, unknown>;
183 if (
184 typeof question.id !== "string" ||
185 typeof question.header !== "string" ||
186 typeof question.question !== "string" ||
187 !Array.isArray(question.options)
188 ) {
189 return null;
190 }
191 const options = question.options
192 .map<UserInputQuestion["options"][number] | null>((option) => {
193 if (!option || typeof option !== "object") return null;
194 const record = option as Record<string, unknown>;
195 if (typeof record.label !== "string" || typeof record.description !== "string") {
196 return null;
197 }
198 return {
199 label: record.label,
200 description: record.description,
201 };
202 })
203 .filter((option): option is UserInputQuestion["options"][number] => option !== null);
204 if (options.length === 0) {
205 return null;
206 }
207 return {
208 id: question.id,
209 header: question.header,
210 question: question.question,
211 options,
212 multiSelect: question.multiSelect === true,
213 };
214 })
215 .filter((question): question is UserInputQuestion => question !== null);
216
217 return parsed.length > 0 ? parsed : null;
218}
219
220function normalizeDraftAnswer(value: string | undefined): string | null {
221 if (typeof value !== "string") {
222 return null;
223 }
224 const trimmed = value.trim();
225 return trimmed.length > 0 ? trimmed : null;
226}
227
228function resolvePendingUserInputAnswer(
229 draft: PendingUserInputDraftAnswer | undefined,
230): string | null {
231 const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
232 if (customAnswer) {
233 return customAnswer;
234 }
235 return normalizeDraftAnswer(draft?.selectedOptionLabel);
236}
237
238function deriveWorkLogEntries(
239 activities: ReadonlyArray<OrchestrationThreadActivity>,
240): DerivedWorkLogEntry[] {
241 const ordered = Arr.sort(activities, activityOrder);
242 const entries: DerivedWorkLogEntry[] = [];
243 for (const activity of ordered) {
244 if (activity.kind === "tool.started") continue;
245 if (activity.kind === "task.started") continue;
246 if (activity.kind === "context-window.updated") continue;
247 if (activity.summary === "Checkpoint captured") continue;
248 if (isPlanBoundaryToolActivity(activity)) continue;
249 entries.push(toDerivedWorkLogEntry(activity));
250 }
251 return collapseDerivedWorkLogEntries(entries);
252}
253
254function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
255 if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") {
256 return false;
257 }
258
259 const payload =
260 activity.payload && typeof activity.payload === "object"
261 ? (activity.payload as Record<string, unknown>)
262 : null;
263 return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
264}
265
266function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
267 const payload =
268 activity.payload && typeof activity.payload === "object"
269 ? (activity.payload as Record<string, unknown>)
270 : null;
271 const commandPreview = extractToolCommand(payload);
272 const changedFiles = extractChangedFiles(payload);
273 const title = extractToolTitle(payload);
274 const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";
275 const taskSummary =
276 isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0
277 ? payload.summary
278 : null;
279 const taskDetailAsLabel =
280 isTaskActivity &&
281 !taskSummary &&
282 typeof payload?.detail === "string" &&
283 payload.detail.length > 0
284 ? payload.detail
285 : null;
286 const taskLabel = taskSummary || taskDetailAsLabel;
287 const entry: DerivedWorkLogEntry = {
288 id: activity.id,
289 createdAt: activity.createdAt,
290 turnId: activity.turnId,
291 label: taskLabel || activity.summary,
292 tone:
293 activity.kind === "task.progress"
294 ? "thinking"
295 : activity.tone === "approval"
296 ? "info"
297 : activity.tone,
298 activityKind: activity.kind,
299 };
300 const itemType = extractWorkLogItemType(payload);
301 const requestKind = extractWorkLogRequestKind(payload);
302 if (
303 !taskDetailAsLabel &&
304 payload &&
305 typeof payload.detail === "string" &&
306 payload.detail.length > 0
307 ) {
308 const detail = stripTrailingExitCode(payload.detail).output;
309 if (detail) {
310 entry.detail = detail;
311 }
312 }
313 if (commandPreview.command) {
314 entry.command = commandPreview.command;
315 }
316 if (commandPreview.rawCommand) {
317 entry.rawCommand = commandPreview.rawCommand;
318 }
319 if (changedFiles.length > 0) {
320 entry.changedFiles = changedFiles;
321 }
322 if (title) {
323 entry.toolTitle = title;
324 }
325 if (itemType === "mcp_tool_call") {
326 const data = asRecord(payload?.data);
327 if (data?.item !== undefined) {
328 entry.toolData = data.item;
329 }
330 }
331 if (itemType) {
332 entry.itemType = itemType;
333 }
334 if (requestKind) {
335 entry.requestKind = requestKind;
336 }
337 let toolLifecycleStatus = extractWorkLogToolLifecycleStatus(payload);
338 if (!toolLifecycleStatus && activity.kind === "tool.completed") {
339 toolLifecycleStatus = "completed";
340 }
341 if (toolLifecycleStatus) {
342 entry.toolLifecycleStatus = toolLifecycleStatus;
343 }
344 const collapseKey = deriveToolLifecycleCollapseKey(entry);
345 if (collapseKey) {
346 entry.collapseKey = collapseKey;
347 }
348 return entry;
349}
350
351function collapseDerivedWorkLogEntries(
352 entries: ReadonlyArray<DerivedWorkLogEntry>,
353): DerivedWorkLogEntry[] {
354 const collapsed: DerivedWorkLogEntry[] = [];
355 for (const entry of entries) {
356 const previous = collapsed.at(-1);
357 if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
358 collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
359 continue;
360 }
361 collapsed.push(entry);
362 }
363 return collapsed;
364}
365
366function shouldCollapseToolLifecycleEntries(
367 previous: DerivedWorkLogEntry,
368 next: DerivedWorkLogEntry,
369): boolean {
370 if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") {
371 return false;
372 }
373 if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") {
374 return false;
375 }
376 if (previous.activityKind === "tool.completed") {
377 return false;
378 }
379 return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey;
380}
381
382function mergeDerivedWorkLogEntries(
383 previous: DerivedWorkLogEntry,
384 next: DerivedWorkLogEntry,
385): DerivedWorkLogEntry {
386 const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);
387 const detail = next.detail ?? previous.detail;
388 const command = next.command ?? previous.command;
389 const rawCommand = next.rawCommand ?? previous.rawCommand;
390 const toolTitle = next.toolTitle ?? previous.toolTitle;
391 const itemType = next.itemType ?? previous.itemType;
392 const requestKind = next.requestKind ?? previous.requestKind;
393 const collapseKey = next.collapseKey ?? previous.collapseKey;
394 const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
395 const toolData = next.toolData ?? previous.toolData;
396 return {
397 ...previous,
398 ...next,
399 ...(detail ? { detail } : {}),
400 ...(command ? { command } : {}),
401 ...(rawCommand ? { rawCommand } : {}),
402 ...(changedFiles.length > 0 ? { changedFiles } : {}),
403 ...(toolTitle ? { toolTitle } : {}),
404 ...(itemType ? { itemType } : {}),
405 ...(requestKind ? { requestKind } : {}),
406 ...(collapseKey ? { collapseKey } : {}),
407 ...(toolLifecycleStatus ? { toolLifecycleStatus } : {}),
408 ...(toolData !== undefined ? { toolData } : {}),
409 };
410}
411
412function mergeChangedFiles(
413 previous: ReadonlyArray<string> | undefined,
414 next: ReadonlyArray<string> | undefined,
415): string[] {
416 const merged = [...(previous ?? []), ...(next ?? [])];
417 if (merged.length === 0) {
418 return [];
419 }
420 return [...new Set(merged)];
421}
422
423function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined {
424 if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {
425 return undefined;
426 }
427 const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label);
428 const detail = entry.detail?.trim() ?? "";
429 const itemType = entry.itemType ?? "";
430 if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) {
431 return undefined;
432 }
433 return [itemType, normalizedLabel, detail].join("\u001f");
434}
435
436function normalizeCompactToolLabel(value: string): string {
437 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
438}
439
440function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
441 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") {
442 return true;
443 }
444 if (entry.command !== undefined && entry.command.trim().length > 0) {
445 return true;
446 }
447 if (entry.requestKind !== undefined) {
448 return true;
449 }
450 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
451}
452
453function toolDetailTextLooksLikeFailure(text: string): boolean {
454 const normalized = text.toLowerCase();
455 return (
456 normalized.includes("file not found") ||
457 normalized.includes("no files found") ||
458 normalized.includes("enoent") ||
459 normalized.includes("no such file or directory") ||
460 normalized.includes("no such file") ||
461 normalized.includes("commandnotfoundexception") ||
462 normalized.includes("command not found") ||
463 (normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
464 (normalized.includes("is not recognized") && normalized.includes("the term '")) ||
465 /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
466 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
467 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
468 );
469}
470
471function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {
472 if (entry.tone === "error") {
473 return true;
474 }
475 if (entry.toolLifecycleStatus === "failed" || entry.toolLifecycleStatus === "declined") {
476 return true;
477 }
478 if (!workLogEntryIsToolLike(entry)) {
479 return false;
480 }
481 return toolDetailTextLooksLikeFailure([entry.detail, entry.command].filter(Boolean).join("\n"));
482}
483
484function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
485 if (!workLogEntryIsToolLike(entry) || workEntryIndicatesToolFailure(entry)) {
486 return false;
487 }
488 if (entry.tone === "thinking") {
489 return false;
490 }
491 return (
492 entry.toolLifecycleStatus !== "inProgress" &&
493 entry.toolLifecycleStatus !== "stopped" &&
494 entry.toolLifecycleStatus !== "failed" &&
495 entry.toolLifecycleStatus !== "declined"
496 );
497}
498
499function workEntryStatus(entry: WorkLogEntry): ThreadFeedActivity["status"] {
500 if (!workLogEntryIsToolLike(entry)) {
501 return null;
502 }
503 if (workEntryIndicatesToolFailure(entry)) {
504 return "failure";
505 }
506 if (workEntryIndicatesToolSuccess(entry)) {
507 return "success";
508 }
509 return "neutral";
510}
511
512function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {
513 if (
514 entry.activityKind === "user-input.requested" ||
515 entry.activityKind === "user-input.resolved"
516 ) {
517 return "message";
518 }
519 if (entry.activityKind === "runtime.warning") return "warning";
520 if (entry.requestKind === "command") return "command";
521 if (entry.requestKind === "file-read") return "eye";
522 if (entry.requestKind === "file-change") return "edit";
523 if (entry.itemType === "command_execution" || entry.command) return "command";
524 if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit";
525 if (entry.itemType === "web_search") return "globe";
526 if (entry.itemType === "image_view") return "eye";
527 if (entry.itemType === "mcp_tool_call") return "wrench";
528 if (entry.itemType === "dynamic_tool_call" || entry.itemType === "collab_agent_tool_call") {
529 return "hammer";
530 }
531 if (entry.tone === "error") return "alert";
532 if (entry.tone === "thinking") return "agent";
533 if (entry.tone === "info") return "check";
534 return "zap";
535}
536
537function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
538 const blocks: string[] = [];
539 const appendUniqueBlock = (value: string | null | undefined) => {
540 const trimmed = value?.trim();
541 if (trimmed && !blocks.includes(trimmed)) {
542 blocks.push(trimmed);
543 }
544 };
545
546 if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) {
547 appendUniqueBlock(`MCP call\n${JSON.stringify(entry.toolData, null, 2)}`);
548 }
549 appendUniqueBlock(entry.rawCommand ?? entry.command);
550 appendUniqueBlock(entry.detail);
551 if ((entry.changedFiles?.length ?? 0) > 0) {
552 appendUniqueBlock(entry.changedFiles!.join("\n"));
553 }
554
555 return blocks.length > 0 ? blocks.join("\n\n") : null;
556}
557
558function workEntryHasExpandedBody(entry: WorkLogEntry): boolean {
559 return (
560 (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) ||
561 Boolean((entry.rawCommand ?? entry.command)?.trim()) ||
562 Boolean(entry.detail?.trim()) ||
563 (entry.changedFiles?.some((path) => path.trim().length > 0) ?? false)
564 );
565}
566
567function memoizeValue<T>(build: () => T): () => T {
568 let value: T;
569 let initialized = false;
570 return () => {
571 if (!initialized) {
572 value = build();
573 initialized = true;
574 }
575 return value;
576 };
577}
578
579function workEntryPreview(
580 workEntry: Pick<WorkLogEntry, "detail" | "command" | "changedFiles">,
581): string | null {
582 if (workEntry.command) return workEntry.command;
583 if (workEntry.detail) return workEntry.detail;
584 if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
585 const [firstPath] = workEntry.changedFiles ?? [];
586 if (!firstPath) return null;
587 return workEntry.changedFiles!.length === 1
588 ? firstPath
589 : `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
590}
591
592function capitalizePhrase(value: string): string {
593 const trimmed = value.trim();
594 if (trimmed.length === 0) {
595 return value;
596 }
597 return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
598}
599
600function workEntryHeading(workEntry: WorkLogEntry): string {
601 if (!workEntry.toolTitle) {
602 return capitalizePhrase(normalizeCompactToolLabel(workEntry.label));
603 }
604 return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle));
605}
606
607function asRecord(value: unknown): Record<string, unknown> | null {
608 return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
609}
610
611function asTrimmedString(value: unknown): string | null {
612 if (typeof value !== "string") {
613 return null;
614 }
615 const trimmed = value.trim();
616 return trimmed.length > 0 ? trimmed : null;
617}
618
619function trimMatchingOuterQuotes(value: string): string {
620 const trimmed = value.trim();
621 if (
622 (trimmed.startsWith("'") && trimmed.endsWith("'")) ||
623 (trimmed.startsWith('"') && trimmed.endsWith('"'))
624 ) {
625 const unquoted = trimmed.slice(1, -1).trim();
626 return unquoted.length > 0 ? unquoted : trimmed;
627 }
628 return trimmed;
629}
630
631function executableBasename(value: string): string | null {
632 const trimmed = trimMatchingOuterQuotes(value);
633 if (trimmed.length === 0) {
634 return null;
635 }
636 const normalized = trimmed.replace(/\\/g, "/");
637 const segments = normalized.split("/");
638 const last = segments.at(-1)?.trim() ?? "";
639 return last.length > 0 ? last.toLowerCase() : null;
640}
641
642function splitExecutableAndRest(value: string): { executable: string; rest: string } | null {
643 const trimmed = value.trim();
644 if (trimmed.length === 0) {
645 return null;
646 }
647
648 if (trimmed.startsWith('"') || trimmed.startsWith("'")) {
649 const quote = trimmed.charAt(0);
650 const closeIndex = trimmed.indexOf(quote, 1);
651 if (closeIndex <= 0) {
652 return null;
653 }
654 return {
655 executable: trimmed.slice(0, closeIndex + 1),
656 rest: trimmed.slice(closeIndex + 1).trim(),
657 };
658 }
659
660 const firstWhitespace = trimmed.search(/\s/);
661 if (firstWhitespace < 0) {
662 return {
663 executable: trimmed,
664 rest: "",
665 };
666 }
667
668 return {
669 executable: trimmed.slice(0, firstWhitespace),
670 rest: trimmed.slice(firstWhitespace).trim(),
671 };
672}
673
674const SHELL_WRAPPER_SPECS = [
675 {
676 executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"],
677 wrapperFlagPattern: /(?:^|\s)-command\s+/i,
678 },
679 {
680 executables: ["cmd", "cmd.exe"],
681 wrapperFlagPattern: /(?:^|\s)\/c\s+/i,
682 },
683 {
684 executables: ["bash", "sh", "zsh"],
685 wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i,
686 },
687] as const;
688
689function findShellWrapperSpec(shell: string) {
690 return SHELL_WRAPPER_SPECS.find((spec) =>
691 (spec.executables as ReadonlyArray<string>).includes(shell),
692 );
693}
694
695function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null {
696 const match = wrapperFlagPattern.exec(value);
697 if (!match) {
698 return null;
699 }
700
701 const command = value.slice(match.index + match[0].length).trim();
702 if (command.length === 0) {
703 return null;
704 }
705
706 const unwrapped = trimMatchingOuterQuotes(command);
707 return unwrapped.length > 0 ? unwrapped : null;
708}
709
710function unwrapKnownShellCommandWrapper(value: string): string {
711 const split = splitExecutableAndRest(value);
712 if (!split || split.rest.length === 0) {
713 return value;
714 }
715
716 const shell = executableBasename(split.executable);
717 if (!shell) {
718 return value;
719 }
720
721 const spec = findShellWrapperSpec(shell);
722 if (!spec) {
723 return value;
724 }
725
726 return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value;
727}
728
729function formatCommandArrayPart(value: string): string {
730 return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;
731}
732
733function formatCommandValue(value: unknown): string | null {
734 const direct = asTrimmedString(value);
735 if (direct) {
736 return direct;
737 }
738 if (!Array.isArray(value)) {
739 return null;
740 }
741 const parts: Array<string> = [];
742 for (const entry of value) {
743 const part = asTrimmedString(entry);
744 if (part !== null) {
745 parts.push(part);
746 }
747 }
748 if (parts.length === 0) {
749 return null;
750 }
751 return parts.map((part) => formatCommandArrayPart(part)).join(" ");
752}
753
754function normalizeCommandValue(value: unknown): string | null {
755 const formatted = formatCommandValue(value);
756 return formatted ? unwrapKnownShellCommandWrapper(formatted) : null;
757}
758
759function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null {
760 const formatted = formatCommandValue(value);
761 if (!formatted || normalizedCommand === null) {
762 return null;
763 }
764 return formatted === normalizedCommand ? null : formatted;
765}
766
767function extractToolCommand(payload: Record<string, unknown> | null): {
768 command: string | null;
769 rawCommand: string | null;
770} {
771 const data = asRecord(payload?.data);
772 const item = asRecord(data?.item);
773 const itemResult = asRecord(item?.result);
774 const itemInput = asRecord(item?.input);
775 const itemType = asTrimmedString(payload?.itemType);
776 const detail = asTrimmedString(payload?.detail);
777 const candidates: unknown[] = [
778 item?.command,
779 itemInput?.command,
780 itemResult?.command,
781 data?.command,
782 itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null,
783 ];
784
785 for (const candidate of candidates) {
786 const command = normalizeCommandValue(candidate);
787 if (!command) {
788 continue;
789 }
790 return {
791 command,
792 rawCommand: toRawToolCommand(candidate, command),
793 };
794 }
795
796 return {
797 command: null,
798 rawCommand: null,
799 };
800}
801
802function extractToolTitle(payload: Record<string, unknown> | null): string | null {
803 return asTrimmedString(payload?.title);
804}
805
806function extractWorkLogToolLifecycleStatus(
807 payload: Record<string, unknown> | null,
808): WorkLogToolLifecycleStatus | undefined {
809 const status = payload?.status;
810 if (
811 status === "inProgress" ||
812 status === "completed" ||
813 status === "failed" ||
814 status === "declined" ||
815 status === "stopped"
816 ) {
817 return status;
818 }
819 return undefined;
820}
821
822function stripTrailingExitCode(value: string): {
823 output: string | null;
824 exitCode?: number | undefined;
825} {
826 const trimmed = value.trim();
827 const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code (?<code>\d+)>)\s*$/i.exec(
828 trimmed,
829 );
830 if (!match?.groups) {
831 return {
832 output: trimmed.length > 0 ? trimmed : null,
833 };
834 }
835 const exitCode = Number.parseInt(match.groups.code ?? "", 10);
836 const normalizedOutput = match.groups.output?.trim() ?? "";
837 return {
838 output: normalizedOutput.length > 0 ? normalizedOutput : null,
839 ...(Number.isInteger(exitCode) ? { exitCode } : {}),
840 };
841}
842
843function extractWorkLogItemType(
844 payload: Record<string, unknown> | null,
845): WorkLogEntry["itemType"] | undefined {
846 if (typeof payload?.itemType === "string" && isToolLifecycleItemType(payload.itemType)) {
847 return payload.itemType;
848 }
849 return undefined;
850}
851
852function extractWorkLogRequestKind(
853 payload: Record<string, unknown> | null,
854): WorkLogEntry["requestKind"] | undefined {
855 if (
856 payload?.requestKind === "command" ||
857 payload?.requestKind === "file-read" ||
858 payload?.requestKind === "file-change"
859 ) {
860 return payload.requestKind;
861 }
862 return requestKindFromRequestType(payload?.requestType) ?? undefined;
863}
864
865function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
866 const normalized = asTrimmedString(value);
867 if (!normalized || seen.has(normalized)) {
868 return;
869 }
870 seen.add(normalized);
871 target.push(normalized);
872}
873
874function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {
875 if (depth > 4 || target.length >= 12) {
876 return;
877 }
878 if (Array.isArray(value)) {
879 for (const entry of value) {
880 collectChangedFiles(entry, target, seen, depth + 1);
881 if (target.length >= 12) {
882 return;
883 }
884 }
885 return;
886 }
887
888 const record = asRecord(value);
889 if (!record) {
890 return;
891 }
892
893 pushChangedFile(target, seen, record.path);
894 pushChangedFile(target, seen, record.filePath);
895 pushChangedFile(target, seen, record.relativePath);
896 pushChangedFile(target, seen, record.filename);
897 pushChangedFile(target, seen, record.newPath);
898 pushChangedFile(target, seen, record.oldPath);
899
900 for (const nestedKey of [
901 "item",
902 "result",
903 "input",
904 "data",
905 "changes",
906 "files",
907 "edits",
908 "patch",
909 "patches",
910 "operations",
911 ]) {
912 if (!(nestedKey in record)) {
913 continue;
914 }
915 collectChangedFiles(record[nestedKey], target, seen, depth + 1);
916 if (target.length >= 12) {
917 return;
918 }
919 }
920}
921
922function extractChangedFiles(payload: Record<string, unknown> | null): string[] {
923 const changedFiles: string[] = [];
924 const seen = new Set<string>();
925 collectChangedFiles(asRecord(payload?.data), changedFiles, seen, 0);
926 return changedFiles;
927}
928
929function compareActivityLifecycleRank(kind: string): number {
930 if (kind.endsWith(".started") || kind === "tool.started") {
931 return 0;
932 }
933 if (kind.endsWith(".progress") || kind.endsWith(".updated")) {
934 return 1;
935 }
936 if (kind.endsWith(".completed") || kind.endsWith(".resolved")) {
937 return 2;
938 }
939 return 1;
940}
941
942const activityOrder = Order.combineAll<OrchestrationThreadActivity>([
943 Order.mapInput(Order.Number, (activity) => activity.sequence ?? Number.MAX_SAFE_INTEGER),
944 Order.mapInput(Order.String, (activity) => activity.createdAt),
945 Order.mapInput(Order.Number, (activity) => compareActivityLifecycleRank(activity.kind)),
946 Order.mapInput(Order.String, (activity) => activity.id),
947]);
948
949function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
950 if (entry.type !== "message") {
951 return false;
952 }
953 const hasText = entry.message.text.trim().length > 0;
954 const hasAttachments = (entry.message.attachments ?? []).length > 0;
955 return !hasText && !hasAttachments;
956}
957
958function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
959 const grouped: ThreadFeedEntry[] = [];
960 // Mutable backing array for the trailing group so appending an activity is
961 // O(1) instead of re-copying the group (which made this loop quadratic on
962 // long tool runs). The array is only mutated while it is the trailing group.
963 let openGroupActivities: ThreadFeedActivity[] | null = null;
964 let openGroupTurnId: TurnId | null = null;
965
966 for (const entry of entries) {
967 // Skip empty messages so they don't break activity grouping.
968 if (isEmptyMessage(entry)) {
969 continue;
970 }
971
972 if (entry.type !== "activity") {
973 grouped.push(entry);
974 openGroupActivities = null;
975 continue;
976 }
977
978 if (openGroupActivities !== null && openGroupTurnId === entry.turnId) {
979 openGroupActivities.push(entry.activity);
980 continue;
981 }
982
983 openGroupActivities = [entry.activity];
984 openGroupTurnId = entry.turnId;
985 grouped.push({
986 type: "activity-group",
987 id: entry.id,
988 createdAt: entry.createdAt,
989 turnId: entry.turnId,
990 activities: openGroupActivities,
991 });
992 }
993
994 return grouped;
995}
996
997function computeElapsedMs(startIso: string, endIso: string): number | null {
998 const start = Date.parse(startIso);
999 const end = Date.parse(endIso);
1000 if (!Number.isFinite(start) || !Number.isFinite(end)) {
1001 return null;
1002 }
1003 return Math.max(0, end - start);
1004}
1005
1006function maxIsoTimestamp(a: string | null, b: string | null): string | null {
1007 if (a === null) return b;
1008 if (b === null) return a;
1009 const aMs = Date.parse(a);
1010 const bMs = Date.parse(b);
1011 if (!Number.isFinite(aMs)) return b;
1012 if (!Number.isFinite(bMs)) return a;
1013 return bMs > aMs ? b : a;
1014}
1015
1016function deriveUnsettledTurnId(latestTurn: ThreadFeedLatestTurn | null): TurnId | null {
1017 if (!latestTurn) {
1018 return null;
1019 }
1020 const settled = latestTurn.completedAt !== null && latestTurn.state !== "running";
1021 return settled ? null : latestTurn.turnId;
1022}
1023
1024interface ThreadFeedTurnFold {
1025 readonly turnId: TurnId;
1026 readonly createdAt: string;
1027 readonly hiddenEntryIds: ReadonlySet<string>;
1028 readonly label: string;
1029}
1030
1031function deriveThreadFeedTurnFolds(
1032 feed: ReadonlyArray<ThreadFeedEntry>,
1033 latestTurn: ThreadFeedLatestTurn | null,
1034): ReadonlyMap<string, ThreadFeedTurnFold> {
1035 const terminalAssistantMessageIdByTurn = new Map<TurnId, string>();
1036 for (const entry of feed) {
1037 if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
1038 terminalAssistantMessageIdByTurn.set(entry.message.turnId, entry.id);
1039 }
1040 }
1041
1042 interface TurnGroup {
1043 readonly entries: ThreadFeedEntry[];
1044 readonly startBoundary: string | null;
1045 }
1046 const groupsByTurnId = new Map<TurnId, TurnGroup>();
1047 let pendingUserBoundary: string | null = null;
1048 for (const entry of feed) {
1049 if (entry.type === "message" && entry.message.role === "user") {
1050 pendingUserBoundary = entry.message.createdAt;
1051 continue;
1052 }
1053 const turnId =
1054 entry.type === "message" && entry.message.role === "assistant"
1055 ? entry.message.turnId
1056 : entry.type === "activity-group"
1057 ? entry.turnId
1058 : null;
1059 if (!turnId) {
1060 continue;
1061 }
1062 let group = groupsByTurnId.get(turnId);
1063 if (!group) {
1064 group = {
1065 entries: [],
1066 startBoundary: pendingUserBoundary,
1067 };
1068 pendingUserBoundary = null;
1069 groupsByTurnId.set(turnId, group);
1070 }
1071 group.entries.push(entry);
1072 }
1073
1074 const unsettledTurnId = deriveUnsettledTurnId(latestTurn);
1075 const foldsByAnchorId = new Map<string, ThreadFeedTurnFold>();
1076 for (const [turnId, group] of groupsByTurnId) {
1077 const { entries } = group;
1078 if (turnId === unsettledTurnId) {
1079 continue;
1080 }
1081 if (entries.some((entry) => entry.type === "message" && entry.message.streaming)) {
1082 continue;
1083 }
1084
1085 const terminalAssistantMessageId = terminalAssistantMessageIdByTurn.get(turnId);
1086 const hiddenEntryIds = new Set(
1087 entries.filter((entry) => entry.id !== terminalAssistantMessageId).map((entry) => entry.id),
1088 );
1089 if (hiddenEntryIds.size === 0) {
1090 continue;
1091 }
1092
1093 const firstEntry = entries[0];
1094 const lastEntry = entries.at(-1);
1095 if (!firstEntry || !lastEntry) {
1096 continue;
1097 }
1098 const terminalEntry = terminalAssistantMessageId
1099 ? entries.find((entry) => entry.id === terminalAssistantMessageId)
1100 : null;
1101 const latestTurnMatches = latestTurn?.turnId === turnId;
1102 const lastEntryEnd =
1103 lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
1104 const elapsedMs =
1105 latestTurnMatches && latestTurn.startedAt && latestTurn.completedAt
1106 ? computeElapsedMs(latestTurn.startedAt, latestTurn.completedAt)
1107 : computeElapsedMs(
1108 group.startBoundary ?? firstEntry.createdAt,
1109 maxIsoTimestamp(
1110 terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
1111 lastEntryEnd,
1112 ) ?? lastEntryEnd,
1113 );
1114 const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
1115 const interrupted = latestTurnMatches && latestTurn.state === "interrupted";
1116 const label = interrupted
1117 ? duration
1118 ? `You stopped after ${duration}`
1119 : "You stopped this response"
1120 : duration
1121 ? `Worked for ${duration}`
1122 : "Worked";
1123
1124 foldsByAnchorId.set(firstEntry.id, {
1125 turnId,
1126 createdAt: firstEntry.createdAt,
1127 hiddenEntryIds,
1128 label,
1129 });
1130 }
1131 return foldsByAnchorId;
1132}
1133
1134export function deriveThreadFeedPresentation(
1135 feed: ReadonlyArray<ThreadFeedEntry>,
1136 latestTurn: ThreadFeedLatestTurn | null,
1137 expandedTurnIds: ReadonlySet<TurnId>,
1138 expandedWorkGroupIds: ReadonlySet<string> = new Set(),
1139 activeWorkStartedAt: string | null = null,
1140): ThreadFeedEntry[] {
1141 const sourceFeed = feed.filter(
1142 (entry) =>
1143 entry.type !== "turn-fold" && entry.type !== "work-toggle" && entry.type !== "working",
1144 );
1145 const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
1146 const collapsedEntryIds = new Set<string>();
1147 for (const fold of foldsByAnchorId.values()) {
1148 if (!expandedTurnIds.has(fold.turnId)) {
1149 for (const entryId of fold.hiddenEntryIds) {
1150 collapsedEntryIds.add(entryId);
1151 }
1152 }
1153 }
1154
1155 const result: ThreadFeedEntry[] = [];
1156 for (const entry of sourceFeed) {
1157 const fold = foldsByAnchorId.get(entry.id);
1158 if (fold) {
1159 result.push({
1160 type: "turn-fold",
1161 id: `turn-fold:${fold.turnId}`,
1162 createdAt: fold.createdAt,
1163 turnId: fold.turnId,
1164 label: fold.label,
1165 expanded: expandedTurnIds.has(fold.turnId),
1166 });
1167 }
1168 if (!collapsedEntryIds.has(entry.id)) {
1169 appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
1170 }
1171 }
1172 if (activeWorkStartedAt !== null) {
1173 result.push({
1174 type: "working",
1175 id: "working-indicator-row",
1176 createdAt: activeWorkStartedAt,
1177 });
1178 }
1179 return result;
1180}
1181
1182function appendPresentedFeedEntry(
1183 result: ThreadFeedEntry[],
1184 entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" | "working" }>,
1185 expandedWorkGroupIds: ReadonlySet<string>,
1186): void {
1187 if (entry.type !== "activity-group") {
1188 result.push(entry);
1189 return;
1190 }
1191
1192 const activities = entry.activities.filter(
1193 (activity) => !(activity.toolLike && activity.status === "neutral"),
1194 );
1195 if (activities.length === 0) {
1196 return;
1197 }
1198 if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
1199 result.push({
1200 ...entry,
1201 activities,
1202 });
1203 return;
1204 }
1205
1206 const groupId = entry.id;
1207 const expanded = expandedWorkGroupIds.has(groupId);
1208 const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES;
1209 const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
1210
1211 for (const activity of visibleActivities) {
1212 result.push({
1213 type: "activity-group",
1214 id: activity.id,
1215 createdAt: activity.createdAt,
1216 turnId: activity.turnId,
1217 activities: [activity],
1218 });
1219 }
1220 result.push({
1221 type: "work-toggle",
1222 id: `work-toggle:${groupId}`,
1223 createdAt: entry.createdAt,
1224 turnId: entry.turnId,
1225 groupId,
1226 hiddenCount,
1227 expanded,
1228 onlyToolActivities: activities.every((activity) => activity.toolLike),
1229 });
1230}
1231
1232/**
1233 * Sorts activities into lifecycle order. `derivePendingApprovals` and
1234 * `derivePendingUserInputs` both expect this ordering; sorting once and
1235 * passing the result to both avoids re-sorting the full activity history
1236 * per derivation.
1237 */
1238export function sortThreadActivities(
1239 activities: ReadonlyArray<OrchestrationThreadActivity>,
1240): ReadonlyArray<OrchestrationThreadActivity> {
1241 return Arr.sort(activities, activityOrder);
1242}
1243
1244export function derivePendingApprovals(
1245 sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
1246): PendingApproval[] {
1247 const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
1248
1249 for (const activity of sortedActivities) {
1250 const payload =
1251 activity.payload && typeof activity.payload === "object"
1252 ? (activity.payload as Record<string, unknown>)
1253 : null;
1254 const requestId = parseApprovalRequestId(payload?.requestId);
1255 const requestKind =
1256 payload?.requestKind === "command" ||
1257 payload?.requestKind === "file-read" ||
1258 payload?.requestKind === "file-change"
1259 ? payload.requestKind
1260 : requestKindFromRequestType(payload?.requestType);
1261 const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
1262
1263 if (activity.kind === "approval.requested" && requestId && requestKind) {
1264 openByRequestId.set(requestId, {
1265 requestId,
1266 requestKind,
1267 createdAt: activity.createdAt,
1268 ...(detail ? { detail } : {}),
1269 });
1270 continue;
1271 }
1272
1273 if (activity.kind === "approval.resolved" && requestId) {
1274 openByRequestId.delete(requestId);
1275 continue;
1276 }
1277
1278 if (
1279 activity.kind === "provider.approval.respond.failed" &&
1280 requestId &&
1281 isStalePendingRequestFailureDetail(detail)
1282 ) {
1283 openByRequestId.delete(requestId);
1284 }
1285 }
1286
1287 return Arr.sortWith([...openByRequestId.values()], (s) => new Date(s.createdAt), Order.Date);
1288}
1289
1290export function derivePendingUserInputs(
1291 sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
1292): PendingUserInput[] {
1293 const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
1294
1295 for (const activity of sortedActivities) {
1296 const payload =
1297 activity.payload && typeof activity.payload === "object"
1298 ? (activity.payload as Record<string, unknown>)
1299 : null;
1300 const requestId = parseApprovalRequestId(payload?.requestId);
1301 const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
1302
1303 if (activity.kind === "user-input.requested" && requestId) {
1304 const questions = parseUserInputQuestions(payload);
1305 if (!questions) {
1306 continue;
1307 }
1308 openByRequestId.set(requestId, {
1309 requestId,
1310 createdAt: activity.createdAt,
1311 questions,
1312 });
1313 continue;
1314 }
1315
1316 if (activity.kind === "user-input.resolved" && requestId) {
1317 openByRequestId.delete(requestId);
1318 continue;
1319 }
1320
1321 if (
1322 activity.kind === "provider.user-input.respond.failed" &&
1323 requestId &&
1324 isStalePendingRequestFailureDetail(detail)
1325 ) {
1326 openByRequestId.delete(requestId);
1327 }
1328 }
1329
1330 return Arr.sortWith(openByRequestId.values(), (s) => new Date(s.createdAt), Order.Date);
1331}
1332
1333export function setPendingUserInputCustomAnswer(
1334 draft: PendingUserInputDraftAnswer | undefined,
1335 customAnswer: string,
1336): PendingUserInputDraftAnswer {
1337 const selectedOptionLabel =
1338 customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
1339 return {
1340 customAnswer,
1341 ...(selectedOptionLabel ? { selectedOptionLabel } : {}),
1342 };
1343}
1344
1345export function buildPendingUserInputAnswers(
1346 questions: ReadonlyArray<UserInputQuestion>,
1347 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
1348): Record<string, string> | null {
1349 const answers: Record<string, string> = {};
1350
1351 for (const question of questions) {
1352 const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
1353 if (!answer) {
1354 return null;
1355 }
1356 answers[question.id] = answer;
1357 }
1358
1359 return answers;
1360}
1361
1362export function buildThreadFeed(
1363 thread: OrchestrationThread,
1364 options?: {
1365 readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
1366 },
1367): ThreadFeedEntry[] {
1368 const loadedMessages = options?.loadedMessages ?? thread.messages;
1369 const oldestLoadedMessageCreatedAt =
1370 options?.loadedMessages !== undefined ? (loadedMessages[0]?.createdAt ?? null) : null;
1371 const workLogEntries = deriveWorkLogEntries(thread.activities);
1372 const entries = Arr.sortWith(
1373 [
1374 ...loadedMessages.map<RawThreadFeedEntry>((message) => ({
1375 type: "message",
1376 id: message.id,
1377 createdAt: message.createdAt,
1378 message,
1379 })),
1380 ...workLogEntries
1381 .filter((entry) => {
1382 if (options?.loadedMessages === undefined) {
1383 return true;
1384 }
1385 return (
1386 oldestLoadedMessageCreatedAt === null || entry.createdAt >= oldestLoadedMessageCreatedAt
1387 );
1388 })
1389 .map<RawThreadFeedEntry>((entry) => {
1390 const summary = workEntryHeading(entry);
1391 const detail = workEntryPreview(entry);
1392 const getFullDetail = memoizeValue(() => buildWorkEntryExpandedBody(entry));
1393 const getCopyText = memoizeValue(() =>
1394 [summary, detail, getFullDetail()]
1395 .filter((value, index, values): value is string => {
1396 return Boolean(value) && values.indexOf(value) === index;
1397 })
1398 .join("\n"),
1399 );
1400 return {
1401 type: "activity",
1402 id: entry.id,
1403 createdAt: entry.createdAt,
1404 turnId: entry.turnId,
1405 activity: {
1406 id: entry.id,
1407 createdAt: entry.createdAt,
1408 turnId: entry.turnId,
1409 summary,
1410 detail,
1411 canExpand: workEntryHasExpandedBody(entry),
1412 getFullDetail,
1413 getCopyText,
1414 icon: workEntryIcon(entry),
1415 toolLike: workLogEntryIsToolLike(entry),
1416 status: workEntryStatus(entry),
1417 },
1418 };
1419 }),
1420 ],
1421 (s) => new Date(s.createdAt),
1422 Order.Date,
1423 );
1424
1425 return groupAdjacentActivities(entries);
1426}