dsh-ta 0.2.0 → 0.4.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +111 -1
  2. package/README.md +325 -140
  3. package/cordis.patch.yml +5 -35
  4. package/docs/RELEASE.md +63 -46
  5. package/docs/USAGE.md +25 -9
  6. package/docs/presets.example.yml +7 -43
  7. package/index.js +3 -170
  8. package/locale/en.json +1 -1
  9. package/locale/zh.json +1 -1
  10. package/package.json +6 -19
  11. package/src/client/client.js +3176 -0
  12. package/{config.js → src/host/config.js} +39 -4
  13. package/src/host/constants.js +7 -0
  14. package/src/host/gates.js +34 -0
  15. package/src/host/identity.js +145 -0
  16. package/{im → src/host/im}/bindings.js +1 -1
  17. package/src/host/index.js +173 -0
  18. package/{jurisdiction.js → src/host/jurisdiction.js} +1 -1
  19. package/src/host/maintenance/collect.js +362 -0
  20. package/src/host/maintenance/completions.js +56 -0
  21. package/src/host/maintenance/consumption.js +67 -0
  22. package/src/host/maintenance/cursors.js +53 -0
  23. package/src/host/maintenance/engine.js +392 -0
  24. package/src/host/maintenance/llm.js +381 -0
  25. package/src/host/maintenance/lock.js +105 -0
  26. package/src/host/maintenance/prompts.js +255 -0
  27. package/src/host/maintenance/runs.js +47 -0
  28. package/src/host/maintenance/schedule.js +173 -0
  29. package/src/host/maintenance/session-cleanup.js +289 -0
  30. package/src/host/maintenance/session-watcher.js +107 -0
  31. package/src/host/maintenance/sleep.js +3 -0
  32. package/src/host/maintenance/stages.js +241 -0
  33. package/src/host/maintenance/state.js +192 -0
  34. package/src/host/prompts.js +96 -0
  35. package/src/host/records.js +175 -0
  36. package/{reme.js → src/host/reme.js} +3 -1
  37. package/src/host/runtime-manager.js +281 -0
  38. package/{runtime.js → src/host/runtime.js} +28 -50
  39. package/src/host/settings/defaults.js +55 -0
  40. package/src/host/settings/errors.js +29 -0
  41. package/src/host/settings/home.js +316 -0
  42. package/src/host/settings/http.js +164 -0
  43. package/src/host/settings/im.js +148 -0
  44. package/src/host/settings/lifecycle.js +373 -0
  45. package/src/host/settings/persona.js +113 -0
  46. package/src/host/settings/routes.js +229 -0
  47. package/src/host/settings/status.js +192 -0
  48. package/src/host/state/appraisals.js +56 -0
  49. package/src/host/state/feel.js +78 -0
  50. package/src/host/state/index.js +9 -0
  51. package/src/host/state/mood.js +103 -0
  52. package/src/host/state/notes.js +18 -0
  53. package/{life.js → src/host/state/outing.js} +13 -136
  54. package/src/host/state/values.js +9 -0
  55. package/{stickers → src/host/stickers}/tool.js +1 -1
  56. package/src/host/storage/fs.js +29 -0
  57. package/src/host/storage/index.js +8 -0
  58. package/src/host/storage/paths.js +20 -0
  59. package/src/host/storage/revision.js +5 -0
  60. package/src/host/storage/session-state.js +38 -0
  61. package/src/host/storage/time.js +127 -0
  62. package/src/host/tools/index.js +152 -0
  63. package/src/host/tools/read.js +252 -0
  64. package/src/host/tools/shared.js +23 -0
  65. package/src/host/tools/wiki.js +35 -0
  66. package/src/host/tools/write.js +164 -0
  67. package/{usage → src/host/usage}/aggregate.js +4 -1
  68. package/src/host/usage/ledger.js +186 -0
  69. package/src/host/usage/serve.js +116 -0
  70. package/client.js +0 -618
  71. package/gates.js +0 -18
  72. package/identity.js +0 -97
  73. package/prompts.js +0 -28
  74. package/storage.js +0 -95
  75. package/tools.js +0 -540
  76. package/usage/ledger.js +0 -126
  77. package/usage/serve.js +0 -38
  78. /package/{im → src/host/im}/say.js +0 -0
  79. /package/{memory → src/host/memory}/capture.js +0 -0
  80. /package/{memory → src/host/memory}/messages.js +0 -0
  81. /package/{memory → src/host/memory}/outbox.js +0 -0
  82. /package/{stickers → src/host/stickers}/load.js +0 -0
  83. /package/{stickers → src/host/stickers}/select.js +0 -0
  84. /package/{stickers → src/host/stickers}/serve.js +0 -0
  85. /package/{usage → src/host/usage}/pricing.js +0 -0
@@ -0,0 +1,229 @@
1
+ /**
2
+ * 设置页 Host 路由:统一前缀 /api/dsh-ta。
3
+ *
4
+ * 这里只做 HTTP 适配(方法、JSON body、64 KiB 上限、错误映射),
5
+ * 业务逻辑全部放在 settings/ 与 maintenance/ 下的模块里;dispatch() 不写 HTTP,
6
+ * 测试和真实请求共用同一套分发逻辑。
7
+ */
8
+
9
+ import { SettingsError, badRequest, conflict } from './errors.js'
10
+ import { readPersona, writePersonaField } from './persona.js'
11
+ import { readStatus } from './status.js'
12
+ import { readImState } from './im.js'
13
+ import { editConfigValues, initializeHome, reincarnate } from './lifecycle.js'
14
+ import { acceptSoulProposal, readProposals, rejectSoulProposal } from '../records.js'
15
+ import { latestRun } from '../maintenance/runs.js'
16
+ import { readMaintenanceState } from '../maintenance/state.js'
17
+
18
+ export const ROOT = '/api/dsh-ta'
19
+
20
+ function notFoundRoute() {
21
+ return new SettingsError(404, 'NOT_FOUND', '未知的设置接口')
22
+ }
23
+
24
+ function addressFromBody(body) {
25
+ if (body?.addressAs === undefined) return ''
26
+ if (typeof body.addressAs !== 'string') throw badRequest('ADDRESS_INVALID', '称呼必须是文本')
27
+ const line = body.addressAs.split(/\r?\n/)[0].trim()
28
+ if (line.length > 40) throw badRequest('ADDRESS_TOO_LONG', '称呼最多 40 字')
29
+ return line
30
+ }
31
+
32
+ function mapRecordError(error) {
33
+ if (error?.code === 'PROPOSAL_NOT_FOUND') return new SettingsError(404, 'PROPOSAL_NOT_FOUND', error.message)
34
+ if (error?.code === 'PROPOSAL_CLOSED') return conflict('PROPOSAL_CLOSED', error.message)
35
+ if (error?.code === 'PROPOSAL_STALE') return conflict('PROPOSAL_STALE', error.message)
36
+ throw error
37
+ }
38
+
39
+ const ROUTES = [
40
+ {
41
+ pattern: /^\/status$/,
42
+ allow: ['GET'],
43
+ run: host => readStatus(host),
44
+ },
45
+ {
46
+ pattern: /^\/persona$/,
47
+ allow: ['GET', 'PUT'],
48
+ run: (host, { method, body }) => {
49
+ if (method === 'GET') return readPersona(host.config)
50
+ const write = () => {
51
+ if (body?.field !== 'soul') {
52
+ throw badRequest('PERSONA_FIELD_INVALID', '人设页只编辑 SOUL.md;完整请求体是 {field:"soul", content, revision}')
53
+ }
54
+ return writePersonaField(host.config, body)
55
+ }
56
+ // 与生命周期写操作共用同一个串行队列,避免“边删边写”。
57
+ return typeof host?.queue === 'function' ? host.queue(write) : write()
58
+ },
59
+ },
60
+ {
61
+ pattern: /^\/settings\/address$/,
62
+ allow: ['GET', 'PUT'],
63
+ run: async (host, { method, body }) => {
64
+ if (method === 'GET') return { addressAs: host.config.addressAs ?? '' }
65
+ const addressAs = addressFromBody(body)
66
+ await editConfigValues(host, { addressAs })
67
+ return { addressAs }
68
+ },
69
+ },
70
+ {
71
+ pattern: /^\/soul-proposals$/,
72
+ allow: ['GET'],
73
+ run: host => {
74
+ const proposals = readProposals(host.config)
75
+ return {
76
+ pending: proposals.filter(item => item.status === 'pending').length,
77
+ proposals,
78
+ }
79
+ },
80
+ },
81
+ {
82
+ pattern: /^\/soul-proposals\/([^/]+)\/accept$/,
83
+ allow: ['POST'],
84
+ run: (host, { params, body }) => {
85
+ try {
86
+ const result = acceptSoulProposal(host.config, decodeURIComponent(params[0]), { revision: body?.revision })
87
+ return { accepted: true, proposal: result.proposal, revision: result.revision }
88
+ } catch (error) {
89
+ throw mapRecordError(error)
90
+ }
91
+ },
92
+ },
93
+ {
94
+ pattern: /^\/soul-proposals\/([^/]+)\/reject$/,
95
+ allow: ['POST'],
96
+ run: (host, { params }) => {
97
+ try {
98
+ return { rejected: true, proposal: rejectSoulProposal(host.config, decodeURIComponent(params[0])) }
99
+ } catch (error) {
100
+ throw mapRecordError(error)
101
+ }
102
+ },
103
+ },
104
+ {
105
+ pattern: /^\/maintenance\/run$/,
106
+ allow: ['POST'],
107
+ status: 202,
108
+ run: (host, { body }) => {
109
+ const result = host?.runtime?.runMaintenanceNow?.({
110
+ reason: 'manual',
111
+ forceProfile: body?.forceProfile === true,
112
+ })
113
+ if (!result?.started) {
114
+ throw conflict('MAINTENANCE_NOT_STARTED', `维护没有启动:${result?.reason ?? 'unknown'}`)
115
+ }
116
+ return { started: true, runId: result.runId, runDate: result.runDate }
117
+ },
118
+ },
119
+ {
120
+ pattern: /^\/runs\/latest$/,
121
+ allow: ['GET'],
122
+ run: host => ({
123
+ run: latestRun(host.config),
124
+ state: host?.runtime?.maintenanceStatus?.() ?? readMaintenanceState(host.config),
125
+ }),
126
+ },
127
+ {
128
+ pattern: /^\/integrations$/,
129
+ allow: ['GET'],
130
+ run: async host => {
131
+ const status = await readStatus(host)
132
+ return {
133
+ reme: status?.reme,
134
+ im: status?.im ?? readImState(host.config),
135
+ }
136
+ },
137
+ },
138
+ {
139
+ pattern: /^\/home\/init$/,
140
+ allow: ['POST'],
141
+ run: (host, { body }) => initializeHome(host, body),
142
+ },
143
+ {
144
+ pattern: /^\/lifecycle\/reincarnate$/,
145
+ allow: ['POST'],
146
+ run: (host, { body }) => reincarnate(host, body),
147
+ },
148
+ ]
149
+
150
+ function methodNotAllowedError(allow) {
151
+ const error = new SettingsError(405, 'METHOD_NOT_ALLOWED', `该接口只支持 ${allow.join('、')}`)
152
+ error.allow = allow
153
+ return error
154
+ }
155
+
156
+ export function normalizeMethod(method) {
157
+ return typeof method === 'string' && method.trim() ? method.trim().toUpperCase() : 'GET'
158
+ }
159
+
160
+ /** 把 /api/dsh-ta/xxx 或 /xxx 统一成 /xxx,忽略末尾斜杠和查询串。 */
161
+ function canonicalPath(pathname) {
162
+ let suffix = pathname
163
+ if (suffix === ROOT) suffix = '/'
164
+ else if (suffix.startsWith(ROOT + '/')) suffix = suffix.slice(ROOT.length)
165
+ suffix = suffix.replace(/\/+$/, '')
166
+ if (!suffix) return '/'
167
+ return suffix.startsWith('/') ? suffix : `/${suffix}`
168
+ }
169
+
170
+ /** HTTP 侧:必须落在 /api/dsh-ta 前缀内。 */
171
+ export function parseHttpPath(rawUrl) {
172
+ let pathname
173
+ try {
174
+ pathname = new URL(rawUrl ?? '/', 'http://localhost').pathname
175
+ } catch {
176
+ throw badRequest('INVALID_REQUEST_PATH', '请求路径不合法')
177
+ }
178
+ if (pathname !== ROOT && !pathname.startsWith(ROOT + '/')) throw notFoundRoute()
179
+ return canonicalPath(pathname)
180
+ }
181
+
182
+ /** dispatch 侧:允许直接传 /status,也允许带完整前缀。 */
183
+ function normalizeDispatchPath(rawPath) {
184
+ let pathname
185
+ try {
186
+ pathname = new URL(String(rawPath ?? '/'), 'http://localhost').pathname
187
+ } catch {
188
+ throw notFoundRoute()
189
+ }
190
+ return canonicalPath(pathname)
191
+ }
192
+
193
+ export function findRoute(path) {
194
+ for (const route of ROUTES) {
195
+ const match = route.pattern.exec(path)
196
+ if (match) return { route, params: match.slice(1) }
197
+ }
198
+ throw notFoundRoute()
199
+ }
200
+
201
+ export function assertAllowed(route, method) {
202
+ if (!route.allow.includes(method)) throw methodNotAllowedError(route.allow)
203
+ }
204
+
205
+ function assertBodyObject(method, body) {
206
+ if (method !== 'POST' && method !== 'PUT') return
207
+ if (body === undefined || body === null || typeof body !== 'object' || Array.isArray(body)) {
208
+ throw badRequest('INVALID_BODY', '请求体必须是 JSON 对象')
209
+ }
210
+ }
211
+
212
+ /**
213
+ * 测试与 HTTP 共用入口。
214
+ * 成功返回 { status, payload };预期错误抛 SettingsError,未知异常原样抛出,
215
+ * 由 HTTP 适配层统一记录并映射成 500。
216
+ */
217
+ export async function dispatch(host, { method, path, body } = {}) {
218
+ const verb = normalizeMethod(method)
219
+ const routePath = normalizeDispatchPath(path)
220
+ const { route, params } = findRoute(routePath)
221
+ assertAllowed(route, verb)
222
+ assertBodyObject(verb, body)
223
+ // 转生期间暂停其他写入,避免切换中的家被并发修改。
224
+ if (host?.lifecycle?.operation && (verb === 'PUT' || verb === 'POST')) {
225
+ throw conflict('LIFECYCLE_BUSY', 'TA 正在转生中,请稍候再试')
226
+ }
227
+ const data = await route.run(host, { method: verb, body, params })
228
+ return { status: route.status ?? 200, payload: { ok: true, data } }
229
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * 设置页状态聚合:四件套、维护、SOUL 建议、IM。
3
+ *
4
+ * 状态全部从文件、配置与 im-connect 派生,不写任何状态文件。
5
+ * ReMe 健康检查最多等 1.5s,任何失败都降级为状态值,不向上抛错。
6
+ */
7
+
8
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { coreFileSummary } from '../identity.js'
11
+ import { isWritableDirectory, readTextIfExists } from '../storage/index.js'
12
+ import { readHomeMarker } from './home.js'
13
+ import { readImState, imModeFor } from './im.js'
14
+ import { readMaintenanceState } from '../maintenance/state.js'
15
+ import { readRuns } from '../maintenance/runs.js'
16
+
17
+ const REME_TIMEOUT_MS = 1500
18
+ const DIARY_FILE_PATTERN = /^(\d{4}-\d{2}-\d{2})\.md$/
19
+
20
+ function now() {
21
+ return new Date().toISOString()
22
+ }
23
+
24
+ function isDirectory(path) {
25
+ if (typeof path !== 'string' || path.length === 0) return false
26
+ try {
27
+ return statSync(path).isDirectory()
28
+ } catch {
29
+ return false
30
+ }
31
+ }
32
+
33
+ /** ReMe 健康检查:POST /health_check,兼容 success / metadata.health / answer 三种成功标志。 */
34
+ async function checkReme(config) {
35
+ const endpoint = String(config?.remeEndpoint ?? '').replace(/\/+$/, '')
36
+ if (!endpoint) {
37
+ return { state: 'disconnected', endpoint, checkedAt: now(), message: '尚未配置 ReMe 地址' }
38
+ }
39
+ const controller = new AbortController()
40
+ const timer = setTimeout(() => controller.abort(), REME_TIMEOUT_MS)
41
+ try {
42
+ const response = await fetch(`${endpoint}/health_check`, {
43
+ method: 'POST',
44
+ headers: { 'content-type': 'application/json' },
45
+ body: '{}',
46
+ signal: controller.signal,
47
+ })
48
+ if (!response.ok) {
49
+ return { state: 'error', endpoint, checkedAt: now(), message: `ReMe 健康检查失败:HTTP ${response.status}` }
50
+ }
51
+ let data
52
+ try {
53
+ data = await response.json()
54
+ } catch {
55
+ return { state: 'error', endpoint, checkedAt: now(), message: 'ReMe 健康检查返回的内容不是 JSON' }
56
+ }
57
+ if (data?.success === false || data?.metadata?.health?.healthy === false) {
58
+ const detail = typeof data?.error === 'string' && data.error ? data.error : ''
59
+ return {
60
+ state: 'error',
61
+ endpoint,
62
+ checkedAt: now(),
63
+ message: detail ? `ReMe 报告异常:${detail}` : 'ReMe 报告自身不健康',
64
+ }
65
+ }
66
+ if (data?.success === true || data?.metadata?.health?.healthy === true || typeof data?.answer === 'string') {
67
+ return { state: 'connected', endpoint, checkedAt: now() }
68
+ }
69
+ return { state: 'error', endpoint, checkedAt: now(), message: 'ReMe 健康检查返回无法识别的响应' }
70
+ } catch {
71
+ return {
72
+ state: 'disconnected',
73
+ endpoint,
74
+ checkedAt: now(),
75
+ message: controller.signal.aborted ? 'ReMe 健康检查超时' : '无法连接 ReMe',
76
+ }
77
+ } finally {
78
+ clearTimeout(timer)
79
+ }
80
+ }
81
+
82
+ function generatedState(home) {
83
+ const empty = { diaryCount: 0, latestDiary: null }
84
+ if (!home) return empty
85
+ let diaryCount = 0
86
+ let latestDiary = null
87
+ try {
88
+ for (const entry of readdirSync(join(home, 'diary'), { withFileTypes: true })) {
89
+ if (!entry.isFile()) continue
90
+ const match = DIARY_FILE_PATTERN.exec(entry.name)
91
+ if (!match) continue
92
+ diaryCount += 1
93
+ if (latestDiary === null || match[1] > latestDiary) latestDiary = match[1]
94
+ }
95
+ } catch {
96
+ /* 没有日记目录就按 0 篇处理 */
97
+ }
98
+ return { diaryCount, latestDiary }
99
+ }
100
+
101
+ function pendingProposalCount(config, home) {
102
+ try {
103
+ const text = readFileSync(join(home, 'state/soul-proposals.jsonl'), 'utf8')
104
+ let count = 0
105
+ for (const line of text.split(/\r?\n/)) {
106
+ if (!line.trim()) continue
107
+ try {
108
+ const value = JSON.parse(line)
109
+ if (value && value.status !== 'accepted' && value.status !== 'rejected') count += 1
110
+ } catch {
111
+ /* 损坏行忽略 */
112
+ }
113
+ }
114
+ return count
115
+ } catch {
116
+ return 0
117
+ }
118
+ }
119
+
120
+ function imState(config) {
121
+ try {
122
+ const state = readImState(config)
123
+ const dmBindings = (state.accounts ?? []).filter(account => account.bound === true).length
124
+ const mode = imModeFor(config)
125
+ return {
126
+ ...state,
127
+ dmBindings,
128
+ mode,
129
+ warning: dmBindings > 1
130
+ ? '检测到多个 IM 私聊绑定;已自动降级为 reduced(IM 不注入 self/RECENT/认识)'
131
+ : (state.compatible === false && state.installed ? 'IM 配置与 TA 家不一致' : undefined),
132
+ }
133
+ } catch {
134
+ return { installed: false, compatible: false, accounts: [], dmBindings: 0, mode: 'owner', error: '无法读取 IM 连接状态' }
135
+ }
136
+ }
137
+
138
+ function maintenanceState(config, host) {
139
+ let runtimeStatus = null
140
+ try {
141
+ runtimeStatus = host?.runtime?.maintenanceStatus?.() ?? null
142
+ } catch {
143
+ runtimeStatus = null
144
+ }
145
+ const stored = readMaintenanceState(config)
146
+ const latest = readRuns(config).at(-1) ?? null
147
+ return {
148
+ enabled: config?.maintenanceEnabled === true,
149
+ time: config?.maintenanceTime ?? '23:00',
150
+ weeklyDay: config?.weeklyDay ?? 0,
151
+ running: runtimeStatus?.running ?? Boolean(stored.currentRun),
152
+ lastSuccessDate: stored.lastSuccessDate,
153
+ lastAttemptAt: stored.lastAttemptAt,
154
+ nextRetryAt: stored.nextRetryAt,
155
+ consecutiveFailures: stored.consecutiveFailures,
156
+ weekly: stored.weekly,
157
+ scheduleMode: runtimeStatus?.scheduleMode ?? 'timer',
158
+ lastRun: latest ?? stored.lastRun,
159
+ }
160
+ }
161
+
162
+ /**
163
+ * host = { ctx, config, lifecycle, runtime };也接受直接传 config。
164
+ */
165
+ export async function readStatus(host) {
166
+ const config = host?.config ?? host ?? {}
167
+ const home = typeof config?.taHome === 'string' ? config.taHome : ''
168
+ const existing = isDirectory(home)
169
+ const marker = existing ? readHomeMarker(home) : { exists: false, valid: false }
170
+ const homeMarked = existing && marker.valid
171
+ const writable = existing && isWritableDirectory(home)
172
+ const core = existing ? coreFileSummary(config) : {}
173
+ const initialized = existing && (homeMarked || Boolean(core?.soul?.exists))
174
+ const generated = existing ? generatedState(home) : generatedState('')
175
+ const [reme, im] = await Promise.all([checkReme(config), Promise.resolve(imState(config))])
176
+ const operation = host?.lifecycle?.operation ?? null
177
+ return {
178
+ initialized,
179
+ lifecycle: operation ?? (initialized ? 'initialized' : 'uninitialized'),
180
+ home,
181
+ homeMarked,
182
+ writable,
183
+ existing,
184
+ core,
185
+ generated,
186
+ maintenance: maintenanceState(config, host),
187
+ soulProposals: { pending: existing ? pendingProposalCount(config, home) : 0 },
188
+ reme,
189
+ im,
190
+ updatedAt: now(),
191
+ }
192
+ }
@@ -0,0 +1,56 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { readFileSync } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+ import { localDateText, writeAtomic } from '../storage/index.js'
5
+ import { clamp01, clampSigned } from './values.js'
6
+
7
+ export const APPRAISAL_FILE = 'state/appraisals.jsonl'
8
+ export const APPRAISAL_LIMIT = 500
9
+
10
+ export function appraisalsPath(config) {
11
+ return resolve(config.taHome, APPRAISAL_FILE)
12
+ }
13
+
14
+ export function readAppraisals(config) {
15
+ let text = ''
16
+ try {
17
+ text = readFileSync(appraisalsPath(config), 'utf8')
18
+ } catch {
19
+ return []
20
+ }
21
+ const records = []
22
+ for (const line of text.split(/\r?\n/)) {
23
+ if (!line.trim()) continue
24
+ try {
25
+ const value = JSON.parse(line)
26
+ if (value && typeof value === 'object') records.push(value)
27
+ } catch {
28
+ /* 损坏行跳过 */
29
+ }
30
+ }
31
+ return records
32
+ }
33
+
34
+ export function appendAppraisal(config, entry) {
35
+ const record = {
36
+ id: typeof entry?.id === 'string' && entry.id ? entry.id : `appraisal:${randomUUID()}`,
37
+ at: typeof entry?.at === 'string' && entry.at ? entry.at : new Date().toISOString(),
38
+ event: String(entry?.event ?? '').trim(),
39
+ why: String(entry?.why ?? '').trim(),
40
+ intensity: clamp01(entry?.intensity, 0),
41
+ valence: clampSigned(entry?.valence, 0),
42
+ energy: clamp01(entry?.energy, 0.6),
43
+ attention: clamp01(entry?.attention, 0.6),
44
+ label: typeof entry?.label === 'string' ? entry.label.slice(0, 20) : '',
45
+ sources: Array.isArray(entry?.sources) ? entry.sources.map(String).slice(0, 10) : [],
46
+ provenance: entry?.provenance === 'explicit' ? 'explicit' : 'inferred',
47
+ }
48
+ const kept = [...readAppraisals(config), record].slice(-APPRAISAL_LIMIT)
49
+ writeAtomic(appraisalsPath(config), kept.map(item => JSON.stringify(item)).join('\n') + '\n')
50
+ return record
51
+ }
52
+
53
+ /** 某天(默认今天)的 appraisal 条数;情绪整合只在该天有条目时运行。 */
54
+ export function appraisalCountForDay(config, dateText = localDateText(config)) {
55
+ return readAppraisals(config).filter(item => localDateText(config, Date.parse(item.at ?? '')) === dateText).length
56
+ }
@@ -0,0 +1,78 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import { localDateText, writeAtomic } from '../storage/index.js'
4
+ import { appendAppraisal } from './appraisals.js'
5
+ import { readMood, writeMood } from './mood.js'
6
+ import { clamp01, clampSigned } from './values.js'
7
+
8
+ export const FEEL_LIMITS_FILE = 'state/feel-limits.json'
9
+
10
+ function feelLimitsPath(config) {
11
+ return resolve(config.taHome, FEEL_LIMITS_FILE)
12
+ }
13
+
14
+ function readFeelLimits(config, date) {
15
+ try {
16
+ const value = JSON.parse(readFileSync(feelLimitsPath(config), 'utf8'))
17
+ if (value?.day === date) {
18
+ return {
19
+ day: date,
20
+ globalCount: Number.isSafeInteger(value.globalCount) ? value.globalCount : 0,
21
+ sessions: value.sessions && typeof value.sessions === 'object' ? value.sessions : {},
22
+ turns: value.turns && typeof value.turns === 'object' ? value.turns : {},
23
+ }
24
+ }
25
+ } catch {
26
+ /* fall through */
27
+ }
28
+ return { day: date, globalCount: 0, sessions: {}, turns: {} }
29
+ }
30
+
31
+ /**
32
+ * ta_feel:写 appraisal + 当前情绪,并执行限频。
33
+ * 限频:每轮 1 次、每会话 3 次/日、全局 6 次/日。
34
+ */
35
+ export function recordFeel(config, {
36
+ event, why, valence, energy, attention, label, sources = [], sessionId, turn, nowMs = Date.now(),
37
+ } = {}) {
38
+ const eventText = String(event ?? '').trim()
39
+ const whyText = String(why ?? '').trim()
40
+ if (!eventText || !whyText) throw new Error('event and why are required')
41
+ const date = localDateText(config, nowMs)
42
+ const limits = readFeelLimits(config, date)
43
+ const sessionKey = String(sessionId ?? 'unknown')
44
+ const turnKey = `${sessionKey}:${turn ?? 'unknown'}`
45
+ if (limits.turns[turnKey]) throw new Error('这一轮已经记录过情绪了')
46
+ const sessionCount = Number(limits.sessions[sessionKey]) || 0
47
+ if (sessionCount >= 3) throw new Error('这个会话今天记录情绪的次数已用完')
48
+ if (limits.globalCount >= 6) throw new Error('今天记录情绪的次数已用完')
49
+
50
+ const previous = readMood(config, nowMs)
51
+ const nextValence = clampSigned(valence, previous.valence)
52
+ const nextEnergy = clamp01(energy, previous.energy)
53
+ const nextAttention = clamp01(attention, previous.attention)
54
+ const intensity = Math.max(
55
+ Math.abs(nextValence - previous.valence),
56
+ Math.abs(nextEnergy - previous.energy),
57
+ Math.abs(nextAttention - previous.attention),
58
+ )
59
+ const nextLabel = typeof label === 'string' && label.trim() ? label.trim().slice(0, 20) : previous.label
60
+ const appraisal = appendAppraisal(config, {
61
+ at: new Date(nowMs).toISOString(),
62
+ event: eventText,
63
+ why: whyText,
64
+ intensity: clamp01(intensity, 0),
65
+ valence: nextValence,
66
+ energy: nextEnergy,
67
+ attention: nextAttention,
68
+ label: nextLabel,
69
+ sources,
70
+ provenance: 'explicit',
71
+ })
72
+ writeMood(config, { label: nextLabel, valence: nextValence, energy: nextEnergy, attention: nextAttention }, nowMs)
73
+ limits.globalCount += 1
74
+ limits.sessions[sessionKey] = sessionCount + 1
75
+ limits.turns[turnKey] = true
76
+ writeAtomic(feelLimitsPath(config), JSON.stringify(limits) + '\n')
77
+ return { appraisal, intensity }
78
+ }
@@ -0,0 +1,9 @@
1
+ export { readNoteLines, addNote } from './notes.js'
2
+ export {
3
+ readOutingActive, startOuting, finishOuting, cleanupOutings,
4
+ } from './outing.js'
5
+ export { readMood, writeMood, applyEmotionUpdate, moodLine } from './mood.js'
6
+ export {
7
+ readAppraisals, appendAppraisal, appraisalCountForDay,
8
+ } from './appraisals.js'
9
+ export { recordFeel } from './feel.js'
@@ -0,0 +1,103 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import { writeAtomic } from '../storage/index.js'
4
+ import { clamp01, clampSigned } from './values.js'
5
+
6
+ const MOOD_BASELINE = { label: '平静', valence: 0, energy: 0.6, attention: 0.6 }
7
+ const MOOD_TAU_HOURS = { valence: 8, energy: 6, attention: 8 }
8
+ const MOOD_LABEL_TTL_HOURS = 12
9
+
10
+ function moodPath(config) {
11
+ return resolve(config.taHome, 'state/mood.json')
12
+ }
13
+
14
+ function labelFor(valence, energy) {
15
+ if (valence <= -0.35) return energy < 0.4 ? '低落' : '烦躁'
16
+ if (valence >= 0.45) return energy >= 0.6 ? '愉快' : '温暖'
17
+ if (energy < 0.35) return '疲惫'
18
+ if (energy >= 0.75) return '有精神'
19
+ return '平静'
20
+ }
21
+
22
+ function readStoredMood(config) {
23
+ try {
24
+ const value = JSON.parse(readFileSync(moodPath(config), 'utf8'))
25
+ return value && typeof value === 'object' ? value : {}
26
+ } catch {
27
+ return {}
28
+ }
29
+ }
30
+
31
+ /** 读取时按 tau 衰减到 baseline,不写文件。 */
32
+ export function readMood(config, nowMs = Date.now()) {
33
+ const stored = readStoredMood(config)
34
+ const baselineStored = stored.baseline && typeof stored.baseline === 'object' ? stored.baseline : {}
35
+ const baseline = {
36
+ label: typeof baselineStored.label === 'string' && baselineStored.label ? baselineStored.label : MOOD_BASELINE.label,
37
+ valence: clampSigned(baselineStored.valence, MOOD_BASELINE.valence),
38
+ energy: clamp01(baselineStored.energy, MOOD_BASELINE.energy),
39
+ attention: clamp01(baselineStored.attention, MOOD_BASELINE.attention),
40
+ }
41
+ const current = stored.current && typeof stored.current === 'object' ? stored.current : {}
42
+ const label = typeof current.label === 'string' && current.label ? current.label : baseline.label
43
+ const rawValence = clampSigned(current.valence, baseline.valence)
44
+ const rawEnergy = clamp01(current.energy, baseline.energy)
45
+ const rawAttention = clamp01(current.attention, baseline.attention)
46
+ const updatedAt = typeof current.updatedAt === 'string' ? current.updatedAt : null
47
+ const updated = Date.parse(updatedAt ?? '')
48
+ const hours = Number.isFinite(updated) ? Math.max(0, (nowMs - updated) / 3_600_000) : 24
49
+ const decay = (value, base, tau) => base + (value - base) * Math.exp(-hours / tau)
50
+ const valence = clampSigned(decay(rawValence, baseline.valence, MOOD_TAU_HOURS.valence))
51
+ const energy = clamp01(decay(rawEnergy, baseline.energy, MOOD_TAU_HOURS.energy))
52
+ const attention = clamp01(decay(rawAttention, baseline.attention, MOOD_TAU_HOURS.attention))
53
+ return {
54
+ label: hours <= MOOD_LABEL_TTL_HOURS ? label : labelFor(valence, energy),
55
+ valence,
56
+ energy,
57
+ attention,
58
+ baseline,
59
+ updatedAt,
60
+ hours,
61
+ raw: { label, valence: rawValence, energy: rawEnergy, attention: rawAttention },
62
+ }
63
+ }
64
+
65
+ /** 写当前情绪;baseline 不变。 */
66
+ export function writeMood(config, patch = {}, nowMs = Date.now()) {
67
+ const previous = readMood(config, nowMs)
68
+ const label = typeof patch.label === 'string' && patch.label.trim()
69
+ ? patch.label.trim().slice(0, 20)
70
+ : previous.raw.label
71
+ const current = {
72
+ label,
73
+ valence: clampSigned(patch.valence, previous.raw.valence),
74
+ energy: clamp01(patch.energy, previous.raw.energy),
75
+ attention: clamp01(patch.attention, previous.raw.attention),
76
+ updatedAt: new Date(nowMs).toISOString(),
77
+ }
78
+ const next = { baseline: previous.baseline, current }
79
+ writeAtomic(moodPath(config), JSON.stringify(next, null, 2) + '\n')
80
+ return readMood(config, nowMs)
81
+ }
82
+
83
+ /** 维护情绪阶段:把整合结果写回 current。 */
84
+ export function applyEmotionUpdate(config, update, nowMs = Date.now()) {
85
+ return writeMood(config, {
86
+ label: update.label,
87
+ valence: update.valence,
88
+ energy: update.energy,
89
+ attention: update.attention,
90
+ }, nowMs)
91
+ }
92
+
93
+ function moodWord(value) {
94
+ if (value >= 0.7) return '充足'
95
+ if (value >= 0.4) return '一般'
96
+ return '偏低'
97
+ }
98
+
99
+ export function moodLine(config) {
100
+ const mood = readMood(config)
101
+ const line = `你现在的心情:${mood.label};精力${moodWord(mood.energy)},注意力${moodWord(mood.attention)}。`
102
+ return line.length > 200 ? line.slice(0, 197) + '…' : line
103
+ }
@@ -0,0 +1,18 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { withinHome, writeAtomic } from '../storage/index.js'
3
+
4
+ export function readNoteLines(config) {
5
+ try {
6
+ return readFileSync(withinHome('notes/note.md', config), 'utf8').split(/\r?\n/).filter(Boolean)
7
+ } catch {
8
+ return []
9
+ }
10
+ }
11
+
12
+ export function addNote(config, text) {
13
+ const line = String(text ?? '').replace(/\s+/g, ' ').trim()
14
+ if (!line) throw new Error('text is required')
15
+ const lines = [...readNoteLines(config), line].slice(-80)
16
+ writeAtomic(withinHome('notes/note.md', config), lines.join('\n') + '\n')
17
+ return `notes/note.md (${lines.length}/80)`
18
+ }