@capyclaw/browser-workbench 0.0.0-stage → 0.1.19

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 (168) hide show
  1. package/README.md +88 -2
  2. package/contract/browser-contract.json +1349 -0
  3. package/demo/form.html +112 -0
  4. package/lib/host.mjs +1 -0
  5. package/node_modules/@capyclaw/asset-service/README.md +48 -0
  6. package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
  7. package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
  8. package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
  9. package/node_modules/@capyclaw/asset-service/package.json +59 -0
  10. package/node_modules/@capyclaw/asset-service/src/index.mjs +304 -0
  11. package/node_modules/@capyclaw/document-workbench/README.md +125 -0
  12. package/node_modules/@capyclaw/document-workbench/package.json +44 -0
  13. package/node_modules/@capyclaw/document-workbench/src/bridge/index.mjs +321 -0
  14. package/node_modules/@capyclaw/document-workbench/src/client/index.mjs +625 -0
  15. package/node_modules/@capyclaw/document-workbench/src/client/screenshot.mjs +98 -0
  16. package/node_modules/@capyclaw/document-workbench/src/index.mjs +9 -0
  17. package/node_modules/@capyclaw/document-workbench/src/model/audit.mjs +101 -0
  18. package/node_modules/@capyclaw/document-workbench/src/model/conformance.mjs +92 -0
  19. package/node_modules/@capyclaw/document-workbench/src/model/ids.mjs +56 -0
  20. package/node_modules/@capyclaw/document-workbench/src/model/index.mjs +18 -0
  21. package/node_modules/@capyclaw/document-workbench/src/model/locate.mjs +118 -0
  22. package/node_modules/@capyclaw/document-workbench/src/model/manifest.mjs +148 -0
  23. package/node_modules/@capyclaw/document-workbench/src/model/ops.mjs +160 -0
  24. package/node_modules/@capyclaw/document-workbench/src/model/validate.mjs +72 -0
  25. package/node_modules/@capyclaw/document-workbench/src/ops/index.mjs +93 -0
  26. package/node_modules/@capyclaw/document-workbench/src/session/context.mjs +103 -0
  27. package/node_modules/@capyclaw/document-workbench/src/session/index.mjs +394 -0
  28. package/node_modules/@capyclaw/document-workbench/src/session/lease.mjs +105 -0
  29. package/node_modules/@capyclaw/document-workbench/src/session/mode.mjs +80 -0
  30. package/node_modules/@capyclaw/document-workbench/src/session/sanitize.mjs +107 -0
  31. package/node_modules/@capyclaw/document-workbench/src/session/state.mjs +159 -0
  32. package/node_modules/@capyclaw/document-workbench/src/session/watch.mjs +63 -0
  33. package/node_modules/@capyclaw/document-workbench/src/store/file-backend.mjs +158 -0
  34. package/node_modules/@capyclaw/document-workbench/src/testing/index.mjs +75 -0
  35. package/node_modules/@capyclaw/foundation/README.md +51 -0
  36. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  37. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  38. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  39. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  40. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  41. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  42. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  43. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  44. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  45. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  46. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  47. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  48. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  49. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  50. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  51. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  52. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  53. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  54. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  55. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  56. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  57. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  58. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  59. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  60. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  61. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  62. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  63. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  64. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  65. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  66. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  67. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  68. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  69. package/node_modules/@capyclaw/foundation/package.json +53 -0
  70. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  71. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  72. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  73. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  74. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +58 -0
  79. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  80. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  81. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  82. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  83. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  84. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  85. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  86. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  87. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  88. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  89. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  90. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  91. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  92. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  93. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  94. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  95. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  96. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  97. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  98. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  99. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  100. package/node_modules/@capyclaw/service-host/README.md +86 -0
  101. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  102. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  103. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  104. package/node_modules/@capyclaw/service-host/package.json +60 -0
  105. package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
  106. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  107. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  108. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  109. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  110. package/node_modules/@capyclaw/tool-host/lib/host.mjs +16 -0
  111. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  112. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  113. package/node_modules/@capyclaw/tool-host/src/index.mjs +416 -0
  114. package/package.json +77 -4
  115. package/plugin.mjs +1 -0
  116. package/server/constants.mjs +16 -0
  117. package/server/contract-snapshots.mjs +81 -0
  118. package/server/contract.mjs +24 -0
  119. package/server/embedded-host.mjs +247 -0
  120. package/server/engine.mjs +2466 -0
  121. package/server/governor.mjs +189 -0
  122. package/server/http-utils.mjs +2 -0
  123. package/server/human.mjs +628 -0
  124. package/server/infra/http.mjs +2 -0
  125. package/server/infra/tuning.mjs +2 -0
  126. package/server/input.mjs +154 -0
  127. package/server/login-vault.mjs +109 -0
  128. package/server/mcp/handler.mjs +2 -0
  129. package/server/mcp/instructions.mjs +31 -0
  130. package/server/orphans.mjs +163 -0
  131. package/server/relay.mjs +198 -0
  132. package/server/routes/api.mjs +233 -0
  133. package/server/routes/assets.mjs +2 -0
  134. package/server/routes/mcp.mjs +17 -0
  135. package/server/routes/workbench.mjs +33 -0
  136. package/server/session-engines.mjs +223 -0
  137. package/server/shared/SHARED_MANIFEST.json +70 -0
  138. package/server/shared/asset-service.mjs +2 -0
  139. package/server/shared/editor-host.mjs +2 -0
  140. package/server/shared/kit/editor/lease.mjs +2 -0
  141. package/server/shared/kit/service/api.mjs +2 -0
  142. package/server/shared/kit/service/http.mjs +2 -0
  143. package/server/shared/kit/service/mcp-http.mjs +2 -0
  144. package/server/shared/kit/tools/validate.mjs +2 -0
  145. package/server/shared/kit/tuning.mjs +2 -0
  146. package/server/shared/kit/util/fs-lock.mjs +2 -0
  147. package/server/shared/service-host.mjs +2 -0
  148. package/server/shared/tool-host.mjs +2 -0
  149. package/server/shared/tuning.mjs +2 -0
  150. package/server/tools/capabilities/contract.mjs +55 -0
  151. package/server/tools/capabilities/evaluate.mjs +36 -0
  152. package/server/tools/capabilities/index.mjs +26 -0
  153. package/server/tools/capabilities/interaction.mjs +215 -0
  154. package/server/tools/capabilities/navigation.mjs +35 -0
  155. package/server/tools/capabilities/screenshot.mjs +50 -0
  156. package/server/tools/capabilities/session.mjs +81 -0
  157. package/server/tools/capabilities/snapshot.mjs +30 -0
  158. package/server/tools/capabilities/tabs.mjs +35 -0
  159. package/server/tools/index.mjs +12 -0
  160. package/server/tools/kernel/define.mjs +5 -0
  161. package/server/tools/kernel/output.mjs +30 -0
  162. package/server/tools/kernel/ports.mjs +59 -0
  163. package/server/tools/kernel/registry.mjs +17 -0
  164. package/server/tools.mjs +3 -0
  165. package/server/workbench-framework.mjs +305 -0
  166. package/ui/app.js +447 -0
  167. package/ui/index.html +46 -0
  168. package/ui/style.css +144 -0
@@ -0,0 +1,159 @@
1
+ /**
2
+ * 版本化文档会话的标准信封与纯状态迁移。
3
+ *
4
+ * 这层只认识 seq/cmds/ack/state/ui/shot/owner 这些协议字段;领域文档放在
5
+ * 调用方指定的 documentKey 下,由 adapter 负责解释。
6
+ */
7
+
8
+ export const SESSION_DEFAULTS = Object.freeze({
9
+ seq: 0,
10
+ cmds: [],
11
+ title: '',
12
+ applied_seq: 0,
13
+ applied: 0,
14
+ error: '',
15
+ updated: 0,
16
+ pending_since: 0,
17
+ state_seq: 0,
18
+ ui_seq: 0,
19
+ ui: [],
20
+ shot_req: 0,
21
+ shot: { req: 0, data: '' },
22
+ /* 截图渲染选项:跟请求一起送到编辑器(通用渲染参数,不认识就忽略)。 */
23
+ shot_opts: null,
24
+ })
25
+
26
+ export function nowSeconds() {
27
+ return Date.now() / 1000
28
+ }
29
+
30
+ /** 创建一份带标准信封的会话状态;initial 可携带领域字段(deck/doc/value)。 */
31
+ export function createSessionState(initial = {}) {
32
+ const source = initial && typeof initial === 'object' ? initial : {}
33
+ return {
34
+ ...structuredClone(SESSION_DEFAULTS),
35
+ ...structuredClone(source),
36
+ cmds: Array.isArray(source.cmds) ? structuredClone(source.cmds) : [],
37
+ ui: Array.isArray(source.ui) ? structuredClone(source.ui) : [],
38
+ shot: { ...SESSION_DEFAULTS.shot, ...(source.shot || {}) },
39
+ }
40
+ }
41
+
42
+ function optionsOf(nowOrOptions) {
43
+ return typeof nowOrOptions === 'number' ? { now: nowOrOptions } : (nowOrOptions || {})
44
+ }
45
+
46
+ /** 新批次入队:seq 自增,清空上批回执,保留领域文档。 */
47
+ export function applyPush(doc, cmds, title, nowOrOptions = {}) {
48
+ const opts = optionsOf(nowOrOptions)
49
+ const now = opts.now ?? nowSeconds()
50
+ Object.assign(doc, {
51
+ seq: (doc.seq | 0) + 1,
52
+ cmds: Array.isArray(cmds) ? cmds : [],
53
+ title: title || '',
54
+ applied_seq: 0,
55
+ applied: 0,
56
+ error: '',
57
+ pending_since: now,
58
+ updated: now,
59
+ })
60
+ return doc
61
+ }
62
+
63
+ /** 服务端执行完成:只有当前批次可以落回执。 */
64
+ export function applyServer(doc, seq, applied, error, nowOrOptions = {}) {
65
+ const opts = optionsOf(nowOrOptions)
66
+ if ((doc.seq | 0) !== (seq | 0)) return doc
67
+ Object.assign(doc, {
68
+ applied_seq: seq,
69
+ applied: applied | 0,
70
+ error: error || '',
71
+ state_seq: seq,
72
+ pending_since: 0,
73
+ updated: opts.now ?? nowSeconds(),
74
+ })
75
+ if (typeof opts.onApplied === 'function') opts.onApplied(doc, seq)
76
+ if (opts.stateCompact !== false) doc.cmds = []
77
+ return doc
78
+ }
79
+
80
+ /** 编辑器回执:同样只接受当前批次。 */
81
+ export function applyAck(doc, seq, applied, error, nowOrOptions = {}) {
82
+ const opts = optionsOf(nowOrOptions)
83
+ if ((doc.seq | 0) !== (seq | 0)) return doc
84
+ Object.assign(doc, {
85
+ applied_seq: seq,
86
+ applied: applied | 0,
87
+ error: error || '',
88
+ pending_since: 0,
89
+ updated: opts.now ?? nowSeconds(),
90
+ })
91
+ return doc
92
+ }
93
+
94
+ /** 编辑器镜像:旧 seq 的镜像不能覆盖新文档。 */
95
+ export function applyState(doc, value, seq, nowOrOptions = {}) {
96
+ const opts = optionsOf(nowOrOptions)
97
+ if (seq != null && (seq | 0) < (doc.seq | 0)) return doc
98
+ const key = opts.documentKey || 'document'
99
+ doc[key] = value
100
+ if (seq != null) doc.state_seq = seq | 0
101
+ doc.updated = opts.now ?? nowSeconds()
102
+ return doc
103
+ }
104
+
105
+ export function applyUi(doc, cmds, nowOrOptions = {}) {
106
+ const opts = optionsOf(nowOrOptions)
107
+ doc.ui_seq = (doc.ui_seq | 0) + 1
108
+ doc.ui = Array.isArray(cmds) ? cmds : []
109
+ doc.updated = opts.now ?? nowSeconds()
110
+ return doc
111
+ }
112
+
113
+ /**
114
+ * 截图选项白名单:只放行通用渲染参数,其它键一律丢弃。
115
+ * 协议是「不认识就忽略」——老编辑器收不到也不会坏;新编辑器据此只渲染指定页。
116
+ */
117
+ export function normalizeShotOpts(raw) {
118
+ if (!raw || typeof raw !== 'object') return null
119
+ const out = {}
120
+ const indices = Array.isArray(raw.indices)
121
+ ? raw.indices
122
+ .map((n) => Number(n))
123
+ .filter((n) => Number.isInteger(n) && n >= 0)
124
+ .slice(0, 12)
125
+ : []
126
+ if (indices.length) out.indices = [...new Set(indices)]
127
+ const width = Number(raw.width)
128
+ if (Number.isFinite(width) && width > 0) out.width = Math.min(2400, Math.max(200, Math.round(width)))
129
+ const quality = Number(raw.quality)
130
+ if (Number.isFinite(quality) && quality > 0 && quality <= 1) out.quality = quality
131
+ if (typeof raw.format === 'string' && /^(png|jpe?g|webp)$/i.test(raw.format)) {
132
+ out.format = raw.format.toLowerCase() === 'jpg' ? 'jpeg' : raw.format.toLowerCase()
133
+ }
134
+ return Object.keys(out).length ? out : null
135
+ }
136
+
137
+ export function applyShotRequest(doc, opts = null, nowOrOptions = {}) {
138
+ const clock = optionsOf(nowOrOptions)
139
+ doc.shot_req = (doc.shot_req | 0) + 1
140
+ doc.shot = { req: 0, data: '' }
141
+ doc.shot_opts = normalizeShotOpts(opts)
142
+ doc.updated = clock.now ?? nowSeconds()
143
+ return doc
144
+ }
145
+
146
+ export function applyShotResult(doc, req, data, nowOrOptions = {}) {
147
+ const opts = optionsOf(nowOrOptions)
148
+ if ((doc.shot_req | 0) !== (req | 0)) return doc
149
+ doc.shot = { req, data: data || '' }
150
+ doc.updated = opts.now ?? nowSeconds()
151
+ return doc
152
+ }
153
+
154
+ export function pendingOf(doc) {
155
+ if ((doc.seq | 0) > (doc.applied_seq | 0) && Array.isArray(doc.cmds) && doc.cmds.length) {
156
+ return { seq: doc.seq | 0, title: doc.title || '', cmds: doc.cmds }
157
+ }
158
+ return null
159
+ }
@@ -0,0 +1,63 @@
1
+ /** 长轮询:seq / shot / ui 任一变化即返回。
2
+ *
3
+ * 唤醒双保险:session 带 subscribe(事件)时变化即时返回——轮询粒度不再
4
+ * 进入延迟路径;pollMs 定时器保留为兜底(事件丢失/老 session 无订阅面)。
5
+ */
6
+
7
+ export function watchSession(session, {
8
+ seq = 0,
9
+ shot = 0,
10
+ ui = 0,
11
+ timeoutS,
12
+ isAborted = () => false,
13
+ pollMs = 75,
14
+ timeoutSec = 20,
15
+ maxTimeoutSec = 30,
16
+ } = {}) {
17
+ const poll = Math.max(10, Number(pollMs) || 75)
18
+ const maxTimeout = Math.max(1, Number(maxTimeoutSec) || 30)
19
+ const defaultTimeout = Math.max(1, Number(timeoutSec) || 20)
20
+ const timeout = Math.min(Math.max(Number(timeoutS) || defaultTimeout, 1), maxTimeout)
21
+
22
+ return new Promise((resolve) => {
23
+ const deadline = Date.now() + timeout * 1000
24
+ let settled = false
25
+ let timer = null
26
+ let unsubscribe = null
27
+
28
+ const finish = (value) => {
29
+ if (settled) return
30
+ settled = true
31
+ if (timer) clearTimeout(timer)
32
+ if (unsubscribe) {
33
+ try { unsubscribe() } catch { /* ignore */ }
34
+ }
35
+ resolve(value)
36
+ }
37
+
38
+ const changed = (doc) => (doc.seq | 0) !== (seq | 0)
39
+ || (doc.shot_req | 0) !== (shot | 0)
40
+ || (doc.ui_seq | 0) !== (ui | 0)
41
+
42
+ const check = () => {
43
+ if (isAborted()) return finish(null)
44
+ const doc = session.get()
45
+ if (changed(doc) || Date.now() > deadline) finish(doc)
46
+ }
47
+
48
+ /* 兜底轮询:事件路径正常时每次 tick 都是空检查(微秒级)。 */
49
+ const tick = () => {
50
+ if (settled) return
51
+ check()
52
+ if (!settled) timer = setTimeout(tick, poll)
53
+ }
54
+
55
+ if (typeof session.subscribe === 'function') {
56
+ unsubscribe = session.subscribe(() => {
57
+ if (settled) return
58
+ check()
59
+ })
60
+ }
61
+ tick()
62
+ })
63
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * 文档持久化后端:原子 JSON 状态 + append-only journal(可轮转)+ 命名 checkpoint。
3
+ *
4
+ * 从 @capyclaw/state-service 移入 document-workbench:
5
+ * 桥的持久化是「文档会话」的一部分,不该让每个 workbench 都依赖 state 插件包。
6
+ * state-service 已于 2026-11-15 退役删包,这里是唯一实现源。
7
+ */
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+
11
+ export class FileStateBackend {
12
+ /* journalMaxBytes 默认 512KB 由 NSGA-II 进化搜索固化(evolution/,2026-11-01):
13
+ * 尾读 p95 4.3→1.9ms、磁盘占用 -33%、追加吞吐 +8%,恢复 0 失败。
14
+ *
15
+ * fsyncEvery 默认 16:状态写是「write tmp → rename」的原子替换,进程崩溃时
16
+ * 页缓存中的数据已对其它进程可见(rename 原子),只有掉电才需要 fsync 保证落盘。
17
+ * 实测每写一次 fsync 使 157KB 状态从 0.67ms 涨到 1.80ms(+1.13ms),而
18
+ * document-workbench 每个编辑批次会写 2 次状态——节流到每 16 次写一次 fsync,
19
+ * 把该链路成本从 ~3.6ms/批降到 ~1.5ms/批;checkpoint 仍强制 fsync(里程碑语义)。
20
+ * 设为 1 恢复「每次写都 fsync」的旧行为;设为 0 则完全不做 fsync。 */
21
+ constructor(file, { initialDoc = {}, journalMaxBytes = 512 * 1024, fsyncEvery = 16 } = {}) {
22
+ if (!file) throw new Error('FileStateBackend 需要 file')
23
+ this.file = file
24
+ this.dir = path.dirname(file)
25
+ this.journalFile = path.join(this.dir, 'journal.jsonl')
26
+ this.checkpointDir = path.join(this.dir, 'checkpoints')
27
+ this.initialDoc = initialDoc
28
+ this.journalMaxBytes = Math.max(64 * 1024, Number(journalMaxBytes) || 512 * 1024)
29
+ this.fsyncEvery = Math.max(0, Number(fsyncEvery) || 0)
30
+ this._writeCount = 0
31
+ /** 最近一次读状态失败的原因;ENOENT 不算错误。 */
32
+ this.lastStateError = null
33
+ }
34
+
35
+ readState() {
36
+ let raw
37
+ try {
38
+ raw = fs.readFileSync(this.file, 'utf8')
39
+ } catch (error) {
40
+ if (error.code === 'ENOENT') return null
41
+ this.lastStateError = { code: 'STATE_IO', message: error.message }
42
+ return null
43
+ }
44
+ try {
45
+ const parsed = JSON.parse(raw)
46
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
47
+ return { ...structuredClone(this.initialDoc), ...parsed }
48
+ }
49
+ throw new Error('state 根节点不是 object')
50
+ } catch (error) {
51
+ /* 坏状态不能静默当成空库:先隔离原文件,避免下一次保存直接覆盖证据。 */
52
+ this.lastStateError = { code: 'STATE_CORRUPT', message: error.message }
53
+ const quarantine = `${this.file}.corrupt-${Date.now()}`
54
+ try { fs.renameSync(this.file, quarantine) } catch { /* 隔离失败也要保持只读语义 */ }
55
+ console.error(`[document-workbench] state 损坏,已隔离到 ${quarantine}: ${error.message}`)
56
+ return null
57
+ }
58
+ }
59
+
60
+ /** 强制把当前状态文件刷盘(checkpoint/退出等里程碑用;失败不抛)。 */
61
+ flush() {
62
+ try {
63
+ const fd = fs.openSync(this.file, 'r+')
64
+ try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
65
+ } catch { /* 文件不存在或文件系统不支持 fsync */ }
66
+ }
67
+
68
+ writeState(doc) {
69
+ fs.mkdirSync(path.dirname(this.file), { recursive: true })
70
+ const tmp = `${this.file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`
71
+ fs.writeFileSync(tmp, JSON.stringify(doc))
72
+ this._writeCount += 1
73
+ /* fsyncEvery=0 → 从不周期刷盘;=1 → 每次刷盘(旧行为);=N → 每 N 次写刷一次。 */
74
+ const due = this.fsyncEvery > 0 && (this.fsyncEvery === 1 || this._writeCount % this.fsyncEvery === 0)
75
+ if (due) {
76
+ try {
77
+ const fd = fs.openSync(tmp, 'r+')
78
+ try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
79
+ } catch { /* fsync 在部分文件系统不可用 */ }
80
+ }
81
+ fs.renameSync(tmp, this.file)
82
+ }
83
+
84
+ appendJournal(event) {
85
+ try {
86
+ fs.mkdirSync(this.dir, { recursive: true })
87
+ fs.appendFileSync(this.journalFile, JSON.stringify({ ...event, ts: Date.now() / 1000 }) + '\n')
88
+ if (fs.statSync(this.journalFile).size > this.journalMaxBytes) {
89
+ const rotated = this.journalFile + '.1'
90
+ try { fs.rmSync(rotated, { force: true }) } catch { /* 忽略 */ }
91
+ try { fs.renameSync(this.journalFile, rotated) } catch (error) {
92
+ console.error('[document-workbench] journal 轮转失败(继续追加):', error.message)
93
+ }
94
+ }
95
+ } catch { /* journal 失败不阻塞主状态 */ }
96
+ }
97
+
98
+ journalTail(limit = 8) {
99
+ const read = (file) => {
100
+ try {
101
+ return fs.readFileSync(file, 'utf8').trim().split(/\r?\n/).filter(Boolean)
102
+ } catch { return [] }
103
+ }
104
+ /* 轮转后的 .1 仍是最近历史的一部分,tail 必须跨文件读取。 */
105
+ const lines = [...read(this.journalFile + '.1'), ...read(this.journalFile)]
106
+ return lines.slice(-limit).map((line) => {
107
+ try { return JSON.parse(line) } catch { return { type: 'invalid', raw: line.slice(0, 120) } }
108
+ })
109
+ }
110
+
111
+ writeCheckpoint(name, payload) {
112
+ const safe = checkpointName(name)
113
+ fs.mkdirSync(this.checkpointDir, { recursive: true })
114
+ const file = path.join(this.checkpointDir, safe + '.json')
115
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`
116
+ fs.writeFileSync(tmp, JSON.stringify(payload))
117
+ /* checkpoint 是恢复里程碑:无视 fsyncEvery 节流,强制落盘。 */
118
+ try {
119
+ const fd = fs.openSync(tmp, 'r+')
120
+ try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
121
+ } catch { /* fsync 在部分文件系统不可用 */ }
122
+ fs.renameSync(tmp, file)
123
+ }
124
+
125
+ listCheckpoints() {
126
+ try {
127
+ return fs.readdirSync(this.checkpointDir)
128
+ .filter((name) => name.endsWith('.json'))
129
+ .map((name) => {
130
+ try {
131
+ const payload = JSON.parse(fs.readFileSync(path.join(this.checkpointDir, name), 'utf8'))
132
+ return {
133
+ name: payload.name,
134
+ seq: payload.seq,
135
+ appliedSeq: payload.appliedSeq,
136
+ pending: !!payload.pending,
137
+ title: payload.title,
138
+ slides: payload.slides,
139
+ createdAt: payload.createdAt,
140
+ meta: payload.meta || {},
141
+ }
142
+ } catch { return null }
143
+ })
144
+ .filter(Boolean)
145
+ .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
146
+ } catch { return [] }
147
+ }
148
+
149
+ readCheckpoint(name) {
150
+ return JSON.parse(fs.readFileSync(path.join(this.checkpointDir, checkpointName(name) + '.json'), 'utf8'))
151
+ }
152
+ }
153
+
154
+ export function checkpointName(name) {
155
+ const safe = String(name || '')
156
+ if (!/^[a-zA-Z0-9._-]{1,64}$/.test(safe)) throw new Error('checkpoint 名称必须是 1-64 位字母/数字/._-')
157
+ return safe
158
+ }
@@ -0,0 +1,75 @@
1
+ /** 测试工具:内存 backend 与 fake editor adapter,供框架自身和消费者做一致性测试。 */
2
+
3
+ export function createMemoryBackend({ initialDoc = {} } = {}) {
4
+ let state = null
5
+ const journal = []
6
+ const checkpoints = new Map()
7
+ return {
8
+ dir: '',
9
+ file: '',
10
+ journalFile: '',
11
+ checkpointDir: '',
12
+ lastStateError: null,
13
+ readState() {
14
+ return state ? structuredClone(state) : null
15
+ },
16
+ writeState(doc) {
17
+ state = structuredClone(doc)
18
+ },
19
+ appendJournal(event) {
20
+ journal.push({ ...structuredClone(event), ts: Date.now() / 1000 })
21
+ },
22
+ journalTail(limit = 8) {
23
+ return journal.slice(-limit).map((event) => structuredClone(event))
24
+ },
25
+ writeCheckpoint(name, payload) {
26
+ checkpoints.set(name, structuredClone(payload))
27
+ },
28
+ listCheckpoints() {
29
+ return [...checkpoints.values()]
30
+ .map((payload) => ({
31
+ name: payload.name,
32
+ seq: payload.seq,
33
+ appliedSeq: payload.appliedSeq,
34
+ pending: !!payload.pending,
35
+ title: payload.title,
36
+ slides: payload.slides,
37
+ createdAt: payload.createdAt,
38
+ meta: payload.meta || {},
39
+ }))
40
+ .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
41
+ },
42
+ readCheckpoint(name) {
43
+ const payload = checkpoints.get(name)
44
+ if (!payload) throw new Error('checkpoint 不存在: ' + name)
45
+ return structuredClone(payload)
46
+ },
47
+ initialDoc,
48
+ }
49
+ }
50
+
51
+ export function createFakeEditorAdapter({
52
+ document = {},
53
+ applyCommand = (doc) => doc,
54
+ renderScreenshot = async () => 'data:image/png;base64,eA==',
55
+ } = {}) {
56
+ let current = structuredClone(document)
57
+ const listeners = new Set()
58
+ return {
59
+ isMounted: () => true,
60
+ load(value) { current = structuredClone(value) },
61
+ dump() { return structuredClone(current) },
62
+ async apply(commands) {
63
+ for (const command of commands || []) current = await applyCommand(current, command)
64
+ return (commands || []).length
65
+ },
66
+ async applyUi(commands) { return (commands || []).length },
67
+ onChange(handler) {
68
+ listeners.add(handler)
69
+ return () => listeners.delete(handler)
70
+ },
71
+ async renderScreenshot(opts) { return renderScreenshot(opts) },
72
+ emitChange() { for (const handler of listeners) handler() },
73
+ get document() { return current },
74
+ }
75
+ }
@@ -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
+ }