@capyclaw/wall-suite 0.1.0 → 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 (63) hide show
  1. package/composition.lock.json +15 -15
  2. package/contract/wall-contract.json +1 -1
  3. package/dsh-suite.json +19 -9
  4. package/node_modules/@capyclaw/asset-service/dsh-suite.json +1 -1
  5. package/node_modules/@capyclaw/asset-service/package.json +1 -1
  6. package/node_modules/@capyclaw/asset-service/src/index.mjs +96 -9
  7. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  8. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +3 -1
  9. package/node_modules/@capyclaw/foundation/abi/index.mjs +15 -0
  10. package/node_modules/@capyclaw/foundation/abi/loader.mjs +8 -1
  11. package/node_modules/@capyclaw/foundation/abi/spec.mjs +5 -2
  12. package/node_modules/@capyclaw/foundation/abi/version.mjs +63 -5
  13. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  14. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
  15. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +11 -10
  16. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +8 -1
  17. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
  18. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
  19. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
  20. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +29 -2
  21. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
  22. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +31 -3
  23. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +12 -2
  24. package/node_modules/@capyclaw/foundation/package.json +1 -1
  25. package/node_modules/@capyclaw/plugin-kit/package.json +3 -1
  26. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
  27. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  28. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +3 -82
  29. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +13 -6
  30. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  31. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +31 -15
  32. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
  33. package/node_modules/@capyclaw/portal/package.json +1 -1
  34. package/node_modules/@capyclaw/service-broker/README.md +1 -1
  35. package/node_modules/@capyclaw/service-broker/lib/control.mjs +23 -7
  36. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +60 -6
  37. package/node_modules/@capyclaw/service-broker/lib/host.mjs +11 -6
  38. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +15 -2
  39. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +0 -50
  40. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +30 -10
  41. package/node_modules/@capyclaw/service-broker/package.json +1 -1
  42. package/node_modules/@capyclaw/service-host/dsh-suite.json +1 -1
  43. package/node_modules/@capyclaw/service-host/package.json +1 -1
  44. package/node_modules/@capyclaw/service-host/src/index.mjs +18 -19
  45. package/node_modules/@capyclaw/tool-host/dsh-suite.json +2 -2
  46. package/node_modules/@capyclaw/tool-host/lib/host.mjs +34 -4
  47. package/node_modules/@capyclaw/tool-host/package.json +1 -1
  48. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  49. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  50. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +28 -4
  51. package/node_modules/@capyclaw/tool-host/src/index.mjs +90 -19
  52. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
  53. package/node_modules/@capyclaw/wall-workbench/contract/wall-contract.json +1 -1
  54. package/node_modules/@capyclaw/wall-workbench/package.json +6 -6
  55. package/node_modules/@capyclaw/wall-workbench/plugin.mjs +13 -1
  56. package/node_modules/@capyclaw/wall-workbench/server/activate-log.mjs +66 -0
  57. package/node_modules/@capyclaw/wall-workbench/server/contract.mjs +1 -1
  58. package/node_modules/@capyclaw/wall-workbench/server/embedded-host.mjs +3 -1
  59. package/node_modules/@capyclaw/wall-workbench/server/shared/SHARED_MANIFEST.json +4 -4
  60. package/node_modules/@capyclaw/wall-workbench/server/workbench-framework.mjs +34 -0
  61. package/node_modules/@capyclaw/wall-workbench/ui/app.js +83 -0
  62. package/node_modules/@capyclaw/wall-workbench/ui/style.css +14 -11
  63. package/package.json +8 -8
@@ -0,0 +1,272 @@
1
+ /**
2
+ * 会话模式锁 —— 工具面标准框架的强制闸(基础设施能力,非各套件自接)。
3
+ *
4
+ * 设计目标(用户诉求):锁定一种工作模式(如 rsp)后,本会话只看得见、调得动
5
+ * 该领域的工具;其余已注册能力(browser_* 等)从工具声明里消失,且即便被强行
6
+ * 调用也在分发层硬拒。所有经 tool-host 注册的能力自动受此约束。
7
+ *
8
+ * 三道原生闸在此全部落地:
9
+ * · when(可见性):registerWithDsh / bridge host 给每个领域工具挂 whenFor(name),
10
+ * DSH 每步 resolve() 求值,false 同时从声明与分发中排除该工具。
11
+ * · guard(分发硬拒,兜底):install(tools) 挂一个全局 ToolGuard,异领域调用返回
12
+ * denial。单调不可翻回,兜住任何绕过 when 的路径。
13
+ * · awareness(模型感知):installPrompt(systemPrompt) 注册一个动态提示 section,
14
+ * 每次组装按会话读锁状态,锁定即告知模型「主区工作台是唯一交付界面、用本领域
15
+ * 工具、勿用文件工具绕过」。缺了这道闸,when/guard 只挡得住领域工具,模型仍会
16
+ * 用无 domain 的内置文件工具(write/pwsh/office_*)绕过主区(2026-11-23 根因)。
17
+ *
18
+ * 领域来源:TOOL_META.domain(defineTool/defineCapability/createRegistry 声明)。
19
+ * 存储真源:work-store.getSessionMode(sid)(终生固化,无 unlock)。
20
+ * 降级:无 workStore / 无 sid / 未锁定 → 恒可见、不拒(与既有“底座缺席不启用”一致)。
21
+ * 无 domain 的工具(conductor/capyclaw/框架核心 mode_*)恒可见,不受锁限制。
22
+ */
23
+
24
+ /**
25
+ * @param {{ getWorkStore?: () => object|null }} deps
26
+ */
27
+ export function createModeGate({ getWorkStore } = {}) {
28
+ const domainByTool = new Map() // 原生工具名 → domain
29
+ const domainBySuite = new Map() // 套件名 → domain(描述符发现面按 suite 兜底)
30
+ const lockCache = new Map() // sid → kind(锁终生固化,一旦落定永不变更,可缓存)
31
+ let guardInstalled = false
32
+ const guardDisposers = []
33
+ let coreToolsRegistered = false
34
+ const coreDisposers = []
35
+ let installRefs = 0 // 安装方引用计数(见 install 注释)
36
+ let promptInstalled = false // 感知闸:动态提示 section 是否已注册
37
+ const promptDisposers = []
38
+ let promptRefs = 0 // 感知闸安装方引用计数(与 install 同语义)
39
+
40
+ function store() {
41
+ try { return typeof getWorkStore === 'function' ? getWorkStore() : null } catch { return null }
42
+ }
43
+
44
+ /** 当前会话锁定的工作模式 kind;未锁定/底座缺席/无 sid → null。 */
45
+ function modeOf(sessionId) {
46
+ const sid = String(sessionId || '').trim()
47
+ if (!sid) return null
48
+ if (lockCache.has(sid)) return lockCache.get(sid)
49
+ const ws = store()
50
+ if (!ws || typeof ws.getSessionMode !== 'function') return null
51
+ let rec = null
52
+ try { rec = ws.getSessionMode(sid) } catch { return null }
53
+ const kind = rec && rec.kind ? String(rec.kind) : null
54
+ if (kind) lockCache.set(sid, kind) // 只缓存已落定的锁;null 不缓存(可能稍后被认领)
55
+ return kind
56
+ }
57
+
58
+ /** 领域工具在指定会话里是否可见。无 domain / 未锁定 / 同领域 → 可见。 */
59
+ function isVisible(domain, sessionId) {
60
+ if (!domain) return true
61
+ const lock = modeOf(sessionId)
62
+ return !lock || domain === lock
63
+ }
64
+
65
+ /** 声明一组工具属于某领域(registerWithDsh / bridge host 注册时调用)。 */
66
+ function declareTools(domain, names = [], suite = domain) {
67
+ const d = String(domain || '').trim()
68
+ if (!d) return
69
+ for (const name of names || []) {
70
+ if (name) domainByTool.set(String(name), d)
71
+ }
72
+ if (suite) domainBySuite.set(String(suite), d)
73
+ }
74
+
75
+ /** 某工具的领域;未声明 → ''(恒可见)。 */
76
+ function domainOf(name) {
77
+ return domainByTool.get(String(name)) || ''
78
+ }
79
+
80
+ /**
81
+ * DSH register 的 when 条件。未声明领域的工具返回 undefined(不挂 when,恒可见,
82
+ * 也避免给内置/核心工具增加每步求值开销)。
83
+ * @returns {((context: object) => boolean)|undefined}
84
+ */
85
+ function whenFor(name) {
86
+ const domain = domainOf(name)
87
+ if (!domain) return undefined
88
+ return (context) => isVisible(domain, context?.agent?.session?.id)
89
+ }
90
+
91
+ /**
92
+ * 全局 ToolGuard(分发硬拒兜底)。非领域工具立即放行(不读 store,内置工具零开销);
93
+ * 领域工具在异领域锁定的会话里返回 denial。
94
+ * @returns {{reason: string, info: object}|undefined}
95
+ */
96
+ function guard(execution) {
97
+ const name = execution?.name
98
+ const domain = domainByTool.get(String(name))
99
+ if (!domain) return undefined
100
+ const lock = modeOf(execution?.agent?.session?.id)
101
+ if (!lock || domain === lock) return undefined
102
+ return {
103
+ reason: `本会话已锁定为「${lock}」工作模式,「${name}」属于「${domain}」领域,已被框架屏蔽。`
104
+ + `请只用「${lock}」领域的工具完成任务;确需其他领域,请新开一个会话。`,
105
+ info: { name: 'SessionModeLocked', code: 'SESSION_MODE_LOCKED', reason: `locked to ${lock}, tool domain ${domain}` },
106
+ }
107
+ }
108
+
109
+ /** 框架核心工具 mode_lock / mode_status(无领域,恒可见)——显式锁定入口与状态查询。
110
+ * 存储经 modeGate 的 getWorkStore 解析(不依赖插件 ctx),故可在任何 tools 就绪时机注册。 */
111
+ function coreTools() {
112
+ const textRender = (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }]
113
+ const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true }
114
+ const modeLock = {
115
+ name: 'mode_lock',
116
+ description: '把当前会话锁定到一种工作模式(领域),如 rsp/browser/ppt/canvas。锁定后本会话只看得见、调得动该领域的工具,'
117
+ + '其余领域能力被框架从工具面屏蔽并在分发层硬拒。锁终生固化、不可解锁;确需其他领域请新开一个会话。',
118
+ parameters: {
119
+ type: 'object',
120
+ properties: { kind: { type: 'string', description: '要锁定的工作模式/领域,如 rsp、browser、ppt、canvas' } },
121
+ required: ['kind'],
122
+ additionalProperties: false,
123
+ },
124
+ output: { schema: OUTPUT_SCHEMA, render: textRender },
125
+ execute: async (args, exec) => {
126
+ const kind = String(args?.kind || '').trim()
127
+ if (!kind) return { ok: false, error: '需要 kind(要锁定的工作模式/领域)' }
128
+ const sid = exec?.agent?.session?.id
129
+ if (!sid) return { ok: false, error: '无法识别当前会话,不能锁定' }
130
+ const ws = store()
131
+ if (!ws || typeof ws.claimSessionMode !== 'function') return { ok: false, error: 'work-store 底座缺席,无法锁定' }
132
+ const res = ws.claimSessionMode(sid, kind, 'mode-lock', { explicit: true })
133
+ if (res && res.ok === false) {
134
+ return { ok: false, lockedTo: res.lockedTo, error: `本会话已固化为「${res.lockedTo}」模式,不能改为「${kind}」。确需其他领域请新开一个会话。` }
135
+ }
136
+ return {
137
+ ok: true, kind: res.kind, fresh: !!res.fresh, explicit: true,
138
+ message: res.fresh ? `已锁定为「${res.kind}」工作模式,本会话此后只用该领域工具。` : `本会话已处于「${res.kind}」工作模式。`,
139
+ }
140
+ },
141
+ }
142
+ const modeStatus = {
143
+ name: 'mode_status',
144
+ description: '查询当前会话的工作模式锁状态:是否锁定、锁定到哪个领域、由谁何时认领。未锁定时所有领域工具可见。',
145
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
146
+ output: { schema: OUTPUT_SCHEMA, render: textRender },
147
+ execute: async (_args, exec) => {
148
+ const sid = exec?.agent?.session?.id
149
+ const ws = store()
150
+ if (!ws || typeof ws.getSessionMode !== 'function') return { locked: false, reason: 'work-store 底座缺席' }
151
+ if (!sid) return { locked: false, reason: '无法识别当前会话' }
152
+ const rec = ws.getSessionMode(sid)
153
+ if (!rec) return { locked: false, kind: null, message: '本会话未锁定工作模式,所有领域工具可见。' }
154
+ return {
155
+ locked: true, kind: rec.kind, claimedBy: rec.claimedBy || '', claimedAt: rec.claimedAt || '', explicit: !!rec.explicit,
156
+ message: `本会话已锁定为「${rec.kind}」工作模式,其余领域工具已被屏蔽。`,
157
+ }
158
+ },
159
+ }
160
+ return [modeLock, modeStatus]
161
+ }
162
+
163
+ /** 把 guard + 核心锁定工具挂到 DSH tools 服务(幂等)。每个套件在 tools 就绪时都会调用,
164
+ * 故核心工具注册不依赖 tool-host driver apply 那一刻 tools 是否已就绪(加载顺序鲁棒)。返回 disposer。
165
+ * 引用计数:多个安装方(driver apply / 各套件 registerWithDsh)共享同一份核心注册,
166
+ * 任一安装方卸载只减引用;最后一个释放才真正摘 guard + 核心工具,避免「丢 disposer」泄漏
167
+ * 与「先卸载者拆掉幸存者底座」两种事故。 */
168
+ function install(tools) {
169
+ if (!tools) return () => {}
170
+ if (!guardInstalled && typeof tools.guard === 'function') {
171
+ try {
172
+ const dispose = tools.guard(guard)
173
+ if (typeof dispose === 'function') guardDisposers.push(dispose)
174
+ guardInstalled = true
175
+ } catch { /* 底座不支持 guard 时降级:仅 when 生效 */ }
176
+ }
177
+ if (!coreToolsRegistered && typeof tools.register === 'function') {
178
+ for (const tool of coreTools()) {
179
+ try {
180
+ const d = tools.register(tool)
181
+ if (typeof d === 'function') coreDisposers.push(d)
182
+ } catch (err) {
183
+ console.warn(`[tool-host] 注册核心工具 ${tool.name} 失败:`, err?.message || err)
184
+ }
185
+ }
186
+ coreToolsRegistered = true
187
+ }
188
+ installRefs++
189
+ let released = false
190
+ return () => {
191
+ if (released) return
192
+ released = true
193
+ installRefs--
194
+ if (installRefs > 0) return
195
+ for (const dispose of guardDisposers.splice(0)) {
196
+ try { dispose() } catch { /* 忽略重复释放 */ }
197
+ }
198
+ for (const dispose of coreDisposers.splice(0)) {
199
+ try { dispose() } catch { /* 忽略重复释放 */ }
200
+ }
201
+ guardInstalled = false
202
+ coreToolsRegistered = false
203
+ }
204
+ }
205
+
206
+ /**
207
+ * 感知闸文本:锁定会话里注入系统提示,让模型知道主区工作台的存在与唯一交付地位。
208
+ * 只约束「工作台内容任务」的交付路径,不禁止为修插件/查资料等元任务读文件。
209
+ */
210
+ function awarenessText(kind) {
211
+ return `【会话工作模式锁】本会话已锁定为「${kind}」工作模式:GUI 主区界面就是「${kind}」工作台,它是本会话工作台内容任务的指定交付界面。\n`
212
+ + `- 用户要求创作/编辑文档、稿件等工作台内容时,必须用 ${kind}_* 专用工具直接读写主区工作台(先加载 ${kind} 相关 skill),让用户在主区实时看到结果。\n`
213
+ + `- 不得改用 write/pwsh/office_* 等通用文件工具生成独立文件来绕过主区交付;其他领域的工具与技能不适用于本会话。\n`
214
+ + `- 锁终生固化、不可解锁;确需其他领域,请提示用户新开会话。锁状态可用 mode_status 查询。`
215
+ }
216
+
217
+ /**
218
+ * 感知闸:把锁状态作为动态系统提示 section 挂到 DSH systemPrompt 服务(幂等)。
219
+ * text 回调每次 assemble 求值(DSH 每步组装提示时调用),按 context.agent.session.id
220
+ * 读锁:锁定 → 注入感知文本;未锁定/无会话 → 返回 ''(空 section 自动消失,零开销)。
221
+ * 锁可在会话中途被认领(墙上点选),回调动态读取故无需监听 agent 生命周期。
222
+ * 引用计数与 install(tools) 同语义:driver apply 与各套件 registerWithDsh 共享一份注册。
223
+ * 底座缺席(无 systemPrompt / 不支持 section)→ 降级为仅 when/guard 生效。
224
+ * @returns {() => void} 引用计数 disposer
225
+ */
226
+ function installPrompt(systemPrompt) {
227
+ if (!systemPrompt || typeof systemPrompt.section !== 'function') return () => {}
228
+ if (!promptInstalled) {
229
+ try {
230
+ const dispose = systemPrompt.section({
231
+ name: 'capyclaw:session-mode-lock',
232
+ order: 900,
233
+ interpolate: false,
234
+ text: (context) => {
235
+ const kind = modeOf(context?.agent?.session?.id)
236
+ return kind ? awarenessText(kind) : ''
237
+ },
238
+ })
239
+ if (typeof dispose === 'function') promptDisposers.push(dispose)
240
+ promptInstalled = true
241
+ } catch { /* 底座不支持 section 时降级:仅 when/guard 生效 */ }
242
+ }
243
+ promptRefs++
244
+ let released = false
245
+ return () => {
246
+ if (released) return
247
+ released = true
248
+ promptRefs--
249
+ if (promptRefs > 0) return
250
+ for (const dispose of promptDisposers.splice(0)) {
251
+ try { dispose() } catch { /* 忽略重复释放 */ }
252
+ }
253
+ promptInstalled = false
254
+ }
255
+ }
256
+
257
+ /**
258
+ * 能力发现面过滤:锁定会话里剔除异领域描述符(conductor_discover 自动受约束)。
259
+ * 无 domain 的描述符(编排/核心基建)保留。未锁定 → 原样返回。
260
+ */
261
+ function filterEntries(entries, sessionId) {
262
+ const lock = modeOf(sessionId)
263
+ if (!lock) return entries
264
+ return (entries || []).filter((entry) => {
265
+ const d = entry?.descriptor || {}
266
+ const domain = domainByTool.get(String(d.tool || d.name)) || domainBySuite.get(String(entry?.suite)) || ''
267
+ return !domain || domain === lock
268
+ })
269
+ }
270
+
271
+ return { declareTools, domainOf, modeOf, isVisible, whenFor, guard, install, installPrompt, filterEntries }
272
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contractVersion": "1.0.0",
3
- "packageVersion": "0.1.0",
3
+ "packageVersion": "0.1.2",
4
4
  "toolCount": 0,
5
5
  "tools": [],
6
6
  "features": [],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/wall-workbench",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "展示墙工作台运行时:主区空态选择器(列出已注册工作台类型,点选显式认领会话模式)。零工具、零引擎、零文档模型。",
5
5
  "type": "module",
6
6
  "main": "./plugin.mjs",
@@ -40,11 +40,11 @@
40
40
  "license": "MIT",
41
41
  "scripts": {},
42
42
  "dependencies": {
43
- "@capyclaw/asset-service": "^0.1.4",
44
- "@capyclaw/foundation": "^0.1.9",
45
- "@capyclaw/plugin-kit": "^0.2.6",
46
- "@capyclaw/service-host": "^0.1.5",
47
- "@capyclaw/tool-host": "^0.2.0"
43
+ "@capyclaw/asset-service": "^0.1.6",
44
+ "@capyclaw/foundation": "^0.1.11",
45
+ "@capyclaw/plugin-kit": "^0.2.8",
46
+ "@capyclaw/service-host": "^0.1.7",
47
+ "@capyclaw/tool-host": "^0.3.2"
48
48
  },
49
49
  "author": {
50
50
  "name": "CapyClaw",
@@ -1 +1,13 @@
1
- export { name, inject, apply } from './server/embedded-host.mjs'
1
+ /**
2
+ * foundation ABI raw@1 wrapper:准入闸扩面后宿主必须走 ABI(见 bridge-build 注释)。
3
+ * raw@1 逃生舱承载多面共生命周期(webServer 路由 + toolHost 工具 + 描述符/表面/portal,
4
+ * 共享 workId/relay);额外 inject 仅 raw@1 可声明。core/os.skills 是套件运行时前提。
5
+ */
6
+ import { createPlugin, rawPlugin } from '@capyclaw/foundation/abi'
7
+ import { name as hostName, apply as applyHost } from './server/embedded-host.mjs'
8
+
9
+ export const { name, inject, apply } = createPlugin({
10
+ name: hostName,
11
+ inject: ['webServer'],
12
+ implements: [rawPlugin(({ ctx, config }) => applyHost(ctx, config))],
13
+ }, import.meta.url)
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 激活失败诊断日志的有界写入(防 activate-error.log 无界增长)。
3
+ *
4
+ * 旧实现直接 fs.appendFileSync 追加完整栈,长期反复激活失败会让日志无限膨胀。
5
+ * 这里改为「读尾部 + 追加 + 超限裁剪 + 整体重写」:
6
+ * - 行数硬上限 ACTIVATE_LOG_MAX_LINES(200):每次追加只保留最近 200 行;
7
+ * - 字节硬上限 ACTIVATE_LOG_MAX_BYTES(256KB):仍超则按字节取尾部并丢掉
8
+ * 首条不完整行,保证不截断出半行乱码。
9
+ * 只读取文件尾部 maxBytes 字节,内存占用有界;失败信息(最近若干条栈)始终可诊断。
10
+ *
11
+ * 本模块不依赖构建期才生成的 ./shared/*,可被 src 直接 import 做回归测试。
12
+ */
13
+ import fs from 'node:fs'
14
+
15
+ export const ACTIVATE_LOG_MAX_BYTES = 256 * 1024
16
+ export const ACTIVATE_LOG_MAX_LINES = 200
17
+
18
+ /** 只读文件尾部 maxBytes 字节;若从中间读起则丢掉首条不完整行。读失败返回空串。 */
19
+ function readTail(filePath, maxBytes) {
20
+ let fd
21
+ try {
22
+ fd = fs.openSync(filePath, 'r')
23
+ const size = fs.fstatSync(fd).size
24
+ const start = Math.max(0, size - maxBytes)
25
+ const len = size - start
26
+ const buf = Buffer.alloc(len)
27
+ fs.readSync(fd, buf, 0, len, start)
28
+ let text = buf.toString('utf8')
29
+ if (start > 0) {
30
+ const i = text.indexOf('\n')
31
+ text = i >= 0 ? text.slice(i + 1) : ''
32
+ }
33
+ return text
34
+ } catch {
35
+ return ''
36
+ } finally {
37
+ if (fd !== undefined) { try { fs.closeSync(fd) } catch { /* 忽略 */ } }
38
+ }
39
+ }
40
+
41
+ /**
42
+ * 向 filePath 有界追加一条 entry(自动补尾换行)。超限按行/按字节裁剪后整体重写。
43
+ * @param {string} filePath 目标日志文件绝对路径
44
+ * @param {string} entry 要追加的一条诊断文本(通常含时间戳与错误栈)
45
+ * @param {{maxBytes?:number, maxLines?:number}} [opts] 覆盖默认上限
46
+ */
47
+ export function appendBoundedLog(filePath, entry, opts = {}) {
48
+ const maxBytes = opts.maxBytes ?? ACTIVATE_LOG_MAX_BYTES
49
+ const maxLines = opts.maxLines ?? ACTIVATE_LOG_MAX_LINES
50
+ const line = String(entry)
51
+ const text = line.endsWith('\n') ? line : `${line}\n`
52
+ let combined = readTail(filePath, maxBytes) + text
53
+ /* 行数硬上限:每次追加都只保留最近 maxLines 行(最新一条必在末尾)。 */
54
+ const lines = combined.split('\n').filter((l) => l.length > 0)
55
+ if (lines.length > maxLines) combined = `${lines.slice(-maxLines).join('\n')}\n`
56
+ /* 字节硬上限:仍超则按字节取尾部并丢首条不完整行,避免截出半行乱码。 */
57
+ if (Buffer.byteLength(combined, 'utf8') > maxBytes) {
58
+ let tail = Buffer.from(combined, 'utf8').subarray(-maxBytes).toString('utf8')
59
+ const i = tail.indexOf('\n')
60
+ tail = i >= 0 ? tail.slice(i + 1) : tail
61
+ /* 极端:单条 entry 本身就超过 maxBytes,按字节裁剪可能整条丢空——
62
+ 兜底保留 entry 尾部,确保最新失败信息不丢。 */
63
+ combined = tail.length > 0 ? tail : text.slice(-maxBytes)
64
+ }
65
+ fs.writeFileSync(filePath, combined)
66
+ }
@@ -9,4 +9,4 @@
9
9
  export const CONTRACT_VERSION = '1.0.0'
10
10
 
11
11
  /** 工作台包版本。 */
12
- export const PACKAGE_VERSION = '0.1.0'
12
+ export const PACKAGE_VERSION = '0.1.2'
@@ -15,6 +15,7 @@ import path from 'node:path'
15
15
  import fs from 'node:fs'
16
16
  import { fileURLToPath, pathToFileURL } from 'node:url'
17
17
  import { assertServiceApi } from './shared/kit/service/api.mjs'
18
+ import { appendBoundedLog } from './activate-log.mjs'
18
19
 
19
20
  export const name = 'wall-workbench-host'
20
21
  /* 依赖倒置:业务等的是「宿主给的 HTTP 路由」,不是端口。 */
@@ -68,7 +69,8 @@ export async function apply(ctx, config) {
68
69
  const fallbackDir = path.join(os.homedir(), '.dsh-wall-bridge')
69
70
  const hostDir = (config && config.hostDir) || process.env.WALL_BRIDGE_HOME || fallbackDir
70
71
  fs.mkdirSync(hostDir, { recursive: true })
71
- fs.appendFileSync(
72
+ /* 有界写入:防反复激活失败把 activate-error.log 撑到无界(保留最近若干条栈)。 */
73
+ appendBoundedLog(
72
74
  path.join(hostDir, 'activate-error.log'),
73
75
  `[${new Date().toISOString()}] ${(error && error.stack) || error}\n`,
74
76
  )
@@ -4,28 +4,28 @@
4
4
  "packages": {
5
5
  "service-host": {
6
6
  "package": "@capyclaw/service-host",
7
- "version": "0.1.5",
7
+ "version": "0.1.7",
8
8
  "apiVersion": "1.0.0",
9
9
  "spec": "@capyclaw/service-host/src",
10
10
  "sha256": "af0a57d779bfe6a66dc935320178d591ef799a7e037f7a5823cdfa1fe5878eeb"
11
11
  },
12
12
  "tool-host": {
13
13
  "package": "@capyclaw/tool-host",
14
- "version": "0.2.0",
14
+ "version": "0.3.2",
15
15
  "apiVersion": "1.1.0",
16
16
  "spec": "@capyclaw/tool-host/src",
17
17
  "sha256": "23256dbcd5cbee0b96b33c97e4eb4e74d0e169cbdde52f91d4526f2fc0f60d3e"
18
18
  },
19
19
  "asset-service": {
20
20
  "package": "@capyclaw/asset-service",
21
- "version": "0.1.4",
21
+ "version": "0.1.6",
22
22
  "apiVersion": "1.0.0",
23
23
  "spec": "@capyclaw/asset-service/src",
24
24
  "sha256": "311a83e95d56dbb69b739d61aced0889b64e85eddd95b883e322e0fa5be8bd6f"
25
25
  },
26
26
  "editor-host": {
27
27
  "package": "@capyclaw/editor-host",
28
- "version": "0.1.5",
28
+ "version": "0.1.7",
29
29
  "apiVersion": "1.0.0",
30
30
  "spec": "@capyclaw/editor-host/src",
31
31
  "sha256": "c8b80dbd4f1b2bee9ef9001423a013031a21ea9a3b8897b5536fe6e5687f01b3"
@@ -111,7 +111,13 @@ export function createWorkbench(spec) {
111
111
  * 已创建的资源——否则引擎/仓库泄漏在仍存活的进程里(reused 分支的 stop 是
112
112
  * no-op,不会有人替它清理)。外部传入的 assetStore 不归本框架关。 */
113
113
  let app
114
+ /* 资产仓库周期 GC:默认只清孤儿临时文件(安全——内容寻址资产被稿件引用,
115
+ * 按龄/LRU 淘汰会毁掉旧稿渲染,必须经 tuning 显式 opt-in)。定时器 unref,
116
+ * 不拖住进程退出;所有关闭路径都要清掉它。 */
117
+ let assetGcTimer = null
118
+ const stopAssetGc = () => { if (assetGcTimer) { clearInterval(assetGcTimer); assetGcTimer = null } }
114
119
  const closeCreatedResources = async (why) => {
120
+ stopAssetGc()
115
121
  try { if (spec.beforeStop) await spec.beforeStop(ctx) } catch (error) { console.error(`[${spec.id}] ${why}:beforeStop 失败`, error?.message || error) }
116
122
  try { if (!givenAssetStore) await assetStore?.close?.() } catch (error) { console.error(`[${spec.id}] ${why}:assetStore 关闭失败`, error?.message || error) }
117
123
  try { await store?.close?.() } catch (error) { console.error(`[${spec.id}] ${why}:store 关闭失败`, error?.message || error) }
@@ -213,6 +219,32 @@ export function createWorkbench(spec) {
213
219
  }
214
220
  }
215
221
 
222
+ /* 只有真正提供服务的形态才起周期 GC(reused 形态已回收资源,不起定时器)。
223
+ * tuning.assetGcIntervalMs<=0 可整体关闭;maxAgeMs/maxBytes 缺省 0=不按龄/量淘汰。 */
224
+ if (assetStore && typeof assetStore.gc === 'function') {
225
+ const gcIntervalMs = Number(tuning.assetGcIntervalMs ?? 3600000)
226
+ if (gcIntervalMs > 0) {
227
+ const gcOptions = {
228
+ maxAgeMs: Number(tuning.assetGcMaxAgeMs) || 0,
229
+ maxBytes: Number(tuning.assetGcMaxBytes) || 0,
230
+ }
231
+ const runGc = async () => {
232
+ try {
233
+ const result = await assetStore.gc(gcOptions)
234
+ if (result?.removed || result?.orphanTmpRemoved) {
235
+ console.log(`[${spec.id}] 资产 GC:清理 ${result.removed || 0} 项、孤儿临时文件 ${result.orphanTmpRemoved || 0} 个,释放 ${result.freedBytes || 0} 字节`)
236
+ }
237
+ } catch (error) {
238
+ console.error(`[${spec.id}] 资产 GC 失败(下轮再试):`, error?.message || error)
239
+ }
240
+ }
241
+ assetGcTimer = setInterval(runGc, gcIntervalMs)
242
+ assetGcTimer.unref?.()
243
+ /* 启动即跑一轮:清掉上次进程崩溃留下的孤儿 tmp,不必等第一个周期。 */
244
+ runGc()
245
+ }
246
+ }
247
+
216
248
  try {
217
249
  /* 业务钩子:设置 URL 环境变量、崩溃恢复等(必须在工具装载之前)。 */
218
250
  if (spec.onListening) await spec.onListening(ctx, info, url)
@@ -255,12 +287,14 @@ export function createWorkbench(spec) {
255
287
  tools: ctx.toolsRegistry || null,
256
288
  ...(spec.resultExtras ? spec.resultExtras(ctx) : {}),
257
289
  stop: async () => {
290
+ stopAssetGc()
258
291
  if (!ctx.embedded) removeDiscovery(hostDir)
259
292
  if (spec.beforeStop) await spec.beforeStop(ctx)
260
293
  await info.stop()
261
294
  },
262
295
  }
263
296
  } catch (error) {
297
+ stopAssetGc()
264
298
  try { if (!ctx.embedded) removeDiscovery(hostDir) } catch { /* 忽略 */ }
265
299
  try { if (spec.beforeStop) await spec.beforeStop(ctx) } catch { /* 忽略 */ }
266
300
  try { await info.stop() } catch { /* 忽略 */ }
@@ -3,12 +3,68 @@
3
3
  * - 从主区舞台 /__portal_hud__/state 读已注册的工作台类型(类型无关,不硬编码清单);
4
4
  * - 点选 → POST claim 显式认领会话模式(explicit),舞台随后收掉墙、摆出真实工作台;
5
5
  * - 舞台换会话时 postMessage 通知本页(retarget):立即回 ack,再按新会话重取清单。
6
+ * - 表面可见性生命周期(标准 §4):收宿主 visibility 信号,存状态并恒回 ack
7
+ * (静态选择页无渲染循环可挂起,宿主靠 ack 判半挂起)。
6
8
  *
7
9
  * standalone(无 portal-hud)时 state 取不到 → 降级为提示,不报错。
8
10
  */
9
11
  (function () {
10
12
  'use strict'
11
13
 
14
+ /* iframe 不继承宿主 CSS 变量:把宿主当前主题的 --dsw-alias-* 计算值镜像到本页 :root,
15
+ 使选择墙与 DSH 自带主题同一套肤色(暗色随暗色)。独立打开时保留 CSS 回退色。 */
16
+ var THEME_MAP = [
17
+ ['--paper', '--dsw-alias-bg-base'],
18
+ ['--card', '--dsw-alias-bg-layer-1'],
19
+ ['--ink', '--dsw-alias-label-primary'],
20
+ ['--muted', '--dsw-alias-label-secondary'],
21
+ ['--line', '--dsw-alias-border-l2'],
22
+ ['--accent', '--dsw-alias-brand-primary'],
23
+ ['--warn', '--dsw-alias-state-warn-label'],
24
+ ['--ok', '--dsw-alias-state-success-primary'],
25
+ ]
26
+ var themeObserver = null
27
+
28
+ function syncTheme() {
29
+ try {
30
+ if (!window.parent || window.parent === window) return
31
+ var doc = window.parent.document
32
+ if (!doc || !doc.body) return
33
+ var bodyStyle = window.parent.getComputedStyle(doc.body)
34
+ var htmlStyle = window.parent.getComputedStyle(doc.documentElement)
35
+ var root = document.documentElement
36
+ var found = false
37
+ for (var i = 0; i < THEME_MAP.length; i++) {
38
+ var value = bodyStyle.getPropertyValue(THEME_MAP[i][1]).trim()
39
+ || htmlStyle.getPropertyValue(THEME_MAP[i][1]).trim()
40
+ if (value) { root.style.setProperty(THEME_MAP[i][0], value); found = true }
41
+ }
42
+ if (found) {
43
+ var dark = doc.body.hasAttribute('data-ds-dark-theme') || doc.documentElement.hasAttribute('data-ds-dark-theme')
44
+ root.style.colorScheme = dark ? 'dark' : 'light'
45
+ }
46
+ } catch (err) { /* 独立或隔离预览保留 CSS 回退色。 */ }
47
+ }
48
+
49
+ function watchTheme() {
50
+ try {
51
+ if (!window.parent || window.parent === window || typeof MutationObserver === 'undefined') return
52
+ var doc = window.parent.document
53
+ if (!doc || !doc.body) return
54
+ if (themeObserver) themeObserver.disconnect()
55
+ themeObserver = new MutationObserver(syncTheme)
56
+ themeObserver.observe(doc.body, { attributes: true, attributeFilter: ['style', 'data-ds-dark-theme', 'class'] })
57
+ themeObserver.observe(doc.documentElement, { attributes: true, attributeFilter: ['style', 'data-ds-dark-theme', 'class'] })
58
+ } catch (err) { /* 独立或隔离预览保留 CSS 回退色。 */ }
59
+ }
60
+
61
+ syncTheme()
62
+ watchTheme()
63
+ window.addEventListener('load', function () { syncTheme(); watchTheme() })
64
+ window.addEventListener('pagehide', function () {
65
+ if (themeObserver) { themeObserver.disconnect(); themeObserver = null }
66
+ })
67
+
12
68
  /* 与 service-host 的会话段规则一致:/s/<sid>(sid 字母数字开头,可含 . _ ~ -)。 */
13
69
  var SESSION_RE = /\/s\/([A-Za-z0-9][A-Za-z0-9._~-]{0,127})(?=\/|$)/
14
70
 
@@ -123,6 +179,33 @@
123
179
  })
124
180
  }
125
181
 
182
+ /* ---- 表面可见性生命周期(标准 §4 信号通道,阶段3) ----
183
+ * 本 UI 无构建、原样拷贝部署(build-plugin.mjs copyDirs),不能 import 共享包,
184
+ * 故内联一个最小 visibility 订阅器(照 browser src/ui/app.js 先例)。展示墙是
185
+ * 静态选择页:没有渲染循环可挂起/恢复,只把表面状态存下来(平凡实现);但必须
186
+ * 恒回 ack——宿主靠 ack 判半挂起(标准 §4 兜底)。协议常量真源:
187
+ * C/packages/capyclaw-foundation/abi/visibility.mjs —— 改那边必须同步这里。 */
188
+ var VISIBILITY_MESSAGE = 'capyclaw:workbench:visibility'
189
+ var VISIBILITY_ACK_MESSAGE = 'capyclaw:workbench:visibility-ack'
190
+ var VISIBILITY_STATES = ['foreground', 'background', 'hidden', 'detached']
191
+ var visibilityState = 'foreground'
192
+
193
+ function onVisibilityMessage(event) {
194
+ if (event.origin !== location.origin) return
195
+ var data = event.data
196
+ if (!data || data.type !== VISIBILITY_MESSAGE) return
197
+ if (VISIBILITY_STATES.indexOf(data.state) === -1) return
198
+ /* 静态页无渲染面可挂起/恢复:状态存下来即可(suspendRender/resumeRender 平凡)。 */
199
+ visibilityState = data.state
200
+ /* 无条件回 ack(即使状态未变,宿主可重发):ack 形状与 abi 一致。 */
201
+ try {
202
+ if (event.source) {
203
+ event.source.postMessage({ type: VISIBILITY_ACK_MESSAGE, state: data.state, sid: data.sid }, event.origin)
204
+ }
205
+ } catch (err) { /* 回执失败不致命 */ }
206
+ }
207
+ window.addEventListener('message', onVisibilityMessage)
208
+
126
209
  /* 舞台 retarget:同工作台换会话不重载 iframe,只 postMessage。
127
210
  * 必须立刻回 ack(父侧 600ms 无 ack 会硬重载),再按新会话重取清单。 */
128
211
  window.addEventListener('message', function (e) {
@@ -1,13 +1,16 @@
1
- /* 展示墙选择器:中性纸面 + 单一强调色,铺满主区容器(无窗壳)。 */
1
+ /* 展示墙选择器:直接复用宿主 DSH 主题肤色(--dsw-alias-*),铺满主区容器(无窗壳)。
2
+ iframe 不继承父页 CSS 变量:app.js 会把宿主计算值镜像到本页 :root;
3
+ 这里的 var() 回退色仅在独立打开(无宿主)时生效。 */
2
4
  :root {
3
- --paper: #f7f7f5;
4
- --ink: #1c1e21;
5
- --muted: #6b7075;
6
- --line: #e3e4e0;
7
- --accent: #2f6f4f;
8
- --accent-soft: #eaf2ec;
9
- --warn: #8a5a00;
10
- --ok: #2f6f4f;
5
+ --paper: var(--dsw-alias-bg-base, #f7f7f5);
6
+ --card: var(--dsw-alias-bg-layer-1, #fff);
7
+ --ink: var(--dsw-alias-label-primary, #1c1e21);
8
+ --muted: var(--dsw-alias-label-secondary, #6b7075);
9
+ --line: var(--dsw-alias-border-l2, #e3e4e0);
10
+ --accent: var(--dsw-alias-brand-primary, #2f6f4f);
11
+ --accent-soft: color-mix(in srgb, var(--accent) 12%, transparent);
12
+ --warn: var(--dsw-alias-state-warn-label, #8a5a00);
13
+ --ok: var(--dsw-alias-state-success-primary, #2f6f4f);
11
14
  }
12
15
 
13
16
  * { box-sizing: border-box; }
@@ -48,7 +51,7 @@ html, body {
48
51
  gap: 6px;
49
52
  align-items: flex-start;
50
53
  padding: 20px 22px;
51
- background: #fff;
54
+ background: var(--card);
52
55
  border: 1px solid var(--line);
53
56
  border-radius: 12px;
54
57
  cursor: pointer;
@@ -59,7 +62,7 @@ html, body {
59
62
  }
60
63
  .card:hover:not(:disabled) {
61
64
  border-color: var(--accent);
62
- box-shadow: 0 4px 16px rgba(28, 30, 33, .08);
65
+ box-shadow: 0 4px 16px color-mix(in srgb, var(--ink) 8%, transparent);
63
66
  transform: translateY(-2px);
64
67
  }
65
68
  .card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }