@capyclaw/wall-suite 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/composition.lock.json +48 -0
- package/contract/wall-contract.json +8 -0
- package/cordis.patch.yml +6 -0
- package/dsh-suite.json +118 -0
- package/lib/index.mjs +6 -0
- package/node_modules/@capyclaw/asset-service/README.md +48 -0
- package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
- package/node_modules/@capyclaw/asset-service/package.json +59 -0
- package/node_modules/@capyclaw/asset-service/src/index.mjs +223 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +143 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +41 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/node_modules/@capyclaw/portal/README.md +70 -0
- package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
- package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
- package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
- package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
- package/node_modules/@capyclaw/portal/package.json +40 -0
- package/node_modules/@capyclaw/service-broker/README.md +104 -0
- package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
- package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
- package/node_modules/@capyclaw/service-broker/lib/control.mjs +193 -0
- package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
- package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1236 -0
- package/node_modules/@capyclaw/service-broker/lib/host.mjs +182 -0
- package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +249 -0
- package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +325 -0
- package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +28 -0
- package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
- package/node_modules/@capyclaw/service-broker/package.json +65 -0
- package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
- package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
- package/node_modules/@capyclaw/service-broker/services.json +3 -0
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- package/node_modules/@capyclaw/tool-host/README.md +56 -0
- package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +16 -0
- package/node_modules/@capyclaw/tool-host/package.json +59 -0
- package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +142 -0
- package/node_modules/@capyclaw/tool-host/src/index.mjs +390 -0
- package/node_modules/@capyclaw/wall-workbench/README.md +58 -0
- package/node_modules/@capyclaw/wall-workbench/contract/wall-contract.json +8 -0
- package/node_modules/@capyclaw/wall-workbench/lib/host.mjs +1 -0
- package/node_modules/@capyclaw/wall-workbench/package.json +63 -0
- package/node_modules/@capyclaw/wall-workbench/plugin.mjs +1 -0
- package/node_modules/@capyclaw/wall-workbench/server/constants.mjs +12 -0
- package/node_modules/@capyclaw/wall-workbench/server/contract.mjs +12 -0
- package/node_modules/@capyclaw/wall-workbench/server/embedded-host.mjs +160 -0
- package/node_modules/@capyclaw/wall-workbench/server/infra/http.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/infra/tuning.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/relay.mjs +68 -0
- package/node_modules/@capyclaw/wall-workbench/server/routes/claim.mjs +46 -0
- package/node_modules/@capyclaw/wall-workbench/server/routes/workbench.mjs +29 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/SHARED_MANIFEST.json +70 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/asset-service.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/editor-host.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/editor/lease.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/api.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/http.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/mcp-http.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tools/validate.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tuning.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/util/fs-lock.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/service-host.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/tool-host.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/tuning.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/tools/capabilities/index.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/tools/index.mjs +12 -0
- package/node_modules/@capyclaw/wall-workbench/server/tools.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/workbench-framework.mjs +305 -0
- package/node_modules/@capyclaw/wall-workbench/ui/app.js +142 -0
- package/node_modules/@capyclaw/wall-workbench/ui/index.html +20 -0
- package/node_modules/@capyclaw/wall-workbench/ui/style.css +74 -0
- package/package.json +72 -4
- package/services.json +3 -0
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/service-host —— 通用服务宿主。
|
|
3
|
+
*
|
|
4
|
+
* 功能插件只声明“我有哪些路由、健康字段、指标”,不再自己写:
|
|
5
|
+
* - http server / listen / 端口扫描 / strictPort
|
|
6
|
+
* - 单实例锁 / 复用探测 / discovery 文件
|
|
7
|
+
* - /healthz /metrics 标准骨架
|
|
8
|
+
* - 静态资源、路径穿越防护、优雅关闭
|
|
9
|
+
*
|
|
10
|
+
* 两种模式:
|
|
11
|
+
* standalone(默认):自建 loopback server,行为与旧 relay 一致;
|
|
12
|
+
* embedded:传入 DSH 的 ctx.webServer,把同一套路由挂到 `<basePath>` 前缀。
|
|
13
|
+
*/
|
|
14
|
+
import http from 'node:http'
|
|
15
|
+
import fs from 'node:fs'
|
|
16
|
+
import os from 'node:os'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import crypto from 'node:crypto'
|
|
19
|
+
import { listen, send, sendText, readBody } from '@capyclaw/plugin-kit/service/http'
|
|
20
|
+
import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
|
|
21
|
+
import { isLoopbackOrigin as sharedIsLoopbackOrigin, mimeFor } from '@capyclaw/plugin-kit/util/http'
|
|
22
|
+
import { tuning } from './tuning.mjs'
|
|
23
|
+
|
|
24
|
+
function slugOf(id) {
|
|
25
|
+
return String(id || 'service').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'service'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function pidAlive(pid) {
|
|
29
|
+
if (!pid) return false
|
|
30
|
+
try { process.kill(pid, 0); return true } catch (error) { return error.code === 'EPERM' }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 浏览器跨源写请求防护:只允许本机 loopback 页面 POST(空 Origin 视为同源导航,放行)。 */
|
|
34
|
+
const isLoopbackOrigin = sharedIsLoopbackOrigin
|
|
35
|
+
|
|
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 } = {}) {
|
|
55
|
+
fs.mkdirSync(path.dirname(lockFile), { recursive: true })
|
|
56
|
+
const token = crypto.randomBytes(12).toString('hex')
|
|
57
|
+
const { lockFreshGraceMs } = tuning()
|
|
58
|
+
/** 刚拿到锁、还没 listen 成功的实例允许占位多久(秒级即可,超时视为卡死)。 */
|
|
59
|
+
const startingGraceMs = Math.max(lockFreshGraceMs, 15000)
|
|
60
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
61
|
+
try {
|
|
62
|
+
/* 原子创建:两个进程同时启动时只有一个能拿到 'wx'。 */
|
|
63
|
+
const fd = fs.openSync(lockFile, 'wx')
|
|
64
|
+
try {
|
|
65
|
+
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, token, port: 0, timestamp: Date.now() }))
|
|
66
|
+
try { fs.fsyncSync(fd) } catch { /* 部分文件系统不支持 */ }
|
|
67
|
+
} finally {
|
|
68
|
+
fs.closeSync(fd)
|
|
69
|
+
}
|
|
70
|
+
return { file: lockFile, token }
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error.code !== 'EEXIST') throw error
|
|
73
|
+
let info = null
|
|
74
|
+
try { info = JSON.parse(fs.readFileSync(lockFile, 'utf8')) } catch { /* 可能正在写入 */ }
|
|
75
|
+
let age = 0
|
|
76
|
+
try { age = Date.now() - fs.statSync(lockFile).mtimeMs } catch { /* 已被移除 */ }
|
|
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
|
+
}
|
|
94
|
+
try { fs.rmSync(lockFile, { force: true }) } catch { /* 忽略 */ }
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return null
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function writeLock(lock, port) {
|
|
101
|
+
let current = null
|
|
102
|
+
try { current = JSON.parse(fs.readFileSync(lock.file, 'utf8')) } catch { /* 忽略 */ }
|
|
103
|
+
if (!current || current.token !== lock.token) {
|
|
104
|
+
throw new Error(`锁已被其它实例接管: ${lock.file}`)
|
|
105
|
+
}
|
|
106
|
+
fs.writeFileSync(lock.file, JSON.stringify({
|
|
107
|
+
pid: process.pid, token: lock.token, port, timestamp: Date.now(),
|
|
108
|
+
}))
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function releaseLock(lock) {
|
|
112
|
+
if (!lock) return
|
|
113
|
+
try {
|
|
114
|
+
const data = JSON.parse(fs.readFileSync(lock.file, 'utf8'))
|
|
115
|
+
if (data.token === lock.token) fs.rmSync(lock.file, { force: true })
|
|
116
|
+
} catch { /* 不是自己的锁或已被删除 */ }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function probeExisting(origin, healthPath, id) {
|
|
120
|
+
try {
|
|
121
|
+
const res = await fetch(`${origin}${healthPath}`, { signal: AbortSignal.timeout(tuning().reuseProbeTimeoutMs) })
|
|
122
|
+
if (!res.ok) return { verdict: 'absent' }
|
|
123
|
+
const info = await res.json()
|
|
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
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function safeJoin(root, rel) {
|
|
137
|
+
const target = path.resolve(root, `.${path.sep}${rel}`)
|
|
138
|
+
const base = path.resolve(root)
|
|
139
|
+
return target === base || target.startsWith(base + path.sep) ? target : null
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* @param {{
|
|
144
|
+
* id: string,
|
|
145
|
+
* title?: string,
|
|
146
|
+
* version?: string,
|
|
147
|
+
* contractVersion?: string,
|
|
148
|
+
* publicBasePath?: string,
|
|
149
|
+
* health?: (() => object)|object,
|
|
150
|
+
* metrics?: (() => Array<[string, number]>|string)|Array<[string, number]>|string,
|
|
151
|
+
* }} options
|
|
152
|
+
*/
|
|
153
|
+
export function createServiceApp(options = {}) {
|
|
154
|
+
if (!options.id) throw new Error('createServiceApp: id 必填')
|
|
155
|
+
const id = String(options.id)
|
|
156
|
+
const title = options.title || id
|
|
157
|
+
const version = options.version || '0.0.0'
|
|
158
|
+
const contractVersion = options.contractVersion || '1.0.0'
|
|
159
|
+
const slug = slugOf(options.slug || id)
|
|
160
|
+
const startedAt = Date.now()
|
|
161
|
+
const routes = []
|
|
162
|
+
let healthExtra = options.health || null
|
|
163
|
+
let metricsExtra = options.metrics || null
|
|
164
|
+
let server = null
|
|
165
|
+
let embeddedDispose = null
|
|
166
|
+
let basePath = options.publicBasePath || ''
|
|
167
|
+
let listeningPort = 0
|
|
168
|
+
let url = ''
|
|
169
|
+
let closed = false
|
|
170
|
+
let workdir = ''
|
|
171
|
+
|
|
172
|
+
const app = {
|
|
173
|
+
id,
|
|
174
|
+
title,
|
|
175
|
+
version,
|
|
176
|
+
contractVersion,
|
|
177
|
+
slug,
|
|
178
|
+
get port() { return listeningPort },
|
|
179
|
+
get url() { return url },
|
|
180
|
+
get running() { return !!server || !!embeddedDispose },
|
|
181
|
+
|
|
182
|
+
/** 注册一个中间件式路由:返回 true 表示已处理。 */
|
|
183
|
+
use(handler) {
|
|
184
|
+
if (typeof handler !== 'function') throw new Error('service-host: route handler 必须是函数')
|
|
185
|
+
routes.push(handler)
|
|
186
|
+
return () => {
|
|
187
|
+
const index = routes.indexOf(handler)
|
|
188
|
+
if (index >= 0) routes.splice(index, 1)
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
|
|
192
|
+
get(pathname, handler) {
|
|
193
|
+
return app.use((req, res, u) => {
|
|
194
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return false
|
|
195
|
+
if (u.pathname !== pathname) return false
|
|
196
|
+
return Promise.resolve(handler(req, res, u)).then(() => true)
|
|
197
|
+
})
|
|
198
|
+
},
|
|
199
|
+
|
|
200
|
+
post(pathname, handler) {
|
|
201
|
+
return app.use((req, res, u) => {
|
|
202
|
+
if (req.method !== 'POST' || u.pathname !== pathname) return false
|
|
203
|
+
return Promise.resolve(handler(req, res, u)).then(() => true)
|
|
204
|
+
})
|
|
205
|
+
},
|
|
206
|
+
|
|
207
|
+
/** 静态目录挂载。files 可给显式映射:{ '/': ['index.html','text/html'] }。 */
|
|
208
|
+
static(prefix, dir, { files = null, index = 'index.html' } = {}) {
|
|
209
|
+
const cleanPrefix = prefix === '/' ? '' : prefix.replace(/\/+$/, '')
|
|
210
|
+
return app.use((req, res, u) => {
|
|
211
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return false
|
|
212
|
+
if (cleanPrefix && u.pathname !== cleanPrefix && !u.pathname.startsWith(cleanPrefix + '/')) return false
|
|
213
|
+
const relRaw = cleanPrefix ? u.pathname.slice(cleanPrefix.length) : u.pathname
|
|
214
|
+
const rel = relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
|
|
215
|
+
let file = null
|
|
216
|
+
let type = mimeFor(rel)
|
|
217
|
+
if (files) {
|
|
218
|
+
const hit = files[relRaw === '' ? '/' : relRaw] || files[relRaw]
|
|
219
|
+
if (!hit) return false
|
|
220
|
+
const [name, explicitType] = Array.isArray(hit) ? hit : [hit]
|
|
221
|
+
file = safeJoin(dir, name)
|
|
222
|
+
type = explicitType || type
|
|
223
|
+
} else {
|
|
224
|
+
file = safeJoin(dir, rel)
|
|
225
|
+
}
|
|
226
|
+
if (!file) return false
|
|
227
|
+
try {
|
|
228
|
+
const data = fs.readFileSync(file)
|
|
229
|
+
res.writeHead(200, {
|
|
230
|
+
'content-type': type,
|
|
231
|
+
'content-length': data.length,
|
|
232
|
+
'x-content-type-options': 'nosniff',
|
|
233
|
+
'referrer-policy': 'no-referrer',
|
|
234
|
+
'cache-control': 'no-cache',
|
|
235
|
+
})
|
|
236
|
+
res.end(req.method === 'HEAD' ? undefined : data)
|
|
237
|
+
return true
|
|
238
|
+
} catch {
|
|
239
|
+
return false
|
|
240
|
+
}
|
|
241
|
+
})
|
|
242
|
+
},
|
|
243
|
+
|
|
244
|
+
setHealth(fn) { healthExtra = fn; return app },
|
|
245
|
+
setMetrics(fn) { metricsExtra = fn; return app },
|
|
246
|
+
|
|
247
|
+
async health() {
|
|
248
|
+
const extra = typeof healthExtra === 'function' ? await healthExtra() : (healthExtra || {})
|
|
249
|
+
return {
|
|
250
|
+
...extra,
|
|
251
|
+
ok: true,
|
|
252
|
+
service: id,
|
|
253
|
+
name: id,
|
|
254
|
+
title,
|
|
255
|
+
version,
|
|
256
|
+
contractVersion,
|
|
257
|
+
pid: process.pid,
|
|
258
|
+
port: listeningPort,
|
|
259
|
+
...(workdir ? { workdir } : {}),
|
|
260
|
+
uptimeSec: Math.max(0, Math.round((Date.now() - startedAt) / 1000)),
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
|
|
264
|
+
async metricsText() {
|
|
265
|
+
const uptime = Math.max(0, Math.round((Date.now() - startedAt) / 1000))
|
|
266
|
+
const lines = [
|
|
267
|
+
`# HELP ${slug}_up 服务是否在线`,
|
|
268
|
+
`# TYPE ${slug}_up gauge`,
|
|
269
|
+
`${slug}_up 1`,
|
|
270
|
+
`# HELP ${slug}_uptime_seconds 服务运行秒数`,
|
|
271
|
+
`# TYPE ${slug}_uptime_seconds gauge`,
|
|
272
|
+
`${slug}_uptime_seconds ${uptime}`,
|
|
273
|
+
`# HELP ${slug}_port 实际监听端口`,
|
|
274
|
+
`# TYPE ${slug}_port gauge`,
|
|
275
|
+
`${slug}_port ${listeningPort}`,
|
|
276
|
+
]
|
|
277
|
+
const extra = typeof metricsExtra === 'function' ? await metricsExtra() : metricsExtra
|
|
278
|
+
if (typeof extra === 'string' && extra) lines.push(extra.replace(/\s+$/, ''))
|
|
279
|
+
else if (Array.isArray(extra)) {
|
|
280
|
+
for (const row of extra) {
|
|
281
|
+
if (!Array.isArray(row)) continue
|
|
282
|
+
const [name, value] = row
|
|
283
|
+
if (name) lines.push(`${name} ${Number(value) || 0}`)
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return lines.join('\n') + '\n'
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
async dispatch(req, res, stripPrefix = '') {
|
|
290
|
+
try {
|
|
291
|
+
/* 畸形请求行(如 absolute-form URL)不能让整个宿主进程崩溃。 */
|
|
292
|
+
const u = new URL(req.url || '/', 'http://127.0.0.1')
|
|
293
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && !isLoopbackOrigin(req.headers.origin)) {
|
|
294
|
+
return send(req, res, 403, { ok: false, error: 'cross-origin write blocked' })
|
|
295
|
+
}
|
|
296
|
+
if (stripPrefix && (u.pathname === stripPrefix || u.pathname.startsWith(stripPrefix + '/'))) {
|
|
297
|
+
u.pathname = u.pathname.slice(stripPrefix.length) || '/'
|
|
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
|
+
}
|
|
320
|
+
if (u.pathname === '/healthz') {
|
|
321
|
+
return send(req, res, 200, await app.health())
|
|
322
|
+
}
|
|
323
|
+
if (u.pathname === '/metrics') {
|
|
324
|
+
return sendText(req, res, 200, await app.metricsText(), 'text/plain; version=0.0.4; charset=utf-8')
|
|
325
|
+
}
|
|
326
|
+
for (const handler of routes) {
|
|
327
|
+
if (await handler(req, res, u)) return
|
|
328
|
+
}
|
|
329
|
+
return send(req, res, 404, { ok: false, error: 'not found', path: u.pathname })
|
|
330
|
+
} catch (error) {
|
|
331
|
+
const status = error?.code === 'BODY_TOO_LARGE'
|
|
332
|
+
? 413
|
|
333
|
+
: error?.code === 'BAD_JSON' || error?.code === 'ERR_INVALID_URL'
|
|
334
|
+
? 400
|
|
335
|
+
: 500
|
|
336
|
+
if (!res.headersSent) send(req, res, status, { ok: false, error: String((error && error.message) || error) })
|
|
337
|
+
else res.destroy()
|
|
338
|
+
}
|
|
339
|
+
},
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* @param {{
|
|
343
|
+
* port?: number, host?: string, strictPort?: boolean, allowReuse?: boolean,
|
|
344
|
+
* scanLimit?: number, lockFile?: string, hostDir?: string,
|
|
345
|
+
* discoveryFile?: string, discovery?: object, publicBasePath?: string,
|
|
346
|
+
* webServer?: object, basePath?: string,
|
|
347
|
+
* }} listenOptions
|
|
348
|
+
*/
|
|
349
|
+
async listen(listenOptions = {}) {
|
|
350
|
+
if (app.running) throw new Error(`service-host ${id}: 已经在运行`)
|
|
351
|
+
/* close 之后允许再次 listen:复位 closed,否则第二次 close 变空操作,
|
|
352
|
+
* 注册/锁/discovery 全部泄漏(历史故障形态)。 */
|
|
353
|
+
closed = false
|
|
354
|
+
const host = listenOptions.host || '127.0.0.1'
|
|
355
|
+
const port = Number(listenOptions.port ?? 0)
|
|
356
|
+
const strictPort = !!listenOptions.strictPort
|
|
357
|
+
const allowReuse = listenOptions.allowReuse !== false
|
|
358
|
+
const scanLimit = Number(listenOptions.scanLimit ?? tuning().portScanLimit)
|
|
359
|
+
basePath = listenOptions.publicBasePath ?? listenOptions.basePath ?? basePath ?? ''
|
|
360
|
+
if (basePath === '/') basePath = ''
|
|
361
|
+
|
|
362
|
+
const webServer = listenOptions.webServer
|
|
363
|
+
if (webServer && typeof webServer.register === 'function') {
|
|
364
|
+
const prefix = basePath || `/plugins/${id}`
|
|
365
|
+
embeddedDispose = webServer.register({
|
|
366
|
+
kind: 'prefix',
|
|
367
|
+
path: prefix,
|
|
368
|
+
handler: (req, res) => app.dispatch(req, res, prefix),
|
|
369
|
+
})
|
|
370
|
+
listeningPort = Number(webServer.port) || 0
|
|
371
|
+
url = `http://127.0.0.1:${listeningPort}${prefix}`
|
|
372
|
+
return { url, port: listeningPort, reused: false, mode: 'embedded', stop: app.close }
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const hostDir = listenOptions.hostDir || path.join(os.tmpdir(), `dsh-${id}`)
|
|
376
|
+
workdir = path.resolve(hostDir)
|
|
377
|
+
const lockFile = listenOptions.lockFile || path.join(hostDir, 'service.lock')
|
|
378
|
+
const publicBasePath = basePath
|
|
379
|
+
const healthPath = `${publicBasePath}/healthz` || '/healthz'
|
|
380
|
+
|
|
381
|
+
if (allowReuse && port > 0) {
|
|
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) {
|
|
392
|
+
listeningPort = port
|
|
393
|
+
url = `http://127.0.0.1:${port}${publicBasePath}`
|
|
394
|
+
return { url, port, reused: true, mode: 'standalone', stop: async () => {} }
|
|
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
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const lock = await acquireLock(lockFile, { healthPath, id })
|
|
406
|
+
if (!lock) {
|
|
407
|
+
throw new Error(`${id} 已有另一个实例在运行;如确认没有,请删除锁文件: ${lockFile}`)
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
let actualPort = port
|
|
411
|
+
let lastError = null
|
|
412
|
+
const requestTimeoutMs = Number(listenOptions.requestTimeoutMs) || 30000
|
|
413
|
+
const headersTimeoutMs = Number(listenOptions.headersTimeoutMs) || 10000
|
|
414
|
+
const keepAliveTimeoutMs = Number(listenOptions.keepAliveTimeoutMs) || 5000
|
|
415
|
+
for (let attempt = 0; attempt <= (strictPort ? 0 : scanLimit); attempt++) {
|
|
416
|
+
const tryPort = port === 0 ? 0 : port + attempt
|
|
417
|
+
try {
|
|
418
|
+
server = await listen(tryPort, { host, requestTimeoutMs, headersTimeoutMs, keepAliveTimeoutMs })
|
|
419
|
+
actualPort = server.address().port
|
|
420
|
+
break
|
|
421
|
+
} catch (error) {
|
|
422
|
+
lastError = error
|
|
423
|
+
if (port === 0 || strictPort || attempt === scanLimit) {
|
|
424
|
+
releaseLock(lock)
|
|
425
|
+
throw new Error(`端口 ${tryPort} 不可用${strictPort ? '(strictPort)' : ''}: ${(error && error.message) || error}`)
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (!server) {
|
|
430
|
+
releaseLock(lock)
|
|
431
|
+
throw lastError || new Error('无法监听端口')
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
try {
|
|
435
|
+
writeLock(lock, actualPort)
|
|
436
|
+
} catch (error) {
|
|
437
|
+
try { server.close() } catch { /* 忽略 */ }
|
|
438
|
+
server = null
|
|
439
|
+
releaseLock(lock)
|
|
440
|
+
throw error
|
|
441
|
+
}
|
|
442
|
+
listeningPort = actualPort
|
|
443
|
+
url = `http://127.0.0.1:${actualPort}${publicBasePath}`
|
|
444
|
+
|
|
445
|
+
server.on('request', (req, res) => {
|
|
446
|
+
Promise.resolve(app.dispatch(req, res, publicBasePath)).catch((error) => {
|
|
447
|
+
try {
|
|
448
|
+
if (!res.headersSent) send(req, res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
449
|
+
else res.destroy()
|
|
450
|
+
} catch { /* 连接已断开 */ }
|
|
451
|
+
})
|
|
452
|
+
})
|
|
453
|
+
const discoveryFile = listenOptions.discoveryFile
|
|
454
|
+
|| (listenOptions.hostDir ? path.join(hostDir, 'discovery.json') : '')
|
|
455
|
+
if (discoveryFile) {
|
|
456
|
+
try {
|
|
457
|
+
fs.mkdirSync(path.dirname(discoveryFile), { recursive: true })
|
|
458
|
+
fs.writeFileSync(discoveryFile, JSON.stringify({
|
|
459
|
+
service: id,
|
|
460
|
+
...(listenOptions.discovery || {}),
|
|
461
|
+
url, port: actualPort, pid: process.pid, updated: new Date().toISOString(),
|
|
462
|
+
}, null, 2))
|
|
463
|
+
} catch { /* discovery 写失败不影响服务 */ }
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
app._lock = lock
|
|
467
|
+
app._discoveryFile = discoveryFile
|
|
468
|
+
return { url, port: actualPort, reused: false, mode: 'standalone', stop: app.close }
|
|
469
|
+
},
|
|
470
|
+
|
|
471
|
+
async close() {
|
|
472
|
+
if (closed) return
|
|
473
|
+
closed = true
|
|
474
|
+
if (embeddedDispose) {
|
|
475
|
+
try { embeddedDispose() } catch { /* 忽略 */ }
|
|
476
|
+
embeddedDispose = null
|
|
477
|
+
return
|
|
478
|
+
}
|
|
479
|
+
if (!server) return
|
|
480
|
+
const srv = server
|
|
481
|
+
server = null
|
|
482
|
+
await new Promise((resolve) => {
|
|
483
|
+
const { closeGraceMs, closeForceMs } = tuning()
|
|
484
|
+
let done = false
|
|
485
|
+
const finish = () => { if (done) return; done = true; resolve() }
|
|
486
|
+
srv.close(finish)
|
|
487
|
+
setTimeout(() => srv.closeAllConnections?.(), closeGraceMs).unref?.()
|
|
488
|
+
setTimeout(finish, closeForceMs).unref?.()
|
|
489
|
+
})
|
|
490
|
+
if (app._discoveryFile) {
|
|
491
|
+
try {
|
|
492
|
+
const data = JSON.parse(fs.readFileSync(app._discoveryFile, 'utf8'))
|
|
493
|
+
if (data.pid === process.pid) fs.rmSync(app._discoveryFile, { force: true })
|
|
494
|
+
} catch { /* 忽略 */ }
|
|
495
|
+
}
|
|
496
|
+
if (app._lock) releaseLock(app._lock)
|
|
497
|
+
},
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
return app
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
export function createServiceHost(config = {}) {
|
|
504
|
+
return {
|
|
505
|
+
api: createServiceApi('serviceHost', '1.0.0', ['http', 'static', 'health', 'metrics', 'lock', 'reuse', 'discovery', 'shared-host']),
|
|
506
|
+
version: '0.1.0',
|
|
507
|
+
createApp(options = {}) {
|
|
508
|
+
return createServiceApp({ ...config, ...options })
|
|
509
|
+
},
|
|
510
|
+
createSharedHost(options = {}) {
|
|
511
|
+
return createSharedHost({ ...config, ...options })
|
|
512
|
+
},
|
|
513
|
+
readBody,
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* 共享宿主:多个功能插件挂到同一个 HTTP server / 同一个端口。
|
|
519
|
+
*
|
|
520
|
+
* const host = ctx.serviceHost.createSharedHost({ id: 'dsh-app' })
|
|
521
|
+
* host.mount('/plugins/ppt', pptApp)
|
|
522
|
+
* host.mount('/plugins/canvas', canvasApp)
|
|
523
|
+
* await host.listen({ port: 3080 })
|
|
524
|
+
*
|
|
525
|
+
* 每个子 app 仍由 createServiceApp 创建;共享宿主只负责前缀分发和统一生命周期。
|
|
526
|
+
* @param {{ id?: string, title?: string, version?: string, contractVersion?: string, health?: Function|object }} options
|
|
527
|
+
*/
|
|
528
|
+
export function createSharedHost(options = {}) {
|
|
529
|
+
const mounts = new Map()
|
|
530
|
+
const id = options.id || 'dsh-shared-host'
|
|
531
|
+
const app = createServiceApp({
|
|
532
|
+
...options,
|
|
533
|
+
id,
|
|
534
|
+
title: options.title || 'DSH Shared Host',
|
|
535
|
+
version: options.version || '0.1.0',
|
|
536
|
+
contractVersion: options.contractVersion || '1.0.0',
|
|
537
|
+
health: options.health || (() => ({ children: [...mounts.keys()] })),
|
|
538
|
+
})
|
|
539
|
+
|
|
540
|
+
const mount = (prefix, child) => {
|
|
541
|
+
const clean = String(prefix || '').replace(/\/+$/, '') || '/'
|
|
542
|
+
if (clean === '/') throw new Error('shared-host: 子插件必须使用非根前缀')
|
|
543
|
+
if (mounts.has(clean)) throw new Error(`shared-host: 前缀已挂载: ${clean}`)
|
|
544
|
+
if (!child || typeof child.dispatch !== 'function') throw new Error(`shared-host: ${clean} 的子 app 必须提供 dispatch()`)
|
|
545
|
+
const dispose = app.use((req, res, u) => {
|
|
546
|
+
if (u.pathname !== clean && !u.pathname.startsWith(clean + '/')) return false
|
|
547
|
+
return child.dispatch(req, res, clean).then(() => true)
|
|
548
|
+
})
|
|
549
|
+
mounts.set(clean, { child, dispose })
|
|
550
|
+
return () => {
|
|
551
|
+
dispose()
|
|
552
|
+
mounts.delete(clean)
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
return {
|
|
557
|
+
id,
|
|
558
|
+
app,
|
|
559
|
+
api: createServiceApi('serviceHost', '1.0.0', ['shared-host']),
|
|
560
|
+
mount,
|
|
561
|
+
children() { return [...mounts.keys()] },
|
|
562
|
+
listen(listenOptions = {}) {
|
|
563
|
+
return app.listen(listenOptions)
|
|
564
|
+
},
|
|
565
|
+
close() {
|
|
566
|
+
return app.close()
|
|
567
|
+
},
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
export { send, sendText, readBody }
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/service-host 运行时调优层。
|
|
3
|
+
*
|
|
4
|
+
* 默认值与进化搜索(evolution/ NSGA-II)的 founder 基线保持一致;
|
|
5
|
+
* 生产环境可用 DSH_TUNING_JSON 覆盖(按包名分组),测试/评估用 setTuning 注入。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const DEFAULTS = {
|
|
9
|
+
/* 端口被占时向后顺延扫描的次数上限(非 strictPort) */
|
|
10
|
+
portScanLimit: 50,
|
|
11
|
+
/* 复用既有实例的 /healthz 探测超时
|
|
12
|
+
* 200ms 由进化搜索固化(evolution/,2026-11-01):黑洞端口启动阻塞 425→227ms;
|
|
13
|
+
* 健康实例 RTT 1-3ms,仍有 60 倍以上余量。 */
|
|
14
|
+
reuseProbeTimeoutMs: 200,
|
|
15
|
+
/* 单实例锁:空/坏锁视为残留前的宽限 */
|
|
16
|
+
lockFreshGraceMs: 2000,
|
|
17
|
+
/* 优雅关闭:先等 N ms 再断开全部连接 */
|
|
18
|
+
closeGraceMs: 50,
|
|
19
|
+
/* 优雅关闭:强制完成的兜底时限 */
|
|
20
|
+
closeForceMs: 1000,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let overrides = {}
|
|
24
|
+
let envLoaded = false
|
|
25
|
+
|
|
26
|
+
function loadEnv() {
|
|
27
|
+
if (envLoaded) return
|
|
28
|
+
envLoaded = true
|
|
29
|
+
try {
|
|
30
|
+
const raw = process.env.DSH_TUNING_JSON
|
|
31
|
+
if (!raw) return
|
|
32
|
+
const parsed = JSON.parse(raw)
|
|
33
|
+
if (!parsed || typeof parsed !== 'object') return
|
|
34
|
+
const own = parsed['dsh-service-host'] && typeof parsed['dsh-service-host'] === 'object'
|
|
35
|
+
? parsed['dsh-service-host']
|
|
36
|
+
: parsed
|
|
37
|
+
for (const key of Object.keys(DEFAULTS)) {
|
|
38
|
+
if (own[key] !== undefined) overrides[key] = own[key]
|
|
39
|
+
}
|
|
40
|
+
} catch { /* 非法 JSON 静默忽略:调优失败不能阻塞启动 */ }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 当前生效参数(默认值 + env + setTuning 覆盖)。 */
|
|
44
|
+
export function tuning() {
|
|
45
|
+
loadEnv()
|
|
46
|
+
return { ...DEFAULTS, ...overrides }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 测试/评估注入。只接受已知键,避免拼写错误静默生效。 */
|
|
50
|
+
export function setTuning(patch = {}) {
|
|
51
|
+
loadEnv()
|
|
52
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
53
|
+
if (key in DEFAULTS) overrides[key] = value
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 恢复到默认值 + env 覆盖。 */
|
|
58
|
+
export function resetTuning() {
|
|
59
|
+
overrides = {}
|
|
60
|
+
envLoaded = false
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const TUNING_DEFAULTS = { ...DEFAULTS }
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# @capyclaw/tool-host
|
|
2
|
+
|
|
3
|
+
DSH 公共工具面插件。把每个插件都会重复写的工具声明、注册表、参数校验、契约报告、MCP 协议壳和 instructions 模板收成一套。
|
|
4
|
+
|
|
5
|
+
## 使用
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
export const inject = ['toolHost']
|
|
9
|
+
|
|
10
|
+
const echo = ctx.toolHost.defineTool({
|
|
11
|
+
name: 'demo_echo',
|
|
12
|
+
description: '回显文本',
|
|
13
|
+
inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
|
|
14
|
+
handler: ({ text }) => ({ content: [{ type: 'text', text }] }),
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
const capabilities = [
|
|
18
|
+
ctx.toolHost.defineCapability({ id: 'demo', title: 'Demo', tools: [echo] }),
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
const registry = ctx.toolHost.createRegistry(capabilities)
|
|
22
|
+
const mcp = ctx.toolHost.createMcpHandler({
|
|
23
|
+
registry,
|
|
24
|
+
instructions: ctx.toolHost.buildInstructions({ title: 'Demo', capabilities: registry.CAPABILITIES }),
|
|
25
|
+
})
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## 原生 DSH 工具面
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
export const inject = ['toolHost']
|
|
32
|
+
|
|
33
|
+
export function apply(ctx) {
|
|
34
|
+
const registry = ctx.toolHost.createRegistry(capabilities)
|
|
35
|
+
const dispose = ctx.toolHost.registerWithDsh(ctx, registry, { namespace: 'demo' })
|
|
36
|
+
return dispose
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
注册后工具直接出现在 `ctx.tools`,不需要 loopback `/mcp` 和 `dsh-mcp-client` row。
|
|
41
|
+
MCP handler 仍保留给跨进程/外部客户端。
|
|
42
|
+
|
|
43
|
+
## 提供什么
|
|
44
|
+
|
|
45
|
+
- `defineTool` / `defineCapability`:声明式能力 DSL
|
|
46
|
+
- `createRegistry`:校验 id/工具名/依赖/服务唯一性,派生 `TOOLS / TOOL_IMPL / TOOL_META / FEATURES / CAPABILITIES`
|
|
47
|
+
- `createToolDispatcher`:统一参数校验后分派
|
|
48
|
+
- `createMcpHandler`:MCP Streamable HTTP(initialize / ping / tools/list / tools/call)
|
|
49
|
+
- `createCapabilityReport`:契约报告
|
|
50
|
+
- `buildInstructions`:MCP server instructions 模板
|
|
51
|
+
|
|
52
|
+
## 边界
|
|
53
|
+
|
|
54
|
+
- 不绑定具体插件;PPT 只是第一个消费者
|
|
55
|
+
- 不负责 HTTP 监听;和 `@capyclaw/service-host` 组合使用
|
|
56
|
+
- 不负责契约快照文件;由构建脚本调用 `registry.ctx.contract.report()` 生成
|