VoltAgent 工作区技能实战:使用 playwright-cli run-code 运行自定义 Playwright 代码

原创2026-09-23 14:34:482,246 阅读
文章标签:人工智能AI AgentAgent 框架多智能体工具调用MCP 服务Agent 记忆RAGAgent 工作流Agent 编排可观测性AI 评测语音后端

VoltAgent 工作区技能实战:使用 playwright-cli run-code 运行自定义 Playwright 代码

playwright-cli run-code 是 VoltAgent 工作区(Workspace)技能体系中用于执行任意 Playwright 代码的高级命令,专门覆盖 CLI 内置命令无法表达的复杂浏览器自动化场景。本文以 VoltAgent 仓库 examples/with-workspace 中 playwright-cli 技能附带的 running-code.md 参考文档为骨架,完整讲解 run-code 的语法、上下文(定位、权限、媒体仿真、等待策略、跨域 iframe、下载、剪贴板、页面信息、JavaScript 求值与错误处理)以及复杂工作流组合,并结合 packages/core/src/workspace/skills/index.ts 源码说明该技能如何被 Agent 发现、加载与调用。读完本文,你将能够为 VoltAgent Agent 编写可复制的自定义浏览器操作脚本,并理解 run-code 与工作区技能系统的衔接原理。

一、run-code 在技能体系中的定位

1.1 技能与命令的层级关系

在 VoltAgent 中,浏览器自动化能力被打包成一个名为 playwright-cli 的“技能(Skill)”。技能定义位于 SKILL.md,其 frontmatter 声明了技能的用途边界与可用工具:

---
name: playwright-cli
description: Automates browser interactions for web testing, form filling, screenshots, and data extraction. Use when the user needs to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.
allowed-tools: Bash(playwright-cli:*)
---

allowed-tools: Bash(playwright-cli:*) 意味着该技能只能通过 Bash 调用 playwright-cli 开头的命令,其余命令不在授权范围内。run-code 就是该技能 DevTools 命令组中的一员,与 console、network、tracing-start/stop、video-start/stop 并列。

1.2 技能如何被 VoltAgent 工作区发现与加载

从源码结构看,VoltAgent 的 WorkspaceSkills 实现(packages/core/src/workspace/skills/index.ts)通过默认根路径 <a href="https://link.gitcode.com/i/cfc427f440df3fc970ad6e8e720ae3fb" target="_blank">"/skills"]、默认 glob **/SKILL.md 递归发现技能文件,并使用 gray-matter 解析 frontmatter 与指令正文(parseSkillFile,见 [index.ts)。

关键设计点是参考文件白名单的推断:当 SKILL.md 正文中出现类似 <a href="https://link.gitcode.com/i/087352c7890abf50b880e8ca43ee2be4" target="_blank">Running Playwright code</a> 这样的相对链接时,inferSkillFileAllowlistsFromInstructions 会把它自动加入 references 白名单(见 index.ts)。这一点在测试 packages/core/src/workspace/skills/index.spec.ts 中有直接验证:当 frontmatter 未显式声明 references 时,相对链接会被自动推断为允许读取的参考文件,而越界路径(如 ../secret.txt)会被 workspace_read_skill_reference 拒绝并返回 File not allowed。

在 examples/with-workspace/src/index.ts 中可以看到实际接线方式:Workspace 配置了 skills.rootPaths: ["/skills"],Agent 通过 workspaceSkillsPrompt 开启技能提示注入,Agent 便能在会话中按需读取 running-code.md 等参考文档,学习 run-code 的用法。

二、run-code 基础语法

run-code 接受一个 异步箭头函数,该函数接收 Playwright 的 page 对象作为唯一参数。函数体内部可以访问 page.context() 进行浏览器上下文(Browser Context)层面的操作(权限、地理位置、storage state 等),也可以直接使用 page 上的全部 API。

playwright-cli run-code "async page => {
  // Your Playwright code here
  // Access page.context() for browser context operations
}"

使用要点:

  • 命令参数是一个字符串形式的函数体,因此外层必须用双引号包裹,函数体内部避免与双引号冲突,必要时使用反引号模板字符串(见后文多页面抓取示例)。
  • 函数体内可使用 await 执行异步操作;返回的 Promise 结果会被 run-code 捕获并作为命令输出返回给调用方(Agent)。
  • 该命令面向“CLI 命令覆盖不到的高级场景”,例如同时涉及权限授予、上下文覆盖、事件监听与文件落盘等多步组合操作。

三、Geolocation:地理位置权限与模拟

浏览器默认不向页面暴露精确地理位置。run-code 可以在浏览器上下文中授予 geolocation 权限,再通过 setGeolocation 覆盖当前坐标:

# Grant geolocation permission and set location
playwright-cli run-code "async page => {
  await page.context().grantPermissions(['geolocation']);
  await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
}"

# Set location to London
playwright-cli run-code "async page => {
  await page.context().grantPermissions(['geolocation']);
  await page.context().setGeolocation({ latitude: 51.5074, longitude: -0.1278 });
}"

# Clear geolocation override
playwright-cli run-code "async page => {
  await page.context().clearPermissions();
}"

说明:

  • grantPermissions 授予能力,setGeolocation 写入经纬度,两者需成对出现;clearPermissions 会撤销所有已授予的权限并移除地理位置覆盖。
  • 典型应用场景包括:测试基于地理围栏的推荐逻辑、验证不同地区定价、模拟“定位服务被拒绝”的分支。

四、Permissions:批量授权与按源授权

浏览器权限可按 permissions 数组一次性批量授予,也可以限定在指定 origin 下生效:

# Grant multiple permissions
playwright-cli run-code "async page => {
  await page.context().grantPermissions([
    'geolocation',
    'notifications',
    'camera',
    'microphone'
  ]);
}"

# Grant permissions for specific origin
playwright-cli run-code "async page => {
  await page.context().grantPermissions(['clipboard-read'], {
    origin: 'https://example.com'
  });
}"

实践要点:

  • 多权限批量授予适合一次初始化“全功能”测试环境(摄像头、麦克风、通知、定位同时开启)。
  • origin 限定让权限只作用于指定站点,避免影响其他标签页或后续导航,是更精细的控制手段。
  • clipboard-read 通常需要与用户手势配合,配合下文“剪贴板”一节的 page.evaluate 使用。

五、Media Emulation:媒体特性仿真

无需真实设备即可模拟用户的偏好设置与媒体类型,用于验证响应式布局、无障碍体验与打印样式:

# Emulate dark color scheme
playwright-cli run-code "async page => {
  await page.emulateMedia({ colorScheme: 'dark' });
}"

# Emulate light color scheme
playwright-cli run-code "async page => {
  await page.emulateMedia({ colorScheme: 'light' });
}"

# Emulate reduced motion
playwright-cli run-code "async page => {
  await page.emulateMedia({ reducedMotion: 'reduce' });
}"

# Emulate print media
playwright-cli run-code "async page => {
  await page.emulateMedia({ media: 'print' });
}"

应用场景:

  • 验证暗色模式下对比度与图片适配;
  • 模拟 prefers-reduced-motion,检查动画降级逻辑;
  • 通过 media: 'print' 预览打印版式,可与 playwright-cli pdf 配合生成 PDF(参考 SKILL.md 中的 pdf --filename=page.pdf)。

六、Wait Strategies:等待策略

SPA 应用中元素出现时机不确定,run-code 提供四种等待手段:

# Wait for network idle
playwright-cli run-code "async page => {
  await page.waitForLoadState('networkidle');
}"

# Wait for specific element
playwright-cli run-code "async page => {
  await page.waitForSelector('.loading', { state: 'hidden' });
}"

# Wait for function to return true
playwright-cli run-code "async page => {
  await page.waitForFunction(() => window.appReady === true);
}"

# Wait with timeout
playwright-cli run-code "async page => {
  await page.waitForSelector('.result', { timeout: 10000 });
}"
  • waitForLoadState('networkidle'):等待网络空闲,适合页面加载完全后再断言。
  • waitForSelector('.loading', { state: 'hidden' }):等待选择器满足指定状态(如加载动画消失),比固定 sleep 更可靠。
  • waitForFunction:等待页面内表达式返回 truthy,常用于“应用已初始化完成”这类无 DOM 钩子的信号。
  • timeout 参数(单位毫秒):控制最长等待时间,超时抛出异常,可配合下文“错误处理”捕获。

七、Frames and Iframes:跨框架操作

页面内嵌 iframe 属于独立的执行环境,run-code 通过 contentFrame() 拿到 Frame 对象后再操作:

# Work with iframe
playwright-cli run-code "async page => {
  const frame = page.locator('iframe#my-iframe').contentFrame();
  await frame.locator('button').click();
}"

# Get all frames
playwright-cli run-code "async page => {
  const frames = page.frames();
  return frames.map(f => f.url());
}"
  • 主页面选择器定位不到 iframe 内部元素,必须先取得 Frame 引用,再在 Frame 内重新定位。
  • page.frames() 返回所有 Frame(含主 Frame 与各 iframe),配合 f.url() 可以审计页面实际加载了哪些第三方嵌入内容。

八、File Downloads:文件下载处理

run-code 通过“事件等待 + 触发点击”的并行模式捕获下载事件,并可把文件落盘到本地:

# Handle file download
playwright-cli run-code "async page => {
  const [download] = await Promise.all([
    page.waitForEvent('download'),
    page.click('a.download-link')
  ]);
  await download.saveAs('./downloaded-file.pdf');
  return download.suggestedFilename();
}"

要点:

  • Promise.all 保证监听事件与触发下载同时就绪,避免竞态导致下载事件丢失。
  • download.saveAs(path) 将下载内容写入指定路径(相对当前工作目录),download.suggestedFilename() 返回服务端建议的文件名,可作为返回信息供 Agent 使用。
  • 这在 VoltAgent 工作区示例中特别有意义:工作区根目录 ./workspace 即 Agent 的持久化文件系统,下载的文件可直接被后续技能引用。

九、Clipboard:剪贴板读写

读取剪贴板需要 clipboard-read 权限,写入一般无需额外授权:

# Read clipboard (requires permission)
playwright-cli run-code "async page => {
  await page.context().grantPermissions(['clipboard-read']);
  return await page.evaluate(() => navigator.clipboard.readText());
}"

# Write to clipboard
playwright-cli run-code "async page => {
  await page.evaluate(text => navigator.clipboard.writeText(text), 'Hello clipboard!');
}"
  • 读取前先 grantPermissions(['clipboard-read']),这是该场景下授权与求值顺序的经典组合。
  • page.evaluate 的第二个参数用于向页面函数传参(此处的 'Hello clipboard!'),是“Node 侧数据 → 页面侧逻辑”的标准通道。

十、Page Information:页面信息获取

快速获取标题、URL、页面内容与视口尺寸,用于状态确认或断言:

# Get page title
playwright-cli run-code "async page => {
  return await page.title();
}"

# Get current URL
playwright-cli run-code "async page => {
  return page.url();
}"

# Get page content
playwright-cli run-code "async page => {
  return await page.content();
}"

# Get viewport size
playwright-cli run-code "async page => {
  return page.viewportSize();
}"
  • title()、content() 返回 Promise,需要 await;url()、viewportSize() 为同步方法。
  • 这些返回值会作为 run-code 的输出返回给 Agent,可用于在复杂工作流中确认导航结果。

十一、JavaScript Execution:页面内 JS 求值

page.evaluate 在页面上下文中执行任意 JavaScript,并支持传参:

# Execute JavaScript and return result
playwright-cli run-code "async page => {
  return await page.evaluate(() => {
    return {
      userAgent: navigator.userAgent,
      language: navigator.language,
      cookiesEnabled: navigator.cookieEnabled
    };
  });
}"

# Pass arguments to evaluate
playwright-cli run-code "async page => {
  const multiplier = 5;
  return await page.evaluate(m => document.querySelectorAll('li').length * m, multiplier);
}"
  • 第一个示例返回结构化对象,一次性采集 UA、语言与 Cookie 开关状态,适合环境指纹校验。
  • 第二个示例演示参数传递:page.evaluate(fn, arg) 会把 arg 作为 fn 的第一个参数注入,避免在字符串中拼接变量带来的转义与注入风险。
  • 所有返回值都会被序列化回 Node 侧,因此复杂的 DOM 节点需先转换成可序列化的数据。

十二、Error Handling:try-catch 容错

run-code 支持在函数体内自行捕获异常,从而把“元素缺失”等失败转化为可读的返回信息:

# Try-catch in run-code
playwright-cli run-code "async page => {
  try {
    await page.click('.maybe-missing', { timeout: 1000 });
    return 'clicked';
  } catch (e) {
    return 'element not found';
  }
}"
  • 通过 { timeout: 1000 } 缩短等待,快速触发超时分支,避免长时间卡死。
  • 将异常降级为返回值后,Agent 可以依据返回值做出分支决策(如改走备用路径),而不是直接收到命令失败。这是将 run-code 用于 Agent 决策循环时的推荐写法。

十三、Complex Workflows:组合成完整工作流

run-code 的真正价值在于把多步操作压缩成一次命令调用,返回给 Agent 的是可理解的结果而非中间过程。

13.1 登录并保存会话状态

# Login and save state
playwright-cli run-code "async page => {
  await page.goto('https://example.com/login');
  await page.fill('input[name=email]', 'user@example.com');
  await page.fill('input[name=password]', 'secret');
  await page.click('button[type=submit]');
  await page.waitForURL('**/dashboard');
  await page.context().storageState({ path: 'auth.json' });
  return 'Login successful';
}"
  • waitForURL('**/dashboard') 是 Playwright 的 glob 通配 URL 匹配,比硬编码完整地址更健壮。
  • storageState({ path: 'auth.json' }) 把 cookies 与 localStorage 持久化到文件,后续会话可用 playwright-cli state-load auth.json 直接复用登录态(对应 SKILL.md 中的 Storage 命令组)。

13.2 多页面数据抓取

# Scrape data from multiple pages
playwright-cli run-code "async page => {
  const results = [];
  for (let i = 1; i <= 3; i++) {
    await page.goto(\`https://example.com/page/\${i}\`);
    const items = await page.locator('.item').allTextContents();
    results.push(...items);
  }
  return results;
}"
  • 这里函数体位于 Bash 双引号内,模板字符串必须使用 \`` 与 ${}` 转义,否则会被外层 shell 提前解析。
  • allTextContents() 一次性取出所有 .item 的文本;循环 3 个页面后把结果合并返回,Agent 可直接获得结构化数据数组。

十四、与工作区技能体系的协同使用

run-code 虽然强大,但应在 VoltAgent 工作区技能框架内正确使用:

  1. 技能发现:技能通过 **/SKILL.md 被自动发现(WorkspaceSkills 的 discoverSkills,见 index.ts),并解析 frontmatter 中的 name、description、references 等元数据。
  2. 参考文档白名单:running-code.md 这类参考文件只有通过 workspace_read_skill_reference 才能读取,路径必须位于 SKILL.md 声明或正文链接推断出的白名单内(见 index.spec.ts 的“允许白名单、拒绝越界”测试)。
  3. 提示注入:Agent 配置了 workspaceSkillsPrompt 后(见 examples/with-workspace/src/index.ts),已激活技能的元数据会注入系统提示,指导 Agent 优先使用 workspace_* 技能工具(对应 SKILLS_SYSTEM_PROMPT,见 index.ts),而不是用沙箱命令直接翻看技能目录。
  4. 沙箱隔离:run-code 最终经由 LocalSandbox 的 execute_command 在工作区根目录内执行(见 examples/with-workspace/src/index.ts),因此下载、saveAs、storageState 落盘都发生在工作区文件系统内,天然受到沙箱约束。

完整的技能命令参考(导航、键盘、鼠标、标签页、存储、网络拦截、DevTools、会话管理等)见 SKILL.md;与 run-code 相邻的进阶参考还包括 request-mocking.md、session-management.md、storage-state.md、test-generation.md、tracing.md 与 video-recording.md。

十五、最佳实践小结

综合 running-code.md 全篇与源码实现,使用 run-code 时应遵循:

  • 能用内置命令就不用 run-code:导航、点击、填充、截图等均有专门命令,run-code 只处理“CLI 命令无法表达的组合逻辑”;
  • 返回结构化结果:尽量 return 可序列化的字符串、数组或对象,便于 Agent 读取和决策;
  • 显式等待:优先 waitForLoadState、waitForSelector、waitForFunction 而非固定延时;
  • 权限与上下文成对操作:grantPermissions 后记得配合 setGeolocation / clearPermissions 等,避免上下文状态污染后续步骤;
  • 内部容错:用 try-catch 把可预期失败转化为返回值,提升工作流鲁棒性;
  • 注意 shell 转义:函数体内出现模板字符串时使用 \`` 与 ${}` 转义,保证在 Bash 双引号中正确传递。
登录后查看全文
voltagent