@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
@@ -19,6 +19,7 @@ import crypto from 'node:crypto'
19
19
  import { listen, send, sendText, readBody } from '@capyclaw/plugin-kit/service/http'
20
20
  import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
21
21
  import { isLoopbackOrigin as sharedIsLoopbackOrigin, mimeFor } from '@capyclaw/plugin-kit/util/http'
22
+ import { safeJoin, cleanStaticPrefix, staticPrefixHit, staticRelRaw, decodeStaticRel, staticFileHit, staticHitNameType, staticBaseHeaders } from '@capyclaw/plugin-kit/service/static'
22
23
  import { tuning } from './tuning.mjs'
23
24
 
24
25
  function slugOf(id) {
@@ -133,11 +134,7 @@ async function probeExisting(origin, healthPath, id) {
133
134
  }
134
135
  }
135
136
 
136
- function safeJoin(root, rel) {
137
- const target = path.resolve(root, `.${path.sep}${rel}`)
138
- const base = path.resolve(root)
139
- return target === base || target.startsWith(base + path.sep) ? target : null
140
- }
137
+ /* safeJoin 已收敛到 @capyclaw/plugin-kit/service/static(P2-13a 静态公共核心)。 */
141
138
 
142
139
  /**
143
140
  * @param {{
@@ -204,20 +201,28 @@ export function createServiceApp(options = {}) {
204
201
  })
205
202
  },
206
203
 
207
- /** 静态目录挂载。files 可给显式映射:{ '/': ['index.html','text/html'] }。 */
204
+ /** 静态目录挂载。files 可给显式映射:{ '/': ['index.html','text/html'] }。
205
+ * 路径/头部计算走 @capyclaw/plugin-kit/service/static 公共核心(P2-13a);
206
+ * 本宿主保留自己的响应政策:畸形编码回 400、content-type 取 mimeFor(请求 rel)、每次读盘。 */
208
207
  static(prefix, dir, { files = null, index = 'index.html' } = {}) {
209
- const cleanPrefix = prefix === '/' ? '' : prefix.replace(/\/+$/, '')
208
+ const cleanPrefix = cleanStaticPrefix(prefix)
210
209
  return app.use((req, res, u) => {
211
210
  if (req.method !== 'GET' && req.method !== 'HEAD') return false
212
- if (cleanPrefix && u.pathname !== cleanPrefix && !u.pathname.startsWith(cleanPrefix + '/')) return false
213
- const relRaw = cleanPrefix ? u.pathname.slice(cleanPrefix.length) : u.pathname
214
- const rel = relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
211
+ if (!staticPrefixHit(u.pathname, cleanPrefix)) return false
212
+ const relRaw = staticRelRaw(u.pathname, cleanPrefix)
213
+ const rel = decodeStaticRel(relRaw, index)
214
+ if (rel === null) {
215
+ /* 畸形百分号编码 → URIError,不包会冒成 500;客户端错误回 400。 */
216
+ res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
217
+ res.end(req.method === 'HEAD' ? undefined : 'malformed path encoding')
218
+ return true
219
+ }
215
220
  let file = null
216
221
  let type = mimeFor(rel)
217
222
  if (files) {
218
- const hit = files[relRaw === '' ? '/' : relRaw] || files[relRaw]
223
+ const hit = staticFileHit(files, relRaw)
219
224
  if (!hit) return false
220
- const [name, explicitType] = Array.isArray(hit) ? hit : [hit]
225
+ const [name, explicitType] = staticHitNameType(hit)
221
226
  file = safeJoin(dir, name)
222
227
  type = explicitType || type
223
228
  } else {
@@ -226,13 +231,7 @@ export function createServiceApp(options = {}) {
226
231
  if (!file) return false
227
232
  try {
228
233
  const data = fs.readFileSync(file)
229
- res.writeHead(200, {
230
- 'content-type': type,
231
- 'content-length': data.length,
232
- 'x-content-type-options': 'nosniff',
233
- 'referrer-policy': 'no-referrer',
234
- 'cache-control': 'no-cache',
235
- })
234
+ res.writeHead(200, staticBaseHeaders(type, data.length))
236
235
  res.end(req.method === 'HEAD' ? undefined : data)
237
236
  return true
238
237
  } catch {
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "$schema": "../capyclaw-suite-kit/suite.schema.json",
3
3
  "name": "dsh-tool-host-suite",
4
- "version": "0.2.0",
4
+ "version": "0.3.0",
5
5
  "title": "Tool Host",
6
6
  "description": "通用工具面:能力 DSL、注册表、校验、契约、MCP 壳、跨套件能力描述符注册/发现。",
7
7
  "packages": {
8
8
  "@capyclaw/tool-host": {
9
9
  "role": "provider",
10
- "version": "^0.2.0",
10
+ "version": "^0.3.2",
11
11
  "path": ".",
12
12
  "provides": {
13
13
  "services": [
@@ -1,16 +1,46 @@
1
1
  /**
2
2
  * @capyclaw/tool-host 插件:向同进程插件提供 ctx.toolHost。
3
+ *
4
+ * 同时落地“会话模式锁”这一基础设施能力:
5
+ * · 把 work-store 惰性解析器注入 toolHost(模式锁的存储真源);
6
+ * · 给 DSH tools 服务挂全局 guard(异领域调用硬拒兜底);
7
+ * · 注册框架核心工具 mode_lock / mode_status(无领域,恒可见)——显式锁定入口;
8
+ * · 给 DSH systemPrompt 挂动态感知 section(锁定即告知模型主区工作台与交付路径)。
9
+ * 核心工具与 guard 的注册统一走 modeGate.install(tools)(幂等):apply 时 best-effort 挂一次,
10
+ * 若那一刻 tools 服务尚未就绪,首个套件注册(registerWithDsh / bridge host)会再调 install 补上,
11
+ * 故不依赖加载顺序。感知闸同理走 modeGate.installPrompt(systemPrompt)。
12
+ * 所有经 toolHost.registerWithDsh / bridge host 注册的领域能力自动受锁约束,套件零接线。
3
13
  */
4
14
  import { defineDriver } from '@capyclaw/foundation/abi'
5
15
  import { createToolHost } from '../src/index.mjs'
6
16
 
17
+ const safeGet = (ctx, name) => {
18
+ try { return ctx.reflect?.get?.(name) ?? ctx[name] } catch { return null }
19
+ }
20
+
7
21
  export const { name, inject, apply } = defineDriver({
8
22
  name: 'tool-host',
9
23
  service: 'toolHost',
10
24
  apply(ctx, config = {}) {
11
- const service = createToolHost(config)
25
+ const service = createToolHost({ ...config, getWorkStore: () => safeGet(ctx, 'workStore') })
12
26
  const dispose = ctx.provide('toolHost', service)
13
- console.log('[tool-host] ready')
14
- return () => { if (typeof dispose === 'function') dispose() }
27
+
28
+ /* 模式锁兜底闸 + 核心锁定工具(幂等)。tools 缺席则降级:稍后套件注册时经 install 补挂。
29
+ * install 返回引用计数 disposer,必须随 driver 卸载释放,否则核心工具/guard 永驻。 */
30
+ const tools = safeGet(ctx, 'tools')
31
+ const gateDispose = (tools && typeof tools.register === 'function') ? service.modeGate.install(tools) : null
32
+
33
+ /* 感知闸(幂等):锁定会话的系统提示里注入主区工作台感知。systemPrompt 缺席则降级,
34
+ * 稍后套件注册时经 installPrompt 补挂。disposer 同样必须随 driver 卸载释放。 */
35
+ const systemPrompt = safeGet(ctx, 'systemPrompt')
36
+ const promptDispose = (systemPrompt && typeof systemPrompt.section === 'function')
37
+ ? service.modeGate.installPrompt(systemPrompt) : null
38
+
39
+ console.log('[tool-host] ready (mode-gate enabled)')
40
+ return () => {
41
+ if (typeof promptDispose === 'function') promptDispose()
42
+ if (typeof gateDispose === 'function') gateDispose()
43
+ if (typeof dispose === 'function') dispose()
44
+ }
15
45
  },
16
- })
46
+ })
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/tool-host",
3
- "version": "0.2.0",
3
+ "version": "0.3.2",
4
4
  "description": "DSH 公共工具面插件:能力 DSL、工具注册表、参数校验、契约报告、MCP 协议壳与 instructions 模板,向插件提供 ctx.toolHost。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 工具结果图像准入 —— DSH 原生工具面专用。
3
+ *
4
+ * 背景(2026-11-22 会话中断根因):DSH 的 ImageBlock 契约要求
5
+ * `{ type:'image', attachment: ImageAttachmentRef }`(见 @deepseek-ai/dsh-llm
6
+ * types.ts)。但部分工作台工具(rsp_screen / browser_screenshot 等)为了「图片直接
7
+ * 回给模型」返回了 MCP wire 形态的裸 base64 块 `{ type:'image', data, mimeType }`。
8
+ * 原生面 `dsh-tools/batch.ts` 把 result.content 原样写进 session 日志、不做形状校验,
9
+ * 于是坏块永久留在历史里;下一步构建请求时序列化器读 `block.attachment.attachmentId`
10
+ * 抛 TypeError(deepseek 侧包成 TRANSPORT,qwen4 侧冒泡成 UNKNOWN),该会话此后每一轮
11
+ * 都在发出前崩掉。
12
+ *
13
+ * 官方工具(read_image / mcp-client / office)都是自己先 `attachments.saveImage`
14
+ * 再回 attachment ref。这里在注册层补上同一道准入:把裸 base64 图像块持久化成
15
+ * attachment ref 再交给 DSH,一处修复覆盖所有 capyclaw 原生工具。
16
+ *
17
+ * 注意:只用于原生面(registerWithDsh)。MCP 面(createMcpHandler/dispatcher)必须
18
+ * 保留 `{data,mimeType}` wire 形态——那是 MCP 协议本身,由 dsh-mcp-client 负责落盘。
19
+ */
20
+
21
+ /** 是否是一个尚未准入的裸 base64 图像块(缺 attachment、带 string data)。 */
22
+ function isRawImageBlock(block) {
23
+ return !!block && block.type === 'image' && !block.attachment && typeof block.data === 'string'
24
+ }
25
+
26
+ /**
27
+ * 从执行上下文 / 注册上下文解析 attachments 服务。
28
+ * agent 的会话级 ctx 与 read_image 用的是同一棵上下文树,attachments 必在其上;
29
+ * 注册 ctx 作为兜底。cordis 未 inject 时 get 可能抛错,逐一吞掉换下一个候选。
30
+ * @returns {object|null} 带 saveImage 的 AttachmentStore,或 null。
31
+ */
32
+ export function resolveAttachments(exec, ctx) {
33
+ for (const candidate of [exec?.agent?.ctx, ctx]) {
34
+ if (!candidate) continue
35
+ try {
36
+ const viaGet = typeof candidate.get === 'function' ? candidate.get('attachments') : undefined
37
+ const service = viaGet ?? candidate.attachments ?? candidate.reflect?.get?.('attachments')
38
+ if (service && typeof service.saveImage === 'function') return service
39
+ } catch { /* 该上下文取不到,换下一个候选 */ }
40
+ }
41
+ return null
42
+ }
43
+
44
+ /**
45
+ * 把工具结果 content 里的裸 base64 图像块准入为持久 attachment ref。
46
+ * 非图像块、已带 attachment 的图像块原样保留;无图像块时零开销直接返回原数组。
47
+ *
48
+ * 降级原则:宁可丢图也不毒化会话——attachments 缺席或 saveImage 失败时,把该图像块
49
+ * 换成一条说明性 text 块(工具通常另有一条带落盘路径的 text 块,信息不丢)。
50
+ *
51
+ * @param {Array} content 归一化后的 MCP content 块数组。
52
+ * @param {object|null} attachments AttachmentStore(resolveAttachments 的结果)。
53
+ * @param {{ name?: string }} [opts] 可选显示名(写入 ref.name,绝不解释为路径)。
54
+ * @returns {Promise<Array>} 准入后的 content 块数组。
55
+ */
56
+ export async function admitToolResultImages(content, attachments, { name } = {}) {
57
+ if (!Array.isArray(content)) return content
58
+ if (!content.some(isRawImageBlock)) return content
59
+
60
+ const out = []
61
+ for (const block of content) {
62
+ if (!isRawImageBlock(block)) { out.push(block); continue }
63
+
64
+ const mediaType = block.mediaType || block.mimeType || 'image/png'
65
+ if (!attachments) {
66
+ out.push({ type: 'text', text: `[image omitted: no attachment service mounted; ${mediaType}]` })
67
+ continue
68
+ }
69
+ try {
70
+ const data = Buffer.from(block.data, 'base64')
71
+ const ref = await attachments.saveImage({ data, mediaType, ...(name ? { name } : {}) })
72
+ out.push({ type: 'image', attachment: ref })
73
+ } catch (error) {
74
+ const code = error?.code || error?.name || 'ERROR'
75
+ const message = String(error?.message || error)
76
+ out.push({ type: 'text', text: `[image omitted: attachment save failed (${code}): ${message}]` })
77
+ }
78
+ }
79
+ return out
80
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * 调用者会话上下文(框架级 ALS)。
3
+ *
4
+ * registerWithDsh 把每个原生工具的执行包进 runWithCallerSession(sid, …),
5
+ * 于是工具 handler 执行期间(哪怕 handler 只拿到 (args, ctx)、丢了 exec),
6
+ * 框架内部任何一层都能用 currentCallerSession() 取回“是谁在调我”。
7
+ *
8
+ * 用途:会话模式锁在能力发现面(discoverCapabilities)按调用者会话过滤异领域
9
+ * 描述符——conductor_discover 这类 read 工具无需自己接线 exec 即自动受约束。
10
+ *
11
+ * 无会话(HTTP/MCP 管理面、墙聚合视图)时返回 '',调用方据此降级为不过滤。
12
+ */
13
+ import { AsyncLocalStorage } from 'node:async_hooks'
14
+
15
+ const als = new AsyncLocalStorage()
16
+
17
+ /** 在指定调用者会话上下文里执行 fn(同步/异步均可,ALS 随 await 传播)。 */
18
+ export function runWithCallerSession(sessionId, fn) {
19
+ return als.run(String(sessionId || ''), fn)
20
+ }
21
+
22
+ /** 当前调用者会话 id;不在工具调用上下文里时返回 ''。 */
23
+ export function currentCallerSession() {
24
+ return als.getStore() || ''
25
+ }
@@ -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
@@ -12,8 +12,14 @@ import { validateToolArguments } from '@capyclaw/plugin-kit/tools/validate'
12
12
  import { normalizeToolResult, resultText } from '@capyclaw/plugin-kit/tools/result'
13
13
  import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
14
14
  import { createDescriptorRegistry } from './descriptors.mjs'
15
+ import { createModeGate } from './mode-gate.mjs'
16
+ import { runWithCallerSession, currentCallerSession } from './caller-session.mjs'
17
+ import { admitToolResultImages, resolveAttachments } from './admit-images.mjs'
15
18
 
19
+ export { admitToolResultImages, resolveAttachments } from './admit-images.mjs'
16
20
  export { createDescriptorRegistry } from './descriptors.mjs'
21
+ export { createModeGate } from './mode-gate.mjs'
22
+ export { runWithCallerSession, currentCallerSession } from './caller-session.mjs'
17
23
 
18
24
  const KINDS = new Set(['read', 'write', 'control'])
19
25
 
@@ -23,12 +29,13 @@ export function defineTool({
23
29
  inputSchema = { type: 'object', properties: {}, additionalProperties: false },
24
30
  kind = 'write',
25
31
  since = '1.0.0',
32
+ domain = '',
26
33
  handler,
27
34
  } = {}) {
28
35
  if (!name || typeof name !== 'string') throw new Error('defineTool 需要 name')
29
36
  if (typeof handler !== 'function') throw new Error(`工具 ${name} 需要 handler`)
30
37
  if (!KINDS.has(kind)) throw new Error(`工具 ${name} 的 kind 非法: ${kind}`)
31
- return Object.freeze({ name, description, inputSchema, kind, since, handler })
38
+ return Object.freeze({ name, description, inputSchema, kind, since, domain: String(domain || ''), handler })
32
39
  }
33
40
 
34
41
  export function defineCapability({
@@ -40,6 +47,7 @@ export function defineCapability({
40
47
  dependsOn = [],
41
48
  provides = {},
42
49
  features = [],
50
+ domain = '',
43
51
  tools = [],
44
52
  } = {}) {
45
53
  if (!id || typeof id !== 'string') throw new Error('defineCapability 需要 id')
@@ -53,6 +61,7 @@ export function defineCapability({
53
61
  dependsOn: Object.freeze([...dependsOn]),
54
62
  provides: Object.freeze({ ...provides }),
55
63
  features: Object.freeze([...features]),
64
+ domain: String(domain || ''),
56
65
  tools: Object.freeze([...tools]),
57
66
  })
58
67
  }
@@ -99,7 +108,7 @@ function selectCapabilities(capabilities, enabled) {
99
108
  * @param {Array} capabilities
100
109
  * @param {{ enabled?: string[], ports?: object, report?: Function, reserved?: string[] }} options
101
110
  */
102
- export function createRegistry(capabilities, { enabled = null, ports = null, report = null, reserved = [] } = {}) {
111
+ export function createRegistry(capabilities, { enabled = null, ports = null, report = null, reserved = [], domain = '' } = {}) {
103
112
  validateCapabilities(capabilities)
104
113
  const selected = selectCapabilities(capabilities, enabled)
105
114
 
@@ -145,11 +154,12 @@ export function createRegistry(capabilities, { enabled = null, ports = null, rep
145
154
  title: cap.title,
146
155
  description: cap.description,
147
156
  tags: [...cap.tags],
157
+ domain: cap.domain || domain || '',
148
158
  tools: cap.tools.map((tool) => tool.name),
149
159
  })
150
160
  for (const tool of cap.tools) {
151
161
  TOOLS.push({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema })
152
- TOOL_META[tool.name] = { kind: tool.kind, since: tool.since, capability: cap.id }
162
+ TOOL_META[tool.name] = { kind: tool.kind, since: tool.since, capability: cap.id, domain: tool.domain || cap.domain || domain || '' }
153
163
  TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
154
164
  }
155
165
  }
@@ -166,7 +176,28 @@ export function createRegistry(capabilities, { enabled = null, ports = null, rep
166
176
  }),
167
177
  }
168
178
 
169
- return { TOOLS, TOOL_IMPL, TOOL_META, FEATURES, CAPABILITIES, ctx }
179
+ /* 动态增删工具:配合 MCP 活引用(tools/list 读 registry.TOOLS),注册/注销后
180
+ * 客户端重新 list 即见最新工具集,无需重建 handler。旧 registry 是纯静态,
181
+ * 套件热重载/能力开关无法反映到工具面。 */
182
+ function registerTool(tool, capabilityId = '') {
183
+ if (!tool || typeof tool.name !== 'string' || !tool.name) throw new Error('registerTool 需要 tool.name')
184
+ if (typeof tool.handler !== 'function') throw new Error(`工具 ${tool.name} 需要 handler`)
185
+ if (TOOL_IMPL[tool.name]) throw new Error(`工具已存在: ${tool.name}`)
186
+ TOOLS.push({ name: tool.name, description: tool.description || '', inputSchema: tool.inputSchema || { type: 'object', properties: {} } })
187
+ TOOL_META[tool.name] = { kind: tool.kind || 'write', since: tool.since || '1.0.0', capability: capabilityId, domain: tool.domain || domain || '' }
188
+ TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
189
+ return true
190
+ }
191
+ function unregisterTool(name) {
192
+ const index = TOOLS.findIndex((tool) => tool.name === name)
193
+ if (index < 0) return false
194
+ TOOLS.splice(index, 1)
195
+ delete TOOL_IMPL[name]
196
+ delete TOOL_META[name]
197
+ return true
198
+ }
199
+
200
+ return { TOOLS, TOOL_IMPL, TOOL_META, FEATURES, CAPABILITIES, ctx, registerTool, unregisterTool }
170
201
  }
171
202
 
172
203
  /** 与 MCP 工具面解耦:调用前统一校验。 */
@@ -199,21 +230,26 @@ export function createToolDispatcher({ tools, callTool }) {
199
230
  * { tools, callTool }(旧 relay 形态)
200
231
  * @param {{ registry?: object, tools?: Array, toolImpl?: object, callTool?: Function, serverInfo?: object, instructions?: string }} options
201
232
  */
202
- export function createMcpHandler({ registry, tools, toolImpl, callTool, serverInfo, instructions } = {}) {
203
- const list = tools || registry?.TOOLS || []
233
+ export function createMcpHandler({ registry, tools, toolImpl, callTool, serverInfo, instructions, listChanged } = {}) {
234
+ /* registry 形态走活引用:tools/list 每次读 registry.TOOLS,callTool 读 registry.TOOL_IMPL,
235
+ * 于是 registerTool/unregisterTool 的动态增删立刻可见,无需重建 handler。 */
236
+ const useRegistry = !tools && !!registry
204
237
  const impl = toolImpl || registry?.TOOL_IMPL || null
205
- if (!Array.isArray(list) || !list.length) throw new Error('createMcpHandler: 没有工具可暴露')
238
+ const staticList = tools || null
239
+ if (!useRegistry && (!Array.isArray(staticList) || !staticList.length)) throw new Error('createMcpHandler: 没有工具可暴露')
206
240
  if (!impl && typeof callTool !== 'function') throw new Error('createMcpHandler: 需要 toolImpl 或 callTool')
207
241
  return createKitMcpHandler({
208
- tools: list,
242
+ tools: useRegistry ? () => registry.TOOLS : staticList,
209
243
  callTool: (name, args, context) => {
210
244
  if (typeof callTool === 'function' && !impl) return callTool(name, args, context)
211
- const fn = impl[name]
245
+ const source = useRegistry ? registry.TOOL_IMPL : impl
246
+ const fn = source[name]
212
247
  if (!fn) throw new Error(`未知工具: ${name}`)
213
248
  return fn(args, context)
214
249
  },
215
250
  serverInfo: serverInfo || { name: 'dsh-tool-host', version: '0.1.0' },
216
251
  instructions,
252
+ listChanged,
217
253
  })
218
254
  }
219
255
 
@@ -315,17 +351,39 @@ export function buildInstructions({
315
351
  *
316
352
  * @param {object} ctx DSH cordis context
317
353
  * @param {object} registry createRegistry() 的返回值
318
- * @param {{ namespace?: string }} options
354
+ * @param {{ namespace?: string, domain?: string, modeGate?: object }} options
355
+ * domain:本 registry 的兜底领域(工具/能力未各自声明时用);
356
+ * modeGate:会话模式锁闸(createToolHost 服务级自动注入;独立调用可显式传)。
319
357
  * @returns {() => void} 反注册全部工具
320
358
  */
321
- export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
359
+ export function registerWithDsh(ctx, registry, { namespace = '', domain = '', modeGate = null } = {}) {
322
360
  if (!ctx?.tools?.register) throw new Error('registerWithDsh: 当前 DSH 没有 ctx.tools.register')
361
+ /* 领域工具一旦注册即声明给模式锁,并挂全局 guard 兜底(幂等)。
362
+ * install 的引用计数 disposer 必须随本次注册一起释放(旧写法丢弃⇒核心工具/guard 泄漏)。 */
363
+ const gateDispose = modeGate ? modeGate.install(ctx.tools) : null
323
364
  const disposers = []
365
+ if (typeof gateDispose === 'function') disposers.push(gateDispose)
366
+ /* 感知闸补挂(幂等):driver apply 那一刻 systemPrompt 可能尚未就绪,套件注册时再挂一次。
367
+ * 引用计数 disposer 随本次注册一起释放。cordis 服务缺席时访问可能抛错,try 包裹降级。 */
368
+ if (modeGate && typeof modeGate.installPrompt === 'function') {
369
+ let systemPrompt = null
370
+ try { systemPrompt = ctx.systemPrompt } catch { systemPrompt = null }
371
+ if (systemPrompt && typeof systemPrompt.section === 'function') {
372
+ const promptDispose = modeGate.installPrompt(systemPrompt)
373
+ if (typeof promptDispose === 'function') disposers.push(promptDispose)
374
+ }
375
+ }
324
376
  try {
325
377
  for (const tool of registry?.TOOLS || []) {
326
378
  const impl = registry.TOOL_IMPL?.[tool.name]
327
379
  if (typeof impl !== 'function') throw new Error(`registerWithDsh: 工具缺少实现 ${tool.name}`)
328
380
  const name = namespace ? `${namespace}_${tool.name}` : tool.name
381
+ const toolDomain = registry.TOOL_META?.[tool.name]?.domain || domain || ''
382
+ let when
383
+ if (modeGate && toolDomain) {
384
+ modeGate.declareTools(toolDomain, [name])
385
+ when = modeGate.whenFor(name)
386
+ }
329
387
  disposers.push(ctx.tools.register({
330
388
  name,
331
389
  description: tool.description || '',
@@ -338,16 +396,20 @@ export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
338
396
  ? value.content
339
397
  : normalizeToolResult(value).content),
340
398
  },
341
- execute: async (args, exec) => {
399
+ execute: async (args, exec) => runWithCallerSession(exec?.agent?.session?.id, async () => {
342
400
  const normalized = normalizeToolResult(await impl(args, exec))
343
401
  /* DSH 原生面成功恒 isError:false,失败必须 throw 才走错误路径(B 轴 P0-1)。
344
402
  * 把工具自报的 isError:true 转成 throw,与 MCP 面的失败语义对齐。 */
345
403
  if (normalized.isError === true) {
346
404
  throw new Error(resultText(normalized) || `工具 ${name} 执行失败`)
347
405
  }
348
- return normalized
349
- },
350
- }))
406
+ /* 图像准入:裸 base64 图像块(rsp_screen/browser_screenshot 等)必须先持久化成
407
+ * attachment ref 再入 session 日志,否则下一步序列化读 block.attachment.attachmentId
408
+ * 抛错、永久毒化该会话(2026-11-22 根因)。MCP 面不走这里,保留 wire 形态。 */
409
+ const content = await admitToolResultImages(normalized.content, resolveAttachments(exec, ctx), { name })
410
+ return { ...normalized, content }
411
+ }),
412
+ }, when ? { when } : {}))
351
413
  }
352
414
  } catch (error) {
353
415
  /* 全有或全无:任一工具注册失败,逆序释放已注册的,避免部分注册泄漏(B 轴 P0-6)。 */
@@ -366,9 +428,14 @@ export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
366
428
  export function createToolHost(config = {}) {
367
429
  // 跨套件能力发现注册表(互联标准 §A.4/§E)。深度校验器可选注入(suite-kit)。
368
430
  const descriptors = createDescriptorRegistry({ validate: config.validateDescriptor })
431
+ // 会话模式锁:全服务共享一个闸实例(所有套件的注册都经此)。getWorkStore 惰性解析
432
+ // (driver 注入 () => safeGet(ctx,'workStore'));底座缺席则降级为恒可见、不拒。
433
+ const modeGate = createModeGate({ getWorkStore: config.getWorkStore })
369
434
  return {
370
- api: createServiceApi('toolHost', '1.1.0', ['dsl', 'registry', 'validate', 'contract', 'mcp', 'instructions', 'native-tools', 'descriptors']),
371
- version: '0.2.0',
435
+ // M12 对齐:自报以 package.json 为权威——dsh.apiVersion=1.1.0(对外契约,
436
+ // 消费者 assertServiceApi 只断言 major 1),version=0.3.1。旧自报 1.2.0/0.3.0 是漂移。
437
+ api: createServiceApi('toolHost', '1.1.0', ['dsl', 'registry', 'validate', 'contract', 'mcp', 'instructions', 'native-tools', 'descriptors', 'mode-gate']),
438
+ version: '0.3.1',
372
439
  defineTool,
373
440
  defineCapability,
374
441
  createRegistry: (capabilities, options = {}) => createRegistry(capabilities, { ...config, ...options }),
@@ -376,12 +443,16 @@ export function createToolHost(config = {}) {
376
443
  createToolDispatcher,
377
444
  createCapabilityReport,
378
445
  buildInstructions,
379
- registerWithDsh,
446
+ // 服务级注册自动带会话模式锁(when 可见性 + guard 硬拒 + 感知提示 + 调用者会话 ALS),套件零接线。
447
+ registerWithDsh: (ctx, registry, options = {}) => registerWithDsh(ctx, registry, { modeGate, ...options }),
380
448
  validateToolArguments,
449
+ modeGate,
381
450
  // 能力描述符注册/发现(编排器按类型动态发现,套件零互依赖)。
382
451
  registerCapabilityDescriptor: (descriptor, options) => descriptors.register(descriptor, options),
383
452
  unregisterCapabilityDescriptor: (name) => descriptors.unregister(name),
384
- discoverCapabilities: (query) => descriptors.discover(query),
453
+ // 发现面按调用者会话过滤:原生工具调用里自动从 ALS 取会话(conductor_discover 无需接线);
454
+ // HTTP/墙等管理面无会话 → 不过滤(全局视图)。query.sessionId 可显式覆盖。
455
+ discoverCapabilities: (query = {}) => modeGate.filterEntries(descriptors.discover(query), query.sessionId || currentCallerSession()),
385
456
  capabilityCatalog: () => descriptors.catalog(),
386
457
  listSurfaces: () => descriptors.listSurfaces(),
387
458
  }