dsh-agent-soul 0.1.0 → 0.2.0

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/README.md CHANGED
@@ -265,14 +265,37 @@ grep "\[tool\]" ~/.dsh/agents/soul.log | tail -5 # 工具注册成功没
265
265
  ## 开发
266
266
 
267
267
  ```bash
268
- npm test # 210 条断言:记忆 65 / 人格 35 / 目的 48 / 主进程冒烟 41 / 浏览器半侧 21
268
+ npm test # 全量:先构建 client,再跑记忆 / 心情 / 人格 / 目的 / 登记 / 冒烟 / 浏览器半侧
269
+ npm run build:client # 只把 lib/client/*.js 拼成 lib/client.js
269
270
  npm run test:memory # 只跑记忆引擎
270
271
  npm run test:smoke # 用假宿主跑一遍 apply():注入段 + 工具 + API
271
- npm run test:client # 用假 __ModuleLoader__ 跑一遍浏览器 bundle
272
+ npm run test:client # 先构建,再用假 __ModuleLoader__ 跑一遍浏览器 bundle
272
273
  ```
273
274
 
274
275
  单测只碰纯函数,用临时目录,不动真实的 `~/.dsh`。
275
276
 
277
+ ### 浏览器半侧是拆开写的,`lib/client.js` 是生成物
278
+
279
+ DSH 客户端模块系统**一个包只出一个 bundle、兄弟文件无法同步 require**,所以浏览器
280
+ 半侧不能真的拆成互相 `import` 的文件。这里的做法是:源码按职责放在 `lib/client/`:
281
+
282
+ ```
283
+ lib/client/styles.js 样式(CSS + ensureStyles)
284
+ lib/client/api.js 同源 HTTP + cwd/时间工具
285
+ lib/client/components.js 共享小组件(Badge/Card/Dot/Pill/Switch/Kv)
286
+ lib/client/overview-tab.js 概览
287
+ lib/client/persona-tab.js 人格
288
+ lib/client/memory-tab.js 记忆
289
+ lib/client/purpose-tab.js 目的
290
+ lib/client/mood-tab.js 心情
291
+ lib/client/settings-tab.js 设置
292
+ lib/client/app.js 外壳(SoulSection/ErrorBoundary/apply/导出)
293
+ ```
294
+
295
+ `tools/build-client.mjs` 按固定顺序把它们拼回**唯一入口 `lib/client.js`**。要改浏览器
296
+ 半侧就改 `lib/client/` 里的片段,然后跑 `npm run build:client`(`npm test` 会自动先构建)。
297
+ 每个片段都能单独 `node --check`,引用未定义变量只是运行时的事,不影响语法检查。
298
+
276
299
  后两个测试是**装进 DSH 之前唯一的保险**,因为这两类错误 `node --check` 抓不到:
277
300
 
278
301
  - `smoke`:`apply()` 在某个 ctx 服务上炸掉 → 插件加载了但注入没生效
Binary file
Binary file
Binary file
Binary file
Binary file
package/lib/api.js CHANGED
@@ -18,8 +18,9 @@
18
18
  * POST /mood/decay 手动跑一次时间衰减
19
19
  */
20
20
  import { spawn } from 'node:child_process'
21
- import { statSync } from 'node:fs'
22
- import { dirname } from 'node:path'
21
+ import { readFileSync, statSync } from 'node:fs'
22
+ import { dirname, join } from 'node:path'
23
+ import { fileURLToPath } from 'node:url'
23
24
  import { note, serviceOf } from './env.js'
24
25
  import { composePersona, localPersonaPath, MAX_INJECT_CHARS, resolveSources, storedProjectPersonaPath } from './persona.js'
25
26
  import { atomicWrite, exists, globalPersonaPath, readText, slugFor } from './paths.js'
@@ -31,13 +32,14 @@ import {
31
32
  memoryStats,
32
33
  saveConfig,
33
34
  purposeState,
35
+ savePurposeState,
34
36
  saveGlobalCard,
35
37
  saveProjectCard,
36
38
  moodState,
37
39
  resetMood,
38
40
  decayMoodFor
39
41
  } from './store.js'
40
- import { displayDims, moodEmoji, moodLabel, topDims, TIMELINE_CAP } from './mood.js'
42
+ import { displayDims, moodFace, moodLabel, topDims, TIMELINE_CAP } from './mood.js'
41
43
  import { forgetRecord, setPinned, addRecord } from './memory.js'
42
44
  import { closeGoal, openGoals, summarize } from './purpose.js'
43
45
  import { MEMORY_FACTS } from './facts.js'
@@ -46,6 +48,24 @@ import { getFallbackCwd } from './tool.js'
46
48
 
47
49
  export const API_PREFIX = '/api/soul'
48
50
 
51
+ /**
52
+ * 静态资源前缀:心情那五张表情图从这里出去(/dsh-agent-soul/face-ok.png)。
53
+ * 跟 dsh-feiyu-mood 的老习惯一致,也避开宿主自己的路径。
54
+ */
55
+ export const ASSET_PREFIX = '/dsh-agent-soul'
56
+
57
+ /** 只认这五张图 —— 白名单挡住 ../ 之类的路径穿越,别让外面翻目录。 */
58
+ const FACE_ASSETS = new Set([
59
+ 'face-great.png',
60
+ 'face-good.png',
61
+ 'face-ok.png',
62
+ 'face-worry.png',
63
+ 'face-sad.png'
64
+ ])
65
+
66
+ /** 插件自己的 assets 目录(跟 lib/ 平级;npm 装完也在那儿)。 */
67
+ const ASSETS_DIR = fileURLToPath(new URL('../assets/', import.meta.url))
68
+
49
69
  /** 请求体上限:设置页只传配置和短文本,1MB 足够,挡住手滑。 */
50
70
  const MAX_BODY = 1024 * 1024
51
71
 
@@ -327,7 +347,7 @@ export function registerApi(ctx) {
327
347
  return {
328
348
  mood: Math.round(s.mood),
329
349
  label: moodLabel(s.mood),
330
- emoji: moodEmoji(s.mood),
350
+ face: moodFace(s.mood),
331
351
  dims: displayDims(s),
332
352
  top: topDims(s),
333
353
  lastReason: s.lastReason,
@@ -439,7 +459,7 @@ export function registerApi(ctx) {
439
459
  mood: Math.round(s.mood),
440
460
  rawMood: s.mood,
441
461
  label: moodLabel(s.mood),
442
- emoji: moodEmoji(s.mood),
462
+ face: moodFace(s.mood),
443
463
  dims: displayDims(s),
444
464
  top: topDims(s),
445
465
  lastReason: s.lastReason,
@@ -492,10 +512,7 @@ export function registerApi(ctx) {
492
512
  const state = purposeState()
493
513
  const id = String(body?.id ?? '')
494
514
  const ok = closeGoal(state, id)
495
- if (ok) {
496
- const { savePurposeState } = await import('./store.js')
497
- savePurposeState(state)
498
- }
515
+ if (ok) savePurposeState(state)
499
516
  return json(res, ok ? 200 : 404, { ok, goals: openGoals(state, { limit: 20 }) })
500
517
  }
501
518
 
@@ -538,3 +555,49 @@ export function registerApi(ctx) {
538
555
  note('api', `设置页接口已注册 ${API_PREFIX}`)
539
556
  return dispose
540
557
  }
558
+
559
+ /**
560
+ * 表情图那五张 PNG 走这儿出去。
561
+ * 之前用的是系统 emoji(😊🙂那种),跟原插件那套画不一致 —— 现在直接给图。
562
+ * 只此五张、只读,顺永远不会变,所以缓存直接拉到最长。
563
+ */
564
+ export function registerAssets(ctx) {
565
+ const webServer = serviceOf(ctx, 'webServer')
566
+ if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
567
+ note('api', '宿主没有 webServer 服务,表情图未注册')
568
+ return undefined
569
+ }
570
+ const dispose = webServer.register({
571
+ kind: 'prefix',
572
+ path: ASSET_PREFIX,
573
+ handler: (req, res) => {
574
+ const url = (req.url ?? '').split('?')[0]
575
+ const raw = url.slice(ASSET_PREFIX.length).replace(/^\/+/, '')
576
+ const name = decodeURIComponent(raw)
577
+ if (!FACE_ASSETS.has(name)) {
578
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
579
+ res.end('not found')
580
+ return
581
+ }
582
+ try {
583
+ const bytes = readFileSync(join(ASSETS_DIR, name))
584
+ res.writeHead(200, {
585
+ 'Content-Type': 'image/png',
586
+ 'Content-Length': bytes.length,
587
+ // 文件名不带版本号,但内容从不改 → 让浏览器只取一次
588
+ 'Cache-Control': 'public, max-age=31536000, immutable'
589
+ })
590
+ res.end(bytes)
591
+ } catch {
592
+ note('api', `表情图读不出来:${name}(assets 目录丢了?${ASSETS_DIR})`)
593
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
594
+ res.end('not found')
595
+ }
596
+ }
597
+ })
598
+ if (typeof dispose === 'function' && typeof ctx.effect === 'function') {
599
+ ctx.effect(() => dispose, 'dsh-agent-soul: assets')
600
+ }
601
+ note('api', `表情图已注册 ${ASSET_PREFIX}(${FACE_ASSETS.size} 张)`)
602
+ return dispose
603
+ }
@@ -0,0 +1,52 @@
1
+ // ---- 同源 API ---------------------------------------------------------
2
+ // 片段:运行在 client.js 工厂函数作用域内。与宿主只走同源 HTTP(/api/soul/*),
3
+ // 不碰 RPC:浏览器半侧只要能 fetch 就能用,插件卸载/重装时页面顶多拿到 404。
4
+
5
+ var API = '/api/soul'
6
+
7
+ function readJson(res) {
8
+ return res.text().then(function (text) {
9
+ var data = null
10
+ try { data = text === '' ? null : JSON.parse(text) } catch (e) { data = null }
11
+ if (!res.ok) {
12
+ var err = new Error(data && data.error ? data.error : 'HTTP ' + res.status)
13
+ err.status = res.status
14
+ throw err
15
+ }
16
+ return data
17
+ })
18
+ }
19
+ function apiGet(path) {
20
+ return fetch(API + path, { cache: 'no-store' }).then(readJson)
21
+ }
22
+ function apiPost(path, body) {
23
+ return fetch(API + path, {
24
+ method: 'POST',
25
+ headers: { 'content-type': 'application/json' },
26
+ body: JSON.stringify(body || {}),
27
+ }).then(readJson)
28
+ }
29
+
30
+ /** 从会话上下文里刨出 cwd —— 刨不到就全局视图,再不够还有服务端兜底与手选。 */
31
+ function cwdOf(props) {
32
+ var p = props || {}
33
+ var candidates = [
34
+ p.cwd,
35
+ p.session && p.session.header && p.session.header.cwd,
36
+ p.session && p.session.cwd,
37
+ p.agent && p.agent.session && p.agent.session.header && p.agent.session.header.cwd,
38
+ ]
39
+ for (var i = 0; i < candidates.length; i += 1) {
40
+ if (typeof candidates[i] === 'string' && candidates[i] !== '') return candidates[i]
41
+ }
42
+ return ''
43
+ }
44
+
45
+ /** ISO 时间 → 「10月26日 12:48」(设置页文件栏用)。 */
46
+ function timeLabel(iso) {
47
+ if (!iso) return ''
48
+ var d = new Date(iso)
49
+ if (isNaN(d.getTime())) return ''
50
+ var pad = function (n) { return (n < 10 ? '0' : '') + n }
51
+ return (d.getMonth() + 1) + '月' + d.getDate() + '日 ' + pad(d.getHours()) + ':' + pad(d.getMinutes())
52
+ }
@@ -0,0 +1,120 @@
1
+ // ---- 外壳 -------------------------------------------------------------
2
+ // 片段:运行在 client.js 工厂函数作用域内。最后一个片段 —— 依赖前面所有的 Tab。
3
+ // 可用:h / Dot / apiGet / cwdOf / ensureStyles / NS / useState / useEffect /
4
+ // useCallback / 六个 Tab 组件。
5
+
6
+ function SoulSection(props) {
7
+ var [tab, setTab] = useState('overview')
8
+ var [state, setState] = useState(null)
9
+ var [error, setError] = useState('')
10
+ // 手选工作区覆盖:设置页是全局弹层,宿主经常不给 cwd —— 用户从下拉/任意目录挑一个后,全页跟着切
11
+ var [cwdOverride, setCwdOverride] = useState('')
12
+ var cwd = cwdOverride !== '' ? cwdOverride : cwdOf(props)
13
+
14
+ var reload = useCallback(function () {
15
+ apiGet('/state' + (cwd ? '?cwd=' + encodeURIComponent(cwd) : ''))
16
+ .then(function (data) { setState(data); setError('') })
17
+ .catch(function (e) { setError('读取失败:' + e.message + '(插件可能还没加载完)') })
18
+ }, [cwd])
19
+
20
+ useEffect(function () { reload() }, [reload])
21
+
22
+ var tabs = [
23
+ ['overview', '概览'],
24
+ ['persona', '人格'],
25
+ ['memory', '记忆'],
26
+ ['purpose', '目的'],
27
+ ['mood', '心情'],
28
+ ['settings', '设置'],
29
+ ]
30
+
31
+ // 头部三个状态点:一眼看出哪里没配好
32
+ var personaOk = Boolean(state && state.persona && state.persona.sources && state.persona.sources.length > 0)
33
+ var memCount = state && state.memory && state.memory.global ? state.memory.global.count : 0
34
+ var memRatio = state && state.memory && state.memory.global ? (state.memory.global.ratio || 0) : 0
35
+ var memTone = memRatio >= 1 ? 'bad' : memRatio >= 0.8 ? 'warn' : 'ok'
36
+ var goalCount = state && state.purpose ? state.purpose.open : 0
37
+ var moodInfo = state && state.mood ? state.mood : null
38
+
39
+ return h('div', { className: 'soul-app' },
40
+ h('div', { className: 'soul-head' },
41
+ h('div', null,
42
+ h('p', { className: 'soul-kicker' }, 'agent soul'),
43
+ h('h1', { className: 'soul-title' }, '灵魂'),
44
+ h('p', { className: 'soul-sub' }, cwd === '' ? '当前没有工作目录 · 只用全局人格与全局记忆' : '工作目录:' + cwd)
45
+ ),
46
+ h('div', { className: 'soul-dots' },
47
+ h(Dot, { tone: personaOk ? 'ok' : 'warn' }, personaOk ? '人格已注入' : '人格未配置'),
48
+ h(Dot, { tone: memCount === 0 ? 'warn' : memTone }, memCount + ' 条记忆'),
49
+ h(Dot, { tone: 'ok' }, goalCount + ' 件惦记'),
50
+ h(Dot, { tone: moodInfo && moodInfo.mood >= 42 ? 'ok' : 'warn' }, '心情 ' + (moodInfo ? moodInfo.mood : '—'))
51
+ )
52
+ ),
53
+ h('div', { className: 'soul-tabs' }, tabs.map(function (item) {
54
+ return h('button', {
55
+ key: item[0],
56
+ className: 'soul-tab' + (tab === item[0] ? ' on' : ''),
57
+ onClick: function () { setTab(item[0]) },
58
+ }, item[1])
59
+ })),
60
+ h('div', { className: 'soul-body' },
61
+ error ? h('p', { className: 'soul-err' }, error) : null,
62
+ tab === 'overview' ? h(OverviewTab, { state: state, cwd: cwd }) : null,
63
+ tab === 'persona' ? h(PersonaTab, {
64
+ cwd: cwd,
65
+ workspace: state && state.workspace,
66
+ workspaces: state && state.workspaces,
67
+ config: state && state.config,
68
+ reload: reload,
69
+ onSelectCwd: setCwdOverride,
70
+ }) : null,
71
+ tab === 'memory' ? h(MemoryTab, { cwd: cwd, config: state && state.config, reload: reload }) : null,
72
+ tab === 'purpose' ? h(PurposeTab, { state: state, cwd: cwd, reload: reload }) : null,
73
+ tab === 'mood' ? h(MoodTab, { cwd: cwd, state: state, reload: reload }) : null,
74
+ tab === 'settings' ? h(SettingsTab, { state: state, cwd: cwd, reload: reload }) : null
75
+ )
76
+ )
77
+ }
78
+
79
+ /** 错误边界:设置页崩了要看得见原因,而不是整块白屏。 */
80
+ function ErrorBoundary(props) {
81
+ var [err, setErr] = useState(null)
82
+ useEffect(function () {
83
+ function onError(e) { setErr(e && e.message ? e.message : String(e)) }
84
+ window.addEventListener('error', onError)
85
+ return function () { window.removeEventListener('error', onError) }
86
+ }, [])
87
+ if (err !== null) {
88
+ return h('div', { className: 'soul-app' },
89
+ h('div', { className: 'soul-body' },
90
+ h('div', { className: 'soul-card-h' }, h('p', { className: 'soul-card-t' }, '设置页出错了')),
91
+ h('p', { className: 'soul-err' }, err),
92
+ h('p', { className: 'soul-note' }, '这不影响人格与记忆本身,注入和记录都还在跑。可以点「继续」重试,或者重新加载页面。'),
93
+ h('div', { className: 'soul-row', style: { marginTop: 10 } },
94
+ h('button', { className: 'soul-btn', onClick: function () { setErr(null) } }, '继续'),
95
+ h('button', { className: 'soul-btn', onClick: function () { window.location.reload() } }, '重新加载页面')
96
+ )
97
+ )
98
+ )
99
+ }
100
+ return props.children
101
+ }
102
+
103
+ function apply(ctx) {
104
+ if (typeof ctx.effect === 'function') ctx.effect(function () { return ensureStyles(ctx) }, NS + ': styles')
105
+
106
+ ctx.slots.inject('settings.section', function () {
107
+ return ctx.slots.register({
108
+ name: 'settings.section',
109
+ id: 'soul',
110
+ order: 47,
111
+ locale: NS,
112
+ label: function () { return '灵魂' },
113
+ }, function (props) {
114
+ var p = props !== null && props !== undefined ? props : {}
115
+ return h(ErrorBoundary, null, h(SoulSection, p))
116
+ })
117
+ })
118
+ }
119
+
120
+ module.exports = { name: 'soul', inject: ['slots'], apply: apply }
@@ -0,0 +1,68 @@
1
+ // ---- 小组件 -----------------------------------------------------------
2
+ // 片段:运行在 client.js 工厂函数作用域内。可用:h / React。
3
+
4
+ var CLARITY_LABEL = { vivid: '清晰', clear: '清楚', fuzzy: '模糊', trace: '只剩印象', forgotten: '已遗忘' }
5
+ var NEED_LABEL = { curiosity: '想弄明白', care: '在乎', share: '想分享', mastery: '想搞懂' }
6
+ var KIND_LABEL = { question: '想弄明白', promise: '答应过的', curious: '想试试', followup: '还没聊完' }
7
+ // 七情顺序跟 lib/mood.js 的 DIMS 一致(界面按这个排)
8
+ var MOOD_DIMS = [
9
+ ['happy', '开心'], ['calm', '踏实'], ['sweet', '甜蜜'], ['heartache', '心疼'],
10
+ ['worry', '担心'], ['sad', '难过'], ['jealous', '吃醋'],
11
+ ]
12
+ // 心情表情图的地址前缀:由 lib/api.js 的 registerAssets 注册出去(跟 ASSET_PREFIX 对齐)
13
+ var MOOD_FACE_URL = '/dsh-agent-soul/face-'
14
+
15
+ function Badge(props) {
16
+ return h('span', { className: 'soul-badge ' + (props.clarity || '') }, props.children)
17
+ }
18
+
19
+ function Card(props) {
20
+ return h('div', { className: 'soul-card' },
21
+ props.title
22
+ ? h('div', { className: 'soul-card-h' },
23
+ h('p', { className: 'soul-card-t' }, props.title),
24
+ props.meta ? h('span', { className: 'soul-card-m' }, props.meta) : null
25
+ )
26
+ : null,
27
+ props.children
28
+ )
29
+ }
30
+
31
+ /** 状态点:绿=正常、黄=要留意、红=有问题。 */
32
+ function Dot(props) {
33
+ return h('span', { className: 'soul-dot ' + (props.tone || '') },
34
+ h('i', null),
35
+ props.children
36
+ )
37
+ }
38
+
39
+ /** 药丸页签(跟原人格插件一致的交互)。 */
40
+ function Pill(props) {
41
+ return h('button', {
42
+ className: 'soul-pill-tab' + (props.active ? ' on' : ''),
43
+ disabled: props.disabled === true,
44
+ title: props.title || '',
45
+ onClick: props.onClick,
46
+ }, props.children)
47
+ }
48
+
49
+ /** 开关(带文字状态,比裸 checkbox 清楚)。 */
50
+ function Switch(props) {
51
+ return h('label', { className: 'soul-switch' },
52
+ h('input', {
53
+ type: 'checkbox',
54
+ checked: props.checked === true,
55
+ disabled: props.disabled === true,
56
+ onChange: props.onChange,
57
+ }),
58
+ h('span', null, props.label)
59
+ )
60
+ }
61
+
62
+ /** 一行键值(比裸 div 好读)。 */
63
+ function Kv(props) {
64
+ return h('div', { className: 'soul-kv' },
65
+ h('span', null, props.label),
66
+ h('b', null, props.value)
67
+ )
68
+ }
@@ -0,0 +1,152 @@
1
+ // ---- 记忆 -------------------------------------------------------------
2
+ // 片段:运行在 client.js 工厂函数作用域内。
3
+ // 可用:h / Card / Badge / apiGet / apiPost / useState / useEffect / useCallback / CLARITY_LABEL。
4
+
5
+ function MemoryTab(props) {
6
+ var [scope, setScope] = useState('global')
7
+ var [query, setQuery] = useState('')
8
+ var [data, setData] = useState(null)
9
+ var [status, setStatus] = useState('')
10
+ var [draft, setDraft] = useState('')
11
+ var cwd = props.cwd
12
+ var config = props.config || {}
13
+
14
+ function patchConfig(next) {
15
+ var merged = {}
16
+ Object.keys(config).forEach(function (k) { merged[k] = config[k] })
17
+ Object.keys(next).forEach(function (k) { merged[k] = next[k] })
18
+ apiPost('/config', { config: merged })
19
+ .then(function () { setStatus('配置已保存'); if (typeof props.reload === 'function') props.reload() })
20
+ .catch(function (e) { setStatus('保存失败:' + e.message) })
21
+ }
22
+
23
+ var load = useCallback(function () {
24
+ var url = '/memory?scope=' + scope + (cwd ? '&cwd=' + encodeURIComponent(cwd) : '') + (query ? '&query=' + encodeURIComponent(query) : '')
25
+ apiGet(url).then(setData).catch(function (e) { setStatus('读取失败:' + e.message) })
26
+ }, [scope, cwd, query])
27
+
28
+ useEffect(function () { load() }, [load])
29
+
30
+ function act(action, id, extra) {
31
+ var body = { scope: scope, cwd: cwd, action: action, id: id }
32
+ if (extra) Object.keys(extra).forEach(function (k) { body[k] = extra[k] })
33
+ apiPost('/memory', body)
34
+ .then(function () { setStatus('已' + (action === 'delete' ? '删除' : action === 'pin' ? '固定' : '更新')); load() })
35
+ .catch(function (e) { setStatus('操作失败:' + e.message) })
36
+ }
37
+
38
+ function add() {
39
+ if (draft.trim() === '') return
40
+ apiPost('/memory', { scope: scope, cwd: cwd, action: 'edit', id: '', text: draft })
41
+ .catch(function () {
42
+ // edit 需要 id,新增走 write:这里直接用 write 语义
43
+ return apiPost('/memory', { scope: scope, cwd: cwd, action: 'write', text: draft })
44
+ })
45
+ .then(function () { setDraft(''); setStatus('记下了'); load() })
46
+ .catch(function (e) { setStatus('添加失败:' + e.message) })
47
+ }
48
+
49
+ var records = (data && data.records) || []
50
+
51
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
52
+ h('div', { className: 'soul-row' },
53
+ h('button', { className: 'soul-btn' + (scope === 'global' ? ' on' : ''), onClick: function () { setScope('global') } }, '全局记忆'),
54
+ h('button', { className: 'soul-btn' + (scope === 'project' ? ' on' : ''), onClick: function () { setScope('project') } }, '本项目'),
55
+ h('input', {
56
+ className: 'soul-input soul-grow',
57
+ placeholder: '搜关键词',
58
+ value: query,
59
+ style: { maxWidth: 220 },
60
+ onChange: function (e) { setQuery(e.target.value) },
61
+ }),
62
+ h('button', { className: 'soul-btn', onClick: load }, '刷新')
63
+ ),
64
+ h('p', { className: 'soul-meta' }, (data ? data.total : 0) + ' 条' + (status ? ' · ' + status : '')),
65
+
66
+ h(Card, { title: '手动记一条' },
67
+ h('div', { className: 'soul-row' },
68
+ h('input', {
69
+ className: 'soul-input soul-grow',
70
+ placeholder: '写一件值得记住的事(会按重要度自动定衰减速度)',
71
+ value: draft,
72
+ onChange: function (e) { setDraft(e.target.value) },
73
+ onKeyDown: function (e) { if (e.key === 'Enter') add() },
74
+ }),
75
+ h('button', { className: 'soul-btn', onClick: add }, '记下来')
76
+ ),
77
+ h('p', { className: 'soul-note' }, '主人的偏好/目标、约定、"第一次"类的事会自动判高重要度,衰减得慢。')
78
+ ),
79
+
80
+ records.length === 0
81
+ ? h('div', { className: 'soul-empty' }, query ? '没搜到' : '还没有记忆。多聊几句,值得记的会自动进来')
82
+ : h('div', { className: 'soul-list' }, records.map(function (r) {
83
+ return h('div', { key: r.id, className: 'soul-item' },
84
+ h(Badge, { clarity: r.clarity }, CLARITY_LABEL[r.clarity] || r.clarity),
85
+ h('div', { className: 'soul-item-text' },
86
+ h('div', null, r.text),
87
+ h('div', { className: 'soul-meta' },
88
+ '重要度 ' + r.importance +
89
+ ' · 提到过 ' + r.recallCount + ' 次' +
90
+ ' · ' + (r.source === 'auto' ? '自动记的' : r.source === 'tool' ? '她自己记的' : '手动') +
91
+ (r.pinned ? ' · 已固定' : '') +
92
+ (r.tags && r.tags.length ? ' · ' + r.tags.join('/') : '')
93
+ )
94
+ ),
95
+ h('button', { className: 'soul-btn', onClick: function () { act('pin', r.id, { pinned: !r.pinned }) }, title: '固定后永不遗忘' }, r.pinned ? '取消固定' : '固定'),
96
+ h('button', { className: 'soul-btn danger', onClick: function () { act('delete', r.id) } }, '删')
97
+ )
98
+ })),
99
+
100
+ // ---- 记忆模块自己的配置(从「设置」页挪进来,模块化) ----
101
+ h(Card, { title: '记忆注入与整理' },
102
+ h('div', { className: 'soul-row' },
103
+ h('span', { className: 'soul-grow' }, '注入预算(字)'),
104
+ h('input', {
105
+ className: 'soul-input',
106
+ type: 'number',
107
+ style: { maxWidth: 110 },
108
+ value: config.injectMaxChars || 1600,
109
+ onChange: function (e) { patchConfig({ injectMaxChars: Number(e.target.value) || 1600 }) },
110
+ })
111
+ ),
112
+ h('p', { className: 'soul-note' }, '这段**每回合重发**,是常驻成本。中文按 DSH 口径的 1.4~1.9 倍算:1600 字约 1100~1500 token。'),
113
+ h('div', { className: 'soul-row', style: { padding: '6px 0' } },
114
+ h('div', { className: 'soul-grow' },
115
+ h('div', null, '注入记忆'),
116
+ h('p', { className: 'soul-note' }, '关掉后记忆不再进提示词,但仍在后台记录')
117
+ ),
118
+ h('input', {
119
+ type: 'checkbox',
120
+ checked: config.memoryEnabled !== false,
121
+ onChange: function (e) { patchConfig({ memoryEnabled: e.target.checked }) },
122
+ })
123
+ ),
124
+ h('div', { className: 'soul-row', style: { padding: '6px 0' } },
125
+ h('div', { className: 'soul-grow' },
126
+ h('div', null, '项目记忆独立一张卡'),
127
+ h('p', { className: 'soul-note' }, '关掉则所有记忆都进全局卡')
128
+ ),
129
+ h('input', {
130
+ type: 'checkbox',
131
+ checked: config.projectMemoryEnabled !== false,
132
+ onChange: function (e) { patchConfig({ projectMemoryEnabled: e.target.checked }) },
133
+ })
134
+ ),
135
+ h('div', { className: 'soul-row', style: { marginTop: 8 } },
136
+ h('button', {
137
+ className: 'soul-btn',
138
+ onClick: function () {
139
+ setStatus('整理中…')
140
+ apiPost('/maintain', { cwd: cwd })
141
+ .then(function (data) {
142
+ var r = data.report || {}
143
+ setStatus('整理完成:衰减 ' + (r.decayed || []).length + ' 张,压缩 ' + (r.compacted || []).length + ' 处')
144
+ if (typeof props.reload === 'function') props.reload()
145
+ })
146
+ .catch(function (e) { setStatus('失败:' + e.message) })
147
+ }
148
+ }, '立即整理一次')
149
+ )
150
+ )
151
+ )
152
+ }