@capyclaw/browser-workbench 0.1.0 → 0.1.19

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 (161) hide show
  1. package/README.md +29 -7
  2. package/contract/browser-contract.json +484 -25
  3. package/demo/form.html +27 -0
  4. package/lib/host.mjs +1 -68
  5. package/node_modules/@capyclaw/asset-service/README.md +48 -0
  6. package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
  7. package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
  8. package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
  9. package/node_modules/@capyclaw/asset-service/package.json +59 -0
  10. package/node_modules/@capyclaw/asset-service/src/index.mjs +304 -0
  11. package/node_modules/@capyclaw/document-workbench/README.md +125 -0
  12. package/node_modules/@capyclaw/document-workbench/package.json +44 -0
  13. package/node_modules/@capyclaw/document-workbench/src/bridge/index.mjs +321 -0
  14. package/node_modules/@capyclaw/document-workbench/src/client/index.mjs +625 -0
  15. package/node_modules/@capyclaw/document-workbench/src/client/screenshot.mjs +98 -0
  16. package/node_modules/@capyclaw/document-workbench/src/index.mjs +9 -0
  17. package/node_modules/@capyclaw/document-workbench/src/model/audit.mjs +101 -0
  18. package/node_modules/@capyclaw/document-workbench/src/model/conformance.mjs +92 -0
  19. package/node_modules/@capyclaw/document-workbench/src/model/ids.mjs +56 -0
  20. package/node_modules/@capyclaw/document-workbench/src/model/index.mjs +18 -0
  21. package/node_modules/@capyclaw/document-workbench/src/model/locate.mjs +118 -0
  22. package/node_modules/@capyclaw/document-workbench/src/model/manifest.mjs +148 -0
  23. package/node_modules/@capyclaw/document-workbench/src/model/ops.mjs +160 -0
  24. package/node_modules/@capyclaw/document-workbench/src/model/validate.mjs +72 -0
  25. package/node_modules/@capyclaw/document-workbench/src/ops/index.mjs +93 -0
  26. package/node_modules/@capyclaw/document-workbench/src/session/context.mjs +103 -0
  27. package/node_modules/@capyclaw/document-workbench/src/session/index.mjs +394 -0
  28. package/node_modules/@capyclaw/document-workbench/src/session/lease.mjs +105 -0
  29. package/node_modules/@capyclaw/document-workbench/src/session/mode.mjs +80 -0
  30. package/node_modules/@capyclaw/document-workbench/src/session/sanitize.mjs +107 -0
  31. package/node_modules/@capyclaw/document-workbench/src/session/state.mjs +159 -0
  32. package/node_modules/@capyclaw/document-workbench/src/session/watch.mjs +63 -0
  33. package/{server/shared/state-service.mjs → node_modules/@capyclaw/document-workbench/src/store/file-backend.mjs} +6 -97
  34. package/node_modules/@capyclaw/document-workbench/src/testing/index.mjs +75 -0
  35. package/node_modules/@capyclaw/foundation/README.md +51 -0
  36. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  37. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  38. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  39. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  40. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  41. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  42. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  43. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  44. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  45. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  46. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  47. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  48. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  49. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  50. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  51. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  52. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  53. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  54. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  55. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  56. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  57. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  58. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  59. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  60. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  61. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  62. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  63. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  64. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  65. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  66. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  67. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  68. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  69. package/node_modules/@capyclaw/foundation/package.json +53 -0
  70. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  71. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  72. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  73. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  74. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +58 -0
  79. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  80. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  81. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  82. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  83. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  84. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  85. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  86. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  87. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  88. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  89. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  90. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  91. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  92. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  93. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  94. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  95. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  96. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  97. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  98. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  99. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  100. package/node_modules/@capyclaw/service-host/README.md +86 -0
  101. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  102. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  103. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  104. package/node_modules/@capyclaw/service-host/package.json +60 -0
  105. package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
  106. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  107. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  108. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  109. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  110. package/node_modules/@capyclaw/tool-host/lib/host.mjs +16 -0
  111. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  112. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  113. package/node_modules/@capyclaw/tool-host/src/index.mjs +416 -0
  114. package/package.json +28 -12
  115. package/plugin.mjs +1 -0
  116. package/server/contract.mjs +3 -3
  117. package/server/embedded-host.mjs +247 -0
  118. package/server/engine.mjs +1906 -115
  119. package/server/governor.mjs +189 -0
  120. package/server/http-utils.mjs +1 -1
  121. package/server/human.mjs +628 -0
  122. package/server/infra/http.mjs +2 -113
  123. package/server/infra/tuning.mjs +2 -82
  124. package/server/input.mjs +154 -0
  125. package/server/login-vault.mjs +109 -0
  126. package/server/mcp/handler.mjs +1 -1
  127. package/server/mcp/instructions.mjs +5 -2
  128. package/server/orphans.mjs +163 -0
  129. package/server/relay.mjs +160 -188
  130. package/server/routes/api.mjs +126 -13
  131. package/server/routes/assets.mjs +1 -1
  132. package/server/session-engines.mjs +223 -0
  133. package/server/shared/SHARED_MANIFEST.json +47 -24
  134. package/server/shared/asset-service.mjs +2 -217
  135. package/server/shared/editor-host.mjs +2 -125
  136. package/server/shared/kit/editor/lease.mjs +2 -139
  137. package/server/shared/kit/service/api.mjs +2 -45
  138. package/server/shared/kit/service/http.mjs +2 -113
  139. package/server/shared/kit/service/mcp-http.mjs +2 -142
  140. package/server/shared/kit/tools/validate.mjs +2 -115
  141. package/server/shared/kit/tuning.mjs +2 -82
  142. package/server/shared/kit/util/fs-lock.mjs +2 -132
  143. package/server/shared/service-host.mjs +2 -511
  144. package/server/shared/tool-host.mjs +2 -341
  145. package/server/shared/tuning.mjs +2 -63
  146. package/server/tools/capabilities/contract.mjs +25 -5
  147. package/server/tools/capabilities/interaction.mjs +113 -9
  148. package/server/tools/capabilities/navigation.mjs +5 -2
  149. package/server/tools/capabilities/screenshot.mjs +25 -8
  150. package/server/tools/capabilities/session.mjs +13 -7
  151. package/server/tools/capabilities/snapshot.mjs +1 -1
  152. package/server/tools/capabilities/tabs.mjs +2 -2
  153. package/server/tools/kernel/define.mjs +1 -1
  154. package/server/tools/kernel/output.mjs +8 -0
  155. package/server/tools/kernel/ports.mjs +12 -7
  156. package/server/tools/kernel/registry.mjs +1 -1
  157. package/server/workbench-framework.mjs +305 -0
  158. package/ui/app.js +409 -119
  159. package/ui/index.html +29 -39
  160. package/ui/style.css +131 -63
  161. package/cordis.patch.yml +0 -25
@@ -1,6 +1,11 @@
1
- /** 截图能力:PNG 落盘并返回绝对路径。 */
1
+ /** 截图能力:PNG 直接回给模型(富内容块),同时落盘保留路径。 */
2
2
  import { defineCapability, defineTool } from '../kernel/define.mjs'
3
- import { runTool } from '../kernel/output.mjs'
3
+ import { fail, ok, okBlocks } from '../kernel/output.mjs'
4
+
5
+ /** 大图挡在 MCP 体量上限之外:超过就只回路径,避免整条结果被宿主拒绝。 */
6
+ const MAX_INLINE_IMAGE_BYTES = 4 * 1024 * 1024
7
+
8
+ const TAB_PROP = { type: 'string', maxLength: 16, description: '目标标签页 id(缺省=当前活动标签页)' }
4
9
 
5
10
  export const screenshotCapability = defineCapability({
6
11
  id: 'screenshot',
@@ -11,23 +16,35 @@ export const screenshotCapability = defineCapability({
11
16
  tools: [
12
17
  defineTool({
13
18
  name: 'browser_screenshot',
14
- description: '当前页面截图(PNG 保存到本机,返回绝对路径)。默认视口截图;fullPage=true 截整页。工作台地址可实时观察页面。',
19
+ description: '当前页面截图,图片直接返回给你看(PNG,同时落盘并给出路径);不要再调 read_image 去读它。默认视口截图;fullPage=true 截整页。工作台地址可实时观察页面。',
15
20
  inputSchema: {
16
21
  type: 'object',
17
22
  properties: {
18
23
  fullPage: { type: 'boolean', description: '是否截取整页(默认 false)' },
19
- tab: { type: 'string', maxLength: 16, description: '目标标签页 id(缺省=当前活动标签页)' },
24
+ tab: TAB_PROP,
20
25
  },
21
26
  additionalProperties: false,
22
27
  },
23
28
  kind: 'read',
24
29
  since: '1.0.0',
25
- handler: async (args, ctx) => runTool(async () => {
26
- const out = await ctx.engine.screenshot({ fullPage: args.fullPage, tab: args.tab })
30
+ handler: async (args, ctx) => {
31
+ let out
32
+ try {
33
+ out = await ctx.engine.screenshot({ fullPage: args.fullPage, tab: args.tab })
34
+ } catch (error) {
35
+ return fail(error)
36
+ }
27
37
  let workbench = ''
28
38
  try { workbench = ctx.server.url() } catch { /* 未注入则省略 */ }
29
- return `截图已保存: ${out.path}(${out.bytes} 字节)${workbench ? `\n工作台实时画面: ${workbench}` : ''}`
30
- }),
39
+ const note = `截图已保存: ${out.path}(${out.bytes} 字节)${workbench ? `\n工作台实时画面: ${workbench}` : ''}`
40
+ if (!out.data || out.bytes > MAX_INLINE_IMAGE_BYTES) {
41
+ return ok(`${note}\n(${out.bytes > MAX_INLINE_IMAGE_BYTES ? '图片过大' : '当前运行时未提供图像数据'},只回路径;需要查看再用 read_image 读该文件)`)
42
+ }
43
+ return okBlocks([
44
+ { type: 'image', data: out.data, mimeType: out.mimeType || 'image/png' },
45
+ { type: 'text', text: `${note}\n上图即当前页面,直接据此判断,无需再调用 read_image。` },
46
+ ])
47
+ },
31
48
  }),
32
49
  ],
33
50
  })
@@ -17,14 +17,15 @@ export const sessionCapability = defineCapability({
17
17
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
18
18
  kind: 'read',
19
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)
20
+ handler: async (_args, ctx) => runTool(async () => {
21
+ const status = await ctx.engine.status()
22
+ const log = await ctx.engine.actionLog()
23
+ return JSON.stringify({ ...status, recentActions: log.slice(0, 8) }, null, 2)
23
24
  }),
24
25
  }),
25
26
  defineTool({
26
27
  name: 'browser_wait',
27
- description: '等待:ms=毫秒;selector=等元素出现(如 .result);都不给=等页面 load 完成。动作后页面还在加载/渲染时用它。',
28
+ description: '等待指定条件后返回**等待后的新快照**(不用再单独 browser_snapshot)。selector=等元素出现(首选,如 .result),ms=固定毫秒(上限 30000),都不给=等页面 load 完成。',
28
29
  inputSchema: {
29
30
  type: 'object',
30
31
  properties: {
@@ -38,7 +39,12 @@ export const sessionCapability = defineCapability({
38
39
  since: '1.0.0',
39
40
  handler: async (args, ctx) => runTool(async () => {
40
41
  const out = await ctx.engine.wait({ ms: args.ms, selector: args.selector, tab: args.tab })
41
- return `已等待完成(标签页 ${out.tab})`
42
+ const head = args.selector
43
+ ? `已等到元素 ${args.selector}`
44
+ : args.ms
45
+ ? `已等待 ${args.ms}ms`
46
+ : '已等到页面 load'
47
+ return `${head}(标签页 ${out.tab})——下面是等待后的快照${out.snapshot.authWall ? `\n⚠ ${out.snapshot.authWall}` : ''}\n\n${out.snapshot.text}`
42
48
  }),
43
49
  }),
44
50
  defineTool({
@@ -57,12 +63,12 @@ export const sessionCapability = defineCapability({
57
63
  handler: async (args, ctx) => runTool(async () => {
58
64
  const out = await ctx.engine.history({ action: args.action, tab: args.tab })
59
65
  const label = args.action === 'reload' ? '已重载' : args.action === 'forward' ? '已前进到' : '已后退到'
60
- return `${label} ${out.url}(标签页 ${out.tab})\n\n${out.snapshot.text}`
66
+ return `${label} ${out.url}(标签页 ${out.tab})${out.note ? `\n⚠ ${out.note}` : ''}\n\n${out.snapshot.text}`
61
67
  }),
62
68
  }),
63
69
  defineTool({
64
70
  name: 'browser_close',
65
- description: '关闭浏览器(所有标签页)。登录态与 profile 持久化,下次 navigate 自动重启浏览器并保留登录。任务结束或页面卡死时用它重置。',
71
+ description: '关闭浏览器(所有标签页)并清空标签页记录——这是一次显式重置:登录态保留在 profile,但下次 navigate 是干净浏览器(不恢复旧标签)。空闲回收/服务重启则会自动恢复上次标签页。任务结束或页面卡死时用它重置。',
66
72
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
67
73
  kind: 'control',
68
74
  since: '1.0.0',
@@ -23,7 +23,7 @@ export const snapshotCapability = defineCapability({
23
23
  since: '1.0.0',
24
24
  handler: async (args, ctx) => runTool(async () => {
25
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}`
26
+ return `# ${out.title || '(无标题)'}\n${out.url}(标签页 ${out.tab},${out.elements} 个元素${out.truncated ? ',已截断' : ''})${out.note ? `\n⚠ ${out.note}` : ''}\n\n${out.text}`
27
27
  }),
28
28
  }),
29
29
  ],
@@ -25,8 +25,8 @@ export const tabsCapability = defineCapability({
25
25
  since: '1.0.0',
26
26
  handler: async (args, ctx) => runTool(async () => {
27
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}`
28
+ if (args.action === 'new') return `已打开新标签页 ${out.tab}(${out.url || 'about:blank'})${out.note ? `\n⚠ ${out.note}` : ''}\n\n${out.snapshot.text}`
29
+ if (args.action === 'select') return `已切换到标签页 ${out.tab}${out.note ? `\n⚠ ${out.note}` : ''}\n\n${out.snapshot.text}`
30
30
  if (args.action === 'close') return `已关闭标签页 ${out.closed},剩余 ${out.tabs.length} 个`
31
31
  return JSON.stringify(out, null, 2)
32
32
  }),
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 能力声明 DSL:统一来自 dsh-tool-host 公共插件。
2
+ * 能力声明 DSL:统一来自 @capyclaw/tool-host 公共插件。
3
3
  * 保留此文件作为稳定 import 路径,capabilities/* 不需要改。
4
4
  */
5
5
  export { defineTool, defineCapability } from '../../shared/tool-host.mjs'
@@ -6,6 +6,14 @@ export function ok(text) {
6
6
  return { content: [{ type: 'text', text }], isError: false }
7
7
  }
8
8
 
9
+ /**
10
+ * 富内容成功结果(文本 + 图片等 MCP 内容块,按原顺序透传给宿主)。
11
+ * 图片必须是 canonical base64(无换行),mimeType 限 PNG/JPEG/WebP/GIF。
12
+ */
13
+ export function okBlocks(blocks) {
14
+ return { content: Array.isArray(blocks) ? blocks : [], isError: false }
15
+ }
16
+
9
17
  export function fail(error) {
10
18
  const code = error?.code ? `[${error.code}] ` : ''
11
19
  const hint = error?.hint ? `\n提示:${error.hint}` : ''
@@ -2,12 +2,15 @@
2
2
  * 内核端口:能力模块唯一允许接触的 I/O 面。
3
3
  *
4
4
  * engine —— 浏览器引擎控制器(lib 侧 src/mcp/engine.mjs;relay 启动后
5
- * setEngine 绑定实例,能力经 ctx.engine.* 调用;模块级 registry
6
- * 在未绑定时调用会得到结构化 ENGINE_UNBOUND 错误)。
5
+ * setEngine 绑定「实例」或「解析器函数」,能力经 ctx.engine.* 调用;
6
+ * 模块级 registry 在未绑定时调用会得到结构化 ENGINE_UNBOUND 错误)。
7
+ * F2 每会话隔离:relay 绑定的是解析器 () => sessionEngines.current(),
8
+ * 每次调用现场按当前会话(ALS)解析到那个会话自己的引擎——所以包装是
9
+ * async 的,能力侧统一 await ctx.engine.*(同步方法也经此异步化)。
7
10
  * server —— relay 侧注入的工作台地址(capabilities 报告用)。
8
11
  */
9
12
  const ENGINE_METHODS = [
10
- 'navigate', 'snapshot', 'click', 'fill', 'press', 'select', 'scroll',
13
+ 'navigate', 'snapshot', 'click', 'fill', 'press', 'select', 'scroll', 'act', 'drag',
11
14
  'wait', 'history', 'tabsAction', 'screenshot', 'screenshotBuffer',
12
15
  'evaluate', 'close', 'status', 'actionLog',
13
16
  ]
@@ -15,7 +18,7 @@ const ENGINE_METHODS = [
15
18
  let currentEngine = null
16
19
  let serverUrl = ''
17
20
 
18
- /** relay 绑定引擎实例(工具面在 relay 进程内运行)。 */
21
+ /** relay 绑定引擎:实例(旧单引擎形态)或解析器函数(F2 每会话,返回引擎或 Promise<引擎>)。 */
19
22
  export function setEngine(engine) {
20
23
  currentEngine = engine || null
21
24
  }
@@ -33,14 +36,16 @@ export function createKernelPorts({ serverBaseUrl = '' } = {}) {
33
36
  const base = serverBaseUrl || serverUrl
34
37
  const engine = {}
35
38
  for (const method of ENGINE_METHODS) {
36
- engine[method] = (...args) => {
37
- if (!currentEngine || typeof currentEngine[method] !== 'function') {
39
+ engine[method] = async (...args) => {
40
+ /* F2:currentEngine 可以是解析器函数(每会话现场解析),也可以是实例(兼容旧形态)。 */
41
+ const eng = typeof currentEngine === 'function' ? await currentEngine() : currentEngine
42
+ if (!eng || typeof eng[method] !== 'function') {
38
43
  throw Object.assign(new Error('引擎未绑定(relay 未完成装配)'), {
39
44
  code: 'ENGINE_UNBOUND',
40
45
  hint: '该调用应经 relay 的 /mcp 进入;独立 import 工具面时没有引擎实例。',
41
46
  })
42
47
  }
43
- return currentEngine[method](...args)
48
+ return eng[method](...args)
44
49
  }
45
50
  }
46
51
  return {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 能力注册表:通用实现来自 dsh-tool-host;本文件只注入 Browser 的内核端口与契约报告。
2
+ * 能力注册表:通用实现来自 @capyclaw/tool-host;本文件只注入 Browser 的内核端口与契约报告。
3
3
  */
4
4
  import { createRegistry as createBaseRegistry } from '../../shared/tool-host.mjs'
5
5
  import { createKernelPorts, KERNEL_PORT_NAMES } from './ports.mjs'
@@ -0,0 +1,305 @@
1
+ /**
2
+ * B 段提供的运行时框架:工作台 relay 的骨架。
3
+ *
4
+ * 这个文件由 build/bridge-build.mjs 从本目录拷进每个包的 server/workbench-framework.mjs。
5
+ * A 段(projects/<id>/src)只写业务钩子,不再自己拼 HTTP/MCP/锁/发现/独立入口。
6
+ *
7
+ * 框架职责(A 不再考虑):
8
+ * - serviceHost / 内置 createServiceApp 的选择与降级
9
+ * - 端口复用、单实例锁、优雅关闭、请求超时
10
+ * - MCP Streamable HTTP handler 装配与契约拒绝
11
+ * - 对象仓库(/assets)兜底
12
+ * - bridge.json 发现文件写入与清理
13
+ * - 独立运行入口(node server/relay.mjs --port --dir)
14
+ *
15
+ * A 段职责(全部是业务决策):
16
+ * prepare / createStore / routes / health / metrics / tools / instructions / getTuning
17
+ *
18
+ * 两种承载形态,都由框架决定,A 段不选端口:
19
+ * embedded(默认,DSH 宿主进程内)—— 传 `webServer`,应用挂到宿主 HTTP 路由的
20
+ * 前缀下(默认 `/capyclaw/<id>`),**不监听任何端口**,生命周期随 DSH。
21
+ * standalone(仅开发/测试)—— 没传 `webServer` 时按 `port` 自己监听 loopback。
22
+ *
23
+ * 窗口不在这里:桌面窗口是基建能力(@capyclaw/portal-hud 主区舞台)。workbench
24
+ * 只提供页面,就绪时把编辑地址记进活动台账;开不开窗由舞台的内容闸与链接拦截决定。
25
+ */
26
+ import fs from 'node:fs'
27
+ import os from 'node:os'
28
+ import path from 'node:path'
29
+ import { fileURLToPath } from 'node:url'
30
+
31
+ const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
32
+
33
+ /**
34
+ * 返回与历史签名兼容的 startRelay。
35
+ *
36
+ * spec:
37
+ * id / title / packageVersion / contractVersion
38
+ * port / basePath / homeEnv / defaultHome
39
+ * getTuning() 调优参数(A 的业务模块;缺省用框架默认值)
40
+ * contract { version, inspect(dir, version), describe(state) }
41
+ * createStore({ hostDir, backend, packageDir }) => store
42
+ * createAssetStore({ hostDir }) => assetStore | null
43
+ * prepare(ctx) => 额外业务资源(例如浏览器引擎),合并进 ctx
44
+ * routes(ctx) => route[](业务路由,按声明顺序挂载)
45
+ * health(ctx) / metrics(ctx) 业务健康与指标
46
+ * tools(ctx) => { TOOLS, TOOL_IMPL, CAPABILITIES, exemptTool? }
47
+ * instructions(ctx) => string
48
+ * onListening(ctx, info, url) 监听后、装载工具前(设 URL 环境变量、崩溃恢复)
49
+ * resultExtras(ctx) 追加进返回对象的字段(历史形状兼容)
50
+ * beforeStop(ctx) 停服前的业务清理(例如关浏览器)
51
+ */
52
+ export function createWorkbench(spec) {
53
+ return async function startRelay(options = {}) {
54
+ const {
55
+ port = spec.port,
56
+ /* embedded 形态:宿主(DSH)把 HTTP 路由借给我们,不监听端口。 */
57
+ webServer = null,
58
+ mountPrefix = spec.mountPrefix || `/capyclaw/${spec.id}`,
59
+ hostDir: hostDirOption = null,
60
+ packageDir = spec.packageDir || PKG_ROOT,
61
+ scanLimit = 50,
62
+ lockFile,
63
+ strictPort = false,
64
+ allowReuse = true,
65
+ backend = null,
66
+ assetStore: givenAssetStore = null,
67
+ assetService = null,
68
+ capabilities = null,
69
+ serviceHost = null,
70
+ toolHost = null,
71
+ editorHost = null,
72
+ ...extra
73
+ } = options
74
+
75
+ /* 承载形态决定状态目录:embedded 归 DSH 的 `~/.dsh/workbenches/<id>`,
76
+ * standalone(开发/测试)沿用历史 `~/.dsh-<id>-bridge` 之类的位置。 */
77
+ const hostDir = hostDirOption
78
+ || (spec.homeEnv && process.env[spec.homeEnv])
79
+ || (webServer
80
+ ? path.join(os.homedir(), '.dsh', 'workbenches', spec.id)
81
+ : path.join(os.homedir(), spec.defaultHome || `.dsh-${spec.id}`))
82
+
83
+ const { createServiceApp } = await import('./shared/service-host.mjs')
84
+ const { createMcpHandler } = await import('./shared/kit/service/mcp-http.mjs')
85
+
86
+ const contractState = spec.contract
87
+ ? spec.contract.inspect(packageDir, spec.contract.version)
88
+ : { ok: true, checked: 0 }
89
+ if (!contractState.ok) {
90
+ console.error(`[${spec.id}] 契约快照不一致,工具调用将被拒绝:`, spec.contract.describe?.(contractState) || '')
91
+ }
92
+
93
+ const store = await spec.createStore({ hostDir, backend, packageDir })
94
+ let assetStore = givenAssetStore
95
+ if (!assetStore && !assetService && spec.createAssetStore) {
96
+ try {
97
+ assetStore = spec.createAssetStore({ hostDir })
98
+ } catch (error) {
99
+ console.error(`[${spec.id}] 对象仓库不可用(/assets 将返回 503):`, error.message)
100
+ }
101
+ }
102
+
103
+ const ctx = {
104
+ id: spec.id, hostDir, store, capabilities, contractState, packageDir,
105
+ serviceHost, toolHost, editorHost, assetService, ...extra,
106
+ }
107
+ Object.defineProperty(ctx, 'assetStore', { get: () => assetStore, enumerable: true })
108
+
109
+ /* 资源闭合:createStore/createAssetStore/prepare 都发生在 listen 之前。任何
110
+ * 「没进入正常服务」的路径(prepare 失败、listen 抛错、复用命中)都必须回收
111
+ * 已创建的资源——否则引擎/仓库泄漏在仍存活的进程里(reused 分支的 stop 是
112
+ * no-op,不会有人替它清理)。外部传入的 assetStore 不归本框架关。 */
113
+ let app
114
+ const closeCreatedResources = async (why) => {
115
+ try { if (spec.beforeStop) await spec.beforeStop(ctx) } catch (error) { console.error(`[${spec.id}] ${why}:beforeStop 失败`, error?.message || error) }
116
+ try { if (!givenAssetStore) await assetStore?.close?.() } catch (error) { console.error(`[${spec.id}] ${why}:assetStore 关闭失败`, error?.message || error) }
117
+ try { await store?.close?.() } catch (error) { console.error(`[${spec.id}] ${why}:store 关闭失败`, error?.message || error) }
118
+ try { await app?.close?.() } catch (error) { console.error(`[${spec.id}] ${why}:app 关闭失败`, error?.message || error) }
119
+ }
120
+
121
+ /* 业务资源准备(例如浏览器引擎、进程内 session 注入):失败即启动失败。 */
122
+ if (spec.prepare) {
123
+ try {
124
+ Object.assign(ctx, (await spec.prepare(ctx)) || {})
125
+ } catch (error) {
126
+ await closeCreatedResources('prepare 失败')
127
+ throw error
128
+ }
129
+ }
130
+
131
+ const createApp = serviceHost?.createApp ? (opts) => serviceHost.createApp(opts) : createServiceApp
132
+ /* 桥声明(来自 foundation declareBridge):对外暴露成 bridgeInfo,
133
+ * 供 suite 清单校验与巡检对齐「声明 vs 运行时」。 */
134
+ const bridgeInfo = spec.bridge
135
+ ? { id: spec.bridge.id, protocol: spec.bridge.protocol, model: spec.bridge.model || null, editor: spec.bridge.editor || 'required' }
136
+ : null
137
+ app = createApp({
138
+ id: spec.id,
139
+ title: spec.title,
140
+ version: spec.packageVersion,
141
+ contractVersion: spec.contractVersion,
142
+ health: () => ({
143
+ ...(bridgeInfo ? { bridgeInfo } : {}),
144
+ ...(spec.health ? spec.health(ctx) : {}),
145
+ contractsOk: contractState.ok,
146
+ contractsChecked: contractState.checked,
147
+ }),
148
+ metrics: () => (spec.metrics ? spec.metrics(ctx) : []),
149
+ })
150
+
151
+ /* routes 里可能要用 app 本身(例如公共 asset-service 的 mount)。 */
152
+ ctx.app = app
153
+ /* 挂载前缀必须在 route 工厂**之前**可见:稿件/图片路由会把给浏览器的媒体地址
154
+ * 拼成 `<mountPath><basePath>/media/<sha>`;embedded 下晚一步设,就会漏掉
155
+ * `/capyclaw/<ns>`,编辑器和导出取图全部 404(2026-11-10 实测)。 */
156
+ const embeddable = !!(webServer && typeof webServer.register === 'function')
157
+ ctx.mountPath = embeddable ? mountPrefix : ''
158
+ for (const route of spec.routes(ctx) || []) app.use(route)
159
+
160
+ const tuning = spec.getTuning ? spec.getTuning() : {}
161
+ let info
162
+ try {
163
+ info = embeddable
164
+ ? await app.listen({
165
+ webServer,
166
+ basePath: mountPrefix,
167
+ requestTimeoutMs: Number(tuning.httpRequestTimeoutMs) || 30000,
168
+ headersTimeoutMs: Number(tuning.httpHeadersTimeoutMs) || 10000,
169
+ keepAliveTimeoutMs: Number(tuning.httpKeepAliveTimeoutMs) || 5000,
170
+ })
171
+ : await app.listen({
172
+ port,
173
+ hostDir,
174
+ scanLimit,
175
+ lockFile: lockFile || path.join(hostDir, '.relay-instance.lock'),
176
+ strictPort,
177
+ allowReuse,
178
+ discoveryFile: '',
179
+ requestTimeoutMs: Number(tuning.httpRequestTimeoutMs) || 30000,
180
+ headersTimeoutMs: Number(tuning.httpHeadersTimeoutMs) || 10000,
181
+ keepAliveTimeoutMs: Number(tuning.httpKeepAliveTimeoutMs) || 5000,
182
+ })
183
+ } catch (error) {
184
+ /* listen 抛错(端口冲突/锁失败等)同样要回收已建的 store/引擎,
185
+ * 这里在下方 try 之外,旧代码会让它们永久泄漏。 */
186
+ await closeCreatedResources('listen 失败')
187
+ throw error
188
+ }
189
+
190
+ /* info.url 在 embedded 下已经是「origin + 挂载前缀」,standalone 下是 origin。
191
+ * 业务只认 ctx.editorUrl / ctx.url(接口基址),不需要知道端口或前缀。 */
192
+ const base = info.url
193
+ const url = `${base}${spec.basePath || ''}`
194
+ ctx.port = info.port
195
+ ctx.embedded = info.mode === 'embedded'
196
+ ctx.origin = info.mode === 'embedded' ? `http://127.0.0.1:${info.port}` : info.url
197
+ ctx.mountPath = info.mode === 'embedded' ? new URL(base).pathname.replace(/\/$/, '') : ''
198
+ ctx.editorUrl = `${base}/`
199
+ ctx.url = url
200
+
201
+ if (info.reused) {
202
+ /* 复用命中:本进程不提供服务,必须回收已创建的 store/引擎等资源,
203
+ * 否则它们泄漏在仍存活的进程里(下面的 stop 是 no-op,无人清理)。 */
204
+ await closeCreatedResources('复用既有实例')
205
+ return {
206
+ url,
207
+ editorUrl: ctx.editorUrl,
208
+ port: info.port,
209
+ mode: info.mode || 'standalone',
210
+ reused: true,
211
+ ...(spec.resultExtras ? spec.resultExtras(ctx) : {}),
212
+ stop: async () => {},
213
+ }
214
+ }
215
+
216
+ try {
217
+ /* 业务钩子:设置 URL 环境变量、崩溃恢复等(必须在工具装载之前)。 */
218
+ if (spec.onListening) await spec.onListening(ctx, info, url)
219
+
220
+ if (spec.tools) {
221
+ const registry = (await spec.tools(ctx)) || {}
222
+ const TOOLS = registry.TOOLS || []
223
+ ctx.tools = TOOLS
224
+ ctx.toolsRegistry = registry
225
+ const mcpHandler = createMcpHandler({
226
+ tools: TOOLS,
227
+ callTool: (name, args) => {
228
+ if (!contractState.ok && !registry.exemptTool?.(name)) {
229
+ throw new Error(
230
+ `契约快照与运行时 major 不一致,已拒绝 ${name}:` +
231
+ `${spec.contract.describe?.(contractState) || ''}。请重装/升级对应 suite 后重试。`,
232
+ )
233
+ }
234
+ const impl = registry.TOOL_IMPL[name]
235
+ if (!impl) throw new Error('未知工具: ' + name)
236
+ return impl(args)
237
+ },
238
+ serverInfo: { name: spec.id, version: spec.packageVersion },
239
+ instructions: spec.instructions ? spec.instructions(ctx) : undefined,
240
+ maxBodyBytes: Number(tuning.bodyLimitBytes) || 12 * 1024 * 1024,
241
+ maxBatch: Number(tuning.mcpBatchLimit) || 100,
242
+ })
243
+ ctx.getMcpHandler = () => mcpHandler
244
+ }
245
+
246
+ spec.onStarted?.({ url, port: info.port, hostDir, store, ctx })
247
+ /* 独立端口形态才写发现文件;embedded 的生命周期由宿主 ctx.effect 管。 */
248
+ if (!ctx.embedded) writeDiscovery(hostDir, spec.id, url, info.port)
249
+ return {
250
+ url,
251
+ editorUrl: ctx.editorUrl,
252
+ port: info.port,
253
+ mode: info.mode || 'standalone',
254
+ reused: false,
255
+ tools: ctx.toolsRegistry || null,
256
+ ...(spec.resultExtras ? spec.resultExtras(ctx) : {}),
257
+ stop: async () => {
258
+ if (!ctx.embedded) removeDiscovery(hostDir)
259
+ if (spec.beforeStop) await spec.beforeStop(ctx)
260
+ await info.stop()
261
+ },
262
+ }
263
+ } catch (error) {
264
+ try { if (!ctx.embedded) removeDiscovery(hostDir) } catch { /* 忽略 */ }
265
+ try { if (spec.beforeStop) await spec.beforeStop(ctx) } catch { /* 忽略 */ }
266
+ try { await info.stop() } catch { /* 忽略 */ }
267
+ throw error
268
+ }
269
+ }
270
+ }
271
+
272
+ /** 独立运行入口:node server/relay.mjs --port <n> --dir <hostDir>(符号链接安装下也判得准)。 */
273
+ export function runIfMain(moduleUrl, main) {
274
+ if (!process.argv[1]) return false
275
+ let isMain = false
276
+ try {
277
+ isMain = fs.realpathSync(path.resolve(process.argv[1])) === fileURLToPath(moduleUrl)
278
+ } catch {
279
+ isMain = path.resolve(process.argv[1]) === fileURLToPath(moduleUrl)
280
+ }
281
+ if (!isMain) return false
282
+ const arg = (flag, fallback) => {
283
+ const i = process.argv.indexOf(flag)
284
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback
285
+ }
286
+ main({ port: Number(arg('--port', undefined)) || undefined, dir: arg('--dir', undefined) })
287
+ return true
288
+ }
289
+
290
+ function writeDiscovery(hostDir, id, url, port) {
291
+ try {
292
+ fs.mkdirSync(hostDir, { recursive: true })
293
+ fs.writeFileSync(path.join(hostDir, 'bridge.json'), JSON.stringify({
294
+ bridge: id, url, port, pid: process.pid, updated: new Date().toISOString(),
295
+ }, null, 2))
296
+ } catch { /* 发现文件写失败不影响服务 */ }
297
+ }
298
+
299
+ function removeDiscovery(hostDir) {
300
+ const file = path.join(hostDir, 'bridge.json')
301
+ try {
302
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'))
303
+ if (data.pid === process.pid) fs.rmSync(file, { force: true })
304
+ } catch { /* 不存在或不是本进程写的 */ }
305
+ }