@capyclaw/capyclaw-workbench 0.1.0 → 0.1.2
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.
- package/README.md +29 -1
- package/lib/host.mjs +84 -80
- package/lib/session-port.mjs +89 -15
- package/lib/session-watch.mjs +82 -0
- package/lib/workspace-attach.mjs +147 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +3 -1
- package/node_modules/@capyclaw/foundation/abi/index.mjs +15 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +8 -1
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +5 -2
- package/node_modules/@capyclaw/foundation/abi/version.mjs +63 -5
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +11 -10
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +8 -1
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +29 -2
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +31 -3
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +12 -2
- package/node_modules/@capyclaw/foundation/package.json +1 -1
- package/node_modules/@capyclaw/plugin-kit/package.json +3 -1
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +3 -82
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +13 -6
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +31 -15
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
- package/node_modules/@capyclaw/service-host/dsh-suite.json +1 -1
- package/node_modules/@capyclaw/service-host/package.json +1 -1
- package/node_modules/@capyclaw/service-host/src/index.mjs +18 -19
- package/node_modules/@capyclaw/suite-kit/README.md +52 -1
- package/node_modules/@capyclaw/suite-kit/package.json +6 -2
- package/node_modules/@capyclaw/suite-kit/src/host.mjs +230 -0
- package/node_modules/@capyclaw/suite-kit/src/index.mjs +14 -0
- package/node_modules/@capyclaw/suite-kit/suite.schema.json +16 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +2 -2
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +34 -4
- package/node_modules/@capyclaw/tool-host/package.json +1 -1
- package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
- package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
- package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +28 -4
- package/node_modules/@capyclaw/tool-host/src/index.mjs +90 -19
- package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
- package/package.json +2 -2
- package/plugin.mjs +17 -1
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 套件宿主脚手架(P1-9「新套件宿主胶水抽共享」):capyclaw/conductor/rsp 三个
|
|
3
|
+
* 「新套件」宿主 lib/host.mjs 的公共胶水收敛到这里,未来新套件按同一 spec 接入。
|
|
4
|
+
*
|
|
5
|
+
* 封装的公共胶水(与三宿主原实现行为等价):
|
|
6
|
+
* 1. safeGet 服务懒解析(ctx.reflect.get 优先,回退 ctx[name],异常→null);
|
|
7
|
+
* 2. toolHost/serviceHost 缺席 bail+warn(降级不崩宿主)+ assertServiceApi major 断言;
|
|
8
|
+
* 3. 路由冲突先 probe 占位再 listen(2026-11-19 崩溃教训:前缀路由全局唯一,
|
|
9
|
+
* service-host app.listen 是 async,冲突变 rejected Promise 逃出 try/catch,
|
|
10
|
+
* 被 cordis 当 load failure 杀掉整个宿主);listen rejection 再 .catch 兜底;
|
|
11
|
+
* 4. 原生工具面 registerWithDsh(safeGet 解析 tools 服务后传平对象);
|
|
12
|
+
* 5. 能力描述符 publish/unpublish(validateCapabilityDescriptor 深度校验);
|
|
13
|
+
* 6. `${mountPath}/__host__` 自检端点(hostInfo 钩子补各套件差异字段);
|
|
14
|
+
* 7. portal.recordActivity(portal 可选);
|
|
15
|
+
* 8. disposers 逆序释放(每个 try/catch,重复释放安全);
|
|
16
|
+
* 9. DIAG 日志 env 门控(CAPYCLAW_WB_DIAG=1 才写 os.tmpdir()/<ns>-diag.log,默认不写盘)。
|
|
17
|
+
*
|
|
18
|
+
* 宿主差异经 spec 钩子注入(prepare/afterListen/afterTools/routes/hostInfo),
|
|
19
|
+
* 钩子拿到的 push() 把 disposer 压入公共栈,释放顺序与手写时代一致。
|
|
20
|
+
*
|
|
21
|
+
* 依赖方向:运行时模块。内部仅 import ./capability.mjs;外部仅
|
|
22
|
+
* @capyclaw/plugin-kit/service/api(纯契约断言,无副作用)。不 import 构建期模块。
|
|
23
|
+
*/
|
|
24
|
+
import fs from 'node:fs'
|
|
25
|
+
import os from 'node:os'
|
|
26
|
+
import path from 'node:path'
|
|
27
|
+
import { assertServiceApi } from '@capyclaw/plugin-kit/service/api'
|
|
28
|
+
import { validateCapabilityDescriptor } from './capability.mjs'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 服务懒解析:cordis 未 inject 的服务直接访问 ctx[name] 可能抛错,
|
|
32
|
+
* 统一走 reflect.get(权威)→ ctx[name](兜底)→ null(缺席降级)。
|
|
33
|
+
* @param {object} ctx cordis 上下文
|
|
34
|
+
* @param {string} serviceName 服务名
|
|
35
|
+
* @returns {object|null}
|
|
36
|
+
*/
|
|
37
|
+
export function safeGet(ctx, serviceName) {
|
|
38
|
+
try { return ctx.reflect?.get?.(serviceName) ?? ctx[serviceName] } catch { return null }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* workStore 可选解析:优先 foundation 的 os.works 能力面(内核 getter 返回
|
|
43
|
+
* work-store 服务或 null),回退 safeGet(ctx,'workStore')。两者皆缺席返回 null,
|
|
44
|
+
* 消费者自行降级内存态(语义与旧 safeGet 裸摸一致)。
|
|
45
|
+
* @param {object} ctx cordis 上下文
|
|
46
|
+
* @returns {object|null}
|
|
47
|
+
*/
|
|
48
|
+
export function resolveWorkStore(ctx) {
|
|
49
|
+
try {
|
|
50
|
+
const osSvc = safeGet(ctx, 'os')
|
|
51
|
+
const works = osSvc ? osSvc.works : null
|
|
52
|
+
if (works) return works
|
|
53
|
+
} catch { /* os.works getter 异常 → 落回裸摸兜底 */ }
|
|
54
|
+
return safeGet(ctx, 'workStore') ?? null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @typedef {object} SuiteHostSpec
|
|
59
|
+
* @property {string} ns 宿主名(如 'conductor-workbench'):__host__.name / portal id /
|
|
60
|
+
* 日志与警告前缀 / diag 文件名 `<ns>-diag.log`。
|
|
61
|
+
* @property {string} suite 套件短名(如 'conductor'):缺服务 bail 警告里的 `<suite>-suite`。
|
|
62
|
+
* @property {string} mountPath 默认挂载前缀(config.mountPath 可覆盖)。
|
|
63
|
+
* @property {string} title portal.recordActivity 标题。
|
|
64
|
+
* @property {Array<{name:string}>} descriptors 本套件描述符清单(释放时逐个 unregister)。
|
|
65
|
+
* @property {(api:HostApi & {extra:object}) => object} createWorkbench 工厂:返回
|
|
66
|
+
* { app, registry, publishDescriptors(baseUrl,{validate}), ... }(各套件 workbench.mjs)。
|
|
67
|
+
* @property {(api:HostApi) => object|false} [prepare] 断言后、建 workbench 前的差异装配
|
|
68
|
+
* (capyclaw 的 sessionPort/session-watch、conductor 的 discoverCapabilities 闸 + workStore)。
|
|
69
|
+
* 返回 false(或 {bail:true})= 放弃挂载(钩子内已自行 warn/diag),返回对象 = extra。
|
|
70
|
+
* @property {(api:HostApi & {workbench:object, extra:object, webServer:object|null}) => void} [afterListen]
|
|
71
|
+
* listen 之后、工具注册之前的钩子(rsp:manager.close disposer + bindToolsToSessionMode)。
|
|
72
|
+
* @property {(api:HostApi & {workbench:object, extra:object, webServer:object|null}) => void} [afterTools]
|
|
73
|
+
* 工具注册之后、描述符发布之前的钩子(rsp:startPersistent)。
|
|
74
|
+
* @property {(args:{webServer:object, workbench:object, extra:object, push:(d:Function)=>void, log:object}) => void} [routes]
|
|
75
|
+
* __host__ 之后的额外固定端点(capyclaw 的 agent-pending/host-pending)。仅 webServer.register 可用时调用。
|
|
76
|
+
* @property {(workbench:object, extra:object) => object} [hostInfo] __host__ 响应附加字段
|
|
77
|
+
* (请求时求值;capyclaw: available、conductor: persisted、rsp: protocol/status)。
|
|
78
|
+
* @property {boolean} [descriptorsRequired] true = 无条件 publish(conductor 已在 prepare
|
|
79
|
+
* 里因缺 discoverCapabilities bail,描述符面必然在场);缺省 = 探测
|
|
80
|
+
* registerCapabilityDescriptor,缺席 warn 跳过(capyclaw/rsp 降级语义)。
|
|
81
|
+
* @property {string} [diagTag] diag 消息短标签(缺省 ns 去掉 '-workbench' 后缀)。
|
|
82
|
+
* @property {(toolHost:object|null) => string} [diagApplyExtra] apply diag 行附加段
|
|
83
|
+
* (conductor 的 ` discover=...`)。
|
|
84
|
+
*/
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 钩子公共参数面。
|
|
88
|
+
* @typedef {object} HostApi
|
|
89
|
+
* @property {object} ctx cordis 上下文
|
|
90
|
+
* @property {object} config 插件配置(mountPath/port/version/...)
|
|
91
|
+
* @property {string} mountPath 生效挂载前缀(config.mountPath || spec.mountPath)
|
|
92
|
+
* @property {object} toolHost 已断言 major 1 的工具宿主服务
|
|
93
|
+
* @property {object} serviceHost 已断言 major 1 的服务宿主服务
|
|
94
|
+
* @property {(ctx:object, name:string) => object|null} safeGet 服务懒解析
|
|
95
|
+
* @property {{info:Function, warn:Function}} log ctx.logger 优先、console 兜底
|
|
96
|
+
* @property {(m:string) => void} diag env 门控诊断日志(默认不写盘)
|
|
97
|
+
* @property {(d:Function) => void} push 压入公共 disposer 栈(逆序释放)
|
|
98
|
+
*/
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 挂载一个套件工作台:返回 disposer(与 cordis apply 契约一致)。
|
|
102
|
+
* 任何失败都降级为 warn + 安全 disposer,绝不把路由冲突/服务缺席升级成宿主崩溃。
|
|
103
|
+
* @param {object} ctx cordis 上下文
|
|
104
|
+
* @param {object} [config] 插件配置
|
|
105
|
+
* @param {SuiteHostSpec} spec 套件差异规格
|
|
106
|
+
* @returns {() => void} disposer(逆序释放全部已登记资源;重复调用安全)
|
|
107
|
+
*/
|
|
108
|
+
export function mountSuiteWorkbench(ctx, config = {}, spec) {
|
|
109
|
+
const { ns, suite, title, descriptors = [], createWorkbench } = spec
|
|
110
|
+
const tag = spec.diagTag || String(ns || '').replace(/-workbench$/, '')
|
|
111
|
+
/* 诊断日志默认关闭;设 CAPYCLAW_WB_DIAG=1 时写到系统临时目录(不硬编码任何本机路径)。 */
|
|
112
|
+
const DIAG_LOG = process.env.CAPYCLAW_WB_DIAG ? path.join(os.tmpdir(), `${ns}-diag.log`) : null
|
|
113
|
+
const diag = (m) => { if (!DIAG_LOG) return; try { fs.appendFileSync(DIAG_LOG, `[${new Date().toISOString()}] ${m}\n`) } catch { /* 忽略 */ } }
|
|
114
|
+
const log = {
|
|
115
|
+
info: (...a) => (ctx.logger?.info ? ctx.logger.info(...a) : console.log(`[${tag}]`, ...a)),
|
|
116
|
+
warn: (...a) => (ctx.logger?.warn ? ctx.logger.warn(...a) : console.warn(`[${tag}]`, ...a)),
|
|
117
|
+
}
|
|
118
|
+
const mountPath = config.mountPath || spec.mountPath
|
|
119
|
+
const disposers = []
|
|
120
|
+
const push = (d) => { if (typeof d === 'function') disposers.push(d) }
|
|
121
|
+
// splice(0) 清空栈再逆序:首次释放顺序与手写时代一致,重复释放是真 no-op
|
|
122
|
+
// (原 disposers.reverse() 原地反转,二次调用会重跑——与「忽略重复释放」注释意图相悖)。
|
|
123
|
+
const releaseAll = () => { for (const d of disposers.splice(0).reverse()) { try { d() } catch { /* 忽略重复释放 */ } } }
|
|
124
|
+
const noop = () => {}
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
if (!ns || !suite || !mountPath || !title || typeof createWorkbench !== 'function') {
|
|
128
|
+
throw new Error('mountSuiteWorkbench: spec 需要 ns/suite/mountPath/title/createWorkbench')
|
|
129
|
+
}
|
|
130
|
+
const toolHost = safeGet(ctx, 'toolHost')
|
|
131
|
+
const serviceHost = safeGet(ctx, 'serviceHost')
|
|
132
|
+
diag(`${tag} apply: toolHost=${!!toolHost} serviceHost=${!!serviceHost} webServer=${!!safeGet(ctx, 'webServer')} reflect=${!!ctx.reflect}${spec.diagApplyExtra ? spec.diagApplyExtra(toolHost) : ''}`)
|
|
133
|
+
if (!toolHost || !serviceHost) {
|
|
134
|
+
diag(`${tag} BAIL: missing toolHost/serviceHost`)
|
|
135
|
+
log.warn(`缺少 toolHost/serviceHost 公共服务,${suite}-suite 未激活(请安装对应基础套件)`)
|
|
136
|
+
return noop
|
|
137
|
+
}
|
|
138
|
+
assertServiceApi(toolHost, { name: 'toolHost', major: 1 })
|
|
139
|
+
assertServiceApi(serviceHost, { name: 'serviceHost', major: 1 })
|
|
140
|
+
|
|
141
|
+
/** @type {HostApi} */
|
|
142
|
+
const api = { ctx, config, mountPath, toolHost, serviceHost, safeGet, log, diag, push }
|
|
143
|
+
let extra = {}
|
|
144
|
+
if (spec.prepare) {
|
|
145
|
+
const prepared = spec.prepare(api)
|
|
146
|
+
if (prepared === false || (prepared && prepared.bail === true)) return noop
|
|
147
|
+
if (prepared && typeof prepared === 'object') extra = prepared
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const workbench = createWorkbench({ ...api, extra })
|
|
151
|
+
|
|
152
|
+
const webServer = safeGet(ctx, 'webServer')
|
|
153
|
+
|
|
154
|
+
// 前缀路由是全局唯一的(dsh-host-webserver 的 register 遇到同 (kind,path) 直接抛)。
|
|
155
|
+
// service-host 的 app.listen 是 async:冲突会变成 rejected Promise,而不是同步抛错。
|
|
156
|
+
// 不 await、也不 .catch 的话,冲突逃出外层 try/catch,被 cordis 当成 load failure
|
|
157
|
+
// 杀掉整个宿主(2026-11-19 两次:安全模式回滚把用户 patch 层清空)。
|
|
158
|
+
// 先探一次占位,冲突就只警告并退出本条目,绝不把路由冲突升级成宿主崩溃。
|
|
159
|
+
if (webServer && typeof webServer.register === 'function') {
|
|
160
|
+
let taken = false
|
|
161
|
+
try {
|
|
162
|
+
const probe = webServer.register({ kind: 'prefix', path: mountPath, handler: () => {} })
|
|
163
|
+
if (typeof probe === 'function') probe()
|
|
164
|
+
} catch {
|
|
165
|
+
taken = true
|
|
166
|
+
}
|
|
167
|
+
if (taken) {
|
|
168
|
+
diag(`${tag} BAIL: prefix ${mountPath} already registered`)
|
|
169
|
+
log.warn(`${ns}: 路由前缀 ${mountPath} 已被占用,本条目不挂载(不影响其它插件)`)
|
|
170
|
+
return noop
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const listenOpts = webServer ? { webServer, basePath: mountPath } : { port: config.port || 0 }
|
|
175
|
+
const listening = workbench.app.listen(listenOpts)
|
|
176
|
+
// 兜底:即使上面的探测有竞态,也把 rejection 收在这里,不让它变成未处理拒绝。
|
|
177
|
+
if (listening && typeof listening.catch === 'function') {
|
|
178
|
+
listening.catch((err) => {
|
|
179
|
+
diag(`${tag} listen rejected: ${err?.stack || err}`)
|
|
180
|
+
log.warn(`${ns}: 挂载 ${mountPath} 失败,本条目不生效:`, err?.message || err)
|
|
181
|
+
try { workbench.app.close() } catch { /* 忽略 */ }
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
push(() => workbench.app.close())
|
|
185
|
+
|
|
186
|
+
if (spec.afterListen) spec.afterListen({ ...api, workbench, extra, webServer })
|
|
187
|
+
|
|
188
|
+
// 原生工具面:safeGet 解析 tools 服务后传平对象,避免 cordis 未 inject 禁访问 ctx.tools。
|
|
189
|
+
const tools = safeGet(ctx, 'tools')
|
|
190
|
+
if (tools?.register) {
|
|
191
|
+
const { registerWithDsh } = toolHost
|
|
192
|
+
push(registerWithDsh({ tools }, workbench.registry))
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (spec.afterTools) spec.afterTools({ ...api, workbench, extra, webServer })
|
|
196
|
+
|
|
197
|
+
// 能力描述符 + 调用地址 → 公共注册表(供 conductor 发现)。
|
|
198
|
+
if (spec.descriptorsRequired || typeof toolHost.registerCapabilityDescriptor === 'function') {
|
|
199
|
+
workbench.publishDescriptors(workbench.app.url, { validate: validateCapabilityDescriptor })
|
|
200
|
+
push(() => { for (const d of descriptors) toolHost.unregisterCapabilityDescriptor?.(d.name) })
|
|
201
|
+
} else {
|
|
202
|
+
log.warn(`toolHost 无描述符面(需 >=0.2.0):跳过能力注册,conductor 将无法发现 ${suite}`)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// 自检端点。
|
|
206
|
+
if (webServer?.register) {
|
|
207
|
+
const off = webServer.register({
|
|
208
|
+
kind: 'exact', path: `${mountPath}/__host__`,
|
|
209
|
+
handler: (req, res) => {
|
|
210
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
211
|
+
res.end(JSON.stringify({ ok: true, name: ns, mountPath, url: workbench.app.url, ...(spec.hostInfo ? spec.hostInfo(workbench, extra) : {}) }))
|
|
212
|
+
},
|
|
213
|
+
})
|
|
214
|
+
push(off)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if (spec.routes && webServer?.register) spec.routes({ webServer, workbench, extra, push, log })
|
|
218
|
+
|
|
219
|
+
const portal = safeGet(ctx, 'portal')
|
|
220
|
+
portal?.recordActivity?.({ id: ns, url: workbench.app.url, title, kind: 'service' })
|
|
221
|
+
|
|
222
|
+
log.info(`${ns} 已挂载 ${mountPath} → ${workbench.app.url}`)
|
|
223
|
+
diag(`${tag} MOUNTED ${mountPath} → ${workbench.app.url}`)
|
|
224
|
+
return releaseAll
|
|
225
|
+
} catch (err) {
|
|
226
|
+
diag(`${tag} ERROR: ${err?.stack || err}`)
|
|
227
|
+
log.warn(`${ns} 激活失败:`, err?.stack || err)
|
|
228
|
+
return releaseAll
|
|
229
|
+
}
|
|
230
|
+
}
|
|
@@ -1,8 +1,22 @@
|
|
|
1
|
+
// @capyclaw/suite-kit 主入口(P2-12:双重身份显式文档化,暂不拆包)。
|
|
2
|
+
// 本包同时是:
|
|
3
|
+
// 构建期库 —— manifest/compose/profile/domain/artifacts/activation-registry
|
|
4
|
+
// (清单校验、组合、profile 安装、领域解析、artifact 打包);
|
|
5
|
+
// 运行时库 —— capability/orchestration/embed/surface/host(能力描述符、编排闸/Mandate/
|
|
6
|
+
// 事件、嵌入握手、surface 挂载、套件宿主脚手架),被 capyclaw/rsp/conductor 等
|
|
7
|
+
// 套件工作台在运行时 import。
|
|
8
|
+
// 依赖方向严格单向:运行时模块绝不 import 构建期模块(运行时内部 surface → embed、
|
|
9
|
+
// host → capability;host 另依赖 @capyclaw/plugin-kit/service/api 纯契约断言)。
|
|
10
|
+
// 根入口 export * 同时导出两类;运行时消费者应优先走子路径(./capability 等),
|
|
11
|
+
// 避免把构建期代码拉进运行时依赖图。
|
|
12
|
+
// 为什么不拆:拆包会破坏 9 个项目的 import 面,收益不抵成本;
|
|
13
|
+
// 决策记录与模块归属清单见 README「双重身份:构建期库 + 运行时库」。
|
|
1
14
|
export * from './manifest.mjs'
|
|
2
15
|
export * from './capability.mjs'
|
|
3
16
|
export * from './orchestration.mjs'
|
|
4
17
|
export * from './embed.mjs'
|
|
5
18
|
export * from './surface.mjs'
|
|
19
|
+
export * from './host.mjs'
|
|
6
20
|
export * from './compose.mjs'
|
|
7
21
|
export * from './profile.mjs'
|
|
8
22
|
export * from './domain.mjs'
|
|
@@ -54,6 +54,22 @@
|
|
|
54
54
|
"additionalProperties": { "type": "string", "minLength": 1 }
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
+
},
|
|
58
|
+
"surfaceLifecycle": {
|
|
59
|
+
"type": "object",
|
|
60
|
+
"additionalProperties": false,
|
|
61
|
+
"required": ["hooks", "headlessObservation"],
|
|
62
|
+
"description": "表面可见性生命周期标准声明(docs/SURFACE-LIFECYCLE-STANDARD.md §6):四个渲染面钩子齐全 + 无头观察兜底。协议真源 C/packages/capyclaw-foundation/abi/visibility.mjs。",
|
|
63
|
+
"properties": {
|
|
64
|
+
"hooks": {
|
|
65
|
+
"type": "array",
|
|
66
|
+
"items": { "enum": ["onVisibility", "suspendRender", "resumeRender", "rehydrate"] },
|
|
67
|
+
"minItems": 4,
|
|
68
|
+
"maxItems": 4,
|
|
69
|
+
"uniqueItems": true
|
|
70
|
+
},
|
|
71
|
+
"headlessObservation": { "const": true }
|
|
72
|
+
}
|
|
57
73
|
}
|
|
58
74
|
}
|
|
59
75
|
}
|
|
@@ -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.
|
|
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
|
|
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
|
-
|
|
14
|
-
|
|
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
|
+
})
|
|
@@ -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:
|
|
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 && !
|
|
96
|
-
if (query.consumes && !
|
|
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
|