dsh-agent-soul 0.2.0 → 0.4.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/README.md +236 -125
- package/docs/preview.html +8 -8
- package/lib/api.js +304 -30
- package/lib/client/api.js +39 -0
- package/lib/client/app.js +3 -1
- package/lib/client/diary-tab.js +347 -0
- package/lib/client/memory-tab.js +26 -4
- package/lib/client/mood-tab.js +12 -10
- package/lib/client/overview-tab.js +33 -0
- package/lib/client/persona-tab.js +1 -0
- package/lib/client/settings-tab.js +1 -1
- package/lib/client.js +464 -16
- package/lib/diary.js +1265 -0
- package/lib/env.js +57 -9
- package/lib/extract.js +323 -9
- package/lib/index.js +498 -67
- package/lib/memory.js +1377 -807
- package/lib/mood.js +270 -23
- package/lib/paths.js +196 -168
- package/lib/purpose.js +195 -1
- package/lib/refine.js +221 -0
- package/lib/registry.js +236 -236
- package/lib/store.js +697 -383
- package/lib/tool.js +27 -8
- package/package.json +84 -71
- package/tools/build-client.mjs +1 -0
- package/tools/sync.mjs +131 -0
package/lib/api.js
CHANGED
|
@@ -16,6 +16,12 @@
|
|
|
16
16
|
* GET /mood 心情全量(值 + 七情 + 时间线)
|
|
17
17
|
* POST /mood/reset 重置心情
|
|
18
18
|
* POST /mood/decay 手动跑一次时间衰减
|
|
19
|
+
* POST /diary 手动触发日记({ date?: "YYYY-MM-DD", note?: "备注" })
|
|
20
|
+
* GET /diary/list 日记列表(最近 N 天,公开日记带预览,私密只报存在性)
|
|
21
|
+
* GET /diary/read 读某一天的日记(公开全文,私密只报存在性)
|
|
22
|
+
* GET /diary/private 读私密正文(2026-10-31;仅回环 + diaryPrivateVisible=true)
|
|
23
|
+
* POST /diary/bind 把会话绑定成日记会话({ sessionId? },缺省取当前会话)
|
|
24
|
+
* POST /diary/unbind 清除日记会话绑定
|
|
19
25
|
*/
|
|
20
26
|
import { spawn } from 'node:child_process'
|
|
21
27
|
import { readFileSync, statSync } from 'node:fs'
|
|
@@ -23,7 +29,19 @@ import { dirname, join } from 'node:path'
|
|
|
23
29
|
import { fileURLToPath } from 'node:url'
|
|
24
30
|
import { note, serviceOf } from './env.js'
|
|
25
31
|
import { composePersona, localPersonaPath, MAX_INJECT_CHARS, resolveSources, storedProjectPersonaPath } from './persona.js'
|
|
26
|
-
import {
|
|
32
|
+
import {
|
|
33
|
+
archivePath,
|
|
34
|
+
atomicWrite,
|
|
35
|
+
exists,
|
|
36
|
+
globalPersonaPath,
|
|
37
|
+
normalizePathKey,
|
|
38
|
+
readText,
|
|
39
|
+
slugFor,
|
|
40
|
+
diaryPublicDir,
|
|
41
|
+
diaryPrivateDir,
|
|
42
|
+
diaryPublicPath,
|
|
43
|
+
diaryPrivatePath
|
|
44
|
+
} from './paths.js'
|
|
27
45
|
import {
|
|
28
46
|
globalCard,
|
|
29
47
|
projectCard,
|
|
@@ -39,8 +57,9 @@ import {
|
|
|
39
57
|
resetMood,
|
|
40
58
|
decayMoodFor
|
|
41
59
|
} from './store.js'
|
|
42
|
-
import {
|
|
43
|
-
import {
|
|
60
|
+
import { todayKey, yesterdayKey, runDiaryOnce } from './diary.js'
|
|
61
|
+
import { displayDimPercents, displayDims, moodFace, moodLabel, topDims, TIMELINE_CAP } from './mood.js'
|
|
62
|
+
import { forgetRecord, makeArchiver, setPinned, addRecord } from './memory.js'
|
|
44
63
|
import { closeGoal, openGoals, summarize } from './purpose.js'
|
|
45
64
|
import { MEMORY_FACTS } from './facts.js'
|
|
46
65
|
import { listWorkspaces, registerProject } from './registry.js'
|
|
@@ -99,6 +118,78 @@ const json = (res, code, payload) => {
|
|
|
99
118
|
res.end(JSON.stringify(payload))
|
|
100
119
|
}
|
|
101
120
|
|
|
121
|
+
/**
|
|
122
|
+
* 请求是不是从本机回环地址发来的(2026-10-31)。
|
|
123
|
+
*
|
|
124
|
+
* 为什么单独判一次:私密日记正文默认永不出服务器。开了 diaryPrivateVisible
|
|
125
|
+
* 也只给「这台机器上的自己」看 —— 远程访问(局域网 / 反代)拿到的应当仍是 403。
|
|
126
|
+
* remoteAddress 的三种写法都要认:IPv4 直连、IPv6 回环、IPv4-mapped IPv6。
|
|
127
|
+
*/
|
|
128
|
+
export function isLoopbackRequest(req) {
|
|
129
|
+
const remote = String(req?.socket?.remoteAddress ?? '')
|
|
130
|
+
return remote === '127.0.0.1' || remote === '::1' || remote === '::ffff:127.0.0.1'
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* 私密日记的访问闸门 + 读取(2026-10-31,纯函数便于测试)。
|
|
135
|
+
*
|
|
136
|
+
* 顺序不能换:先判回环,再判开关,最后才读文件 —— 开关关着时连「文件在不在」
|
|
137
|
+
* 之外的任何内容都不回。鉴权沿用 /api/soul 全局那道 Origin 跨源检查(POST /diary
|
|
138
|
+
* 用的也是它),这里再加一层回环限制,是私密内容的第二道锁。
|
|
139
|
+
*
|
|
140
|
+
* @returns {{ status: number, payload: object }}
|
|
141
|
+
*/
|
|
142
|
+
export function privateDiaryView(req, config) {
|
|
143
|
+
if (!isLoopbackRequest(req)) {
|
|
144
|
+
return { status: 403, payload: { ok: false, error: '私密日记只允许本机回环请求' } }
|
|
145
|
+
}
|
|
146
|
+
if (config === null || config === undefined || config.diaryPrivateVisible !== true) {
|
|
147
|
+
return { status: 403, payload: { ok: false, error: '私密日记查看未开启(diaryPrivateVisible=false)' } }
|
|
148
|
+
}
|
|
149
|
+
let dateStr = ''
|
|
150
|
+
try {
|
|
151
|
+
dateStr = String(new URL(req?.url ?? '/', 'http://127.0.0.1').searchParams.get('date') ?? '').trim()
|
|
152
|
+
} catch {
|
|
153
|
+
dateStr = ''
|
|
154
|
+
}
|
|
155
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
|
|
156
|
+
return { status: 400, payload: { ok: false, error: '缺少或非法的 date 参数(YYYY-MM-DD)' } }
|
|
157
|
+
}
|
|
158
|
+
const file = diaryPrivatePath(dateStr)
|
|
159
|
+
const hasPrivate = exists(file)
|
|
160
|
+
return {
|
|
161
|
+
status: 200,
|
|
162
|
+
payload: { ok: true, date: dateStr, hasPrivate, content: hasPrivate ? readText(file) : '' }
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 会话服务里最近更新的会话 id(拿不到返回空串)。
|
|
168
|
+
*
|
|
169
|
+
* 2026-10-31:这台 DSH 的设置页 renderSlot('settings.section') 只传 { close },
|
|
170
|
+
* 前端拿不到当前会话 id。点「把当前会话指定为日记会话」时请求里就没 id,
|
|
171
|
+
* 这里按 updatedAt 取「最近动过的那个」当当前会话 —— 只用于【手动绑定这一步】;
|
|
172
|
+
* 投递侧只认配置里的 id,绝不回退到这里。
|
|
173
|
+
*/
|
|
174
|
+
function currentSessionIdOf(ctx) {
|
|
175
|
+
const sessions = serviceOf(ctx, 'sessions')
|
|
176
|
+
if (sessions === undefined || sessions === null || typeof sessions.list !== 'function') return ''
|
|
177
|
+
try {
|
|
178
|
+
const list = sessions.list()
|
|
179
|
+
if (!Array.isArray(list)) return ''
|
|
180
|
+
let best = null
|
|
181
|
+
for (const session of list) {
|
|
182
|
+
const id = String(session?.header?.id ?? session?.id ?? '')
|
|
183
|
+
if (id === '') continue
|
|
184
|
+
const stamp = String(session?.header?.updatedAt ?? session?.header?.createdAt ?? session?.updatedAt ?? session?.createdAt ?? '')
|
|
185
|
+
if (best === null || stamp > best.stamp) best = { id, stamp }
|
|
186
|
+
}
|
|
187
|
+
return best === null ? '' : best.id
|
|
188
|
+
} catch {
|
|
189
|
+
return ''
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
102
193
|
/**
|
|
103
194
|
* 弹一个系统「选择文件夹」对话框,返回选中的目录(取消返回空串)。
|
|
104
195
|
*
|
|
@@ -117,7 +208,7 @@ function pickFolder() {
|
|
|
117
208
|
'-NoProfile',
|
|
118
209
|
'-STA',
|
|
119
210
|
'-Command',
|
|
120
|
-
// ① [Console]::OutputEncoding 必须先设成 UTF-8:否则中文路径(例 D
|
|
211
|
+
// ① [Console]::OutputEncoding 必须先设成 UTF-8:否则中文路径(例 D:\某个中文目录)会以
|
|
121
212
|
// 控制台代码页(CP936)吐出来,Node 侧按 UTF-8 解码就变成乱码。
|
|
122
213
|
// ② -STA 是 WinForms 对话框的要求,缺了会直接抛。
|
|
123
214
|
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Windows.Forms | Out-Null; $d = New-Object System.Windows.Forms.FolderBrowserDialog; $d.Description = '选择要用项目人格的工作目录'; $d.ShowNewFolderButton = $true; if ($d.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($d.SelectedPath) }",
|
|
@@ -173,6 +264,34 @@ function recentSessionOf(ctx) {
|
|
|
173
264
|
}
|
|
174
265
|
}
|
|
175
266
|
|
|
267
|
+
/**
|
|
268
|
+
* 接口取 cwd 的唯一入口:三级兜底。
|
|
269
|
+
*
|
|
270
|
+
* 2026-10-29 真事故:这套兜底原来**只写在 /state 里**,其它路由各自
|
|
271
|
+
* `query.get('cwd') ?? ''` 就直接用。于是设置页拿不到会话 cwd 时:
|
|
272
|
+
*
|
|
273
|
+
* 概览 /state → 兜底到最近活跃会话 → 心情 80
|
|
274
|
+
* 详情 /mood → 拿到空串 → 落到 mood/global.json → 文件不存在 → 空白 70、七情全 0
|
|
275
|
+
*
|
|
276
|
+
* 同一个页面左边 80 右边 70,而且右边还显示「还没聊出变化」——
|
|
277
|
+
* 看起来像心情功能整个坏了,其实是读了两份不同的文件。
|
|
278
|
+
* 更糟的是 /mood/reset:用空 cwd 会把心情重置到一个从没用过的作用域上,
|
|
279
|
+
* 页面还看不见自己刚才重置的那份。
|
|
280
|
+
*
|
|
281
|
+
* 三级的顺序不能改:页面手选 > 最近活跃会话 > 最近一次注入记下的。
|
|
282
|
+
*/
|
|
283
|
+
function resolveCwd(ctx, query) {
|
|
284
|
+
const direct = String(query?.get?.('cwd') ?? '').trim()
|
|
285
|
+
if (direct !== '') return { cwd: direct, source: 'path' }
|
|
286
|
+
const recent = recentSessionOf(ctx)
|
|
287
|
+
if (recent !== '') return { cwd: recent, source: 'recent' }
|
|
288
|
+
const fallback = getFallbackCwd()
|
|
289
|
+
// 标 fallback 而不是 recent:这两条来源不同(一个是会话服务里捞的,一个是注入时记下的),
|
|
290
|
+
// 排查「设置页到底认了哪个目录」时混在一起会看不出走的哪条
|
|
291
|
+
if (fallback !== '') return { cwd: fallback, source: 'fallback' }
|
|
292
|
+
return { cwd: '', source: 'none' }
|
|
293
|
+
}
|
|
294
|
+
|
|
176
295
|
export function registerApi(ctx) {
|
|
177
296
|
const webServer = serviceOf(ctx, 'webServer')
|
|
178
297
|
if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
|
|
@@ -184,6 +303,39 @@ export function registerApi(ctx) {
|
|
|
184
303
|
kind: 'prefix',
|
|
185
304
|
path: API_PREFIX,
|
|
186
305
|
handler: async (req, res) => {
|
|
306
|
+
// ---- 跨源防护(CSRF) ----
|
|
307
|
+
// 这套接口没有任何鉴权:POST /persona 能改写人格注入内容,POST /open 能弹 explorer,
|
|
308
|
+
// POST /pick 能弹系统文件选择框。也就是说,你浏览器里随便一个恶意页面
|
|
309
|
+
// fetch('http://127.0.0.1:PORT/api/soul/persona', {method:'POST',...}) 就能改写她的魂。
|
|
310
|
+
//
|
|
311
|
+
// 判据只认「明确是外站」这一种:
|
|
312
|
+
// · 没带 Origin(同源导航、非浏览器客户端)→ 放行
|
|
313
|
+
// · Origin 是 'null'(sandboxed iframe / file:// 宿主)→ 放行,拒了会误伤本地 webview
|
|
314
|
+
// · Origin 是 http(s) 且 host 与本次请求的 Host 对不上 → 拒绝
|
|
315
|
+
// 这样挡掉网页端发起的跨站请求,又不至于把宿主自己锁在门外。
|
|
316
|
+
const origin = req.headers.origin
|
|
317
|
+
if (typeof origin === 'string' && origin !== '' && origin !== 'null') {
|
|
318
|
+
let crossed = false
|
|
319
|
+
try {
|
|
320
|
+
const parsed = new URL(origin)
|
|
321
|
+
const isHttp = parsed.protocol === 'http:' || parsed.protocol === 'https:'
|
|
322
|
+
// 非 http(s) 的来源(file://、app://、chrome-extension:// 等)都是本地宿主自己,
|
|
323
|
+
// 一律放行 —— 拒掉它们会把设置页锁在门外,那是比 CSRF 更糟的故障。
|
|
324
|
+
if (isHttp) {
|
|
325
|
+
const host = String(req.headers.host ?? '')
|
|
326
|
+
const isLocal = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '[::1]'
|
|
327
|
+
const samePort = parsed.port === String(host).split(':')[1]
|
|
328
|
+
crossed = !(host !== '' && (parsed.host === host || (isLocal && samePort)))
|
|
329
|
+
}
|
|
330
|
+
} catch {
|
|
331
|
+
crossed = true // Origin 都解析不了,不认
|
|
332
|
+
}
|
|
333
|
+
if (crossed) {
|
|
334
|
+
note('api', `拒绝跨源请求:Origin=${origin} Host=${String(req.headers.host ?? '')}`)
|
|
335
|
+
return json(res, 403, { ok: false, error: '跨源请求被拒绝' })
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
187
339
|
const url = (req.url ?? '').split('?')[0]
|
|
188
340
|
const route = url.slice(API_PREFIX.length) || '/'
|
|
189
341
|
const query = new URLSearchParams((req.url ?? '').split('?')[1] ?? '')
|
|
@@ -262,23 +414,19 @@ export function registerApi(ctx) {
|
|
|
262
414
|
// cwd 三级兜底(学 dsh-agent-md):设置页是全局弹层,某些 DSH 版本
|
|
263
415
|
// 不给 settings.section 传会话 cwd,光靠 query 会整块灰死。
|
|
264
416
|
// ① 页面显式传的(宿主 props 或用户手选) ② 最近活跃的会话 ③ 最近一次注入记下的
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
417
|
+
// 三级兜底抽到 resolveCwd 里了 —— 这套逻辑以前只属于本路由,
|
|
418
|
+
// /mood 那边没有,于是概览和详情读到了两份不同的心情文件
|
|
419
|
+
const cwdPick = resolveCwd(ctx, query)
|
|
420
|
+
const cwd = cwdPick.cwd
|
|
421
|
+
const cwdSource = cwdPick.source
|
|
422
|
+
// 设置页每 20 秒轮询一次 /state —— 不能每次都往 projects.json 写一遍:
|
|
423
|
+
// 那会不停刷 lastSeen、改 active、重排顺序,纯属无谓写盘。
|
|
424
|
+
// 只有「这个工作区还没登记过」才补登;切换 active 走 POST /register。
|
|
425
|
+
if (cwd !== '') {
|
|
426
|
+
const key = normalizePathKey(cwd)
|
|
427
|
+
const known = listWorkspaces().some((item) => normalizePathKey(item?.cwd) === key)
|
|
428
|
+
if (!known) registerProject(cwd, { active: true })
|
|
273
429
|
}
|
|
274
|
-
if (cwd === '') {
|
|
275
|
-
const fallback = getFallbackCwd()
|
|
276
|
-
if (fallback !== '') {
|
|
277
|
-
cwd = fallback
|
|
278
|
-
cwdSource = 'recent'
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
if (cwd !== '') registerProject(cwd, { active: true })
|
|
282
430
|
const config = loadConfig()
|
|
283
431
|
const persona = composePersona({ cwd, config })
|
|
284
432
|
const stats = memoryStats(cwd, config)
|
|
@@ -349,6 +497,7 @@ export function registerApi(ctx) {
|
|
|
349
497
|
label: moodLabel(s.mood),
|
|
350
498
|
face: moodFace(s.mood),
|
|
351
499
|
dims: displayDims(s),
|
|
500
|
+
dimsPercent: displayDimPercents(s),
|
|
352
501
|
top: topDims(s),
|
|
353
502
|
lastReason: s.lastReason,
|
|
354
503
|
updatedAt: s.updatedAt,
|
|
@@ -359,7 +508,21 @@ export function registerApi(ctx) {
|
|
|
359
508
|
workspaces: listWorkspaces(),
|
|
360
509
|
purpose: { ...purpose, goals: openGoals(purposeState(), { limit: 10 }) },
|
|
361
510
|
facts: MEMORY_FACTS,
|
|
362
|
-
dirs: { log: 'agents/soul.log' }
|
|
511
|
+
dirs: { log: 'agents/soul.log' },
|
|
512
|
+
// 2026-10-31:概览页「最近」那张卡要看昨天那篇写没写。
|
|
513
|
+
// 只报状态,不读正文 —— 私密那篇的正文不该出现在概览里。
|
|
514
|
+
diary: (() => {
|
|
515
|
+
const y = yesterdayKey(Date.now())
|
|
516
|
+
const t = todayKey(Date.now())
|
|
517
|
+
return {
|
|
518
|
+
today: t,
|
|
519
|
+
yesterday: y,
|
|
520
|
+
yesterdayPublic: exists(diaryPublicPath(y)),
|
|
521
|
+
yesterdayPrivate: exists(diaryPrivatePath(y)),
|
|
522
|
+
// 两篇都算写完才算「已写」
|
|
523
|
+
yesterdayDone: exists(diaryPublicPath(y)) && exists(diaryPrivatePath(y))
|
|
524
|
+
}
|
|
525
|
+
})()
|
|
363
526
|
})
|
|
364
527
|
}
|
|
365
528
|
|
|
@@ -367,14 +530,15 @@ export function registerApi(ctx) {
|
|
|
367
530
|
if (route === '/config' && req.method === 'POST') {
|
|
368
531
|
const body = await readBody(req)
|
|
369
532
|
const next = saveConfig(body?.config ?? body ?? {})
|
|
370
|
-
note('api', `配置已保存:mode=${next.mode} 记忆预算=${next.injectMaxChars}`)
|
|
533
|
+
note('api', `配置已保存:mode=${next.mode} 记忆预算=${next.injectMaxChars} 相关区=${next.memoryRecall !== false ? `开(${next.memoryRecallTopK ?? 6})` : '关'}`)
|
|
371
534
|
return json(res, 200, { ok: true, config: next })
|
|
372
535
|
}
|
|
373
536
|
|
|
374
537
|
// ---- 列记忆 ----
|
|
375
538
|
if (route === '/memory' && req.method === 'GET') {
|
|
376
539
|
const scope = query.get('scope') === 'project' ? 'project' : 'global'
|
|
377
|
-
|
|
540
|
+
// 列记忆也要跟着当前工作区走,否则「项目记忆」会永远显示空
|
|
541
|
+
const { cwd } = resolveCwd(ctx, query)
|
|
378
542
|
const keyword = (query.get('query') ?? '').trim().toLowerCase()
|
|
379
543
|
const card = scope === 'project' && cwd !== '' ? projectCard(cwd) : globalCard()
|
|
380
544
|
let records = [...card.records].sort((a, b) => (b.importance ?? 0) - (a.importance ?? 0))
|
|
@@ -406,16 +570,26 @@ export function registerApi(ctx) {
|
|
|
406
570
|
if (route === '/memory' && req.method === 'POST') {
|
|
407
571
|
const body = await readBody(req)
|
|
408
572
|
const scope = body?.scope === 'project' ? 'project' : 'global'
|
|
409
|
-
|
|
573
|
+
// 必须和 GET /memory 用同一套兜底。
|
|
574
|
+
// 原来这里直接 String(body?.cwd ?? ''):设置页拿不到会话 cwd 时,
|
|
575
|
+
// 列表走兜底读到项目卡、显示得出来,删除却按空 cwd 去查全局卡 ——
|
|
576
|
+
// 全局卡是空的,于是永远「没找到这条记忆」。删 / 固定 / 编辑都一样。
|
|
577
|
+
const given = String(body?.cwd ?? '').trim()
|
|
578
|
+
const cwd = given !== '' ? given : resolveCwd(ctx, query).cwd
|
|
410
579
|
const card = scope === 'project' && cwd !== '' ? projectCard(cwd) : globalCard()
|
|
411
580
|
const action = String(body?.action ?? '')
|
|
412
581
|
const id = String(body?.id ?? '')
|
|
413
582
|
|
|
414
583
|
if (action === 'delete') {
|
|
415
|
-
|
|
416
|
-
|
|
584
|
+
// 传 archive:设置页点删除也算「遗忘」,要能在 archive.jsonl 里查回来
|
|
585
|
+
const removed = forgetRecord(card, id, makeArchiver(archivePath()))
|
|
586
|
+
if (removed === null) {
|
|
587
|
+
note('api', `删除落空:scope=${scope} cwd=「${cwd}」卡里 ${card.records.length} 条,找不到 id=${id}`)
|
|
588
|
+
return json(res, 404, { ok: false, error: '没找到这条记忆' })
|
|
589
|
+
}
|
|
417
590
|
} else if (action === 'pin') {
|
|
418
591
|
if (!setPinned(card, id, body?.pinned !== false)) {
|
|
592
|
+
note('api', `固定落空:scope=${scope} cwd=「${cwd}」卡里 ${card.records.length} 条,找不到 id=${id}`)
|
|
419
593
|
return json(res, 404, { ok: false, error: '没找到这条记忆' })
|
|
420
594
|
}
|
|
421
595
|
} else if (action === 'write') {
|
|
@@ -441,14 +615,16 @@ export function registerApi(ctx) {
|
|
|
441
615
|
// ---- 手动维护 ----
|
|
442
616
|
if (route === '/maintain' && req.method === 'POST') {
|
|
443
617
|
const body = await readBody(req)
|
|
444
|
-
const
|
|
618
|
+
const given = String(body?.cwd ?? '').trim()
|
|
619
|
+
const cwd = given !== '' ? given : resolveCwd(ctx, query).cwd
|
|
445
620
|
const report = maintain(cwd, loadConfig())
|
|
446
621
|
return json(res, 200, { ok: true, report })
|
|
447
622
|
}
|
|
448
623
|
|
|
449
624
|
// ---- 心情:读全量(值 + 七情 + 时间线) ----
|
|
450
625
|
if (route === '/mood' && req.method === 'GET') {
|
|
451
|
-
|
|
626
|
+
// 必须和 /state 用同一套兜底,否则详情页和概览页读的是两份文件
|
|
627
|
+
const { cwd } = resolveCwd(ctx, query)
|
|
452
628
|
const cfg = loadConfig()
|
|
453
629
|
const s = moodState(cwd)
|
|
454
630
|
return json(res, 200, {
|
|
@@ -461,6 +637,7 @@ export function registerApi(ctx) {
|
|
|
461
637
|
label: moodLabel(s.mood),
|
|
462
638
|
face: moodFace(s.mood),
|
|
463
639
|
dims: displayDims(s),
|
|
640
|
+
dimsPercent: displayDimPercents(s),
|
|
464
641
|
top: topDims(s),
|
|
465
642
|
lastReason: s.lastReason,
|
|
466
643
|
lastConfidence: s.lastConfidence,
|
|
@@ -486,7 +663,10 @@ export function registerApi(ctx) {
|
|
|
486
663
|
// ---- 心情:重置 ----
|
|
487
664
|
if (route === '/mood/reset' && req.method === 'POST') {
|
|
488
665
|
const body = await readBody(req)
|
|
489
|
-
const
|
|
666
|
+
const given = String(body?.cwd ?? '').trim()
|
|
667
|
+
// 页面没给 cwd 就按当前工作区兜底:不然会把心情重置到一个从没用过的作用域上,
|
|
668
|
+
// 页面还看不见自己刚重置的那份(表现为「点了重置却没反应」)
|
|
669
|
+
const cwd = given !== '' ? given : resolveCwd(ctx, query).cwd
|
|
490
670
|
const s = resetMood(cwd)
|
|
491
671
|
note('api', `心情已重置(cwd=${cwd || '全局'})→ ${Math.round(s.mood)}`)
|
|
492
672
|
return json(res, 200, { ok: true, mood: Math.round(s.mood) })
|
|
@@ -495,12 +675,14 @@ export function registerApi(ctx) {
|
|
|
495
675
|
// ---- 心情:手动跑一次时间衰减(页面刷新时用,幂等) ----
|
|
496
676
|
if (route === '/mood/decay' && req.method === 'POST') {
|
|
497
677
|
const body = await readBody(req)
|
|
498
|
-
const
|
|
678
|
+
const given = String(body?.cwd ?? '').trim()
|
|
679
|
+
const cwd = given !== '' ? given : resolveCwd(ctx, query).cwd
|
|
499
680
|
const s = decayMoodFor(cwd)
|
|
500
681
|
return json(res, 200, {
|
|
501
682
|
ok: true,
|
|
502
683
|
mood: Math.round(s.mood),
|
|
503
684
|
dims: displayDims(s),
|
|
685
|
+
dimsPercent: displayDimPercents(s),
|
|
504
686
|
lastReason: s.lastReason,
|
|
505
687
|
updatedAt: s.updatedAt
|
|
506
688
|
})
|
|
@@ -540,6 +722,98 @@ export function registerApi(ctx) {
|
|
|
540
722
|
}
|
|
541
723
|
}
|
|
542
724
|
|
|
725
|
+
// ---- 日记:列表(只列公开日记的预览;私密内容不出服务器) ----
|
|
726
|
+
if (route === '/diary/list' && req.method === 'GET') {
|
|
727
|
+
const days = Math.min(30, Math.max(1, Math.round(Number(query.get('days')) || 14)))
|
|
728
|
+
const today = new Date()
|
|
729
|
+
today.setHours(0, 0, 0, 0)
|
|
730
|
+
const list = []
|
|
731
|
+
for (let i = 0; i < days; i++) {
|
|
732
|
+
const day = new Date(today.getTime() - i * 24 * 60 * 60 * 1000)
|
|
733
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
734
|
+
const dateStr = `${day.getFullYear()}-${pad(day.getMonth() + 1)}-${pad(day.getDate())}`
|
|
735
|
+
const publicFile = diaryPublicPath(dateStr)
|
|
736
|
+
const privateFile = diaryPrivatePath(dateStr)
|
|
737
|
+
const hasPublic = exists(publicFile)
|
|
738
|
+
const hasPrivate = exists(privateFile)
|
|
739
|
+
if (!hasPublic && !hasPrivate) continue
|
|
740
|
+
list.push({
|
|
741
|
+
date: dateStr,
|
|
742
|
+
hasPublic,
|
|
743
|
+
hasPrivate,
|
|
744
|
+
preview: hasPublic ? readText(publicFile).slice(0, 400) : '',
|
|
745
|
+
updatedAt: hasPublic ? statSync(publicFile).mtime.toISOString() : null
|
|
746
|
+
})
|
|
747
|
+
}
|
|
748
|
+
return json(res, 200, { ok: true, list })
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// ---- 日记:读取某一天(私密不出服务器,只返回存在性) ----
|
|
752
|
+
if (route === '/diary/read' && req.method === 'GET') {
|
|
753
|
+
const dateStr = String(query.get('date') ?? '').trim()
|
|
754
|
+
if (dateStr === '') return json(res, 400, { ok: false, error: '缺少 date 参数' })
|
|
755
|
+
const publicFile = diaryPublicPath(dateStr)
|
|
756
|
+
const privateFile = diaryPrivatePath(dateStr)
|
|
757
|
+
const hasPublic = exists(publicFile)
|
|
758
|
+
const hasPrivate = exists(privateFile)
|
|
759
|
+
return json(res, 200, {
|
|
760
|
+
ok: true,
|
|
761
|
+
date: dateStr,
|
|
762
|
+
hasPublic,
|
|
763
|
+
hasPrivate,
|
|
764
|
+
publicContent: hasPublic ? readText(publicFile) : '',
|
|
765
|
+
// 私密日记不出服务器,只告诉有没有
|
|
766
|
+
})
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// ---- 日记:读私密正文(2026-10-31;仅回环 + 显式开启) ----
|
|
770
|
+
// 默认 diaryPrivateVisible=false 时这里一律 403,行为和以前一样:
|
|
771
|
+
// 私密只报存在性,正文永不出服务器。开关打开也只对本机回环放行。
|
|
772
|
+
if (route === '/diary/private' && req.method === 'GET') {
|
|
773
|
+
const view = privateDiaryView(req, loadConfig())
|
|
774
|
+
return json(res, view.status, view.payload)
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// ---- 日记:绑定当前会话 / 清除绑定(2026-10-31) ----
|
|
778
|
+
// 为什么绑:agents.create 造出来的日记会话没有宿主的标准工具集,写不出文件。
|
|
779
|
+
// 只接受明确的会话 id;请求没带就取「最近更新的会话」(这台 DSH 的设置页
|
|
780
|
+
// 拿不到 sessionId,见 currentSessionIdOf 的注释)。
|
|
781
|
+
if (route === '/diary/bind' && req.method === 'POST') {
|
|
782
|
+
const body = await readBody(req)
|
|
783
|
+
let sessionId = String(body?.sessionId ?? '').trim()
|
|
784
|
+
const source = sessionId === '' ? 'recent' : 'client'
|
|
785
|
+
if (sessionId === '') sessionId = currentSessionIdOf(ctx)
|
|
786
|
+
if (sessionId === '') {
|
|
787
|
+
return json(res, 400, { ok: false, error: '拿不到当前会话 id:请求没带,会话服务里也没有可用会话' })
|
|
788
|
+
}
|
|
789
|
+
const next = saveConfig({ diarySessionId: sessionId })
|
|
790
|
+
note('api', `日记会话已绑定:${sessionId}(来源 ${source})`)
|
|
791
|
+
return json(res, 200, { ok: true, sessionId, source, config: next })
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
if (route === '/diary/unbind' && req.method === 'POST') {
|
|
795
|
+
const next = saveConfig({ diarySessionId: '' })
|
|
796
|
+
note('api', '日记会话绑定已清除')
|
|
797
|
+
return json(res, 200, { ok: true, sessionId: '', config: next })
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// ---- 手动触发日记 ----
|
|
801
|
+
if (route === '/diary' && req.method === 'POST') {
|
|
802
|
+
const body = await readBody(req)
|
|
803
|
+
const dateStr = String(body?.date ?? '').trim() || todayKey(Date.now())
|
|
804
|
+
const noteText = String(body?.note ?? '').trim()
|
|
805
|
+
const config = loadConfig()
|
|
806
|
+
if (config.diaryEnabled === false) {
|
|
807
|
+
return json(res, 403, { ok: false, error: '日记功能已关闭' })
|
|
808
|
+
}
|
|
809
|
+
const ok2 = await runDiaryOnce(ctx, dateStr, noteText || undefined)
|
|
810
|
+
return json(res, ok2 ? 200 : 500, {
|
|
811
|
+
ok: ok2,
|
|
812
|
+
date: dateStr,
|
|
813
|
+
message: ok2 ? '已触发日记写作' : '日记触发失败(无可用会话或 LLM 异常)'
|
|
814
|
+
})
|
|
815
|
+
}
|
|
816
|
+
|
|
543
817
|
return json(res, 404, { ok: false, error: `不认识的路由:${route}` })
|
|
544
818
|
} catch (error) {
|
|
545
819
|
const message = error instanceof Error ? error.message : String(error)
|
package/lib/client/api.js
CHANGED
|
@@ -42,6 +42,45 @@
|
|
|
42
42
|
return ''
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
/**
|
|
46
|
+
* 服务端兜底出来的工作区(/state 里带回来的)。
|
|
47
|
+
*
|
|
48
|
+
* 2026-10-29:本页拿不到会话 cwd 时,各标签页原来各自拿着空串去请求,
|
|
49
|
+
* 于是概览拿到 80、心情详情拿到空白 70 —— 同一个页面两个数字。
|
|
50
|
+
* 服务端已经兜过底了,页面就把这个结果沿用下去,保证各标签页看的是同一份。
|
|
51
|
+
*/
|
|
52
|
+
function serverCwdOf(props) {
|
|
53
|
+
var ws = props && props.state && props.state.workspace
|
|
54
|
+
return ws && typeof ws.cwd === 'string' ? ws.cwd : ''
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 当前标签页该用的 cwd:页面自己有的优先,没有就沿用服务端兜底的那个。 */
|
|
58
|
+
function cwdWithFallback(props) {
|
|
59
|
+
var own = cwdOf(props)
|
|
60
|
+
return own !== '' ? own : serverCwdOf(props)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 当前会话 id(2026-10-31)。
|
|
65
|
+
*
|
|
66
|
+
* 设置页是全局弹层,这个 DSH 版本的 renderSlot('settings.section') 只传
|
|
67
|
+
* { close },所以 props 里通常没有会话;拿不到就返回空串,由后端
|
|
68
|
+
* /diary/bind 兜底成「最近更新的会话」,绑定结果会回显 id 供核对。
|
|
69
|
+
*/
|
|
70
|
+
function sessionIdOf(props) {
|
|
71
|
+
var p = props || {}
|
|
72
|
+
var candidates = [
|
|
73
|
+
p.sessionId,
|
|
74
|
+
p.session && p.session.header && p.session.header.id,
|
|
75
|
+
p.session && p.session.id,
|
|
76
|
+
p.agent && p.agent.session && p.agent.session.header && p.agent.session.header.id,
|
|
77
|
+
]
|
|
78
|
+
for (var i = 0; i < candidates.length; i += 1) {
|
|
79
|
+
if (typeof candidates[i] === 'string' && candidates[i] !== '') return candidates[i]
|
|
80
|
+
}
|
|
81
|
+
return ''
|
|
82
|
+
}
|
|
83
|
+
|
|
45
84
|
/** ISO 时间 → 「10月26日 12:48」(设置页文件栏用)。 */
|
|
46
85
|
function timeLabel(iso) {
|
|
47
86
|
if (!iso) return ''
|
package/lib/client/app.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
var [error, setError] = useState('')
|
|
10
10
|
// 手选工作区覆盖:设置页是全局弹层,宿主经常不给 cwd —— 用户从下拉/任意目录挑一个后,全页跟着切
|
|
11
11
|
var [cwdOverride, setCwdOverride] = useState('')
|
|
12
|
-
var cwd = cwdOverride !== '' ? cwdOverride :
|
|
12
|
+
var cwd = cwdOverride !== '' ? cwdOverride : cwdWithFallback(props)
|
|
13
13
|
|
|
14
14
|
var reload = useCallback(function () {
|
|
15
15
|
apiGet('/state' + (cwd ? '?cwd=' + encodeURIComponent(cwd) : ''))
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
['memory', '记忆'],
|
|
26
26
|
['purpose', '目的'],
|
|
27
27
|
['mood', '心情'],
|
|
28
|
+
['diary', '日记'],
|
|
28
29
|
['settings', '设置'],
|
|
29
30
|
]
|
|
30
31
|
|
|
@@ -71,6 +72,7 @@
|
|
|
71
72
|
tab === 'memory' ? h(MemoryTab, { cwd: cwd, config: state && state.config, reload: reload }) : null,
|
|
72
73
|
tab === 'purpose' ? h(PurposeTab, { state: state, cwd: cwd, reload: reload }) : null,
|
|
73
74
|
tab === 'mood' ? h(MoodTab, { cwd: cwd, state: state, reload: reload }) : null,
|
|
75
|
+
tab === 'diary' ? h(DiaryTab, { state: state, reload: reload, sessionId: sessionIdOf(props) }) : null,
|
|
74
76
|
tab === 'settings' ? h(SettingsTab, { state: state, cwd: cwd, reload: reload }) : null
|
|
75
77
|
)
|
|
76
78
|
)
|