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

itemDetail.ts

478 lines17.2 KB

1import type {
2 AssetResource,
3 OrchestrationV2FileSearchResult,
4 OrchestrationV2TurnItem,
5} from "@t3tools/contracts";
6import { EnvironmentId, ThreadId } from "@t3tools/contracts";
7import { commandItemOutput } from "@t3tools/shared/commandOutput";
8import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp";
9import {
10 isJavaScriptReplTool,
11 truncatedCommandNotificationPrefix,
12} from "@t3tools/shared/toolActivity";
13import {
14 compactDynamicToolOutput,
15 mcpToolResultOutput,
16 toolOutputImageBlocks,
17 toolOutputImages,
18} from "@t3tools/shared/toolOutput";
19import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
20import { replaceThreadLinks, threadLinkCandidates } from "@t3tools/shared/threadLinks";
21import * as DateTime from "effect/DateTime";
22​
23const MAX_TEXT_BLOCK_DEPTH = 4;
24​
25export function threadReadTarget(
26 item: OrchestrationV2TurnItem | undefined,
27 sourceEnvironmentId: EnvironmentId,
28) {
29 if (item?.type !== "dynamic_tool" || resolveT3McpToolId(item.toolName) !== "t3_thread_read") {
30 return null;
31 }
32 const input = isRecord(item.input) ? item.input : undefined;
33 const args = isRecord(input?.args) ? input.args : input;
34 const output = compactDynamicToolOutput(item.output, item.toolName);
35 const returned = output?.isError ? undefined : output?.thread;
36 const id = typeof args?.threadId === "string" ? args.threadId.trim() : "";
37 const threadId = id ? ThreadId.make(id) : returned ? ThreadId.make(returned.threadId) : null;
38 if (threadId === null) return null;
39 const thread = returned?.threadId === threadId ? returned : undefined;
40 let linkedEnvironmentId: EnvironmentId | null = null;
41 if (thread?.link) {
42 replaceThreadLinks(thread.link, (link) => {
43 if (
44 link.environmentId !== null &&
45 threadLinkCandidates(link, sourceEnvironmentId).some((ref) => ref.threadId === threadId)
46 ) {
47 linkedEnvironmentId ??= link.environmentId;
48 }
49 return undefined;
50 });
51 }
52 const inputEnvironment = typeof args?.environmentId === "string" ? args.environmentId.trim() : "";
53 const environmentId = inputEnvironment
54 ? EnvironmentId.make(inputEnvironment)
55 : (linkedEnvironmentId ?? sourceEnvironmentId);
56 return {
57 ref: { environmentId, threadId },
58 title:
59 linkedEnvironmentId === null || linkedEnvironmentId === environmentId
60 ? (thread?.title ?? null)
61 : null,
62 };
64​
65function isRecord(value: unknown): value is Record<string, unknown> {
66 return typeof value === "object" && value !== null && !Array.isArray(value);
68​
69function isSummarizedValue(value: unknown): boolean {
70 return isRecord(value) && value.truncated === true && typeof value.summary === "string";
72​
73function textFromBlocks(
74 value: unknown,
75 depth: number,
76 imageBlocks: ReadonlyArray<unknown>,
77): string | null {
78 if (depth > MAX_TEXT_BLOCK_DEPTH) return null;
79 if (typeof value === "string") return value;
80 if (Array.isArray(value)) {
81 const parts = value.map((block) => textFromBlocks(block, depth + 1, imageBlocks));
82 return parts.every((part) => part !== null)
83 ? parts.filter((part) => part !== "").join("\n")
84 : null;
85 }
86 if (!isRecord(value)) return null;
87 if (value.type === "text" && typeof value.text === "string") return value.text;
88 // ACP tool calls wrap each content block in a `content` entry.
89 if (value.type === "content" && isRecord(value.content)) {
90 return textFromBlocks(value.content, depth + 1, imageBlocks);
91 }
92 if (value.type === "image") return imageBlocks.includes(value) ? "" : "[image]";
93 if (value.type === "resource_link" && typeof value.uri === "string") return value.uri;
94 if (value.type === "resource" && isRecord(value.resource)) {
95 const resource = value.resource;
96 if (typeof resource.text === "string") return resource.text;
97 if (typeof resource.uri === "string") return resource.uri;
98 }
99 const keys = Object.keys(value).filter(
100 (key) => key !== "isError" && key !== "is_error" && key !== "_meta",
101 );
102 if (keys.length === 1 && keys[0] === "content")
103 return textFromBlocks(value.content, depth + 1, imageBlocks);
104 if (keys.length === 2 && keys.includes("content") && keys.includes("structuredContent")) {
105 const text = textFromBlocks(value.content, depth + 1, imageBlocks);
106 const images = Array.isArray(value.content)
107 ? value.content.filter((block) => isRecord(block) && block.type === "image")
108 : [];
109 const structured = formatJsonValue(value.structuredContent);
110 if (structured !== null && (images.length > 0 || !text?.trim())) {
111 const markers = textFromBlocks(images, depth + 1, imageBlocks);
112 return [structured, markers].filter(Boolean).join("\n");
113 }
114 return text;
115 }
116 return null;
118​
119function parseJson(text: string): unknown {
120 try {
121 return JSON.parse(text);
122 } catch {
123 return undefined;
124 }
126​
127export function isJsonToolText(text: string): boolean {
128 if (parseJson(text) !== undefined) return true;
129 const trimmed = text.trim();
130 const documents = trimmed.split(/\n\s*\n/);
131 if (documents.length > 1 && documents.every((document) => parseJson(document) !== undefined)) {
132 return true;
133 }
134 return trimmed
135 .split(/\n\s*/)
136 .every((line) => /^[[{]/.test(line) && parseJson(line) !== undefined);
138​
139interface ToolArgument {
140 readonly key: string;
141 readonly text: string;
142 readonly inlineJson: boolean;
144​
145export function toolArgumentLanguage(
146 argument: ToolArgument,
147 tool?: Pick<
148 Extract<OrchestrationV2TurnItem, { type: "dynamic_tool" }>,
149 "toolName" | "nativeItemRef"
150 >,
151): "html" | "typescript" | "json" | null {
152 const { key, inlineJson } = argument;
153 if (inlineJson) return "json";
154 if (key === "html") return "html";
155 if (
156 key === "code" &&
157 (isJavaScriptReplTool(tool?.toolName) ||
158 (tool?.toolName === "execute" && tool.nativeItemRef?.driver === "opencode"))
159 ) {
160 return "typescript";
161 }
162 const text = argument.text.trim();
163 return (/^[[{]/.test(text) || text.includes("\n")) && isJsonToolText(text) ? "json" : null;
165​
166// Strings match whole so numbers inside them are skipped. Scan only parsed JSON: every string closes.
167const JSON_TOKEN = /("(?:[^"\\]|\\.)*")(\s*:)?|[{}[\]]|(-?\d+(?:\.\d+)?)(?:[eE][+-]?\d+)?/g;
168​
169/** Normalizes a decimal to `<sign><digits>e<exponent>` so `1.50` and `15e-1` compare equal. */
170function decimalKey(number: string): string {
171 const [, sign = "", whole = "", fraction = "", exponent = "0"] =
172 /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(number) ?? [];
173 const digits = (whole + fraction).replace(/^0+/, "");
174 let end = digits.length;
175 while (end > 0 && digits[end - 1] === "0") end--;
176 if (end === 0) return "0";
177 return `${sign}${digits.slice(0, end)}e${Number(exponent) - fraction.length + digits.length - end}`;
179​
180/**
181 * Keep raw JSON when parsing would drop a repeated key or change a number's value, or when
182 * stringifying would move a key: array-index keys always come first, in ascending order.
183 */
184function hasLossyJson(json: string): boolean {
185 const objectKeys: Array<{ keys: Set<unknown>; lastIndex: number } | null> = [];
186 for (const [token, string, colon, mantissa] of json.matchAll(JSON_TOKEN)) {
187 if (token === "{" || token === "[") {
188 objectKeys.push(token === "{" ? { keys: new Set(), lastIndex: -1 } : null);
189 } else if (token === "}" || token === "]") objectKeys.pop();
190 else if (string !== undefined && colon !== undefined) {
191 const object = objectKeys.at(-1);
192 if (object) {
193 const key = parseJson(string);
194 if (object.keys.has(key)) return true;
195 object.keys.add(key);
196 const index =
197 typeof key === "string" && /^(?:0|[1-9]\d*)$/.test(key) && Number(key) < 2 ** 32 - 1
198 ? Number(key)
199 : Infinity;
200 if (index < object.lastIndex) return true;
201 object.lastIndex = index;
202 }
203 }
204 if (mantissa === undefined) continue;
205 const value = Number(token);
206 if (
207 !Number.isFinite(value) ||
208 (Number.isInteger(value) && !Number.isSafeInteger(value)) ||
209 decimalKey(token) !== decimalKey(String(value))
210 ) {
211 return true;
212 }
213 }
214 return false;
216​
217function prettyJsonText(text: string): string {
218 const trimmed = text.trim();
219 if (!/^[[{]/.test(trimmed)) return text;
220 const whole = parseJson(trimmed);
221 if (whole !== undefined) {
222 return hasLossyJson(trimmed) ? text : JSON.stringify(whole, null, 2);
223 }
224 const lines = trimmed.split("\n").filter((line) => line.trim());
225 const documents = lines.map((line) => parseJson(line.trim()));
226 if (documents.some((document) => document === undefined) || hasLossyJson(trimmed)) {
227 return text;
228 }
229 return documents.map((document) => JSON.stringify(document, null, 2)).join("\n\n");
231​
232function formatJsonValue(value: unknown): string | null {
233 if (value === undefined || value === null) return null;
234 if (typeof value === "string" && !value.trim()) return null;
235 let json: string | undefined;
236 try {
237 json = JSON.stringify(value, null, 2);
238 } catch {
239 return String(value);
240 }
241 if (json === undefined || json === "{}" || json === "[]") return null;
242 return json;
244​
245function formatToolValue(
246 value: unknown,
247 hasImagePreview = false,
248 previewedImageBlocks = toolOutputImageBlocks(value),
249): string | null {
250 if (value === undefined || value === null) return null;
251 if (hasImagePreview && isRecord(value) && value.type === "image") return null;
252 const text = textFromBlocks(value, 0, previewedImageBlocks);
253 if (text !== null) return text.trim() ? prettyJsonText(text) : null;
254 return formatJsonValue(value);
256​
257export function toolCallLines(input: {
258 readonly command?: string | undefined;
259 readonly args?: unknown;
260}): {
261 readonly command: string | null;
262 readonly args: ReadonlyArray<ToolArgument> | null;
263 readonly argsText: string | null;
264} {
265 if (input.command !== undefined) {
266 const command = input.command.trim();
267 return { command: command || null, args: null, argsText: null };
268 }
269 const args = input.args;
270 if (isRecord(args) && !isSummarizedValue(args)) {
271 const entries = Object.entries(args).flatMap(([key, value]): ToolArgument[] => {
272 if (value === undefined) return [];
273 // An empty string or null can be the point of a call (a clear or reset), so show it.
274 return [
275 {
276 key,
277 text:
278 typeof value === "string" && value !== ""
279 ? value
280 : (JSON.stringify(value) ?? String(value)),
281 inlineJson: value === null || typeof value === "boolean" || typeof value === "number",
282 },
283 ];
284 });
285 return { command: null, args: entries.length > 0 ? entries : null, argsText: null };
286 }
287 return { command: null, args: null, argsText: formatToolValue(args) };
289​
290function toolCallHasLines(lines: ReturnType<typeof toolCallLines>): boolean {
291 return lines.command !== null || lines.args !== null || lines.argsText !== null;
293​
294const LIVE_TURN_ITEM_STATUSES: ReadonlySet<OrchestrationV2TurnItem["status"]> = new Set([
295 "idle",
296 "pending",
297 "running",
298 "waiting",
299]);
300​
301/**
302 * A running item keeps one key, so an open row fetches once while it streams and
303 * again when it finishes, not on every update.
304 */
305export function turnItemDetailRevision(item: OrchestrationV2TurnItem): string {
306 return LIVE_TURN_ITEM_STATUSES.has(item.status) ? "live" : DateTime.formatIso(item.updatedAt);
308​
309export function turnItemNeedsDetailFetch(item: OrchestrationV2TurnItem): boolean {
310 switch (item.type) {
311 case "command_execution":
312 return item.outputOmitted === true;
313 case "dynamic_tool":
314 return item.outputOmitted === true || isSummarizedValue(item.input);
315 case "notification":
316 return (
317 item.detailTruncated === true ||
318 (!item.detail?.trim() &&
319 item.runId !== null &&
320 truncatedCommandNotificationPrefix(item) !== undefined)
321 );
322 default:
323 return false;
324 }
326​
327// App calls store the provider result beside the app reference; its images get no preview.
328function dynamicToolOutputText(
329 item: Extract<OrchestrationV2TurnItem, { readonly type: "dynamic_tool" }>,
330): string | null {
331 const output = item.output;
332 if (!isRecord(output) || !(MCP_APP_OUTPUT_KEY in output) || !("result" in output)) {
333 return formatToolValue(output, item.viewedImagePath !== undefined);
334 }
335 const result = output.result;
336 return formatToolValue(isRecord(result) ? mcpToolResultOutput(result) : result, false, []);
338​
339export interface FileSearchResultGroup {
340 readonly fileName: string;
341 readonly results: ReadonlyArray<OrchestrationV2FileSearchResult>;
343​
344/** Results under one heading per file, in first-seen order, the way `rg --heading` prints them. */
345export function groupFileSearchResults(
346 results: ReadonlyArray<OrchestrationV2FileSearchResult>,
347): ReadonlyArray<FileSearchResultGroup> {
348 const groups = new Map<string, OrchestrationV2FileSearchResult[]>();
349 for (const result of results) {
350 const group = groups.get(result.fileName);
351 if (group) group.push(result);
352 else groups.set(result.fileName, [result]);
353 }
354 return Array.from(groups, ([fileName, grouped]) => ({ fileName, results: grouped }));
356​
357function fileSearchResultsText(results: ReadonlyArray<OrchestrationV2FileSearchResult>): string {
358 const groups = groupFileSearchResults(results).map((group) => [
359 group.fileName,
360 ...group.results.flatMap((result) => {
361 const preview = result.preview?.trimEnd() ?? "";
362 if (result.line === undefined) return preview.trim() ? [preview] : [];
363 const position = `${result.line}${result.column === undefined ? "" : `:${result.column}`}`;
364 return [`${position}: ${preview}`.trimEnd()];
365 }),
366 ]);
367 // A plain file list stays one path per line; files with matches get a blank line between them.
368 return groups.every((lines) => lines.length === 1)
369 ? groups.map(([fileName]) => fileName).join("\n")
370 : groups.map((lines) => lines.join("\n")).join("\n\n");
372​
373export function fileSearchFailureText(
374 item: Extract<OrchestrationV2TurnItem, { type: "file_search" }>,
375): string | null {
376 if (item.status !== "failed" || item.results?.length !== 1) return null;
377 const result = item.results[0];
378 if (!result || result.line !== undefined || result.column !== undefined) return null;
379 // Adapters record unstructured failures as a single preview under the search root.
380 const preview = result.preview?.trim();
381 if (!preview) return null;
382 const error = preview.startsWith("{") ? parseJson(preview) : undefined;
383 return isRecord(error) &&
384 Object.keys(error).length === 1 &&
385 typeof error.message === "string" &&
386 error.message.trim()
387 ? error.message.trim()
388 : preview;
390​
391export function turnItemOutputText(item: OrchestrationV2TurnItem): string | null {
392 switch (item.type) {
393 case "notification":
394 return item.detail?.trim() || null;
395 case "command_execution": {
396 const output = commandItemOutput(item);
397 return output?.trim() ? output : null;
398 }
399 case "dynamic_tool":
400 return item.outputOmitted === true ? null : dynamicToolOutputText(item);
401 case "file_search":
402 return (
403 fileSearchFailureText(item) ??
404 (item.results?.length ? fileSearchResultsText(item.results) : null)
405 );
406 case "web_search":
407 return item.results?.length
408 ? item.results
409 .map((result) =>
410 [
411 result.title?.trim() || result.url,
412 result.title ? result.url : undefined,
413 result.snippet?.trim(),
414 ]
415 .filter(Boolean)
416 .join("\n"),
417 )
418 .join("\n\n")
419 : null;
420 default:
421 return null;
422 }
424​
425export function turnItemOutputImages(
426 item: OrchestrationV2TurnItem,
427): ReadonlyArray<Extract<AssetResource, { readonly _tag: "tool-output-image" }>> {
428 if (item.type !== "dynamic_tool" || item.outputOmitted === true) return [];
429 return toolOutputImages(item.output).map((_, index) => ({
430 _tag: "tool-output-image",
431 threadId: item.threadId,
432 itemId: item.id,
433 index,
434 }));
436​
437export function turnItemHasDetail(item: OrchestrationV2TurnItem): boolean {
438 switch (item.type) {
439 case "reasoning":
440 return item.text.trim().length > 0;
441 case "command_execution":
442 return (
443 toolCallLines({ command: item.input }).command !== null ||
444 item.outputOmitted === true ||
445 Boolean(item.output?.trim()) ||
446 (item.exitCode !== undefined && item.exitCode !== 0)
447 );
448 case "file_change":
449 case "checkpoint":
450 case "fork":
451 case "handoff":
452 return true;
453 case "file_search":
454 return (item.results?.length ?? 0) > 0 || Boolean(item.pattern?.trim());
455 case "web_search":
456 return (item.results?.length ?? 0) > 0 || (item.patterns?.length ?? 0) > 0;
457 case "dynamic_tool":
458 return item.outputOmitted === true || toolCallHasLines(toolCallLines({ args: item.input }));
459 case "approval_request":
460 return Boolean(item.prompt?.trim());
461 case "user_input_request":
462 return item.questions.length > 0;
463 case "notification":
464 return Boolean(item.detail?.trim()) || turnItemNeedsDetailFetch(item);
465 case "system_notice":
466 return item.message.trim().length > 0;
467 case "error":
468 return item.failure.message.trim().length > 0;
469 case "proposed_plan":
470 return item.markdown.trim().length > 0;
471 case "todo_list":
472 return item.steps.length > 0;
473 case "subagent":
474 return item.childThreadId !== null;
475 default:
476 return false;
477 }