dsh-ta 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +95 -0
- package/README.md +160 -107
- package/cordis.patch.yml +5 -35
- package/docs/RELEASE.md +62 -49
- package/docs/USAGE.md +6 -7
- package/docs/presets.example.yml +7 -43
- package/index.js +3 -164
- package/package.json +5 -28
- package/src/client/client.js +3176 -0
- package/{config.js → src/host/config.js} +39 -3
- package/src/host/constants.js +7 -0
- package/src/host/gates.js +34 -0
- package/src/host/identity.js +145 -0
- package/{im → src/host/im}/bindings.js +1 -1
- package/src/host/index.js +173 -0
- package/{jurisdiction.js → src/host/jurisdiction.js} +1 -1
- package/src/host/maintenance/collect.js +362 -0
- package/src/host/maintenance/completions.js +56 -0
- package/src/host/maintenance/consumption.js +67 -0
- package/src/host/maintenance/cursors.js +53 -0
- package/src/host/maintenance/engine.js +392 -0
- package/src/host/maintenance/llm.js +381 -0
- package/src/host/maintenance/lock.js +105 -0
- package/src/host/maintenance/prompts.js +255 -0
- package/src/host/maintenance/runs.js +47 -0
- package/src/host/maintenance/schedule.js +173 -0
- package/src/host/maintenance/session-cleanup.js +289 -0
- package/src/host/maintenance/session-watcher.js +107 -0
- package/src/host/maintenance/sleep.js +3 -0
- package/src/host/maintenance/stages.js +241 -0
- package/src/host/maintenance/state.js +192 -0
- package/src/host/prompts.js +96 -0
- package/src/host/records.js +175 -0
- package/src/host/runtime-manager.js +287 -0
- package/{runtime.js → src/host/runtime.js} +6 -8
- package/src/host/settings/defaults.js +55 -0
- package/{settings → src/host/settings}/home.js +4 -3
- package/{settings/routes.js → src/host/settings/http.js} +5 -137
- package/{settings → src/host/settings}/im.js +18 -1
- package/{settings → src/host/settings}/lifecycle.js +29 -43
- package/src/host/settings/persona.js +113 -0
- package/src/host/settings/routes.js +229 -0
- package/{settings → src/host/settings}/status.js +70 -42
- package/src/host/state/appraisals.js +56 -0
- package/src/host/state/feel.js +78 -0
- package/src/host/state/index.js +9 -0
- package/src/host/state/mood.js +103 -0
- package/src/host/state/notes.js +18 -0
- package/{life.js → src/host/state/outing.js} +13 -136
- package/src/host/state/values.js +9 -0
- package/{stickers → src/host/stickers}/tool.js +1 -1
- package/src/host/storage/fs.js +29 -0
- package/src/host/storage/index.js +8 -0
- package/src/host/storage/paths.js +20 -0
- package/src/host/storage/revision.js +5 -0
- package/src/host/storage/session-state.js +38 -0
- package/src/host/storage/time.js +127 -0
- package/src/host/tools/index.js +152 -0
- package/src/host/tools/read.js +252 -0
- package/src/host/tools/shared.js +23 -0
- package/src/host/tools/wiki.js +35 -0
- package/src/host/tools/write.js +164 -0
- package/{usage → src/host/usage}/aggregate.js +4 -1
- package/{usage → src/host/usage}/ledger.js +47 -21
- package/client.js +0 -2554
- package/gates.js +0 -18
- package/identity.js +0 -97
- package/prompts.js +0 -28
- package/runtime-manager.js +0 -153
- package/settings/defaults.js +0 -41
- package/settings/persona.js +0 -203
- package/settings/schedule.js +0 -156
- package/storage.js +0 -122
- package/tools.js +0 -540
- /package/{im → src/host/im}/say.js +0 -0
- /package/{memory → src/host/memory}/capture.js +0 -0
- /package/{memory → src/host/memory}/messages.js +0 -0
- /package/{memory → src/host/memory}/outbox.js +0 -0
- /package/{reme.js → src/host/reme.js} +0 -0
- /package/{settings → src/host/settings}/errors.js +0 -0
- /package/{stickers → src/host/stickers}/load.js +0 -0
- /package/{stickers → src/host/stickers}/select.js +0 -0
- /package/{stickers → src/host/stickers}/serve.js +0 -0
- /package/{usage → src/host/usage}/pricing.js +0 -0
- /package/{usage → src/host/usage}/serve.js +0 -0
|
@@ -0,0 +1,287 @@
|
|
|
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
|
+
// 家还不存在(全新安装、家已删除)时不要建维护任务,否则会在缺失的 cwd 上
|
|
91
|
+
// 每天新建一个无法完成维护的会话。
|
|
92
|
+
if (!this.engine || !homeExists(this.config)) return
|
|
93
|
+
const schedule = this.ctx.get?.('schedule')
|
|
94
|
+
if (!schedule?.catalog) {
|
|
95
|
+
try { this.engine?.start() } catch { /* engine start is best effort */ }
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
this.schedulePending = true
|
|
99
|
+
void ensureMaintenanceSchedule(this.ctx, this.config)
|
|
100
|
+
.then(result => {
|
|
101
|
+
if (this.disposed) {
|
|
102
|
+
// ensure 可能晚于 dispose 完成;把刚建出来的任务再清掉,避免留下无工具可用
|
|
103
|
+
// 的“TA 维护”任务。
|
|
104
|
+
try { void removeMaintenanceSchedule(this.ctx) } catch { /* best effort */ }
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
if (result?.active) {
|
|
108
|
+
this.scheduleActive = true
|
|
109
|
+
this.engine?.stopTimer()
|
|
110
|
+
} else {
|
|
111
|
+
this.scheduleActive = false
|
|
112
|
+
this.engine?.start()
|
|
113
|
+
}
|
|
114
|
+
})
|
|
115
|
+
.catch(cause => {
|
|
116
|
+
if (this.disposed) return
|
|
117
|
+
this.scheduleActive = false
|
|
118
|
+
this.logger?.warn?.(`[dsh-ta] schedule 维护任务不可用,退回插件内定时器:${cause instanceof Error ? cause.message : String(cause)}`)
|
|
119
|
+
try { this.engine?.start() } catch { /* best effort */ }
|
|
120
|
+
})
|
|
121
|
+
.finally(() => { this.schedulePending = false })
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
handle(session, event) {
|
|
125
|
+
if (this.disposed) return
|
|
126
|
+
try {
|
|
127
|
+
this.capture?.handle(session, event)
|
|
128
|
+
} catch {
|
|
129
|
+
/* adapter diagnostics must not stop sessions */
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
dispose() {
|
|
134
|
+
if (this.disposed) return
|
|
135
|
+
this.disposed = true
|
|
136
|
+
// 插件卸载/换家时移除官方任务,避免留下没有工具可用的空会话任务。
|
|
137
|
+
try { void removeMaintenanceSchedule(this.ctx) } catch { /* best effort */ }
|
|
138
|
+
try {
|
|
139
|
+
this.capture?.dispose()
|
|
140
|
+
} catch {
|
|
141
|
+
/* capture cleanup is best effort */
|
|
142
|
+
}
|
|
143
|
+
this.capture = undefined
|
|
144
|
+
try {
|
|
145
|
+
this.engine?.stop()
|
|
146
|
+
} catch {
|
|
147
|
+
/* 停止失败不阻塞换家 */
|
|
148
|
+
}
|
|
149
|
+
for (const cleanup of this.cleanups.splice(0).reverse()) {
|
|
150
|
+
try {
|
|
151
|
+
cleanup()
|
|
152
|
+
} catch {
|
|
153
|
+
/* each timer cleanup is independent */
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
whenIdle() {
|
|
159
|
+
try {
|
|
160
|
+
return this.engine?.whenIdle() ?? Promise.resolve(null)
|
|
161
|
+
} catch {
|
|
162
|
+
return Promise.resolve(null)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
runMaintenanceNow(options) {
|
|
167
|
+
return this.engine?.runNow(options) ?? { started: false, reason: 'disabled' }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
maintenanceStatus() {
|
|
171
|
+
const status = this.engine?.status()
|
|
172
|
+
return status ? { ...status, scheduleMode: this.scheduleActive ? 'official' : 'timer' } : null
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export class RuntimeManager {
|
|
177
|
+
constructor({ ctx, config, logger }) {
|
|
178
|
+
this.ctx = ctx
|
|
179
|
+
this.config = config
|
|
180
|
+
this.logger = logger
|
|
181
|
+
this.current = undefined
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
get running() {
|
|
185
|
+
return Boolean(this.current)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
get home() {
|
|
189
|
+
return this.current?.homeAtStart ?? this.config.taHome
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
get captureActive() {
|
|
193
|
+
return Boolean(this.current?.capture)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
get engine() {
|
|
197
|
+
return this.current?.engine
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 当前维护运行结束的 promise;转生/删旧家前用。 */
|
|
201
|
+
whenIdle() {
|
|
202
|
+
return this.current?.whenIdle() ?? Promise.resolve(null)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
runMaintenanceNow(options) {
|
|
206
|
+
return this.current?.runMaintenanceNow(options) ?? { started: false, reason: 'disabled' }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
maintenanceStatus() {
|
|
210
|
+
return this.current?.maintenanceStatus() ?? null
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
attachSchedule() {
|
|
214
|
+
this.current?.attachSchedule?.()
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
start() {
|
|
218
|
+
if (this.current && !this.current.disposed) return this.current
|
|
219
|
+
this.current = new RuntimeHandle({ ctx: this.ctx, config: this.config, logger: this.logger })
|
|
220
|
+
return this.current
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
stop() {
|
|
224
|
+
const current = this.current
|
|
225
|
+
this.current = undefined
|
|
226
|
+
try {
|
|
227
|
+
current?.dispose()
|
|
228
|
+
} catch (cause) {
|
|
229
|
+
this.logger?.warn?.(`[dsh-ta] runtime stop failed: ${cause instanceof Error ? cause.message : String(cause)}`)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
rebind() {
|
|
234
|
+
this.stop()
|
|
235
|
+
return this.start()
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
/** 有官方 schedule 就让 schedule 触发;没有就退回插件内定时器。 */
|
|
240
|
+
attachSchedule() {
|
|
241
|
+
if (this.disposed || this.scheduleActive || this.schedulePending) return
|
|
242
|
+
// 家还不存在(全新安装、家已删除)时不要建维护任务,否则会在缺失的 cwd 上
|
|
243
|
+
// 每天新建一个无法完成维护的会话。
|
|
244
|
+
if (!this.engine || !homeExists(this.config)) return
|
|
245
|
+
const schedule = this.ctx.get?.('schedule')
|
|
246
|
+
if (!schedule?.catalog) {
|
|
247
|
+
try { this.engine?.start() } catch { /* engine start is best effort */ }
|
|
248
|
+
return
|
|
249
|
+
}
|
|
250
|
+
this.schedulePending = true
|
|
251
|
+
void ensureMaintenanceSchedule(this.ctx, this.config)
|
|
252
|
+
.then(result => {
|
|
253
|
+
if (this.disposed) {
|
|
254
|
+
// ensure 可能晚于 dispose 完成;把刚建出来的任务再清掉,避免留下无工具可用
|
|
255
|
+
// 的“TA 维护”任务。
|
|
256
|
+
try { void removeMaintenanceSchedule(this.ctx) } catch { /* best effort */ }
|
|
257
|
+
return
|
|
258
|
+
}
|
|
259
|
+
if (result?.active) {
|
|
260
|
+
this.scheduleActive = true
|
|
261
|
+
this.engine?.stopTimer()
|
|
262
|
+
} else {
|
|
263
|
+
this.scheduleActive = false
|
|
264
|
+
this.engine?.start()
|
|
265
|
+
}
|
|
266
|
+
})
|
|
267
|
+
.catch(cause => {
|
|
268
|
+
if (this.disposed) return
|
|
269
|
+
this.scheduleActive = false
|
|
270
|
+
this.logger?.warn?.(`[dsh-ta] schedule 维护任务不可用,退回插件内定时器:${cause instanceof Error ? cause.message : String(cause)}`)
|
|
271
|
+
try { this.engine?.start() } catch { /* best effort */ }
|
|
272
|
+
})
|
|
273
|
+
.finally(() => { this.schedulePending = false })
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
handle(session, event) {
|
|
277
|
+
this.current?.handle(session, event)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
handleDispose(session) {
|
|
281
|
+
this.handle(session, { type: 'session/disposed' })
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
dispose() {
|
|
285
|
+
this.stop()
|
|
286
|
+
}
|
|
287
|
+
}
|
|
@@ -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 './
|
|
5
|
-
import {
|
|
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 ||
|
|
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 =
|
|
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 ||
|
|
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 ||
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
12
|
-
} from './
|
|
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
|
+
}
|