@capyclaw/scrapling 1.1.4 → 1.1.7

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 (96) hide show
  1. package/README.md +7 -7
  2. package/cordis.patch.yml +0 -2
  3. package/lib/html-parser.mjs +1 -1
  4. package/lib/index.mjs +1 -1
  5. package/lib/runtime.mjs +102 -0
  6. package/lib/selectors.mjs +1 -1
  7. package/node_modules/@capyclaw/foundation/README.md +51 -0
  8. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  9. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  10. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  11. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  12. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  13. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  14. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  15. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  16. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  17. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  18. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  19. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  20. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  30. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  31. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  32. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  33. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  34. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  35. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  36. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  37. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
  38. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  39. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  40. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  41. package/node_modules/@capyclaw/foundation/package.json +53 -0
  42. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  43. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  44. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  45. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  46. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  72. package/node_modules/@capyclaw/portal/README.md +70 -0
  73. package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
  74. package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
  75. package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
  76. package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
  77. package/node_modules/@capyclaw/portal/package.json +40 -0
  78. package/node_modules/@capyclaw/service-broker/README.md +104 -0
  79. package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
  80. package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
  81. package/node_modules/@capyclaw/service-broker/lib/control.mjs +193 -0
  82. package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
  83. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1236 -0
  84. package/node_modules/@capyclaw/service-broker/lib/host.mjs +182 -0
  85. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +249 -0
  86. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +325 -0
  87. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +28 -0
  88. package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
  89. package/node_modules/@capyclaw/service-broker/package.json +65 -0
  90. package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
  91. package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
  92. package/node_modules/@capyclaw/service-broker/services.json +3 -0
  93. package/package.json +20 -7
  94. package/plugin.mjs +57 -0
  95. package/server/server.mjs +2 -10
  96. package/lib/host.mjs +0 -170
package/README.md CHANGED
@@ -14,7 +14,7 @@ Scrapling 网页抓取插件 —— 为 DeepSeek Harness 提供网页数据爬
14
14
  - `:first-child` / `:last-child` / `:nth-child(k)`
15
15
  - 逗号分组按文档序合并去重(XPath union 语义)
16
16
  - 支持中文类名/属性值
17
- - **爬虫工作台**(默认 `http://127.0.0.1:39640/`,端口由 broker 管理)—— 浏览器打开即用:
17
+ - **爬虫工作台**(挂在宿主前缀 `/plugins/scrapling/`,同源,地址里不含端口)—— 浏览器打开即用:
18
18
  - 三步引导:选目标 → 观察流程 → 取数据
19
19
  - 爬取流程逐步回放(每步真实耗时:解析 URL → 发请求 → 收响应 → 读内容 → 建文档树 → 提取 → 完成)
20
20
  - 选择器试玩(随时改随时提取,不重新请求)
@@ -32,8 +32,8 @@ Scrapling 网页抓取插件 —— 为 DeepSeek Harness 提供网页数据爬
32
32
 
33
33
  ```bash
34
34
  # 方式一:独立启动工作台(推荐,浏览器打开即用)
35
- cd extensions/official/capyclaw-scrapling
36
- node server/server.mjs # 默认 http://127.0.0.1:39640/
35
+ cd B/official/capyclaw-scrapling
36
+ node server/server.mjs # 启动后日志会打印当前绑定地址
37
37
  # 或指定端口
38
38
  node server/server.mjs --port 39641
39
39
 
@@ -128,7 +128,7 @@ capyclaw-scrapling/
128
128
 
129
129
  ```bash
130
130
  # 单元测试(52 项:解析器 / 选择器 / API / 宿主装配 / 真实世界边界)
131
- cd extensions/official/capyclaw-scrapling && npm test
131
+ cd B/official/capyclaw-scrapling && npm test
132
132
 
133
133
  # 真实互联网实测(多站点多结构:quotes/books/baidu/gitee/httpbin)
134
134
  node test/internet-campaign.mjs
@@ -137,14 +137,14 @@ node test/internet-campaign.mjs
137
137
  node scripts/e2e-all.mjs --layer l3
138
138
 
139
139
  # 插件规范校验
140
- node tools/capyclaw-plugin-validator/bin/cli.mjs extensions/official/capyclaw-scrapling
140
+ node C/tools/capyclaw-plugin-validator/bin/cli.mjs B/official/capyclaw-scrapling
141
141
  ```
142
142
 
143
143
  ## 故障排除
144
144
 
145
145
  | 症状 | 处理 |
146
146
  |---|---|
147
- | 打不开 39640 | `node server/server.mjs` 看启动日志;端口被占时用 `--port` 换一个 |
147
+ | 打不开工作台 | `node server/server.mjs` 看启动日志(里面有当前绑定地址);端口被占时用 `--port` 换一个 |
148
148
  | 爬取报「无法连接到目标网址」 | 先在浏览器里确认目标网址能打开;内网地址确认服务已启动 |
149
149
  | 提取 0 条数据 | 展开页面上的「原始 HTML」对照选择器写法;从演示目标开始学 |
150
150
  | 想要浏览器渲染 / XPath | 当前版本未实现,需要外部 Python scrapling 运行时 |
@@ -162,7 +162,7 @@ MIT License
162
162
  ## 版本历史
163
163
 
164
164
  ### 1.1.0 (2026-11-05)
165
- - 🆕 可视化爬虫工作台(`http://127.0.0.1:39640/`):流程回放、选择器试玩、JSON/CSV 导出、历史回看、三个内置离线演示页
165
+ - 🆕 可视化爬虫工作台(宿主前缀 `/plugins/scrapling/`):流程回放、选择器试玩、JSON/CSV 导出、历史回看、三个内置离线演示页
166
166
  - 🆕 `parse()` 真实实现:自研容错 HTML 解析器 + CSS 选择器引擎(`::text` / `::attr` / 组合器 / 伪类 / 中文标识符)
167
167
  - 🆕 爬取流水线 `crawler.crawl()`:步骤计时、结构化错误(含「下一步」提示)、20 条历史
168
168
  - 🆕 服务契约 `/healthz` + `/metrics`,浏览器半挂 DSH 右侧边栏
package/cordis.patch.yml CHANGED
@@ -10,8 +10,6 @@
10
10
  # workbench 是否拉起工作台 DSH_SCRAPLING_WORKBENCH true
11
11
 
12
12
  - insert:
13
- - id: service-broker
14
- name: "@capyclaw/service-broker"
15
13
  - id: scrapling-host
16
14
  name: "@capyclaw/scrapling"
17
15
  config:
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * 容错 HTML 解析器(纯 Node 内置实现,零外部依赖)。
3
3
  *
4
- * 目的:为 ctx.scrapling.parse() / 选择器引擎提供文档树。
4
+ * 目的:为 scrapling.parse() / 选择器引擎提供文档树。
5
5
  * 仓库约定不引入 cheerio/jsdom 等依赖,因此这里实现一个
6
6
  * 「HTML5 子集 + 常见畸形容错」的单遍解析器:
7
7
  *
package/lib/index.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  * dsh-scrapling API 导出
3
3
  */
4
4
 
5
- export { name, apply, DEFAULT_PORT } from './host.mjs'
5
+ export { DEFAULT_PORT, PKG_VERSION, createScraplingRuntime, resolveScraplingConfig } from './runtime.mjs'
6
6
  export { parseHtml, documentStats, decodeEntities } from './html-parser.mjs'
7
7
  export { createSelectorDocument, extract, SelectorError } from './selectors.mjs'
8
8
  export { createCrawler } from './crawler.mjs'
@@ -0,0 +1,102 @@
1
+ /**
2
+ * scrapling 纯运行时:不接触 Cordis ctx。
3
+ *
4
+ * 进程内服务走 service-provider;工作台进程走 runtime-driver;
5
+ * 页面注入走 client-panel。工作台固定端口 39640,保证 boot global 先于 broker 就绪。
6
+ */
7
+ import { createRequire } from 'node:module'
8
+ import { resolveConfig } from '@capyclaw/plugin-kit/config'
9
+
10
+ import { createCrawler } from './crawler.mjs'
11
+ import { createSelectorDocument } from './selectors.mjs'
12
+
13
+ const requireFromHere = createRequire(import.meta.url)
14
+ const { version: PKG_VERSION } = requireFromHere('../package.json')
15
+
16
+ export const DEFAULT_PORT = 39640
17
+
18
+ function notImplemented(feature) {
19
+ const error = new Error(
20
+ `[dsh-scrapling] ${feature} 未实现:浏览器渲染与 XPath 依赖外部 Python scrapling 运行时。` +
21
+ '请使用 fetch()/parse()(HTTP 抓取 + CSS 选择器),或另行部署 scrapling 服务后通过 HTTP 调用。',
22
+ )
23
+ error.code = 'NOT_IMPLEMENTED'
24
+ return error
25
+ }
26
+
27
+ export function resolveScraplingConfig(config = {}) {
28
+ const { value: cfg, issues } = resolveConfig(config, {
29
+ envPrefix: 'DSH_SCRAPLING',
30
+ defaults: {
31
+ enabled: true,
32
+ port: DEFAULT_PORT,
33
+ host: '127.0.0.1',
34
+ timeoutMs: 20000,
35
+ workbench: true,
36
+ },
37
+ fields: {
38
+ enabled: { env: 'ENABLED', type: 'boolean' },
39
+ port: { env: 'PORT', type: 'string' },
40
+ host: { env: 'HOST' },
41
+ timeoutMs: { env: 'TIMEOUT_MS', type: 'number' },
42
+ userAgent: { env: 'USER_AGENT' },
43
+ workbench: { env: 'WORKBENCH', type: 'boolean' },
44
+ },
45
+ })
46
+ const port = cfg.port === 'auto' ? 'auto' : Number(cfg.port)
47
+ const servicePort = port === 'auto' || !Number.isInteger(port) || port < 1 || port > 65535
48
+ ? DEFAULT_PORT
49
+ : port
50
+ return { ...cfg, servicePort, issues }
51
+ }
52
+
53
+ export function scraplingEnabled(config = {}) {
54
+ return config.enabled !== false
55
+ }
56
+
57
+ export function scraplingWorkbenchEnabled(config = {}) {
58
+ return config.enabled !== false && config.workbench !== false
59
+ }
60
+
61
+ export function createScraplingRuntime({ config = {}, log }) {
62
+ const cfg = resolveScraplingConfig(config)
63
+ for (const issue of cfg.issues) log?.warn?.(`[dsh-scrapling] 配置: ${issue}`)
64
+ if (cfg.port !== 'auto' && (!Number.isInteger(Number(cfg.port)) || Number(cfg.port) < 1 || Number(cfg.port) > 65535)) {
65
+ log?.warn?.(`[dsh-scrapling] 非法 port=${cfg.port},回退为默认 ${DEFAULT_PORT}`)
66
+ }
67
+ const crawler = createCrawler({ timeoutMs: cfg.timeoutMs, userAgent: cfg.userAgent })
68
+
69
+ const service = {
70
+ async fetch(url, options = {}) {
71
+ const record = await crawler.crawl({
72
+ url,
73
+ timeoutMs: options.timeoutMs,
74
+ userAgent: options.userAgent || options.headers?.['user-agent'],
75
+ })
76
+ if (record.error) {
77
+ const error = new Error(record.error.message)
78
+ error.code = record.error.code
79
+ error.hint = record.error.hint
80
+ throw error
81
+ }
82
+ return { url: record.url, status: record.status, ok: record.ok, headers: {}, html: record.html }
83
+ },
84
+ async fetchWithBrowser() {
85
+ throw notImplemented('fetchWithBrowser')
86
+ },
87
+ parse(html, options = {}) {
88
+ return createSelectorDocument(html, options)
89
+ },
90
+ crawler,
91
+ }
92
+
93
+ return {
94
+ cfg,
95
+ service,
96
+ globals: scraplingWorkbenchEnabled(config)
97
+ ? { __DSH_SCRAPLING__: { url: `http://${cfg.host === '0.0.0.0' ? '127.0.0.1' : cfg.host}:${cfg.servicePort}/`, version: PKG_VERSION } }
98
+ : {},
99
+ }
100
+ }
101
+
102
+ export { PKG_VERSION }
package/lib/selectors.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * CSS 选择器引擎(Scrapy/parsel 语义子集,纯 Node 实现)。
3
3
  *
4
- * 与 ctx.scrapling.parse(html).css(selector) 配套:
4
+ * 与 scrapling.parse(html).css(selector) 配套:
5
5
  * - 复合选择器:tag / * / .class / #id / [attr] / [attr=v] / [attr^=v] /
6
6
  * [attr$=v] / [attr*=v] / [attr~=v] / [attr|=v]
7
7
  * - 结构伪类::first-child / :last-child / :nth-child(k)(k 从 1 计)
@@ -0,0 +1,51 @@
1
+ # @capyclaw/foundation
2
+
3
+ dsh 插件基石层:接口 ABI、插件加载器与内核服务 `ctx.os`。
4
+
5
+ 应用插件不再写 `inject` / `apply` / provider 装配,只声明「我实现了哪个接口」:
6
+
7
+ ```js
8
+ import { createPlugin, skillProvider } from '@capyclaw/foundation/abi'
9
+
10
+ export const { name, inject, apply } = createPlugin({
11
+ name: 'canvas',
12
+ requires: ['canvas.runtime@^1'],
13
+ implements: [skillProvider({ skill: './skills/canvas' })],
14
+ }, import.meta.url)
15
+ ```
16
+
17
+ ## 四个入口
18
+
19
+ | 入口 | 内容 | 谁用 |
20
+ |---|---|---|
21
+ | `.` | Cordis 插件,产出 `ctx.os` | dsh profile |
22
+ | `./abi` | 描述符构建器、加载器、错误码、版本工具 | 应用插件 |
23
+ | `./kit` | plugin-kit 兼容导出,包含 Node/dsh 耦合,非纯函数库 | 兼容调用方 |
24
+ | `./runtime` | `createKernel` 等宿主 API | dsh 之外的宿主(独立技能服务、测试夹具) |
25
+
26
+ ## 状态
27
+
28
+ - 包清单当前为 `0.1.6`;0.1.6 修的是「关掉插件再启用撞 E_DUP_PLUGIN」(disposer 未登记 + 失败
29
+ 记录占名),详见下面的「生命周期」。
30
+ - 分层:应用插件 → ABI → 内核 → Host 适配器 → 本地 Node.js agent 运行时。
31
+ dsh 服务访问位于 Host 适配层;memory 只是参考实现,不证明第二个真实 agent 兼容。
32
+ HTTP/资源/进程仍有本地 Node 协议约束,详见 `docs/HOST-ADAPTER.md`。
33
+ - ABI v1,六个标准接口 + `host-event@1` + `client-panel@1` + `service-provider@1` +
34
+ `own-server@1` + 可执行 `raw@1`;基建插件使用 `defineDriver` 驱动入口。
35
+ - 能力表按 `ctx` 实际服务探测(见 `lib/kernel.mjs` 的 `detectCapabilities`),不做空头承诺。
36
+ - 当前仓库:27 个插件走标准接口,`raw@1` 当前为空,6 个基建插件走
37
+ `defineDriver` 驱动层;`meta/foundation.allowlist.json` 的模糊豁免为 0。
38
+ 详见 `docs/POLICY.md` 与 `docs/spec/plugin-abi.md`。
39
+
40
+ 设计规范见 `docs/spec/plugin-abi.md`,强制规则见 `docs/POLICY.md`。
41
+
42
+ ## 生命周期(0.1.6 起)
43
+
44
+ `createPlugin().apply` 会把 `os.mount()` 的 disposer 通过 `ctx.effect(() => () => dispose())`
45
+ 登记到本次激活的 ctx 上——**不能只靠 apply 的返回值**:Cordis 只认 `ctx.effect` 回调返回的
46
+ disposer,返回值不可靠。漏登记时,关掉插件后内核里的记录不会摘除,再次启用就会撞
47
+ `E_DUP_PLUGIN: 插件 xxx 已挂载`。
48
+
49
+ 加载器侧另有两条兜底:`mount()` 遇到 `disposed` / `failed` 的旧记录会先摘掉并尽力回收;
50
+ `start` 失败清理完成后立即让出插件名。两者共同保证「关掉 → 再启用」可重复无数次。
51
+
@@ -0,0 +1,86 @@
1
+ /**
2
+ * 桥(editor bridge)与文档模型的标准声明。
3
+ *
4
+ * 这一层只放「协议常量 + 声明校验」,不放运行时:
5
+ * - 常量:协议版本、模型版本、能力名(suite 清单与 healthz 都用它)
6
+ * - declareBridge():把工作台的声明冻结成标准形状
7
+ * - assertBridgeRuntime():启动/巡检时把「声明」与「运行时实际上报」对齐
8
+ *
9
+ * 运行时(relay / 队列 / 租约)仍在 @capyclaw/document-workbench + service-host,
10
+ * 不进 ABI 层:foundation 是所有插件的地基,不该背 HTTP/store 依赖。
11
+ *
12
+ * 能力名(与 suite 清单的 requires/provides.capabilities 对应):
13
+ * editor.bridge —— 插件提供一个编辑器权威桥(/healthz + /status + /watch + /ack)
14
+ * doc.model —— 插件提供文档模型(稳定 ID / 清单 / 定位 / 编辑计划 / 校验)
15
+ */
16
+
17
+ /** 桥协议版本:端点集合与状态机语义的主版本。不兼容变更才升 major。 */
18
+ export const BRIDGE_PROTOCOL_VERSION = '1.0.0'
19
+
20
+ /** 文档模型版本:清单字段、定位器语义、编辑 op 的主版本。 */
21
+ export const DOC_MODEL_VERSION = '1.0.0'
22
+
23
+ export const BRIDGE_CAPABILITY = 'editor.bridge'
24
+ export const DOC_MODEL_CAPABILITY = 'doc.model'
25
+
26
+ /** healthz 里桥声明的字段名(避免与既有的 bridge: '<name>' 字符串冲突)。 */
27
+ export const BRIDGE_INFO_FIELD = 'bridgeInfo'
28
+
29
+ const ID_RE = /^[a-z0-9][a-z0-9-]*$/
30
+ const VERSION_RE = /^\d+\.\d+\.\d+$/
31
+
32
+ /**
33
+ * 校验并冻结一份桥声明。
34
+ * @param {{ id: string, protocol?: string, model?: string|null, editor?: 'required'|'optional' }} input
35
+ */
36
+ export function declareBridge(input = {}) {
37
+ const { id, protocol = BRIDGE_PROTOCOL_VERSION, model = null, editor = 'required' } = input
38
+ const errors = []
39
+ if (typeof id !== 'string' || !ID_RE.test(id)) errors.push(`id 必须是 kebab-case:${id}`)
40
+ if (!VERSION_RE.test(protocol)) errors.push(`protocol 版本非法:${protocol}`)
41
+ if (model !== null && !VERSION_RE.test(model)) errors.push(`model 版本非法:${model}`)
42
+ if (editor !== 'required' && editor !== 'optional') errors.push(`editor 只能是 required/optional:${editor}`)
43
+ if (errors.length) throw new Error(`桥声明非法:${errors.join(';')}`)
44
+ return Object.freeze({ id, protocol, model, editor })
45
+ }
46
+
47
+ /** 桥声明 → suite 清单里的 provides.capabilities。 */
48
+ export function bridgeCapabilities(declaration) {
49
+ const decl = declaration && declaration.protocol ? declaration : declareBridge(declaration)
50
+ return Object.freeze({
51
+ [BRIDGE_CAPABILITY]: decl.protocol,
52
+ ...(decl.model ? { [DOC_MODEL_CAPABILITY]: decl.model } : {}),
53
+ })
54
+ }
55
+
56
+ /** 桥声明 → suite 清单里工具面对运行时的 requires.capabilities(skill 包用)。 */
57
+ export function bridgeConsumerRequirements(ns, { needsModel = false } = {}) {
58
+ const out = { [`${ns}.runtime`]: `^${BRIDGE_PROTOCOL_VERSION}` }
59
+ if (needsModel) out[DOC_MODEL_CAPABILITY] = `^${DOC_MODEL_VERSION}`
60
+ return Object.freeze(out)
61
+ }
62
+
63
+ /**
64
+ * 声明与运行时对账:启动或巡检时调用。
65
+ *
66
+ * @param {object} declaration declareBridge 的结果(来自插件代码/清单)
67
+ * @param {object} runtime healthz 里的 bridgeInfo(实际运行值)
68
+ * @returns {{ ok: boolean, issues: string[] }}
69
+ */
70
+ export function assertBridgeRuntime(declaration, runtime) {
71
+ const issues = []
72
+ const decl = declaration && declaration.id ? declaration : declareBridge(declaration || {})
73
+ if (!runtime || typeof runtime !== 'object') {
74
+ return { ok: false, issues: [`运行时没有上报 ${BRIDGE_INFO_FIELD}`] }
75
+ }
76
+ if (runtime.id !== decl.id) issues.push(`id 不一致:声明 ${decl.id} / 运行 ${runtime.id}`)
77
+ if (runtime.protocol !== decl.protocol) {
78
+ issues.push(`协议版本不一致:声明 ${decl.protocol} / 运行 ${runtime.protocol}`)
79
+ }
80
+ const declaredModel = decl.model || null
81
+ const runtimeModel = runtime.model || null
82
+ if (declaredModel !== runtimeModel) {
83
+ issues.push(`模型版本不一致:声明 ${declaredModel || '无'} / 运行 ${runtimeModel || '无'}`)
84
+ }
85
+ return { ok: issues.length === 0, issues }
86
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * ABI 错误模型:稳定的错误码 + 结构化 detail。
3
+ *
4
+ * 约定:
5
+ * - 应用插件按 code 分支,不解析 message 文案;
6
+ * - message 面向人,detail 面向程序;
7
+ * - 所有加载期失败都必须是 AbiError,不允许裸 Error 穿透。
8
+ */
9
+
10
+ /** 稳定错误码。新增只能追加,不得改语义。 */
11
+ export const ERROR_CODES = Object.freeze({
12
+ /** 插件入口形状不对:缺 name / 没有 implements / 导出了 apply 等。 */
13
+ E_PLUGIN_SHAPE: 'E_PLUGIN_SHAPE',
14
+ /** 插件声明的 ABI 主版本与内核不兼容。 */
15
+ E_ABI_MISMATCH: 'E_ABI_MISMATCH',
16
+ /** 描述符的 kind 不在内核认识的接口表里。 */
17
+ E_KIND_UNKNOWN: 'E_KIND_UNKNOWN',
18
+ /** 描述符字段不满足接口 schema。 */
19
+ E_SCHEMA: 'E_SCHEMA',
20
+ /** 内核没有提供该能力(通常是 os.* 子系统缺失)。 */
21
+ E_CAP_MISSING: 'E_CAP_MISSING',
22
+ /** 唯一性接口被第二个插件实现(例如同 id 的 runtime-driver)。 */
23
+ E_DUP_INTERFACE: 'E_DUP_INTERFACE',
24
+ /** 同名插件被重复挂载。 */
25
+ E_DUP_PLUGIN: 'E_DUP_PLUGIN',
26
+ /** 内核没有为这个 kind 注册适配器(接口定义存在但实现未就绪)。 */
27
+ E_KIND_UNAVAILABLE: 'E_KIND_UNAVAILABLE',
28
+ /** 适配器在编译期抛错。 */
29
+ E_ADAPTER_THREW: 'E_ADAPTER_THREW',
30
+ /** 插件入口没有拿到 baseUrl,相对路径无法解析。 */
31
+ E_BASE_URL_MISSING: 'E_BASE_URL_MISSING',
32
+ /** 运行时没有 ctx.os:foundation 未安装或未启用。 */
33
+ E_KERNEL_MISSING: 'E_KERNEL_MISSING',
34
+ E_KERNEL_CLOSED: 'E_KERNEL_CLOSED',
35
+ E_NOT_READY: 'E_NOT_READY',
36
+ E_CAP_RESERVED: 'E_CAP_RESERVED',
37
+ E_CAP_CONFLICT: 'E_CAP_CONFLICT',
38
+ })
39
+
40
+ export class AbiError extends Error {
41
+ /**
42
+ * @param {string} code ERROR_CODES 中的一项
43
+ * @param {string} message 面向人的说明
44
+ * @param {Record<string, unknown>} [detail] 面向程序的结构化信息
45
+ */
46
+ constructor(code, message, detail = {}) {
47
+ super(`[${code}] ${message}`)
48
+ this.name = 'AbiError'
49
+ this.code = code
50
+ this.detail = detail
51
+ if (detail.cause instanceof Error) this.cause = detail.cause
52
+ }
53
+ }
54
+
55
+ export function isAbiError(error) {
56
+ return error instanceof AbiError
57
+ }
58
+
59
+ /** 把任意异常归一成 AbiError(已归一的原样返回)。 */
60
+ export function toAbiError(error, code = ERROR_CODES.E_ADAPTER_THREW, detail = {}) {
61
+ if (error instanceof AbiError) return error
62
+ return new AbiError(code, error?.message || String(error), { ...detail, cause: error })
63
+ }
@@ -0,0 +1,35 @@
1
+ /** 接口 ABI 的唯一入口:应用插件只需要 import 这个模块。 */
2
+ export { ABI_MAJOR, INTERFACE_KINDS, INTERFACE_KIND_NAMES, getInterfaceKind } from './kinds.mjs'
3
+ export {
4
+ defineInterface,
5
+ definePlugin,
6
+ createPlugin,
7
+ skillProvider,
8
+ toolProvider,
9
+ runtimeDriver,
10
+ httpRouter,
11
+ uiPanel,
12
+ lifecycleHook,
13
+ hostEvent,
14
+ clientPanel,
15
+ ownServer,
16
+ serviceProvider,
17
+ defineDriver,
18
+ rawPlugin,
19
+ } from './spec.mjs'
20
+ export { createLoader } from './loader.mjs'
21
+ export {
22
+ BRIDGE_CAPABILITY,
23
+ BRIDGE_INFO_FIELD,
24
+ BRIDGE_PROTOCOL_VERSION,
25
+ DOC_MODEL_CAPABILITY,
26
+ DOC_MODEL_VERSION,
27
+ assertBridgeRuntime,
28
+ bridgeCapabilities,
29
+ bridgeConsumerRequirements,
30
+ declareBridge,
31
+ } from './bridge.mjs'
32
+ export { validateInterface } from './validate.mjs'
33
+ export { AbiError, ERROR_CODES, isAbiError, toAbiError } from './errors.mjs'
34
+ export { validateSchema } from './schema.mjs'
35
+ export { parseVersion, compareVersions, satisfies } from './version.mjs'