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,392 @@
1
+ /**
2
+ * 维护引擎:插件内定时器 + 单日单次主运行 + 失败有界重试。
3
+ *
4
+ * 阶段顺序:collect → emotion → diary → recent →(周更 self/认识)→ finalize。
5
+ * 每个阶段独立 try/catch;只有 ok 的 artifact 才写消费账本;
6
+ * lastSuccessDate 只在所有必跑阶段 ok/skipped 时写。
7
+ */
8
+
9
+ import { localDateText, startOfLocalDay, zonedIso } from '../storage/index.js'
10
+ import { addNote, appraisalCountForDay } from '../state/index.js'
11
+ import { calculateCost, loadPricing } from '../usage/pricing.js'
12
+ import { imModeFor } from '../settings/im.js'
13
+ import { readCore, runDiary, runEmotion, updateTarget, waitForOuting } from './stages.js'
14
+ import { collectAllMaterials, formatMaterialsForPrompt } from './collect.js'
15
+ import { readConsumption, writeConsumption, markConsumed } from './consumption.js'
16
+ import { readSessionCursors, writeSessionCursors } from './cursors.js'
17
+ import { acquireMaintenanceLock, releaseMaintenanceLock } from './lock.js'
18
+ import { MaintenanceLlm } from './llm.js'
19
+ import { TARGET_SPECS, soulValueSection } from './prompts.js'
20
+ import { appendCompletion } from './completions.js'
21
+ import {
22
+ beginRun, evaluateMaintenance, finishRun, markWeeklyResult, readMaintenanceState, runIdFor,
23
+ weeklyDue, writeMaintenanceState,
24
+ } from './state.js'
25
+ import { appendRun } from './runs.js'
26
+
27
+ const HOUR_MS = 3_600_000
28
+ export const DEFAULT_TICK_MS = 60_000
29
+ export const DEFAULT_OUTING_WAIT_MS = 10 * 60_000
30
+ export const DEFAULT_OUTING_POLL_MS = 15_000
31
+
32
+ function emptyUsage() {
33
+ return { uncachedInput: 0, cacheRead: 0, cacheWrite: 0, output: 0, costCny: 0 }
34
+ }
35
+
36
+ function addUsage(total, usage, config, model) {
37
+ if (!usage) return total
38
+ total.uncachedInput += usage.uncachedInput ?? 0
39
+ total.cacheRead += usage.cacheRead ?? 0
40
+ total.cacheWrite += usage.cacheWrite ?? 0
41
+ total.output += usage.output ?? 0
42
+ const cost = calculateCost(total, model, loadPricing(config))
43
+ total.costCny = typeof cost === 'number' ? cost : 0
44
+ return total
45
+ }
46
+
47
+ function stageUsage(result) {
48
+ return result?.usage ?? null
49
+ }
50
+
51
+ export class MaintenanceEngine {
52
+ constructor({
53
+ ctx, config, logger,
54
+ tickIntervalMs = DEFAULT_TICK_MS,
55
+ outingWaitMs = DEFAULT_OUTING_WAIT_MS,
56
+ outingPollMs = DEFAULT_OUTING_POLL_MS,
57
+ now = () => Date.now(),
58
+ llm = null,
59
+ } = {}) {
60
+ this.ctx = ctx
61
+ this.config = config
62
+ this.logger = logger
63
+ this.intervalMs = tickIntervalMs
64
+ this.outingWaitMs = outingWaitMs
65
+ this.outingPollMs = outingPollMs
66
+ this.now = now
67
+ this.timer = null
68
+ this.running = null
69
+ this.controller = null
70
+ this.llm = llm ?? new MaintenanceLlm({ ctx, config, logger })
71
+ this.unavailableLoggedAt = 0
72
+ }
73
+
74
+ start() {
75
+ if (this.timer) return
76
+ const timer = setInterval(() => {
77
+ void this.tick().catch(cause => this.warn(`维护检查失败:${describe(cause)}`))
78
+ }, this.intervalMs)
79
+ timer.unref?.()
80
+ this.timer = timer
81
+ }
82
+
83
+ /** 官方 schedule 接管后停掉插件内定时器,但保留引擎供工具/手动运行。 */
84
+ stopTimer() {
85
+ if (!this.timer) return
86
+ clearInterval(this.timer)
87
+ this.timer = null
88
+ }
89
+
90
+ stop() {
91
+ this.stopTimer()
92
+ try {
93
+ this.controller?.abort()
94
+ } catch {
95
+ /* abort is best effort */
96
+ }
97
+ }
98
+
99
+ /** 供转生/删旧家前等待:返回当前运行结束的 promise。 */
100
+ whenIdle() {
101
+ return this.running ?? Promise.resolve(null)
102
+ }
103
+
104
+ isRunning() {
105
+ return Boolean(this.running)
106
+ }
107
+
108
+ warn(message) {
109
+ try {
110
+ this.logger?.warn?.(`[dsh-ta] ${message}`)
111
+ } catch {
112
+ /* logging must never break maintenance */
113
+ }
114
+ }
115
+
116
+ status() {
117
+ const state = readMaintenanceState(this.config)
118
+ return {
119
+ enabled: this.config.maintenanceEnabled === true,
120
+ time: this.config.maintenanceTime,
121
+ weeklyDay: this.config.weeklyDay,
122
+ running: this.isRunning(),
123
+ lastSuccessDate: state.lastSuccessDate,
124
+ nextRetryAt: state.nextRetryAt,
125
+ consecutiveFailures: state.consecutiveFailures,
126
+ currentRun: state.currentRun,
127
+ lastRun: state.lastRun,
128
+ weekly: state.weekly,
129
+ }
130
+ }
131
+
132
+ /** 每分钟检查一次;到点才真正启动。 */
133
+ async tick(nowMs = this.now()) {
134
+ if (this.isRunning()) return { skipped: 'running' }
135
+ if (this.config.maintenanceEnabled !== true) return { skipped: 'disabled' }
136
+ const state = readMaintenanceState(this.config)
137
+ const evaluation = evaluateMaintenance(state, this.config, nowMs)
138
+ if (!evaluation.due) return { skipped: evaluation.reason, evaluation }
139
+ return this.runNow({ nowMs, reason: 'schedule', evaluation })
140
+ }
141
+
142
+ /** 手动/定时触发:立刻返回 { started, runId },运行在后台继续。 */
143
+ runNow({ nowMs = this.now(), reason = 'manual', evaluation, forceProfile = false, triggerSessionId = null } = {}) {
144
+ if (this.isRunning()) return { started: false, reason: 'running' }
145
+ const selection = this.llm.available()
146
+ if (!selection) {
147
+ if (nowMs - this.unavailableLoggedAt > HOUR_MS) {
148
+ this.unavailableLoggedAt = nowMs
149
+ this.warn('没有可用的默认模型,本次维护跳过')
150
+ }
151
+ return { started: false, reason: 'llm-unavailable' }
152
+ }
153
+ const runDate = evaluation?.runDate ?? localDateText(this.config, nowMs)
154
+ const runId = runIdFor(this.config, nowMs)
155
+ const promise = this.execute({ runId, runDate, nowMs, reason, forceProfile, triggerSessionId })
156
+ this.running = promise
157
+ void promise.finally(() => {
158
+ if (this.running === promise) this.running = null
159
+ })
160
+ return { started: true, runId, runDate }
161
+ }
162
+
163
+ /**
164
+ * 完整运行。所有失败都落到 runs.jsonl 与 maintenance-state,不向上抛。
165
+ */
166
+ async execute({ runId, runDate, nowMs, reason, forceProfile = false, triggerSessionId = null }) {
167
+ const config = this.config
168
+ const controller = new AbortController()
169
+ this.controller = controller
170
+ const startedAt = zonedIso(config, nowMs)
171
+ const run = {
172
+ runId,
173
+ runDate,
174
+ reason,
175
+ startedAt,
176
+ finishedAt: null,
177
+ window: { from: zonedIso(config, startOfLocalDay(config, runDate)), to: startedAt },
178
+ materials: [],
179
+ stages: [],
180
+ artifacts: [],
181
+ usage: emptyUsage(),
182
+ model: this.llm.selection?.model ?? null,
183
+ status: 'failed',
184
+ }
185
+ const lock = acquireMaintenanceLock(config, { runId, runDate, nowMs })
186
+ if (!lock.acquired) {
187
+ this.warn(`维护锁被占用(${lock.reason ?? 'held'}),本次跳过`)
188
+ return { runId, skipped: 'locked', reason: lock.reason }
189
+ }
190
+ let state = readMaintenanceState(config)
191
+ beginRun(config, state, { runId, runDate, nowMs })
192
+ writeMaintenanceState(config, state)
193
+ const consumption = readConsumption(config)
194
+ let consumptionDirty = false
195
+ let collection = null
196
+ const addStage = stage => {
197
+ run.stages.push(stage)
198
+ addUsage(run.usage, stageUsage(stage), config, run.model)
199
+ if (stage.status === 'ok' && typeof stage.artifact === 'string' && stage.artifact) {
200
+ run.artifacts.push(stage.artifact)
201
+ if (!consumptionDirty) consumptionDirty = true
202
+ for (const materialId of Array.isArray(stage.sourceIds) ? stage.sourceIds : []) {
203
+ markConsumed(consumption, materialId, stage.artifact, { runId, at: zonedIso(config, this.now()) })
204
+ }
205
+ }
206
+ return stage
207
+ }
208
+
209
+ let collectFailed = false
210
+ try {
211
+ const outingNote = await waitForOuting({
212
+ config, now: this.now, maxWaitMs: this.outingWaitMs, pollMs: this.outingPollMs, signal: controller.signal,
213
+ })
214
+ const weeklyState = weeklyDue(state, config, nowMs)
215
+ const weeklyPlanned = forceProfile === true || weeklyState.due === true
216
+ const imMode = imModeFor(config)
217
+ try {
218
+ collection = await collectAllMaterials({
219
+ config,
220
+ query: this.ctx?.get?.('sessionQuery'),
221
+ cursors: readSessionCursors(config),
222
+ consumption,
223
+ nowMs,
224
+ runDate,
225
+ imMode,
226
+ weekly: weeklyPlanned,
227
+ })
228
+ run.materials = collection.materials.map(material => ({
229
+ id: material.id,
230
+ kind: material.kind,
231
+ chars: material.chars,
232
+ consumedFor: material.consumedFor ?? [],
233
+ }))
234
+ addStage({
235
+ stage: 'collect',
236
+ target: null,
237
+ status: 'ok',
238
+ decision: outingNote ?? null,
239
+ artifact: null,
240
+ sourceIds: collection.materials.map(material => material.id),
241
+ error: null,
242
+ usage: null,
243
+ warnings: collection.warnings,
244
+ })
245
+ } catch (error) {
246
+ collectFailed = true
247
+ addStage({
248
+ stage: 'collect', target: null, status: 'failed', decision: null,
249
+ artifact: null, sourceIds: [], error: describe(error), usage: null,
250
+ })
251
+ }
252
+
253
+ if (!collectFailed && collection) {
254
+ const materials = collection.materials
255
+ const materialsText = formatMaterialsForPrompt(materials)
256
+ const soulText = readCore(config, 'SOUL.md')
257
+ const recentText = readCore(config, 'RECENT-MEMORY.md')
258
+ const soulValue = soulValueSection(soulText)
259
+ const outingSuffix = outingNote ? '\n注意:辖区 outing 尚未结束,今天出门记录可能不完整。' : ''
260
+
261
+ // emotion:只有当天有 appraisal 才跑
262
+ if (appraisalCountForDay(config, runDate) > 0) {
263
+ addStage(await runEmotion({ config, llm: this.llm, runId, runDate, controller, nowMs }))
264
+ } else {
265
+ addStage({
266
+ stage: 'emotion', target: 'state/mood.json', status: 'skipped', decision: null,
267
+ artifact: null, sourceIds: [], error: null, usage: null, reason: 'no-appraisal',
268
+ })
269
+ }
270
+
271
+ // diary:有当天素材才跑
272
+ const diaryMaterials = materials.filter(material => ['chat', 'outing', 'note'].includes(material.kind))
273
+ if (diaryMaterials.length > 0) {
274
+ addStage(await runDiary({
275
+ config, llm: this.llm, runId, runDate, controller, nowMs, materials, materialsText, soulText, recentText, outingSuffix,
276
+ }))
277
+ } else {
278
+ addStage({
279
+ stage: 'diary', target: `diary/${runDate}.md`, status: 'skipped', decision: null,
280
+ artifact: null, sourceIds: [], error: null, usage: null, reason: 'no-materials',
281
+ })
282
+ }
283
+
284
+ // recent:每天判断一次
285
+ addStage(await updateTarget({
286
+ config, llm: this.llm,
287
+ spec: TARGET_SPECS.recent,
288
+ materials,
289
+ soulValue,
290
+ recentText,
291
+ materialsText: materialsText + outingSuffix,
292
+ runId,
293
+ runDate,
294
+ controller,
295
+ nowMs,
296
+ }))
297
+
298
+ if (weeklyPlanned) {
299
+ const selfStage = await updateTarget({
300
+ config, llm: this.llm,
301
+ spec: TARGET_SPECS.self,
302
+ materials,
303
+ soulValue,
304
+ recentText,
305
+ materialsText,
306
+ runId,
307
+ runDate,
308
+ controller,
309
+ nowMs,
310
+ })
311
+ addStage(selfStage)
312
+ const userStage = await updateTarget({
313
+ config, llm: this.llm,
314
+ spec: TARGET_SPECS.user,
315
+ materials,
316
+ soulValue,
317
+ recentText,
318
+ materialsText,
319
+ runId,
320
+ runDate,
321
+ controller,
322
+ nowMs,
323
+ })
324
+ addStage(userStage)
325
+ const weeklyOk = selfStage.status !== 'failed' && userStage.status !== 'failed'
326
+ markWeeklyResult(state, { anchor: weeklyState.anchor, success: weeklyOk })
327
+ }
328
+
329
+ }
330
+ } catch (error) {
331
+ addStage({
332
+ stage: 'engine', target: null, status: 'failed', decision: null,
333
+ artifact: null, sourceIds: [], error: describe(error), usage: null,
334
+ })
335
+ } finally {
336
+ const finishedAt = zonedIso(config, this.now())
337
+ run.finishedAt = finishedAt
338
+ const anyFailed = run.stages.some(stage => stage.status === 'failed')
339
+ const success = !collectFailed && !anyFailed
340
+ run.status = collectFailed ? 'failed' : (anyFailed ? 'partial' : 'ok')
341
+ try {
342
+ appendRun(config, run)
343
+ } catch (error) {
344
+ this.warn(`runs.jsonl 写入失败:${describe(error)}`)
345
+ }
346
+ if (consumptionDirty) {
347
+ try {
348
+ writeConsumption(config, consumption)
349
+ } catch (error) {
350
+ this.warn(`消费账本写入失败:${describe(error)}`)
351
+ }
352
+ }
353
+ if (success && collection) {
354
+ try {
355
+ writeSessionCursors(config, collection.cursors)
356
+ } catch (error) {
357
+ this.warn(`会话游标写入失败:${describe(error)}`)
358
+ }
359
+ }
360
+ try {
361
+ finishRun(config, state, { runId, runDate, status: run.status, success, nowMs: this.now() })
362
+ writeMaintenanceState(config, state)
363
+ if (state.consecutiveFailures === 3) {
364
+ addNote(config, `维护已经连续失败 ${state.consecutiveFailures} 次,请检查模型与网络。`)
365
+ }
366
+ } catch (error) {
367
+ this.warn(`维护状态写入失败:${describe(error)}`)
368
+ }
369
+ releaseMaintenanceLock(config, runId)
370
+ if (triggerSessionId) {
371
+ try {
372
+ appendCompletion(config, {
373
+ sessionId: triggerSessionId,
374
+ runId,
375
+ runDate,
376
+ status: run.status,
377
+ success,
378
+ finishedAt,
379
+ })
380
+ } catch (error) {
381
+ this.warn(`维护完成记录写入失败:${describe(error)}`)
382
+ }
383
+ }
384
+ this.controller = null
385
+ }
386
+ return { runId, runDate, status: run.status, success: run.status === 'ok', stages: run.stages }
387
+ }
388
+ }
389
+
390
+ function describe(cause) {
391
+ return cause instanceof Error ? cause.message : String(cause ?? '未知错误')
392
+ }