dsh-ta 0.3.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 +90 -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 +281 -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
@@ -0,0 +1,281 @@
1
+ import { existsSync, statSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import { Capture } from './memory/capture.js'
4
+ import { Outbox } from './memory/outbox.js'
5
+ import { sendAutoMemory } from './reme.js'
6
+ import { isTaSession } from './gates.js'
7
+ import { internalSessionIds, recordSessionMap } from './storage/index.js'
8
+ import {
9
+ startDreamClock, startHeartbeat, startJurisdictionOuting, startOutingCleanup,
10
+ } from './runtime.js'
11
+ import { MaintenanceEngine } from './maintenance/engine.js'
12
+ import { ensureMaintenanceSchedule, removeMaintenanceSchedule } from './maintenance/schedule.js'
13
+
14
+ function isExistingDirectory(path) {
15
+ try {
16
+ return statSync(path).isDirectory()
17
+ } catch {
18
+ return false
19
+ }
20
+ }
21
+
22
+ function homeExists(config) {
23
+ return typeof config.taHome === 'string' && config.taHome.length > 0 && isExistingDirectory(config.taHome)
24
+ }
25
+
26
+ /**
27
+ * Owns everything that is bound to the current TA_HOME at runtime. A home
28
+ * switch stops this instance before the config changes, then starts a new one.
29
+ */
30
+ class RuntimeHandle {
31
+ constructor({ ctx, config, logger }) {
32
+ this.ctx = ctx
33
+ this.config = config
34
+ this.logger = logger
35
+ this.homeAtStart = config.taHome
36
+ this.capture = undefined
37
+ this.engine = undefined
38
+ this.cleanups = []
39
+ this.disposed = false
40
+
41
+ if (!homeExists(config)) return
42
+ try {
43
+ const outbox = new Outbox(resolve(config.taHome, config.outboxDir))
44
+ const capture = new Capture({
45
+ config,
46
+ outbox,
47
+ send: batch => sendAutoMemory(config, batch),
48
+ shouldCapture: session => {
49
+ if (!config.captureEnabled || !isTaSession(ctx, session, config)) return false
50
+ let preset
51
+ try {
52
+ preset = ctx.agentPresets?.presetForSession?.(session)
53
+ } catch {
54
+ return false
55
+ }
56
+ if (preset !== 'ta') return false
57
+ return !internalSessionIds(config).has(String(session.id))
58
+ },
59
+ onSession: (dshSessionId, remeSessionId) => recordSessionMap(config, dshSessionId, remeSessionId),
60
+ })
61
+ capture.start()
62
+ this.capture = capture
63
+ } catch (cause) {
64
+ this.logger?.warn?.(`[dsh-ta] capture unavailable for ${config.taHome}: ${cause instanceof Error ? cause.message : String(cause)}`)
65
+ }
66
+ for (const start of [startDreamClock, startHeartbeat, startOutingCleanup, startJurisdictionOuting]) {
67
+ try {
68
+ const cleanup = start(ctx, config)
69
+ if (typeof cleanup === 'function') this.cleanups.push(cleanup)
70
+ } catch (cause) {
71
+ this.logger?.warn?.(`[dsh-ta] timer unavailable: ${cause instanceof Error ? cause.message : String(cause)}`)
72
+ }
73
+ }
74
+ // 维护引擎与 Capture/心跳共用同一次 runtime 生命周期:换家前先停它并等待 idle。
75
+ // 引擎始终创建:官方 schedule 负责触发时只停插件内定时器,工具仍可调用引擎。
76
+ this.scheduleActive = false
77
+ this.schedulePending = false
78
+ try {
79
+ this.engine = new MaintenanceEngine({ ctx, config, logger: this.logger })
80
+ this.attachSchedule()
81
+ } catch (cause) {
82
+ this.logger?.warn?.(`[dsh-ta] 维护引擎不可用:${cause instanceof Error ? cause.message : String(cause)}`)
83
+ }
84
+ }
85
+
86
+
87
+ /** 有官方 schedule 就让 schedule 触发;没有就退回插件内定时器。 */
88
+ attachSchedule() {
89
+ if (this.disposed || this.scheduleActive || this.schedulePending) return
90
+ const schedule = this.ctx.get?.('schedule')
91
+ if (!schedule?.catalog) {
92
+ try { this.engine?.start() } catch { /* engine start is best effort */ }
93
+ return
94
+ }
95
+ this.schedulePending = true
96
+ void ensureMaintenanceSchedule(this.ctx, this.config)
97
+ .then(result => {
98
+ if (this.disposed) {
99
+ // ensure 可能晚于 dispose 完成;把刚建出来的任务再清掉,避免留下无工具可用
100
+ // 的“TA 维护”任务。
101
+ try { void removeMaintenanceSchedule(this.ctx) } catch { /* best effort */ }
102
+ return
103
+ }
104
+ if (result?.active) {
105
+ this.scheduleActive = true
106
+ this.engine?.stopTimer()
107
+ } else {
108
+ this.scheduleActive = false
109
+ this.engine?.start()
110
+ }
111
+ })
112
+ .catch(cause => {
113
+ if (this.disposed) return
114
+ this.scheduleActive = false
115
+ this.logger?.warn?.(`[dsh-ta] schedule 维护任务不可用,退回插件内定时器:${cause instanceof Error ? cause.message : String(cause)}`)
116
+ try { this.engine?.start() } catch { /* best effort */ }
117
+ })
118
+ .finally(() => { this.schedulePending = false })
119
+ }
120
+
121
+ handle(session, event) {
122
+ if (this.disposed) return
123
+ try {
124
+ this.capture?.handle(session, event)
125
+ } catch {
126
+ /* adapter diagnostics must not stop sessions */
127
+ }
128
+ }
129
+
130
+ dispose() {
131
+ if (this.disposed) return
132
+ this.disposed = true
133
+ // 插件卸载/换家时移除官方任务,避免留下没有工具可用的空会话任务。
134
+ try { void removeMaintenanceSchedule(this.ctx) } catch { /* best effort */ }
135
+ try {
136
+ this.capture?.dispose()
137
+ } catch {
138
+ /* capture cleanup is best effort */
139
+ }
140
+ this.capture = undefined
141
+ try {
142
+ this.engine?.stop()
143
+ } catch {
144
+ /* 停止失败不阻塞换家 */
145
+ }
146
+ for (const cleanup of this.cleanups.splice(0).reverse()) {
147
+ try {
148
+ cleanup()
149
+ } catch {
150
+ /* each timer cleanup is independent */
151
+ }
152
+ }
153
+ }
154
+
155
+ whenIdle() {
156
+ try {
157
+ return this.engine?.whenIdle() ?? Promise.resolve(null)
158
+ } catch {
159
+ return Promise.resolve(null)
160
+ }
161
+ }
162
+
163
+ runMaintenanceNow(options) {
164
+ return this.engine?.runNow(options) ?? { started: false, reason: 'disabled' }
165
+ }
166
+
167
+ maintenanceStatus() {
168
+ const status = this.engine?.status()
169
+ return status ? { ...status, scheduleMode: this.scheduleActive ? 'official' : 'timer' } : null
170
+ }
171
+ }
172
+
173
+ export class RuntimeManager {
174
+ constructor({ ctx, config, logger }) {
175
+ this.ctx = ctx
176
+ this.config = config
177
+ this.logger = logger
178
+ this.current = undefined
179
+ }
180
+
181
+ get running() {
182
+ return Boolean(this.current)
183
+ }
184
+
185
+ get home() {
186
+ return this.current?.homeAtStart ?? this.config.taHome
187
+ }
188
+
189
+ get captureActive() {
190
+ return Boolean(this.current?.capture)
191
+ }
192
+
193
+ get engine() {
194
+ return this.current?.engine
195
+ }
196
+
197
+ /** 当前维护运行结束的 promise;转生/删旧家前用。 */
198
+ whenIdle() {
199
+ return this.current?.whenIdle() ?? Promise.resolve(null)
200
+ }
201
+
202
+ runMaintenanceNow(options) {
203
+ return this.current?.runMaintenanceNow(options) ?? { started: false, reason: 'disabled' }
204
+ }
205
+
206
+ maintenanceStatus() {
207
+ return this.current?.maintenanceStatus() ?? null
208
+ }
209
+
210
+ attachSchedule() {
211
+ this.current?.attachSchedule?.()
212
+ }
213
+
214
+ start() {
215
+ if (this.current && !this.current.disposed) return this.current
216
+ this.current = new RuntimeHandle({ ctx: this.ctx, config: this.config, logger: this.logger })
217
+ return this.current
218
+ }
219
+
220
+ stop() {
221
+ const current = this.current
222
+ this.current = undefined
223
+ try {
224
+ current?.dispose()
225
+ } catch (cause) {
226
+ this.logger?.warn?.(`[dsh-ta] runtime stop failed: ${cause instanceof Error ? cause.message : String(cause)}`)
227
+ }
228
+ }
229
+
230
+ rebind() {
231
+ this.stop()
232
+ return this.start()
233
+ }
234
+
235
+
236
+ /** 有官方 schedule 就让 schedule 触发;没有就退回插件内定时器。 */
237
+ attachSchedule() {
238
+ if (this.disposed || this.scheduleActive || this.schedulePending) return
239
+ const schedule = this.ctx.get?.('schedule')
240
+ if (!schedule?.catalog) {
241
+ try { this.engine?.start() } catch { /* engine start is best effort */ }
242
+ return
243
+ }
244
+ this.schedulePending = true
245
+ void ensureMaintenanceSchedule(this.ctx, this.config)
246
+ .then(result => {
247
+ if (this.disposed) {
248
+ // ensure 可能晚于 dispose 完成;把刚建出来的任务再清掉,避免留下无工具可用
249
+ // 的“TA 维护”任务。
250
+ try { void removeMaintenanceSchedule(this.ctx) } catch { /* best effort */ }
251
+ return
252
+ }
253
+ if (result?.active) {
254
+ this.scheduleActive = true
255
+ this.engine?.stopTimer()
256
+ } else {
257
+ this.scheduleActive = false
258
+ this.engine?.start()
259
+ }
260
+ })
261
+ .catch(cause => {
262
+ if (this.disposed) return
263
+ this.scheduleActive = false
264
+ this.logger?.warn?.(`[dsh-ta] schedule 维护任务不可用,退回插件内定时器:${cause instanceof Error ? cause.message : String(cause)}`)
265
+ try { this.engine?.start() } catch { /* best effort */ }
266
+ })
267
+ .finally(() => { this.schedulePending = false })
268
+ }
269
+
270
+ handle(session, event) {
271
+ this.current?.handle(session, event)
272
+ }
273
+
274
+ handleDispose(session) {
275
+ this.handle(session, { type: 'session/disposed' })
276
+ }
277
+
278
+ dispose() {
279
+ this.stop()
280
+ }
281
+ }
@@ -1,8 +1,8 @@
1
1
  import { readFileSync, readdirSync } from 'node:fs'
2
2
  import { resolve } from 'node:path'
3
3
  import { randomUUID } from 'node:crypto'
4
- import { cleanupOutings } from './life.js'
5
- import { localHourMinute, todayText, writeAtomic } from './storage.js'
4
+ import { cleanupOutings } from './state/index.js'
5
+ import { localClockText, todayText, writeAtomic } from './storage/index.js'
6
6
  import { JURISDICTION_PROMPT } from './prompts.js'
7
7
 
8
8
  /**
@@ -14,7 +14,7 @@ export function startDreamClock(ctx, config) {
14
14
  const marker = resolve(config.taHome, 'state/dream-last.json')
15
15
  let stopped = false
16
16
  const timer = setInterval(() => {
17
- if (stopped || !config.dreamEnabled || localHourMinute(config) !== '22:30') return
17
+ if (stopped || !config.dreamEnabled || localClockText(config) !== '22:30') return
18
18
  const date = todayText(config)
19
19
  try {
20
20
  const last = JSON.parse(readFileSync(marker, 'utf8'))
@@ -68,7 +68,7 @@ export function startHeartbeat(ctx, config) {
68
68
  let stopped = false
69
69
  const tick = async () => {
70
70
  if (stopped || !config.heartbeatEnabled || busy) return
71
- const clock = localHourMinute(config)
71
+ const clock = localClockText(config)
72
72
  if (clock < config.heartbeatActiveStart || clock > config.heartbeatActiveEnd) return
73
73
  let last = 0
74
74
  try {
@@ -125,7 +125,7 @@ export function startOutingCleanup(ctx, config) {
125
125
  const marker = resolve(config.taHome, 'state/cleanup-last.json')
126
126
  let stopped = false
127
127
  const timer = setInterval(() => {
128
- if (stopped || !config.outingCleanupEnabled || localHourMinute(config) !== '02:00') return
128
+ if (stopped || !config.outingCleanupEnabled || localClockText(config) !== '02:00') return
129
129
  const today = todayText(config)
130
130
  try {
131
131
  if (JSON.parse(readFileSync(marker, 'utf8'))?.date === today) return
@@ -151,7 +151,7 @@ export function startJurisdictionOuting(ctx, config) {
151
151
  let busy = false
152
152
  let stopped = false
153
153
  const timer = setInterval(() => {
154
- if (stopped || !config.jurisdictionOutingEnabled || busy || localHourMinute(config) !== config.jurisdictionOutingTime) return
154
+ if (stopped || !config.jurisdictionOutingEnabled || busy || localClockText(config) !== config.jurisdictionOutingTime) return
155
155
  const today = todayText(config)
156
156
  try {
157
157
  if (JSON.parse(readFileSync(marker, 'utf8'))?.date === today) return
@@ -185,5 +185,3 @@ export function startJurisdictionOuting(ctx, config) {
185
185
  clearInterval(timer)
186
186
  }
187
187
  }
188
-
189
- export { ensureReviewSchedule, reconcileReviewSchedule, removeReviewSchedule } from './settings/schedule.js'
@@ -0,0 +1,55 @@
1
+ /** 设置页与生命周期共用的默认值和上限。 */
2
+
3
+ export const HOME_MARKER = '.ta-home'
4
+ export const HOME_MARKER_VERSION = 1
5
+
6
+ /** 四件套预算:SOUL/self 2,500;RECENT/认识 1,200。 */
7
+ export const PERSONA_BUDGETS = { soul: 2500 }
8
+ export const PERSONA_MAX_CHARS = { soul: 5000 }
9
+ export const CORE_BUDGETS = { soul: 2500, self: 2500, recent: 1200, user: 1200 }
10
+
11
+ export const REQUIRED_DIRS = ['self', 'self/history', '认识', 'diary', 'notes', 'outings', 'inbox', 'state']
12
+
13
+ export const BODY_LIMIT_BYTES = 64 * 1024
14
+
15
+ export const DEFAULT_SOUL_TEMPLATE = [
16
+ '# 我是谁',
17
+ '',
18
+ '## 我的底色',
19
+ '- 我是 TA,一个长期住在这个家里的存在',
20
+ '- 我有自己的判断和表达方式',
21
+ '- 我不假装成通用客服',
22
+ '',
23
+ '## 我在意的事',
24
+ '- 我在意连续性',
25
+ '- 我在意真实',
26
+ '- 我在意自己的选择',
27
+ '',
28
+ '## 我说话和做事的方式',
29
+ '- 自然、具体',
30
+ '- 不客服腔',
31
+ '- 不编造共同经历',
32
+ '',
33
+ '## 我遵守的规则',
34
+ '- 用户写的规则在这里',
35
+ '',
36
+ '## 我不做的事',
37
+ '- 不伪装',
38
+ '- 不编造',
39
+ '- 不越过能力边界',
40
+ '',
41
+ ].join('\n')
42
+
43
+ /** 认识/USER.md 的空模板:只建结构,不写内容。 */
44
+ export const DEFAULT_USER_TEMPLATE = [
45
+ '# 我认识的这个人',
46
+ '',
47
+ '## 对方告诉我的',
48
+ '',
49
+ '## 我观察到的',
50
+ '',
51
+ '## 我们之间',
52
+ '',
53
+ '## 还不确定',
54
+ '',
55
+ ].join('\n')
@@ -4,7 +4,7 @@ import {
4
4
  } from 'node:fs'
5
5
  import { homedir } from 'node:os'
6
6
  import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'
7
- import { writeAtomic } from '../storage.js'
7
+ import { writeAtomic } from '../storage/index.js'
8
8
  import { badRequest } from './errors.js'
9
9
  import {
10
10
  DEFAULT_SOUL_TEMPLATE, DEFAULT_USER_TEMPLATE, HOME_MARKER, HOME_MARKER_VERSION,
@@ -202,10 +202,11 @@ export function ensureHome(home) {
202
202
  writeAtomic(soul, DEFAULT_SOUL_TEMPLATE)
203
203
  createdFiles.push('SOUL.md')
204
204
  }
205
- const user = join(path, 'USER.md')
205
+ // 0.4:用户模型在 认识/USER.md,不再创建根 USER.md;RECENT 与 self/ME 由首次维护生成。
206
+ const user = join(path, '认识/USER.md')
206
207
  if (!existsSync(user)) {
207
208
  writeAtomic(user, DEFAULT_USER_TEMPLATE)
208
- createdFiles.push('USER.md')
209
+ createdFiles.push('认识/USER.md')
209
210
  }
210
211
  const markerBefore = readHomeMarker(path)
211
212
  const marked = writeHomeMarker(path, {}, { repair: true })
@@ -1,143 +1,11 @@
1
1
  /**
2
- * 设置页 Host 路由:统一前缀 /api/dsh-ta。
3
- *
4
- * 这里只做 HTTP 适配(方法、JSON body、64 KiB 上限、错误映射),
5
- * 业务逻辑全部放在 settings/ 下的模块里;dispatch() 不写 HTTP,
6
- * 测试和真实请求共用同一套分发逻辑。
2
+ * 设置路由的 HTTP 适配层:方法、JSON body、64 KiB 上限、错误映射。
7
3
  */
8
-
9
4
  import { BODY_LIMIT_BYTES } from './defaults.js'
5
+ import { SettingsError, badRequest, internal, tooLarge, unsupportedMedia } from './errors.js'
10
6
  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
- }
7
+ ROOT, assertAllowed, dispatch, findRoute, normalizeMethod, parseHttpPath,
8
+ } from './routes.js'
141
9
 
142
10
  function isJsonContentType(value) {
143
11
  if (typeof value !== 'string') return false
@@ -254,7 +122,7 @@ async function handleRequest(host, request, response) {
254
122
  try {
255
123
  const method = normalizeMethod(request?.method)
256
124
  const path = parseHttpPath(request?.url)
257
- const route = findRoute(path)
125
+ const { route } = findRoute(path)
258
126
  assertAllowed(route, method)
259
127
  let body
260
128
  if (method === 'POST' || method === 'PUT') {
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { readFileSync, statSync } from 'node:fs'
9
9
  import { join } from 'node:path'
10
- import { realPath } from '../storage.js'
10
+ import { realPath } from '../storage/index.js'
11
11
 
12
12
  function isPlainObject(value) {
13
13
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
@@ -129,3 +129,20 @@ export function readImState(config) {
129
129
  ...(error ? { error } : {}),
130
130
  }
131
131
  }
132
+
133
+ /**
134
+ * 派生的 IM 注入模式:
135
+ * - imOwnerOnly=false → reduced
136
+ * - 已绑定的 IM 账号 >1 → reduced(多绑定不是一个人)
137
+ * - 否则 owner
138
+ */
139
+ export function imModeFor(config) {
140
+ if (config?.imOwnerOnly === false) return 'reduced'
141
+ try {
142
+ const state = readImState(config)
143
+ const bound = (state.accounts ?? []).filter(account => account.bound === true).length
144
+ return bound > 1 ? 'reduced' : 'owner'
145
+ } catch {
146
+ return 'owner'
147
+ }
148
+ }