@@ -0,0 +1,309 @@
1+import * as c from "yoctocolors";
2+import { G, writeln } from "./output.ts";
3+
4+// ─── Shared helpers ───────────────────────────────────────────────────────────
5+
6+const MAX_DIFF_PREVIEW_LINES = 24;
7+
8+function colorizeDiffLine(line: string): string {
9+ if (line.startsWith("+++") || line.startsWith("---")) return c.dim(line);
10+ if (line.startsWith("+")) return c.green(line);
11+ if (line.startsWith("-")) return c.red(line);
12+ if (line.startsWith("@@")) return c.cyan(line);
13+ return c.dim(line);
14+}
15+
16+function renderDiff(diff: string): void {
17+ if (!diff || diff === "(no changes)") return;
18+
19+ const normalized = diff.replace(/[\r\n]+$/, "");
20+ if (!normalized) return;
21+
22+ const lines = normalized.split("\n");
23+ const shown = lines.slice(0, MAX_DIFF_PREVIEW_LINES);
24+ for (const line of shown) {
25+ writeln(` ${colorizeDiffLine(line)}`);
26+ }
27+ if (lines.length > shown.length) {
28+ writeln(
29+ ` ${c.dim(`… +${lines.length - shown.length} more diff lines`)}`,
30+ );
31+ }
32+}
33+
34+function writePreviewLines(opts: {
35+ label: string;
36+ value: string;
37+ lineColor: (input: string) => string;
38+ maxLines: number;
39+}): void {
40+ if (!opts.value.trim()) return;
41+ const lines = opts.value.split("\n");
42+ writeln(` ${c.dim(opts.label)} ${c.dim(`(${lines.length} lines)`)}`);
43+ for (const line of lines.slice(0, opts.maxLines)) {
44+ writeln(` ${opts.lineColor("│")} ${line}`);
45+ }
46+ if (lines.length > opts.maxLines) {
47+ writeln(
48+ ` ${opts.lineColor("│")} ${c.dim(`… +${lines.length - opts.maxLines} lines`)}`,
49+ );
50+ }
51+}
52+
53+function truncateOneLine(value: string, max = 100): string {
54+ return value.length > max ? `${value.slice(0, max - 1)}…` : value;
55+}
56+
57+// ─── Tool result renderers ────────────────────────────────────────────────────
58+
59+type ToolResultRenderer = (result: unknown, toolName?: string) => boolean;
60+
61+function renderReadResult(result: unknown): boolean {
62+ const r = result as {
63+ path: string;
64+ line: number;
65+ totalLines: number;
66+ truncated: boolean;
67+ content?: string;
68+ };
69+ if (!r || typeof r.path !== "string") return false;
70+
71+ const linesReturned = r.content ? r.content.split("\n").length : 0;
72+ const endLine = linesReturned > 0 ? r.line + linesReturned - 1 : r.line;
73+ const range =
74+ r.line === 1 && endLine === r.totalLines
75+ ? `${r.totalLines} lines`
76+ : `lines ${r.line}–${endLine} of ${r.totalLines}`;
77+ writeln(
78+ ` ${G.info} ${c.dim(`${r.path} ${range}${r.truncated ? " (truncated)" : ""}`)}`,
79+ );
80+ return true;
81+}
82+
83+function renderCreateResult(result: unknown): boolean {
84+ const r = result as { path: string; diff: string; created: boolean };
85+ if (!r || typeof r.path !== "string") return false;
86+ const verb = r.created ? c.green("created") : c.dim("overwritten");
87+ writeln(` ${G.ok} ${verb} ${r.path}`);
88+ renderDiff(r.diff);
89+ return true;
90+}
91+
92+function renderReplaceOrInsertResult(
93+ toolName: string,
94+ result: unknown,
95+): boolean {
96+ const r = result as { path: string; diff: string; deleted?: boolean };
97+ if (!r || typeof r.path !== "string") return false;
98+ const verb =
99+ toolName === "insert" ? "inserted" : r.deleted ? "deleted" : "replaced";
100+ writeln(` ${G.ok} ${c.dim(verb)} ${r.path}`);
101+ renderDiff(r.diff);
102+ return true;
103+}
104+
105+function renderShellResult(result: unknown): boolean {
106+ const r = result as {
107+ stdout: string;
108+ stderr: string;
109+ exitCode: number;
110+ success: boolean;
111+ timedOut: boolean;
112+ };
113+ if (!r || typeof r.stdout !== "string" || typeof r.stderr !== "string") {
114+ return false;
115+ }
116+
117+ const badge = r.timedOut
118+ ? c.yellow("timeout")
119+ : r.success
120+ ? c.green("success")
121+ : c.red("error");
122+
123+ const stdoutNormalized = r.stdout.replace(/[\r\n]+$/, "");
124+ const stderrNormalized = r.stderr.replace(/[\r\n]+$/, "");
125+ const stdoutLines = stdoutNormalized
126+ ? stdoutNormalized.split(/\r?\n/).length
127+ : 0;
128+ const stderrLines = stderrNormalized
129+ ? stderrNormalized.split(/\r?\n/).length
130+ : 0;
131+ const stdoutSingleLine =
132+ stdoutLines === 1 ? (stdoutNormalized.split(/\r?\n/)[0] ?? "") : null;
133+
134+ const parts = [
135+ `exit ${r.exitCode}`,
136+ `stdout ${stdoutLines}L`,
137+ `stderr ${stderrLines}L`,
138+ ];
139+
140+ if (
141+ r.success &&
142+ !r.timedOut &&
143+ stderrLines === 0 &&
144+ stdoutSingleLine !== null &&
145+ stdoutSingleLine.length > 0
146+ ) {
147+ parts.push(`out: ${truncateOneLine(stdoutSingleLine)}`);
148+ }
149+
150+ writeln(` ${badge} ${c.dim(parts.join(" · "))}`);
151+
152+ if (r.success && !r.timedOut) {
153+ return true;
154+ }
155+
156+ writePreviewLines({
157+ label: "stderr",
158+ value: r.stderr,
159+ lineColor: c.red,
160+ maxLines: 6,
161+ });
162+ writePreviewLines({
163+ label: "stdout",
164+ value: r.stdout,
165+ lineColor: c.dim,
166+ maxLines: 4,
167+ });
168+
169+ return true;
170+}
171+
172+function renderSubagentResult(result: unknown): boolean {
173+ const r = result as {
174+ inputTokens?: number;
175+ outputTokens?: number;
176+ agentName?: string;
177+ };
178+ if (!r || typeof r !== "object") return false;
179+ const label = r.agentName ? ` ${c.dim(c.cyan(`[@${r.agentName}]`))}` : "";
180+ writeln(
181+ ` ${G.agent}${label} ${c.dim(`subagent done (${r.inputTokens ?? 0}in / ${r.outputTokens ?? 0}out tokens)`)}`,
182+ );
183+ return true;
184+}
185+
186+function renderReadSkillResult(result: unknown): boolean {
187+ const r = result as {
188+ skill?: {
189+ name?: string;
190+ description?: string;
191+ source?: "local" | "global";
192+ };
193+ };
194+ if (!r || typeof r !== "object") return false;
195+ if (!r.skill) {
196+ writeln(` ${G.info} ${c.dim("skill")} ${c.dim("(not found)")}`);
197+ return true;
198+ }
199+ const name = r.skill.name ?? "(unknown)";
200+ const source = r.skill.source ?? "unknown";
201+ const description = r.skill.description?.trim();
202+ const descPart = description
203+ ? ` ${c.dim("·")} ${c.dim(description.length > 60 ? `${description.slice(0, 57)}…` : description)}`
204+ : "";
205+ writeln(
206+ ` ${G.info} ${c.dim("skill")} ${name} ${c.dim("·")} ${c.dim(source)}${descPart}`,
207+ );
208+ return true;
209+}
210+
211+function renderWebSearchResult(result: unknown): boolean {
212+ const r = result as {
213+ results?: Array<{ title?: string; url?: string; score?: number }>;
214+ };
215+ if (!Array.isArray(r?.results)) return false;
216+ if (r.results.length === 0) {
217+ writeln(` ${G.info} ${c.dim("no results")}`);
218+ return true;
219+ }
220+
221+ for (const item of r.results.slice(0, 5)) {
222+ const title = (item.title?.trim() || item.url || "(untitled)").replace(
223+ /\s+/g,
224+ " ",
225+ );
226+ const score =
227+ typeof item.score === "number"
228+ ? c.dim(` (${item.score.toFixed(2)})`)
229+ : "";
230+ writeln(` ${c.dim("•")} ${title}${score}`);
231+ if (item.url) writeln(` ${c.dim(item.url)}`);
232+ }
233+
234+ if (r.results.length > 5) {
235+ writeln(` ${c.dim(` +${r.results.length - 5} more`)}`);
236+ }
237+ return true;
238+}
239+
240+function renderWebContentResult(result: unknown): boolean {
241+ const r = result as {
242+ results?: Array<{ url?: string; title?: string; text?: string }>;
243+ };
244+ if (!Array.isArray(r?.results)) return false;
245+ if (r.results.length === 0) {
246+ writeln(` ${G.info} ${c.dim("no pages")}`);
247+ return true;
248+ }
249+
250+ for (const item of r.results.slice(0, 3)) {
251+ const title = (item.title?.trim() || item.url || "(untitled)").replace(
252+ /\s+/g,
253+ " ",
254+ );
255+ writeln(` ${c.dim("•")} ${title}`);
256+ if (item.url) writeln(` ${c.dim(item.url)}`);
257+ const preview = (item.text ?? "").replace(/\s+/g, " ").trim();
258+ if (preview) {
259+ const trimmed =
260+ preview.length > 220 ? `${preview.slice(0, 217)}…` : preview;
261+ writeln(` ${c.dim(trimmed)}`);
262+ }
263+ }
264+
265+ if (r.results.length > 3) {
266+ writeln(` ${c.dim(` +${r.results.length - 3} more`)}`);
267+ }
268+ return true;
269+}
270+
271+function renderMcpResult(result: unknown): boolean {
272+ const content = Array.isArray(result) ? result : [result];
273+ for (const block of (
274+ content as Array<{ type?: string; text?: string }>
275+ ).slice(0, 5)) {
276+ if (block?.type === "text" && block.text) {
277+ const lines = block.text.split("\n").slice(0, 6);
278+ for (const line of lines) writeln(` ${c.dim("│")} ${line}`);
279+ }
280+ }
281+ return true;
282+}
283+
284+// ─── Registry ─────────────────────────────────────────────────────────────────
285+
286+const TOOL_RESULT_RENDERERS: Readonly<Record<string, ToolResultRenderer>> = {
287+ read: renderReadResult,
288+ create: renderCreateResult,
289+ replace: (result) => renderReplaceOrInsertResult("replace", result),
290+ insert: (result) => renderReplaceOrInsertResult("insert", result),
291+ shell: renderShellResult,
292+ subagent: renderSubagentResult,
293+ readSkill: renderReadSkillResult,
294+ webSearch: renderWebSearchResult,
295+ webContent: renderWebContentResult,
296+};
297+
298+export function renderToolResultByName(
299+ toolName: string,
300+ result: unknown,
301+): boolean {
302+ if (toolName.startsWith("mcp_")) {
303+ return renderMcpResult(result);
304+ }
305+
306+ const renderer = TOOL_RESULT_RENDERERS[toolName];
307+ if (!renderer) return false;
308+ return renderer(result, toolName);
309+}