@user-mrz/dsh-system-prompt-studio 0.0.0-stage → 0.1.7

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/lib/index.js ADDED
@@ -0,0 +1,1265 @@
1
+ // dsh-system-prompt-studio — Host 半。
2
+ //
3
+ // 目标:让用户按「对话」管理模型真正收到的**系统提示词**,而不只是用户消息。
4
+ //
5
+ // 三件事:
6
+ // 1. 按 agent 作用域注册提示词段(追加 / 同名影子替换 / 完全替换);
7
+ // 2. 只读观察每次装配,得到该会话真实的段清单(名称/顺序/字符数);
8
+ // 3. 一条回环 HTTP 路由给 Web 面板读写状态,状态自己落在 $DSH_HOME 下。
9
+ //
10
+ // 为什么必须按 agent 作用域注册:`ctx.systemPrompt.section()` 把段写进**调用者
11
+ // 所在作用域**的层,而 `agent.ctx` 正是那个会话的作用域。同层同名段会抛错,
12
+ // 但作用域层会影子覆盖全局同名段——这正是「替换指定段」的实现方式,不需要
13
+ // 改动任何第一方包。
14
+ //
15
+ // 为什么不用 import '@deepseek-ai/*':本包只依赖 Node 内置模块,profile 的依赖
16
+ // 解析与离线测试都不受影响;服务一律通过 `ctx.get(name)` 做可选获取。
17
+
18
+ import { copyFileSync, readFileSync } from 'node:fs'
19
+ import { mkdir, rename, writeFile } from 'node:fs/promises'
20
+ import { dirname, join } from 'node:path'
21
+ import { homedir } from 'node:os'
22
+
23
+ export const name = 'dsh-system-prompt-studio'
24
+ export const inject = ['webServer']
25
+
26
+ /** 支持的覆盖模式。`none` 不是模式,只在内部表示「没有生效覆盖」。 */
27
+ const MODES = ['append', 'replace', 'complete']
28
+ /** 追加段的段名(即使文本为空也必须唯一,避免与第一方段撞名)。 */
29
+ const APPEND_SECTION = 'studio:append'
30
+ /** 完全替换段的段名。 */
31
+ const COMPLETE_SECTION = 'studio:complete'
32
+ /** 段的排序兜底范围,避免用户把段塞到离谱的位置。 */
33
+ const ORDER_MIN = 10201
34
+ const ORDER_MAX = 20000
35
+ /**
36
+ * fork 继承的最大上溯深度(硬上限)。
37
+ *
38
+ * 取 3 是有意的:真实场景里 fork 一次是常态,fork 的 fork 已经很罕见,
39
+ * 再深基本都是子代理链。深度太大既拖慢每次装配(判定会在 text 回调里跑),
40
+ * 也让「这条规则到底从哪继承来的」变得无法向用户解释。
41
+ */
42
+ const MAX_INHERIT_DEPTH = 8
43
+
44
+ /**
45
+ * 第一方段的排序常量(来自 @deepseek-ai/dsh-system-prompt 的 SECTION_ORDERS)。
46
+ * 「替换指定段」必须沿用目标段自己的顺序,否则段会跑到提示词的另一头。
47
+ *
48
+ * 段名以**线上实测**为准(`assembly.sections` 里的 name),不要凭常量名猜:
49
+ * 实测到的名字是 `app:web-surface`、`context:file-reference`、
50
+ * `ui:deliverable-file-references`、`mcp-resource-servers` 这种形式。
51
+ * 未收录的名字由 {@link anchorOrderFor} 按前一次装配里的位置推算。
52
+ */
53
+ const KNOWN_ORDERS = {
54
+ 'harness:identity': -1000,
55
+ 'deployment:persona-prefix': 0,
56
+ 'plan:policy': 500,
57
+ 'team:policy': 600,
58
+ 'ptc:only': 800,
59
+ 'context:file-reference': 900,
60
+ 'tool:bash': 1000,
61
+ 'tool:pwsh': 1010,
62
+ 'tool:read': 1100,
63
+ 'tool:write': 1200,
64
+ 'tool:edit': 1300,
65
+ 'tool:apply_patch': 1350,
66
+ 'tool:glob': 1400,
67
+ 'tool:grep': 1500,
68
+ 'tool:jobs': 1600,
69
+ 'tool:pty': 1700,
70
+ 'tool:web_search': 2000,
71
+ 'tool:web_fetch': 2100,
72
+ 'tool:lsp': 2200,
73
+ 'tool:session_query': 2300,
74
+ 'tool:goal': 2400,
75
+ 'tool:schedule': 2500,
76
+ 'tool:workflow': 2600,
77
+ 'tool:ralph': 2700,
78
+ 'tool:subagent': 2800,
79
+ 'tool:report': 2900,
80
+ 'mcp-resource-servers': 3100,
81
+ 'tools:sdk': 5000,
82
+ 'ui:deliverable-file-references': 9000,
83
+ 'structured-output': 9900,
84
+ 'harness:source': 10000,
85
+ 'app:web-surface': 10100,
86
+ 'deployment:persona-suffix': 10200,
87
+ }
88
+
89
+ const DEFAULTS = {
90
+ enabled: true,
91
+ apiPath: '/api/system-prompt-studio',
92
+ stateFile: '',
93
+ defaultMode: 'append',
94
+ allowComplete: true,
95
+ appendOrder: 10500,
96
+ defaultTargetName: 'deployment:persona-suffix',
97
+ maxChars: 200000,
98
+ observeAssemblies: true,
99
+ maxObservedScopes: 64,
100
+ // 全局默认值套用到哪些会话:roots = 只套用到顶层会话;all = 含子代理。
101
+ globalDefaultScope: 'roots',
102
+ // fork 继承:子会话没有自身覆盖时,沿 parentSession 链向上找。
103
+ // inheritOnFork=false 可退回「各会话独立」的旧行为。
104
+ inheritOnFork: true,
105
+ // 继承深度上限。防环之外还要防「极深的子代理链」把判定拖慢。
106
+ maxInheritDepth: 3,
107
+ // ── 下面是 client 半读的键,host 忽略 ────────────────────────────────
108
+ visible: true,
109
+ showOnNewConversation: true,
110
+ hostURL: '',
111
+ }
112
+
113
+ /**
114
+ * 解析并夹取本行的配置。patch 是整体替换,所以这里必须对每个键做兜底,
115
+ * 不能假设用户会把所有键都写上。
116
+ */
117
+ function resolveConfig(raw) {
118
+ const cfg = raw !== null && typeof raw === 'object' ? raw : {}
119
+ return {
120
+ enabled: cfg.enabled !== false,
121
+ apiPath: apiPath(cfg.apiPath),
122
+ stateFile: typeof cfg.stateFile === 'string' ? cfg.stateFile.trim() : '',
123
+ defaultMode: MODES.includes(cfg.defaultMode) ? cfg.defaultMode : DEFAULTS.defaultMode,
124
+ allowComplete: cfg.allowComplete !== false,
125
+ appendOrder: number(cfg.appendOrder, DEFAULTS.appendOrder, ORDER_MIN, ORDER_MAX),
126
+ defaultTargetName:
127
+ typeof cfg.defaultTargetName === 'string' && cfg.defaultTargetName.trim() !== ''
128
+ ? cfg.defaultTargetName.trim()
129
+ : DEFAULTS.defaultTargetName,
130
+ maxChars: number(cfg.maxChars, DEFAULTS.maxChars, 200, 4000000),
131
+ observeAssemblies: cfg.observeAssemblies !== false,
132
+ maxObservedScopes: number(cfg.maxObservedScopes, DEFAULTS.maxObservedScopes, 1, 4096),
133
+ globalDefaultScope: cfg.globalDefaultScope === 'all' ? 'all' : 'roots',
134
+ inheritOnFork: cfg.inheritOnFork !== false,
135
+ maxInheritDepth: number(cfg.maxInheritDepth, DEFAULTS.maxInheritDepth, 0, MAX_INHERIT_DEPTH),
136
+ visible: cfg.visible !== false,
137
+ showOnNewConversation: cfg.showOnNewConversation !== false,
138
+ hostURL: typeof cfg.hostURL === 'string' ? cfg.hostURL.trim() : '',
139
+ }
140
+ }
141
+
142
+ function number(value, fallback, min, max) {
143
+ const n = typeof value === 'number' && Number.isFinite(value) ? value : Number(value)
144
+ if (!Number.isFinite(n)) return fallback
145
+ return Math.min(max, Math.max(min, Math.round(n)))
146
+ }
147
+
148
+ function apiPath(value) {
149
+ if (typeof value !== 'string') return DEFAULTS.apiPath
150
+ const trimmed = value.trim()
151
+ if (!trimmed.startsWith('/api/')) return DEFAULTS.apiPath
152
+ if (trimmed.includes(' ') || trimmed.includes('?') || trimmed.includes('#')) return DEFAULTS.apiPath
153
+ return trimmed
154
+ }
155
+
156
+ // ---------------------------------------------------------------------------
157
+ // 状态:版本化 JSON,内存镜像 + 串行落盘
158
+ // ---------------------------------------------------------------------------
159
+
160
+ function emptyEntry(mode) {
161
+ return { enabled: false, mode: mode ?? DEFAULTS.defaultMode, text: '', target: '', updatedAt: 0 }
162
+ }
163
+
164
+ function emptyState() {
165
+ return { version: 1, global: emptyEntry(), sessions: {} }
166
+ }
167
+
168
+ /**
169
+ * 状态里出现过的最大写入序号。
170
+ *
171
+ * 重启后 `runtime.writeSeq` 必须从这里接着走,否则新写入的序号可能小于
172
+ * 状态里留存的旧序号——那份段清单会被永久判成「比保存还新」,过期提示再也
173
+ * 不会出现。
174
+ */
175
+ function highestWriteSeq(state) {
176
+ let max = 0
177
+ const consider = (entry) => {
178
+ if (entry !== null && typeof entry === 'object' && typeof entry.writeSeq === 'number' && Number.isFinite(entry.writeSeq)) {
179
+ if (entry.writeSeq > max) max = entry.writeSeq
180
+ }
181
+ }
182
+ consider(state.global)
183
+ for (const entry of Object.values(state.sessions ?? {})) consider(entry)
184
+ return max
185
+ }
186
+
187
+ function defaultStateFile() {
188
+ const home = process.env.DSH_HOME && process.env.DSH_HOME.trim() !== '' ? process.env.DSH_HOME : join(homedir(), '.dsh')
189
+ return join(home, 'dsh-system-prompt-studio', 'state.json')
190
+ }
191
+
192
+ /** 把读入的 entry 洗成合法形状;非法字段回退到默认值而不是抛错。 */
193
+ function normalizeEntry(raw, fallback) {
194
+ const base = fallback !== undefined ? fallback : emptyEntry()
195
+ const entry = raw !== null && typeof raw === 'object' ? raw : {}
196
+ const normalized = {
197
+ enabled: typeof entry.enabled === 'boolean' ? entry.enabled : base.enabled,
198
+ mode: MODES.includes(entry.mode) ? entry.mode : base.mode,
199
+ text: typeof entry.text === 'string' ? entry.text : base.text,
200
+ target: typeof entry.target === 'string' ? entry.target : base.target,
201
+ updatedAt: typeof entry.updatedAt === 'number' && Number.isFinite(entry.updatedAt) ? entry.updatedAt : base.updatedAt,
202
+ }
203
+ // writeSeq 是 0.1.4 起才写的字段。老状态文件没有它,这里不补 0——补了会让
204
+ // 它看起来像「早于任何装配」,从而把一份真正最新的清单判成过期。缺席就是
205
+ // 缺席,快照那边据此退回时间戳比较。
206
+ if (typeof entry.writeSeq === 'number' && Number.isFinite(entry.writeSeq)) normalized.writeSeq = entry.writeSeq
207
+ return normalized
208
+ }
209
+
210
+ /**
211
+ * 读入状态。故意用同步读:apply 发生在 agent/created 之前,异步读会与首批
212
+ * 会话的装段产生竞态,导致「刚打开就有一瞬间用了旧值」。
213
+ * 损坏时不覆盖原文件,而是备份后空状态起步,把原因交给接口回报。
214
+ */
215
+ function loadState(file) {
216
+ const health = { stateFile: file, loaded: false, error: '', backup: '' }
217
+ let text
218
+ try {
219
+ text = readFileSync(file, 'utf8')
220
+ } catch (error) {
221
+ if (error !== null && typeof error === 'object' && error.code === 'ENOENT') {
222
+ health.loaded = true
223
+ return { state: emptyState(), health }
224
+ }
225
+ health.error = `读取状态文件失败:${message(error)}`
226
+ return { state: emptyState(), health }
227
+ }
228
+ let parsed
229
+ try {
230
+ parsed = JSON.parse(text)
231
+ } catch (error) {
232
+ health.error = `状态文件不是合法 JSON:${message(error)}`
233
+ const backup = `${file}.corrupt-${Date.now()}`
234
+ // 同步备份,保证备份先于任何后续写入发生;失败就只报告原因。
235
+ try {
236
+ copyFileSync(file, backup)
237
+ health.backup = backup
238
+ } catch {
239
+ health.backup = ''
240
+ }
241
+ return { state: emptyState(), health }
242
+ }
243
+ const state = emptyState()
244
+ if (parsed !== null && typeof parsed === 'object') {
245
+ state.global = normalizeEntry(parsed.global)
246
+ if (parsed.sessions !== null && typeof parsed.sessions === 'object') {
247
+ for (const [id, entry] of Object.entries(parsed.sessions)) {
248
+ if (typeof id !== 'string' || id === '') continue
249
+ state.sessions[id] = normalizeEntry(entry)
250
+ }
251
+ }
252
+ }
253
+ health.loaded = true
254
+ return { state, health }
255
+ }
256
+
257
+ /**
258
+ * 串行落盘:同目录临时文件 + rename 原子替换。返回 true 表示已持久化;
259
+ * false 时调用方必须把 `persisted:false` 告诉用户,不能假装保存成功。
260
+ */
261
+ function createWriter(file, health, readState) {
262
+ let chain = Promise.resolve(true)
263
+ return function persist() {
264
+ const snapshot = JSON.stringify(readState(), null, 2)
265
+ chain = chain.then(async () => {
266
+ try {
267
+ await mkdir(dirname(file), { recursive: true })
268
+ const temp = `${file}.tmp-${process.pid}-${Date.now()}`
269
+ await writeFile(temp, snapshot, 'utf8')
270
+ await rename(temp, file)
271
+ health.error = ''
272
+ return true
273
+ } catch (error) {
274
+ health.error = `写入状态文件失败:${message(error)}`
275
+ return false
276
+ }
277
+ })
278
+ return chain
279
+ }
280
+ }
281
+
282
+ // ---------------------------------------------------------------------------
283
+ // HTTP 小工具(沿用工作区里已验证的回环围栏写法)
284
+ // ---------------------------------------------------------------------------
285
+
286
+ function isIPv4Loopback(parts) {
287
+ return parts.length === 4 && parts[0] === '127' && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255)
288
+ }
289
+
290
+ function isLoopbackAddress(address) {
291
+ if (address === undefined) return false
292
+ const normalized = String(address).toLowerCase()
293
+ if (normalized === '::1') return true
294
+ if (normalized.startsWith('::ffff:')) return isIPv4Loopback(normalized.slice(7).split('.'))
295
+ return isIPv4Loopback(normalized.split('.'))
296
+ }
297
+
298
+ function isLoopbackHostname(hostname) {
299
+ return hostname === 'localhost' || hostname === '[::1]' || isIPv4Loopback(hostname.split('.'))
300
+ }
301
+
302
+ /**
303
+ * 回环围栏:socket 与 Host 头都必须是回环(挡掉远程客户端),浏览器页面只能
304
+ * 同源访问。桌面壳从自定义协议加载界面(Origin 可能是 "null"),这类来源本身
305
+ * 不可能是远程站点,而 socket/Host 已确认回环,因此放行。
306
+ */
307
+ function isLoopbackRequest(request) {
308
+ if (!isLoopbackAddress(request.socket?.remoteAddress)) return false
309
+ const host = request.headers?.host
310
+ if (typeof host !== 'string') return false
311
+ let hostUrl
312
+ try {
313
+ hostUrl = new URL(`http://${host}`)
314
+ } catch {
315
+ return false
316
+ }
317
+ if (!isLoopbackHostname(hostUrl.hostname)) return false
318
+ const origin = request.headers?.origin
319
+ if (origin === undefined || origin === 'null') return true
320
+ let originUrl
321
+ try {
322
+ originUrl = new URL(origin)
323
+ } catch {
324
+ return false
325
+ }
326
+ if (originUrl.protocol === 'http:' || originUrl.protocol === 'https:') {
327
+ if (request.headers?.['sec-fetch-site'] === 'cross-site') return false
328
+ return originUrl.host === hostUrl.host
329
+ }
330
+ return true
331
+ }
332
+
333
+ function corsHeaders(request) {
334
+ const origin = request.headers?.origin
335
+ const headers = {
336
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
337
+ 'access-control-allow-headers': 'content-type',
338
+ vary: 'Origin',
339
+ }
340
+ if (typeof origin === 'string' && origin !== '' && origin !== 'null') headers['access-control-allow-origin'] = origin
341
+ return headers
342
+ }
343
+
344
+ function writeJson(res, status, body, extra) {
345
+ res.writeHead(status, {
346
+ 'content-type': 'application/json; charset=utf-8',
347
+ 'cache-control': 'no-store',
348
+ ...(extra ?? {}),
349
+ })
350
+ res.end(JSON.stringify(body))
351
+ }
352
+
353
+ function message(error) {
354
+ if (error === null || error === undefined) return 'unknown error'
355
+ if (typeof error === 'string') return error
356
+ return String(error.message ?? error)
357
+ }
358
+
359
+ /**
360
+ * 覆盖的「形态签名」:只描述*装成什么样*,不含正文内容。
361
+ *
362
+ * 文本变化不必重装(`section.text` 是函数,装配时重新求值),但形态、目标段、
363
+ * 顺序、以及**继承来源**变化时必须重装——父会话换了规则或继承链断开时,子会话
364
+ * 的注册要跟着更新,否则会一直沿用旧形态。
365
+ */
366
+ function buildSignature(effective) {
367
+ if (effective === null || effective === undefined) return 'none|'
368
+ if (effective.kind === 'none') return `none|${effective.reason ?? ''}`
369
+ const origin = effective.inheritedFrom === undefined ? '' : `|from:${effective.inheritedFrom}`
370
+ return `${effective.kind}|${effective.target}|${effective.order}${origin}`
371
+ }
372
+
373
+ /** 逐块取出一条消息的纯文本;非文本块跳过。 */
374
+ function textOfMessage(m) {
375
+ const content = m?.content
376
+ if (typeof content === 'string') return content
377
+ if (!Array.isArray(content)) return ''
378
+ const parts = []
379
+ for (const block of content) {
380
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
381
+ parts.push(block.text)
382
+ }
383
+ }
384
+ return parts.join('\n')
385
+ }
386
+
387
+ /**
388
+ * 从一次装配结果推算每个段的顺序值。
389
+ *
390
+ * 装配输出**不带 order**(顺序只是排序输入),所以这里用「已知常量为锚点,
391
+ * 未知段在相邻锚点之间线性插值」的办法还原:已知段直接用常量值,未知段在
392
+ * 前后已知段之间均分,边界外按 ±1 递增。这样未知段也能落在它真实所在的
393
+ * 位置附近,而不是一律贴到末尾。
394
+ *
395
+ * @param bare 装配数组顺序的 `[{ name, chars }]`
396
+ * @returns 带 `order` 的同一列表;完全推算不出时 order 为 null
397
+ */
398
+ function deriveOrders(bare) {
399
+ const rows = bare.map((row) => ({ ...row, order: null }))
400
+ const anchors = []
401
+ for (let index = 0; index < rows.length; index++) {
402
+ const known = KNOWN_ORDERS[rows[index].name]
403
+ if (typeof known === 'number') {
404
+ rows[index].order = known
405
+ anchors.push({ index, order: known })
406
+ }
407
+ }
408
+ if (anchors.length === 0) return rows
409
+
410
+ // 第一个锚点之前:按 -1 递减,保证仍排在它前面。
411
+ const first = anchors[0]
412
+ for (let index = first.index - 1; index >= 0; index--) {
413
+ rows[index].order = first.order - (first.index - index)
414
+ }
415
+ // 相邻锚点之间:均分间隔(至少留 1 的步长)。
416
+ for (let a = 0; a + 1 < anchors.length; a++) {
417
+ const left = anchors[a]
418
+ const right = anchors[a + 1]
419
+ const gap = right.index - left.index
420
+ if (gap <= 1) continue
421
+ const span = right.order - left.order
422
+ for (let offset = 1; offset < gap; offset++) {
423
+ const share = span / gap
424
+ const value = share >= 1 ? Math.round(left.order + share * offset) : left.order + offset
425
+ rows[left.index + offset].order = value
426
+ }
427
+ }
428
+ // 最后一个锚点之后:按 +1 递增。
429
+ const last = anchors[anchors.length - 1]
430
+ for (let index = last.index + 1; index < rows.length; index++) {
431
+ rows[index].order = last.order + (index - last.index)
432
+ }
433
+ // 兜底:插值撞车时按数组顺序强制递增,保证排序仍然稳定可预期。
434
+ let previous = -Infinity
435
+ for (const row of rows) {
436
+ if (row.order === null) continue
437
+ if (row.order <= previous) row.order = Math.floor(previous) + 1
438
+ previous = row.order
439
+ }
440
+ return rows
441
+ }
442
+
443
+ /** 读 JSON 请求体,超过上限直接 413(不截断,避免把半截文本存进去)。 */
444
+ function readJsonBody(req, limit) {
445
+ return new Promise((resolve, reject) => {
446
+ const chunks = []
447
+ let size = 0
448
+ let settled = false
449
+ const fail = (status, code, text) => {
450
+ if (settled) return
451
+ settled = true
452
+ const error = new Error(text)
453
+ error.status = status
454
+ error.code = code
455
+ reject(error)
456
+ }
457
+ req.on('data', (chunk) => {
458
+ if (settled) return
459
+ size += chunk.length
460
+ if (size > limit) {
461
+ fail(413, 'BODY_TOO_LARGE', `请求体超过 ${limit} 字节`)
462
+ try {
463
+ req.destroy()
464
+ } catch {
465
+ /* 连接可能已经断开 */
466
+ }
467
+ return
468
+ }
469
+ chunks.push(chunk)
470
+ })
471
+ req.on('end', () => {
472
+ if (settled) return
473
+ settled = true
474
+ const text = Buffer.concat(chunks).toString('utf8')
475
+ if (text.trim() === '') {
476
+ resolve({})
477
+ return
478
+ }
479
+ try {
480
+ resolve(JSON.parse(text))
481
+ } catch {
482
+ const error = new Error('请求体不是合法 JSON')
483
+ error.status = 400
484
+ error.code = 'INVALID_JSON'
485
+ reject(error)
486
+ }
487
+ })
488
+ req.on('error', (error) => {
489
+ if (settled) return
490
+ settled = true
491
+ reject(error)
492
+ })
493
+ })
494
+ }
495
+
496
+ // ---------------------------------------------------------------------------
497
+ // 插件
498
+ // ---------------------------------------------------------------------------
499
+
500
+ const MOUNTED = Symbol.for('dsh-system-prompt-studio.mounted')
501
+
502
+ /** 同一 profile 里重复挂载本行时,第二次起是 no-op(否则同名路由注册会抛错)。 */
503
+ function mountOnce(packageName, fn) {
504
+ return (...args) => {
505
+ const registry = globalThis
506
+ const mounted = (registry[MOUNTED] ??= new Set())
507
+ if (mounted.has(packageName)) return
508
+ mounted.add(packageName)
509
+ args[0]?.effect?.(() => () => {
510
+ mounted.delete(packageName)
511
+ })
512
+ return fn(...args)
513
+ }
514
+ }
515
+
516
+ /** 运行期状态;apply 时重建,测试可以经 `__internals.runtime` 只读查看。 */
517
+ const runtime = {
518
+ config: resolveConfig({}),
519
+ state: emptyState(),
520
+ health: { stateFile: '', loaded: false, error: '', backup: '' },
521
+ /** sessionId → { agent, sections, signature, effective, error } */
522
+ installed: new Map(),
523
+ /** sessionId → { at, seq, sections:[{name, order, chars}] } */
524
+ observed: new Map(),
525
+ /** 段名 → 最近一次实测到的顺序 */
526
+ observedOrder: new Map(),
527
+ assembles: 0,
528
+ lastObserved: null,
529
+ /**
530
+ * 单调递增的写入序号,用来判断「段清单是否早于当前覆盖」。
531
+ *
532
+ * 为什么不用时间戳:`Date.now()` 的精度是毫秒,而保存和装配完全可能落在
533
+ * 同一毫秒里(测试里几乎必然如此)。那时 `updatedAt > watch.at` 为假,
534
+ * 一份明明已经过期的清单会被判成最新的——面板于是保持沉默,用户继续对着
535
+ * 旧数据猜。序号没有精度问题:每次保存 +1,每次装配记下当时的值,比较就是
536
+ * 严格的大小关系。
537
+ */
538
+ writeSeq: 0,
539
+ persist: () => Promise.resolve(true),
540
+ }
541
+
542
+ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
543
+ const config = resolveConfig(rawConfig)
544
+ runtime.config = config
545
+ const file = config.stateFile !== '' ? config.stateFile : defaultStateFile()
546
+ const loaded = loadState(file)
547
+ runtime.state = loaded.state
548
+ runtime.health = loaded.health
549
+ runtime.persist = createWriter(file, runtime.health, () => runtime.state)
550
+ // 序号必须接着已有的最大值往下走,不能从 0 重新开始:否则重启后新写入的
551
+ // 序号可能小于状态里留存的旧序号,那份清单会被永久判成「比保存新」。
552
+ runtime.writeSeq = highestWriteSeq(runtime.state)
553
+
554
+ /** 可选服务获取;一律带 undefined 检查,缺失不影响插件激活。 */
555
+ const service = (key) => {
556
+ try {
557
+ return typeof ctx.get === 'function' ? ctx.get(key) : undefined
558
+ } catch {
559
+ return undefined
560
+ }
561
+ }
562
+
563
+ // ── 观察:只记录,绝不改写 ───────────────────────────────────────────
564
+ if (config.observeAssemblies) {
565
+ const off = ctx.on('system-prompt/assemble', (assembly, context, next) => {
566
+ try {
567
+ observeAssembly(ctx, assembly, context)
568
+ } catch {
569
+ /* 观察失败绝不能影响装配 */
570
+ }
571
+ return next()
572
+ })
573
+ ctx.effect(() => () => {
574
+ try {
575
+ off()
576
+ } catch {
577
+ /* disposal is best-effort */
578
+ }
579
+ })
580
+ }
581
+
582
+ // ── 覆盖判定 ─────────────────────────────────────────────────────────
583
+ /** 目标段的排序:已知常量 → 实测到的顺序 → 追加段顺序。 */
584
+ function orderFor(target) {
585
+ if (Object.hasOwn(KNOWN_ORDERS, target)) return KNOWN_ORDERS[target]
586
+ const seen = runtime.observedOrder.get(target)
587
+ if (typeof seen === 'number' && Number.isFinite(seen)) return seen
588
+ return config.appendOrder
589
+ }
590
+
591
+ function overrideFromEntry(entry, source) {
592
+ const text = typeof entry.text === 'string' ? entry.text : ''
593
+ if (text.trim() === '') return { kind: 'none', source, reason: 'empty' }
594
+ const mode = MODES.includes(entry.mode) ? entry.mode : config.defaultMode
595
+ if (mode === 'complete') {
596
+ if (!config.allowComplete) return { kind: 'none', source, reason: 'complete-blocked' }
597
+ return { kind: 'complete', source, text, target: COMPLETE_SECTION, order: config.appendOrder }
598
+ }
599
+ if (mode === 'replace') {
600
+ const target = typeof entry.target === 'string' ? entry.target.trim() : ''
601
+ if (target === '') return { kind: 'none', source, reason: 'target-missing' }
602
+ return { kind: 'replace', source, text, target, order: orderFor(target) }
603
+ }
604
+ return { kind: 'append', source, text, target: APPEND_SECTION, order: config.appendOrder }
605
+ }
606
+
607
+ /** 子代理判定:header.parentSession 存在即为子会话;读不到就当作顶层。 */
608
+ function isRootAgent(agent) {
609
+ return parentIdOf(agent) === ''
610
+ }
611
+
612
+ /** 读一个 agent 的父会话 id;读不到就返回空串。 */
613
+ function parentIdOf(agent) {
614
+ try {
615
+ const parent = agent?.session?.header?.parentSession
616
+ return typeof parent === 'string' ? parent : ''
617
+ } catch {
618
+ return ''
619
+ }
620
+ }
621
+
622
+ /**
623
+ * 沿 parentSession 链找「最近的、有自身覆盖的祖先」。
624
+ *
625
+ * 解决的是最扎心的一个静默失败:用户 fork 一个调教好的对话,fork 出来的新
626
+ * sessionId 在状态里没有条目,提示词**悄悄变回默认**,用户根本不知道发生了什么。
627
+ *
628
+ * 两个保护:
629
+ * - `seen` 防环(状态或 header 数据异常时不至于死循环);
630
+ * - `maxInheritDepth` 防深链(判定在每次装配的 text 回调里执行,不能太重)。
631
+ *
632
+ * 只沿「有自身覆盖」的祖先找:祖先只是继承来的不算合格起点,避免把
633
+ * 一条古老的规则穿过很多层传下去、让来源无法解释。
634
+ */
635
+ function findInheritedOverride(agent) {
636
+ if (!config.inheritOnFork) return null
637
+ const limit = config.maxInheritDepth
638
+ if (limit <= 0) return null
639
+ const seen = new Set()
640
+ let current = agent
641
+ let depth = 0
642
+ while (depth < limit) {
643
+ const parentId = parentIdOf(current)
644
+ if (parentId === '' || seen.has(parentId)) return null
645
+ seen.add(parentId)
646
+ depth += 1
647
+ const parentEntry = runtime.state.sessions[parentId]
648
+ if (parentEntry !== undefined && parentEntry.enabled) {
649
+ const inherited = overrideFromEntry(parentEntry, 'session')
650
+ // 父条目存在但内容为空/不完整时继续往上找,不要在这里给出空覆盖。
651
+ if (inherited.kind !== 'none') {
652
+ return { ...inherited, inheritedFrom: parentId, inheritedDepth: depth }
653
+ }
654
+ }
655
+ current = resolveAgentById(parentId)
656
+ if (current === undefined) return null
657
+ }
658
+ return null
659
+ }
660
+
661
+ /** 按 id 找活 agent;没有就返回 undefined。 */
662
+ function resolveAgentById(sessionId) {
663
+ const registry = agents()
664
+ if (registry === undefined) return undefined
665
+ try {
666
+ return registry.get(sessionId)
667
+ } catch {
668
+ return undefined
669
+ }
670
+ }
671
+
672
+ /**
673
+ * 判一个 agent 当前该不该有覆盖、以及是什么形态。
674
+ *
675
+ * 优先级:
676
+ * 1. 自身会话条目
677
+ * 2. 沿 parentSession 链继承(最近的有覆盖的祖先)
678
+ * 3. 全局默认(按 globalDefaultScope 决定是否碰子代理)
679
+ */
680
+ function effectiveFor(agent) {
681
+ const id = typeof agent?.id === 'string' ? agent.id : ''
682
+ const own = id !== '' ? runtime.state.sessions[id] : undefined
683
+ if (own !== undefined && own.enabled) return overrideFromEntry(own, 'session')
684
+ const inherited = findInheritedOverride(agent)
685
+ if (inherited !== null) return inherited
686
+ if (runtime.state.global.enabled) {
687
+ if (config.globalDefaultScope === 'roots' && !isRootAgent(agent)) {
688
+ return { kind: 'none', source: 'global', reason: 'subagent' }
689
+ }
690
+ return overrideFromEntry(runtime.state.global, 'global')
691
+ }
692
+ return { kind: 'none' }
693
+ }
694
+
695
+ /**
696
+ * 冷会话(没有活 agent)时的退化判定。
697
+ *
698
+ * 冷会话读不到 header,因此找不到父链——只能看自身条目与全局默认。
699
+ * 这是本方案的已知边界:冷会话的继承要等它被恢复(有了 agent)之后才成立。
700
+ */
701
+ function effectiveForId(sessionId) {
702
+ const agent = resolveAgentById(sessionId)
703
+ if (agent !== undefined) return effectiveFor(agent)
704
+ const own = runtime.state.sessions[sessionId]
705
+ if (own !== undefined && own.enabled) return overrideFromEntry(own, 'session')
706
+ if (runtime.state.global.enabled) return overrideFromEntry(runtime.state.global, 'global')
707
+ return { kind: 'none' }
708
+ }
709
+
710
+ function signatureOf(effective) {
711
+ return buildSignature(effective)
712
+ }
713
+
714
+ // ── 按 agent 装段 ────────────────────────────────────────────────────
715
+ function agents() {
716
+ const found = service('agents')
717
+ return found !== undefined && typeof found.list === 'function' ? found : undefined
718
+ }
719
+
720
+ /** 该 agent 作用域里的 systemPrompt;拿不到就返回 undefined(绝不退回归全局)。 */
721
+ function systemPromptFor(agent) {
722
+ const agentCtx = agent?.ctx
723
+ if (agentCtx === null || typeof agentCtx !== 'object') return undefined
724
+ try {
725
+ const direct = agentCtx.systemPrompt
726
+ if (direct !== null && typeof direct === 'object' && typeof direct.section === 'function') return direct
727
+ } catch {
728
+ /* 服务在该作用域不可用时属性访问可能抛错,继续走 ctx.get */
729
+ }
730
+ try {
731
+ const viaGet = typeof agentCtx.get === 'function' ? agentCtx.get('systemPrompt') : undefined
732
+ if (viaGet !== null && typeof viaGet === 'object' && typeof viaGet.section === 'function') return viaGet
733
+ } catch {
734
+ /* 同上 */
735
+ }
736
+ return undefined
737
+ }
738
+
739
+ function disposeSections(entry) {
740
+ if (entry === undefined) return
741
+ for (const dispose of entry.sections) {
742
+ try {
743
+ dispose()
744
+ } catch {
745
+ /* 重复释放是安全的 */
746
+ }
747
+ }
748
+ entry.sections = []
749
+ }
750
+
751
+ function recordOf(sessionId) {
752
+ let entry = runtime.installed.get(sessionId)
753
+ if (entry === undefined) {
754
+ entry = { agent: undefined, sections: [], signature: '', effective: { kind: 'none' }, error: '' }
755
+ runtime.installed.set(sessionId, entry)
756
+ }
757
+ return entry
758
+ }
759
+
760
+ /**
761
+ * 让某个 agent 的作用域与当前状态一致:比对「该装什么」与「已装什么」的
762
+ * 签名,只在形态变化时重装注册。文本变化不必重装——段的 text 是函数,
763
+ * 每次装配都会重新求值。
764
+ */
765
+ function install(agent) {
766
+ if (agent === null || typeof agent !== 'object') return
767
+ const sessionId = typeof agent.id === 'string' ? agent.id : ''
768
+ if (sessionId === '') return
769
+ const entry = recordOf(sessionId)
770
+ entry.agent = agent
771
+ if (!config.enabled) {
772
+ disposeSections(entry)
773
+ entry.signature = 'disabled'
774
+ entry.effective = { kind: 'none', reason: 'disabled' }
775
+ return
776
+ }
777
+ const effective = effectiveFor(agent)
778
+ const signature = signatureOf(effective)
779
+ if (entry.signature === signature) return
780
+ disposeSections(entry)
781
+ entry.signature = signature
782
+ entry.effective = effective
783
+ entry.error = ''
784
+ if (effective.kind === 'none') return
785
+
786
+ const systemPrompt = systemPromptFor(agent)
787
+ if (systemPrompt === undefined) {
788
+ entry.error = '该 agent 作用域里没有 systemPrompt 服务'
789
+ entry.effective = { kind: 'none', reason: 'no-systemPrompt' }
790
+ return
791
+ }
792
+ try {
793
+ const dispose = systemPrompt.section({
794
+ name: effective.target,
795
+ order: effective.order,
796
+ // 用户文本里的 {{…}} 必须保持字面,否则装配会因为「未知变量」直接抛错。
797
+ interpolate: false,
798
+ ...(effective.kind === 'complete' ? { complete: true } : {}),
799
+ // 每次装配重新求值:状态被清掉时立刻变空段(空段会被装配丢弃)。
800
+ text: () => {
801
+ try {
802
+ const now = effectiveFor(agent)
803
+ return signatureOf(now) === signature ? now.text : ''
804
+ } catch {
805
+ return ''
806
+ }
807
+ },
808
+ })
809
+ entry.sections.push(dispose)
810
+ } catch (error) {
811
+ entry.error = `注册提示词段失败:${message(error)}`
812
+ entry.effective = { kind: 'none', reason: 'register-failed' }
813
+ ctx.logger?.warn?.(`[system-prompt-studio] ${entry.error}`)
814
+ }
815
+ }
816
+
817
+ function uninstall(sessionId) {
818
+ const entry = runtime.installed.get(sessionId)
819
+ if (entry === undefined) return
820
+ disposeSections(entry)
821
+ runtime.installed.delete(sessionId)
822
+ }
823
+
824
+ function reinstallAll() {
825
+ const registry = agents()
826
+ if (registry === undefined) return
827
+ let list = []
828
+ try {
829
+ list = registry.list()
830
+ } catch {
831
+ list = []
832
+ }
833
+ for (const agent of list) install(agent)
834
+ }
835
+
836
+ // ── 生命周期接线 ──────────────────────────────────────────────────────
837
+ reinstallAll()
838
+ ctx.on('agent/created', (payload) => {
839
+ try {
840
+ install(payload?.agent)
841
+ } catch (error) {
842
+ ctx.logger?.warn?.(`[system-prompt-studio] agent/created 处理失败:${message(error)}`)
843
+ }
844
+ })
845
+ ctx.on('agent/disposed', (payload) => {
846
+ const id = typeof payload?.agent?.id === 'string' ? payload.agent.id : ''
847
+ if (id !== '') uninstall(id)
848
+ })
849
+ ctx.effect(() => () => {
850
+ for (const id of [...runtime.installed.keys()]) uninstall(id)
851
+ runtime.installed.clear()
852
+ runtime.observed.clear()
853
+ runtime.observedOrder.clear()
854
+ })
855
+
856
+ // ── 只读装配观察 ─────────────────────────────────────────────────────
857
+ /**
858
+ * 记录段名/位置/字符数,绝不改写 assembly。
859
+ *
860
+ * 一个实测出来的事实:`assembly.sections` 只带 `name` / `text` /
861
+ * `interpolate`,**没有 `order`**(顺序是装配时用来排序的输入,不进输出)。
862
+ * 所以这里记的是数组下标,顺序值再由 {@link deriveOrders} 从下标 + 已知常量
863
+ * 推算出来。这样「替换指定段」既能沿用它原本的位置,也不需要猜。
864
+ *
865
+ * 归因优先用装配上下文里的 `scope`——`assembleContextFor(agent)` 明确把
866
+ * `scope: agent` 一起传下来(agent 就是该会话的作用域键),所以这里拿到的
867
+ * 就是当步那个会话。拿不到时退回 `agents.currentInitiator()`,再拿不到就
868
+ * 只留在 `lastObserved` 里,面板退化成「最近一次装配」。
869
+ */
870
+ function observeAssembly(innerCtx, assembly, context) {
871
+ const sections = Array.isArray(assembly?.sections) ? assembly.sections : []
872
+ const bare = []
873
+ for (const section of sections) {
874
+ if (section === null || typeof section !== 'object') continue
875
+ const sectionName = typeof section.name === 'string' ? section.name : ''
876
+ if (sectionName === '') continue
877
+ const text = typeof section.text === 'string' ? section.text : ''
878
+ bare.push({ name: sectionName, chars: text.length })
879
+ }
880
+ const rows = deriveOrders(bare)
881
+ runtime.assembles += 1
882
+ // 同时记下时间(给人看)和写入序号(用来判过期)。前者有精度问题,
883
+ // 后者没有——比较新鲜度只认 seq。
884
+ const snapshot = { at: Date.now(), seq: runtime.writeSeq, sections: rows }
885
+ runtime.lastObserved = snapshot
886
+ for (const row of rows) {
887
+ if (typeof row.order === 'number') runtime.observedOrder.set(row.name, row.order)
888
+ }
889
+ let sessionId = typeof context?.scope?.id === 'string' ? context.scope.id : ''
890
+ if (sessionId === '') {
891
+ try {
892
+ const agent = innerCtx.get?.('agents')?.currentInitiator?.()
893
+ if (typeof agent?.id === 'string') sessionId = agent.id
894
+ } catch {
895
+ sessionId = ''
896
+ }
897
+ }
898
+ if (sessionId === '') return
899
+ runtime.observed.set(sessionId, snapshot)
900
+ while (runtime.observed.size > config.maxObservedScopes) {
901
+ const oldest = runtime.observed.keys().next()
902
+ if (oldest.done === true) break
903
+ runtime.observed.delete(oldest.value)
904
+ }
905
+ }
906
+
907
+ // ── 状态快照(GET 与写入后都返回同一形状) ───────────────────────────
908
+ /** 最近一次请求真正发出去的系统提示词:取活会话里最后一个 system 消息。 */
909
+ function currentSystemPrompt(sessions, sessionId) {
910
+ if (sessions === undefined || typeof sessions.get !== 'function') {
911
+ return { text: null, note: '当前 profile 没有 sessions 服务,读不到会话日志。' }
912
+ }
913
+ let session
914
+ try {
915
+ session = sessions.get(sessionId)
916
+ } catch {
917
+ session = undefined
918
+ }
919
+ if (session === undefined) return { text: null, note: '该对话当前没有在运行(冷会话),没有可读的最近请求。' }
920
+ let messages
921
+ try {
922
+ messages = typeof session.deriveMessages === 'function' ? session.deriveMessages() : []
923
+ } catch (error) {
924
+ return { text: null, note: `读取会话消息失败:${message(error)}` }
925
+ }
926
+ for (let index = messages.length - 1; index >= 0; index--) {
927
+ const candidate = messages[index]
928
+ if (candidate !== null && typeof candidate === 'object' && candidate.role === 'system') {
929
+ const text = textOfMessage(candidate)
930
+ if (text !== '') return { text }
931
+ }
932
+ }
933
+ return { text: null, note: '该对话还没有发出过带系统提示词的请求。' }
934
+ }
935
+
936
+ function snapshot(sessionId) {
937
+ const registry = agents()
938
+ const sessions = service('sessions')
939
+ const sysPrompt = service('systemPrompt')
940
+ const entry = sessionId !== '' ? runtime.state.sessions[sessionId] : undefined
941
+ const effective = sessionId !== '' ? effectiveForId(sessionId) : { kind: 'none' }
942
+ const record = sessionId !== '' ? runtime.installed.get(sessionId) : undefined
943
+ const watch = sessionId !== '' ? runtime.observed.get(sessionId) : undefined
944
+ const current = sessionId !== '' ? currentSystemPrompt(sessions, sessionId) : { text: null, note: '未指定会话。' }
945
+ let live = false
946
+ try {
947
+ live = sessionId !== '' && typeof registry?.get === 'function' ? registry.get(sessionId) !== undefined : false
948
+ } catch {
949
+ live = false
950
+ }
951
+ return {
952
+ ok: true,
953
+ ts: Date.now(),
954
+ capability: {
955
+ enabled: config.enabled,
956
+ systemPrompt: sysPrompt !== undefined,
957
+ agents: registry !== undefined,
958
+ sessions: sessions !== undefined,
959
+ observeAssemblies: config.observeAssemblies,
960
+ allowComplete: config.allowComplete,
961
+ },
962
+ sessionId,
963
+ live,
964
+ global: { ...runtime.state.global },
965
+ session: entry !== undefined ? { ...entry } : null,
966
+ effective: {
967
+ kind: effective.kind,
968
+ target: effective.target ?? '',
969
+ chars: typeof effective.text === 'string' ? effective.text.length : 0,
970
+ source: effective.source ?? 'none',
971
+ reason: effective.reason ?? '',
972
+ // 继承信息:面板据此显示「继承自 <父会话>」并提供「在此固定」。
973
+ inheritedFrom: effective.inheritedFrom ?? '',
974
+ inheritedDepth: typeof effective.inheritedDepth === 'number' ? effective.inheritedDepth : 0,
975
+ },
976
+ /** 该会话自身的父会话 id(没有则为空串);面板用来解释继承关系。 */
977
+ parentSession: parentIdOf(resolveAgentById(sessionId)),
978
+ install: record === undefined ? null : { signature: record.signature, error: record.error, count: record.sections.length },
979
+ sections: watch === undefined ? null : watch.sections,
980
+ /**
981
+ * 段清单是「最近一次装配」的快照,不是实时结果:装配只在模型请求时发生,
982
+ * 保存不会触发重新装配。不给时间戳的话,用户保存后打开面板看到旧清单,
983
+ * 会以为「保存没生效」。
984
+ */
985
+ sectionsAt: watch === undefined ? 0 : watch.at,
986
+ /** 该次装配时的写入序号;与 entry.writeSeq 比较即可判新鲜度。 */
987
+ sectionsSeq: watch === undefined || typeof watch.seq !== 'number' ? 0 : watch.seq,
988
+ /**
989
+ * 清单是否早于当前覆盖的保存。true = 面板必须提示「这是保存前的清单」。
990
+ *
991
+ * 比较的是写入序号,不是时间戳:保存和装配可能落在同一毫秒,
992
+ * `updatedAt > watch.at` 会在那时为假,把过期的清单判成最新。序号严格
993
+ * 单调,没有这个问题。旧状态文件里没有 `writeSeq`(升级前写的条目),
994
+ * 那种情况退回时间戳比较,行为与之前一致。
995
+ */
996
+ sectionsStale:
997
+ watch === undefined || entry === undefined
998
+ ? false
999
+ : typeof entry.writeSeq === 'number'
1000
+ ? entry.writeSeq > (typeof watch.seq === 'number' ? watch.seq : -1)
1001
+ : typeof entry.updatedAt === 'number' && entry.updatedAt > watch.at,
1002
+ /**
1003
+ * 当前生效的是 complete 模式。
1004
+ *
1005
+ * 这个标记存在的唯一原因:complete 的压缩发生在 `system-prompt/assemble`
1006
+ * waterfall **之后**(见 dsh-system-prompt 的 assemble:waterfall 拿到的是
1007
+ * 全量 sections,返回前才替换成 `[completeSection]`)。观察器挂在 waterfall
1008
+ * 上,因此它记录的永远是压缩前的全量清单——在 complete 模式下,面板显示的
1009
+ * 段清单与实际发送的内容必然不一致。把这件事明确标出来,而不是让用户自己
1010
+ * 对着 25 个段怀疑替换没生效。
1011
+ */
1012
+ sectionsComplete: effective.kind === 'complete',
1013
+ sectionsNote:
1014
+ watch !== undefined
1015
+ ? ''
1016
+ : config.observeAssemblies
1017
+ ? '该对话还没有装配过提示词(先发一条消息即可看到真实段清单)。'
1018
+ : '配置里关闭了装配观察,无法列出段清单。',
1019
+ current: current.text === null ? null : { text: current.text, chars: current.text.length, source: 'session-log' },
1020
+ currentNote: current.note ?? '',
1021
+ modes: MODES,
1022
+ defaultTargetName: config.defaultTargetName,
1023
+ limits: { maxChars: config.maxChars, appendOrder: config.appendOrder },
1024
+ observes: { assembles: runtime.assembles, sessions: runtime.observed.size, latest: runtime.lastObserved },
1025
+ health: { ...runtime.health },
1026
+ persisted: runtime.health.error === '',
1027
+ }
1028
+ }
1029
+
1030
+ /** 写入后:重装所有会话的段 + 落盘,返回持久化结果。 */
1031
+ async function applyState() {
1032
+ reinstallAll()
1033
+ return runtime.persist()
1034
+ }
1035
+
1036
+ /**
1037
+ * 记录一次状态写入,并返回这条条目该带的 `updatedAt` / `writeSeq`。
1038
+ *
1039
+ * 所有写入路径(set / clear / pin / resetAll)都必须经过这里,否则「清单
1040
+ * 是否过期」的判定就会漏掉某条路径——而漏掉的后果是面板沉默,用户继续
1041
+ * 对着旧清单猜,正是这个字段要解决的问题。
1042
+ */
1043
+ function stampWrite() {
1044
+ runtime.writeSeq += 1
1045
+ return { updatedAt: Date.now(), writeSeq: runtime.writeSeq }
1046
+ }
1047
+
1048
+ function validate(entry) {
1049
+ if (entry.text.length > config.maxChars) return 'TEXT_TOO_LONG'
1050
+ if (entry.enabled && entry.text.trim() === '') return 'EMPTY_TEXT'
1051
+ if (entry.mode === 'replace' && entry.target.trim() === '') return 'TARGET_REQUIRED'
1052
+ if (entry.mode === 'complete' && entry.enabled && !config.allowComplete) return 'COMPLETE_BLOCKED'
1053
+ return ''
1054
+ }
1055
+
1056
+ function reasonFor(code) {
1057
+ if (code === 'TEXT_TOO_LONG') return `正文超过上限 ${config.maxChars} 字符,请精简后再保存(不会被截断保存)。`
1058
+ if (code === 'EMPTY_TEXT') return '启用了覆盖但正文为空:请填写正文,或关掉这个覆盖。'
1059
+ if (code === 'TARGET_REQUIRED') return '替换模式必须给目标段名。'
1060
+ if (code === 'COMPLETE_BLOCKED') return '配置里 allowComplete=false,完全替换模式被禁用。'
1061
+ return code
1062
+ }
1063
+
1064
+ /** POST 的校验与写入。所有拒绝都带稳定 error code,成功时返回写入后的完整快照。 */
1065
+ async function handlePost(payload) {
1066
+ const body = payload !== null && typeof payload === 'object' ? payload : {}
1067
+ const action = typeof body.action === 'string' ? body.action : ''
1068
+ const scope = body.scope === 'global' ? 'global' : 'session'
1069
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1070
+
1071
+ if (action === 'resetAll') {
1072
+ if (body.confirm !== true) {
1073
+ return { status: 400, body: { ok: false, error: 'CONFIRM_REQUIRED', message: '清空全部会话覆盖需要 confirm: true。' } }
1074
+ }
1075
+ runtime.state.sessions = {}
1076
+ const persisted = await applyState()
1077
+ return { status: 200, body: { ...snapshot(''), persisted } }
1078
+ }
1079
+
1080
+ if (action !== 'set' && action !== 'clear' && action !== 'pin') {
1081
+ return { status: 400, body: { ok: false, error: 'UNKNOWN_ACTION', message: `未知 action:${action || '(空)'}` } }
1082
+ }
1083
+ if (scope === 'session' && sessionId === '') {
1084
+ return { status: 400, body: { ok: false, error: 'MISSING_SESSION', message: '作用域是 session 时必须给 sessionId。' } }
1085
+ }
1086
+
1087
+ if (action === 'clear') {
1088
+ if (scope === 'global') runtime.state.global = { ...emptyEntry(config.defaultMode), ...stampWrite() }
1089
+ else delete runtime.state.sessions[sessionId]
1090
+ const persisted = await applyState()
1091
+ return { status: 200, body: { ...snapshot(sessionId), persisted } }
1092
+ }
1093
+
1094
+ /**
1095
+ * pin:把当前「继承来的」覆盖固化成本会话自己的条目。
1096
+ *
1097
+ * 用途是给继承一个可控的出口——用户 fork 之后想在这个分支上独立调整,
1098
+ * 又不想从头再写一遍。父会话之后再改,这个分支就不跟着变了,这正是
1099
+ * 「固定」的语义。
1100
+ */
1101
+ if (action === 'pin') {
1102
+ if (scope !== 'session') {
1103
+ return { status: 400, body: { ok: false, error: 'PIN_SESSION_ONLY', message: 'pin 只对具体会话有效。' } }
1104
+ }
1105
+ const effective = effectiveForId(sessionId)
1106
+ if (effective.kind === 'none') {
1107
+ return { status: 400, body: { ok: false, error: 'NOTHING_TO_PIN', message: '该会话当前没有可固定的覆盖(没有继承,也没有全局默认)。' } }
1108
+ }
1109
+ const pinned = {
1110
+ enabled: true,
1111
+ mode: effective.kind,
1112
+ text: effective.text,
1113
+ target: effective.kind === 'replace' ? effective.target : '',
1114
+ ...stampWrite(),
1115
+ }
1116
+ const invalid = validate(pinned)
1117
+ if (invalid !== '') {
1118
+ return { status: 400, body: { ok: false, error: invalid, message: reasonFor(invalid) } }
1119
+ }
1120
+ runtime.state.sessions[sessionId] = pinned
1121
+ const persisted = await applyState()
1122
+ return { status: 200, body: { ...snapshot(sessionId), persisted } }
1123
+ }
1124
+
1125
+ const patch = body.patch !== null && typeof body.patch === 'object' ? body.patch : {}
1126
+ const current =
1127
+ scope === 'global' ? runtime.state.global : runtime.state.sessions[sessionId] ?? emptyEntry(config.defaultMode)
1128
+ // 逐字段合并:只写用户真正提交的键,避免面板把没传的键清掉。
1129
+ const next = {
1130
+ enabled: typeof patch.enabled === 'boolean' ? patch.enabled : current.enabled,
1131
+ mode: MODES.includes(patch.mode) ? patch.mode : current.mode,
1132
+ text: typeof patch.text === 'string' ? patch.text : current.text,
1133
+ target: typeof patch.target === 'string' ? patch.target : current.target,
1134
+ ...stampWrite(),
1135
+ }
1136
+
1137
+ const invalid = validate(next)
1138
+ if (invalid !== '') {
1139
+ return {
1140
+ status: 400,
1141
+ body: { ok: false, error: invalid, message: reasonFor(invalid), limits: { maxChars: config.maxChars } },
1142
+ }
1143
+ }
1144
+
1145
+ if (scope === 'global') runtime.state.global = next
1146
+ else runtime.state.sessions[sessionId] = next
1147
+ const persisted = await applyState()
1148
+ return { status: 200, body: { ...snapshot(sessionId), persisted } }
1149
+ }
1150
+
1151
+ // ── 路由 ──────────────────────────────────────────────────────────────
1152
+ const webServer = service('webServer')
1153
+ if (webServer !== undefined && typeof webServer.register === 'function') {
1154
+ try {
1155
+ const dispose = webServer.register({
1156
+ kind: 'exact',
1157
+ path: config.apiPath,
1158
+ handler: async (req, res) => {
1159
+ const cors = corsHeaders(req)
1160
+ if (!isLoopbackRequest(req)) {
1161
+ writeJson(res, 403, { ok: false, error: 'forbidden: loopback-only' }, cors)
1162
+ return
1163
+ }
1164
+ if (req.method === 'OPTIONS') {
1165
+ res.writeHead(204, cors)
1166
+ res.end()
1167
+ return
1168
+ }
1169
+ try {
1170
+ if (req.method === 'GET') {
1171
+ let params
1172
+ try {
1173
+ params = new URL(req.url ?? '/', 'http://x').searchParams
1174
+ } catch {
1175
+ params = undefined
1176
+ }
1177
+ writeJson(res, 200, snapshot(params === undefined ? '' : params.get('session') ?? ''), cors)
1178
+ return
1179
+ }
1180
+ if (req.method === 'POST') {
1181
+ const payload = await readJsonBody(req, config.maxChars * 4)
1182
+ const result = await handlePost(payload)
1183
+ writeJson(res, result.status, result.body, cors)
1184
+ return
1185
+ }
1186
+ writeJson(res, 405, { ok: false, error: 'method-not-allowed', allow: 'GET, POST, OPTIONS' }, cors)
1187
+ } catch (error) {
1188
+ const status = typeof error?.status === 'number' ? error.status : 500
1189
+ writeJson(res, status, { ok: false, error: error?.code ?? 'internal-error', message: message(error) }, cors)
1190
+ if (status >= 500) ctx.logger?.warn?.(`[system-prompt-studio] 请求失败:${message(error)}`)
1191
+ }
1192
+ },
1193
+ })
1194
+ ctx.effect(() => () => {
1195
+ try {
1196
+ dispose()
1197
+ } catch {
1198
+ /* disposal is best-effort */
1199
+ }
1200
+ })
1201
+ } catch (error) {
1202
+ ctx.logger?.warn?.(`[system-prompt-studio] 路由注册失败(${config.apiPath}):${message(error)}`)
1203
+ }
1204
+ } else {
1205
+ ctx.logger?.warn?.('[system-prompt-studio] 没有 webServer,面板拿不到状态;提示词覆盖仍然按配置生效。')
1206
+ }
1207
+
1208
+ // 测试出口:只有显式启用时才挂内部句柄,正常运行时这一整段被跳过。
1209
+ // 见 __internals 的注释——模块导出会进入宿主进程,不能默认暴露写入路径。
1210
+ if (testHook === true || process.env.NODE_ENV === 'test') {
1211
+ runtime.test = { install, uninstall, reinstallAll, snapshot, handlePost, effectiveFor, effectiveForId }
1212
+ }
1213
+ })
1214
+
1215
+ /**
1216
+ * 测试与诊断用的只读入口。
1217
+ *
1218
+ * 这里**只放纯函数与状态快照**,绝不放 `install` / `handlePost` / `snapshot` 这类
1219
+ * 能改变运行期的内部函数——模块导出对象会随包一起进入宿主进程,任何同进程代码
1220
+ * 只要 import 就能绕过 HTTP 回环围栏直接改状态。
1221
+ *
1222
+ * 需要驱动 `handlePost` 之类的测试,走 `__internals.testHook()`:它只在
1223
+ * `process.env.NODE_ENV === 'test'` 或显式调用 `__internals.enableTestHook()` 后
1224
+ * 才有值,正常运行时恒为 `undefined`。
1225
+ */
1226
+ let testHook = undefined
1227
+
1228
+ export const __internals = {
1229
+ MODES,
1230
+ DEFAULTS,
1231
+ APPEND_SECTION,
1232
+ COMPLETE_SECTION,
1233
+ KNOWN_ORDERS,
1234
+ ORDER_MIN,
1235
+ ORDER_MAX,
1236
+ MAX_INHERIT_DEPTH,
1237
+ resolveConfig,
1238
+ normalizeEntry,
1239
+ emptyState,
1240
+ emptyEntry,
1241
+ textOfMessage,
1242
+ deriveOrders,
1243
+ isLoopbackRequest,
1244
+ isIPv4Loopback,
1245
+ isLoopbackHostname,
1246
+ readJsonBody,
1247
+ signatureOf: buildSignature,
1248
+ /** 只读的运行期状态快照(配置、计数器、缓存);不含任何可调用入口。 */
1249
+ readRuntime: () => ({
1250
+ config: { ...runtime.config },
1251
+ state: JSON.parse(JSON.stringify(runtime.state)),
1252
+ health: { ...runtime.health },
1253
+ assembles: runtime.assembles,
1254
+ installed: runtime.installed.size,
1255
+ observed: runtime.observed.size,
1256
+ lastObserved: runtime.lastObserved,
1257
+ }),
1258
+ /** 何时可用:测试显式打开,或 NODE_ENV=test。返回值本身不做鉴权,仅作断点。 */
1259
+ testHook: () => testHook,
1260
+ /** 仅供测试进程调用,让下一次 apply 暴露内部句柄。 */
1261
+ enableTestHook: () => {
1262
+ testHook = true
1263
+ },
1264
+ }
1265
+