/** * ============================================================ * src/tools/genimage/genimage.ts —— GenerateImage 工具 * ------------------------------------------------------------ * 专用「图像生成」工具:按 img_plan.json 批量生成 PPT 配图(文生图 / 图生图)。 * * 为什么要专用工具、而不是用 Bash 跑脚本(用户拍板·Claude Code 同款): * ───────────────────────────────────────────────────────── * 图像生成是**专用的长时操作**(单张 Seedream ~50s,一批 5 张 ~250s)。 * 通用 Bash 工具默认超时 120s、硬上限 600s(src/tools/bash/bash.ts), * 用它跑生图必然把整批**在中途 SIGKILL**(实测两次都杀在第 3 张)。 * Bash 该是「最后兜底」,专用长操作应封装专用工具——本工具**无 120s 帽**, * 仅凭 `ctx.signal`(Ctrl+C/ESC)中断,配合脚本自身的「总时长自限 + 降级」, * 让生图永不被误杀、AI 配图失败也优雅退化、绝不阻断工作流。 * * 薄封装:HTTP 双协议 / 重试 / 降级写占位逻辑仍住 `skills/ai-image` * (generate_from_plan.mjs + generate.mjs),本工具只负责「无帽地把它跑完、 * 收口成 ToolResult」,不重写生图逻辑(守减法 + 三层解耦)。 * ============================================================ */ import { spawn } from 'node:child_process'; import { existsSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { z } from 'zod'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { trustedToolEnv } from '../../config/configService.js'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import { findPackageRoot } from '../../utils/packageRoot.js'; import { execSiblingDir } from '../../utils/greenRoot.js'; import { killTree } from '../shared/killTree.js'; import { toToolParameters } from '../../utils/zodToJson.js'; // ---------------- 1. Zod 输入 schema ---------------- const inputSchema = z.object({ plan: z .string() .optional() .describe('img_plan.json 路径(每条 {file,mode,prompt,...});默认 ./build/img_plan.json'), assets: z .string() .optional() .describe('图片输出目录(客户原图也在这);默认 /assets 或 ./build/assets'), size: z.string().optional().describe('生成尺寸档(透传 generate.mjs,默认 1K)'), timeout_ms: z .number() .int() .positive() .optional() .describe('单张生成超时(毫秒,透传 generate_from_plan 的 --timeout-ms,默认 600000=10min)'), wall_budget_ms: z .number() .int() .positive() .optional() // 成本不计、最大努力生图:预算放宽到 60min,防尾部图撞预算被误降级。 .describe('整批总时长预算(毫秒);超了把剩余图全部走降级占位、主动收尾。默认 3600000=60min'), retry_degraded_report: z .string() .optional() .describe('只重试某次 image_generation_report.json 里的 degraded 条目'), concurrency: z .number() .int() .positive() .optional() .describe('批内并发生成张数(透传 generate_from_plan 的 --concurrency,默认 1=顺序)'), max_rounds: z .number() .int() .positive() .optional() .describe('重试轮数;配合 retry_degraded_report 使用时默认 3'), }); type GenImageInput = z.infer; const parameters = toToolParameters(inputSchema); const description = `按 img_plan.json 批量生成 PPT 配图(文生图 / 图生图),专为长时图像生成设计。 - 无 120s 超时帽(区别于 Bash),仅响应 Ctrl+C/ESC 中断;适合一批多张图(每张可达分钟级)。 - 内建优雅退化:单张失败(敏感内容/超时/网络/空输出)会写降级占位资产(图生图退回原图、文生图写渐变背景),**绝不让 deck 坏图、绝不阻断工作流**。 - 输入 plan(默认 ./build/img_plan.json)+ assets(默认同级 assets)。空 plan / 无 plan 直接跳过。`; /** The helper receives provider credentials. Unlike discoverable skills it * must be shipped with the package or alongside the green executable. */ function locateScript(): string | null { const roots = [execSiblingDir()]; try { roots.unshift(findPackageRoot(import.meta.url)); } catch { /* green build */ } for (const base of roots) { const p = join(base, 'skills', 'ai-image', 'scripts', 'generate_from_plan.mjs'); if (existsSync(p)) return p; } return null; } const MAX_LINE_CHARS = 2048; // Discard the whole remainder of an oversized line. A suffix on that line // must not turn into a fabricated receipt, even when it arrives in a new chunk. function boundedLines(onLine: (line: string) => void) { let partial = '', oversized = false; return (chunk: string) => { for (let at = 0; at < chunk.length;) { const newline = chunk.indexOf('\n', at); const end = newline < 0 ? chunk.length : newline; if (!oversized) { if (partial.length + end - at > MAX_LINE_CHARS) { partial = ''; oversized = true; } else partial += chunk.slice(at, end); } if (newline < 0) break; if (!oversized) onLine(partial.trim()); partial = ''; oversized = false; at = end + 1; } }; } export function createProgressLineFeed(onLine: (line: string) => void): (chunk: string) => void { return boundedLines(line => { if (line.startsWith('[ai-image-plan]')) onLine(line); }); } /** generate_from_plan writes terminal success on stdout, diagnostic outcomes on * stderr. DEGRADED is emitted before the report is persisted and isn't itself * completion. Keep only the known receipts and six recent progress lines. */ export function imagePlanOutput(report?: (line: string) => void) { const receipts = new Map(); const progress: string[] = []; let terminal: string | undefined; let conflictingTerminal = false; const stdout = boundedLines(line => { const kind = /^(IMAGE_PLAN_OK|PLAN_EMPTY|PLAN_RETRY_EMPTY):/.exec(line)?.[1]; if (!kind) return; if (terminal && terminal !== kind) conflictingTerminal = true; terminal = kind; receipts.set(kind, line); }); const stderr = boundedLines(line => { const kind = /^(IMAGE_PLAN_DEGRADED|IMAGE_PLAN_FAILED|IMAGE_PLAN_ERROR):/.exec(line)?.[1]; if (kind) receipts.set(kind, line); else if (line.startsWith('[ai-image-plan]')) { if (progress.at(-1) !== line) progress.push(line); if (progress.length > 6) progress.shift(); report?.(line); } }); function finish(code: number | null, sig: NodeJS.Signals | null, aborted = false): ToolResult { // Flush possible final lines without a newline (the close event comes after stream EOF). stdout('\n'); stderr('\n'); const summary = [...receipts.values(), ...(progress.length ? ['进度摘要:', ...progress] : [])].join('\n'); const status = `exit ${code ?? 'null'}${sig ? ' ' + sig : ''}`; if (aborted || sig) return { ok: false, error: `GenerateImage 被中断(${status})。\n${summary}` }; if (code !== 0 || receipts.has('IMAGE_PLAN_FAILED') || receipts.has('IMAGE_PLAN_ERROR')) return { ok: false, error: `GenerateImage 失败(${status})。\n${summary}` }; if (!terminal || conflictingTerminal || (terminal !== 'IMAGE_PLAN_OK' && receipts.has('IMAGE_PLAN_DEGRADED'))) return { ok: false, error: `GenerateImage 缺少一致的完成回执(${status});不能确认生图完成。\n${summary}` }; return { ok: true, content: summary }; } return { stdout, stderr, finish }; } // killTree(中断杀整棵进程树)已升为共享 util —— 见 ../shared/killTree.js // (两次规则:genimage + bash 长命令都需要,2026-07-02 生图事故的同类问题在 Bash 复现)。 // ---------------- call() ---------------- async function call(input: GenImageInput, signal?: AbortSignal, ctx?: ToolCallContext): Promise { if (signal?.aborted) return { ok: false, error: 'GenerateImage 被中断。' }; const cwd = ctx?.cwd ?? getWorkingDir(); const planPath = resolve(cwd, input.plan ?? './build/img_plan.json'); const assetsDir = resolve(cwd, input.assets ?? join(dirname(planPath), 'assets')); if (!existsSync(planPath)) { return { ok: true, content: `PLAN_EMPTY: ${planPath} 不存在,跳过生图。` }; } const script = locateScript(); if (!script) { // 找不到脚本也不抛、不 halt——工作流靠 deck 已写的 enhanced/原图引用降级(onError:continue)。 return { ok: false, error: 'GenerateImage: 未找到 skills/ai-image/scripts/generate_from_plan.mjs(已跳过,不阻断)。', }; } const cmd = [ script, '--plan', planPath, '--assets', assetsDir, '--timeout-ms', String(input.timeout_ms ?? 600_000), '--wall-budget-ms', // 成本不计、最大努力生图:默认 60min(原 25min 偏紧,尾部图常撞预算被降级)。 String(input.wall_budget_ms ?? 3_600_000), '--size', input.size ?? '1K', ]; if (input.retry_degraded_report) { cmd.push('--retry-degraded-report', resolve(cwd, input.retry_degraded_report)); } if (input.max_rounds) { cmd.push('--max-rounds', String(input.max_rounds)); } if (input.concurrency) { cmd.push('--concurrency', String(input.concurrency)); } const trustedEnv = await trustedToolEnv('imageGeneration'); if (signal?.aborted) return { ok: false, error: 'GenerateImage 被中断。' }; return await new Promise((resolvePromise) => { let child: ReturnType; try { // 用 `node` 跑 .mjs(与既有 Bash 步一致;绿色版同样依赖 node 在 PATH)。 // POSIX 下 detached 自成进程组,中断时 kill(-pid) 才能掀到孙进程(见 killTree); // win32 走 taskkill /T,不需要(也不该)detached。 child = spawn('node', cmd, { cwd: dirname(script), stdio: ['ignore', 'pipe', 'pipe'], env: { ...trustedEnv, MINIMAL_AGENT_CAPTURED_STDIO: '1' }, detached: process.platform !== 'win32', }); } catch (e) { resolvePromise({ ok: false, error: `GenerateImage 启动失败:${(e as Error).message}(不阻断)` }); return; } // taskkill /F 杀掉的子进程在 win32 上 close 时 signal=null、exit code 非 0, // 单看 sig 判不出「被用户中断」——用本地 flag 记账,close 时据此正确报「被中断」。 let killedByAbort = false; const onAbort = () => { killedByAbort = true; killTree(child); }; if (signal) { if (signal.aborted) onAbort(); else signal.addEventListener('abort', onAbort, { once: true }); } const output = imagePlanOutput(line => ctx?.reportProgress?.(line)); child.stdout?.setEncoding('utf8').on('data', output.stdout); child.stderr?.setEncoding('utf8').on('data', output.stderr); child.on('error', (e) => { if (signal) signal.removeEventListener('abort', onAbort); resolvePromise({ ok: false, error: `GenerateImage 子进程错误:${e.message}(不阻断)` }); }); child.on('close', (code, sig) => { if (signal) signal.removeEventListener('abort', onAbort); resolvePromise(output.finish(code, sig, killedByAbort)); }); }); } export const genImageTool: Tool = { name: 'GenerateImage', description, inputSchema, parameters, isReadOnly: false, isConcurrencySafe: false, call: (input, signal) => call(input, signal), callWithContext: call, };