@goodandready/dsh-moa 0.2.15 → 0.2.17
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 -0
- package/lib/best-effort.js +38 -0
- package/lib/client.js +172 -4
- package/lib/file-workspace.js +71 -37
- package/lib/history.js +4 -4
- package/lib/index.js +18 -382
- package/lib/moa-candidates.js +225 -0
- package/lib/moa-parser.js +6 -0
- package/lib/moa-runner.js +29 -224
- package/lib/routes.js +412 -0
- package/lib/updater.js +282 -0
- package/package.json +1 -2
- package/docs/README.ru.md +0 -287
- package/docs/README.zh.md +0 -243
- package/docs/design/DESIGN.md +0 -79
- package/docs/plans/47-client-js-split-plan.md +0 -57
- package/docs/plans/55-resilience-plan.md +0 -33
- package/docs/plans/59-power-pack-plan.md +0 -73
- package/docs/plans/63-stability-polish-plan.md +0 -15
package/lib/routes.js
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepSeek Harness Mixture of Agents (MoA) — HTTP Route Handlers
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
getMoaHistory,
|
|
7
|
+
getMoaLeaderboard,
|
|
8
|
+
getMoaRunById,
|
|
9
|
+
exportMoaHistory,
|
|
10
|
+
} from './history.js'
|
|
11
|
+
import { promoteCandidateWorkspace } from './file-workspace.js'
|
|
12
|
+
import { isSafeWriteRequest } from './updater.js'
|
|
13
|
+
import { runMoAPipeline } from './moa-runner.js'
|
|
14
|
+
|
|
15
|
+
function writeJson(res, status, body) {
|
|
16
|
+
res.writeHead(status, {
|
|
17
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
18
|
+
'Cache-Control': 'no-store',
|
|
19
|
+
})
|
|
20
|
+
res.end(JSON.stringify(body))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function readBody(req) {
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
let acc = ''
|
|
26
|
+
req.on('data', (chunk) => {
|
|
27
|
+
acc += chunk
|
|
28
|
+
if (acc.length > 5 * 1024 * 1024) {
|
|
29
|
+
req.destroy()
|
|
30
|
+
reject(new Error('Payload Too Large'))
|
|
31
|
+
}
|
|
32
|
+
})
|
|
33
|
+
req.on('end', () => resolve(acc))
|
|
34
|
+
req.on('error', reject)
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function registerMoaRoutes(ctx, { live, callLlm, liveCanvas, getSettingsScope }) {
|
|
39
|
+
const getScope = () => (typeof getSettingsScope === 'function' ? getSettingsScope() : null)
|
|
40
|
+
|
|
41
|
+
ctx.effect(() => {
|
|
42
|
+
return ctx.webServer.register({
|
|
43
|
+
kind: 'exact',
|
|
44
|
+
path: '/dsh-moa/status',
|
|
45
|
+
handler: (_req, res) => {
|
|
46
|
+
const cfg = live()
|
|
47
|
+
writeJson(res, 200, {
|
|
48
|
+
ok: true,
|
|
49
|
+
enabled: cfg.enabled !== false,
|
|
50
|
+
defaultPreset: cfg.default_preset || 'default',
|
|
51
|
+
presetsCount: (cfg.presets || []).length,
|
|
52
|
+
})
|
|
53
|
+
},
|
|
54
|
+
})
|
|
55
|
+
}, 'dsh-moa: status route')
|
|
56
|
+
|
|
57
|
+
// Route: /dsh-moa/models
|
|
58
|
+
ctx.effect(() => {
|
|
59
|
+
return ctx.webServer.register({
|
|
60
|
+
kind: 'exact',
|
|
61
|
+
path: '/dsh-moa/models',
|
|
62
|
+
handler: async (_req, res) => {
|
|
63
|
+
const result = []
|
|
64
|
+
const seen = new Set()
|
|
65
|
+
|
|
66
|
+
const add = (p, m) => {
|
|
67
|
+
if (!p || !m) return
|
|
68
|
+
const key = `${p}:${m}`
|
|
69
|
+
if (!seen.has(key)) {
|
|
70
|
+
seen.add(key)
|
|
71
|
+
result.push({ provider: p, model: m, label: key })
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (ctx.llm) {
|
|
76
|
+
try {
|
|
77
|
+
if (typeof ctx.llm.listAvailableModels === 'function') {
|
|
78
|
+
const list = await ctx.llm.listAvailableModels()
|
|
79
|
+
for (const item of (list || [])) {
|
|
80
|
+
if (item?.provider && item?.id) add(item.provider, item.id)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
} catch (e) {
|
|
84
|
+
console.warn('[dsh-moa] ctx.llm.listAvailableModels error:', e)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
if (typeof ctx.llm.listConfigurableProviders === 'function') {
|
|
89
|
+
const cProvs = ctx.llm.listConfigurableProviders() || []
|
|
90
|
+
for (const cp of cProvs) {
|
|
91
|
+
const cpId = cp.provider || cp.id
|
|
92
|
+
if (cpId && typeof ctx.llm.listModels === 'function') {
|
|
93
|
+
try {
|
|
94
|
+
const mList = await ctx.llm.listModels(cpId)
|
|
95
|
+
for (const m of (mList || [])) {
|
|
96
|
+
const mId = typeof m === 'string' ? m : (m.id || m.model || m.name)
|
|
97
|
+
if (mId) add(cpId, mId)
|
|
98
|
+
}
|
|
99
|
+
} catch (mErr) { /* listModels best-effort */ }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
} catch (e) {
|
|
104
|
+
console.warn('[dsh-moa] ctx.llm.listConfigurableProviders error:', e)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Query settings for configured providers
|
|
109
|
+
try {
|
|
110
|
+
const s = ctx.get ? ctx.get('settings') : ctx.settings
|
|
111
|
+
const getSetting = (k) => {
|
|
112
|
+
try { return s?.get?.(k) } catch { return undefined }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const def = getSetting('agent-default-model')
|
|
116
|
+
if (def?.provider && def?.model) {
|
|
117
|
+
add(def.provider, def.model)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const piAi = getSetting('llm-pi-ai')
|
|
121
|
+
for (const [pName, pData] of Object.entries(piAi?.providers || {})) {
|
|
122
|
+
for (const m of (pData?.models || [])) {
|
|
123
|
+
const mId = typeof m === 'string' ? m : (m?.id || m?.model)
|
|
124
|
+
if (mId) add(pName, mId)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const sync = getSetting('dsh-model-sync')
|
|
129
|
+
for (const [syncProv, syncModels] of Object.entries(sync?.modelCatalogs || {})) {
|
|
130
|
+
for (const m of (syncModels || [])) {
|
|
131
|
+
const mId = typeof m === 'string' ? m : (m?.id || m?.model)
|
|
132
|
+
if (mId) add(syncProv, mId)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
} catch (e) {
|
|
136
|
+
console.warn('[dsh-moa] Error reading settings:', e)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
writeJson(res, 200, { ok: true, models: result })
|
|
140
|
+
},
|
|
141
|
+
})
|
|
142
|
+
}, 'dsh-moa: models route')
|
|
143
|
+
|
|
144
|
+
// Route: /dsh-moa/presets
|
|
145
|
+
ctx.effect(() => {
|
|
146
|
+
return ctx.webServer.register({
|
|
147
|
+
kind: 'exact',
|
|
148
|
+
path: '/dsh-moa/presets',
|
|
149
|
+
handler: async (req, res) => {
|
|
150
|
+
const cfg = live()
|
|
151
|
+
if (req.method === 'GET') {
|
|
152
|
+
writeJson(res, 200, {
|
|
153
|
+
ok: true,
|
|
154
|
+
defaultPreset: cfg.default_preset || 'default',
|
|
155
|
+
presets: cfg.presets || [],
|
|
156
|
+
})
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (req.method === 'POST' || req.method === 'PUT') {
|
|
161
|
+
if (!isSafeWriteRequest(req)) {
|
|
162
|
+
writeJson(res, 403, { ok: false, error: 'Forbidden: cross-site request rejected' })
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const raw = await readBody(req)
|
|
167
|
+
const payload = JSON.parse(raw)
|
|
168
|
+
const newConfig = {
|
|
169
|
+
enabled: typeof payload.enabled === 'boolean' ? payload.enabled : cfg.enabled !== false,
|
|
170
|
+
default_preset: payload.default_preset || cfg.default_preset || 'default',
|
|
171
|
+
presets: Array.isArray(payload.presets) ? payload.presets : (cfg.presets || []),
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Validate the merged payload through the plugin schema before it
|
|
175
|
+
// reaches the settings storage: malformed payloads must be
|
|
176
|
+
// rejected with 400 instead of being persisted.
|
|
177
|
+
let validated
|
|
178
|
+
try {
|
|
179
|
+
validated = Config(structuredClone(newConfig))
|
|
180
|
+
} catch (verr) {
|
|
181
|
+
writeJson(res, 400, { ok: false, error: 'Invalid presets payload: ' + (verr?.message || String(verr)) })
|
|
182
|
+
return
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Persist via Cordis Settings API
|
|
186
|
+
if (settingsScope && typeof settingsScope.replace === 'function') {
|
|
187
|
+
await settingsScope.replace(validated)
|
|
188
|
+
} else {
|
|
189
|
+
// In-memory fallback if settings service is unavailable
|
|
190
|
+
getConfig = () => validated
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
writeJson(res, 200, {
|
|
194
|
+
ok: true,
|
|
195
|
+
enabled: validated.enabled !== false,
|
|
196
|
+
defaultPreset: validated.default_preset,
|
|
197
|
+
presets: validated.presets,
|
|
198
|
+
})
|
|
199
|
+
} catch (err) {
|
|
200
|
+
writeJson(res, 400, { ok: false, error: err?.message || String(err) })
|
|
201
|
+
}
|
|
202
|
+
return
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
writeJson(res, 405, { ok: false, error: 'Method Not Allowed' })
|
|
206
|
+
},
|
|
207
|
+
})
|
|
208
|
+
}, 'dsh-moa: presets route')
|
|
209
|
+
|
|
210
|
+
// Route: /dsh-moa/history (#9)
|
|
211
|
+
ctx.effect(() => {
|
|
212
|
+
return ctx.webServer.register({
|
|
213
|
+
kind: 'exact',
|
|
214
|
+
path: '/dsh-moa/history',
|
|
215
|
+
handler: async (req, res) => {
|
|
216
|
+
if (req.method !== 'GET') {
|
|
217
|
+
writeJson(res, 405, { ok: false, error: 'GET required' })
|
|
218
|
+
return
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
const u = new URL(req.url, 'http://localhost')
|
|
222
|
+
const limit = parseInt(u.searchParams.get('limit') || '20', 10)
|
|
223
|
+
const offset = parseInt(u.searchParams.get('offset') || '0', 10)
|
|
224
|
+
const data = getMoaHistory(limit, offset)
|
|
225
|
+
writeJson(res, 200, { ok: true, ...data })
|
|
226
|
+
} catch (err) {
|
|
227
|
+
writeJson(res, 500, { ok: false, error: err?.message || String(err) })
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
})
|
|
231
|
+
}, 'dsh-moa: history route')
|
|
232
|
+
|
|
233
|
+
// Route: /dsh-moa/leaderboard
|
|
234
|
+
ctx.effect(() => {
|
|
235
|
+
return ctx.webServer.register({
|
|
236
|
+
kind: 'exact',
|
|
237
|
+
path: '/dsh-moa/leaderboard',
|
|
238
|
+
handler: async (req, res) => {
|
|
239
|
+
if (req.method !== 'GET') {
|
|
240
|
+
writeJson(res, 405, { ok: false, error: 'GET required' })
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
const url = new URL(req.url || '', 'http://127.0.0.1')
|
|
245
|
+
const preset = url.searchParams.get('preset') || null
|
|
246
|
+
const format = url.searchParams.get('format') || 'json'
|
|
247
|
+
|
|
248
|
+
if (format === 'csv') {
|
|
249
|
+
const csv = exportMoaHistory(undefined, { format: 'csv', preset })
|
|
250
|
+
res.writeHead(200, {
|
|
251
|
+
'Content-Type': 'text/csv; charset=utf-8',
|
|
252
|
+
'Content-Disposition': 'attachment; filename="moa-leaderboard.csv"',
|
|
253
|
+
})
|
|
254
|
+
res.end(csv)
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const data = getMoaLeaderboard(undefined, { preset })
|
|
259
|
+
writeJson(res, 200, { ok: true, ...data })
|
|
260
|
+
} catch (err) {
|
|
261
|
+
writeJson(res, 500, { ok: false, error: err?.message || String(err) })
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
})
|
|
265
|
+
}, 'dsh-moa: leaderboard route')
|
|
266
|
+
|
|
267
|
+
// Route: /dsh-moa/promote (Candidate Override Action)
|
|
268
|
+
ctx.effect(() => {
|
|
269
|
+
return ctx.webServer.register({
|
|
270
|
+
kind: 'exact',
|
|
271
|
+
path: '/dsh-moa/promote',
|
|
272
|
+
handler: async (req, res) => {
|
|
273
|
+
if (req.method !== 'POST') {
|
|
274
|
+
writeJson(res, 405, { ok: false, error: 'POST required' })
|
|
275
|
+
return
|
|
276
|
+
}
|
|
277
|
+
if (!isSafeWriteRequest(req)) {
|
|
278
|
+
writeJson(res, 403, { ok: false, error: 'Forbidden: cross-site request rejected' })
|
|
279
|
+
return
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
const raw = await readBody(req)
|
|
283
|
+
const body = JSON.parse(raw || '{}')
|
|
284
|
+
const candidateIndex = parseInt(body?.candidateIndex, 10)
|
|
285
|
+
if (isNaN(candidateIndex) || candidateIndex < 1) {
|
|
286
|
+
writeJson(res, 400, { ok: false, error: 'Valid candidateIndex required (>= 1)' })
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
const cwd = body?.cwd || process.cwd()
|
|
290
|
+
const promotedFiles = await promoteCandidateWorkspace(cwd, candidateIndex, { keepMoa: true })
|
|
291
|
+
writeJson(res, 200, { ok: true, candidateIndex, promotedFiles })
|
|
292
|
+
} catch (err) {
|
|
293
|
+
writeJson(res, 500, { ok: false, error: err?.message || String(err) })
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
})
|
|
297
|
+
}, 'dsh-moa: promote candidate route')
|
|
298
|
+
|
|
299
|
+
// Route: /dsh-moa/history/export
|
|
300
|
+
ctx.effect(() => {
|
|
301
|
+
return ctx.webServer.register({
|
|
302
|
+
kind: 'exact',
|
|
303
|
+
path: '/dsh-moa/history/export',
|
|
304
|
+
handler: async (req, res) => {
|
|
305
|
+
if (req.method !== 'GET') {
|
|
306
|
+
writeJson(res, 405, { ok: false, error: 'GET required' })
|
|
307
|
+
return
|
|
308
|
+
}
|
|
309
|
+
try {
|
|
310
|
+
const url = new URL(req.url || '', 'http://127.0.0.1')
|
|
311
|
+
const preset = url.searchParams.get('preset') || null
|
|
312
|
+
const format = url.searchParams.get('format') || 'json'
|
|
313
|
+
const data = exportMoaHistory(undefined, { format, preset })
|
|
314
|
+
|
|
315
|
+
if (format === 'csv') {
|
|
316
|
+
res.writeHead(200, {
|
|
317
|
+
'Content-Type': 'text/csv; charset=utf-8',
|
|
318
|
+
'Content-Disposition': 'attachment; filename="moa-history.csv"',
|
|
319
|
+
})
|
|
320
|
+
res.end(data)
|
|
321
|
+
return
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
res.writeHead(200, {
|
|
325
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
326
|
+
'Content-Disposition': 'attachment; filename="moa-history.json"',
|
|
327
|
+
})
|
|
328
|
+
res.end(data)
|
|
329
|
+
} catch (err) {
|
|
330
|
+
writeJson(res, 500, { ok: false, error: err?.message || String(err) })
|
|
331
|
+
}
|
|
332
|
+
},
|
|
333
|
+
})
|
|
334
|
+
}, 'dsh-moa: history export route')
|
|
335
|
+
|
|
336
|
+
// Route: /dsh-moa/runs/<id> (run replay by id)
|
|
337
|
+
ctx.effect(() => {
|
|
338
|
+
return ctx.webServer.register({
|
|
339
|
+
kind: 'prefix',
|
|
340
|
+
path: '/dsh-moa/runs/',
|
|
341
|
+
handler: (req, res) => {
|
|
342
|
+
if (req.method !== 'GET') {
|
|
343
|
+
writeJson(res, 405, { ok: false, error: 'GET required' })
|
|
344
|
+
return
|
|
345
|
+
}
|
|
346
|
+
const urlPath = req.url.split('?')[0]
|
|
347
|
+
const parts = urlPath.split('/').filter(Boolean)
|
|
348
|
+
const runId = parts[2] || ''
|
|
349
|
+
const run = runId ? getMoaRunById(runId) : null
|
|
350
|
+
if (!run) {
|
|
351
|
+
writeJson(res, 404, { ok: false, error: 'Run not found' })
|
|
352
|
+
return
|
|
353
|
+
}
|
|
354
|
+
writeJson(res, 200, { ok: true, run })
|
|
355
|
+
},
|
|
356
|
+
})
|
|
357
|
+
}, 'dsh-moa: run by id route')
|
|
358
|
+
|
|
359
|
+
// Route: /dsh-moa/run
|
|
360
|
+
ctx.effect(() => {
|
|
361
|
+
return ctx.webServer.register({
|
|
362
|
+
kind: 'exact',
|
|
363
|
+
path: '/dsh-moa/run',
|
|
364
|
+
handler: async (req, res) => {
|
|
365
|
+
if (req.method !== 'POST') {
|
|
366
|
+
writeJson(res, 405, { ok: false, error: 'POST required' })
|
|
367
|
+
return
|
|
368
|
+
}
|
|
369
|
+
if (!isSafeWriteRequest(req)) {
|
|
370
|
+
writeJson(res, 403, { ok: false, error: 'Forbidden: cross-site request rejected' })
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
try {
|
|
375
|
+
const raw = await readBody(req)
|
|
376
|
+
const payload = JSON.parse(raw)
|
|
377
|
+
const prompt = payload.prompt || ''
|
|
378
|
+
if (!prompt.trim()) {
|
|
379
|
+
writeJson(res, 400, { ok: false, error: 'Empty prompt' })
|
|
380
|
+
return
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const cfg = live()
|
|
384
|
+
if (cfg.enabled === false) {
|
|
385
|
+
writeJson(res, 400, { ok: false, error: 'MoA is disabled in settings' })
|
|
386
|
+
return
|
|
387
|
+
}
|
|
388
|
+
const presetName = payload.preset || cfg.default_preset || 'default'
|
|
389
|
+
const preset = (cfg.presets || []).find((p) => p.name === presetName) || cfg.presets?.[0]
|
|
390
|
+
|
|
391
|
+
const result = await runMoAPipeline({
|
|
392
|
+
userPrompt: prompt,
|
|
393
|
+
messages: payload.messages || [],
|
|
394
|
+
preset,
|
|
395
|
+
callLlm,
|
|
396
|
+
cwd: payload.cwd || process.cwd(),
|
|
397
|
+
prices: cfg.prices || {},
|
|
398
|
+
liveCanvas,
|
|
399
|
+
})
|
|
400
|
+
|
|
401
|
+
if (result?.skippedFiles > 0) {
|
|
402
|
+
ctx.logger?.warn?.(`[dsh-moa] Workspace scan skipped ${result.skippedFiles} file(s): ${result.skippedList.join(', ')}`)
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
writeJson(res, 200, { ok: true, ...result })
|
|
406
|
+
} catch (err) {
|
|
407
|
+
writeJson(res, 500, { ok: false, error: err?.message || String(err) })
|
|
408
|
+
}
|
|
409
|
+
},
|
|
410
|
+
})
|
|
411
|
+
}, 'dsh-moa: run pipeline route')
|
|
412
|
+
}
|
package/lib/updater.js
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// lib/updater.js — Host-side one-click updater for @goodandready/dsh-moa
|
|
2
|
+
// Implements canonical DSH plugin-updater specification.
|
|
3
|
+
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
6
|
+
import { readFile } from 'node:fs/promises';
|
|
7
|
+
import { homedir } from 'node:os';
|
|
8
|
+
import { basename, dirname, isAbsolute, resolve } from 'node:path';
|
|
9
|
+
|
|
10
|
+
const UPDATE_HEADER = 'x-dsh-plugin-update';
|
|
11
|
+
const UPDATE_TIMEOUT_MS = 10 * 60_000;
|
|
12
|
+
const VERSION_CACHE_MS = 5 * 60_000;
|
|
13
|
+
let latestCache;
|
|
14
|
+
|
|
15
|
+
function header(request, name) {
|
|
16
|
+
const value = request?.headers?.[name];
|
|
17
|
+
return Array.isArray(value) ? value[0] : value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function isLoopback(value) {
|
|
21
|
+
const address = value?.toLowerCase().replace(/^\[|\]$/g, '');
|
|
22
|
+
return address === 'localhost' || address === 'localhost.' || address === '::1'
|
|
23
|
+
|| address?.startsWith('127.') === true
|
|
24
|
+
|| address?.startsWith('::ffff:127.') === true;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function isTrustedUpdateRequest(request) {
|
|
28
|
+
if (header(request, UPDATE_HEADER) !== '1') return false;
|
|
29
|
+
if (!isLoopback(request.socket?.remoteAddress)) return false;
|
|
30
|
+
const site = header(request, 'sec-fetch-site');
|
|
31
|
+
if (site !== undefined && site !== 'same-origin') return false;
|
|
32
|
+
const origin = header(request, 'origin');
|
|
33
|
+
const host = header(request, 'host');
|
|
34
|
+
if (origin === undefined || host === undefined) return false;
|
|
35
|
+
try {
|
|
36
|
+
const url = new URL(origin);
|
|
37
|
+
return (url.protocol === 'http:' || url.protocol === 'https:')
|
|
38
|
+
&& isLoopback(url.hostname) && url.host === host;
|
|
39
|
+
} catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** General safe write check for plugin write endpoints (CSRF / Cross-Site protection) */
|
|
45
|
+
export function isSafeWriteRequest(request) {
|
|
46
|
+
const site = header(request, 'sec-fetch-site');
|
|
47
|
+
if (site === 'cross-site') return false;
|
|
48
|
+
const origin = header(request, 'origin');
|
|
49
|
+
const host = header(request, 'host');
|
|
50
|
+
if (origin) {
|
|
51
|
+
try {
|
|
52
|
+
const url = new URL(origin);
|
|
53
|
+
if (host && url.host !== host) return false;
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function validProfileName(value) {
|
|
62
|
+
return typeof value === 'string' && /^[0-9A-Za-z_-]+$/.test(value);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function profileNameFromArgv(argv) {
|
|
66
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
67
|
+
const arg = argv[index];
|
|
68
|
+
if (arg === '--profile' && index + 1 < argv.length) return argv[index + 1];
|
|
69
|
+
if (arg.startsWith('--profile=')) return arg.slice('--profile='.length);
|
|
70
|
+
}
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function findDshCliEntry() {
|
|
75
|
+
const entry = process.argv[1];
|
|
76
|
+
if (typeof entry !== 'string' || entry === '') return undefined;
|
|
77
|
+
for (let directory = dirname(entry); ; directory = dirname(directory)) {
|
|
78
|
+
const manifestPath = resolve(directory, 'package.json');
|
|
79
|
+
if (existsSync(manifestPath)) {
|
|
80
|
+
try {
|
|
81
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
82
|
+
const bin = typeof manifest.bin === 'string'
|
|
83
|
+
? manifest.bin
|
|
84
|
+
: typeof manifest.bin === 'object' && manifest.bin !== null
|
|
85
|
+
? manifest.bin.dsh
|
|
86
|
+
: undefined;
|
|
87
|
+
if (manifest.name === '@deepseek-ai/dsh' && typeof bin === 'string'
|
|
88
|
+
&& !isAbsolute(bin) && resolve(directory, bin) === resolve(entry)) return entry;
|
|
89
|
+
} catch {
|
|
90
|
+
// Continue searching parent package directories.
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const parent = dirname(directory);
|
|
94
|
+
if (parent === directory) return undefined;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function runtime() {
|
|
99
|
+
const profileDir = resolve(process.env.DSH_PROFILE_DIR
|
|
100
|
+
?? resolve(homedir(), '.dsh', 'profiles', 'web'));
|
|
101
|
+
const selected = profileNameFromArgv(process.argv);
|
|
102
|
+
const profileName = validProfileName(selected)
|
|
103
|
+
? selected
|
|
104
|
+
: validProfileName(basename(profileDir)) ? basename(profileDir) : 'web';
|
|
105
|
+
const cliEntry = findDshCliEntry();
|
|
106
|
+
return cliEntry === undefined ? { profileName, profileDir } : { profileName, profileDir, cliEntry };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function parseSemver(value) {
|
|
110
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
|
|
111
|
+
if (match === null) return undefined;
|
|
112
|
+
return {
|
|
113
|
+
core: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
114
|
+
prerelease: match[4]?.split('.') ?? [],
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function comparePrerelease(left, right) {
|
|
119
|
+
if (left.length === 0 || right.length === 0) return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
|
|
120
|
+
const length = Math.max(left.length, right.length);
|
|
121
|
+
for (let index = 0; index < length; index += 1) {
|
|
122
|
+
const a = left[index];
|
|
123
|
+
const b = right[index];
|
|
124
|
+
if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1;
|
|
125
|
+
if (a === b) continue;
|
|
126
|
+
const aNumeric = /^\d+$/.test(a);
|
|
127
|
+
const bNumeric = /^\d+$/.test(b);
|
|
128
|
+
if (aNumeric && bNumeric) {
|
|
129
|
+
const aNumber = BigInt(a);
|
|
130
|
+
const bNumber = BigInt(b);
|
|
131
|
+
if (aNumber !== bNumber) return aNumber > bNumber ? 1 : -1;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
|
|
135
|
+
return a > b ? 1 : -1;
|
|
136
|
+
}
|
|
137
|
+
return 0;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function isNewerVersion(currentValue, candidateValue) {
|
|
141
|
+
const current = parseSemver(currentValue);
|
|
142
|
+
const candidate = parseSemver(candidateValue);
|
|
143
|
+
if (current === undefined || candidate === undefined) return false;
|
|
144
|
+
for (let index = 0; index < 3; index += 1) {
|
|
145
|
+
if (candidate.core[index] !== current.core[index]) return candidate.core[index] > current.core[index];
|
|
146
|
+
}
|
|
147
|
+
return comparePrerelease(candidate.prerelease, current.prerelease) > 0;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function latestVersion(packageName, registry) {
|
|
151
|
+
if (latestCache?.packageName === packageName && latestCache.registry === registry && Date.now() < latestCache.expiresAt) return latestCache.version;
|
|
152
|
+
try {
|
|
153
|
+
const response = await fetch(`${registry.replace(/\/$/, '')}/${encodeURIComponent(packageName)}/latest`, {
|
|
154
|
+
signal: AbortSignal.timeout(8_000),
|
|
155
|
+
});
|
|
156
|
+
if (!response.ok) return undefined;
|
|
157
|
+
const value = await response.json();
|
|
158
|
+
if (typeof value.version !== 'string' || value.version === '') return undefined;
|
|
159
|
+
latestCache = { packageName, registry, version: value.version, expiresAt: Date.now() + VERSION_CACHE_MS };
|
|
160
|
+
return value.version;
|
|
161
|
+
} catch {
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function currentVersion(manifestUrl) {
|
|
167
|
+
const value = JSON.parse(await readFile(manifestUrl, 'utf8'));
|
|
168
|
+
if (typeof value.version !== 'string' || value.version === '') throw new Error('Cannot read current plugin version.');
|
|
169
|
+
return value.version;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function getUpdateStatus(options, target = runtime()) {
|
|
173
|
+
const current = await currentVersion(options.manifestUrl);
|
|
174
|
+
const latest = await latestVersion(options.packageName, options.registry ?? 'https://registry.npmjs.org');
|
|
175
|
+
return {
|
|
176
|
+
packageName: options.packageName,
|
|
177
|
+
currentVersion: current,
|
|
178
|
+
...(latest === undefined ? {} : { latestVersion: latest }),
|
|
179
|
+
latestCheckFailed: latest === undefined,
|
|
180
|
+
updateAvailable: latest !== undefined && isNewerVersion(current, latest),
|
|
181
|
+
profileName: target.profileName,
|
|
182
|
+
canAutoUpdate: target.cliEntry !== undefined,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function installExact(target, packageSpec, options) {
|
|
187
|
+
if (target.cliEntry === undefined) throw new Error('Automatic update is unavailable in this runtime.');
|
|
188
|
+
await new Promise((resolvePromise, reject) => {
|
|
189
|
+
// Note: Respect strict ecosystem quarantine policy without age bypass
|
|
190
|
+
const args = [
|
|
191
|
+
target.cliEntry, 'plugin', '--profile', target.profileName, 'add',
|
|
192
|
+
packageSpec,
|
|
193
|
+
`--registry=${options.registry ?? 'https://registry.npmjs.org/'}`,
|
|
194
|
+
];
|
|
195
|
+
const child = spawn(process.execPath, args, {
|
|
196
|
+
cwd: target.profileDir,
|
|
197
|
+
windowsHide: true,
|
|
198
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
199
|
+
env: { ...process.env, NO_COLOR: '1' },
|
|
200
|
+
});
|
|
201
|
+
let detail = '';
|
|
202
|
+
child.stdout?.on('data', chunk => { detail = (detail + String(chunk)).slice(-4_000); });
|
|
203
|
+
child.stderr?.on('data', chunk => { detail = (detail + String(chunk)).slice(-4_000); });
|
|
204
|
+
const timer = setTimeout(() => {
|
|
205
|
+
child.kill();
|
|
206
|
+
reject(new Error('Update timed out; use the normal DSH update flow.'));
|
|
207
|
+
}, UPDATE_TIMEOUT_MS);
|
|
208
|
+
child.once('error', error => { clearTimeout(timer); reject(error); });
|
|
209
|
+
child.once('exit', code => {
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
if (code === 0) resolvePromise();
|
|
212
|
+
else reject(new Error(detail.trim() || `Update exited with code ${String(code)}.`));
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function json(response, statusCode, value) {
|
|
218
|
+
response.writeHead(statusCode, {
|
|
219
|
+
'content-type': 'application/json; charset=utf-8',
|
|
220
|
+
'cache-control': 'no-store',
|
|
221
|
+
});
|
|
222
|
+
response.end(JSON.stringify(value));
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function registerPluginUpdater(ctx, options) {
|
|
226
|
+
const host = ctx;
|
|
227
|
+
let installing = false;
|
|
228
|
+
return host.webServer.register({
|
|
229
|
+
kind: 'exact',
|
|
230
|
+
path: options.endpoint,
|
|
231
|
+
handler: async (request, response) => {
|
|
232
|
+
try {
|
|
233
|
+
const target = runtime();
|
|
234
|
+
if (request.method === 'GET' || request.method === 'HEAD') {
|
|
235
|
+
const payload = await getUpdateStatus(options, target);
|
|
236
|
+
response.writeHead(200, {
|
|
237
|
+
'content-type': 'application/json; charset=utf-8',
|
|
238
|
+
'cache-control': 'no-store',
|
|
239
|
+
});
|
|
240
|
+
response.end(request.method === 'HEAD' ? undefined : JSON.stringify(payload));
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (request.method !== 'POST') {
|
|
244
|
+
response.writeHead(405, { allow: 'GET, HEAD, POST' });
|
|
245
|
+
response.end();
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (!isTrustedUpdateRequest(request)) {
|
|
249
|
+
json(response, 403, { error: 'Rejected non-local or cross-origin update request.' });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (installing) {
|
|
253
|
+
json(response, 409, { error: 'This plugin is already updating.' });
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
installing = true;
|
|
257
|
+
try {
|
|
258
|
+
const before = await getUpdateStatus(options, target);
|
|
259
|
+
if (before.latestVersion === undefined) {
|
|
260
|
+
json(response, 503, { error: 'The latest version is temporarily unavailable.' });
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (!before.updateAvailable) {
|
|
264
|
+
json(response, 200, before);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
await installExact(target, `${options.packageName}@${before.latestVersion}`, options);
|
|
268
|
+
json(response, 200, {
|
|
269
|
+
...before,
|
|
270
|
+
updatedVersion: before.latestVersion,
|
|
271
|
+
restartRequired: true,
|
|
272
|
+
});
|
|
273
|
+
} finally {
|
|
274
|
+
installing = false;
|
|
275
|
+
}
|
|
276
|
+
} catch (error) {
|
|
277
|
+
ctx.logger?.warn?.(`plugin updater failed: ${String(error)}`);
|
|
278
|
+
json(response, 503, { error: 'Plugin update failed; see server logs.' });
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
}
|