import { z } from 'zod'; import type { Tool, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; const schema = z.object({ lines: z.number().int().min(1).max(200).default(50).optional(), }); export class AnsiScreen { private rows: string[][] = [[]]; private row = 0; private column = 0; private escape = ''; private inStringControl = false; private stringEscape = false; constructor(private columns = process.stdout.columns || 120) {} resize(columns: number): void { this.columns = Math.max(20, columns || 120); } write(value: unknown): void { const text = Buffer.isBuffer(value) ? value.toString('utf8') : String(value); for (const char of text) { if (this.inStringControl) { if (char === '\x07' || (this.stringEscape && char === '\\')) this.inStringControl = false; this.stringEscape = char === '\x1b'; continue; } if (this.escape) { if (this.escape === '\x1b' && ']P^_X'.includes(char)) { this.inStringControl = true; this.stringEscape = false; this.escape = ''; continue; } this.escape += char; if (/^\x1b\[[0-?]*[ -/]*[@-~]$/.test(this.escape)) { this.applyCsi(this.escape); this.escape = ''; } else if ( this.escape.length > 64 || !/^\x1b(?:\[[0-?]*[ -/]*)?$/.test(this.escape) ) { this.escape = ''; } continue; } if (char === '\x1b') { this.escape = char; continue; } if (char === '\r') { this.column = 0; continue; } if (char === '\n') { this.newLine(); continue; } if (char === '\b') { this.column = Math.max(0, this.column - 1); continue; } if (char < ' ') continue; this.put(char); } } snapshot(lines: number): string { return this.rows.slice(-lines).map(row => row.join('')).join('\n') || ''; } private put(char: string): void { // Keep complete Unicode scalars; UTF-16 string offsets split emoji on the next write. const current = this.rows[this.row]!; while (current.length < this.column) current.push(' '); current[this.column] = char; this.column += 1; if (this.column >= this.columns) this.newLine(); } private newLine(): void { this.row += 1; this.column = 0; if (!this.rows[this.row]) this.rows[this.row] = []; if (this.rows.length > 200) { this.rows.splice(0, this.rows.length - 200); this.row = this.rows.length - 1; } } private applyCsi(sequence: string): void { const match = /^\x1b\[([0-9;?]*)([A-Za-z])$/.exec(sequence); if (!match) return; const rawValues = match[1]!.replace(/^\?/, '').split(';'); const values = rawValues.map((value) => value === '' ? undefined : Number(value), ); const amount = values[0] ?? (match[2] === 'J' || match[2] === 'K' ? 0 : 1); switch (match[2]) { case 'A': this.row = Math.max(0, this.row - amount); break; case 'B': this.row = Math.min(this.rows.length - 1, this.row + amount); break; case 'C': this.column = Math.min(this.columns - 1, this.column + amount); break; case 'D': this.column = Math.max(0, this.column - amount); break; case 'G': this.column = Math.min(this.columns - 1, Math.max(0, amount - 1)); break; case 'H': case 'f': this.row = Math.max( 0, Math.min(this.rows.length - 1, (values[0] ?? 1) - 1), ); this.column = Math.min(this.columns - 1, Math.max(0, (values[1] ?? 1) - 1)); break; case 'K': { const current = this.rows[this.row]!; if (amount === 1) current.fill(' ', 0, this.column + 1); else if (amount === 2) this.rows[this.row] = []; else this.rows[this.row] = current.slice(0, this.column); break; } case 'J': if (amount === 2 || amount === 3) { this.rows = [[]]; this.row = 0; this.column = 0; } break; default: break; } } } let uninstall: (() => void) | undefined; let screen: AnsiScreen | undefined; export function installTerminalCapture( enabled = process.env.MINIMAL_AGENT_TUI_CAPTURE === '1', ): () => void { if (!enabled || uninstall) return () => undefined; const capture = new AnsiScreen(); screen = capture; const original = process.stdout.write; const onResize = () => capture.resize(process.stdout.columns || 120); process.stdout.write = ((chunk: unknown, ...args: unknown[]) => { capture.write(chunk); return Reflect.apply(original, process.stdout, [chunk, ...args]); }) as typeof process.stdout.write; process.stdout.on('resize', onResize); const dispose = () => { if (uninstall !== dispose) return; process.stdout.write = original; process.stdout.off('resize', onResize); screen = undefined; uninstall = undefined; }; uninstall = dispose; return dispose; } export function hasTerminalCapture(): boolean { return Boolean(uninstall); } export const terminalCaptureTool: Tool> = { name: 'TerminalCapture', description: 'Returns a bounded text approximation of the current TUI terminal; complex grapheme widths and unsupported escape sequences may differ from the rendered screen. Available only when the TUI host installed its capture provider.', inputSchema: schema, parameters: toToolParameters(schema), isReadOnly: true, isConcurrencySafe: true, resolveAvailability: (runtime) => ({ available: runtime.surface === 'tui' && hasTerminalCapture(), signature: `terminal:${runtime.surface}:${hasTerminalCapture()}`, }), call: async (input): Promise => screen ? { ok: true, content: screen.snapshot(input.lines ?? 50) } : { ok: false, error: 'TUI 屏幕捕获未启用。需要诊断时用 MINIMAL_AGENT_TUI_CAPTURE=1 启动 TUI。' }, };