@capyclaw/session-keeper 0.0.0-stage → 0.1.1

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 +319 -0
  3. package/cordis.patch.yml +9 -0
  4. package/index.js +12 -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 +352 -0
  11. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  12. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  13. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  14. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -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 +69 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -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 +187 -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 +115 -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 +198 -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 +60 -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-keeper
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`
6
+ 一个 cordis 服务,仅四个成员(无多余对外面):
7
+ - `manage(id)`:显式纳入受管集合——清除关闭宽限、加入标签序、建立保活 retain、立即心跳。
8
+ - `unmanage(id)`:解除保活——移出受管集合、释放 retain、记关闭时间(5s 宽限窗内不自动重纳)、立即心跳。
9
+ - `subscribe(fn)`:订阅状态发布(内容签名去重,无变化不发布);返回退订函数。
10
+ - `getState()`:读当前快照 `{phase, ids, auto, activeId, sessions, beatAt}`。
11
+ - `phase`:宿主列表 `'pending' | 'ready'`。
12
+ - `ids`:受管会话顺序(UI 标签序即此;仅 user 来源落盘)。
13
+ - `auto[id]`:`true` = 心跳自动纳入(只活在内存、绝不落盘,刷新不还原)。
14
+ - `activeId`:当前主会话(首个 `retainedBy.mainView > 0`)。
15
+ - `sessions[id]`:`{title, running, updatedAt, status, awaiting, lastBeat}`;`status ∈ alive | stalled | missing`;`awaiting=true` 表示该会话挂着待用户应答的交互(UI 以红 ? 替代 spinner)。
16
+ - `beatAt`:最近一次心跳时间戳。
17
+
18
+ ## 对内职责(三件事:保活 / 心跳判活 / 归位收掉)
19
+ 1. **保活**:对每个受管会话长期 `ctx.sessions.retain(id, {source:'sessionKeeper'})`——切走/关标签不释放,直到 `unmanage` 或插件卸载(卸载释放全部引用)。retain 会打开会话历史,保证受管会话不被宿主回收。
20
+ 2. **心跳判活**:`setInterval` 5s 周期轮询 `ctx.sessions.list.getSnapshot()`(另订阅列表变化即时补拍)。每拍:
21
+ - 首个 ready 拍 prune 持久化中已消失的 id(跨刷新自愈);
22
+ - 自动纳入 `running` 或 `retainedBy.mainView > 0` 的会话(关闭宽限窗 5s 内除外),标记 `auto[id]=true`——只存内存、绝不落盘;
23
+ - 更新 `activeId`;
24
+ - 判活:目录无 row ⇒ `missing`(受管集合保留,供 UI 淡化呈现);`running` 且超过 120s 无进展 ⇒ `stalled`;否则 `alive`。进展时间戳 = max(row.updatedAt, 实时事件流 append/settle-assistant 到达时间)——流式思考/正文块也算进展,避免 durable 消息时间戳造成的误报停滞;binding/eventSource 缺席时降级为仅 updatedAt;
25
+ - 等待:`ctx.uiSession.sessionStatus` 的 pendingInteraction 非空 ⇒ `awaiting=true`(与 status 独立);uiSession 缺席时恒 false;
26
+ - 内容签名去重后 `subscribe` 广播。
27
+ 3. **归位收掉(仅 auto)**:auto 会话「不再运行 + 不是当前视图(mainView=0)+ 空闲超 `IDLE_DROP_MS`」自动移出受管集合并释放保活引用;空闲按最后活动 max(row.updatedAt, liveAt) 计,与判活一致。user 来源永不自动收;成为当前视图不会把 auto 升级为 user。
28
+
29
+ 常量:`BEAT_MS=5000`、`STALL_MS=120000`、`CLOSED_TTL=5000`、`IDLE_DROP_MS=30000`。持久化键 `localStorage['capyclaw.sessionKeeper.v1']`(键名遗留),结构 `{v:3, ids}`、SCHEMA=3:只存 user 来源的 ids 顺序(auto 绝不落盘);读到 v1/v2 旧结构整份丢弃(不做迁移),还原时重复 id 去重。
30
+
31
+ ## 边界(不做什么)
32
+ 不渲染任何 UI;不读 UI 状态;不取消/停止会话(停止是消费方的用户意图,经 `sessions.using(...).cancel()` 自行执行);不新建会话;不碰 `uiWorkspace`。模块 `inject: ['sessions', 'uiSession']`(uiSession 缺席时 awaiting 降级恒 false),不 require 任何外部模块。
33
+
34
+ ## 安装 / 回滚
35
+ - 安装:`plugin_manager install_bundle target=link:<本目录绝对路径>`(已写入 desktop profile)。
36
+ - 回滚:`plugin_manager set_plugin target=@capyclaw/session-keeper enabled=false`——卸载即释放全部保活引用、清心跳定时器、撤销服务;消费方(如 @capyclaw/session-tabs)因 `inject` 等待而缺席,不崩页。
37
+ - 消费方示例:`inject:['sessionKeeper']` 后 `ctx.sessionKeeper.getState()/subscribe(...)`。
38
+
39
+ ## 验证边界
40
+ 隔离浏览器无法通过宿主鉴权(root 401),故无运行截图;已做 JS 语法/manifest 校验。视觉/运行时确认请在已鉴权 GUI 刷新(Ctrl+R)。
41
+
42
+ 逻辑回归:`node test/regression.cjs`(74 条断言全过)。vm 沙箱 + fake 定时器/`Date.now`,mock 宿主 `sessions.list`(createSnapshotStore 表面)/`retain`/`provide`/`binding`/`uiSession.sessionStatus`。覆盖:接口仅四成员、inject sessions+uiSession、5s 心跳、自动纳入与 retain source、active 跟随、发布去重、unmanage 释放+宽限窗+过窗重纳、manage 清宽限与幂等、missing/stalled/alive 三态、持久化(v3 只存 user、重复 ids 去重、v1/v2 整份丢弃)、卸载对称(释放/清定时器/撤服务/退订阅)与 dispose 后零副作用/幂等卸载、跨刷新 prune、awaiting 出现/清除/去重/缺席降级、实时事件流停滞判据(append/settle-assistant 计进展且立即回蓝、prepend/replace 不计)、事件流订阅随 unmanage/dispose 对称退订、auto 归位收掉(idle 按 max(updatedAt,liveAt)、成为视图不升级 user)。
43
+
44
+ 设计来源(2026-11-20):用户要求"单一职责:只负责管理会话,对外只暴露一个接口,对内只负责保活和心跳检测";四项决策=拆独立 UI 插件 / 长期 retain 保活 / 周期轮询快照判活 / 单一 cordis 服务 `ctx.sessionKeeper`。
@@ -0,0 +1,319 @@
1
+ /*
2
+ * @capyclaw/session-keeper 浏览器半:会话保活 + 心跳检测服务(无 UI)。
3
+ *
4
+ * 单一职责:本插件只负责"管理会话"——
5
+ * 对外:唯一接口 ctx.sessionKeeper(cordis service),仅四个成员:
6
+ * manage(id) / unmanage(id) / subscribe(fn) / getState()。
7
+ * 对内:只做三件事——
8
+ * 1) 保活:对受管会话持有 ctx.sessions.retain(id,{source:'sessionKeeper'})
9
+ * 引用,切走/关闭视图不释放,直到 unmanage 或插件卸载;
10
+ * 2) 心跳:周期(BEAT_MS)轮询 ctx.sessions.list.getSnapshot(),对受管会话
11
+ * 判活 alive / stalled(running 但「最后活动」久无进展)/ missing(目录消失),
12
+ * 并按策略自动纳入 running 与当前主视图会话;列表变更即时补一拍;
13
+ * 3) 归位:受管集合分两种来源——auto(心跳自动纳入)与 user(manage 显式纳入)。
14
+ * auto 的会话「不再运行、且不是当前视图、且已空闲 IDLE_DROP_MS」就自动收掉
15
+ * (空闲按最后活动 max(updatedAt, liveAt) 计;并释放保活引用),user 的永不
16
+ * 自动收。auto 只活在内存里、绝不落盘;成为
17
+ * 当前视图也不升级为 user(旧策略会把每个点过的会话永久钉死,越攒越多)。
18
+ * 最后活动 = max(durable updatedAt, 实时事件流 liveAt):updatedAt 只随
19
+ * 落盘消息前进,思考/正文流式块(assistant/live-chunk)经 binding.eventSource
20
+ * 订阅计入 liveAt,避免"屏幕在蹦字却误报停滞"。
21
+ * 不含任何渲染/DOM/标签序 presentation 逻辑;受管集合里的 user 来源持久化于 localStorage。
22
+ */
23
+ window.__ModuleLoader__.load({
24
+ id: '@capyclaw/session-keeper',
25
+ factory: function (require) {
26
+ var KEY = 'capyclaw.sessionKeeper.v1'
27
+ var SCHEMA = 3 // 持久化结构版本:v3 起只落盘 user 来源;旧结构一律丢弃
28
+ var BEAT_MS = 5000 // 心跳周期
29
+ var STALL_MS = 120000 // running 但最后活动 max(updatedAt, liveAt) 超过该时长无进展 ⇒ stalled(仅提示,不 destructive)
30
+ var CLOSED_TTL = 5000 // unmanage 后的宽限:期间心跳不自动重新纳入(给 cancel 留时间)
31
+ var IDLE_DROP_MS = 30000 // auto 标签在「不再运行」后仍保留的宽限,避免刚跑完的标签瞬移消失
32
+
33
+ function loadPersisted() {
34
+ /* 只还原 user 来源(v3 起 auto 不落盘)。旧结构(v1/v2 或坏数据)直接丢弃:
35
+ 那两版把「曾经 running / 曾经看过」的会话都堆在 ids 里,还原即一次弹回
36
+ 几十个历史标签——这是必须一次性清掉的脏数据,宁可空标签条。 */
37
+ try {
38
+ var p = JSON.parse(localStorage.getItem(KEY) || 'null') || {}
39
+ if (p.v !== SCHEMA || !Array.isArray(p.ids)) return []
40
+ var seen = {}
41
+ return p.ids.filter(function (x) {
42
+ if (typeof x !== 'string' || seen[x]) return false
43
+ seen[x] = true
44
+ return true
45
+ })
46
+ } catch (err) { return [] }
47
+ }
48
+
49
+ function createKeeper(ctx) {
50
+ var persisted = loadPersisted()
51
+ var listeners = []
52
+ var refs = {} // id -> ClientSessionReference(保活引用)
53
+ var closedAt = {} // id -> unmanage 时间戳(宽限窗)
54
+ var liveAt = {} // id -> 实时事件流最后活动时间(含流式思考/正文块)
55
+ var feeds = {} // id -> {source,un}:eventSource 订阅(绑定换代自动重订)
56
+ var pruned = false
57
+ var lastSig = null
58
+ var disposed = false // 卸载后冻结一切副作用:缓存的 service 引用不得再写盘/retain/订阅
59
+ var state = {
60
+ phase: 'pending',
61
+ ids: persisted,
62
+ auto: {}, // id -> true:本次运行里心跳自动纳入(只存内存,绝不落盘)
63
+ activeId: null,
64
+ sessions: {}, // id -> {title,running,updatedAt,status,lastBeat,awaiting}
65
+ beatAt: 0
66
+ }
67
+
68
+ function saveIds() {
69
+ if (disposed) return
70
+ try {
71
+ var ids = state.ids.filter(function (id) { return !state.auto[id] })
72
+ localStorage.setItem(KEY, JSON.stringify({ v: SCHEMA, ids: ids }))
73
+ } catch (err) { /* 隐私模式等:忽略 */ }
74
+ }
75
+ function sig() {
76
+ var slim = {}
77
+ state.ids.forEach(function (id) {
78
+ var s = state.sessions[id] || {}
79
+ slim[id] = [s.title, s.running, s.updatedAt, s.status, s.awaiting]
80
+ })
81
+ return JSON.stringify({ ids: state.ids, activeId: state.activeId, sessions: slim })
82
+ }
83
+ function publish() {
84
+ var s = sig()
85
+ if (s === lastSig) return
86
+ lastSig = s
87
+ listeners.forEach(function (fn) { fn(state) })
88
+ }
89
+ function readList() {
90
+ var list = ctx.sessions && ctx.sessions.list
91
+ // 宿主 createSnapshotStore 表面仅 {getSnapshot,subscribe,update,set}
92
+ if (list && typeof list.getSnapshot === 'function') return list.getSnapshot()
93
+ return null
94
+ }
95
+ /* 等待用户操作信号:宿主 uiSession.sessionStatus 的 per-session
96
+ pendingInteraction(问题卡/审批卡等经 registerPendingInteraction 发布)。
97
+ 宿主缺席时降级为 false,不影响判活主链路。 */
98
+ function readPending() {
99
+ var us = ctx.uiSession
100
+ var store = us && us.sessionStatus
101
+ if (store && typeof store.getSnapshot === 'function') {
102
+ var snap = store.getSnapshot()
103
+ if (snap && typeof snap.get === 'function') return snap
104
+ }
105
+ return null
106
+ }
107
+ function isAwaiting(pend, id) {
108
+ if (!pend) return false
109
+ var st = pend.get(id)
110
+ return !!(st && st.pendingInteraction)
111
+ }
112
+ function retain(id) {
113
+ if (refs[id]) return
114
+ try {
115
+ refs[id] = ctx.sessions.retain(id, { source: 'sessionKeeper' })
116
+ } catch (err) {
117
+ console.warn('[session-keeper] retain failed for', id, err)
118
+ }
119
+ }
120
+ function release(id) {
121
+ var ref = refs[id]
122
+ delete refs[id]
123
+ if (ref && typeof ref.release === 'function') ref.release()
124
+ }
125
+ /* 实时活动信号:binding.eventSource 的每次 live 尾部变更(append /
126
+ settle-assistant)都算主机进展——append 里含 assistant/live-chunk
127
+ 流式思考/正文块。replace/prepend 属历史装载与重连 machinery,不计。
128
+ 宿主无 binding/eventSource 时降级:仅用 durable updatedAt。 */
129
+ function watchFeed(id) {
130
+ var sessions = ctx.sessions
131
+ var b = (sessions && typeof sessions.binding === 'function') ? sessions.binding(id) : null
132
+ var src = b && b.eventSource
133
+ if (!src || typeof src.subscribe !== 'function') { unwatchFeed(id); return }
134
+ if (feeds[id] && feeds[id].source === src) return
135
+ unwatchFeed(id)
136
+ feeds[id] = {
137
+ source: src,
138
+ un: src.subscribe(function () {
139
+ var snap = typeof src.getSnapshot === 'function' ? src.getSnapshot() : null
140
+ var ch = snap && snap.change
141
+ if (ch && (ch.kind === 'append' || ch.kind === 'settle-assistant')) {
142
+ liveAt[id] = Date.now()
143
+ // 已误报停滞的会话收到第一个流式块时立即回蓝,不等下一拍
144
+ if (state.sessions[id] && state.sessions[id].status === 'stalled') beat()
145
+ }
146
+ })
147
+ }
148
+ }
149
+ function unwatchFeed(id) {
150
+ var f = feeds[id]
151
+ if (!f) return
152
+ delete feeds[id]
153
+ try { f.un() } catch (err) { /* 绑定已销毁等:忽略 */ }
154
+ }
155
+ function forgetFeed(id) {
156
+ unwatchFeed(id)
157
+ delete liveAt[id]
158
+ }
159
+
160
+ /* ---- 心跳:唯一判活入口 ---- */
161
+ function beat() {
162
+ if (disposed) return
163
+ var snap = readList()
164
+ if (!snap) return
165
+ var now = Date.now()
166
+ // 宽限窗条目只进不出:清扫已过期的,避免长会话里 closedAt 无界增长
167
+ Object.keys(closedAt).forEach(function (id) {
168
+ if (now - closedAt[id] >= CLOSED_TTL) delete closedAt[id]
169
+ })
170
+ var pend = readPending()
171
+ state.phase = snap.phase === 'pending' ? 'pending' : 'ready'
172
+ state.beatAt = now
173
+ var idsChanged = false
174
+ // 首个 ready 快照:清理跨刷新已消失的持久化 id
175
+ if (!pruned && state.phase === 'ready') {
176
+ pruned = true
177
+ var alive = state.ids.filter(function (id) { return !!snap.byId[id] })
178
+ if (alive.length !== state.ids.length) { state.ids = alive; idsChanged = true }
179
+ // 跨刷新还原的受管集合本来就该保活:补上引用(此前只有自动纳入/manage 才 retain)
180
+ state.ids.forEach(retain)
181
+ }
182
+ // 保活策略:running 与当前主视图会话自动纳入(宽限窗内除外);auto 不进持久化
183
+ ;(snap.ids || []).forEach(function (id) {
184
+ var row = snap.byId[id]
185
+ if (!row) return
186
+ var want = !!row.running || (row.retainedBy && row.retainedBy.mainView > 0)
187
+ if (!want) return
188
+ if (state.ids.indexOf(id) >= 0) return
189
+ if (closedAt[id] && now - closedAt[id] < CLOSED_TTL) return
190
+ state.ids.push(id)
191
+ state.auto[id] = true
192
+ retain(id)
193
+ })
194
+ // 归位:auto 会话「不再运行 + 不是当前视图 + 空闲超宽限」⇒ 自动收掉;
195
+ // 成为当前视图不再升级为 user(那会把每个点过的会话永久钉死)。
196
+ var dropped = []
197
+ state.ids.forEach(function (id) {
198
+ if (!state.auto[id]) return
199
+ var row = snap.byId[id]
200
+ if (!row) { dropped.push(id); return }
201
+ if (row.running) return
202
+ if (row.retainedBy && row.retainedBy.mainView > 0) return
203
+ // 空闲判据与判活一致:max(updatedAt, liveAt)。durable 写滞后时
204
+ // 刚结束的流式活动(liveAt 新鲜)不应导致提前收掉。
205
+ var lastAct = Math.max(row.updatedAt || 0, liveAt[id] || 0)
206
+ if (now - lastAct < IDLE_DROP_MS) return
207
+ dropped.push(id)
208
+ })
209
+ if (dropped.length) {
210
+ state.ids = state.ids.filter(function (id) { return dropped.indexOf(id) < 0 })
211
+ dropped.forEach(function (id) { delete state.auto[id]; forgetFeed(id); release(id) })
212
+ }
213
+ if (idsChanged) saveIds()
214
+ // 当前主视图会话
215
+ state.activeId = null
216
+ ;(snap.ids || []).some(function (id) {
217
+ var row = snap.byId[id]
218
+ if (row && row.retainedBy && row.retainedBy.mainView > 0) { state.activeId = id; return true }
219
+ return false
220
+ })
221
+ // 受管会话判活
222
+ var next = {}
223
+ state.ids.forEach(function (id) {
224
+ var row = snap.byId[id]
225
+ var prev = state.sessions[id]
226
+ if (!row) {
227
+ forgetFeed(id)
228
+ next[id] = {
229
+ title: (prev && prev.title) || id,
230
+ running: false, updatedAt: (prev && prev.updatedAt) || 0,
231
+ status: 'missing', lastBeat: now, awaiting: false
232
+ }
233
+ return
234
+ }
235
+ var title = row.displayTitle || row.title || (row.blank ? '新会话' : '会话')
236
+ watchFeed(id)
237
+ var lastAct = Math.max(row.updatedAt || 0, liveAt[id] || 0)
238
+ var stalled = !!row.running && lastAct > 0 && (now - lastAct) > STALL_MS
239
+ next[id] = {
240
+ title: title, running: !!row.running, updatedAt: row.updatedAt || 0,
241
+ status: stalled ? 'stalled' : 'alive', lastBeat: now,
242
+ awaiting: isAwaiting(pend, id)
243
+ }
244
+ })
245
+ state.sessions = next
246
+ publish()
247
+ }
248
+
249
+ /* ---- 唯一接口的四个成员 ---- */
250
+ function manage(id) {
251
+ if (disposed) return false
252
+ if (typeof id !== 'string' || !id) return false
253
+ delete closedAt[id]
254
+ delete state.auto[id] // 显式纳入 ⇒ user 标签,此后不再被自动收
255
+ if (state.ids.indexOf(id) < 0) { state.ids.push(id) }
256
+ saveIds()
257
+ retain(id)
258
+ beat()
259
+ return true
260
+ }
261
+ function unmanage(id) {
262
+ if (disposed) return
263
+ var i = state.ids.indexOf(id)
264
+ if (i >= 0) { state.ids.splice(i, 1); saveIds() }
265
+ delete state.auto[id]
266
+ closedAt[id] = Date.now()
267
+ forgetFeed(id)
268
+ release(id)
269
+ beat()
270
+ }
271
+ function subscribe(fn) {
272
+ if (disposed) return function () {}
273
+ listeners.push(fn)
274
+ return function () {
275
+ var i = listeners.indexOf(fn)
276
+ if (i >= 0) listeners.splice(i, 1)
277
+ }
278
+ }
279
+ function getState() { return state }
280
+
281
+ var service = { manage: manage, unmanage: unmanage, subscribe: subscribe, getState: getState }
282
+
283
+ // 装配:暴露唯一接口 + 心跳定时器 + 列表变更即时补一拍
284
+ var provideFn = typeof ctx.provide === 'function'
285
+ ? ctx.provide.bind(ctx)
286
+ : (ctx.reflect && ctx.reflect.provide ? ctx.reflect.provide.bind(ctx.reflect) : null)
287
+ var unprovide = provideFn ? provideFn('sessionKeeper', service) : null
288
+ var timer = setInterval(beat, BEAT_MS)
289
+ var list = ctx.sessions && ctx.sessions.list
290
+ var unList = (list && typeof list.subscribe === 'function') ? list.subscribe(beat) : null
291
+ var statusStore = ctx.uiSession && ctx.uiSession.sessionStatus
292
+ var unStatus = (statusStore && typeof statusStore.subscribe === 'function') ? statusStore.subscribe(beat) : null
293
+ beat()
294
+
295
+ function dispose() {
296
+ if (disposed) return // 幂等:二次卸载不重复 unprovide/退订
297
+ disposed = true
298
+ clearInterval(timer)
299
+ if (typeof unList === 'function') unList()
300
+ if (typeof unStatus === 'function') unStatus()
301
+ Object.keys(refs).forEach(release)
302
+ Object.keys(feeds).forEach(forgetFeed)
303
+ listeners.length = 0
304
+ if (typeof unprovide === 'function') unprovide()
305
+ }
306
+ return { service: service, dispose: dispose }
307
+ }
308
+
309
+ var api = {
310
+ name: '@capyclaw/session-keeper',
311
+ inject: ['sessions', 'uiSession'],
312
+ apply: function (ctx) {
313
+ var keeper = createKeeper(ctx)
314
+ return keeper.dispose
315
+ }
316
+ }
317
+ return api
318
+ }
319
+ })
@@ -0,0 +1,9 @@
1
+ # @capyclaw/session-keeper bundle patch:把纯会话保活/心跳服务挂进 Harness 模块图。
2
+ #
3
+ # 宿主半(index.js)是空操作 —— 本包没有路由、没有模型面,只提供一个浏览器模块。
4
+ # 浏览器半(client/client.js)注册 id 为 @capyclaw/session-keeper 的 factory:
5
+ # inject ['sessions', 'uiSession'],经 ctx.provide 暴露唯一接口 ctx.sessionKeeper;
6
+ # 对内只做 retain 保活 + 周期心跳判活 + auto 归位收掉,不含任何 UI。
7
+ - insert:
8
+ - id: session-keeper
9
+ name: "@capyclaw/session-keeper"
package/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /*
2
+ * @capyclaw/session-keeper 宿主半:空操作。
3
+ *
4
+ * 纯客户端包(会话保活/心跳服务),没有 HTTP 路由、没有模型面。宿主半存在的唯一
5
+ * 理由是让 cordis 有一个 Loader entry,从而把浏览器半(client/client.js,
6
+ * id '@capyclaw/session-keeper')送进模块图。真正的实现全在浏览器半:
7
+ * - inject ['sessions', 'uiSession'],经 ctx.provide('sessionKeeper', ...) 暴露唯一接口;
8
+ * - 对内只做受管会话的 retain 保活、周期心跳判活与 auto 归位收掉,不含任何 UI。
9
+ */
10
+ export const name = 'session-keeper'
11
+ export const inject = []
12
+ 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'