@capyclaw/browser-workbench 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +66 -2
  2. package/contract/browser-contract.json +890 -0
  3. package/cordis.patch.yml +25 -0
  4. package/demo/form.html +85 -0
  5. package/lib/host.mjs +68 -0
  6. package/package.json +61 -4
  7. package/server/constants.mjs +16 -0
  8. package/server/contract-snapshots.mjs +81 -0
  9. package/server/contract.mjs +24 -0
  10. package/server/engine.mjs +675 -0
  11. package/server/http-utils.mjs +2 -0
  12. package/server/infra/http.mjs +113 -0
  13. package/server/infra/tuning.mjs +82 -0
  14. package/server/mcp/handler.mjs +2 -0
  15. package/server/mcp/instructions.mjs +28 -0
  16. package/server/relay.mjs +226 -0
  17. package/server/routes/api.mjs +120 -0
  18. package/server/routes/assets.mjs +2 -0
  19. package/server/routes/mcp.mjs +17 -0
  20. package/server/routes/workbench.mjs +33 -0
  21. package/server/shared/SHARED_MANIFEST.json +47 -0
  22. package/server/shared/asset-service.mjs +217 -0
  23. package/server/shared/editor-host.mjs +125 -0
  24. package/server/shared/kit/editor/lease.mjs +139 -0
  25. package/server/shared/kit/service/api.mjs +45 -0
  26. package/server/shared/kit/service/http.mjs +113 -0
  27. package/server/shared/kit/service/mcp-http.mjs +142 -0
  28. package/server/shared/kit/tools/validate.mjs +115 -0
  29. package/server/shared/kit/tuning.mjs +82 -0
  30. package/server/shared/kit/util/fs-lock.mjs +132 -0
  31. package/server/shared/service-host.mjs +511 -0
  32. package/server/shared/state-service.mjs +249 -0
  33. package/server/shared/tool-host.mjs +341 -0
  34. package/server/shared/tuning.mjs +63 -0
  35. package/server/tools/capabilities/contract.mjs +35 -0
  36. package/server/tools/capabilities/evaluate.mjs +36 -0
  37. package/server/tools/capabilities/index.mjs +26 -0
  38. package/server/tools/capabilities/interaction.mjs +111 -0
  39. package/server/tools/capabilities/navigation.mjs +32 -0
  40. package/server/tools/capabilities/screenshot.mjs +33 -0
  41. package/server/tools/capabilities/session.mjs +75 -0
  42. package/server/tools/capabilities/snapshot.mjs +30 -0
  43. package/server/tools/capabilities/tabs.mjs +35 -0
  44. package/server/tools/index.mjs +12 -0
  45. package/server/tools/kernel/define.mjs +5 -0
  46. package/server/tools/kernel/output.mjs +22 -0
  47. package/server/tools/kernel/ports.mjs +54 -0
  48. package/server/tools/kernel/registry.mjs +17 -0
  49. package/server/tools.mjs +3 -0
  50. package/ui/app.js +157 -0
  51. package/ui/index.html +56 -0
  52. package/ui/style.css +76 -0
@@ -0,0 +1,36 @@
1
+ /**
2
+ * 脚本执行能力:默认关闭(安全默认),如实返回 NOT_IMPLEMENTED。
3
+ *
4
+ * 与 scrapling 的诚实边界同一口径:不伪造结果、返回结构化错误与开启方法。
5
+ */
6
+ import { defineCapability, defineTool } from '../kernel/define.mjs'
7
+ import { runTool } from '../kernel/output.mjs'
8
+
9
+ export const evaluateCapability = defineCapability({
10
+ id: 'evaluate',
11
+ title: '页面脚本',
12
+ tags: ['advanced'],
13
+ requires: ['engine'],
14
+ features: ['browser.evaluate'],
15
+ tools: [
16
+ defineTool({
17
+ name: 'browser_evaluate',
18
+ description: '在页面里执行 JS 表达式并返回结果。默认关闭(安全默认);关闭时返回 NOT_IMPLEMENTED 与开启方法。优先用快照+ref 完成任务,本工具留给快照覆盖不了的场景。',
19
+ inputSchema: {
20
+ type: 'object',
21
+ properties: {
22
+ script: { type: 'string', maxLength: 20000, description: 'JS 表达式(如 document.title)' },
23
+ tab: { type: 'string', maxLength: 16, description: '目标标签页 id(缺省=当前活动标签页)' },
24
+ },
25
+ required: ['script'],
26
+ additionalProperties: false,
27
+ },
28
+ kind: 'write',
29
+ since: '1.0.0',
30
+ handler: async (args, ctx) => runTool(async () => {
31
+ const out = await ctx.engine.evaluate({ script: args.script, tab: args.tab })
32
+ return JSON.stringify({ tab: out.tab, result: out.result }, null, 2)
33
+ }),
34
+ }),
35
+ ],
36
+ })
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 能力清单:唯一扩展点。
3
+ *
4
+ * 新增能力:新建 capabilities/<id>.mjs,导出 defineCapability(...),
5
+ * 然后在这里加一行 import 和数组项即可。contract / instructions / 测试
6
+ * 全部由 registry 自动派生。
7
+ */
8
+ import { contractCapability } from './contract.mjs'
9
+ import { navigationCapability } from './navigation.mjs'
10
+ import { snapshotCapability } from './snapshot.mjs'
11
+ import { interactionCapability } from './interaction.mjs'
12
+ import { tabsCapability } from './tabs.mjs'
13
+ import { screenshotCapability } from './screenshot.mjs'
14
+ import { sessionCapability } from './session.mjs'
15
+ import { evaluateCapability } from './evaluate.mjs'
16
+
17
+ export const CAPABILITIES = [
18
+ contractCapability,
19
+ navigationCapability,
20
+ snapshotCapability,
21
+ interactionCapability,
22
+ tabsCapability,
23
+ screenshotCapability,
24
+ sessionCapability,
25
+ evaluateCapability,
26
+ ]
@@ -0,0 +1,111 @@
1
+ /** 交互能力:点击 / 填写 / 按键 / 下拉选择 / 滚动(动作后自动返回新快照)。 */
2
+ import { defineCapability, defineTool } from '../kernel/define.mjs'
3
+ import { runTool } from '../kernel/output.mjs'
4
+
5
+ const TAB_PROP = { type: 'string', maxLength: 16, description: '目标标签页 id(缺省=当前活动标签页)' }
6
+
7
+ export const interactionCapability = defineCapability({
8
+ id: 'interaction',
9
+ title: '页面交互',
10
+ tags: ['core'],
11
+ requires: ['engine'],
12
+ features: ['browser.interaction'],
13
+ tools: [
14
+ defineTool({
15
+ name: 'browser_click',
16
+ description: '点击元素。ref 来自最近一次 browser_navigate/browser_snapshot 的快照;元素已变化时报 STALE_SNAPSHOT,重新快照后用新 ref。动作成功后返回新快照。',
17
+ inputSchema: {
18
+ type: 'object',
19
+ properties: { ref: { type: 'string', maxLength: 16, description: '快照里的元素引用,如 e5' }, tab: TAB_PROP },
20
+ required: ['ref'],
21
+ additionalProperties: false,
22
+ },
23
+ kind: 'write',
24
+ since: '1.0.0',
25
+ handler: async (args, ctx) => runTool(async () => {
26
+ const out = await ctx.engine.click({ ref: args.ref, tab: args.tab })
27
+ return `已点击 ${out.clicked}(标签页 ${out.tab})\n\n${out.snapshot.text}`
28
+ }),
29
+ }),
30
+ defineTool({
31
+ name: 'browser_fill',
32
+ description: '在输入框/文本域填写文字(整体替换,兼容 React/Vue 受控输入)。submit=true 时填写后按回车提交。密码框会被快照掩码显示,但填写不受影响。',
33
+ inputSchema: {
34
+ type: 'object',
35
+ properties: {
36
+ ref: { type: 'string', maxLength: 16, description: '目标输入框的 ref' },
37
+ text: { type: 'string', maxLength: 10000, description: '要填入的文字(空字符串=清空)' },
38
+ submit: { type: 'boolean', description: '填写后按 Enter 提交(默认 false)' },
39
+ tab: TAB_PROP,
40
+ },
41
+ required: ['ref', 'text'],
42
+ additionalProperties: false,
43
+ },
44
+ kind: 'write',
45
+ since: '1.0.0',
46
+ handler: async (args, ctx) => runTool(async () => {
47
+ const out = await ctx.engine.fill({ ref: args.ref, text: args.text, submit: args.submit, tab: args.tab })
48
+ return `已填写 ${out.filled}${out.submit ? ' 并回车提交' : ''}(标签页 ${out.tab})\n\n${out.snapshot.text}`
49
+ }),
50
+ }),
51
+ defineTool({
52
+ name: 'browser_press',
53
+ description: '按键。给 ref 时在指定元素上按(如输入框内 Enter),不给 ref 时对当前页面按(如 Tab / Escape / Control+a)。',
54
+ inputSchema: {
55
+ type: 'object',
56
+ properties: {
57
+ key: { type: 'string', maxLength: 40, description: '键名:Enter / Tab / Escape / ArrowDown / Control+a 等(Playwright 键名)' },
58
+ ref: { type: 'string', maxLength: 16, description: '目标元素 ref(缺省=页面级按键)' },
59
+ tab: TAB_PROP,
60
+ },
61
+ required: ['key'],
62
+ additionalProperties: false,
63
+ },
64
+ kind: 'write',
65
+ since: '1.0.0',
66
+ handler: async (args, ctx) => runTool(async () => {
67
+ const out = await ctx.engine.press({ key: args.key, ref: args.ref, tab: args.tab })
68
+ return `已按键 ${out.key}(标签页 ${out.tab})\n\n${out.snapshot.text}`
69
+ }),
70
+ }),
71
+ defineTool({
72
+ name: 'browser_select',
73
+ description: '选择下拉框(select)的选项。value 先按 <option value> 匹配,失败自动按选项文本匹配。',
74
+ inputSchema: {
75
+ type: 'object',
76
+ properties: {
77
+ ref: { type: 'string', maxLength: 16, description: '目标下拉框的 ref' },
78
+ value: { type: 'string', maxLength: 300, description: '选项的 value 或可见文本' },
79
+ tab: TAB_PROP,
80
+ },
81
+ required: ['ref', 'value'],
82
+ additionalProperties: false,
83
+ },
84
+ kind: 'write',
85
+ since: '1.0.0',
86
+ handler: async (args, ctx) => runTool(async () => {
87
+ const out = await ctx.engine.select({ ref: args.ref, value: args.value, tab: args.tab })
88
+ return `已选择 ${out.selected}(标签页 ${out.tab})\n\n${out.snapshot.text}`
89
+ }),
90
+ }),
91
+ defineTool({
92
+ name: 'browser_scroll',
93
+ description: '滚动当前页面(默认向下 600px)。懒加载页面翻内容用它。',
94
+ inputSchema: {
95
+ type: 'object',
96
+ properties: {
97
+ direction: { type: 'string', enum: ['up', 'down'], description: '方向(默认 down)' },
98
+ amount: { type: 'number', description: '像素数(默认 600)' },
99
+ tab: TAB_PROP,
100
+ },
101
+ additionalProperties: false,
102
+ },
103
+ kind: 'write',
104
+ since: '1.0.0',
105
+ handler: async (args, ctx) => runTool(async () => {
106
+ const out = await ctx.engine.scroll({ direction: args.direction, amount: args.amount, tab: args.tab })
107
+ return `已滚动 ${out.scrolled}(标签页 ${out.tab})\n\n${out.snapshot.text}`
108
+ }),
109
+ }),
110
+ ],
111
+ })
@@ -0,0 +1,32 @@
1
+ /** 导航能力:打开网址并返回首屏快照。 */
2
+ import { defineCapability, defineTool } from '../kernel/define.mjs'
3
+ import { runTool } from '../kernel/output.mjs'
4
+
5
+ export const navigationCapability = defineCapability({
6
+ id: 'navigation',
7
+ title: '导航',
8
+ tags: ['core'],
9
+ requires: ['engine'],
10
+ features: ['browser.navigation'],
11
+ tools: [
12
+ defineTool({
13
+ name: 'browser_navigate',
14
+ description: '打开网址(仅 http/https;URL 内嵌用户名密码会被拒绝)。首次调用会自动拉起浏览器(默认有头可见,登录态持久化)。返回新页面的元素快照,后续动作直接引用其中的 ref。',
15
+ inputSchema: {
16
+ type: 'object',
17
+ properties: {
18
+ url: { type: 'string', maxLength: 2048, description: '目标网址,如 https://example.com/' },
19
+ tab: { type: 'string', maxLength: 16, description: '在指定标签页打开(缺省=当前活动标签页;浏览器未启动时自动新建)' },
20
+ },
21
+ required: ['url'],
22
+ additionalProperties: false,
23
+ },
24
+ kind: 'write',
25
+ since: '1.0.0',
26
+ handler: async (args, ctx) => runTool(async () => {
27
+ const out = await ctx.engine.navigate({ url: args.url, tab: args.tab })
28
+ return `已打开 ${out.url} — ${out.title || '(无标题)'}(标签页 ${out.tab})\n\n${out.snapshot.text}`
29
+ }),
30
+ }),
31
+ ],
32
+ })
@@ -0,0 +1,33 @@
1
+ /** 截图能力:PNG 落盘并返回绝对路径。 */
2
+ import { defineCapability, defineTool } from '../kernel/define.mjs'
3
+ import { runTool } from '../kernel/output.mjs'
4
+
5
+ export const screenshotCapability = defineCapability({
6
+ id: 'screenshot',
7
+ title: '页面截图',
8
+ tags: ['verify'],
9
+ requires: ['engine', 'server'],
10
+ features: ['browser.screenshot'],
11
+ tools: [
12
+ defineTool({
13
+ name: 'browser_screenshot',
14
+ description: '当前页面截图(PNG 保存到本机,返回绝对路径)。默认视口截图;fullPage=true 截整页。工作台地址可实时观察页面。',
15
+ inputSchema: {
16
+ type: 'object',
17
+ properties: {
18
+ fullPage: { type: 'boolean', description: '是否截取整页(默认 false)' },
19
+ tab: { type: 'string', maxLength: 16, description: '目标标签页 id(缺省=当前活动标签页)' },
20
+ },
21
+ additionalProperties: false,
22
+ },
23
+ kind: 'read',
24
+ since: '1.0.0',
25
+ handler: async (args, ctx) => runTool(async () => {
26
+ const out = await ctx.engine.screenshot({ fullPage: args.fullPage, tab: args.tab })
27
+ let workbench = ''
28
+ try { workbench = ctx.server.url() } catch { /* 未注入则省略 */ }
29
+ return `截图已保存: ${out.path}(${out.bytes} 字节)${workbench ? `\n工作台实时画面: ${workbench}` : ''}`
30
+ }),
31
+ }),
32
+ ],
33
+ })
@@ -0,0 +1,75 @@
1
+ /** 会话能力:状态 / 等待 / 历史 / 关闭浏览器。 */
2
+ import { defineCapability, defineTool } from '../kernel/define.mjs'
3
+ import { runTool } from '../kernel/output.mjs'
4
+
5
+ const TAB_PROP = { type: 'string', maxLength: 16, description: '目标标签页 id(缺省=当前活动标签页)' }
6
+
7
+ export const sessionCapability = defineCapability({
8
+ id: 'session',
9
+ title: '会话管理',
10
+ tags: ['core'],
11
+ requires: ['engine'],
12
+ features: ['browser.session'],
13
+ tools: [
14
+ defineTool({
15
+ name: 'browser_status',
16
+ description: '引擎状态:是否运行、有头/无头、标签页清单(id+地址)、累计动作数、最近动作日志。不确定浏览器是否还活着时先看它。',
17
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
18
+ kind: 'read',
19
+ since: '1.0.0',
20
+ handler: async (_args, ctx) => runTool(() => {
21
+ const status = ctx.engine.status()
22
+ return JSON.stringify({ ...status, recentActions: ctx.engine.actionLog().slice(0, 8) }, null, 2)
23
+ }),
24
+ }),
25
+ defineTool({
26
+ name: 'browser_wait',
27
+ description: '等待:ms=毫秒;selector=等元素出现(如 .result);都不给=等页面 load 完成。动作后页面还在加载/渲染时用它。',
28
+ inputSchema: {
29
+ type: 'object',
30
+ properties: {
31
+ ms: { type: 'number', description: '等待毫秒数(上限 30000)' },
32
+ selector: { type: 'string', maxLength: 300, description: '等待出现的 CSS 选择器' },
33
+ tab: TAB_PROP,
34
+ },
35
+ additionalProperties: false,
36
+ },
37
+ kind: 'control',
38
+ since: '1.0.0',
39
+ handler: async (args, ctx) => runTool(async () => {
40
+ const out = await ctx.engine.wait({ ms: args.ms, selector: args.selector, tab: args.tab })
41
+ return `已等待完成(标签页 ${out.tab})`
42
+ }),
43
+ }),
44
+ defineTool({
45
+ name: 'browser_history',
46
+ description: '浏览历史:back 后退 / forward 前进 / reload 重载。返回操作后的新快照。',
47
+ inputSchema: {
48
+ type: 'object',
49
+ properties: {
50
+ action: { type: 'string', enum: ['back', 'forward', 'reload'], description: '动作(默认 back)' },
51
+ tab: TAB_PROP,
52
+ },
53
+ additionalProperties: false,
54
+ },
55
+ kind: 'control',
56
+ since: '1.0.0',
57
+ handler: async (args, ctx) => runTool(async () => {
58
+ const out = await ctx.engine.history({ action: args.action, tab: args.tab })
59
+ const label = args.action === 'reload' ? '已重载' : args.action === 'forward' ? '已前进到' : '已后退到'
60
+ return `${label} ${out.url}(标签页 ${out.tab})\n\n${out.snapshot.text}`
61
+ }),
62
+ }),
63
+ defineTool({
64
+ name: 'browser_close',
65
+ description: '关闭浏览器(所有标签页)。登录态与 profile 持久化,下次 navigate 自动重启浏览器并保留登录。任务结束或页面卡死时用它重置。',
66
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
67
+ kind: 'control',
68
+ since: '1.0.0',
69
+ handler: async (_args, ctx) => runTool(async () => {
70
+ const out = await ctx.engine.close()
71
+ return out.closed ? '浏览器已关闭(登录态已持久化,下次 navigate 自动重启)' : '浏览器本就未在运行'
72
+ }),
73
+ }),
74
+ ],
75
+ })
@@ -0,0 +1,30 @@
1
+ /** 观察能力:无障碍风格的元素快照(ref 引用的唯一来源)。 */
2
+ import { defineCapability, defineTool } from '../kernel/define.mjs'
3
+ import { runTool } from '../kernel/output.mjs'
4
+
5
+ export const snapshotCapability = defineCapability({
6
+ id: 'snapshot',
7
+ title: '页面快照',
8
+ tags: ['core'],
9
+ requires: ['engine'],
10
+ features: ['browser.snapshot'],
11
+ tools: [
12
+ defineTool({
13
+ name: 'browser_snapshot',
14
+ description: '观察当前页面:返回可交互元素(链接/按钮/输入框/下拉…)与结构节点(标题/图片)的缩进文本树,每个元素带 ref=eN。click/fill/select 等动作只用 ref 定位;页面变化后 ref 会过期(报 STALE_SNAPSHOT),重新快照即可。',
15
+ inputSchema: {
16
+ type: 'object',
17
+ properties: {
18
+ tab: { type: 'string', maxLength: 16, description: '目标标签页 id(缺省=当前活动标签页)' },
19
+ },
20
+ additionalProperties: false,
21
+ },
22
+ kind: 'read',
23
+ since: '1.0.0',
24
+ handler: async (args, ctx) => runTool(async () => {
25
+ const out = await ctx.engine.snapshot({ tab: args.tab })
26
+ return `# ${out.title || '(无标题)'}\n${out.url}(标签页 ${out.tab},${out.elements} 个元素${out.truncated ? ',已截断' : ''})\n\n${out.text}`
27
+ }),
28
+ }),
29
+ ],
30
+ })
@@ -0,0 +1,35 @@
1
+ /** 标签页能力:列出 / 新建 / 切换 / 关闭(稳定 id:T1、T2…)。 */
2
+ import { defineCapability, defineTool } from '../kernel/define.mjs'
3
+ import { runTool } from '../kernel/output.mjs'
4
+
5
+ export const tabsCapability = defineCapability({
6
+ id: 'tabs',
7
+ title: '标签页管理',
8
+ tags: ['core'],
9
+ requires: ['engine'],
10
+ features: ['browser.tabs'],
11
+ tools: [
12
+ defineTool({
13
+ name: 'browser_tabs',
14
+ description: '标签页四合一:action=list 列出(含稳定 id 与当前地址);new 打开新标签页(可带 url);select 切换活动标签页;close 关闭。后续动作默认作用于活动标签页,也可用 tab 参数显式指定。',
15
+ inputSchema: {
16
+ type: 'object',
17
+ properties: {
18
+ action: { type: 'string', enum: ['list', 'new', 'select', 'close'], description: '动作(默认 list)' },
19
+ url: { type: 'string', maxLength: 2048, description: 'new 动作要打开的网址' },
20
+ tab: { type: 'string', maxLength: 16, description: 'select/close 的目标标签页 id' },
21
+ },
22
+ additionalProperties: false,
23
+ },
24
+ kind: 'control',
25
+ since: '1.0.0',
26
+ handler: async (args, ctx) => runTool(async () => {
27
+ const out = await ctx.engine.tabsAction({ action: args.action, url: args.url, tab: args.tab })
28
+ if (args.action === 'new') return `已打开新标签页 ${out.tab}(${out.url || 'about:blank'})\n\n${out.snapshot.text}`
29
+ if (args.action === 'select') return `已切换到标签页 ${out.tab}\n\n${out.snapshot.text}`
30
+ if (args.action === 'close') return `已关闭标签页 ${out.closed},剩余 ${out.tabs.length} 个`
31
+ return JSON.stringify(out, null, 2)
32
+ }),
33
+ }),
34
+ ],
35
+ })
@@ -0,0 +1,12 @@
1
+ /**
2
+ * 工具组装:能力 → registry → TOOLS/TOOL_IMPL/契约。
3
+ * relay 与测试都从这里拿工具面。
4
+ */
5
+ import { createRegistry } from './kernel/registry.mjs'
6
+ import { CAPABILITIES } from './capabilities/index.mjs'
7
+
8
+ export { createRegistry } from './kernel/registry.mjs'
9
+ export { CAPABILITIES } from './capabilities/index.mjs'
10
+
11
+ export const registry = createRegistry(CAPABILITIES)
12
+ export const { TOOLS, TOOL_IMPL, TOOL_META, FEATURES } = registry
@@ -0,0 +1,5 @@
1
+ /**
2
+ * 能力声明 DSL:统一来自 dsh-tool-host 公共插件。
3
+ * 保留此文件作为稳定 import 路径,capabilities/* 不需要改。
4
+ */
5
+ export { defineTool, defineCapability } from '../../shared/tool-host.mjs'
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 工具输出格式:引擎的结构化错误(code/hint)转成模型可读文本,
3
+ * 不让 MCP 协议壳把提示信息吞掉。
4
+ */
5
+ export function ok(text) {
6
+ return { content: [{ type: 'text', text }], isError: false }
7
+ }
8
+
9
+ export function fail(error) {
10
+ const code = error?.code ? `[${error.code}] ` : ''
11
+ const hint = error?.hint ? `\n提示:${error.hint}` : ''
12
+ return { content: [{ type: 'text', text: `${code}${error?.message || String(error)}${hint}` }], isError: true }
13
+ }
14
+
15
+ /** 包一层:handler 里只写业务,错误统一转 fail。 */
16
+ export async function runTool(fn) {
17
+ try {
18
+ return ok(await fn())
19
+ } catch (error) {
20
+ return fail(error)
21
+ }
22
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * 内核端口:能力模块唯一允许接触的 I/O 面。
3
+ *
4
+ * engine —— 浏览器引擎控制器(lib 侧 src/mcp/engine.mjs;relay 启动后
5
+ * setEngine 绑定实例,能力经 ctx.engine.* 调用;模块级 registry
6
+ * 在未绑定时调用会得到结构化 ENGINE_UNBOUND 错误)。
7
+ * server —— relay 侧注入的工作台地址(capabilities 报告用)。
8
+ */
9
+ const ENGINE_METHODS = [
10
+ 'navigate', 'snapshot', 'click', 'fill', 'press', 'select', 'scroll',
11
+ 'wait', 'history', 'tabsAction', 'screenshot', 'screenshotBuffer',
12
+ 'evaluate', 'close', 'status', 'actionLog',
13
+ ]
14
+
15
+ let currentEngine = null
16
+ let serverUrl = ''
17
+
18
+ /** relay 绑定引擎实例(工具面在 relay 进程内运行)。 */
19
+ export function setEngine(engine) {
20
+ currentEngine = engine || null
21
+ }
22
+
23
+ /** relay 绑定工作台地址(capabilities 报告展示用)。 */
24
+ export function setServerUrl(url) {
25
+ serverUrl = String(url || '')
26
+ }
27
+
28
+ export function getEngine() {
29
+ return currentEngine
30
+ }
31
+
32
+ export function createKernelPorts({ serverBaseUrl = '' } = {}) {
33
+ const base = serverBaseUrl || serverUrl
34
+ const engine = {}
35
+ for (const method of ENGINE_METHODS) {
36
+ engine[method] = (...args) => {
37
+ if (!currentEngine || typeof currentEngine[method] !== 'function') {
38
+ throw Object.assign(new Error('引擎未绑定(relay 未完成装配)'), {
39
+ code: 'ENGINE_UNBOUND',
40
+ hint: '该调用应经 relay 的 /mcp 进入;独立 import 工具面时没有引擎实例。',
41
+ })
42
+ }
43
+ return currentEngine[method](...args)
44
+ }
45
+ }
46
+ return {
47
+ engine,
48
+ server: {
49
+ url: () => base,
50
+ },
51
+ }
52
+ }
53
+
54
+ export const KERNEL_PORT_NAMES = Object.freeze(['engine', 'server'])
@@ -0,0 +1,17 @@
1
+ /**
2
+ * 能力注册表:通用实现来自 dsh-tool-host;本文件只注入 Browser 的内核端口与契约报告。
3
+ */
4
+ import { createRegistry as createBaseRegistry } from '../../shared/tool-host.mjs'
5
+ import { createKernelPorts, KERNEL_PORT_NAMES } from './ports.mjs'
6
+ import { capabilityReport } from '../../contract.mjs'
7
+
8
+ export function createRegistry(capabilities, options = {}) {
9
+ const { toolHost = null, serverBaseUrl = '', ...rest } = options
10
+ const factory = toolHost?.createRegistry || createBaseRegistry
11
+ return factory(capabilities, {
12
+ ports: createKernelPorts({ serverBaseUrl }),
13
+ reserved: KERNEL_PORT_NAMES,
14
+ report: ({ editorUrl = '', runtime = {}, ...args }) => capabilityReport(args, editorUrl, runtime),
15
+ ...rest,
16
+ })
17
+ }
@@ -0,0 +1,3 @@
1
+ /** 工具 facade:能力清单在 tools/capabilities/,registry 派生工具面。 */
2
+ export { createRegistry, CAPABILITIES, TOOLS, TOOL_IMPL, TOOL_META, FEATURES } from './tools/index.mjs'
3
+ export { setEngine } from './tools/kernel/ports.mjs'
package/ui/app.js ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * 浏览器操控工作台前端(无框架无构建)。
3
+ *
4
+ * 数据面全部来自本服务的 /api/*:状态轮询 2s;浏览器运行时实时画面轮询
5
+ * 1.2s(未运行不请求)。所有按钮只是便捷入口,与 AI 的 browser_* 工具
6
+ * 共用同一引擎实例与动作互斥队列。
7
+ */
8
+ (function () {
9
+ 'use strict'
10
+
11
+ var $ = function (id) { return document.getElementById(id) }
12
+ var els = {
13
+ engine: $('badge-engine'), mode: $('badge-mode'), tabs: $('tabs'),
14
+ view: $('view'), log: $('log'), snapshot: $('snapshot'), counters: $('counters'),
15
+ urlInput: $('url-input'),
16
+ btnOpen: $('btn-open'), btnDemo: $('btn-demo'), btnSnapshot: $('btn-snapshot'), btnClose: $('btn-close'),
17
+ }
18
+ var running = false
19
+ var shotBusy = false
20
+ var statusBusy = false
21
+
22
+ function fmtUrl(url) {
23
+ if (!url || url === 'about:blank') return '(空白页)'
24
+ return url.replace(/^https?:\/\//, '').slice(0, 40)
25
+ }
26
+
27
+ function renderStatus(data) {
28
+ var st = data.status || {}
29
+ running = !!st.running
30
+ els.engine.textContent = running
31
+ ? (st.launching ? '浏览器启动中…' : '浏览器运行中 · ' + (st.channel || 'chromium'))
32
+ : '浏览器未启动'
33
+ els.engine.className = 'badge ' + (running ? 'on' : 'off')
34
+ els.mode.hidden = !running
35
+ els.mode.textContent = st.headless ? '无头' : '有头'
36
+ els.counters.textContent = st.counters
37
+ ? '动作 ' + st.counters.actions + ' · 失败 ' + st.counters.errors + ' · 快照 ' + st.counters.snapshots
38
+ : ''
39
+ /* 标签页 */
40
+ els.tabs.innerHTML = ''
41
+ var tabs = st.tabs || []
42
+ if (tabs.length > 1 || (tabs.length && !running)) {
43
+ tabs.forEach(function (tab) {
44
+ var el = document.createElement('span')
45
+ el.className = 'tab' + (tab.active ? ' active' : '')
46
+ el.textContent = (tab.id || '?') + ' ' + fmtUrl(tab.url)
47
+ el.title = tab.url
48
+ el.onclick = function () { post('/api/tabs', { action: 'select', tab: tab.id }) }
49
+ els.tabs.appendChild(el)
50
+ })
51
+ }
52
+ /* 动作日志 */
53
+ var actions = data.actions || []
54
+ if (actions.length) {
55
+ els.log.innerHTML = ''
56
+ actions.forEach(function (a) {
57
+ var li = document.createElement('li')
58
+ var t = document.createElement('span')
59
+ t.className = 't'
60
+ t.textContent = (a.at || '').slice(11, 19)
61
+ var name = document.createElement('span')
62
+ name.className = a.ok ? 'ok' : 'fail'
63
+ name.textContent = (a.ok ? '✓ ' : '✗ ') + a.tool + (a.detail ? ' · ' + a.detail : '')
64
+ if (!a.ok && a.error) name.title = a.error
65
+ var ms = document.createElement('span')
66
+ ms.className = 'ms'
67
+ ms.textContent = a.ms + 'ms'
68
+ li.appendChild(t); li.appendChild(name); li.appendChild(ms)
69
+ els.log.appendChild(li)
70
+ })
71
+ }
72
+ }
73
+
74
+ function pollStatus() {
75
+ if (statusBusy) return
76
+ statusBusy = true
77
+ fetch('/api/status').then(function (r) { return r.json() }).then(function (data) {
78
+ renderStatus(data)
79
+ }).catch(function () { /* 服务重启间隙 */ }).finally(function () { statusBusy = false })
80
+ }
81
+
82
+ function pollScreenshot() {
83
+ if (!running || shotBusy) return
84
+ shotBusy = true
85
+ fetch('/api/screenshot').then(function (r) {
86
+ if (!r.ok) throw new Error('shot ' + r.status)
87
+ return r.blob()
88
+ }).then(function (blob) {
89
+ var img = els.view.querySelector('img')
90
+ if (!img) {
91
+ els.view.innerHTML = ''
92
+ img = document.createElement('img')
93
+ img.alt = '当前页面实时画面'
94
+ els.view.appendChild(img)
95
+ }
96
+ var url = URL.createObjectURL(blob)
97
+ var prev = img.src
98
+ img.src = url
99
+ if (prev && prev.startsWith('blob:')) URL.revokeObjectURL(prev)
100
+ }).catch(function () { /* 引擎未运行/页面关闭 */ }).finally(function () { shotBusy = false })
101
+ }
102
+
103
+ function post(path, body) {
104
+ return fetch(path, {
105
+ method: 'POST',
106
+ headers: { 'content-type': 'application/json' },
107
+ body: JSON.stringify(body),
108
+ }).then(function (r) { return r.json() }).then(function (data) {
109
+ pollStatus()
110
+ if (data && data.ok === false && data.error) {
111
+ alert('[' + (data.error.code || 'ERROR') + '] ' + data.error.message +
112
+ (data.error.hint ? '\n' + data.error.hint : ''))
113
+ }
114
+ return data
115
+ }).catch(function (e) { alert('请求失败: ' + e.message) })
116
+ }
117
+
118
+ function openUrl(url) {
119
+ els.btnOpen.disabled = true
120
+ post('/api/navigate', { url: url }).finally(function () {
121
+ els.btnOpen.disabled = false
122
+ pollScreenshot()
123
+ })
124
+ }
125
+
126
+ els.btnOpen.onclick = function () {
127
+ var url = els.urlInput.value.trim()
128
+ if (!url) return
129
+ if (!/^https?:\/\//i.test(url)) url = 'https://' + url
130
+ openUrl(url)
131
+ }
132
+ els.urlInput.addEventListener('keydown', function (e) {
133
+ if (e.key === 'Enter') els.btnOpen.click()
134
+ })
135
+ els.btnDemo.onclick = function () { openUrl(location.origin + '/demo/form.html') }
136
+ els.btnSnapshot.onclick = function () {
137
+ fetch('/api/snapshot').then(function (r) { return r.json() }).then(function (data) {
138
+ if (data.ok === false) {
139
+ els.snapshot.textContent = (data.error ? data.error.message : '快照失败')
140
+ return
141
+ }
142
+ els.snapshot.textContent =
143
+ '# ' + (data.title || '(无标题)') + '\n' + data.url + '(' + data.elements + ' 个元素' +
144
+ (data.truncated ? ',已截断' : '') + ')\n\n' + data.text
145
+ }).catch(function (e) { els.snapshot.textContent = '快照失败: ' + e.message })
146
+ }
147
+ els.btnClose.onclick = function () {
148
+ if (!confirm('关闭浏览器?登录态会持久化,下次打开网址自动重启。')) return
149
+ post('/api/control', { action: 'close' }).then(function () {
150
+ els.view.innerHTML = '<div class="placeholder"><p>浏览器已关闭。</p><p>登录态已持久化;下次打开网址时自动重启。</p></div>'
151
+ })
152
+ }
153
+
154
+ pollStatus()
155
+ setInterval(pollStatus, 2000)
156
+ setInterval(pollScreenshot, 1200)
157
+ })()