@istarry/spoon-companion 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -1540,6 +1540,171 @@ var MIC_CSS = `
1540
1540
  }
1541
1541
  `;
1542
1542
 
1543
+ // src/client/screen-settings.tsx
1544
+ var import_react3 = require("react");
1545
+ var import_jsx_runtime3 = require("react/jsx-runtime");
1546
+ var API = "/api/spoon-companion/screen";
1547
+ var box = {
1548
+ display: "flex",
1549
+ flexDirection: "column",
1550
+ gap: 18,
1551
+ padding: "4px 2px 24px",
1552
+ maxWidth: 620,
1553
+ fontSize: 13
1554
+ };
1555
+ var rowTitle = { fontWeight: 600, fontSize: 14 };
1556
+ var hint = { opacity: 0.6, lineHeight: 1.6, marginTop: 2 };
1557
+ var group = { display: "flex", flexDirection: "column", gap: 10 };
1558
+ var sliderRow = { display: "grid", gridTemplateColumns: "96px 1fr 92px", alignItems: "center", gap: 10 };
1559
+ var num = { textAlign: "right", fontVariantNumeric: "tabular-nums", opacity: 0.85 };
1560
+ var card = {
1561
+ border: "1px solid rgba(128,128,128,0.28)",
1562
+ borderRadius: 10,
1563
+ padding: "12px 14px",
1564
+ display: "grid",
1565
+ gap: 6
1566
+ };
1567
+ var kv = { display: "grid", gridTemplateColumns: "72px 1fr", gap: 8, fontSize: 12.5 };
1568
+ function ago(at, now) {
1569
+ if (!at) return "\u8FD8\u6CA1\u770B\u8FC7";
1570
+ const mins = Math.floor(Math.max(0, now - at) / 6e4);
1571
+ if (mins < 1) return "\u521A\u521A";
1572
+ if (mins < 60) return `${mins} \u5206\u949F\u524D`;
1573
+ return `${Math.floor(mins / 60)} \u5C0F\u65F6\u524D`;
1574
+ }
1575
+ function ScreenSettingsSection() {
1576
+ const [snap, setSnap] = (0, import_react3.useState)(null);
1577
+ const [busy, setBusy] = (0, import_react3.useState)(false);
1578
+ const [error, setError] = (0, import_react3.useState)("");
1579
+ const load = (0, import_react3.useCallback)(async () => {
1580
+ try {
1581
+ const res = await fetch(API, { headers: { accept: "application/json" } });
1582
+ const data = await res.json();
1583
+ if (data?.ok) {
1584
+ setSnap(data);
1585
+ setError("");
1586
+ } else {
1587
+ setError("\u8BFB\u4E0D\u5230\u8BBE\u7F6E");
1588
+ }
1589
+ } catch (reason) {
1590
+ setError(String(reason));
1591
+ }
1592
+ }, []);
1593
+ (0, import_react3.useEffect)(() => {
1594
+ void load();
1595
+ const timer = setInterval(() => void load(), 5e3);
1596
+ return () => clearInterval(timer);
1597
+ }, [load]);
1598
+ const save = async (patch) => {
1599
+ setBusy(true);
1600
+ try {
1601
+ const res = await fetch(API, {
1602
+ method: "POST",
1603
+ headers: { "content-type": "application/json" },
1604
+ body: JSON.stringify(patch)
1605
+ });
1606
+ const data = await res.json();
1607
+ if (data?.ok) {
1608
+ setSnap(data);
1609
+ setError("");
1610
+ } else {
1611
+ setError("\u4FDD\u5B58\u5931\u8D25");
1612
+ }
1613
+ } catch (reason) {
1614
+ setError(String(reason));
1615
+ } finally {
1616
+ setBusy(false);
1617
+ }
1618
+ };
1619
+ const cfg = snap?.config;
1620
+ const st = snap?.state;
1621
+ const slider = (label, value, min, max, suffix, onCommit) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("label", { style: sliderRow, children: [
1622
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { opacity: 0.8 }, children: label }),
1623
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1624
+ "input",
1625
+ {
1626
+ type: "range",
1627
+ min,
1628
+ max,
1629
+ value,
1630
+ disabled: busy,
1631
+ onChange: (event) => onCommit(Number(event.target.value)),
1632
+ style: { width: "100%" }
1633
+ }
1634
+ ),
1635
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { style: num, children: [
1636
+ value,
1637
+ " ",
1638
+ suffix
1639
+ ] })
1640
+ ] });
1641
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: box, children: [
1642
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: group, children: [
1643
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: rowTitle, children: "\u770B\u5C4F\u5E55" }),
1644
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: hint, children: "\u5979\u5076\u5C14\u8D70\u8FC7\u53BB\u770B\u4E00\u773C\uFF0C\u4E0D\u662F\u76D1\u89C6\u3002\u770B\u4E00\u773C\u7684\u9891\u7387\u7531\u60C5\u7EEA\u51B3\u5B9A\uFF1A\u5B64\u5355\u7684\u65F6\u5019\u60F3\u770B\u4F60\uFF0C\u70E6\u7684\u65F6\u5019\u4E0D\u60F3\u770B\uFF0C\u56F0\u7684\u65F6\u5019\u51E0\u4E4E\u4E0D\u770B\u3002" }),
1645
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("label", { style: { display: "flex", alignItems: "center", gap: 8 }, children: [
1646
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1647
+ "input",
1648
+ {
1649
+ type: "checkbox",
1650
+ checked: cfg?.enabled === true,
1651
+ disabled: busy || !cfg,
1652
+ onChange: (event) => void save({ enabled: event.target.checked })
1653
+ }
1654
+ ),
1655
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: cfg?.enabled ? "\u5F00\u7740 \u2014\u2014 \u4F1A\u81EA\u5DF1\u770B" : "\u5173\u7740 \u2014\u2014 \u4E00\u6B21\u90FD\u4E0D\u622A" })
1656
+ ] })
1657
+ ] }),
1658
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: group, children: [
1659
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { ...rowTitle, opacity: cfg?.enabled ? 1 : 0.45 }, children: "\u8282\u594F" }),
1660
+ cfg ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
1661
+ slider("\u6574\u4F53\u5FEB\u6162", cfg.baseMinutes, 2, 30, "\u5206\u949F", (next) => void save({ baseMinutes: next })),
1662
+ slider("\u6700\u77ED", cfg.minMinutes, 1, 15, "\u5206\u949F", (next) => void save({ minMinutes: next })),
1663
+ slider("\u6700\u957F", cfg.maxMinutes, 10, 180, "\u5206\u949F", (next) => void save({ maxMinutes: next })),
1664
+ slider("\u6DF1\u591C", cfg.nightFactor, 2, 20, "\xD7", (next) => void save({ nightFactor: next })),
1665
+ slider("\u6BCF\u5929\u6700\u591A", cfg.dailyLimit, 10, 500, "\u6B21", (next) => void save({ dailyLimit: next }))
1666
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: hint, children: "\u8BFB\u8BBE\u7F6E\u4E2D\u2026" }),
1667
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: hint, children: "\u6DF1\u591C\u662F\u4F4E\u9891\uFF0C\u4E0D\u662F\u4E0D\u770B\u3002\u500D\u6570\u8D8A\u5927\u8D8A\u5C11\u770B\uFF088\xD7 \u5927\u7EA6\u662F\u6BCF\u5C0F\u65F6\u4E00\u6B21\uFF09\u3002" })
1668
+ ] }),
1669
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: group, children: [
1670
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: rowTitle, children: "\u73B0\u5728" }),
1671
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: card, children: [
1672
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: kv, children: [
1673
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { opacity: 0.6 }, children: "\u521A\u624D\u770B\u89C1" }),
1674
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: st?.title ? `${st.title}` : "\u8FD8\u6CA1\u770B\u8FC7" })
1675
+ ] }),
1676
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: kv, children: [
1677
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { opacity: 0.6 }, children: "\u770B\u7684\u65F6\u95F4" }),
1678
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: snap ? ago(st?.lastAt ?? 0, snap.now) : "\u2014" })
1679
+ ] }),
1680
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: kv, children: [
1681
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { opacity: 0.6 }, children: "\u4ECA\u5929" }),
1682
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { children: [
1683
+ st?.today ?? 0,
1684
+ " \u6B21"
1685
+ ] })
1686
+ ] }),
1687
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: kv, children: [
1688
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { opacity: 0.6 }, children: "\u4E0B\u4E00\u6B21" }),
1689
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { children: [
1690
+ st?.inMinutes ? `\u7EA6 ${st.inMinutes} \u5206\u949F\u540E` : "\u968F\u65F6",
1691
+ st?.everyMinutes ? `\uFF08\u5F53\u524D\u8282\u594F ${st.everyMinutes} \u5206\u949F${st.night ? "\uFF0C\u6DF1\u591C" : ""}\uFF09` : ""
1692
+ ] })
1693
+ ] }),
1694
+ st && st.fails > 0 ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: kv, children: [
1695
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { opacity: 0.6 }, children: "\u72B6\u6001" }),
1696
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { style: { color: "#d08a3a" }, children: [
1697
+ "\u8FDE\u7EED\u5931\u8D25 ",
1698
+ st.fails,
1699
+ " \u6B21\uFF0C\u6B63\u5728\u9000\u907F"
1700
+ ] })
1701
+ ] }) : null
1702
+ ] })
1703
+ ] }),
1704
+ error ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { color: "#d0563a", fontSize: 12 }, children: error }) : null
1705
+ ] });
1706
+ }
1707
+
1543
1708
  // src/client/index.ts
1544
1709
  var inject = ["slots", "sessions"];
1545
1710
  function apply2(ctx) {
@@ -1586,6 +1751,21 @@ function apply2(ctx) {
1586
1751
  );
1587
1752
  } catch {
1588
1753
  }
1754
+ try {
1755
+ ctx.slots.inject(
1756
+ "settings.section",
1757
+ () => ctx.slots.register(
1758
+ {
1759
+ name: "settings.section",
1760
+ id: "spoon-companion-screen",
1761
+ order: 60,
1762
+ label: "Spoon \u966A\u4F34"
1763
+ },
1764
+ ScreenSettingsSection
1765
+ )
1766
+ );
1767
+ } catch {
1768
+ }
1589
1769
  apply(ctx);
1590
1770
  }
1591
1771
  return module.exports; } });
package/lib/prompt.js CHANGED
@@ -168,7 +168,10 @@ export function renderStateBlock(view) {
168
168
  }
169
169
  const look = lookLine(view, view.now)
170
170
  if (look) lines.push(look)
171
- if (view.urge) lines.push(`想做的事:${view.urge.kind === 'share' ? '想把这件事说出去' : '想被安慰两句'}`)
171
+ if (view.urge) {
172
+ const note = view.urge.note ? `(${view.urge.note})` : ''
173
+ lines.push(`想做的事:${view.urge.kind === 'share' ? `想把刚才看到的那个说出去${note}` : '想被安慰两句'}`)
174
+ }
172
175
  // 感受和表现是两回事:她可以心里翻江倒海,表面照旧嘴硬
173
176
  if (emo.hidden) {
174
177
  const how = emo.def.mask && emo.def.mask !== '—' ? emo.def.mask : '照常说话,不主动提;问到了就轻描淡写'
@@ -222,7 +225,10 @@ export function renderMoodReport(view) {
222
225
  const times = view.scene.events > 1 ? ` · 第 ${view.scene.events} 次` : ''
223
226
  lines.push(`场景:${view.scene.word}${times} · 尺度 ${view.intimacyLevel ?? 1}(0 日常 / 1 暧昧 / 2 露骨)`)
224
227
  }
225
- if (view.urge) lines.push(`想做的事:${view.urge.kind === 'share' ? '想把这件事说出去' : '想被安慰两句'}`)
228
+ if (view.urge) {
229
+ const note = view.urge.note ? `(${view.urge.note})` : ''
230
+ lines.push(`想做的事:${view.urge.kind === 'share' ? `想把刚才看到的那个说出去${note}` : '想被安慰两句'}`)
231
+ }
226
232
  const relation = relationLine(view)
227
233
  if (relation) lines.push(`关系:${relation}`)
228
234
  if (view.today.length) lines.push(`今天:${view.today.join(';')}`)
package/lib/state.js CHANGED
@@ -92,7 +92,11 @@ export function emptyState() {
92
92
  // 尺度:0 日常 / 1 暧昧 / 2 露骨
93
93
  intimacy: { level: 1 },
94
94
  // 看屏幕:记「刚才瞧见了什么」,不记图。lastAt 超过 30 分钟就不往提示词里写。
95
- screen: { lastAt: 0, saw: '', scene: '', changed: false, worth: 0, nextAt: 0, today: 0, day: '', path: '' },
95
+ screen: {
96
+ lastAt: 0, saw: '', scene: '', changed: false, worth: 0, nextAt: 0, today: 0, day: '', path: '', title: '',
97
+ // 「值得说一句」的记账:看过多少、说过几次、上次是什么时候
98
+ talkAt: 0, talkToday: 0, talkDay: '', hook: '',
99
+ },
96
100
  affect: [],
97
101
  habits: {},
98
102
  memories: [],
@@ -974,6 +978,28 @@ export function lookInterval(state, cfg = {}, now = Date.now()) {
974
978
  return { minutes: Math.round(minutes * 10) / 10, factor: Math.round(factor * 100) / 100, night }
975
979
  }
976
980
 
981
+ /** 窗口标题里有没有「值得说一句」的钩子。没有就返回空串。 */
982
+ const SCREEN_HOOKS = [
983
+ [/报错|错误|异常|Error|Failed|failed|Exception|Traceback|崩溃/, '屏幕上红了一片'],
984
+ [/直播|Bilibili|哔哩哔哩|YouTube|虎牙|斗鱼/, '在看直播'],
985
+ [/Steam|游戏|原神|Minecraft|WeGame|Switch/, '在打游戏'],
986
+ [/微信|QQ|Telegram|Discord|Slack|飞书|钉钉/, '在跟人说话'],
987
+ [/照片|相册|截图|Photos/, '在看照片'],
988
+ ]
989
+
990
+ /**
991
+ * 一眼看过去,这屏值不值得说一句。
992
+ * 只看窗口标题,不额外调模型 —— 宁可漏,不乱说。
993
+ */
994
+ export function screenHook(title) {
995
+ const text = String(title ?? '')
996
+ if (!text) return ''
997
+ for (const [pattern, tag] of SCREEN_HOOKS) {
998
+ if (pattern.test(text)) return tag
999
+ }
1000
+ return ''
1001
+ }
1002
+
977
1003
  /** 性格用几个词说出来(不是把分数报出来) */
978
1004
  export function traitWords(traits = {}) {
979
1005
  const words = []
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@istarry/spoon-companion",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "description": "让对话角色有自己的内心和声音:心情情绪随时间和对话自己演,回复一条一条发出来,能念出声(DeepSeek / 小米 MiMo),也能听得见——点麦克风说话,本地识别后直接发送。四块都能单独关。",
5
5
  "type": "module",
6
6
  "main": "plugin.js",
package/plugin.js CHANGED
@@ -23,14 +23,14 @@ import * as voicePlugin from './lib/voice.js'
23
23
  import { capture, screenSupported } from './lib/screen.js'
24
24
  import { applyAsrRoutes } from './lib/asr-route.js'
25
25
  import { isCallActive, markCallSession, setCallGlobal } from './lib/asr.js'
26
- import { appendFileSync, readFileSync } from 'node:fs'
26
+ import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
27
27
  import { homedir } from 'node:os'
28
28
  import { join } from 'node:path'
29
29
  import { EMOTION_KEYS, EMOTION_MENU, TRAITS, resolveEmotion, tierOf } from './lib/catalog.js'
30
30
  import { appraise } from './lib/appraise.js'
31
31
  import {
32
32
  applyImpulse, catharsis, circadian, decay, dueRumination, loadState, lookInterval, maybeLifeEvent, maybeMoodRepair,
33
- nightlyReview, pruneState, remember, saveState, snapshot,
33
+ nightlyReview, pruneState, remember, saveState, screenHook, snapshot,
34
34
  } from './lib/state.js'
35
35
  import { channelOfSession, lastSpeaker, readUserMessages, reactToMessages, sessionEventsOf } from './lib/react.js'
36
36
  import { RULES_TEXT, renderDiary, renderMoodReport, renderMoodSection } from './lib/prompt.js'
@@ -104,6 +104,10 @@ const DEFAULTS = {
104
104
  dailyLimit: 120,
105
105
  maxEdge: 1280,
106
106
  exclude: [],
107
+ // 「值得说一句」的闸门:宁可一天不说,也不说废话
108
+ speak: 'never',
109
+ speakPerDay: 2,
110
+ speakCooldownMin: 120,
107
111
  },
108
112
  }
109
113
 
@@ -188,6 +192,35 @@ export function apply(ctx, config = {}) {
188
192
  if (Number.isFinite(Number(settings.intimacy?.level))) {
189
193
  state.intimacy = { ...(state.intimacy ?? {}), level: Math.max(0, Math.min(2, Math.round(Number(settings.intimacy.level)))) }
190
194
  }
195
+
196
+ // 看屏幕的设置:设置页改过的值单独存一份,启动时盖在配置上。
197
+ // 这样不用去动 profile 的 cordis.patch.yml,也不用重启。
198
+ const screenFile = join(stateDir, 'screen.json')
199
+ const readScreenOverrides = () => {
200
+ try {
201
+ const raw = JSON.parse(readFileSync(screenFile, 'utf8'))
202
+ return raw && typeof raw === 'object' ? raw : {}
203
+ } catch {
204
+ return {}
205
+ }
206
+ }
207
+ const writeScreenOverrides = (patch) => {
208
+ const next = { ...readScreenOverrides(), ...patch }
209
+ try {
210
+ writeFileSync(screenFile, JSON.stringify(next, null, 2), 'utf8')
211
+ } catch (error) {
212
+ log('warn', `看屏幕设置写盘失败:${error instanceof Error ? error.message : String(error)}`)
213
+ }
214
+ return next
215
+ }
216
+ {
217
+ const saved = readScreenOverrides()
218
+ for (const key of ['enabled', 'baseMinutes', 'minMinutes', 'maxMinutes', 'nightFactor', 'dailyLimit', 'speak']) {
219
+ if (saved[key] !== undefined) settings.screen[key] = saved[key]
220
+ }
221
+ }
222
+ /** 设置页改完节奏后,让定时器立刻按新值重排 */
223
+ let rescheduleScreen = null
191
224
  const commit = () => {
192
225
  pruneState(state)
193
226
  return saveState(stateDir, state)
@@ -471,21 +504,20 @@ export function apply(ctx, config = {}) {
471
504
  res.end(JSON.stringify(payload))
472
505
  } catch { /* ignore */ }
473
506
  }
474
- // 刷新页面后按钮要知道当前状态
475
- const statusRoute = {
476
- method: 'GET',
477
- path: '/api/spoon-companion/call',
478
- handler: async (_req, res) => {
479
- const query = String(_req?.url ?? '')
480
- const m = /[?&]sessionId=([^&]+)/.exec(query)
481
- const id = m ? decodeURIComponent(m[1]) : ''
482
- const on = callGlobal || (id ? callSessions.has(id) : false)
483
- reply(res, 200, { ok: true, on, lastBody: lastCallBody, global: callGlobal }) },
484
- }
507
+ // 路由按 (kind, path) 去重,不看 method —— GET 查状态、POST 开关,得在同一个 handler 里分支。
508
+ // (之前拆成两个 register,第二个会被判重复而注册失败,POST 一直没生效。)
485
509
  const route = {
486
- method: 'POST',
510
+ kind: 'exact',
487
511
  path: '/api/spoon-companion/call',
488
512
  handler: async (req, res) => {
513
+ if (String(req.method ?? 'GET').toUpperCase() !== 'POST') {
514
+ const query = String(req?.url ?? '')
515
+ const m = /[?&]sessionId=([^&]+)/.exec(query)
516
+ const id = m ? decodeURIComponent(m[1]) : ''
517
+ const on = callGlobal || (id ? callSessions.has(id) : false)
518
+ reply(res, 200, { ok: true, on, lastBody: lastCallBody, global: callGlobal })
519
+ return
520
+ }
489
521
  try {
490
522
  let raw = ''
491
523
  for await (const chunk of req) raw += chunk
@@ -511,16 +543,98 @@ export function apply(ctx, config = {}) {
511
543
  },
512
544
  }
513
545
  try {
514
- const disposers = []
515
- disposers.push(webServer.register(statusRoute))
516
- disposers.push(webServer.register(route))
517
- return () => { for (const d of disposers) { try { d?.() } catch { /* ignore */ } } }
546
+ const dispose = webServer.register(route)
547
+ return () => { try { dispose?.() } catch { /* ignore */ } }
518
548
  } catch (error) {
519
549
  log('warn', `通话按钮通道注册失败:${error instanceof Error ? error.message : String(error)}`)
520
550
  return undefined
521
551
  }
522
552
  }, 'spoon-companion: call route')
523
553
 
554
+ /** 看屏幕:设置页读这个拿配置和状态,写完立刻生效,不用重启 */
555
+ ctx.effect(() => {
556
+ const webServer = ctx.webServer ?? ctx.get('webServer')
557
+ if (!webServer?.register) return undefined
558
+ const reply = (res, code, payload) => {
559
+ try {
560
+ res.statusCode = code
561
+ res.setHeader('Content-Type', 'application/json')
562
+ res.end(JSON.stringify(payload))
563
+ } catch { /* ignore */ }
564
+ }
565
+ const snapshotOf = () => {
566
+ const now = Date.now()
567
+ const sc = state.screen ?? {}
568
+ const plan = lookInterval(state, settings.screen, now)
569
+ const lastAt = Number(sc.lastAt) || 0
570
+ const nextAt = Number(sc.nextAt) || 0
571
+ return {
572
+ ok: true,
573
+ config: {
574
+ enabled: settings.screen.enabled === true,
575
+ baseMinutes: Number(settings.screen.baseMinutes) || 8,
576
+ minMinutes: Number(settings.screen.minMinutes) || 3,
577
+ maxMinutes: Number(settings.screen.maxMinutes) || 45,
578
+ nightFactor: Number(settings.screen.nightFactor) || 8,
579
+ dailyLimit: Number(settings.screen.dailyLimit) || 120,
580
+ speak: String(settings.screen.speak ?? 'never'),
581
+ },
582
+ state: {
583
+ lastAt,
584
+ title: String(sc.title ?? ''),
585
+ today: Number(sc.today) || 0,
586
+ inMinutes: nextAt > now ? Math.round((nextAt - now) / 60_000) : 0,
587
+ everyMinutes: plan.minutes,
588
+ night: plan.night,
589
+ fails: Number(sc.fails) || 0,
590
+ },
591
+ now,
592
+ }
593
+ }
594
+ // DSH 的路由按 (kind, path) 去重,不区分 method —— 所以 GET / POST 必须在同一个 handler 里分支
595
+ const route = {
596
+ kind: 'exact',
597
+ path: '/api/spoon-companion/screen',
598
+ handler: async (req, res) => {
599
+ if (String(req.method ?? 'GET').toUpperCase() !== 'POST') {
600
+ reply(res, 200, snapshotOf())
601
+ return
602
+ }
603
+ try {
604
+ let raw = ''
605
+ for await (const chunk of req) raw += chunk
606
+ const body = raw ? JSON.parse(raw) : {}
607
+ const patch = {}
608
+ if (typeof body.enabled === 'boolean') patch.enabled = body.enabled
609
+ const ranges = [
610
+ ['baseMinutes', 2, 30],
611
+ ['minMinutes', 1, 15],
612
+ ['maxMinutes', 10, 180],
613
+ ['nightFactor', 2, 20],
614
+ ['dailyLimit', 10, 500],
615
+ ]
616
+ for (const [key, lo, hi] of ranges) {
617
+ if (body[key] === undefined) continue
618
+ patch[key] = Math.max(lo, Math.min(hi, Math.round(Number(body[key]) || 0)))
619
+ }
620
+ if (body.speak !== undefined) patch.speak = String(body.speak) === 'urge' ? 'urge' : 'never'
621
+ writeScreenOverrides(patch)
622
+ Object.assign(settings.screen, patch)
623
+ state.screen = { ...(state.screen ?? {}), nextAt: 0 }
624
+ rescheduleScreen?.()
625
+ commit()
626
+ reply(res, 200, snapshotOf())
627
+ } catch (error) {
628
+ reply(res, 400, { ok: false, error: String(error?.message ?? error) })
629
+ }
630
+ },
631
+ }
632
+ const dispose = webServer.register(route)
633
+ return () => {
634
+ try { dispose?.() } catch { /* ignore */ }
635
+ }
636
+ }, 'spoon-companion: screen route')
637
+
524
638
  /**
525
639
  * 这个会话现在在不在通话里。
526
640
  * **只认客户端那把开关** —— 点了通话才算。不拿"有没有在送音频"当证据:
@@ -1113,6 +1227,24 @@ export function apply(ctx, config = {}) {
1113
1227
  sc.today = (Number(sc.today) || 0) + 1
1114
1228
  sc.fails = 0
1115
1229
  sc.nextAt = shot.at + lookInterval(state, settings.screen, shot.at).minutes * 60_000
1230
+ // 值不值得说一句:只看标题,不额外调模型。宁可漏,不乱说。
1231
+ const hook = screenHook(shot.title)
1232
+ if (hook && sc.changed && settings.screen.speak !== 'never') {
1233
+ const today = new Date(now).toDateString()
1234
+ if (sc.talkDay !== today) {
1235
+ sc.talkDay = today
1236
+ sc.talkToday = 0
1237
+ }
1238
+ const cooldownMs = Math.max(10, Number(settings.screen.speakCooldownMin) || 120) * 60_000
1239
+ const perDay = Math.max(1, Number(settings.screen.speakPerDay) || 2)
1240
+ if (now - (Number(sc.talkAt) || 0) > cooldownMs && (Number(sc.talkToday) || 0) < perDay) {
1241
+ sc.talkAt = now
1242
+ sc.talkToday = (Number(sc.talkToday) || 0) + 1
1243
+ sc.hook = hook
1244
+ state.urges = { kind: 'share', until: now + 15 * 60_000, note: hook }
1245
+ audit({ kind: 'screen-worthy', hook, title: String(shot.title ?? '').slice(0, 60) })
1246
+ }
1247
+ }
1116
1248
  audit({ kind: 'screen-look', auto: true, title: String(shot.title ?? '').slice(0, 60) })
1117
1249
  commit()
1118
1250
  } catch (error) {
@@ -1132,9 +1264,16 @@ export function apply(ctx, config = {}) {
1132
1264
  loop()
1133
1265
  }, nextDelay())
1134
1266
  }
1267
+ // 设置页改完节奏,立刻按新值重排,不用等这一轮走完
1268
+ rescheduleScreen = () => {
1269
+ if (stopped) return
1270
+ if (timer) clearTimeout(timer)
1271
+ loop()
1272
+ }
1135
1273
  loop()
1136
1274
  ctx.effect(() => () => {
1137
1275
  stopped = true
1276
+ rescheduleScreen = null
1138
1277
  if (timer) clearTimeout(timer)
1139
1278
  }, 'fish-mood: screen loop')
1140
1279
  }