@capyclaw/wall-suite 0.1.0 → 0.1.1

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 (63) hide show
  1. package/composition.lock.json +15 -15
  2. package/contract/wall-contract.json +1 -1
  3. package/dsh-suite.json +19 -9
  4. package/node_modules/@capyclaw/asset-service/dsh-suite.json +1 -1
  5. package/node_modules/@capyclaw/asset-service/package.json +1 -1
  6. package/node_modules/@capyclaw/asset-service/src/index.mjs +96 -9
  7. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  8. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +3 -1
  9. package/node_modules/@capyclaw/foundation/abi/index.mjs +15 -0
  10. package/node_modules/@capyclaw/foundation/abi/loader.mjs +8 -1
  11. package/node_modules/@capyclaw/foundation/abi/spec.mjs +5 -2
  12. package/node_modules/@capyclaw/foundation/abi/version.mjs +63 -5
  13. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  14. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
  15. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +11 -10
  16. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +8 -1
  17. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
  18. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
  19. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
  20. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +29 -2
  21. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
  22. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +31 -3
  23. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +12 -2
  24. package/node_modules/@capyclaw/foundation/package.json +1 -1
  25. package/node_modules/@capyclaw/plugin-kit/package.json +3 -1
  26. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
  27. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  28. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +3 -82
  29. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +13 -6
  30. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  31. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +31 -15
  32. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
  33. package/node_modules/@capyclaw/portal/package.json +1 -1
  34. package/node_modules/@capyclaw/service-broker/README.md +1 -1
  35. package/node_modules/@capyclaw/service-broker/lib/control.mjs +23 -7
  36. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +60 -6
  37. package/node_modules/@capyclaw/service-broker/lib/host.mjs +11 -6
  38. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +15 -2
  39. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +0 -50
  40. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +30 -10
  41. package/node_modules/@capyclaw/service-broker/package.json +1 -1
  42. package/node_modules/@capyclaw/service-host/dsh-suite.json +1 -1
  43. package/node_modules/@capyclaw/service-host/package.json +1 -1
  44. package/node_modules/@capyclaw/service-host/src/index.mjs +18 -19
  45. package/node_modules/@capyclaw/tool-host/dsh-suite.json +2 -2
  46. package/node_modules/@capyclaw/tool-host/lib/host.mjs +34 -4
  47. package/node_modules/@capyclaw/tool-host/package.json +1 -1
  48. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  49. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  50. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +28 -4
  51. package/node_modules/@capyclaw/tool-host/src/index.mjs +90 -19
  52. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
  53. package/node_modules/@capyclaw/wall-workbench/contract/wall-contract.json +1 -1
  54. package/node_modules/@capyclaw/wall-workbench/package.json +6 -6
  55. package/node_modules/@capyclaw/wall-workbench/plugin.mjs +13 -1
  56. package/node_modules/@capyclaw/wall-workbench/server/activate-log.mjs +66 -0
  57. package/node_modules/@capyclaw/wall-workbench/server/contract.mjs +1 -1
  58. package/node_modules/@capyclaw/wall-workbench/server/embedded-host.mjs +3 -1
  59. package/node_modules/@capyclaw/wall-workbench/server/shared/SHARED_MANIFEST.json +4 -4
  60. package/node_modules/@capyclaw/wall-workbench/server/workbench-framework.mjs +34 -0
  61. package/node_modules/@capyclaw/wall-workbench/ui/app.js +83 -0
  62. package/node_modules/@capyclaw/wall-workbench/ui/style.css +14 -11
  63. package/package.json +8 -8
@@ -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
+ }
@@ -14,24 +14,40 @@
14
14
  * 返回恒为 {content:[...]}(object),因此 DSH 原生面 output.schema 用 object 恒满足。
15
15
  */
16
16
 
17
- /** 把任意工具返回值归一为 MCP content 形态。 */
18
- export function normalizeToolResult(out) {
17
+ /** 单个 text 块的默认上限:防 base64/大输出撑爆 LLM 上下文。image 块不受影响。 */
18
+ export const DEFAULT_MAX_TEXT_BYTES = 256 * 1024
19
+
20
+ function capText(text, max) {
21
+ if (!max || max <= 0 || typeof text !== 'string' || text.length <= max) return text
22
+ return `${text.slice(0, max)}\n…[truncated: original ${text.length} chars, limit ${max}]`
23
+ }
24
+
25
+ function capContent(content, max) {
26
+ return content.map((block) => (
27
+ block && block.type === 'text' && typeof block.text === 'string'
28
+ ? { ...block, text: capText(block.text, max) }
29
+ : block
30
+ ))
31
+ }
32
+
33
+ /** 把任意工具返回值归一为 MCP content 形态(并对超限 text 块截断+提示)。 */
34
+ export function normalizeToolResult(out, { maxTextBytes = DEFAULT_MAX_TEXT_BYTES } = {}) {
19
35
  const isError = out && typeof out.isError === 'boolean' ? { isError: out.isError } : {}
36
+ let content
20
37
  if (out && Array.isArray(out.content)) {
21
- return { content: out.content, ...isError }
22
- }
23
- if (out && typeof out.text === 'string') {
24
- return { content: [{ type: 'text', text: out.text }], ...isError }
25
- }
26
- if (typeof out === 'string') {
27
- return { content: [{ type: 'text', text: out }] }
28
- }
29
- if (out === undefined || out === null) {
30
- return { content: [{ type: 'text', text: '' }] }
38
+ content = out.content
39
+ } else if (out && typeof out.text === 'string') {
40
+ content = [{ type: 'text', text: out.text }]
41
+ } else if (typeof out === 'string') {
42
+ content = [{ type: 'text', text: out }]
43
+ } else if (out === undefined || out === null) {
44
+ content = [{ type: 'text', text: '' }]
45
+ } else {
46
+ let text
47
+ try { text = JSON.stringify(out) } catch { text = String(out) }
48
+ content = [{ type: 'text', text: text ?? String(out) }]
31
49
  }
32
- let text
33
- try { text = JSON.stringify(out) } catch { text = String(out) }
34
- return { content: [{ type: 'text', text: text ?? String(out) }] }
50
+ return { content: capContent(content, maxTextBytes), ...isError }
35
51
  }
36
52
 
37
53
  /** 从归一化结果提取纯文本(用于把失败内容拼成 Error.message)。 */
@@ -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.13",
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 本身。
@@ -186,6 +186,10 @@ export class ServiceEngine {
186
186
  this._unhealthy = new Map()
187
187
  // 深探节流:id → 上次健康/工具探测时间。
188
188
  this._lastProbe = new Map()
189
+ // 重启退避:id → 上次自动重启尝试时间(崩溃循环不再每 2s 硬拉一次)。
190
+ this._lastRestart = new Map()
191
+ // error 态恢复:id → { count, lastAt }(冷却指数翻倍,不再永久移出扫描)。
192
+ this._errorRetries = new Map()
189
193
  // broker 自身的创建身份在本进程生命周期内不变;Windows 上 marker() 约 900ms,
190
194
  // 每次 up 重算会白烧近 1 秒。null 时不缓存(瞬时查询失败可重试)。
191
195
  this._brokerMarker = null
@@ -963,9 +967,10 @@ export class ServiceEngine {
963
967
  maxUnhealthy = 3,
964
968
  requireTools = true,
965
969
  probeEveryMs = 15000,
970
+ errorRetryMs = 300000,
966
971
  } = {}) {
967
972
  if (this._guardTimer) return
968
- this._guardConfig = { maxConsecutive, maxUnhealthy, requireTools, probeEveryMs }
973
+ this._guardConfig = { maxConsecutive, maxUnhealthy, requireTools, probeEveryMs, errorRetryMs }
969
974
  this._guardTimer = setInterval(() => {
970
975
  if (this._stopping || this._sweeping) return
971
976
  this._sweeping = true
@@ -1048,6 +1053,13 @@ export class ServiceEngine {
1048
1053
  cur[row.id] = { ...current, state: 'error', error: message }
1049
1054
  await this._saveRegistry(cur)
1050
1055
  })
1056
+ /* 冷却从「进入 error 态」起算,而不是从恢复尝试起算:否则 breaker 触发前的
1057
+ * 最后一次重启时间会被当成冷却起点,errorRetryMs 短于崩溃循环时长时,
1058
+ * 行刚变 error 就立刻被重试,冷却形同虚设。仅状态真的翻转时登记。 */
1059
+ const after = (await this._loadRegistry())[row.id]
1060
+ if (after?.state === 'error' && after.pid === row.pid && after.startedAt === row.startedAt) {
1061
+ this._errorRetries.set(row.id, { count: 0, lastAt: Date.now() })
1062
+ }
1051
1063
  this.log(`✗ ${row.id} ${message}`)
1052
1064
  }
1053
1065
 
@@ -1058,7 +1070,7 @@ export class ServiceEngine {
1058
1070
  * 孤儿行)。只看 _owned 是历史故障的根因:服务被外部杀掉后行还在、_owned 里
1059
1071
  * 没有它,于是 2s 一轮的守护永远跳过它,注册表一直写着 running 的假状态。 */
1060
1072
  const rows = Object.values(services).filter((row) =>
1061
- row.keepAlive && row.state === 'running'
1073
+ row.keepAlive && (row.state === 'running' || row.state === 'error')
1062
1074
  && (this._owned.has(row.id) || this._lastSpecs.has(row.id)))
1063
1075
  /* 并行探测:一个服务探测慢/超时不能拖住其他服务的巡检。 */
1064
1076
  await Promise.all(rows.map((row) => this._sweepOne(row, maxConsecutive).catch(() => {})))
@@ -1066,8 +1078,12 @@ export class ServiceEngine {
1066
1078
  }
1067
1079
 
1068
1080
  async _sweepOne(row, maxConsecutive) {
1081
+ /* error 态不是终点:带冷却地重试(见 _recoverError),不再永久移出扫描。 */
1082
+ if (row.state === 'error') return this._recoverError(row)
1069
1083
  if (pidAlive(row.pid)) {
1070
- this._guardFailures.delete(row.id)
1084
+ /* 注意:这里**不能**无条件清 _guardFailures——进程只要活过一个巡检间隔
1085
+ * 就把计数清零,「起-死-起」崩溃循环(活得比巡检间隔长)永远打不满熔断,
1086
+ * 变成无限重试。计数只在下方「稳定跑过一分钟」或手动 up 成功时翻篇。 */
1071
1087
  /* 分两档节奏:
1072
1088
  * - 存活检查每一轮都做(默认 2s 一轮)→ 进程一死,2s 内就重启;
1073
1089
  * - 健康/工具深探按 probeEveryMs(默认 15s)做一次,避免频繁打 HTTP。
@@ -1082,7 +1098,11 @@ export class ServiceEngine {
1082
1098
  /* "连续"重启次数:稳定跑过一分钟才算翻篇,避免“起-死-起”抖动
1083
1099
  * 每次都把计数清零,最后无限重试。 */
1084
1100
  const startedAt = Date.parse(row.startedAt || '') || 0
1085
- if (startedAt && Date.now() - startedAt > 60_000) this._guardFailures.delete(row.id)
1101
+ if (startedAt && Date.now() - startedAt > 60_000) {
1102
+ this._guardFailures.delete(row.id)
1103
+ this._errorRetries.delete(row.id)
1104
+ this._lastRestart.delete(row.id)
1105
+ }
1086
1106
  return
1087
1107
  }
1088
1108
  const count = (this._unhealthy.get(row.id) || 0) + 1
@@ -1137,10 +1157,18 @@ export class ServiceEngine {
1137
1157
  const failures = this._guardFailures.get(row.id) || 0
1138
1158
  const spec = this._lastSpecs.get(row.id)
1139
1159
  if (!spec) { await this._markError(row, '缺少重启规格,拒绝自动重启'); return }
1140
- if (failures >= maxConsecutive) { await this._markError(row, '连续重启次数超限,停止自动重启'); return }
1141
- this._guardFailures.set(row.id, failures + 1)
1160
+ if (failures >= maxConsecutive) { await this._markError(row, '连续重启次数超限,进入冷却(稍后自动重试)'); return }
1161
+ /* 重启退避:崩溃循环不能每 2s 硬拉一次,间隔随失败次数翻倍(2s→4s→8s…上限 60s)。 */
1162
+ const backoff = Math.min(2000 * 2 ** failures, 60_000)
1163
+ const lastRestart = this._lastRestart.get(row.id) || 0
1164
+ if (Date.now() - lastRestart < backoff) return
1165
+ this._lastRestart.set(row.id, Date.now())
1142
1166
  try {
1143
1167
  await this._upOnce(spec, {})
1168
+ /* 计数必须在重启**成功后**累加:_upOnce 的健康拉起路径会清 _guardFailures
1169
+ * (手动 up 语义=翻篇),守护重启若先加后清,崩溃循环永远打不满熔断。
1170
+ * 只有「稳定跑过 60s」或手动 up 才真正翻篇(见 _sweepOne)。 */
1171
+ this._guardFailures.set(row.id, failures + 1)
1144
1172
  this.log(`↻ ${row.id} 已自动重启`)
1145
1173
  } catch (err) {
1146
1174
  await this._markError(row, `自动重启失败: ${err.message}`)
@@ -1148,6 +1176,32 @@ export class ServiceEngine {
1148
1176
  })
1149
1177
  }
1150
1178
 
1179
+ /** error 态恢复:冷却指数翻倍(默认 5min→10min→20min…上限 30min)后按规格重试。
1180
+ * _upOnce 自带仲裁——端口上已有健康实例就复用,不会双开;成功即回到 running,
1181
+ * 稳定跑过 60s 后冷却计数清零(见 _sweepOne)。没有重启规格的行无法自愈,留给手动 up。 */
1182
+ async _recoverError(row) {
1183
+ const cfg = this._guardConfig || {}
1184
+ const base = cfg.errorRetryMs ?? 300_000
1185
+ const retry = this._errorRetries.get(row.id) || { count: 0, lastAt: 0 }
1186
+ const cooldown = Math.min(base * 2 ** retry.count, 1_800_000)
1187
+ if (Date.now() - retry.lastAt < cooldown) return
1188
+ const spec = this._lastSpecs.get(row.id)
1189
+ if (!spec) return
1190
+ await this._withServiceLock(row.id, async () => {
1191
+ if (this._stopping) return
1192
+ this._errorRetries.set(row.id, { count: retry.count + 1, lastAt: Date.now() })
1193
+ /* error 恢复是新一轮:不背旧的连续重启计数。 */
1194
+ this._guardFailures.delete(row.id)
1195
+ this._unhealthy.delete(row.id)
1196
+ try {
1197
+ await this._upOnce(spec, {})
1198
+ this.log(`↻ ${row.id} 已从 error 态恢复(第 ${retry.count + 1} 次尝试)`)
1199
+ } catch (err) {
1200
+ this.log(`… ${row.id} error 恢复失败(第 ${retry.count + 1} 次尝试):${err.message},冷却后再试`)
1201
+ }
1202
+ })
1203
+ }
1204
+
1151
1205
  /** 与服务级启动锁串行,避免与并发的 up/stop 交叉执行。 */
1152
1206
  _withServiceLock(id, fn) {
1153
1207
  const prev = this._upLocks.get(id) || Promise.resolve()
@@ -5,8 +5,11 @@
5
5
  * 只做三件事:
6
6
  * 1. 按清单(config.manifest 指向 services.json)把各服务作为独立进程拉起;
7
7
  * 2. 向同进程提供 ctx.serviceBroker(list/start/stop/apply 控制面);
8
- * 3. 可选:config.skills.url 指向技能服务时,提供 ctx.skills 瘦客户端
9
- * (数据来自 HTTP,技能内容不再进程内注册)。
8
+ * 3. 可选:config.skills.url 指向技能服务时,提供 ctx.skillsHttp 瘦客户端
9
+ * (数据来自 HTTP)。技能的标准路径是 skillProvider@1 进程内注册 →
10
+ * DSH 原生 SkillRegistry(ctx.skills);此 HTTP 路是 standalone 可选模式,
11
+ * 默认不启用。服务名用 skillsHttp 而非 skills,避免遮蔽原生注册表
12
+ * (详见 lib/skills-client.mjs 头注释,P1-10 决策)。
10
13
  *
11
14
  * 生命周期:keepAlive 服务(默认)不随插件卸载停止——服务独立于 dsh;
12
15
  * config.stopOnUnload === true 时才随卸载全停。
@@ -40,13 +43,15 @@ export const { name, inject, apply } = defineDriver({
40
43
  }
41
44
  const disposeService = ctx.provide('serviceBroker', api)
42
45
 
43
- // 技能瘦客户端:ctx.skills 形状与原进程内注册表一致(list/get),
44
- // 数据源改为 HTTP 技能服务——技能内容不再进 dsh 进程。
46
+ // 技能瘦客户端(可选 standalone 模式,默认不启用):list/get 形状与进程内
47
+ // 注册表一致,数据源改为 HTTP 技能服务。服务名 skillsHttp——'skills' 归 DSH
48
+ // 原生 SkillRegistry,provide('skills') 会遮蔽它并令 skillProvider@1 插件
49
+ // 因缺 registerProvider 挂载失败(P1-10 决策,见 lib/skills-client.mjs)。
45
50
  let disposeSkills = null
46
51
  if (config.skills?.url) {
47
52
  const client = createSkillsClient(config.skills.url)
48
- disposeSkills = ctx.provide('skills', client)
49
- console.log(`[service-broker] skills ← ${config.skills.url}`)
53
+ disposeSkills = ctx.provide('skillsHttp', client)
54
+ console.log(`[service-broker] skillsHttp ← ${config.skills.url}`)
50
55
  }
51
56
 
52
57
  // 开机清单:有清单就按 up 命令投递给自己(幂等,复用优先)
@@ -39,12 +39,18 @@ export function findSuiteRoot(startDir = path.dirname(PKG_DIR)) {
39
39
  }
40
40
  }
41
41
 
42
+ /** 读 JSON 并剥 UTF-8 BOM:带 BOM 的清单会让 JSON.parse 抛「Unexpected token」,
43
+ * 表现为 boot 永久失败且极难归因(文件看着完全正常)。统一在此剥掉。 */
44
+ function parseJsonFile(file) {
45
+ return JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
46
+ }
47
+
42
48
  /** 套件根判据:含 dsh-suite.json + services.json,且不是 broker 自带的 dsh-suite.json。 */
43
49
  function isSuiteRoot(dir) {
44
50
  const suiteFile = path.join(dir, 'dsh-suite.json')
45
51
  if (!existsSync(suiteFile) || !existsSync(path.join(dir, 'services.json'))) return false
46
52
  try {
47
- const manifest = JSON.parse(readFileSync(suiteFile, 'utf8'))
53
+ const manifest = parseJsonFile(suiteFile)
48
54
  return Boolean(manifest) && typeof manifest === 'object' && manifest.name !== 'dsh-service-broker-suite'
49
55
  } catch {
50
56
  return false
@@ -201,7 +207,7 @@ export function loadManifest(manifestPath) {
201
207
 
202
208
  function loadFile(file) {
203
209
  if (!existsSync(file)) return []
204
- const raw = JSON.parse(readFileSync(file, 'utf8'))
210
+ const raw = parseJsonFile(file)
205
211
  const services = Array.isArray(raw) ? raw : raw.services
206
212
  if (!Array.isArray(services)) throw new Error(`manifest 格式非法(缺 services 数组): ${file}`)
207
213
  const specErrors = validateServiceManifest(services, file)
@@ -245,5 +251,12 @@ function expandPackageDir(service, base) {
245
251
  for (const key of ['url', 'cwd', 'logFile']) {
246
252
  if (typeof out[key] === 'string') out[key] = String(out[key]).replaceAll('${PACKAGE_DIR}', base)
247
253
  }
254
+ /* env 值同样展开 ${PACKAGE_DIR}:旧实现只展开 url/cwd/logFile,env 里引用
255
+ * ${PACKAGE_DIR} 的变量(如自定义数据目录/脚本路径)原样传给子进程 → 路径错。 */
256
+ for (const [key, value] of Object.entries(out.env)) {
257
+ if (typeof value === 'string' && value.includes('${PACKAGE_DIR}')) {
258
+ out.env[key] = value.replaceAll('${PACKAGE_DIR}', base)
259
+ }
260
+ }
248
261
  return out
249
262
  }
@@ -273,53 +273,3 @@ export async function waitReceiptResolvable(receipt, ports, timeoutMs = 3000) {
273
273
  await new Promise((resolve) => setTimeout(resolve, 200))
274
274
  }
275
275
  }
276
-
277
- // Caller must serialize against starting a replacement broker and supply the
278
- // identity captured when it spawned this broker. An absent PID alone is not a receipt.
279
- export async function recoverServices(discovery, broker) {
280
- const unresolved = [], stopped = []
281
- if (!broker?.pid || !broker?.marker || !broker?.recoveryMarker || !absent(broker.pid)) return { stopped, unresolved: ['broker:not-confirmed-absent'] }
282
- let discovered = {}
283
- try { discovered = JSON.parse(fs.readFileSync(discovery, 'utf8'))?.services || {} } catch { /* discovery 缺失时只能依赖收据自身 */ }
284
- let entries
285
- try { entries = fs.readdirSync(receiptDir(discovery)) } catch (e) {
286
- return { stopped, unresolved: [e.code === 'ENOENT' ? 'ownership:missing' : 'ownership:unreadable'] }
287
- }
288
- for (const name of entries) {
289
- if (!name.endsWith('.json')) { unresolved.push(`ownership:${name}:unrecognized`); continue }
290
- let r
291
- try { r = JSON.parse(fs.readFileSync(path.join(receiptDir(discovery), name), 'utf8')) } catch { unresolved.push(`ownership:${name}:unreadable`); continue }
292
- if (!r || `${r.id}.json` !== name || !/^[a-z0-9][a-z0-9._-]*$/i.test(r.id) || r.brokerPid !== broker.pid || r.brokerMarker !== broker.recoveryMarker || r.state !== 'spawned' || !Number.isSafeInteger(r.pid) || r.pid <= 0 || !r.identity) {
293
- unresolved.push(`ownership:${name}:unverified`); continue
294
- }
295
- if (!absent(broker.pid)) { unresolved.push('broker:not-confirmed-absent'); break }
296
- if (absent(r.pid)) {
297
- // Dead root: only a receipt whose declared ports are all free can be
298
- // resolved; any listener may be an unverified descendant.
299
- if (await waitReceiptResolvable(r, discovered[r.id]?.ports)) {
300
- removeReceipt(discovery, r.id)
301
- stopped.push(r.id)
302
- } else unresolved.push(`service:${r.id}:already-exited-descendants-unverified`)
303
- continue
304
- }
305
- if (!absent(r.pid)) {
306
- if (marker(r.pid) !== r.identity) { unresolved.push(`service:${r.id}:identity-unverified`); continue }
307
- if (process.platform === 'win32') {
308
- const result = spawnSync('taskkill', ['/PID', String(r.pid), '/F'], { stdio: 'ignore', timeout: 10000, windowsHide: true })
309
- if (result.status !== 0 && !absent(r.pid)) { unresolved.push(`service:${r.id}:stop-failed`); continue }
310
- } else {
311
- try { process.kill(r.pid, 'SIGTERM') } catch (e) { if (e.code !== 'ESRCH') { unresolved.push(`service:${r.id}:stop-failed`); continue } }
312
- }
313
- for (let i = 0; i < 50 && !absent(r.pid); i++) await new Promise(resolve => setTimeout(resolve, 100))
314
- if (!absent(r.pid)) { unresolved.push(`service:${r.id}:still-running`); continue }
315
- }
316
- // Root exit alone does not prove its descendants exited. It is safe to
317
- // resolve once none of the declared ports is still listening; otherwise
318
- // keep the receipt as evidence (fail closed).
319
- if (await waitReceiptResolvable(r, discovered[r.id]?.ports)) {
320
- removeReceipt(discovery, r.id)
321
- stopped.push(r.id)
322
- } else unresolved.push(`service:${r.id}:descendants-unverified`)
323
- }
324
- return { stopped, unresolved }
325
- }
@@ -1,16 +1,29 @@
1
1
  /**
2
- * 技能瘦客户端:把「技能服务」的 HTTP 面适配成原 ctx.skills 的进程内形状。
2
+ * 技能瘦客户端:把独立技能服务的 HTTP 面适配成进程内形状(list/get)。
3
3
  *
4
- * 技能内容(SKILL.md 正文)不再通过 ctx.skills.registerProvider 进程内注册,
5
- * 而是从独立技能服务拉取——dsh 进程里只剩这一个瘦适配层。
6
- * 服务端形状见 packages/capyclaw-skills-service(GET /skills、GET /skills/:name)。
4
+ * 定位(P1-10 决策):技能的标准路径是 skillProvider@1 进程内注册 →
5
+ * DSH 原生 SkillRegistry(ctx.skills);本客户端只在显式配置 skills.url 的
6
+ * standalone 模式下启用,默认不启用。
7
+ *
8
+ * 服务名刻意叫 **skillsHttp** 而不是 skills:'skills' 是 DSH 原生 SkillRegistry
9
+ * 的服务名(foundation 经 getService(ctx,'skills') 取用,skillProvider@1 靠它的
10
+ * registerProvider 挂载)。若本客户端 provide('skills') 会遮蔽原生注册表,且瘦
11
+ * 客户端没有 registerProvider,全部 skillProvider@1 插件将 E_CAP_MISSING 挂载
12
+ * 失败。改名后原生 ctx.skills 永不被遮蔽,两条路可共存。
13
+ *
14
+ * 服务端形状见 C/packages/capyclaw-skills-service(GET /skills、GET /skills/:name)。
7
15
  */
8
16
  export function createSkillsClient(baseUrl) {
9
17
  const root = String(baseUrl || '').replace(/\/$/, '')
10
18
  return {
11
- api: { name: 'skills', version: '1.0.0', kind: 'thin-client' },
19
+ api: { name: 'skillsHttp', version: '1.0.0', kind: 'thin-client' },
12
20
  async list(signal) {
13
- const res = await fetch(`${root}/skills`, { signal: signal ?? AbortSignal.timeout(5000) })
21
+ let res
22
+ try {
23
+ res = await fetch(`${root}/skills`, { signal: signal ?? AbortSignal.timeout(5000) })
24
+ } catch (error) {
25
+ throw new Error(`skills 服务不可达(${root}):${error.message}`, { cause: error })
26
+ }
14
27
  if (!res.ok) throw new Error(`skills list HTTP ${res.status}`)
15
28
  const body = await res.json()
16
29
  return Array.isArray(body?.skills) ? body.skills : []
@@ -18,10 +31,17 @@ export function createSkillsClient(baseUrl) {
18
31
  async get(candidate, options = {}) {
19
32
  const name = typeof candidate === 'string' ? candidate : candidate?.name
20
33
  if (!name) throw new Error('skills get: 缺 name')
21
- const res = await fetch(`${root}/skills/${encodeURIComponent(name)}`, {
22
- signal: options.signal ?? AbortSignal.timeout(10000),
23
- })
24
- if (!res.ok) throw new Error(`未知 skill ${name}(HTTP ${res.status})`)
34
+ let res
35
+ try {
36
+ res = await fetch(`${root}/skills/${encodeURIComponent(name)}`, {
37
+ signal: options.signal ?? AbortSignal.timeout(10000),
38
+ })
39
+ } catch (error) {
40
+ throw new Error(`skills 服务不可达(${root}):${error.message}`, { cause: error })
41
+ }
42
+ /* 只有 404 才是「未知 skill」;500/503 是服务端故障,不能误导成名字写错。 */
43
+ if (res.status === 404) throw new Error(`未知 skill ${name}(HTTP 404)`)
44
+ if (!res.ok) throw new Error(`skills get ${name} 失败(HTTP ${res.status},服务端错误)`)
25
45
  return res.json()
26
46
  },
27
47
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/service-broker",
3
- "version": "0.2.25",
3
+ "version": "0.2.27",
4
4
  "description": "DSH 服务中间件(唯一进程内插件):按清单/结构化命令把各服务作为独立进程拉起,负责守护、发现(discovery)、控制端点;服务与服务之间不互相带动,跨端口组织一律经过这里。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
@@ -7,7 +7,7 @@
7
7
  "packages": {
8
8
  "@capyclaw/service-host": {
9
9
  "role": "provider",
10
- "version": "^0.1.5",
10
+ "version": "^0.1.7",
11
11
  "path": ".",
12
12
  "provides": {
13
13
  "services": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/service-host",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "DSH 公共服务宿主插件:统一 HTTP 路由、健康检查、指标、单实例锁、端口复用与静态资源,向插件提供 ctx.serviceHost。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",