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

threadActivity.ts

1,386 lines41.1 KB

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