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