@capyclaw/windows-control 0.0.0-stage → 0.1.3
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 +142 -2
- package/THIRD_PARTY_NOTICES.md +20 -0
- package/cordis.patch.yml +32 -0
- package/lib/config.mjs +126 -0
- package/lib/mcp-json.mjs +80 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -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 +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -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 +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -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 +198 -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 +71 -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 +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -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 +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -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 +57 -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 +664 -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 +209 -0
- package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
- package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1290 -0
- package/node_modules/@capyclaw/service-broker/lib/host.mjs +187 -0
- package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +262 -0
- package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +275 -0
- package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +48 -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/package.json +65 -4
- package/plugin.mjs +32 -0
- package/server/relay.mjs +752 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// Durable spawn receipts are separate from discovery, which is only observational.
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import net from 'node:net'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
7
|
+
|
|
8
|
+
const POWERSHELL = process.env.DSH_POWERSHELL || 'powershell.exe'
|
|
9
|
+
const QUERY_TIMEOUT_MS = 5000
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 把子进程输出写到临时文件而不是管道。
|
|
13
|
+
*
|
|
14
|
+
* 动机:`spawn` 的管道 stdio 在受限环境下会被直接拒绝(EPERM),而身份查询失败
|
|
15
|
+
* 会让 broker 拒绝启动**所有**服务——这是把"环境限制"放大成"整个中间件不可用"。
|
|
16
|
+
* 文件重定向只依赖普通的文件写入权限,且在沙箱里同样可用。
|
|
17
|
+
*
|
|
18
|
+
* @template T
|
|
19
|
+
* @param {(file: string, fd: number) => T} fn
|
|
20
|
+
* @returns {T}
|
|
21
|
+
*/
|
|
22
|
+
function withTempFile(fn) {
|
|
23
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-ident-'))
|
|
24
|
+
const file = path.join(dir, 'out.txt')
|
|
25
|
+
fs.writeFileSync(file, '')
|
|
26
|
+
const fd = fs.openSync(file, 'a')
|
|
27
|
+
try {
|
|
28
|
+
return fn(file, fd)
|
|
29
|
+
} finally {
|
|
30
|
+
try { fs.closeSync(fd) } catch { /* 已关闭 */ }
|
|
31
|
+
try { fs.rmSync(dir, { recursive: true, force: true }) } catch { /* 尽力清理 */ }
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 同步跑一次 PowerShell 查询,返回 { status, stdout },永不抛。
|
|
37
|
+
* 走文件重定向:不占用管道,也不受管道被禁的环境影响。
|
|
38
|
+
*/
|
|
39
|
+
export function runPowerShellSync(script) {
|
|
40
|
+
return withTempFile((file, fd) => {
|
|
41
|
+
let r
|
|
42
|
+
try {
|
|
43
|
+
r = spawnSync(POWERSHELL, ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
44
|
+
stdio: ['ignore', fd, fd],
|
|
45
|
+
windowsHide: true,
|
|
46
|
+
timeout: QUERY_TIMEOUT_MS,
|
|
47
|
+
})
|
|
48
|
+
} catch {
|
|
49
|
+
return { status: -1, stdout: '' }
|
|
50
|
+
}
|
|
51
|
+
let out = ''
|
|
52
|
+
try { out = fs.readFileSync(file, 'utf8') } catch { /* 读不到就当空 */ }
|
|
53
|
+
return { status: r?.status ?? -1, stdout: out }
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 异步版:同样是文件重定向,避免管道与 stdout 缓冲问题。 */
|
|
58
|
+
export function runPowerShellAsync(script) {
|
|
59
|
+
return new Promise((resolve) => {
|
|
60
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-ident-'))
|
|
61
|
+
const file = path.join(dir, 'out.txt')
|
|
62
|
+
const cleanup = () => {
|
|
63
|
+
try { fs.rmSync(dir, { recursive: true, force: true }) } catch { /* 尽力清理 */ }
|
|
64
|
+
}
|
|
65
|
+
fs.writeFileSync(file, '')
|
|
66
|
+
let fd
|
|
67
|
+
try { fd = fs.openSync(file, 'a') } catch { cleanup(); resolve(undefined); return }
|
|
68
|
+
let child
|
|
69
|
+
try {
|
|
70
|
+
child = spawn(POWERSHELL, ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
71
|
+
stdio: ['ignore', fd, fd],
|
|
72
|
+
windowsHide: true,
|
|
73
|
+
})
|
|
74
|
+
} catch {
|
|
75
|
+
try { fs.closeSync(fd) } catch { /* 已关闭 */ }
|
|
76
|
+
cleanup()
|
|
77
|
+
resolve(undefined)
|
|
78
|
+
return
|
|
79
|
+
}
|
|
80
|
+
// 子进程持有自己的句柄副本,父进程这份可以立刻关掉。
|
|
81
|
+
try { fs.closeSync(fd) } catch { /* 已关闭 */ }
|
|
82
|
+
let settled = false
|
|
83
|
+
const finish = (value) => {
|
|
84
|
+
if (settled) return
|
|
85
|
+
settled = true
|
|
86
|
+
clearTimeout(timer)
|
|
87
|
+
cleanup()
|
|
88
|
+
resolve(value)
|
|
89
|
+
}
|
|
90
|
+
const timer = setTimeout(() => {
|
|
91
|
+
try { child.kill() } catch { /* 已退出 */ }
|
|
92
|
+
finish(undefined)
|
|
93
|
+
}, QUERY_TIMEOUT_MS)
|
|
94
|
+
child.on('error', () => finish(undefined))
|
|
95
|
+
child.on('close', (code) => {
|
|
96
|
+
if (code !== 0) { finish(undefined); return }
|
|
97
|
+
let out = ''
|
|
98
|
+
try { out = fs.readFileSync(file, 'utf8') } catch { /* 空输出 */ }
|
|
99
|
+
finish(out.trim())
|
|
100
|
+
})
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Retry only unavailable queries, never substitute a PID or a different marker.
|
|
105
|
+
// A successful but different identity is returned immediately to fail comparisons.
|
|
106
|
+
export function queryWindowsIdentity(script, validate, run = runPowerShellSync) {
|
|
107
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
108
|
+
try {
|
|
109
|
+
const r = run(script)
|
|
110
|
+
const value = typeof r?.stdout === 'string' ? r.stdout.trim() : ''
|
|
111
|
+
if (r?.status === 0 && validate(value)) return value
|
|
112
|
+
} catch { /* transient launch failure is not proof */ }
|
|
113
|
+
}
|
|
114
|
+
return null
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 同步跑一次 ps 查询(POSIX),返回 { status, stdout },永不抛。
|
|
119
|
+
* 与 PowerShell 版同口径走文件重定向:受限环境下管道可能被拒(EPERM),
|
|
120
|
+
* 身份查询失败会让 broker 拒绝启动所有服务,不能把环境限制放大成整体不可用。
|
|
121
|
+
* LC_ALL=C 钉死 lstart 的英文日期格式(否则本地化月份/星期会破坏校验与比对)。
|
|
122
|
+
*/
|
|
123
|
+
export function runPsSync(args) {
|
|
124
|
+
return withTempFile((file, fd) => {
|
|
125
|
+
let r
|
|
126
|
+
try {
|
|
127
|
+
r = spawnSync('ps', args, {
|
|
128
|
+
stdio: ['ignore', fd, fd],
|
|
129
|
+
timeout: QUERY_TIMEOUT_MS,
|
|
130
|
+
env: { ...process.env, LC_ALL: 'C' },
|
|
131
|
+
})
|
|
132
|
+
} catch {
|
|
133
|
+
return { status: -1, stdout: '' }
|
|
134
|
+
}
|
|
135
|
+
let out = ''
|
|
136
|
+
try { out = fs.readFileSync(file, 'utf8') } catch { /* 读不到就当空 */ }
|
|
137
|
+
return { status: r?.status ?? -1, stdout: out }
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** macOS 进程创建身份:ps lstart(秒级创建时间,C locale 固定格式)。
|
|
142
|
+
* pid + 创建时间足以区分 PID 复用;重启后 PID 归零但日期不同,跨重启天然失配。
|
|
143
|
+
* run 可注入以便单测(不依赖真实 ps)。 */
|
|
144
|
+
export function darwinMarker(pid, run = runPsSync) {
|
|
145
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return null
|
|
146
|
+
const v = queryWindowsIdentity(
|
|
147
|
+
['-o', 'lstart=', '-p', String(pid)],
|
|
148
|
+
value => /^[A-Za-z]{3} [A-Za-z]{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/.test(value),
|
|
149
|
+
run,
|
|
150
|
+
)
|
|
151
|
+
return v ? `darwin:${v}` : null
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function marker(pid) {
|
|
155
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return null
|
|
156
|
+
try {
|
|
157
|
+
if (process.platform === 'win32') {
|
|
158
|
+
const v = queryWindowsIdentity(`$p = Get-Process -Id ${pid} -ErrorAction Stop; $p.StartTime.ToUniversalTime().Ticks.ToString()`, value => /^\d+$/.test(value))
|
|
159
|
+
return v ? `win:${v}` : null
|
|
160
|
+
}
|
|
161
|
+
if (process.platform === 'linux') {
|
|
162
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')
|
|
163
|
+
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ')
|
|
164
|
+
const boot = fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim()
|
|
165
|
+
return fields[19] && boot ? `linux:${boot}:${fields[19]}` : null
|
|
166
|
+
}
|
|
167
|
+
if (process.platform === 'darwin') {
|
|
168
|
+
return darwinMarker(pid)
|
|
169
|
+
}
|
|
170
|
+
} catch {}
|
|
171
|
+
return null
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* 异步版 marker:Windows 上用异步 spawn 调 PowerShell,避免 spawnSync 阻塞事件循环。
|
|
175
|
+
* 返回格式与 marker() 完全一致,可与同步结果互相比对。
|
|
176
|
+
*
|
|
177
|
+
* 动机(2026-11-04 实测):marker() 在 Windows 单次约 900ms,且 spawnSync 阻塞
|
|
178
|
+
* 事件循环,导致 broker 并发拉起多个服务时完全串行化。异步版让多个身份查询并行。
|
|
179
|
+
*/
|
|
180
|
+
export async function markerAsync(pid) {
|
|
181
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return null
|
|
182
|
+
/* 死 pid 短路:进程已不在就不必白烧 3 次 PowerShell(实测死 pid 查询约 600ms)。
|
|
183
|
+
* absent 用 kill(pid,0),ESRCH=确死;EPERM(活着但无权限)仍走查询。 */
|
|
184
|
+
if (absent(pid)) return null
|
|
185
|
+
if (process.platform !== 'win32') return marker(pid)
|
|
186
|
+
const v = await queryWindowsIdentityAsync(
|
|
187
|
+
`$p = Get-Process -Id ${pid} -ErrorAction Stop; $p.StartTime.ToUniversalTime().Ticks.ToString()`,
|
|
188
|
+
(value) => /^\d+$/.test(value),
|
|
189
|
+
)
|
|
190
|
+
return v ? `win:${v}` : null
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 与 queryWindowsIdentity 同语义(最多 3 次重试),但用异步 spawn。 */
|
|
194
|
+
export async function queryWindowsIdentityAsync(script, validate, attemptLimit = 3) {
|
|
195
|
+
for (let attempt = 0; attempt < attemptLimit; attempt++) {
|
|
196
|
+
const value = await runPowerShellAsync(script)
|
|
197
|
+
if (value !== undefined && validate(value)) return value
|
|
198
|
+
}
|
|
199
|
+
return null
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function absent(pid) {
|
|
203
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false
|
|
204
|
+
try { process.kill(pid, 0); return false } catch (e) { return e.code === 'ESRCH' }
|
|
205
|
+
}
|
|
206
|
+
export function receiptDir(discovery) { return `${discovery}.ownership` }
|
|
207
|
+
export function receiptPath(discovery, id) {
|
|
208
|
+
if (typeof id !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/i.test(id)) throw new Error('invalid service id')
|
|
209
|
+
return path.join(receiptDir(discovery), `${id}.json`)
|
|
210
|
+
}
|
|
211
|
+
export function writeReceipt(discovery, id, value) {
|
|
212
|
+
const file = receiptPath(discovery, id)
|
|
213
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
214
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
|
|
215
|
+
fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600, flag: 'wx' })
|
|
216
|
+
fs.renameSync(tmp, file)
|
|
217
|
+
}
|
|
218
|
+
export function removeReceipt(discovery, id) {
|
|
219
|
+
try { fs.unlinkSync(receiptPath(discovery, id)) } catch (e) { if (e.code !== 'ENOENT') throw e }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function remainingReceipts(discovery) {
|
|
223
|
+
try { return fs.readdirSync(receiptDir(discovery)).map(name => `ownership:${name}:unresolved`) }
|
|
224
|
+
catch (e) { return e.code === 'ENOENT' ? ['ownership:missing'] : ['ownership:unreadable'] }
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function canConnect(port, timeoutMs = 800) {
|
|
228
|
+
return new Promise((resolve) => {
|
|
229
|
+
const socket = net.connect({ port, host: '127.0.0.1' })
|
|
230
|
+
const done = (ok) => { try { socket.destroy() } catch { /* 已销毁 */ } resolve(ok) }
|
|
231
|
+
socket.setTimeout(timeoutMs)
|
|
232
|
+
socket.once('connect', () => done(true))
|
|
233
|
+
socket.once('timeout', () => done(false))
|
|
234
|
+
socket.once('error', () => done(false))
|
|
235
|
+
})
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function portList(value) {
|
|
239
|
+
return Object.values(value || {}).filter((port) => Number.isSafeInteger(port) && port > 0)
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* A dead root alone cannot prove its descendants are gone, so a receipt is
|
|
244
|
+
* normally kept as evidence. The exception we can verify: the root is absent
|
|
245
|
+
* and none of the service's declared ports is listening. An orphan that no
|
|
246
|
+
* longer serves the declared port cannot be the service we were asked to run.
|
|
247
|
+
* Any listener on those ports keeps the receipt (fail closed).
|
|
248
|
+
*/
|
|
249
|
+
export async function receiptResolvable(receipt, ports) {
|
|
250
|
+
if (!receipt) return false
|
|
251
|
+
const list = portList(ports ?? receipt.ports)
|
|
252
|
+
if (!list.length) return false
|
|
253
|
+
/* 没有 pid 的收据只可能来自"写收据 → spawn 结果未知"的崩溃窗口。
|
|
254
|
+
* 这类收据永远不会自己变得可解析(旧实现直接 return false ⇒ 该服务
|
|
255
|
+
* 被永久挡住,每次启动都报「存在未解决的归属记录」)。判据只看端口:
|
|
256
|
+
* 声明的端口全部无人监听 ⇒ 上一代没留下任何东西,收据可以作废。 */
|
|
257
|
+
if (!Number.isSafeInteger(receipt.pid) || receipt.pid <= 0) {
|
|
258
|
+
for (const port of list) if (await canConnect(port)) return false
|
|
259
|
+
return true
|
|
260
|
+
}
|
|
261
|
+
if (!absent(receipt.pid)) return false
|
|
262
|
+
for (const port of list) if (await canConnect(port)) return false
|
|
263
|
+
return true
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Socket teardown can lag slightly behind process exit; give the OS a short,
|
|
267
|
+
// bounded window before declaring the port still owned by an unknown process.
|
|
268
|
+
export async function waitReceiptResolvable(receipt, ports, timeoutMs = 3000) {
|
|
269
|
+
const deadline = Date.now() + timeoutMs
|
|
270
|
+
for (;;) {
|
|
271
|
+
if (await receiptResolvable(receipt, ports)) return true
|
|
272
|
+
if (Date.now() >= deadline) return false
|
|
273
|
+
await new Promise((resolve) => setTimeout(resolve, 200))
|
|
274
|
+
}
|
|
275
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 技能瘦客户端:把独立技能服务的 HTTP 面适配成进程内形状(list/get)。
|
|
3
|
+
*
|
|
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)。
|
|
15
|
+
*/
|
|
16
|
+
export function createSkillsClient(baseUrl) {
|
|
17
|
+
const root = String(baseUrl || '').replace(/\/$/, '')
|
|
18
|
+
return {
|
|
19
|
+
api: { name: 'skillsHttp', version: '1.0.0', kind: 'thin-client' },
|
|
20
|
+
async list(signal) {
|
|
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
|
+
}
|
|
27
|
+
if (!res.ok) throw new Error(`skills list HTTP ${res.status}`)
|
|
28
|
+
const body = await res.json()
|
|
29
|
+
return Array.isArray(body?.skills) ? body.skills : []
|
|
30
|
+
},
|
|
31
|
+
async get(candidate, options = {}) {
|
|
32
|
+
const name = typeof candidate === 'string' ? candidate : candidate?.name
|
|
33
|
+
if (!name) throw new Error('skills get: 缺 name')
|
|
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},服务端错误)`)
|
|
45
|
+
return res.json()
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 服务 spec 校验:service.schema.json 的代码面。
|
|
3
|
+
*
|
|
4
|
+
* stack-services.json(dsh-stack-kit 编译)与 service-manifest.json
|
|
5
|
+
* (@capyclaw/suite-kit 物化)共用这一份 spec;本模块是装载期与跨包测试
|
|
6
|
+
* 共同调用的唯一校验器(结构级——语义由 engine/discovery 在运行期裁决)。
|
|
7
|
+
*/
|
|
8
|
+
const ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/
|
|
9
|
+
|
|
10
|
+
function checkPortValue(value, label, errors) {
|
|
11
|
+
if (value === undefined) return
|
|
12
|
+
if (value === 'auto') return
|
|
13
|
+
if (!Number.isInteger(value) || value <= 0 || value > 65535) {
|
|
14
|
+
errors.push(`${label} 必须是 1-65535 整数或 "auto"`)
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** 校验单个服务 spec;返回错误数组(空 = 通过)。 */
|
|
19
|
+
export function validateServiceSpec(service, at = 'service') {
|
|
20
|
+
const errors = []
|
|
21
|
+
if (!service || typeof service !== 'object' || Array.isArray(service)) {
|
|
22
|
+
return [`${at} 必须是对象`]
|
|
23
|
+
}
|
|
24
|
+
if (typeof service.id !== 'string' || !ID_RE.test(service.id)) {
|
|
25
|
+
errors.push(`${at}.id 必须是非空的服务标识(字母数字开头,可含 . _ -)`)
|
|
26
|
+
}
|
|
27
|
+
if (!Array.isArray(service.cmd) || service.cmd.length === 0 || service.cmd.some((item) => typeof item !== 'string')) {
|
|
28
|
+
errors.push(`${at}.cmd 必须是非空 string[](完整命令行)`)
|
|
29
|
+
}
|
|
30
|
+
if (service.ports !== undefined) {
|
|
31
|
+
if (typeof service.ports !== 'object' || service.ports === null || Array.isArray(service.ports)) {
|
|
32
|
+
errors.push(`${at}.ports 必须是对象(main 或具名端口)`)
|
|
33
|
+
} else {
|
|
34
|
+
for (const [name, value] of Object.entries(service.ports)) {
|
|
35
|
+
checkPortValue(value, `${at}.ports.${name}`, errors)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (service.env !== undefined && (typeof service.env !== 'object' || service.env === null
|
|
40
|
+
|| Array.isArray(service.env) || Object.values(service.env).some((value) => typeof value !== 'string'))) {
|
|
41
|
+
errors.push(`${at}.env 必须是 string -> string 对象`)
|
|
42
|
+
}
|
|
43
|
+
if (service.keepAlive !== undefined && typeof service.keepAlive !== 'boolean') {
|
|
44
|
+
errors.push(`${at}.keepAlive 必须是 boolean`)
|
|
45
|
+
}
|
|
46
|
+
if (service.healthPath !== undefined && typeof service.healthPath !== 'string') {
|
|
47
|
+
errors.push(`${at}.healthPath 必须是 string`)
|
|
48
|
+
}
|
|
49
|
+
if (service.url !== undefined && typeof service.url !== 'string') errors.push(`${at}.url 必须是 string`)
|
|
50
|
+
if (service.cwd !== undefined && typeof service.cwd !== 'string') errors.push(`${at}.cwd 必须是 string`)
|
|
51
|
+
if (service.logFile !== undefined && typeof service.logFile !== 'string') errors.push(`${at}.logFile 必须是 string`)
|
|
52
|
+
if (service.requires !== undefined && (!Array.isArray(service.requires)
|
|
53
|
+
|| service.requires.some((item) => typeof item !== 'string'))) {
|
|
54
|
+
errors.push(`${at}.requires 必须是 string[]`)
|
|
55
|
+
}
|
|
56
|
+
if (service.portFrom !== undefined && !['content', 'urlPort'].includes(service.portFrom)) {
|
|
57
|
+
errors.push(`${at}.portFrom 只允许 content | urlPort`)
|
|
58
|
+
}
|
|
59
|
+
if (service.dirFrom !== undefined && service.dirFrom !== 'contentState') {
|
|
60
|
+
errors.push(`${at}.dirFrom 只允许 contentState`)
|
|
61
|
+
}
|
|
62
|
+
return errors
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 校验整份清单(services 数组 + 同清单 id 唯一);返回错误数组(空 = 通过)。 */
|
|
66
|
+
export function validateServiceManifest(services, label = 'manifest') {
|
|
67
|
+
if (!Array.isArray(services)) return [`${label}: services 必须是数组`]
|
|
68
|
+
const errors = []
|
|
69
|
+
const seen = new Set()
|
|
70
|
+
services.forEach((service, index) => {
|
|
71
|
+
errors.push(...validateServiceSpec(service, `${label}[${index}]`))
|
|
72
|
+
if (service && typeof service === 'object' && typeof service.id === 'string') {
|
|
73
|
+
if (seen.has(service.id)) errors.push(`${label}: 重复的服务 id ${service.id}`)
|
|
74
|
+
seen.add(service.id)
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
return errors
|
|
78
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@capyclaw/service-broker",
|
|
3
|
+
"version": "0.2.27",
|
|
4
|
+
"description": "DSH 服务中间件(唯一进程内插件):按清单/结构化命令把各服务作为独立进程拉起,负责守护、发现(discovery)、控制端点;服务与服务之间不互相带动,跨端口组织一律经过这里。",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./lib/host.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./lib/host.mjs",
|
|
9
|
+
"./engine": "./lib/engine.mjs",
|
|
10
|
+
"./manifest": "./lib/manifest.mjs",
|
|
11
|
+
"./spec": "./lib/spec.mjs",
|
|
12
|
+
"./schema": "./service.schema.json",
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18",
|
|
17
|
+
"dsh": "^0.2.0-rc.2"
|
|
18
|
+
},
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"dsh": {
|
|
23
|
+
"bundle": {
|
|
24
|
+
"patch": "./cordis.patch.yml"
|
|
25
|
+
},
|
|
26
|
+
"suite": "./dsh-suite.json",
|
|
27
|
+
"apiVersion": "1.0.0",
|
|
28
|
+
"category": "service",
|
|
29
|
+
"platform": "both",
|
|
30
|
+
"driver": {
|
|
31
|
+
"service": "serviceBroker"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"meta": {
|
|
35
|
+
"title": "服务中间件",
|
|
36
|
+
"description": "按清单把各服务作为独立进程拉起,守护、发现与控制端点;服务之间不互相带动"
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"lib/",
|
|
40
|
+
"server.mjs",
|
|
41
|
+
"services.json",
|
|
42
|
+
"service.schema.json",
|
|
43
|
+
"cordis.patch.yml",
|
|
44
|
+
"dsh-suite.json",
|
|
45
|
+
"README.md"
|
|
46
|
+
],
|
|
47
|
+
"license": "MIT",
|
|
48
|
+
"scripts": {
|
|
49
|
+
"test": "node --test \"test/*.test.mjs\""
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"@capyclaw/plugin-kit": "^0.2.0",
|
|
53
|
+
"@capyclaw/foundation": "^0.1.1",
|
|
54
|
+
"@capyclaw/portal": "^0.1.11"
|
|
55
|
+
},
|
|
56
|
+
"repository": {
|
|
57
|
+
"type": "git",
|
|
58
|
+
"url": "git+https://github.com/Maple496/capyclaw.git",
|
|
59
|
+
"directory": "C/packages/capyclaw-service-broker"
|
|
60
|
+
},
|
|
61
|
+
"bugs": {
|
|
62
|
+
"url": "https://github.com/Maple496/capyclaw/issues"
|
|
63
|
+
},
|
|
64
|
+
"homepage": "https://github.com/Maple496/capyclaw/tree/main/C/packages/capyclaw-service-broker#readme"
|
|
65
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* @capyclaw/service-broker standalone 入口:中间件以独立端口服务运行。
|
|
4
|
+
*
|
|
5
|
+
* 这是桌面/外部场景的主形态:启动清单(作品/后端)不直接拉服务,
|
|
6
|
+
* 而是把结构化命令 POST 到这里的 /control/apply,由中间件统一执行。
|
|
7
|
+
*
|
|
8
|
+
* 用法:
|
|
9
|
+
* node server.mjs [--port 39610] [--manifest services.json]
|
|
10
|
+
* [--discovery ~/.dsh/services.json] [--stop-on-exit]
|
|
11
|
+
*
|
|
12
|
+
* 环境变量:DSH_BROKER_TOKEN(设置后 /control/* 需带 x-broker-token)。
|
|
13
|
+
*/
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import { mkdirSync } from 'node:fs'
|
|
16
|
+
import { receiptDir } from './lib/recovery.mjs'
|
|
17
|
+
import { fileURLToPath } from 'node:url'
|
|
18
|
+
import { ServiceEngine } from './lib/engine.mjs'
|
|
19
|
+
import { createControlServer } from './lib/control.mjs'
|
|
20
|
+
import { loadManifest } from './lib/manifest.mjs'
|
|
21
|
+
|
|
22
|
+
function arg(name, dflt) {
|
|
23
|
+
const i = process.argv.indexOf(name)
|
|
24
|
+
return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : dflt
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
28
|
+
const port = Number(arg('--port', process.env.DSH_BROKER_PORT || 39610))
|
|
29
|
+
const manifestPath = arg('--manifest', undefined)
|
|
30
|
+
const discoveryPath = arg('--discovery', undefined)
|
|
31
|
+
const stopOnExit = process.argv.includes('--stop-on-exit')
|
|
32
|
+
|
|
33
|
+
const engine = new ServiceEngine({
|
|
34
|
+
discoveryPath,
|
|
35
|
+
log: (msg) => console.log(`${new Date().toISOString().slice(11, 19)} ${msg}`),
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
// Existence distinguishes a broker with receipt support from a legacy broker.
|
|
39
|
+
mkdirSync(receiptDir(engine.discoveryPath), { recursive: true })
|
|
40
|
+
|
|
41
|
+
// 开机清单:幂等(复用优先),失败不阻断中间件自身启动
|
|
42
|
+
try {
|
|
43
|
+
const services = loadManifest(manifestPath)
|
|
44
|
+
if (services.length) {
|
|
45
|
+
const result = await engine.apply(services.map((service) => ({ op: 'up', service })))
|
|
46
|
+
for (const err of result.errors) console.warn(`✗ ${err.id}: ${err.error}`)
|
|
47
|
+
console.log(`开机清单完成:${result.services.length} 个服务就绪`)
|
|
48
|
+
} else {
|
|
49
|
+
console.log('开机清单为空,待命(等待 /control/apply 投递)')
|
|
50
|
+
}
|
|
51
|
+
} catch (err) {
|
|
52
|
+
console.warn(`开机清单失败: ${err.message}`)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
engine.startGuard()
|
|
56
|
+
const server = createControlServer(engine, { token: process.env.DSH_BROKER_TOKEN, manifestPath })
|
|
57
|
+
/* 控制面是 standalone 的本体:监听失败(端口冲突等)不能僵死,明确报错退出(P1-6)。 */
|
|
58
|
+
server.on('error', (err) => {
|
|
59
|
+
console.error(`dsh-service-broker 控制面监听失败(${err.code || err.message}):端口 ${port} 不可用,退出。请改 --port 或先释放该端口。`)
|
|
60
|
+
process.exit(1)
|
|
61
|
+
})
|
|
62
|
+
server.listen(port, '127.0.0.1', () => {
|
|
63
|
+
console.log(`dsh-service-broker 就绪: http://127.0.0.1:${port}/control/*`)
|
|
64
|
+
console.log(`discovery: ${engine.discoveryPath}`)
|
|
65
|
+
console.log(server.brokerTokenFile
|
|
66
|
+
? `控制面鉴权: 需要 x-broker-token,token 见 ${server.brokerTokenFile}`
|
|
67
|
+
: '控制面鉴权: 需要 x-broker-token(来自环境变量)')
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
let exiting = false
|
|
71
|
+
async function shutdown() {
|
|
72
|
+
if (exiting) return
|
|
73
|
+
exiting = true
|
|
74
|
+
console.log('中间件停机…')
|
|
75
|
+
await new Promise((resolve) => server.close(resolve))
|
|
76
|
+
await engine.shutdown({ stopAll: stopOnExit })
|
|
77
|
+
process.exit(0)
|
|
78
|
+
}
|
|
79
|
+
process.on('SIGINT', shutdown)
|
|
80
|
+
process.on('SIGTERM', shutdown)
|
|
81
|
+
process.on('break', shutdown)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
|
+
"$id": "https://dsh.local/schemas/service.schema.json",
|
|
4
|
+
"title": "DSH Broker 服务清单(唯一服务 spec)",
|
|
5
|
+
"description": "stack-services.json(dsh-stack-kit 编译)与 service-manifest.json(@capyclaw/suite-kit 物化)是同一 spec 的两个 runtime 工件;本 schema 是二者共同的契约。${PACKAGE_DIR}/${PORT}/${PORT_<NAME>} 占位符由装载/仲裁层展开。",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"required": ["services"],
|
|
8
|
+
"properties": {
|
|
9
|
+
"services": { "type": "array", "items": { "$ref": "#/$defs/service" } }
|
|
10
|
+
},
|
|
11
|
+
"$defs": {
|
|
12
|
+
"port": {
|
|
13
|
+
"anyOf": [
|
|
14
|
+
{ "type": "integer", "minimum": 1, "maximum": 65535 },
|
|
15
|
+
{ "type": "string", "enum": ["auto"] }
|
|
16
|
+
]
|
|
17
|
+
},
|
|
18
|
+
"service": {
|
|
19
|
+
"type": "object",
|
|
20
|
+
"required": ["id", "cmd"],
|
|
21
|
+
"additionalProperties": true,
|
|
22
|
+
"properties": {
|
|
23
|
+
"id": { "type": "string", "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._-]*$", "description": "服务 id(同清单内唯一)" },
|
|
24
|
+
"cmd": { "type": "array", "items": { "type": "string" }, "minItems": 1, "description": "完整命令行(占位符原样保留,broker 展开分配)" },
|
|
25
|
+
"ports": {
|
|
26
|
+
"type": "object",
|
|
27
|
+
"additionalProperties": { "$ref": "#/$defs/port" },
|
|
28
|
+
"description": "main 为主端口;具名端口映射 PORT_<NAME>"
|
|
29
|
+
},
|
|
30
|
+
"url": { "type": "string", "description": "服务入口 URL 模板" },
|
|
31
|
+
"healthPath": { "type": "string", "description": "健康探测路径(默认 /healthz)" },
|
|
32
|
+
"keepAlive": { "type": "boolean", "description": "进程死亡后由 broker 原端口复活" },
|
|
33
|
+
"env": { "type": "object", "additionalProperties": { "type": "string" } },
|
|
34
|
+
"cwd": { "type": "string" },
|
|
35
|
+
"requires": { "type": "array", "items": { "type": "string" }, "description": "同清单内依赖的服务 id" },
|
|
36
|
+
"logFile": { "type": "string" },
|
|
37
|
+
"portFrom": { "type": "string", "enum": ["content", "urlPort"], "description": "suite 物化期提示:主端口取 runtime content/urlPort(物化后删除)" },
|
|
38
|
+
"dirFrom": { "type": "string", "enum": ["contentState"], "description": "suite 物化期提示:--dir 参数指向 runtime contentState(物化后删除)" },
|
|
39
|
+
"window": {
|
|
40
|
+
"description": "声明式弹窗:服务就绪那一刻由基建(@capyclaw/portal)把 url 开成置顶小窗;业务插件不写窗口代码。省略或 false = 不弹。",
|
|
41
|
+
"oneOf": [
|
|
42
|
+
{ "type": "boolean", "enum": [false] },
|
|
43
|
+
{
|
|
44
|
+
"type": "object",
|
|
45
|
+
"additionalProperties": true,
|
|
46
|
+
"properties": {
|
|
47
|
+
"title": { "type": "string", "description": "窗口标题(默认「工作台」)" },
|
|
48
|
+
"width": { "type": "number", "description": "宽(DIP,默认 820)" },
|
|
49
|
+
"height": { "type": "number", "description": "高(DIP,默认 940)" },
|
|
50
|
+
"anchor": { "type": "string", "enum": ["left", "right", "center"], "description": "贴边位置(默认 right)" },
|
|
51
|
+
"margin": { "type": "number", "description": "贴边留白(DIP,默认 24)" },
|
|
52
|
+
"topmost": { "type": "boolean", "description": "置顶(默认 true)" },
|
|
53
|
+
"frameless": { "type": "boolean", "description": "拆原生边框(默认 false)" },
|
|
54
|
+
"path": { "type": "string", "description": "开窗落在服务下的哪个路径(默认 /)" }
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
]
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|