@ centroinc/ 浏览器
使用计算机使用 Playwright 的浏览器自动化代理. 这个TypeScript SDK将Anthropic的计算机使用能力与Playwright相结合,为使用克洛德的计算机使用能力实现浏览器交互自动化提供清洁,类型安全的接口.
这个叉子是 为高容量的RPA情景设计——思考大型保险后台,政府形式填报门户等数据繁多的工作流程.
它运行 在临时工作流程中无缝: 代理商为本地人 pause 编号 : resume 编号 : cancel 信号 可被浮出水面 临时信号,让你的管弦乐层协调长期的工作,而操作员则在需要时跳入(人与Temperal本身之间没有紧密的接合).
我们的目标是揭露一个 高可塑性、精致的制剂——分拨为生速或分拨为下拨为像素完美,人相精准.
此分叉中的其他特性
亮度特征矩阵
* 能力 它会做什么 怎么会这样 工具登记 任何工具通用能力系统 用Slack,Discord,数据库等扩展代理. 智能滚动 90%的取景口卷轴+即时文本导航 Turbo 页面翻转 财务报告和审定财务报表 零废物倒放控制 打字模式 填充、快速特征、人类特征 匹配 CAPTCHA 相容性或通过输入燃烧 信号总线 暂停/ 恢复/ 取消任何步骤 在生产中增加人质检检查站 URL 提取器 通过可见文本查找链接 需要零 CSS 选择器 速度调整 屏幕截图 + 延迟优化 截断多步流从分到秒 浏览器上下文 为自定义工具创建Page( ) 子代理、 孤立任务、 共享会话
以下是分叉中运出的主要改进:
URL 提取工具
从任何可见元素提取 URL - 不需要 CSS 选择器 ! 这个特性是 此叉子独有。 。 。 .
如何运作
代理在您通过可见文本请求 URL 时自动使用 URL 提取工具 :
// Simple URL extraction - just ask naturally!
const url = await agent.execute('Extract the URL from the "Learn More" link');
// Extract from article titles
const articleUrl = await agent.execute(
'Get the URL from the article titled "Introduction to AI"',
);
// Extract multiple URLs with structured output
const urls = await agent.execute(
"Extract URLs from the top 3 navigation links",
z.array(
z.object({
linkText: z.string(),
url: z.string(),
}),
),
);
高级能力
智能搜索策略 (按顺序排列):
- 准确的文本匹配 - 查找包含准确可见文本的元素
- 部分文本匹配 - 在更大的内容块内匹配文本
- 锁定标记检测 - 地点
<a>包含文本的标签 - CSS 选择器倒置 - 如果文本是有效的选择器,则直接选择元素
- 可点击元素搜索 - 找到与文本互动的元素
- URL 模式提取 - 检测直接在文本内容中的 URL
技术特征数字 :
- 计算机使用优化 - 与克洛德的视觉感知无缝工作
- 多个 HTML 结构 - 处理复杂的嵌入元素和动态内容
- 自动 URL 正常化 - 相对于绝对 URL 转换
- 智能错误处理 - 在元素找不到时提供有益的反馈
- 日志和调试 - 内置控制台记录故障
最佳做法数字 :
- 使用页面上可见的文本
- 对于按钮或链接,请使用其标签文本(例如"Download","Read More","View Details")
- 对于文章或故事,请使用其标题文本
- 该工具将自动处理查找关联的 URL
工具登记系统
扩展您的代理 任何外部工具 使用我们灵活的能力系统 不只是Playwright!
如何运作
工具注册提供了一种简单、安全的方式,为您的代理人添加能力:
import { registerPlaywrightCapability } from "@centralinc/browseragent";
// Add a custom Playwright capability
registerPlaywrightCapability({
method: "check_all",
displayName: "Check All Checkboxes",
description: "Check all checkboxes matching a pattern",
usage: "Check multiple checkboxes at once by pattern",
schema: z.tuple([z.string()]),
handler: async (page, args) => {
const [pattern] = args;
await page.locator(`input[type="checkbox"]${pattern}`).check();
return { output: `Checked all checkboxes matching ${pattern}` };
},
});
// Use it naturally in prompts
await agent.execute('Check all the "Accept Terms" checkboxes on this form');
扩展超越播放机
登记册支持 任何工具类型。这里有一个Slack整合的例子:
// Create a Slack tool
class SlackTool implements ComputerUseTool {
name: "slack" = "slack";
// ... implementation
}
// Use it with the agent
const agent = new ComputerUseAgent({
apiKey: ANTHROPIC_API_KEY,
page,
additionalTools: [new SlackTool(SLACK_TOKEN)],
});
// Natural language Slack operations
await agent.execute(
"Send a message to #general saying the deployment is complete",
);
await agent.execute(
"Navigate to the metrics dashboard and share a screenshot in #analytics",
);
支持的工具类型数字 :
- 📧 通讯: Slack, Discord, Teams, 电子邮件
- 🗄️ 数据: 数据库、 API、 文件系统
- 🔧 公用事业: AWS, GitHub, 吉拉语
- 🤖 自定义:任何你能想象的工具!
关键特性数字 :
- 带有 Zod 计划的类型安全
- 自动生成的文档
- 自然语言提示
- 不需要复杂的遗产
见 工具注册设计文档 用于完整的例子.
QQ 即时文本导航
直接跳转到下拉、列表或可滚动容器中的任何文本 - 不需要多次滚动尝试 !
如何运作
探员可以使用 scroll_to_text 立即导航特定文本的剧作家方法 :
// The agent sees a state dropdown and needs Wyoming
await agent.execute(`
Use the playwright scroll_to_text method to find "Wyoming" in the state picker
`);
// Behind the scenes, the agent calls:
// {"name": "playwright", "input": {"method": "scroll_to_text", "args": ["Wyoming"]}}
智能特性数字 :
- 在取景口自动检测可滚动容器
- 首先搜索可见的容器, 然后搜索整页
- 找不到精确匹配的大小写后退
- 如果找不到文本, 则光彩地返回正则滚动
- 不需要 CSS 选择器 - 只是可见的文本!
当代理使用时数字 :
- 在降水中寻找具体选项(国家、国家等)
- 浏览长列表中的产品
- 跳转到边栏中的特定项目
- 任何确切文本已知的情景
示例:取而代之的是取出"怀俄明"的"10+"小卷轴",而现在却成了单一的即时跳出!
智能滚动( 90% Viewport)
在小的UI元素中保留精确控制的同时通过长页速度.
- 默认行为 ^ 卷起~90%的取景口与~10%相重叠,达到最大吞吐量.
- 精细控制 →
scroll_amount介于 5-20 (中文(简体) ) 做细小的卷轴 完全适合倒地 列表 侧面板. - 可配置 • 接受任何
scroll_amount1 -100 和优雅地贬低.
为什么这很重要:Form-havy门户网站(例如保险索赔系统)往往需要快速的页平面滚动,由所选部件内部的像素-完美调整来取出. 此功能会自动处理两个案件.
速度优化
现在抓取屏幕截图 ~5× 更快 ~ 行动后等待时间缩短:
| 行动 | 旧的延迟 | 新建延迟 |
|---|---|---|
| 屏幕截图等待 | 2个s | 0.3 s (中文(简体) ) |
| 后打字等待 | 0.5 s (单位:千美元) | 0.1 s (中文(简体) ) |
| 滚动后等待 | 0.5 s (单位:千美元) | 0.1 s (中文(简体) ) |
| 鼠标移动暂停 | 0.1 s (中文(简体) ) | 0.02 s (中文(简体) ) |
这些切口 1-2秒 从每个多步交互.
⚠️ 备注: 一些站点依靠人相距来进行反机器人检查. 如果您遇到 Captchas 或 缺失的状态, 请通过新的构造参数增加延迟 :
const fastComputer = new ComputerTool( page, "20250124", /* screenshotDelay */ 0.5, ); // or adjust post-action waits inside ComputerTool if needed
* 代理信号(暂停/恢复/取消)
带上 人员控制 到长期运行的自动化工作流程.
- 暂停 活动
agent.execute()运行以检查或修正页面 - 继续 从你离开的确切一步
- 取消 优雅而又不破坏过程
- 实时活动:
onPause, (中文(简体) ),onResume, (中文(简体) ),onCancel, (中文(简体) ),onError
const agent = new ComputerUseAgent({ apiKey, page });
// Subscribe to events
agent.controller.on("onPause", ({ step }) => console.log("Paused at", step));
===================================================================================================================================================================================
这个分叉包括一个强大的配置系统,允许您自定义代理如何执行浏览器自动化任务. 您可以控制打字速度、 截图时间、 滚动策略、 鼠标行为以及其他自动化设置以优化原始速度 或者说 人性互动.
可用的配置选项
import type { ExecutionConfig } from "@centralinc/browseragent";
const executionConfig: ExecutionConfig = {
typing: {
mode: "fill" | "character-by-character",
characterDelay: 12, // milliseconds between characters (character-by-character mode)
completionDelay: 100, // milliseconds to wait after typing completes
},
screenshot: {
delay: 0.3, // seconds to wait before taking screenshots
quality: "low" | "medium" | "high",
},
mouse: {
moveSpeed: "instant" | "fast" | "normal" | "slow",
clickDelay: 50, // milliseconds to wait after clicks
},
scrolling: {
/**
* When no scroll_amount is provided the agent will use this mode
* with ~90 % viewport coverage for page-level scrolling.
*/
mode: "percentage", // (future-proofed for pixel or element-based modes)
/** Default percentage of the viewport to scroll. */
percentage: 90,
/** Overlap percentage to keep for context during large scrolls. */
overlap: 10,
},
};
打字模式配置
最有影响的配置是打字行为. 您可以选择两种模式:
QQ 填充模式( Fasters) - 直接填补全部绕过键盘事件的输入字段:
const fastAgent = new ComputerUseAgent({
apiKey: process.env.ANTHROPIC_API_KEY!,
page,
executionConfig: {
typing: { mode: "fill", completionDelay: 50 },
},
});
++ 字符逐字模式( 类似人) - 在可配置的延迟情况下,一次输入文本一个字符:
const humanLikeAgent = new ComputerUseAgent({
apiKey: process.env.ANTHROPIC_API_KEY!,
page,
executionConfig: {
typing: {
mode: "character-by-character",
characterDelay: 100, // 100ms between each character
completionDelay: 200,
},
},
});
QQ 快字符模式 (Balanced) - 最好的两个世界 - 可见的打字,但非常快:
const balancedAgent = new ComputerUseAgent({
apiKey: process.env.ANTHROPIC_API_KEY!,
page,
executionConfig: {
typing: {
mode: "character-by-character",
characterDelay: 5, // Very fast character typing
completionDelay: 75,
},
},
});
性能比较 :
| 模式 | 速度 | 可见度 | 使用大小写 |
|---|---|---|---|
| 填充 | ⚡⚡⚡最快 | * 即时 | 生产、速度关键任务 |
| 快速字符 | {\fn华文楷体\fs16\1cHE0E0E0}非常快 {\fn华文楷体\fs16\1cHE0E0E0}非常快 | * 可见 | 开发、调试 |
| 慢字符 | 像人类一样 | * * * 十分明显 | 人型自动化软件 |
尝试示例
运行包含的示例以查看性能差异 :
# Run the typing configuration example (set ANTHROPIC_API_KEY first)
npx ts-node examples/example-typing-config.ts
agent.controller.on('onResume', () => console.log('Resumed'));
// Trigger a pause after 5 s
setTimeout(() => agent.controller.signal('pause'), 5_000);
// Start a task (the controller is available immediately)
await agent.execute('Get the titles of the top 10 stories');
用于调试、监视超时和手动操作.
QQ 自定义工具的上下文访问
自定义工具现在可以生成新页面甚至 将任务委托给子代理人 ,同时共享同一浏览器会话(cookies,代理,反检测).
如何运作
这个 ToolExecutionContext 现规定:
createPage()- 创建一个有防检测脚本的新页面browserContext- 直接进入 PlaywrightBrowserContext
import type { ComputerUseTool, ToolResult, ToolExecutionContext } from "@centralinc/browseragent";
class ActivationLinkTool implements ComputerUseTool {
name = "click_activation_link";
async call(params: Record<string, unknown>, ctx?: ToolExecutionContext): Promise<ToolResult> {
if (!ctx?.createPage) {
return { error: "Browser context not available" };
}
const { url } = params as { url: string };
const page = await ctx.createPage();
try {
await page.goto(url, { waitUntil: "domcontentloaded" });
return { output: `Navigated to ${page.url()}` };
} finally {
await page.close();
}
}
}
副代理代表团模式
真正的权力是 产出子剂 用于执行孤立任务的新页面:
import { ComputerUseAgent } from "@centralinc/browseragent";
import { z } from "zod";
class DelegatedTaskTool implements ComputerUseTool {
name = "delegated_task";
async call(params: Record<string, unknown>, ctx?: ToolExecutionContext): Promise<ToolResult> {
if (!ctx?.createPage) {
return { error: "Browser context not available" };
}
const { task, url } = params as { task: string; url: string };
const page = await ctx.createPage();
try {
await page.goto(url);
// Create a sub-agent on the new page
const subAgent = new ComputerUseAgent({
apiKey: process.env.ANTHROPIC_API_KEY!,
page,
});
// Execute task and get structured result
const result = await subAgent.execute(
task,
z.object({ data: z.string(), success: z.boolean() })
);
return { output: JSON.stringify(result) };
} finally {
await page.close();
}
}
}
使用大小写 :
- 📧 电子邮件验证 - 导航激活链接, 返回成功状态
- 🔐 OA 流量 - 在单独的一页中处理 OAuth, 返回符号
- 📊 数据刮取 - 与外界隔绝,返回结构化数据
- 🔄 多站工作流程 - A探员触发B副探员获取数据
- ⚡ 平行行动 - 不同页面上的多个子代理人同时使用
共享输入脚本
在您的初始页面中应用相同的反检测脚本 :
import { applyInitScripts, ComputerUseAgent } from "@centralinc/browseragent";
const page = await context.newPage();
await applyInitScripts(page); // Same scripts used by createPage()
await page.goto("https://example.com");
const agent = new ComputerUseAgent({ apiKey, page });
主要惠益:
- 页面共享 cookie, 存储和会话状态
- 自动继承代理配置
- 一致适用反侦查脚本
- 管理好的页面被清理出错误
特征
- 🤖 简单 API单人
ComputerUseAgent所有计算机使用任务的类 - 🔄 双重反应类型:支持案文和结构化(JSON)对策
- 🛡️ 类型安全: 用 Zod schema 验证的完整类型脚本支持
- ⚡ 优化: 清除错误处理和强大的 JSON 解析
- 🎯 重点: 具有合理默认的清洁 API 表面
安装
npm install @centralinc/browseragent playwright @playwright/test
# or
yarn add @centralinc/browseragent playwright @playwright/test
# or
pnpm add @centralinc/browseragent playwright @playwright/test
快速启动
import { chromium } from "playwright";
import { ComputerUseAgent } from "@centralinc/browseragent";
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
// Navigate to Hacker News manually first
await page.goto("https://news.ycombinator.com/");
const agent = new ComputerUseAgent({
apiKey: process.env.ANTHROPIC_API_KEY!,
page,
});
// Simple text response
const answer = await agent.execute("Tell me the title of the top story");
console.log(answer);
await browser.close();
API 参考
ComputerUseAgent
计算机使用自动化主课.
构造器
new ComputerUseAgent(options: {
apiKey: string;
page: Page;
model?: string;
})
参数:
apiKey你的Anthropic API密钥。 从一个 自动控制台page(页):用于控制的 Playwright 页面实例model(弦,可选): 使用Anthropic模型. 默认为'claude-sonnet-4-20250514'
支持的模式 : 见 Anthropic 的计算机使用文档 用于最新的模型兼容性.
execute() 方法
async execute<T = string>(
query: string,
schema?: z.ZodSchema<T>,
options?: {
systemPromptSuffix?: string;
thinkingBudget?: number;
}
): Promise<T>
参数:
query(字符串):克劳德要执行的任务描述schema(ZodSchema,可选): Zod schema 用于结构化响应. 提供后,将对照这一计划验证答复options(对象,可选):systemPromptSuffix(字符串):系统上附加的补充指令提示thinkingBudget(数字):克劳德内部推理过程的托肯预算. 默认 :1024。见 扩展思维文档 详情
回返情况:
Promise<T>: 当schema提供了类型已验证的返回数据TPromise<string>: 当无schema返回文本响应
用法实例
文本回应
import { ComputerUseAgent } from "@centralinc/browseragent";
// Navigate to the target page first
await page.goto("https://news.ycombinator.com/");
const agent = new ComputerUseAgent({
apiKey: process.env.ANTHROPIC_API_KEY!,
page,
});
const result = await agent.execute(
"Tell me the title of the top story on this page",
);
console.log(result); // "Title of the top story"
与Zod的结构性反应
import { z } from "zod";
import { ComputerUseAgent } from "@centralinc/browseragent";
const agent = new ComputerUseAgent({
apiKey: process.env.ANTHROPIC_API_KEY!,
page,
});
const HackerNewsStory = z.object({
title: z.string(),
points: z.number(),
author: z.string(),
comments: z.number(),
url: z.string().optional(),
});
const stories = await agent.execute(
"Get the top 5 Hacker News stories with their details",
z.array(HackerNewsStory).max(5),
);
console.log(stories);
// [
// {
// title: "Example Story",
// points: 150,
// author: "user123",
// comments: 42,
// url: "https://example.com"
// },
// ...
// ]
高级选项
const result = await agent.execute(
"Complex task requiring more thinking",
undefined, // No schema for text response
{
systemPromptSuffix: "Be extra careful with form submissions.",
thinkingBudget: 4096, // More thinking tokens for complex tasks
},
);
重试配置
SDK包括处理连接错误和瞬间故障的内置重试逻辑:
import { ComputerUseAgent, type RetryConfig } from "@centralinc/browseragent";
const retryConfig: RetryConfig = {
maxRetries: 5, // Maximum retry attempts (default: 3)
initialDelayMs: 2000, // Initial delay between retries (default: 1000ms)
maxDelayMs: 60000, // Maximum delay between retries (default: 30000ms)
backoffMultiplier: 2.5, // Exponential backoff multiplier (default: 2)
preferIPv4: true, // Prefer IPv4 DNS resolution (helpful with VPNs like Tailscale)
retryableErrors: [ // Errors that trigger retries
"Connection error",
"ECONNREFUSED",
"ETIMEDOUT",
"ECONNRESET",
"socket hang up",
],
};
const agent = new ComputerUseAgent({
apiKey: process.env.ANTHROPIC_API_KEY!,
page,
retryConfig, // Custom retry configuration
});
复试机制使用与焦躁相伴的指数回放来避免打雷群出问题. 连接出错和网络超时会随着越来越多的延迟而自动重审.
VPN/ Tailscale 用户的说明 : 如果你正在经历 ENETUNREACH iPv6 地址出错, 设置 preferIPv4: true 在您重试配置中将 DNS 解析为 IPv4 地址.
工具注册 API
SDK输出功能用于扩展能力:
import {
registerPlaywrightCapability,
getToolRegistry,
defineCapability,
} from "@centralinc/browseragent";
// Register a new Playwright capability
registerPlaywrightCapability({
method: "custom_action",
displayName: "Custom Action",
description: "Performs a custom browser action",
usage: "Detailed usage instructions",
schema: z.object({ selector: z.string() }),
handler: async (page, args) => {
// Implementation
return { output: "Success" };
},
});
// Register capabilities for other tools
const registry = getToolRegistry();
registry.register(
defineCapability("slack", "send_message", {
displayName: "Send Message",
description: "Send a Slack message",
usage: "Send message to channel",
schema: z.tuple([z.string(), z.string()]),
}),
);
环境设置
-
Anthropic API 密钥: 将您的 API 密钥设置为环境变量 :
export ANTHROPIC_API_KEY=your_api_key_here -
剧作家: 安装 Playwright 和浏览器依赖性 :
npx playwright install
计算机使用参数
这个SDK利用了Anthropic的"计算机使用API",其关键参数如下:
模式选择
- Claude 3.5 索内:大多数任务的速度和能力的最佳平衡
- 克洛德4型号: 增强思维能力
- 克洛德·3.7 索内: 思维透明的高级推理
思考预算
这个 thinkingBudget 参数控制克洛德的内部推理过程:
- 1024个纪念品 (默认):适合简单的任务
- 4096+ 纪念品: 更适合复杂的推理任务
- 16k+ 符号建议采取高度复杂的多步骤行动
见 Anthropic 扩展思维指南 用于优化提示.
处理错误
SDK包括内置错误处理:
try {
const result = await agent.execute("Your task here");
console.log(result);
} catch (error) {
if (error.message.includes("No response received")) {
console.log("Agent did not receive a response from Claude");
} else {
console.log("Other error:", error.message);
}
}
最佳做法
-
使用具体、明确的指令:"点击红色"屈服"按钮对"点击提交"
-
对于复杂的任务,拆开: 在查询中使用分步指示
-
优化思维预算: 从默认开始( 1024) 为复杂任务增加
-
处理错误优雅: 为生产用途实施适当的错误处理
-
使用结构化响应: 当您需要特定的数据格式时, 请使用 Zod schemas
-
无头测试:虚假: 在开发过程中, 使用可见浏览器来调试
安全考虑
⚠️ 重要:计算机的使用可以与任何可见的应用程序相互作用. 总是:
- 在孤立的环境中运行(容器/VMs),用于生产
- 避免提供访问敏感账户或数据的机会
- 在部署生产前审查克洛德在日志中的行动
- 可能时使用允许列表域
见 Anthropic 计算机使用安全指南 详细安保建议.
所需资源
- 节点.js 18+
- 类型脚本 5+
- 剧作家 1.52+
- Anthropic API 键
相关资源
许可证
见 许可证