@octopi-agent/engine 0.102.10 → 0.121.15

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 (321) hide show
  1. package/dist/builtin-model-info.js +28 -7
  2. package/dist/config-admin/agent-presets.d.ts +32 -0
  3. package/dist/config-admin/agent-presets.js +133 -0
  4. package/dist/config-admin/console-access-key.d.ts +46 -0
  5. package/dist/config-admin/console-access-key.js +47 -0
  6. package/dist/config-admin/discover.d.ts +33 -4
  7. package/dist/config-admin/discover.js +101 -6
  8. package/dist/config-admin/env.d.ts +11 -0
  9. package/dist/config-admin/env.js +41 -0
  10. package/dist/config-admin/error-copy.d.ts +106 -0
  11. package/dist/config-admin/error-copy.js +287 -0
  12. package/dist/config-admin/i18n.d.ts +21 -0
  13. package/dist/config-admin/i18n.js +19 -0
  14. package/dist/config-admin/index.d.ts +8 -2
  15. package/dist/config-admin/index.js +4 -1
  16. package/dist/config-admin/model-presets.d.ts +14 -0
  17. package/dist/config-admin/model-presets.js +595 -70
  18. package/dist/config-admin/onboarding-apply.d.ts +83 -0
  19. package/dist/config-admin/onboarding-apply.js +259 -0
  20. package/dist/config-admin/onboarding.d.ts +160 -0
  21. package/dist/config-admin/onboarding.js +298 -0
  22. package/dist/config-admin/password-policy.d.ts +24 -0
  23. package/dist/config-admin/password-policy.js +31 -0
  24. package/dist/config-admin/redact.d.ts +42 -9
  25. package/dist/config-admin/redact.js +69 -5
  26. package/dist/config-schema/agent.d.ts +5 -1
  27. package/dist/config-schema/agent.js +20 -2
  28. package/dist/config-schema/browser.d.ts +62 -0
  29. package/dist/config-schema/browser.js +89 -0
  30. package/dist/config-schema/context.d.ts +7 -2
  31. package/dist/config-schema/context.js +6 -3
  32. package/dist/config-schema/engine.d.ts +86 -7
  33. package/dist/config-schema/engine.js +9 -2
  34. package/dist/config-schema/governance.d.ts +12 -1
  35. package/dist/config-schema/governance.js +10 -2
  36. package/dist/config-schema/models.d.ts +12 -8
  37. package/dist/config-schema/models.js +16 -1
  38. package/dist/config-schema/run.d.ts +4 -0
  39. package/dist/config-schema/run.js +10 -0
  40. package/dist/config-schema/shared.d.ts +1 -0
  41. package/dist/config-schema/shared.js +4 -2
  42. package/dist/config-schema/substrate.d.ts +5 -0
  43. package/dist/config-schema/substrate.js +8 -0
  44. package/dist/config.d.ts +116 -10
  45. package/dist/config.js +109 -13
  46. package/dist/file-mode.d.ts +67 -0
  47. package/dist/file-mode.js +182 -0
  48. package/dist/fork-child.d.ts +82 -0
  49. package/dist/fork-child.js +123 -0
  50. package/dist/harness/activation/delegated-run.d.ts +42 -0
  51. package/dist/harness/activation/delegated-run.js +71 -0
  52. package/dist/harness/activation/dispatcher.js +4 -0
  53. package/dist/harness/activation/index.d.ts +1 -0
  54. package/dist/harness/activation/run-backend.d.ts +92 -0
  55. package/dist/harness/activation/run-backend.js +16 -0
  56. package/dist/harness/activation/run-protocol.d.ts +392 -0
  57. package/dist/harness/activation/run-protocol.js +19 -0
  58. package/dist/harness/activation/runtime.d.ts +33 -0
  59. package/dist/harness/activation/runtime.js +119 -28
  60. package/dist/harness/activation/types.d.ts +19 -2
  61. package/dist/harness/agent/builder.d.ts +12 -0
  62. package/dist/harness/agent/builder.js +78 -22
  63. package/dist/harness/agent/config-bridge.d.ts +10 -1
  64. package/dist/harness/agent/config-bridge.js +15 -3
  65. package/dist/harness/agent/registered-tool-adapter.d.ts +27 -0
  66. package/dist/harness/agent/registered-tool-adapter.js +67 -0
  67. package/dist/harness/agent/wire-agent-builder.d.ts +2 -0
  68. package/dist/harness/agent/wire-agent-builder.js +9 -2
  69. package/dist/harness/capabilities/document/backends/plain.js +2 -1
  70. package/dist/harness/capabilities/document/legacy/factory.js +3 -2
  71. package/dist/harness/collaboration/autonomous-subsystem/audit/reader.d.ts +17 -0
  72. package/dist/harness/collaboration/autonomous-subsystem/audit/reader.js +66 -36
  73. package/dist/harness/collaboration/autonomous-subsystem/audit/writer.d.ts +6 -2
  74. package/dist/harness/collaboration/autonomous-subsystem/audit/writer.js +27 -7
  75. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.js +13 -0
  76. package/dist/harness/collaboration/autonomous-subsystem/loader.js +1 -0
  77. package/dist/harness/collaboration/autonomous-subsystem/runtime.d.ts +11 -0
  78. package/dist/harness/collaboration/autonomous-subsystem/runtime.js +17 -0
  79. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.d.ts +13 -3
  80. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +48 -39
  81. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -0
  82. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +4 -0
  83. package/dist/harness/collaboration/delegation/child-run.d.ts +9 -0
  84. package/dist/harness/collaboration/delegation/child-run.js +34 -2
  85. package/dist/harness/collaboration/delegation/registry-types.d.ts +2 -0
  86. package/dist/harness/collaboration/delegation/service.d.ts +9 -4
  87. package/dist/harness/collaboration/delegation/service.js +33 -12
  88. package/dist/harness/collaboration/delegation/store.d.ts +2 -0
  89. package/dist/harness/collaboration/delegation/store.js +1 -0
  90. package/dist/harness/collaboration/delegation/types.d.ts +11 -0
  91. package/dist/harness/collaboration/delegation/wiring.d.ts +2 -0
  92. package/dist/harness/collaboration/delegation/wiring.js +1 -0
  93. package/dist/harness/context/capabilities/compact/engine.d.ts +44 -5
  94. package/dist/harness/context/capabilities/compact/engine.js +127 -39
  95. package/dist/harness/context/capabilities/compact/index.d.ts +2 -1
  96. package/dist/harness/context/capabilities/compact/index.js +1 -1
  97. package/dist/harness/context/capabilities/compact/types.d.ts +59 -9
  98. package/dist/harness/context/capabilities/summary/gate.d.ts +19 -2
  99. package/dist/harness/context/capabilities/summary/gate.js +53 -6
  100. package/dist/harness/context/capabilities/summary/registry.js +20 -0
  101. package/dist/harness/context/capabilities/summary/tool-binding.js +16 -12
  102. package/dist/harness/context/capabilities/summary/tool-bindings.d.ts +13 -0
  103. package/dist/harness/context/capabilities/summary/tool-bindings.js +22 -0
  104. package/dist/harness/context/capabilities/summary/types.d.ts +16 -0
  105. package/dist/harness/context/constitution/default-agents.md +85 -0
  106. package/dist/harness/context/context-size-ledger.js +8 -1
  107. package/dist/harness/context/default-context-engine.d.ts +100 -6
  108. package/dist/harness/context/default-context-engine.js +382 -89
  109. package/dist/harness/context/index.d.ts +2 -1
  110. package/dist/harness/context/index.js +1 -0
  111. package/dist/harness/context/layer-health.d.ts +4 -0
  112. package/dist/harness/context/layer-health.js +4 -0
  113. package/dist/harness/context/layer-types.d.ts +57 -0
  114. package/dist/harness/context/layer-types.js +73 -1
  115. package/dist/harness/context/layers.d.ts +3 -0
  116. package/dist/harness/context/layers.js +13 -6
  117. package/dist/harness/context/prefix-fingerprint.d.ts +46 -0
  118. package/dist/harness/context/prefix-fingerprint.js +52 -0
  119. package/dist/harness/context/summarize.js +18 -0
  120. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  121. package/dist/harness/context/system-prompt-assembler.js +5 -2
  122. package/dist/harness/context/tool-result-aging.d.ts +104 -16
  123. package/dist/harness/context/tool-result-aging.js +211 -57
  124. package/dist/harness/context/types.d.ts +71 -4
  125. package/dist/harness/context/types.js +25 -1
  126. package/dist/harness/extension/execution-environment/effect-policy.d.ts +4 -3
  127. package/dist/harness/extension/execution-environment/effect-policy.js +2 -2
  128. package/dist/harness/extension/execution-environment/privileged-exec.js +4 -1
  129. package/dist/harness/extension/execution-environment/workspace.js +1 -1
  130. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +27 -1
  131. package/dist/harness/extension/plugin-ecosystem/channel-types.js +11 -2
  132. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.d.ts +12 -0
  133. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.js +25 -0
  134. package/dist/harness/extension/plugin-ecosystem/commands/builtin.js +28 -1
  135. package/dist/harness/extension/plugin-ecosystem/index.d.ts +1 -0
  136. package/dist/harness/extension/plugin-ecosystem/index.js +1 -0
  137. package/dist/harness/extension/plugin-ecosystem/plugins/api.d.ts +168 -1
  138. package/dist/harness/extension/plugin-ecosystem/plugins/api.js +156 -15
  139. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-instances.d.ts +95 -0
  140. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-instances.js +170 -0
  141. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-kinds.d.ts +178 -0
  142. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-kinds.js +314 -0
  143. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.d.ts +40 -5
  144. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.js +45 -26
  145. package/dist/harness/extension/plugin-ecosystem/plugins/index.d.ts +1 -1
  146. package/dist/harness/extension/plugin-ecosystem/plugins/loader.d.ts +11 -1
  147. package/dist/harness/extension/plugin-ecosystem/plugins/loader.js +42 -76
  148. package/dist/harness/extension/plugin-ecosystem/plugins/manager.d.ts +30 -1
  149. package/dist/harness/extension/plugin-ecosystem/plugins/manager.js +46 -0
  150. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.d.ts +9 -0
  151. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.js +19 -14
  152. package/dist/harness/extension/plugin-ecosystem/plugins/staging.d.ts +3 -1
  153. package/dist/harness/extension/plugin-ecosystem/plugins/staging.js +1 -1
  154. package/dist/harness/extension/plugin-ecosystem/tools/browser-types.d.ts +333 -0
  155. package/dist/harness/extension/plugin-ecosystem/tools/browser-types.js +16 -0
  156. package/dist/harness/extension/plugin-ecosystem/tools/browser.d.ts +64 -0
  157. package/dist/harness/extension/plugin-ecosystem/tools/browser.js +692 -0
  158. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +0 -37
  159. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +108 -4
  160. package/dist/harness/extension/plugin-ecosystem/tools/delegation.js +18 -0
  161. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +34 -0
  162. package/dist/harness/extension/plugin-ecosystem/tools/file-search.d.ts +0 -6
  163. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +57 -4
  164. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +81 -13
  165. package/dist/harness/extension/plugin-ecosystem/tools/http.js +5 -0
  166. package/dist/harness/extension/plugin-ecosystem/tools/knowledge.js +13 -7
  167. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +126 -14
  168. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +1 -1
  169. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +44 -5
  170. package/dist/harness/extension/plugin-ecosystem/tools/tool-bus.js +10 -24
  171. package/dist/harness/extension/plugin-ecosystem/tools/tool-set.d.ts +7 -0
  172. package/dist/harness/extension/plugin-ecosystem/tools/tool-set.js +4 -0
  173. package/dist/harness/governance/credentials/db.d.ts +9 -0
  174. package/dist/harness/governance/credentials/db.js +122 -31
  175. package/dist/harness/governance/credentials/store.d.ts +68 -7
  176. package/dist/harness/governance/credentials/store.js +177 -64
  177. package/dist/harness/governance/credentials/types.d.ts +13 -2
  178. package/dist/harness/governance/index.d.ts +1 -0
  179. package/dist/harness/governance/index.js +1 -0
  180. package/dist/harness/governance/registry/db.d.ts +32 -0
  181. package/dist/harness/governance/registry/db.js +142 -0
  182. package/dist/harness/governance/registry/index.d.ts +9 -0
  183. package/dist/harness/governance/registry/index.js +9 -0
  184. package/dist/harness/governance/registry/service.d.ts +381 -0
  185. package/dist/harness/governance/registry/service.js +825 -0
  186. package/dist/harness/governance/registry/types.d.ts +77 -0
  187. package/dist/harness/governance/registry/types.js +7 -0
  188. package/dist/harness/governance/security/default-security-guard.d.ts +3 -0
  189. package/dist/harness/governance/security/default-security-guard.js +12 -1
  190. package/dist/harness/governance/security/risk-evaluator.d.ts +13 -3
  191. package/dist/harness/governance/security/risk-evaluator.js +307 -21
  192. package/dist/harness/governance/security/shell-parser-treesitter.js +12 -4
  193. package/dist/harness/governance/session-acl/tool-rights.d.ts +1 -0
  194. package/dist/harness/index.d.ts +5 -3
  195. package/dist/harness/index.js +2 -2
  196. package/dist/harness/knowledge/boot-config.d.ts +2 -0
  197. package/dist/harness/knowledge/boot-config.js +2 -0
  198. package/dist/harness/knowledge/client.d.ts +53 -7
  199. package/dist/harness/knowledge/client.js +77 -20
  200. package/dist/harness/knowledge/db.d.ts +16 -0
  201. package/dist/harness/knowledge/db.js +107 -41
  202. package/dist/harness/knowledge/engine-thread.js +5 -7
  203. package/dist/harness/knowledge/grounding.js +4 -1
  204. package/dist/harness/knowledge/http-app.d.ts +15 -0
  205. package/dist/harness/knowledge/http-app.js +82 -21
  206. package/dist/harness/knowledge/http-bridge.d.ts +15 -0
  207. package/dist/harness/knowledge/http-bridge.js +19 -0
  208. package/dist/harness/knowledge/knowledge-serve-child.js +2 -3
  209. package/dist/harness/knowledge/query-service.d.ts +12 -2
  210. package/dist/harness/knowledge/query-service.js +75 -41
  211. package/dist/harness/knowledge/query-worker-client.d.ts +5 -1
  212. package/dist/harness/knowledge/query-worker-client.js +4 -1
  213. package/dist/harness/knowledge/query-worker.js +5 -3
  214. package/dist/harness/knowledge/read-http.d.ts +2 -0
  215. package/dist/harness/knowledge/read-http.js +9 -2
  216. package/dist/harness/knowledge/retriever.d.ts +1 -1
  217. package/dist/harness/knowledge/retriever.js +1 -2
  218. package/dist/harness/knowledge/serve.d.ts +6 -1
  219. package/dist/harness/knowledge/serve.js +5 -6
  220. package/dist/harness/knowledge/source-store.d.ts +101 -5
  221. package/dist/harness/knowledge/source-store.js +297 -71
  222. package/dist/harness/knowledge/start-service-process.d.ts +27 -8
  223. package/dist/harness/knowledge/start-service-process.js +49 -90
  224. package/dist/harness/knowledge/tenant-gate.d.ts +81 -0
  225. package/dist/harness/knowledge/tenant-gate.js +167 -0
  226. package/dist/harness/knowledge/writer-service.d.ts +18 -2
  227. package/dist/harness/knowledge/writer-service.js +80 -16
  228. package/dist/harness/knowledge/writer-worker-client.d.ts +9 -2
  229. package/dist/harness/knowledge/writer-worker-client.js +20 -3
  230. package/dist/harness/knowledge/writer-worker.js +11 -4
  231. package/dist/harness/memory/backfill-trigger.d.ts +10 -3
  232. package/dist/harness/memory/backfill-trigger.js +19 -19
  233. package/dist/harness/memory/cognition-seeds.d.ts +45 -0
  234. package/dist/harness/memory/cognition-seeds.js +67 -0
  235. package/dist/harness/memory/cognition.d.ts +12 -3
  236. package/dist/harness/memory/cognition.js +55 -35
  237. package/dist/harness/memory/conceptualizer.d.ts +11 -1
  238. package/dist/harness/memory/conceptualizer.js +10 -1
  239. package/dist/harness/memory/context-slice.d.ts +42 -0
  240. package/dist/harness/memory/context-slice.js +197 -0
  241. package/dist/harness/memory/health-probe.d.ts +8 -2
  242. package/dist/harness/memory/health-probe.js +10 -13
  243. package/dist/harness/memory/index.d.ts +5 -1
  244. package/dist/harness/memory/index.js +3 -1
  245. package/dist/harness/memory/sqlite/agent-db.d.ts +1 -0
  246. package/dist/harness/memory/sqlite/agent-db.js +9 -8
  247. package/dist/harness/memory/sqlite/cognition-store.d.ts +26 -3
  248. package/dist/harness/memory/sqlite/cognition-store.js +103 -45
  249. package/dist/harness/memory/sqlite/memory-store.js +4 -0
  250. package/dist/harness/memory/sqlite/sqlite-vec.d.ts +24 -1
  251. package/dist/harness/memory/sqlite/sqlite-vec.js +37 -1
  252. package/dist/harness/memory/types.d.ts +18 -2
  253. package/dist/harness/observability/observer/hub.d.ts +10 -0
  254. package/dist/harness/observability/observer/hub.js +95 -2
  255. package/dist/harness/run/agent/agent.js +3 -2
  256. package/dist/harness/run/concurrency/tool-validator.js +4 -3
  257. package/dist/harness/run/reliability/run-agent.d.ts +22 -0
  258. package/dist/harness/run/reliability/run-agent.js +79 -10
  259. package/dist/harness/run/run-host.d.ts +302 -0
  260. package/dist/harness/run/run-host.js +978 -0
  261. package/dist/harness/run/run-scope.d.ts +11 -0
  262. package/dist/harness/run/run-scope.js +19 -1
  263. package/dist/harness/run/runner.d.ts +149 -22
  264. package/dist/harness/run/runner.js +352 -35
  265. package/dist/harness/session/in-memory-store.js +13 -1
  266. package/dist/harness/session/schedules/service.d.ts +10 -2
  267. package/dist/harness/session/schedules/service.js +13 -2
  268. package/dist/harness/session/tasks/tools.js +12 -0
  269. package/dist/harness/session/types.d.ts +10 -14
  270. package/dist/harness/shared/events/agent-event-map.d.ts +29 -0
  271. package/dist/harness/shared/types/agent-definition.d.ts +6 -0
  272. package/dist/index.d.ts +3 -2
  273. package/dist/index.js +2 -1
  274. package/dist/integration/agent-runtime/channel-message-source.d.ts +3 -1
  275. package/dist/integration/agent-runtime/channel-message-source.js +4 -3
  276. package/dist/integration/browser/camoufox.d.ts +40 -0
  277. package/dist/integration/browser/camoufox.js +80 -0
  278. package/dist/integration/browser/index.d.ts +91 -0
  279. package/dist/integration/browser/index.js +110 -0
  280. package/dist/integration/browser/install.d.ts +47 -0
  281. package/dist/integration/browser/install.js +214 -0
  282. package/dist/integration/browser/playwright.d.ts +224 -0
  283. package/dist/integration/browser/playwright.js +925 -0
  284. package/dist/integration/browser/service.d.ts +41 -0
  285. package/dist/integration/browser/service.js +181 -0
  286. package/dist/integration/browser/stealth.d.ts +42 -0
  287. package/dist/integration/browser/stealth.js +104 -0
  288. package/dist/integration/providers/anthropic-message-normalize.d.ts +20 -0
  289. package/dist/integration/providers/anthropic-message-normalize.js +48 -0
  290. package/dist/integration/providers/anthropic.js +27 -2
  291. package/dist/integration/providers/fetch-timeout.d.ts +17 -0
  292. package/dist/integration/providers/fetch-timeout.js +24 -0
  293. package/dist/integration/providers/openai.d.ts +8 -0
  294. package/dist/integration/providers/openai.js +41 -1
  295. package/dist/integration/providers/wire-dump-diff.js +2 -1
  296. package/dist/integration/providers/wire-dump.d.ts +56 -2
  297. package/dist/integration/providers/wire-dump.js +119 -6
  298. package/dist/integration/storage/archive-manager.d.ts +14 -2
  299. package/dist/integration/storage/archive-manager.js +24 -8
  300. package/dist/integration/storage/atomic-tmp.d.ts +12 -0
  301. package/dist/integration/storage/atomic-tmp.js +36 -0
  302. package/dist/integration/storage/jsonl.d.ts +9 -0
  303. package/dist/integration/storage/jsonl.js +137 -38
  304. package/dist/integration/storage/session-index.d.ts +5 -0
  305. package/dist/integration/storage/session-index.js +25 -4
  306. package/dist/integration/tools/assemble.d.ts +50 -0
  307. package/dist/integration/tools/assemble.js +137 -0
  308. package/dist/paths.d.ts +18 -0
  309. package/dist/paths.js +36 -0
  310. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +3 -1
  311. package/dist/subsystems/cognition-steward/conceptualize/handler.js +74 -5
  312. package/dist/subsystems/cognition-steward/consolidate/SUBSYSTEM.md +3 -2
  313. package/dist/subsystems/cognition-steward/consolidate/config.yaml +11 -2
  314. package/dist/subsystems/cognition-steward/consolidate/handler.d.ts +6 -3
  315. package/dist/subsystems/cognition-steward/consolidate/handler.js +266 -28
  316. package/dist/subsystems/memory-steward/backfill/handler.js +3 -2
  317. package/dist/subsystems/memory-steward/govern/config.yaml +6 -1
  318. package/dist/subsystems/wisdom-steward/attribute/config.yaml +5 -1
  319. package/dist/subsystems/wisdom-steward/formation/config.yaml +3 -0
  320. package/dist/subsystems/wisdom-steward/govern/config.yaml +6 -1
  321. package/package.json +5 -3
@@ -0,0 +1,925 @@
1
+ /**
2
+ * playwright 后端 — BrowserPort 的 Playwright 实现(arch/browser-capability.md §3.3)
3
+ *
4
+ * 可选依赖纪律:`playwright-core` 经 optionalDependencies 提供,运行时动态 import
5
+ * (零编译期耦合,结构化类型自描述);缺失/浏览器二进制缺失时 fail-loud
6
+ * (`not_implemented` + 安装指引),不装哑 stub。
7
+ *
8
+ * 请求级策略(arch/browser-capability.md §3.6):经 CDP Fetch 域逐请求暂停
9
+ * 对**每个网络请求**(含重定向/子资源/页内导航)执行注入的 BrowserRequestPolicy——
10
+ * URL 判定与外部写闸门在网络层收口,DOM 层敏感标记只是提前预判。
11
+ */
12
+ import { randomUUID } from 'node:crypto';
13
+ import { access } from 'node:fs/promises';
14
+ import { join } from 'node:path';
15
+ import { BROWSER_DEFAULT_TIMEOUT_MS } from '../../harness/extension/plugin-ecosystem/tools/browser-types.js';
16
+ const INTERACTIVE_SELECTOR = [
17
+ 'a[href]',
18
+ 'button',
19
+ 'input',
20
+ 'select',
21
+ 'textarea',
22
+ 'summary',
23
+ '[role=button]',
24
+ '[role=link]',
25
+ '[role=checkbox]',
26
+ '[role=radio]',
27
+ '[role=tab]',
28
+ '[role=menuitem]',
29
+ '[role=option]',
30
+ '[role=switch]',
31
+ '[role=textbox]',
32
+ '[contenteditable="true"]',
33
+ ].join(',');
34
+ const TEXTY_TAGS = new Set(['P', 'LI', 'BLOCKQUOTE', 'TD', 'TH', 'PRE']);
35
+ // 网络层外部写方法(非 GET/HEAD/OPTIONS)
36
+ const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
37
+ // 挑战页识别标记(启发式、刻意小表;命中透出 marker,漏检是已知边界)。
38
+ // `titleOnly` 标记(captcha 一类)只匹配标题——正文子串极易在帮助页/文档里误伤(评审 F11)
39
+ const CHALLENGE_MARKERS = [
40
+ { kind: 'interstitial', marker: 'just a moment' }, // Cloudflare
41
+ { kind: 'interstitial', marker: 'attention required' },
42
+ { kind: 'interstitial', marker: 'checking your browser' },
43
+ { kind: 'interstitial', marker: 'enable javascript and cookies' },
44
+ { kind: 'captcha', marker: 'captcha', titleOnly: true },
45
+ { kind: 'captcha', marker: '人机验证', titleOnly: true },
46
+ { kind: 'captcha', marker: '安全验证', titleOnly: true },
47
+ { kind: 'captcha', marker: 'verify you are human', titleOnly: true },
48
+ ];
49
+ const driverPromises = new Map();
50
+ /**
51
+ * 按 specifier 解析 playwright 系驱动(每个 specifier 单飞缓存)。
52
+ * P3:rebrowser 后端 = `rebrowser-playwright-core`(drop-in,API 同构);
53
+ * camoufox 后端经自定义 launcher 注入,不经此函数。
54
+ */
55
+ async function resolveDriver(spec) {
56
+ let promise = driverPromises.get(spec);
57
+ if (!promise) {
58
+ promise = (async () => {
59
+ // 变量 specifier:编译期零解析(可选依赖缺席时 tsc 也能过);运行期解析缺席即 fail-loud
60
+ try {
61
+ return (await import(spec));
62
+ }
63
+ catch (err) {
64
+ driverPromises.delete(spec); // 允许安装后重试
65
+ throw new Error(`not_implemented: browser engine not installed (${spec}) — run "octopi browser install"`, { cause: err });
66
+ }
67
+ })();
68
+ driverPromises.set(spec, promise);
69
+ }
70
+ return promise;
71
+ }
72
+ /** profile 文件存在性(不存在 = 全新身份,从零开始;不抛) */
73
+ async function fileExists(path) {
74
+ try {
75
+ await access(path);
76
+ return true;
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ }
82
+ /** 隔离不可用的 storageState 档(改名保留现场,不静默删);返回是否隔离成功 */
83
+ async function quarantineProfileState(path) {
84
+ try {
85
+ const { rename } = await import('node:fs/promises');
86
+ await rename(path, `${path}.corrupt-${Date.now()}`);
87
+ return true;
88
+ }
89
+ catch {
90
+ // 隔离失败:调用方禁用 persist(不得覆盖现场);后续 launch 仍会撞同一错(fail-loud 仍在)
91
+ return false;
92
+ }
93
+ }
94
+ /** chromium 启动失败→安装指引(二进制缺失 fail-loud,不静默换引擎) */
95
+ function mapLaunchError(err) {
96
+ const message = err instanceof Error ? err.message : String(err);
97
+ if (/executable|browser.*not.*(found|installed)|doesn't exist/i.test(message)) {
98
+ return new Error(`not_implemented: browser engine not installed (chromium) — run "octopi browser install" (${message})`);
99
+ }
100
+ return err instanceof Error ? err : new Error(String(err));
101
+ }
102
+ const PAGE_WALK_FN = (arg) => {
103
+ const { epoch, interactiveOnly, selector, textyTags } = arg;
104
+ const doc = globalThis.document;
105
+ const texty = new Set(textyTags);
106
+ const out = [];
107
+ let n = 0;
108
+ const visible = (el) => el.getClientRects().length > 0;
109
+ const nameOf = (el) => el.getAttribute('aria-label') ||
110
+ (el.innerText || el.textContent || '').trim().slice(0, 120) ||
111
+ el.getAttribute('placeholder') ||
112
+ el.getAttribute('title') ||
113
+ el.getAttribute('name') ||
114
+ '';
115
+ const tagsOf = (el) => {
116
+ const tags = [];
117
+ if (el.type === 'password')
118
+ tags.push('password');
119
+ if (el.type === 'submit' || el.type === 'image')
120
+ tags.push('submit');
121
+ if (el.type === 'file')
122
+ tags.push('file');
123
+ if (/^H[1-6]$/.test(el.tagName))
124
+ tags.push('heading');
125
+ return tags;
126
+ };
127
+ const roleOf = (el) => {
128
+ const attrRole = el.getAttribute('role');
129
+ if (attrRole)
130
+ return attrRole;
131
+ const t = el.tagName;
132
+ if (t === 'A')
133
+ return 'link';
134
+ if (t === 'BUTTON')
135
+ return 'button';
136
+ if (t === 'SELECT')
137
+ return 'combobox';
138
+ if (t === 'TEXTAREA')
139
+ return 'textbox';
140
+ if (t === 'INPUT') {
141
+ if (el.type === 'checkbox')
142
+ return 'checkbox';
143
+ if (el.type === 'radio')
144
+ return 'radio';
145
+ if (el.type === 'submit' || el.type === 'image')
146
+ return 'button';
147
+ return 'textbox';
148
+ }
149
+ return t.toLowerCase();
150
+ };
151
+ const walk = (node) => {
152
+ for (let i = 0; i < node.children.length; i++) {
153
+ const child = node.children[i];
154
+ const tag = child.tagName;
155
+ if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT')
156
+ continue;
157
+ if (!visible(child))
158
+ continue;
159
+ const interactive = child.matches(selector);
160
+ const isHeading = /^H[1-6]$/.test(tag);
161
+ const isTexty = texty.has(tag);
162
+ if (interactive) {
163
+ n += 1;
164
+ const ref = `r${epoch}-e${n}`;
165
+ child.setAttribute('data-octopi-ref', ref);
166
+ const entry = {
167
+ ref,
168
+ role: roleOf(child),
169
+ name: nameOf(child),
170
+ };
171
+ const tags = tagsOf(child);
172
+ if (tags.length)
173
+ entry.tags = tags;
174
+ if (child.value !== undefined && child.value !== '')
175
+ entry.value = child.value.slice(0, 200);
176
+ if (child.type === 'checkbox' || child.type === 'radio')
177
+ entry.checked = Boolean(child.checked);
178
+ out.push(entry);
179
+ }
180
+ else if (!interactiveOnly && (isHeading || isTexty)) {
181
+ const text = (child.innerText || child.textContent || '').trim().slice(0, 300);
182
+ if (text) {
183
+ const entry = {
184
+ role: isHeading ? 'heading' : 'text',
185
+ name: text,
186
+ };
187
+ const tags = tagsOf(child);
188
+ if (tags.length)
189
+ entry.tags = tags;
190
+ out.push(entry);
191
+ }
192
+ }
193
+ walk(child);
194
+ }
195
+ };
196
+ walk(doc.body);
197
+ return out;
198
+ };
199
+ export class PlaywrightBrowserSession {
200
+ browser;
201
+ context;
202
+ page;
203
+ actionTimeoutMs;
204
+ onClosed;
205
+ sessionOptions;
206
+ id;
207
+ engine;
208
+ identity;
209
+ ownerKey;
210
+ /** 当前快照的 ref 元数据(ref 绑定快照代数;导航/重渲染即失效) */
211
+ refMeta = new Map();
212
+ epoch = 0;
213
+ /** 最近一次被策略拦截的 URL/原因(goto 报错时给人话,不裸抛 ERR_BLOCKED_BY_CLIENT) */
214
+ lastBlock;
215
+ closed = false;
216
+ constructor(browser, context, page, actionTimeoutMs, ownerKey, onClosed, sessionOptions) {
217
+ this.browser = browser;
218
+ this.context = context;
219
+ this.page = page;
220
+ this.actionTimeoutMs = actionTimeoutMs;
221
+ this.onClosed = onClosed;
222
+ this.sessionOptions = sessionOptions;
223
+ this.id = `bs_${randomUUID()}`;
224
+ this.engine = sessionOptions?.engine ?? 'playwright';
225
+ this.identity = sessionOptions?.identity ?? { kind: 'incognito' };
226
+ this.ownerKey = ownerKey;
227
+ // 顶层导航(goto 与 act 引起的跳转都算)→ 旧 ref 全失效(stale_ref 契约对 act 导航成立)
228
+ page.on('framenavigated', (frame) => {
229
+ if (frame === page.mainFrame())
230
+ this.invalidateRefs();
231
+ });
232
+ }
233
+ /** 策略拦截回调(port 路由处理器注入) */
234
+ noteBlocked(url, reason) {
235
+ this.lastBlock = { url, reason };
236
+ }
237
+ /**
238
+ * ref 全失效(导航时由监听触发)。epoch 保持单调递增——
239
+ * **不得归零**:归零会让导航前后的 ref 命名空间碰撞(旧 ref 静默命中新页面元素)。
240
+ */
241
+ invalidateRefs() {
242
+ this.refMeta.clear();
243
+ }
244
+ get url() {
245
+ return this.page.url();
246
+ }
247
+ async goto(url, options) {
248
+ this.lastBlock = undefined;
249
+ let resp;
250
+ try {
251
+ resp = await this.page.goto(url, {
252
+ waitUntil: options?.waitUntil ?? 'load',
253
+ timeout: options?.timeoutMs ?? this.actionTimeoutMs,
254
+ });
255
+ }
256
+ catch (err) {
257
+ throw this.mapBlockedError(err);
258
+ }
259
+ const result = { url: this.page.url(), title: await this.page.title() };
260
+ // 无 HTTP 响应(同文档导航/特殊 scheme)时省略 status,不编造
261
+ const status = resp?.status();
262
+ if (typeof status === 'number')
263
+ result.status = status;
264
+ return result;
265
+ }
266
+ /** 策略拦截导致的失败 → 报人话原因(不裸抛 ERR_BLOCKED_BY_CLIENT) */
267
+ mapBlockedError(err) {
268
+ const message = err instanceof Error ? err.message : String(err);
269
+ if (this.lastBlock && /ERR_BLOCKED_BY_CLIENT|net::ERR/.test(message)) {
270
+ return new Error(this.lastBlock.reason);
271
+ }
272
+ return err instanceof Error ? err : new Error(String(err));
273
+ }
274
+ async snapshot(options) {
275
+ this.epoch += 1;
276
+ this.refMeta.clear();
277
+ const raw = await this.page.evaluate(PAGE_WALK_FN, {
278
+ epoch: this.epoch,
279
+ interactiveOnly: options?.interactiveOnly ?? false,
280
+ selector: INTERACTIVE_SELECTOR,
281
+ textyTags: [...TEXTY_TAGS],
282
+ });
283
+ const maxChars = options?.maxChars ?? 8000;
284
+ let cost = 0;
285
+ let truncated = false;
286
+ const items = [];
287
+ for (const entry of raw) {
288
+ const item = entry.ref
289
+ ? {
290
+ ref: entry.ref,
291
+ role: entry.role,
292
+ name: entry.name,
293
+ ...(entry.value === undefined ? {} : { value: entry.value }),
294
+ ...(entry.checked === undefined ? {} : { checked: entry.checked }),
295
+ ...(entry.tags?.length ? { tags: entry.tags } : {}),
296
+ }
297
+ : { role: entry.role === 'heading' ? 'heading' : 'text', name: entry.name };
298
+ cost += item.name.length + ('value' in item ? item.value?.length ?? 0 : 0);
299
+ if (cost > maxChars) {
300
+ truncated = true;
301
+ break;
302
+ }
303
+ items.push(item);
304
+ if (entry.ref) {
305
+ this.refMeta.set(entry.ref, {
306
+ role: entry.role,
307
+ name: entry.name,
308
+ tags: entry.tags ?? [],
309
+ });
310
+ }
311
+ }
312
+ return {
313
+ url: this.page.url(),
314
+ title: await this.page.title(),
315
+ items,
316
+ ...(truncated ? { truncated: true } : {}),
317
+ };
318
+ }
319
+ async inspectAction(action) {
320
+ const target = 'ref' in action && action.ref ? this.refMeta.get(action.ref) : undefined;
321
+ if ('ref' in action && action.ref && !target) {
322
+ throw new Error(`stale_ref: ${action.ref} is not in the latest snapshot — call browser_snapshot`);
323
+ }
324
+ let sensitive = false;
325
+ if (target?.tags.includes('password') && action.kind === 'fill') {
326
+ sensitive = {
327
+ kind: 'passwordField',
328
+ description: `fill password field "${target.name || 'password'}"`,
329
+ };
330
+ }
331
+ else if (target?.tags.includes('submit') && action.kind === 'click') {
332
+ sensitive = {
333
+ kind: 'formSubmit',
334
+ description: `submit form via "${target.name || 'submit'}"`,
335
+ };
336
+ }
337
+ else if (action.kind === 'upload') {
338
+ sensitive = {
339
+ kind: 'fileUpload',
340
+ description: `upload file to "${target?.name || 'file input'}"`,
341
+ };
342
+ }
343
+ return {
344
+ action,
345
+ sensitive,
346
+ ...(target ? { target: { role: target.role, name: target.name } } : {}),
347
+ };
348
+ }
349
+ async act(action) {
350
+ try {
351
+ await this.runAction(action);
352
+ }
353
+ catch (err) {
354
+ // act 引起的导航被策略拦截时同样报人话原因(与 goto 同一映射)
355
+ throw this.mapBlockedError(err);
356
+ }
357
+ return { ok: true, url: this.page.url(), title: await this.page.title() };
358
+ }
359
+ async runAction(action) {
360
+ const locatorFor = async (ref) => {
361
+ if (!this.refMeta.has(ref)) {
362
+ throw new Error(`stale_ref: ${ref} is not in the latest snapshot — call browser_snapshot`);
363
+ }
364
+ const loc = this.page.locator(`[data-octopi-ref="${ref}"]`);
365
+ // DOM 重渲染会抹掉属性:找不到目标即 stale_ref fail-loud(不 30s 干等)
366
+ if ((await loc.count()) === 0) {
367
+ throw new Error(`stale_ref: ${ref} no longer present in the page (re-rendered?) — call browser_snapshot`);
368
+ }
369
+ return loc;
370
+ };
371
+ switch (action.kind) {
372
+ case 'click':
373
+ await (await locatorFor(action.ref)).click({ timeout: this.actionTimeoutMs });
374
+ break;
375
+ case 'fill': {
376
+ const locator = await locatorFor(action.ref);
377
+ const typing = this.sessionOptions?.humanize?.typingDelayMs;
378
+ if (typing) {
379
+ // P3 拟人化:逐键敲入(每键延迟在区间内随机采样),行为面接近真人
380
+ const [lo, hi] = typing;
381
+ const min = Math.max(0, Math.min(lo, hi));
382
+ const span = Math.abs(hi - lo);
383
+ for (const ch of action.value) {
384
+ await locator.pressSequentially(ch, { timeout: this.actionTimeoutMs });
385
+ await this.page.waitForTimeout(min + Math.random() * span);
386
+ }
387
+ }
388
+ else {
389
+ await locator.fill(action.value, { timeout: this.actionTimeoutMs });
390
+ }
391
+ break;
392
+ }
393
+ case 'select':
394
+ await (await locatorFor(action.ref)).selectOption(action.value, {
395
+ timeout: this.actionTimeoutMs,
396
+ });
397
+ break;
398
+ case 'check':
399
+ await (await locatorFor(action.ref)).check({ timeout: this.actionTimeoutMs });
400
+ break;
401
+ case 'uncheck':
402
+ await (await locatorFor(action.ref)).uncheck({ timeout: this.actionTimeoutMs });
403
+ break;
404
+ case 'hover':
405
+ await (await locatorFor(action.ref)).hover({ timeout: this.actionTimeoutMs });
406
+ break;
407
+ case 'press':
408
+ if (action.ref) {
409
+ await (await locatorFor(action.ref)).press(action.key, {
410
+ timeout: this.actionTimeoutMs,
411
+ });
412
+ }
413
+ else {
414
+ await this.page.keyboard.press(action.key);
415
+ }
416
+ break;
417
+ case 'scroll':
418
+ await this.page.mouse.wheel(0, action.deltaY);
419
+ break;
420
+ case 'wait':
421
+ await this.page.waitForTimeout(Math.min(Math.max(action.ms, 0), 10_000));
422
+ break;
423
+ case 'upload':
424
+ await (await locatorFor(action.ref)).setInputFiles(action.path, {
425
+ timeout: this.actionTimeoutMs,
426
+ });
427
+ break;
428
+ }
429
+ }
430
+ /**
431
+ * 挑战页启发式识别(arch/browser-capability.md §3.7)。
432
+ * 标记表刻意小而诚实:命中即透出 kind+marker,不装懂(漏检是已知边界)。
433
+ */
434
+ async detectChallenge() {
435
+ const probe = await this.page.evaluate(() => {
436
+ const doc = globalThis
437
+ .document;
438
+ return {
439
+ title: (doc.title || '').toLowerCase(),
440
+ text: (doc.body?.innerText || '').slice(0, 4000).toLowerCase(),
441
+ };
442
+ });
443
+ for (const entry of CHALLENGE_MARKERS) {
444
+ const haystack = entry.titleOnly ? probe.title : `${probe.title}\n${probe.text}`;
445
+ if (haystack.includes(entry.marker)) {
446
+ return { kind: entry.kind, marker: entry.marker };
447
+ }
448
+ }
449
+ return undefined;
450
+ }
451
+ /** 确定性结构化抽取(CSS 选择器 → 真实数据;无匹配字段/属性 = null,不编造) */
452
+ async extract(spec) {
453
+ return this.page.evaluate((rawSpec) => {
454
+ const doc = globalThis.document;
455
+ const out = {};
456
+ const counts = {};
457
+ let truncated = false;
458
+ for (const [key, field] of Object.entries(rawSpec)) {
459
+ const els = Array.from(doc.querySelectorAll(field.selector));
460
+ const pick = (el) => field.attribute
461
+ ? el.getAttribute(field.attribute) // 属性缺失 = null(如实,不编空串)
462
+ : (el.textContent ?? '').trim();
463
+ // multiple 预算:maxItems(缺省 50)截断并回报命中总数(评审 N5:截断≠全量)
464
+ const maxItems = typeof field.maxItems === 'number' && field.maxItems > 0 ? field.maxItems : 50;
465
+ if (field.multiple) {
466
+ counts[key] = els.length;
467
+ if (els.length > maxItems)
468
+ truncated = true;
469
+ out[key] = els.slice(0, maxItems).map(pick);
470
+ }
471
+ else {
472
+ out[key] = els.length > 0 ? pick(els[0]) : null;
473
+ }
474
+ }
475
+ return { data: out, truncated, counts };
476
+ }, spec);
477
+ }
478
+ async screenshot(options) {
479
+ const type = options?.type === 'jpeg' ? 'jpeg' : 'png';
480
+ const data = options?.ref != null
481
+ ? await this.locatorForScreenshot(options.ref).screenshot({ type })
482
+ : await this.page.screenshot({ type, ...(options?.fullPage ? { fullPage: true } : {}) });
483
+ return { mimeType: type === 'jpeg' ? 'image/jpeg' : 'image/png', data };
484
+ }
485
+ locatorForScreenshot(ref) {
486
+ if (!this.refMeta.has(ref)) {
487
+ throw new Error(`stale_ref: ${ref} is not in the latest snapshot — call browser_snapshot`);
488
+ }
489
+ return this.page.locator(`[data-octopi-ref="${ref}"]`);
490
+ }
491
+ async close() {
492
+ if (this.closed)
493
+ return;
494
+ this.closed = true;
495
+ this.refMeta.clear();
496
+ // 两个关闭步骤都尽力执行;无论成败都自报(否则端口表残留死会话)
497
+ let firstError;
498
+ // profile 归档必须在上下文关闭前(storageState 需要活上下文);失败如实带出(登录态未存盘)
499
+ const profile = this.sessionOptions?.profile;
500
+ if (profile?.persist && this.sessionOptions?.closeMode !== 'attach') {
501
+ try {
502
+ await this.persistProfileState(profile);
503
+ }
504
+ catch (err) {
505
+ firstError = err;
506
+ }
507
+ }
508
+ try {
509
+ if (this.sessionOptions?.closeMode === 'attach') {
510
+ // attach:只关我们开的页 + 断开连接——绝不动用户的上下文/浏览器(close=断开,已实证)。
511
+ // 页已被用户手动关掉时 close 会抛:目标已达成,幂等化不冒泡(评审 F15)
512
+ await this.page.close().catch(() => {
513
+ /* 用户已自行关页:视为目标达成 */
514
+ });
515
+ }
516
+ else {
517
+ await this.context.close();
518
+ }
519
+ }
520
+ catch (err) {
521
+ firstError ??= err;
522
+ }
523
+ try {
524
+ await this.browser.close();
525
+ }
526
+ catch (err) {
527
+ firstError ??= err;
528
+ }
529
+ this.onClosed?.(this.id);
530
+ if (firstError)
531
+ throw firstError;
532
+ }
533
+ async persistProfileState(profile) {
534
+ const state = await this.context.storageState();
535
+ const { mkdir, rename, writeFile } = await import('node:fs/promises');
536
+ const { join } = await import('node:path');
537
+ // storageState 含全部站点 cookie(凭据级):目录 0700、文件 0600、原子替换(评审 F6)
538
+ await mkdir(profile.dir, { recursive: true, mode: 0o700 });
539
+ const target = join(profile.dir, `${profile.id}.json`);
540
+ const tmp = `${target}.tmp-${randomUUID()}`;
541
+ await writeFile(tmp, typeof state === 'string' ? state : JSON.stringify(state), {
542
+ mode: 0o600,
543
+ });
544
+ await rename(tmp, target); // 半写 JSON 会把 profile 永久 brick——必须原子落盘
545
+ }
546
+ }
547
+ /** Playwright BrowserPort 实现 */
548
+ export class PlaywrightBrowserPort {
549
+ defaults;
550
+ sessions = new Map();
551
+ constructor(defaults = {}) {
552
+ this.defaults = defaults;
553
+ }
554
+ async launch(options) {
555
+ // attach 引擎:会话建立在用户已打开的真实浏览器上(复用登录/指纹)
556
+ if (this.defaults.attachMode) {
557
+ return this.attach({
558
+ endpoint: this.defaults.attachEndpoint,
559
+ timeoutMs: options?.timeoutMs,
560
+ ownerKey: options?.ownerKey,
561
+ policy: options?.policy,
562
+ });
563
+ }
564
+ const channel = options?.channel ?? this.defaults.channel;
565
+ const headless = options?.headless ?? this.defaults.headless ?? true;
566
+ let browser;
567
+ try {
568
+ if (this.defaults.launcher) {
569
+ browser = await this.defaults.launcher({
570
+ headless,
571
+ channel,
572
+ timeoutMs: options?.timeoutMs ?? this.defaults.timeoutMs,
573
+ });
574
+ }
575
+ else {
576
+ const pw = await resolveDriver(this.defaults.driver ?? 'playwright-core');
577
+ browser = await pw.chromium.launch({
578
+ headless,
579
+ ...(channel === 'chrome' ? { channel: 'chrome' } : {}),
580
+ });
581
+ }
582
+ }
583
+ catch (err) {
584
+ throw mapLaunchError(err);
585
+ }
586
+ // 持久 profile:恢复既有 storageState(文件不存在 = 全新,如实从零开始)
587
+ const profile = options?.profileId && options?.profileDir
588
+ ? {
589
+ id: options.profileId,
590
+ dir: options.profileDir,
591
+ persist: options.persistProfile ?? false,
592
+ }
593
+ : undefined;
594
+ const statePath = profile ? join(profile.dir, `${profile.id}.json`) : undefined;
595
+ const storageState = statePath && (await fileExists(statePath)) ? statePath : undefined;
596
+ const newContextPage = async (state) => {
597
+ const context = await browser.newContext({
598
+ ...(state ? { storageState: state } : {}),
599
+ ...(options?.viewport ?? this.defaults.viewport
600
+ ? { viewport: options?.viewport ?? this.defaults.viewport }
601
+ : {}),
602
+ ...(options?.locale ?? this.defaults.locale
603
+ ? { locale: options?.locale ?? this.defaults.locale }
604
+ : {}),
605
+ });
606
+ return { context, page: await context.newPage() };
607
+ };
608
+ let created;
609
+ try {
610
+ created = await newContextPage(storageState);
611
+ }
612
+ catch (err) {
613
+ if (!storageState) {
614
+ // context/page 建失败必须回收 browser,否则泄漏浏览器进程
615
+ await browser.close().catch(() => {
616
+ /* 已失败路径上再失败不掩盖首错 */
617
+ });
618
+ throw err instanceof Error ? err : new Error(String(err));
619
+ }
620
+ // storageState 损坏/不兼容:隔离坏档(保留现场)并从零开始——显式降级不 brick(评审 F6)
621
+ const quarantined = await quarantineProfileState(storageState);
622
+ console.warn(`[browser] profile state unusable, ${quarantined ? 'quarantined' : 'quarantine FAILED'} and starting fresh: ${storageState}`);
623
+ if (!quarantined && profile) {
624
+ // 隔离失败:close 时不得再写覆盖坏档(现场优先于归档,评审 N6)
625
+ profile.persist = false;
626
+ console.warn('[browser] refusing to overwrite the corrupt profile file on close (persist disabled)');
627
+ }
628
+ try {
629
+ created = await newContextPage(undefined);
630
+ }
631
+ catch (err2) {
632
+ await browser.close().catch(() => {
633
+ /* 同上 */
634
+ });
635
+ throw err2 instanceof Error ? err2 : new Error(String(err2));
636
+ }
637
+ }
638
+ const { context, page } = created;
639
+ const session = new PlaywrightBrowserSession(browser, context, page, options?.timeoutMs ?? this.defaults.timeoutMs ?? BROWSER_DEFAULT_TIMEOUT_MS, options?.ownerKey ?? '', (id) => {
640
+ this.sessions.delete(id);
641
+ }, {
642
+ identity: profile ? { kind: 'profile', profileId: profile.id } : { kind: 'incognito' },
643
+ closeMode: 'managed',
644
+ ...(this.defaults.engine ? { engine: this.defaults.engine } : {}),
645
+ ...(profile ? { profile } : {}),
646
+ ...(options?.humanize ? { humanize: options.humanize } : {}),
647
+ });
648
+ try {
649
+ await this.installRequestPolicy(context, page, options?.policy, (url, reason) => session.noteBlocked(url, reason));
650
+ }
651
+ catch (err) {
652
+ // 策略安装失败 = 会话不可安全使用:回收 browser(否则泄漏进程且无策略裸奔)
653
+ await browser.close().catch(() => {
654
+ /* 回收失败不掩盖首错 */
655
+ });
656
+ throw err instanceof Error ? err : new Error(String(err));
657
+ }
658
+ this.installPopupGuard(context, page, options?.policy, 'managed');
659
+ this.sessions.set(session.id, session);
660
+ return session;
661
+ }
662
+ /**
663
+ * 单页契约弹窗收口。按模式分支(评审 F2/N2):
664
+ * - `managed`:context 为本会话独占——**所有**新页都关。防御性设计:不依赖 CDP 的
665
+ * opener 行为(实证:本栈页内创建的弹窗即使 `rel=noopener` 也带 openerId;
666
+ * opener-less 页面只可能来自 context.newPage() 等页外路径);
667
+ * - `attach`:同 context 里有用户自己的标签——只关**本页打开的**弹窗(opener 实例
668
+ * 同一性判定,异步),用户自己的标签不碰。
669
+ * 首请求存在与关闭的竞态窗口(KNOWN-ISSUES)。
670
+ */
671
+ installPopupGuard(context, ownerPage, policy, closeMode) {
672
+ context.on('page', (p) => {
673
+ void (async () => {
674
+ const popup = p;
675
+ if (closeMode === 'attach') {
676
+ // opener() 是异步的;同一 context 下实例同一性成立(实证)
677
+ const opener = await popup.opener().catch(() => null);
678
+ if (opener !== ownerPage)
679
+ return; // 用户自己的新标签/无主弹窗:不碰
680
+ }
681
+ try {
682
+ policy?.record?.({
683
+ kind: 'blocked',
684
+ url: popup.url(),
685
+ reason: 'popup not allowed (single-page session contract)',
686
+ });
687
+ }
688
+ catch {
689
+ /* 审计回调抛错不得影响收口(与请求层同一原则) */
690
+ }
691
+ await popup.close().catch(() => {
692
+ /* 已关/已崩时无可挽回 */
693
+ });
694
+ })();
695
+ });
696
+ }
697
+ /**
698
+ * 请求级策略安装(每请求收口:URL 判定 + 非 GET 导航写闸 + 账本)。
699
+ *
700
+ * Chromium 系走 **CDP Fetch 域**(网络栈级逐请求暂停):`context.route` 在重定向
701
+ * 跟随跳上不触发(实证:302 目标由网络栈内部跟走、route 看不到)——路由级拦截
702
+ * 会漏掉正是策略最该管的跳转目标,故 Chromium 弃用 route(评审 B2)。Firefox 系
703
+ * (camoufox)无 CDP Fetch 域,走 {@link installRequestPolicyRouteWalk} 逐跳走查
704
+ * 同等语义(P3)。
705
+ */
706
+ async installRequestPolicy(context, page, policy, onBlock) {
707
+ if (!policy)
708
+ return; // 裸端口直用(无策略注入)不做拦截
709
+ if ((this.defaults.policyMode ?? 'cdp-fetch') === 'route-walk') {
710
+ await this.installRequestPolicyRouteWalk(context, policy, onBlock);
711
+ return;
712
+ }
713
+ const cdp = await context.newCDPSession(page);
714
+ // 审计/回执回调的抛错不得影响请求终局(否则请求悬停到超时)——统一吞在 safe 调用里
715
+ const safeRecord = (event) => {
716
+ try {
717
+ policy.record?.(event);
718
+ }
719
+ catch {
720
+ /* 审计回调自身抛错:吞掉(终局动作优先,悬停比丢一条账更糟) */
721
+ }
722
+ };
723
+ const safeBlock = (url, reason) => {
724
+ try {
725
+ onBlock(url, reason);
726
+ }
727
+ catch {
728
+ /* 拦截回执抛错:吞掉(同上) */
729
+ }
730
+ };
731
+ cdp.on('Fetch.requestPaused', (e) => {
732
+ void (async () => {
733
+ const url = e.request.url;
734
+ const method = e.request.method;
735
+ let decision = 'continue';
736
+ try {
737
+ await policy.checkUrl(url);
738
+ // 外部写闸门(P2 收紧):**所有非 GET 请求**都过 confirmWrite——
739
+ // 文档级(表单/上传)与页内 fetch/XHR 都是外部写;工具层按 method+origin 缓存审批
740
+ if (WRITE_METHODS.has(method)) {
741
+ safeRecord({ kind: 'write.attempt', url, method });
742
+ const allowed = await policy.confirmWrite({
743
+ method,
744
+ url,
745
+ documentLevel: e.resourceType === 'Document',
746
+ });
747
+ if (!allowed) {
748
+ decision = 'deny';
749
+ const reason = `denied: browser write ${method} not approved`;
750
+ safeBlock(url, reason);
751
+ safeRecord({ kind: 'write.blocked', url, method, reason });
752
+ }
753
+ }
754
+ }
755
+ catch (err) {
756
+ decision = 'deny';
757
+ const reason = err instanceof Error ? err.message : String(err);
758
+ safeBlock(url, reason);
759
+ safeRecord({ kind: 'blocked', url, method, reason });
760
+ }
761
+ finally {
762
+ // 终局动作保证:任何中间异常(含回调抛错)都不让请求悬停
763
+ try {
764
+ if (decision === 'continue') {
765
+ await cdp.send('Fetch.continueRequest', { requestId: e.requestId });
766
+ }
767
+ else {
768
+ await cdp.send('Fetch.failRequest', {
769
+ requestId: e.requestId,
770
+ errorReason: 'BlockedByClient',
771
+ });
772
+ }
773
+ }
774
+ catch {
775
+ /* CDP 会话已随浏览器关闭:请求自然终止,无可挽回 */
776
+ }
777
+ }
778
+ })();
779
+ });
780
+ await cdp.send('Fetch.enable', { patterns: [{ urlPattern: '*' }] });
781
+ }
782
+ /**
783
+ * 路由级策略(P3:Firefox/camoufox 后端——Juggler 无 CDP Fetch 域)。
784
+ *
785
+ * `context.route` 同样不触发于重定向跟随跳,故**逐跳走查**:`route.fetch` 以
786
+ * `maxRedirects: 0` 把每一跳摊在明面,每跳都过 URL 策略与写闸,最终响应
787
+ * `route.fulfill` 回填——与 CDP Fetch 路径语义对齐(arch §3.6 同等语义)。
788
+ * 307/308 保留方法(写随跳走、闸跟着走);301/302/303 降级 GET(丢 body)。
789
+ * 残余边界(KNOWN-ISSUES):WS/ServiceWorker 请求不经 route。
790
+ */
791
+ async installRequestPolicyRouteWalk(context, policy, onBlock) {
792
+ // 审计/回执回调的抛错不得影响请求终局(否则请求悬停到超时)——统一吞在 safe 调用里
793
+ const safeRecord = (event) => {
794
+ try {
795
+ policy.record?.(event);
796
+ }
797
+ catch {
798
+ /* 审计回调自身抛错:吞掉(终局动作优先,悬停比丢一条账更糟) */
799
+ }
800
+ };
801
+ const safeBlock = (url, reason) => {
802
+ try {
803
+ onBlock(url, reason);
804
+ }
805
+ catch {
806
+ /* 拦截回执抛错:吞掉(同上) */
807
+ }
808
+ };
809
+ await context.route('**/*', (route) => {
810
+ void (async () => {
811
+ const req = route.request();
812
+ let url = req.url();
813
+ let method = req.method();
814
+ const documentLevel = req.resourceType() === 'Document';
815
+ try {
816
+ // 逐跳走查(10 跳为安全界,非部署旋钮):每跳过 URL 策略 + 写闸
817
+ for (let hop = 0; hop < 10; hop++) {
818
+ await policy.checkUrl(url);
819
+ if (WRITE_METHODS.has(method)) {
820
+ safeRecord({ kind: 'write.attempt', url, method });
821
+ const allowed = await policy.confirmWrite({ method, url, documentLevel });
822
+ if (!allowed) {
823
+ const reason = `denied: browser write ${method} not approved`;
824
+ safeBlock(url, reason);
825
+ safeRecord({ kind: 'write.blocked', url, method, reason });
826
+ await route.abort('blockedbyclient').catch(() => {
827
+ /* 页已关:请求自然终止 */
828
+ });
829
+ return;
830
+ }
831
+ }
832
+ const resp = await route.fetch({
833
+ url,
834
+ method,
835
+ maxRedirects: 0,
836
+ ...(method === 'GET' || method === 'HEAD' ? { postData: '' } : {}),
837
+ });
838
+ const status = resp.status();
839
+ if (status >= 300 && status < 400) {
840
+ const headers = resp.headers();
841
+ const location = headers['location'] ?? headers['Location'];
842
+ if (!location)
843
+ break; // 无 Location 的 3xx:原样回填(无下一跳可走查)
844
+ url = new URL(location, url).toString();
845
+ // 307/308 保留方法(写随跳走);其余依规降级 GET(丢 body)
846
+ if (status !== 307 && status !== 308)
847
+ method = 'GET';
848
+ continue;
849
+ }
850
+ await route.fulfill({ response: resp });
851
+ return;
852
+ }
853
+ throw new Error('denied: too many redirects (10 hops)');
854
+ }
855
+ catch (err) {
856
+ const reason = err instanceof Error ? err.message : String(err);
857
+ safeBlock(url, reason);
858
+ safeRecord({ kind: 'blocked', url, method, reason });
859
+ await route.abort('blockedbyclient').catch(() => {
860
+ /* 页已关:请求自然终止 */
861
+ });
862
+ }
863
+ })();
864
+ });
865
+ }
866
+ /**
867
+ * attach 用户真实浏览器(P2;connectOverCDP,复用其登录/指纹)。
868
+ *
869
+ * 安全语义(已实证):策略经 CDP Fetch 同样逐请求收口;`browser.close()` = 断开
870
+ * 连接、不杀用户浏览器;会话关闭只关我们开的页(closeMode='attach')。
871
+ */
872
+ async attach(options) {
873
+ // attach 恒为 Chromium CDP(用户真实 Chrome);与 launcher/driver 旋钮无关
874
+ const pw = await resolveDriver('playwright-core');
875
+ const endpoint = options?.endpoint ?? this.defaults.attachEndpoint ?? 'http://127.0.0.1:9222';
876
+ let browser;
877
+ try {
878
+ browser = await pw.chromium.connectOverCDP(endpoint, {
879
+ timeout: options?.timeoutMs ?? this.defaults.timeoutMs ?? BROWSER_DEFAULT_TIMEOUT_MS,
880
+ });
881
+ }
882
+ catch (err) {
883
+ const detail = (err instanceof Error ? err.message : String(err)).split('\n')[0];
884
+ throw new Error(`browser_attach_failed: cannot connect to ${endpoint} — start Chrome with --remote-debugging-port and retry (${detail})`, { cause: err });
885
+ }
886
+ const context = browser.contexts()[0] ?? (await browser.newContext());
887
+ let page;
888
+ try {
889
+ page = await context.newPage();
890
+ }
891
+ catch (err) {
892
+ await browser.close().catch(() => {
893
+ /* 断开失败不掩盖首错 */
894
+ });
895
+ throw err instanceof Error ? err : new Error(String(err));
896
+ }
897
+ const session = new PlaywrightBrowserSession(browser, context, page, options?.timeoutMs ?? this.defaults.timeoutMs ?? BROWSER_DEFAULT_TIMEOUT_MS, options?.ownerKey ?? '', (id) => {
898
+ this.sessions.delete(id);
899
+ }, { identity: { kind: 'attach' }, engine: 'cdp-attach', closeMode: 'attach' });
900
+ try {
901
+ await this.installRequestPolicy(context, page, options?.policy, (url, reason) => session.noteBlocked(url, reason));
902
+ }
903
+ catch (err) {
904
+ // 策略安装失败 = 会话不可安全使用:关掉我们开的页并断开(用户浏览器不受影响)
905
+ await page.close().catch(() => {
906
+ /* 已失败路径上再失败不掩盖首错 */
907
+ });
908
+ await browser.close().catch(() => {
909
+ /* 同上 */
910
+ });
911
+ throw err instanceof Error ? err : new Error(String(err));
912
+ }
913
+ this.installPopupGuard(context, page, options?.policy, 'attach');
914
+ this.sessions.set(session.id, session);
915
+ return session;
916
+ }
917
+ async list() {
918
+ return [...this.sessions.values()].map((s) => ({
919
+ id: s.id,
920
+ engine: s.engine,
921
+ identity: s.identity,
922
+ url: s.url,
923
+ }));
924
+ }
925
+ }