@capyclaw/browser-suite 0.2.37 → 0.2.38

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 (200) hide show
  1. package/composition.lock.json +5 -5
  2. package/contract/browser-contract.json +45 -19
  3. package/dsh-suite.json +6 -6
  4. package/node_modules/@capyclaw/asset-service/src/index.mjs +6 -1
  5. package/node_modules/@capyclaw/browser-skill-api/contract/browser-contract.json +45 -19
  6. package/node_modules/@capyclaw/browser-skill-api/skills/browser-api/references/tool-contract.md +1 -1
  7. package/node_modules/@capyclaw/browser-skill-browser/contract/browser-contract.json +45 -19
  8. package/node_modules/@capyclaw/browser-skill-ops/contract/browser-contract.json +45 -19
  9. package/node_modules/@capyclaw/browser-workbench/contract/browser-contract.json +45 -19
  10. package/node_modules/@capyclaw/browser-workbench/package.json +2 -2
  11. package/node_modules/@capyclaw/browser-workbench/server/contract.mjs +1 -1
  12. package/node_modules/@capyclaw/browser-workbench/server/embedded-host.mjs +10 -1
  13. package/node_modules/@capyclaw/browser-workbench/server/shared/SHARED_MANIFEST.json +1 -1
  14. package/node_modules/@capyclaw/browser-workbench/server/workbench-framework.mjs +34 -0
  15. package/node_modules/@capyclaw/foundation/abi/loader.mjs +8 -1
  16. package/node_modules/@capyclaw/foundation/abi/spec.mjs +5 -2
  17. package/node_modules/@capyclaw/foundation/abi/version.mjs +63 -5
  18. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +29 -2
  19. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +12 -2
  20. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +3 -82
  21. package/node_modules/@capyclaw/service-broker/lib/control.mjs +23 -7
  22. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +60 -6
  23. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +15 -2
  24. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +0 -50
  25. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +17 -5
  26. package/node_modules/@capyclaw/service-host/src/index.mjs +9 -1
  27. package/node_modules/@capyclaw/tool-host/dsh-suite.json +2 -2
  28. package/node_modules/@capyclaw/tool-host/lib/host.mjs +23 -4
  29. package/node_modules/@capyclaw/tool-host/package.json +1 -1
  30. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  31. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  32. package/node_modules/@capyclaw/tool-host/src/index.mjs +45 -14
  33. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +204 -0
  34. package/node_modules/playwright/LICENSE +202 -0
  35. package/node_modules/playwright/NOTICE +5 -0
  36. package/node_modules/playwright/README.md +318 -0
  37. package/node_modules/playwright/ThirdPartyNotices.txt +14 -0
  38. package/node_modules/playwright/cli.js +19 -0
  39. package/node_modules/playwright/index.d.ts +17 -0
  40. package/node_modules/playwright/index.js +17 -0
  41. package/node_modules/playwright/index.mjs +18 -0
  42. package/node_modules/playwright/lib/agents/agentParser.js +89 -0
  43. package/node_modules/playwright/lib/agents/copilot-setup-steps.yml +34 -0
  44. package/node_modules/playwright/lib/agents/generateAgents.js +395 -0
  45. package/node_modules/playwright/lib/agents/playwright-test-coverage.prompt.md +31 -0
  46. package/node_modules/playwright/lib/agents/playwright-test-generate.prompt.md +8 -0
  47. package/node_modules/playwright/lib/agents/playwright-test-generator.agent.md +88 -0
  48. package/node_modules/playwright/lib/agents/playwright-test-heal.prompt.md +6 -0
  49. package/node_modules/playwright/lib/agents/playwright-test-healer.agent.md +56 -0
  50. package/node_modules/playwright/lib/agents/playwright-test-plan.prompt.md +9 -0
  51. package/node_modules/playwright/lib/agents/playwright-test-planner.agent.md +74 -0
  52. package/node_modules/playwright/lib/cli/reportActions.js +78 -0
  53. package/node_modules/playwright/lib/cli/testActions.js +217 -0
  54. package/node_modules/playwright/lib/common/index.js +2937 -0
  55. package/node_modules/playwright/lib/common/index.js.txt +33 -0
  56. package/node_modules/playwright/lib/errorContext.js +129 -0
  57. package/node_modules/playwright/lib/globals.js +58 -0
  58. package/node_modules/playwright/lib/index.js +827 -0
  59. package/node_modules/playwright/lib/isomorphic.js +260 -0
  60. package/node_modules/playwright/lib/isomorphic.js.txt +9 -0
  61. package/node_modules/playwright/lib/loader/loaderProcessEntry.js +34 -0
  62. package/node_modules/playwright/lib/loader/loaderProcessEntry.js.txt +9 -0
  63. package/node_modules/playwright/lib/matchers/expect.js +13496 -0
  64. package/node_modules/playwright/lib/matchers/expect.js.LICENSE +640 -0
  65. package/node_modules/playwright/lib/matchers/expect.js.txt +67 -0
  66. package/node_modules/playwright/lib/package.js +47 -0
  67. package/node_modules/playwright/lib/program.js +242 -0
  68. package/node_modules/playwright/lib/runner/index.js +8721 -0
  69. package/node_modules/playwright/lib/runner/index.js.txt +62 -0
  70. package/node_modules/playwright/lib/transform/babelBundle.js +72490 -0
  71. package/node_modules/playwright/lib/transform/babelBundle.js.LICENSE +2384 -0
  72. package/node_modules/playwright/lib/transform/babelBundle.js.txt +328 -0
  73. package/node_modules/playwright/lib/transform/esmLoader.js +8066 -0
  74. package/node_modules/playwright/lib/transform/esmLoader.js.LICENSE +355 -0
  75. package/node_modules/playwright/lib/transform/esmLoader.js.txt +60 -0
  76. package/node_modules/playwright/lib/util.js +373 -0
  77. package/node_modules/playwright/lib/worker/workerProcessEntry.js +1860 -0
  78. package/node_modules/playwright/lib/worker/workerProcessEntry.js.txt +19 -0
  79. package/node_modules/playwright/package.json +50 -0
  80. package/node_modules/playwright/test.d.ts +18 -0
  81. package/node_modules/playwright/test.js +24 -0
  82. package/node_modules/playwright/test.mjs +35 -0
  83. package/node_modules/playwright/types/test.d.ts +11191 -0
  84. package/node_modules/playwright/types/testReporter.d.ts +950 -0
  85. package/node_modules/playwright-core/LICENSE +202 -0
  86. package/node_modules/playwright-core/NOTICE +5 -0
  87. package/node_modules/playwright-core/README.md +3 -0
  88. package/node_modules/playwright-core/ThirdPartyNotices.txt +13 -0
  89. package/node_modules/playwright-core/bin/install_media_pack.ps1 +5 -0
  90. package/node_modules/playwright-core/bin/install_webkit_wsl.ps1 +33 -0
  91. package/node_modules/playwright-core/bin/reinstall_chrome_beta_linux.sh +42 -0
  92. package/node_modules/playwright-core/bin/reinstall_chrome_beta_mac.sh +13 -0
  93. package/node_modules/playwright-core/bin/reinstall_chrome_beta_win.ps1 +24 -0
  94. package/node_modules/playwright-core/bin/reinstall_chrome_stable_linux.sh +42 -0
  95. package/node_modules/playwright-core/bin/reinstall_chrome_stable_mac.sh +12 -0
  96. package/node_modules/playwright-core/bin/reinstall_chrome_stable_win.ps1 +24 -0
  97. package/node_modules/playwright-core/bin/reinstall_msedge_beta_linux.sh +48 -0
  98. package/node_modules/playwright-core/bin/reinstall_msedge_beta_mac.sh +11 -0
  99. package/node_modules/playwright-core/bin/reinstall_msedge_beta_win.ps1 +23 -0
  100. package/node_modules/playwright-core/bin/reinstall_msedge_dev_linux.sh +48 -0
  101. package/node_modules/playwright-core/bin/reinstall_msedge_dev_mac.sh +11 -0
  102. package/node_modules/playwright-core/bin/reinstall_msedge_dev_win.ps1 +23 -0
  103. package/node_modules/playwright-core/bin/reinstall_msedge_stable_linux.sh +48 -0
  104. package/node_modules/playwright-core/bin/reinstall_msedge_stable_mac.sh +11 -0
  105. package/node_modules/playwright-core/bin/reinstall_msedge_stable_win.ps1 +24 -0
  106. package/node_modules/playwright-core/browsers.json +52 -0
  107. package/node_modules/playwright-core/cli.js +22 -0
  108. package/node_modules/playwright-core/index.d.ts +17 -0
  109. package/node_modules/playwright-core/index.js +17 -0
  110. package/node_modules/playwright-core/index.mjs +28 -0
  111. package/node_modules/playwright-core/lib/bootstrap.js +149 -0
  112. package/node_modules/playwright-core/lib/coreBundle.js +78041 -0
  113. package/node_modules/playwright-core/lib/entry/cliDaemon.js +5 -0
  114. package/node_modules/playwright-core/lib/entry/dashboardApp.js +3 -0
  115. package/node_modules/playwright-core/lib/entry/mcp.js +10 -0
  116. package/node_modules/playwright-core/lib/entry/oopBrowserDownload.js +3 -0
  117. package/node_modules/playwright-core/lib/package.js +50 -0
  118. package/node_modules/playwright-core/lib/server/chromium/appIcon.png +0 -0
  119. package/node_modules/playwright-core/lib/server/electron/loader.js +123 -0
  120. package/node_modules/playwright-core/lib/serverRegistry.js +1939 -0
  121. package/node_modules/playwright-core/lib/serverRegistry.js.LICENSE +65 -0
  122. package/node_modules/playwright-core/lib/tools/cli-client/channelSessions.js +141 -0
  123. package/node_modules/playwright-core/lib/tools/cli-client/cli.js +7 -0
  124. package/node_modules/playwright-core/lib/tools/cli-client/help.json +808 -0
  125. package/node_modules/playwright-core/lib/tools/cli-client/minimist.js +128 -0
  126. package/node_modules/playwright-core/lib/tools/cli-client/output.js +352 -0
  127. package/node_modules/playwright-core/lib/tools/cli-client/program.js +422 -0
  128. package/node_modules/playwright-core/lib/tools/cli-client/registry.js +180 -0
  129. package/node_modules/playwright-core/lib/tools/cli-client/session.js +261 -0
  130. package/node_modules/playwright-core/lib/tools/dashboard/appIcon.png +0 -0
  131. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/SKILL.md +493 -0
  132. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/element-attributes.md +23 -0
  133. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/playwright-tests.md +39 -0
  134. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/pr-attachments.md +60 -0
  135. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/request-mocking.md +87 -0
  136. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/running-code.md +245 -0
  137. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/session-management.md +227 -0
  138. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/storage-state.md +275 -0
  139. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/test-generation.md +433 -0
  140. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/tracing.md +139 -0
  141. package/node_modules/playwright-core/lib/tools/skills/playwright-cli/references/video-recording.md +216 -0
  142. package/node_modules/playwright-core/lib/tools/skills/playwright-component-testing/SKILL.md +136 -0
  143. package/node_modules/playwright-core/lib/tools/skills/playwright-component-testing/references/gallery-spec.md +144 -0
  144. package/node_modules/playwright-core/lib/tools/skills/playwright-component-testing/references/migration.md +89 -0
  145. package/node_modules/playwright-core/lib/tools/skills/playwright-component-testing/references/react.md +69 -0
  146. package/node_modules/playwright-core/lib/tools/skills/playwright-component-testing/references/typing.md +173 -0
  147. package/node_modules/playwright-core/lib/tools/skills/playwright-component-testing/references/vue.md +77 -0
  148. package/node_modules/playwright-core/lib/tools/skills/playwright-trace/SKILL.md +174 -0
  149. package/node_modules/playwright-core/lib/tools/utils/extension.js +112 -0
  150. package/node_modules/playwright-core/lib/tools/utils/socketConnection.js +108 -0
  151. package/node_modules/playwright-core/lib/utilsBundle.js +86078 -0
  152. package/node_modules/playwright-core/lib/utilsBundle.js.LICENSE +1890 -0
  153. package/node_modules/playwright-core/lib/vite/dashboard/assets/codeMirrorModule--QdMvsKi.css +1 -0
  154. package/node_modules/playwright-core/lib/vite/dashboard/assets/codeMirrorModule-CQ8RZGBm.js +32 -0
  155. package/node_modules/playwright-core/lib/vite/dashboard/assets/codicon-DCmgc-ay.ttf +0 -0
  156. package/node_modules/playwright-core/lib/vite/dashboard/assets/firefox-1bWoP6pv.svg +1 -0
  157. package/node_modules/playwright-core/lib/vite/dashboard/assets/firefox-beta-k3eOH_eK.svg +1 -0
  158. package/node_modules/playwright-core/lib/vite/dashboard/assets/firefox-nightly-Cp5nfeDT.svg +1 -0
  159. package/node_modules/playwright-core/lib/vite/dashboard/assets/index-AwgwcYie.css +1 -0
  160. package/node_modules/playwright-core/lib/vite/dashboard/assets/index-hRvO4yU2.js +12 -0
  161. package/node_modules/playwright-core/lib/vite/dashboard/assets/safari-na3_-uQk.svg +1 -0
  162. package/node_modules/playwright-core/lib/vite/dashboard/index.html +29 -0
  163. package/node_modules/playwright-core/lib/vite/dashboard/playwright-logo.svg +24 -0
  164. package/node_modules/playwright-core/lib/vite/htmlReport/index.html +16 -0
  165. package/node_modules/playwright-core/lib/vite/htmlReport/report.css +2 -0
  166. package/node_modules/playwright-core/lib/vite/htmlReport/report.js +32 -0
  167. package/node_modules/playwright-core/lib/vite/recorder/assets/codeMirrorModule--QdMvsKi.css +1 -0
  168. package/node_modules/playwright-core/lib/vite/recorder/assets/codeMirrorModule-DK72OMRi.js +32 -0
  169. package/node_modules/playwright-core/lib/vite/recorder/assets/codicon-DCmgc-ay.ttf +0 -0
  170. package/node_modules/playwright-core/lib/vite/recorder/assets/index-BZpYJZ-P.css +1 -0
  171. package/node_modules/playwright-core/lib/vite/recorder/assets/index-Cn0mmDuv.js +129 -0
  172. package/node_modules/playwright-core/lib/vite/recorder/index.html +29 -0
  173. package/node_modules/playwright-core/lib/vite/recorder/playwright-logo.svg +9 -0
  174. package/node_modules/playwright-core/lib/vite/traceViewer/assets/codeMirrorModule-BEB2e8M3.js +32 -0
  175. package/node_modules/playwright-core/lib/vite/traceViewer/assets/defaultSettingsView-D-g2vrvf.js +184 -0
  176. package/node_modules/playwright-core/lib/vite/traceViewer/assets/urlMatch-L3liM589.js +1 -0
  177. package/node_modules/playwright-core/lib/vite/traceViewer/assets/xtermModule-B794rD2Z.js +7 -0
  178. package/node_modules/playwright-core/lib/vite/traceViewer/codeMirrorModule.-QdMvsKi.css +1 -0
  179. package/node_modules/playwright-core/lib/vite/traceViewer/codicon.DCmgc-ay.ttf +0 -0
  180. package/node_modules/playwright-core/lib/vite/traceViewer/defaultSettingsView.C8BeHuxd.css +1 -0
  181. package/node_modules/playwright-core/lib/vite/traceViewer/index.B_TqY17P.css +1 -0
  182. package/node_modules/playwright-core/lib/vite/traceViewer/index.html +44 -0
  183. package/node_modules/playwright-core/lib/vite/traceViewer/index.oNry3Hjv.js +1 -0
  184. package/node_modules/playwright-core/lib/vite/traceViewer/manifest.webmanifest +16 -0
  185. package/node_modules/playwright-core/lib/vite/traceViewer/playwright-logo.svg +9 -0
  186. package/node_modules/playwright-core/lib/vite/traceViewer/snapshot.B_Jk1wbt.js +1 -0
  187. package/node_modules/playwright-core/lib/vite/traceViewer/snapshot.html +10 -0
  188. package/node_modules/playwright-core/lib/vite/traceViewer/sw.bundle.js +4 -0
  189. package/node_modules/playwright-core/lib/vite/traceViewer/uiMode.CYwC_gH1.js +5 -0
  190. package/node_modules/playwright-core/lib/vite/traceViewer/uiMode.CyMfwkXJ.css +1 -0
  191. package/node_modules/playwright-core/lib/vite/traceViewer/uiMode.html +18 -0
  192. package/node_modules/playwright-core/lib/vite/traceViewer/xtermModule.kHJ-D0s7.css +1 -0
  193. package/node_modules/playwright-core/lib/webp_codec.LICENSE +173 -0
  194. package/node_modules/playwright-core/lib/webp_codec.wasm +0 -0
  195. package/node_modules/playwright-core/lib/xdg-open +1267 -0
  196. package/node_modules/playwright-core/package.json +34 -0
  197. package/node_modules/playwright-core/types/protocol.d.ts +24776 -0
  198. package/node_modules/playwright-core/types/structs.d.ts +52 -0
  199. package/node_modules/playwright-core/types/types.d.ts +27167 -0
  200. package/package.json +6 -5
@@ -6,8 +6,9 @@
6
6
  */
7
7
  import { tuning } from '../tuning.mjs'
8
8
 
9
- const DEFAULT_TTL = 15 // 秒
10
- const DEFAULT_HEARTBEAT = 3 // 秒(心跳间隔应小于 TTL)
9
+ /* 与文档 owner 租约(document-workbench OWNER_TTL)对齐为 10s:
10
+ * 两条租约线共用「心跳 3s、TTL 10s」的并发协议,避免编辑器判活比文档慢半拍。 */
11
+ const DEFAULT_TTL = 10 // 秒
11
12
 
12
13
  /**
13
14
  * 创建编辑器租约仲裁器。
@@ -57,83 +58,3 @@ export function createEditorLease(opts = {}) {
57
58
  },
58
59
  }
59
60
  }
60
-
61
- /**
62
- * 编辑器端自动挂接循环。
63
- * 首次 claim 强制抢占(后打开者赢),之后静默心跳。
64
- * @param {{
65
- * clientId: string,
66
- * claim: (force: boolean) => Promise<boolean>,
67
- * release?: () => void,
68
- * onActive?: () => void,
69
- * onStandby?: () => void,
70
- * retryMs?: number,
71
- * heartbeatMs?: number,
72
- * setInterval?: (cb: () => void) => any,
73
- * clearInterval?: (handle: any) => void
74
- * }} o
75
- */
76
- export function startAutoAttach(o) {
77
- if (!o || !o.clientId) throw new Error('startAutoAttach: clientId 必填')
78
- if (typeof o.claim !== 'function') throw new Error('startAutoAttach: claim 必须是函数')
79
-
80
- const retryMs = o.retryMs || 1000
81
- const heartbeatMs = o.heartbeatMs || DEFAULT_HEARTBEAT * 1000
82
- const setI = o.setInterval || ((cb) => setInterval(cb, heartbeatMs))
83
- const clearI = o.clearInterval || ((handle) => clearInterval(handle))
84
-
85
- let active = false
86
- let heartbeat = null
87
- let disposed = false
88
-
89
- async function tryClaim(force) {
90
- try {
91
- return await o.claim(force)
92
- } catch {
93
- return false
94
- }
95
- }
96
-
97
- function goActive() {
98
- if (active) return
99
- active = true
100
- try { o.onActive && o.onActive() } catch { /* 用户回调失败不阻塞挂接 */ }
101
- heartbeat = setI(async () => {
102
- if (disposed) return
103
- const ok = await tryClaim(false)
104
- if (!ok) goStandby()
105
- })
106
- }
107
-
108
- function goStandby() {
109
- if (!active) return
110
- active = false
111
- if (heartbeat != null) {
112
- clearI(heartbeat)
113
- heartbeat = null
114
- }
115
- try { o.onStandby && o.onStandby() } catch { /* 静默 */ }
116
- }
117
-
118
- ;(async () => {
119
- let first = true
120
- while (!disposed) {
121
- const ok = await tryClaim(first)
122
- first = false
123
- if (ok) {
124
- goActive()
125
- return
126
- }
127
- await new Promise((resolve) => setTimeout(resolve, retryMs))
128
- }
129
- })()
130
-
131
- return {
132
- get active() { return active },
133
- dispose() {
134
- disposed = true
135
- goStandby()
136
- try { o.release && o.release() } catch { /* 释放失败不阻塞退出 */ }
137
- },
138
- }
139
- }
@@ -61,21 +61,36 @@ function tokenMatches(expected, actual) {
61
61
 
62
62
  const isLoopback = isLoopbackAddress
63
63
 
64
- function jsonBody(req, limit = 8 * 1024 * 1024) {
64
+ function jsonBody(req, res, limit = 8 * 1024 * 1024) {
65
65
  return new Promise((resolve, reject) => {
66
66
  let size = 0
67
+ let aborted = false
67
68
  const chunks = []
68
69
  req.on('data', (chunk) => {
70
+ if (aborted) return
69
71
  size += chunk.length
70
- if (size > limit) { reject(new Error('body too large')); req.destroy(); return }
72
+ if (size > limit) {
73
+ /* 先回 413 再处理连接:客户端要能区分「体太大」与「连接被莫名掐断」。
74
+ * 不能立刻 destroy——响应字节还没刷出去就断连,客户端只会看到 ECONNRESET。
75
+ * 这里回完 413 后把剩余请求体排空丢弃(有 8MB 上限兜底,量可控),
76
+ * 让响应干净送达;病态超长上传由服务器级请求超时兜底。 */
77
+ aborted = true
78
+ if (res && !res.headersSent && !res.writableEnded) {
79
+ send(res, 413, { ok: false, error: `请求体超过上限 ${limit} 字节` })
80
+ }
81
+ reject(new Error('body too large'))
82
+ req.resume()
83
+ return
84
+ }
71
85
  chunks.push(chunk)
72
86
  })
73
87
  req.on('end', () => {
88
+ if (aborted) return
74
89
  const raw = Buffer.concat(chunks).toString('utf8')
75
90
  if (!raw) return resolve({})
76
91
  try { resolve(JSON.parse(raw)) } catch { reject(new Error('bad json')) }
77
92
  })
78
- req.on('error', reject)
93
+ req.on('error', (err) => { if (!aborted) reject(err) })
79
94
  })
80
95
  }
81
96
 
@@ -132,13 +147,13 @@ export function createControlServer(engine, options = {}) {
132
147
  }
133
148
 
134
149
  if (route === 'POST /control/apply') {
135
- const body = await jsonBody(req)
150
+ const body = await jsonBody(req, res)
136
151
  const result = await engine.apply(body.commands || [], { waitMs: body.waitMs })
137
152
  return send(res, result.ok ? 200 : 207, result)
138
153
  }
139
154
 
140
155
  if (route === 'POST /control/start') {
141
- const body = await jsonBody(req)
156
+ const body = await jsonBody(req, res)
142
157
  let spec = body.service
143
158
  if (!spec && body.id && manifestPath && existsSync(manifestPath)) {
144
159
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
@@ -170,7 +185,7 @@ export function createControlServer(engine, options = {}) {
170
185
  }
171
186
 
172
187
  if (route === 'POST /control/stop') {
173
- const body = await jsonBody(req)
188
+ const body = await jsonBody(req, res)
174
189
  if (!body.id) return send(res, 400, { ok: false, error: '缺 id' })
175
190
  return send(res, 200, await engine.stop(body.id))
176
191
  }
@@ -183,7 +198,8 @@ export function createControlServer(engine, options = {}) {
183
198
 
184
199
  send(res, 404, { ok: false, error: `未知端点 ${route}` })
185
200
  } catch (err) {
186
- send(res, 400, { ok: false, error: err.message })
201
+ /* jsonBody 超限时已回过 413 并断连,不能再往已结束的响应上写。 */
202
+ if (!res.headersSent && !res.writableEnded) send(res, 400, { ok: false, error: err.message })
187
203
  }
188
204
  })
189
205
  // 供宿主打日志用:只暴露位置,不暴露 token 本身。
@@ -186,6 +186,10 @@ export class ServiceEngine {
186
186
  this._unhealthy = new Map()
187
187
  // 深探节流:id → 上次健康/工具探测时间。
188
188
  this._lastProbe = new Map()
189
+ // 重启退避:id → 上次自动重启尝试时间(崩溃循环不再每 2s 硬拉一次)。
190
+ this._lastRestart = new Map()
191
+ // error 态恢复:id → { count, lastAt }(冷却指数翻倍,不再永久移出扫描)。
192
+ this._errorRetries = new Map()
189
193
  // broker 自身的创建身份在本进程生命周期内不变;Windows 上 marker() 约 900ms,
190
194
  // 每次 up 重算会白烧近 1 秒。null 时不缓存(瞬时查询失败可重试)。
191
195
  this._brokerMarker = null
@@ -963,9 +967,10 @@ export class ServiceEngine {
963
967
  maxUnhealthy = 3,
964
968
  requireTools = true,
965
969
  probeEveryMs = 15000,
970
+ errorRetryMs = 300000,
966
971
  } = {}) {
967
972
  if (this._guardTimer) return
968
- this._guardConfig = { maxConsecutive, maxUnhealthy, requireTools, probeEveryMs }
973
+ this._guardConfig = { maxConsecutive, maxUnhealthy, requireTools, probeEveryMs, errorRetryMs }
969
974
  this._guardTimer = setInterval(() => {
970
975
  if (this._stopping || this._sweeping) return
971
976
  this._sweeping = true
@@ -1048,6 +1053,13 @@ export class ServiceEngine {
1048
1053
  cur[row.id] = { ...current, state: 'error', error: message }
1049
1054
  await this._saveRegistry(cur)
1050
1055
  })
1056
+ /* 冷却从「进入 error 态」起算,而不是从恢复尝试起算:否则 breaker 触发前的
1057
+ * 最后一次重启时间会被当成冷却起点,errorRetryMs 短于崩溃循环时长时,
1058
+ * 行刚变 error 就立刻被重试,冷却形同虚设。仅状态真的翻转时登记。 */
1059
+ const after = (await this._loadRegistry())[row.id]
1060
+ if (after?.state === 'error' && after.pid === row.pid && after.startedAt === row.startedAt) {
1061
+ this._errorRetries.set(row.id, { count: 0, lastAt: Date.now() })
1062
+ }
1051
1063
  this.log(`✗ ${row.id} ${message}`)
1052
1064
  }
1053
1065
 
@@ -1058,7 +1070,7 @@ export class ServiceEngine {
1058
1070
  * 孤儿行)。只看 _owned 是历史故障的根因:服务被外部杀掉后行还在、_owned 里
1059
1071
  * 没有它,于是 2s 一轮的守护永远跳过它,注册表一直写着 running 的假状态。 */
1060
1072
  const rows = Object.values(services).filter((row) =>
1061
- row.keepAlive && row.state === 'running'
1073
+ row.keepAlive && (row.state === 'running' || row.state === 'error')
1062
1074
  && (this._owned.has(row.id) || this._lastSpecs.has(row.id)))
1063
1075
  /* 并行探测:一个服务探测慢/超时不能拖住其他服务的巡检。 */
1064
1076
  await Promise.all(rows.map((row) => this._sweepOne(row, maxConsecutive).catch(() => {})))
@@ -1066,8 +1078,12 @@ export class ServiceEngine {
1066
1078
  }
1067
1079
 
1068
1080
  async _sweepOne(row, maxConsecutive) {
1081
+ /* error 态不是终点:带冷却地重试(见 _recoverError),不再永久移出扫描。 */
1082
+ if (row.state === 'error') return this._recoverError(row)
1069
1083
  if (pidAlive(row.pid)) {
1070
- this._guardFailures.delete(row.id)
1084
+ /* 注意:这里**不能**无条件清 _guardFailures——进程只要活过一个巡检间隔
1085
+ * 就把计数清零,「起-死-起」崩溃循环(活得比巡检间隔长)永远打不满熔断,
1086
+ * 变成无限重试。计数只在下方「稳定跑过一分钟」或手动 up 成功时翻篇。 */
1071
1087
  /* 分两档节奏:
1072
1088
  * - 存活检查每一轮都做(默认 2s 一轮)→ 进程一死,2s 内就重启;
1073
1089
  * - 健康/工具深探按 probeEveryMs(默认 15s)做一次,避免频繁打 HTTP。
@@ -1082,7 +1098,11 @@ export class ServiceEngine {
1082
1098
  /* "连续"重启次数:稳定跑过一分钟才算翻篇,避免“起-死-起”抖动
1083
1099
  * 每次都把计数清零,最后无限重试。 */
1084
1100
  const startedAt = Date.parse(row.startedAt || '') || 0
1085
- if (startedAt && Date.now() - startedAt > 60_000) this._guardFailures.delete(row.id)
1101
+ if (startedAt && Date.now() - startedAt > 60_000) {
1102
+ this._guardFailures.delete(row.id)
1103
+ this._errorRetries.delete(row.id)
1104
+ this._lastRestart.delete(row.id)
1105
+ }
1086
1106
  return
1087
1107
  }
1088
1108
  const count = (this._unhealthy.get(row.id) || 0) + 1
@@ -1137,10 +1157,18 @@ export class ServiceEngine {
1137
1157
  const failures = this._guardFailures.get(row.id) || 0
1138
1158
  const spec = this._lastSpecs.get(row.id)
1139
1159
  if (!spec) { await this._markError(row, '缺少重启规格,拒绝自动重启'); return }
1140
- if (failures >= maxConsecutive) { await this._markError(row, '连续重启次数超限,停止自动重启'); return }
1141
- this._guardFailures.set(row.id, failures + 1)
1160
+ if (failures >= maxConsecutive) { await this._markError(row, '连续重启次数超限,进入冷却(稍后自动重试)'); return }
1161
+ /* 重启退避:崩溃循环不能每 2s 硬拉一次,间隔随失败次数翻倍(2s→4s→8s…上限 60s)。 */
1162
+ const backoff = Math.min(2000 * 2 ** failures, 60_000)
1163
+ const lastRestart = this._lastRestart.get(row.id) || 0
1164
+ if (Date.now() - lastRestart < backoff) return
1165
+ this._lastRestart.set(row.id, Date.now())
1142
1166
  try {
1143
1167
  await this._upOnce(spec, {})
1168
+ /* 计数必须在重启**成功后**累加:_upOnce 的健康拉起路径会清 _guardFailures
1169
+ * (手动 up 语义=翻篇),守护重启若先加后清,崩溃循环永远打不满熔断。
1170
+ * 只有「稳定跑过 60s」或手动 up 才真正翻篇(见 _sweepOne)。 */
1171
+ this._guardFailures.set(row.id, failures + 1)
1144
1172
  this.log(`↻ ${row.id} 已自动重启`)
1145
1173
  } catch (err) {
1146
1174
  await this._markError(row, `自动重启失败: ${err.message}`)
@@ -1148,6 +1176,32 @@ export class ServiceEngine {
1148
1176
  })
1149
1177
  }
1150
1178
 
1179
+ /** error 态恢复:冷却指数翻倍(默认 5min→10min→20min…上限 30min)后按规格重试。
1180
+ * _upOnce 自带仲裁——端口上已有健康实例就复用,不会双开;成功即回到 running,
1181
+ * 稳定跑过 60s 后冷却计数清零(见 _sweepOne)。没有重启规格的行无法自愈,留给手动 up。 */
1182
+ async _recoverError(row) {
1183
+ const cfg = this._guardConfig || {}
1184
+ const base = cfg.errorRetryMs ?? 300_000
1185
+ const retry = this._errorRetries.get(row.id) || { count: 0, lastAt: 0 }
1186
+ const cooldown = Math.min(base * 2 ** retry.count, 1_800_000)
1187
+ if (Date.now() - retry.lastAt < cooldown) return
1188
+ const spec = this._lastSpecs.get(row.id)
1189
+ if (!spec) return
1190
+ await this._withServiceLock(row.id, async () => {
1191
+ if (this._stopping) return
1192
+ this._errorRetries.set(row.id, { count: retry.count + 1, lastAt: Date.now() })
1193
+ /* error 恢复是新一轮:不背旧的连续重启计数。 */
1194
+ this._guardFailures.delete(row.id)
1195
+ this._unhealthy.delete(row.id)
1196
+ try {
1197
+ await this._upOnce(spec, {})
1198
+ this.log(`↻ ${row.id} 已从 error 态恢复(第 ${retry.count + 1} 次尝试)`)
1199
+ } catch (err) {
1200
+ this.log(`… ${row.id} error 恢复失败(第 ${retry.count + 1} 次尝试):${err.message},冷却后再试`)
1201
+ }
1202
+ })
1203
+ }
1204
+
1151
1205
  /** 与服务级启动锁串行,避免与并发的 up/stop 交叉执行。 */
1152
1206
  _withServiceLock(id, fn) {
1153
1207
  const prev = this._upLocks.get(id) || Promise.resolve()
@@ -39,12 +39,18 @@ export function findSuiteRoot(startDir = path.dirname(PKG_DIR)) {
39
39
  }
40
40
  }
41
41
 
42
+ /** 读 JSON 并剥 UTF-8 BOM:带 BOM 的清单会让 JSON.parse 抛「Unexpected token」,
43
+ * 表现为 boot 永久失败且极难归因(文件看着完全正常)。统一在此剥掉。 */
44
+ function parseJsonFile(file) {
45
+ return JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
46
+ }
47
+
42
48
  /** 套件根判据:含 dsh-suite.json + services.json,且不是 broker 自带的 dsh-suite.json。 */
43
49
  function isSuiteRoot(dir) {
44
50
  const suiteFile = path.join(dir, 'dsh-suite.json')
45
51
  if (!existsSync(suiteFile) || !existsSync(path.join(dir, 'services.json'))) return false
46
52
  try {
47
- const manifest = JSON.parse(readFileSync(suiteFile, 'utf8'))
53
+ const manifest = parseJsonFile(suiteFile)
48
54
  return Boolean(manifest) && typeof manifest === 'object' && manifest.name !== 'dsh-service-broker-suite'
49
55
  } catch {
50
56
  return false
@@ -201,7 +207,7 @@ export function loadManifest(manifestPath) {
201
207
 
202
208
  function loadFile(file) {
203
209
  if (!existsSync(file)) return []
204
- const raw = JSON.parse(readFileSync(file, 'utf8'))
210
+ const raw = parseJsonFile(file)
205
211
  const services = Array.isArray(raw) ? raw : raw.services
206
212
  if (!Array.isArray(services)) throw new Error(`manifest 格式非法(缺 services 数组): ${file}`)
207
213
  const specErrors = validateServiceManifest(services, file)
@@ -245,5 +251,12 @@ function expandPackageDir(service, base) {
245
251
  for (const key of ['url', 'cwd', 'logFile']) {
246
252
  if (typeof out[key] === 'string') out[key] = String(out[key]).replaceAll('${PACKAGE_DIR}', base)
247
253
  }
254
+ /* env 值同样展开 ${PACKAGE_DIR}:旧实现只展开 url/cwd/logFile,env 里引用
255
+ * ${PACKAGE_DIR} 的变量(如自定义数据目录/脚本路径)原样传给子进程 → 路径错。 */
256
+ for (const [key, value] of Object.entries(out.env)) {
257
+ if (typeof value === 'string' && value.includes('${PACKAGE_DIR}')) {
258
+ out.env[key] = value.replaceAll('${PACKAGE_DIR}', base)
259
+ }
260
+ }
248
261
  return out
249
262
  }
@@ -273,53 +273,3 @@ export async function waitReceiptResolvable(receipt, ports, timeoutMs = 3000) {
273
273
  await new Promise((resolve) => setTimeout(resolve, 200))
274
274
  }
275
275
  }
276
-
277
- // Caller must serialize against starting a replacement broker and supply the
278
- // identity captured when it spawned this broker. An absent PID alone is not a receipt.
279
- export async function recoverServices(discovery, broker) {
280
- const unresolved = [], stopped = []
281
- if (!broker?.pid || !broker?.marker || !broker?.recoveryMarker || !absent(broker.pid)) return { stopped, unresolved: ['broker:not-confirmed-absent'] }
282
- let discovered = {}
283
- try { discovered = JSON.parse(fs.readFileSync(discovery, 'utf8'))?.services || {} } catch { /* discovery 缺失时只能依赖收据自身 */ }
284
- let entries
285
- try { entries = fs.readdirSync(receiptDir(discovery)) } catch (e) {
286
- return { stopped, unresolved: [e.code === 'ENOENT' ? 'ownership:missing' : 'ownership:unreadable'] }
287
- }
288
- for (const name of entries) {
289
- if (!name.endsWith('.json')) { unresolved.push(`ownership:${name}:unrecognized`); continue }
290
- let r
291
- try { r = JSON.parse(fs.readFileSync(path.join(receiptDir(discovery), name), 'utf8')) } catch { unresolved.push(`ownership:${name}:unreadable`); continue }
292
- if (!r || `${r.id}.json` !== name || !/^[a-z0-9][a-z0-9._-]*$/i.test(r.id) || r.brokerPid !== broker.pid || r.brokerMarker !== broker.recoveryMarker || r.state !== 'spawned' || !Number.isSafeInteger(r.pid) || r.pid <= 0 || !r.identity) {
293
- unresolved.push(`ownership:${name}:unverified`); continue
294
- }
295
- if (!absent(broker.pid)) { unresolved.push('broker:not-confirmed-absent'); break }
296
- if (absent(r.pid)) {
297
- // Dead root: only a receipt whose declared ports are all free can be
298
- // resolved; any listener may be an unverified descendant.
299
- if (await waitReceiptResolvable(r, discovered[r.id]?.ports)) {
300
- removeReceipt(discovery, r.id)
301
- stopped.push(r.id)
302
- } else unresolved.push(`service:${r.id}:already-exited-descendants-unverified`)
303
- continue
304
- }
305
- if (!absent(r.pid)) {
306
- if (marker(r.pid) !== r.identity) { unresolved.push(`service:${r.id}:identity-unverified`); continue }
307
- if (process.platform === 'win32') {
308
- const result = spawnSync('taskkill', ['/PID', String(r.pid), '/F'], { stdio: 'ignore', timeout: 10000, windowsHide: true })
309
- if (result.status !== 0 && !absent(r.pid)) { unresolved.push(`service:${r.id}:stop-failed`); continue }
310
- } else {
311
- try { process.kill(r.pid, 'SIGTERM') } catch (e) { if (e.code !== 'ESRCH') { unresolved.push(`service:${r.id}:stop-failed`); continue } }
312
- }
313
- for (let i = 0; i < 50 && !absent(r.pid); i++) await new Promise(resolve => setTimeout(resolve, 100))
314
- if (!absent(r.pid)) { unresolved.push(`service:${r.id}:still-running`); continue }
315
- }
316
- // Root exit alone does not prove its descendants exited. It is safe to
317
- // resolve once none of the declared ports is still listening; otherwise
318
- // keep the receipt as evidence (fail closed).
319
- if (await waitReceiptResolvable(r, discovered[r.id]?.ports)) {
320
- removeReceipt(discovery, r.id)
321
- stopped.push(r.id)
322
- } else unresolved.push(`service:${r.id}:descendants-unverified`)
323
- }
324
- return { stopped, unresolved }
325
- }
@@ -10,7 +10,12 @@ export function createSkillsClient(baseUrl) {
10
10
  return {
11
11
  api: { name: 'skills', version: '1.0.0', kind: 'thin-client' },
12
12
  async list(signal) {
13
- const res = await fetch(`${root}/skills`, { signal: signal ?? AbortSignal.timeout(5000) })
13
+ let res
14
+ try {
15
+ res = await fetch(`${root}/skills`, { signal: signal ?? AbortSignal.timeout(5000) })
16
+ } catch (error) {
17
+ throw new Error(`skills 服务不可达(${root}):${error.message}`, { cause: error })
18
+ }
14
19
  if (!res.ok) throw new Error(`skills list HTTP ${res.status}`)
15
20
  const body = await res.json()
16
21
  return Array.isArray(body?.skills) ? body.skills : []
@@ -18,10 +23,17 @@ export function createSkillsClient(baseUrl) {
18
23
  async get(candidate, options = {}) {
19
24
  const name = typeof candidate === 'string' ? candidate : candidate?.name
20
25
  if (!name) throw new Error('skills get: 缺 name')
21
- const res = await fetch(`${root}/skills/${encodeURIComponent(name)}`, {
22
- signal: options.signal ?? AbortSignal.timeout(10000),
23
- })
24
- if (!res.ok) throw new Error(`未知 skill ${name}(HTTP ${res.status})`)
26
+ let res
27
+ try {
28
+ res = await fetch(`${root}/skills/${encodeURIComponent(name)}`, {
29
+ signal: options.signal ?? AbortSignal.timeout(10000),
30
+ })
31
+ } catch (error) {
32
+ throw new Error(`skills 服务不可达(${root}):${error.message}`, { cause: error })
33
+ }
34
+ /* 只有 404 才是「未知 skill」;500/503 是服务端故障,不能误导成名字写错。 */
35
+ if (res.status === 404) throw new Error(`未知 skill ${name}(HTTP 404)`)
36
+ if (!res.ok) throw new Error(`skills get ${name} 失败(HTTP ${res.status},服务端错误)`)
25
37
  return res.json()
26
38
  },
27
39
  }
@@ -211,7 +211,15 @@ export function createServiceApp(options = {}) {
211
211
  if (req.method !== 'GET' && req.method !== 'HEAD') return false
212
212
  if (cleanPrefix && u.pathname !== cleanPrefix && !u.pathname.startsWith(cleanPrefix + '/')) return false
213
213
  const relRaw = cleanPrefix ? u.pathname.slice(cleanPrefix.length) : u.pathname
214
- const rel = relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
214
+ let rel
215
+ try {
216
+ rel = relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
217
+ } catch {
218
+ /* 畸形百分号编码 → URIError,不包会冒成 500;客户端错误回 400。 */
219
+ res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
220
+ res.end(req.method === 'HEAD' ? undefined : 'malformed path encoding')
221
+ return true
222
+ }
215
223
  let file = null
216
224
  let type = mimeFor(rel)
217
225
  if (files) {
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "$schema": "../capyclaw-suite-kit/suite.schema.json",
3
3
  "name": "dsh-tool-host-suite",
4
- "version": "0.2.0",
4
+ "version": "0.3.0",
5
5
  "title": "Tool Host",
6
6
  "description": "通用工具面:能力 DSL、注册表、校验、契约、MCP 壳、跨套件能力描述符注册/发现。",
7
7
  "packages": {
8
8
  "@capyclaw/tool-host": {
9
9
  "role": "provider",
10
- "version": "^0.2.0",
10
+ "version": "^0.3.0",
11
11
  "path": ".",
12
12
  "provides": {
13
13
  "services": [
@@ -1,16 +1,35 @@
1
1
  /**
2
2
  * @capyclaw/tool-host 插件:向同进程插件提供 ctx.toolHost。
3
+ *
4
+ * 同时落地“会话模式锁”这一基础设施能力:
5
+ * · 把 work-store 惰性解析器注入 toolHost(模式锁的存储真源);
6
+ * · 给 DSH tools 服务挂全局 guard(异领域调用硬拒兜底);
7
+ * · 注册框架核心工具 mode_lock / mode_status(无领域,恒可见)——显式锁定入口。
8
+ * 核心工具与 guard 的注册统一走 modeGate.install(tools)(幂等):apply 时 best-effort 挂一次,
9
+ * 若那一刻 tools 服务尚未就绪,首个套件注册(registerWithDsh / bridge host)会再调 install 补上,
10
+ * 故不依赖加载顺序。所有经 toolHost.registerWithDsh / bridge host 注册的领域能力自动受锁约束,套件零接线。
3
11
  */
4
12
  import { defineDriver } from '@capyclaw/foundation/abi'
5
13
  import { createToolHost } from '../src/index.mjs'
6
14
 
15
+ const safeGet = (ctx, name) => {
16
+ try { return ctx.reflect?.get?.(name) ?? ctx[name] } catch { return null }
17
+ }
18
+
7
19
  export const { name, inject, apply } = defineDriver({
8
20
  name: 'tool-host',
9
21
  service: 'toolHost',
10
22
  apply(ctx, config = {}) {
11
- const service = createToolHost(config)
23
+ const service = createToolHost({ ...config, getWorkStore: () => safeGet(ctx, 'workStore') })
12
24
  const dispose = ctx.provide('toolHost', service)
13
- console.log('[tool-host] ready')
14
- return () => { if (typeof dispose === 'function') dispose() }
25
+
26
+ /* 模式锁兜底闸 + 核心锁定工具(幂等)。tools 缺席则降级:稍后套件注册时经 install 补挂。 */
27
+ const tools = safeGet(ctx, 'tools')
28
+ if (tools && typeof tools.register === 'function') service.modeGate.install(tools)
29
+
30
+ console.log('[tool-host] ready (mode-gate enabled)')
31
+ return () => {
32
+ if (typeof dispose === 'function') dispose()
33
+ }
15
34
  },
16
- })
35
+ })
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/tool-host",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "DSH 公共工具面插件:能力 DSL、工具注册表、参数校验、契约报告、MCP 协议壳与 instructions 模板,向插件提供 ctx.toolHost。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 工具结果图像准入 —— DSH 原生工具面专用。
3
+ *
4
+ * 背景(2026-11-22 会话中断根因):DSH 的 ImageBlock 契约要求
5
+ * `{ type:'image', attachment: ImageAttachmentRef }`(见 @deepseek-ai/dsh-llm
6
+ * types.ts)。但部分工作台工具(rsp_screen / browser_screenshot 等)为了「图片直接
7
+ * 回给模型」返回了 MCP wire 形态的裸 base64 块 `{ type:'image', data, mimeType }`。
8
+ * 原生面 `dsh-tools/batch.ts` 把 result.content 原样写进 session 日志、不做形状校验,
9
+ * 于是坏块永久留在历史里;下一步构建请求时序列化器读 `block.attachment.attachmentId`
10
+ * 抛 TypeError(deepseek 侧包成 TRANSPORT,qwen4 侧冒泡成 UNKNOWN),该会话此后每一轮
11
+ * 都在发出前崩掉。
12
+ *
13
+ * 官方工具(read_image / mcp-client / office)都是自己先 `attachments.saveImage`
14
+ * 再回 attachment ref。这里在注册层补上同一道准入:把裸 base64 图像块持久化成
15
+ * attachment ref 再交给 DSH,一处修复覆盖所有 capyclaw 原生工具。
16
+ *
17
+ * 注意:只用于原生面(registerWithDsh)。MCP 面(createMcpHandler/dispatcher)必须
18
+ * 保留 `{data,mimeType}` wire 形态——那是 MCP 协议本身,由 dsh-mcp-client 负责落盘。
19
+ */
20
+
21
+ /** 是否是一个尚未准入的裸 base64 图像块(缺 attachment、带 string data)。 */
22
+ function isRawImageBlock(block) {
23
+ return !!block && block.type === 'image' && !block.attachment && typeof block.data === 'string'
24
+ }
25
+
26
+ /**
27
+ * 从执行上下文 / 注册上下文解析 attachments 服务。
28
+ * agent 的会话级 ctx 与 read_image 用的是同一棵上下文树,attachments 必在其上;
29
+ * 注册 ctx 作为兜底。cordis 未 inject 时 get 可能抛错,逐一吞掉换下一个候选。
30
+ * @returns {object|null} 带 saveImage 的 AttachmentStore,或 null。
31
+ */
32
+ export function resolveAttachments(exec, ctx) {
33
+ for (const candidate of [exec?.agent?.ctx, ctx]) {
34
+ if (!candidate) continue
35
+ try {
36
+ const viaGet = typeof candidate.get === 'function' ? candidate.get('attachments') : undefined
37
+ const service = viaGet ?? candidate.attachments ?? candidate.reflect?.get?.('attachments')
38
+ if (service && typeof service.saveImage === 'function') return service
39
+ } catch { /* 该上下文取不到,换下一个候选 */ }
40
+ }
41
+ return null
42
+ }
43
+
44
+ /**
45
+ * 把工具结果 content 里的裸 base64 图像块准入为持久 attachment ref。
46
+ * 非图像块、已带 attachment 的图像块原样保留;无图像块时零开销直接返回原数组。
47
+ *
48
+ * 降级原则:宁可丢图也不毒化会话——attachments 缺席或 saveImage 失败时,把该图像块
49
+ * 换成一条说明性 text 块(工具通常另有一条带落盘路径的 text 块,信息不丢)。
50
+ *
51
+ * @param {Array} content 归一化后的 MCP content 块数组。
52
+ * @param {object|null} attachments AttachmentStore(resolveAttachments 的结果)。
53
+ * @param {{ name?: string }} [opts] 可选显示名(写入 ref.name,绝不解释为路径)。
54
+ * @returns {Promise<Array>} 准入后的 content 块数组。
55
+ */
56
+ export async function admitToolResultImages(content, attachments, { name } = {}) {
57
+ if (!Array.isArray(content)) return content
58
+ if (!content.some(isRawImageBlock)) return content
59
+
60
+ const out = []
61
+ for (const block of content) {
62
+ if (!isRawImageBlock(block)) { out.push(block); continue }
63
+
64
+ const mediaType = block.mediaType || block.mimeType || 'image/png'
65
+ if (!attachments) {
66
+ out.push({ type: 'text', text: `[image omitted: no attachment service mounted; ${mediaType}]` })
67
+ continue
68
+ }
69
+ try {
70
+ const data = Buffer.from(block.data, 'base64')
71
+ const ref = await attachments.saveImage({ data, mediaType, ...(name ? { name } : {}) })
72
+ out.push({ type: 'image', attachment: ref })
73
+ } catch (error) {
74
+ const code = error?.code || error?.name || 'ERROR'
75
+ const message = String(error?.message || error)
76
+ out.push({ type: 'text', text: `[image omitted: attachment save failed (${code}): ${message}]` })
77
+ }
78
+ }
79
+ return out
80
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * 调用者会话上下文(框架级 ALS)。
3
+ *
4
+ * registerWithDsh 把每个原生工具的执行包进 runWithCallerSession(sid, …),
5
+ * 于是工具 handler 执行期间(哪怕 handler 只拿到 (args, ctx)、丢了 exec),
6
+ * 框架内部任何一层都能用 currentCallerSession() 取回“是谁在调我”。
7
+ *
8
+ * 用途:会话模式锁在能力发现面(discoverCapabilities)按调用者会话过滤异领域
9
+ * 描述符——conductor_discover 这类 read 工具无需自己接线 exec 即自动受约束。
10
+ *
11
+ * 无会话(HTTP/MCP 管理面、墙聚合视图)时返回 '',调用方据此降级为不过滤。
12
+ */
13
+ import { AsyncLocalStorage } from 'node:async_hooks'
14
+
15
+ const als = new AsyncLocalStorage()
16
+
17
+ /** 在指定调用者会话上下文里执行 fn(同步/异步均可,ALS 随 await 传播)。 */
18
+ export function runWithCallerSession(sessionId, fn) {
19
+ return als.run(String(sessionId || ''), fn)
20
+ }
21
+
22
+ /** 当前调用者会话 id;不在工具调用上下文里时返回 ''。 */
23
+ export function currentCallerSession() {
24
+ return als.getStore() || ''
25
+ }