dsh-ta 0.1.0 → 0.3.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.
@@ -0,0 +1,296 @@
1
+ /**
2
+ * 设置页 Host 路由:统一前缀 /api/dsh-ta。
3
+ *
4
+ * 这里只做 HTTP 适配(方法、JSON body、64 KiB 上限、错误映射),
5
+ * 业务逻辑全部放在 settings/ 下的模块里;dispatch() 不写 HTTP,
6
+ * 测试和真实请求共用同一套分发逻辑。
7
+ */
8
+
9
+ import { BODY_LIMIT_BYTES } from './defaults.js'
10
+ import {
11
+ SettingsError, badRequest, conflict, internal, tooLarge, unsupportedMedia,
12
+ } from './errors.js'
13
+ import { readPersona, writePersona, writePersonaField } from './persona.js'
14
+ import { readStatus } from './status.js'
15
+ import { readImState } from './im.js'
16
+ import { initializeHome, reincarnate } from './lifecycle.js'
17
+
18
+ export const ROOT = '/api/dsh-ta'
19
+
20
+ /** 路由表:键是去掉前缀后的规范路径。 */
21
+ const ROUTES = new Map([
22
+ ['/status', {
23
+ allow: ['GET'],
24
+ run: host => readStatus(host),
25
+ }],
26
+ ['/persona', {
27
+ allow: ['GET', 'PUT'],
28
+ run: (host, { method, body }) => {
29
+ if (method === 'GET') return readPersona(host.config)
30
+ const write = () => (body && typeof body.field === 'string'
31
+ ? writePersonaField(host.config, body)
32
+ : writePersona(host.config, body))
33
+ // 与生命周期写操作共用同一个串行队列,避免“边删边写”。
34
+ return typeof host?.queue === 'function' ? host.queue(write) : write()
35
+ },
36
+ }],
37
+ ['/home/init', {
38
+ allow: ['POST'],
39
+ run: (host, { body }) => initializeHome(host, body),
40
+ }],
41
+ ['/lifecycle/reincarnate', {
42
+ allow: ['POST'],
43
+ run: (host, { body }) => reincarnate(host, body),
44
+ }],
45
+ ['/integrations', {
46
+ allow: ['GET'],
47
+ run: async host => {
48
+ const status = await readStatus(host)
49
+ // readStatus 正常会带 im;万一某个早期实现没有,退回只读检测。
50
+ const im = status?.im ?? await readImState(host.config)
51
+ return {
52
+ reme: status?.reme,
53
+ im,
54
+ }
55
+ },
56
+ }],
57
+ ])
58
+
59
+ function notFoundError() {
60
+ return new SettingsError(404, 'NOT_FOUND', '未知的设置接口')
61
+ }
62
+
63
+ function methodNotAllowedError(allow) {
64
+ const error = new SettingsError(405, 'METHOD_NOT_ALLOWED', `该接口只支持 ${allow.join('、')}`)
65
+ error.allow = allow
66
+ return error
67
+ }
68
+
69
+ function normalizeMethod(method) {
70
+ return typeof method === 'string' && method.trim() ? method.trim().toUpperCase() : 'GET'
71
+ }
72
+
73
+ /** 把 /api/dsh-ta/xxx 或 /xxx 统一成 /xxx,忽略末尾斜杠和查询串。 */
74
+ function canonicalPath(pathname) {
75
+ let suffix = pathname
76
+ if (suffix === ROOT) suffix = '/'
77
+ else if (suffix.startsWith(ROOT + '/')) suffix = suffix.slice(ROOT.length)
78
+ suffix = suffix.replace(/\/+$/, '')
79
+ if (!suffix) return '/'
80
+ return suffix.startsWith('/') ? suffix : `/${suffix}`
81
+ }
82
+
83
+ /** HTTP 侧:必须落在 /api/dsh-ta 前缀内。 */
84
+ function parseHttpPath(rawUrl) {
85
+ let pathname
86
+ try {
87
+ pathname = new URL(rawUrl ?? '/', 'http://localhost').pathname
88
+ } catch {
89
+ throw badRequest('INVALID_REQUEST_PATH', '请求路径不合法')
90
+ }
91
+ if (pathname !== ROOT && !pathname.startsWith(ROOT + '/')) throw notFoundError()
92
+ return canonicalPath(pathname)
93
+ }
94
+
95
+ /** dispatch 侧:允许直接传 /status,也允许带完整前缀。 */
96
+ function normalizeDispatchPath(rawPath) {
97
+ let pathname
98
+ try {
99
+ pathname = new URL(String(rawPath ?? '/'), 'http://localhost').pathname
100
+ } catch {
101
+ throw notFoundError()
102
+ }
103
+ return canonicalPath(pathname)
104
+ }
105
+
106
+ function findRoute(path) {
107
+ const route = ROUTES.get(path)
108
+ if (!route) throw notFoundError()
109
+ return route
110
+ }
111
+
112
+ function assertAllowed(route, method) {
113
+ if (!route.allow.includes(method)) throw methodNotAllowedError(route.allow)
114
+ }
115
+
116
+ function assertBodyObject(method, body) {
117
+ if (method !== 'POST' && method !== 'PUT') return
118
+ if (body === undefined || body === null || typeof body !== 'object' || Array.isArray(body)) {
119
+ throw badRequest('INVALID_BODY', '请求体必须是 JSON 对象')
120
+ }
121
+ }
122
+
123
+ /**
124
+ * 测试与 HTTP 共用入口。
125
+ * 成功返回 { status, payload };预期错误抛 SettingsError,未知异常原样抛出,
126
+ * 由 HTTP 适配层统一记录并映射成 500。
127
+ */
128
+ export async function dispatch(host, { method, path, body } = {}) {
129
+ const verb = normalizeMethod(method)
130
+ const routePath = normalizeDispatchPath(path)
131
+ const route = findRoute(routePath)
132
+ assertAllowed(route, verb)
133
+ assertBodyObject(verb, body)
134
+ // 转生期间暂停其他写入,避免切换中的家被并发修改。
135
+ if (host?.lifecycle?.operation && (verb === 'PUT' || verb === 'POST')) {
136
+ throw conflict('LIFECYCLE_BUSY', 'TA 正在转生中,请稍候再试')
137
+ }
138
+ const data = await route.run(host, { method: verb, body })
139
+ return { status: 200, payload: { ok: true, data } }
140
+ }
141
+
142
+ function isJsonContentType(value) {
143
+ if (typeof value !== 'string') return false
144
+ const [mediaType] = value.split(';')
145
+ return mediaType.trim().toLowerCase() === 'application/json'
146
+ }
147
+
148
+ function headerValue(headers, name) {
149
+ if (!headers || typeof headers !== 'object') return undefined
150
+ if (headers[name] !== undefined) return headers[name]
151
+ const key = Object.keys(headers).find(item => item.toLowerCase() === name.toLowerCase())
152
+ return key === undefined ? undefined : headers[key]
153
+ }
154
+
155
+ function assertJsonRequest(request) {
156
+ if (!isJsonContentType(headerValue(request?.headers, 'content-type'))) throw unsupportedMedia()
157
+ }
158
+
159
+ /** 用 for await 读取 body;超过 64 KiB 立即抛 413,由上层响应并结束请求。 */
160
+ async function readJsonBody(request) {
161
+ const declared = Number(headerValue(request?.headers, 'content-length'))
162
+ if (Number.isFinite(declared) && declared > BODY_LIMIT_BYTES) throw tooLarge()
163
+
164
+ const chunks = []
165
+ let size = 0
166
+ for await (const chunk of request) {
167
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
168
+ size += buffer.length
169
+ if (size > BODY_LIMIT_BYTES) throw tooLarge()
170
+ chunks.push(buffer)
171
+ }
172
+ const text = Buffer.concat(chunks).toString('utf8')
173
+ if (!text.trim()) throw badRequest('INVALID_JSON', '请求体不能为空')
174
+ try {
175
+ return JSON.parse(text)
176
+ } catch {
177
+ throw badRequest('INVALID_JSON', '请求体不是合法的 JSON')
178
+ }
179
+ }
180
+
181
+ function responseGone(response) {
182
+ return !response
183
+ || response.destroyed === true
184
+ || response.writableEnded === true
185
+ || response.headersSent === true
186
+ }
187
+
188
+ function writeJson(response, status, payload, extraHeaders, onEnd) {
189
+ if (responseGone(response)) return
190
+ const body = JSON.stringify(payload)
191
+ const headers = {
192
+ 'content-type': 'application/json; charset=utf-8',
193
+ 'cache-control': 'no-store',
194
+ ...(extraHeaders ?? {}),
195
+ }
196
+ try {
197
+ response.writeHead(status, headers)
198
+ if (typeof onEnd === 'function') response.end(body, onEnd)
199
+ else response.end(body)
200
+ } catch {
201
+ /* 客户端已经断开时不再抛错 */
202
+ }
203
+ }
204
+
205
+ function logWarn(host, message, error) {
206
+ try {
207
+ const logger = host?.logger ?? host?.ctx?.logger
208
+ logger?.warn?.(message, error)
209
+ } catch {
210
+ /* 日志失败不能影响响应 */
211
+ }
212
+ }
213
+
214
+ function mapError(host, error) {
215
+ if (error instanceof SettingsError) {
216
+ const headers = error.allow
217
+ ? { allow: Array.isArray(error.allow) ? error.allow.join(', ') : String(error.allow) }
218
+ : undefined
219
+ return {
220
+ status: error.status,
221
+ payload: { ok: false, error: { code: error.code, message: error.message } },
222
+ headers,
223
+ overflow: error.status === 413,
224
+ }
225
+ }
226
+ logWarn(host, `[dsh-ta] 设置接口处理失败:${error instanceof Error ? error.message : String(error)}`, error)
227
+ const fallback = internal()
228
+ return {
229
+ status: 500,
230
+ payload: { ok: false, error: { code: fallback.code, message: fallback.message } },
231
+ overflow: false,
232
+ }
233
+ }
234
+
235
+ function writeError(host, request, response, error) {
236
+ try {
237
+ const mapped = mapError(host, error)
238
+ const onEnd = mapped.overflow
239
+ ? () => {
240
+ try {
241
+ if (!request?.destroyed) request?.destroy?.()
242
+ } catch {
243
+ /* 请求已经结束 */
244
+ }
245
+ }
246
+ : undefined
247
+ writeJson(response, mapped.status, mapped.payload, mapped.headers, onEnd)
248
+ } catch {
249
+ /* 响应阶段不再抛错 */
250
+ }
251
+ }
252
+
253
+ async function handleRequest(host, request, response) {
254
+ try {
255
+ const method = normalizeMethod(request?.method)
256
+ const path = parseHttpPath(request?.url)
257
+ const route = findRoute(path)
258
+ assertAllowed(route, method)
259
+ let body
260
+ if (method === 'POST' || method === 'PUT') {
261
+ assertJsonRequest(request)
262
+ body = await readJsonBody(request)
263
+ }
264
+ const result = await dispatch(host, { method, path, body })
265
+ writeJson(response, result.status, result.payload)
266
+ } catch (error) {
267
+ writeError(host, request, response, error)
268
+ }
269
+ }
270
+
271
+ export function mountSettingsRoutes(ctx, config, host) {
272
+ if (typeof ctx?.inject !== 'function') return
273
+ const settingsHost = host ?? { ctx, config, logger: ctx?.logger }
274
+ try {
275
+ ctx.inject(['webServer'], scope => {
276
+ const server = scope?.webServer ?? scope?.get?.('webServer')
277
+ if (typeof server?.register !== 'function') return
278
+ if (typeof scope?.effect !== 'function') {
279
+ logWarn(settingsHost, '[dsh-ta] webServer 作用域缺少 effect,设置路由没有注册')
280
+ return
281
+ }
282
+ try {
283
+ scope.effect(() => server.register({
284
+ kind: 'prefix',
285
+ path: ROOT,
286
+ auth: 'required',
287
+ handler: (request, response) => handleRequest(settingsHost, request, response),
288
+ }), 'dsh-ta settings route')
289
+ } catch (error) {
290
+ logWarn(settingsHost, `[dsh-ta] 设置路由注册失败:${error instanceof Error ? error.message : String(error)}`, error)
291
+ }
292
+ })
293
+ } catch (error) {
294
+ logWarn(settingsHost, `[dsh-ta] 设置路由注入失败:${error instanceof Error ? error.message : String(error)}`, error)
295
+ }
296
+ }
@@ -0,0 +1,156 @@
1
+ import { REVIEW_PROMPT, REVIEW_TITLE } from '../prompts.js'
2
+ import { realPath } from '../storage.js'
3
+
4
+ function targetHome(entry) {
5
+ const target = entry?.target
6
+ if (target?.kind === 'new_once' || target?.kind === 'new') {
7
+ return typeof target.create?.cwd === 'string' ? target.create.cwd : undefined
8
+ }
9
+ return undefined
10
+ }
11
+
12
+ /**
13
+ * 只把 new_once / new 目标的任务当作回顾任务候选;没有 target 的老任务
14
+ * 仍然允许按标题保守匹配(下面还会要求“全库唯一同名”)。
15
+ * 明确指向已有 Session 的同名任务不是 Ta 的回顾任务,永远不碰。
16
+ */
17
+ function isReviewTarget(entry) {
18
+ const target = entry?.target
19
+ if (target === undefined || target === null) return true
20
+ return target.kind === 'new_once' || target.kind === 'new'
21
+ }
22
+
23
+ async function readCatalog(schedule) {
24
+ if (typeof schedule?.catalog === 'function') {
25
+ const entries = await schedule.catalog()
26
+ return Array.isArray(entries) ? entries : []
27
+ }
28
+ if (typeof schedule?.list === 'function') {
29
+ const page = await schedule.list({ active: true })
30
+ return Array.isArray(page?.items) ? page.items : []
31
+ }
32
+ return undefined
33
+ }
34
+
35
+ function sameHome(left, right) {
36
+ if (typeof left !== 'string' || typeof right !== 'string') return false
37
+ return realPath(left) === realPath(right)
38
+ }
39
+
40
+ /**
41
+ * Remove only the review tasks that provably belong to one home. A title-only
42
+ * match is accepted only when exactly one review task lacks target metadata,
43
+ * so a user-created task can never be swept away by accident.
44
+ */
45
+ export async function removeReviewSchedule(ctx, home, logger) {
46
+ const schedule = ctx?.get?.('schedule')
47
+ const empty = { removed: 0, skipped: 0, warnings: [] }
48
+ if (!schedule?.edit || !schedule?.catalog && !schedule?.list) {
49
+ return { ...empty, warnings: ['日程服务不可用,旧回顾任务没有自动清理'] }
50
+ }
51
+ let entries
52
+ try {
53
+ entries = await readCatalog(schedule)
54
+ } catch (cause) {
55
+ return { ...empty, warnings: [`读取日程失败:${cause instanceof Error ? cause.message : String(cause)}`] }
56
+ }
57
+ if (!entries) return { ...empty, warnings: ['日程服务没有可读列表,旧回顾任务没有自动清理'] }
58
+
59
+ const titled = entries.filter(entry => entry?.title === REVIEW_TITLE)
60
+ const review = titled.filter(isReviewTarget)
61
+ if (review.length === 0) return empty
62
+ const withCwd = review.filter(entry => typeof targetHome(entry) === 'string')
63
+ const withoutCwd = review.filter(entry => typeof targetHome(entry) !== 'string')
64
+ const matched = withCwd.filter(entry => sameHome(targetHome(entry), home))
65
+ const warnings = []
66
+ if (withoutCwd.length === 1 && withCwd.length === 0 && titled.length === 1) {
67
+ matched.push(withoutCwd[0])
68
+ warnings.push('回顾任务缺少目标目录,只能按标题保守匹配')
69
+ } else if (withoutCwd.length > 0) {
70
+ warnings.push(`有 ${withoutCwd.length} 个回顾任务缺少目标目录,已跳过以免误删`)
71
+ }
72
+
73
+ let removed = 0
74
+ let skipped = 0
75
+ for (const entry of new Set(matched)) {
76
+ if (!entry.id) {
77
+ skipped += 1
78
+ continue
79
+ }
80
+ try {
81
+ const result = await schedule.edit({ id: entry.id, action: 'delete' })
82
+ // edit 删除成功固定返回 { id, deleted: true };未找到等拒绝也会带 id,
83
+ // 所以必须只看 deleted 字段,不能按 id 相等来判断。
84
+ const deleted = result?.deleted === true
85
+ if (deleted) {
86
+ removed += 1
87
+ logger?.info?.(`[dsh-ta] removed review schedule ${entry.id} for ${home}`)
88
+ } else {
89
+ skipped += 1
90
+ warnings.push(`回顾任务 ${entry.id} 未删除(${result?.code ?? 'unknown'})`)
91
+ }
92
+ } catch (cause) {
93
+ skipped += 1
94
+ warnings.push(`回顾任务 ${entry.id} 删除失败:${cause instanceof Error ? cause.message : String(cause)}`)
95
+ }
96
+ }
97
+ return { removed, skipped, warnings }
98
+ }
99
+
100
+ function rruleForTomorrow(config) {
101
+ const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000)
102
+ const date = new Intl.DateTimeFormat('en-CA', {
103
+ timeZone: config.timezone,
104
+ year: 'numeric',
105
+ month: '2-digit',
106
+ day: '2-digit',
107
+ }).format(tomorrow).replaceAll('-', '')
108
+ return `DTSTART;TZID=${config.timezone}:${date}T230000\nRRULE:FREQ=DAILY`
109
+ }
110
+
111
+ /** Ensure exactly one nightly review task for the configured home. */
112
+ export async function ensureReviewSchedule(ctx, config) {
113
+ const schedule = ctx?.get?.('schedule')
114
+ if (!schedule?.create) return { created: false, existing: false, warnings: [] }
115
+ let entries
116
+ try {
117
+ entries = await readCatalog(schedule)
118
+ } catch {
119
+ entries = undefined
120
+ }
121
+ if (Array.isArray(entries)) {
122
+ const existing = entries.some(entry => entry?.title === REVIEW_TITLE
123
+ && entry?.status !== 'ended'
124
+ && sameHome(targetHome(entry), config.taHome))
125
+ if (existing) return { created: false, existing: true, warnings: [] }
126
+ }
127
+ try {
128
+ await schedule.create({
129
+ title: REVIEW_TITLE,
130
+ prompt: REVIEW_PROMPT,
131
+ timing: { kind: 'rrule', rrule: rruleForTomorrow(config) },
132
+ target: {
133
+ kind: 'new_once',
134
+ create: { cwd: config.taHome, agentPreset: 'ta-review' },
135
+ },
136
+ })
137
+ return { created: true, existing: false, warnings: [] }
138
+ } catch (cause) {
139
+ return {
140
+ created: false,
141
+ existing: false,
142
+ warnings: [`创建回顾任务失败:${cause instanceof Error ? cause.message : String(cause)}`],
143
+ }
144
+ }
145
+ }
146
+
147
+ export async function reconcileReviewSchedule(ctx, config, previousHome, logger) {
148
+ const warnings = []
149
+ if (previousHome && !sameHome(previousHome, config.taHome)) {
150
+ const removed = await removeReviewSchedule(ctx, previousHome, logger)
151
+ warnings.push(...removed.warnings)
152
+ }
153
+ const ensured = await ensureReviewSchedule(ctx, config)
154
+ warnings.push(...(ensured.warnings ?? []))
155
+ return { ...ensured, warnings }
156
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * 设置页状态聚合。
3
+ *
4
+ * 状态全部从文件、配置与 im-connect 派生,不写任何状态文件。
5
+ * ReMe 健康检查最多等 1.5s,任何失败都降级为状态值,不向上抛错。
6
+ */
7
+
8
+ import { readdirSync, statSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { isWritableDirectory, readTextIfExists } from '../storage.js'
11
+ import { PERSONA_BUDGETS } from './defaults.js'
12
+ import { readHomeMarker } from './home.js'
13
+ import { readImState } from './im.js'
14
+ import { readPersona } from './persona.js'
15
+
16
+ const REME_TIMEOUT_MS = 1500
17
+ const DIARY_FILE_PATTERN = /^(\d{4}-\d{2}-\d{2})\.md$/
18
+
19
+ function now() {
20
+ return new Date().toISOString()
21
+ }
22
+
23
+ function isDirectory(path) {
24
+ if (typeof path !== 'string' || path.length === 0) return false
25
+ try {
26
+ return statSync(path).isDirectory()
27
+ } catch {
28
+ return false
29
+ }
30
+ }
31
+
32
+ /** ReMe 健康检查:POST /health_check,兼容 success / metadata.health / answer 三种成功标志。 */
33
+ async function checkReme(config) {
34
+ const endpoint = String(config?.remeEndpoint ?? '').replace(/\/+$/, '')
35
+ if (!endpoint) {
36
+ return { state: 'disconnected', endpoint, checkedAt: now(), message: '尚未配置 ReMe 地址' }
37
+ }
38
+ const controller = new AbortController()
39
+ const timer = setTimeout(() => controller.abort(), REME_TIMEOUT_MS)
40
+ try {
41
+ const response = await fetch(`${endpoint}/health_check`, {
42
+ method: 'POST',
43
+ headers: { 'content-type': 'application/json' },
44
+ // 当前 ReMe(0.4.2.3)要求带 JSON body,空对象即可。
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 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
+ function generatedState(home) {
106
+ const empty = { memory: false, self: false, diaryCount: 0, latestDiary: null }
107
+ if (!home) return empty
108
+ const memory = readTextIfExists(join(home, 'MEMORY.md')) !== undefined
109
+ const self = readTextIfExists(join(home, 'self', '我.md')) !== undefined
110
+ let diaryCount = 0
111
+ let latestDiary = null
112
+ try {
113
+ for (const entry of readdirSync(join(home, 'diary'), { withFileTypes: true })) {
114
+ if (!entry.isFile()) continue
115
+ const match = DIARY_FILE_PATTERN.exec(entry.name)
116
+ if (!match) continue
117
+ diaryCount += 1
118
+ if (latestDiary === null || match[1] > latestDiary) latestDiary = match[1]
119
+ }
120
+ } catch {
121
+ /* 没有日记目录就按 0 篇处理 */
122
+ }
123
+ return { memory, self, diaryCount, latestDiary }
124
+ }
125
+
126
+ function imState(config) {
127
+ try {
128
+ return readImState(config)
129
+ } catch {
130
+ return { installed: false, compatible: false, accounts: [], error: '无法读取 IM 连接状态' }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * host = { ctx, config, lifecycle };也接受直接传 config,便于内部复用。
136
+ * lifecycle.operation 非空时(reincarnating)优先生效。
137
+ */
138
+ export async function readStatus(host) {
139
+ const config = host?.config ?? host ?? {}
140
+ const home = typeof config?.taHome === 'string' ? config.taHome : ''
141
+ const existing = isDirectory(home)
142
+ const marker = existing ? readHomeMarker(home) : { exists: false, valid: false }
143
+ const homeMarked = existing && marker.valid
144
+ const writable = existing && isWritableDirectory(home)
145
+ const persona = personaState(config, existing)
146
+ // 初始化只取决于「家」:有效标记,或带人设的老家。人设内容可以稍后补。
147
+ const initialized = existing && (homeMarked || persona.soul || persona.user)
148
+ const generated = existing ? generatedState(home) : generatedState('')
149
+ const [reme, im] = await Promise.all([checkReme(config), Promise.resolve(imState(config))])
150
+ const operation = host?.lifecycle?.operation ?? null
151
+ return {
152
+ initialized,
153
+ lifecycle: operation ?? (initialized ? 'initialized' : 'uninitialized'),
154
+ home,
155
+ homeMarked,
156
+ writable,
157
+ existing,
158
+ persona,
159
+ generated,
160
+ reme,
161
+ im,
162
+ updatedAt: now(),
163
+ }
164
+ }