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