@capyclaw/skills-service 0.1.3 → 0.2.2
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/README.md +7 -7
- 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/package.json +18 -2
- package/server.mjs +237 -201
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI 脚手架(纯函数,无副作用)。
|
|
3
|
+
*
|
|
4
|
+
* 全仓 8+ 个 bin 脚本各自手写参数解析/导入守卫/失败退出——这里收敛为一套:
|
|
5
|
+
* 新的 bin 只需要写「命令表 + 用法文本 + 业务逻辑」,解析与守卫交给本模块。
|
|
6
|
+
*
|
|
7
|
+
* import { parseArgs, isMain, fail } from '@capyclaw/plugin-kit'
|
|
8
|
+
*
|
|
9
|
+
* const commands = { async do(arg, flags) { … } }
|
|
10
|
+
* if (isMain(import.meta.url)) { … dispatch & print usage … }
|
|
11
|
+
*/
|
|
12
|
+
import { resolve } from 'node:path'
|
|
13
|
+
import { pathToFileURL } from 'node:url'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 解析命令行:位置参数与 `--flag`/`--flag value` 混排。
|
|
17
|
+
* @param {string[]} argv - 不含 node 与脚本路径的原始参数
|
|
18
|
+
* @returns {{ positional: string[], flags: Record<string, string|boolean> }}
|
|
19
|
+
* `--flag value` → 字符串;`--flag`(后随缺失或另一个 -- 项)→ true;`--flag=x` → 字符串
|
|
20
|
+
*/
|
|
21
|
+
export function parseArgs(argv) {
|
|
22
|
+
const positional = []
|
|
23
|
+
const flags = {}
|
|
24
|
+
for (let i = 0; i < argv.length; i++) {
|
|
25
|
+
const arg = argv[i]
|
|
26
|
+
if (arg.startsWith('--')) {
|
|
27
|
+
const eq = arg.indexOf('=')
|
|
28
|
+
if (eq > 2) {
|
|
29
|
+
flags[arg.slice(2, eq)] = arg.slice(eq + 1)
|
|
30
|
+
continue
|
|
31
|
+
}
|
|
32
|
+
const key = arg.slice(2)
|
|
33
|
+
const next = argv[i + 1]
|
|
34
|
+
if (next !== undefined && !next.startsWith('--')) { flags[key] = next; i++ }
|
|
35
|
+
else flags[key] = true
|
|
36
|
+
} else {
|
|
37
|
+
positional.push(arg)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { positional, flags }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 导入守卫:仅当本模块被直接执行(而非被测试/其他模块 import)时为 true。
|
|
45
|
+
* @param {string} importMetaUrl - 调用方的 import.meta.url
|
|
46
|
+
*/
|
|
47
|
+
export function isMain(importMetaUrl, argv = process.argv) {
|
|
48
|
+
const entry = argv[1] ? pathToFileURL(resolve(argv[1])).href : ''
|
|
49
|
+
return importMetaUrl === entry
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 统一失败出口:打印 ✗ 后以非零码退出。 */
|
|
53
|
+
export function fail(message) {
|
|
54
|
+
console.error(`✗ ${message}`)
|
|
55
|
+
process.exit(1)
|
|
56
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 插件配置解析(统一入口)。
|
|
3
|
+
*
|
|
4
|
+
* 目的:让插件不把端口/URL/路径写死在代码或 cordis.patch.yml 里,
|
|
5
|
+
* 而是遵循一条可预测的优先级链:
|
|
6
|
+
*
|
|
7
|
+
* ctx config(由 stack / profile patch 注入的运行时配置)
|
|
8
|
+
* → 环境变量(逐字段,如 DSH_LAUNCHPAD_PORT)
|
|
9
|
+
* → defaults(安全默认值)
|
|
10
|
+
*
|
|
11
|
+
* 所有取值都带上来源,便于 doctor / 日志说明「这个值是哪来的」。
|
|
12
|
+
*
|
|
13
|
+
* 用法:
|
|
14
|
+
* import { resolveConfig } from '@capyclaw/plugin-kit/config'
|
|
15
|
+
*
|
|
16
|
+
* export function apply(ctx, config = {}) {
|
|
17
|
+
* const cfg = resolveConfig(config, {
|
|
18
|
+
* envPrefix: 'DSH_PPT',
|
|
19
|
+
* 不写端口默认值:端口由基建的 runtime.json / env 注入(见 INTEGRATION.md)。
|
|
20
|
+
* defaults: { host: '127.0.0.1' },
|
|
21
|
+
* fields: {
|
|
22
|
+
* port: { env: 'PORT', type: 'port' },
|
|
23
|
+
* host: { env: 'HOST' },
|
|
24
|
+
* backendUrl: { env: 'BACKEND_URL', type: 'url' },
|
|
25
|
+
* },
|
|
26
|
+
* })
|
|
27
|
+
* cfg.value.port // 解析后的值
|
|
28
|
+
* cfg.source.port // 'config' | 'env:DSH_PPT_PORT' | 'default'
|
|
29
|
+
* }
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
const TYPE_CHECKS = {
|
|
33
|
+
port(value) {
|
|
34
|
+
const n = Number(value)
|
|
35
|
+
return Number.isInteger(n) && n > 0 && n < 65536 ? n : null
|
|
36
|
+
},
|
|
37
|
+
number(value) {
|
|
38
|
+
const n = Number(value)
|
|
39
|
+
return Number.isFinite(n) ? n : null
|
|
40
|
+
},
|
|
41
|
+
boolean(value) {
|
|
42
|
+
if (typeof value === 'boolean') return value
|
|
43
|
+
const s = String(value).trim().toLowerCase()
|
|
44
|
+
if (['1', 'true', 'yes', 'on'].includes(s)) return true
|
|
45
|
+
if (['0', 'false', 'no', 'off'].includes(s)) return false
|
|
46
|
+
return null
|
|
47
|
+
},
|
|
48
|
+
url(value) {
|
|
49
|
+
const s = String(value).trim()
|
|
50
|
+
try {
|
|
51
|
+
const u = new URL(s)
|
|
52
|
+
return u.protocol === 'http:' || u.protocol === 'https:' ? s : null
|
|
53
|
+
} catch {
|
|
54
|
+
return null
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
string(value) {
|
|
58
|
+
const s = String(value)
|
|
59
|
+
return s.length ? s : null
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function coerce(raw, type) {
|
|
64
|
+
if (raw === undefined || raw === null || raw === '') return { ok: false }
|
|
65
|
+
const check = TYPE_CHECKS[type] || TYPE_CHECKS.string
|
|
66
|
+
const value = check(raw)
|
|
67
|
+
return value === null ? { ok: false } : { ok: true, value }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param {object} config dsh 传给 apply() 的 config(来自 cordis.patch.yml / stack configs)
|
|
72
|
+
* @param {object} options
|
|
73
|
+
* @param {string} [options.envPrefix] 环境变量前缀,如 'DSH_PPT'
|
|
74
|
+
* @param {object} [options.defaults] 默认值表
|
|
75
|
+
* @param {object} [options.fields] { 字段名: { env?: string, type?: 'port'|'number'|'boolean'|'url'|'string' } }
|
|
76
|
+
* @param {(msg:string)=>void} [options.onInvalid] 无效值回调(默认收集到 issues)
|
|
77
|
+
* @returns {{ value: object, source: object, issues: string[] }}
|
|
78
|
+
*/
|
|
79
|
+
export function resolveConfig(config = {}, options = {}) {
|
|
80
|
+
const { envPrefix = '', defaults = {}, fields = {}, env = process.env } = options
|
|
81
|
+
const value = {}
|
|
82
|
+
const source = {}
|
|
83
|
+
const issues = []
|
|
84
|
+
|
|
85
|
+
const keys = new Set([...Object.keys(defaults), ...Object.keys(fields)])
|
|
86
|
+
|
|
87
|
+
for (const key of keys) {
|
|
88
|
+
const field = fields[key] || {}
|
|
89
|
+
const type = field.type || inferType(defaults[key])
|
|
90
|
+
const envName = field.env
|
|
91
|
+
? (envPrefix ? `${envPrefix}_${field.env}` : field.env)
|
|
92
|
+
: (envPrefix ? `${envPrefix}_${key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()}` : '')
|
|
93
|
+
|
|
94
|
+
// 1) ctx config
|
|
95
|
+
const fromConfig = coerce(config?.[key], type)
|
|
96
|
+
if (fromConfig.ok) {
|
|
97
|
+
value[key] = fromConfig.value
|
|
98
|
+
source[key] = 'config'
|
|
99
|
+
continue
|
|
100
|
+
}
|
|
101
|
+
if (config?.[key] !== undefined && config?.[key] !== null && config?.[key] !== '') {
|
|
102
|
+
issues.push(`${key}: config 值无效(期望 ${type}): ${JSON.stringify(config[key])},已降级到下一来源`)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// 2) 环境变量
|
|
106
|
+
if (envName && env?.[envName] !== undefined) {
|
|
107
|
+
const fromEnv = coerce(env[envName], type)
|
|
108
|
+
if (fromEnv.ok) {
|
|
109
|
+
value[key] = fromEnv.value
|
|
110
|
+
source[key] = `env:${envName}`
|
|
111
|
+
continue
|
|
112
|
+
}
|
|
113
|
+
issues.push(`${key}: 环境变量 ${envName} 值无效(期望 ${type}): ${JSON.stringify(env[envName])},已降级到默认值`)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// 3) 默认值
|
|
117
|
+
if (defaults[key] !== undefined) {
|
|
118
|
+
value[key] = defaults[key]
|
|
119
|
+
source[key] = 'default'
|
|
120
|
+
continue
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// 无默认值且没解析到 → 不写入,交给调用方判断是否必填
|
|
124
|
+
source[key] = 'unset'
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return { value, source, issues }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function inferType(sample) {
|
|
131
|
+
if (typeof sample === 'boolean') return 'boolean'
|
|
132
|
+
if (typeof sample === 'number') return 'number'
|
|
133
|
+
if (typeof sample === 'string' && /^https?:\/\//.test(sample)) return 'url'
|
|
134
|
+
return 'string'
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 便于在 apply() 里打一条可读的配置来源日志。 */
|
|
138
|
+
export function describeConfig({ value, source }) {
|
|
139
|
+
return Object.entries(value)
|
|
140
|
+
.map(([k, v]) => `${k}=${JSON.stringify(v)} (${source[k] || 'unknown'})`)
|
|
141
|
+
.join(', ')
|
|
142
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/* Web Worker:独立线程保持心跳,不受浏览器标签页节流影响
|
|
2
|
+
*
|
|
3
|
+
* 设计原则:
|
|
4
|
+
* 1. 健壮降级:任何失败都通知主线程,主线程决定是否降级
|
|
5
|
+
* 2. 自我监控:内置健康检查,连续失败自动报告
|
|
6
|
+
* 3. 优雅退出:stop 后立即停止,不留残留定时器
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
let active = false;
|
|
10
|
+
let clientId = null;
|
|
11
|
+
let apiBase = null;
|
|
12
|
+
let intervalHandle = null;
|
|
13
|
+
let consecutiveFailures = 0;
|
|
14
|
+
const MAX_FAILURES = 3; // 连续失败 3 次后通知主线程降级
|
|
15
|
+
|
|
16
|
+
self.onmessage = function(e) {
|
|
17
|
+
const { type, data } = e.data;
|
|
18
|
+
|
|
19
|
+
if (type === 'start') {
|
|
20
|
+
active = true;
|
|
21
|
+
clientId = data.clientId;
|
|
22
|
+
apiBase = data.apiBase;
|
|
23
|
+
consecutiveFailures = 0;
|
|
24
|
+
startHeartbeat();
|
|
25
|
+
self.postMessage({ type: 'started', clientId });
|
|
26
|
+
} else if (type === 'stop') {
|
|
27
|
+
active = false;
|
|
28
|
+
if (intervalHandle) {
|
|
29
|
+
clearInterval(intervalHandle);
|
|
30
|
+
intervalHandle = null;
|
|
31
|
+
}
|
|
32
|
+
self.postMessage({ type: 'stopped' });
|
|
33
|
+
} else if (type === 'ping') {
|
|
34
|
+
// 主线程健康检查:返回当前状态
|
|
35
|
+
self.postMessage({
|
|
36
|
+
type: 'pong',
|
|
37
|
+
active,
|
|
38
|
+
clientId,
|
|
39
|
+
consecutiveFailures,
|
|
40
|
+
timestamp: Date.now()
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function startHeartbeat() {
|
|
46
|
+
if (intervalHandle) clearInterval(intervalHandle);
|
|
47
|
+
|
|
48
|
+
// 每 4 秒发送心跳(留 1 秒缓冲,避免刚好 5 秒时被判过期)
|
|
49
|
+
intervalHandle = setInterval(() => {
|
|
50
|
+
if (!active) return;
|
|
51
|
+
|
|
52
|
+
sendClaim().catch(err => {
|
|
53
|
+
consecutiveFailures++;
|
|
54
|
+
self.postMessage({
|
|
55
|
+
type: 'error',
|
|
56
|
+
message: err.message,
|
|
57
|
+
consecutiveFailures,
|
|
58
|
+
fatal: consecutiveFailures >= MAX_FAILURES
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// 连续失败达到阈值,建议主线程降级
|
|
62
|
+
if (consecutiveFailures >= MAX_FAILURES) {
|
|
63
|
+
self.postMessage({
|
|
64
|
+
type: 'fatal',
|
|
65
|
+
message: `连续 ${MAX_FAILURES} 次心跳失败,建议降级到主线程`
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}, 4000);
|
|
70
|
+
|
|
71
|
+
// 立即发送第一次
|
|
72
|
+
sendClaim().catch(() => {});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function sendClaim() {
|
|
76
|
+
if (!apiBase || !clientId) {
|
|
77
|
+
throw new Error('Worker 未初始化:缺少 apiBase 或 clientId');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const url = `${apiBase}/claim`;
|
|
81
|
+
const controller = new AbortController();
|
|
82
|
+
const timeoutId = setTimeout(() => controller.abort(), 8000); // 8 秒超时
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
const response = await fetch(url, {
|
|
86
|
+
method: 'POST',
|
|
87
|
+
headers: { 'content-type': 'application/json' },
|
|
88
|
+
body: JSON.stringify({ id: clientId }),
|
|
89
|
+
signal: controller.signal,
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
clearTimeout(timeoutId);
|
|
93
|
+
|
|
94
|
+
if (!response.ok) {
|
|
95
|
+
throw new Error(`HTTP ${response.status}`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const data = await response.json();
|
|
99
|
+
|
|
100
|
+
/* HTTP 200 但 ok:false = 租约已被其他窗口抢走(claim 被拒)。
|
|
101
|
+
* 不能当成功:停止心跳并通知主线程回到待命,否则被抢占的窗口会一直
|
|
102
|
+
* 以为自己还是 owner,继续写共享画面。 */
|
|
103
|
+
if (data && data.ok === false) {
|
|
104
|
+
active = false;
|
|
105
|
+
if (intervalHandle) {
|
|
106
|
+
clearInterval(intervalHandle);
|
|
107
|
+
intervalHandle = null;
|
|
108
|
+
}
|
|
109
|
+
self.postMessage({ type: 'lost', owner: data.owner, epoch: data.epoch });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// 成功:重置失败计数
|
|
114
|
+
if (consecutiveFailures > 0) {
|
|
115
|
+
consecutiveFailures = 0;
|
|
116
|
+
self.postMessage({ type: 'recovered' }); // 通知主线程已恢复
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
self.postMessage({
|
|
120
|
+
type: 'heartbeat',
|
|
121
|
+
timestamp: Date.now(),
|
|
122
|
+
response: data,
|
|
123
|
+
consecutiveFailures: 0
|
|
124
|
+
});
|
|
125
|
+
} catch (err) {
|
|
126
|
+
clearTimeout(timeoutId);
|
|
127
|
+
throw err;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「显示即连接」编辑器租约标准模块。
|
|
3
|
+
*
|
|
4
|
+
* 活动权(claim)只存在于内部仲裁;不要把它渲染成 UI 状态。
|
|
5
|
+
* 新打开的窗口强制抢占,旧窗口静默转入待命。
|
|
6
|
+
*/
|
|
7
|
+
import { tuning } from '../tuning.mjs'
|
|
8
|
+
|
|
9
|
+
const DEFAULT_TTL = 15 // 秒
|
|
10
|
+
const DEFAULT_HEARTBEAT = 3 // 秒(心跳间隔应小于 TTL)
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 创建编辑器租约仲裁器。
|
|
14
|
+
* @param {{ ttl?: number }} [opts]
|
|
15
|
+
*/
|
|
16
|
+
export function createEditorLease(opts = {}) {
|
|
17
|
+
const ttl = Number(opts.ttl) || DEFAULT_TTL
|
|
18
|
+
let owner = null // { id, ts }
|
|
19
|
+
|
|
20
|
+
return {
|
|
21
|
+
claim(id, force = false) {
|
|
22
|
+
const now = Date.now() / 1000
|
|
23
|
+
if (force || !owner || owner.id === id || now - owner.ts > ttl) {
|
|
24
|
+
owner = { id, ts: now }
|
|
25
|
+
return { ok: true, owner: id }
|
|
26
|
+
}
|
|
27
|
+
return { ok: false, owner: owner.id }
|
|
28
|
+
},
|
|
29
|
+
|
|
30
|
+
release(id) {
|
|
31
|
+
if (owner && owner.id === id) owner = null
|
|
32
|
+
return { ok: true }
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
isLive() {
|
|
36
|
+
return !!owner && Date.now() / 1000 - owner.ts <= ttl
|
|
37
|
+
},
|
|
38
|
+
|
|
39
|
+
status() {
|
|
40
|
+
return owner
|
|
41
|
+
? { owner: owner.id, age: Math.round((Date.now() / 1000 - owner.ts) * 100) / 100 }
|
|
42
|
+
: null
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
async wait(o = {}) {
|
|
46
|
+
const { leaseWaitPollMs: pollMs, leaseWaitTimeoutMs: defaultTimeoutMs } = tuning()
|
|
47
|
+
const deadline = Date.now() + (o.timeoutMs || defaultTimeoutMs)
|
|
48
|
+
while (true) {
|
|
49
|
+
if (this.isLive()) return this.status()
|
|
50
|
+
if (Date.now() >= deadline) {
|
|
51
|
+
const hint = o.openHint ? `(打开 ${o.openHint})` : ''
|
|
52
|
+
const panel = o.panelHint || '编辑器面板'
|
|
53
|
+
throw new Error(`${panel}尚未连接${hint}。页面加载后会自动连接,无需其他操作。`)
|
|
54
|
+
}
|
|
55
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs))
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 编辑器端自动挂接循环。
|
|
63
|
+
* 首次 claim 强制抢占(后打开者赢),之后静默心跳。
|
|
64
|
+
* @param {{
|
|
65
|
+
* clientId: string,
|
|
66
|
+
* claim: (force: boolean) => Promise<boolean>,
|
|
67
|
+
* release?: () => void,
|
|
68
|
+
* onActive?: () => void,
|
|
69
|
+
* onStandby?: () => void,
|
|
70
|
+
* retryMs?: number,
|
|
71
|
+
* heartbeatMs?: number,
|
|
72
|
+
* setInterval?: (cb: () => void) => any,
|
|
73
|
+
* clearInterval?: (handle: any) => void
|
|
74
|
+
* }} o
|
|
75
|
+
*/
|
|
76
|
+
export function startAutoAttach(o) {
|
|
77
|
+
if (!o || !o.clientId) throw new Error('startAutoAttach: clientId 必填')
|
|
78
|
+
if (typeof o.claim !== 'function') throw new Error('startAutoAttach: claim 必须是函数')
|
|
79
|
+
|
|
80
|
+
const retryMs = o.retryMs || 1000
|
|
81
|
+
const heartbeatMs = o.heartbeatMs || DEFAULT_HEARTBEAT * 1000
|
|
82
|
+
const setI = o.setInterval || ((cb) => setInterval(cb, heartbeatMs))
|
|
83
|
+
const clearI = o.clearInterval || ((handle) => clearInterval(handle))
|
|
84
|
+
|
|
85
|
+
let active = false
|
|
86
|
+
let heartbeat = null
|
|
87
|
+
let disposed = false
|
|
88
|
+
|
|
89
|
+
async function tryClaim(force) {
|
|
90
|
+
try {
|
|
91
|
+
return await o.claim(force)
|
|
92
|
+
} catch {
|
|
93
|
+
return false
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function goActive() {
|
|
98
|
+
if (active) return
|
|
99
|
+
active = true
|
|
100
|
+
try { o.onActive && o.onActive() } catch { /* 用户回调失败不阻塞挂接 */ }
|
|
101
|
+
heartbeat = setI(async () => {
|
|
102
|
+
if (disposed) return
|
|
103
|
+
const ok = await tryClaim(false)
|
|
104
|
+
if (!ok) goStandby()
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function goStandby() {
|
|
109
|
+
if (!active) return
|
|
110
|
+
active = false
|
|
111
|
+
if (heartbeat != null) {
|
|
112
|
+
clearI(heartbeat)
|
|
113
|
+
heartbeat = null
|
|
114
|
+
}
|
|
115
|
+
try { o.onStandby && o.onStandby() } catch { /* 静默 */ }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
;(async () => {
|
|
119
|
+
let first = true
|
|
120
|
+
while (!disposed) {
|
|
121
|
+
const ok = await tryClaim(first)
|
|
122
|
+
first = false
|
|
123
|
+
if (ok) {
|
|
124
|
+
goActive()
|
|
125
|
+
return
|
|
126
|
+
}
|
|
127
|
+
await new Promise((resolve) => setTimeout(resolve, retryMs))
|
|
128
|
+
}
|
|
129
|
+
})()
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
get active() { return active },
|
|
133
|
+
dispose() {
|
|
134
|
+
disposed = true
|
|
135
|
+
goStandby()
|
|
136
|
+
try { o.release && o.release() } catch { /* 释放失败不阻塞退出 */ }
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 影子显示器(shadow display)——平台级「保证有显示器」的兜底责任方。
|
|
3
|
+
*
|
|
4
|
+
* 背景:这套基建的实时像素/截图依赖一个连着租约心跳的编辑器页面("显示即连接")。
|
|
5
|
+
* 真实用户窗口由 GUI 自动挂载;但窗口被关掉、或纯 headless 场景下就没有显示器,
|
|
6
|
+
* editorConnected 永远 false,工具静默退离线渲染——用户被迫手动开窗/刷新。
|
|
7
|
+
*
|
|
8
|
+
* 影子显示器把这件事接管过来:服务端在「有稿件但没有真实窗口」时,自动拉起一个
|
|
9
|
+
* 无头 Chromium 页加载编辑器(?shadow=1),以**礼貌 claim(force=false)**持租约、
|
|
10
|
+
* 渲染真像素。真实用户窗口到来时 force 抢占,影子经 worker 'lost' 让位并被关停;
|
|
11
|
+
* 用户离开后影子再自动补位。用户全程无感。
|
|
12
|
+
*
|
|
13
|
+
* 设计约束(生产级稳定):
|
|
14
|
+
* - **fail-safe**:解析不到 playwright-core 或 Chromium 可执行文件 → 永久禁用并
|
|
15
|
+
* 只记一条日志,reconcile 变 no-op;工具退回离线渲染(与改造前行为一致),绝不
|
|
16
|
+
* 因为影子模块而让桥起不来或报错。
|
|
17
|
+
* - **不抢占**:影子永远 force=false;真实窗口(ownerLive && !ownerShadow)在场时
|
|
18
|
+
* 影子立即关停让位。
|
|
19
|
+
* - **平台无关语义**:本模块不认 ppt/canvas 业务字段,hasContent/ownerLive/
|
|
20
|
+
* ownerShadow 由桥(已 import document-workbench/session)算好传入,避免 kit 反向
|
|
21
|
+
* 依赖 document-workbench 造成环。
|
|
22
|
+
* - 资源回收:beforeStop/dispose 关停所有 browser;页面崩溃下次 reconcile 自动重建。
|
|
23
|
+
*/
|
|
24
|
+
import fs from 'node:fs'
|
|
25
|
+
import os from 'node:os'
|
|
26
|
+
import path from 'node:path'
|
|
27
|
+
|
|
28
|
+
const noop = () => {}
|
|
29
|
+
|
|
30
|
+
/** 在一个 chromium-* 目录里按平台找可执行文件(优先 headless shell)。 */
|
|
31
|
+
function findChromeIn(dir) {
|
|
32
|
+
const headlessNames = new Set(['chrome-headless-shell.exe', 'chrome-headless-shell'])
|
|
33
|
+
const fullNames = new Set(['chrome.exe', 'chrome', 'Chromium'])
|
|
34
|
+
let headless = null
|
|
35
|
+
let full = null
|
|
36
|
+
const walk = (d, depth) => {
|
|
37
|
+
if (depth > 4) return
|
|
38
|
+
let entries = []
|
|
39
|
+
try { entries = fs.readdirSync(d, { withFileTypes: true }) } catch { return }
|
|
40
|
+
for (const entry of entries) {
|
|
41
|
+
const p = path.join(d, entry.name)
|
|
42
|
+
if (entry.isDirectory()) walk(p, depth + 1)
|
|
43
|
+
else if (entry.isFile()) {
|
|
44
|
+
if (headlessNames.has(entry.name) && !headless) headless = p
|
|
45
|
+
else if (fullNames.has(entry.name) && !full) full = p
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
walk(dir, 0)
|
|
50
|
+
return headless || full
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 发现本机 Chromium 可执行文件:显式 env 优先,其次 ms-playwright 缓存(取最高修订)。 */
|
|
54
|
+
export function resolveChromiumExecutable(env = process.env) {
|
|
55
|
+
const explicit = env.SHADOW_CHROMIUM_PATH || env.PLAYWRIGHT_CHROMIUM_EXECUTABLE || env.PUPPETEER_EXECUTABLE_PATH
|
|
56
|
+
if (explicit) {
|
|
57
|
+
try { if (fs.existsSync(explicit)) return explicit } catch { /* ignore */ }
|
|
58
|
+
}
|
|
59
|
+
const roots = []
|
|
60
|
+
if (env.PLAYWRIGHT_BROWSERS_PATH && env.PLAYWRIGHT_BROWSERS_PATH !== '0') roots.push(env.PLAYWRIGHT_BROWSERS_PATH)
|
|
61
|
+
if (process.platform === 'win32') {
|
|
62
|
+
roots.push(path.join(env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'ms-playwright'))
|
|
63
|
+
} else if (process.platform === 'darwin') {
|
|
64
|
+
roots.push(path.join(os.homedir(), 'Library', 'Caches', 'ms-playwright'))
|
|
65
|
+
} else {
|
|
66
|
+
roots.push(path.join(os.homedir(), '.cache', 'ms-playwright'))
|
|
67
|
+
}
|
|
68
|
+
let best = null
|
|
69
|
+
let bestRev = -1
|
|
70
|
+
let bestHeadless = false
|
|
71
|
+
for (const root of roots) {
|
|
72
|
+
let entries = []
|
|
73
|
+
try { entries = fs.readdirSync(root) } catch { continue }
|
|
74
|
+
for (const name of entries) {
|
|
75
|
+
const m = /^chromium(_headless_shell)?-(\d+)$/.exec(name)
|
|
76
|
+
if (!m) continue
|
|
77
|
+
const rev = Number(m[2]) || 0
|
|
78
|
+
const isHeadless = !!m[1]
|
|
79
|
+
const exe = findChromeIn(path.join(root, name))
|
|
80
|
+
if (!exe) continue
|
|
81
|
+
/* 优先 headless shell(更轻),同级取最高修订。 */
|
|
82
|
+
const better = isHeadless !== bestHeadless
|
|
83
|
+
? isHeadless
|
|
84
|
+
: rev > bestRev
|
|
85
|
+
if (!best || better) { best = exe; bestRev = rev; bestHeadless = isHeadless }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return best
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 创建影子管理器。
|
|
93
|
+
* @param {object} opts
|
|
94
|
+
* @param {(msg:string)=>void} [opts.log]
|
|
95
|
+
* @param {()=>Promise<{chromium:any}>} [opts.importPlaywright] 默认动态 import playwright-core
|
|
96
|
+
* @param {()=>string|null} [opts.resolveExecutable]
|
|
97
|
+
*/
|
|
98
|
+
export function createShadowManager({
|
|
99
|
+
log = noop,
|
|
100
|
+
importPlaywright = async () => import('playwright-core'),
|
|
101
|
+
resolveExecutable = () => resolveChromiumExecutable(),
|
|
102
|
+
maxConcurrent = 4,
|
|
103
|
+
} = {}) {
|
|
104
|
+
/** sid -> { browser, page, url, launching, dead } */
|
|
105
|
+
const entries = new Map()
|
|
106
|
+
let disabled = false
|
|
107
|
+
let disposed = false
|
|
108
|
+
let chromiumPromise = null
|
|
109
|
+
|
|
110
|
+
async function getChromium() {
|
|
111
|
+
if (!chromiumPromise) {
|
|
112
|
+
chromiumPromise = (async () => {
|
|
113
|
+
const mod = await importPlaywright()
|
|
114
|
+
const chromium = mod && (mod.chromium || (mod.default && mod.default.chromium))
|
|
115
|
+
if (!chromium || typeof chromium.launch !== 'function') throw new Error('playwright-core 未导出 chromium')
|
|
116
|
+
return chromium
|
|
117
|
+
})().catch((error) => {
|
|
118
|
+
disabled = true
|
|
119
|
+
log(`[shadow] 无头浏览器不可用,影子显示器禁用(工具退回离线渲染):${error.message}`)
|
|
120
|
+
return null
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
return chromiumPromise
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function closeEntry(sid) {
|
|
127
|
+
const entry = entries.get(sid)
|
|
128
|
+
if (!entry) return
|
|
129
|
+
entries.delete(sid)
|
|
130
|
+
try { await entry.page?.close() } catch { /* ignore */ }
|
|
131
|
+
try { await entry.browser?.close() } catch { /* ignore */ }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function launch(sid, url) {
|
|
135
|
+
const chromium = await getChromium()
|
|
136
|
+
if (!chromium || disabled || disposed) return
|
|
137
|
+
const executablePath = resolveExecutable()
|
|
138
|
+
if (!executablePath) {
|
|
139
|
+
disabled = true
|
|
140
|
+
log('[shadow] 未找到 Chromium 可执行文件,影子显示器禁用(工具退回离线渲染)')
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
let browser = null
|
|
144
|
+
try {
|
|
145
|
+
browser = await chromium.launch({
|
|
146
|
+
headless: true,
|
|
147
|
+
executablePath,
|
|
148
|
+
args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
|
|
149
|
+
})
|
|
150
|
+
const page = await browser.newPage()
|
|
151
|
+
const target = url + (url.includes('?') ? '&' : '?') + 'shadow=1'
|
|
152
|
+
await page.goto(target, { waitUntil: 'domcontentloaded', timeout: 30000 })
|
|
153
|
+
const entry = { browser, page, url, launching: false, dead: false, since: Date.now() }
|
|
154
|
+
/* 页面崩溃/被关 → 标死,下一轮 reconcile 重建(不让影子静默失效)。 */
|
|
155
|
+
page.on('close', () => { entry.dead = true })
|
|
156
|
+
browser.on('disconnected', () => { entry.dead = true })
|
|
157
|
+
entries.set(sid, entry)
|
|
158
|
+
log(`[shadow] 影子显示器已就位:${sid}`)
|
|
159
|
+
} catch (error) {
|
|
160
|
+
try { await browser?.close() } catch { /* ignore */ }
|
|
161
|
+
log(`[shadow] 影子显示器启动失败(${sid}):${error.message}`)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 对账一个会话的影子状态。桥周期性调用(带上该会话的 doc 派生旗标)。
|
|
167
|
+
* @param {string} sid
|
|
168
|
+
* @param {string} url 该会话编辑器页基址(不含 ?shadow=1)
|
|
169
|
+
* @param {{hasContent:boolean, ownerLive:boolean, ownerShadow:boolean}} flags
|
|
170
|
+
*/
|
|
171
|
+
async function reconcile(sid, url, { hasContent, ownerLive, ownerShadow }) {
|
|
172
|
+
if (disposed || disabled) return
|
|
173
|
+
try {
|
|
174
|
+
/* 没有稿件,或真实用户窗口在场 → 影子让位/不启动。 */
|
|
175
|
+
if (!hasContent || (ownerLive && !ownerShadow)) {
|
|
176
|
+
await closeEntry(sid)
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
const entry = entries.get(sid)
|
|
180
|
+
if (entry && entry.launching) return
|
|
181
|
+
if (entry && !entry.dead) {
|
|
182
|
+
/* 影子页活着却长时间没认领租约(引导失败/卡死)→ 超宽限重建,避免静默失效。
|
|
183
|
+
* 真实窗口在场或影子已正常认领时不会进这里。 */
|
|
184
|
+
const stuck = hasContent && !ownerLive && !ownerShadow && entry.since && (Date.now() - entry.since > 45000)
|
|
185
|
+
if (!stuck) return /* 已在渲染 */
|
|
186
|
+
await closeEntry(sid)
|
|
187
|
+
} else if (entry) {
|
|
188
|
+
await closeEntry(sid) /* 崩了 → 重建 */
|
|
189
|
+
}
|
|
190
|
+
/* 资源闸:并发影子上限,避免多会话场景拉起过多 Chromium。 */
|
|
191
|
+
const realCount = [...entries.values()].filter((e) => !e.launching).length
|
|
192
|
+
if (!entries.has(sid) && realCount >= maxConcurrent) return
|
|
193
|
+
const placeholder = { launching: true }
|
|
194
|
+
entries.set(sid, placeholder)
|
|
195
|
+
try {
|
|
196
|
+
await launch(sid, url)
|
|
197
|
+
} finally {
|
|
198
|
+
if (entries.get(sid) === placeholder) entries.delete(sid)
|
|
199
|
+
}
|
|
200
|
+
} catch (error) {
|
|
201
|
+
log(`[shadow] reconcile 异常(${sid}):${error.message}`)
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function dispose() {
|
|
206
|
+
disposed = true
|
|
207
|
+
for (const sid of [...entries.keys()]) await closeEntry(sid)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function state() {
|
|
211
|
+
return {
|
|
212
|
+
disabled,
|
|
213
|
+
disposed,
|
|
214
|
+
sessions: [...entries.entries()].map(([sid, e]) => ({ sid, launching: !!e.launching, dead: !!e.dead })),
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return { reconcile, dispose, state }
|
|
219
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** 编辑器 → relay 的最小传输层;页面逻辑不关心 fetch/JSON 细节。 */
|
|
2
|
+
export function createTransport(basePath, fetchImpl = (...args) => fetch(...args)) {
|
|
3
|
+
const api = (path, options) => fetchImpl(basePath + path, options).then((response) => response.json())
|
|
4
|
+
return {
|
|
5
|
+
api,
|
|
6
|
+
get: (path) => api(path),
|
|
7
|
+
post: (path, body) => api(path, {
|
|
8
|
+
method: 'POST',
|
|
9
|
+
headers: { 'content-type': 'application/json' },
|
|
10
|
+
body: JSON.stringify(body),
|
|
11
|
+
}),
|
|
12
|
+
}
|
|
13
|
+
}
|