Open History to see the last commit
1import type { AssetResource, OrchestrationV2TurnItem } from "@t3tools/contracts";
2import { readToolOutputImage, toolOutputImages } from "@t3tools/shared/toolOutput";
3import * as DateTime from "effect/DateTime";
4
5const MAX_TEXT_BLOCK_DEPTH = 4;
6
7function isRecord(value: unknown): value is Record<string, unknown> {
8 return typeof value === "object" && value !== null && !Array.isArray(value);
9}
10
11/** Wire projection replaces a large dynamic input with `{ summary, truncated: true }`. */
12function isSummarizedValue(value: unknown): boolean {
13 return isRecord(value) && value.truncated === true && typeof value.summary === "string";
14}
15
16function textFromBlocks(value: unknown, depth: number): string | null {
17 if (depth > MAX_TEXT_BLOCK_DEPTH) return null;
18 if (typeof value === "string") return value;
19 if (Array.isArray(value)) {
20 const parts = value.map((block) => textFromBlocks(block, depth + 1));
21 return parts.every((part) => part !== null)
22 ? parts.filter((part) => part !== "").join("\n")
23 : null;
24 }
25 if (!isRecord(value)) return null;
26 if (value.type === "text" && typeof value.text === "string") return value.text;
27 // Images clients can show render on their own (see turnItemOutputImages).
28 if (value.type === "image") return readToolOutputImage(value) ? "" : "[image]";
29 if (value.type === "resource_link" && typeof value.uri === "string") return value.uri;
30 if (value.type === "resource" && isRecord(value.resource)) {
31 const resource = value.resource;
32 if (typeof resource.text === "string") return resource.text;
33 if (typeof resource.uri === "string") return resource.uri;
34 }
35 const keys = Object.keys(value).filter((key) => key !== "isError" && key !== "is_error");
36 // MCP results and provider tool results wrap their text in `content`.
37 // `structuredContent` usually repeats it as data, so it only shows when the
38 // text is empty.
39 if (keys.length === 1 && keys[0] === "content") return textFromBlocks(value.content, depth + 1);
40 if (keys.length === 2 && keys.includes("content") && keys.includes("structuredContent")) {
41 const text = textFromBlocks(value.content, depth + 1);
42 return text?.trim() ? text : null;
43 }
44 return null;
45}
46
47function parseJson(text: string): unknown {
48 try {
49 return JSON.parse(text);
50 } catch {
51 return undefined;
52 }
53}
54
55/** MCP tools often return JSON as minified text, one document per line. Indent each. */
56function prettyJsonText(text: string): string {
57 const trimmed = text.trim();
58 if (!/^[[{]/.test(trimmed)) return text;
59 const whole = parseJson(trimmed);
60 if (whole !== undefined) return JSON.stringify(whole, null, 2);
61 const lines = trimmed.split("\n").filter((line) => line.trim());
62 const documents = lines.map((line) => parseJson(line.trim()));
63 if (documents.some((document) => document === undefined)) return text;
64 return documents.map((document) => JSON.stringify(document, null, 2)).join("\n\n");
65}
66
67/** Formats a tool input or output for display: text blocks as text, the rest as JSON. */
68function formatToolValue(value: unknown): string | null {
69 if (value === undefined || value === null) return null;
70 const text = textFromBlocks(value, 0);
71 if (text !== null) return text.trim() ? prettyJsonText(text) : null;
72 let json: string | undefined;
73 try {
74 json = JSON.stringify(value, null, 2);
75 } catch {
76 return String(value);
77 }
78 if (json === undefined || json === "{}" || json === "[]") return null;
79 return json;
80}
81
82/**
83 * The call a tool row's body shows above its result: the full command, the
84 * arguments as `key value` pairs, or formatted text when they are not flat.
85 */
86export function toolCallLines(input: {
87 readonly command?: string | undefined;
88 readonly args?: unknown;
89}): {
90 readonly command: string | null;
91 readonly args: ReadonlyArray<readonly [string, string]> | null;
92 readonly argsText: string | null;
93} {
94 if (input.command !== undefined) {
95 // The row title truncates to its width, so the body always has the full command.
96 const command = input.command.trim();
97 return { command: command || null, args: null, argsText: null };
98 }
99 const args = input.args;
100 if (isRecord(args) && !isSummarizedValue(args)) {
101 const entries = Object.entries(args).flatMap(
102 ([key, value]): Array<readonly [string, string]> => {
103 if (value === undefined) return [];
104 // An empty string or null can be the point of a call (a clear or reset), so show it.
105 return [
106 [
107 key,
108 typeof value === "string" && value !== ""
109 ? value
110 : (JSON.stringify(value) ?? String(value)),
111 ],
112 ];
113 },
114 );
115 return { command: null, args: entries.length > 0 ? entries : null, argsText: null };
116 }
117 return { command: null, args: null, argsText: formatToolValue(args) };
118}
119
120function toolCallHasLines(lines: ReturnType<typeof toolCallLines>): boolean {
121 return lines.command !== null || lines.args !== null || lines.argsText !== null;
122}
123
124const LIVE_TURN_ITEM_STATUSES: ReadonlySet<OrchestrationV2TurnItem["status"]> = new Set([
125 "idle",
126 "pending",
127 "running",
128 "waiting",
129]);
130
131/**
132 * Cache key for a fetched item. A running item keeps one key, so an open row
133 * fetches once while it streams and again when it finishes, not on every update.
134 */
135export function turnItemDetailRevision(item: OrchestrationV2TurnItem): string {
136 return LIVE_TURN_ITEM_STATUSES.has(item.status) ? "live" : DateTime.formatIso(item.updatedAt);
137}
138
139/** True when the timeline item withholds content that `getTurnItem` returns. */
140export function turnItemNeedsDetailFetch(item: OrchestrationV2TurnItem): boolean {
141 switch (item.type) {
142 case "command_execution":
143 return item.outputOmitted === true;
144 case "dynamic_tool":
145 return item.outputOmitted === true || isSummarizedValue(item.input);
146 default:
147 return false;
148 }
149}
150
151/** Older Claude bash rows stored the raw `{ stdout, stderr, interrupted, ... }` result. */
152function commandOutputText(output: string): string {
153 if (!output.trimStart().startsWith('{"stdout"')) return output;
154 const parsed = parseJson(output.trim());
155 if (
156 !isRecord(parsed) ||
157 typeof parsed.stdout !== "string" ||
158 typeof parsed.stderr !== "string" ||
159 typeof parsed.interrupted !== "boolean"
160 ) {
161 return output;
162 }
163 return [parsed.stdout, parsed.stderr]
164 .filter((part): part is string => typeof part === "string" && part.trim().length > 0)
165 .join("\n");
166}
167
168/** The tool output carried by a fetched item, formatted for display. */
169export function turnItemOutputText(item: OrchestrationV2TurnItem): string | null {
170 switch (item.type) {
171 case "command_execution":
172 return item.output?.trim() ? commandOutputText(item.output) || null : null;
173 case "dynamic_tool":
174 return item.outputOmitted === true ? null : formatToolValue(item.output);
175 case "file_search":
176 return item.results?.length
177 ? item.results
178 .map((result) =>
179 [
180 `${result.fileName}${result.line === undefined ? "" : `:${result.line}`}`,
181 result.preview?.trim(),
182 ]
183 .filter(Boolean)
184 .join("\n"),
185 )
186 .join("\n")
187 : null;
188 case "web_search":
189 return item.results?.length
190 ? item.results
191 .map((result) =>
192 [
193 result.title?.trim() || result.url,
194 result.title ? result.url : undefined,
195 result.snippet?.trim(),
196 ]
197 .filter(Boolean)
198 .join("\n"),
199 )
200 .join("\n\n")
201 : null;
202 default:
203 return null;
204 }
205}
206
207/**
208 * Images in a fetched item's tool output, as assets. The detail read leaves
209 * the bytes out, so each loads over HTTP by its index.
210 */
211export function turnItemOutputImages(
212 item: OrchestrationV2TurnItem,
213): ReadonlyArray<Extract<AssetResource, { readonly _tag: "tool-output-image" }>> {
214 if (item.type !== "dynamic_tool" || item.outputOmitted === true) return [];
215 return toolOutputImages(item.output).map((_, index) => ({
216 _tag: "tool-output-image",
217 threadId: item.threadId,
218 itemId: item.id,
219 index,
220 }));
221}
222
223/**
224 * Whether expanding the item shows anything. Rows without content must not
225 * offer a disclosure, otherwise they open to an empty panel.
226 */
227export function turnItemHasDetail(item: OrchestrationV2TurnItem): boolean {
228 switch (item.type) {
229 case "reasoning":
230 return item.text.trim().length > 0;
231 case "command_execution":
232 return (
233 toolCallLines({ command: item.input }).command !== null ||
234 item.outputOmitted === true ||
235 Boolean(item.output?.trim()) ||
236 (item.exitCode !== undefined && item.exitCode !== 0)
237 );
238 case "file_change":
239 case "checkpoint":
240 case "fork":
241 case "handoff":
242 return true;
243 case "file_search":
244 return (item.results?.length ?? 0) > 0 || Boolean(item.pattern?.trim());
245 case "web_search":
246 return (item.results?.length ?? 0) > 0 || (item.patterns?.length ?? 0) > 0;
247 case "dynamic_tool":
248 return item.outputOmitted === true || toolCallHasLines(toolCallLines({ args: item.input }));
249 case "approval_request":
250 return Boolean(item.prompt?.trim());
251 case "user_input_request":
252 return item.questions.length > 0;
253 case "notification":
254 return Boolean(item.detail?.trim());
255 case "system_notice":
256 return item.message.trim().length > 0;
257 case "error":
258 return item.failure.message.trim().length > 0;
259 case "proposed_plan":
260 return item.markdown.trim().length > 0;
261 case "todo_list":
262 return item.steps.length > 0;
263 case "subagent":
264 return item.childThreadId !== null;
265 default:
266 return false;
267 }
268}