@istarry/spoon-companion 0.9.0 → 0.9.1

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 (3) hide show
  1. package/lib/client.js +180 -0
  2. package/package.json +1 -1
  3. package/plugin.js +134 -17
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@istarry/spoon-companion",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "让对话角色有自己的内心和声音:心情情绪随时间和对话自己演,回复一条一条发出来,能念出声(DeepSeek / 小米 MiMo),也能听得见——点麦克风说话,本地识别后直接发送。四块都能单独关。",
5
5
  "type": "module",
6
6
  "main": "plugin.js",
package/plugin.js CHANGED
@@ -23,7 +23,7 @@ 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'
@@ -188,6 +188,35 @@ export function apply(ctx, config = {}) {
188
188
  if (Number.isFinite(Number(settings.intimacy?.level))) {
189
189
  state.intimacy = { ...(state.intimacy ?? {}), level: Math.max(0, Math.min(2, Math.round(Number(settings.intimacy.level)))) }
190
190
  }
191
+
192
+ // 看屏幕的设置:设置页改过的值单独存一份,启动时盖在配置上。
193
+ // 这样不用去动 profile 的 cordis.patch.yml,也不用重启。
194
+ const screenFile = join(stateDir, 'screen.json')
195
+ const readScreenOverrides = () => {
196
+ try {
197
+ const raw = JSON.parse(readFileSync(screenFile, 'utf8'))
198
+ return raw && typeof raw === 'object' ? raw : {}
199
+ } catch {
200
+ return {}
201
+ }
202
+ }
203
+ const writeScreenOverrides = (patch) => {
204
+ const next = { ...readScreenOverrides(), ...patch }
205
+ try {
206
+ writeFileSync(screenFile, JSON.stringify(next, null, 2), 'utf8')
207
+ } catch (error) {
208
+ log('warn', `看屏幕设置写盘失败:${error instanceof Error ? error.message : String(error)}`)
209
+ }
210
+ return next
211
+ }
212
+ {
213
+ const saved = readScreenOverrides()
214
+ for (const key of ['enabled', 'baseMinutes', 'minMinutes', 'maxMinutes', 'nightFactor', 'dailyLimit', 'speak']) {
215
+ if (saved[key] !== undefined) settings.screen[key] = saved[key]
216
+ }
217
+ }
218
+ /** 设置页改完节奏后,让定时器立刻按新值重排 */
219
+ let rescheduleScreen = null
191
220
  const commit = () => {
192
221
  pruneState(state)
193
222
  return saveState(stateDir, state)
@@ -471,21 +500,20 @@ export function apply(ctx, config = {}) {
471
500
  res.end(JSON.stringify(payload))
472
501
  } catch { /* ignore */ }
473
502
  }
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
- }
503
+ // 路由按 (kind, path) 去重,不看 method —— GET 查状态、POST 开关,得在同一个 handler 里分支。
504
+ // (之前拆成两个 register,第二个会被判重复而注册失败,POST 一直没生效。)
485
505
  const route = {
486
- method: 'POST',
506
+ kind: 'exact',
487
507
  path: '/api/spoon-companion/call',
488
508
  handler: async (req, res) => {
509
+ if (String(req.method ?? 'GET').toUpperCase() !== 'POST') {
510
+ const query = String(req?.url ?? '')
511
+ const m = /[?&]sessionId=([^&]+)/.exec(query)
512
+ const id = m ? decodeURIComponent(m[1]) : ''
513
+ const on = callGlobal || (id ? callSessions.has(id) : false)
514
+ reply(res, 200, { ok: true, on, lastBody: lastCallBody, global: callGlobal })
515
+ return
516
+ }
489
517
  try {
490
518
  let raw = ''
491
519
  for await (const chunk of req) raw += chunk
@@ -511,16 +539,98 @@ export function apply(ctx, config = {}) {
511
539
  },
512
540
  }
513
541
  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 */ } } }
542
+ const dispose = webServer.register(route)
543
+ return () => { try { dispose?.() } catch { /* ignore */ } }
518
544
  } catch (error) {
519
545
  log('warn', `通话按钮通道注册失败:${error instanceof Error ? error.message : String(error)}`)
520
546
  return undefined
521
547
  }
522
548
  }, 'spoon-companion: call route')
523
549
 
550
+ /** 看屏幕:设置页读这个拿配置和状态,写完立刻生效,不用重启 */
551
+ ctx.effect(() => {
552
+ const webServer = ctx.webServer ?? ctx.get('webServer')
553
+ if (!webServer?.register) return undefined
554
+ const reply = (res, code, payload) => {
555
+ try {
556
+ res.statusCode = code
557
+ res.setHeader('Content-Type', 'application/json')
558
+ res.end(JSON.stringify(payload))
559
+ } catch { /* ignore */ }
560
+ }
561
+ const snapshotOf = () => {
562
+ const now = Date.now()
563
+ const sc = state.screen ?? {}
564
+ const plan = lookInterval(state, settings.screen, now)
565
+ const lastAt = Number(sc.lastAt) || 0
566
+ const nextAt = Number(sc.nextAt) || 0
567
+ return {
568
+ ok: true,
569
+ config: {
570
+ enabled: settings.screen.enabled === true,
571
+ baseMinutes: Number(settings.screen.baseMinutes) || 8,
572
+ minMinutes: Number(settings.screen.minMinutes) || 3,
573
+ maxMinutes: Number(settings.screen.maxMinutes) || 45,
574
+ nightFactor: Number(settings.screen.nightFactor) || 8,
575
+ dailyLimit: Number(settings.screen.dailyLimit) || 120,
576
+ speak: String(settings.screen.speak ?? 'never'),
577
+ },
578
+ state: {
579
+ lastAt,
580
+ title: String(sc.title ?? ''),
581
+ today: Number(sc.today) || 0,
582
+ inMinutes: nextAt > now ? Math.round((nextAt - now) / 60_000) : 0,
583
+ everyMinutes: plan.minutes,
584
+ night: plan.night,
585
+ fails: Number(sc.fails) || 0,
586
+ },
587
+ now,
588
+ }
589
+ }
590
+ // DSH 的路由按 (kind, path) 去重,不区分 method —— 所以 GET / POST 必须在同一个 handler 里分支
591
+ const route = {
592
+ kind: 'exact',
593
+ path: '/api/spoon-companion/screen',
594
+ handler: async (req, res) => {
595
+ if (String(req.method ?? 'GET').toUpperCase() !== 'POST') {
596
+ reply(res, 200, snapshotOf())
597
+ return
598
+ }
599
+ try {
600
+ let raw = ''
601
+ for await (const chunk of req) raw += chunk
602
+ const body = raw ? JSON.parse(raw) : {}
603
+ const patch = {}
604
+ if (typeof body.enabled === 'boolean') patch.enabled = body.enabled
605
+ const ranges = [
606
+ ['baseMinutes', 2, 30],
607
+ ['minMinutes', 1, 15],
608
+ ['maxMinutes', 10, 180],
609
+ ['nightFactor', 2, 20],
610
+ ['dailyLimit', 10, 500],
611
+ ]
612
+ for (const [key, lo, hi] of ranges) {
613
+ if (body[key] === undefined) continue
614
+ patch[key] = Math.max(lo, Math.min(hi, Math.round(Number(body[key]) || 0)))
615
+ }
616
+ if (body.speak !== undefined) patch.speak = String(body.speak) === 'urge' ? 'urge' : 'never'
617
+ writeScreenOverrides(patch)
618
+ Object.assign(settings.screen, patch)
619
+ state.screen = { ...(state.screen ?? {}), nextAt: 0 }
620
+ rescheduleScreen?.()
621
+ commit()
622
+ reply(res, 200, snapshotOf())
623
+ } catch (error) {
624
+ reply(res, 400, { ok: false, error: String(error?.message ?? error) })
625
+ }
626
+ },
627
+ }
628
+ const dispose = webServer.register(route)
629
+ return () => {
630
+ try { dispose?.() } catch { /* ignore */ }
631
+ }
632
+ }, 'spoon-companion: screen route')
633
+
524
634
  /**
525
635
  * 这个会话现在在不在通话里。
526
636
  * **只认客户端那把开关** —— 点了通话才算。不拿"有没有在送音频"当证据:
@@ -1132,9 +1242,16 @@ export function apply(ctx, config = {}) {
1132
1242
  loop()
1133
1243
  }, nextDelay())
1134
1244
  }
1245
+ // 设置页改完节奏,立刻按新值重排,不用等这一轮走完
1246
+ rescheduleScreen = () => {
1247
+ if (stopped) return
1248
+ if (timer) clearTimeout(timer)
1249
+ loop()
1250
+ }
1135
1251
  loop()
1136
1252
  ctx.effect(() => () => {
1137
1253
  stopped = true
1254
+ rescheduleScreen = null
1138
1255
  if (timer) clearTimeout(timer)
1139
1256
  }, 'fish-mood: screen loop')
1140
1257
  }