@istarry/spoon-companion 0.8.1 → 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.
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
@@ -109,6 +109,38 @@ function relationLine(view) {
109
109
  return rows.join(' / ')
110
110
  }
111
111
 
112
+ /**
113
+ * 窗口标题太长、后缀一堆,收成一句人话。
114
+ * 不是"识别到的进程名",是她凑过去能看见的那行字。
115
+ */
116
+ export function shortTitle(title) {
117
+ let text = String(title ?? '').trim()
118
+ if (!text) return ''
119
+ text = text
120
+ .replace(/\s*[—–-]\s*DeepSeek Harness\s*$/i, '')
121
+ .replace(/\s*[—–-]\s*(Google Chrome|Microsoft.*Edge|Mozilla Firefox)\s*$/i, '')
122
+ .replace(/\s+/g, ' ')
123
+ .trim()
124
+ if (text.length > 34) text = `${text.slice(0, 34)}…`
125
+ return text
126
+ }
127
+
128
+ /**
129
+ * 「刚才走过去看了一眼」那一行。
130
+ * 没看过、或超过 30 分钟,就整行不出现 —— 不写"没看",也不提眼睛。
131
+ */
132
+ export function lookLine(view, now = Date.now()) {
133
+ const sc = view?.screen
134
+ const at = Number(sc?.lastAt) || 0
135
+ if (!at) return ''
136
+ const age = now - at
137
+ if (age > 30 * 60_000) return ''
138
+ const mins = Math.floor(age / 60_000)
139
+ const when = mins < 1 ? '刚刚' : `${mins} 分钟前`
140
+ const what = shortTitle(sc.title)
141
+ return what ? `刚才:走过去看了一眼 —— ${what}(${when})` : `刚才:走过去看了一眼(${when})`
142
+ }
143
+
112
144
  /**
113
145
  * 实时状态块。固定模板、固定字段顺序:
114
146
  * 第一行永远是标题,最后一行永远是回复参数 —— 中间按需增减,顺序不变。
@@ -134,6 +166,8 @@ export function renderStateBlock(view) {
134
166
  const times = view.scene.events > 1 ? ` · 第 ${view.scene.events} 次` : ''
135
167
  lines.push(`场景:${view.scene.word}${times}`)
136
168
  }
169
+ const look = lookLine(view, view.now)
170
+ if (look) lines.push(look)
137
171
  if (view.urge) lines.push(`想做的事:${view.urge.kind === 'share' ? '想把这件事说出去' : '想被安慰两句'}`)
138
172
  // 感受和表现是两回事:她可以心里翻江倒海,表面照旧嘴硬
139
173
  if (emo.hidden) {
package/lib/screen.js ADDED
@@ -0,0 +1,149 @@
1
+ // 看屏幕:截一张全屏图,存成 JPEG,把路径交回去。
2
+ //
3
+ // 设计上的几条硬约束:
4
+ // · 不落成"随手一堆文件" —— 只保留最近 N 张,旧的自己删。
5
+ // · 不常驻进程、不装依赖 —— 每次 spawn 一次 powershell,截完就退。
6
+ // · 不替调用方判断该不该看 —— 那是情绪那一层的事,这里只负责"能截到"。
7
+ //
8
+ // Windows 上用 System.Drawing + CopyFromScreen,不需要任何授权;
9
+ // macOS / Linux 直接返回 unsupported,让上层安静跳过。
10
+
11
+ import { spawn } from 'node:child_process'
12
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
13
+ import { homedir } from 'node:os'
14
+ import { join } from 'node:path'
15
+
16
+ /** 落盘目录:和情绪状态放一起,方便一起清理 */
17
+ export const SHOT_DIR = join(homedir(), '.dsh', 'fish-mood', 'shots')
18
+
19
+ /** 保留最近几张 */
20
+ const KEEP = 12
21
+
22
+ /** 截图脚本:纯 ASCII,避免编码问题。窗口标题单独写文件(UTF-8),不走 stdout。 */
23
+ const PS1 = `param([string]$Out, [int]$MaxEdge, [string]$TitleOut)
24
+ $ErrorActionPreference = 'Stop'
25
+ Add-Type -AssemblyName System.Drawing
26
+ Add-Type -AssemblyName System.Windows.Forms
27
+ Add-Type @"
28
+ using System;
29
+ using System.Runtime.InteropServices;
30
+ using System.Text;
31
+ public class WinInfo {
32
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
33
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder s, int n);
34
+ }
35
+ "@
36
+ $title = ''
37
+ try {
38
+ $h = [WinInfo]::GetForegroundWindow()
39
+ $sb = New-Object System.Text.StringBuilder 512
40
+ [void][WinInfo]::GetWindowText($h, $sb, 512)
41
+ $title = $sb.ToString()
42
+ } catch { }
43
+ if ($TitleOut) { [System.IO.File]::WriteAllText($TitleOut, $title, (New-Object System.Text.UTF8Encoding $false)) }
44
+ $b = [System.Windows.Forms.SystemInformation]::VirtualScreen
45
+ if ($b.Width -le 0 -or $b.Height -le 0) { throw 'no-screen' }
46
+ $bmp = New-Object System.Drawing.Bitmap($b.Width, $b.Height)
47
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
48
+ $g.CopyFromScreen($b.Left, $b.Top, 0, 0, $bmp.Size)
49
+ $g.Dispose()
50
+ $ratio = [Math]::Min(1.0, [double]$MaxEdge / [Math]::Max($bmp.Width, $bmp.Height))
51
+ if ($ratio -lt 1.0) {
52
+ $w = [int]($bmp.Width * $ratio)
53
+ $h2 = [int]($bmp.Height * $ratio)
54
+ $small = New-Object System.Drawing.Bitmap($w, $h2)
55
+ $sg = [System.Drawing.Graphics]::FromImage($small)
56
+ $sg.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
57
+ $sg.DrawImage($bmp, 0, 0, $w, $h2)
58
+ $sg.Dispose()
59
+ $bmp.Dispose()
60
+ $bmp = $small
61
+ }
62
+ $bmp.Save($Out, [System.Drawing.Imaging.ImageFormat]::Jpeg)
63
+ Write-Output ("{0}x{1}" -f $bmp.Width, $bmp.Height)
64
+ $bmp.Dispose()
65
+ `
66
+
67
+ /** Windows 自带的 powershell.exe。DSH 进程的 PATH 可能是旧的,所以写全路径。 */
68
+ const PS_EXE = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
69
+
70
+ /** 这个平台能不能截 */
71
+ export function screenSupported() {
72
+ return process.platform === 'win32'
73
+ }
74
+
75
+ function run(cmd, args, timeoutMs) {
76
+ return new Promise((resolve, reject) => {
77
+ const child = spawn(cmd, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
78
+ let out = ''
79
+ let err = ''
80
+ const timer = setTimeout(() => {
81
+ try { child.kill() } catch { /* ignore */ }
82
+ reject(new Error('timeout'))
83
+ }, timeoutMs)
84
+ child.stdout.on('data', (d) => { out += d.toString() })
85
+ child.stderr.on('data', (d) => { err += d.toString() })
86
+ child.on('error', (e) => { clearTimeout(timer); reject(e) })
87
+ child.on('close', (code) => {
88
+ clearTimeout(timer)
89
+ if (code === 0) resolve(out.trim())
90
+ else reject(new Error((err || out || `exit ${code}`).trim().slice(0, 300)))
91
+ })
92
+ })
93
+ }
94
+
95
+ /** 只留最近 KEEP 张 */
96
+ export function pruneShots() {
97
+ try {
98
+ if (!existsSync(SHOT_DIR)) return 0
99
+ const rows = readdirSync(SHOT_DIR)
100
+ .filter((name) => name.endsWith('.jpg'))
101
+ .map((name) => ({ name, at: statSync(join(SHOT_DIR, name)).mtimeMs }))
102
+ .sort((a, b) => b.at - a.at)
103
+ let n = 0
104
+ for (const row of rows.slice(KEEP)) {
105
+ try { unlinkSync(join(SHOT_DIR, row.name)); n++ } catch { /* ignore */ }
106
+ }
107
+ return n
108
+ } catch {
109
+ return 0
110
+ }
111
+ }
112
+
113
+ /**
114
+ * 截一张。
115
+ * @param {{ maxEdge?: number, timeoutMs?: number }} [opts]
116
+ * @returns {Promise<{ path: string, width: number, height: number, bytes: number, at: number }>}
117
+ */
118
+ export async function capture(opts = {}) {
119
+ if (!screenSupported()) throw new Error('unsupported-platform')
120
+ const maxEdge = Math.max(320, Math.min(2560, Number(opts.maxEdge) || 1280))
121
+ const timeoutMs = Math.max(2000, Math.min(20000, Number(opts.timeoutMs) || 9000))
122
+ mkdirSync(SHOT_DIR, { recursive: true })
123
+ const stamp = new Date()
124
+ const name = `shot-${stamp.getFullYear()}${String(stamp.getMonth() + 1).padStart(2, '0')}${String(stamp.getDate()).padStart(2, '0')}-${String(stamp.getHours()).padStart(2, '0')}${String(stamp.getMinutes()).padStart(2, '0')}${String(stamp.getSeconds()).padStart(2, '0')}-${Math.random().toString(36).slice(2, 6)}.jpg`
125
+ const out = join(SHOT_DIR, name)
126
+ const ps1 = join(SHOT_DIR, '_shot.ps1')
127
+ const titlePath = join(SHOT_DIR, '_title.txt')
128
+ writeFileSync(ps1, PS1, 'utf8')
129
+ try {
130
+ const size = await run(PS_EXE, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', ps1, '-Out', out, '-MaxEdge', String(maxEdge), '-TitleOut', titlePath], timeoutMs)
131
+ const [w, h] = String(size).split('x').map((n) => Number(n) || 0)
132
+ const bytes = statSync(out).size
133
+ let title = ''
134
+ try { title = readFileSync(titlePath, 'utf8').trim() } catch { title = '' }
135
+ pruneShots()
136
+ return { path: out, width: w, height: h, bytes, at: Date.now(), title }
137
+ } catch (error) {
138
+ try { if (existsSync(out)) unlinkSync(out) } catch { /* ignore */ }
139
+ throw error
140
+ } finally {
141
+ try { rmSync(ps1, { force: true }) } catch { /* ignore */ }
142
+ try { rmSync(titlePath, { force: true }) } catch { /* ignore */ }
143
+ }
144
+ }
145
+
146
+ /** 把截图读成 base64(给需要内联图片的调用方用) */
147
+ export function readShotAsBase64(path) {
148
+ return readFileSync(path).toString('base64')
149
+ }
package/lib/state.js CHANGED
@@ -91,6 +91,8 @@ export function emptyState() {
91
91
  scene: { phase: 'daily', startedAt: 0, lastEventAt: 0, intensity: 0, events: 0, afterglowUntil: 0 },
92
92
  // 尺度:0 日常 / 1 暧昧 / 2 露骨
93
93
  intimacy: { level: 1 },
94
+ // 看屏幕:记「刚才瞧见了什么」,不记图。lastAt 超过 30 分钟就不往提示词里写。
95
+ screen: { lastAt: 0, saw: '', scene: '', changed: false, worth: 0, nextAt: 0, today: 0, day: '', path: '' },
94
96
  affect: [],
95
97
  habits: {},
96
98
  memories: [],
@@ -119,6 +121,7 @@ export function migrate(raw) {
119
121
  body: { ...base.body, ...(raw.body ?? {}) },
120
122
  scene: { ...base.scene, ...(raw.scene ?? {}) },
121
123
  intimacy: { ...base.intimacy, ...(raw.intimacy ?? {}) },
124
+ screen: { ...base.screen, ...(raw.screen ?? {}) },
122
125
  }
123
126
  }
124
127
  const state = emptyState()
@@ -929,6 +932,48 @@ export function moodLabel(state, now = Date.now()) {
929
932
  return { label, tint: round(tint), energy: Math.round(energy), reason, count: rows.length }
930
933
  }
931
934
 
935
+ // ── 看屏幕的节奏 ────────────────────────────────────────────────────────────
936
+
937
+ /** 不同情绪对「想不想看一眼」的影响:小于 1 是想看,大于 1 是缩回去 */
938
+ const LOOK_FACTOR = {
939
+ lonely: 0.4, aroused: 0.5, needy: 0.5, bored: 0.6, curious: 0.7,
940
+ happy: 0.8, excited: 0.8, playful: 0.8, amused: 0.8, surprised: 0.8,
941
+ tender: 1, gentle: 1, content: 1, calm: 1, relieved: 1, grateful: 1, moved: 1, proud: 1,
942
+ sad: 1.5, down: 1.5, disappointed: 1.5, wronged: 1.5, wistful: 1.5,
943
+ shamed: 2, shy: 2, awkward: 2,
944
+ annoyed: 2.5, angry: 2.5, indignant: 2.5, disdain: 2.5, jealous: 2,
945
+ tired: 3, sleepy: 3, overstim: 2, sated: 2,
946
+ }
947
+
948
+ /**
949
+ * 下次「走过去看一眼」隔多久。
950
+ * 基础间隔是配置里的,情绪和驱动在这个基础上乘系数,最后夹在 min / max 之间。
951
+ * 深夜不是不看,是乘一个倍率变成低频。
952
+ */
953
+ export function lookInterval(state, cfg = {}, now = Date.now()) {
954
+ const base = Math.max(1, Number(cfg.baseMinutes) || 8)
955
+ const min = Math.max(1, Number(cfg.minMinutes) || 3)
956
+ const max = Math.max(min, Number(cfg.maxMinutes) || 45)
957
+ let factor = LOOK_FACTOR[String(state.emotion?.key ?? 'calm')] ?? 1
958
+
959
+ const drives = state.drives ?? {}
960
+ if (Number(drives.cling ?? 0) >= 0.7) factor *= 0.6
961
+ if (Number(drives.desire ?? 0) >= 0.6) factor *= 0.7
962
+ if (Number(drives.fatigue ?? 0) >= 0.7) factor *= 2
963
+ if (state.urges?.kind === 'comfort' && Number(state.urges.until) > now) factor *= 0.5
964
+
965
+ const [from, to] = Array.isArray(cfg.nightHours) ? cfg.nightHours : [0, 7]
966
+ const hour = new Date(now).getHours()
967
+ const night = from < to ? hour >= from && hour < to : hour >= from || hour < to
968
+ if (night) factor *= Math.max(1, Number(cfg.nightFactor) || 8)
969
+
970
+ // 画面没变就别老去看 —— 拉长
971
+ if (state.screen?.changed === false && Number(state.screen?.lastAt) > 0) factor *= 1.8
972
+
973
+ const minutes = Math.min(max, Math.max(min, base * factor))
974
+ return { minutes: Math.round(minutes * 10) / 10, factor: Math.round(factor * 100) / 100, night }
975
+ }
976
+
932
977
  /** 性格用几个词说出来(不是把分数报出来) */
933
978
  export function traitWords(traits = {}) {
934
979
  const words = []
@@ -1035,6 +1080,7 @@ export function snapshot(state, { now = Date.now(), conv = '', person = '' } = {
1035
1080
  body: { ...(state.body ?? {}) },
1036
1081
  scene: { ...(state.scene ?? {}), word: sceneWord(state) },
1037
1082
  intimacyLevel: intimacyLevelOf(state),
1083
+ screen: { ...(state.screen ?? {}) },
1038
1084
  urge: state.urges && state.urges.until > now ? state.urges : null,
1039
1085
  conv: convRow ? { key: conv, ...convRow } : null,
1040
1086
  person: personRow ? { key: person, ...personRow, label: warmthLabel(personRow.warmth, personRow.closeness) } : null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@istarry/spoon-companion",
3
- "version": "0.8.1",
3
+ "version": "0.9.1",
4
4
  "description": "让对话角色有自己的内心和声音:心情情绪随时间和对话自己演,回复一条一条发出来,能念出声(DeepSeek / 小米 MiMo),也能听得见——点麦克风说话,本地识别后直接发送。四块都能单独关。",
5
5
  "type": "module",
6
6
  "main": "plugin.js",
package/plugin.js CHANGED
@@ -20,15 +20,16 @@
20
20
 
21
21
  import { createHash, randomUUID } from 'node:crypto'
22
22
  import * as voicePlugin from './lib/voice.js'
23
+ import { capture, screenSupported } from './lib/screen.js'
23
24
  import { applyAsrRoutes } from './lib/asr-route.js'
24
25
  import { isCallActive, markCallSession, setCallGlobal } from './lib/asr.js'
25
- import { appendFileSync, readFileSync } from 'node:fs'
26
+ import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
26
27
  import { homedir } from 'node:os'
27
28
  import { join } from 'node:path'
28
29
  import { EMOTION_KEYS, EMOTION_MENU, TRAITS, resolveEmotion, tierOf } from './lib/catalog.js'
29
30
  import { appraise } from './lib/appraise.js'
30
31
  import {
31
- applyImpulse, catharsis, circadian, decay, dueRumination, loadState, maybeLifeEvent, maybeMoodRepair,
32
+ applyImpulse, catharsis, circadian, decay, dueRumination, loadState, lookInterval, maybeLifeEvent, maybeMoodRepair,
32
33
  nightlyReview, pruneState, remember, saveState, snapshot,
33
34
  } from './lib/state.js'
34
35
  import { channelOfSession, lastSpeaker, readUserMessages, reactToMessages, sessionEventsOf } from './lib/react.js'
@@ -87,6 +88,23 @@ const DEFAULTS = {
87
88
  * 默认 1;切换只认显式配置,不从对话里猜。
88
89
  */
89
90
  intimacy: { level: 1 },
91
+ /**
92
+ * 看屏幕。默认关 —— 开了之后才会截图。
93
+ * 频率不是固定值:基础间隔再乘情绪系数,烦的时候自己拉长,孤单的时候缩短。
94
+ * 深夜不是不看,是乘一个倍率变成低频。
95
+ */
96
+ screen: {
97
+ enabled: false,
98
+ scope: 'full',
99
+ baseMinutes: 8,
100
+ minMinutes: 3,
101
+ maxMinutes: 45,
102
+ nightFactor: 8,
103
+ nightHours: [0, 7],
104
+ dailyLimit: 120,
105
+ maxEdge: 1280,
106
+ exclude: [],
107
+ },
90
108
  }
91
109
 
92
110
  /** 工具输出统一成 { text }:模型看 render,程序调用方拿规范值,两边一致 */
@@ -143,6 +161,7 @@ export function mergeConfig(config = {}) {
143
161
  merged.heartbeat = { ...DEFAULTS.heartbeat, ...(config.heartbeat ?? {}) }
144
162
  merged.feel = { ...DEFAULTS.feel, ...(config.feel ?? {}) }
145
163
  merged.intimacy = { ...DEFAULTS.intimacy, ...(config.intimacy ?? {}) }
164
+ merged.screen = { ...DEFAULTS.screen, ...(config.screen ?? {}) }
146
165
  merged.traits = { ...(config.traits ?? {}) }
147
166
  return merged
148
167
  }
@@ -169,6 +188,35 @@ export function apply(ctx, config = {}) {
169
188
  if (Number.isFinite(Number(settings.intimacy?.level))) {
170
189
  state.intimacy = { ...(state.intimacy ?? {}), level: Math.max(0, Math.min(2, Math.round(Number(settings.intimacy.level)))) }
171
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
172
220
  const commit = () => {
173
221
  pruneState(state)
174
222
  return saveState(stateDir, state)
@@ -452,21 +500,20 @@ export function apply(ctx, config = {}) {
452
500
  res.end(JSON.stringify(payload))
453
501
  } catch { /* ignore */ }
454
502
  }
455
- // 刷新页面后按钮要知道当前状态
456
- const statusRoute = {
457
- method: 'GET',
458
- path: '/api/spoon-companion/call',
459
- handler: async (_req, res) => {
460
- const query = String(_req?.url ?? '')
461
- const m = /[?&]sessionId=([^&]+)/.exec(query)
462
- const id = m ? decodeURIComponent(m[1]) : ''
463
- const on = callGlobal || (id ? callSessions.has(id) : false)
464
- reply(res, 200, { ok: true, on, lastBody: lastCallBody, global: callGlobal }) },
465
- }
503
+ // 路由按 (kind, path) 去重,不看 method —— GET 查状态、POST 开关,得在同一个 handler 里分支。
504
+ // (之前拆成两个 register,第二个会被判重复而注册失败,POST 一直没生效。)
466
505
  const route = {
467
- method: 'POST',
506
+ kind: 'exact',
468
507
  path: '/api/spoon-companion/call',
469
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
+ }
470
517
  try {
471
518
  let raw = ''
472
519
  for await (const chunk of req) raw += chunk
@@ -492,16 +539,98 @@ export function apply(ctx, config = {}) {
492
539
  },
493
540
  }
494
541
  try {
495
- const disposers = []
496
- disposers.push(webServer.register(statusRoute))
497
- disposers.push(webServer.register(route))
498
- return () => { for (const d of disposers) { try { d?.() } catch { /* ignore */ } } }
542
+ const dispose = webServer.register(route)
543
+ return () => { try { dispose?.() } catch { /* ignore */ } }
499
544
  } catch (error) {
500
545
  log('warn', `通话按钮通道注册失败:${error instanceof Error ? error.message : String(error)}`)
501
546
  return undefined
502
547
  }
503
548
  }, 'spoon-companion: call route')
504
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
+
505
634
  /**
506
635
  * 这个会话现在在不在通话里。
507
636
  * **只认客户端那把开关** —— 点了通话才算。不拿"有没有在送音频"当证据:
@@ -968,6 +1097,71 @@ export function apply(ctx, config = {}) {
968
1097
  return { text: `最近 ${days} 天,记了 ${rows.length} 条:\n${renderDiary(rows)}` }
969
1098
  },
970
1099
  })
1100
+
1101
+ // 看屏幕:被动看。凑过去瞄一眼,不是常驻监视。
1102
+ // 图交给调用方自己看(read_image),插件不解读 —— 解读走主动看那条线。
1103
+ tools.register({
1104
+ name: 'look_screen',
1105
+ description:
1106
+ '看一眼屏幕现在是什么样 —— 不是监视,是凑过去瞄一眼。' +
1107
+ '返回一张图的路径;想知道画面里是什么,再用 read_image 打开它。' +
1108
+ '这个功能关着的时候会直接说不看。',
1109
+ parameters: {
1110
+ type: 'object',
1111
+ properties: {
1112
+ reason: { type: 'string', description: '可选:为什么想看(一句短的,只记在审计里)' },
1113
+ },
1114
+ required: [],
1115
+ additionalProperties: false,
1116
+ },
1117
+ output: TEXT_OUTPUT,
1118
+ async execute(args) {
1119
+ const now = Date.now()
1120
+ if (settings.screen?.enabled !== true) {
1121
+ return { text: '现在没在看屏幕。' }
1122
+ }
1123
+ if (!screenSupported()) {
1124
+ return { text: '这台机器上截不了图(只支持 Windows)。' }
1125
+ }
1126
+ const sc = state.screen ?? (state.screen = {})
1127
+ const day = new Date(now).toDateString()
1128
+ if (sc.day !== day) {
1129
+ sc.day = day
1130
+ sc.today = 0
1131
+ }
1132
+ const limit = Math.max(1, Number(settings.screen.dailyLimit) || 120)
1133
+ if ((Number(sc.today) || 0) >= limit) {
1134
+ return { text: `今天看得够多了(${sc.today} 次),先歇会儿。` }
1135
+ }
1136
+ try {
1137
+ const shot = await capture({ maxEdge: settings.screen.maxEdge })
1138
+ const prevTitle = String(sc.title ?? '')
1139
+ const changed = String(shot.title ?? '') !== prevTitle
1140
+ sc.lastAt = shot.at
1141
+ sc.path = shot.path
1142
+ sc.title = shot.title
1143
+ sc.changed = changed
1144
+ sc.today = (Number(sc.today) || 0) + 1
1145
+ sc.fails = 0
1146
+ sc.nextAt = shot.at + lookInterval(state, settings.screen, shot.at).minutes * 60_000
1147
+ audit({ kind: 'screen-look', path: shot.path, bytes: shot.bytes, why: String(args.reason ?? '').slice(0, 60) })
1148
+ commit()
1149
+ const where = shot.title ? `屏幕上停在「${shot.title}」` : '屏幕上是亮的'
1150
+ return {
1151
+ text:
1152
+ `看了一眼 —— ${where}。\n` +
1153
+ `图在这里,想知道画面细节就用 read_image 打开:\n${shot.path}\n` +
1154
+ `(${shot.width}x${shot.height}, ${Math.round(shot.bytes / 1024)} KB)`,
1155
+ }
1156
+ } catch (error) {
1157
+ const msg = error instanceof Error ? error.message : String(error)
1158
+ sc.fails = (Number(sc.fails) || 0) + 1
1159
+ sc.nextAt = Date.now() + Math.min(60, 5 * sc.fails) * 60_000
1160
+ audit({ kind: 'screen-fail', error: msg.slice(0, 120) })
1161
+ return { text: `没截到:${msg}` }
1162
+ }
1163
+ },
1164
+ })
971
1165
  }
972
1166
 
973
1167
  // ── 心跳 ────────────────────────────────────────────────────────────────
@@ -990,6 +1184,78 @@ export function apply(ctx, config = {}) {
990
1184
  }, 'fish-mood: heartbeat')
991
1185
  }
992
1186
 
1187
+ // ── 自己去看 ────────────────────────────────────────────────────────────
1188
+ // 到点了自己截一张,记下「刚才瞧见了什么」,不产生消息。
1189
+ // 节奏由情绪决定:孤单就短,烦就长,困就几乎不看。深夜不是不看,是低频。
1190
+ if (settings.screen?.enabled === true && screenSupported()) {
1191
+ let stopped = false
1192
+ let timer = null
1193
+
1194
+ const nextDelay = () => {
1195
+ const now = Date.now()
1196
+ const plan = lookInterval(state, settings.screen, now)
1197
+ const at = Number(state.screen?.nextAt) || 0
1198
+ const due = at > now ? at : now + plan.minutes * 60_000
1199
+ return Math.max(20_000, Math.min(due - now, 60 * 60_000))
1200
+ }
1201
+
1202
+ const tick = async () => {
1203
+ if (stopped) return
1204
+ const now = Date.now()
1205
+ const sc = state.screen ?? (state.screen = {})
1206
+ const day = new Date(now).toDateString()
1207
+ if (sc.day !== day) {
1208
+ sc.day = day
1209
+ sc.today = 0
1210
+ }
1211
+ const limit = Math.max(1, Number(settings.screen.dailyLimit) || 120)
1212
+ if ((Number(sc.today) || 0) >= limit) {
1213
+ sc.nextAt = now + 3_600_000
1214
+ return
1215
+ }
1216
+ try {
1217
+ const shot = await capture({ maxEdge: settings.screen.maxEdge })
1218
+ const prevTitle = String(sc.title ?? '')
1219
+ sc.lastAt = shot.at
1220
+ sc.path = shot.path
1221
+ sc.title = shot.title
1222
+ sc.changed = String(shot.title ?? '') !== prevTitle
1223
+ sc.today = (Number(sc.today) || 0) + 1
1224
+ sc.fails = 0
1225
+ sc.nextAt = shot.at + lookInterval(state, settings.screen, shot.at).minutes * 60_000
1226
+ audit({ kind: 'screen-look', auto: true, title: String(shot.title ?? '').slice(0, 60) })
1227
+ commit()
1228
+ } catch (error) {
1229
+ const msg = error instanceof Error ? error.message : String(error)
1230
+ sc.fails = (Number(sc.fails) || 0) + 1
1231
+ // 截不到就退避:5、10、15……最多一小时
1232
+ sc.nextAt = now + Math.min(60, 5 * sc.fails) * 60_000
1233
+ audit({ kind: 'screen-fail', auto: true, error: msg.slice(0, 120) })
1234
+ commit()
1235
+ }
1236
+ }
1237
+
1238
+ const loop = () => {
1239
+ if (stopped) return
1240
+ timer = setTimeout(async () => {
1241
+ await tick()
1242
+ loop()
1243
+ }, nextDelay())
1244
+ }
1245
+ // 设置页改完节奏,立刻按新值重排,不用等这一轮走完
1246
+ rescheduleScreen = () => {
1247
+ if (stopped) return
1248
+ if (timer) clearTimeout(timer)
1249
+ loop()
1250
+ }
1251
+ loop()
1252
+ ctx.effect(() => () => {
1253
+ stopped = true
1254
+ rescheduleScreen = null
1255
+ if (timer) clearTimeout(timer)
1256
+ }, 'fish-mood: screen loop')
1257
+ }
1258
+
993
1259
  // ── 语音 ────────────────────────────────────────────────────────────────
994
1260
  // 由 companion-voice 合并进来:注册 /api/companion-voice/* 路由、语音提示词段落、
995
1261
  // 以及与客户端的播放通道。它自己管自己的 ctx.effect,挂不上也不该拖垮情绪系统。