@capyclaw/port-sidebar 1.0.6 → 1.0.7

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.
@@ -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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/port-sidebar",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "在 DSH 右侧边栏稳定展示一个本机端口页面:每个会话的侧边栏都确保存在指向该端口的 Browser tab,切换话题不消失。",
5
5
  "type": "module",
6
6
  "main": "./plugin.mjs",