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

itemDetail.ts

325 lines11.6 KB

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