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

threadActivity.ts

1,372 lines40.7 KB

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