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