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

itemDetail.ts

248 lines8.5 KB

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