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,316 @@
1
+ import {
2
+ accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync,
3
+ realpathSync, renameSync, statSync,
4
+ } from 'node:fs'
5
+ import { homedir } from 'node:os'
6
+ import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'
7
+ import { writeAtomic } from '../storage/index.js'
8
+ import { badRequest } from './errors.js'
9
+ import {
10
+ DEFAULT_SOUL_TEMPLATE, DEFAULT_USER_TEMPLATE, HOME_MARKER, HOME_MARKER_VERSION,
11
+ REQUIRED_DIRS,
12
+ } from './defaults.js'
13
+
14
+ const SYSTEM_DIRS = ['/', '/home', '/tmp', '/var', '/usr', '/etc', '/opt', '/root', '/bin', '/sbin', '/lib']
15
+
16
+ export function expandUserPath(raw) {
17
+ if (typeof raw !== 'string') return ''
18
+ const value = raw.trim()
19
+ if (!value) return ''
20
+ const home = process.env.HOME || homedir()
21
+ if (value === '~') return home
22
+ if (value.startsWith('~/')) return resolve(home, value.slice(2))
23
+ return isAbsolute(value) ? resolve(value) : ''
24
+ }
25
+
26
+ /**
27
+ * Resolve symlinks for the deepest existing ancestor, then append the missing
28
+ * tail. This keeps comparisons meaningful before a home directory exists.
29
+ */
30
+ export function physicalPath(value) {
31
+ let current = resolve(String(value ?? ''))
32
+ const tail = []
33
+ for (let depth = 0; depth < 64; depth += 1) {
34
+ try {
35
+ const real = realpathSync.native(current)
36
+ return tail.length === 0 ? real : resolve(real, ...tail.reverse())
37
+ } catch {
38
+ const parent = dirname(current)
39
+ if (parent === current) return resolve(String(value ?? ''))
40
+ tail.push(basename(current))
41
+ current = parent
42
+ }
43
+ }
44
+ return resolve(String(value ?? ''))
45
+ }
46
+
47
+ export function isSameOrInside(parent, child) {
48
+ const base = physicalPath(parent)
49
+ const target = physicalPath(child)
50
+ return target === base || target.startsWith(base + sep)
51
+ }
52
+
53
+ function nearestExistingAncestor(path) {
54
+ let current = path
55
+ for (let depth = 0; depth < 64; depth += 1) {
56
+ if (existsSync(current)) return current
57
+ const parent = dirname(current)
58
+ if (parent === current) return current
59
+ current = parent
60
+ }
61
+ return dirname(path)
62
+ }
63
+
64
+ function assertWritableAncestor(path) {
65
+ const ancestor = nearestExistingAncestor(path)
66
+ let stat
67
+ try {
68
+ stat = statSync(ancestor)
69
+ } catch {
70
+ throw badRequest('HOME_PATH_UNWRITABLE', '找不到可写的上级目录')
71
+ }
72
+ if (!stat.isDirectory()) throw badRequest('HOME_PATH_NOT_DIRECTORY', '上级路径不是目录')
73
+ try {
74
+ accessSync(ancestor, constants.W_OK)
75
+ } catch {
76
+ throw badRequest('HOME_PATH_UNWRITABLE', '上级目录不可写,请换一个路径')
77
+ }
78
+ }
79
+
80
+ /** Validate a path a user may adopt as TA_HOME (creation may be pending). */
81
+ export function validateHomePath(raw) {
82
+ const expanded = expandUserPath(raw)
83
+ if (!expanded) {
84
+ throw badRequest('HOME_PATH_INVALID', '请填写绝对路径,例如 ~/TATA/home')
85
+ }
86
+ const normalized = resolve(expanded)
87
+ if (normalized === parse(normalized).root) {
88
+ throw badRequest('HOME_PATH_FORBIDDEN', '不能把文件系统根目录作为 TA 的家')
89
+ }
90
+ const userHome = physicalPath(process.env.HOME || homedir())
91
+ if (physicalPath(normalized) === userHome) {
92
+ throw badRequest('HOME_PATH_FORBIDDEN', '不能把用户主目录本身作为 TA 的家')
93
+ }
94
+ if (existsSync(normalized)) {
95
+ let stat
96
+ try {
97
+ stat = statSync(normalized)
98
+ } catch {
99
+ throw badRequest('HOME_PATH_INVALID', '无法读取这个路径')
100
+ }
101
+ if (!stat.isDirectory()) {
102
+ throw badRequest('HOME_PATH_NOT_DIRECTORY', '这个路径已经存在,而且不是目录')
103
+ }
104
+ }
105
+ assertWritableAncestor(normalized)
106
+ return { path: normalized, physical: physicalPath(normalized) }
107
+ }
108
+
109
+ /** Validate the destination of a reincarnation. */
110
+ export function validateNewHome(oldHome, raw) {
111
+ const next = validateHomePath(raw)
112
+ const oldPhysical = physicalPath(oldHome)
113
+ const newPhysical = physicalPath(next.path)
114
+ if (newPhysical === oldPhysical) {
115
+ throw badRequest('NEW_HOME_SAME', '新家不能和旧家是同一个目录')
116
+ }
117
+ if (newPhysical.startsWith(oldPhysical + sep)) {
118
+ throw badRequest('NEW_HOME_INSIDE_OLD', '新家不能在旧家内部')
119
+ }
120
+ if (oldPhysical.startsWith(newPhysical + sep)) {
121
+ throw badRequest('NEW_HOME_ANCESTOR', '新家不能是旧家的上级目录')
122
+ }
123
+ let existed = false
124
+ if (existsSync(next.path)) {
125
+ existed = true
126
+ let entries = []
127
+ try {
128
+ entries = readdirSync(next.path)
129
+ } catch {
130
+ throw badRequest('NEW_HOME_UNREADABLE', '无法读取新家路径')
131
+ }
132
+ if (entries.length > 0) {
133
+ throw badRequest('NEW_HOME_NOT_EMPTY', '新家的目录必须为空,或尚未创建')
134
+ }
135
+ }
136
+ return { ...next, existed }
137
+ }
138
+
139
+ /** @returns {{ exists: boolean, valid: boolean, version?: number, createdAt?: string }} */
140
+ export function readHomeMarker(home) {
141
+ const target = join(home, HOME_MARKER)
142
+ if (!existsSync(target)) return { exists: false, valid: false }
143
+ try {
144
+ const value = JSON.parse(readFileSync(target, 'utf8'))
145
+ const valid = Boolean(value)
146
+ && typeof value === 'object'
147
+ && value.version === HOME_MARKER_VERSION
148
+ && typeof value.createdAt === 'string'
149
+ return { exists: true, valid, version: value?.version, createdAt: value?.createdAt }
150
+ } catch {
151
+ return { exists: true, valid: false }
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Write the marker unless a valid one already exists. Returns whether this call
157
+ * wrote it. A damaged marker is only replaced when `repair` is explicitly set;
158
+ * the damaged file is renamed beside it rather than deleted.
159
+ */
160
+ export function writeHomeMarker(home, meta = {}, { repair = false } = {}) {
161
+ const existing = readHomeMarker(home)
162
+ if (existing.exists && existing.valid) return false
163
+ mkdirSync(home, { recursive: true, mode: 0o700 })
164
+ if (existing.exists) {
165
+ if (!repair) return false
166
+ const damaged = join(home, `${HOME_MARKER}.broken-${Date.now()}`)
167
+ try {
168
+ renameSync(join(home, HOME_MARKER), damaged)
169
+ } catch {
170
+ return false
171
+ }
172
+ }
173
+ writeAtomic(join(home, HOME_MARKER), JSON.stringify({
174
+ version: HOME_MARKER_VERSION,
175
+ createdAt: new Date().toISOString(),
176
+ kind: 'ta-home',
177
+ ...meta,
178
+ }, null, 2) + '\n')
179
+ return true
180
+ }
181
+
182
+ /**
183
+ * Create the standard structure in an empty directory, or adopt an existing
184
+ * directory without overwriting any file that is already there.
185
+ */
186
+ export function ensureHome(home) {
187
+ const { path } = validateHomePath(home)
188
+ const existed = existsSync(path)
189
+ const adopted = existed && readdirSync(path).length > 0
190
+ mkdirSync(path, { recursive: true, mode: 0o700 })
191
+ const createdDirs = []
192
+ for (const name of REQUIRED_DIRS) {
193
+ const directory = join(path, name)
194
+ if (!existsSync(directory)) {
195
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
196
+ createdDirs.push(name)
197
+ }
198
+ }
199
+ const createdFiles = []
200
+ const soul = join(path, 'SOUL.md')
201
+ if (!existsSync(soul)) {
202
+ writeAtomic(soul, DEFAULT_SOUL_TEMPLATE)
203
+ createdFiles.push('SOUL.md')
204
+ }
205
+ // 0.4:用户模型在 认识/USER.md,不再创建根 USER.md;RECENT 与 self/ME 由首次维护生成。
206
+ const user = join(path, '认识/USER.md')
207
+ if (!existsSync(user)) {
208
+ writeAtomic(user, DEFAULT_USER_TEMPLATE)
209
+ createdFiles.push('认识/USER.md')
210
+ }
211
+ const markerBefore = readHomeMarker(path)
212
+ const marked = writeHomeMarker(path, {}, { repair: true })
213
+ return {
214
+ path,
215
+ created: !existed,
216
+ adopted,
217
+ marked,
218
+ repairedMarker: markerBefore.exists && !markerBefore.valid && marked,
219
+ createdDirs,
220
+ createdFiles,
221
+ }
222
+ }
223
+
224
+ export function isTaHome(home) {
225
+ try {
226
+ if (!statSync(home).isDirectory()) return false
227
+ } catch {
228
+ return false
229
+ }
230
+ return readHomeMarker(home).valid
231
+ }
232
+
233
+ function protectedPaths(ctx, extra) {
234
+ const userHome = physicalPath(process.env.HOME || homedir())
235
+ const cwd = physicalPath(process.cwd())
236
+ const values = [...SYSTEM_DIRS, process.env.HOME || homedir()].map(value => ({
237
+ raw: value,
238
+ physical: physicalPath(value),
239
+ inside: false,
240
+ allowSelf: false,
241
+ }))
242
+ // DSH 常从 HOME 启动;此时 cwd 内部就是默认 TA 家所在位置,不能拒绝。
243
+ values.push({ raw: process.cwd(), physical: cwd, inside: cwd !== userHome, allowSelf: false })
244
+ for (const key of ['DSH_PROFILE_DIR', 'DSH_INSTALL_DIR', 'DSH_HOME']) {
245
+ if (process.env[key]) {
246
+ values.push({
247
+ raw: process.env[key],
248
+ physical: physicalPath(process.env[key]),
249
+ inside: true,
250
+ allowSelf: false,
251
+ })
252
+ }
253
+ }
254
+ try {
255
+ const workspaces = ctx?.get?.('workspaceRegistry')?.list?.()
256
+ for (const workspace of Array.isArray(workspaces) ? workspaces : []) {
257
+ if (typeof workspace?.path === 'string' && workspace.path) {
258
+ // TA 的家本来就会被注册成工作区(“去找TA”/自动注册),所以
259
+ // 工作区根只在它是 TA 家的上级目录时保护;与旧家本身相等时允许删除。
260
+ values.push({
261
+ raw: workspace.path,
262
+ physical: physicalPath(workspace.path),
263
+ inside: false,
264
+ allowSelf: true,
265
+ })
266
+ }
267
+ }
268
+ } catch {
269
+ /* workspace registry is optional; the static guards still apply */
270
+ }
271
+ for (const value of extra ?? []) {
272
+ if (typeof value === 'string' && value) {
273
+ values.push({ raw: value, physical: physicalPath(value), inside: true, allowSelf: false })
274
+ }
275
+ }
276
+ return values
277
+ }
278
+
279
+ /**
280
+ * Validate that a home may be deleted. Requires a valid marker and refuses
281
+ * protected directories, ancestors of protected directories, and locations
282
+ * inside the current project or DSH profile.
283
+ */
284
+ export function assertDestroyableHome(home, { ctx, extraProtected } = {}) {
285
+ const { path } = validateHomePath(home)
286
+ const marker = readHomeMarker(path)
287
+ if (!marker.exists) {
288
+ throw badRequest('HOME_NOT_MARKED', '这个目录没有 .ta-home 标记,不是 TA 的家')
289
+ }
290
+ if (!marker.valid) {
291
+ throw badRequest('HOME_MARKER_INVALID', '.ta-home 标记已损坏,拒绝删除')
292
+ }
293
+ const target = physicalPath(path)
294
+ const candidates = protectedPaths(ctx, extraProtected)
295
+ for (const candidate of candidates) {
296
+ if (!candidate.physical) continue
297
+ if (target === candidate.physical) {
298
+ if (candidate.allowSelf) continue
299
+ throw badRequest('HOME_PROTECTED', `拒绝删除受保护目录:${candidate.raw}`)
300
+ }
301
+ if (candidate.physical.startsWith(target + sep)) {
302
+ throw badRequest('HOME_CONTAINS_PROTECTED', `目录包含受保护路径:${candidate.raw}`)
303
+ }
304
+ if (candidate.inside && target.startsWith(candidate.physical + sep)) {
305
+ throw badRequest('HOME_INSIDE_PROTECTED', `拒绝删除受保护目录内部的路径:${candidate.raw}`)
306
+ }
307
+ }
308
+ for (const key of ['DSH_PROFILE_DIR', 'DSH_INSTALL_DIR']) {
309
+ if (!process.env[key]) continue
310
+ const protectedRoot = physicalPath(process.env[key])
311
+ if (target.startsWith(protectedRoot + sep)) {
312
+ throw badRequest('HOME_INSIDE_DSH', '拒绝删除 DSH 安装目录或 profile 内部的路径')
313
+ }
314
+ }
315
+ return target
316
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * 设置路由的 HTTP 适配层:方法、JSON body、64 KiB 上限、错误映射。
3
+ */
4
+ import { BODY_LIMIT_BYTES } from './defaults.js'
5
+ import { SettingsError, badRequest, internal, tooLarge, unsupportedMedia } from './errors.js'
6
+ import {
7
+ ROOT, assertAllowed, dispatch, findRoute, normalizeMethod, parseHttpPath,
8
+ } from './routes.js'
9
+
10
+ function isJsonContentType(value) {
11
+ if (typeof value !== 'string') return false
12
+ const [mediaType] = value.split(';')
13
+ return mediaType.trim().toLowerCase() === 'application/json'
14
+ }
15
+
16
+ function headerValue(headers, name) {
17
+ if (!headers || typeof headers !== 'object') return undefined
18
+ if (headers[name] !== undefined) return headers[name]
19
+ const key = Object.keys(headers).find(item => item.toLowerCase() === name.toLowerCase())
20
+ return key === undefined ? undefined : headers[key]
21
+ }
22
+
23
+ function assertJsonRequest(request) {
24
+ if (!isJsonContentType(headerValue(request?.headers, 'content-type'))) throw unsupportedMedia()
25
+ }
26
+
27
+ /** 用 for await 读取 body;超过 64 KiB 立即抛 413,由上层响应并结束请求。 */
28
+ async function readJsonBody(request) {
29
+ const declared = Number(headerValue(request?.headers, 'content-length'))
30
+ if (Number.isFinite(declared) && declared > BODY_LIMIT_BYTES) throw tooLarge()
31
+
32
+ const chunks = []
33
+ let size = 0
34
+ for await (const chunk of request) {
35
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
36
+ size += buffer.length
37
+ if (size > BODY_LIMIT_BYTES) throw tooLarge()
38
+ chunks.push(buffer)
39
+ }
40
+ const text = Buffer.concat(chunks).toString('utf8')
41
+ if (!text.trim()) throw badRequest('INVALID_JSON', '请求体不能为空')
42
+ try {
43
+ return JSON.parse(text)
44
+ } catch {
45
+ throw badRequest('INVALID_JSON', '请求体不是合法的 JSON')
46
+ }
47
+ }
48
+
49
+ function responseGone(response) {
50
+ return !response
51
+ || response.destroyed === true
52
+ || response.writableEnded === true
53
+ || response.headersSent === true
54
+ }
55
+
56
+ function writeJson(response, status, payload, extraHeaders, onEnd) {
57
+ if (responseGone(response)) return
58
+ const body = JSON.stringify(payload)
59
+ const headers = {
60
+ 'content-type': 'application/json; charset=utf-8',
61
+ 'cache-control': 'no-store',
62
+ ...(extraHeaders ?? {}),
63
+ }
64
+ try {
65
+ response.writeHead(status, headers)
66
+ if (typeof onEnd === 'function') response.end(body, onEnd)
67
+ else response.end(body)
68
+ } catch {
69
+ /* 客户端已经断开时不再抛错 */
70
+ }
71
+ }
72
+
73
+ function logWarn(host, message, error) {
74
+ try {
75
+ const logger = host?.logger ?? host?.ctx?.logger
76
+ logger?.warn?.(message, error)
77
+ } catch {
78
+ /* 日志失败不能影响响应 */
79
+ }
80
+ }
81
+
82
+ function mapError(host, error) {
83
+ if (error instanceof SettingsError) {
84
+ const headers = error.allow
85
+ ? { allow: Array.isArray(error.allow) ? error.allow.join(', ') : String(error.allow) }
86
+ : undefined
87
+ return {
88
+ status: error.status,
89
+ payload: { ok: false, error: { code: error.code, message: error.message } },
90
+ headers,
91
+ overflow: error.status === 413,
92
+ }
93
+ }
94
+ logWarn(host, `[dsh-ta] 设置接口处理失败:${error instanceof Error ? error.message : String(error)}`, error)
95
+ const fallback = internal()
96
+ return {
97
+ status: 500,
98
+ payload: { ok: false, error: { code: fallback.code, message: fallback.message } },
99
+ overflow: false,
100
+ }
101
+ }
102
+
103
+ function writeError(host, request, response, error) {
104
+ try {
105
+ const mapped = mapError(host, error)
106
+ const onEnd = mapped.overflow
107
+ ? () => {
108
+ try {
109
+ if (!request?.destroyed) request?.destroy?.()
110
+ } catch {
111
+ /* 请求已经结束 */
112
+ }
113
+ }
114
+ : undefined
115
+ writeJson(response, mapped.status, mapped.payload, mapped.headers, onEnd)
116
+ } catch {
117
+ /* 响应阶段不再抛错 */
118
+ }
119
+ }
120
+
121
+ async function handleRequest(host, request, response) {
122
+ try {
123
+ const method = normalizeMethod(request?.method)
124
+ const path = parseHttpPath(request?.url)
125
+ const { route } = findRoute(path)
126
+ assertAllowed(route, method)
127
+ let body
128
+ if (method === 'POST' || method === 'PUT') {
129
+ assertJsonRequest(request)
130
+ body = await readJsonBody(request)
131
+ }
132
+ const result = await dispatch(host, { method, path, body })
133
+ writeJson(response, result.status, result.payload)
134
+ } catch (error) {
135
+ writeError(host, request, response, error)
136
+ }
137
+ }
138
+
139
+ export function mountSettingsRoutes(ctx, config, host) {
140
+ if (typeof ctx?.inject !== 'function') return
141
+ const settingsHost = host ?? { ctx, config, logger: ctx?.logger }
142
+ try {
143
+ ctx.inject(['webServer'], scope => {
144
+ const server = scope?.webServer ?? scope?.get?.('webServer')
145
+ if (typeof server?.register !== 'function') return
146
+ if (typeof scope?.effect !== 'function') {
147
+ logWarn(settingsHost, '[dsh-ta] webServer 作用域缺少 effect,设置路由没有注册')
148
+ return
149
+ }
150
+ try {
151
+ scope.effect(() => server.register({
152
+ kind: 'prefix',
153
+ path: ROOT,
154
+ auth: 'required',
155
+ handler: (request, response) => handleRequest(settingsHost, request, response),
156
+ }), 'dsh-ta settings route')
157
+ } catch (error) {
158
+ logWarn(settingsHost, `[dsh-ta] 设置路由注册失败:${error instanceof Error ? error.message : String(error)}`, error)
159
+ }
160
+ })
161
+ } catch (error) {
162
+ logWarn(settingsHost, `[dsh-ta] 设置路由注入失败:${error instanceof Error ? error.message : String(error)}`, error)
163
+ }
164
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * im-connect 只读检测。
3
+ *
4
+ * 只读 config.imConnectDir 下的 channels.json 与 sessions.json,绝不修改文件,
5
+ * 也绝不把 appSecret / config / chatId / sessionId 等内部字段返回给设置页。
6
+ */
7
+
8
+ import { readFileSync, statSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { realPath } from '../storage/index.js'
11
+
12
+ function isPlainObject(value) {
13
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
14
+ }
15
+
16
+ function isDirectory(path) {
17
+ try {
18
+ return statSync(path).isDirectory()
19
+ } catch {
20
+ return false
21
+ }
22
+ }
23
+
24
+ /**
25
+ * 读取一个 JSON 文件,返回 { value } / { missing: true } / { invalid: true } / { error: true }。
26
+ * 任何异常都不要向上抛:设置页需要的是可展示的错误文案。
27
+ */
28
+ function readJson(path) {
29
+ let text
30
+ try {
31
+ text = readFileSync(path, 'utf8')
32
+ } catch (cause) {
33
+ return cause?.code === 'ENOENT' ? { missing: true } : { error: true }
34
+ }
35
+ try {
36
+ return { value: JSON.parse(text) }
37
+ } catch {
38
+ return { invalid: true }
39
+ }
40
+ }
41
+
42
+ /** sessions.json 中是否存在该 channel 的 :dm: 绑定。 */
43
+ function hasDirectBinding(channelId, sessions) {
44
+ for (const [key, binding] of Object.entries(sessions)) {
45
+ if (!key.includes(':dm:') || !isPlainObject(binding)) continue
46
+ if (key.startsWith(`${channelId}:dm:`) || binding.channel === channelId) return true
47
+ }
48
+ return false
49
+ }
50
+
51
+ /** 只挑选安全字段,账号配置里的密钥等内部信息一律不返回。 */
52
+ function accountView(key, channel, taHomePhysical, sessions) {
53
+ const id = typeof channel.id === 'string' && channel.id ? channel.id : key
54
+ const cwd = typeof channel.cwd === 'string' ? channel.cwd : ''
55
+ const agentPreset = typeof channel.agentPreset === 'string' ? channel.agentPreset : ''
56
+ const privateAccess = typeof channel.privateAccess === 'string' ? channel.privateAccess : ''
57
+ const groupAccess = typeof channel.groupAccess === 'string' ? channel.groupAccess : ''
58
+ const platform = typeof channel.platform === 'string' && channel.platform
59
+ ? channel.platform
60
+ : (id.includes('_') ? id.slice(0, id.indexOf('_')) : '')
61
+ const name = typeof channel.name === 'string' && channel.name.trim() ? channel.name : id
62
+
63
+ const reasons = []
64
+ if (!taHomePhysical || realPath(cwd) !== taHomePhysical) reasons.push('工作目录不是 TA 的家')
65
+ if (agentPreset !== 'ta') reasons.push('没有使用 ta 预设')
66
+ if (groupAccess !== 'disabled') reasons.push('群聊权限没有关闭')
67
+ if (privateAccess !== 'approved') reasons.push('私聊权限不是仅批准用户')
68
+ if (channel.enabled === false) reasons.push('账号已停用')
69
+
70
+ return {
71
+ id,
72
+ name,
73
+ platform,
74
+ compatible: reasons.length === 0,
75
+ cwd,
76
+ agentPreset,
77
+ privateAccess,
78
+ groupAccess,
79
+ bound: hasDirectBinding(id, sessions),
80
+ reasons,
81
+ }
82
+ }
83
+
84
+ /**
85
+ * 读取 IM 集成状态。
86
+ * 返回 { installed, compatible, accounts, error? }。
87
+ * installed:目录存在即视为已安装(channels.json 缺失时尤其依赖目录判断)。
88
+ */
89
+ export function readImState(config) {
90
+ const dir = typeof config?.imConnectDir === 'string' ? config.imConnectDir : ''
91
+ const installed = dir.length > 0 && isDirectory(dir)
92
+ const empty = { installed, compatible: false, accounts: [] }
93
+ if (!installed) return empty
94
+
95
+ const channelsRead = readJson(join(dir, 'channels.json'))
96
+ if (channelsRead.missing) return empty
97
+ if (channelsRead.error) return { ...empty, error: '无法读取 im-connect 账号配置(channels.json)' }
98
+ if (channelsRead.invalid) return { ...empty, error: 'im-connect 账号配置(channels.json)不是有效的 JSON' }
99
+ if (!isPlainObject(channelsRead.value)) return { ...empty, error: 'im-connect 账号配置格式不正确' }
100
+
101
+ // sessions.json 缺失是正常情况(还没绑定过会话),解析失败则要提示但保留账号列表。
102
+ const sessionsRead = readJson(join(dir, 'sessions.json'))
103
+ let sessions = {}
104
+ let error
105
+ if (sessionsRead.value !== undefined) {
106
+ if (isPlainObject(sessionsRead.value)) {
107
+ sessions = sessionsRead.value
108
+ } else {
109
+ error = 'im-connect 会话绑定格式不正确'
110
+ }
111
+ } else if (sessionsRead.invalid) {
112
+ error = 'im-connect 会话绑定(sessions.json)不是有效的 JSON'
113
+ } else if (sessionsRead.error) {
114
+ error = '无法读取 im-connect 会话绑定(sessions.json)'
115
+ }
116
+
117
+ const taHomePhysical = realPath(typeof config?.taHome === 'string' ? config.taHome : '')
118
+ const channelMap = isPlainObject(channelsRead.value.channels) ? channelsRead.value.channels : {}
119
+ const accounts = []
120
+ for (const [key, channel] of Object.entries(channelMap)) {
121
+ if (!isPlainObject(channel)) continue
122
+ accounts.push(accountView(key, channel, taHomePhysical, sessions))
123
+ }
124
+
125
+ return {
126
+ installed: true,
127
+ compatible: accounts.some(account => account.compatible),
128
+ accounts,
129
+ ...(error ? { error } : {}),
130
+ }
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
+ }