@capyclaw/browser-workbench 0.1.17 → 0.1.18

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contractVersion": "1.3.0",
3
- "packageVersion": "0.1.17",
3
+ "packageVersion": "0.1.18",
4
4
  "toolCount": 18,
5
5
  "tools": [
6
6
  {
@@ -107,16 +107,82 @@ export function createFileAssetStore({ dir } = {}) {
107
107
  if (!validId(id)) return false
108
108
  try { return fs.existsSync(path.join(dir, path.basename(String(id)))) } catch { return false }
109
109
  },
110
+ /** 删除单个对象(data + meta)。内容寻址仓库此前只增不删,磁盘无界增长。 */
111
+ async delete(id) {
112
+ if (!validId(id)) return false
113
+ const file = path.join(dir, path.basename(String(id)))
114
+ let existed = false
115
+ try {
116
+ existed = fs.existsSync(file)
117
+ fs.rmSync(file, { force: true })
118
+ fs.rmSync(file + '.meta.json', { force: true })
119
+ } catch { /* 尽力删除 */ }
120
+ return existed
121
+ },
122
+ /**
123
+ * 垃圾回收:清崩溃残留的孤儿 .tmp、按 mtime 龄淘汰、按总量 LRU 淘汰。
124
+ * keepIds 里的对象(仍被引用)永不删。返回 {removed, freedBytes, orphanTmpRemoved}。
125
+ */
126
+ async gc({ maxAgeMs = 0, maxBytes = 0, keepIds = [] } = {}) {
127
+ const keep = new Set(keepIds)
128
+ const now = Date.now()
129
+ let removed = 0
130
+ let freedBytes = 0
131
+ let orphanTmpRemoved = 0
132
+ let names
133
+ try { names = fs.readdirSync(dir) } catch { return { removed, freedBytes, orphanTmpRemoved } }
134
+ /* 孤儿 tmp:put 中途崩溃留下的半成品,超过 1h 宽限才清(避免误删在途写入)。 */
135
+ for (const name of names) {
136
+ if (!name.includes('.tmp-')) continue
137
+ const full = path.join(dir, name)
138
+ try {
139
+ const st = fs.statSync(full)
140
+ if (now - st.mtimeMs > 3600000) { fs.rmSync(full, { force: true }); orphanTmpRemoved += 1 }
141
+ } catch { /* 忽略 */ }
142
+ }
143
+ const objects = []
144
+ for (const name of fs.readdirSync(dir)) {
145
+ if (!validId(name)) continue
146
+ const full = path.join(dir, name)
147
+ try { const st = fs.statSync(full); objects.push({ id: name, full, size: st.size, mtime: st.mtimeMs }) } catch { /* 忽略 */ }
148
+ }
149
+ const removeObject = (o) => {
150
+ try {
151
+ fs.rmSync(o.full, { force: true })
152
+ fs.rmSync(o.full + '.meta.json', { force: true })
153
+ removed += 1
154
+ freedBytes += o.size
155
+ } catch { /* 忽略 */ }
156
+ }
157
+ if (maxAgeMs > 0) {
158
+ for (const o of objects) {
159
+ if (!keep.has(o.id) && now - o.mtime > maxAgeMs) removeObject(o)
160
+ }
161
+ }
162
+ if (maxBytes > 0) {
163
+ const alive = objects.filter((o) => fs.existsSync(o.full)).sort((a, b) => a.mtime - b.mtime)
164
+ let total = alive.reduce((sum, o) => sum + o.size, 0)
165
+ for (const o of alive) {
166
+ if (total <= maxBytes) break
167
+ if (keep.has(o.id)) continue
168
+ removeObject(o)
169
+ total -= o.size
170
+ }
171
+ }
172
+ return { removed, freedBytes, orphanTmpRemoved }
173
+ },
110
174
  }
111
175
  }
112
176
 
113
- /** 防止 text/html / svg 在 loopback 同源执行脚本;图片仍按原 MIME 内联。 */
177
+ /** 防止 text/html / svg 在 loopback 同源执行脚本;图片仍按原 MIME 内联。
178
+ * 安全类型保留原始参数(charset 等),不再一刀切剥掉——否则文本资产 charset 丢失。 */
114
179
  function safeContentType(type) {
115
- const base = String(type || '').split(';')[0].trim().toLowerCase() || 'application/octet-stream'
180
+ const raw = String(type || '').replace(/[\r\n]/g, '').trim()
181
+ const base = raw.split(';')[0].trim().toLowerCase() || 'application/octet-stream'
116
182
  if (base === 'text/html' || base === 'application/xhtml+xml' || base === 'image/svg+xml') {
117
183
  return 'text/plain; charset=utf-8'
118
184
  }
119
- return base
185
+ return raw || 'application/octet-stream'
120
186
  }
121
187
 
122
188
  /**
@@ -170,7 +236,8 @@ export function createAssetRoutes({ assetStore, basePath = '', maxUploadBytes =
170
236
  }
171
237
  if (!buffer.length) { send(req, res, 400, { error: '图片数据为空' }); return true }
172
238
  const asset = await assetStore.put(buffer, body.contentType || 'application/octet-stream')
173
- send(req, res, 200, { ok: true, ...asset })
239
+ /* 回给与 GET 一致的 sanitized content-type(保留 charset、script 类转 text/plain)。 */
240
+ send(req, res, 200, { ok: true, ...asset, contentType: safeContentType(asset.contentType) })
174
241
  return true
175
242
  }
176
243
  return false
@@ -184,8 +251,14 @@ export function createAssetHost(config = {}) {
184
251
  ? createFileAssetStore({ dir: config.dir })
185
252
  : null
186
253
 
254
+ /* 能力标签如实申报:gc/delete 仅当底层 store 支持时才 advertise(file store 有,
255
+ * workspace store 无),避免「声明满足、活实例缺方法」。 */
256
+ const tags = ['workspace-store', 'file-store', 'routes', 'sha256', 'mount']
257
+ if (typeof defaultStore?.gc === 'function') tags.push('gc')
258
+ if (typeof defaultStore?.delete === 'function') tags.push('delete')
259
+
187
260
  return {
188
- api: createServiceApi('assets', '1.0.0', ['workspace-store', 'file-store', 'routes', 'sha256', 'mount']),
261
+ api: createServiceApi('assets', '1.0.0', tags),
189
262
  version: '0.1.0',
190
263
  createStore: createWorkspaceAssetStore,
191
264
  createFileStore: createFileAssetStore,
@@ -219,5 +292,13 @@ export function createAssetHost(config = {}) {
219
292
  if (!defaultStore) throw new Error('asset-service: 未配置 storeClient/dir')
220
293
  return defaultStore.get(id)
221
294
  },
295
+ async delete(id) {
296
+ if (typeof defaultStore?.delete !== 'function') throw new Error('asset-service: 当前 store 不支持 delete')
297
+ return defaultStore.delete(id)
298
+ },
299
+ async gc(options) {
300
+ if (typeof defaultStore?.gc !== 'function') throw new Error('asset-service: 当前 store 不支持 gc')
301
+ return defaultStore.gc(options)
302
+ },
222
303
  }
223
304
  }
@@ -18,15 +18,25 @@ import { AsyncLocalStorage } from 'node:async_hooks'
18
18
 
19
19
  const storage = new AsyncLocalStorage()
20
20
 
21
- /** 在指定会话的上下文里跑一段逻辑(await 链与定时器都会继承)。 */
21
+ /** 在指定会话的上下文里跑一段逻辑(await 链与定时器都会继承)。
22
+ * payload 是对象而非裸字符串:除会话 id 外还携带一个「本请求已钉住的 store」槽位,
23
+ * 让 store 门面在请求内首次访问时解析一次并复用,避免请求中途 active 被别的窗口
24
+ * /activate 翻转后,同一请求的后续写入改向到另一个会话(跨会话写)。 */
22
25
  export function runWithSession(sessionId, fn) {
23
- return storage.run(String(sessionId || ''), fn)
26
+ return storage.run({ sid: String(sessionId || ''), pinned: null }, fn)
24
27
  }
25
28
 
26
29
  /** 当前请求所属的会话 id;不在请求里时返回空串。 */
27
30
  export function currentSession() {
28
31
  const value = storage.getStore()
29
- return typeof value === 'string' ? value : ''
32
+ return value && typeof value.sid === 'string' ? value.sid : ''
33
+ }
34
+
35
+ /** 当前请求的会话上下文对象({sid, pinned});不在请求里时返回 null。
36
+ * store 门面用它把「本请求用哪一份 store」钉住一次,整个请求复用。 */
37
+ export function sessionContext() {
38
+ const value = storage.getStore()
39
+ return value && typeof value === 'object' ? value : null
30
40
  }
31
41
 
32
42
  /**
@@ -58,8 +68,10 @@ export function bindToolsToCallerSession(registry) {
58
68
  const bound = (args, exec) => {
59
69
  const sid = sessionFromExec(exec)
60
70
  /* exec 原样透传:今天的实现体只用 args,但未来若有工具要执行上下文
61
- * (进度/中止等),不能在这层被静默丢掉。 */
62
- return sid ? runWithSession(sid, () => impl(args, exec)) : impl(args, exec)
71
+ * (进度/中止等),不能在这层被静默丢掉。
72
+ * 即使拿不到调用者会话(MCP 传输形态)也建立上下文:store 门面会在本次调用
73
+ * 首次访问时把「最近聚焦窗口」钉住,整个工具执行期间不再随 active 翻转改向。 */
74
+ return runWithSession(sid, () => impl(args, exec))
63
75
  }
64
76
  bound.__sessionBound = true
65
77
  impls[name] = bound
@@ -44,18 +44,19 @@ export function createRawAdapter({ log }) {
44
44
 
45
45
  if (thenable(result)) {
46
46
  let instance = {}
47
- let settled = false
48
- const started = Promise.resolve(result).then((value) => {
49
- instance = normalize(value)
50
- settled = true
51
- return instance.start ? instance.start() : undefined
52
- })
47
+ /* apply 结算只做归一化,绝不在此 eagerly 跑 instance.start()——旧实现
48
+ * 在 compile 返回的 promise resolve 时就启动,绕过 loader 的 start 阶段与
49
+ * stopRequested:loader 正在回滚/已请求卸载时 raw 仍会起进程/监听。
50
+ * start 交给 loader 在 start 阶段显式触发(此时才尊重 stopRequested)。 */
51
+ const ready = Promise.resolve(result).then((value) => { instance = normalize(value) })
53
52
  return {
54
- start: () => started,
53
+ start: async ({ signal } = {}) => {
54
+ await ready
55
+ /* 转发 loader 的卸载 signal,让 raw 实例的 start 也能感知取消。 */
56
+ return instance.start ? instance.start({ signal }) : undefined
57
+ },
55
58
  dispose: async () => {
56
- if (!settled) {
57
- try { await started } catch { /* start 失败由 loader 记录 */ }
58
- }
59
+ try { await ready } catch { /* apply 失败由 loader 记录 */ }
59
60
  if (typeof instance.dispose === 'function') return instance.dispose()
60
61
  },
61
62
  }
@@ -62,14 +62,21 @@ export function createRuntimeDriverAdapter({ host, config, log }) {
62
62
  ...(impl.args || []),
63
63
  ]
64
64
 
65
+ /* keepAlive 由声明推导:restart.max===0 表示「不要自动重启」,对应 keepAlive:false。
66
+ * 旧实现恒 true,应用声明 restart:{max:0} 仍被 broker 拉起,切换/回收行为与声明不符。 */
67
+ const keepAlive = !(impl.restart && impl.restart.max === 0)
65
68
  const serviceSpec = {
66
69
  id: impl.id,
67
70
  cmd,
68
71
  ports: { main: port },
69
72
  url: 'http://127.0.0.1:${PORT}/',
70
- keepAlive: true,
73
+ keepAlive,
71
74
  }
72
75
  if (impl.health?.path) serviceSpec.healthPath = impl.health.path
76
+ /* 声明的健康期望/超时与重启策略必须透传给 broker,不能被静默丢弃。 */
77
+ if (impl.health?.expect && typeof impl.health.expect === 'object') serviceSpec.expect = impl.health.expect
78
+ if (impl.health?.timeoutMs) serviceSpec.waitMs = impl.health.timeoutMs
79
+ if (impl.restart) serviceSpec.restart = impl.restart
73
80
  if (impl.dir) {
74
81
  serviceSpec.cwd = fileURLToPath(new URL(impl.dir, mountContext.context.baseUrl))
75
82
  }
@@ -13,12 +13,40 @@ const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
13
13
  const DEFAULT_RANK = 600
14
14
 
15
15
  export function parseSkill(raw, path) {
16
+ /* BOM 会让 /^---/ 匹配不到 frontmatter,误报「缺少 YAML frontmatter」。先剥掉。 */
17
+ raw = raw.replace(/^\uFEFF/, '')
16
18
  const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(raw)
17
19
  if (!frontmatter?.[1]) throw new Error(`skill ${path} 缺少 YAML frontmatter`)
18
20
  const meta = {}
19
- for (const line of frontmatter[1].split(/\r?\n/)) {
20
- const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line)
21
- if (match) meta[match[1]] = match[2].replace(/^['"]|['"]$/g, '').trim()
21
+ const lines = frontmatter[1].split(/\r?\n/)
22
+ for (let i = 0; i < lines.length; i++) {
23
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(lines[i])
24
+ if (!match) continue
25
+ const key = match[1]
26
+ let value = match[2].trim()
27
+ /* 块标量 description: | / > :旧实现把 '|' 本身当成描述直达 LLM,多行正文全丢。
28
+ * 这里聚合后续缩进行,| 保留换行、> 折叠为空格,按 chomping 处理尾部空白。 */
29
+ const block = /^([|>])([+-]?)$/.exec(value)
30
+ if (block) {
31
+ const body = []
32
+ let j = i + 1
33
+ for (; j < lines.length; j++) {
34
+ const ln = lines[j]
35
+ if (ln.trim() === '') { body.push(''); continue }
36
+ if (/^\s/.test(ln)) body.push(ln)
37
+ else break
38
+ }
39
+ i = j - 1
40
+ const nonEmpty = body.filter((l) => l.trim() !== '')
41
+ const minIndent = nonEmpty.length ? Math.min(...nonEmpty.map((l) => /^\s*/.exec(l)[0].length)) : 0
42
+ const stripped = body.map((l) => l.slice(minIndent))
43
+ let text = stripped.join(block[1] === '>' ? ' ' : '\n')
44
+ if (block[2] !== '+') text = text.replace(/\s+$/, '')
45
+ value = text
46
+ } else {
47
+ value = value.replace(/^['"]|['"]$/g, '').trim()
48
+ }
49
+ meta[key] = value
22
50
  }
23
51
  if (!meta.name || !meta.description) throw new Error(`skill ${path} 缺少 name/description`)
24
52
  if (!NAME_RE.test(meta.name)) throw new Error(`skill ${path} name 必须是 kebab-case`)
@@ -22,12 +22,19 @@ function reply(id, result) {
22
22
 
23
23
  export function createMcpHandler({
24
24
  tools = [], callTool, serverInfo, instructions,
25
- maxBodyBytes = 10 * 1024 * 1024, maxBatch = 100,
25
+ maxBodyBytes = 10 * 1024 * 1024, maxBatch = 100, listChanged = false,
26
26
  } = {}) {
27
- if (!Array.isArray(tools)) throw new Error('createMcpHandler: tools 必须是数组')
27
+ /* tools 可以是静态数组,或一个返回当前数组的函数(活引用)。活引用让
28
+ * tools/list 每次读到最新工具集——registry 动态增删工具后无需重建 handler。 */
29
+ const liveProvider = typeof tools === 'function' ? tools : null
30
+ if (!liveProvider && !Array.isArray(tools)) throw new Error('createMcpHandler: tools 必须是数组或返回数组的函数')
28
31
  if (typeof callTool !== 'function') throw new Error('createMcpHandler: callTool 必须是函数')
29
32
 
30
- const toolMap = new Map(tools.map((tool) => [tool.name, tool]))
33
+ const currentTools = () => {
34
+ const list = liveProvider ? liveProvider() : tools
35
+ return Array.isArray(list) ? list : []
36
+ }
37
+ const toolMapNow = () => new Map(currentTools().map((tool) => [tool.name, tool]))
31
38
 
32
39
  return async function handle(req, res) {
33
40
  /* 长工具调用(如截图)期间客户端可能超时断连;socket 的 'error' 事件
@@ -89,7 +96,7 @@ export function createMcpHandler({
89
96
  if (method === 'initialize') {
90
97
  const result = {
91
98
  protocolVersion: String(params?.protocolVersion || DEFAULT_PROTOCOL),
92
- capabilities: { tools: { listChanged: false } },
99
+ capabilities: { tools: { listChanged: !!listChanged } },
93
100
  serverInfo: serverInfo || { name: 'dsh-plugin', version: '0.0.0' },
94
101
  }
95
102
  if (typeof instructions === 'string' && instructions) result.instructions = instructions
@@ -101,13 +108,13 @@ export function createMcpHandler({
101
108
  if (method === 'ping') return isNotification ? null : reply(id, {})
102
109
 
103
110
  if (method === 'tools/list') {
104
- return isNotification ? null : reply(id, { tools })
111
+ return isNotification ? null : reply(id, { tools: currentTools() })
105
112
  }
106
113
 
107
114
  if (method === 'tools/call') {
108
115
  const name = params?.name
109
116
  const args = params?.arguments && typeof params.arguments === 'object' ? params.arguments : {}
110
- const tool = toolMap.get(name)
117
+ const tool = toolMapNow().get(name)
111
118
  if (!tool) {
112
119
  if (isNotification) return null
113
120
  return reply(id, {
@@ -14,24 +14,40 @@
14
14
  * 返回恒为 {content:[...]}(object),因此 DSH 原生面 output.schema 用 object 恒满足。
15
15
  */
16
16
 
17
- /** 把任意工具返回值归一为 MCP content 形态。 */
18
- export function normalizeToolResult(out) {
17
+ /** 单个 text 块的默认上限:防 base64/大输出撑爆 LLM 上下文。image 块不受影响。 */
18
+ export const DEFAULT_MAX_TEXT_BYTES = 256 * 1024
19
+
20
+ function capText(text, max) {
21
+ if (!max || max <= 0 || typeof text !== 'string' || text.length <= max) return text
22
+ return `${text.slice(0, max)}\n…[truncated: original ${text.length} chars, limit ${max}]`
23
+ }
24
+
25
+ function capContent(content, max) {
26
+ return content.map((block) => (
27
+ block && block.type === 'text' && typeof block.text === 'string'
28
+ ? { ...block, text: capText(block.text, max) }
29
+ : block
30
+ ))
31
+ }
32
+
33
+ /** 把任意工具返回值归一为 MCP content 形态(并对超限 text 块截断+提示)。 */
34
+ export function normalizeToolResult(out, { maxTextBytes = DEFAULT_MAX_TEXT_BYTES } = {}) {
19
35
  const isError = out && typeof out.isError === 'boolean' ? { isError: out.isError } : {}
36
+ let content
20
37
  if (out && Array.isArray(out.content)) {
21
- return { content: out.content, ...isError }
22
- }
23
- if (out && typeof out.text === 'string') {
24
- return { content: [{ type: 'text', text: out.text }], ...isError }
25
- }
26
- if (typeof out === 'string') {
27
- return { content: [{ type: 'text', text: out }] }
28
- }
29
- if (out === undefined || out === null) {
30
- return { content: [{ type: 'text', text: '' }] }
38
+ content = out.content
39
+ } else if (out && typeof out.text === 'string') {
40
+ content = [{ type: 'text', text: out.text }]
41
+ } else if (typeof out === 'string') {
42
+ content = [{ type: 'text', text: out }]
43
+ } else if (out === undefined || out === null) {
44
+ content = [{ type: 'text', text: '' }]
45
+ } else {
46
+ let text
47
+ try { text = JSON.stringify(out) } catch { text = String(out) }
48
+ content = [{ type: 'text', text: text ?? String(out) }]
31
49
  }
32
- let text
33
- try { text = JSON.stringify(out) } catch { text = String(out) }
34
- return { content: [{ type: 'text', text: text ?? String(out) }] }
50
+ return { content: capContent(content, maxTextBytes), ...isError }
35
51
  }
36
52
 
37
53
  /** 从归一化结果提取纯文本(用于把失败内容拼成 Error.message)。 */
@@ -28,6 +28,22 @@ function anyTypeMatches(patterns, type) {
28
28
  return (patterns || []).some((p) => typeMatches(p, type))
29
29
  }
30
30
 
31
+ /** 双向通配匹配:声明侧或查询侧任一带 `/*` 通配都要能命中。
32
+ * 旧实现只把声明当 pattern、查询当 type,查询侧通配(conductor 问「谁产出
33
+ * artifact:image/*」)永远不命中具体类型。 */
34
+ function typesOverlap(declPatterns, queryType) {
35
+ return (declPatterns || []).some((p) => typeMatches(p, queryType) || typeMatches(queryType, p))
36
+ }
37
+
38
+ /** 深冻结:描述符的 produces/consumes/surface/provides 等嵌套结构也要不可变,
39
+ * 否则注册后仍能被外部改写,注册表的「单一真源」失真。 */
40
+ function deepFreeze(value) {
41
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value
42
+ Object.freeze(value)
43
+ for (const key of Object.keys(value)) deepFreeze(value[key])
44
+ return value
45
+ }
46
+
31
47
  /** 最小结构兜底:name/suite/controlMode/kind 必须在场且合法。深度校验走注入的 validate。 */
32
48
  function structuralCheck(descriptor) {
33
49
  const errors = []
@@ -48,7 +64,7 @@ export function createDescriptorRegistry({ validate } = {}) {
48
64
  /** @type {Map<string, {descriptor:object, suite:string, baseUrl:string, registeredAt:number}>} */
49
65
  const entries = new Map()
50
66
 
51
- function register(descriptor, { suite, baseUrl = '' } = {}) {
67
+ function register(descriptor, { suite, baseUrl = '', force = false } = {}) {
52
68
  const merged = { ...descriptor, suite: descriptor?.suite || suite }
53
69
  const errors = structuralCheck(merged)
54
70
  if (errors.length) {
@@ -64,8 +80,16 @@ export function createDescriptorRegistry({ validate } = {}) {
64
80
  throw err
65
81
  }
66
82
  }
83
+ /* owner 校验:同名描述符已属另一套件时拒绝静默覆盖(防跨套件抢占);
84
+ * 同套件热重载刷新放行,确需跨套件替换须显式 force。 */
85
+ const existing = entries.get(merged.name)
86
+ if (existing && existing.suite !== merged.suite && !force) {
87
+ const err = new Error(`能力描述符 ${merged.name} 已属套件 ${existing.suite},套件 ${merged.suite} 不能覆盖(如确需替换请传 force)`)
88
+ err.code = 'DESCRIPTOR_OWNER_CONFLICT'
89
+ throw err
90
+ }
67
91
  const entry = Object.freeze({
68
- descriptor: Object.freeze({ ...merged }),
92
+ descriptor: deepFreeze({ ...merged }),
69
93
  suite: merged.suite,
70
94
  baseUrl: String(baseUrl || ''),
71
95
  registeredAt: Date.now(),
@@ -92,8 +116,8 @@ export function createDescriptorRegistry({ validate } = {}) {
92
116
  if (query.suite && entry.suite !== query.suite) continue
93
117
  if (query.controlMode && d.controlMode !== query.controlMode) continue
94
118
  if (query.kind && d.kind !== query.kind) continue
95
- if (query.produces && !anyTypeMatches(d.produces, query.produces)) continue
96
- if (query.consumes && !anyTypeMatches(d.consumes, query.consumes)) continue
119
+ if (query.produces && !typesOverlap(d.produces, query.produces)) continue
120
+ if (query.consumes && !typesOverlap(d.consumes, query.consumes)) continue
97
121
  out.push(entry)
98
122
  }
99
123
  return out
@@ -166,7 +166,28 @@ export function createRegistry(capabilities, { enabled = null, ports = null, rep
166
166
  }),
167
167
  }
168
168
 
169
- return { TOOLS, TOOL_IMPL, TOOL_META, FEATURES, CAPABILITIES, ctx }
169
+ /* 动态增删工具:配合 MCP 活引用(tools/list 读 registry.TOOLS),注册/注销后
170
+ * 客户端重新 list 即见最新工具集,无需重建 handler。旧 registry 是纯静态,
171
+ * 套件热重载/能力开关无法反映到工具面。 */
172
+ function registerTool(tool, capabilityId = '') {
173
+ if (!tool || typeof tool.name !== 'string' || !tool.name) throw new Error('registerTool 需要 tool.name')
174
+ if (typeof tool.handler !== 'function') throw new Error(`工具 ${tool.name} 需要 handler`)
175
+ if (TOOL_IMPL[tool.name]) throw new Error(`工具已存在: ${tool.name}`)
176
+ TOOLS.push({ name: tool.name, description: tool.description || '', inputSchema: tool.inputSchema || { type: 'object', properties: {} } })
177
+ TOOL_META[tool.name] = { kind: tool.kind || 'write', since: tool.since || '1.0.0', capability: capabilityId }
178
+ TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
179
+ return true
180
+ }
181
+ function unregisterTool(name) {
182
+ const index = TOOLS.findIndex((tool) => tool.name === name)
183
+ if (index < 0) return false
184
+ TOOLS.splice(index, 1)
185
+ delete TOOL_IMPL[name]
186
+ delete TOOL_META[name]
187
+ return true
188
+ }
189
+
190
+ return { TOOLS, TOOL_IMPL, TOOL_META, FEATURES, CAPABILITIES, ctx, registerTool, unregisterTool }
170
191
  }
171
192
 
172
193
  /** 与 MCP 工具面解耦:调用前统一校验。 */
@@ -199,21 +220,26 @@ export function createToolDispatcher({ tools, callTool }) {
199
220
  * { tools, callTool }(旧 relay 形态)
200
221
  * @param {{ registry?: object, tools?: Array, toolImpl?: object, callTool?: Function, serverInfo?: object, instructions?: string }} options
201
222
  */
202
- export function createMcpHandler({ registry, tools, toolImpl, callTool, serverInfo, instructions } = {}) {
203
- const list = tools || registry?.TOOLS || []
223
+ export function createMcpHandler({ registry, tools, toolImpl, callTool, serverInfo, instructions, listChanged } = {}) {
224
+ /* registry 形态走活引用:tools/list 每次读 registry.TOOLS,callTool 读 registry.TOOL_IMPL,
225
+ * 于是 registerTool/unregisterTool 的动态增删立刻可见,无需重建 handler。 */
226
+ const useRegistry = !tools && !!registry
204
227
  const impl = toolImpl || registry?.TOOL_IMPL || null
205
- if (!Array.isArray(list) || !list.length) throw new Error('createMcpHandler: 没有工具可暴露')
228
+ const staticList = tools || null
229
+ if (!useRegistry && (!Array.isArray(staticList) || !staticList.length)) throw new Error('createMcpHandler: 没有工具可暴露')
206
230
  if (!impl && typeof callTool !== 'function') throw new Error('createMcpHandler: 需要 toolImpl 或 callTool')
207
231
  return createKitMcpHandler({
208
- tools: list,
232
+ tools: useRegistry ? () => registry.TOOLS : staticList,
209
233
  callTool: (name, args, context) => {
210
234
  if (typeof callTool === 'function' && !impl) return callTool(name, args, context)
211
- const fn = impl[name]
235
+ const source = useRegistry ? registry.TOOL_IMPL : impl
236
+ const fn = source[name]
212
237
  if (!fn) throw new Error(`未知工具: ${name}`)
213
238
  return fn(args, context)
214
239
  },
215
240
  serverInfo: serverInfo || { name: 'dsh-tool-host', version: '0.1.0' },
216
241
  instructions,
242
+ listChanged,
217
243
  })
218
244
  }
219
245
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/browser-workbench",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
4
4
  "description": "浏览器操控工作台运行时:18 个 browser_* MCP 工具(导航/快照/点击/填写/按键/下拉/上传/滚动/批量连做/拖拽/标签页/截图)+ Playwright 引擎(有头可见、登录态持久化)+ 可视化工作台。",
5
5
  "type": "module",
6
6
  "main": "./plugin.mjs",
@@ -10,7 +10,7 @@ import { createCapabilityReport } from './shared/tool-host.mjs'
10
10
  export const CONTRACT_VERSION = '1.3.0'
11
11
 
12
12
  /** 工作台包版本。 */
13
- export const PACKAGE_VERSION = '0.1.17'
13
+ export const PACKAGE_VERSION = '0.1.18'
14
14
 
15
15
  /** 生成模型可读的能力报告。 */
16
16
  export function capabilityReport(args, workbenchUrl = '', runtime = {}) {
@@ -17,6 +17,7 @@
17
17
  * 缓存的是 Promise<engine>:并发首请求共享同一次创建,不会重复拉起。
18
18
  */
19
19
  import path from 'node:path'
20
+ import fs from 'node:fs'
20
21
  import { currentSession } from '@capyclaw/document-workbench/session-context'
21
22
 
22
23
  const DEFAULT_SESSION = 'default'
@@ -140,6 +141,41 @@ export function createSessionEngines({ hostDir, config, createEngine }) {
140
141
  reapTimer.unref?.()
141
142
  }
142
143
 
144
+ /* ---- 磁盘回收:会话 profile 目录 TTL 清理 ----
145
+ * 进程回收(reap)只挂起浏览器,<hostDir>/sessions/<sid>/ 的 profile 目录从不删,
146
+ * 跨宿主重启越积越多(实测约 40 个陈旧目录)。这里按 mtime TTL 清理「不在本进程
147
+ * 缓存里」的陈旧会话目录——本进程用过的会话常驻 cache,受保护不会被误删;
148
+ * default / login-vault 是共享登录态,永不删。启动即扫一次清历史,之后慢周期巡检。 */
149
+ const sessionDirTtlMs = Number.isFinite(cfg.sessionDirTtlMs) ? cfg.sessionDirTtlMs : 7 * 24 * 3600 * 1000
150
+ const PROTECTED_DIRS = new Set([DEFAULT_SESSION, 'login-vault'])
151
+ async function cleanupSessionDirs() {
152
+ if (sessionDirTtlMs <= 0) return { removed: 0 }
153
+ const sessionsRoot = path.join(hostDir, 'sessions')
154
+ let names
155
+ try { names = fs.readdirSync(sessionsRoot) } catch { return { removed: 0 } }
156
+ const now = Date.now()
157
+ let removed = 0
158
+ for (const name of names) {
159
+ if (PROTECTED_DIRS.has(name) || cache.has(name) || !SID_RE.test(name)) continue
160
+ const full = path.join(sessionsRoot, name)
161
+ try {
162
+ const st = fs.statSync(full)
163
+ if (!st.isDirectory()) continue
164
+ if (now - st.mtimeMs > sessionDirTtlMs) {
165
+ fs.rmSync(full, { recursive: true, force: true })
166
+ removed += 1
167
+ }
168
+ } catch { /* 忽略单个目录失败 */ }
169
+ }
170
+ return { removed }
171
+ }
172
+ let dirCleanupTimer = null
173
+ if (sessionDirTtlMs > 0) {
174
+ cleanupSessionDirs().catch(() => {})
175
+ dirCleanupTimer = setInterval(() => { cleanupSessionDirs().catch(() => {}) }, 3600000)
176
+ dirCleanupTimer.unref?.()
177
+ }
178
+
143
179
  /** 停服前挂起所有已创建的引擎(保留标签日志供下次恢复),避免僵尸浏览器进程。
144
180
  * 停服竞态:框架先调 beforeStop 再关 HTTP,await 期间仍可能有请求进来重建引擎。
145
181
  * 用 drain 循环把「await 期间新创建的」也扫掉(最多 5 轮,防持续流量下无限循环);
@@ -150,6 +186,7 @@ export function createSessionEngines({ hostDir, config, createEngine }) {
150
186
  closingPromise = (async () => {
151
187
  try {
152
188
  if (reapTimer) { clearInterval(reapTimer); reapTimer = null }
189
+ if (dirCleanupTimer) { clearInterval(dirCleanupTimer); dirCleanupTimer = null }
153
190
  for (let pass = 0; pass < 5; pass += 1) {
154
191
  const pending = [...cache.values()]
155
192
  cache.clear()
@@ -180,5 +217,7 @@ export function createSessionEngines({ hostDir, config, createEngine }) {
180
217
  sessions: () => [...cache.keys()],
181
218
  /* 手动触发一次回收巡检(测试用;生产由定时器驱动)。 */
182
219
  reapNow: () => reap(),
220
+ /* 手动触发一次会话目录磁盘清理(测试用;生产启动+慢周期驱动)。 */
221
+ cleanupSessionDirsNow: () => cleanupSessionDirs(),
183
222
  }
184
223
  }