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 selectTarget(targetId) {
for (let attempt = 0; attempt < 30; attempt++) {
for (const candidate of session.context.pages()) {
if (candidate.isClosed()) continue;
const probe = await session.context.newCDPSession(candidate);
try {
if ((await probe.send('Target.getTargetInfo')).targetInfo.targetId === targetId) { session.page = candidate; return; }
} finally { await probe.detach(); }
}
await new Promise(resolve => setTimeout(resolve, 50));
}
throw new Error('找不到当前会话的目标标签页,请重新观察标签列表');
}
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);
session = await helper.openSession({ endpoint: request.endpoint, workDir: request.workDir, timeoutMs: 15000, navigationTimeoutMs: 30000 });
await selectTarget(request.targetId);
const page = session.page;
return { text: '已自动导入 browser-debugger,已连接本应用 WebView2;网络捕获已启动。', outputDir: session.outputDir, url: page.url() };
}
if (!session) throw new Error('No skill session');
if (request.op === 'select_target') { await selectTarget(request.targetId); return { text: '已切换到当前会话的目标标签页' }; }
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 {} }
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 selectTarget(targetId) {
for (let attempt = 0; attempt < 30; attempt++) {
for (const candidate of session.context.pages()) {
if (candidate.isClosed()) continue;
const probe = await session.context.newCDPSession(candidate);
try {
if ((await probe.send('Target.getTargetInfo')).targetInfo.targetId === targetId) { session.page = candidate; return; }
} finally { await probe.detach(); }
}
await new Promise(resolve => setTimeout(resolve, 50));
}
throw new Error('找不到当前会话的目标标签页,请重新观察标签列表');
}
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);
session = await helper.openSession({ endpoint: request.endpoint, workDir: request.workDir, timeoutMs: 15000, navigationTimeoutMs: 30000 });
await selectTarget(request.targetId);
const page = session.page;
return { text: '已自动导入 browser-debugger,已连接本应用 WebView2;网络捕获已启动。', outputDir: session.outputDir, url: page.url() };
}
if (!session) throw new Error('No skill session');
if (request.op === 'select_target') { await selectTarget(request.targetId); return { text: '已切换到当前会话的目标标签页' }; }
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 {} }