@zenux/dsh-theme-endfield 0.0.0-stage → 1.2.27

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,1647 @@
1
+ 'use strict';
2
+ /**
3
+ * @zenux/dsh-theme-endfield — installed (bundle) HOST half.
4
+ *
5
+ * This module is the cordis plugin the loader mounts when the package is
6
+ * installed through the official CLI:
7
+ *
8
+ * dsh plugin --profile web add @zenux/dsh-theme-endfield
9
+ *
10
+ * The `dsh.bundle.patch` layer (cordis.patch.yml) inserts this package's row;
11
+ * the loader requires this main entry and uses its `name` + `apply` exports.
12
+ * The theme itself is pure client-side (browser): token overrides via the
13
+ * `theme` service and a global stylesheet via the `styles` builtin, both
14
+ * registered in the client half (`exports["./client"]` -> client.js).
15
+ *
16
+ * Durable preferences, per DSH generation
17
+ * ---------------------------------------
18
+ * The theme's switches used to live in the browser's `localStorage`, which is
19
+ * scoped to a single origin: DSH Desktop binds a fresh, random loopback port on
20
+ * every launch, so a port change changed the origin and the stored settings
21
+ * silently reset to defaults.
22
+ *
23
+ * DSH 0.1.7-rc.1 replaced that whole persistence layer once more:
24
+ *
25
+ * - `ctx.settings.register(namespace, schema)` is GONE, `@deepseek-ai/
26
+ * dsh-settings-file` is not part of the distribution any more, and
27
+ * `<dshHome>/settings.yaml` is no longer the user-settings carrier (DSH
28
+ * renames an existing file to `settings.yaml.imported` on first boot and
29
+ * only remaps a few section names). `ctx.settings` now *projects plugin
30
+ * Config schemas into forms* (`configure/describe/update/replace/mutate`)
31
+ * and persists user edits into the PROFILE PATCH
32
+ * (`<profile>/cordis.patch.yml`) through `ctx.configEditor`.
33
+ * - The settings namespace of a plugin is therefore the PROFILE ENTRY ID —
34
+ * the `id` of the row this package's `cordis.patch.yml` inserts
35
+ * (`theme-endfield`), NOT the old namespace string. That id is
36
+ * SETTINGS_ENTRY below; the browser half reads/writes it through the
37
+ * `configForms` client service.
38
+ * - Only schema fields marked `.volatile()` are user-editable, which is why
39
+ * every field of the exported `Config` below carries `.volatile()`.
40
+ *
41
+ * The browser half (client.js) reaches the same entry over the
42
+ * `configForms.get('theme-endfield')` mirror and live-reacts to changes with
43
+ * the form's subscription (and still falls back to the pre-0.1.7
44
+ * `ctx.settingsScope` seam on older hosts).
45
+ *
46
+ * The namespace fields mirror exactly the setting keys, defaults and polarity
47
+ * the theme has always shipped (see docs/features.md): default-ON switches
48
+ * default to the string '1' and are read with `!== '0'`, default-OFF switches
49
+ * default to '0' and are read with `=== '1'`. Choosing string-typed schema
50
+ * fields keeps the value model (and the settings panel's own reads/writes)
51
+ * byte-for-byte identical to every previous storage generation, so the client
52
+ * store, its key table and its tests did not have to change with the transport.
53
+ *
54
+ * `schemastery` is deliberately imported lazily and only from the host realm:
55
+ * this package otherwise ships no runtime dependency beyond the optional
56
+ * cordis peer, so the theme degrades to a no-op the same way it always did in
57
+ * any profile that does not supply a settings service.
58
+ *
59
+ * Host-side audio notifications (optional)
60
+ * -------------------------------------------------------------------
61
+ * `lib/audio.js` plays the two (later: four) notification slots. It is wired
62
+ * here because the host, not the page, is what survives a minimized window.
63
+ * `subprocess` is probed at play time rather than declared in `inject`: a
64
+ * profile without that seam must keep the theme fully working and simply stay
65
+ * silent, not fail to load.
66
+ */
67
+
68
+ const { AudioRuntime, PREF, FALLBACK: AUDIO_FALLBACK, LOG_TAG } = require('./lib/audio.js');
69
+ const { SLOT_IDS } = require('./lib/slots.js');
70
+
71
+ const NAME = 'dsh-theme-endfield';
72
+
73
+ /**
74
+ * DSH 0.1.7-rc.1 settings namespace: the profile entry id of this plugin's row
75
+ * (cordis.patch.yml: `id: theme-endfield`). `ctx.settings.describe()` keys every
76
+ * form by `entry.options.id`, and the browser's `configForms.get(ns)` mirrors
77
+ * the same string, so this constant is what ties the two halves together.
78
+ */
79
+ const SETTINGS_ENTRY = 'theme-endfield';
80
+
81
+ /**
82
+ * Pre-0.1.7 settings namespace, registered through `ctx.settings.register` and
83
+ * persisted to `<dshHome>/settings.yaml`. Kept so an older host keeps working
84
+ * (and so the legacy client seam in client.js still has a producer).
85
+ */
86
+ const LEGACY_NAMESPACE = 'dsh-theme-endfield';
87
+
88
+ /** Historical name of the namespace; kept for callers and tests. */
89
+ const NAMESPACE = LEGACY_NAMESPACE;
90
+
91
+ /**
92
+ * Schema defaults for every field. Field names are the short tails of the
93
+ * original localStorage keys (the `dsh-theme-endfield-` prefix is implied by
94
+ * the namespace). Keeping the actual stored values as strings means the value
95
+ * model survives every storage generation unchanged, and an older persisted
96
+ * document still validates without a migration step.
97
+ *
98
+ * Default polarity (same rules as before, now enforced by the schema defaults
99
+ * instead of by an "absent key" check, and documented in docs/features.md):
100
+ * - default-ON switches store '1' and the client reads them as `!== '0'`;
101
+ * - default-OFF switches store '0' and the client reads them as `=== '1'`;
102
+ * - palettes / radii / frame-rate / speed each store exactly one of their
103
+ * documented literals ('valley'/'wuling'/'ember'/'abyss'; 'square'/'round'; fps in
104
+ * 24/60/120; speed in 1/2/4), with the shipped default filled in here.
105
+ */
106
+ const FIELD_DEFAULTS = {
107
+ enabled: '1', // 终末地主题 —— default on
108
+ palette: 'valley', // 主题配色 —— 谷地黄 (walley default)
109
+ glass: 'off', // optional local frost; original material by default
110
+ radius: 'square', // 主题圆角 —— 直角
111
+ contour: '0', // 等高线背景 —— default off
112
+ contourAnim: '1', // 动态等高线 —— default on
113
+ contourFps: '24', // 动态帧率 —— 24 FPS
114
+ contourSpeed: '2', // 动态速度 —— 标准 2x
115
+ contourRenderer: 'canvas', // opt-in Worker/WebGL; original backend by default
116
+ contourTrail: '0', // optional mouse deformation, default off
117
+ contourScrollPause: '1', // 滚动暂停 —— default on
118
+ // 输出滚动动画 —— default ON. It leaves the app's own scroll bookkeeping
119
+ // untouched (the scrollTop read-back stays exact, so stream following survives)
120
+ // and only compensates the transcript column visually, so an install that
121
+ // upgrades into it gets smoother streaming output with nothing to configure.
122
+ scrollAnim: '1',
123
+ scrollAnimLevel: 'standard', // 动画强度 —— soft / standard / snappy
124
+ watermark: '1', // 背景水印 —— default on
125
+ watermarkPersist: '0', // 水印保持显示 —— default off
126
+ // 开机音频的独立音量(0–100):只作用于 login 槽位,与音频通知音量互不影响。
127
+ bootVolume: '100',
128
+ // 视频背景(第二种背景方案,与等高线/水印互斥):素材由 Host 的
129
+ // /theme-endfield/media 路由提供,页面负责 A/B/C/B_rev 的相位编排。
130
+ video: '0',
131
+ // 视频音频(A 用 27.5408s 循环段、B/C 用 30.1s 起的整段):默认开。
132
+ videoSound: '1',
133
+ loader: '0', // 启动加载动画 —— default off
134
+ // 开机音频(03 动画):页面加载时播放 sounds/login.wav。独立于音频通知总开关,
135
+ // 有自己的开关;默认关,避免升级后突然出声。
136
+ bootAudio: '0',
137
+ thunder: '0', // 雷霆大字 —— default off
138
+ thunderAnim: '0', // 大字入场动画 —— default off
139
+ /* 播报词。留空 = 用内置的「任务开始」/「任务完成」,所以这两个字段的默认值
140
+ 不会把任何人的界面改掉。底部那行萨卡兹字母是固定的装饰签名,没有字段。 */
141
+ thunderStartText: '', // 开始播报词,留空用「任务开始」
142
+ thunderDoneText: '', // 结束播报词,留空用「任务完成」
143
+ balanceCapsule: '0', // 顶部余额胶囊 —— default off
144
+ creditDisplay: 'remaining', // 渠道额度主读数 —— remaining(剩余)| used(已用)
145
+ balanceCapsulePosition: 'center', // 余额胶囊位置 —— center(居中)| left(靠左)| right(靠右)
146
+ balanceCapsuleSidebarHide: '0', // 防遮挡:侧边栏展开自动隐藏 —— default off
147
+ balanceCapsuleHoverHide: '1', // 防遮挡:指针靠近自动隐藏 —— default on
148
+ // --- 音频通知 ---------------------------------------------------------
149
+ // Four live slots: the boot plate, the prompt that starts a turn, the final
150
+ // answer that ends one, and `attention` for the two moments that actually
151
+ // need a human (an approval request and my own question). `turn-fail` ships as
152
+ // a sound and a switch but is wired to nothing on purpose: an error that needs
153
+ // no human decision must stay silent.
154
+ //
155
+ // The MASTER switch ships OFF: sound is opt-in, so an install that upgrades
156
+ // into this feature never starts making noise on its own. The per-slot
157
+ // switches stay ON, which is why flipping the master on is enough to hear the
158
+ // live slots; each one can then be silenced individually.
159
+ audioEnabled: '0', // 音频通知总开关 —— default OFF(默认不出声,需手动开启)
160
+ audioVolume: '100', // 音量 0-100 —— rescaled PCM, not system volume
161
+ audioBoot: '1', // 启动加载动画音 —— 页面加载播放加载板时响一次
162
+ audioTurnStart: '1', // 任务开始音 —— 会话框提交后播放
163
+ audioTurnDone: '1', // 任务结束音 —— 最终结果产出后播放
164
+ audioAttention: '1', // 需要你回应 —— 审批请求 / 我的提问 / 计划求批
165
+ audioTurnFail: '1', // 出错音 —— 无事件接线:不需要人工干预的错误保持静音
166
+ audioDebounceMs: '2500', // 同一槽位最小间隔
167
+ audioSoundDir: '', // 自定义音效目录,留空则用工作区/桌面/内置
168
+ audioHumanOnly: '1', // 开始音只认会话框提交(带 rpcId 的用户消息)
169
+ audioDiag: '0', // 诊断日志 —— 记录事件与判定结果
170
+
171
+ // --- 颜色微调(深浅双档案) + 审批弹窗形态 ------------------------------
172
+ // Theme switching stays the one-click form (palette / radius / glass); these
173
+ // values nudge individual colour roles ON TOP of whatever the palette produced,
174
+ // without touching the palette classes. ONE JSON field holds BOTH schemes:
175
+ //
176
+ // tintProfiles = {"light":{"accent":{"hex":"#c05a2b","bright":100,
177
+ // "alpha":100,"src":"user"}, …},
178
+ // "dark": {… "src":"auto"}}
179
+ //
180
+ // Per role per scheme: hex '' = follow the theme, else '#rrggbb'; bright
181
+ // 60..140; alpha 0..100; src 'user' (edited in that scheme) or 'auto'
182
+ // (predicted from the other scheme and cached, so a scheme flip costs a
183
+ // lookup instead of a re-prediction). An empty string is "no tuning at all",
184
+ // which is why an install that upgrades into this block renders as before.
185
+ tintProfiles: '',
186
+ tintDecor: '100', // 装饰强度 —— 水印与等高线描边的不透明度
187
+ // 微调预设:JSON 数组 [{name, profiles: {light,dark}, decor}]。保存时快照
188
+ // 「深浅两套 + 装饰强度」;名称在客户端做冲突校验(不区分大小写),重名拒绝。
189
+ tintPresets: '',
190
+ // 审批弹窗形态:'0' = 终末地全屏白条(默认),'1' = DSH 自己的对话框(颜色仍跟主题)
191
+ approvalNative: '0',
192
+ };
193
+
194
+ /** The two spellings a reachable Schemastery builder can have on disk. */
195
+ const SCHEMA_SPECS = ['@deepseek-ai/schemastery', 'schemastery'];
196
+
197
+ /* Where a usable builder came from, for the diagnostics apply() logs. Set by
198
+ loadSchemastery; stays null while nothing was found. */
199
+ let SCHEMA_SOURCE = null;
200
+
201
+ /* HOW the chosen builder marks a field editable — also for the diagnostics.
202
+ 'native' the builder carries schemastery's own `.volatile()`;
203
+ 'synthesized' it predates `.volatile()`, so the marker is set through the
204
+ generic `.extra('volatile', true)` that `.volatile()` is
205
+ implemented on top of;
206
+ 'plain' the builder marks nothing; only ever chosen for the pre-0.1.7
207
+ registration, which persisted whole namespaces;
208
+ null no usable builder was found at all, so this entry exports no
209
+ Config and every preference stays page-local. */
210
+ let SCHEMA_MODE = null;
211
+
212
+ /* Resolve a Schemastery namespace builder.
213
+
214
+ This file has no schemastery dependency of its own (it must stay installable
215
+ with nothing but an optional cordis peer), so the builder is RESOLVED at
216
+ module-evaluation time — the loader reads `Config` off this module before any
217
+ plugin body runs, which is why the whole search happens at the top level.
218
+
219
+ 1) Published profile installs put schemastery / @deepseek-ai/schemastery on
220
+ this package's OWN require path (real bundles like dsh-better-sidebar do
221
+ `import z from "schemastery"` and it resolves). Those are covered by the
222
+ first tries below.
223
+ 2) A DEV-LINK bundle (this repo symlinked into the profile's node_modules,
224
+ e.g. `"dsh-theme-endfield": "link:E:/..."`) does NOT: Node resolves the
225
+ symlink to its real path first, so this file's own require chain starts at
226
+ the repo (E:\…), where no schemastery lives — the bare requires throw
227
+ MODULE_NOT_FOUND and the profile's node_modules is never consulted. So
228
+ when they miss, every DSH-rooted directory that could own a copy is asked
229
+ explicitly ({@link resolutionRoots}, resolved through
230
+ `require.resolve(spec, { paths })`, the form that expresses "as if from
231
+ here").
232
+ 3) WHICH builder matters, not just any builder. DSH ships BOTH
233
+ `@deepseek-ai/schemastery` (>= 3.18, has `.volatile()`) and the unscoped
234
+ `schemastery` that some third-party plugins depend on (3.18.0, NO
235
+ `.volatile()` at all). Only a volatile schema produces an editable form in
236
+ DSH 0.1.7, so `loadSchemastery(true)` keeps scanning until it finds a
237
+ builder that really has `.volatile()` and returns undefined otherwise —
238
+ silently claiming a form we cannot build is exactly the "settings won't
239
+ save" class of bug this file keeps guarding against.
240
+ Kept guarded throughout: a profile with no usable schemastery degrades to a
241
+ no-op rather than crashing the host half — but a no-op is no longer silent:
242
+ apply() logs which roots were tried, because "the theme works yet every
243
+ switch resets on reload" is precisely this failure and it used to leave no
244
+ trace at all. */
245
+
246
+ /** Every directory a DSH-owned schemastery install could be resolved from.
247
+ * Order is most-likely first; duplicates are dropped.
248
+ * @returns absolute directory paths to resolve from. */
249
+ function resolutionRoots() {
250
+ const fs = require('fs');
251
+ const path = require('path');
252
+ const out = [];
253
+ const push = (dir) => {
254
+ if (typeof dir !== 'string' || dir === '') return;
255
+ if (out.indexOf(dir) === -1) out.push(dir);
256
+ };
257
+ // This module's own tree: a profile- or app-installed package resolves here.
258
+ push(__dirname);
259
+ // The module the DSH process was started with. Its own graph necessarily
260
+ // reaches schemastery (the host settings service imports it), so this is the
261
+ // one root that exists wherever DSH itself is installed — a global npm
262
+ // install, an app bundle, or the profile.
263
+ try { if (require.main && require.main.filename) push(path.dirname(require.main.filename)); } catch (e) { /* no main module */ }
264
+ try { if (require.main && typeof require.main.path === 'string') push(require.main.path); } catch (e) { /* no main module */ }
265
+ // The process working directory: `dsh web` is normally started from a profile.
266
+ try { push(process.cwd()); } catch (e) { /* no cwd */ }
267
+ // Ancestors of this module, so a checkout nested under a tree that has its own
268
+ // node_modules resolves without knowing anything about DSH's layout.
269
+ let dir = __dirname;
270
+ for (let i = 0; i < 6; i += 1) {
271
+ const parent = path.dirname(dir);
272
+ if (!parent || parent === dir) break;
273
+ dir = parent;
274
+ push(path.join(dir, 'node_modules'));
275
+ push(dir);
276
+ }
277
+ // The DSH home and every profile under it — the profiles root itself, each
278
+ // profile, and each profile's node_modules (where the scoped copy lives).
279
+ for (const home of dshHomeDirs()) pushLayout(home, push);
280
+ // The same layout, discovered STRUCTURALLY rather than from the environment:
281
+ // a DSH home is the directory whose `profiles/<name>/node_modules` holds the
282
+ // install, so walking up from anything the process can name finds it without
283
+ // trusting DSH_HOME, homedir() or the working directory to be any particular
284
+ // value. This is the sweep that survives a launcher which sets none of them.
285
+ for (const seed of processSeeds()) {
286
+ let base = seed;
287
+ for (let i = 0; i < 5; i += 1) {
288
+ const parent = path.dirname(base);
289
+ if (!parent || parent === base) break;
290
+ base = parent;
291
+ push(base);
292
+ push(path.join(base, 'node_modules'));
293
+ pushLayout(base, push);
294
+ }
295
+ }
296
+ // The launched script and the node binary: a global `dsh` install keeps its
297
+ // dependencies beside one of them, which is where a copy would live when DSH
298
+ // itself is not installed into the profile.
299
+ try { if (process.argv && typeof process.argv[1] === 'string') push(path.dirname(process.argv[1])); } catch (e) { /* no argv */ }
300
+ try { push(path.dirname(process.execPath)); } catch (e) { /* no execPath */ }
301
+ try {
302
+ const appData = process.env && (process.env.APPDATA || process.env.LOCALAPPDATA);
303
+ if (typeof appData === 'string' && appData) push(path.join(appData, 'npm', 'node_modules'));
304
+ } catch (e) { /* no app data */ }
305
+ // Every PATH directory (bounded): the parent of a global `dsh` shim, and any
306
+ // other install root an operator put in front of it.
307
+ try {
308
+ const raw = process.env && process.env.PATH;
309
+ if (typeof raw === 'string' && raw) {
310
+ const entries = raw.split(path.delimiter);
311
+ for (let i = 0; i < entries.length && i < 40; i += 1) push(entries[i]);
312
+ }
313
+ } catch (e) { /* no PATH */ }
314
+ return out;
315
+ }
316
+
317
+ /** Every directory this process can name as a starting point for a layout
318
+ * search. Each one is expected to sit INSIDE a DSH tree of some shape.
319
+ * @returns absolute directory paths. */
320
+ function processSeeds() {
321
+ const path = require('path');
322
+ const out = [];
323
+ const push = (dir) => {
324
+ if (typeof dir !== 'string' || dir === '') return;
325
+ if (out.indexOf(dir) === -1) out.push(dir);
326
+ };
327
+ push(__dirname);
328
+ try { push(process.cwd()); } catch (e) { /* no cwd */ }
329
+ try { if (require.main && require.main.filename) push(path.dirname(require.main.filename)); } catch (e) { /* no main module */ }
330
+ try { if (process.argv && typeof process.argv[1] === 'string') push(path.dirname(process.argv[1])); } catch (e) { /* no argv */ }
331
+ try { push(path.dirname(process.execPath)); } catch (e) { /* no execPath */ }
332
+ return out;
333
+ }
334
+
335
+ /** Add one directory's DSH layout: the directory itself, its node_modules, and
336
+ * each of its profiles with that profile's node_modules.
337
+ * @param base - candidate DSH home.
338
+ * @param push - collector for a de-duplicated root. */
339
+ function pushLayout(base, push) {
340
+ if (typeof base !== 'string' || base === '') return;
341
+ const fs = require('fs');
342
+ const path = require('path');
343
+ push(base);
344
+ push(path.join(base, 'node_modules'));
345
+ const profiles = path.join(base, 'profiles');
346
+ push(profiles);
347
+ push(path.join(profiles, 'node_modules'));
348
+ try {
349
+ if (fs.existsSync(profiles)) {
350
+ for (const name of fs.readdirSync(profiles)) {
351
+ const profile = path.join(profiles, name);
352
+ push(profile);
353
+ push(path.join(profile, 'node_modules'));
354
+ }
355
+ }
356
+ } catch (e) { /* an unreadable profiles dir just yields no extra roots */ }
357
+ }
358
+
359
+ /** The DSH home directories to consider, most explicit first.
360
+ * @returns candidate absolute home paths (may be empty). */
361
+ function dshHomeDirs() {
362
+ const out = [];
363
+ const push = (dir) => {
364
+ if (typeof dir !== 'string' || dir === '') return;
365
+ if (out.indexOf(dir) === -1) out.push(dir);
366
+ };
367
+ try { if (process.env && typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME) push(process.env.DSH_HOME); } catch (e) { /* no env */ }
368
+ try { push(require('path').join(require('os').homedir(), '.dsh')); } catch (e) { /* no home dir */ }
369
+ return out;
370
+ }
371
+
372
+ function normalizeSchemastery(found) {
373
+ if (!found) return undefined;
374
+ // Normalize a CJS default-export wrapper to a plain { string, object } API.
375
+ if (found.default && !found.object && found.default.object && found.default.string) {
376
+ return {
377
+ string: (v) => found.default.string(v),
378
+ object: (o) => found.default.object(o),
379
+ union: typeof found.default.union === 'function' ? (...a) => found.default.union(...a) : undefined,
380
+ };
381
+ }
382
+ return found;
383
+ }
384
+
385
+ /** Does this builder have the `.volatile()` modifier (schemastery >= 3.18)? */
386
+ function hasVolatile(z) {
387
+ try { return !!(z && typeof z.string === 'function' && typeof z.string().volatile === 'function'); }
388
+ catch (e) { return false; }
389
+ }
390
+
391
+ /** Does this builder expose the generic `.extra()` metadata setter?
392
+ *
393
+ * `Schema.prototype.volatile` (schemastery >= 3.18.4) is LITERALLY
394
+ * `this.extra('volatile', true)`, and `.extra()` has existed since long before
395
+ * it — including in the unscoped `schemastery` 3.18.0 that ships NO
396
+ * `.volatile()` at all. Marking a field through `.extra()` therefore produces
397
+ * the very schema node DSH's settings service looks for (`meta.volatile`),
398
+ * which is what keeps the form editable on a host whose only reachable *and
399
+ * loadable* builder is one of those older copies. */
400
+ function hasVolatileMarker(z) {
401
+ try { return !!(z && typeof z.string === 'function' && typeof z.string().extra === 'function'); }
402
+ catch (e) { return false; }
403
+ }
404
+
405
+ /** Mark one leaf field editable, by whichever of the two spellings the selected
406
+ * builder supports. The leaf comes back unchanged only when it supports
407
+ * neither, which {@link selectBuilder} never picks on purpose.
408
+ * @param leaf - a schema node produced by the selected builder.
409
+ * @returns the field schema with `meta.volatile === true`. */
410
+ function volatileField(leaf) {
411
+ if (leaf && typeof leaf.volatile === 'function') return leaf.volatile();
412
+ if (leaf && typeof leaf.extra === 'function') return leaf.extra('volatile', true);
413
+ return leaf;
414
+ }
415
+
416
+ /** Every reachable schemastery builder, closest require path first.
417
+ * @returns `{ z, source }` records; `source` names the root that answered, for
418
+ * the diagnostics apply() logs when nothing usable was found. */
419
+ /* WHY a fast path AND a cache: the full scan below (resolutionRoots +
420
+ require.resolve across every root) costs ~80ms of module-evaluation time on a
421
+ real install. That window is not free — the host half must finish evaluating
422
+ before its loader entry activates, and a web page that boots while it runs
423
+ picks up a boot graph without this theme's row ("import failed (see
424
+ console)"). Heavy sibling plugins (e.g. dsh-codearts-auth) widen that window
425
+ further, so every millisecond shaved here narrows the race. The fast path
426
+ answers from the two require chains — a handful of stats — and short-circuits
427
+ ONLY on a native-volatile builder, the top preference of selectBuilder, so it
428
+ can never choose worse than the scan would. The cache key is a registry
429
+ Symbol so re-evaluation of this module in the SAME process (plugin reload,
430
+ dual require/import) reuses the first scan with zero filesystem access.
431
+
432
+ The cache holds SUCCESSFUL scans only (see cacheableScan): a scan that found
433
+ nothing usable is a statement about this millisecond, not about this process,
434
+ and memoizing it is what converts a transient boot race into permanent
435
+ "settings never save". */
436
+ const SCHEMA_SCAN_CACHE = Symbol.for('dsh-theme-endfield.schemastery.scan');
437
+
438
+ /** Whether a scan result is worth memoizing process-wide.
439
+ *
440
+ * "No usable builder right now" and "this entry has no settings form" are not
441
+ * the same claim, and DSH treats the second one as permanent: an entry without
442
+ * a volatile Config gets no settings form at all, so every preference stays
443
+ * page-local and resets on reload. The first one, by contrast, is a property of
444
+ * the moment and heals by itself:
445
+ *
446
+ * - `require(esm)` throws ERR_REQUIRE_ESM_RACE_CONDITION while the ESM
447
+ * dependency of a CJS candidate is still in flight (DSH's own concurrent
448
+ * boot does exactly that to `@deepseek-ai/schemastery`, whose CJS build
449
+ * requires the pure-ESM `@deepseek-ai/cosmokit`), and
450
+ * - the module cache can hold a half-evaluated copy, whose `exports` is still
451
+ * `{}` — truthy, so it would otherwise be recorded as a candidate that
452
+ * fails every builder check in selectBuilder.
453
+ *
454
+ * Both states clear within milliseconds, so a later evaluation (a hot reload, a
455
+ * re-mounted entry) deserves a fresh scan. A successful scan is what the cache
456
+ * is FOR; a failed one costs a filesystem sweep that the fast path usually
457
+ * short-circuits anyway.
458
+ *
459
+ * @param list - a candidate list, possibly one left by an earlier scan.
460
+ * @returns true when at least one candidate can actually build a schema. */
461
+ function cacheableScan(list) {
462
+ if (!Array.isArray(list)) return false;
463
+ return list.some((candidate) => {
464
+ const z = candidate && candidate.z;
465
+ return !!(z && typeof z.object === 'function' && typeof z.string === 'function');
466
+ });
467
+ }
468
+
469
+ function schemasteryCandidates() {
470
+ /* Same-process re-evaluation: the first USABLE scan's answer is still this
471
+ process's answer. */
472
+ try {
473
+ const cached = globalThis[SCHEMA_SCAN_CACHE];
474
+ if (cacheableScan(cached)) return cached;
475
+ } catch (e) { /* fall through to a fresh scan */ }
476
+ const out = [];
477
+ const seenBuilders = [];
478
+ const take = (found, source) => {
479
+ const builder = normalizeSchemastery(found);
480
+ if (!builder) return;
481
+ /* Reject anything that cannot build a schema before it is recorded. A
482
+ half-evaluated module in the require cache exports `{}`, which is truthy
483
+ and would otherwise enter the list as a candidate that then fails every
484
+ check in selectBuilder — indistinguishable, downstream, from "this
485
+ process has no schemastery". */
486
+ if (typeof builder.object !== 'function' || typeof builder.string !== 'function') return;
487
+ if (seenBuilders.indexOf(builder) !== -1) return;
488
+ seenBuilders.push(builder);
489
+ out.push({ z: builder, source });
490
+ };
491
+ /* FAST PATH — scoped spec first, plain require chain then require.main's, the
492
+ two shapes a real install answers through (published profile installs
493
+ resolve from this package's own chain; dev-link installs from the host
494
+ process's). Each miss is a failed resolve against a short ancestor chain,
495
+ i.e. microseconds. A hit is accepted only when it carries schemastery's
496
+ OWN .volatile(): that is selectBuilder's highest preference, so skipping
497
+ the scan cannot demote the choice. A marker-only builder (.extra(), no
498
+ .volatile()) deliberately falls through — the scan's candidate order still
499
+ decides between it and a native copy found elsewhere. */
500
+ for (const spec of SCHEMA_SPECS) {
501
+ const attempts = [[spec, () => require(spec)]];
502
+ try {
503
+ if (require.main && typeof require.main.require === 'function') {
504
+ attempts.push([spec + ' via require.main', () => require.main.require(spec)]);
505
+ }
506
+ } catch (e) { /* no main module to ask */ }
507
+ for (const [source, attempt] of attempts) {
508
+ try {
509
+ const builder = normalizeSchemastery(attempt());
510
+ if (builder && typeof builder.object === 'function' && typeof builder.string === 'function' && hasVolatile(builder)) {
511
+ out.push({ z: builder, source });
512
+ try { if (cacheableScan(out)) globalThis[SCHEMA_SCAN_CACHE] = out; } catch (e) { /* cache is best-effort */ }
513
+ return out;
514
+ }
515
+ } catch (e) { /* keep trying */ }
516
+ }
517
+ }
518
+ // Roots are computed once: the scan touches the filesystem.
519
+ const roots = resolutionRoots();
520
+ /* Spec-major, SCOPED FIRST: `@deepseek-ai/schemastery` is the builder DSH's
521
+ own settings service validates against, so whenever a scoped copy exists
522
+ anywhere it must win over the unscoped one a sibling plugin may have left on
523
+ an earlier path. Within one spec the plain require chain is asked first
524
+ (that is the published-install case), then every explicit root. */
525
+ for (const spec of SCHEMA_SPECS) {
526
+ try { take(require(spec), spec); } catch (e) { /* not on this path */ }
527
+ for (const dir of roots) {
528
+ try {
529
+ take(require(require.resolve(spec, { paths: [dir] })), spec + ' from ' + dir);
530
+ } catch (e) { /* keep scanning the remaining roots */ }
531
+ }
532
+ }
533
+ // Finally, the host process's own main module, asked through ITS require: the
534
+ // last resort for a layout none of the paths above describes.
535
+ try {
536
+ if (require.main && typeof require.main.require === 'function') {
537
+ for (const spec of SCHEMA_SPECS) {
538
+ try { take(require.main.require(spec), spec + ' via require.main'); } catch (e) { /* keep scanning */ }
539
+ }
540
+ }
541
+ } catch (e) { /* no main module to ask */ }
542
+ // Absolute last resort: a copy ALREADY LOADED in this process. DSH's own
543
+ // settings service imports schemastery, so whatever reached the CommonJS
544
+ // module cache is usable by identity even when no path describes this
545
+ // install. Read-only: nothing is executed, only cached exports inspected.
546
+ try {
547
+ const cache = require.cache || {};
548
+ for (const id of Object.keys(cache)) {
549
+ if (id.indexOf('schemastery') === -1) continue;
550
+ let exported = null;
551
+ try { exported = cache[id] && cache[id].exports; } catch (e) { continue; }
552
+ take(exported, id + ' (already loaded in this process)');
553
+ }
554
+ } catch (e) { /* no module cache to read */ }
555
+ /* Successful scans only: see cacheableScan. Leaving the slot empty makes the
556
+ next evaluation rescan, which is exactly what a caller that lost a race
557
+ needs. */
558
+ try { if (cacheableScan(out)) globalThis[SCHEMA_SCAN_CACHE] = out; } catch (e) { /* cache is best-effort */ }
559
+ return out;
560
+ }
561
+
562
+ /**
563
+ * Pick the builder to build `Config` with: the best of the reachable ones.
564
+ *
565
+ * The preference order is the whole point of this function.
566
+ *
567
+ * 1. a builder with schemastery's OWN `.volatile()` — highest fidelity, the
568
+ * exact copy DSH validates against;
569
+ * 2. a builder that only has `.extra()`, with the marker synthesized.
570
+ *
571
+ * Step 2 exists because "no `.volatile()` anywhere" used to mean "no Config",
572
+ * and a missing Config is NOT a degraded theme — it is no persistence at all.
573
+ * DSH projects no settings form for an entry without a volatile Config, so
574
+ * every switch the user flips stays page-local and resets on the next reload:
575
+ * the panel opens, the switches move, and nothing is ever written down. That is
576
+ * exactly what happened on a host whose only *loadable* schemastery was the
577
+ * unscoped 3.18.0 (no `.volatile()`), while the 3.18.4 copy that does have it
578
+ * resolved from the profile but could not be required. Marking through
579
+ * `.extra()` builds the same node shape (`.meta.volatile === true`), which is
580
+ * all DSH's projection reads.
581
+ *
582
+ * @param candidates - `{ z, source }` records, closest require path first.
583
+ * @param requireVolatile - when true only an editable (volatile) schema is
584
+ * acceptable, because DSH drops a non-volatile field and suppresses the whole
585
+ * form; when false any usable builder does (the pre-0.1.7 registration
586
+ * persisted whole namespaces instead of a volatile Config).
587
+ * @returns `{ z, source, mode }`, or undefined when nothing is usable. */
588
+ function selectBuilder(candidates, requireVolatile) {
589
+ const usable = [];
590
+ for (const candidate of candidates) {
591
+ const z = candidate.z;
592
+ if (!z || typeof z.object !== 'function' || typeof z.string !== 'function') continue;
593
+ usable.push(candidate);
594
+ }
595
+ if (!requireVolatile) {
596
+ const first = usable[0];
597
+ if (!first) return undefined;
598
+ /* 'plain' unconditionally: this call site deliberately marks NOTHING, so
599
+ naming the builder's own capability here would misdescribe the schema. */
600
+ return { z: first.z, source: first.source, mode: 'plain' };
601
+ }
602
+ for (const candidate of usable) {
603
+ if (hasVolatile(candidate.z)) return { z: candidate.z, source: candidate.source, mode: 'native' };
604
+ }
605
+ for (const candidate of usable) {
606
+ if (hasVolatileMarker(candidate.z)) return { z: candidate.z, source: candidate.source, mode: 'synthesized' };
607
+ }
608
+ return undefined;
609
+ }
610
+
611
+ /**
612
+ * @param requireVolatile - when true only a builder that can produce an
613
+ * editable (volatile) schema is acceptable (needed for DSH 0.1.7's Config).
614
+ * @returns a usable builder, or undefined when none is reachable. On success
615
+ * SCHEMA_SOURCE records the root it came from and SCHEMA_MODE how it marks a
616
+ * field editable.
617
+ */
618
+ function loadSchemastery(requireVolatile) {
619
+ const chosen = selectBuilder(schemasteryCandidates(), requireVolatile);
620
+ if (!chosen) return undefined;
621
+ SCHEMA_SOURCE = chosen.source;
622
+ SCHEMA_MODE = chosen.mode;
623
+ return chosen.z;
624
+ }
625
+
626
+ /** Build the object schema over FIELD_DEFAULTS with an EXPLICIT builder.
627
+ *
628
+ * Split out of {@link buildSchema} so the field contract — one string field per
629
+ * FIELD_DEFAULTS entry, each carrying its shipped default and, when asked, the
630
+ * volatile marker — can be asserted against a stand-in builder instead of
631
+ * whatever schemastery the test machine happens to have. A Host check that
632
+ * silently skips on a schemastery-free machine is precisely how
633
+ * "settings won't save" shipped green.
634
+ *
635
+ * @param z - a schemastery builder.
636
+ * @param volatileFields - mark every field editable.
637
+ * @returns the object schema. */
638
+ function buildSchemaWith(z, volatileFields) {
639
+ const fields = {};
640
+ for (const [field, fallback] of Object.entries(FIELD_DEFAULTS)) {
641
+ let leaf = z.string().default(fallback);
642
+ if (volatileFields) leaf = volatileField(leaf);
643
+ fields[field] = leaf;
644
+ }
645
+ return z.object(fields);
646
+ }
647
+
648
+ /**
649
+ * Build one schemastery object schema over FIELD_DEFAULTS with the best
650
+ * reachable builder.
651
+ *
652
+ * @param volatileFields - when true every field is marked editable (volatile),
653
+ * which is what makes it user-editable through DSH 0.1.7's settings service
654
+ * (only volatile paths are projected into a form and accepted by a write).
655
+ * The legacy pre-0.1.7 registration used the same schema shape without the
656
+ * flag, because that generation persisted whole namespaces instead of a
657
+ * Config.
658
+ * @returns the schema, or undefined when no usable schemastery builder is
659
+ * reachable (the theme then stays a no-op instead of crashing the host half).
660
+ */
661
+ function buildSchema(volatileFields) {
662
+ try {
663
+ const z = loadSchemastery(volatileFields === true);
664
+ if (z === undefined || typeof z.object !== 'function' || typeof z.string !== 'function') return undefined;
665
+ return buildSchemaWith(z, volatileFields === true);
666
+ } catch (e) {
667
+ // A schema we cannot build must never take the entry (and the theme) down.
668
+ return undefined;
669
+ }
670
+ }
671
+
672
+ /**
673
+ * The Config DSH 0.1.7 projects into a settings form for this entry. It is
674
+ * read off the plugin module namespace (`entry.fiber.runtime.Config`) when the
675
+ * loader mounts the row, so it must exist at module evaluation time.
676
+ *
677
+ * `ctx.settings` refuses a write to any path that is not volatile, and it
678
+ * suppresses the whole form when NO field is volatile — hence `true` here.
679
+ * When no schemastery is reachable the property is omitted entirely, which is
680
+ * exactly "this plugin has nothing to configure" and not an error — but it is
681
+ * also the one failure that silently costs the user every preference on every
682
+ * reload, so apply() reports it instead of staying quiet.
683
+ */
684
+ const Config = buildSchema(true);
685
+
686
+ /** File name of the failure report written next to the profile patch. */
687
+ const DIAGNOSTIC_FILE = 'theme-endfield-diagnostic.json';
688
+
689
+ /** Where the failure report goes: the profile directory when the context names
690
+ * one, else the DSH home. Written only when no Config could be built, and
691
+ * deleted again the moment one can.
692
+ * @returns an absolute path, or null when neither location is derivable. */
693
+ function diagnosticPath(ctx) {
694
+ const path = require('path');
695
+ try {
696
+ const base = ctx && typeof ctx.baseUrl === 'string' ? ctx.baseUrl : null;
697
+ if (base && base.indexOf('file:') === 0) {
698
+ return path.join(require('url').fileURLToPath(base), DIAGNOSTIC_FILE);
699
+ }
700
+ // A few hosts carry the profile as a plain directory rather than a URL.
701
+ if (base && path.isAbsolute(base)) return path.join(base, DIAGNOSTIC_FILE);
702
+ } catch (e) { /* fall through to the DSH home */ }
703
+ try {
704
+ const homes = dshHomeDirs();
705
+ if (homes.length) return path.join(homes[0], DIAGNOSTIC_FILE);
706
+ } catch (e) { /* no home to write into */ }
707
+ return null;
708
+ }
709
+
710
+ /** Per-root resolution outcome, for the failure report.
711
+ * @returns one row per spec/root pair, or a single row describing the throw. */
712
+ function resolutionReport() {
713
+ const rows = [];
714
+ let roots = [];
715
+ try { roots = resolutionRoots(); } catch (e) { return [{ roots: 'threw: ' + String((e && e.message) || e) }]; }
716
+ for (const spec of SCHEMA_SPECS) {
717
+ try { rows.push({ spec, from: 'plain require', resolved: require.resolve(spec) }); } catch (e) { rows.push({ spec, from: 'plain require', error: String((e && e.code) || (e && e.message) || e) }); }
718
+ }
719
+ for (const dir of roots) {
720
+ for (const spec of SCHEMA_SPECS) {
721
+ const row = { spec, from: dir };
722
+ try {
723
+ row.resolved = require.resolve(spec, { paths: [dir] });
724
+ /* Resolving is NOT loading: a copy can resolve perfectly and still throw
725
+ on require (a dependency that will not load, a half-written install).
726
+ The old report stopped at the resolve, so a row reading "resolved"
727
+ next to a Config that was never built looked like a contradiction
728
+ instead of an answer. Record what the require actually did. */
729
+ try {
730
+ const loaded = require(row.resolved);
731
+ row.loaded = true;
732
+ row.volatile = hasVolatile(loaded);
733
+ row.marker = hasVolatileMarker(loaded);
734
+ } catch (e) {
735
+ row.loadError = String((e && e.code) || (e && e.message) || e);
736
+ }
737
+ } catch (e) { row.error = String((e && e.code) || (e && e.message) || e); }
738
+ rows.push(row);
739
+ }
740
+ }
741
+ return rows;
742
+ }
743
+
744
+ /** Everything needed to explain a missing settings form on THIS machine.
745
+ * @returns a JSON-serializable snapshot; every read is individually guarded. */
746
+ function diagnosticSnapshot(ctx) {
747
+ const read = (produce) => { try { return produce(); } catch (e) { return 'threw: ' + String((e && e.message) || e); } };
748
+ let loader = null;
749
+ try { loader = ctx && typeof ctx.get === 'function' ? ctx.get('loader') : null; } catch (e) { loader = null; }
750
+ return {
751
+ at: new Date().toISOString(),
752
+ plugin: read(() => NAME + ' ' + require('./package.json').version),
753
+ configBuilt: Config !== undefined,
754
+ schemaSource: SCHEMA_SOURCE,
755
+ schemaMode: SCHEMA_MODE,
756
+ node: process.version,
757
+ pid: process.pid,
758
+ execPath: process.execPath,
759
+ argv: process.argv.slice(0, 6),
760
+ cwd: read(() => process.cwd()),
761
+ dirname: __dirname,
762
+ filename: __filename,
763
+ mainModule: read(() => (require.main && require.main.filename) || null),
764
+ baseUrl: read(() => (ctx && typeof ctx.baseUrl === 'string' ? ctx.baseUrl : null)),
765
+ dshHomeDirs: read(dshHomeDirs),
766
+ homedir: read(() => require('os').homedir()),
767
+ envDshHome: read(() => (process.env && process.env.DSH_HOME) || null),
768
+ envCordisShared: read(() => (process.env && process.env.CORDIS_SHARED) || null),
769
+ loaderStartedAt: read(() => {
770
+ const start = loader && loader.envData && loader.envData.startTime;
771
+ return typeof start === 'number' ? new Date(start).toISOString() : null;
772
+ }),
773
+ cachedSchemasteryModules: read(() => Object.keys(require.cache || {}).filter((id) => id.indexOf('schemastery') !== -1)),
774
+ resolution: read(resolutionReport),
775
+ };
776
+ }
777
+
778
+ /** Report a missing settings form: a warn line for the log, plus the JSON
779
+ * report above so the exact machine state can be inspected afterwards. */
780
+ function reportMissingConfig(ctx) {
781
+ const note = NAME + ': no schemastery builder that can mark a field volatile was reachable, so this entry'
782
+ + ' exports no Config: DSH projects no settings form for it and every preference stays'
783
+ + ' page-local (it resets on each reload). Tried ' + SCHEMA_SPECS.join(', ') + ' through the'
784
+ + ' plain require chain, this module\'s own tree, the DSH home profiles, the working'
785
+ + ' directory, this module\'s ancestors, require.main and the process module cache.'
786
+ + ' Neither `.volatile()` nor the `.extra()` it is built on was available, so no field'
787
+ + ' could be marked editable.';
788
+ try {
789
+ if (ctx.logger && typeof ctx.logger.warn === 'function') ctx.logger.warn(note);
790
+ else if (typeof console !== 'undefined' && console.warn) console.warn(note);
791
+ } catch (e) { /* a logger that throws must not kill the theme */ }
792
+ try {
793
+ const target = diagnosticPath(ctx);
794
+ if (!target) return;
795
+ require('fs').writeFileSync(target, JSON.stringify(diagnosticSnapshot(ctx), null, 2) + '\n');
796
+ if (ctx.logger && typeof ctx.logger.warn === 'function') {
797
+ ctx.logger.warn(NAME + ': wrote the failure report to ' + target);
798
+ }
799
+ } catch (e) { /* a report that cannot be written must not kill the theme */ }
800
+ }
801
+
802
+ /** Drop a report left by an earlier boot: the form exists now. */
803
+ function clearStaleDiagnostic(ctx) {
804
+ try {
805
+ const target = diagnosticPath(ctx);
806
+ if (!target) return;
807
+ const fs = require('fs');
808
+ if (fs.existsSync(target)) fs.unlinkSync(target);
809
+ } catch (e) { /* nothing to clean up */ }
810
+ }
811
+
812
+ /* ------------------------------------------------------------------ *
813
+ * Audio notification host half
814
+ * ------------------------------------------------------------------ */
815
+
816
+ /** Read a service off the context without letting a missing one throw. */
817
+ function serviceOf(ctx, key) {
818
+ try {
819
+ return ctx.get(key);
820
+ } catch (error) {
821
+ return undefined;
822
+ }
823
+ }
824
+
825
+ /**
826
+ * Whether one inbox message is a prompt the USER typed into the composer.
827
+ *
828
+ * The only positive evidence available at this seam is the prompt-RPC identity
829
+ * that DSH attaches to a browser-submitted prompt: `source = { kind: 'user',
830
+ * rpcId }` (`dsh-api-session-controller`, where `promptRpcId()` reads exactly
831
+ * that field). Everything that injects work programmatically — goal rounds,
832
+ * background-job wakeups, subagent hand-offs, plugin context — produces
833
+ * `kind: 'user'` too, or a `next-step` context message, so "has rpcId" is the
834
+ * discriminator; with `humanOnly` off, the looser `kind: 'user'` test applies.
835
+ *
836
+ * @param message - the claimed inbox message.
837
+ * @param humanOnly - whether to require the composer identity.
838
+ * @returns `{ human, why }` for diagnostics.
839
+ */
840
+ function classifyPrompt(message, humanOnly) {
841
+ const source = message === undefined || message === null ? undefined : message.source;
842
+ if (source === undefined || source === null) return { human: false, why: 'no source' };
843
+ const kind = source.kind;
844
+ const hasRpcId = typeof source.rpcId === 'string' && source.rpcId !== '';
845
+ if (hasRpcId) return { human: true, why: 'composer prompt (rpcId)' };
846
+ if (kind === 'user' && !humanOnly) return { human: true, why: 'user-source message (humanOnly off)' };
847
+ return { human: false, why: `source.kind=${String(kind)} without rpcId` };
848
+ }
849
+
850
+ /** Whether one assistant message carried visible text (as opposed to only calls). */
851
+ function hasVisibleText(message) {
852
+ if (message === undefined || message === null) return false;
853
+ const content = Array.isArray(message.content) ? message.content : [];
854
+ for (const block of content) {
855
+ if (block === null || block === undefined) continue;
856
+ if (block.type === 'text' && typeof block.text === 'string' && block.text.trim() !== '') return true;
857
+ }
858
+ return false;
859
+ }
860
+
861
+ /**
862
+ * Install the notification feature on one host context.
863
+ *
864
+ * @param ctx - host Cordis context.
865
+ * @param settingsScope - the registered settings scope, when one exists.
866
+ */
867
+ function installAudio(ctx, settingsScope) {
868
+ const audio = new AudioRuntime(ctx);
869
+ const terminals = new Map(); // `${sessionId}:${turn}` -> saw a text answer
870
+ const playedDone = new Set(); // turn keys already reported, so a turn speaks once
871
+ /** How many human-intervention requests actually reached this host half.
872
+ `ui` counts confirmations the PAGE observed and reported — the path that
873
+ actually works in this deployment; `approval`/`question` count the host-side
874
+ seams, which a different composition may drive instead. */
875
+ const attentionSeen = { approval: 0, question: 0, ui: 0, uiLastAt: 0, uiLastKind: '' };
876
+
877
+ if (settingsScope !== undefined) {
878
+ try {
879
+ audio.setValues(settingsScope.get());
880
+ settingsScope.watch(() => {
881
+ audio.setValues(settingsScope.get());
882
+ });
883
+ } catch (error) {
884
+ audio.note('settings-unavailable', String(error && error.message ? error.message : error));
885
+ }
886
+ }
887
+
888
+ /** Whether one agent is a top-level conversation (never a subagent). */
889
+ const isRootAgent = (agent) => {
890
+ if (agent === undefined || agent === null) return false;
891
+ const agents = serviceOf(ctx, 'agents');
892
+ if (agents === undefined || typeof agents.roots !== 'function') return true; // cannot tell: stay permissive
893
+ try {
894
+ return agents.roots().some((candidate) => candidate === agent || candidate?.id === agent.id);
895
+ } catch (error) {
896
+ return true;
897
+ }
898
+ };
899
+
900
+ const turnKey = (agent, turn) => `${agent === undefined ? '?' : agent.id}:${turn}`;
901
+
902
+ // --- event wiring --------------------------------------------------
903
+ ctx.on('agent/inbox/claimed', ({ agent, message, turn }) => {
904
+ if (!isRootAgent(agent)) return;
905
+ const verdict = classifyPrompt(message, audio.enabled(PREF.humanOnly));
906
+ if (audio.diagnosing) {
907
+ audio.note('inbox/claimed', `turn=${turn} -> ${verdict.why}`);
908
+ }
909
+ if (!verdict.human) return;
910
+ if (!audio.enabled(PREF.start)) return;
911
+ audio.play('turn-start', { reason: 'human prompt' });
912
+ });
913
+
914
+ ctx.on('session/event', (subject, event) => {
915
+ if (event === null || event === undefined) return;
916
+ if (event.type !== 'assistant/message') return;
917
+ const data = event.data;
918
+ if (data === null || data === undefined) return;
919
+ const sessionId = subject !== null && subject !== undefined && subject.id !== undefined ? subject.id : '?';
920
+ const key = `${sessionId}:${data.turn}`;
921
+ if (hasVisibleText(data.message)) terminals.set(key, true);
922
+ else if (!terminals.has(key)) terminals.set(key, false);
923
+ /* The map is only reaped by agent/turn-stopping, and a turn that ends any
924
+ other way (agent/error, a destroyed session) never fires it — in a host
925
+ process that runs for days those entries would accumulate forever. Bound
926
+ it FIFO like playedDone below: the entries evicted earliest belong to the
927
+ oldest turns, and by the time 512 newer turns have been recorded, a
928
+ turn-stopping for the evicted one is not a live question any more. */
929
+ if (terminals.size > 512) terminals.delete(terminals.keys().next().value);
930
+ });
931
+
932
+ /* The two "a human has to do something" triggers, and the ONLY things that
933
+ sound besides the boot plate and a finished answer.
934
+
935
+ A turn that fails on its own is deliberately NOT one of them: the user's
936
+ rule is that an error needing no human decision should stay silent, so
937
+ `agent/error` is not wired to any slot. The `turn-fail` sound still ships
938
+ and can still be previewed, but nothing fires it.
939
+
940
+ Each handler keeps a counter so the settings bridge can answer "did the host
941
+ actually receive this request?" — the failure mode where the event exists
942
+ but never reaches a host listener is otherwise invisible from the outside. */
943
+ ctx.on('approval/request', (request, next) => {
944
+ attentionSeen.approval += 1;
945
+ if (audio.diagnosing) audio.note('approval/request', String(request === undefined ? '' : request.kind || ''));
946
+ if (audio.enabled(PREF.attention)) {
947
+ /* This event is a waterfall: play() must never be allowed to throw past
948
+ next(), or the whole approval chain dies exactly the way the
949
+ tools/execute note below describes. play() itself guards its file
950
+ parsing, so this is the belt to that brace. */
951
+ try { audio.play('attention', { reason: 'approval request' }); }
952
+ catch (error) { audio.note('play-threw', `approval/request: ${error && error.message ? error.message : error}`); }
953
+ }
954
+ return typeof next === 'function' ? next() : undefined;
955
+ });
956
+
957
+ ctx.on('user-questions/request', (request, next) => {
958
+ attentionSeen.question += 1;
959
+ if (audio.diagnosing) audio.note('user-questions/request', 'pending question');
960
+ if (audio.enabled(PREF.attention)) {
961
+ // Same waterfall contract as approval/request above.
962
+ try { audio.play('attention', { reason: 'user question' }); }
963
+ catch (error) { audio.note('play-threw', `user-questions/request: ${error && error.message ? error.message : error}`); }
964
+ }
965
+ return typeof next === 'function' ? next() : undefined;
966
+ });
967
+
968
+ /* There is deliberately NO `tools/execute` handler here.
969
+
970
+ An earlier version added one as a redundant second trigger for
971
+ `ask_user_question`. It was wrong and it was destructive: `tools/execute` is
972
+ a WATERFALL (`dsh-tools`: `await this.ctx.waterfall(carrier, 'tools/execute',
973
+ mutableExec, () => this.dispatchToolBody(mutableExec))`), so a listener that
974
+ inspects the call and returns `undefined` without calling `next()` reports
975
+ "no result" for that tool — the tool never runs and the failure surfaces on
976
+ every subsequent call in the session (observed as every tool returning
977
+ `Cannot read properties of undefined (reading 'isError')` while this plugin
978
+ was mounted, and the tool chain recovering the moment it was removed).
979
+
980
+ The attention slot does not need it: `approval/request` and
981
+ `user-questions/request` are the two moments that need a human, and both are
982
+ already wired above to the same slot. A redundant path is not worth a seam
983
+ that can silently break every tool in the profile. */
984
+
985
+ ctx.on('agent/turn-stopping', ({ agent, turn }) => {
986
+ const key = turnKey(agent, turn);
987
+ /* Cleanup runs BEFORE the switches below. Both early returns used to sit in
988
+ front of the delete, which leaked entries two ways: subagent turns fail
989
+ isRootAgent yet are recorded by the session/event handler above, and a
990
+ user who turned the done sound off stopped reaping anything at all. */
991
+ const hadText = terminals.get(key) === true;
992
+ terminals.delete(key);
993
+ if (!isRootAgent(agent)) return;
994
+ if (!audio.enabled(PREF.done)) return;
995
+ // One report per turn, and only for a turn that actually produced a written
996
+ // result: a turn the user interrupted, or one that stopped on an approval
997
+ // prompt, has nothing to announce.
998
+ if (!hadText) {
999
+ if (audio.diagnosing) audio.note('turn-stopping', `turn=${turn} no final text -> silent`);
1000
+ return;
1001
+ }
1002
+ if (playedDone.has(key)) return;
1003
+ playedDone.add(key);
1004
+ if (playedDone.size > 64) playedDone.delete(playedDone.values().next().value);
1005
+ audio.play('turn-done', { reason: 'final answer' });
1006
+ });
1007
+
1008
+ // --- settings-page bridge (preview + diagnostics) -------------------
1009
+ const registerBridge = (webServer) => {
1010
+ if (webServer === undefined || typeof webServer.register !== 'function') {
1011
+ audio.note('bridge-unavailable', 'webServer service absent; preview buttons disabled');
1012
+ return;
1013
+ }
1014
+ const readJson = (req) => new Promise((resolve) => {
1015
+ let body = '';
1016
+ req.on('data', (chunk) => {
1017
+ body += chunk;
1018
+ if (body.length > 65536) body = body.slice(0, 65536);
1019
+ });
1020
+ req.on('end', () => {
1021
+ try { resolve(JSON.parse(body === '' ? '{}' : body)); } catch (error) { resolve({}); }
1022
+ });
1023
+ req.on('error', () => resolve({}));
1024
+ });
1025
+ const send = (res, code, payload) => {
1026
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1027
+ res.end(JSON.stringify(payload));
1028
+ };
1029
+ /* Uploads are binary and far bigger than a JSON control message: the
1030
+ preview/attention routes cap their bodies at 64 KB, while a 2.5 s stereo
1031
+ wav is a few hundred KB. 8 MB is the hard ceiling — roomy for any clip the
1032
+ duration rule will accept, small enough that one stray request cannot
1033
+ exhaust the host's memory. */
1034
+ const UPLOAD_LIMIT = 8 * 1024 * 1024;
1035
+ /**
1036
+ * Read a raw request body into one Buffer.
1037
+ *
1038
+ * @returns the bytes, or null when the body exceeded `limit` (the stream is
1039
+ * still drained so the response can be written instead of reset).
1040
+ */
1041
+ const readBytes = (req, limit) => new Promise((resolve) => {
1042
+ const chunks = [];
1043
+ let total = 0;
1044
+ let over = false;
1045
+ req.on('data', (chunk) => {
1046
+ if (over) return;
1047
+ total += chunk.length;
1048
+ if (total > limit) {
1049
+ over = true;
1050
+ chunks.length = 0;
1051
+ return;
1052
+ }
1053
+ chunks.push(chunk);
1054
+ });
1055
+ req.on('end', () => resolve(over ? null : Buffer.concat(chunks)));
1056
+ req.on('error', () => resolve(null));
1057
+ });
1058
+ try {
1059
+ webServer.register({
1060
+ kind: 'prefix',
1061
+ path: '/theme-endfield/audio',
1062
+ handler: async (req, res) => {
1063
+ const url = String(req.url || '');
1064
+ const pathname = url.split('?')[0];
1065
+ const query = url.includes('?') ? new URLSearchParams(url.slice(url.indexOf('?') + 1)) : new URLSearchParams();
1066
+ /* Both preview routes force the play (bypassing the debounce window),
1067
+ because a preview that silently does nothing is indistinguishable
1068
+ from a broken feature. The GET form takes the slot in the query
1069
+ string so a non-JS caller can trigger the same play; neither route
1070
+ is a new capability — both end in audio.play() under the user's own
1071
+ settings, and the Host web server already authenticates the page. */
1072
+ const playForPreview = (slotId, reason) => {
1073
+ const id = String(slotId || '');
1074
+ // The slot's own switch is authoritative even for a preview: playing a
1075
+ // sound the user switched off would make the switch look broken.
1076
+ if (SLOT_IDS.includes(id) && !audio.slotEnabled(id)) {
1077
+ return { slot: id, played: false, why: `slot switch "${id}" is off` };
1078
+ }
1079
+ const result = audio.play(id, { force: true, reason });
1080
+ return Object.assign({ slot: id }, result);
1081
+ };
1082
+ try {
1083
+ if (req.method === 'GET' && pathname === '/theme-endfield/audio/state') {
1084
+ // `attention` rides along so a caller can tell "the host never got
1085
+ // the request" apart from "the host got it and chose to stay
1086
+ // silent" — the two look identical from the page otherwise.
1087
+ return send(res, 200, Object.assign(audio.snapshot(), { attention: Object.assign({}, attentionSeen) }));
1088
+ }
1089
+ if (req.method === 'GET' && pathname === '/theme-endfield/audio/preview') {
1090
+ const result = playForPreview(query.get('slot'), 'preview (GET)');
1091
+ return send(res, result.played ? 200 : 409, result);
1092
+ }
1093
+ if (req.method === 'POST' && pathname === '/theme-endfield/audio/preview') {
1094
+ const body = await readJson(req);
1095
+ const result = playForPreview(body.slot, 'settings preview');
1096
+ return send(res, result.played ? 200 : 409, result);
1097
+ }
1098
+ /* 开机音频(03 动画)。The page calls this once per load, AFTER the
1099
+ settings section settled (before that the stored switch is unknown
1100
+ and the shipped default is OFF, so an early call would always be
1101
+ silent). It is the one route that deliberately IGNORES the
1102
+ notification master switch: this sound lives under 动画 and has its
1103
+ own toggle, and requiring "音频通知" for a login voice would make
1104
+ the two settings fight. Volume and the still-speaking gate still
1105
+ apply — both are user-visible knobs on the same page.
1106
+ preview:true brings the settings 试听 button through the same path,
1107
+ forced past the debounce like every other preview. */
1108
+ if (req.method === 'POST' && pathname === '/theme-endfield/audio/boot') {
1109
+ const body = await readJson(req);
1110
+ if (!audio.slotEnabled('login')) {
1111
+ return send(res, 409, { played: false, why: 'boot audio switch is off' });
1112
+ }
1113
+ const preview = body.preview === true;
1114
+ const result = audio.play('login', {
1115
+ force: preview,
1116
+ ignoreMaster: true,
1117
+ reason: preview ? 'boot audio preview' : 'page load',
1118
+ });
1119
+ return send(res, result.played ? 200 : 409, result);
1120
+ }
1121
+ /* The page reports "a confirmation box is on screen".
1122
+
1123
+ This route exists because the two host-side seams that would
1124
+ normally carry this moment (`approval/request`,
1125
+ `user-questions/request`) do not fire in every composition: in this
1126
+ deployment `ask_user_question` is provided OUTSIDE the profile's
1127
+ plugin stack, so `dsh-tool-ask-user` never runs and the waterfall is
1128
+ never raised — measured directly as a zero counter while a question
1129
+ was on screen. The UI is the one place the moment is always real.
1130
+
1131
+ It deliberately does NOT force: unlike a settings preview, a real
1132
+ notification must respect the switch, the volume and the per-slot
1133
+ debounce, all of which stay owned by the host. `force` is what makes
1134
+ a preview bypass the window, and reusing it here would let two rapid
1135
+ boxes beep twice because the browser holds no shared clock. */
1136
+ if (req.method === 'POST' && pathname === '/theme-endfield/audio/attention') {
1137
+ const body = await readJson(req);
1138
+ attentionSeen.ui += 1;
1139
+ attentionSeen.uiLastAt = Date.now();
1140
+ attentionSeen.uiLastKind = String(body.kind || 'pending');
1141
+ if (audio.diagnosing) audio.note('attention (page)', `saw ${attentionSeen.uiLastKind}`);
1142
+ if (!audio.slotEnabled('attention')) {
1143
+ return send(res, 409, { played: false, why: 'slot switch "attention" is off' });
1144
+ }
1145
+ const result = audio.play('attention', { reason: `page: ${attentionSeen.uiLastKind}` });
1146
+ return send(res, result.played ? 200 : 409, result);
1147
+ }
1148
+ /* 上传 / 恢复 one slot's own sound.
1149
+
1150
+ The body is the RAW wav (`application/octet-stream`), not
1151
+ multipart and not base64: the page already holds the File, and
1152
+ base64 would inflate a 400 KB clip by a third to no benefit. The
1153
+ slot arrives in the query string; `action=remove` drops the
1154
+ uploaded override instead of writing one.
1155
+
1156
+ Writes are confined to the plugin's own upload directory (see
1157
+ `saveUpload` in lib/audio.js) — the route has no way to write
1158
+ anywhere else, which is what makes it acceptable on a host bridge
1159
+ that a page can call. */
1160
+ if (req.method === 'POST' && pathname === '/theme-endfield/audio/upload') {
1161
+ const slot = String(query.get('slot') || '');
1162
+ if (query.get('action') === 'remove') {
1163
+ const removed = audio.removeUpload(slot);
1164
+ return send(res, removed.ok ? 200 : 400, removed);
1165
+ }
1166
+ const bytes = await readBytes(req, UPLOAD_LIMIT);
1167
+ if (bytes === null) {
1168
+ return send(res, 413, { ok: false, why: `body larger than ${UPLOAD_LIMIT} bytes` });
1169
+ }
1170
+ const saved = audio.saveUpload(slot, bytes);
1171
+ return send(res, saved.ok ? 200 : 400, saved);
1172
+ }
1173
+ return send(res, 404, { error: 'not found' });
1174
+ } catch (error) {
1175
+ return send(res, 500, { error: String(error && error.message ? error.message : error) });
1176
+ }
1177
+ },
1178
+ });
1179
+ audio.note('bridge', 'settings bridge mounted at /theme-endfield/audio');
1180
+ } catch (error) {
1181
+ audio.note('bridge-failed', String(error && error.message ? error.message : error));
1182
+ }
1183
+ };
1184
+ const webServerNow = serviceOf(ctx, 'webServer');
1185
+ if (webServerNow !== undefined) registerBridge(webServerNow);
1186
+ else if (typeof ctx.inject === 'function') ctx.inject(['webServer'], (scope) => registerBridge(scope.webServer));
1187
+
1188
+ console.log(`${LOG_TAG} ready (host half)`);
1189
+ return audio;
1190
+ }
1191
+
1192
+ /* ---------------------------------------------------------------------------
1193
+ * Balance bridge — GET /theme-endfield/balance
1194
+ *
1195
+ * The browser half cannot reach the account balance itself: only Host
1196
+ * consumers can obtain the request credential the account service needs, so
1197
+ * the capsule in the page asks THIS route instead. The handler mirrors the
1198
+ * account service's own client-metadata shape (version/locale/timezone) and
1199
+ * returns the balance payload verbatim; a failure is reported as
1200
+ * { ok: false } rather than a thrown 500 so the page can keep the last known
1201
+ * numbers on screen instead of flickering an error state.
1202
+ *
1203
+ * TWO BALANCE ROUTES, API KEY FIRST (mirrors dsh-whale-widget v759/v781).
1204
+ * A user who only configured DEEPSEEK_API_KEY and never logged into the
1205
+ * DeepSeek account gets NOTHING from the account service — that route answers
1206
+ * only for the client-login identity. So the handler now tries, in order:
1207
+ * 1. API key route — GET https://api.deepseek.com/user/balance with the
1208
+ * resolved DEEPSEEK_API_KEY credential. Always first when a key exists.
1209
+ * 2. Account route — the DSH `deepseekAccount` service (the original path).
1210
+ * The two never fall back into each other silently in reverse: with a key
1211
+ * configured, the key route's answer is authoritative even when it fails
1212
+ * (the failure reason is reported so the page can keep stale numbers); the
1213
+ * account route is only consulted when no key resolves at all.
1214
+ * ------------------------------------------------------------------------ */
1215
+ const DSH_CLIENT_VERSION_FALLBACK = '0.2.0-rc.2';
1216
+ const BALANCE_API_URL = 'https://api.deepseek.com/user/balance';
1217
+ const BALANCE_API_TIMEOUT_MS = 8000;
1218
+
1219
+ /* Route 1: the API key path. Resolves the DEEPSEEK_API_KEY credential through
1220
+ * the host credentials service and asks the official balance endpoint.
1221
+ * Returns null when there is no key to try (caller falls through to the
1222
+ * account route) or `{ ok:false, why }` on a definitive failure; a success is
1223
+ * the same wallet payload the account route produces, so the page-side
1224
+ * contract never changes. Transient network/5xx failures retry once after a
1225
+ * short backoff before being reported. */
1226
+ async function fetchApiKeyBalance(ctx) {
1227
+ let cred = null;
1228
+ try {
1229
+ const credentials = serviceOf(ctx, 'credentials');
1230
+ if (credentials && typeof credentials.resolve === 'function') {
1231
+ cred = await credentials.resolve('DEEPSEEK_API_KEY');
1232
+ }
1233
+ } catch (error) {
1234
+ return { ok: false, why: 'API key 读取失败: ' + String(error && error.message ? error.message : error) };
1235
+ }
1236
+ if (!cred || !cred.value) return null; // no key configured -> account route
1237
+ let lastError = '';
1238
+ for (let attempt = 0; attempt < 2; attempt++) {
1239
+ let res;
1240
+ try {
1241
+ res = await fetch(BALANCE_API_URL, {
1242
+ headers: { Authorization: 'Bearer ' + cred.value },
1243
+ signal: AbortSignal.timeout(BALANCE_API_TIMEOUT_MS),
1244
+ });
1245
+ } catch (error) {
1246
+ lastError = String(error && error.message ? error.message : error);
1247
+ if (attempt === 0) { await new Promise((resolve) => setTimeout(resolve, 500)); continue; }
1248
+ return { ok: false, why: '余额接口请求失败: ' + lastError };
1249
+ }
1250
+ if (!res.ok) {
1251
+ lastError = 'HTTP ' + res.status;
1252
+ if (res.status < 500) return { ok: false, why: '余额接口返回 ' + lastError }; // 4xx: key bad/unauthorized, no retry
1253
+ if (attempt === 0) { await new Promise((resolve) => setTimeout(resolve, 500)); continue; }
1254
+ return { ok: false, why: '余额接口请求失败: ' + lastError };
1255
+ }
1256
+ let data;
1257
+ try {
1258
+ data = await res.json();
1259
+ } catch (error) {
1260
+ return { ok: false, why: '余额接口返回不是合法 JSON' };
1261
+ }
1262
+ const infos = Array.isArray(data && data.balance_infos) ? data.balance_infos : [];
1263
+ const info = infos.find((x) => x && x.currency === 'CNY') || infos[0];
1264
+ if (!info || info.total_balance === undefined || !Number.isFinite(Number(info.total_balance))) {
1265
+ return { ok: false, why: '余额接口返回结构异常' };
1266
+ }
1267
+ return {
1268
+ ok: true,
1269
+ wallets: [{ currency: String(info.currency || 'CNY'), balance: String(info.total_balance) }],
1270
+ bonusWallets: info.granted_balance !== undefined && Number.isFinite(Number(info.granted_balance))
1271
+ ? [{ currency: String(info.currency || 'CNY'), balance: String(info.granted_balance) }]
1272
+ : [],
1273
+ at: Date.now(),
1274
+ };
1275
+ }
1276
+ return { ok: false, why: '余额接口请求失败: ' + lastError }; // unreachable, keeps lint honest
1277
+ }
1278
+
1279
+ /* Route 2: the DSH account-login path (the original implementation). Returns
1280
+ * the wallet payload on success, `{ ok:false, why }` on any failure — the
1281
+ * why text distinguishes "service absent" (no such host generation) from
1282
+ * "not logged in" so a user can tell the two apart. */
1283
+ async function fetchAccountBalance(ctx) {
1284
+ const account = serviceOf(ctx, 'deepseekAccount');
1285
+ if (!account || typeof account.getBalance !== 'function') {
1286
+ return { ok: false, why: 'account service absent' };
1287
+ }
1288
+ const client = {
1289
+ version: DSH_CLIENT_VERSION_FALLBACK,
1290
+ locale: 'zh-CN',
1291
+ timezoneOffsetSeconds: -(new Date()).getTimezoneOffset() * 60,
1292
+ };
1293
+ const balance = await account.getBalance(client);
1294
+ if (!balance || balance.status !== 'ready') {
1295
+ return { ok: false, why: balance && balance.status ? String(balance.status) : 'null' };
1296
+ }
1297
+ return {
1298
+ ok: true,
1299
+ wallets: balance.value || [],
1300
+ bonusWallets: balance.bonusWallets || [],
1301
+ at: Date.now(),
1302
+ };
1303
+ }
1304
+
1305
+ function registerBalanceBridge(ctx) {
1306
+ const webServer = serviceOf(ctx, 'webServer');
1307
+ const mount = (webServer) => {
1308
+ if (webServer === undefined || typeof webServer.register !== 'function') return;
1309
+ const send = (res, code, payload) => {
1310
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1311
+ res.end(JSON.stringify(payload));
1312
+ };
1313
+ try {
1314
+ webServer.register({
1315
+ kind: 'prefix',
1316
+ path: '/theme-endfield/balance',
1317
+ handler: async (req, res) => {
1318
+ const pathname = String(req.url || '').split('?')[0];
1319
+ if (req.method !== 'GET' || pathname !== '/theme-endfield/balance') {
1320
+ return send(res, 404, { error: 'not found' });
1321
+ }
1322
+ try {
1323
+ // API key route first; a resolved key makes its answer authoritative
1324
+ // (success or reported failure — no silent fall-through to login).
1325
+ const apiKeyResult = await fetchApiKeyBalance(ctx);
1326
+ if (apiKeyResult !== null) return send(res, 200, apiKeyResult);
1327
+ // No API key configured -> the account-login route.
1328
+ return send(res, 200, await fetchAccountBalance(ctx));
1329
+ } catch (error) {
1330
+ return send(res, 200, { ok: false, why: String(error && error.message ? error.message : error) });
1331
+ }
1332
+ },
1333
+ });
1334
+ } catch (error) {
1335
+ console.error(`${LOG_TAG} balance bridge failed: ${error && error.message ? error.message : error}`);
1336
+ }
1337
+ };
1338
+ if (webServer !== undefined) mount(webServer);
1339
+ else if (typeof ctx.inject === 'function') ctx.inject(['webServer'], (scope) => mount(scope.webServer));
1340
+ }
1341
+
1342
+ /**
1343
+ * A `get()` / `watch()` view over this plugin's OWN resolved Config.
1344
+ *
1345
+ * DSH >= 0.1.7 has no scope to hand a plugin: a preference edit reaches a running
1346
+ * entry as a committed `.volatile()` reference — the loader writes it into the
1347
+ * live config and emits `loader/volatile-update` — so the current values are read
1348
+ * straight off the resolved config `apply()` was started with (every
1349
+ * `.volatile()` leaf is a `{ get() }` reference) and the audio runtime re-reads
1350
+ * them whenever the loader commits a new one.
1351
+ *
1352
+ * Returns `undefined` when there is nothing to read, which leaves the runtime on
1353
+ * its shipped defaults — the same behaviour as a host with no settings service.
1354
+ *
1355
+ * @param ctx - host Cordis context; its event seam is optional.
1356
+ * @param config - the resolved plugin config (volatile leaves or plain values).
1357
+ */
1358
+ function configPrefScope(ctx, config) {
1359
+ if (config === undefined || config === null || typeof config !== 'object') return undefined;
1360
+ const read = () => {
1361
+ const values = {};
1362
+ for (const [key, value] of Object.entries(config)) {
1363
+ if (value === undefined || value === null) continue;
1364
+ values[key] = typeof value.get === 'function' ? value.get() : value;
1365
+ }
1366
+ return values;
1367
+ };
1368
+ return {
1369
+ get: read,
1370
+ watch: (listener) => {
1371
+ if (typeof ctx.on !== 'function') return () => {};
1372
+ try {
1373
+ return ctx.on('loader/volatile-update', () => { listener(); });
1374
+ } catch (error) {
1375
+ return () => {};
1376
+ }
1377
+ },
1378
+ };
1379
+ }
1380
+
1381
+ /* ---------- 视频背景的素材路由 ----------
1382
+ 视频背景的四个片段与两段音乐体积远大于源码,不能塞进 client.js 的 bundle
1383
+ (base64 会把 14MB 再放大三分之一,而且首屏解码一次没意义)。所以由 Host
1384
+ 以 HTTP 提供,页面按需拉取,浏览器自己处理缓冲、循环与 seek。
1385
+
1386
+ 只服务白名单里的六个文件,路径永远是 `media/<白名单键>`——这个路由没有
1387
+ 办法读到别处,和音频上传路由的"只写自己的目录"是同一条边界。Range 必须
1388
+ 支持:<video> 循环与 seek 会发 `Range: bytes=...`,不回 206 的话 A 段
1389
+ 循环会被浏览器整段重下,或者干脆不循环。 */
1390
+ const MEDIA_ROUTE = '/theme-endfield/media';
1391
+ const MEDIA_FILES = {
1392
+ 'video/A.mp4': 'video/mp4',
1393
+ 'video/B.mp4': 'video/mp4',
1394
+ 'video/B_rev.mp4': 'video/mp4',
1395
+ 'video/C.mp4': 'video/mp4',
1396
+ 'audio/loop.m4a': 'audio/mp4',
1397
+ 'audio/rest.m4a': 'audio/mp4',
1398
+ };
1399
+
1400
+ /**
1401
+ * Resolve one request to a file window. Pure apart from statting the file, so
1402
+ * the range maths can be asserted without a socket.
1403
+ *
1404
+ * @param url - the request URL (query string ignored).
1405
+ * @param rangeHeader - the request's Range header, if any.
1406
+ * @returns `{ status, file, type, start, end, total }`, or `{ status: 404 }`.
1407
+ */
1408
+ function resolveMediaRequest(url, rangeHeader) {
1409
+ /* Required locally: the host bundle is one module, but its fragments keep
1410
+ their own require scope (same convention as the audio install block). */
1411
+ const path = require('path');
1412
+ const fs = require('fs');
1413
+ const pathname = String(url || '').split('?')[0];
1414
+ if (!pathname.startsWith(MEDIA_ROUTE + '/')) return { status: 404 };
1415
+ const key = decodeURIComponent(pathname.slice((MEDIA_ROUTE + '/').length));
1416
+ const type = MEDIA_FILES[key];
1417
+ if (type === undefined) return { status: 404 };
1418
+ /* The whitelist key is also the path suffix; rejecting anything containing
1419
+ a separator keeps `..` from becoming a directory traversal even if a
1420
+ future key is added carelessly. */
1421
+ if (key.split('/').some((part) => part === '..' || part === '')) return { status: 404 };
1422
+ const file = path.join(__dirname, 'media', key);
1423
+ let total = 0;
1424
+ try { total = fs.statSync(file).size; } catch (error) { return { status: 404 }; }
1425
+ const header = String(rangeHeader || '').trim();
1426
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header);
1427
+ if (match === null) return { status: 200, file, type, start: 0, end: total - 1, total };
1428
+ const hasStart = match[1] !== '';
1429
+ const hasEnd = match[2] !== '';
1430
+ if (!hasStart && !hasEnd) return { status: 416, file, type, total };
1431
+ let start;
1432
+ let end;
1433
+ if (!hasStart) {
1434
+ const suffix = Number.parseInt(match[2], 10);
1435
+ if (!Number.isFinite(suffix) || suffix <= 0) return { status: 416, file, type, total };
1436
+ start = Math.max(0, total - suffix);
1437
+ end = total - 1;
1438
+ } else {
1439
+ start = Number.parseInt(match[1], 10);
1440
+ end = hasEnd ? Number.parseInt(match[2], 10) : total - 1;
1441
+ }
1442
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= total) {
1443
+ return { status: 416, file, type, total };
1444
+ }
1445
+ return { status: 206, file, type, start, end: Math.min(end, total - 1), total };
1446
+ }
1447
+
1448
+ /** Register the media route on whatever webServer the host has, if any. */
1449
+ function registerMediaBridge(ctx) {
1450
+ const install = (server) => {
1451
+ if (server === undefined || server === null || typeof server.register !== 'function') return;
1452
+ const handler = (req, res) => {
1453
+ const fs = require('fs');
1454
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
1455
+ res.writeHead(405, { 'content-type': 'text/plain' });
1456
+ res.end();
1457
+ return;
1458
+ }
1459
+ const resolved = resolveMediaRequest(req.url, req.headers && req.headers.range);
1460
+ if (resolved.status === 404) {
1461
+ res.writeHead(404, { 'content-type': 'text/plain' });
1462
+ res.end();
1463
+ return;
1464
+ }
1465
+ if (resolved.status === 416) {
1466
+ res.writeHead(416, { 'content-range': 'bytes */' + String(resolved.total) });
1467
+ res.end();
1468
+ return;
1469
+ }
1470
+ const headers = {
1471
+ 'content-type': resolved.type,
1472
+ 'content-length': String(resolved.end - resolved.start + 1),
1473
+ 'accept-ranges': 'bytes',
1474
+ 'cache-control': 'public, max-age=86400',
1475
+ };
1476
+ if (resolved.status === 206) {
1477
+ headers['content-range'] = 'bytes ' + String(resolved.start) + '-' + String(resolved.end) + '/' + String(resolved.total);
1478
+ }
1479
+ res.writeHead(resolved.status, headers);
1480
+ if (req.method === 'HEAD') { res.end(); return; }
1481
+ const stream = fs.createReadStream(resolved.file, { start: resolved.start, end: resolved.end });
1482
+ stream.on('error', () => { try { res.destroy(); } catch (error) { /* already gone */ } });
1483
+ stream.pipe(res);
1484
+ };
1485
+ try {
1486
+ server.register({ kind: 'prefix', path: MEDIA_ROUTE, handler });
1487
+ } catch (error) {
1488
+ /* A route that cannot register only costs the video background; the
1489
+ theme itself must keep working. */
1490
+ }
1491
+ };
1492
+ const direct = (() => { try { return ctx.get('webServer'); } catch (error) { return undefined; } })();
1493
+ if (direct !== undefined) install(direct);
1494
+ else if (typeof ctx.inject === 'function') {
1495
+ try { ctx.inject(['webServer'], (scope) => install(scope && scope.webServer)); } catch (error) { /* optional service */ }
1496
+ }
1497
+ }
1498
+
1499
+ function apply(ctx, config) {
1500
+ /* Diagnostics, once per mount. Without a volatile Config this entry has no
1501
+ settings form, so the browser half reads and writes its preferences
1502
+ page-locally: every switch still works, and every switch is gone on the next
1503
+ reload. That is indistinguishable from "the theme is broken" unless the host
1504
+ says what happened — so it says it in the log AND leaves a readable report
1505
+ behind, because the reason is a property of this machine's install layout
1506
+ (see resolutionRoots) that no generic message can name. */
1507
+ if (Config === undefined) {
1508
+ reportMissingConfig(ctx);
1509
+ } else {
1510
+ clearStaleDiagnostic(ctx);
1511
+ // Which copy answered, at debug level: the one question that decides whether
1512
+ // a form exists at all, and otherwise invisible.
1513
+ try {
1514
+ if (ctx.logger && typeof ctx.logger.debug === 'function') ctx.logger.debug(NAME + ': Config built from ' + String(SCHEMA_SOURCE) + ' (volatile mode: ' + String(SCHEMA_MODE) + ')');
1515
+ } catch (e) { /* logging is never load-bearing */ }
1516
+ }
1517
+
1518
+ /* The notification feature installs alongside the settings work below: which
1519
+ settings GENERATION answered does not matter to it. A host WITHOUT the
1520
+ inject capability starts the engine right here, on the shipped defaults; a
1521
+ host WITH it starts the engine when the settings service arrives — and if
1522
+ that service never appears, inject keeps waiting, so the engine (and the
1523
+ bridge mounted together with it) never comes up. No known DSH generation
1524
+ behaves that way. The guard keeps the two in-apply paths from installing
1525
+ two engines on one context. */
1526
+ // The balance capsule route mounts unconditionally: the page polls it only
1527
+ // when its own switch is on, so the route itself costs nothing at rest.
1528
+ try { registerBalanceBridge(ctx); } catch (e) { /* never load-bearing */ }
1529
+ /* 视频背景的素材路由:同样无条件挂载——只有在开关打开、页面真的去拉视频时才会
1530
+ 读出文件;路由本身不持有状态。 */
1531
+ try { registerMediaBridge(ctx); } catch (e) { /* never load-bearing */ }
1532
+
1533
+ let audioInstalled = false;
1534
+ const startAudio = (settingsScope) => {
1535
+ if (audioInstalled) return;
1536
+ audioInstalled = true;
1537
+ try {
1538
+ /* The legacy scope wins where a host hands one out; on 0.1.7 the live
1539
+ values are this plugin's own resolved Config (see configPrefScope). */
1540
+ installAudio(ctx, settingsScope === undefined ? configPrefScope(ctx, config) : settingsScope);
1541
+ } catch (error) {
1542
+ // The theme must keep working even if the notification feature cannot
1543
+ // install at all.
1544
+ console.error(`${LOG_TAG} install failed: ${error && error.message ? error.message : error}`);
1545
+ }
1546
+ };
1547
+
1548
+ // Wait for the host settings service. Cordis `ctx.inject(['settings'], ...)`
1549
+ // WAITS for the service (same convention as @deepseek-ai/dsh-client-ui-theme,
1550
+ // dsh-agent-presets, …), so registration is reliable however concurrently
1551
+ // mounted plugins interleave; a synchronous `ctx.get('settings')` probe would
1552
+ // race and could see it absent.
1553
+ //
1554
+ // It is still only an ASK, and asking is what has to be feature-detected — the
1555
+ // webServer lookup above does. A context without `inject` used to throw here
1556
+ // and take the whole mount down; it now ends up on the same defaults-only
1557
+ // engine that a host with no settings service gets.
1558
+ if (typeof ctx.inject !== 'function') {
1559
+ startAudio(undefined);
1560
+ return;
1561
+ }
1562
+ ctx.inject(['settings'], (settingsCtx) => {
1563
+ if (!settingsCtx || !settingsCtx.settings) {
1564
+ startAudio(undefined);
1565
+ return;
1566
+ }
1567
+ const settings = settingsCtx.settings;
1568
+
1569
+ /* DSH >= 0.1.7: page policy only.
1570
+ This plugin renders its own settings page (client.js registers a
1571
+ `settings.section` row with four groups and live previews), so the
1572
+ auto-generated Config page would be a second, poorer copy of it. An
1573
+ absent `autoGenerate:false` policy is what makes DSH add that page.
1574
+ Scoped to this plugin's fiber and disposed with the run. */
1575
+ if (typeof settings.configure === 'function') {
1576
+ try {
1577
+ settingsCtx.effect(() => settings.configure({ auto: false }, ctx.fiber));
1578
+ } catch (e) {
1579
+ // A policy may already be registered for this fiber (double mount);
1580
+ // the theme must still load.
1581
+ }
1582
+ }
1583
+
1584
+ /* DSH <= 0.1.5-rc.2: the legacy namespace registration.
1585
+ Those hosts persisted a plugin-declared namespace to
1586
+ `<dshHome>/settings.yaml` and mirrored it to the browser through
1587
+ `ctx.settingsScope`, which the client half still binds when no
1588
+ `configForms` service exists. Feature-detected: on 0.1.7 `register` is
1589
+ gone and this branch is simply skipped — the Config above is the
1590
+ declaration instead. Its RETURN VALUE is also the only live preference
1591
+ scope those hosts expose, so it is what the audio runtime reads. */
1592
+ let scope;
1593
+ if (typeof settings.register === 'function') {
1594
+ const schema = buildSchema(false);
1595
+ if (schema !== undefined) {
1596
+ try {
1597
+ // Registration is scoped to this plugin's fiber and disposed with the run.
1598
+ scope = settings.register(LEGACY_NAMESPACE, schema, { applies: 'live' });
1599
+ } catch (e) {
1600
+ // A throw here must not kill the whole theme; leaving it unregistered
1601
+ // just means browser prefs stay page-local on that host generation.
1602
+ }
1603
+ }
1604
+ }
1605
+ startAudio(scope);
1606
+ });
1607
+ }
1608
+
1609
+ /* The module export.
1610
+ *
1611
+ * `Config` is written as a STATIC property of the literal on purpose. DSH
1612
+ * imports loader entries through Node's internal ESM loader, which interops a
1613
+ * CommonJS file by building its namespace from cjs-module-lexer's static
1614
+ * analysis of this file. A property assigned afterwards
1615
+ * (`exported.Config = Config`) is invisible to that analysis, and a namespace
1616
+ * that cannot see it leaves DSH's `unwrapExports()` with an object whose
1617
+ * `apply` (a literal property, so detected) mounts the entry while `Config`
1618
+ * stays undefined — the entry runs, `Config.listConfigs` reports `absent`, and
1619
+ * no settings form exists. Hence: literal property, always present, with the
1620
+ * value `undefined` when no schemastery builder was reachable (which is a
1621
+ * legitimate "nothing to configure" and not a broken schema). */
1622
+ module.exports = {
1623
+ name: NAME,
1624
+ apply,
1625
+ Config,
1626
+ // Exposed for tests/documentation.
1627
+ NAMESPACE,
1628
+ SETTINGS_ENTRY,
1629
+ LEGACY_NAMESPACE,
1630
+ FIELD_DEFAULTS,
1631
+ /* Pure helpers, so the settings contracts below can be asserted against a
1632
+ stand-in builder instead of whatever schemastery the test machine happens
1633
+ to have (see test/settings-config-fallback.test.js). */
1634
+ buildSchemaWith,
1635
+ selectBuilder,
1636
+ volatileField,
1637
+ /* Audio-notification surface, asserted by test/audio-notify.test.js. */
1638
+ AUDIO_PREF_DEFAULTS: AUDIO_FALLBACK,
1639
+ classifyPrompt,
1640
+ hasVisibleText,
1641
+ installAudio,
1642
+ registerBalanceBridge,
1643
+ registerMediaBridge,
1644
+ resolveMediaRequest,
1645
+ MEDIA_FILES,
1646
+ configPrefScope,
1647
+ };