dsh-coexist-plugin 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +87 -2
- package/assets/icon.svg +20 -0
- package/cordis.patch.yml +12 -0
- package/index.js +267 -0
- package/lib/client.js +545 -0
- package/package.json +57 -4
- package/src/aliasing.js +214 -0
- package/src/cleanup.js +207 -0
- package/src/commands.js +78 -0
- package/src/config.js +49 -0
- package/src/diagnostics.js +912 -0
- package/src/patch.js +355 -0
- package/src/providers.js +231 -0
- package/src/toolpolicy.js +152 -0
- package/src/ui.js +418 -0
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
function agentId(exec) {
|
|
2
|
+
const agent = exec?.agent
|
|
3
|
+
if (!agent) return null
|
|
4
|
+
const candidate = agent.session?.id ?? agent.id ?? agent.name ?? agent.preset
|
|
5
|
+
return candidate == null ? null : String(candidate)
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function ruleFor(policies, name) {
|
|
9
|
+
if (!policies || typeof policies !== 'object') return null
|
|
10
|
+
if (typeof name === 'string' && policies[name] && typeof policies[name] === 'object') {
|
|
11
|
+
return { name, rule: policies[name] }
|
|
12
|
+
}
|
|
13
|
+
if (policies['*'] && typeof policies['*'] === 'object') {
|
|
14
|
+
return { name: '*', rule: policies['*'] }
|
|
15
|
+
}
|
|
16
|
+
return null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function evaluateRule(rule, exec) {
|
|
20
|
+
const agent = agentId(exec)
|
|
21
|
+
const agents = rule.agents ?? {}
|
|
22
|
+
|
|
23
|
+
if (Array.isArray(rule.denyAgents) && agent && rule.denyAgents.includes(agent)) {
|
|
24
|
+
return rule.reason ?? `agent "${agent}" is denied for tool "${exec?.name}"`
|
|
25
|
+
}
|
|
26
|
+
if (Array.isArray(agents.deny) && agent && agents.deny.includes(agent)) {
|
|
27
|
+
return rule.reason ?? `agent "${agent}" is denied for tool "${exec?.name}"`
|
|
28
|
+
}
|
|
29
|
+
if (Array.isArray(rule.allowAgents) && rule.allowAgents.length > 0) {
|
|
30
|
+
if (!agent || !rule.allowAgents.includes(agent)) {
|
|
31
|
+
return rule.reason ?? `agent "${agent ?? 'unknown'}" is not allowed to call tool "${exec?.name}"`
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (Array.isArray(agents.allow) && agents.allow.length > 0) {
|
|
35
|
+
if (!agent || !agents.allow.includes(agent)) {
|
|
36
|
+
return rule.reason ?? `agent "${agent ?? 'unknown'}" is not allowed to call tool "${exec?.name}"`
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (rule.deny === true) {
|
|
40
|
+
return typeof rule.reason === 'string' && rule.reason.length > 0
|
|
41
|
+
? rule.reason
|
|
42
|
+
: `tool "${exec?.name}" is disabled by coexist policy`
|
|
43
|
+
}
|
|
44
|
+
if (typeof rule.deny === 'string' && rule.deny.length > 0) {
|
|
45
|
+
return rule.deny
|
|
46
|
+
}
|
|
47
|
+
return undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 用 tools.guard() 注册一个同步门禁。guard 是单调拒绝:任何匹配规则返回字符串即拒绝,
|
|
52
|
+
* 不会覆盖别的插件已经做出的放行决定。
|
|
53
|
+
* 配置:toolPolicies: { "memory_search": { deny: true|"原因", allowAgents: [...], denyAgents: [...] } }
|
|
54
|
+
*/
|
|
55
|
+
export function installToolPolicies(service, options = {}) {
|
|
56
|
+
if (!service || typeof service.guard !== 'function') {
|
|
57
|
+
return { installed: false, dispose: null }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const policies = options.policies && typeof options.policies === 'object' ? options.policies : {}
|
|
61
|
+
if (Object.keys(policies).length === 0) {
|
|
62
|
+
return { installed: false, dispose: null }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const previous = globalThis.__dshCoexistToolPolicyDispose
|
|
66
|
+
if (typeof previous === 'function') {
|
|
67
|
+
try {
|
|
68
|
+
previous()
|
|
69
|
+
} catch {
|
|
70
|
+
// 旧 guard 已被宿主清理时忽略。
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let dispose
|
|
75
|
+
try {
|
|
76
|
+
dispose = service.guard((exec) => {
|
|
77
|
+
const matched = ruleFor(policies, exec?.name)
|
|
78
|
+
if (!matched) return undefined
|
|
79
|
+
const reason = evaluateRule(matched.rule, exec)
|
|
80
|
+
if (reason !== undefined) {
|
|
81
|
+
options.log?.(`[coexist] tool policy denied: ${exec?.name} (${reason})`)
|
|
82
|
+
}
|
|
83
|
+
return reason
|
|
84
|
+
})
|
|
85
|
+
} catch {
|
|
86
|
+
return { installed: false, dispose: null }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
globalThis.__dshCoexistToolPolicyDispose = typeof dispose === 'function' ? dispose : null
|
|
90
|
+
options.log?.(
|
|
91
|
+
`[coexist] tool policy active (${Object.keys(policies).length} rule${Object.keys(policies).length === 1 ? '' : 's'})`,
|
|
92
|
+
)
|
|
93
|
+
return { installed: true, dispose: typeof dispose === 'function' ? dispose : null }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 观察 tools/post-execute:只记录调用、耗时、是否被拒绝,不修改结果。
|
|
98
|
+
* 监听器把 next() 的决定原样返回,保证不改变宿主行为。
|
|
99
|
+
*/
|
|
100
|
+
export function installToolObservation(ctx, options = {}) {
|
|
101
|
+
if (options.enabled === false) return { installed: false, dispose: null }
|
|
102
|
+
if (!ctx || typeof ctx.on !== 'function') return { installed: false, dispose: null }
|
|
103
|
+
|
|
104
|
+
const previous = globalThis.__dshCoexistToolObservationDispose
|
|
105
|
+
if (typeof previous === 'function') {
|
|
106
|
+
try {
|
|
107
|
+
previous()
|
|
108
|
+
} catch {
|
|
109
|
+
// 旧监听器已被宿主清理时忽略。
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
let dispose
|
|
114
|
+
try {
|
|
115
|
+
dispose = ctx.on('tools/post-execute', async (exec, result, next) => {
|
|
116
|
+
const started = Date.now()
|
|
117
|
+
try {
|
|
118
|
+
const decision = typeof next === 'function' ? await next() : { kind: 'accept' }
|
|
119
|
+
try {
|
|
120
|
+
options.onCall?.({
|
|
121
|
+
tool: exec?.name ?? null,
|
|
122
|
+
agent: agentId(exec),
|
|
123
|
+
durationMs: Date.now() - started,
|
|
124
|
+
blocked: decision?.kind === 'block',
|
|
125
|
+
isError: result?.isError === true,
|
|
126
|
+
})
|
|
127
|
+
} catch {
|
|
128
|
+
// 观测回调不能影响宿主。
|
|
129
|
+
}
|
|
130
|
+
return decision
|
|
131
|
+
} catch (error) {
|
|
132
|
+
try {
|
|
133
|
+
options.onCall?.({
|
|
134
|
+
tool: exec?.name ?? null,
|
|
135
|
+
agent: agentId(exec),
|
|
136
|
+
durationMs: Date.now() - started,
|
|
137
|
+
error: error?.message ?? String(error),
|
|
138
|
+
})
|
|
139
|
+
} catch {
|
|
140
|
+
// 观测回调不能影响宿主。
|
|
141
|
+
}
|
|
142
|
+
throw error
|
|
143
|
+
}
|
|
144
|
+
})
|
|
145
|
+
} catch {
|
|
146
|
+
return { installed: false, dispose: null }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
globalThis.__dshCoexistToolObservationDispose = typeof dispose === 'function' ? dispose : null
|
|
150
|
+
options.log?.('[coexist] tool observation active (tools/post-execute)')
|
|
151
|
+
return { installed: true, dispose: typeof dispose === 'function' ? dispose : null }
|
|
152
|
+
}
|
package/src/ui.js
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import fsp from 'node:fs/promises'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { createRequire } from 'node:module'
|
|
6
|
+
import { fileURLToPath } from 'node:url'
|
|
7
|
+
import { execFile } from 'node:child_process'
|
|
8
|
+
import { promisify } from 'node:util'
|
|
9
|
+
|
|
10
|
+
const execFileAsync = promisify(execFile)
|
|
11
|
+
const requireFromPlugin = createRequire(import.meta.url)
|
|
12
|
+
const ROUTE_PREFIX = '/coexist-api/'
|
|
13
|
+
|
|
14
|
+
function resolveHome(config = {}) {
|
|
15
|
+
return path.resolve(
|
|
16
|
+
config.home ?? process.env.DSH_COEXIST_HOME ?? process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh'),
|
|
17
|
+
)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function resolveProfile(home, config = {}) {
|
|
21
|
+
if (config.profile) return config.profile
|
|
22
|
+
if (process.env.DSH_COEXIST_PROFILE) return process.env.DSH_COEXIST_PROFILE
|
|
23
|
+
return fs.existsSync(path.join(home, 'profiles', 'desktop')) ? 'desktop' : 'web'
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 从 loader 的 baseUrl 反推当前 profile 与 home,避免 UI 操作错 profile。 */
|
|
27
|
+
export function detectProfile(ctx, config = {}) {
|
|
28
|
+
let home = config.home ?? process.env.DSH_COEXIST_HOME ?? process.env.DSH_HOME ?? null
|
|
29
|
+
if (config.profile && home) return { home: path.resolve(home), profile: config.profile }
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
const loader = typeof ctx.get === 'function' ? ctx.get('loader') : ctx.loader
|
|
33
|
+
const baseUrl = loader?.config?.baseUrl ?? ctx.baseUrl
|
|
34
|
+
if (typeof baseUrl === 'string' && baseUrl.length > 0) {
|
|
35
|
+
const dir = baseUrl.startsWith('file:') ? fileURLToPath(baseUrl) : path.resolve(baseUrl)
|
|
36
|
+
const profilesDir = path.dirname(dir)
|
|
37
|
+
if (path.basename(profilesDir) === 'profiles') {
|
|
38
|
+
const detectedHome = path.dirname(profilesDir)
|
|
39
|
+
return {
|
|
40
|
+
home: home ? path.resolve(home) : detectedHome,
|
|
41
|
+
profile: config.profile ?? path.basename(dir),
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
} catch {
|
|
46
|
+
// 没有 loader 时退回默认探测。
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const resolvedHome = resolveHome({ ...config, home })
|
|
50
|
+
return { home: resolvedHome, profile: resolveProfile(resolvedHome, config) }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readJson(file) {
|
|
54
|
+
try {
|
|
55
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
56
|
+
} catch {
|
|
57
|
+
return null
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function writeJsonAtomic(file, value) {
|
|
62
|
+
await fsp.mkdir(path.dirname(file), { recursive: true })
|
|
63
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`
|
|
64
|
+
await fsp.writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
|
|
65
|
+
await fsp.rename(tmp, file)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function readBody(req, limit = 1024 * 1024) {
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
const chunks = []
|
|
71
|
+
let size = 0
|
|
72
|
+
req.on('data', (chunk) => {
|
|
73
|
+
size += chunk.length
|
|
74
|
+
if (size > limit) {
|
|
75
|
+
reject(new Error('request body too large'))
|
|
76
|
+
req.destroy()
|
|
77
|
+
return
|
|
78
|
+
}
|
|
79
|
+
chunks.push(chunk)
|
|
80
|
+
})
|
|
81
|
+
req.on('end', () => {
|
|
82
|
+
if (chunks.length === 0) return resolve({})
|
|
83
|
+
try {
|
|
84
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
|
|
85
|
+
} catch {
|
|
86
|
+
reject(new Error('request body is not valid JSON'))
|
|
87
|
+
}
|
|
88
|
+
})
|
|
89
|
+
req.on('error', reject)
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function sendJson(res, status, value) {
|
|
94
|
+
res.writeHead(status, {
|
|
95
|
+
'content-type': 'application/json; charset=utf-8',
|
|
96
|
+
'cache-control': 'no-store',
|
|
97
|
+
})
|
|
98
|
+
res.end(JSON.stringify(value))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 只接受本机回环连接;IPC/进程内调用没有 remoteAddress,按本机处理。 */
|
|
102
|
+
export function isLoopbackAddress(address) {
|
|
103
|
+
if (!address) return true
|
|
104
|
+
const normalized = address.startsWith('::ffff:') ? address.slice(7) : address
|
|
105
|
+
return normalized === '::1' || /^127\./.test(normalized)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 浏览器 POST 会带 Origin;http(s) 必须同源,桌面自定义协议/无 Origin 视为应用内调用。 */
|
|
109
|
+
export function isSameOrigin(headers = {}) {
|
|
110
|
+
const origin = headers.origin
|
|
111
|
+
if (!origin || origin === 'null') return true
|
|
112
|
+
try {
|
|
113
|
+
const url = new URL(origin)
|
|
114
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return true
|
|
115
|
+
return url.host === headers.host
|
|
116
|
+
} catch {
|
|
117
|
+
return false
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 写接口的请求闸门:
|
|
123
|
+
* - 只接受 POST + application/json,跨站表单/text-plain 因此进不来;
|
|
124
|
+
* - 只接受本机回环,避免 DSH 绑定局域网地址时被外部直接调用;
|
|
125
|
+
* - Origin 存在时必须同源。
|
|
126
|
+
*/
|
|
127
|
+
export function rejectReason(req) {
|
|
128
|
+
if (req.method !== 'POST') return 'POST required'
|
|
129
|
+
if (!isLoopbackAddress(req.socket?.remoteAddress)) return 'local requests only'
|
|
130
|
+
if (!isSameOrigin(req.headers)) return 'cross-origin request rejected'
|
|
131
|
+
const type = String(req.headers['content-type'] ?? '').toLowerCase()
|
|
132
|
+
if (!type.startsWith('application/json')) return 'application/json required'
|
|
133
|
+
return null
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* DSH 原生的 Host/Origin 校验与浏览器会话认证(`dsh web` 的 Connection 服务)。
|
|
138
|
+
* 返回 401/403 表示拒绝,undefined 表示放行。
|
|
139
|
+
* 宿主没有 Connection 服务时放行,交由 rejectReason 兜底,避免桌面/旧宿主整页不可用;
|
|
140
|
+
* 服务存在但检查抛错时按拒绝处理,保持 fail-closed。
|
|
141
|
+
*/
|
|
142
|
+
export function connectionRejection(ctx, req, log) {
|
|
143
|
+
let connection
|
|
144
|
+
try {
|
|
145
|
+
connection = typeof ctx?.get === 'function' ? ctx.get('connection') ?? ctx.connection : ctx?.connection
|
|
146
|
+
} catch {
|
|
147
|
+
connection = undefined
|
|
148
|
+
}
|
|
149
|
+
if (typeof connection?.requestRejection !== 'function') return undefined
|
|
150
|
+
try {
|
|
151
|
+
const rejection = connection.requestRejection(req)
|
|
152
|
+
return rejection === 401 || rejection === 403 ? rejection : undefined
|
|
153
|
+
} catch (error) {
|
|
154
|
+
log?.(`[coexist] connection check failed: ${error?.message ?? String(error)}`)
|
|
155
|
+
return 403
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 插件自带的 CLI 依赖(dsh-coexist-cli),无需用户配置路径。 */
|
|
160
|
+
function bundledCli() {
|
|
161
|
+
try {
|
|
162
|
+
const pkgPath = requireFromPlugin.resolve('dsh-coexist-cli/package.json')
|
|
163
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
|
|
164
|
+
const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.['dsh-coexist']
|
|
165
|
+
if (!rel) return null
|
|
166
|
+
const bin = path.resolve(path.dirname(pkgPath), rel)
|
|
167
|
+
if (!fs.existsSync(bin)) return null
|
|
168
|
+
return { ok: true, file: process.execPath, prefix: [bin], display: bin, source: 'dependency' }
|
|
169
|
+
} catch {
|
|
170
|
+
return null
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** CLI 解析顺序:显式配置 > 环境变量 > 插件依赖 > PATH。 */
|
|
175
|
+
export function resolveCli(config = {}) {
|
|
176
|
+
const explicit = config.cliPath ?? process.env.DSH_COEXIST_CLI
|
|
177
|
+
if (explicit) {
|
|
178
|
+
const resolved = path.resolve(explicit)
|
|
179
|
+
if (!fs.existsSync(resolved)) return { ok: false, error: `CLI not found: ${resolved}` }
|
|
180
|
+
if (/\.(c|m)?js$/i.test(resolved)) {
|
|
181
|
+
return { ok: true, file: process.execPath, prefix: [resolved], display: resolved, source: 'configured' }
|
|
182
|
+
}
|
|
183
|
+
return { ok: true, file: resolved, prefix: [], display: resolved, source: 'configured' }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const bundled = bundledCli()
|
|
187
|
+
if (bundled) return bundled
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
ok: true,
|
|
191
|
+
file: process.platform === 'win32' ? 'dsh-coexist.cmd' : 'dsh-coexist',
|
|
192
|
+
prefix: [],
|
|
193
|
+
display: 'dsh-coexist',
|
|
194
|
+
source: 'path',
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function runCli(cli, args, { home } = {}) {
|
|
199
|
+
const needsShell = process.platform === 'win32' && /\.(cmd|bat)$/i.test(cli.file)
|
|
200
|
+
try {
|
|
201
|
+
const { stdout, stderr } = await execFileAsync(cli.file, [...cli.prefix, ...args], {
|
|
202
|
+
env: { ...process.env, DSH_HOME: home },
|
|
203
|
+
timeout: 10 * 60_000,
|
|
204
|
+
windowsHide: true,
|
|
205
|
+
shell: needsShell,
|
|
206
|
+
maxBuffer: 24 * 1024 * 1024,
|
|
207
|
+
})
|
|
208
|
+
return { ok: true, stdout, stderr }
|
|
209
|
+
} catch (error) {
|
|
210
|
+
return {
|
|
211
|
+
ok: false,
|
|
212
|
+
error: error?.stderr?.trim() || error?.message || String(error),
|
|
213
|
+
stdout: error?.stdout ?? '',
|
|
214
|
+
stderr: error?.stderr ?? '',
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function parseCliJson(result) {
|
|
220
|
+
if (!result.ok) return result
|
|
221
|
+
try {
|
|
222
|
+
return { ok: true, value: JSON.parse(result.stdout), stderr: result.stderr }
|
|
223
|
+
} catch {
|
|
224
|
+
return { ok: false, error: `CLI did not return JSON: ${result.stdout.slice(0, 400)}` }
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function listBackups(home, profile) {
|
|
229
|
+
const marker = `${path.sep}profiles${path.sep}${profile}${path.sep}`
|
|
230
|
+
try {
|
|
231
|
+
return fs
|
|
232
|
+
.readdirSync(path.join(home, 'coexist', 'backups'), { withFileTypes: true })
|
|
233
|
+
.filter((entry) => entry.isDirectory())
|
|
234
|
+
.map((entry) => entry.name)
|
|
235
|
+
.filter((id) => {
|
|
236
|
+
const manifest = readJson(path.join(home, 'coexist', 'backups', id, 'manifest.json'))
|
|
237
|
+
return (manifest?.files ?? []).some((item) => String(item.file).includes(marker))
|
|
238
|
+
})
|
|
239
|
+
.sort()
|
|
240
|
+
.reverse()
|
|
241
|
+
} catch {
|
|
242
|
+
return []
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function statusPayload(home, profile) {
|
|
247
|
+
const coexistDir = path.join(home, 'coexist')
|
|
248
|
+
const profileDir = path.join(home, 'profiles', profile)
|
|
249
|
+
const manifest = readJson(path.join(profileDir, 'package.json'))
|
|
250
|
+
return {
|
|
251
|
+
home,
|
|
252
|
+
profile,
|
|
253
|
+
profileDir,
|
|
254
|
+
hostVersion: (() => {
|
|
255
|
+
const fromProfile = readJson(path.join(profileDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json'))
|
|
256
|
+
return fromProfile?.version ?? null
|
|
257
|
+
})(),
|
|
258
|
+
report: readJson(path.join(coexistDir, 'report.json')),
|
|
259
|
+
state: readJson(path.join(coexistDir, 'state.json')),
|
|
260
|
+
graph: readJson(path.join(coexistDir, 'graph.json')),
|
|
261
|
+
config: readJson(path.join(coexistDir, 'config.json')) ?? {},
|
|
262
|
+
bundles: manifest?.dsh?.profile?.bundles ?? [],
|
|
263
|
+
dependencies: manifest?.dependencies ?? {},
|
|
264
|
+
backups: listBackups(home, profile),
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* 给桌面/网页设置页提供本地 HTTP 接口。
|
|
270
|
+
* 所有写操作仍由 CLI 执行,避免 UI 与 CLI 两套逻辑分叉。
|
|
271
|
+
*/
|
|
272
|
+
export function installUiRoutes(ctx, options = {}) {
|
|
273
|
+
let installed = false
|
|
274
|
+
|
|
275
|
+
const install = (webServer) => {
|
|
276
|
+
if (installed || !webServer) return installed
|
|
277
|
+
installed = true
|
|
278
|
+
|
|
279
|
+
const { home, profile } = detectProfile(ctx, options)
|
|
280
|
+
const cli = resolveCli(options)
|
|
281
|
+
|
|
282
|
+
const routes = {
|
|
283
|
+
status: async () => ({ ok: true, ...statusPayload(home, profile), cli }),
|
|
284
|
+
check: async () =>
|
|
285
|
+
parseCliJson(
|
|
286
|
+
await runCli(cli, ['check', '--home', home, '--profile', profile, '--json', '--no-log-scan'], { home }),
|
|
287
|
+
),
|
|
288
|
+
plan: async () =>
|
|
289
|
+
parseCliJson(
|
|
290
|
+
await runCli(
|
|
291
|
+
cli,
|
|
292
|
+
['plan', '--home', home, '--profile', profile, '--json', '--no-log-scan', '--no-diff'],
|
|
293
|
+
{ home },
|
|
294
|
+
),
|
|
295
|
+
),
|
|
296
|
+
apply: async (body) => {
|
|
297
|
+
const args = ['apply', '--home', home, '--profile', profile, '--yes', '--no-diff', '--json']
|
|
298
|
+
if (body.planId) args.push('--plan', String(body.planId))
|
|
299
|
+
return parseCliJson(await runCli(cli, args, { home }))
|
|
300
|
+
},
|
|
301
|
+
rollback: async (body) => {
|
|
302
|
+
const available = listBackups(home, profile)
|
|
303
|
+
const id = body.id ? String(body.id) : available[0]
|
|
304
|
+
if (!id) return { ok: false, error: 'no backup for this profile' }
|
|
305
|
+
if (!available.includes(id)) {
|
|
306
|
+
return { ok: false, error: `backup not found for profile ${profile}: ${id}`, available }
|
|
307
|
+
}
|
|
308
|
+
const args = ['rollback', '--home', home, '--profile', profile, '--id', id, '--json']
|
|
309
|
+
if (body.reinstall !== false) args.push('--reinstall')
|
|
310
|
+
return parseCliJson(await runCli(cli, args, { home }))
|
|
311
|
+
},
|
|
312
|
+
install: async (body) => {
|
|
313
|
+
if (!body.spec) return { ok: false, error: 'missing spec' }
|
|
314
|
+
return parseCliJson(
|
|
315
|
+
await runCli(
|
|
316
|
+
cli,
|
|
317
|
+
['install', String(body.spec), '--home', home, '--profile', profile, '--json'],
|
|
318
|
+
{ home },
|
|
319
|
+
),
|
|
320
|
+
)
|
|
321
|
+
},
|
|
322
|
+
uninstall: async (body) => {
|
|
323
|
+
if (!body.name) return { ok: false, error: 'missing name' }
|
|
324
|
+
return parseCliJson(
|
|
325
|
+
await runCli(
|
|
326
|
+
cli,
|
|
327
|
+
['uninstall', String(body.name), '--home', home, '--profile', profile, '--json'],
|
|
328
|
+
{ home },
|
|
329
|
+
),
|
|
330
|
+
)
|
|
331
|
+
},
|
|
332
|
+
'free-port': async (body) => {
|
|
333
|
+
const port = Number(body.port)
|
|
334
|
+
if (!Number.isInteger(port)) return { ok: false, error: 'invalid port' }
|
|
335
|
+
return parseCliJson(
|
|
336
|
+
await runCli(cli, ['free-port', String(port), '--yes', '--json'], { home }),
|
|
337
|
+
)
|
|
338
|
+
},
|
|
339
|
+
prefer: async (body) => {
|
|
340
|
+
if (!body.plugin) return { ok: false, error: 'missing plugin' }
|
|
341
|
+
return parseCliJson(
|
|
342
|
+
await runCli(
|
|
343
|
+
cli,
|
|
344
|
+
['prefer', String(body.plugin), '--home', home, '--profile', profile, '--json'],
|
|
345
|
+
{ home },
|
|
346
|
+
),
|
|
347
|
+
)
|
|
348
|
+
},
|
|
349
|
+
config: async (body) => {
|
|
350
|
+
const file = path.join(home, 'coexist', 'config.json')
|
|
351
|
+
const current = readJson(file) ?? {}
|
|
352
|
+
if (!body.patch || typeof body.patch !== 'object') {
|
|
353
|
+
return { ok: true, config: current, file }
|
|
354
|
+
}
|
|
355
|
+
const next = { ...current, ...body.patch }
|
|
356
|
+
await writeJsonAtomic(file, next)
|
|
357
|
+
return { ok: true, config: next, file }
|
|
358
|
+
},
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
for (const [name, handler] of Object.entries(routes)) {
|
|
362
|
+
try {
|
|
363
|
+
ctx.effect(
|
|
364
|
+
() =>
|
|
365
|
+
webServer.register({
|
|
366
|
+
kind: 'exact',
|
|
367
|
+
path: `${ROUTE_PREFIX}${name}`,
|
|
368
|
+
handler: async (req, res) => {
|
|
369
|
+
const blocked = connectionRejection(ctx, req, options.log)
|
|
370
|
+
if (blocked) {
|
|
371
|
+
sendJson(res, blocked, {
|
|
372
|
+
ok: false,
|
|
373
|
+
error: blocked === 401 ? 'unauthorized' : 'forbidden',
|
|
374
|
+
})
|
|
375
|
+
return
|
|
376
|
+
}
|
|
377
|
+
const rejected = rejectReason(req)
|
|
378
|
+
if (rejected) {
|
|
379
|
+
sendJson(res, rejected === 'POST required' ? 405 : 403, { ok: false, error: rejected })
|
|
380
|
+
return
|
|
381
|
+
}
|
|
382
|
+
try {
|
|
383
|
+
const body = await readBody(req)
|
|
384
|
+
const result = await handler(body)
|
|
385
|
+
sendJson(res, result?.ok === false ? 400 : 200, result)
|
|
386
|
+
} catch (error) {
|
|
387
|
+
sendJson(res, 500, { ok: false, error: error?.message ?? String(error) })
|
|
388
|
+
}
|
|
389
|
+
},
|
|
390
|
+
}),
|
|
391
|
+
`coexist-ui: ${name}`,
|
|
392
|
+
)
|
|
393
|
+
} catch (error) {
|
|
394
|
+
options.log?.(`[coexist] ui route failed (${name}): ${error.message}`)
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
options.log?.(`[coexist] ui routes active: ${Object.keys(routes).length} (${profile})`)
|
|
399
|
+
return true
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
let webServer
|
|
403
|
+
try {
|
|
404
|
+
webServer = typeof ctx.get === 'function' ? ctx.get('webServer') : ctx.webServer
|
|
405
|
+
} catch {
|
|
406
|
+
webServer = undefined
|
|
407
|
+
}
|
|
408
|
+
if (install(webServer)) return true
|
|
409
|
+
|
|
410
|
+
try {
|
|
411
|
+
ctx.on('internal/service', (name, service) => {
|
|
412
|
+
if (name === 'webServer' && service) install(service)
|
|
413
|
+
})
|
|
414
|
+
} catch {
|
|
415
|
+
// 没有事件服务时只能依赖 apply 时的 webServer。
|
|
416
|
+
}
|
|
417
|
+
return false
|
|
418
|
+
}
|