@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
|
@@ -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
|
}
|
|
@@ -174,7 +184,7 @@ export function createRegistry(capabilities, { enabled = null, ports = null, rep
|
|
|
174
184
|
if (typeof tool.handler !== 'function') throw new Error(`工具 ${tool.name} 需要 handler`)
|
|
175
185
|
if (TOOL_IMPL[tool.name]) throw new Error(`工具已存在: ${tool.name}`)
|
|
176
186
|
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 }
|
|
187
|
+
TOOL_META[tool.name] = { kind: tool.kind || 'write', since: tool.since || '1.0.0', capability: capabilityId, domain: tool.domain || domain || '' }
|
|
178
188
|
TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
|
|
179
189
|
return true
|
|
180
190
|
}
|
|
@@ -341,17 +351,29 @@ export function buildInstructions({
|
|
|
341
351
|
*
|
|
342
352
|
* @param {object} ctx DSH cordis context
|
|
343
353
|
* @param {object} registry createRegistry() 的返回值
|
|
344
|
-
* @param {{ namespace?: string }} options
|
|
354
|
+
* @param {{ namespace?: string, domain?: string, modeGate?: object }} options
|
|
355
|
+
* domain:本 registry 的兜底领域(工具/能力未各自声明时用);
|
|
356
|
+
* modeGate:会话模式锁闸(createToolHost 服务级自动注入;独立调用可显式传)。
|
|
345
357
|
* @returns {() => void} 反注册全部工具
|
|
346
358
|
*/
|
|
347
|
-
export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
|
|
359
|
+
export function registerWithDsh(ctx, registry, { namespace = '', domain = '', modeGate = null } = {}) {
|
|
348
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
|
|
349
364
|
const disposers = []
|
|
365
|
+
if (typeof gateDispose === 'function') disposers.push(gateDispose)
|
|
350
366
|
try {
|
|
351
367
|
for (const tool of registry?.TOOLS || []) {
|
|
352
368
|
const impl = registry.TOOL_IMPL?.[tool.name]
|
|
353
369
|
if (typeof impl !== 'function') throw new Error(`registerWithDsh: 工具缺少实现 ${tool.name}`)
|
|
354
370
|
const name = namespace ? `${namespace}_${tool.name}` : tool.name
|
|
371
|
+
const toolDomain = registry.TOOL_META?.[tool.name]?.domain || domain || ''
|
|
372
|
+
let when
|
|
373
|
+
if (modeGate && toolDomain) {
|
|
374
|
+
modeGate.declareTools(toolDomain, [name])
|
|
375
|
+
when = modeGate.whenFor(name)
|
|
376
|
+
}
|
|
355
377
|
disposers.push(ctx.tools.register({
|
|
356
378
|
name,
|
|
357
379
|
description: tool.description || '',
|
|
@@ -364,16 +386,20 @@ export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
|
|
|
364
386
|
? value.content
|
|
365
387
|
: normalizeToolResult(value).content),
|
|
366
388
|
},
|
|
367
|
-
execute: async (args, exec) => {
|
|
389
|
+
execute: async (args, exec) => runWithCallerSession(exec?.agent?.session?.id, async () => {
|
|
368
390
|
const normalized = normalizeToolResult(await impl(args, exec))
|
|
369
391
|
/* DSH 原生面成功恒 isError:false,失败必须 throw 才走错误路径(B 轴 P0-1)。
|
|
370
392
|
* 把工具自报的 isError:true 转成 throw,与 MCP 面的失败语义对齐。 */
|
|
371
393
|
if (normalized.isError === true) {
|
|
372
394
|
throw new Error(resultText(normalized) || `工具 ${name} 执行失败`)
|
|
373
395
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
396
|
+
/* 图像准入:裸 base64 图像块(rsp_screen/browser_screenshot 等)必须先持久化成
|
|
397
|
+
* attachment ref 再入 session 日志,否则下一步序列化读 block.attachment.attachmentId
|
|
398
|
+
* 抛错、永久毒化该会话(2026-11-22 根因)。MCP 面不走这里,保留 wire 形态。 */
|
|
399
|
+
const content = await admitToolResultImages(normalized.content, resolveAttachments(exec, ctx), { name })
|
|
400
|
+
return { ...normalized, content }
|
|
401
|
+
}),
|
|
402
|
+
}, when ? { when } : {}))
|
|
377
403
|
}
|
|
378
404
|
} catch (error) {
|
|
379
405
|
/* 全有或全无:任一工具注册失败,逆序释放已注册的,避免部分注册泄漏(B 轴 P0-6)。 */
|
|
@@ -392,9 +418,12 @@ export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
|
|
|
392
418
|
export function createToolHost(config = {}) {
|
|
393
419
|
// 跨套件能力发现注册表(互联标准 §A.4/§E)。深度校验器可选注入(suite-kit)。
|
|
394
420
|
const descriptors = createDescriptorRegistry({ validate: config.validateDescriptor })
|
|
421
|
+
// 会话模式锁:全服务共享一个闸实例(所有套件的注册都经此)。getWorkStore 惰性解析
|
|
422
|
+
// (driver 注入 () => safeGet(ctx,'workStore'));底座缺席则降级为恒可见、不拒。
|
|
423
|
+
const modeGate = createModeGate({ getWorkStore: config.getWorkStore })
|
|
395
424
|
return {
|
|
396
|
-
api: createServiceApi('toolHost', '1.
|
|
397
|
-
version: '0.
|
|
425
|
+
api: createServiceApi('toolHost', '1.2.0', ['dsl', 'registry', 'validate', 'contract', 'mcp', 'instructions', 'native-tools', 'descriptors', 'mode-gate']),
|
|
426
|
+
version: '0.3.0',
|
|
398
427
|
defineTool,
|
|
399
428
|
defineCapability,
|
|
400
429
|
createRegistry: (capabilities, options = {}) => createRegistry(capabilities, { ...config, ...options }),
|
|
@@ -402,12 +431,16 @@ export function createToolHost(config = {}) {
|
|
|
402
431
|
createToolDispatcher,
|
|
403
432
|
createCapabilityReport,
|
|
404
433
|
buildInstructions,
|
|
405
|
-
|
|
434
|
+
// 服务级注册自动带会话模式锁(when 可见性 + guard 硬拒 + 调用者会话 ALS),套件零接线。
|
|
435
|
+
registerWithDsh: (ctx, registry, options = {}) => registerWithDsh(ctx, registry, { modeGate, ...options }),
|
|
406
436
|
validateToolArguments,
|
|
437
|
+
modeGate,
|
|
407
438
|
// 能力描述符注册/发现(编排器按类型动态发现,套件零互依赖)。
|
|
408
439
|
registerCapabilityDescriptor: (descriptor, options) => descriptors.register(descriptor, options),
|
|
409
440
|
unregisterCapabilityDescriptor: (name) => descriptors.unregister(name),
|
|
410
|
-
|
|
441
|
+
// 发现面按调用者会话过滤:原生工具调用里自动从 ALS 取会话(conductor_discover 无需接线);
|
|
442
|
+
// HTTP/墙等管理面无会话 → 不过滤(全局视图)。query.sessionId 可显式覆盖。
|
|
443
|
+
discoverCapabilities: (query = {}) => modeGate.filterEntries(descriptors.discover(query), query.sessionId || currentCallerSession()),
|
|
411
444
|
capabilityCatalog: () => descriptors.catalog(),
|
|
412
445
|
listSurfaces: () => descriptors.listSurfaces(),
|
|
413
446
|
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话模式锁 —— 工具面标准框架的强制闸(基础设施能力,非各套件自接)。
|
|
3
|
+
*
|
|
4
|
+
* 设计目标(用户诉求):锁定一种工作模式(如 rsp)后,本会话只看得见、调得动
|
|
5
|
+
* 该领域的工具;其余已注册能力(browser_* 等)从工具声明里消失,且即便被强行
|
|
6
|
+
* 调用也在分发层硬拒。所有经 tool-host 注册的能力自动受此约束。
|
|
7
|
+
*
|
|
8
|
+
* 三道原生闸里的两道在此落地:
|
|
9
|
+
* · when(可见性):registerWithDsh / bridge host 给每个领域工具挂 whenFor(name),
|
|
10
|
+
* DSH 每步 resolve() 求值,false 同时从声明与分发中排除该工具。
|
|
11
|
+
* · guard(分发硬拒,兜底):install(tools) 挂一个全局 ToolGuard,异领域调用返回
|
|
12
|
+
* denial。单调不可翻回,兜住任何绕过 when 的路径。
|
|
13
|
+
*
|
|
14
|
+
* 领域来源:TOOL_META.domain(defineTool/defineCapability/createRegistry 声明)。
|
|
15
|
+
* 存储真源:work-store.getSessionMode(sid)(终生固化,无 unlock)。
|
|
16
|
+
* 降级:无 workStore / 无 sid / 未锁定 → 恒可见、不拒(与既有“底座缺席不启用”一致)。
|
|
17
|
+
* 无 domain 的工具(conductor/capyclaw/框架核心 mode_*)恒可见,不受锁限制。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {{ getWorkStore?: () => object|null }} deps
|
|
22
|
+
*/
|
|
23
|
+
export function createModeGate({ getWorkStore } = {}) {
|
|
24
|
+
const domainByTool = new Map() // 原生工具名 → domain
|
|
25
|
+
const domainBySuite = new Map() // 套件名 → domain(描述符发现面按 suite 兜底)
|
|
26
|
+
const lockCache = new Map() // sid → kind(锁终生固化,一旦落定永不变更,可缓存)
|
|
27
|
+
let guardInstalled = false
|
|
28
|
+
const guardDisposers = []
|
|
29
|
+
let coreToolsRegistered = false
|
|
30
|
+
const coreDisposers = []
|
|
31
|
+
let installRefs = 0 // 安装方引用计数(见 install 注释)
|
|
32
|
+
|
|
33
|
+
function store() {
|
|
34
|
+
try { return typeof getWorkStore === 'function' ? getWorkStore() : null } catch { return null }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 当前会话锁定的工作模式 kind;未锁定/底座缺席/无 sid → null。 */
|
|
38
|
+
function modeOf(sessionId) {
|
|
39
|
+
const sid = String(sessionId || '').trim()
|
|
40
|
+
if (!sid) return null
|
|
41
|
+
if (lockCache.has(sid)) return lockCache.get(sid)
|
|
42
|
+
const ws = store()
|
|
43
|
+
if (!ws || typeof ws.getSessionMode !== 'function') return null
|
|
44
|
+
let rec = null
|
|
45
|
+
try { rec = ws.getSessionMode(sid) } catch { return null }
|
|
46
|
+
const kind = rec && rec.kind ? String(rec.kind) : null
|
|
47
|
+
if (kind) lockCache.set(sid, kind) // 只缓存已落定的锁;null 不缓存(可能稍后被认领)
|
|
48
|
+
return kind
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 领域工具在指定会话里是否可见。无 domain / 未锁定 / 同领域 → 可见。 */
|
|
52
|
+
function isVisible(domain, sessionId) {
|
|
53
|
+
if (!domain) return true
|
|
54
|
+
const lock = modeOf(sessionId)
|
|
55
|
+
return !lock || domain === lock
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 声明一组工具属于某领域(registerWithDsh / bridge host 注册时调用)。 */
|
|
59
|
+
function declareTools(domain, names = [], suite = domain) {
|
|
60
|
+
const d = String(domain || '').trim()
|
|
61
|
+
if (!d) return
|
|
62
|
+
for (const name of names || []) {
|
|
63
|
+
if (name) domainByTool.set(String(name), d)
|
|
64
|
+
}
|
|
65
|
+
if (suite) domainBySuite.set(String(suite), d)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 某工具的领域;未声明 → ''(恒可见)。 */
|
|
69
|
+
function domainOf(name) {
|
|
70
|
+
return domainByTool.get(String(name)) || ''
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* DSH register 的 when 条件。未声明领域的工具返回 undefined(不挂 when,恒可见,
|
|
75
|
+
* 也避免给内置/核心工具增加每步求值开销)。
|
|
76
|
+
* @returns {((context: object) => boolean)|undefined}
|
|
77
|
+
*/
|
|
78
|
+
function whenFor(name) {
|
|
79
|
+
const domain = domainOf(name)
|
|
80
|
+
if (!domain) return undefined
|
|
81
|
+
return (context) => isVisible(domain, context?.agent?.session?.id)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 全局 ToolGuard(分发硬拒兜底)。非领域工具立即放行(不读 store,内置工具零开销);
|
|
86
|
+
* 领域工具在异领域锁定的会话里返回 denial。
|
|
87
|
+
* @returns {{reason: string, info: object}|undefined}
|
|
88
|
+
*/
|
|
89
|
+
function guard(execution) {
|
|
90
|
+
const name = execution?.name
|
|
91
|
+
const domain = domainByTool.get(String(name))
|
|
92
|
+
if (!domain) return undefined
|
|
93
|
+
const lock = modeOf(execution?.agent?.session?.id)
|
|
94
|
+
if (!lock || domain === lock) return undefined
|
|
95
|
+
return {
|
|
96
|
+
reason: `本会话已锁定为「${lock}」工作模式,「${name}」属于「${domain}」领域,已被框架屏蔽。`
|
|
97
|
+
+ `请只用「${lock}」领域的工具完成任务;确需其他领域,请新开一个会话。`,
|
|
98
|
+
info: { name: 'SessionModeLocked', code: 'SESSION_MODE_LOCKED', reason: `locked to ${lock}, tool domain ${domain}` },
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 框架核心工具 mode_lock / mode_status(无领域,恒可见)——显式锁定入口与状态查询。
|
|
103
|
+
* 存储经 modeGate 的 getWorkStore 解析(不依赖插件 ctx),故可在任何 tools 就绪时机注册。 */
|
|
104
|
+
function coreTools() {
|
|
105
|
+
const textRender = (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }]
|
|
106
|
+
const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true }
|
|
107
|
+
const modeLock = {
|
|
108
|
+
name: 'mode_lock',
|
|
109
|
+
description: '把当前会话锁定到一种工作模式(领域),如 rsp/browser/ppt/canvas。锁定后本会话只看得见、调得动该领域的工具,'
|
|
110
|
+
+ '其余领域能力被框架从工具面屏蔽并在分发层硬拒。锁终生固化、不可解锁;确需其他领域请新开一个会话。',
|
|
111
|
+
parameters: {
|
|
112
|
+
type: 'object',
|
|
113
|
+
properties: { kind: { type: 'string', description: '要锁定的工作模式/领域,如 rsp、browser、ppt、canvas' } },
|
|
114
|
+
required: ['kind'],
|
|
115
|
+
additionalProperties: false,
|
|
116
|
+
},
|
|
117
|
+
output: { schema: OUTPUT_SCHEMA, render: textRender },
|
|
118
|
+
execute: async (args, exec) => {
|
|
119
|
+
const kind = String(args?.kind || '').trim()
|
|
120
|
+
if (!kind) return { ok: false, error: '需要 kind(要锁定的工作模式/领域)' }
|
|
121
|
+
const sid = exec?.agent?.session?.id
|
|
122
|
+
if (!sid) return { ok: false, error: '无法识别当前会话,不能锁定' }
|
|
123
|
+
const ws = store()
|
|
124
|
+
if (!ws || typeof ws.claimSessionMode !== 'function') return { ok: false, error: 'work-store 底座缺席,无法锁定' }
|
|
125
|
+
const res = ws.claimSessionMode(sid, kind, 'mode-lock', { explicit: true })
|
|
126
|
+
if (res && res.ok === false) {
|
|
127
|
+
return { ok: false, lockedTo: res.lockedTo, error: `本会话已固化为「${res.lockedTo}」模式,不能改为「${kind}」。确需其他领域请新开一个会话。` }
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
ok: true, kind: res.kind, fresh: !!res.fresh, explicit: true,
|
|
131
|
+
message: res.fresh ? `已锁定为「${res.kind}」工作模式,本会话此后只用该领域工具。` : `本会话已处于「${res.kind}」工作模式。`,
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
}
|
|
135
|
+
const modeStatus = {
|
|
136
|
+
name: 'mode_status',
|
|
137
|
+
description: '查询当前会话的工作模式锁状态:是否锁定、锁定到哪个领域、由谁何时认领。未锁定时所有领域工具可见。',
|
|
138
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
139
|
+
output: { schema: OUTPUT_SCHEMA, render: textRender },
|
|
140
|
+
execute: async (_args, exec) => {
|
|
141
|
+
const sid = exec?.agent?.session?.id
|
|
142
|
+
const ws = store()
|
|
143
|
+
if (!ws || typeof ws.getSessionMode !== 'function') return { locked: false, reason: 'work-store 底座缺席' }
|
|
144
|
+
if (!sid) return { locked: false, reason: '无法识别当前会话' }
|
|
145
|
+
const rec = ws.getSessionMode(sid)
|
|
146
|
+
if (!rec) return { locked: false, kind: null, message: '本会话未锁定工作模式,所有领域工具可见。' }
|
|
147
|
+
return {
|
|
148
|
+
locked: true, kind: rec.kind, claimedBy: rec.claimedBy || '', claimedAt: rec.claimedAt || '', explicit: !!rec.explicit,
|
|
149
|
+
message: `本会话已锁定为「${rec.kind}」工作模式,其余领域工具已被屏蔽。`,
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
}
|
|
153
|
+
return [modeLock, modeStatus]
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 把 guard + 核心锁定工具挂到 DSH tools 服务(幂等)。每个套件在 tools 就绪时都会调用,
|
|
157
|
+
* 故核心工具注册不依赖 tool-host driver apply 那一刻 tools 是否已就绪(加载顺序鲁棒)。返回 disposer。
|
|
158
|
+
* 引用计数:多个安装方(driver apply / 各套件 registerWithDsh)共享同一份核心注册,
|
|
159
|
+
* 任一安装方卸载只减引用;最后一个释放才真正摘 guard + 核心工具,避免「丢 disposer」泄漏
|
|
160
|
+
* 与「先卸载者拆掉幸存者底座」两种事故。 */
|
|
161
|
+
function install(tools) {
|
|
162
|
+
if (!tools) return () => {}
|
|
163
|
+
if (!guardInstalled && typeof tools.guard === 'function') {
|
|
164
|
+
try {
|
|
165
|
+
const dispose = tools.guard(guard)
|
|
166
|
+
if (typeof dispose === 'function') guardDisposers.push(dispose)
|
|
167
|
+
guardInstalled = true
|
|
168
|
+
} catch { /* 底座不支持 guard 时降级:仅 when 生效 */ }
|
|
169
|
+
}
|
|
170
|
+
if (!coreToolsRegistered && typeof tools.register === 'function') {
|
|
171
|
+
for (const tool of coreTools()) {
|
|
172
|
+
try {
|
|
173
|
+
const d = tools.register(tool)
|
|
174
|
+
if (typeof d === 'function') coreDisposers.push(d)
|
|
175
|
+
} catch (err) {
|
|
176
|
+
console.warn(`[tool-host] 注册核心工具 ${tool.name} 失败:`, err?.message || err)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
coreToolsRegistered = true
|
|
180
|
+
}
|
|
181
|
+
installRefs++
|
|
182
|
+
let released = false
|
|
183
|
+
return () => {
|
|
184
|
+
if (released) return
|
|
185
|
+
released = true
|
|
186
|
+
installRefs--
|
|
187
|
+
if (installRefs > 0) return
|
|
188
|
+
for (const dispose of guardDisposers.splice(0)) {
|
|
189
|
+
try { dispose() } catch { /* 忽略重复释放 */ }
|
|
190
|
+
}
|
|
191
|
+
for (const dispose of coreDisposers.splice(0)) {
|
|
192
|
+
try { dispose() } catch { /* 忽略重复释放 */ }
|
|
193
|
+
}
|
|
194
|
+
guardInstalled = false
|
|
195
|
+
coreToolsRegistered = false
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* 能力发现面过滤:锁定会话里剔除异领域描述符(conductor_discover 自动受约束)。
|
|
201
|
+
* 无 domain 的描述符(编排/核心基建)保留。未锁定 → 原样返回。
|
|
202
|
+
*/
|
|
203
|
+
function filterEntries(entries, sessionId) {
|
|
204
|
+
const lock = modeOf(sessionId)
|
|
205
|
+
if (!lock) return entries
|
|
206
|
+
return (entries || []).filter((entry) => {
|
|
207
|
+
const d = entry?.descriptor || {}
|
|
208
|
+
const domain = domainByTool.get(String(d.tool || d.name)) || domainBySuite.get(String(entry?.suite)) || ''
|
|
209
|
+
return !domain || domain === lock
|
|
210
|
+
})
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return { declareTools, domainOf, modeOf, isVisible, whenFor, guard, install, filterEntries }
|
|
214
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capyclaw/publisher",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "npm 发布器:插件页里把打包好的插件包拖进来就能发布或更新到 npm,发布后可就地更新本机安装;同时保留 publisher_* 原生工具做批量预演与真发布",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./plugin.mjs",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@capyclaw/plugin-kit": "^0.2.0",
|
|
45
45
|
"@capyclaw/plugin-validator": "^1.0.0",
|
|
46
|
-
"@capyclaw/tool-host": "^0.
|
|
46
|
+
"@capyclaw/tool-host": "^0.3.0",
|
|
47
47
|
"@capyclaw/foundation": "^0.1.1"
|
|
48
48
|
},
|
|
49
49
|
"engines": {
|
package/server/archive.mjs
CHANGED
|
@@ -10,14 +10,26 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import path from 'node:path'
|
|
12
12
|
import os from 'node:os'
|
|
13
|
-
import { mkdir, writeFile } from 'node:fs/promises'
|
|
13
|
+
import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
|
|
14
14
|
import { gunzipSync, inflateRawSync } from 'node:zlib'
|
|
15
15
|
|
|
16
16
|
const MAX_DEPTH = 3
|
|
17
|
+
/* 解压上限(与 @capyclaw/plugin-drop 的 archive.js 同源):zip bomb 靠「压缩态很小、
|
|
18
|
+
* 解压态巨大」吃光内存,必须在解压这一步就掐断,而不是等落盘。 */
|
|
19
|
+
const MAX_UNPACKED_BYTES = 128 * 1024 * 1024
|
|
20
|
+
const MAX_ENTRIES = 4096
|
|
21
|
+
|
|
22
|
+
function tooManyEntries() {
|
|
23
|
+
return new Error(`压缩包里的文件太多,超出 ${MAX_ENTRIES} 的上限。`)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function tooLarge() {
|
|
27
|
+
return new Error(`压缩包解压后超过 ${Math.round(MAX_UNPACKED_BYTES / 1024 / 1024)} MB 上限。`)
|
|
28
|
+
}
|
|
17
29
|
|
|
18
30
|
/** 读 .zip / .tgz / .tar.gz(或裸 .tar)为一个扁平条目表。 */
|
|
19
31
|
export function unpack(buffer, filename) {
|
|
20
|
-
if (buffer.length > 2 && buffer[0] === 0x1f && buffer[1] === 0x8b) return untar(gunzipSync(buffer))
|
|
32
|
+
if (buffer.length > 2 && buffer[0] === 0x1f && buffer[1] === 0x8b) return untar(gunzipSync(buffer, { maxOutputLength: MAX_UNPACKED_BYTES }))
|
|
21
33
|
if (buffer.length > 4 && buffer[0] === 0x50 && buffer[1] === 0x4b && buffer[2] === 0x03 && buffer[3] === 0x04) {
|
|
22
34
|
return unzip(buffer)
|
|
23
35
|
}
|
|
@@ -33,6 +45,7 @@ function untar(buffer) {
|
|
|
33
45
|
while (offset + 512 <= buffer.length) {
|
|
34
46
|
const header = buffer.subarray(offset, offset + 512)
|
|
35
47
|
if (header.every((byte) => byte === 0)) break
|
|
48
|
+
if (entries.length >= MAX_ENTRIES) throw tooManyEntries()
|
|
36
49
|
|
|
37
50
|
const name = readCString(header, 0, 100)
|
|
38
51
|
const prefix = readCString(header, 345, 155)
|
|
@@ -90,9 +103,11 @@ function unzip(buffer) {
|
|
|
90
103
|
const directoryOffset = buffer.readUInt32LE(eocd + 16)
|
|
91
104
|
const entries = []
|
|
92
105
|
let cursor = directoryOffset
|
|
106
|
+
let total = 0
|
|
93
107
|
|
|
94
108
|
for (let index = 0; index < count; index += 1) {
|
|
95
109
|
if (cursor + 46 > buffer.length || buffer.readUInt32LE(cursor) !== 0x02014b50) break
|
|
110
|
+
if (entries.length >= MAX_ENTRIES) throw tooManyEntries()
|
|
96
111
|
const method = buffer.readUInt16LE(cursor + 10)
|
|
97
112
|
const compressedSize = buffer.readUInt32LE(cursor + 20)
|
|
98
113
|
const nameLength = buffer.readUInt16LE(cursor + 28)
|
|
@@ -114,9 +129,17 @@ function unzip(buffer) {
|
|
|
114
129
|
const raw = buffer.subarray(dataStart, Math.min(dataStart + compressedSize, buffer.length))
|
|
115
130
|
|
|
116
131
|
let data
|
|
117
|
-
if (method === 0)
|
|
118
|
-
|
|
119
|
-
|
|
132
|
+
if (method === 0) {
|
|
133
|
+
if (total + raw.length > MAX_UNPACKED_BYTES) throw tooLarge()
|
|
134
|
+
data = Buffer.from(raw)
|
|
135
|
+
total += raw.length
|
|
136
|
+
} else if (method === 8) {
|
|
137
|
+
/* 剩余配额逐条目递减:炸弹不必是单个大文件,几个「看似无害」的条目加起来
|
|
138
|
+
* 也能超限。配额为 0 时 maxOutputLength 会报 ERR_OUT_OF_RANGE,先拦下给可读错误。 */
|
|
139
|
+
if (total >= MAX_UNPACKED_BYTES) throw tooLarge()
|
|
140
|
+
data = inflateRawSync(raw, { maxOutputLength: MAX_UNPACKED_BYTES - total })
|
|
141
|
+
total += data.length
|
|
142
|
+
} else throw new Error(`不支持的 ZIP 压缩方式(method ${method})。`)
|
|
120
143
|
|
|
121
144
|
entries.push({ path: name, data })
|
|
122
145
|
}
|
|
@@ -208,47 +231,58 @@ export function storeRoot() {
|
|
|
208
231
|
}
|
|
209
232
|
|
|
210
233
|
/**
|
|
211
|
-
*
|
|
234
|
+
* 新 staging 目录的候选名。时间戳之外再挂随机后缀:两个请求落在同一毫秒时
|
|
212
235
|
* 不会写进同一个目录(否则后到的包会污染前一个包的文件清单)。
|
|
213
236
|
*/
|
|
214
|
-
|
|
237
|
+
function stageCandidate() {
|
|
238
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
239
|
+
const suffix = Math.random().toString(36).slice(2, 8)
|
|
240
|
+
return path.join(storeRoot(), `${stamp}-${suffix}`)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* 把条目表写到 staging 下的一个新目录,返回包目录的绝对路径。
|
|
245
|
+
* 先全部写进 .tmp- 目录、成功后原子 rename 成正式名:写一半失败不会留下
|
|
246
|
+
* 「看似有效却缺文件」的 staging(那会被预检/发布当成真包);失败时清掉 tmp,
|
|
247
|
+
* 磁盘上不落垃圾。与 plugin-drop 的差别:这里每次上传都要独立目录(发布后回收),
|
|
248
|
+
* 不做内容地址化复用。
|
|
249
|
+
*/
|
|
250
|
+
export async function materialize(entries, packageDir) {
|
|
215
251
|
await mkdir(storeRoot(), { recursive: true })
|
|
216
252
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
217
|
-
const
|
|
218
|
-
const
|
|
219
|
-
const candidate = path.join(storeRoot(), `${stamp}-${suffix}`)
|
|
253
|
+
const base = stageCandidate()
|
|
254
|
+
const tmp = `${base}.tmp-${process.pid}`
|
|
220
255
|
try {
|
|
221
|
-
await mkdir(
|
|
222
|
-
|
|
256
|
+
await mkdir(tmp)
|
|
257
|
+
try {
|
|
258
|
+
for (const entry of entries) {
|
|
259
|
+
const relative = safeRelative(entry.path)
|
|
260
|
+
if (!relative) continue
|
|
261
|
+
const target = path.join(tmp, ...relative.split('/'))
|
|
262
|
+
if (!isInside(tmp, target)) continue
|
|
263
|
+
if (entry.dir) {
|
|
264
|
+
await mkdir(target, { recursive: true })
|
|
265
|
+
continue
|
|
266
|
+
}
|
|
267
|
+
await mkdir(path.dirname(target), { recursive: true })
|
|
268
|
+
await writeFile(target, entry.data)
|
|
269
|
+
}
|
|
270
|
+
if (packageDir) await mkdir(path.join(tmp, ...packageDir.split('/')), { recursive: true })
|
|
271
|
+
await rename(tmp, base)
|
|
272
|
+
} catch (error) {
|
|
273
|
+
await rm(tmp, { recursive: true, force: true }).catch(() => {})
|
|
274
|
+
throw error
|
|
275
|
+
}
|
|
276
|
+
return packageDir ? path.join(base, ...packageDir.split('/')) : base
|
|
223
277
|
} catch (error) {
|
|
224
|
-
|
|
278
|
+
/* 撞名(EEXIST):换一个候选名重试;其它错误原样抛出。 */
|
|
279
|
+
if (error?.code === 'EEXIST' && attempt < 4) continue
|
|
280
|
+
throw error
|
|
225
281
|
}
|
|
226
282
|
}
|
|
227
283
|
throw new Error(`无法在 ${storeRoot()} 下创建临时目录,请检查磁盘权限。`)
|
|
228
284
|
}
|
|
229
285
|
|
|
230
|
-
/** 把条目表写到 staging 下的一个新目录,返回包目录的绝对路径。 */
|
|
231
|
-
export async function materialize(entries, packageDir) {
|
|
232
|
-
const base = await createStageDir()
|
|
233
|
-
|
|
234
|
-
for (const entry of entries) {
|
|
235
|
-
const relative = safeRelative(entry.path)
|
|
236
|
-
if (!relative) continue
|
|
237
|
-
const target = path.join(base, ...relative.split('/'))
|
|
238
|
-
if (!isInside(base, target)) continue
|
|
239
|
-
if (entry.dir) {
|
|
240
|
-
await mkdir(target, { recursive: true })
|
|
241
|
-
continue
|
|
242
|
-
}
|
|
243
|
-
await mkdir(path.dirname(target), { recursive: true })
|
|
244
|
-
await writeFile(target, entry.data)
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
const target = packageDir ? path.join(base, ...packageDir.split('/')) : base
|
|
248
|
-
await mkdir(target, { recursive: true })
|
|
249
|
-
return target
|
|
250
|
-
}
|
|
251
|
-
|
|
252
286
|
function isInside(parent, target) {
|
|
253
287
|
const relative = path.relative(parent, target)
|
|
254
288
|
return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative)
|
package/server/drop.mjs
CHANGED
|
@@ -64,8 +64,9 @@ export function npmRun(args, options = {}) {
|
|
|
64
64
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
65
65
|
})
|
|
66
66
|
} catch (error) {
|
|
67
|
-
finish
|
|
67
|
+
/* 先赋值再 finish:finish 会立刻 resolve Promise,后赋值 stderr 就丢了。 */
|
|
68
68
|
stderr = messageOf(error)
|
|
69
|
+
finish(-1)
|
|
69
70
|
return
|
|
70
71
|
}
|
|
71
72
|
|
|
@@ -87,6 +88,11 @@ export function npmRun(args, options = {}) {
|
|
|
87
88
|
})
|
|
88
89
|
}
|
|
89
90
|
|
|
91
|
+
/* 与 routes.mjs 的 messageOf 同形:spawn 同步抛错与 child 'error' 事件都要用它。 */
|
|
92
|
+
function messageOf(error) {
|
|
93
|
+
return error instanceof Error ? error.message : String(error)
|
|
94
|
+
}
|
|
95
|
+
|
|
90
96
|
const delay = (ms) => new Promise((resolve) => { setTimeout(resolve, ms) })
|
|
91
97
|
|
|
92
98
|
// ---------------------------------------------------------------------------
|
|
@@ -266,7 +272,6 @@ export async function previewStage(stage, { npm = npmRun, cacheTtlMs } = {}) {
|
|
|
266
272
|
blocking,
|
|
267
273
|
warnings,
|
|
268
274
|
description: typeof pkg.description === 'string' ? pkg.description : '',
|
|
269
|
-
stagedDir: stage.dir,
|
|
270
275
|
}
|
|
271
276
|
}
|
|
272
277
|
|
|
@@ -334,7 +339,8 @@ export async function publishStage(stage, {
|
|
|
334
339
|
|
|
335
340
|
for (let attempt = 0; attempt < verifyAttempts; attempt += 1) {
|
|
336
341
|
const check = await npm(['view', `${pkg.name}@${version}`, 'version'], { timeout: 30000 })
|
|
337
|
-
|
|
342
|
+
/* 精确匹配:startsWith 会把 1.0.10 当成 1.0.1 回读成功(与 impl.mjs alreadyPublished 同形)。 */
|
|
343
|
+
if (check.status === 0 && String(check.stdout).trim() === version) {
|
|
338
344
|
forgetPublished(pkg.name)
|
|
339
345
|
return {
|
|
340
346
|
ok: true,
|