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,373 @@
1
+ /**
2
+ * TA 生命周期:初始化、转生。
3
+ *
4
+ * 两个入口都从 host 读取运行时依赖,并统一放进同一个串行队列里执行:
5
+ * host = { ctx, config, runtime, lifecycle, queue, logger, configEditor }
6
+ *
7
+ * lifecycle 是可变对象 { operation: null | 'reincarnating' },
8
+ * 供状态接口展示“正在转生”。所有写操作串行,失败不能把后续操作卡死。
9
+ */
10
+
11
+ import { AsyncLocalStorage } from 'node:async_hooks'
12
+ import { readdirSync, rmSync, statSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+ import { SettingsError, badRequest, conflict } from './errors.js'
15
+ import {
16
+ assertDestroyableHome, ensureHome, isTaHome, physicalPath, validateHomePath,
17
+ validateNewHome,
18
+ } from './home.js'
19
+
20
+ const QUIESCE_TIMEOUT_MS = 10_000
21
+
22
+ /**
23
+ * 创建串行队列。fn 抛错只影响本次调用,后续任务照常执行。
24
+ * 用 AsyncLocalStorage 识别“已在队列任务内部”的调用:直接执行而不是排到队尾,
25
+ * 避免路由层和生命周期层同时套队列时死锁。
26
+ */
27
+ export function createLifecycleQueue() {
28
+ const inside = new AsyncLocalStorage()
29
+ let tail = Promise.resolve()
30
+
31
+ const enqueue = fn => {
32
+ if (typeof fn !== 'function') return Promise.reject(new TypeError('queue 需要一个函数'))
33
+ if (inside.getStore() === enqueue) return Promise.resolve().then(fn)
34
+ const run = tail.then(() => inside.run(enqueue, fn))
35
+ tail = run.then(() => undefined, () => undefined)
36
+ return run
37
+ }
38
+ return enqueue
39
+ }
40
+
41
+ /** host 没有显式 queue 时,按 host 维度兜底一个,保证同一 host 的写操作仍串行。 */
42
+ const fallbackQueues = new WeakMap()
43
+
44
+ function queueFor(host) {
45
+ if (typeof host?.queue === 'function') return host.queue
46
+ if (host && (typeof host === 'object' || typeof host === 'function')) {
47
+ let queue = fallbackQueues.get(host)
48
+ if (!queue) {
49
+ queue = createLifecycleQueue()
50
+ fallbackQueues.set(host, queue)
51
+ }
52
+ return queue
53
+ }
54
+ return createLifecycleQueue()
55
+ }
56
+
57
+ function runQueued(host, fn) {
58
+ return queueFor(host)(fn)
59
+ }
60
+
61
+ function lifecycleOf(host) {
62
+ if (host?.lifecycle && typeof host.lifecycle === 'object') return host.lifecycle
63
+ const created = { operation: null }
64
+ if (host && typeof host === 'object') host.lifecycle = created
65
+ return created
66
+ }
67
+
68
+ function loggerOf(host) {
69
+ return host?.logger
70
+ }
71
+
72
+ function describe(cause) {
73
+ return cause instanceof Error ? cause.message : String(cause ?? '未知错误')
74
+ }
75
+
76
+ function warn(host, message) {
77
+ try {
78
+ loggerOf(host)?.warn?.(`[dsh-ta] ${message}`)
79
+ } catch {
80
+ /* 日志失败不能影响生命周期 */
81
+ }
82
+ }
83
+
84
+ function info(host, message) {
85
+ try {
86
+ loggerOf(host)?.info?.(`[dsh-ta] ${message}`)
87
+ } catch {
88
+ /* 日志失败不能影响生命周期 */
89
+ }
90
+ }
91
+
92
+ /** 路径比较以 realpath 后结果为准;用于判断“是不是同一个家”。 */
93
+ function samePath(left, right) {
94
+ if (typeof left !== 'string' || typeof right !== 'string') return false
95
+ if (!left || !right) return false
96
+ return physicalPath(left) === physicalPath(right)
97
+ }
98
+
99
+ /** 已初始化 = 目录存在,并且带有有效的 .ta-home 标记。 */
100
+ function isInitializedHome(home) {
101
+ if (typeof home !== 'string' || !home) return false
102
+ try {
103
+ if (!statSync(home).isDirectory()) return false
104
+ } catch {
105
+ return false
106
+ }
107
+ return isTaHome(home)
108
+ }
109
+
110
+ function configEditorOf(host) {
111
+ if (typeof host?.configEditor?.edit === 'function') return host.configEditor
112
+ const editor = host?.ctx?.get?.('configEditor')
113
+ return typeof editor?.edit === 'function' ? editor : undefined
114
+ }
115
+
116
+ function requireConfigEditor(host) {
117
+ const editor = configEditorOf(host)
118
+ if (!editor) {
119
+ throw new SettingsError(500, 'CONFIG_EDITOR_UNAVAILABLE', '无法写入配置:配置编辑器不可用')
120
+ }
121
+ return editor
122
+ }
123
+
124
+ /** 把 taHome 写进 profile 配置;写入完成后 volatile getter 会看到新值。 */
125
+ async function editTaHome(host, home) {
126
+ const editor = requireConfigEditor(host)
127
+ const entry = host?.ctx?.fiber?.entry
128
+ if (!entry) {
129
+ throw new SettingsError(500, 'CONFIG_EDITOR_UNAVAILABLE', '无法写入配置:找不到插件配置项')
130
+ }
131
+ await editor.edit(entry, current => ({ ...current, taHome: home }))
132
+ }
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
+
144
+ function stopRuntime(host) {
145
+ const runtime = host?.runtime
146
+ if (runtime && typeof runtime.stop === 'function') runtime.stop()
147
+ }
148
+
149
+ function startRuntime(host) {
150
+ const runtime = host?.runtime
151
+ if (runtime && typeof runtime.start === 'function') return runtime.start()
152
+ return undefined
153
+ }
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
+
169
+ function rebindRuntime(host) {
170
+ const runtime = host?.runtime
171
+ if (runtime && typeof runtime.rebind === 'function') return runtime.rebind()
172
+ stopRuntime(host)
173
+ return startRuntime(host)
174
+ }
175
+
176
+ /** 删除旧家前尽力停止/等待运行中的 TA 会话;超时只记录 warning。 */
177
+ async function quiesceHomeSessions(host, home) {
178
+ let agents
179
+ try {
180
+ agents = host?.ctx?.agents?.list?.()
181
+ } catch {
182
+ agents = undefined
183
+ }
184
+ if (!Array.isArray(agents) || agents.length === 0) return
185
+ const waits = []
186
+ for (const agent of agents) {
187
+ const cwd = agent?.session?.header?.cwd
188
+ if (typeof cwd !== 'string' || !samePath(cwd, home)) continue
189
+ try {
190
+ agent.cancel?.({ kind: 'hook', reason: 'ta-reincarnate-cleanup' })
191
+ } catch {
192
+ /* 取消失败仍尽量等待 */
193
+ }
194
+ try {
195
+ const idle = agent.whenIdle?.()
196
+ if (idle && typeof idle.then === 'function') waits.push(Promise.resolve(idle).catch(() => {}))
197
+ } catch {
198
+ /* whenIdle 不可用时继续 */
199
+ }
200
+ }
201
+ if (waits.length === 0) return
202
+ await Promise.race([
203
+ Promise.all(waits),
204
+ new Promise(resolvePromise => setTimeout(resolvePromise, QUIESCE_TIMEOUT_MS)),
205
+ ])
206
+ }
207
+
208
+ function busyError() {
209
+ return conflict('LIFECYCLE_BUSY', 'TA 正在转生中,请稍候再试')
210
+ }
211
+
212
+ function assertLifecycleIdle(host) {
213
+ if (lifecycleOf(host).operation) throw busyError()
214
+ }
215
+
216
+ function ensureResult(path, ensured) {
217
+ return {
218
+ initialized: true,
219
+ home: path,
220
+ created: ensured.created,
221
+ adopted: ensured.adopted,
222
+ marked: ensured.marked,
223
+ repairedMarker: ensured.repairedMarker === true,
224
+ createdDirs: ensured.createdDirs,
225
+ createdFiles: ensured.createdFiles,
226
+ }
227
+ }
228
+
229
+ /**
230
+ * 初始化 TA 的家。
231
+ *
232
+ * - 未初始化:校验路径 → 建家 → (路径和配置不同时)写 taHome → rebind → 同步回顾任务。
233
+ * - 已初始化且路径就是当前家:只补缺失的标记/模板,已有文件不覆盖;runtime 没跑就启动。
234
+ * - 已初始化但换了路径:拒绝,换家必须走转生。
235
+ */
236
+ export async function initializeHome(host, input) {
237
+ assertLifecycleIdle(host)
238
+ return runQueued(host, async () => {
239
+ const config = host?.config ?? {}
240
+ const currentHome = config.taHome
241
+ const initialized = isInitializedHome(currentHome)
242
+ const requested = validateHomePath(input?.path)
243
+
244
+ if (initialized) {
245
+ if (!samePath(requested.path, currentHome)) {
246
+ throw badRequest('ALREADY_INITIALIZED', 'TA 已经有了家,改变家请使用转生')
247
+ }
248
+ // 老用户补标记、补目录;ensureHome 只创建缺失项,绝不覆盖 SOUL.md / USER.md。
249
+ const ensured = ensureHome(currentHome)
250
+ const runtime = host?.runtime
251
+ if (runtime && typeof runtime.start === 'function' && runtime.running !== true) runtime.start()
252
+ info(host, `TA 的家已存在,补齐标记/模板:${ensured.path}`)
253
+ return {
254
+ ...ensureResult(ensured.path, ensured),
255
+ configChanged: false,
256
+ warnings: [],
257
+ }
258
+ }
259
+
260
+ let existingEntries = []
261
+ try {
262
+ existingEntries = readdirSync(requested.path)
263
+ } catch {
264
+ existingEntries = []
265
+ }
266
+ if (existingEntries.length > 0
267
+ && !isInitializedHome(requested.path)
268
+ && input?.confirmAdopt !== true) {
269
+ throw badRequest(
270
+ 'ADOPT_CONFIRM_REQUIRED',
271
+ '这个目录已有内容。确认接管后只会补写 .ta-home 和缺失的模板/目录,不会覆盖已有文件。',
272
+ )
273
+ }
274
+ const ensured = ensureHome(requested.path)
275
+ const configChanged = !samePath(ensured.path, currentHome)
276
+ const warnings = []
277
+ if (configChanged) {
278
+ await editTaHome(host, ensured.path)
279
+ }
280
+ rebindRuntime(host)
281
+ info(host, `TA 的家已初始化:${ensured.path}`)
282
+ return {
283
+ ...ensureResult(ensured.path, ensured),
284
+ configChanged,
285
+ warnings,
286
+ }
287
+ })
288
+ }
289
+
290
+ /**
291
+ * 转生:保留 ReMe 记忆,换一个全新的空家。
292
+ * 默认保留旧家;用户显式勾选并确认时,切换成功后删除旧家。
293
+ * 失败时尽量恢复旧 runtime(配置尚未改)或对新家 rebind;已创建的新家不删除。
294
+ */
295
+ export async function reincarnate(host, input) {
296
+ assertLifecycleIdle(host)
297
+ if (input?.confirm !== '转生') {
298
+ throw badRequest('CONFIRM_REQUIRED', '请输入“转生”以确认转生')
299
+ }
300
+ const config = host?.config ?? {}
301
+ const oldHome = config.taHome
302
+ if (!isInitializedHome(oldHome)) {
303
+ throw badRequest('NOT_INITIALIZED', 'TA 还没有家,请先初始化 TA 的家')
304
+ }
305
+ const deleteOldHome = input?.deleteOldHome === true
306
+ if (deleteOldHome) {
307
+ if (input?.deleteConfirm !== '删除旧家') {
308
+ throw badRequest('DELETE_CONFIRM_REQUIRED', '要删除旧家,请输入“删除旧家”确认')
309
+ }
310
+ // 在动任何东西之前先验证旧家可以安全删除。
311
+ assertDestroyableHome(oldHome, { ctx: host?.ctx })
312
+ }
313
+ const target = validateNewHome(oldHome, input?.newHome)
314
+ const lifecycle = lifecycleOf(host)
315
+ lifecycle.operation = 'reincarnating'
316
+
317
+ return runQueued(host, async () => {
318
+ let configChanged = false
319
+ let oldHomeDeleted = false
320
+ let ensured
321
+ const warnings = []
322
+ try {
323
+ stopRuntime(host)
324
+ await waitRuntimeIdle(host)
325
+ ensured = ensureHome(target.path)
326
+ await editTaHome(host, target.path)
327
+ configChanged = true
328
+ rebindRuntime(host)
329
+ if (deleteOldHome) {
330
+ try {
331
+ await waitRuntimeIdle(host)
332
+ await quiesceHomeSessions(host, oldHome)
333
+ rmSync(physicalPath(oldHome), { recursive: true, force: true })
334
+ oldHomeDeleted = true
335
+ info(host, `旧家已删除:${oldHome}`)
336
+ } catch (cleanupCause) {
337
+ warnings.push(`旧家删除失败,旧家仍保留:${describe(cleanupCause)}`)
338
+ warn(host, warnings[warnings.length - 1])
339
+ }
340
+ }
341
+ info(host, `TA 已转生:${oldHome} -> ${target.path}${oldHomeDeleted ? '(旧家已删除)' : '(旧家保留)'}`)
342
+ return { previousHome: oldHome, home: target.path, oldHomeDeleted, warnings }
343
+ } catch (cause) {
344
+ // 恢复:配置没改成 → 旧家继续可用;配置已指到新家 → 对新家 rebind。
345
+ if (!configChanged) {
346
+ try {
347
+ startRuntime(host)
348
+ } catch (recoverCause) {
349
+ warnings.push(`恢复旧 runtime 失败:${describe(recoverCause)}`)
350
+ }
351
+ // 只清理本次刚创建的新家;用户原有空目录不能删。
352
+ if (ensured?.created) {
353
+ try {
354
+ rmSync(target.path, { recursive: true, force: true })
355
+ } catch (cleanupCause) {
356
+ warnings.push(`清理未使用的新家失败:${describe(cleanupCause)}`)
357
+ }
358
+ }
359
+ } else {
360
+ try {
361
+ rebindRuntime(host)
362
+ } catch (recoverCause) {
363
+ warnings.push(`新家 runtime 启动失败:${describe(recoverCause)}`)
364
+ }
365
+ }
366
+ for (const message of warnings) warn(host, message)
367
+ if (cause instanceof SettingsError && cause.status === 400) throw cause
368
+ throw new SettingsError(500, 'REINCARNATE_FAILED', `转生失败:${describe(cause)}`)
369
+ } finally {
370
+ lifecycle.operation = null
371
+ }
372
+ })
373
+ }
@@ -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
+ }