dsh-ta 0.3.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +160 -107
  3. package/cordis.patch.yml +5 -35
  4. package/docs/RELEASE.md +62 -49
  5. package/docs/USAGE.md +6 -7
  6. package/docs/presets.example.yml +7 -43
  7. package/index.js +3 -164
  8. package/package.json +5 -28
  9. package/src/client/client.js +3176 -0
  10. package/{config.js → src/host/config.js} +39 -3
  11. package/src/host/constants.js +7 -0
  12. package/src/host/gates.js +34 -0
  13. package/src/host/identity.js +145 -0
  14. package/{im → src/host/im}/bindings.js +1 -1
  15. package/src/host/index.js +173 -0
  16. package/{jurisdiction.js → src/host/jurisdiction.js} +1 -1
  17. package/src/host/maintenance/collect.js +362 -0
  18. package/src/host/maintenance/completions.js +56 -0
  19. package/src/host/maintenance/consumption.js +67 -0
  20. package/src/host/maintenance/cursors.js +53 -0
  21. package/src/host/maintenance/engine.js +392 -0
  22. package/src/host/maintenance/llm.js +381 -0
  23. package/src/host/maintenance/lock.js +105 -0
  24. package/src/host/maintenance/prompts.js +255 -0
  25. package/src/host/maintenance/runs.js +47 -0
  26. package/src/host/maintenance/schedule.js +173 -0
  27. package/src/host/maintenance/session-cleanup.js +289 -0
  28. package/src/host/maintenance/session-watcher.js +107 -0
  29. package/src/host/maintenance/sleep.js +3 -0
  30. package/src/host/maintenance/stages.js +241 -0
  31. package/src/host/maintenance/state.js +192 -0
  32. package/src/host/prompts.js +96 -0
  33. package/src/host/records.js +175 -0
  34. package/src/host/runtime-manager.js +287 -0
  35. package/{runtime.js → src/host/runtime.js} +6 -8
  36. package/src/host/settings/defaults.js +55 -0
  37. package/{settings → src/host/settings}/home.js +4 -3
  38. package/{settings/routes.js → src/host/settings/http.js} +5 -137
  39. package/{settings → src/host/settings}/im.js +18 -1
  40. package/{settings → src/host/settings}/lifecycle.js +29 -43
  41. package/src/host/settings/persona.js +113 -0
  42. package/src/host/settings/routes.js +229 -0
  43. package/{settings → src/host/settings}/status.js +70 -42
  44. package/src/host/state/appraisals.js +56 -0
  45. package/src/host/state/feel.js +78 -0
  46. package/src/host/state/index.js +9 -0
  47. package/src/host/state/mood.js +103 -0
  48. package/src/host/state/notes.js +18 -0
  49. package/{life.js → src/host/state/outing.js} +13 -136
  50. package/src/host/state/values.js +9 -0
  51. package/{stickers → src/host/stickers}/tool.js +1 -1
  52. package/src/host/storage/fs.js +29 -0
  53. package/src/host/storage/index.js +8 -0
  54. package/src/host/storage/paths.js +20 -0
  55. package/src/host/storage/revision.js +5 -0
  56. package/src/host/storage/session-state.js +38 -0
  57. package/src/host/storage/time.js +127 -0
  58. package/src/host/tools/index.js +152 -0
  59. package/src/host/tools/read.js +252 -0
  60. package/src/host/tools/shared.js +23 -0
  61. package/src/host/tools/wiki.js +35 -0
  62. package/src/host/tools/write.js +164 -0
  63. package/{usage → src/host/usage}/aggregate.js +4 -1
  64. package/{usage → src/host/usage}/ledger.js +47 -21
  65. package/client.js +0 -2554
  66. package/gates.js +0 -18
  67. package/identity.js +0 -97
  68. package/prompts.js +0 -28
  69. package/runtime-manager.js +0 -153
  70. package/settings/defaults.js +0 -41
  71. package/settings/persona.js +0 -203
  72. package/settings/schedule.js +0 -156
  73. package/storage.js +0 -122
  74. package/tools.js +0 -540
  75. /package/{im → src/host/im}/say.js +0 -0
  76. /package/{memory → src/host/memory}/capture.js +0 -0
  77. /package/{memory → src/host/memory}/messages.js +0 -0
  78. /package/{memory → src/host/memory}/outbox.js +0 -0
  79. /package/{reme.js → src/host/reme.js} +0 -0
  80. /package/{settings → src/host/settings}/errors.js +0 -0
  81. /package/{stickers → src/host/stickers}/load.js +0 -0
  82. /package/{stickers → src/host/stickers}/select.js +0 -0
  83. /package/{stickers → src/host/stickers}/serve.js +0 -0
  84. /package/{usage → src/host/usage}/pricing.js +0 -0
  85. /package/{usage → src/host/usage}/serve.js +0 -0
@@ -9,16 +9,14 @@
9
9
  */
10
10
 
11
11
  import { AsyncLocalStorage } from 'node:async_hooks'
12
- import { readFileSync, readdirSync, rmSync, statSync } from 'node:fs'
12
+ import { readdirSync, rmSync, statSync } from 'node:fs'
13
13
  import { join } from 'node:path'
14
14
  import { SettingsError, badRequest, conflict } from './errors.js'
15
15
  import {
16
16
  assertDestroyableHome, ensureHome, isTaHome, physicalPath, validateHomePath,
17
17
  validateNewHome,
18
18
  } from './home.js'
19
- import { reconcileReviewSchedule, removeReviewSchedule } from './schedule.js'
20
19
 
21
- const PERSONA_FILES = ['SOUL.md', 'USER.md']
22
20
  const QUIESCE_TIMEOUT_MS = 10_000
23
21
 
24
22
  /**
@@ -98,24 +96,7 @@ function samePath(left, right) {
98
96
  return physicalPath(left) === physicalPath(right)
99
97
  }
100
98
 
101
- /** 老家的判定:SOUL.md、USER.md 去空白后都非空。 */
102
- function hasPersona(home) {
103
- for (const name of PERSONA_FILES) {
104
- try {
105
- const file = join(home, name)
106
- if (!statSync(file).isFile()) return false
107
- if (readFileSync(file, 'utf8').trim() === '') return false
108
- } catch {
109
- return false
110
- }
111
- }
112
- return true
113
- }
114
-
115
- /**
116
- * 已初始化 = 目录存在,并且带有有效 .ta-home 标记,或者已经有人设文件。
117
- * 后者用于 0.3.0 之前创建、缺少标记的老家:必须被认成“已有 TA”,不能被当成空目录。
118
- */
99
+ /** 已初始化 = 目录存在,并且带有有效的 .ta-home 标记。 */
119
100
  function isInitializedHome(home) {
120
101
  if (typeof home !== 'string' || !home) return false
121
102
  try {
@@ -123,7 +104,7 @@ function isInitializedHome(home) {
123
104
  } catch {
124
105
  return false
125
106
  }
126
- return isTaHome(home) || hasPersona(home)
107
+ return isTaHome(home)
127
108
  }
128
109
 
129
110
  function configEditorOf(host) {
@@ -150,6 +131,16 @@ async function editTaHome(host, home) {
150
131
  await editor.edit(entry, current => ({ ...current, taHome: home }))
151
132
  }
152
133
 
134
+ /** 把若干配置项写进 profile;用于称呼、维护开关等设置页字段。 */
135
+ export async function editConfigValues(host, patch) {
136
+ const editor = requireConfigEditor(host)
137
+ const entry = host?.ctx?.fiber?.entry
138
+ if (!entry) {
139
+ throw new SettingsError(500, 'CONFIG_EDITOR_UNAVAILABLE', '无法写入配置:找不到插件配置项')
140
+ }
141
+ await editor.edit(entry, current => ({ ...current, ...patch }))
142
+ }
143
+
153
144
  function stopRuntime(host) {
154
145
  const runtime = host?.runtime
155
146
  if (runtime && typeof runtime.stop === 'function') runtime.stop()
@@ -161,6 +152,20 @@ function startRuntime(host) {
161
152
  return undefined
162
153
  }
163
154
 
155
+ /** 维护引擎 abort 后等待其真正退出;超时只记录 warning。 */
156
+ async function waitRuntimeIdle(host, timeoutMs = QUIESCE_TIMEOUT_MS) {
157
+ const runtime = host?.runtime
158
+ if (!runtime || typeof runtime.whenIdle !== 'function') return
159
+ try {
160
+ await Promise.race([
161
+ Promise.resolve(runtime.whenIdle()).catch(() => {}),
162
+ new Promise(resolvePromise => setTimeout(resolvePromise, timeoutMs)),
163
+ ])
164
+ } catch {
165
+ /* idle 等待失败不阻塞生命周期 */
166
+ }
167
+ }
168
+
164
169
  function rebindRuntime(host) {
165
170
  const runtime = host?.runtime
166
171
  if (runtime && typeof runtime.rebind === 'function') return runtime.rebind()
@@ -208,23 +213,6 @@ function assertLifecycleIdle(host) {
208
213
  if (lifecycleOf(host).operation) throw busyError()
209
214
  }
210
215
 
211
- /**
212
- * 回顾任务同步:用户关掉 reviewScheduleEnabled 时不创建新任务;
213
- * 换家时旧家的回顾任务仍然要清掉。
214
- */
215
- async function syncReviewSchedule(host, previousHome) {
216
- const { ctx, config } = host
217
- if (config?.reviewScheduleEnabled === false) {
218
- const warnings = []
219
- if (previousHome && !samePath(previousHome, config.taHome)) {
220
- const removed = await removeReviewSchedule(ctx, previousHome, loggerOf(host))
221
- warnings.push(...(removed.warnings ?? []))
222
- }
223
- return { created: false, existing: false, disabled: true, warnings }
224
- }
225
- return reconcileReviewSchedule(ctx, config, previousHome, loggerOf(host))
226
- }
227
-
228
216
  function ensureResult(path, ensured) {
229
217
  return {
230
218
  initialized: true,
@@ -290,8 +278,6 @@ export async function initializeHome(host, input) {
290
278
  await editTaHome(host, ensured.path)
291
279
  }
292
280
  rebindRuntime(host)
293
- const schedule = await syncReviewSchedule(host, configChanged ? currentHome : undefined)
294
- warnings.push(...(schedule.warnings ?? []))
295
281
  info(host, `TA 的家已初始化:${ensured.path}`)
296
282
  return {
297
283
  ...ensureResult(ensured.path, ensured),
@@ -335,14 +321,14 @@ export async function reincarnate(host, input) {
335
321
  const warnings = []
336
322
  try {
337
323
  stopRuntime(host)
324
+ await waitRuntimeIdle(host)
338
325
  ensured = ensureHome(target.path)
339
326
  await editTaHome(host, target.path)
340
327
  configChanged = true
341
328
  rebindRuntime(host)
342
- const schedule = await syncReviewSchedule(host, oldHome)
343
- warnings.push(...(schedule.warnings ?? []))
344
329
  if (deleteOldHome) {
345
330
  try {
331
+ await waitRuntimeIdle(host)
346
332
  await quiesceHomeSessions(host, oldHome)
347
333
  rmSync(physicalPath(oldHome), { recursive: true, force: true })
348
334
  oldHomeDeleted = true
@@ -0,0 +1,113 @@
1
+ /**
2
+ * 人设读写:0.4 起只允许 SOUL.md。
3
+ *
4
+ * 认识/USER.md 由维护任务写;根 USER.md 只在迁移确认前只读注入。
5
+ * revision = sha256:<hex>;冲突返回 409 PERSONA_CONFLICT。
6
+ */
7
+
8
+ import { statSync } from 'node:fs'
9
+ import { readTextIfExists, sha256Revision, withinHome, writeAtomic } from '../storage/index.js'
10
+ import { PERSONA_BUDGETS, PERSONA_MAX_CHARS } from './defaults.js'
11
+ import { badRequest, conflict } from './errors.js'
12
+
13
+ const SOUL_FILE = 'SOUL.md'
14
+
15
+ let writeTail = Promise.resolve()
16
+
17
+ function enqueueWrite(task) {
18
+ const run = writeTail.then(task)
19
+ writeTail = run.catch(() => undefined)
20
+ return run
21
+ }
22
+
23
+ function requireHome(config) {
24
+ const home = config?.taHome
25
+ if (typeof home !== 'string' || home.length === 0) {
26
+ throw badRequest('HOME_INVALID', 'TA 的家尚未配置')
27
+ }
28
+ }
29
+
30
+ function requireExistingHome(config) {
31
+ requireHome(config)
32
+ try {
33
+ if (statSync(config.taHome).isDirectory()) return
34
+ } catch {
35
+ /* fall through */
36
+ }
37
+ throw badRequest('HOME_NOT_INITIALIZED', '先创建 TA 的家,再保存人设')
38
+ }
39
+
40
+ function soulPath(config) {
41
+ try {
42
+ return withinHome(SOUL_FILE, config)
43
+ } catch {
44
+ throw badRequest('PERSONA_PATH_INVALID', 'SOUL.md 不在 TA 的家内,已拒绝访问')
45
+ }
46
+ }
47
+
48
+ function readSoul(config) {
49
+ const text = readTextIfExists(soulPath(config))
50
+ return typeof text === 'string' ? text : ''
51
+ }
52
+
53
+ function budgetWarnings(soul) {
54
+ if (soul.length > PERSONA_BUDGETS.soul) {
55
+ return [`SOUL.md 已有 ${soul.length} 字,超过建议预算 ${PERSONA_BUDGETS.soul} 字,注入时会截断`]
56
+ }
57
+ return []
58
+ }
59
+
60
+ function personaRecord(soul) {
61
+ return {
62
+ field: 'soul',
63
+ soul,
64
+ revision: sha256Revision(soul),
65
+ budget: PERSONA_BUDGETS.soul,
66
+ maxChars: PERSONA_MAX_CHARS.soul,
67
+ warnings: budgetWarnings(soul),
68
+ }
69
+ }
70
+
71
+ function requireText(value, label) {
72
+ if (typeof value !== 'string') throw badRequest('PERSONA_INVALID', `${label} 内容必须是文本`)
73
+ return value
74
+ }
75
+
76
+ function requireRevision(value, label) {
77
+ if (typeof value !== 'string' || value.length === 0) {
78
+ throw badRequest('PERSONA_INVALID', `缺少 ${label} 的版本号,请刷新后重试`)
79
+ }
80
+ return value
81
+ }
82
+
83
+ function assertWithinMaxChars(text) {
84
+ if (text.length > PERSONA_MAX_CHARS.soul) {
85
+ throw badRequest('PERSONA_TOO_LARGE', `SOUL.md 最多 ${PERSONA_MAX_CHARS.soul} 字,请压缩后再保存`)
86
+ }
87
+ }
88
+
89
+ function personaConflict() {
90
+ return conflict('PERSONA_CONFLICT', 'SOUL.md 已被其他会话修改,请刷新后重试')
91
+ }
92
+
93
+ /** 读取 SOUL 与 revision。 */
94
+ export function readPersona(config) {
95
+ requireHome(config)
96
+ return personaRecord(readSoul(config))
97
+ }
98
+
99
+ /** 单字段保存:只接受 { field:'soul', content, revision }。 */
100
+ export function writePersonaField(config, input) {
101
+ return enqueueWrite(async () => {
102
+ requireExistingHome(config)
103
+ if (input?.field !== 'soul') {
104
+ throw badRequest('PERSONA_FIELD_INVALID', '人设页只编辑 SOUL.md;field 必须是 soul')
105
+ }
106
+ const content = requireText(input?.content, 'SOUL.md')
107
+ const revision = requireRevision(input?.revision, 'SOUL.md')
108
+ assertWithinMaxChars(content)
109
+ if (revision !== sha256Revision(readSoul(config))) throw personaConflict()
110
+ writeAtomic(soulPath(config), content)
111
+ return personaRecord(content)
112
+ })
113
+ }
@@ -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
+ }
@@ -1,17 +1,18 @@
1
1
  /**
2
- * 设置页状态聚合。
2
+ * 设置页状态聚合:四件套、维护、SOUL 建议、IM。
3
3
  *
4
4
  * 状态全部从文件、配置与 im-connect 派生,不写任何状态文件。
5
5
  * ReMe 健康检查最多等 1.5s,任何失败都降级为状态值,不向上抛错。
6
6
  */
7
7
 
8
- import { readdirSync, statSync } from 'node:fs'
8
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
9
9
  import { join } from 'node:path'
10
- import { isWritableDirectory, readTextIfExists } from '../storage.js'
11
- import { PERSONA_BUDGETS } from './defaults.js'
10
+ import { coreFileSummary } from '../identity.js'
11
+ import { isWritableDirectory, readTextIfExists } from '../storage/index.js'
12
12
  import { readHomeMarker } from './home.js'
13
- import { readImState } from './im.js'
14
- import { readPersona } from './persona.js'
13
+ import { readImState, imModeFor } from './im.js'
14
+ import { readMaintenanceState } from '../maintenance/state.js'
15
+ import { readRuns } from '../maintenance/runs.js'
15
16
 
16
17
  const REME_TIMEOUT_MS = 1500
17
18
  const DIARY_FILE_PATTERN = /^(\d{4}-\d{2}-\d{2})\.md$/
@@ -41,7 +42,6 @@ async function checkReme(config) {
41
42
  const response = await fetch(`${endpoint}/health_check`, {
42
43
  method: 'POST',
43
44
  headers: { 'content-type': 'application/json' },
44
- // 当前 ReMe(0.4.2.3)要求带 JSON body,空对象即可。
45
45
  body: '{}',
46
46
  signal: controller.signal,
47
47
  })
@@ -79,34 +79,9 @@ async function checkReme(config) {
79
79
  }
80
80
  }
81
81
 
82
- function personaState(config, existing) {
83
- const empty = { soul: false, user: false, soulChars: 0, userChars: 0 }
84
- if (!existing) {
85
- return { ...empty, soulBudget: PERSONA_BUDGETS.soul, userBudget: PERSONA_BUDGETS.user }
86
- }
87
- let record
88
- try {
89
- record = readPersona(config)
90
- } catch {
91
- // 人设文件不可读(例如被替换成指向家目录外的符号链接)时按空人设降级。
92
- record = { soul: '', user: '' }
93
- }
94
- return {
95
- soul: record.soul.trim().length > 0,
96
- user: record.user.trim().length > 0,
97
- soulChars: record.soul.length,
98
- userChars: record.user.length,
99
- soulBudget: PERSONA_BUDGETS.soul,
100
- userBudget: PERSONA_BUDGETS.user,
101
- }
102
- }
103
-
104
- /** TA 生成的内容:MEMORY.md、self/我.md、日记数量与最新一篇的日期。 */
105
82
  function generatedState(home) {
106
- const empty = { memory: false, self: false, diaryCount: 0, latestDiary: null }
83
+ const empty = { diaryCount: 0, latestDiary: null }
107
84
  if (!home) return empty
108
- const memory = readTextIfExists(join(home, 'MEMORY.md')) !== undefined
109
- const self = readTextIfExists(join(home, 'self', '我.md')) !== undefined
110
85
  let diaryCount = 0
111
86
  let latestDiary = null
112
87
  try {
@@ -120,20 +95,72 @@ function generatedState(home) {
120
95
  } catch {
121
96
  /* 没有日记目录就按 0 篇处理 */
122
97
  }
123
- return { memory, self, diaryCount, latestDiary }
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
+ }
124
118
  }
125
119
 
126
120
  function imState(config) {
127
121
  try {
128
- return readImState(config)
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
129
142
  } catch {
130
- return { installed: false, compatible: false, accounts: [], error: '无法读取 IM 连接状态' }
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,
131
159
  }
132
160
  }
133
161
 
134
162
  /**
135
- * host = { ctx, config, lifecycle };也接受直接传 config,便于内部复用。
136
- * lifecycle.operation 非空时(reincarnating)优先生效。
163
+ * host = { ctx, config, lifecycle, runtime };也接受直接传 config。
137
164
  */
138
165
  export async function readStatus(host) {
139
166
  const config = host?.config ?? host ?? {}
@@ -142,9 +169,8 @@ export async function readStatus(host) {
142
169
  const marker = existing ? readHomeMarker(home) : { exists: false, valid: false }
143
170
  const homeMarked = existing && marker.valid
144
171
  const writable = existing && isWritableDirectory(home)
145
- const persona = personaState(config, existing)
146
- // 初始化只取决于「家」:有效标记,或带人设的老家。人设内容可以稍后补。
147
- const initialized = existing && (homeMarked || persona.soul || persona.user)
172
+ const core = existing ? coreFileSummary(config) : {}
173
+ const initialized = existing && (homeMarked || Boolean(core?.soul?.exists))
148
174
  const generated = existing ? generatedState(home) : generatedState('')
149
175
  const [reme, im] = await Promise.all([checkReme(config), Promise.resolve(imState(config))])
150
176
  const operation = host?.lifecycle?.operation ?? null
@@ -155,8 +181,10 @@ export async function readStatus(host) {
155
181
  homeMarked,
156
182
  writable,
157
183
  existing,
158
- persona,
184
+ core,
159
185
  generated,
186
+ maintenance: maintenanceState(config, host),
187
+ soulProposals: { pending: existing ? pendingProposalCount(config, home) : 0 },
160
188
  reme,
161
189
  im,
162
190
  updatedAt: now(),