@capyclaw/publisher 0.1.3 → 0.1.5
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/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/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/memory.mjs +29 -2
- 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 +1 -1
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +3 -82
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +2 -2
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +25 -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/index.mjs +47 -14
- package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +214 -0
- package/package.json +2 -2
- package/server/archive.mjs +69 -35
- package/server/drop.mjs +9 -3
- package/server/impl.mjs +141 -95
- package/server/tools.mjs +1 -1
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { ABI_MAJOR, getInterfaceKind } from './kinds.mjs'
|
|
3
3
|
import { validateInterface } from './validate.mjs'
|
|
4
4
|
import { AbiError, ERROR_CODES, toAbiError } from './errors.mjs'
|
|
5
|
-
import { satisfies } from './version.mjs'
|
|
5
|
+
import { satisfies, isValidRange } from './version.mjs'
|
|
6
6
|
|
|
7
7
|
const thenable = (value) => value && typeof value.then === 'function'
|
|
8
8
|
|
|
@@ -164,6 +164,13 @@ export function createLoader({ adapters = {}, capabilities = {}, log = null, abi
|
|
|
164
164
|
plugins.delete(spec.name)
|
|
165
165
|
void previous.handle?.dispose?.()
|
|
166
166
|
}
|
|
167
|
+
/* 非法范围单独报 E_SCHEMA:旧实现把「range 写错」和「能力真缺」都归成
|
|
168
|
+
* E_CAP_MISSING「能力不可用」,误导排障。先区分两者。 */
|
|
169
|
+
const badRanges = spec.requires.filter((need) => need.name.startsWith('os.') && !isValidRange(need.range))
|
|
170
|
+
if (badRanges.length) {
|
|
171
|
+
throw error(ERROR_CODES.E_SCHEMA, `插件 ${spec.name} 能力范围非法:${badRanges.map((r) => r.raw).join(', ')}`,
|
|
172
|
+
{ plugin: spec.name, invalid: badRanges })
|
|
173
|
+
}
|
|
167
174
|
const missing = spec.requires.filter((need) => need.name.startsWith('os.')
|
|
168
175
|
&& !satisfies(capabilityMap()[need.name] || '', need.range))
|
|
169
176
|
if (missing.length) {
|
|
@@ -191,9 +191,12 @@ export function definePlugin(options = {}) {
|
|
|
191
191
|
const requiresEntries = requires.map((entry) => parseCapability(entry, 'requires'))
|
|
192
192
|
const providesEntries = provides.map((entry) => parseCapability(entry, 'provides'))
|
|
193
193
|
for (const entry of providesEntries) {
|
|
194
|
-
|
|
194
|
+
/* 白名单而非黑名单:provides 必须是完整 x.y.z(可带 prerelease)。旧实现只拒
|
|
195
|
+
* ^~<>= 前缀,'1.x' / '1.*' / 裸 '1' 漏网被当成版本发布,消费方 parseVersion
|
|
196
|
+
* 解析不了 → satisfies 恒 false,能力永远「不可用」。 */
|
|
197
|
+
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(entry.range)) {
|
|
195
198
|
throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE,
|
|
196
|
-
`provides
|
|
199
|
+
`provides 必须写精确版本(x.y.z),不能写范围:${entry.raw}`, { entry: entry.raw })
|
|
197
200
|
}
|
|
198
201
|
}
|
|
199
202
|
|
|
@@ -2,25 +2,57 @@
|
|
|
2
2
|
* 版本与范围:能力声明用 `^1` / `^1.2.0` / `>=1.2` / `1.x` / 精确版本。
|
|
3
3
|
*
|
|
4
4
|
* 只实现这份 ABI 需要的语义,不引入 semver 依赖:
|
|
5
|
-
* - `^1.2.3` → >=1.2.3 且同主版本;`^0.2.3` → >=0.2.3
|
|
5
|
+
* - `^1.2.3` → >=1.2.3 且同主版本;`^0.2.3` → >=0.2.3 且同次版本;
|
|
6
|
+
* `^0.0.3` → >=0.0.3 且同补丁(0.0.x 约定,semver 标准)
|
|
6
7
|
* - `~1.2.3` → >=1.2.3 且同次版本
|
|
7
8
|
* - `1.x` / `1.*` → 同主版本
|
|
8
9
|
* - `>=` `>` `<=` `<` `=` 前缀
|
|
9
10
|
* - 裸版本 → 精确匹配(比较时忽略末位 0)
|
|
11
|
+
* - prerelease 保留并参与比较:1.0.0-beta < 1.0.0;带 prerelease 的版本只满足
|
|
12
|
+
* 同 [major,minor,patch] 且同样带 prerelease 的范围(semver 标准,避免预发布
|
|
13
|
+
* 版本被当成正式版本放行)。
|
|
10
14
|
*/
|
|
11
15
|
|
|
12
16
|
export function parseVersion(text) {
|
|
13
17
|
if (typeof text !== 'string') return null
|
|
14
|
-
const match = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?$/.exec(text.trim())
|
|
18
|
+
const match = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(text.trim())
|
|
15
19
|
if (!match) return null
|
|
16
|
-
|
|
20
|
+
const parts = [Number(match[1]), Number(match[2] || 0), Number(match[3] || 0)]
|
|
21
|
+
parts.prerelease = match[4] || null
|
|
22
|
+
return parts
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function comparePrerelease(a, b) {
|
|
26
|
+
/* 无 prerelease > 有 prerelease(1.0.0 > 1.0.0-beta)。 */
|
|
27
|
+
if (!a && !b) return 0
|
|
28
|
+
if (!a) return 1
|
|
29
|
+
if (!b) return -1
|
|
30
|
+
const left = a.split('.')
|
|
31
|
+
const right = b.split('.')
|
|
32
|
+
for (let i = 0; i < Math.max(left.length, right.length); i++) {
|
|
33
|
+
const x = left[i]
|
|
34
|
+
const y = right[i]
|
|
35
|
+
if (x === undefined) return -1
|
|
36
|
+
if (y === undefined) return 1
|
|
37
|
+
const xn = /^\d+$/.test(x)
|
|
38
|
+
const yn = /^\d+$/.test(y)
|
|
39
|
+
if (xn && yn) {
|
|
40
|
+
const d = Number(x) - Number(y)
|
|
41
|
+
if (d !== 0) return d < 0 ? -1 : 1
|
|
42
|
+
} else if (xn !== yn) {
|
|
43
|
+
return xn ? -1 : 1 // 数字标识符 < 字母数字标识符
|
|
44
|
+
} else if (x !== y) {
|
|
45
|
+
return x < y ? -1 : 1
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return 0
|
|
17
49
|
}
|
|
18
50
|
|
|
19
51
|
function compareParts(a, b) {
|
|
20
52
|
for (let i = 0; i < 3; i++) {
|
|
21
53
|
if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
|
|
22
54
|
}
|
|
23
|
-
return
|
|
55
|
+
return comparePrerelease(a.prerelease || null, b.prerelease || null)
|
|
24
56
|
}
|
|
25
57
|
|
|
26
58
|
export function compareVersions(a, b) {
|
|
@@ -44,12 +76,23 @@ export function satisfies(version, range) {
|
|
|
44
76
|
if (raw.startsWith('^')) {
|
|
45
77
|
const base = parseVersion(raw.slice(1))
|
|
46
78
|
if (!base) return false
|
|
79
|
+
/* prerelease 只满足同 [major,minor,patch] 且带 prerelease 的范围(semver 标准),
|
|
80
|
+
* 避免 1.1.0-beta 被 ^1.0.0 当正式版本放行。 */
|
|
81
|
+
if (current.prerelease && (!base.prerelease
|
|
82
|
+
|| current[0] !== base[0] || current[1] !== base[1] || current[2] !== base[2])) return false
|
|
47
83
|
if (compareParts(current, base) < 0) return false
|
|
48
|
-
|
|
84
|
+
if (base[0] === 0) {
|
|
85
|
+
/* 0.0.x caret 收紧到补丁位:^0.0.3 只容 0.0.3,不容 0.0.9。 */
|
|
86
|
+
if (base[1] === 0) return current[0] === 0 && current[1] === 0 && current[2] === base[2]
|
|
87
|
+
return current[0] === 0 && current[1] === base[1]
|
|
88
|
+
}
|
|
89
|
+
return current[0] === base[0]
|
|
49
90
|
}
|
|
50
91
|
if (raw.startsWith('~')) {
|
|
51
92
|
const base = parseVersion(raw.slice(1))
|
|
52
93
|
if (!base) return false
|
|
94
|
+
if (current.prerelease && (!base.prerelease
|
|
95
|
+
|| current[0] !== base[0] || current[1] !== base[1] || current[2] !== base[2])) return false
|
|
53
96
|
return compareParts(current, base) >= 0 && current[0] === base[0] && current[1] === base[1]
|
|
54
97
|
}
|
|
55
98
|
if (raw.startsWith('>=')) {
|
|
@@ -80,3 +123,18 @@ export function satisfies(version, range) {
|
|
|
80
123
|
const exact = parseVersion(raw)
|
|
81
124
|
return Boolean(exact) && compareParts(current, exact) === 0
|
|
82
125
|
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 范围是否「语义合法」(区别于「合法但不满足」)。供加载器把非法范围单独报
|
|
129
|
+
* E_SCHEMA,而不是误归因成「能力不可用」误导排障。空范围视为「任意」,合法。
|
|
130
|
+
*/
|
|
131
|
+
export function isValidRange(range) {
|
|
132
|
+
const raw = String(range ?? '').trim()
|
|
133
|
+
if (!raw || raw === '*' || raw === 'x') return true
|
|
134
|
+
if (/^[\^~]/.test(raw)) return Boolean(parseVersion(raw.slice(1)))
|
|
135
|
+
if (/^(>=|<=)/.test(raw)) return Boolean(parseVersion(raw.slice(2)))
|
|
136
|
+
if (/^[><]/.test(raw)) return Boolean(parseVersion(raw.slice(1)))
|
|
137
|
+
if (raw.startsWith('=')) return isValidRange(raw.slice(1))
|
|
138
|
+
if (/^(\d+)(?:\.(\d+))?\.[x*]$/.test(raw)) return true
|
|
139
|
+
return Boolean(parseVersion(raw))
|
|
140
|
+
}
|
|
@@ -44,18 +44,19 @@ export function createRawAdapter({ log }) {
|
|
|
44
44
|
|
|
45
45
|
if (thenable(result)) {
|
|
46
46
|
let instance = {}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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: () =>
|
|
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
|
-
|
|
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
|
|
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
|
}
|
|
@@ -11,6 +11,10 @@ import { BASE_CAPABILITIES } from './caps.mjs'
|
|
|
11
11
|
|
|
12
12
|
const NOOP_LOG = { debug() {}, info() {}, warn() {}, error() {} }
|
|
13
13
|
|
|
14
|
+
/* 内存宿主也要有界:app 不 dispose、asset 只 put 不 delete 的用法会让数组/Map
|
|
15
|
+
* 无限增长。app 提供 dispose() 摘除自己;assets 提供 delete() 与上限 LRU 淘汰。 */
|
|
16
|
+
const DEFAULT_MAX_ASSETS = 1024
|
|
17
|
+
|
|
14
18
|
export function createMemoryHost(options = {}) {
|
|
15
19
|
const state = {
|
|
16
20
|
providers: [],
|
|
@@ -24,6 +28,9 @@ export function createMemoryHost(options = {}) {
|
|
|
24
28
|
plugins: [],
|
|
25
29
|
}
|
|
26
30
|
const log = options.log ?? NOOP_LOG
|
|
31
|
+
const maxAssets = Number(options.maxAssets) > 0 ? Number(options.maxAssets) : DEFAULT_MAX_ASSETS
|
|
32
|
+
/* 单调序号:不能用 size+1 拼 id——淘汰后 size 回落,同毫秒内会撞掉已有资产。 */
|
|
33
|
+
let assetSeq = 0
|
|
27
34
|
|
|
28
35
|
function http() {
|
|
29
36
|
return {
|
|
@@ -41,6 +48,11 @@ export function createMemoryHost(options = {}) {
|
|
|
41
48
|
}
|
|
42
49
|
},
|
|
43
50
|
async dispatch() {},
|
|
51
|
+
dispose() {
|
|
52
|
+
const index = state.apps.indexOf(app)
|
|
53
|
+
if (index >= 0) state.apps.splice(index, 1)
|
|
54
|
+
routes.length = 0
|
|
55
|
+
},
|
|
44
56
|
}
|
|
45
57
|
state.apps.push(app)
|
|
46
58
|
return app
|
|
@@ -149,12 +161,27 @@ export function createMemoryHost(options = {}) {
|
|
|
149
161
|
}),
|
|
150
162
|
assets: () => ({
|
|
151
163
|
async put(value, contentType = 'application/octet-stream') {
|
|
152
|
-
const id = `asset-${state.assets.size + 1}`
|
|
153
164
|
const buffer = Buffer.isBuffer(value) ? value : Buffer.from(String(value))
|
|
165
|
+
/* Map 保持插入序:超限淘汰最旧(LRU 近似),get 命中会刷新到队尾。 */
|
|
166
|
+
while (state.assets.size >= maxAssets) {
|
|
167
|
+
const oldest = state.assets.keys().next().value
|
|
168
|
+
state.assets.delete(oldest)
|
|
169
|
+
}
|
|
170
|
+
const id = `asset-${++assetSeq}`
|
|
154
171
|
state.assets.set(id, { data: buffer, contentType })
|
|
155
172
|
return { id, url: `/assets/${id}`, size: buffer.length, contentType }
|
|
156
173
|
},
|
|
157
|
-
get(id) {
|
|
174
|
+
get(id) {
|
|
175
|
+
const entry = state.assets.get(id)
|
|
176
|
+
if (entry) { state.assets.delete(id); state.assets.set(id, entry) }
|
|
177
|
+
return entry
|
|
178
|
+
},
|
|
179
|
+
delete(id) { return state.assets.delete(id) },
|
|
180
|
+
gc() {
|
|
181
|
+
const removed = state.assets.size
|
|
182
|
+
state.assets.clear()
|
|
183
|
+
return { removed }
|
|
184
|
+
},
|
|
158
185
|
}),
|
|
159
186
|
}
|
|
160
187
|
}
|
|
@@ -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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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`)
|
|
@@ -91,7 +91,11 @@ export function createNet(host, config = {}) {
|
|
|
91
91
|
}
|
|
92
92
|
return
|
|
93
93
|
}
|
|
94
|
-
await new Promise((resolve) =>
|
|
94
|
+
await new Promise((resolve) => {
|
|
95
|
+
/* unref:迟到补挂的轮询定时器不得拖住进程退出(最长 60s 的尾延迟)。 */
|
|
96
|
+
const timer = setTimeout(resolve, WEB_LATE_POLL_MS)
|
|
97
|
+
timer.unref?.()
|
|
98
|
+
})
|
|
95
99
|
}
|
|
96
100
|
})().catch(() => {})
|
|
97
101
|
}
|
|
@@ -116,7 +120,10 @@ export function createNet(host, config = {}) {
|
|
|
116
120
|
if (!web && shouldWaitForWeb()) {
|
|
117
121
|
const deadline = Date.now() + WEB_WAIT_MS
|
|
118
122
|
while (!web && Date.now() < deadline && !closed) {
|
|
119
|
-
await new Promise((resolve) =>
|
|
123
|
+
await new Promise((resolve) => {
|
|
124
|
+
const timer = setTimeout(resolve, WEB_POLL_MS)
|
|
125
|
+
timer.unref?.()
|
|
126
|
+
})
|
|
120
127
|
web = webServer()
|
|
121
128
|
}
|
|
122
129
|
}
|
|
@@ -140,6 +147,9 @@ export function createNet(host, config = {}) {
|
|
|
140
147
|
disposal = (async () => {
|
|
141
148
|
if (!sharedHost) return
|
|
142
149
|
// listen 失败由 ready/start 报告;清理仍需执行,且 close 失败不能被吞掉。
|
|
150
|
+
// 注意:dispose 在 listen 失败时仍 RESOLVE(错误经 ready/start 上报)——这是
|
|
151
|
+
// 被 network-lifecycle 测试固化的契约,close 不再二次上抛 listen 错,避免
|
|
152
|
+
// 破坏「清理成功即 dispose 成功」的语义。
|
|
143
153
|
await listening.catch(() => {})
|
|
144
154
|
// 迟到补挂的路由要一起撤掉,否则共享宿主关了、宿主网页端口上还留着分发器。
|
|
145
155
|
try {
|
|
@@ -6,8 +6,9 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { tuning } from '../tuning.mjs'
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
/* 与文档 owner 租约(document-workbench OWNER_TTL)对齐为 10s:
|
|
10
|
+
* 两条租约线共用「心跳 3s、TTL 10s」的并发协议,避免编辑器判活比文档慢半拍。 */
|
|
11
|
+
const DEFAULT_TTL = 10 // 秒
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* 创建编辑器租约仲裁器。
|
|
@@ -57,83 +58,3 @@ export function createEditorLease(opts = {}) {
|
|
|
57
58
|
},
|
|
58
59
|
}
|
|
59
60
|
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* 编辑器端自动挂接循环。
|
|
63
|
-
* 首次 claim 强制抢占(后打开者赢),之后静默心跳。
|
|
64
|
-
* @param {{
|
|
65
|
-
* clientId: string,
|
|
66
|
-
* claim: (force: boolean) => Promise<boolean>,
|
|
67
|
-
* release?: () => void,
|
|
68
|
-
* onActive?: () => void,
|
|
69
|
-
* onStandby?: () => void,
|
|
70
|
-
* retryMs?: number,
|
|
71
|
-
* heartbeatMs?: number,
|
|
72
|
-
* setInterval?: (cb: () => void) => any,
|
|
73
|
-
* clearInterval?: (handle: any) => void
|
|
74
|
-
* }} o
|
|
75
|
-
*/
|
|
76
|
-
export function startAutoAttach(o) {
|
|
77
|
-
if (!o || !o.clientId) throw new Error('startAutoAttach: clientId 必填')
|
|
78
|
-
if (typeof o.claim !== 'function') throw new Error('startAutoAttach: claim 必须是函数')
|
|
79
|
-
|
|
80
|
-
const retryMs = o.retryMs || 1000
|
|
81
|
-
const heartbeatMs = o.heartbeatMs || DEFAULT_HEARTBEAT * 1000
|
|
82
|
-
const setI = o.setInterval || ((cb) => setInterval(cb, heartbeatMs))
|
|
83
|
-
const clearI = o.clearInterval || ((handle) => clearInterval(handle))
|
|
84
|
-
|
|
85
|
-
let active = false
|
|
86
|
-
let heartbeat = null
|
|
87
|
-
let disposed = false
|
|
88
|
-
|
|
89
|
-
async function tryClaim(force) {
|
|
90
|
-
try {
|
|
91
|
-
return await o.claim(force)
|
|
92
|
-
} catch {
|
|
93
|
-
return false
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
function goActive() {
|
|
98
|
-
if (active) return
|
|
99
|
-
active = true
|
|
100
|
-
try { o.onActive && o.onActive() } catch { /* 用户回调失败不阻塞挂接 */ }
|
|
101
|
-
heartbeat = setI(async () => {
|
|
102
|
-
if (disposed) return
|
|
103
|
-
const ok = await tryClaim(false)
|
|
104
|
-
if (!ok) goStandby()
|
|
105
|
-
})
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
function goStandby() {
|
|
109
|
-
if (!active) return
|
|
110
|
-
active = false
|
|
111
|
-
if (heartbeat != null) {
|
|
112
|
-
clearI(heartbeat)
|
|
113
|
-
heartbeat = null
|
|
114
|
-
}
|
|
115
|
-
try { o.onStandby && o.onStandby() } catch { /* 静默 */ }
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
;(async () => {
|
|
119
|
-
let first = true
|
|
120
|
-
while (!disposed) {
|
|
121
|
-
const ok = await tryClaim(first)
|
|
122
|
-
first = false
|
|
123
|
-
if (ok) {
|
|
124
|
-
goActive()
|
|
125
|
-
return
|
|
126
|
-
}
|
|
127
|
-
await new Promise((resolve) => setTimeout(resolve, retryMs))
|
|
128
|
-
}
|
|
129
|
-
})()
|
|
130
|
-
|
|
131
|
-
return {
|
|
132
|
-
get active() { return active },
|
|
133
|
-
dispose() {
|
|
134
|
-
disposed = true
|
|
135
|
-
goStandby()
|
|
136
|
-
try { o.release && o.release() } catch { /* 释放失败不阻塞退出 */ }
|
|
137
|
-
},
|
|
138
|
-
}
|
|
139
|
-
}
|
|
@@ -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.
|
|
10
|
+
"version": "^0.3.1",
|
|
11
11
|
"path": ".",
|
|
12
12
|
"provides": {
|
|
13
13
|
"services": [
|
|
@@ -1,16 +1,37 @@
|
|
|
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
|
+
* 核心工具与 guard 的注册统一走 modeGate.install(tools)(幂等):apply 时 best-effort 挂一次,
|
|
9
|
+
* 若那一刻 tools 服务尚未就绪,首个套件注册(registerWithDsh / bridge host)会再调 install 补上,
|
|
10
|
+
* 故不依赖加载顺序。所有经 toolHost.registerWithDsh / bridge host 注册的领域能力自动受锁约束,套件零接线。
|
|
3
11
|
*/
|
|
4
12
|
import { defineDriver } from '@capyclaw/foundation/abi'
|
|
5
13
|
import { createToolHost } from '../src/index.mjs'
|
|
6
14
|
|
|
15
|
+
const safeGet = (ctx, name) => {
|
|
16
|
+
try { return ctx.reflect?.get?.(name) ?? ctx[name] } catch { return null }
|
|
17
|
+
}
|
|
18
|
+
|
|
7
19
|
export const { name, inject, apply } = defineDriver({
|
|
8
20
|
name: 'tool-host',
|
|
9
21
|
service: 'toolHost',
|
|
10
22
|
apply(ctx, config = {}) {
|
|
11
|
-
const service = createToolHost(config)
|
|
23
|
+
const service = createToolHost({ ...config, getWorkStore: () => safeGet(ctx, 'workStore') })
|
|
12
24
|
const dispose = ctx.provide('toolHost', service)
|
|
13
|
-
|
|
14
|
-
|
|
25
|
+
|
|
26
|
+
/* 模式锁兜底闸 + 核心锁定工具(幂等)。tools 缺席则降级:稍后套件注册时经 install 补挂。
|
|
27
|
+
* install 返回引用计数 disposer,必须随 driver 卸载释放,否则核心工具/guard 永驻。 */
|
|
28
|
+
const tools = safeGet(ctx, 'tools')
|
|
29
|
+
const gateDispose = (tools && typeof tools.register === 'function') ? service.modeGate.install(tools) : null
|
|
30
|
+
|
|
31
|
+
console.log('[tool-host] ready (mode-gate enabled)')
|
|
32
|
+
return () => {
|
|
33
|
+
if (typeof gateDispose === 'function') gateDispose()
|
|
34
|
+
if (typeof dispose === 'function') dispose()
|
|
35
|
+
}
|
|
15
36
|
},
|
|
16
|
-
})
|
|
37
|
+
})
|
|
@@ -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
|
+
}
|