@capyclaw/service-host 0.1.2 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +23 -5
  2. package/cordis.patch.yml +2 -2
  3. package/dsh-suite.json +2 -2
  4. package/lib/host.mjs +12 -9
  5. package/node_modules/@capyclaw/foundation/README.md +51 -0
  6. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  7. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  8. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  9. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  10. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  11. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  12. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  13. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  14. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  15. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  16. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  17. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  18. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  19. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  20. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  28. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  29. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  30. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  31. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  32. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  33. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  34. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  35. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
  36. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  37. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  38. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  39. package/node_modules/@capyclaw/foundation/package.json +53 -0
  40. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  41. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  42. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  43. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  44. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  45. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  70. package/package.json +18 -6
  71. package/src/index.mjs +99 -39
  72. package/src/tuning.mjs +1 -1
@@ -0,0 +1,181 @@
1
+ /**
2
+ * 极简跨平台 ZIP 读写(store + deflate 读,store 写;无外部依赖)——全仓单一真源。
3
+ *
4
+ * 之前三处实现各持一份(plugin-development 写 / tools-plugin-release 读 /
5
+ * @capyclaw/suite-kit zip-read 读),本模块合并之。旧位置保留兼容 shim。
6
+ *
7
+ * 写入:store 模式(内容不压缩,跨平台稳定,产物可被任何标准读取器读)。
8
+ * 读取:支持 store(0) 与 deflate(8);接受 Buffer 或文件路径——本地文件与
9
+ * 远端下载源共用同一条校验/解包路径。
10
+ */
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import zlib from 'node:zlib'
14
+
15
+ /* ------------------------------------------------------------------ 写入 */
16
+
17
+ const CRC_TABLE = (() => {
18
+ const table = new Uint32Array(256)
19
+ for (let n = 0; n < 256; n++) {
20
+ let c = n
21
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1)
22
+ table[n] = c >>> 0
23
+ }
24
+ return table
25
+ })()
26
+
27
+ function crc32(buffer) {
28
+ let crc = 0xffffffff
29
+ for (let i = 0; i < buffer.length; i++) crc = CRC_TABLE[(crc ^ buffer[i]) & 0xff] ^ (crc >>> 8)
30
+ return (crc ^ 0xffffffff) >>> 0
31
+ }
32
+
33
+ function dosDateTime(date = new Date()) {
34
+ const year = Math.max(1980, date.getFullYear())
35
+ const time = ((date.getHours() & 0x1f) << 11) | ((date.getMinutes() & 0x3f) << 5) | (Math.floor(date.getSeconds() / 2) & 0x1f)
36
+ const day = (((year - 1980) & 0x7f) << 9) | (((date.getMonth() + 1) & 0x0f) << 5) | (date.getDate() & 0x1f)
37
+ return { time, day }
38
+ }
39
+
40
+ function walkFiles(dir, base = dir) {
41
+ const out = []
42
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
43
+ const full = path.join(dir, entry.name)
44
+ if (entry.isDirectory()) out.push(...walkFiles(full, base))
45
+ else if (entry.isFile()) out.push(path.relative(base, full).replace(/\\/g, '/'))
46
+ }
47
+ return out.sort()
48
+ }
49
+
50
+ /** 把目录写成 store 模式 ZIP。返回打包的相对路径列表。 */
51
+ export function writeZipFromDir(sourceDir, outFile) {
52
+ const files = walkFiles(sourceDir)
53
+ const now = dosDateTime()
54
+ const localParts = []
55
+ const centralParts = []
56
+ let offset = 0
57
+
58
+ for (const name of files) {
59
+ const data = fs.readFileSync(path.join(sourceDir, name))
60
+ const nameBytes = Buffer.from(name, 'utf8')
61
+ const crc = crc32(data)
62
+
63
+ const local = Buffer.alloc(30)
64
+ local.writeUInt32LE(0x04034b50, 0)
65
+ local.writeUInt16LE(20, 4)
66
+ local.writeUInt16LE(0x0800, 6)
67
+ local.writeUInt16LE(0, 8)
68
+ local.writeUInt16LE(now.time, 10)
69
+ local.writeUInt16LE(now.day, 12)
70
+ local.writeUInt32LE(crc, 14)
71
+ local.writeUInt32LE(data.length, 18)
72
+ local.writeUInt32LE(data.length, 22)
73
+ local.writeUInt16LE(nameBytes.length, 26)
74
+ local.writeUInt16LE(0, 28)
75
+ localParts.push(local, nameBytes, data)
76
+
77
+ const central = Buffer.alloc(46)
78
+ central.writeUInt32LE(0x02014b50, 0)
79
+ central.writeUInt16LE(20, 4)
80
+ central.writeUInt16LE(20, 6)
81
+ central.writeUInt16LE(0x0800, 8)
82
+ central.writeUInt16LE(0, 10)
83
+ central.writeUInt16LE(now.time, 12)
84
+ central.writeUInt16LE(now.day, 14)
85
+ central.writeUInt32LE(crc, 16)
86
+ central.writeUInt32LE(data.length, 20)
87
+ central.writeUInt32LE(data.length, 24)
88
+ central.writeUInt16LE(nameBytes.length, 28)
89
+ central.writeUInt16LE(0, 30)
90
+ central.writeUInt16LE(0, 32)
91
+ central.writeUInt16LE(0, 34)
92
+ central.writeUInt16LE(0, 36)
93
+ central.writeUInt32LE(0, 38)
94
+ central.writeUInt32LE(offset, 42)
95
+ centralParts.push(central, nameBytes)
96
+
97
+ offset += local.length + nameBytes.length + data.length
98
+ }
99
+
100
+ const centralBuffer = Buffer.concat(centralParts)
101
+ const eocd = Buffer.alloc(22)
102
+ eocd.writeUInt32LE(0x06054b50, 0)
103
+ eocd.writeUInt16LE(0, 4)
104
+ eocd.writeUInt16LE(0, 6)
105
+ eocd.writeUInt16LE(files.length, 8)
106
+ eocd.writeUInt16LE(files.length, 10)
107
+ eocd.writeUInt32LE(centralBuffer.length, 12)
108
+ eocd.writeUInt32LE(offset, 16)
109
+ eocd.writeUInt16LE(0, 20)
110
+
111
+ fs.mkdirSync(path.dirname(outFile), { recursive: true })
112
+ fs.writeFileSync(outFile, Buffer.concat([...localParts, centralBuffer, eocd]))
113
+ return files
114
+ }
115
+
116
+ /* ------------------------------------------------------------------ 读取 */
117
+
118
+ function locateEocd(data, label) {
119
+ for (let i = data.length - 22; i >= 0; i--) {
120
+ if (data.readUInt32LE(i) === 0x06054b50) return i
121
+ }
122
+ throw new Error(`不是有效的 ZIP: ${label}`)
123
+ }
124
+
125
+ /**
126
+ * 列出 ZIP 全部条目名。
127
+ * @param {Buffer|string} input - ZIP 字节或文件路径
128
+ */
129
+ export function listZipEntryNames(input, label = 'zip') {
130
+ const data = Buffer.isBuffer(input) ? input : fs.readFileSync(input)
131
+ const eocd = locateEocd(data, label)
132
+ const count = data.readUInt16LE(eocd + 10)
133
+ let offset = data.readUInt32LE(eocd + 16)
134
+ const names = []
135
+ for (let i = 0; i < count; i++) {
136
+ if (data.readUInt32LE(offset) !== 0x02014b50) throw new Error(`ZIP 中央目录损坏: ${label}`)
137
+ const nameLength = data.readUInt16LE(offset + 28)
138
+ const extraLength = data.readUInt16LE(offset + 30)
139
+ const commentLength = data.readUInt16LE(offset + 32)
140
+ names.push(data.subarray(offset + 46, offset + 46 + nameLength).toString('utf8'))
141
+ offset += 46 + nameLength + extraLength + commentLength
142
+ }
143
+ return names
144
+ }
145
+
146
+ /**
147
+ * 从 ZIP 读单个条目的原始字节;不存在返回 undefined。
148
+ * @param {Buffer|string} input - ZIP 字节或文件路径
149
+ */
150
+ export function readZipEntryBuffer(input, entryName, label = 'zip') {
151
+ const data = Buffer.isBuffer(input) ? input : fs.readFileSync(input)
152
+ const eocd = locateEocd(data, label)
153
+ const count = data.readUInt16LE(eocd + 10)
154
+ let offset = data.readUInt32LE(eocd + 16)
155
+ for (let i = 0; i < count; i++) {
156
+ if (data.readUInt32LE(offset) !== 0x02014b50) throw new Error(`ZIP 中央目录损坏: ${label}`)
157
+ const method = data.readUInt16LE(offset + 10)
158
+ const compSize = data.readUInt32LE(offset + 20)
159
+ const nameLength = data.readUInt16LE(offset + 28)
160
+ const extraLength = data.readUInt16LE(offset + 30)
161
+ const commentLength = data.readUInt16LE(offset + 32)
162
+ const localOffset = data.readUInt32LE(offset + 42)
163
+ const name = data.subarray(offset + 46, offset + 46 + nameLength).toString('utf8')
164
+ if (name === entryName) {
165
+ const localNameLength = data.readUInt16LE(localOffset + 26)
166
+ const localExtraLength = data.readUInt16LE(localOffset + 28)
167
+ const start = localOffset + 30 + localNameLength + localExtraLength
168
+ const body = data.subarray(start, start + compSize)
169
+ if (method === 0) return body
170
+ if (method === 8) return zlib.inflateRawSync(body)
171
+ throw new Error(`不支持的 ZIP 压缩方式 ${method}: ${label}`)
172
+ }
173
+ offset += 46 + nameLength + extraLength + commentLength
174
+ }
175
+ return undefined
176
+ }
177
+
178
+ /** 读取 ZIP 中央目录条目名(文件路径版;打包自检/测试用)。 */
179
+ export function listZipEntries(file) {
180
+ return listZipEntryNames(fs.readFileSync(file), file)
181
+ }
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@capyclaw/service-host",
3
- "version": "0.1.2",
3
+ "version": "0.1.5",
4
4
  "description": "DSH 公共服务宿主插件:统一 HTTP 路由、健康检查、指标、单实例锁、端口复用与静态资源,向插件提供 ctx.serviceHost。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
7
7
  "exports": {
8
8
  ".": "./lib/host.mjs",
9
9
  "./src": "./src/index.mjs",
10
- "./package.json": "./package.json"
10
+ "./package.json": "./package.json",
11
+ "./tuning": "./src/tuning.mjs"
11
12
  },
12
13
  "engines": {
13
14
  "node": ">=18",
@@ -23,7 +24,10 @@
23
24
  "suite": "./dsh-suite.json",
24
25
  "category": "service",
25
26
  "platform": "both",
26
- "apiVersion": "1.0.0"
27
+ "apiVersion": "1.0.0",
28
+ "driver": {
29
+ "service": "serviceHost"
30
+ }
27
31
  },
28
32
  "meta": {
29
33
  "title": "公共服务宿主",
@@ -37,16 +41,24 @@
37
41
  "README.md"
38
42
  ],
39
43
  "license": "MIT",
44
+ "scripts": {
45
+ "test": "node --test test/*.test.mjs"
46
+ },
40
47
  "dependencies": {
41
- "@capyclaw/plugin-kit": "^0.2.0"
48
+ "@capyclaw/plugin-kit": "^0.2.0",
49
+ "@capyclaw/foundation": "^0.1.1"
42
50
  },
43
51
  "repository": {
44
52
  "type": "git",
45
53
  "url": "git+https://github.com/Maple496/capyclaw.git",
46
- "directory": "packages/capyclaw-service-host"
54
+ "directory": "C/packages/capyclaw-service-host"
47
55
  },
48
56
  "bugs": {
49
57
  "url": "https://github.com/Maple496/capyclaw/issues"
50
58
  },
51
- "homepage": "https://github.com/Maple496/capyclaw/tree/main/packages/capyclaw-service-host#readme"
59
+ "homepage": "https://github.com/Maple496/capyclaw/tree/main/C/packages/capyclaw-service-host#readme",
60
+ "bundledDependencies": [
61
+ "@capyclaw/foundation",
62
+ "@capyclaw/plugin-kit"
63
+ ]
52
64
  }
package/src/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * dsh-service-host —— 通用服务宿主。
2
+ * @capyclaw/service-host —— 通用服务宿主。
3
3
  *
4
4
  * 功能插件只声明“我有哪些路由、健康字段、指标”,不再自己写:
5
5
  * - http server / listen / 端口扫描 / strictPort
@@ -18,23 +18,9 @@ import path from 'node:path'
18
18
  import crypto from 'node:crypto'
19
19
  import { listen, send, sendText, readBody } from '@capyclaw/plugin-kit/service/http'
20
20
  import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
21
+ import { isLoopbackOrigin as sharedIsLoopbackOrigin, mimeFor } from '@capyclaw/plugin-kit/util/http'
21
22
  import { tuning } from './tuning.mjs'
22
23
 
23
- const MIME = {
24
- '.html': 'text/html; charset=utf-8',
25
- '.js': 'text/javascript; charset=utf-8',
26
- '.mjs': 'text/javascript; charset=utf-8',
27
- '.css': 'text/css; charset=utf-8',
28
- '.json': 'application/json; charset=utf-8',
29
- '.svg': 'image/svg+xml',
30
- '.png': 'image/png',
31
- '.jpg': 'image/jpeg',
32
- '.jpeg': 'image/jpeg',
33
- '.webp': 'image/webp',
34
- '.woff2': 'font/woff2',
35
- '.map': 'application/json; charset=utf-8',
36
- }
37
-
38
24
  function slugOf(id) {
39
25
  return String(id || 'service').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'service'
40
26
  }
@@ -44,21 +30,33 @@ function pidAlive(pid) {
44
30
  try { process.kill(pid, 0); return true } catch (error) { return error.code === 'EPERM' }
45
31
  }
46
32
 
47
- /** 浏览器跨源写请求防护:只允许本机 loopback 页面 POST。 */
48
- function isLoopbackOrigin(origin) {
49
- if (!origin) return true
50
- try {
51
- const parsed = new URL(origin)
52
- return parsed.hostname === '127.0.0.1' || parsed.hostname === 'localhost' || parsed.hostname === '::1' || parsed.hostname === '[::1]'
53
- } catch {
54
- return false
55
- }
56
- }
33
+ /** 浏览器跨源写请求防护:只允许本机 loopback 页面 POST(空 Origin 视为同源导航,放行)。 */
34
+ const isLoopbackOrigin = sharedIsLoopbackOrigin
57
35
 
58
- function acquireLock(lockFile) {
36
+ /**
37
+ * 挂载前缀之后的可选会话段:`<prefix>/s/<会话id>/…`。
38
+ *
39
+ * 「每个会话一个地址」不该由每个插件各自拼 query,而是基建默认行为:工作台挂到
40
+ * `/capyclaw/ppt/` 之后,`/capyclaw/ppt/s/<sid>/` 自动可用,页面用自己的
41
+ * pathname 就知道该在哪个会话里呈现。形状与网关 `/s/<会话id>/` 一致,sid 也只
42
+ * 放行安全字符(与 gateway 的 SID_RE 同形),不引入路径分隔歧义。
43
+ */
44
+ const SESSION_PATH = /^\/s\/([A-Za-z0-9][A-Za-z0-9._~-]{0,127})(?=\/|$)/
45
+
46
+ /**
47
+ * 抢占实例锁。
48
+ *
49
+ * 判定「有没有别的实例在跑」不能只看 pid:Windows 会复用 pid,relay 崩溃后那个
50
+ * 号码很容易落到无关进程(本机就撞上过 BaiduNetdiskUnite),于是锁永远抢不到、
51
+ * workbench 再也起不来。所以 pid 存活只是必要条件,最终以「锁里记的端口是否还在
52
+ * 应答本服务的健康端点」为准。
53
+ */
54
+ async function acquireLock(lockFile, { healthPath, id } = {}) {
59
55
  fs.mkdirSync(path.dirname(lockFile), { recursive: true })
60
56
  const token = crypto.randomBytes(12).toString('hex')
61
57
  const { lockFreshGraceMs } = tuning()
58
+ /** 刚拿到锁、还没 listen 成功的实例允许占位多久(秒级即可,超时视为卡死)。 */
59
+ const startingGraceMs = Math.max(lockFreshGraceMs, 15000)
62
60
  for (let attempt = 0; attempt < 2; attempt++) {
63
61
  try {
64
62
  /* 原子创建:两个进程同时启动时只有一个能拿到 'wx'。 */
@@ -76,9 +74,23 @@ function acquireLock(lockFile) {
76
74
  try { info = JSON.parse(fs.readFileSync(lockFile, 'utf8')) } catch { /* 可能正在写入 */ }
77
75
  let age = 0
78
76
  try { age = Date.now() - fs.statSync(lockFile).mtimeMs } catch { /* 已被移除 */ }
79
- /* 有效且 pid 存活:绝不抢占;空/坏锁只有在存在超过宽限期后才视为残留。 */
80
- if (info && pidAlive(info.pid)) return null
81
- if (!info && age < lockFreshGraceMs) return null
77
+ if (info && info.pid) {
78
+ const alive = pidAlive(info.pid)
79
+ if (alive) {
80
+ if (Number(info.port) > 0 && healthPath) {
81
+ const probe = await probeExisting(`http://127.0.0.1:${Number(info.port)}`, healthPath, id)
82
+ if (probe.verdict === 'found') return null
83
+ /* 探针不可结论(超时等)≠ 端口没人:保守拒绝抢锁,宁可本次不起,
84
+ * 也不把可能活着的实例顶成双开(split-brain)。 */
85
+ if (probe.verdict === 'inconclusive') return null
86
+ /* pid 活着但锁里的端口明确拒绝连接 ⇒ pid 是被复用的号码,锁是残留。 */
87
+ } else if (age < startingGraceMs) {
88
+ return null
89
+ }
90
+ }
91
+ } else if (age < lockFreshGraceMs) {
92
+ return null
93
+ }
82
94
  try { fs.rmSync(lockFile, { force: true }) } catch { /* 忽略 */ }
83
95
  }
84
96
  }
@@ -107,11 +119,18 @@ function releaseLock(lock) {
107
119
  async function probeExisting(origin, healthPath, id) {
108
120
  try {
109
121
  const res = await fetch(`${origin}${healthPath}`, { signal: AbortSignal.timeout(tuning().reuseProbeTimeoutMs) })
110
- if (!res.ok) return null
122
+ if (!res.ok) return { verdict: 'absent' }
111
123
  const info = await res.json()
112
- if (info?.service === id || info?.name === id || info?.bridge === id) return info
113
- } catch { /* 端口没有本服务 */ }
114
- return null
124
+ if (info?.service === id || info?.name === id || info?.bridge === id) return { verdict: 'found', info }
125
+ return { verdict: 'absent' }
126
+ } catch (error) {
127
+ /* 只有「连接被拒绝」能证明端口上没有服务;超时/连接重置等是「不可结论」——
128
+ * 锁持有者可能只是应答慢。把不可结论当成「没人」会回收活锁,让两个实例同时
129
+ * 跑起来(split-brain)。调用方对 inconclusive 必须保守拒绝,而不是抢锁。 */
130
+ const code = error?.cause?.code || error?.code
131
+ if (code === 'ECONNREFUSED') return { verdict: 'absent' }
132
+ return { verdict: 'inconclusive' }
133
+ }
115
134
  }
116
135
 
117
136
  function safeJoin(root, rel) {
@@ -148,6 +167,7 @@ export function createServiceApp(options = {}) {
148
167
  let listeningPort = 0
149
168
  let url = ''
150
169
  let closed = false
170
+ let workdir = ''
151
171
 
152
172
  const app = {
153
173
  id,
@@ -193,7 +213,7 @@ export function createServiceApp(options = {}) {
193
213
  const relRaw = cleanPrefix ? u.pathname.slice(cleanPrefix.length) : u.pathname
194
214
  const rel = relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
195
215
  let file = null
196
- let type = MIME[path.extname(rel).toLowerCase()] || 'application/octet-stream'
216
+ let type = mimeFor(rel)
197
217
  if (files) {
198
218
  const hit = files[relRaw === '' ? '/' : relRaw] || files[relRaw]
199
219
  if (!hit) return false
@@ -236,6 +256,7 @@ export function createServiceApp(options = {}) {
236
256
  contractVersion,
237
257
  pid: process.pid,
238
258
  port: listeningPort,
259
+ ...(workdir ? { workdir } : {}),
239
260
  uptimeSec: Math.max(0, Math.round((Date.now() - startedAt) / 1000)),
240
261
  }
241
262
  },
@@ -275,6 +296,27 @@ export function createServiceApp(options = {}) {
275
296
  if (stripPrefix && (u.pathname === stripPrefix || u.pathname.startsWith(stripPrefix + '/'))) {
276
297
  u.pathname = u.pathname.slice(stripPrefix.length) || '/'
277
298
  }
299
+ /* 挂载前缀之后再允许一层会话段:`<prefix>/s/<会话id>/…`。
300
+ * 剥掉它再交给工作台自己的路由,相对资源和相对 API 因此一行都不用改;
301
+ * 会话 id 同时挂在 `u.sessionId` / `req.sessionId` 上,需要区分的路由直接读。 */
302
+ const session = SESSION_PATH.exec(u.pathname)
303
+ if (session) {
304
+ const sid = session[1]
305
+ const rest = u.pathname.slice(session[0].length)
306
+ if (!rest) {
307
+ /* `<prefix>/s/<sid>` 少了尾斜杠:相对地址会被解析成 `<prefix>/s/<文件>`,
308
+ * 页面里的 ./app.js 直接 404。和静态宿主一样 301 补齐。 */
309
+ const location = `${stripPrefix || ''}${u.pathname}/${u.search || ''}`
310
+ try {
311
+ res.writeHead(301, { location, 'cache-control': 'no-store' })
312
+ res.end()
313
+ } catch { res.destroy() }
314
+ return
315
+ }
316
+ u.sessionId = sid
317
+ req.sessionId = sid
318
+ u.pathname = rest
319
+ }
278
320
  if (u.pathname === '/healthz') {
279
321
  return send(req, res, 200, await app.health())
280
322
  }
@@ -306,6 +348,9 @@ export function createServiceApp(options = {}) {
306
348
  */
307
349
  async listen(listenOptions = {}) {
308
350
  if (app.running) throw new Error(`service-host ${id}: 已经在运行`)
351
+ /* close 之后允许再次 listen:复位 closed,否则第二次 close 变空操作,
352
+ * 注册/锁/discovery 全部泄漏(历史故障形态)。 */
353
+ closed = false
309
354
  const host = listenOptions.host || '127.0.0.1'
310
355
  const port = Number(listenOptions.port ?? 0)
311
356
  const strictPort = !!listenOptions.strictPort
@@ -328,21 +373,36 @@ export function createServiceApp(options = {}) {
328
373
  }
329
374
 
330
375
  const hostDir = listenOptions.hostDir || path.join(os.tmpdir(), `dsh-${id}`)
376
+ workdir = path.resolve(hostDir)
331
377
  const lockFile = listenOptions.lockFile || path.join(hostDir, 'service.lock')
332
378
  const publicBasePath = basePath
333
379
  const healthPath = `${publicBasePath}/healthz` || '/healthz'
334
380
 
335
381
  if (allowReuse && port > 0) {
336
- const existing = await probeExisting(`http://127.0.0.1:${port}`, healthPath, id)
337
- /* 只复用同契约版本的实例:旧代码/半初始化实例不能被当成本实例。 */
338
- if (existing && existing.contractVersion && existing.contractVersion === contractVersion) {
382
+ const probe = await probeExisting(`http://127.0.0.1:${port}`, healthPath, id)
383
+ const existing = probe.verdict === 'found' ? probe.info : null
384
+ /* 复用必须“同身份”:契约版本相同只说明协议兼容,不代表跑的是当前代码。
385
+ * 历史故障:套件升级到 0.2.1 后,9 小时前的 0.2.0 进程因 contractVersion
386
+ * 同为 1.0.0 被复用,新代码根本没跑起来。身份 = 包版本 + 契约版本 + 数据目录。
387
+ * workdir 不同 = 同版本但指向另一份数据,静默复用会把请求打进错实例。 */
388
+ const sameContract = !!existing?.contractVersion && existing.contractVersion === contractVersion
389
+ const sameVersion = !existing?.version || existing.version === version
390
+ const sameWorkdir = !existing?.workdir || path.resolve(existing.workdir) === workdir
391
+ if (existing && sameContract && sameVersion && sameWorkdir) {
339
392
  listeningPort = port
340
393
  url = `http://127.0.0.1:${port}${publicBasePath}`
341
394
  return { url, port, reused: true, mode: 'standalone', stop: async () => {} }
342
395
  }
396
+ if (existing && !(sameContract && sameVersion && sameWorkdir)) {
397
+ const old = `pid ${existing.pid || '?'},version ${existing.version || '?'},contract ${existing.contractVersion || '?'},workdir ${existing.workdir || '?'}`
398
+ throw new Error(
399
+ `${id} 端口 ${port} 被不同身份的实例占用(${old};当前 ${version} / ${contractVersion} / ${workdir})。` +
400
+ `为避免“新套件 + 旧进程”或“同版本 + 错数据目录”的假启动,已拒绝复用:请结束 ${existing.pid || '该'} 进程或重启 DSH 后再启动。`,
401
+ )
402
+ }
343
403
  }
344
404
 
345
- const lock = acquireLock(lockFile)
405
+ const lock = await acquireLock(lockFile, { healthPath, id })
346
406
  if (!lock) {
347
407
  throw new Error(`${id} 已有另一个实例在运行;如确认没有,请删除锁文件: ${lockFile}`)
348
408
  }
package/src/tuning.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * dsh-service-host 运行时调优层。
2
+ * @capyclaw/service-host 运行时调优层。
3
3
  *
4
4
  * 默认值与进化搜索(evolution/ NSGA-II)的 founder 基线保持一致;
5
5
  * 生产环境可用 DSH_TUNING_JSON 覆盖(按包名分组),测试/评估用 setTuning 注入。