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