dsh-dev-plan-presets 0.0.0-stage → 0.3.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/index.js ADDED
@@ -0,0 +1,703 @@
1
+ /**
2
+ * dsh-dev-plan-presets — Host 插件入口(0.3.0)
3
+ *
4
+ * 本包做四件事:
5
+ * 1. 用 ctx.agentPresets.register() 动态注册 dev-plan preset:Cordis 配置变更后插件重建,
6
+ * 新会话使用新代际,旧会话保留旧代际(registry 的既有语义)。
7
+ * 2. 维护四个委派工具(recon / review / scribe / develop)的配置真源;
8
+ * develop 的 agentPreset 取自宿主 agentPresets 目录中的任意可用 preset。
9
+ * 3. 吸收 dsh-subagent-model-pin 的模型守门:默认只管理 dev-plan 父会话的子代理,
10
+ * guardAllSubagents=true 时恢复全局子代理守门;创建时选路由、agent/pre-step 逐步核查、
11
+ * 越界在发请求前 reject + cancel + 通知父会话。
12
+ * 4. 暴露 /plugins/dev-plan-presets/state 与 /config 两个 HTTP 路由,
13
+ * 供 Client 设置页读取预设目录、模型目录、回退原因、越界记录,并通过 configEditor 写回配置。
14
+ *
15
+ * 运行期不 import js-yaml,也不 import @deepseek-ai/* 包:link 安装时插件目录解析不到宿主包。
16
+ * 所有注册/监听都通过 ctx.effect / ctx.on 清理;动态 preset 的 disposer 也交还给 effect。
17
+ */
18
+
19
+ import {
20
+ Config,
21
+ normalizeSettings,
22
+ routeOf,
23
+ validateSettings,
24
+ } from './settings.js'
25
+ import {
26
+ DEEP_PTC_PRESET_ID,
27
+ PRESET_ID,
28
+ buildPresetDefinition,
29
+ resolveDevelopMode,
30
+ } from './preset.js'
31
+ import { installModelGuard } from './guard.js'
32
+
33
+ export { Config }
34
+ export const name = 'dev-plan-presets'
35
+ export const version = '0.3.0'
36
+ export const DEEP_PTC_PACKAGE_NAME = 'dsh-deep-ptc-mode'
37
+
38
+ const MAX_VIOLATIONS = 50
39
+ const MAX_WARNINGS = 20
40
+ const DEFAULT_VERIFY_DELAY_MS = 2000
41
+
42
+ const isPlainObject = (value) =>
43
+ typeof value === 'object' && value !== null && !Array.isArray(value)
44
+
45
+ /** 兼容旧 UI/调用方:从目录行里汇总 deep-ptc 状态(新逻辑不再依赖它判断可用性)。 */
46
+ function summarizePreset(rows, id) {
47
+ const row = (rows ?? []).find((item) => item?.id === id)
48
+ return {
49
+ available: Boolean(row) && !(typeof row.broken === 'string' && row.broken.length > 0),
50
+ presetPresent: Boolean(row),
51
+ ...(row?.broken ? { broken: row.broken } : {}),
52
+ }
53
+ }
54
+
55
+ const MAX_PROBE_MS = 1200
56
+
57
+ /** 带超时的 promise:保留真实拒绝原因,不把失败伪装成超时。 */
58
+ const withTimeout = (promise, ms, message) =>
59
+ new Promise((resolve, reject) => {
60
+ const timer = setTimeout(() => reject(new Error(message)), ms)
61
+ if (typeof timer?.unref === 'function') timer.unref()
62
+ Promise.resolve(promise).then(
63
+ (value) => {
64
+ clearTimeout(timer)
65
+ resolve(value)
66
+ },
67
+ (error) => {
68
+ clearTimeout(timer)
69
+ reject(error)
70
+ },
71
+ )
72
+ })
73
+
74
+ /** 只等一小会儿:registry.list() 在 Host 启动期可能等 Loader 收敛,不能让它拖死注册。 */
75
+ const settleWithin = (promise, ms) =>
76
+ new Promise((resolve) => {
77
+ const timer = setTimeout(() => resolve(undefined), ms)
78
+ if (typeof timer?.unref === 'function') timer.unref()
79
+ Promise.resolve(promise).then(
80
+ (value) => {
81
+ clearTimeout(timer)
82
+ resolve(value)
83
+ },
84
+ () => {
85
+ clearTimeout(timer)
86
+ resolve(undefined)
87
+ },
88
+ )
89
+ })
90
+
91
+ /**
92
+ * 探测宿主 agentPresets 目录。目录是唯一事实源:
93
+ * - checked=true 且 rows 含目标 id、没有 broken,才算可用;
94
+ * - 读取超时/异常时 checked=false、rows=[],调用方显式回退 standard 并稍后复检;
95
+ * - loader entry 不再参与可用性判断。
96
+ * @returns {Promise<{ checked: boolean, timedOut: boolean, error?: string, rows: Array<{id:string,name:string,description:string,broken?:string}> }>}
97
+ */
98
+ export async function probePresets(ctx, registry) {
99
+ let checked = false
100
+ let timedOut = false
101
+ let error
102
+ let rows = []
103
+ try {
104
+ const listed = await settleWithin(registry?.list?.(), MAX_PROBE_MS)
105
+ if (Array.isArray(listed)) {
106
+ checked = true
107
+ rows = listed
108
+ .filter((row) => isPlainObject(row) && typeof row.id === 'string' && row.id.trim().length > 0)
109
+ .map((row) => ({
110
+ id: row.id.trim(),
111
+ name: typeof row.name === 'string' ? row.name.trim() : '',
112
+ description: typeof row.description === 'string' ? row.description : '',
113
+ ...(typeof row.broken === 'string' && row.broken.length > 0 ? { broken: row.broken } : {}),
114
+ }))
115
+ } else {
116
+ timedOut = true
117
+ }
118
+ } catch (cause) {
119
+ timedOut = true
120
+ error = String(cause?.message ?? cause).slice(0, 200)
121
+ }
122
+ return { checked, timedOut, rows, ...(error === undefined ? {} : { error }) }
123
+ }
124
+
125
+ const send = (res, code, payload) => {
126
+ let body
127
+ try {
128
+ body = JSON.stringify(payload)
129
+ } catch (error) {
130
+ body = JSON.stringify({ error: `序列化响应失败:${String(error?.message ?? error)}` })
131
+ code = 500
132
+ }
133
+ res.writeHead(code, {
134
+ 'content-type': 'application/json; charset=utf-8',
135
+ 'cache-control': 'no-store',
136
+ 'content-length': Buffer.byteLength(body),
137
+ })
138
+ res.end(body)
139
+ }
140
+
141
+ const readBody = async (req, limit) => {
142
+ let body = ''
143
+ for await (const chunk of req) {
144
+ body += chunk
145
+ if (body.length > limit) throw new Error('body too large')
146
+ }
147
+ return body
148
+ }
149
+
150
+ const mediaTypeOf = (req) =>
151
+ String(req?.headers?.['content-type'] ?? '')
152
+ .split(';')[0]
153
+ .trim()
154
+ .toLowerCase()
155
+
156
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1'])
157
+ const normalizeHost = (host) => String(host).replace(/^\[|\]$/g, '').toLowerCase()
158
+ const defaultPort = (protocol) => (protocol === 'https:' ? '443' : '80')
159
+ const endpointOf = (url) => ({
160
+ protocol: url.protocol.toLowerCase(),
161
+ host: normalizeHost(url.hostname),
162
+ port: url.port || defaultPort(url.protocol),
163
+ })
164
+ const sameEndpoint = (left, right) =>
165
+ left.protocol === right.protocol &&
166
+ left.port === right.port &&
167
+ (left.host === right.host ||
168
+ (LOOPBACK_HOSTS.has(left.host) && LOOPBACK_HOSTS.has(right.host)))
169
+
170
+ /**
171
+ * 浏览器跨源写保护。只做来源校验,不替代宿主认证:
172
+ * - Sec-Fetch-Site: cross-site 直接拒绝;
173
+ * - 带 Origin 时,Origin 必须同时匹配请求 Host 和 webServer.getOrigin() 的实际监听 origin;
174
+ * 127.0.0.1 / localhost / [::1] 同端口视为有限等价,避免正常本机别名被误伤;
175
+ * - 没有 Origin 的非浏览器客户端放行(仍受宿主认证约束);
176
+ * - 反代改写 Host/Origin 的场景不在本轮支持,需保持权威监听地址。
177
+ * @returns 问题代码或 null
178
+ */
179
+ const originProblem = (req, authoritativeOrigin) => {
180
+ const site = String(req?.headers?.['sec-fetch-site'] ?? '').toLowerCase()
181
+ if (site === 'cross-site') return 'cross-site'
182
+ const origin = req?.headers?.origin
183
+ if (origin === undefined || origin === null || origin === '') return null
184
+ let originUrl
185
+ try {
186
+ originUrl = new URL(String(origin))
187
+ } catch {
188
+ return 'invalid-origin'
189
+ }
190
+ const hostHeader = String(req?.headers?.host ?? '')
191
+ if (hostHeader === '') return 'invalid-host'
192
+ let hostUrl
193
+ try {
194
+ hostUrl = new URL(`${originUrl.protocol}//${hostHeader}`)
195
+ } catch {
196
+ return 'invalid-host'
197
+ }
198
+ const originEndpoint = endpointOf(originUrl)
199
+ if (!sameEndpoint(originEndpoint, endpointOf(hostUrl))) return 'origin-mismatch'
200
+ if (authoritativeOrigin === undefined || authoritativeOrigin === null || authoritativeOrigin === '') {
201
+ return 'authority-unavailable'
202
+ }
203
+ let authorityUrl
204
+ try {
205
+ authorityUrl = new URL(String(authoritativeOrigin))
206
+ } catch {
207
+ return 'authority-unavailable'
208
+ }
209
+ if (!sameEndpoint(originEndpoint, endpointOf(authorityUrl))) return 'origin-not-authoritative'
210
+ return null
211
+ }
212
+
213
+ /**
214
+ * Host 插件入口。
215
+ * @param {any} ctx Cordis Context
216
+ * @param {any} rawConfig Loader 配置(由 Config 校验/规范化)
217
+ * @param {{ verificationDelayMs?: number, now?: () => number }} [runtime] 仅测试用的运行参数
218
+ */
219
+ export function apply(ctx, rawConfig, runtime = {}) {
220
+ const settings = normalizeSettings(rawConfig)
221
+ const now = typeof runtime?.now === 'function' ? runtime.now : () => Date.now()
222
+ const violations = []
223
+ const warnings = []
224
+ const state = {
225
+ settings,
226
+ mode: null,
227
+ definition: null,
228
+ preset: null,
229
+ presets: { checked: false, timedOut: false, rows: [] },
230
+ deepPtc: { available: false, checked: false },
231
+ registration: 'pending',
232
+ error: null,
233
+ }
234
+
235
+ const log = (level, message) => {
236
+ try {
237
+ const fn = ctx.logger?.[level]
238
+ if (typeof fn === 'function') fn.call(ctx.logger, `[dev-plan-presets] ${message}`)
239
+ } catch {
240
+ /* 日志不可用不是失败理由 */
241
+ }
242
+ }
243
+
244
+ const rememberWarning = (message) => {
245
+ warnings.unshift(String(message))
246
+ if (warnings.length > MAX_WARNINGS) warnings.length = MAX_WARNINGS
247
+ }
248
+
249
+ const audit = (event, detail) => {
250
+ if (!settings.audit) return
251
+ log('info', `audit ${event} ${JSON.stringify(detail ?? {})}`)
252
+ }
253
+
254
+ const recordViolation = (entry) => {
255
+ violations.unshift(entry)
256
+ if (violations.length > MAX_VIOLATIONS) violations.length = MAX_VIOLATIONS
257
+ log('warn', `模型守门:${entry?.text ?? '子代理越界'}`)
258
+ }
259
+
260
+ // ── 1. 模型守门(只管子代理;off 时完全不注册监听)──────────────────────────
261
+ ctx.effect(
262
+ () =>
263
+ installModelGuard(ctx, settings, {
264
+ recordViolation,
265
+ audit,
266
+ warn: (message) => {
267
+ rememberWarning(message)
268
+ log('warn', message)
269
+ },
270
+ }),
271
+ 'dev-plan-presets: model guard',
272
+ )
273
+
274
+ // ── 2. 动态 preset 注册(等 agentPresets 服务可用)──────────────────────────
275
+ const delayMs = Number.isFinite(runtime?.verificationDelayMs)
276
+ ? Math.max(0, Number(runtime.verificationDelayMs))
277
+ : DEFAULT_VERIFY_DELAY_MS
278
+
279
+ ctx.inject(['agentPresets'], (child) => {
280
+ const registry = child.agentPresets
281
+ let disposed = false
282
+ let release
283
+ let queue = Promise.resolve()
284
+ let timer
285
+
286
+ const enqueue = (task) => {
287
+ queue = queue
288
+ .then(async () => {
289
+ if (disposed) return
290
+ await task()
291
+ })
292
+ .catch((error) => {
293
+ const message = String(error?.message ?? error)
294
+ state.registration = 'failed'
295
+ state.error = message
296
+ rememberWarning(message)
297
+ log('error', `注册 dev-plan preset 失败:${message}`)
298
+ })
299
+ return queue
300
+ }
301
+
302
+ const publish = async (probe) => {
303
+ if (disposed) return
304
+ const mode = resolveDevelopMode({
305
+ requestedMode: settings.developMode,
306
+ presets: probe?.rows ?? [],
307
+ catalogChecked: probe?.checked === true,
308
+ catalogError: probe?.error,
309
+ })
310
+ state.mode = mode
311
+ state.presets = {
312
+ checked: probe?.checked === true,
313
+ timedOut: probe?.timedOut === true,
314
+ rows: probe?.rows ?? [],
315
+ ...(probe?.error === undefined ? {} : { error: probe.error }),
316
+ }
317
+ state.deepPtc = {
318
+ ...summarizePreset(probe?.rows, DEEP_PTC_PRESET_ID),
319
+ checked: probe?.checked === true,
320
+ ...(probe?.timedOut ? { registryTimedOut: true } : {}),
321
+ }
322
+ const definition = buildPresetDefinition({ settings, mode })
323
+ if (mode.fallback) {
324
+ const message = `施工子代理已回退 standard:${mode.reason}`
325
+ rememberWarning(message)
326
+ log('warn', message)
327
+ } else if (mode.effective === 'standard') {
328
+ log('info', '施工子代理使用 standard preset。')
329
+ } else {
330
+ log('info', `施工子代理使用 ${mode.effective} preset(宿主预设目录已确认可用)。`)
331
+ }
332
+ const unregister = await registry.register(definition)
333
+ if (typeof unregister !== 'function') {
334
+ throw new Error('agentPresets.register 没有返回 disposer')
335
+ }
336
+ if (disposed) {
337
+ await unregister()
338
+ return
339
+ }
340
+ release = unregister
341
+ state.definition = definition
342
+ state.preset = {
343
+ id: definition.id,
344
+ name: definition.name,
345
+ description: definition.description,
346
+ }
347
+ state.registration = 'active'
348
+ state.error = null
349
+ }
350
+
351
+ const switchTo = async (probe) => {
352
+ if (disposed) return
353
+ const next = resolveDevelopMode({
354
+ requestedMode: settings.developMode,
355
+ presets: probe?.rows ?? [],
356
+ catalogChecked: probe?.checked === true,
357
+ catalogError: probe?.error,
358
+ })
359
+ const unchanged =
360
+ state.mode !== null &&
361
+ state.mode.effective === next.effective &&
362
+ state.mode.fallback === next.fallback &&
363
+ state.mode.reason === next.reason
364
+ if (unchanged) {
365
+ state.presets = {
366
+ checked: probe?.checked === true,
367
+ timedOut: probe?.timedOut === true,
368
+ rows: probe?.rows ?? [],
369
+ ...(probe?.error === undefined ? {} : { error: probe.error }),
370
+ }
371
+ state.deepPtc = {
372
+ ...summarizePreset(probe?.rows, DEEP_PTC_PRESET_ID),
373
+ checked: probe?.checked === true,
374
+ ...(probe?.timedOut ? { registryTimedOut: true } : {}),
375
+ }
376
+ return
377
+ }
378
+ // effective/fallback 相同但 reason 变了也要重新发布:description/persona 带着回退原因。
379
+ state.registration = 'switching'
380
+ const previous = release
381
+ release = undefined
382
+ if (previous) await previous()
383
+ await publish(probe)
384
+ }
385
+
386
+ const scheduleVerification = () => {
387
+ const needsRecheck = settings.developMode !== 'standard' || state.presets.checked !== true
388
+ if (!needsRecheck || delayMs <= 0) return
389
+ timer = setTimeout(() => {
390
+ timer = undefined
391
+ enqueue(async () => {
392
+ if (disposed) return
393
+ const probe = await probePresets(ctx, registry)
394
+ if (disposed) return
395
+ await switchTo(probe)
396
+ })
397
+ }, delayMs)
398
+ // 不阻止进程退出;Cordis 卸载时会清理。
399
+ if (typeof timer?.unref === 'function') timer.unref()
400
+ }
401
+
402
+ // 卸载:先标记,等队列收敛,再交还动态 preset 的 disposer。
403
+ child.effect(
404
+ () =>
405
+ async () => {
406
+ disposed = true
407
+ if (timer !== undefined) clearTimeout(timer)
408
+ timer = undefined
409
+ await queue.catch(() => {})
410
+ const current = release
411
+ release = undefined
412
+ if (current) {
413
+ try {
414
+ await current()
415
+ } catch (error) {
416
+ log('warn', `释放动态 preset 失败:${String(error?.message ?? error)}`)
417
+ }
418
+ }
419
+ state.registration = 'disposed'
420
+ },
421
+ 'dev-plan-presets: dynamic preset',
422
+ )
423
+
424
+ enqueue(async () => {
425
+ const probe = await probePresets(ctx, registry)
426
+ if (disposed) return
427
+ await publish(probe)
428
+ scheduleVerification()
429
+ })
430
+ })
431
+
432
+ // ── 3. 设置页 HTTP 路由(webServer 可选)────────────────────────────────────
433
+ const MODEL_CATALOG_TTL_MS = 60_000
434
+ let modelCatalog = { checked: false, providers: [], failures: [], error: null }
435
+ let modelCatalogUpdatedAt = Number.NEGATIVE_INFINITY
436
+ let modelCatalogInFlight
437
+
438
+ /**
439
+ * 枚举当前可用 provider / model。单个 provider 失败只影响它自己:
440
+ * 其余 provider 仍返回,失败项进 failures,前端能区分“目录空”和“局部失败”。
441
+ * 该函数只由后台刷新调用,/state 永远不 await 它。
442
+ */
443
+ const refreshModelCatalog = () => {
444
+ if (modelCatalogInFlight) return modelCatalogInFlight
445
+ modelCatalogInFlight = (async () => {
446
+ const llm = (() => {
447
+ try {
448
+ return ctx.get('llm')
449
+ } catch {
450
+ return undefined
451
+ }
452
+ })()
453
+ if (!llm || typeof llm.listProviders !== 'function') {
454
+ modelCatalog = { checked: false, providers: [], failures: [], error: 'llm-unavailable' }
455
+ modelCatalogUpdatedAt = now()
456
+ return modelCatalog
457
+ }
458
+ let providers
459
+ try {
460
+ providers = llm.listProviders()
461
+ } catch (error) {
462
+ modelCatalog = {
463
+ checked: false,
464
+ providers: [],
465
+ failures: [],
466
+ error: String(error?.message ?? error),
467
+ }
468
+ modelCatalogUpdatedAt = now()
469
+ return modelCatalog
470
+ }
471
+ const normalized = (Array.isArray(providers) ? providers : [])
472
+ .filter((provider) => isPlainObject(provider) && typeof provider.id === 'string' && provider.id.length > 0)
473
+ .map((provider) => ({
474
+ id: provider.id,
475
+ name:
476
+ typeof provider.name === 'string' && provider.name.length > 0 ? provider.name : provider.id,
477
+ }))
478
+ // 并行枚举,单个 provider 超时/失败只影响它自己。
479
+ const entries = await Promise.all(
480
+ normalized.map(async (provider) => {
481
+ try {
482
+ const models = await withTimeout(llm.listModels(provider.id), 3000, '模型列表读取超时')
483
+ if (!Array.isArray(models)) throw new Error('模型列表返回了非数组')
484
+ return {
485
+ provider: provider.id,
486
+ name: provider.name,
487
+ models: models
488
+ .filter((model) => isPlainObject(model) && typeof model.id === 'string' && model.id.length > 0)
489
+ .map((model) => ({
490
+ model: model.id,
491
+ name:
492
+ typeof model.name === 'string' && model.name.length > 0 ? model.name : model.id,
493
+ })),
494
+ }
495
+ } catch (error) {
496
+ return {
497
+ provider: provider.id,
498
+ name: provider.name,
499
+ models: [],
500
+ failure: String(error?.message ?? error).slice(0, 200),
501
+ }
502
+ }
503
+ }),
504
+ )
505
+ const out = entries.map(({ failure, ...entry }) => entry)
506
+ const failures = entries
507
+ .filter((entry) => typeof entry.failure === 'string')
508
+ .map((entry) => ({ provider: entry.provider, message: entry.failure }))
509
+ modelCatalog = { checked: true, providers: out, failures, error: null }
510
+ modelCatalogUpdatedAt = now()
511
+ return modelCatalog
512
+ })()
513
+ .catch((error) => {
514
+ // 后台失败必须落到状态里,且不能产生未处理拒绝。
515
+ modelCatalog = {
516
+ checked: false,
517
+ providers: [],
518
+ failures: [],
519
+ error: String(error?.message ?? error).slice(0, 200),
520
+ }
521
+ modelCatalogUpdatedAt = now()
522
+ return modelCatalog
523
+ })
524
+ .finally(() => {
525
+ modelCatalogInFlight = undefined
526
+ })
527
+ return modelCatalogInFlight
528
+ }
529
+
530
+ /**
531
+ * 同步返回最后一次目录快照;超过 TTL 时只启动后台刷新,不阻塞 /state。
532
+ * 60s TTL 保证设置页静置 60s 最多“初始 + 一次刷新”两轮全量枚举。
533
+ */
534
+ const modelCatalogSnapshot = () => {
535
+ if (now() - modelCatalogUpdatedAt >= MODEL_CATALOG_TTL_MS) {
536
+ void refreshModelCatalog()
537
+ }
538
+ return modelCatalog
539
+ }
540
+
541
+ const buildState = async () => ({
542
+ version,
543
+ config: state.settings,
544
+ route: routeOf(state.settings),
545
+ requestedMode: state.mode?.requested ?? settings.developMode,
546
+ effectiveMode: state.mode?.effective ?? null,
547
+ modeName: state.mode?.name ?? null,
548
+ fallback: {
549
+ active: state.mode?.fallback === true,
550
+ reason: state.mode?.reason ?? '',
551
+ },
552
+ presets: {
553
+ checked: state.presets.checked === true,
554
+ timedOut: state.presets.timedOut === true,
555
+ selfId: PRESET_ID,
556
+ rows: state.presets.rows,
557
+ ...(typeof state.presets.error === 'string' ? { error: state.presets.error } : {}),
558
+ },
559
+ modelCatalog: modelCatalogSnapshot(),
560
+ deepPtc: {
561
+ presetId: DEEP_PTC_PRESET_ID,
562
+ packageName: DEEP_PTC_PACKAGE_NAME,
563
+ ...state.deepPtc,
564
+ },
565
+ preset: state.preset,
566
+ registration: state.registration,
567
+ error: state.error,
568
+ errorCode: state.error === null ? null : 'preset-registration-failed',
569
+ violations: violations.slice(0, 20),
570
+ warnings: warnings.slice(0, 10),
571
+ })
572
+
573
+ ctx.inject(['webServer'], (webCtx) => {
574
+ try {
575
+ webCtx.effect(function* devPlanPresetRoutes() {
576
+ const webServer = webCtx.webServer
577
+ const offState = webServer.register({
578
+ kind: 'exact',
579
+ path: '/plugins/dev-plan-presets/state',
580
+ handler: async (req, res) => {
581
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
582
+ send(res, 405, { error: 'method not allowed', code: 'method-not-allowed' })
583
+ return
584
+ }
585
+ try {
586
+ send(res, 200, await buildState())
587
+ } catch (error) {
588
+ send(res, 500, { error: String(error?.message ?? error), code: 'internal-error' })
589
+ }
590
+ },
591
+ })
592
+
593
+ const offConfig = webServer.register({
594
+ kind: 'exact',
595
+ path: '/plugins/dev-plan-presets/config',
596
+ handler: async (req, res) => {
597
+ if (req.method !== 'POST') {
598
+ send(res, 405, { error: 'method not allowed', code: 'method-not-allowed' })
599
+ return
600
+ }
601
+ let authoritativeOrigin
602
+ try {
603
+ authoritativeOrigin = webServer.getOrigin()
604
+ } catch {
605
+ authoritativeOrigin = undefined
606
+ }
607
+ const originIssue = originProblem(req, authoritativeOrigin)
608
+ if (originIssue !== null) {
609
+ send(res, 403, {
610
+ error: `origin rejected: ${originIssue}`,
611
+ code: 'forbidden-origin',
612
+ reason: originIssue,
613
+ })
614
+ return
615
+ }
616
+ if (mediaTypeOf(req) !== 'application/json') {
617
+ send(res, 415, {
618
+ error: 'content-type must be application/json',
619
+ code: 'unsupported-media-type',
620
+ })
621
+ return
622
+ }
623
+ try {
624
+ let body
625
+ try {
626
+ body = await readBody(req, 16384)
627
+ } catch (error) {
628
+ if (String(error?.message ?? error).includes('too large')) {
629
+ send(res, 413, { error: 'request body too large', code: 'body-too-large' })
630
+ return
631
+ }
632
+ throw error
633
+ }
634
+ let parsed
635
+ try {
636
+ parsed = body.trim().length === 0 ? {} : JSON.parse(body)
637
+ } catch {
638
+ send(res, 400, { error: 'request body is not valid JSON', code: 'invalid-json' })
639
+ return
640
+ }
641
+ const patch = isPlainObject(parsed?.settings) ? parsed.settings : parsed
642
+ if (!isPlainObject(patch)) {
643
+ send(res, 400, { error: 'config body must be a JSON object', code: 'invalid-body' })
644
+ return
645
+ }
646
+ const current = normalizeSettings(state.settings)
647
+ // 先校验“当前值 + 补丁”的原始对象,再取规范化结果:
648
+ // 直接校验 normalize 后的值会把非法枚举悄悄改成默认值,等于接受脏输入。
649
+ const checked = validateSettings({ ...current, ...patch })
650
+ if (checked.issues) {
651
+ send(res, 400, {
652
+ error: 'invalid config',
653
+ code: 'invalid-config',
654
+ issues: checked.issues,
655
+ })
656
+ return
657
+ }
658
+ const next = checked.value
659
+ const entry = ctx.fiber?.entry
660
+ const editor = ctx.get('configEditor')
661
+ if (!entry || typeof editor?.edit !== 'function') {
662
+ send(res, 503, {
663
+ error:
664
+ 'configEditor 不可用:当前 profile 没有可写的 root patch。请通过插件管理/配置编辑修改本行配置。',
665
+ code: 'config-editor-unavailable',
666
+ })
667
+ return
668
+ }
669
+ if (JSON.stringify(next) === JSON.stringify(current)) {
670
+ send(res, 200, { ok: true, unchanged: true, config: next })
671
+ return
672
+ }
673
+ await editor.edit(entry, () => ({ ...next }))
674
+ // configEditor.edit 已写入 profile patch 并 await reconcileProfilePatches:
675
+ // 它返回时 Loader 已尝试重建/应用新配置,不存在“没有 HMR 就只是落盘”的分支。
676
+ send(res, 200, { ok: true, config: next, applying: true })
677
+ } catch (error) {
678
+ send(res, 500, { error: String(error?.message ?? error), code: 'internal-error' })
679
+ }
680
+ },
681
+ })
682
+
683
+ yield () => {
684
+ try {
685
+ offState()
686
+ } catch {
687
+ /* ignore */
688
+ }
689
+ try {
690
+ offConfig()
691
+ } catch {
692
+ /* ignore */
693
+ }
694
+ }
695
+ }, 'dev-plan-presets: settings routes')
696
+ } catch (error) {
697
+ rememberWarning(`无法注册设置页路由:${String(error?.message ?? error)}`)
698
+ log('warn', `无法注册设置页路由:${String(error?.message ?? error)}`)
699
+ }
700
+ })
701
+ }
702
+
703
+ export { PRESET_ID }