@capyclaw/publisher 0.1.5 → 0.1.6

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 (24) hide show
  1. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  2. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +3 -1
  3. package/node_modules/@capyclaw/foundation/abi/index.mjs +15 -0
  4. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  5. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
  6. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
  7. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
  8. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
  9. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
  10. package/node_modules/@capyclaw/foundation/package.json +1 -1
  11. package/node_modules/@capyclaw/plugin-kit/package.json +3 -1
  12. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
  13. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  14. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  15. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
  16. package/node_modules/@capyclaw/plugin-validator/lib/index.mjs +13 -8
  17. package/node_modules/@capyclaw/plugin-validator/package.json +4 -2
  18. package/node_modules/@capyclaw/tool-host/dsh-suite.json +1 -1
  19. package/node_modules/@capyclaw/tool-host/lib/host.mjs +11 -2
  20. package/node_modules/@capyclaw/tool-host/package.json +1 -1
  21. package/node_modules/@capyclaw/tool-host/src/index.mjs +15 -3
  22. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +60 -2
  23. package/package.json +1 -1
  24. package/server/impl.mjs +41 -27
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 资产引用契约的单一真源(公共 ABI 常量)。
3
+ *
4
+ * 互操作标准里资产有两副面孔,前缀在这里定义一次,内核门面与资产服务都引用它,
5
+ * 避免「路由实现」与「URL 门面」各写一份 '/assets/' 而漂移:
6
+ * - 字节仓 HTTP 路由前缀 ASSET_URL_PREFIX = '/assets/' (asset-service 挂 GET/HEAD)
7
+ * - 结构化正文里的引用前缀 ASSET_REF_PREFIX = '@asset/' (work-store 信封/正文只存引用)
8
+ *
9
+ * 这是契约常量,不是宿主服务名——放 ABI 层,应用与驱动都可 import。
10
+ */
11
+
12
+ /** 资产字节仓的 HTTP 路由前缀(asset-service 实现,内核 os.assets.url 复用)。 */
13
+ export const ASSET_URL_PREFIX = '/assets/'
14
+
15
+ /** 结构化正文/产物信封里的内容寻址引用前缀(@asset/<sha256>)。 */
16
+ export const ASSET_REF_PREFIX = '@asset/'
17
+
18
+ /** 由资产 id 生成可加载 URL:/assets/<id>(id 做 URI 编码)。 */
19
+ export function assetUrl(id) {
20
+ return `${ASSET_URL_PREFIX}${encodeURIComponent(String(id))}`
21
+ }
22
+
23
+ /** 由资产 id 生成规范引用:@asset/<id>。 */
24
+ export function assetRef(id) {
25
+ return `${ASSET_REF_PREFIX}${String(id)}`
26
+ }
@@ -14,6 +14,8 @@
14
14
  * doc.model —— 插件提供文档模型(稳定 ID / 清单 / 定位 / 编辑计划 / 校验)
15
15
  */
16
16
 
17
+ import { AbiError, ERROR_CODES } from './errors.mjs'
18
+
17
19
  /** 桥协议版本:端点集合与状态机语义的主版本。不兼容变更才升 major。 */
18
20
  export const BRIDGE_PROTOCOL_VERSION = '1.0.0'
19
21
 
@@ -40,7 +42,7 @@ export function declareBridge(input = {}) {
40
42
  if (!VERSION_RE.test(protocol)) errors.push(`protocol 版本非法:${protocol}`)
41
43
  if (model !== null && !VERSION_RE.test(model)) errors.push(`model 版本非法:${model}`)
42
44
  if (editor !== 'required' && editor !== 'optional') errors.push(`editor 只能是 required/optional:${editor}`)
43
- if (errors.length) throw new Error(`桥声明非法:${errors.join(';')}`)
45
+ if (errors.length) throw new AbiError(ERROR_CODES.E_SCHEMA, `桥声明非法:${errors.join(';')}`, { errors })
44
46
  return Object.freeze({ id, protocol, model, editor })
45
47
  }
46
48
 
@@ -17,6 +17,8 @@ export {
17
17
  defineDriver,
18
18
  rawPlugin,
19
19
  } from './spec.mjs'
20
+ /* createLoader 是宿主/测试侧装配 API(内核 createKernel 与一致性测试用),虽从 abi 导出,
21
+ * 应用插件不应直接调用——应用只用 createPlugin + 接口 builders(见 plugin-abi.md §二)。 */
20
22
  export { createLoader } from './loader.mjs'
21
23
  export {
22
24
  BRIDGE_CAPABILITY,
@@ -29,6 +31,19 @@ export {
29
31
  bridgeConsumerRequirements,
30
32
  declareBridge,
31
33
  } from './bridge.mjs'
34
+ export {
35
+ SURFACE_LIFECYCLE_VERSION,
36
+ SURFACE_LIFECYCLE_CAPABILITY_SUFFIX,
37
+ VISIBILITY_ACK_MESSAGE,
38
+ VISIBILITY_DEFAULTS,
39
+ VISIBILITY_MESSAGE,
40
+ VISIBILITY_STATES,
41
+ assertSurfaceLifecycle,
42
+ isVisibilityState,
43
+ normalizeVisibilityState,
44
+ surfaceLifecycleCapability,
45
+ } from './visibility.mjs'
46
+ export { ASSET_URL_PREFIX, ASSET_REF_PREFIX, assetUrl, assetRef } from './assets.mjs'
32
47
  export { validateInterface } from './validate.mjs'
33
48
  export { AbiError, ERROR_CODES, isAbiError, toAbiError } from './errors.mjs'
34
49
  export { validateSchema } from './schema.mjs'
@@ -0,0 +1,90 @@
1
+ /**
2
+ * 表面生命周期(surface lifecycle)的标准声明。
3
+ *
4
+ * 与 bridge.mjs 同层:只放「协议常量 + 声明校验」,不放运行时。
5
+ * 依据 docs/SURFACE-LIFECYCLE-STANDARD.md:
6
+ * - 宿主(portal-hud + window-kit)是表面可见性的唯一真源,经统一 postMessage
7
+ * 信号通道下发给 iframe;iframe 内 document.hidden 只反映顶层 tab,不能用来
8
+ * 推断「被宿主藏起来」,所以表面可见性必须宿主显式告知。
9
+ * - 只有渲染面响应可见性;权威/数据面与桥接/仲裁面(租约心跳、apply/ack)
10
+ * 永远在线,与可见性无关。
11
+ *
12
+ * 消费方:
13
+ * - 宿主侧:@capyclaw/window-kit 的 visibility 驱动器(CJS 自包含叶子,无法
14
+ * import 本 ESM 模块,内联同名常量,由 parity 测试钉死一致)。
15
+ * - iframe 侧:@capyclaw/document-workbench/client 的 visibility 订阅器,
16
+ * 以及各编辑器前端(ppt/canvas/browser)。
17
+ * - 注册面:suite 清单 provides.capabilities 的 <ns>.surfaceLifecycle。
18
+ */
19
+
20
+ import { AbiError, ERROR_CODES } from './errors.mjs'
21
+
22
+ /** 表面生命周期契约版本:状态机语义与信号形状的主版本。不兼容变更才升 major。 */
23
+ export const SURFACE_LIFECYCLE_VERSION = '1.0.0'
24
+
25
+ /** 宿主 → iframe 的可见性信号:{ type, state, sid },targetOrigin 同源。 */
26
+ export const VISIBILITY_MESSAGE = 'capyclaw:workbench:visibility'
27
+
28
+ /** iframe → 宿主 的回执:{ type, state, sid }。detached 由宿主直接卸载,无需回执。 */
29
+ export const VISIBILITY_ACK_MESSAGE = 'capyclaw:workbench:visibility-ack'
30
+
31
+ /**
32
+ * 可见性状态(标准 §3):
33
+ * foreground 前台可见全速;background 可见非焦点(降速,SHOULD 档);
34
+ * hidden 不再绘制(渲染面必须挂起);detached 久藏卸载(影子编辑器接管)。
35
+ */
36
+ export const VISIBILITY_STATES = Object.freeze(['foreground', 'background', 'hidden', 'detached'])
37
+
38
+ /**
39
+ * 节奏/预算默认值(标准 §3/§4/§5)。运行时经 tuning 单一真源可调;
40
+ * 这里是协议默认,不是各插件私设的第二份。
41
+ * detachAfterMs hidden 持续多久才卸载 iframe(编辑器权威型可更长)
42
+ * visibilityAckTimeoutMs 信号发出后多久没回执算半挂起(宿主可强制重载)
43
+ * hiddenGraceMs shown→hidden 的去抖宽限,避免快速切换抖动
44
+ */
45
+ export const VISIBILITY_DEFAULTS = Object.freeze({
46
+ detachAfterMs: 120000,
47
+ visibilityAckTimeoutMs: 1500,
48
+ hiddenGraceMs: 250,
49
+ })
50
+
51
+ /** 能力名后缀:与 suite 清单 provides.capabilities 的 <ns>.surfaceLifecycle 对应。 */
52
+ export const SURFACE_LIFECYCLE_CAPABILITY_SUFFIX = 'surfaceLifecycle'
53
+
54
+ const STATE_SET = new Set(VISIBILITY_STATES)
55
+
56
+ /** 是否合法状态。 */
57
+ export function isVisibilityState(value) {
58
+ return typeof value === 'string' && STATE_SET.has(value)
59
+ }
60
+
61
+ /** 归一化:非法/缺省一律退回 foreground(宁可多渲染,不可假挂起)。 */
62
+ export function normalizeVisibilityState(value) {
63
+ return isVisibilityState(value) ? value : 'foreground'
64
+ }
65
+
66
+ /** 注册声明 → suite 清单 provides.capabilities(标准 §6)。 */
67
+ export function surfaceLifecycleCapability(ns, version = SURFACE_LIFECYCLE_VERSION) {
68
+ if (typeof ns !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(ns)) {
69
+ throw new AbiError(ERROR_CODES.E_SCHEMA, `surfaceLifecycle 命名空间必须是 kebab-case:${ns}`)
70
+ }
71
+ return Object.freeze({ [`${ns}.${SURFACE_LIFECYCLE_CAPABILITY_SUFFIX}`]: version })
72
+ }
73
+
74
+ /**
75
+ * 校验一份表面生命周期声明(注册契约,标准 §6)。
76
+ * 渲染面四钩子必须齐;editor-gated 观察必须声明无头兜底。
77
+ * @param {{ hooks?: string[], headlessObservation?: boolean }} input
78
+ */
79
+ export function assertSurfaceLifecycle(input = {}) {
80
+ const required = ['onVisibility', 'suspendRender', 'resumeRender', 'rehydrate']
81
+ const hooks = Array.isArray(input.hooks) ? input.hooks : []
82
+ const issues = []
83
+ for (const hook of required) {
84
+ if (!hooks.includes(hook)) issues.push(`缺少渲染面钩子 ${hook}`)
85
+ }
86
+ if (input.headlessObservation !== true) {
87
+ issues.push('editor-gated 观察必须声明无头兜底(headlessObservation:true)')
88
+ }
89
+ return { ok: issues.length === 0, issues }
90
+ }
@@ -1,10 +1,14 @@
1
1
  /**
2
2
  * lifecycle-hook@1 的适配器。
3
3
  *
4
- * 运行时只执行 onStart / onStop;onInstall / onUpgrade 属于安装与升级流程,
5
- * 由安装器(publisher / dsh profile 安装)在对应时点读取描述符后调用。
6
- * 这里把它们登记进 hook 注册表,保证「声明了就找得到」。
4
+ * 运行时只执行 onStart / onStop。onInstall / onUpgrade 属于安装与升级流程:
5
+ * 这里把它们登记进 hook 注册表(os.hooks),保证「声明了就找得到」。
6
+ * 截至本版本仓内尚无自动 fire 它们的安装/升级消费者(见 plugin-abi.md §4.6)——
7
+ * 这是已声明的集成点,不是已落地的自动钩子。安装器可经 os.hooks.run('install'|'upgrade', args)
8
+ * 主动触发;run() 只提供调用 API,是否/何时调用由安装器决定。
7
9
  */
10
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
11
+
8
12
  export const kind = 'lifecycle-hook@1'
9
13
 
10
14
  export function createHookRegistry() {
@@ -12,7 +16,7 @@ export function createHookRegistry() {
12
16
  install: [],
13
17
  upgrade: [],
14
18
  register(phase, entry) {
15
- if (!this[phase]) throw new Error(`未知生命周期阶段 ${phase}`)
19
+ if (!this[phase]) throw new AbiError(ERROR_CODES.E_SCHEMA, `未知生命周期阶段 ${phase}`)
16
20
  this[phase].push(entry)
17
21
  return () => {
18
22
  const index = this[phase].indexOf(entry)
@@ -25,6 +29,19 @@ export function createHookRegistry() {
25
29
  upgrade: this.upgrade.map((entry) => entry.plugin),
26
30
  }
27
31
  },
32
+ /**
33
+ * 安装/升级集成点:按登记顺序触发某阶段全部钩子,逐个 await。
34
+ * 仓内暂无自动调用方(见头注);这是给安装器(plugin-sync / plugin-drop / publisher)
35
+ * 预留的调用 API。未知阶段抛稳定错误码 E_SCHEMA。
36
+ */
37
+ async run(phase, args = {}) {
38
+ if (!this[phase]) throw new AbiError(ERROR_CODES.E_SCHEMA, `未知生命周期阶段 ${phase}`)
39
+ const results = []
40
+ for (const entry of [...this[phase]]) {
41
+ results.push({ plugin: entry.plugin, result: await entry.run(args) })
42
+ }
43
+ return results
44
+ },
28
45
  }
29
46
  }
30
47
 
@@ -6,6 +6,7 @@
6
6
  * editorHost)的地方——它们属于 dsh 适配层,不属于 ABI。
7
7
  */
8
8
  import { getService } from '../ctx-service.mjs'
9
+ import { HOST_SERVICE_CONTRACT } from './contract.mjs'
9
10
 
10
11
  export const BASE_CAPABILITIES = Object.freeze({
11
12
  'os.events': '1.0.0',
@@ -26,9 +27,12 @@ export function detectDshCapabilities(ctx) {
26
27
  && hasMethods(getService(ctx, 'tools'), 'register')) capabilities['os.tools'] = '1.0.0'
27
28
  if (hasMethods(getService(ctx, 'serviceBroker'), 'start', 'stop')) capabilities['os.proc'] = '1.0.0'
28
29
  if (capabilities['os.net'] && hasMethods(getService(ctx, 'editorHost'), 'createEditorHost')) capabilities['os.ui'] = '1.0.0'
29
- if (hasMethods(getService(ctx, 'pluginManager'), 'listBundles', 'listPlugins', 'setBundleEnabled', 'setPluginEnabled')) {
30
+ if (hasMethods(getService(ctx, 'pluginManager'), ...HOST_SERVICE_CONTRACT['os.plugins'][1])) {
30
31
  capabilities['os.plugins'] = '1.0.0'
31
32
  }
32
33
  if (hasMethods(getService(ctx, 'assets'), 'put', 'get')) capabilities['os.assets'] = '1.0.0'
34
+ // work-store 是可选持久化层(不在 core 六件内):探测到才 advertise os.works,
35
+ // 应用用 os.caps.has('os.works') 判断降级,不再 safeGet(ctx, 'workStore') 裸摸。
36
+ if (hasMethods(getService(ctx, 'workStore'), 'backendFor')) capabilities['os.works'] = '1.0.0'
33
37
  return capabilities
34
38
  }
@@ -3,7 +3,9 @@ import { parseVersion } from '../../abi/version.mjs'
3
3
  import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
4
4
 
5
5
  const ACCESSORS = ['capabilities', 'log', 'skills', 'tools', 'http', 'proc', 'ui']
6
- const SERVICES = {
6
+ /** Host v1 能力→[访问器, 必需方法] 契约。导出为单一真源:内核门面与能力探测都引用它,
7
+ * 不再各自硬编码 os.plugins 的 dsh 方法名(listBundles/setPluginEnabled…)。 */
8
+ export const HOST_SERVICE_CONTRACT = {
7
9
  'os.skills': ['skills', ['registerProvider']],
8
10
  'os.tools': ['tools', ['register']],
9
11
  'os.net': ['http', ['createApp', 'createSharedHost']],
@@ -12,6 +14,7 @@ const SERVICES = {
12
14
  'os.ui': ['ui', ['createEditorHost']],
13
15
  'os.plugins': ['plugins', ['listBundles', 'listPlugins', 'setBundleEnabled', 'setPluginEnabled']],
14
16
  'os.assets': ['assets', ['put', 'get']],
17
+ 'os.works': ['works', ['backendFor']],
15
18
  }
16
19
 
17
20
  function invalid(path, expectation) {
@@ -68,7 +71,7 @@ export function assertHostContract(host) {
68
71
  if (typeof logger[method] !== 'function') invalid(`host.log().${method}`, 'must be a function')
69
72
  }
70
73
  }
71
- for (const [capability, [accessor, methods]] of Object.entries(SERVICES)) {
74
+ for (const [capability, [accessor, methods]] of Object.entries(HOST_SERVICE_CONTRACT)) {
72
75
  if (!Object.hasOwn(capabilities, capability)) continue
73
76
  if (typeof host[accessor] !== 'function') {
74
77
  invalid(`host.${accessor}`, `must be a function when advertising ${capability}`)
@@ -15,6 +15,9 @@
15
15
  * web() { register({kind, path, handler}) => dispose, port } | undefined
16
16
  * proc() { start(serviceSpec) => Promise<{errors?}>, stop(id) }
17
17
  * ui() { createEditorHost({ id, dir, basePath, index }) }
18
+ * assets() { put, get, ... } | undefined —— 资产字节仓(asset-service)
19
+ * works() { backendFor, claimSessionMode, ... } | undefined —— 作品目录(work-store,
20
+ * 可选持久化层:缺席时内核 os.works 返回 null,应用自行降级内存态)
18
21
  *
19
22
  * `web()` 是宿主网页端口本身(dsh 即 ctx.webServer)。拿到它时,内核一律把 HTTP
20
23
  * 挂到该端口的路径前缀下,不再另起端口;拿不到才退回 os.net 的独立监听。
@@ -46,5 +49,6 @@ export function createDshHost(ctx) {
46
49
  ui: () => getService(ctx, 'editorHost'),
47
50
  plugins: () => getService(ctx, 'pluginManager'),
48
51
  assets: () => getService(ctx, 'assets'),
52
+ works: () => getService(ctx, 'workStore'),
49
53
  }
50
54
  }
@@ -13,7 +13,8 @@ import { AbiError, ERROR_CODES, toAbiError } from '../abi/errors.mjs'
13
13
  import { createLoader } from '../abi/loader.mjs'
14
14
  import { BASE_CAPABILITIES, detectDshCapabilities } from './host/caps.mjs'
15
15
  import { createDshHost } from './host/dsh.mjs'
16
- import { assertHostContract } from './host/contract.mjs'
16
+ import { assertHostContract, HOST_SERVICE_CONTRACT } from './host/contract.mjs'
17
+ import { assetUrl } from '../abi/assets.mjs'
17
18
  import { createSkillAdapter } from './adapters/skill-provider.mjs'
18
19
  import { createToolProviderAdapter } from './adapters/tool-provider.mjs'
19
20
  import { createRuntimeDriverAdapter } from './adapters/runtime-driver.mjs'
@@ -88,7 +89,8 @@ export function createKernel(ctx, config = {}, options = {}) {
88
89
 
89
90
  function pluginManager() {
90
91
  const service = hostService('plugins', 'os.plugins')
91
- for (const method of ['listBundles', 'listPlugins', 'setBundleEnabled', 'setPluginEnabled']) {
92
+ // 方法名单一真源 = Host 契约(contract.mjs),内核不再硬编码 dsh 方法名。
93
+ for (const method of HOST_SERVICE_CONTRACT['os.plugins'][1]) {
92
94
  if (typeof service[method] !== 'function') {
93
95
  throw new AbiError(ERROR_CODES.E_CAP_MISSING,
94
96
  `os.plugins 不可用:pluginManager 缺少 ${method}`, { capability: 'os.plugins', method })
@@ -143,7 +145,15 @@ export function createKernel(ctx, config = {}, options = {}) {
143
145
  assets: {
144
146
  put: (value, contentType) => hostService('assets', 'os.assets').put(value, contentType),
145
147
  get: (id) => hostService('assets', 'os.assets').get(id),
146
- url: (id) => `/assets/${encodeURIComponent(String(id))}`,
148
+ url: (id) => assetUrl(id),
149
+ },
150
+
151
+ /** 作品目录门面(可选持久化层):work-store 缺席时返回 null,应用自行降级内存态。
152
+ * 与 os.assets(必需字节仓,缺席抛 E_CAP_MISSING)不同——works 是可选增强,
153
+ * 不在 core 六件内。用 os.caps.has('os.works') 探测可用性,不再 safeGet(ctx,'workStore') 裸摸。 */
154
+ get works() {
155
+ const service = typeof host.works === 'function' ? host.works() : null
156
+ return service && typeof service.then !== 'function' ? service : null
147
157
  },
148
158
 
149
159
  /** 能力检查与自报。 */
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/foundation",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "dsh 插件基石层:接口 ABI、插件加载器与内核服务 ctx.os。应用插件只声明接口,不写装配代码。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/plugin-kit",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "description": "DSH 插件基础设施标准件:HTTP/MCP、单实例锁、参数校验、技能 provider、journal 存储、编辑器传输与租约。",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -10,11 +10,13 @@
10
10
  "./service/mcp-http": "./src/service/mcp-http.mjs",
11
11
  "./service/server": "./src/service/server.mjs",
12
12
  "./service/api": "./src/service/api.mjs",
13
+ "./service/static": "./src/service/static.mjs",
13
14
  "./tools/validate": "./src/tools/validate.mjs",
14
15
  "./tools/result": "./src/tools/result.mjs",
15
16
  "./skills/provider": "./src/skills/provider.mjs",
16
17
  "./editor/transport": "./src/editor/transport.js",
17
18
  "./editor/lease": "./src/editor/lease.mjs",
19
+ "./editor/heartbeat": "./src/editor/heartbeat.mjs",
18
20
  "./editor/shadow": "./src/editor/shadow.mjs",
19
21
  "./store/journal-store": "./src/store/journal-store.mjs",
20
22
  "./store/blob-store": "./src/store/blob-store.mjs",
@@ -45,7 +45,10 @@ self.onmessage = function(e) {
45
45
  function startHeartbeat() {
46
46
  if (intervalHandle) clearInterval(intervalHandle);
47
47
 
48
- // 每 4 秒发送心跳(留 1 秒缓冲,避免刚好 5 秒时被判过期)
48
+ // 心跳节奏统一为 3s:单一真源是 editor/heartbeat.mjs 的 HEARTBEAT_INTERVAL_MS。
49
+ // 本文件是原样拷贝的经典 Worker,运行时不能 import npm 模块,故以字面量承载节奏,
50
+ // 由 test/heartbeat-constants.test.mjs 钉死与常量一致,防止再次漂移。
51
+ // 心跳对象是编辑器「在场租约」(editor-host /claim);两层租约语义见 heartbeat.mjs 头注。
49
52
  intervalHandle = setInterval(() => {
50
53
  if (!active) return;
51
54
 
@@ -66,7 +69,7 @@ function startHeartbeat() {
66
69
  });
67
70
  }
68
71
  });
69
- }, 4000);
72
+ }, 3000);
70
73
 
71
74
  // 立即发送第一次
72
75
  sendClaim().catch(() => {});
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 编辑器「在场租约」心跳节奏常量单一真源(P2-13b)。
3
+ *
4
+ * 背景:心跳节奏曾在两处手工对齐而漂移——plugin-kit 的 heartbeat-worker.js 写死
5
+ * 4000ms(还留着「避免 5 秒判过期」的过期注释),document-workbench 客户端却是
6
+ * 3000ms。两者必须同拍,否则编辑器判活与文档 owner 判活快慢不一。这里把节奏收敛
7
+ * 成一个常量,客户端直接 import;worker 是原样拷贝的经典 Web Worker(运行时不能
8
+ * import npm 模块),其 setInterval 字面量由 test/heartbeat-constants.test.mjs 钉死
9
+ * 等于本常量,防止再次漂移。统一取架构审查建议的 3s。
10
+ *
11
+ * 两层租约语义不同,都要保留(本常量只统一「心跳节奏」,不合并两层租约):
12
+ * 1. 在场租约(presence)——@capyclaw/plugin-kit/editor/lease.mjs 的 createEditorLease,
13
+ * 由 editor-host 的 /claim 消费,「显示即连接」:新窗口强制抢占、旧窗口静默待命;
14
+ * TTL 10s、无 epoch,靠客户端每 HEARTBEAT_INTERVAL_MS 心跳续租。
15
+ * 2. 所有权租约(owner)——@capyclaw/document-workbench/session 的 claimOwner/OWNER_TTL,
16
+ * deck/文档级所有权,带 epoch fencing(换人 +1、旧 owner 回执被丢弃)。PPT 的
17
+ * A/projects/ppt/src/server/store/lease.mjs 只是它的兼容再导出。此为套件领域件,
18
+ * 不在本次改造范围,仅在此说清两层,避免误把在场租约当成所有权租约。
19
+ * 两条租约线共用「心跳 3s、TTL 10s」的并发协议;TTL 的运行时真源仍是 lease.mjs 的
20
+ * DEFAULT_TTL 与 document-workbench 的 OWNER_TTL(均已为 10s,未漂移,不在本次改动范围)。
21
+ *
22
+ * 本文件零依赖、browser-safe(无 node:*),可被编辑器客户端 bundle 直接 import。
23
+ */
24
+
25
+ /** 心跳间隔(毫秒):在场租约与文档 owner 租约共用的续租节奏,单一真源。 */
26
+ export const HEARTBEAT_INTERVAL_MS = 3000
@@ -0,0 +1,79 @@
1
+ /**
2
+ * 静态文件服务公共核心(P2-13a)。
3
+ *
4
+ * service-host 与 editor-host 各有一套静态文件服务,其中「路径穿越防护 / 挂载前缀
5
+ * 归一与命中 / 相对路径解码 / files 显式映射 / 基础响应头」这几段逻辑逐字重复。
6
+ * 这里把它们收敛成一组纯函数作为单一真源,两个宿主都 import 本文件,不再各写一份。
7
+ *
8
+ * 边界(刻意不收敛的部分):本文件只做「无 IO 的路径/头部计算」,不碰响应政策。
9
+ * 两宿主的行为差异必须各自保留——
10
+ * - 畸形百分号编码:service-host 回 400,editor-host 交还路由链(return false);
11
+ * - 目录入口补尾斜杠 301、ETag/gzip/304/vary:仅 editor-host;
12
+ * - content-type 取值:service-host 用 mimeFor(请求 rel) + explicitType,
13
+ * editor-host 用 mimeFor(落盘文件路径);
14
+ * - 读盘策略:service-host 每次 readFileSync,editor-host 走 (size,mtime) 缓存。
15
+ * 因此 decodeStaticRel 畸形时返回 null(而非抛错/替宿主回响应),由调用方决定 400 还是放行。
16
+ *
17
+ * 只依赖 node 内置(node:path),不 import 本包其它文件,不成环(与 util/http.mjs 同风格)。
18
+ */
19
+ import path from 'node:path'
20
+
21
+ /** 路径穿越防护:只允许落在 root 内(含 root 自身),越界返回 null。两宿主共用。 */
22
+ export function safeJoin(root, rel) {
23
+ const target = path.resolve(root, `.${path.sep}${rel}`)
24
+ const base = path.resolve(root)
25
+ return target === base || target.startsWith(base + path.sep) ? target : null
26
+ }
27
+
28
+ /** 挂载前缀归一:'/' → ''(挂全部);其余去掉尾斜杠。空/缺省按 '' 处理。 */
29
+ export function cleanStaticPrefix(prefix) {
30
+ return prefix === '/' ? '' : String(prefix || '').replace(/\/+$/, '')
31
+ }
32
+
33
+ /** 前缀命中:空前缀命中一切;非空须精确等于前缀或其子路径。 */
34
+ export function staticPrefixHit(pathname, prefix) {
35
+ return !prefix || pathname === prefix || pathname.startsWith(prefix + '/')
36
+ }
37
+
38
+ /** 去掉挂载前缀后的原始相对路径(未解码)。 */
39
+ export function staticRelRaw(pathname, prefix) {
40
+ return prefix ? pathname.slice(prefix.length) : pathname
41
+ }
42
+
43
+ /**
44
+ * 解码相对路径:空/'/' 落到 index;其余去掉 leading 斜杠后 decodeURIComponent。
45
+ * 畸形百分号编码(URIError)返回 null——由宿主决定回 400(service-host)还是
46
+ * 交还路由链(editor-host),本核心不替宿主做响应政策。
47
+ */
48
+ export function decodeStaticRel(relRaw, index = 'index.html') {
49
+ try {
50
+ return relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
51
+ } catch {
52
+ return null
53
+ }
54
+ }
55
+
56
+ /** files 显式映射查表:relRaw 为空时用 '/' 键;未命中返回 null(宿主交还路由链)。 */
57
+ export function staticFileHit(files, relRaw) {
58
+ if (!files) return null
59
+ return files[relRaw === '' ? '/' : relRaw] || files[relRaw] || null
60
+ }
61
+
62
+ /** 映射条目 → [文件名, 显式 content-type(可空)]。字符串条目无显式 type。 */
63
+ export function staticHitNameType(hit) {
64
+ return Array.isArray(hit) ? [hit[0], hit[1]] : [hit, undefined]
65
+ }
66
+
67
+ /**
68
+ * 静态 200 基础响应头:content-type/length + 安全与缓存政策(两宿主一致的五项)。
69
+ * no-cache = 允许缓存但每次回源校验;editor-host 会在此之上追加 etag/vary。
70
+ */
71
+ export function staticBaseHeaders(type, length) {
72
+ return {
73
+ 'content-type': type,
74
+ 'content-length': length,
75
+ 'x-content-type-options': 'nosniff',
76
+ 'referrer-policy': 'no-referrer',
77
+ 'cache-control': 'no-cache',
78
+ }
79
+ }
@@ -575,7 +575,7 @@ export class WorkspaceClient {
575
575
 
576
576
  /** 插件的 JournalStore 持久化接口 → 中间层 workspace。 */
577
577
  export class WorkspaceBackend {
578
- constructor({ client, workId = 'main', journalPath = null }) {
578
+ constructor({ client, workId = 'main', journalPath = null, project = null }) {
579
579
  /* 结构化契约:workspace-service 可能来自另一份 kit 快照。 */
580
580
  if (!client || typeof client.put !== 'function' || typeof client.getJson !== 'function') {
581
581
  throw new Error('WorkspaceBackend 需要 WorkspaceClient 兼容实现')
@@ -583,6 +583,9 @@ export class WorkspaceBackend {
583
583
  this.client = client
584
584
  this.workId = workId
585
585
  this.journalPath = journalPath || null
586
+ /* checkpoint 列表投影(形状声明):内核只产出通用信封,业务字段(如 PPT 的 slides)
587
+ * 由套件适配层传入 project(payload, base) 叠加。缺省纯信封,不硬编码任何业务名词。 */
588
+ this.project = typeof project === 'function' ? project : null
586
589
  this.stateKey = 'state.json'
587
590
  this.journalKey = 'journal.jsonl'
588
591
  this.checkpointPrefix = 'checkpoints/'
@@ -624,23 +627,27 @@ export class WorkspaceBackend {
624
627
  return { name, createdAt: payload.createdAt, meta: payload.meta || {} }
625
628
  }
626
629
 
627
- listCheckpoints() {
630
+ listCheckpoints(opts = {}) {
631
+ const project = typeof opts.project === 'function' ? opts.project : this.project
628
632
  return this.client.list(this.workId)
629
633
  .filter((item) => item.key.startsWith(this.checkpointPrefix) && item.key.endsWith('.json'))
630
634
  .map((item) => {
631
635
  try {
632
636
  const payload = this.client.getJson(this.workId, item.key)
633
637
  if (!payload) return null
634
- return {
638
+ /* 通用会话信封:不含任何业务名词(slides/deck 等)。业务字段经 project 叠加。
639
+ * 约定与 document-workbench projectCheckpoint 一致:project(payload, base) 只返回
640
+ * 「扩展字段」,由 backend 合并 base({...base, ...extra}),保证 name/createdAt/meta 不丢。 */
641
+ const base = {
635
642
  name: payload.name,
636
643
  seq: payload.seq,
637
644
  appliedSeq: payload.appliedSeq,
638
645
  pending: !!payload.pending,
639
646
  title: payload.title,
640
- slides: payload.slides,
641
647
  createdAt: payload.createdAt,
642
648
  meta: payload.meta || {},
643
649
  }
650
+ return project ? { ...base, ...project(payload, base) } : base
644
651
  } catch { return null }
645
652
  })
646
653
  .filter(Boolean)
@@ -650,7 +657,8 @@ export class WorkspaceBackend {
650
657
  readCheckpoint(name) {
651
658
  const key = `${this.checkpointPrefix}${name}.json`
652
659
  const payload = this.client.getJson(this.workId, key, null)
653
- if (!payload || !payload.deck) throw new Error('checkpoint 内容损坏: ' + name)
660
+ /* 只校验载荷存在;业务形状(如 PPT 的 deck)由套件适配层 / DocumentSession 的 documentKey 校验。 */
661
+ if (!payload) throw new Error('checkpoint 内容损坏: ' + name)
654
662
  return payload
655
663
  }
656
664
  }
@@ -9,8 +9,9 @@ import semver from 'semver'
9
9
 
10
10
  /**
11
11
  * 验证规则定义
12
+ * (导出供回归测试使用:test/versions.test.mjs 校验版本表与实际包版本对齐,M12)
12
13
  */
13
- const RULES = {
14
+ export const RULES = {
14
15
  // 必需文件
15
16
  REQUIRED_FILES: ['package.json', 'README.md', 'lib'],
16
17
 
@@ -29,14 +30,18 @@ const RULES = {
29
30
  // 有效的平台
30
31
  VALID_PLATFORMS: ['web', 'desktop', 'both'],
31
32
 
32
- // 基础设施包的锁定版本范围(统一走 @capyclaw/* scope 名)
33
+ // 基础设施包的锁定版本范围(统一走 @capyclaw/* scope 名)。
34
+ // M12 对齐:以 C/packages/<pkg>/package.json 的实际版本为准(2026-11-23 核对:
35
+ // foundation 0.1.10 / plugin-kit 0.2.7 / service-host 0.1.6 / tool-host 0.3.1 /
36
+ // asset-service 0.1.5 / suite-kit 0.2.0)。检查用 intersects/satisfies 语义,
37
+ // 旧声明(如 ^0.1.1、^0.3.0)仍与现值相交,不会新增噪音;真正过期的范围才告警。
33
38
  INFRASTRUCTURE_VERSIONS: {
34
- '@capyclaw/foundation': '^0.1.1',
35
- '@capyclaw/plugin-kit': '^0.2.0',
36
- '@capyclaw/service-host': '^0.1.0',
37
- '@capyclaw/tool-host': '^0.1.0',
38
- '@capyclaw/asset-service': '^0.1.0',
39
- '@capyclaw/suite-kit': '^0.1.0'
39
+ '@capyclaw/foundation': '^0.1.10',
40
+ '@capyclaw/plugin-kit': '^0.2.7',
41
+ '@capyclaw/service-host': '^0.1.6',
42
+ '@capyclaw/tool-host': '^0.3.1',
43
+ '@capyclaw/asset-service': '^0.1.5',
44
+ '@capyclaw/suite-kit': '^0.2.0'
40
45
  }
41
46
  }
42
47
 
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "@capyclaw/plugin-validator",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "DSH 插件强制验证工具:检查目录结构、依赖规范、代码质量",
5
5
  "type": "module",
6
6
  "main": "./lib/index.mjs",
7
7
  "bin": {
8
8
  "validate-plugin": "./bin/cli.mjs"
9
9
  },
10
- "scripts": {},
10
+ "scripts": {
11
+ "test": "node --test test/*.test.mjs"
12
+ },
11
13
  "dependencies": {
12
14
  "semver": "^7.5.4",
13
15
  "yaml": "^2.3.4"
@@ -7,7 +7,7 @@
7
7
  "packages": {
8
8
  "@capyclaw/tool-host": {
9
9
  "role": "provider",
10
- "version": "^0.3.1",
10
+ "version": "^0.3.2",
11
11
  "path": ".",
12
12
  "provides": {
13
13
  "services": [
@@ -4,10 +4,12 @@
4
4
  * 同时落地“会话模式锁”这一基础设施能力:
5
5
  * · 把 work-store 惰性解析器注入 toolHost(模式锁的存储真源);
6
6
  * · 给 DSH tools 服务挂全局 guard(异领域调用硬拒兜底);
7
- * · 注册框架核心工具 mode_lock / mode_status(无领域,恒可见)——显式锁定入口。
7
+ * · 注册框架核心工具 mode_lock / mode_status(无领域,恒可见)——显式锁定入口;
8
+ * · 给 DSH systemPrompt 挂动态感知 section(锁定即告知模型主区工作台与交付路径)。
8
9
  * 核心工具与 guard 的注册统一走 modeGate.install(tools)(幂等):apply 时 best-effort 挂一次,
9
10
  * 若那一刻 tools 服务尚未就绪,首个套件注册(registerWithDsh / bridge host)会再调 install 补上,
10
- * 故不依赖加载顺序。所有经 toolHost.registerWithDsh / bridge host 注册的领域能力自动受锁约束,套件零接线。
11
+ * 故不依赖加载顺序。感知闸同理走 modeGate.installPrompt(systemPrompt)。
12
+ * 所有经 toolHost.registerWithDsh / bridge host 注册的领域能力自动受锁约束,套件零接线。
11
13
  */
12
14
  import { defineDriver } from '@capyclaw/foundation/abi'
13
15
  import { createToolHost } from '../src/index.mjs'
@@ -28,8 +30,15 @@ export const { name, inject, apply } = defineDriver({
28
30
  const tools = safeGet(ctx, 'tools')
29
31
  const gateDispose = (tools && typeof tools.register === 'function') ? service.modeGate.install(tools) : null
30
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
+
31
39
  console.log('[tool-host] ready (mode-gate enabled)')
32
40
  return () => {
41
+ if (typeof promptDispose === 'function') promptDispose()
33
42
  if (typeof gateDispose === 'function') gateDispose()
34
43
  if (typeof dispose === 'function') dispose()
35
44
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/tool-host",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "DSH 公共工具面插件:能力 DSL、工具注册表、参数校验、契约报告、MCP 协议壳与 instructions 模板,向插件提供 ctx.toolHost。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
@@ -363,6 +363,16 @@ export function registerWithDsh(ctx, registry, { namespace = '', domain = '', mo
363
363
  const gateDispose = modeGate ? modeGate.install(ctx.tools) : null
364
364
  const disposers = []
365
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
+ }
366
376
  try {
367
377
  for (const tool of registry?.TOOLS || []) {
368
378
  const impl = registry.TOOL_IMPL?.[tool.name]
@@ -422,8 +432,10 @@ export function createToolHost(config = {}) {
422
432
  // (driver 注入 () => safeGet(ctx,'workStore'));底座缺席则降级为恒可见、不拒。
423
433
  const modeGate = createModeGate({ getWorkStore: config.getWorkStore })
424
434
  return {
425
- api: createServiceApi('toolHost', '1.2.0', ['dsl', 'registry', 'validate', 'contract', 'mcp', 'instructions', 'native-tools', 'descriptors', 'mode-gate']),
426
- version: '0.3.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',
427
439
  defineTool,
428
440
  defineCapability,
429
441
  createRegistry: (capabilities, options = {}) => createRegistry(capabilities, { ...config, ...options }),
@@ -431,7 +443,7 @@ export function createToolHost(config = {}) {
431
443
  createToolDispatcher,
432
444
  createCapabilityReport,
433
445
  buildInstructions,
434
- // 服务级注册自动带会话模式锁(when 可见性 + guard 硬拒 + 调用者会话 ALS),套件零接线。
446
+ // 服务级注册自动带会话模式锁(when 可见性 + guard 硬拒 + 感知提示 + 调用者会话 ALS),套件零接线。
435
447
  registerWithDsh: (ctx, registry, options = {}) => registerWithDsh(ctx, registry, { modeGate, ...options }),
436
448
  validateToolArguments,
437
449
  modeGate,
@@ -5,11 +5,15 @@
5
5
  * 该领域的工具;其余已注册能力(browser_* 等)从工具声明里消失,且即便被强行
6
6
  * 调用也在分发层硬拒。所有经 tool-host 注册的能力自动受此约束。
7
7
  *
8
- * 三道原生闸里的两道在此落地:
8
+ * 三道原生闸在此全部落地:
9
9
  * · when(可见性):registerWithDsh / bridge host 给每个领域工具挂 whenFor(name),
10
10
  * DSH 每步 resolve() 求值,false 同时从声明与分发中排除该工具。
11
11
  * · guard(分发硬拒,兜底):install(tools) 挂一个全局 ToolGuard,异领域调用返回
12
12
  * denial。单调不可翻回,兜住任何绕过 when 的路径。
13
+ * · awareness(模型感知):installPrompt(systemPrompt) 注册一个动态提示 section,
14
+ * 每次组装按会话读锁状态,锁定即告知模型「主区工作台是唯一交付界面、用本领域
15
+ * 工具、勿用文件工具绕过」。缺了这道闸,when/guard 只挡得住领域工具,模型仍会
16
+ * 用无 domain 的内置文件工具(write/pwsh/office_*)绕过主区(2026-11-23 根因)。
13
17
  *
14
18
  * 领域来源:TOOL_META.domain(defineTool/defineCapability/createRegistry 声明)。
15
19
  * 存储真源:work-store.getSessionMode(sid)(终生固化,无 unlock)。
@@ -29,6 +33,9 @@ export function createModeGate({ getWorkStore } = {}) {
29
33
  let coreToolsRegistered = false
30
34
  const coreDisposers = []
31
35
  let installRefs = 0 // 安装方引用计数(见 install 注释)
36
+ let promptInstalled = false // 感知闸:动态提示 section 是否已注册
37
+ const promptDisposers = []
38
+ let promptRefs = 0 // 感知闸安装方引用计数(与 install 同语义)
32
39
 
33
40
  function store() {
34
41
  try { return typeof getWorkStore === 'function' ? getWorkStore() : null } catch { return null }
@@ -196,6 +203,57 @@ export function createModeGate({ getWorkStore } = {}) {
196
203
  }
197
204
  }
198
205
 
206
+ /**
207
+ * 感知闸文本:锁定会话里注入系统提示,让模型知道主区工作台的存在与唯一交付地位。
208
+ * 只约束「工作台内容任务」的交付路径,不禁止为修插件/查资料等元任务读文件。
209
+ */
210
+ function awarenessText(kind) {
211
+ return `【会话工作模式锁】本会话已锁定为「${kind}」工作模式:GUI 主区界面就是「${kind}」工作台,它是本会话工作台内容任务的指定交付界面。\n`
212
+ + `- 用户要求创作/编辑文档、稿件等工作台内容时,必须用 ${kind}_* 专用工具直接读写主区工作台(先加载 ${kind} 相关 skill),让用户在主区实时看到结果。\n`
213
+ + `- 不得改用 write/pwsh/office_* 等通用文件工具生成独立文件来绕过主区交付;其他领域的工具与技能不适用于本会话。\n`
214
+ + `- 锁终生固化、不可解锁;确需其他领域,请提示用户新开会话。锁状态可用 mode_status 查询。`
215
+ }
216
+
217
+ /**
218
+ * 感知闸:把锁状态作为动态系统提示 section 挂到 DSH systemPrompt 服务(幂等)。
219
+ * text 回调每次 assemble 求值(DSH 每步组装提示时调用),按 context.agent.session.id
220
+ * 读锁:锁定 → 注入感知文本;未锁定/无会话 → 返回 ''(空 section 自动消失,零开销)。
221
+ * 锁可在会话中途被认领(墙上点选),回调动态读取故无需监听 agent 生命周期。
222
+ * 引用计数与 install(tools) 同语义:driver apply 与各套件 registerWithDsh 共享一份注册。
223
+ * 底座缺席(无 systemPrompt / 不支持 section)→ 降级为仅 when/guard 生效。
224
+ * @returns {() => void} 引用计数 disposer
225
+ */
226
+ function installPrompt(systemPrompt) {
227
+ if (!systemPrompt || typeof systemPrompt.section !== 'function') return () => {}
228
+ if (!promptInstalled) {
229
+ try {
230
+ const dispose = systemPrompt.section({
231
+ name: 'capyclaw:session-mode-lock',
232
+ order: 900,
233
+ interpolate: false,
234
+ text: (context) => {
235
+ const kind = modeOf(context?.agent?.session?.id)
236
+ return kind ? awarenessText(kind) : ''
237
+ },
238
+ })
239
+ if (typeof dispose === 'function') promptDisposers.push(dispose)
240
+ promptInstalled = true
241
+ } catch { /* 底座不支持 section 时降级:仅 when/guard 生效 */ }
242
+ }
243
+ promptRefs++
244
+ let released = false
245
+ return () => {
246
+ if (released) return
247
+ released = true
248
+ promptRefs--
249
+ if (promptRefs > 0) return
250
+ for (const dispose of promptDisposers.splice(0)) {
251
+ try { dispose() } catch { /* 忽略重复释放 */ }
252
+ }
253
+ promptInstalled = false
254
+ }
255
+ }
256
+
199
257
  /**
200
258
  * 能力发现面过滤:锁定会话里剔除异领域描述符(conductor_discover 自动受约束)。
201
259
  * 无 domain 的描述符(编排/核心基建)保留。未锁定 → 原样返回。
@@ -210,5 +268,5 @@ export function createModeGate({ getWorkStore } = {}) {
210
268
  })
211
269
  }
212
270
 
213
- return { declareTools, domainOf, modeOf, isVisible, whenFor, guard, install, filterEntries }
271
+ return { declareTools, domainOf, modeOf, isVisible, whenFor, guard, install, installPrompt, filterEntries }
214
272
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/publisher",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "npm 发布器:插件页里把打包好的插件包拖进来就能发布或更新到 npm,发布后可就地更新本机安装;同时保留 publisher_* 原生工具做批量预演与真发布",
5
5
  "type": "module",
6
6
  "main": "./plugin.mjs",
package/server/impl.mjs CHANGED
@@ -299,15 +299,24 @@ export async function orderGate(pkg, localMap, batch, npm) {
299
299
  * 认证令牌字段的模式用拼接构造,注释里也不写整串,
300
300
  * 否则扫描器会把自己的源码当成泄漏(自噬假阳性)。) */
301
301
  const AUTH_TOKEN_RE = new RegExp('_auth' + 'Token', 'i')
302
+ /* 凭据形态:任何文件(含随包携带的第三方依赖)里出现都拒绝——泄漏的令牌不分出处。 */
302
303
  const SECRET_PATTERNS = [
303
304
  [/sk-[A-Za-z0-9]{20,}/, 'API key 形态(sk-…)'],
304
305
  [/npm_[A-Za-z0-9]{20,}/, 'npm token 形态(npm_…)'],
305
306
  [AUTH_TOKEN_RE, 'npmrc 认证令牌字段'],
307
+ ]
308
+ /* 本机绝对路径形态:只查包自身的代码/配置。随包实体化的公共第三方依赖
309
+ * (node_modules 下,本就发布在 npm 上)携带的是示例/CI 路径(如 Playwright
310
+ * coreBundle 里的 CI 用户家目录、@types/node JSDoc 里的示例用户目录),属良性内容,
311
+ * 不是发布者本机信息泄漏——对它们跳过路径形态,避免误报阻断正常发布。
312
+ * (本注释刻意不写整串示例路径,防扫描器自噬假阳性,见 AUTH_TOKEN_RE 处说明。) */
313
+ const LOCAL_PATH_PATTERNS = [
306
314
  [/[A-Za-z]:\\Users\\/i, '本机绝对路径(盘符:\\Users\\)'],
307
315
  [/\/(home|Users)\/[A-Za-z0-9._-]+\//, '本机绝对路径(/home/ / /Users/)'],
308
316
  ]
309
317
 
310
- /** 扫描目录内全部文本文件,返回命中的密钥/本机信息描述串。 */
318
+ /** 扫描目录内全部文本文件,返回命中的密钥/本机信息描述串。
319
+ * node_modules 内的第三方文件只查凭据形态,不查本机路径形态(见 LOCAL_PATH_PATTERNS 注释)。 */
311
320
  export function scanDirForSecrets(root) {
312
321
  const hits = []
313
322
  const walk = (dir) => {
@@ -318,8 +327,11 @@ export function scanDirForSecrets(root) {
318
327
  if (entry.isDirectory()) { walk(file); continue }
319
328
  let text = null
320
329
  try { text = fs.readFileSync(file, 'utf8') } catch { continue } /* 二进制/不可读跳过 */
321
- for (const [pattern, label] of SECRET_PATTERNS) {
322
- if (pattern.test(text)) hits.push(`${path.relative(root, file)}: ${label}`)
330
+ const rel = path.relative(root, file)
331
+ const vendored = rel.split(path.sep).includes('node_modules')
332
+ const patterns = vendored ? SECRET_PATTERNS : [...SECRET_PATTERNS, ...LOCAL_PATH_PATTERNS]
333
+ for (const [pattern, label] of patterns) {
334
+ if (pattern.test(text)) hits.push(`${rel}: ${label}`)
323
335
  }
324
336
  }
325
337
  }
@@ -337,16 +349,11 @@ export async function packGateErrors(pkg, dir, npm) {
337
349
  for (const rel of Array.isArray(patch) ? patch : patch ? [patch] : []) {
338
350
  mustHave.push(String(rel).replace(/^\.\//, ''))
339
351
  }
340
- /* dsh.client 的浏览器半入口以 package.json 的 `./client` export 为准(DSH 就是这么
341
- * 解析的);只有没声明 export 时才回落约定的 client/client.js。
342
- * 旧断言硬编码 client/client.js,把 skin-aurora(./client.js)、plugin-drop
343
- * (./client.js)、my-works(./lib/client.js)这类合法布局误判成 pack-incomplete。 */
344
352
  if (pkg.dsh?.client) {
345
- const declared = pkg.exports?.['./client']
346
- const entry = typeof declared === 'string'
347
- ? declared
348
- : declared?.default || declared?.import || declared?.require
349
- mustHave.push(String(entry || 'client/client.js').replace(/^\.\//, ''))
353
+ /* client 入口以 exports['./client'] 为准(各插件布局不一:client/client.js、
354
+ * 根 client.js、lib/client.js 都有),不能硬编码 client/client.js。 */
355
+ const clientEntry = pkg.exports?.['./client']
356
+ mustHave.push(clientEntry ? String(clientEntry).replace(/^\.\//, '') : 'client/client.js')
350
357
  }
351
358
  if (pkg.dsh?.suite) mustHave.push(String(pkg.dsh.suite).replace(/^\.\//, ''))
352
359
  const r = await npm.rawNpmRun(['pack', '--dry-run', '--json'], { cwd: dir })
@@ -404,21 +411,28 @@ function isRealSuite(dir, pkg) {
404
411
  }
405
412
  }
406
413
 
407
- /** 在 dist/suites/<bridge>/package 里找同名同版本的自包含拼装产物。 */
414
+ /** 在自包含拼装产物里找同名同版本的 suite。
415
+ * 现行 assemble 输出在 A/artifacts/suites/<bridge>/package;
416
+ * 兼容历史位置 dist/suites/<bridge>/package。 */
408
417
  function findAssembledSuite(root, name, version) {
409
- const suitesDir = path.join(root, 'dist', 'suites')
410
- if (!fs.existsSync(suitesDir)) return null
411
- let entries = []
412
- try { entries = fs.readdirSync(suitesDir, { withFileTypes: true }) } catch { return null }
413
- for (const entry of entries) {
414
- if (!entry.isDirectory()) continue
415
- const candidate = path.join(suitesDir, entry.name, 'package')
416
- const pkgFile = path.join(candidate, 'package.json')
417
- if (!fs.existsSync(pkgFile)) continue
418
- try {
419
- const p = JSON.parse(fs.readFileSync(pkgFile, 'utf8'))
420
- if (p.name === name && p.version === version) return candidate
421
- } catch { /* 坏包跳过 */ }
418
+ const suitesDirs = [
419
+ path.join(root, 'A', 'artifacts', 'suites'),
420
+ path.join(root, 'dist', 'suites'),
421
+ ]
422
+ for (const suitesDir of suitesDirs) {
423
+ if (!fs.existsSync(suitesDir)) continue
424
+ let entries = []
425
+ try { entries = fs.readdirSync(suitesDir, { withFileTypes: true }) } catch { continue }
426
+ for (const entry of entries) {
427
+ if (!entry.isDirectory()) continue
428
+ const candidate = path.join(suitesDir, entry.name, 'package')
429
+ const pkgFile = path.join(candidate, 'package.json')
430
+ if (!fs.existsSync(pkgFile)) continue
431
+ try {
432
+ const p = JSON.parse(fs.readFileSync(pkgFile, 'utf8'))
433
+ if (p.name === name && p.version === version) return candidate
434
+ } catch { /* 坏包跳过 */ }
435
+ }
422
436
  }
423
437
  return null
424
438
  }
@@ -443,7 +457,7 @@ export function preparePublishDir(dir, root, pkg) {
443
457
  const assembled = findAssembledSuite(root, pkg.name, pkg.version)
444
458
  if (!assembled) {
445
459
  return {
446
- error: `找不到自包含拼装产物:${pkg.name}@${pkg.version} 不在 dist/suites/*/package 里。`
460
+ error: `找不到自包含拼装产物:${pkg.name}@${pkg.version} 不在 A/artifacts/suites/*/package(或 dist/suites)里。`
447
461
  + '先跑 npm run assemble,否则发出去的 suite 里没有成员,安装后要回 registry 拉取。',
448
462
  }
449
463
  }