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.
- package/CHANGELOG.md +111 -1
- package/README.md +325 -140
- package/cordis.patch.yml +5 -35
- package/docs/RELEASE.md +63 -46
- package/docs/USAGE.md +25 -9
- package/docs/presets.example.yml +7 -43
- package/index.js +3 -170
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +6 -19
- package/src/client/client.js +3176 -0
- package/{config.js → src/host/config.js} +39 -4
- 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/{reme.js → src/host/reme.js} +3 -1
- package/src/host/runtime-manager.js +281 -0
- package/{runtime.js → src/host/runtime.js} +28 -50
- package/src/host/settings/defaults.js +55 -0
- package/src/host/settings/errors.js +29 -0
- package/src/host/settings/home.js +316 -0
- package/src/host/settings/http.js +164 -0
- package/src/host/settings/im.js +148 -0
- package/src/host/settings/lifecycle.js +373 -0
- package/src/host/settings/persona.js +113 -0
- package/src/host/settings/routes.js +229 -0
- package/src/host/settings/status.js +192 -0
- 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/src/host/usage/ledger.js +186 -0
- package/src/host/usage/serve.js +116 -0
- package/client.js +0 -618
- package/gates.js +0 -18
- package/identity.js +0 -97
- package/prompts.js +0 -28
- package/storage.js +0 -95
- package/tools.js +0 -540
- package/usage/ledger.js +0 -126
- package/usage/serve.js +0 -38
- /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/{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
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 删除薄触发维护会话:日志、投影缓存、rewind、工作区成员、归档、置顶、live store。
|
|
3
|
+
*
|
|
4
|
+
* 参考社区实现(dsh-session-ops / dsh-forget-session)的顺序:
|
|
5
|
+
* 1. 先摘工作区成员关系;
|
|
6
|
+
* 2. 再移除 live session;
|
|
7
|
+
* 3. 再清归档/置顶(顺序反了会留归档 id);
|
|
8
|
+
* 4. 最后删磁盘,并在短延迟后复查晚到写入。
|
|
9
|
+
* 没有官方删除 API,live detach 走 sessions.store 的内部通道;不可用时不删文件,
|
|
10
|
+
* 改为归档 + 清理队列,等下次插件启动(会话已冷)再删。
|
|
11
|
+
*/
|
|
12
|
+
import { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'
|
|
13
|
+
import { homedir } from 'node:os'
|
|
14
|
+
import { dirname, join, resolve } from 'node:path'
|
|
15
|
+
import { realPath, writeAtomic } from '../storage/index.js'
|
|
16
|
+
import { latestCompletion } from './completions.js'
|
|
17
|
+
|
|
18
|
+
export const CLEANUP_QUEUE_FILE = 'state/maintenance-session-cleanup.json'
|
|
19
|
+
function lateWriteWaitMs() {
|
|
20
|
+
return Number(process.env.DSH_TA_CLEANUP_WAIT_MS ?? 1500)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function dshHome() {
|
|
24
|
+
const raw = process.env.DSH_HOME
|
|
25
|
+
return raw && raw.trim() ? resolve(raw.trim()) : join(homedir(), '.dsh')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function cleanupQueuePath(config) {
|
|
29
|
+
return resolve(config.taHome, CLEANUP_QUEUE_FILE)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function readCleanupQueue(config) {
|
|
33
|
+
try {
|
|
34
|
+
const value = JSON.parse(readFileSync(cleanupQueuePath(config), 'utf8'))
|
|
35
|
+
if (!Array.isArray(value)) return []
|
|
36
|
+
return value.filter(item => typeof item === 'string' && item)
|
|
37
|
+
} catch {
|
|
38
|
+
return []
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function enqueueCleanup(config, sessionId) {
|
|
43
|
+
const id = String(sessionId ?? '')
|
|
44
|
+
if (!id) return []
|
|
45
|
+
const queue = readCleanupQueue(config)
|
|
46
|
+
if (!queue.includes(id)) queue.push(id)
|
|
47
|
+
writeAtomic(cleanupQueuePath(config), JSON.stringify(queue) + '\n')
|
|
48
|
+
return queue
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function dequeueCleanup(config, sessionId) {
|
|
52
|
+
const id = String(sessionId ?? '')
|
|
53
|
+
const queue = readCleanupQueue(config).filter(item => item !== id)
|
|
54
|
+
writeAtomic(cleanupQueuePath(config), JSON.stringify(queue) + '\n')
|
|
55
|
+
return queue
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sleep(ms) {
|
|
59
|
+
return new Promise(resolvePromise => setTimeout(resolvePromise, ms))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function tryRemove(path) {
|
|
63
|
+
try {
|
|
64
|
+
rmSync(path, { recursive: true, force: true })
|
|
65
|
+
return true
|
|
66
|
+
} catch {
|
|
67
|
+
return false
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function pruneEmpty(dir) {
|
|
72
|
+
try {
|
|
73
|
+
if (existsSync(dir) && statSync(dir).isDirectory() && readdirSync(dir).length === 0) {
|
|
74
|
+
rmSync(dir, { recursive: true, force: true })
|
|
75
|
+
}
|
|
76
|
+
} catch {
|
|
77
|
+
/* 清不掉就留着 */
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function findLogDir(sessionId) {
|
|
82
|
+
const sessionsRoot = join(dshHome(), 'sessions')
|
|
83
|
+
let projects = []
|
|
84
|
+
try {
|
|
85
|
+
projects = readdirSync(sessionsRoot)
|
|
86
|
+
} catch {
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
for (const project of projects) {
|
|
90
|
+
const candidate = join(sessionsRoot, project, sessionId)
|
|
91
|
+
if (existsSync(candidate)) return candidate
|
|
92
|
+
}
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function logDirOf(ctx, sessionId) {
|
|
97
|
+
try {
|
|
98
|
+
const persistence = ctx.get?.('sessionPersistence')
|
|
99
|
+
if (persistence?.stat) {
|
|
100
|
+
const stat = await persistence.stat(sessionId)
|
|
101
|
+
const path = stat?.location?.path
|
|
102
|
+
if (typeof path === 'string' && path) return dirname(path)
|
|
103
|
+
}
|
|
104
|
+
} catch {
|
|
105
|
+
/* fall through to a disk scan */
|
|
106
|
+
}
|
|
107
|
+
return findLogDir(sessionId)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function projectDirOf(logDir) {
|
|
111
|
+
return logDir ? dirname(logDir) : null
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function maintenanceHeader(header, config) {
|
|
115
|
+
try {
|
|
116
|
+
return header?.agentPreset === 'ta-maintenance'
|
|
117
|
+
&& typeof header?.cwd === 'string'
|
|
118
|
+
&& realPath(header.cwd) === realPath(config.taHome)
|
|
119
|
+
} catch {
|
|
120
|
+
return false
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 该会话是否是可删除的维护会话(身份 + 成功完成记录)。 */
|
|
125
|
+
export function isDeletableMaintenanceSession(ctx, session, config) {
|
|
126
|
+
const header = session?.header
|
|
127
|
+
if (!maintenanceHeader(header, config)) return false
|
|
128
|
+
const completion = latestCompletion(config, session?.id)
|
|
129
|
+
return completion?.success === true
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 删除一个维护会话。成功返回 { status:'deleted' };不能安全删除时保留现场并排队。
|
|
134
|
+
*/
|
|
135
|
+
export async function cleanupSession({ ctx, config, sessionId, logger } = {}) {
|
|
136
|
+
const id = String(sessionId ?? '')
|
|
137
|
+
if (!id) return { status: 'skipped', reason: 'missing-session-id' }
|
|
138
|
+
const registry = ctx.get?.('workspaceRegistry')
|
|
139
|
+
const sessions = ctx.get?.('sessions')
|
|
140
|
+
|
|
141
|
+
// 1) 先摘工作区成员关系;失败就不删文件,避免磁盘与内存脱节。
|
|
142
|
+
if (registry?.list) {
|
|
143
|
+
try {
|
|
144
|
+
for (const workspace of registry.list()) {
|
|
145
|
+
let ids = []
|
|
146
|
+
try {
|
|
147
|
+
ids = Array.from(workspace.sessionIds ?? [])
|
|
148
|
+
} catch {
|
|
149
|
+
ids = []
|
|
150
|
+
}
|
|
151
|
+
if (!ids.includes(id)) continue
|
|
152
|
+
await workspace.detachSession(id)
|
|
153
|
+
}
|
|
154
|
+
} catch (error) {
|
|
155
|
+
enqueueCleanup(config, id)
|
|
156
|
+
return { status: 'pending', reason: `workspace-detach: ${error instanceof Error ? error.message : String(error)}` }
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// 2) 移除 live session;没有内部 detach 时归档并排队,等冷清理。
|
|
161
|
+
let live = false
|
|
162
|
+
try {
|
|
163
|
+
const entry = sessions?.store?.get?.(id)
|
|
164
|
+
if (entry && typeof entry.detach === 'function') {
|
|
165
|
+
entry.detach()
|
|
166
|
+
live = true
|
|
167
|
+
} else if (sessions?.get?.(id) !== undefined) {
|
|
168
|
+
live = true
|
|
169
|
+
}
|
|
170
|
+
} catch (error) {
|
|
171
|
+
enqueueCleanup(config, id)
|
|
172
|
+
return { status: 'pending', reason: `live-detach: ${error instanceof Error ? error.message : String(error)}` }
|
|
173
|
+
}
|
|
174
|
+
if (live && sessions?.get?.(id) !== undefined) {
|
|
175
|
+
try {
|
|
176
|
+
await registry?.archiveSession?.(id, { stopActivity: true })
|
|
177
|
+
} catch {
|
|
178
|
+
/* archive is best effort before queuing */
|
|
179
|
+
}
|
|
180
|
+
enqueueCleanup(config, id)
|
|
181
|
+
return { status: 'pending', reason: 'live-session-not-detached' }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// 3) 归档/置顶移除放在 live 移除之后,避免归档仍被后续写入保留。
|
|
185
|
+
try {
|
|
186
|
+
await registry?.unarchiveSession?.(id)
|
|
187
|
+
await registry?.unpinSession?.(id)
|
|
188
|
+
} catch (error) {
|
|
189
|
+
enqueueCleanup(config, id)
|
|
190
|
+
return { status: 'pending', reason: `archive-clean: ${error instanceof Error ? error.message : String(error)}` }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// 4) 删磁盘;状态查询可能已经拿不到 log 路径,退化为扫描。
|
|
194
|
+
const logDir = await logDirOf(ctx, id)
|
|
195
|
+
const projectDir = projectDirOf(logDir)
|
|
196
|
+
const projCache = join(dshHome(), 'storages', 'session_projcache', 'sessions', `${id}.json`)
|
|
197
|
+
const rewindDir = join(dshHome(), 'rewind-snapshots', id)
|
|
198
|
+
const deleted = {
|
|
199
|
+
log: logDir ? tryRemove(logDir) : true,
|
|
200
|
+
projCache: tryRemove(projCache),
|
|
201
|
+
rewind: tryRemove(rewindDir),
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// 5) 晚到写入守卫:会话死后缓存/日志可能被异步写回一次。
|
|
205
|
+
await sleep(lateWriteWaitMs())
|
|
206
|
+
const late = {
|
|
207
|
+
log: Boolean(logDir && existsSync(logDir)),
|
|
208
|
+
projCache: existsSync(projCache),
|
|
209
|
+
rewind: existsSync(rewindDir),
|
|
210
|
+
}
|
|
211
|
+
if (late.log) tryRemove(logDir)
|
|
212
|
+
if (late.projCache) tryRemove(projCache)
|
|
213
|
+
if (late.rewind) tryRemove(rewindDir)
|
|
214
|
+
if (projectDir) pruneEmpty(projectDir)
|
|
215
|
+
if (logDir) pruneEmpty(dirname(logDir))
|
|
216
|
+
|
|
217
|
+
// 6) 让派生查询索引在下次读取时收敛(索引本身是 disposable 的)。
|
|
218
|
+
try {
|
|
219
|
+
await ctx.get?.('sessionQuery')?.filterSessions?.([{ kind: 'cwd', values: [config.taHome] }])
|
|
220
|
+
} catch {
|
|
221
|
+
/* 索引是派生数据,失败不影响删除 */
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
dequeueCleanup(config, id)
|
|
225
|
+
logger?.info?.(`[dsh-ta] maintenance session removed: ${id}`)
|
|
226
|
+
return {
|
|
227
|
+
status: 'deleted',
|
|
228
|
+
sessionId: id,
|
|
229
|
+
logDir,
|
|
230
|
+
deleted,
|
|
231
|
+
lateResurrection: late.log || late.projCache || late.rewind,
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** 处理清理队列(插件启动时调用;此时会话通常已是冷的)。 */
|
|
236
|
+
export async function processCleanupQueue({ ctx, config, logger } = {}) {
|
|
237
|
+
const queue = readCleanupQueue(config)
|
|
238
|
+
const results = []
|
|
239
|
+
for (const id of queue) {
|
|
240
|
+
try {
|
|
241
|
+
results.push(await cleanupSession({ ctx, config, sessionId: id, logger }))
|
|
242
|
+
} catch (error) {
|
|
243
|
+
results.push({ status: 'pending', sessionId: id, reason: error instanceof Error ? error.message : String(error) })
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return results
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 启动恢复:找出已成功完成但没被删掉的维护会话并清理。 */
|
|
250
|
+
export async function recoverMaintenanceSessions({ ctx, config, logger } = {}) {
|
|
251
|
+
const results = []
|
|
252
|
+
const headers = []
|
|
253
|
+
// 优先直接读持久化列表,避免启动早期 sessionQuery 还没就绪。
|
|
254
|
+
try {
|
|
255
|
+
const persistence = ctx.get?.('sessionPersistence')
|
|
256
|
+
if (persistence?.list) {
|
|
257
|
+
const entries = await persistence.list()
|
|
258
|
+
for (const entry of entries ?? []) {
|
|
259
|
+
const header = entry?.header ?? entry
|
|
260
|
+
if (header?.id) headers.push(header)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
} catch {
|
|
264
|
+
/* fall through to query */
|
|
265
|
+
}
|
|
266
|
+
if (headers.length === 0) {
|
|
267
|
+
try {
|
|
268
|
+
const records = await ctx.get?.('sessionQuery')?.filterSessions?.([{ kind: 'cwd', values: [config.taHome] }]) ?? []
|
|
269
|
+
for (const record of records) headers.push(record?.header)
|
|
270
|
+
} catch {
|
|
271
|
+
return results
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const seen = new Set()
|
|
275
|
+
for (const header of headers) {
|
|
276
|
+
const id = header?.id
|
|
277
|
+
if (!id || seen.has(id)) continue
|
|
278
|
+
seen.add(id)
|
|
279
|
+
if (!maintenanceHeader(header, config)) continue
|
|
280
|
+
if (latestCompletion(config, id)?.success !== true) continue
|
|
281
|
+
if (ctx.get?.('sessions')?.get?.(id) !== undefined) continue
|
|
282
|
+
try {
|
|
283
|
+
results.push(await cleanupSession({ ctx, config, sessionId: id, logger }))
|
|
284
|
+
} catch (error) {
|
|
285
|
+
results.push({ status: 'pending', sessionId: id, reason: error instanceof Error ? error.message : String(error) })
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return results
|
|
289
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 监听薄触发会话:完成记录 + durable turn/end(completed) + 短静默窗口,
|
|
3
|
+
* 三者都满足才删除会话;异常结束或没有成功记录时保留现场。
|
|
4
|
+
*/
|
|
5
|
+
import { isMaintenanceSession } from '../gates.js'
|
|
6
|
+
import { latestCompletion } from './completions.js'
|
|
7
|
+
import {
|
|
8
|
+
cleanupSession, processCleanupQueue, recoverMaintenanceSessions,
|
|
9
|
+
} from './session-cleanup.js'
|
|
10
|
+
|
|
11
|
+
function quietMs() {
|
|
12
|
+
return Number(process.env.DSH_TA_CLEANUP_QUIET_MS ?? 2000)
|
|
13
|
+
}
|
|
14
|
+
const RECOVER_DELAY_MS = 1500
|
|
15
|
+
|
|
16
|
+
export class MaintenanceSessionWatcher {
|
|
17
|
+
constructor({ ctx, config, logger }) {
|
|
18
|
+
this.ctx = ctx
|
|
19
|
+
this.config = config
|
|
20
|
+
this.logger = logger
|
|
21
|
+
this.timers = new Map()
|
|
22
|
+
this.recoverTimer = null
|
|
23
|
+
this.disposed = false
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
start() {
|
|
27
|
+
this.recoverTimer = setTimeout(() => {
|
|
28
|
+
this.recoverTimer = null
|
|
29
|
+
void this.recover()
|
|
30
|
+
}, RECOVER_DELAY_MS)
|
|
31
|
+
this.recoverTimer.unref?.()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async recover() {
|
|
35
|
+
if (this.disposed) return
|
|
36
|
+
try {
|
|
37
|
+
await processCleanupQueue({ ctx: this.ctx, config: this.config, logger: this.logger })
|
|
38
|
+
await recoverMaintenanceSessions({ ctx: this.ctx, config: this.config, logger: this.logger })
|
|
39
|
+
} catch (error) {
|
|
40
|
+
this.logger?.warn?.(`[dsh-ta] 维护会话恢复清理失败:${error instanceof Error ? error.message : String(error)}`)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
handle(session, event) {
|
|
45
|
+
if (this.disposed || !session?.id || !event?.type) return
|
|
46
|
+
const id = String(session.id)
|
|
47
|
+
if (event.type === 'turn/start') {
|
|
48
|
+
this.cancel(id)
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
if (event.type !== 'turn/end') return
|
|
52
|
+
if (event.data?.reason?.kind !== 'completed') return
|
|
53
|
+
try {
|
|
54
|
+
if (!isMaintenanceSession(this.ctx, session, this.config)) return
|
|
55
|
+
} catch {
|
|
56
|
+
return
|
|
57
|
+
}
|
|
58
|
+
if (latestCompletion(this.config, id)?.success !== true) return
|
|
59
|
+
this.schedule(id)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
schedule(id) {
|
|
63
|
+
this.cancel(id)
|
|
64
|
+
const timer = setTimeout(() => {
|
|
65
|
+
this.timers.delete(id)
|
|
66
|
+
void this.cleanup(id)
|
|
67
|
+
}, quietMs())
|
|
68
|
+
timer.unref?.()
|
|
69
|
+
this.timers.set(id, timer)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
cancel(id) {
|
|
73
|
+
const timer = this.timers.get(id)
|
|
74
|
+
if (!timer) return
|
|
75
|
+
clearTimeout(timer)
|
|
76
|
+
this.timers.delete(id)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async cleanup(id) {
|
|
80
|
+
if (this.disposed) return
|
|
81
|
+
// 静默窗口结束再确认一次:没有成功记录就不删。
|
|
82
|
+
if (latestCompletion(this.config, id)?.success !== true) return
|
|
83
|
+
try {
|
|
84
|
+
const result = await cleanupSession({
|
|
85
|
+
ctx: this.ctx,
|
|
86
|
+
config: this.config,
|
|
87
|
+
sessionId: id,
|
|
88
|
+
logger: this.logger,
|
|
89
|
+
})
|
|
90
|
+
if (result?.status !== 'deleted') {
|
|
91
|
+
this.logger?.warn?.(`[dsh-ta] 维护会话暂未删除(${result?.status}):${id} ${result?.reason ?? ''}`)
|
|
92
|
+
}
|
|
93
|
+
} catch (error) {
|
|
94
|
+
this.logger?.warn?.(`[dsh-ta] 维护会话删除失败:${error instanceof Error ? error.message : String(error)}`)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
dispose() {
|
|
99
|
+
this.disposed = true
|
|
100
|
+
for (const timer of this.timers.values()) clearTimeout(timer)
|
|
101
|
+
this.timers.clear()
|
|
102
|
+
if (this.recoverTimer) {
|
|
103
|
+
clearTimeout(this.recoverTimer)
|
|
104
|
+
this.recoverTimer = null
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 维护阶段实现:情绪整合、日记、两段式目标更新;由 engine 负责编排。
|
|
3
|
+
*/
|
|
4
|
+
import { readdirSync, unlinkSync } from 'node:fs'
|
|
5
|
+
import { resolve } from 'node:path'
|
|
6
|
+
import { localDateText, readTextIfExists, withinHome, writeAtomic } from '../storage/index.js'
|
|
7
|
+
import {
|
|
8
|
+
applyEmotionUpdate, appraisalCountForDay, readAppraisals, readMood,
|
|
9
|
+
} from '../state/index.js'
|
|
10
|
+
import {
|
|
11
|
+
DIARY_SYSTEM, EMOTION_SYSTEM, JUDGMENT_SYSTEM, TARGET_SPECS, WRITING_SYSTEM,
|
|
12
|
+
diaryPrompt, emotionPrompt, judgmentPrompt, writingPrompt,
|
|
13
|
+
} from './prompts.js'
|
|
14
|
+
import { parseJsonOutput, validateDecision, validateEmotion, validateWriting } from './llm.js'
|
|
15
|
+
import { readOutingActive } from '../state/index.js'
|
|
16
|
+
import { sleep } from './sleep.js'
|
|
17
|
+
|
|
18
|
+
export function readCore(config, relative) {
|
|
19
|
+
try {
|
|
20
|
+
return readTextIfExists(withinHome(relative, config)) ?? ''
|
|
21
|
+
} catch {
|
|
22
|
+
return ''
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function waitForOuting({ config, now, maxWaitMs, pollMs, signal }) {
|
|
27
|
+
const maxWait = Math.max(0, maxWaitMs)
|
|
28
|
+
if (!readOutingActive(config)) return null
|
|
29
|
+
const deadline = now() + maxWait
|
|
30
|
+
while (now() < deadline) {
|
|
31
|
+
if (signal?.aborted) return 'outing-active'
|
|
32
|
+
await sleep(Math.min(pollMs, Math.max(0, deadline - now())))
|
|
33
|
+
if (!readOutingActive(config)) return null
|
|
34
|
+
}
|
|
35
|
+
return 'outing-active'
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function runEmotion({ config, llm, runId, runDate, controller, nowMs }) {
|
|
39
|
+
const currentMood = readMood(config, nowMs)
|
|
40
|
+
const appraisals = readAppraisals(config)
|
|
41
|
+
.filter(item => localDateText(config, Date.parse(item.at ?? '')) === runDate)
|
|
42
|
+
.map(item => `- ${item.label}(${item.valence},能量 ${item.energy},注意力 ${item.attention}):${item.event};${item.why}`)
|
|
43
|
+
.join('\n')
|
|
44
|
+
const result = await llm.call({
|
|
45
|
+
runId, stage: 'emotion', system: EMOTION_SYSTEM,
|
|
46
|
+
input: emotionPrompt({ currentMood, appraisals }), maxTokens: 600, timeoutMs: 30_000,
|
|
47
|
+
signal: controller.signal,
|
|
48
|
+
})
|
|
49
|
+
const sourceIds = readAppraisals(config)
|
|
50
|
+
.filter(item => localDateText(config, Date.parse(item.at ?? '')) === runDate)
|
|
51
|
+
.map(item => item.id)
|
|
52
|
+
if (!result.ok) {
|
|
53
|
+
return {
|
|
54
|
+
stage: 'emotion', target: 'state/mood.json', status: 'failed', decision: null,
|
|
55
|
+
artifact: null, sourceIds, error: result.code, usage: result.usage,
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const parsed = parseJsonOutput(result.text)
|
|
59
|
+
if (!parsed.ok) {
|
|
60
|
+
return {
|
|
61
|
+
stage: 'emotion', target: 'state/mood.json', status: 'failed', decision: null,
|
|
62
|
+
artifact: null, sourceIds, error: `JSON: ${parsed.error}`, usage: result.usage,
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const emotion = validateEmotion(parsed.value)
|
|
66
|
+
if (!emotion.ok) {
|
|
67
|
+
return {
|
|
68
|
+
stage: 'emotion', target: 'state/mood.json', status: 'failed', decision: null,
|
|
69
|
+
artifact: null, sourceIds, error: emotion.error, usage: result.usage,
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (emotion.update) applyEmotionUpdate(config, emotion, nowMs)
|
|
73
|
+
return {
|
|
74
|
+
stage: 'emotion', target: 'state/mood.json', status: 'ok',
|
|
75
|
+
decision: emotion.update ? 'UPDATE' : 'NO_UPDATE',
|
|
76
|
+
artifact: null, sourceIds, error: null, usage: result.usage,
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function runDiary({ config, llm, runId, runDate, controller, nowMs, materials, materialsText, soulText, recentText, outingSuffix }) {
|
|
81
|
+
const spec = TARGET_SPECS.diary
|
|
82
|
+
const relative = `diary/${runDate}.md`
|
|
83
|
+
const target = withinHome(relative, config)
|
|
84
|
+
if (readTextIfExists(target)) {
|
|
85
|
+
return {
|
|
86
|
+
stage: 'diary', target: relative, status: 'skipped', decision: null,
|
|
87
|
+
artifact: null, sourceIds: [], error: null, usage: null, reason: 'diary-exists',
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const sourceIds = materials.filter(material => ['chat', 'outing', 'note'].includes(material.kind)).map(material => material.id)
|
|
91
|
+
const sourceText = materialsText + outingSuffix
|
|
92
|
+
let lastError = null
|
|
93
|
+
let usage = null
|
|
94
|
+
let input = diaryPrompt({
|
|
95
|
+
soul: soulText,
|
|
96
|
+
mood: readMood(config, nowMs),
|
|
97
|
+
materialsText: sourceText,
|
|
98
|
+
recent: recentText,
|
|
99
|
+
date: runDate,
|
|
100
|
+
})
|
|
101
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
102
|
+
const result = await llm.call({
|
|
103
|
+
runId, stage: 'diary', system: DIARY_SYSTEM, input,
|
|
104
|
+
maxTokens: spec.maxTokens, timeoutMs: 120_000, signal: controller.signal,
|
|
105
|
+
})
|
|
106
|
+
usage = result.usage ?? usage
|
|
107
|
+
if (!result.ok) {
|
|
108
|
+
return {
|
|
109
|
+
stage: 'diary', target: relative, status: 'failed', decision: null,
|
|
110
|
+
artifact: null, sourceIds, error: result.code, usage,
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const validated = validateWriting(result.text, { cap: spec.cap })
|
|
114
|
+
if (validated.ok) {
|
|
115
|
+
writeAtomic(target, validated.text + '\n')
|
|
116
|
+
return {
|
|
117
|
+
stage: 'diary', target: relative, status: 'ok', decision: 'UPDATE',
|
|
118
|
+
artifact: relative, sourceIds, error: null, usage,
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
lastError = validated.error
|
|
122
|
+
input = `${input}\n\n上一次输出不合格:${validated.error}。请只输出日记正文。`
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
stage: 'diary', target: relative, status: 'failed', decision: null,
|
|
126
|
+
artifact: null, sourceIds, error: lastError, usage,
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** self 写入前保留旧版本,最多 30 份。 */
|
|
131
|
+
function archiveSelf(config, previous, nowMs) {
|
|
132
|
+
if (!String(previous ?? '').trim()) return
|
|
133
|
+
try {
|
|
134
|
+
const stamp = new Date(nowMs).toISOString().replace(/[:.]/g, '-')
|
|
135
|
+
const relative = `self/history/${stamp}.md`
|
|
136
|
+
writeAtomic(withinHome(relative, config), previous)
|
|
137
|
+
const directory = resolve(config.taHome, 'self/history')
|
|
138
|
+
const names = readdirSync(directory).filter(name => name.endsWith('.md')).sort()
|
|
139
|
+
for (const name of names.slice(0, Math.max(0, names.length - 30))) {
|
|
140
|
+
try {
|
|
141
|
+
unlinkSync(resolve(directory, name))
|
|
142
|
+
} catch {
|
|
143
|
+
/* 清理失败留给下次 */
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
} catch {
|
|
147
|
+
/* 历史归档失败不阻塞写入 */
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 两段式更新一个目标文件。
|
|
153
|
+
* 判断失败/写作失败都保留旧文件;只有成功落盘才返回 artifact。
|
|
154
|
+
*/
|
|
155
|
+
export async function updateTarget({
|
|
156
|
+
config, llm, spec, materials, soulValue, recentText, materialsText, runId, runDate, controller, nowMs,
|
|
157
|
+
}) {
|
|
158
|
+
const relative = spec.path
|
|
159
|
+
const target = withinHome(relative, config)
|
|
160
|
+
const current = readTextIfExists(target) ?? ''
|
|
161
|
+
const sourceIds = materials.map(material => material.id)
|
|
162
|
+
const stageSpec = { ...spec, soulValue }
|
|
163
|
+
let usage = null
|
|
164
|
+
let judgment = null
|
|
165
|
+
let lastError = null
|
|
166
|
+
let input = judgmentPrompt({ spec: stageSpec, current, materialsText })
|
|
167
|
+
|
|
168
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
169
|
+
const result = await llm.call({
|
|
170
|
+
runId, stage: `${spec.stage}:judgment`, system: JUDGMENT_SYSTEM, input,
|
|
171
|
+
maxTokens: spec.maxTokens, timeoutMs: 60_000, signal: controller.signal,
|
|
172
|
+
})
|
|
173
|
+
usage = result.usage ?? usage
|
|
174
|
+
if (!result.ok) {
|
|
175
|
+
return {
|
|
176
|
+
stage: spec.stage, target: relative, status: 'failed', decision: null,
|
|
177
|
+
artifact: null, sourceIds, error: result.code, usage,
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const parsed = parseJsonOutput(result.text)
|
|
181
|
+
if (parsed.ok) {
|
|
182
|
+
const validated = validateDecision(parsed.value)
|
|
183
|
+
if (validated.ok) {
|
|
184
|
+
judgment = validated
|
|
185
|
+
break
|
|
186
|
+
}
|
|
187
|
+
lastError = validated.error
|
|
188
|
+
} else {
|
|
189
|
+
lastError = `JSON: ${parsed.error}`
|
|
190
|
+
}
|
|
191
|
+
input = `${input}\n\n上一次输出不是合法 JSON:${lastError}。请只输出 JSON 对象。`
|
|
192
|
+
}
|
|
193
|
+
if (!judgment) {
|
|
194
|
+
return {
|
|
195
|
+
stage: spec.stage, target: relative, status: 'failed', decision: null,
|
|
196
|
+
artifact: null, sourceIds, error: lastError, usage,
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (judgment.decision === 'NO_UPDATE') {
|
|
200
|
+
return {
|
|
201
|
+
stage: spec.stage, target: relative, status: 'ok', decision: 'NO_UPDATE',
|
|
202
|
+
artifact: null, sourceIds, error: null, usage,
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const context = spec.stage === 'self'
|
|
207
|
+
? `当前 RECENT:\n${recentText || '(空)'}\n\n最近素材:\n${materialsText}`
|
|
208
|
+
: spec.stage === 'user'
|
|
209
|
+
? `对方明确表达与待纠正内容:\n${materialsText}`
|
|
210
|
+
: `SOUL 价值段:\n${soulValue}\n\n最近素材:\n${materialsText}`
|
|
211
|
+
let writingInput = writingPrompt({ spec, current, decision: judgment, context })
|
|
212
|
+
let lastWritingError = null
|
|
213
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
214
|
+
const result = await llm.call({
|
|
215
|
+
runId, stage: `${spec.stage}:writing`, system: WRITING_SYSTEM, input: writingInput,
|
|
216
|
+
maxTokens: spec.maxTokens, timeoutMs: 120_000, signal: controller.signal,
|
|
217
|
+
})
|
|
218
|
+
usage = result.usage ?? usage
|
|
219
|
+
if (!result.ok) {
|
|
220
|
+
return {
|
|
221
|
+
stage: spec.stage, target: relative, status: 'failed', decision: judgment.decision,
|
|
222
|
+
artifact: null, sourceIds, error: result.code, usage,
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const validated = validateWriting(result.text, { cap: spec.cap, headings: spec.headings })
|
|
226
|
+
if (validated.ok) {
|
|
227
|
+
writeAtomic(target, validated.text + '\n')
|
|
228
|
+
return {
|
|
229
|
+
stage: spec.stage, target: relative, status: 'ok', decision: judgment.decision,
|
|
230
|
+
artifact: relative, sourceIds, error: null, usage,
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
lastWritingError = validated.error
|
|
234
|
+
writingInput = `${writingInput}\n\n上一次输出不合格:${validated.error}。请只输出目标文件的完整正文。`
|
|
235
|
+
}
|
|
236
|
+
return {
|
|
237
|
+
stage: spec.stage, target: relative, status: 'failed', decision: judgment.decision,
|
|
238
|
+
artifact: null, sourceIds, error: lastWritingError, usage,
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|