XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
import readline from 'node:readline';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { mkdir } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';

// stdout is reserved for framed responses. User scripts and the skill may log to stderr.
const respond = process.stdout.write.bind(process.stdout);
console.log = console.info = console.warn = (...args) => process.stderr.write(args.map(String).join(' ') + '\n');
let session;
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const stringify = value => {
  const seen = new WeakSet();
  return JSON.stringify(value ?? null, (_, v) => {
    if (typeof v === 'bigint') return v.toString();
    if (v && typeof v === 'object') { if (seen.has(v)) return '[circular]'; seen.add(v); }
    return v;
  }, 2);
};

async function run(request) {
  const args = request.arguments ?? {};
  if (request.op === 'start') {
    if (session) throw new Error('Session already started');
    const endpoint = new URL(request.endpoint);
    if (endpoint.protocol !== 'http:' || !['127.0.0.1', 'localhost', '[::1]'].includes(endpoint.hostname)) throw new Error('Only the application loopback endpoint is allowed');
    // Verify ownership BEFORE attaching the recorder; a port-allocation race must not capture another browser.
    const targets = await (await fetch(new URL('/json/list', endpoint), { signal: AbortSignal.timeout(10000) })).json();
    if (!Array.isArray(targets) || !targets.some(target => target.id === request.targetId)) throw new Error('CDP 端点不属于当前 WebView2;请关闭并重新启用 Agent 浏览器插件重试');
    const helper = await import(pathToFileURL(path.join(request.skill, 'scripts/browser-session.mjs')).href);
    const doctor = await helper.doctor();
    if (!doctor.ready) throw new Error('browser-debugger 依赖未就绪:需要 Node.js 22+;请在技能目录执行 npm.cmd ci --ignore-scripts --no-audit --no-fund');
    session = await helper.openSession({ endpoint: request.endpoint, workDir: request.workDir, timeoutMs: 15000, navigationTimeoutMs: 30000 });
    let page;
    for (const candidate of session.context.pages()) {
      const cdp = await session.context.newCDPSession(candidate);
      try { if ((await cdp.send('Target.getTargetInfo')).targetInfo.targetId === request.targetId) page = candidate; }
      finally { await cdp.detach(); }
    }
    if (!page) { await session.close(); session = null; throw new Error('找不到本应用 Agent 浏览器的目标标签页'); }
    session.page = page;
    return { text: '已自动导入 browser-debugger,已连接本应用 WebView2;网络捕获已启动。', outputDir: session.outputDir, url: page.url() };
  }
  if (!session) throw new Error('No skill session');
  const page = session.page;
  if (request.op === 'browser_observe') {
    const frames = [];
    for (const frame of page.frames()) {
      try { frames.push({ name: frame.name(), url: frame.url(), text: (await frame.locator('body').innerText({ timeout: 3000 })).slice(0, 16000) }); }
      catch (error) { frames.push({ url: frame.url(), error: String(error.message) }); }
    }
    let aria = '';
    try { aria = (await page.locator('body').ariaSnapshot({ timeout: 5000 })).slice(0, 24000); } catch (error) { aria = String(error.message); }
    return { text: stringify({ url: page.url(), title: await page.title(), aria, frames }) };
  }
  if (request.op === 'browser_screenshot') {
    const directory = path.join(session.outputDir, 'screenshots'); await mkdir(directory, { recursive: true });
    const imagePath = path.join(directory, randomUUID() + '.png');
    await page.screenshot({ path: imagePath, fullPage: Boolean(args.fullPage), timeout: 15000 });
    return { text: '已截取当前 Agent 浏览器页面。', imagePath };
  }
  if (request.op === 'browser_execute') {
    if (typeof args.code !== 'string' || args.code.length > 60000) throw new Error('code must be a string up to 60000 characters');
    // Trusted local plugin code, per SDK execution model. The prompt limits operations to the user's browser task.
    const task = new AsyncFunction('session', 'page', 'context', 'outputDir', args.code);
    const result = await task(session, page, session.context, session.outputDir);
    await session.flush();
    const text = stringify(result);
    return { text: text.length > 120000 ? text.slice(0, 120000) + '\n[结果已截断,完整证据请写入 outputDir]' : text };
  }
  if (request.op === 'close') {
    const result = await session.close(); session = null;
    return { text: '技能连接和捕获已关闭;WebView2 由应用保留。', summary: result };
  }
  throw new Error('Unknown operation: ' + request.op);
}

for await (const line of readline.createInterface({ input: process.stdin, crlfDelay: Infinity })) {
  let request;
  try {
    request = JSON.parse(line);
    const result = await run(request);
    respond(JSON.stringify({ id: request.id, ok: true, result }) + '\n');
    if (request.op === 'close') break;
  } catch (error) { respond(JSON.stringify({ id: request?.id, ok: false, error: String(error?.message ?? error) }) + '\n'); }
}
if (session) { try { await session.close(); } catch {} }