@ssamurias/dsh-fish 1.0.7 → 1.0.9

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.
Files changed (77) hide show
  1. package/AGENTS.md +32 -3
  2. package/CHANGELOG.md +4366 -4265
  3. package/README.md +243 -627
  4. package/RELEASE-NOTES-1.0.8.md +81 -0
  5. package/RELEASE-NOTES-1.0.9.md +79 -0
  6. package/THIRD-PARTY-NOTICES.md +1 -1
  7. package/docs/troubleshooting.md +79 -1
  8. package/docs//350/256/244/344/272/272/345/210/244/346/215/256.md +112 -0
  9. package/lib/appoint.js +106 -22
  10. package/lib/ask.js +8 -3
  11. package/lib/at.js +16 -1
  12. package/lib/capture.js +51 -1
  13. package/lib/claim.js +103 -0
  14. package/lib/client/00-shell.js +500 -0
  15. package/lib/client/01-state-load.js +860 -0
  16. package/lib/client/02-actions.js +670 -0
  17. package/lib/client/03-widgets-header.js +721 -0
  18. package/lib/client/04-pressure-lab.js +891 -0
  19. package/lib/client/05-pressure-charts.js +431 -0
  20. package/lib/client/06-tab-status-grow.js +468 -0
  21. package/lib/client/07-tab-home-bili.js +542 -0
  22. package/lib/client/08-tab-memory-plugins.js +733 -0
  23. package/lib/client/09-tab-outing.js +710 -0
  24. package/lib/client/10-data-handlers.js +519 -0
  25. package/lib/client/11-tab-data-frame.js +661 -0
  26. package/lib/client/12-pressure-chip-mount.js +565 -0
  27. package/lib/client.js +109 -24
  28. package/lib/comment.js +18 -3
  29. package/lib/cue.js +102 -5
  30. package/lib/deliver.js +3 -1
  31. package/lib/derive.js +308 -41
  32. package/lib/doing.js +31 -15
  33. package/lib/drive.js +3 -5
  34. package/lib/env.d.ts +224 -0
  35. package/lib/health.js +56 -0
  36. package/lib/hear.js +70 -0
  37. package/lib/home.js +48 -20
  38. package/lib/identity.js +25 -2
  39. package/lib/index.js +32 -18
  40. package/lib/look.js +2 -1
  41. package/lib/loops.js +39 -0
  42. package/lib/make.js +60 -12
  43. package/lib/markup.js +77 -1
  44. package/lib/match.js +262 -0
  45. package/lib/observe-bili.js +331 -0
  46. package/lib/observe-config.js +223 -0
  47. package/lib/observe-data.js +522 -0
  48. package/lib/observe-home.js +383 -0
  49. package/lib/observe-http.js +250 -0
  50. package/lib/observe-outing.js +650 -0
  51. package/lib/observe-state.js +419 -0
  52. package/lib/observe-trip.js +286 -0
  53. package/lib/observe.js +99 -3574
  54. package/lib/persona.js +187 -40
  55. package/lib/proactive.js +48 -47
  56. package/lib/pronounask.js +15 -1
  57. package/lib/restrict.js +146 -9
  58. package/lib/say.js +68 -4
  59. package/lib/scheduler.js +63 -25
  60. package/lib/schema.js +57 -4
  61. package/lib/scrub.js +16 -1
  62. package/lib/settings.js +128 -12
  63. package/lib/stance.js +131 -19
  64. package/lib/status.js +14 -5
  65. package/lib/store.js +24 -2
  66. package/lib/sub.js +7 -1
  67. package/lib/talkmem.js +12 -8
  68. package/lib/transcript.js +205 -0
  69. package/lib/turns.js +147 -19
  70. package/lib/types.d.ts +513 -0
  71. package/lib/voices.js +26 -1
  72. package/lib/wiki.js +47 -13
  73. package/lib/works.js +200 -49
  74. package/media/banner.jpg +0 -0
  75. package/package.json +1 -1
  76. package/scripts/build-client.mjs +83 -0
  77. package/scripts/sync-pressure-formulas.mjs +12 -15
@@ -0,0 +1,383 @@
1
+ // @ts-check
2
+ /**
3
+ * observe-home.js —— 观测台屋子、叫醒、桥接投递、信箱、头像、静态图、交接导入与重置/换房路由
4
+ *
5
+ * 路由:
6
+ * /wake · /say · /whoami · /inbox · /home · /paths · /notify · /avatar · /media
7
+ * /import · /reset · /home/rebuild · /home/rotate
8
+ */
9
+
10
+ import fs from 'node:fs'
11
+ import { join } from 'node:path'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { readEvents, paths } from './store.js'
14
+ import { loadConfig, updateConfig, dateKey } from './settings.js'
15
+ import { selfPronounOf, fillSelf } from './selfpronoun.js'
16
+ import { deriveSelf } from './derive.js'
17
+ import { wakeNow } from './scheduler.js'
18
+ import { sayToHer } from './say.js'
19
+ import { readInbox, markRead, writeInboxFile } from './inbox.js'
20
+ import { avatarFile, avatarInfo, saveAvatar, removeAvatar } from './avatar.js'
21
+ import { describeState, resetAll } from './reset.js'
22
+ import { applyHandover, hasOwnStart, IMPORT_TEMPLATE } from './import.js'
23
+ import { bridgeUrl } from './bridgeserve.js'
24
+ import { readHomeRecord, retireHomeSessions } from './retire.js'
25
+ import { bootstrapHome, homeStatus, wakeIfBlank, rotateTalkSession } from './home.js'
26
+ import { selfDocStatus, refreshSelfDoc } from './selfdoc.js'
27
+ import { ensureDataReadme } from './readme.js'
28
+ import { readPending, markShown } from './notify.js'
29
+ import { decodeBase64Image, saveImage } from './media.js'
30
+ import { PREFIX, send, sentTooLarge, readBody } from './observe-http.js'
31
+
32
+ /**
33
+ * 宿主内 `/dsh-fish/say`、`/dsh-fish/whoami` 与回环投递口 `bridgeserve.js` 共用的两个 handler。
34
+ *
35
+ * @param {import('./types.js').ObserveEnv} env
36
+ */
37
+ export function createBridgeHandlers(env) {
38
+ const { ctx, root, deps, flog } = env
39
+
40
+ /**
41
+ * @param {import('./types.js').HttpRequest} req
42
+ * @param {import('./types.js').HttpResponse} res
43
+ */
44
+ const sayHandler = async (req, res) => {
45
+ if (req.method !== 'POST') return send(res, 405, { error: 'method not allowed' })
46
+ const raw = await readBody(req, 12_000_000)
47
+ /** @type {Record<string, any>} */
48
+ let body = {}
49
+ try { body = JSON.parse(raw || '{}') } catch { return send(res, 400, { error: 'body 不是 JSON' }) }
50
+ const text = String(body.text ?? '').trim()
51
+
52
+ let imagePath = ''
53
+ if (body.image) {
54
+ const dec = decodeBase64Image(body.image)
55
+ if (!dec.ok || !dec.buf) return send(res, 400, { error: dec.why })
56
+ const saved = await saveImage(root, dec.buf, { prefix: 'him' })
57
+ if (!saved.ok || !saved.path) return send(res, 400, { error: saved.why })
58
+ imagePath = saved.path
59
+ }
60
+
61
+ if (!text && !imagePath) return send(res, 400, { error: 'text 不能为空' })
62
+ const r = await sayToHer(ctx, text, {
63
+ root,
64
+ imagePath,
65
+ scene: body.scene,
66
+ channel: body.channel,
67
+ speaker: body.speaker,
68
+ room: body.room,
69
+ title: body.title,
70
+ guest: body.guest,
71
+ owner: body.owner,
72
+ log: flog('info'),
73
+ })
74
+ send(res, 200, r)
75
+ }
76
+
77
+ /**
78
+ * @param {import('./types.js').HttpRequest} req
79
+ * @param {import('./types.js').HttpResponse} res
80
+ */
81
+ const whoamiHandler = async (req, res) => {
82
+ if (req.method !== 'GET') return send(res, 405, { error: 'method not allowed' })
83
+ const h = await homeStatus(root)
84
+ const tenant = deps.tenancy?.tenant ?? { ok: true }
85
+ send(res, 200, {
86
+ ok: true,
87
+ plugin: 'dsh-fish',
88
+ version: deps.version ?? '',
89
+ root,
90
+ home: Boolean(h.sessionId),
91
+ sessionId: h.sessionId ?? '',
92
+ writable: tenant.ok !== false,
93
+ bridge: bridgeUrl(),
94
+ })
95
+ }
96
+
97
+ return { sayHandler, whoamiHandler }
98
+ }
99
+
100
+ /**
101
+ * @param {import('./types.js').ObserveEnv} env
102
+ * @param {{ sayHandler: import('./types.js').ObserveHandler, whoamiHandler: import('./types.js').ObserveHandler }} bridgeHandlers
103
+ * @returns {import('./types.js').ObserveRouteEntry[]}
104
+ */
105
+ export function buildHomeRoutes(env, bridgeHandlers) {
106
+ const { ctx, root, flog, inflight, awayFromBeat, reclaimTenant } = env
107
+ const { sayHandler, whoamiHandler } = bridgeHandlers
108
+
109
+ return [
110
+ ['/wake', async (req, res) => {
111
+ if (req.method !== 'POST') return send(res, 405, { error: 'method not allowed' })
112
+ let focus = ''
113
+ try { focus = new URL(String(req.url ?? '/'), 'http://localhost').searchParams.get('focus') ?? '' } catch { /* 解析失败就当没传 */ }
114
+ const r = /** @type {any} */ (await wakeNow(ctx, { root, focus, log: flog('info') }))
115
+ send(res, r.ok ? 200 : 409, r.ok ? r : { ...r, error: r.why || '这次没叫醒' })
116
+ }],
117
+
118
+ ['/say', sayHandler],
119
+ ['/whoami', whoamiHandler],
120
+
121
+ ['/inbox', async (req, res) => {
122
+ if (req.method === 'POST') {
123
+ const r = await markRead(root)
124
+ await writeInboxFile(root).catch(() => null)
125
+ return send(res, 200, r)
126
+ }
127
+ const url = new URL(req.url ?? '/', 'http://x')
128
+ const limit = Math.min(500, Number(url.searchParams.get('limit') ?? 200) || 200)
129
+ const box = await readInbox(root, { limit })
130
+ await writeInboxFile(root, { limit: 60 }).catch(() => null)
131
+ send(res, 200, box)
132
+ }],
133
+
134
+ ['/home', async (_req, res) => {
135
+ const h = await homeStatus(root)
136
+ const d = await selfDocStatus(root)
137
+ let wsTitle = ''
138
+ try {
139
+ const reg = ctx.get?.('workspaceRegistry')
140
+ wsTitle = String(reg?.get?.(h.wsId)?.title ?? '')
141
+ } catch { wsTitle = '' }
142
+ send(res, 200, {
143
+ workspace: { id: h.wsId, ok: Boolean(h.wsId), title: wsTitle },
144
+ session: { id: h.sessionId, ok: Boolean(h.sessionId) },
145
+ dir: h.dir,
146
+ createdAt: h.createdAt,
147
+ selfDoc: { exists: d.exists, bytes: d.bytes, mtime: d.mtime },
148
+ })
149
+ }],
150
+
151
+ ['/paths', async (req, res) => {
152
+ const p = paths(root)
153
+ await ensureDataReadme(root)
154
+ send(res, 200, {
155
+ root: p.root,
156
+ events: p.events,
157
+ out: p.outDir,
158
+ diary: p.diaryDir,
159
+ home: p.herDir,
160
+ inbox: join(p.root, 'inbox.md'),
161
+ log: join(p.root, 'logs', 'dsh-fish.log'),
162
+ })
163
+ }],
164
+
165
+ ['/notify', async (req, res) => {
166
+ const { config } = await loadConfig(root)
167
+ if (req.method === 'POST') {
168
+ const raw = await readBody(req)
169
+ /** @type {Record<string, any>} */
170
+ let body = {}
171
+ try { body = JSON.parse(raw || '{}') } catch { return send(res, 400, { error: 'body 不是 JSON' }) }
172
+ if (body.shown === true) {
173
+ const r = await markShown(root, dateKey())
174
+ return send(res, 200, { ok: r.ok, lastShown: r.lastShown, today: dateKey() })
175
+ }
176
+ if (typeof body.enabled !== 'boolean') return send(res, 400, { error: 'enabled 必须是 true/false,或 shown:true' })
177
+ const next = await updateConfig({ notify: { enabled: body.enabled } }, root)
178
+ return send(res, 200, {
179
+ enabled: next.notify?.enabled === true,
180
+ lastShown: next.notify?.lastShown ?? '',
181
+ today: dateKey(),
182
+ })
183
+ }
184
+ const p = await readPending(root, { today: dateKey() })
185
+ send(res, 200, { ...p, enabled: config.notify?.enabled === true })
186
+ }],
187
+
188
+ ['/avatar', async (req, res) => {
189
+ const url = String(req.url ?? '')
190
+ if (url.startsWith(PREFIX + '/avatar/info')) { send(res, 200, avatarInfo(root)); return }
191
+ if (req.method === 'POST') {
192
+ /** @type {Record<string, any>} */
193
+ let body = {}
194
+ try {
195
+ const raw = await readBody(req, 4_000_000)
196
+ body = raw ? JSON.parse(raw) : {}
197
+ } catch (err) {
198
+ if (sentTooLarge(res, err)) return
199
+ body = {}
200
+ }
201
+ const r = /** @type {any} */ (body && body.remove ? removeAvatar(root) : saveAvatar(root, body))
202
+ if (!r || r.ok === false) { send(res, 400, { error: (r && r.why) || '没存上' }); return }
203
+ send(res, 200, { ok: true, removed: Boolean(r.removed), ...avatarInfo(root) })
204
+ return
205
+ }
206
+ const file = avatarFile(root)
207
+ if (!file) { send(res, 404, { error: 'no avatar' }); return }
208
+ try {
209
+ const buf = fs.readFileSync(file)
210
+ const ext = (file.split('.').pop() || '').toLowerCase()
211
+ const ct = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : ext === 'gif' ? 'image/gif' : 'image/jpeg'
212
+ res.writeHead(200, { 'content-type': ct, 'content-length': buf.length, 'cache-control': 'no-store' })
213
+ res.end(buf)
214
+ } catch { send(res, 404, { error: 'no avatar' }) }
215
+ }],
216
+
217
+ ['/media', async (req, res) => {
218
+ const m = String(req.url ?? '').match(/^\/dsh-fish\/media\/((?:principle-[a-z]+\.svg)|(?:feedback-qr\.jpg))(?:\?[^#]*)?$/)
219
+ if (!m) { send(res, 404, { error: 'no file' }); return }
220
+ try {
221
+ const file = fileURLToPath(new URL(`../media/${m[1]}`, import.meta.url))
222
+ const buf = fs.readFileSync(file)
223
+ const isJpg = m[1].endsWith('.jpg')
224
+ res.writeHead(200, {
225
+ 'content-type': isJpg ? 'image/jpeg' : 'image/svg+xml; charset=utf-8',
226
+ 'content-length': buf.length,
227
+ 'cache-control': 'private, max-age=3600',
228
+ })
229
+ res.end(buf)
230
+ } catch { send(res, 404, { error: 'no file' }) }
231
+ }],
232
+
233
+ ['/import', async (req, res) => {
234
+ if (req.method === 'GET') {
235
+ const { events } = await readEvents(root).catch(() => ({ events: [] }))
236
+ const blocked = hasOwnStart(events)
237
+ const { config } = await loadConfig(root).catch(() => ({ config: null }))
238
+ const model = deriveSelf(events, { growthDays: config?.growthDays })
239
+ return send(res, 200, {
240
+ canImport: !blocked,
241
+ reason: blocked ? '她已经有自己的起点了。想换成别人养的那一位,先重置成新的一局。' : '',
242
+ persona: { imported: model?.persona?.imported === true, source: model?.persona?.source ?? '' },
243
+ template: IMPORT_TEMPLATE,
244
+ })
245
+ }
246
+ if (req.method !== 'POST') return send(res, 405, { error: 'method not allowed' })
247
+ const raw = await readBody(req, 200_000)
248
+ /** @type {Record<string, any>} */
249
+ let b = {}
250
+ try { b = JSON.parse(raw || '{}') } catch { return send(res, 400, { error: 'body 不是合法 JSON' }) }
251
+ const r = /** @type {any} */ (await applyHandover(b.text, root, /** @type {any} */ ({
252
+ log: flog('info'),
253
+ source: b.source ? String(b.source) : '',
254
+ })))
255
+ if (!r.ok) return send(res, 409, { ok: false, error: r.why })
256
+ await refreshSelfDoc(root).catch(() => {})
257
+ const { events } = await readEvents(root).catch(() => ({ events: [] }))
258
+ const cfgNow = await loadConfig(root).then((x) => x.config, () => undefined)
259
+ const model = deriveSelf(events, cfgNow)
260
+ send(res, 200, {
261
+ ok: true,
262
+ name: r.name,
263
+ tools: r.tools,
264
+ toolsAdded: r.toolsAdded ?? [],
265
+ toolsError: r.toolsError ?? '',
266
+ bodyChars: r.bodyChars,
267
+ day: model.day,
268
+ stage: model.stage,
269
+ called: model.name,
270
+ note: fillSelf('人设已经接过来。{S}是从第 1 天开始的,往后按你和她的事自己长。', selfPronounOf(cfgNow)),
271
+ })
272
+ }],
273
+
274
+ ['/reset', async (req, res) => {
275
+ if (req.method === 'GET') {
276
+ const info = await describeState(root)
277
+ return send(res, 200, { ...info, root })
278
+ }
279
+ if (req.method !== 'POST') return send(res, 405, { error: 'method not allowed' })
280
+ const body = await readBody(req)
281
+ /** @type {Record<string, any>} */
282
+ let b = {}
283
+ try { b = JSON.parse(body || '{}') } catch { return send(res, 400, { error: 'body 不是合法 JSON' }) }
284
+ if (b.confirm !== 'reset') return send(res, 400, { error: '要带 confirm:"reset"' })
285
+ const home = await readHomeRecord(root)
286
+ const r = /** @type {any} */ (await awayFromBeat(() => resetAll(root)))
287
+ if (!r.ok) return send(res, 409, { ok: false, error: r.why })
288
+ try { await fs.promises.mkdir(root, { recursive: true }) } catch { /* ignore */ }
289
+ await reclaimTenant()
290
+ const retired = /** @type {any} */ (await retireHomeSessions(ctx, { root, home, log: flog('info') }))
291
+ const { config: cfg } = await loadConfig(root)
292
+ const fresh = /** @type {any} */ (await bootstrapHome(ctx, /** @type {any} */ ({
293
+ root,
294
+ preset: cfg?.tools?.preset ?? '',
295
+ log: flog('info'),
296
+ force: true,
297
+ })))
298
+ const woke = fresh.ok
299
+ ? await wakeIfBlank(ctx, /** @type {any} */ ({ sessionId: fresh.sessionId, root, log: flog('info'), freshOnly: !fresh.reused, verify: true }))
300
+ : { woke: false }
301
+ send(res, 200, {
302
+ ok: true,
303
+ movedTo: r.movedTo,
304
+ archived: retired.archived,
305
+ retiredError: retired.ok ? '' : retired.why,
306
+ fresh: fresh.ok ? { wsId: fresh.wsId, sessionId: fresh.sessionId, title: fresh.reused ? '' : '跟大肥鱼说话', woke: woke.woke === true } : null,
307
+ freshError: fresh.ok ? '' : fresh.why,
308
+ note: fresh.ok
309
+ ? (retired.ok
310
+ ? '旧的一切已经封存,旧会话移进「已归档」。新的一局已经开好;点一下「叫醒大肥鱼」,侧栏里才会出现那条会话。'
311
+ : '状态库已封存,新的一局也开好了;只有旧会话没全收进「已归档」。点一下「叫醒大肥鱼」,侧栏里才会出现会话。')
312
+ : '状态库已封存,但新会话没建出来(重启 DSH 会自动建)。',
313
+ })
314
+ }],
315
+
316
+ ['/home/rebuild', async (req, res) => {
317
+ if (req.method !== 'POST') return send(res, 405, { error: 'method not allowed' })
318
+ const body = await readBody(req)
319
+ /** @type {Record<string, any>} */
320
+ let b = {}
321
+ try { b = JSON.parse(body || '{}') } catch { return send(res, 400, { error: 'body 不是合法 JSON' }) }
322
+ if (b.confirm !== 'rebuild') return send(res, 400, { error: '要带 confirm:"rebuild"' })
323
+ const { config: cfg } = await loadConfig(root)
324
+ const fresh = /** @type {any} */ (await bootstrapHome(ctx, /** @type {any} */ ({
325
+ root,
326
+ preset: cfg?.tools?.preset ?? '',
327
+ log: flog('info'),
328
+ force: true,
329
+ })))
330
+ const woke = fresh.ok
331
+ ? await wakeIfBlank(ctx, /** @type {any} */ ({ sessionId: fresh.sessionId, root, log: flog('info'), freshOnly: !fresh.reused, verify: true }))
332
+ : { woke: false }
333
+ send(res, fresh.ok ? 200 : 409, {
334
+ ok: fresh.ok,
335
+ sessionId: fresh.sessionId ?? '',
336
+ wasArchived: fresh.wasArchived === true,
337
+ woke: woke.woke === true,
338
+ error: fresh.ok ? '' : fresh.why,
339
+ note: fresh.ok
340
+ ? '新的一局搭好了。点一下「叫醒大肥鱼」,侧栏里才会出现这条会话。'
341
+ : fresh.why,
342
+ })
343
+ }],
344
+
345
+ ['/home/rotate', async (req, res) => {
346
+ if (req.method !== 'POST') return send(res, 405, { error: 'method not allowed' })
347
+ const body = await readBody(req)
348
+ /** @type {Record<string, any>} */
349
+ let b = {}
350
+ try { b = JSON.parse(body || '{}') } catch { return send(res, 400, { error: 'body 不是合法 JSON' }) }
351
+ if (b.confirm !== 'rotate') return send(res, 400, { error: '要带 confirm:"rotate"' })
352
+ const h = await homeStatus(root)
353
+ const current = String(h.sessionId ?? '')
354
+ const busyAt = inflight.get(String(b.from ?? current))
355
+ if (busyAt && Date.now() - busyAt < 15 * 60_000) {
356
+ return send(res, 409, { ok: false, busy: true, error: '她这轮还没说完,等这句话出来再换。' })
357
+ }
358
+ const out = /** @type {any} */ (await rotateTalkSession(ctx, {
359
+ root,
360
+ from: current,
361
+ log: flog('info'),
362
+ }))
363
+ if (!out.ok) return send(res, 409, { ok: false, error: out.why || '没换成。' })
364
+ const woke = await wakeIfBlank(ctx, /** @type {any} */ ({
365
+ sessionId: out.sessionId,
366
+ root,
367
+ log: flog('info'),
368
+ freshOnly: true,
369
+ verify: true,
370
+ })).catch(() => ({ woke: false }))
371
+ send(res, 200, {
372
+ ok: true,
373
+ sessionId: out.sessionId ?? '',
374
+ old: out.old ?? '',
375
+ skipped: out.skipped === true,
376
+ woke: woke?.woke === true,
377
+ note: woke?.woke === true
378
+ ? '新的一间开好了,也叫了她一声——侧栏里等她说出第一句就会出现。'
379
+ : '新的一间开好了。到「状态」页点一下「现在叫醒大肥鱼」,她开一次口,侧栏里才看得见。',
380
+ })
381
+ }],
382
+ ]
383
+ }
@@ -0,0 +1,250 @@
1
+ // @ts-check
2
+ /**
3
+ * observe-http.js —— 观测台 HTTP 读写、信任栅栏与宿主辅助函数
4
+ *
5
+ * 从 observe.js 拆出:只管请求体解码、JSON 响应、连接信任校验与打开系统目录,
6
+ * 不掺杂具体业务路由。
7
+ */
8
+
9
+ import { spawn } from 'node:child_process'
10
+ import { looksMojibake } from './guard.js'
11
+ import { logLine } from './log.js'
12
+
13
+ export const PREFIX = '/dsh-fish'
14
+
15
+ /**
16
+ * @param {import('./types.js').HostContext | null | undefined} ctx
17
+ * @param {string} key
18
+ * @returns {any}
19
+ */
20
+ export function safeGet(ctx, key) {
21
+ try { return ctx?.get?.(key) } catch { return null }
22
+ }
23
+
24
+ /**
25
+ * 用系统文件管理器打开一个目录(2026-11-17)。
26
+ * win32 = explorer,darwin = open,其它 = xdg-open。
27
+ * 只接受服务端算好的目录;explorer.exe 成功时也常回非 0 退出码,所以不看退出码。
28
+ *
29
+ * @param {string} dir
30
+ * @returns {Promise<boolean>}
31
+ */
32
+ export function openFolderInSystem(dir) {
33
+ const cmd = process.platform === 'win32' ? 'explorer' : process.platform === 'darwin' ? 'open' : 'xdg-open'
34
+ return new Promise((resolve) => {
35
+ let child
36
+ try {
37
+ child = spawn(cmd, [dir], { detached: true, stdio: 'ignore', windowsHide: false })
38
+ } catch {
39
+ resolve(false)
40
+ return
41
+ }
42
+ let settled = false
43
+ /** @param {boolean} ok */
44
+ const done = (ok) => {
45
+ if (settled) return
46
+ settled = true
47
+ clearTimeout(timer)
48
+ resolve(ok)
49
+ }
50
+ const timer = setTimeout(() => done(true), 800)
51
+ child.on('spawn', () => done(true))
52
+ child.on('error', () => done(false))
53
+ child.unref()
54
+ })
55
+ }
56
+
57
+ /**
58
+ * @param {import('./types.js').HttpResponse} res
59
+ * @param {number} code
60
+ * @param {unknown} obj
61
+ */
62
+ export function send(res, code, obj) {
63
+ if (res.writableEnded) return
64
+ const body = JSON.stringify(obj, null, 2)
65
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
66
+ res.end(body)
67
+ }
68
+
69
+ /**
70
+ * readBody 超限(413)时原样回 413,返回 true;别的错误返回 false,交给调用方原来的处理。
71
+ *
72
+ * @param {import('./types.js').HttpResponse} res
73
+ * @param {any} err
74
+ * @returns {boolean}
75
+ */
76
+ export function sentTooLarge(res, err) {
77
+ if (err?.statusCode !== 413) return false
78
+ send(res, 413, { error: String(err.message ?? 'body too large') })
79
+ return true
80
+ }
81
+
82
+ /**
83
+ * 读请求体(Buffer 数组拼完一次性按 UTF-8 解码,防止多字节汉字跨 TCP chunk 碎成 \uFFFD)。
84
+ *
85
+ * @param {import('./types.js').HttpRequest} req
86
+ * @param {number} [maxBytes]
87
+ * @param {{ mojibake?: boolean }} [opts]
88
+ * @returns {Promise<string>}
89
+ */
90
+ export function readBody(req, maxBytes = 1_000_000, { mojibake = true } = {}) {
91
+ return new Promise((resolve, reject) => {
92
+ /** @type {Buffer[]} */
93
+ const chunks = []
94
+ let size = 0
95
+ let over = false
96
+ req.on('data', (c) => {
97
+ const b = Buffer.isBuffer(c) ? c : Buffer.from(c)
98
+ size += b.length
99
+ if (over) {
100
+ if (size > 2 * maxBytes) req.destroy?.()
101
+ return
102
+ }
103
+ if (size > maxBytes) {
104
+ over = true
105
+ chunks.length = 0
106
+ const err = /** @type {Error & { statusCode?: number }} */ (new Error('body too large'))
107
+ err.statusCode = 413
108
+ reject(err)
109
+ return
110
+ }
111
+ chunks.push(b)
112
+ })
113
+ req.on('end', () => {
114
+ if (over) return
115
+ const text = Buffer.concat(chunks).toString('utf8')
116
+ if (mojibake && looksMojibake(text)) {
117
+ const err = /** @type {Error & { statusCode?: number }} */ (new Error('正文不是 UTF-8,没递给她'))
118
+ err.statusCode = 400
119
+ return reject(err)
120
+ }
121
+ resolve(text)
122
+ })
123
+ req.on('error', reject)
124
+ })
125
+ }
126
+
127
+ /**
128
+ * 收原始字节,**不解码**(给 `.json.enc` 二进制加密备份恢复用)。
129
+ *
130
+ * @param {import('./types.js').HttpRequest} req
131
+ * @param {number} [maxBytes]
132
+ * @returns {Promise<Buffer>}
133
+ */
134
+ export function readBodyBuffer(req, maxBytes = 1_000_000) {
135
+ return new Promise((resolve, reject) => {
136
+ /** @type {Buffer[]} */
137
+ const chunks = []
138
+ let size = 0
139
+ let over = false
140
+ req.on('data', (c) => {
141
+ const b = Buffer.isBuffer(c) ? c : Buffer.from(c)
142
+ size += b.length
143
+ if (over) {
144
+ if (size > 2 * maxBytes) req.destroy?.()
145
+ return
146
+ }
147
+ if (size > maxBytes) {
148
+ over = true
149
+ chunks.length = 0
150
+ const err = /** @type {Error & { statusCode?: number }} */ (new Error('body too large'))
151
+ err.statusCode = 413
152
+ reject(err)
153
+ return
154
+ }
155
+ chunks.push(b)
156
+ })
157
+ req.on('end', () => {
158
+ if (over) return
159
+ resolve(Buffer.concat(chunks))
160
+ })
161
+ req.on('error', reject)
162
+ })
163
+ }
164
+
165
+ /** @param {any} rejection */
166
+ function rejectionCode(rejection) {
167
+ if (typeof rejection === 'number') return rejection
168
+ const n = Number(rejection?.status)
169
+ return Number.isFinite(n) && n >= 400 && n <= 599 ? n : 403
170
+ }
171
+
172
+ /** @param {any} rejection */
173
+ function rejectionMessage(rejection) {
174
+ if (typeof rejection === 'number') {
175
+ return rejection === 401
176
+ ? 'unauthenticated(这条路由要 App 的登录 cookie,外部进程请用插件自带的本机投递口)'
177
+ : 'forbidden(这个 Host 不认)'
178
+ }
179
+ const s = String(rejection?.message ?? '').trim()
180
+ return s || 'forbidden'
181
+ }
182
+
183
+ /**
184
+ * 信任栅栏:失败即拒绝(拿不到 connection 服务就 503,不放行)。
185
+ *
186
+ * @param {import('./types.js').HostContext} ctx
187
+ * @param {string} root
188
+ */
189
+ export function makeGuarded(ctx, root) {
190
+ /**
191
+ * @param {(req: import('./types.js').HttpRequest, res: import('./types.js').HttpResponse) => Promise<any> | any} handler
192
+ */
193
+ return function guarded(handler) {
194
+ /**
195
+ * @param {import('./types.js').HttpRequest} req
196
+ * @param {import('./types.js').HttpResponse} res
197
+ */
198
+ return async (req, res) => {
199
+ const conn = safeGet(ctx, 'connection')
200
+ if (!conn) return send(res, 503, { error: 'connection service unavailable' })
201
+ try {
202
+ const rejection = conn.requestRejection?.(req)
203
+ if (rejection) return send(res, rejectionCode(rejection), { error: rejectionMessage(rejection) })
204
+ } catch (err) {
205
+ logLine('warn', [
206
+ '信任校验抛错,这次请求没进处理',
207
+ `${req?.method ?? ''} ${req?.url ?? ''}`.trim(),
208
+ String(/** @type {any} */ (err)?.message ?? err).slice(0, 160),
209
+ ], root)
210
+ return send(res, 503, { error: 'trust check failed' })
211
+ }
212
+ try {
213
+ await handler(req, res)
214
+ } catch (err) {
215
+ const code = /** @type {any} */ (err)?.statusCode ?? 500
216
+ logLine(code >= 500 ? 'error' : 'warn', [
217
+ '处理这条请求时抛错',
218
+ `${req?.method ?? ''} ${req?.url ?? ''}`.trim(),
219
+ `-> ${code}`,
220
+ String(/** @type {any} */ (err)?.message ?? err).slice(0, 200),
221
+ ], root)
222
+ send(res, code, { error: String(/** @type {any} */ (err)?.message ?? err) })
223
+ }
224
+ }
225
+ }
226
+ }
227
+
228
+ /**
229
+ * 独立页面的替代品(浏览器直接敲 /dsh-fish 且带了认证时的说明页)。
230
+ */
231
+ export const PAGE = [
232
+ '<!doctype html>',
233
+ '<html lang="zh-CN"><head><meta charset="utf-8">',
234
+ '<meta name="viewport" content="width=device-width,initial-scale=1">',
235
+ '<title>鱼 · 观测台搬进 App 了</title>',
236
+ '<style>',
237
+ 'body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0e1116;color:#d7dde5;',
238
+ ' font:14px/1.7 -apple-system,"Segoe UI","Microsoft YaHei",sans-serif}',
239
+ '.box{max-width:540px;padding:26px 30px;border:1px solid #262d36;border-radius:12px;background:#12161c}',
240
+ 'h1{font-size:16px;margin:0 0 12px;font-weight:600}',
241
+ 'p{margin:9px 0;color:#9aa4b2;font-size:13px;line-height:1.75}',
242
+ 'code{background:#1b212a;border:1px solid #262d36;border-radius:5px;padding:1px 6px;font-size:12px;color:#d7dde5}',
243
+ '</style></head>',
244
+ '<body><div class="box">',
245
+ ' <h1>观测台搬进 App 里了</h1>',
246
+ ' <p>这一页只能从 App 内部打开 —— 在浏览器里直接访问会被登录栅栏拦下。这是设计如此,不是坏了。</p>',
247
+ ' <p>请到 <code>设置 → 鱼</code>:她的状态、她自己说过的话、日记、生长环境,都在那里。</p>',
248
+ ' <p>她的数据仍然全部在 <code>~/.dsh-fish</code>,可以直接看文件。</p>',
249
+ '</div></body></html>',
250
+ ].join('\n')