@alequet/dsh-patchkeeper 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +78 -2
- package/bin/cli.mjs +905 -0
- package/client.js +497 -0
- package/cordis.patch.yml +6 -0
- package/index.js +280 -0
- package/package.json +41 -4
package/index.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-patchkeeper — cordis 插件壳(常驻挂载模式)。
|
|
3
|
+
*
|
|
4
|
+
* 生命周期(0.5.0 起改为常驻):
|
|
5
|
+
* DSH 启动时先用 createRuntimeResolution 冻结包路径快照,再加载插件——
|
|
6
|
+
* 所以补丁必须在进程启动前就挂在磁盘上,「退出时回退」会让补丁永远赶不上快照。
|
|
7
|
+
* 挂载常驻:启动时只做保底清除(崩溃残留/升级替换的修复)+ 版本匹配检查补挂。
|
|
8
|
+
* 升级安全由结构保证:原版完整备份在数据目录 shadows/orig/,node_modules 条目只是
|
|
9
|
+
* 一根软链,pnpm/安装器随时可以用新包替换它(保底清除会识别并丢弃过时备份)。
|
|
10
|
+
*
|
|
11
|
+
* UI 通道:注册 /dsh-patchkeeper-api
|
|
12
|
+
* GET → 实时清单(插件管理页的徽章/提示卡/管理台取数)
|
|
13
|
+
* POST {action, name} → adapt / extract / revert / enable / disable / note
|
|
14
|
+
*/
|
|
15
|
+
import { spawnSync } from 'node:child_process'
|
|
16
|
+
import fsSync from 'node:fs'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import { fileURLToPath } from 'node:url'
|
|
19
|
+
|
|
20
|
+
export const name = 'dsh-patchkeeper'
|
|
21
|
+
// 本进程(≈冻结快照)时刻:快照之后挂载的补丁要下次启动才进运行代码
|
|
22
|
+
const BOOT_TS = Date.now()
|
|
23
|
+
// cordis 规矩:访问 ctx 上的服务必须先在这里声明;声明后服务不可用时仍为 null(参照 dsh-meme 同款写法)
|
|
24
|
+
export const inject = ['webServer', 'llm']
|
|
25
|
+
|
|
26
|
+
const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'cli.mjs')
|
|
27
|
+
const DATA_DIR = process.env.DSH_PATCHKEEPER_HOME || path.join(process.env.HOME || '~', '.dsh', 'patch-manager')
|
|
28
|
+
const STATE_FILE_PATH = path.join(DATA_DIR, 'state.json')
|
|
29
|
+
const ROUTE = '/dsh-patchkeeper-api'
|
|
30
|
+
|
|
31
|
+
function runCli(logger, args, timeoutMs = 180_000) {
|
|
32
|
+
let res
|
|
33
|
+
try {
|
|
34
|
+
res = spawnSync(process.execPath, [CLI, ...args, '--json'], {
|
|
35
|
+
encoding: 'utf8',
|
|
36
|
+
timeout: timeoutMs,
|
|
37
|
+
})
|
|
38
|
+
} catch (err) {
|
|
39
|
+
logger.warn(`patchkeeper ${args[0]} 执行失败: ${err.message}`)
|
|
40
|
+
return null
|
|
41
|
+
}
|
|
42
|
+
if (res.status !== 0 && res.status !== 2) {
|
|
43
|
+
logger.warn(`patchkeeper ${args[0]} 异常退出 (${res.status}): ${(res.stderr || '').slice(0, 500)}`)
|
|
44
|
+
return null
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(res.stdout)
|
|
48
|
+
} catch {
|
|
49
|
+
logger.warn(`patchkeeper ${args[0]} 输出无法解析: ${(res.stdout || '').slice(0, 300)}`)
|
|
50
|
+
return null
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function applyPatches(logger) {
|
|
55
|
+
const out = runCli(logger, ['apply'])
|
|
56
|
+
if (!out) return
|
|
57
|
+
const applied = out.results.filter((r) => r.status === 'applied-now')
|
|
58
|
+
const skipped = out.results.filter((r) => r.status === 'version-mismatch')
|
|
59
|
+
const bad = out.results.filter((r) => ['conflict', 'missing-target', 'apply-failed'].includes(r.status))
|
|
60
|
+
if (applied.length) {
|
|
61
|
+
logger.info(`已为 ${applied.length} 个插件热打补丁: ${applied.map((r) => r.name).join(', ')}`)
|
|
62
|
+
}
|
|
63
|
+
if (skipped.length) {
|
|
64
|
+
logger.info(
|
|
65
|
+
`${skipped.length} 个补丁因版本不匹配未加载: ${skipped.map((r) => `${r.name} 补丁${r.patchVersion}/已装${r.installedVersion}`).join(', ')}——请到插件管理页处理`,
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
for (const r of bad) {
|
|
69
|
+
logger.warn(`补丁未打上: ${r.name} [${r.status}](补丁版本 ${r.patchVersion} / 已装 ${r.installedVersion ?? '无'})`)
|
|
70
|
+
}
|
|
71
|
+
return out.results
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// ---- AI 适配管线:版本失配 → 机械合 → 冲突交 AI → 成功则下次重启自动挂载;失败记录不再重试 ----
|
|
75
|
+
|
|
76
|
+
function readState() {
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(fsSync.readFileSync(STATE_FILE_PATH, 'utf8'))
|
|
79
|
+
} catch {
|
|
80
|
+
return {}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function callAiForPatch(ctx, contextPack) {
|
|
85
|
+
const filesText = Object.entries(contextPack.files)
|
|
86
|
+
.map(([f, info]) => `### 文件 ${f}\n没打进去的 hunk(旧版语境):\n\`\`\`\n${info.rej}\n\`\`\`\n该文件的**新版**内容:\n\`\`\`\n${info_truncate(f, info.newContent)}\n\`\`\``)
|
|
87
|
+
.join('\n\n')
|
|
88
|
+
const prompt = `你是补丁适配器。插件 ${contextPack.name} 从 ${contextPack.fromVersion} 升级到 ${contextPack.toVersion},旧补丁有几个文件打不进新代码了。
|
|
89
|
+
|
|
90
|
+
下面按文件给出:没打进去的 hunk(旧版语境)+ 该文件的新版内容。请为每个文件输出能直接打进新版本的 unified diff(路径前缀 a/ b/,patch -p1 可用,diff 头格式:diff -ruN a/<路径> b/<路径>)。只输出补丁本体,不要任何解释。
|
|
91
|
+
|
|
92
|
+
${filesText}`
|
|
93
|
+
const call = await ctx.llm.prepareCall({ maxTokens: 8192 })
|
|
94
|
+
let text = ''
|
|
95
|
+
const stream = call.stream({
|
|
96
|
+
...call.config,
|
|
97
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
98
|
+
sessionId: 'patchkeeper-adapt',
|
|
99
|
+
purpose: 'patch-adapt',
|
|
100
|
+
})
|
|
101
|
+
for await (const chunk of stream) {
|
|
102
|
+
if (chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text
|
|
103
|
+
}
|
|
104
|
+
return text
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function info_truncate(f, content) {
|
|
108
|
+
if (content == null) return '(该文件在新版中不存在)'
|
|
109
|
+
const MAX = 40000
|
|
110
|
+
return content.length > MAX ? content.slice(0, MAX) + '\n…(文件过大已截断)' : content
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// 从 AI 回复里抠出补丁本体(容错 markdown 围栏)
|
|
114
|
+
function extractPatch(text) {
|
|
115
|
+
const fence = /```(?:diff|patch)?\s*\n([\s\S]*?)```/.exec(text)
|
|
116
|
+
let body = fence ? fence[1] : text
|
|
117
|
+
const start = body.search(/^(diff ---|--- a\/)/m)
|
|
118
|
+
return start >= 0 ? body.slice(start) : null
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function adaptPipeline(ctx, logger, results) {
|
|
122
|
+
const mismatched = results.filter((r) => r.status === 'version-mismatch' && r.enabled !== false)
|
|
123
|
+
if (!mismatched.length) return
|
|
124
|
+
const state = readState()
|
|
125
|
+
const records = state.adapt || {}
|
|
126
|
+
for (const r of mismatched) {
|
|
127
|
+
const key = `${r.name}@${r.installedVersion}`
|
|
128
|
+
if (records[key]) continue // 适配过(成功或失败)都不重复,失败留人工
|
|
129
|
+
logger.info(`检测到版本失配:${r.name} 补丁${r.patchVersion} ≠ 已装${r.installedVersion},启动 AI 适配…`)
|
|
130
|
+
records[key] = { outcome: 'running', at: new Date().toISOString() }
|
|
131
|
+
fsSync.writeFileSync(STATE_FILE_PATH, JSON.stringify({ ...state, adapt: records }, null, 2))
|
|
132
|
+
try {
|
|
133
|
+
const auto = runCli(logger, ['adapt-auto', '--pkg', r.name, '--to', r.installedVersion])
|
|
134
|
+
if (auto?.outcome === 'auto-merged') {
|
|
135
|
+
records[key] = { outcome: 'adapted', mode: 'auto', at: new Date().toISOString() }
|
|
136
|
+
logger.info(`${r.name} 补丁机械适配成功(${r.patchVersion} → ${r.installedVersion}),重启后自动挂载`)
|
|
137
|
+
} else if (auto?.outcome === 'needs-ai') {
|
|
138
|
+
const contextPack = JSON.parse(fsSync.readFileSync(path.join(auto.contextDir, 'context.json'), 'utf8'))
|
|
139
|
+
const aiText = await callAiForPatch(ctx, contextPack)
|
|
140
|
+
const patchText = extractPatch(aiText)
|
|
141
|
+
if (!patchText) throw new Error('AI 回复里没有可用的补丁')
|
|
142
|
+
fsSync.writeFileSync(path.join(auto.contextDir, 'ai.patch'), patchText)
|
|
143
|
+
const applied = runCli(logger, ['adapt-apply', '--pkg', r.name, '--to', r.installedVersion])
|
|
144
|
+
if (applied?.outcome !== 'adapted') throw new Error(`AI 补丁验证失败: ${applied?.outcome || 'unknown'} ${applied?.error || ''}`)
|
|
145
|
+
records[key] = { outcome: 'adapted', mode: 'ai', at: new Date().toISOString() }
|
|
146
|
+
logger.info(`${r.name} 补丁 AI 适配成功(${r.patchVersion} → ${r.installedVersion}),重启后自动挂载`)
|
|
147
|
+
} else {
|
|
148
|
+
throw new Error(`机械合并未启动: ${auto?.outcome || 'unknown'} ${auto?.error || ''}`)
|
|
149
|
+
}
|
|
150
|
+
} catch (err) {
|
|
151
|
+
records[key] = { outcome: 'ai-failed', at: new Date().toISOString(), error: String(err?.message || err).slice(0, 500) }
|
|
152
|
+
logger.warn(`${r.name} AI 适配失败:${err?.message || err}——已记录,不再自动重试,请人工适配`)
|
|
153
|
+
}
|
|
154
|
+
fsSync.writeFileSync(STATE_FILE_PATH, JSON.stringify({ ...readState(), adapt: records }, null, 2))
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// 挂载变更后尝试借插件管理器的机器即时生效:
|
|
159
|
+
// 刷新 resolution 快照 + HMR 重载。任一环节缺席/失败就退回「重启后生效」。
|
|
160
|
+
async function tryLiveReload(ctx, logger) {
|
|
161
|
+
try {
|
|
162
|
+
const hmr = typeof ctx.get === 'function' ? ctx.get('hmr') : null
|
|
163
|
+
const packages = typeof ctx.get === 'function' ? ctx.get('pluginPackages') : null
|
|
164
|
+
if (!hmr || typeof hmr.runExclusive !== 'function' || typeof hmr.reconcileProfile !== 'function') return 'restart-required'
|
|
165
|
+
if (packages?.resolution !== undefined && typeof packages.refresh === 'function') {
|
|
166
|
+
try {
|
|
167
|
+
await packages.refresh()
|
|
168
|
+
} catch (err) {
|
|
169
|
+
if (!String(err?.name || err).includes('ResolutionRestartRequired')) throw err
|
|
170
|
+
return 'restart-required'
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
await hmr.runExclusive(() => hmr.reconcileProfile([]))
|
|
174
|
+
return 'reloaded'
|
|
175
|
+
} catch (err) {
|
|
176
|
+
logger.warn(`热重载未完成(重启后生效): ${err?.message || err}`)
|
|
177
|
+
return 'restart-required'
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ---- UI HTTP 通道 ----
|
|
182
|
+
|
|
183
|
+
function sendJson(res, code, obj) {
|
|
184
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' })
|
|
185
|
+
res.end(JSON.stringify(obj))
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function readBody(req) {
|
|
189
|
+
return new Promise((resolve) => {
|
|
190
|
+
let data = ''
|
|
191
|
+
req.on('data', (c) => {
|
|
192
|
+
data += c
|
|
193
|
+
if (data.length > 64 * 1024) req.destroy()
|
|
194
|
+
})
|
|
195
|
+
req.on('end', () => resolve(data))
|
|
196
|
+
req.on('error', () => resolve(''))
|
|
197
|
+
})
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function registerApi(ctx, logger) {
|
|
201
|
+
const webServer = ctx.webServer ?? ctx.get('webServer')
|
|
202
|
+
if (!webServer) {
|
|
203
|
+
logger.info('webServer 服务不可用,插件管理页提示卡不生效(补丁功能本身不受影响)')
|
|
204
|
+
return
|
|
205
|
+
}
|
|
206
|
+
ctx.effect(() =>
|
|
207
|
+
webServer.register({
|
|
208
|
+
kind: 'prefix',
|
|
209
|
+
path: ROUTE,
|
|
210
|
+
async handler(req, res) {
|
|
211
|
+
try {
|
|
212
|
+
if (req.method === 'GET') {
|
|
213
|
+
const out = runCli(logger, ['list'])
|
|
214
|
+
return sendJson(res, 200, { ...(out || { patches: [] }), bootTs: BOOT_TS })
|
|
215
|
+
}
|
|
216
|
+
if (req.method === 'POST') {
|
|
217
|
+
let payload = {}
|
|
218
|
+
try {
|
|
219
|
+
payload = JSON.parse(await readBody(req))
|
|
220
|
+
} catch {
|
|
221
|
+
return sendJson(res, 400, { error: 'bad json' })
|
|
222
|
+
}
|
|
223
|
+
const { action, name: pkgName, note } = payload
|
|
224
|
+
if (!pkgName || typeof pkgName !== 'string') return sendJson(res, 400, { error: 'missing name' })
|
|
225
|
+
let out
|
|
226
|
+
if (action === 'adapt') out = runCli(logger, ['apply', '--force', '--pkg', pkgName])
|
|
227
|
+
else if (action === 'extract') out = runCli(logger, ['extract', '--pkg', pkgName])
|
|
228
|
+
else if (action === 'revert') out = runCli(logger, ['revert', '--pkg', pkgName])
|
|
229
|
+
else if (action === 'enable') out = runCli(logger, ['enable', '--pkg', pkgName])
|
|
230
|
+
else if (action === 'disable') out = runCli(logger, ['disable', '--pkg', pkgName])
|
|
231
|
+
else if (action === 'note') out = runCli(logger, ['note', '--pkg', pkgName, String(payload.note ?? '')])
|
|
232
|
+
else if (action === 'adapt-retry') {
|
|
233
|
+
// 人工点重试:清掉该版本的适配记录并重跑管线
|
|
234
|
+
const cur = runCli(logger, ['status', '--pkg', pkgName])
|
|
235
|
+
const row = cur?.results?.[0]
|
|
236
|
+
if (!row) return sendJson(res, 404, { error: 'patch not found' })
|
|
237
|
+
const st = readState()
|
|
238
|
+
const adapt = { ...(st.adapt || {}) }
|
|
239
|
+
delete adapt[`${pkgName}@${row.installedVersion}`]
|
|
240
|
+
fsSync.writeFileSync(STATE_FILE_PATH, JSON.stringify({ ...st, adapt }, null, 2))
|
|
241
|
+
void adaptPipeline(ctx, logger, [row]).catch(() => {})
|
|
242
|
+
out = { command: 'adapt-retry', name: pkgName, started: true }
|
|
243
|
+
}
|
|
244
|
+
else return sendJson(res, 400, { error: 'unknown action' })
|
|
245
|
+
if (!out) return sendJson(res, 500, { error: 'cli failed' })
|
|
246
|
+
// 挂载类操作成功后,借插件管理器的 HMR 机器尝试即时生效
|
|
247
|
+
let reload = null
|
|
248
|
+
if (['enable', 'disable', 'adapt', 'revert'].includes(action)) {
|
|
249
|
+
reload = await tryLiveReload(ctx, logger)
|
|
250
|
+
}
|
|
251
|
+
// 操作后附上一份最新清单,前端直接刷新
|
|
252
|
+
const list = runCli(logger, ['list'])
|
|
253
|
+
return sendJson(res, 200, { action, result: out, reload, list })
|
|
254
|
+
}
|
|
255
|
+
sendJson(res, 405, { error: 'method not allowed' })
|
|
256
|
+
} catch (err) {
|
|
257
|
+
sendJson(res, 500, { error: String(err?.message || err) })
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
}),
|
|
261
|
+
)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export function apply(ctx, config = {}) {
|
|
265
|
+
if (config.enabled === false) return
|
|
266
|
+
const logger = ctx.logger('patchkeeper')
|
|
267
|
+
|
|
268
|
+
// 启动:保底清除 + 版本匹配补挂。挂载是常驻的——本进程的冻结快照已在用它们。
|
|
269
|
+
const results = applyPatches(logger)
|
|
270
|
+
// 版本失配的补丁:后台 AI 适配(不阻塞启动)
|
|
271
|
+
if (results?.some((r) => r.status === 'version-mismatch' && r.enabled !== false)) {
|
|
272
|
+
void adaptPipeline(ctx, logger, results).catch((err) => logger.warn(`AI 适配管线异常: ${err?.message || err}`))
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// UI 通道
|
|
276
|
+
registerApi(ctx, logger)
|
|
277
|
+
|
|
278
|
+
// 注意:退出时【不要】revert。冻结快照机制要求补丁在下次进程启动前就在磁盘上;
|
|
279
|
+
// 常驻挂载下,原版由 shadows/orig/ 备份保护,升级器替换软链后启动清理会自动归位。
|
|
280
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alequet/dsh-patchkeeper",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "【补丁总开关:禁用我会让所有插件补丁静默失效!】本地补丁管家:影子副本热挂载,原版永远干净,官方升级后自动重打。Local patch keeper for DSH plugins — disabling me silently disables every patch.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./index.js",
|
|
10
|
+
"./client": "./client.js",
|
|
11
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"index.js",
|
|
16
|
+
"client.js",
|
|
17
|
+
"cordis.patch.yml",
|
|
18
|
+
"bin/",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/alequet/dsh-patchkeeper.git"
|
|
25
|
+
},
|
|
26
|
+
"homepage": "https://github.com/alequet/dsh-patchkeeper#readme",
|
|
27
|
+
"keywords": [
|
|
28
|
+
"dsh",
|
|
29
|
+
"deepseek-harness",
|
|
30
|
+
"plugin",
|
|
31
|
+
"patch",
|
|
32
|
+
"patch-manager"
|
|
33
|
+
],
|
|
34
|
+
"dsh": {
|
|
35
|
+
"bundle": {
|
|
36
|
+
"patch": "./cordis.patch.yml"
|
|
37
|
+
},
|
|
38
|
+
"client": {
|
|
39
|
+
"platform": "web",
|
|
40
|
+
"inject": []
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|