@capyclaw/scrapling 1.1.7 → 1.1.9

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 (35) 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/loader.mjs +8 -1
  5. package/node_modules/@capyclaw/foundation/abi/spec.mjs +5 -2
  6. package/node_modules/@capyclaw/foundation/abi/version.mjs +63 -5
  7. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  8. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
  9. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +11 -10
  10. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +8 -1
  11. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
  12. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
  13. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
  14. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +29 -2
  15. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
  16. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +31 -3
  17. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +12 -2
  18. package/node_modules/@capyclaw/foundation/package.json +1 -1
  19. package/node_modules/@capyclaw/plugin-kit/package.json +4 -1
  20. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
  21. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  22. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +3 -82
  23. package/node_modules/@capyclaw/plugin-kit/src/ledger.mjs +151 -0
  24. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  25. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
  26. package/node_modules/@capyclaw/portal/package.json +1 -1
  27. package/node_modules/@capyclaw/service-broker/README.md +1 -1
  28. package/node_modules/@capyclaw/service-broker/lib/control.mjs +23 -7
  29. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +60 -6
  30. package/node_modules/@capyclaw/service-broker/lib/host.mjs +11 -6
  31. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +15 -2
  32. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +0 -50
  33. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +30 -10
  34. package/node_modules/@capyclaw/service-broker/package.json +1 -1
  35. package/package.json +1 -1
@@ -91,7 +91,11 @@ export function createNet(host, config = {}) {
91
91
  }
92
92
  return
93
93
  }
94
- await new Promise((resolve) => setTimeout(resolve, WEB_LATE_POLL_MS))
94
+ await new Promise((resolve) => {
95
+ /* unref:迟到补挂的轮询定时器不得拖住进程退出(最长 60s 的尾延迟)。 */
96
+ const timer = setTimeout(resolve, WEB_LATE_POLL_MS)
97
+ timer.unref?.()
98
+ })
95
99
  }
96
100
  })().catch(() => {})
97
101
  }
@@ -116,7 +120,10 @@ export function createNet(host, config = {}) {
116
120
  if (!web && shouldWaitForWeb()) {
117
121
  const deadline = Date.now() + WEB_WAIT_MS
118
122
  while (!web && Date.now() < deadline && !closed) {
119
- await new Promise((resolve) => setTimeout(resolve, WEB_POLL_MS))
123
+ await new Promise((resolve) => {
124
+ const timer = setTimeout(resolve, WEB_POLL_MS)
125
+ timer.unref?.()
126
+ })
120
127
  web = webServer()
121
128
  }
122
129
  }
@@ -140,6 +147,9 @@ export function createNet(host, config = {}) {
140
147
  disposal = (async () => {
141
148
  if (!sharedHost) return
142
149
  // listen 失败由 ready/start 报告;清理仍需执行,且 close 失败不能被吞掉。
150
+ // 注意:dispose 在 listen 失败时仍 RESOLVE(错误经 ready/start 上报)——这是
151
+ // 被 network-lifecycle 测试固化的契约,close 不再二次上抛 listen 错,避免
152
+ // 破坏「清理成功即 dispose 成功」的语义。
143
153
  await listening.catch(() => {})
144
154
  // 迟到补挂的路由要一起撤掉,否则共享宿主关了、宿主网页端口上还留着分发器。
145
155
  try {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/foundation",
3
- "version": "0.1.9",
3
+ "version": "0.1.12",
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.6",
3
+ "version": "0.2.10",
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",
@@ -30,6 +32,7 @@
30
32
  "./tuning": "./src/tuning.mjs",
31
33
  "./util/fs-lock": "./src/util/fs-lock.mjs",
32
34
  "./util/http": "./src/util/http.mjs",
35
+ "./ledger": "./src/ledger.mjs",
33
36
  "./editor/heartbeat-worker": "./src/editor/heartbeat-worker.js"
34
37
  },
35
38
  "bin": {
@@ -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
@@ -6,8 +6,9 @@
6
6
  */
7
7
  import { tuning } from '../tuning.mjs'
8
8
 
9
- const DEFAULT_TTL = 15 // 秒
10
- const DEFAULT_HEARTBEAT = 3 // 秒(心跳间隔应小于 TTL)
9
+ /* 与文档 owner 租约(document-workbench OWNER_TTL)对齐为 10s:
10
+ * 两条租约线共用「心跳 3s、TTL 10s」的并发协议,避免编辑器判活比文档慢半拍。 */
11
+ const DEFAULT_TTL = 10 // 秒
11
12
 
12
13
  /**
13
14
  * 创建编辑器租约仲裁器。
@@ -57,83 +58,3 @@ export function createEditorLease(opts = {}) {
57
58
  },
58
59
  }
59
60
  }
60
-
61
- /**
62
- * 编辑器端自动挂接循环。
63
- * 首次 claim 强制抢占(后打开者赢),之后静默心跳。
64
- * @param {{
65
- * clientId: string,
66
- * claim: (force: boolean) => Promise<boolean>,
67
- * release?: () => void,
68
- * onActive?: () => void,
69
- * onStandby?: () => void,
70
- * retryMs?: number,
71
- * heartbeatMs?: number,
72
- * setInterval?: (cb: () => void) => any,
73
- * clearInterval?: (handle: any) => void
74
- * }} o
75
- */
76
- export function startAutoAttach(o) {
77
- if (!o || !o.clientId) throw new Error('startAutoAttach: clientId 必填')
78
- if (typeof o.claim !== 'function') throw new Error('startAutoAttach: claim 必须是函数')
79
-
80
- const retryMs = o.retryMs || 1000
81
- const heartbeatMs = o.heartbeatMs || DEFAULT_HEARTBEAT * 1000
82
- const setI = o.setInterval || ((cb) => setInterval(cb, heartbeatMs))
83
- const clearI = o.clearInterval || ((handle) => clearInterval(handle))
84
-
85
- let active = false
86
- let heartbeat = null
87
- let disposed = false
88
-
89
- async function tryClaim(force) {
90
- try {
91
- return await o.claim(force)
92
- } catch {
93
- return false
94
- }
95
- }
96
-
97
- function goActive() {
98
- if (active) return
99
- active = true
100
- try { o.onActive && o.onActive() } catch { /* 用户回调失败不阻塞挂接 */ }
101
- heartbeat = setI(async () => {
102
- if (disposed) return
103
- const ok = await tryClaim(false)
104
- if (!ok) goStandby()
105
- })
106
- }
107
-
108
- function goStandby() {
109
- if (!active) return
110
- active = false
111
- if (heartbeat != null) {
112
- clearI(heartbeat)
113
- heartbeat = null
114
- }
115
- try { o.onStandby && o.onStandby() } catch { /* 静默 */ }
116
- }
117
-
118
- ;(async () => {
119
- let first = true
120
- while (!disposed) {
121
- const ok = await tryClaim(first)
122
- first = false
123
- if (ok) {
124
- goActive()
125
- return
126
- }
127
- await new Promise((resolve) => setTimeout(resolve, retryMs))
128
- }
129
- })()
130
-
131
- return {
132
- get active() { return active },
133
- dispose() {
134
- disposed = true
135
- goStandby()
136
- try { o.release && o.release() } catch { /* 释放失败不阻塞退出 */ }
137
- },
138
- }
139
- }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * @capyclaw/plugin-kit/ledger —— capyclaw 全插件统一操作/状态台账(append-only JSONL)。
3
+ *
4
+ * 设计目标(2026-11-25 用户要求「统一管理、是否工作/工作状态如何都记录」):
5
+ * - 单一存储:每个 profile 一份 `plugin-data/capyclaw/plugin-log.jsonl`,所有底盘
6
+ * (wizard 管理操作、suite-kit 挂载状态、service-host 服务生命周期/运行时错误)
7
+ * 往同一份台账追加,读取面统一查询,不按插件各写各的。
8
+ * - 只记事件不记噪音:管理操作结果、挂载/退让/降级/失败/释放、listen/dispatch 错误。
9
+ * - 永不反噬宿主:所有写盘 try/catch 吞错(台账坏了不能影响插件激活)。
10
+ * - 环形上限:超过 maxBytes(默认 2MB)轮转为 `.1`(保留一代历史),不无限增长。
11
+ * - 去重聚合在读取侧:fingerprint = hash(name + code + 归一化栈顶/消息前三行),
12
+ * 同指纹累加 count/firstAt/lastAt,复发一眼可见;原始行保留审计轨迹。
13
+ * - 纯本地:不上传、不记会话内容;导出由用户手动脱敏。
14
+ *
15
+ * 依赖方向:仅 node 内置模块(fs/path/crypto),任何底盘都可安全 import。
16
+ */
17
+ import fs from 'node:fs'
18
+ import path from 'node:path'
19
+ import crypto from 'node:crypto'
20
+
21
+ /** 台账文件名(profile 的 plugin-data/capyclaw/ 下)。 */
22
+ export const LEDGER_FILENAME = 'plugin-log.jsonl'
23
+
24
+ /** profile 目录 → 台账绝对路径;profileDir 缺席返回 null(调用方降级为不记录)。 */
25
+ export function ledgerFileFor(profileDir) {
26
+ return profileDir ? path.join(profileDir, 'plugin-data', 'capyclaw', LEDGER_FILENAME) : null
27
+ }
28
+
29
+ /**
30
+ * 复发指纹:name + code + 归一化消息/栈顶前三行(数字/地址抹平),
31
+ * 同一缺陷的不同实例(端口号、时间戳、pid 不同)归到同一指纹。
32
+ */
33
+ export function fingerprintOf({ name, code, message, stackTop } = {}) {
34
+ const head = String(stackTop || message || '')
35
+ .split('\n').slice(0, 3).join('|')
36
+ .replace(/0x[0-9a-f]+/gi, '')
37
+ .replace(/\d+/g, '#')
38
+ const basis = `${name || ''}::${code || ''}::${head}`
39
+ return crypto.createHash('sha1').update(basis).digest('hex').slice(0, 12)
40
+ }
41
+
42
+ const clip = (v, n) => (typeof v === 'string' && v.length > n ? `${v.slice(0, n)}\n…(truncated)` : v)
43
+
44
+ /** 归一化一条台账记录:补 at/pid/fingerprint,截断超长 message/stackTop。 */
45
+ export function normalizeEntry(entry = {}) {
46
+ const e = {
47
+ at: typeof entry.at === 'number' ? entry.at : Date.now(),
48
+ pid: process.pid,
49
+ source: entry.source || 'unknown',
50
+ name: entry.name || null,
51
+ suite: entry.suite || null,
52
+ version: entry.version || null,
53
+ specKind: entry.specKind || null,
54
+ phase: entry.phase || 'runtime',
55
+ action: entry.action || null,
56
+ ok: entry.ok !== false,
57
+ degraded: entry.degraded === true,
58
+ code: entry.code || null,
59
+ message: clip(entry.message || null, 2000),
60
+ stackTop: clip(entry.stackTop || null, 1200),
61
+ mountPath: entry.mountPath || null,
62
+ url: entry.url || null,
63
+ jobId: entry.jobId || null,
64
+ }
65
+ e.fingerprint = entry.fingerprint || fingerprintOf(e)
66
+ return e
67
+ }
68
+
69
+ /**
70
+ * 追加一条记录(best-effort,绝不抛错)。超 maxBytes 先轮转 `.1`。
71
+ * @returns {object|null} 归一化后的记录;file 缺席或写失败返回 null。
72
+ */
73
+ export function appendLedger(entry, { file, maxBytes = 2 * 1024 * 1024 } = {}) {
74
+ if (!file) return null
75
+ try {
76
+ const e = normalizeEntry(entry)
77
+ fs.mkdirSync(path.dirname(file), { recursive: true })
78
+ try {
79
+ const st = fs.statSync(file)
80
+ if (st.size > maxBytes) { try { fs.renameSync(file, `${file}.1`) } catch { /* 轮转失败继续追加 */ } }
81
+ } catch { /* 新文件 */ }
82
+ fs.appendFileSync(file, `${JSON.stringify(e)}\n`)
83
+ return e
84
+ } catch {
85
+ return null
86
+ }
87
+ }
88
+
89
+ /**
90
+ * 读取台账(坏行跳过)。filter:since(epoch ms)/name(匹配 name 或 suite)/source/
91
+ * errorsOnly(ok===false)/degradedOnly;limit 上限 2000,返回时间序尾部。
92
+ */
93
+ export function readLedger({ file, since = 0, name = null, source = null, errorsOnly = false, degradedOnly = false, limit = 200 } = {}) {
94
+ if (!file) return []
95
+ let raw = ''
96
+ try { raw = fs.readFileSync(file, 'utf8') } catch { return [] }
97
+ const out = []
98
+ for (const line of raw.split('\n')) {
99
+ if (!line.trim()) continue
100
+ try {
101
+ const e = JSON.parse(line)
102
+ if (e && typeof e === 'object') out.push(e)
103
+ } catch { /* 坏行跳过 */ }
104
+ }
105
+ let rows = out.filter((e) => (e.at || 0) >= since)
106
+ if (name) rows = rows.filter((e) => e.name === name || e.suite === name)
107
+ if (source) rows = rows.filter((e) => e.source === source)
108
+ if (errorsOnly) rows = rows.filter((e) => e.ok === false)
109
+ if (degradedOnly) rows = rows.filter((e) => e.degraded === true)
110
+ const n = Math.max(1, Math.min(Number(limit) || 200, 2000))
111
+ return rows.slice(-n)
112
+ }
113
+
114
+ /** 按指纹聚合:复发计数 + 首末时间 + 最近一条样本(count 降序)。 */
115
+ export function aggregateLedger(entries = []) {
116
+ const groups = new Map()
117
+ for (const e of entries) {
118
+ const key = e.fingerprint || fingerprintOf(e)
119
+ const g = groups.get(key) || { fingerprint: key, name: e.name, code: e.code, count: 0, firstAt: e.at, lastAt: e.at, message: e.message, stackTop: e.stackTop }
120
+ g.count += 1
121
+ g.firstAt = Math.min(g.firstAt, e.at || g.firstAt)
122
+ if ((e.at || 0) >= g.lastAt) { g.lastAt = e.at || g.lastAt; g.message = e.message; g.stackTop = e.stackTop }
123
+ groups.set(key, g)
124
+ }
125
+ return [...groups.values()].sort((a, b) => b.count - a.count || b.lastAt - a.lastAt)
126
+ }
127
+
128
+ /**
129
+ * 健康摘要:窗口内(默认 24h)按 name 汇总 events/errors/degraded/lastAction,
130
+ * 外加 top 指纹(默认 5 条),供 capyclaw_health 一眼看出「谁没在工作/谁在复发」。
131
+ */
132
+ export function summarizeLedger(entries = [], { windowMs = 24 * 3600 * 1000, top = 5, now = Date.now() } = {}) {
133
+ const rows = entries.filter((e) => (e.at || 0) >= now - windowMs)
134
+ const per = new Map()
135
+ for (const e of rows) {
136
+ const key = e.name || e.suite || e.source || '?'
137
+ const p = per.get(key) || { name: key, events: 0, errors: 0, degraded: 0, lastAt: 0, lastAction: null, lastOk: null }
138
+ p.events += 1
139
+ if (e.ok === false) p.errors += 1
140
+ if (e.degraded === true) p.degraded += 1
141
+ if ((e.at || 0) >= p.lastAt) { p.lastAt = e.at || p.lastAt; p.lastAction = e.action; p.lastOk = e.ok }
142
+ per.set(key, p)
143
+ }
144
+ return {
145
+ windowMs,
146
+ events: rows.length,
147
+ errors: rows.filter((e) => e.ok === false).length,
148
+ per: [...per.values()].sort((a, b) => b.errors - a.errors || b.lastAt - a.lastAt),
149
+ top: aggregateLedger(rows.filter((e) => e.ok === false)).slice(0, top),
150
+ }
151
+ }
@@ -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
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/portal",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "DSH 基础设施标准件:服务就绪后把它的页面弹成置顶小窗(Edge/Chromium app 窗口 + Win32 几何/置顶),业务插件只需在 services.json 里声明 window。",
5
5
  "type": "module",
6
6
  "main": "./lib/index.mjs",
@@ -45,7 +45,7 @@ cordis insert 唯一一行(`cordis.patch.yml`),config:
45
45
  controlPort: 0 # >0 时embedded 也开控制端点
46
46
  stopOnUnload: false # true=插件卸载时全停(默认服务独立存活)
47
47
  skills:
48
- url: "http://127.0.0.1:<真实端口>" # 可选:ctx.skills 瘦客户端数据源(从 discovery 读回)
48
+ url: "http://127.0.0.1:<真实端口>" # 可选 standalone 模式:ctx.skillsHttp 瘦客户端数据源(默认不启用;技能标准路径是 skillProvider@1 进程内注册,不占用原生 ctx.skills)
49
49
  ```
50
50
 
51
51
  ## 服务规格 spec(与桌面后端 works_services 契约对齐)
@@ -61,21 +61,36 @@ function tokenMatches(expected, actual) {
61
61
 
62
62
  const isLoopback = isLoopbackAddress
63
63
 
64
- function jsonBody(req, limit = 8 * 1024 * 1024) {
64
+ function jsonBody(req, res, limit = 8 * 1024 * 1024) {
65
65
  return new Promise((resolve, reject) => {
66
66
  let size = 0
67
+ let aborted = false
67
68
  const chunks = []
68
69
  req.on('data', (chunk) => {
70
+ if (aborted) return
69
71
  size += chunk.length
70
- if (size > limit) { reject(new Error('body too large')); req.destroy(); return }
72
+ if (size > limit) {
73
+ /* 先回 413 再处理连接:客户端要能区分「体太大」与「连接被莫名掐断」。
74
+ * 不能立刻 destroy——响应字节还没刷出去就断连,客户端只会看到 ECONNRESET。
75
+ * 这里回完 413 后把剩余请求体排空丢弃(有 8MB 上限兜底,量可控),
76
+ * 让响应干净送达;病态超长上传由服务器级请求超时兜底。 */
77
+ aborted = true
78
+ if (res && !res.headersSent && !res.writableEnded) {
79
+ send(res, 413, { ok: false, error: `请求体超过上限 ${limit} 字节` })
80
+ }
81
+ reject(new Error('body too large'))
82
+ req.resume()
83
+ return
84
+ }
71
85
  chunks.push(chunk)
72
86
  })
73
87
  req.on('end', () => {
88
+ if (aborted) return
74
89
  const raw = Buffer.concat(chunks).toString('utf8')
75
90
  if (!raw) return resolve({})
76
91
  try { resolve(JSON.parse(raw)) } catch { reject(new Error('bad json')) }
77
92
  })
78
- req.on('error', reject)
93
+ req.on('error', (err) => { if (!aborted) reject(err) })
79
94
  })
80
95
  }
81
96
 
@@ -132,13 +147,13 @@ export function createControlServer(engine, options = {}) {
132
147
  }
133
148
 
134
149
  if (route === 'POST /control/apply') {
135
- const body = await jsonBody(req)
150
+ const body = await jsonBody(req, res)
136
151
  const result = await engine.apply(body.commands || [], { waitMs: body.waitMs })
137
152
  return send(res, result.ok ? 200 : 207, result)
138
153
  }
139
154
 
140
155
  if (route === 'POST /control/start') {
141
- const body = await jsonBody(req)
156
+ const body = await jsonBody(req, res)
142
157
  let spec = body.service
143
158
  if (!spec && body.id && manifestPath && existsSync(manifestPath)) {
144
159
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
@@ -170,7 +185,7 @@ export function createControlServer(engine, options = {}) {
170
185
  }
171
186
 
172
187
  if (route === 'POST /control/stop') {
173
- const body = await jsonBody(req)
188
+ const body = await jsonBody(req, res)
174
189
  if (!body.id) return send(res, 400, { ok: false, error: '缺 id' })
175
190
  return send(res, 200, await engine.stop(body.id))
176
191
  }
@@ -183,7 +198,8 @@ export function createControlServer(engine, options = {}) {
183
198
 
184
199
  send(res, 404, { ok: false, error: `未知端点 ${route}` })
185
200
  } catch (err) {
186
- send(res, 400, { ok: false, error: err.message })
201
+ /* jsonBody 超限时已回过 413 并断连,不能再往已结束的响应上写。 */
202
+ if (!res.headersSent && !res.writableEnded) send(res, 400, { ok: false, error: err.message })
187
203
  }
188
204
  })
189
205
  // 供宿主打日志用:只暴露位置,不暴露 token 本身。