@capyclaw/session-tabs 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +43 -2
  2. package/client/client.js +300 -0
  3. package/cordis.patch.yml +9 -0
  4. package/index.js +15 -0
  5. package/node_modules/@capyclaw/foundation/README.md +51 -0
  6. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  7. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  8. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  9. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  10. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  11. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  12. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  13. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  14. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  15. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  16. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  17. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  18. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  19. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  20. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  28. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  29. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  30. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  31. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  32. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  33. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  34. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  35. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
  36. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  37. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  38. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  39. package/node_modules/@capyclaw/foundation/package.json +53 -0
  40. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  41. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  42. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  43. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  44. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  45. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  70. package/package.json +44 -4
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @capyclaw/session-tabs
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DSH Web shell 的**浏览器式会话标签条**——纯呈现层(薄 UI)。单一职责:只负责"把受管会话画成标签 + 翻译用户意图",**不做任何会话管理**。
4
+
5
+ 会话的保活、心跳判活、受管集合、标签序真源全部在唯一接口 `ctx.sessionKeeper`(由 [@capyclaw/session-keeper](../capyclaw-session-keeper/README.md) 提供)。本插件不读 `ctx.sessions.list`、不订阅 `api-session/status`、不持久化、不持有 retain 引用。
6
+
7
+ ## 行为(不变量由 keeper 保证,本插件只呈现与触发)
8
+ 1. **关闭标签 ⇒ 停止/解除保活**:空闲标签直接 `keeper.unmanage`(历史保留);运行中标签弹主题化确认,`sessions.using(...).session.cancel()` 成功后才 `unmanage`,失败保留标签并以主题化 toast 提示(4s 自动消失,不用原生 alert)。
9
+ 2. **运行中 ⇒ 必有标签**:keeper 心跳自动纳入 running 会话,本插件照单渲染。
10
+ 3. **被打开/查看 ⇒ 有标签**:keeper 自动纳入 mainView 会话;点击标签 additionally `keeper.manage` 显式保活。
11
+ 4. **末尾「+」**:`uiWorkspace.startSession()` 新建会话(宿主回退链:当前工作区 → 最近工作区)。
12
+
13
+ 其它:点击切换(`openSession`);关当前标签跳相邻、关最后一个自动新建;键盘 Enter/Space 切换、Delete 关闭、←/→ 移动焦点;运行中 spinner;**判活态可视化**:`stalled` 标签 spinner 转警告色、`missing` 标签淡化;溢出横向收缩滚动;active 滚入视野;浅色/深色全用 `--dsw-alias-*` token;停用对称还原 DOM/样式。
14
+
15
+ ## 切换反馈(v0.3:零附加图层)
16
+ 宿主 `openSession` 同步换选择,历史拉取+渲染由宿主自己完成。本插件**只补标签层的即时反馈,主区一个像素都不加**:
17
+ 1. **乐观高亮 + paint-first(v0.4,Chrome 式点击手感)**:高亮在点击任务里进 DOM、由浏览器先画出来;宿主 `openSession`+`manage` 是同步换选择+重建视图的重活,推迟到两帧之后(双 rAF,无 rAF 环境降级 setTimeout)——此前高亮与宿主重活同在点击任务里,高亮要等重活干完才画得出来,就是"点一下卡一下"的根源。连点取消上一次未执行的交换(latest-wins,只最后目标进宿主);点当前标签=零操作,不重复触发宿主交换。
18
+ 2. **主区零图层**:不盖遮罩、不做快照、不挂 MutationObserver/ResizeObserver/resize 监听、不序列化主区 innerHTML。等待期就是宿主默认背景与宿主自己的加载态,内容出现即宿主原生速度;插件侧零开销,不可能拖慢宿主渲染,也不挡主区任何点击。
19
+ 3. **历史与教训**:v0.2 曾加主区遮罩(骨架扫光/上一屏快照)求"秒显",实测反而更慢——整树 childList 观察让宿主每批渲染 mutation 触发全页扫描+强制布局(thrash),点击路径同步序列化整屏 innerHTML 阻塞主线程;v0.2.1 修观察器与快照护栏后仍多一层等待感。按用户要求("不需要图层挡着,什么都不需要有")v0.3 整套移除,只留乐观高亮。
20
+
21
+ ## 放置(v4:caption-map 预留栏位挂载锚)
22
+ 标签条**不再自占全宽 fixed 顶栏**,而是注册进 [@capyclaw/caption-map](../capyclaw-caption-map/README.md) 在标题栏「其他」按钮右侧分配的**预留栏位**:经挂载锚服务 `ctx.captionExtra` 的 `acquire()` 声明占用、`getMount()` 取 mount 节点、`subscribe()` 跟随其出现/消失/重建,再用 `react-dom/client` 的 `createRoot` 把视图挂进该节点。条本身 `position:static`、28px 高紧凑排布(无 fixed/无 drag/透明无边框),位置与让位全由 caption-map 编排器负责;确认模态与失败 toast 仍 `position:fixed` 浮于全局。**不读对方 DOM/样式估位置**(空间由锚显式分配),锚缺席(keeper/caption-map 停用、drawer、纯 web)则不渲染、不崩页;锚重建则 unmount 旧根、重挂新节点。停用对称:unmount + `release()` + 退订。
23
+
24
+ ## 架构(单一职责·唯一接口消费)
25
+ - **本地 presentation 状态**:仅 `{pendingClose, notice, switchTo}` 三类纯界面状态 + 订阅。不含任何会话事实。
26
+ - **意图桥**:open⇒`local.setSwitchTo`(乐观高亮)先于 `uiWorkspace.openSession`+`keeper.manage`;create⇒`uiWorkspace.startSession`;close⇒`keeper.unmanage`(运行中先确认+cancel)。停止失败提示走本地 notice。
27
+ - **TopBarView**(纯视图):读 `keeper.getState()`(`phase/ids/activeId/sessions`)渲染,订阅 keeper 与本地状态刷新。
28
+ - **挂载**:`ctx.captionExtra.acquire()`(持 **default 租约**,多租约锚下与他消费者共存互不覆盖)+ `subscribe(sync)` + `sync()`;`sync` 比较 `getMount()` 与当前根容器,变化则 unmount 旧根 / `createRoot` 新根。放置与切换均不依赖 window-kit / 宿主 slots(v0.3 起连可选几何探针依赖也移除,`dsh.client.external` 已删)。
29
+ - 模块 `inject: ['uiWorkspace','sessions','sessionKeeper','captionExtra']`——loader 会等待 keeper 与挂载锚两个服务就绪后才装配,无需手动轮询。
30
+
31
+ ## 安装 / 回滚
32
+ - 前置:`@capyclaw/session-keeper` 与 `@capyclaw/caption-map` 必须 enabled(本插件经 `inject` 等待二者服务;任一停用则标签条缺席,不报错不崩页)。
33
+ - 安装:`plugin_manager install_bundle target=link:<本目录绝对路径>`。
34
+ - 回滚:`plugin_manager set_plugin target=@capyclaw/session-tabs enabled=false`(live 生效,GUI 刷新后标签条消失,caption-map 预留栏位回到虚线占位态)。
35
+ - 标签序持久化在 **keeper** 侧:`localStorage['capyclaw.sessionKeeper.v1']`;本插件零持久化。
36
+
37
+ ## 验证边界
38
+ 隔离浏览器无法通过宿主鉴权(root 401),故无运行截图;已做 JS 语法/manifest 校验 + 代码级 UI/UX 评审。视觉确认请在已鉴权 GUI 刷新(Ctrl+R)。
39
+
40
+ 逻辑回归:`node test/regression.cjs`(50 条断言全过)。vm 沙箱加载 client.js,mock 唯一接口 `sessionKeeper`(可注入状态/订阅)、挂载锚 `captionExtra`(acquire/release/getMount/subscribe + 测试注入 mount 节点)、`react-dom/client` createRoot(记录 render/unmount 与容器)、`uiWorkspace`、`sessions.using/cancel`,最小 React stub 真实调用视图函数(含卸载 cleanup 模拟)。**单一职责强断言**:`ctx.sessions.list` / `ctx.sessions.retain` / `ctx.remote` / `ctx.slots` 均设为 getter 陷阱——薄 UI 一旦触碰即抛错失败;另断言零 `localStorage` 写入。**放置强断言**:acquire 占用、锚缺席不渲染、挂到锚给的 mount、不再 fixed 全宽、锚消失 unmount、锚重建重挂、卸载 release+订阅清零。**零图层强断言**(第二沙箱:mini DOM + MutationObserver/ResizeObserver 桩 + rAF 桩):点击任务零同步宿主调用(paint-first)、两帧后才 openSession、body 零附加子节点(样式只进 head)、乐观高亮 cst-switching+spinner、宿主跟上即清、宿主 settling 期仍零图层、全程零 MutationObserver/零 resize 监听、连点合并到最后目标(未执行交换被取消)、点当前标签零操作、点击路径零 innerHTML 序列化(getter 陷阱计数=0)、dispose 取消在途交换+零残留+订阅解除+锚归还。覆盖:pending/ready 渲染、active/spinner/missing/stalled 态、点击 manage、空闲直关、运行中确认+cancel 成功/失败、toast 与自动消失、active 跳邻居、「+」、卸载对称。
41
+
42
+ 链路稳定性/可拓展回归在 [@capyclaw/caption-map 的 workspaces-dropdown 套件](../capyclaw-caption-map/test/workspaces-dropdown.test.mjs):真源同沙箱装配 caption-map 锚 + session-keeper + 本插件整条链,断言标签挂进真实 mount、随 keeper 心跳扩容并持久化、门控循环 8 次根收支平衡/单 mount/样式不泄漏/卸载后无僵尸根、命名租约共存与交接、全卸载释放 retain 后重载仍工作。当前 24 用例 17 过:7 败全在 caption-map 自身单测(并行工作既有问题,其 load() 只 eval caption-map 源码、不含本插件),session-tabs 整链 4 用例全绿。
43
+
44
+ 重构记录(2026-11-20):① 按单一职责要求从"UI+桥接+状态"混合体拆出——会话管理整体迁入 @capyclaw/session-keeper,本插件降为薄 UI,仅经 `ctx.sessionKeeper` 消费。② 放置从自占全宽 `shell.overlay` 顶栏改为注册进 caption-map 预留栏位挂载锚(`ctx.captionExtra` + createRoot),去掉 window-kit 依赖。此前修复(readSnap 补 getSnapshot、alert→主题化 toast)的管理侧逻辑已随迁入 keeper 或保留于意图桥。③ v0.2 切换秒响应:乐观高亮 + 主区扫光骨架/上一屏快照遮罩 + latest-wins + 就绪稳定确认(见「切换遮罩」节);window-kit 以可选 external 回归(仅几何探针,缺席降级)。④ v0.2.1 性能修正:就绪观察器从整树 childList+attributes 改为 content 节点属性-only(消除宿主渲染期每批 mutation 的扫描+强制布局 thrash);快照上限 1.2MB→220KB、节点数 >3000 不抓(消除点击路径上的整屏序列化/大快照解析阻塞);稳定确认 150→100ms、淡出 200→140ms。⑤ v0.2.2 按用户要求移除骨架屏与扫光:无缓存等待改为纯默认背景一层,就绪淡出保留;淡出 transition .18s→.14s 与 140ms 移除定时器对齐(此前淡出未完成就被移除,视觉上是跳变)。⑥ v0.3 按用户要求("不是一个图层挡着,而是什么都不需要有")整套移除切换遮罩/快照缓存/就绪观察器与 window-kit 可选依赖:主区完全交宿主默认背景与加载态,插件只留乐观高亮+spinner;点击路径零 DOM 序列化、零观察器、零附加图层。⑦ v0.4 paint-first:用户仍反馈点击卡顿,根因是高亮与宿主同步换选择+视图重建同在点击任务、高亮等重活干完才绘制;改为高亮先画、宿主交换推迟两帧(双 rAF),连点 latest-wins 合并、点当前标签零操作、卸载取消在途交换。
@@ -0,0 +1,300 @@
1
+ /*
2
+ * @capyclaw/session-tabs 浏览器半:薄 UI(浏览器式会话标签条)。
3
+ *
4
+ * 单一职责:本插件只负责"呈现与用户意图",不做任何会话管理——
5
+ * 会话保活/心跳/受管集合/判活状态全部来自唯一接口 ctx.sessionKeeper
6
+ * (@capyclaw/session-keeper)。本插件不读 ctx.sessions.list、不订阅
7
+ * api-session/status、不持久化标签序、不持有 retain 引用。
8
+ * 仅保留三类本地 presentation 状态:待确认关闭(pendingClose)、失败提示(notice)、
9
+ * 乐观切换目标(switchTo)。
10
+ * 用户意图翻译:open⇒uiWorkspace.openSession+keeper.manage;create⇒uiWorkspace.startSession;
11
+ * close⇒keeper.unmanage(运行中先主题化确认并 sessions.using(...).cancel())。
12
+ * 放置:经 ctx.captionExtra(@capyclaw/caption-map 预留栏位挂载锚)acquire 一枚 mount
13
+ * 节点,用 react-dom/client createRoot 挂进去;锚缺席/让位时不渲染、不崩页。
14
+ * 切换体验(v0.3 起无任何附加图层):宿主 openSession 同步换选择,历史拉取/渲染在
15
+ * 视图内异步完成。点击标签只做立即乐观高亮(switchTo),主区完全交给宿主自己的
16
+ * 默认背景/加载态——不盖遮罩、不存快照、不挂观察器、不挡任何点击(用户明确要求)。
17
+ * 宿主 activeId 跟上点击目标后乐观态自动清除。
18
+ */
19
+ window.__ModuleLoader__.load({
20
+ id: '@capyclaw/session-tabs',
21
+ factory: function (require) {
22
+ var module = { exports: {} }
23
+ var React = require('react')
24
+ var ReactDOM = require('react-dom/client')
25
+ var e = React.createElement
26
+
27
+ /* ================= 本地 presentation 状态(pendingClose/notice/switchTo) ================= */
28
+ function createLocal() {
29
+ var listeners = []
30
+ var state = { pendingClose: null, notice: null, switchTo: null }
31
+ function emit() { state = Object.assign({}, state); listeners.forEach(function (fn) { fn() }) }
32
+ return {
33
+ getState: function () { return state },
34
+ subscribe: function (fn) { listeners.push(fn); return function () { listeners = listeners.filter(function (x) { return x !== fn }) } },
35
+ setPending: function (id) { state.pendingClose = id; emit() },
36
+ setNotice: function (msg) { state.notice = msg; emit() },
37
+ setSwitchTo: function (id) { if (state.switchTo === id) return; state.switchTo = id; emit() }
38
+ }
39
+ }
40
+
41
+ /* ================= 用户意图翻译(只经 keeper + 宿主 UI/停止 API) ================= */
42
+ function createBridge(ctx, keeper, local) {
43
+ var noticeTimer = null
44
+ var pendingOpen = null /* {id,cancel}:latest-wins,连点只保留最后一次宿主交换 */
45
+ var disposed = false
46
+ function notifyFail() {
47
+ local.setNotice('停止会话失败,标签已保留。')
48
+ if (noticeTimer) clearTimeout(noticeTimer)
49
+ noticeTimer = setTimeout(function () { noticeTimer = null; local.setNotice(null) }, 4000)
50
+ }
51
+ function cancelPending() {
52
+ if (pendingOpen) { pendingOpen.cancel(); pendingOpen = null }
53
+ }
54
+ /* paint-first(Chrome 式点击手感的关键):高亮在点击任务里进 DOM、由浏览器先画出来;
55
+ 宿主 openSession+manage 是同步换选择+重建视图的重活,推迟到两帧之后再做——
56
+ 否则高亮要等宿主重活干完才画得出来,点击就"卡"。双 rAF 保证中间至少画过一帧
57
+ 带高亮的画面;无 rAF 的环境降级 setTimeout。连点取消上一次未执行的交换。 */
58
+ function scheduleHost(id) {
59
+ cancelPending()
60
+ var done = false
61
+ var handles = []
62
+ function run() {
63
+ if (done || disposed) return
64
+ done = true
65
+ pendingOpen = null
66
+ try { ctx.uiWorkspace.openSession(id) } catch (err) {}
67
+ keeper.manage(id)
68
+ }
69
+ var raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : null
70
+ var caf = typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : null
71
+ if (raf) handles.push(raf(function () { handles.push(raf(run)) }))
72
+ else handles.push(setTimeout(run, 0))
73
+ pendingOpen = {
74
+ id: id,
75
+ cancel: function () {
76
+ done = true
77
+ handles.forEach(function (h) { try { (caf || clearTimeout)(h) } catch (err) {} })
78
+ }
79
+ }
80
+ }
81
+ function open(id) {
82
+ if (disposed) return
83
+ /* 点当前标签=零操作(Chrome 同款):不重复触发宿主换选择/重建。 */
84
+ if (keeper.getState().activeId === id && !pendingOpen) { local.setSwitchTo(null); return }
85
+ local.setSwitchTo(id) /* 乐观高亮立即进 DOM,先画 */
86
+ if (pendingOpen && pendingOpen.id === id) return
87
+ scheduleHost(id)
88
+ }
89
+ function create() { try { ctx.uiWorkspace.startSession() } catch (err) {} }
90
+ function closeNow(id) {
91
+ var st = keeper.getState()
92
+ var wasActive = st.activeId === id
93
+ var idx = st.ids.indexOf(id)
94
+ var neighbor = st.ids[idx + 1] || st.ids[idx - 1] || null
95
+ keeper.unmanage(id)
96
+ if (wasActive) { if (neighbor) open(neighbor); else create() }
97
+ }
98
+ return {
99
+ open: open,
100
+ create: create,
101
+ requestClose: function (id) {
102
+ var info = keeper.getState().sessions[id]
103
+ if (info && info.running) local.setPending(id)
104
+ else closeNow(id)
105
+ },
106
+ confirmClose: function () {
107
+ var id = local.getState().pendingClose
108
+ local.setPending(null)
109
+ if (!id) return
110
+ var pr = null
111
+ try {
112
+ pr = ctx.sessions.using(id, { source: 'controllerOperation' }, function (ref) { return ref.binding.session.cancel() })
113
+ } catch (err) {}
114
+ if (pr && typeof pr.then === 'function') {
115
+ pr.then(function (res) {
116
+ if (res && res.ok === false) notifyFail()
117
+ else closeNow(id)
118
+ }).catch(function () { notifyFail() })
119
+ } else closeNow(id)
120
+ },
121
+ dispose: function () {
122
+ disposed = true
123
+ cancelPending()
124
+ if (noticeTimer) { clearTimeout(noticeTimer); noticeTimer = null }
125
+ }
126
+ }
127
+ }
128
+
129
+ /* ================= 纯视图 ================= */
130
+ var CSS = [
131
+ '.cst-top{display:flex;align-items:center;box-sizing:border-box;height:28px;max-width:100%;min-width:0;',
132
+ ' background:transparent;border:none;-webkit-app-region:no-drag;}',
133
+ '.cst-tab,.cst-close,.cst-new,.cst-mask{-webkit-app-region:no-drag;}',
134
+ '.cst-scroll{display:flex;align-items:center;gap:2px;flex:1 1 auto;min-width:0;overflow-x:auto;overflow-y:hidden;scrollbar-width:thin;}',
135
+ '.cst-scroll::-webkit-scrollbar{height:4px}.cst-scroll::-webkit-scrollbar-thumb{background:var(--dsw-alias-border-l3,rgba(127,127,127,.3));border-radius:2px}',
136
+ '.cst-tab{display:inline-flex;align-items:center;gap:5px;flex:0 1 140px;min-width:56px;max-width:160px;height:24px;',
137
+ ' padding:0 4px 0 8px;border-radius:6px;box-sizing:border-box;cursor:pointer;',
138
+ ' font-size:12px;line-height:1;color:var(--dsw-alias-label-secondary,inherit);background:transparent;border:1px solid transparent;}',
139
+ '.cst-tab:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12));color:var(--dsw-alias-label-primary,inherit);}',
140
+ '.cst-tab.cst-active{background:var(--dsw-alias-interactive-bg-active,rgba(127,127,127,.16));color:var(--dsw-alias-label-primary,inherit);border-color:var(--dsw-alias-border-l3,rgba(127,127,127,.25));}',
141
+ '.cst-tab.cst-missing{opacity:.45;}',
142
+ '.cst-tab.cst-stalled .cst-spin{border-top-color:var(--dsw-alias-state-warn-primary,#f5a524);}',
143
+ '.cst-tab:focus-visible,.cst-close:focus-visible,.cst-new:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#3b82f6);outline-offset:-2px;}',
144
+ '.cst-title{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
145
+ '.cst-close{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border:none;border-radius:5px;background:transparent;color:inherit;cursor:pointer;font-size:12px;line-height:1;padding:0;opacity:.7;}',
146
+ '.cst-close:hover{opacity:1;background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.2));}',
147
+ '.cst-spin{flex:0 0 auto;width:11px;height:11px;border-radius:50%;box-sizing:border-box;border:1.5px solid var(--dsw-alias-border-l3,rgba(127,127,127,.35));border-top-color:var(--dsw-alias-state-business-primary,#3b82f6);animation:cst-rot .8s linear infinite;}',
148
+ '@keyframes cst-rot{to{transform:rotate(360deg)}}',
149
+ '@media (prefers-reduced-motion: reduce){.cst-spin{animation:none;}}',
150
+ '.cst-new{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;align-self:center;margin-left:2px;border:none;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary,inherit);cursor:pointer;font-size:14px;line-height:1;padding:0;}',
151
+ '.cst-new:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.15));color:var(--dsw-alias-label-primary,inherit);}',
152
+ '.cst-empty{align-self:center;font-size:11px;color:var(--dsw-alias-label-tertiary,inherit);opacity:.7;padding:0 4px;white-space:nowrap;}',
153
+ '.cst-mask{position:fixed;inset:0;z-index:1600;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.35);pointer-events:auto;}',
154
+ '.cst-modal{width:320px;max-width:80vw;border-radius:12px;padding:16px;box-sizing:border-box;background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-primary,#222);border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.25));box-shadow:0 8px 32px rgba(0,0,0,.25);}',
155
+ '.cst-modal h3{margin:0 0 8px;font-size:14px;}',
156
+ '.cst-modal p{margin:0 0 16px;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary,#666);word-break:break-all;}',
157
+ '.cst-modal .row{display:flex;justify-content:flex-end;gap:8px;}',
158
+ '.cst-btn{border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.3));border-radius:8px;padding:6px 12px;font-size:12px;cursor:pointer;background:transparent;color:inherit;}',
159
+ '.cst-btn.danger{background:var(--dsw-alias-state-business-primary,#3b82f6);border-color:transparent;color:#fff;}',
160
+ '.cst-notice{position:fixed;top:calc(var(--dsh-windows-titlebar-height,var(--dsh-frame-top-clearance,40px)) + 8px);left:50%;transform:translateX(-50%);',
161
+ ' z-index:1600;max-width:80vw;padding:8px 14px;border-radius:8px;box-sizing:border-box;pointer-events:none;',
162
+ ' font-size:12px;line-height:1.5;background:var(--dsw-alias-bg-overlay,#fff);color:var(--dsw-alias-label-primary,#222);',
163
+ ' border:1px solid var(--dsw-alias-state-error-primary,#e5484d);box-shadow:0 4px 16px rgba(0,0,0,.2);}'
164
+ ].join('\n')
165
+
166
+ function makeTopBarView(keeper, local, bridge, menus) {
167
+ return function TopBarView() {
168
+ var tick = React.useState(0)
169
+ var setTick = tick[1]
170
+ var ks = keeper.getState()
171
+ var ls = local.getState()
172
+ React.useEffect(function () {
173
+ var unK = keeper.subscribe(function () { setTick(function (t) { return t + 1 }) })
174
+ var unL = local.subscribe(function () { setTick(function (t) { return t + 1 }) })
175
+ return function () { unK(); unL() }
176
+ }, [keeper, local])
177
+ React.useEffect(function () {
178
+ var style = document.createElement('style')
179
+ style.id = 'cst-css'
180
+ style.textContent = CSS
181
+ document.head.appendChild(style)
182
+ return function () { if (style.parentNode) style.parentNode.removeChild(style) }
183
+ }, [])
184
+ React.useEffect(function () {
185
+ var act = document.querySelector('.cst-tab.cst-active')
186
+ if (act && act.scrollIntoView) act.scrollIntoView({ block: 'nearest', inline: 'nearest' })
187
+ }, [ks.activeId, ls.switchTo, ks.ids.length])
188
+
189
+ function onKey(ev, id, idx) {
190
+ var k = ev.key
191
+ if (k === 'Enter' || k === ' ') { ev.preventDefault(); bridge.open(id) }
192
+ else if (k === 'Delete' || k === 'Backspace') { ev.preventDefault(); bridge.requestClose(id) }
193
+ else if (k === 'ContextMenu' || (ev.shiftKey && k === 'F10')) {
194
+ ev.preventDefault()
195
+ var r = ev.currentTarget.getBoundingClientRect()
196
+ openMenu(id, (keeper.getState().sessions[id] || {}).title || '会话', r.left, r.bottom)
197
+ }
198
+ else if (k === 'ArrowRight' || k === 'ArrowLeft') {
199
+ ev.preventDefault()
200
+ var tabs = document.querySelectorAll('.cst-tab')
201
+ var n = tabs[idx + (k === 'ArrowRight' ? 1 : -1)]
202
+ if (n) n.focus()
203
+ }
204
+ }
205
+
206
+ /* 右键/菜单键 ⇒ 复用宿主会话右键菜单(与工作区侧栏同一组贡献,不复制菜单项)。 */
207
+ function openMenu(id, title, x, y) {
208
+ if (menus && menus.open) menus.open({ kind: 'session', value: { sessionId: id, displayTitle: title } }, { x: x, y: y })
209
+ }
210
+
211
+ /* 乐观高亮:宿主 activeId 未跟上时先亮点击目标;跟上后 switchTo 被清。 */
212
+ var switching = ls.switchTo && ls.switchTo !== ks.activeId ? ls.switchTo : null
213
+ var tabs = ks.ids.map(function (id, idx) {
214
+ var info = ks.sessions[id] || {}
215
+ var active = id === ks.activeId || id === ls.switchTo
216
+ var running = !!info.running
217
+ var missing = info.status === 'missing'
218
+ var stalled = info.status === 'stalled'
219
+ var title = info.title || '会话'
220
+ var suffix = running ? '(运行中)' : stalled ? '(疑似停滞)' : missing ? '(已消失)' : ''
221
+ return e('div', {
222
+ key: id,
223
+ className: 'cst-tab' + (active ? ' cst-active' : '') + (missing ? ' cst-missing' : '') + (stalled ? ' cst-stalled' : '') + (id === switching ? ' cst-switching' : ''),
224
+ role: 'tab', tabIndex: 0,
225
+ 'aria-selected': active, 'aria-busy': id === switching ? true : undefined,
226
+ title: title + suffix,
227
+ onClick: function () { bridge.open(id) },
228
+ onContextMenu: function (ev) { ev.preventDefault(); ev.stopPropagation(); openMenu(id, title, ev.clientX, ev.clientY) },
229
+ onKeyDown: function (ev) { onKey(ev, id, idx) }
230
+ },
231
+ (running || id === switching) ? e('span', { className: 'cst-spin', 'aria-hidden': true }) : null,
232
+ e('span', { className: 'cst-title' }, title),
233
+ e('button', {
234
+ className: 'cst-close', tabIndex: -1, 'aria-label': '关闭标签 ' + title,
235
+ title: running ? '停止并关闭' : missing ? '移除标签' : '关闭标签',
236
+ onClick: function (ev) { ev.stopPropagation(); bridge.requestClose(id) }
237
+ }, '×')
238
+ )
239
+ })
240
+ var scroll = e('div', { className: 'cst-scroll' }, tabs.length ? tabs : [e('span', { key: '__e', className: 'cst-empty' }, ks.phase === 'ready' ? '没有打开的会话' : '加载中…')])
241
+ var bar = e('div', { className: 'cst-top', role: 'tablist' }, scroll,
242
+ e('button', { className: 'cst-new', 'aria-label': '新建会话', title: '新建会话(当前/最近工作区)', onClick: function () { bridge.create() } }, '+'))
243
+
244
+ var modal = null
245
+ if (ls.pendingClose) {
246
+ var pTitle = (ks.sessions[ls.pendingClose] || {}).title || '会话'
247
+ modal = e('div', { className: 'cst-mask', onClick: function () { local.setPending(null) } },
248
+ e('div', { className: 'cst-modal', role: 'dialog', 'aria-modal': true, onClick: function (ev) { ev.stopPropagation() } },
249
+ e('h3', null, '停止并关闭标签?'),
250
+ e('p', null, '「' + pTitle + '」正在运行。关闭标签将停止它正在进行的任务。'),
251
+ e('div', { className: 'row' },
252
+ e('button', { className: 'cst-btn', onClick: function () { local.setPending(null) } }, '取消'),
253
+ e('button', { className: 'cst-btn danger', onClick: function () { bridge.confirmClose() } }, '停止并关闭'))))
254
+ }
255
+ var notice = ls.notice ? e('div', { className: 'cst-notice', role: 'alert' }, ls.notice) : null
256
+ return e(React.Fragment, null, bar, modal, notice)
257
+ }
258
+ }
259
+
260
+ /* ================= 装配 ================= */
261
+ var api = {
262
+ name: '@capyclaw/session-tabs',
263
+ inject: ['uiWorkspace', 'sessions', 'sessionKeeper', 'captionExtra', 'contextMenus'],
264
+ apply: function (ctx) {
265
+ var keeper = ctx.sessionKeeper
266
+ var anchor = ctx.captionExtra
267
+ var local = createLocal()
268
+ var bridge = createBridge(ctx, keeper, local)
269
+ var View = makeTopBarView(keeper, local, bridge, ctx.contextMenus)
270
+ /* 宿主选择跟上点击目标后清乐观高亮。 */
271
+ var unSwitch = keeper.subscribe(function () {
272
+ var sw = local.getState().switchTo
273
+ if (sw && keeper.getState().activeId === sw) local.setSwitchTo(null)
274
+ })
275
+ /* 挂载锚同步:mount 节点出现/消失/重建时重挂 React 根;缺席则不渲染。 */
276
+ var root = null
277
+ var rootEl = null
278
+ function sync() {
279
+ var el = anchor.getMount()
280
+ if (el === rootEl) return
281
+ if (root) { root.unmount(); root = null }
282
+ rootEl = el
283
+ if (el) { root = ReactDOM.createRoot(el); root.render(e(View)) }
284
+ }
285
+ anchor.acquire()
286
+ var unSub = anchor.subscribe(sync)
287
+ sync()
288
+ return function () {
289
+ unSub()
290
+ unSwitch()
291
+ if (root) { root.unmount(); root = null; rootEl = null }
292
+ anchor.release()
293
+ bridge.dispose()
294
+ }
295
+ }
296
+ }
297
+ module.exports = api
298
+ return module.exports
299
+ }
300
+ })
@@ -0,0 +1,9 @@
1
+ # @capyclaw/session-tabs bundle patch:把浏览器式会话标签条这个纯客户端包挂进 Harness 模块图。
2
+ #
3
+ # 宿主半(index.js)是空操作 —— 本包没有路由、没有模型面,只提供一个浏览器模块。
4
+ # 浏览器半(client/client.js)注册 id 为 @capyclaw/session-tabs 的 factory:
5
+ # 经 ctx.captionExtra 挂载锚挂进 caption-map 预留栏位,只经 ctx.sessionKeeper 听会话状态;
6
+ # 点击乐观高亮,主区零附加图层(v0.3,无 window-kit 依赖)。
7
+ - insert:
8
+ - id: session-tabs
9
+ name: "@capyclaw/session-tabs"
package/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /*
2
+ * @capyclaw/session-tabs 宿主半:空操作。
3
+ *
4
+ * 纯客户端包(浏览器式会话标签条),没有 HTTP 路由、没有模型面。宿主半存在的唯一
5
+ * 理由是让 cordis 有一个 Loader entry,从而把浏览器半(client/client.js,
6
+ * id '@capyclaw/session-tabs')送进模块图。真正的实现全在浏览器半:
7
+ * - 经 ctx.captionExtra 挂载锚把标签条 createRoot 进 caption-map 预留栏位;
8
+ * - 只经 ctx.sessionKeeper 消费受管会话状态(保活/心跳在 keeper);
9
+ * - 经 ctx.uiWorkspace.openSession/startSession 切换/新建会话,经
10
+ * ctx.sessions.using(...).binding.session.cancel() 停止运行中会话;
11
+ * - 点击乐观高亮;主区零附加图层(v0.3,无 window-kit 依赖)。
12
+ */
13
+ export const name = 'session-tabs'
14
+ export const inject = []
15
+ export function apply() {}
@@ -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'