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,381 @@
1
+ /**
2
+ * 维护直调模型封装。
3
+ *
4
+ * 平台契约(P0 实测,见修复方案 §7 / F1 / F4):
5
+ * - 每次尝试都要重新 prepareCall;复用并改配置会报 INVALID_PREPARED_CALL;
6
+ * - finish.kind 为 stop / max-tokens / aborted / error;max-tokens 与 aborted 都算失败;
7
+ * - 启动期 NO_ADAPTER / MISSING_CREDENTIAL 是凭据连接竞态,需要短退避重试;
8
+ * - usage 字段是 inputTokens/outputTokens/cacheReadTokens/cacheWriteTokens;
9
+ * - 一次调用不属于任何会话,不会产生 session。
10
+ */
11
+
12
+ import { localDateText, zonedIso } from '../storage/index.js'
13
+ import { appendUsageRecord } from '../usage/ledger.js'
14
+
15
+ export const TRANSIENT_SETUP_CODES = ['NO_ADAPTER', 'MISSING_CREDENTIAL']
16
+ export const MAX_ATTEMPTS = 3
17
+
18
+ const DEFAULT_BACKOFF = {
19
+ initialDelayMs: 500,
20
+ maxDelayMs: 10_000,
21
+ jitterRatio: 0.1,
22
+ }
23
+
24
+ function number(value) {
25
+ return Number.isFinite(Number(value)) ? Number(value) : 0
26
+ }
27
+
28
+ /** 把平台 TokenUsage 映射成账本内部字段。 */
29
+ export function mapUsage(usage) {
30
+ if (!usage || typeof usage !== 'object') return null
31
+ const mapped = {
32
+ uncachedInput: number(usage.inputTokens),
33
+ cacheRead: number(usage.cacheReadTokens),
34
+ cacheWrite: number(usage.cacheWriteTokens),
35
+ output: number(usage.outputTokens),
36
+ }
37
+ if (mapped.uncachedInput + mapped.cacheRead + mapped.cacheWrite + mapped.output <= 0) return null
38
+ return mapped
39
+ }
40
+
41
+ /**
42
+ * 轻量文本聚合器:只关心 text-delta / usage / finish。
43
+ * 不依赖 @deepseek-ai/dsh-llm 的内部 BlockAssembler,插件保持独立可发布。
44
+ */
45
+ export function createTextAssembler() {
46
+ let text = ''
47
+ let usage = null
48
+ let finish = null
49
+ let chunks = 0
50
+ return {
51
+ push(chunk) {
52
+ chunks += 1
53
+ if (!chunk || typeof chunk !== 'object') return
54
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text
55
+ else if (chunk.type === 'usage') usage = mapUsage(chunk.usage) ?? usage
56
+ else if (chunk.type === 'finish') finish = chunk.reason ?? null
57
+ },
58
+ result() {
59
+ return { text, usage, finish, chunks }
60
+ },
61
+ }
62
+ }
63
+
64
+ export function classifyFinish(finish) {
65
+ const kind = typeof finish?.kind === 'string' ? finish.kind : 'unknown'
66
+ if (kind === 'stop') return { ok: true, kind }
67
+ return {
68
+ ok: false,
69
+ kind,
70
+ code: kind === 'max-tokens' ? 'MAX_TOKENS' : (finish?.failure?.code ?? kind.toUpperCase()),
71
+ message: finish?.failure?.message ?? `finish kind ${kind}`,
72
+ retryAfterMs: finish?.failure?.providerRetryAfterMs,
73
+ }
74
+ }
75
+
76
+ /** 去掉 markdown 围栏后再解析 JSON;失败时返回可读错误与预览。 */
77
+ export function parseJsonOutput(text) {
78
+ const raw = String(text ?? '').trim()
79
+ if (!raw) return { ok: false, error: '输出为空', raw }
80
+ const candidates = [raw]
81
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(raw)
82
+ if (fenced?.[1]) candidates.push(fenced[1].trim())
83
+ const firstBrace = raw.indexOf('{')
84
+ const lastBrace = raw.lastIndexOf('}')
85
+ if (firstBrace !== -1 && lastBrace > firstBrace) candidates.push(raw.slice(firstBrace, lastBrace + 1))
86
+ for (const candidate of candidates) {
87
+ try {
88
+ return { ok: true, value: JSON.parse(candidate), raw }
89
+ } catch {
90
+ /* try the next candidate */
91
+ }
92
+ }
93
+ return { ok: false, error: '不是合法 JSON', preview: raw.slice(0, 200), raw }
94
+ }
95
+
96
+ const DECISIONS = new Set(['NO_UPDATE', 'DECAY_UPDATE', 'UPDATE'])
97
+
98
+ /** 校验判断输出;返回规范化后的 decision。 */
99
+ export function validateDecision(value) {
100
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
101
+ return { ok: false, error: 'decision 必须是对象' }
102
+ }
103
+ const decision = String(value.decision ?? '').trim().toUpperCase()
104
+ if (!DECISIONS.has(decision)) return { ok: false, error: `decision 不在枚举内:${value.decision}` }
105
+ if (typeof value.reason !== 'string' || !value.reason.trim()) {
106
+ return { ok: false, error: 'reason 必须是非空字符串' }
107
+ }
108
+ const asList = input => (Array.isArray(input) ? input.map(item => String(item)).filter(Boolean) : [])
109
+ return {
110
+ ok: true,
111
+ decision,
112
+ reason: value.reason.trim(),
113
+ changes: asList(value.changes),
114
+ decay: asList(value.decay),
115
+ }
116
+ }
117
+
118
+ /** 情绪整合输出校验。 */
119
+ export function validateEmotion(value) {
120
+ if (!value || typeof value !== 'object') return { ok: false, error: '输出必须是对象' }
121
+ if (value.update !== true) return { ok: true, update: false }
122
+ const label = typeof value.label === 'string' ? value.label.trim().slice(0, 20) : ''
123
+ const clamp = input => Math.max(-1, Math.min(1, Number(input) || 0))
124
+ const clamp01 = input => Math.max(0, Math.min(1, Number(input) || 0))
125
+ return {
126
+ ok: true,
127
+ update: true,
128
+ label: label || '有变化',
129
+ valence: clamp(value.valence),
130
+ energy: clamp01(value.energy),
131
+ attention: clamp01(value.attention),
132
+ reason: typeof value.reason === 'string' ? value.reason.trim() : '',
133
+ }
134
+ }
135
+
136
+ /**
137
+ * 校验写作输出:纯 Markdown 正文、长度上限、必要标题。
138
+ * headings 为空表示自由结构(日记)。
139
+ */
140
+ export function validateWriting(text, { cap, headings = [], forbid = [] } = {}) {
141
+ let body = String(text ?? '').trim()
142
+ if (!body) return { ok: false, error: '正文为空' }
143
+ if (body.startsWith('```')) {
144
+ const inner = /```(?:markdown|md)?\s*([\s\S]*?)```/i.exec(body)
145
+ if (inner?.[1]) body = inner[1].trim()
146
+ }
147
+ // 去掉常见的解释性前后缀:模型偶尔会写“这是更新后的版本:”之类。
148
+ body = body.replace(/^(以下是|这是|更新后)[^\n]*\n+/, '').trim()
149
+ if (/作为(一个)?\s*AI/i.test(body)) return { ok: false, error: '正文出现 AI 自述' }
150
+ for (const pattern of forbid) {
151
+ if (pattern.test(body)) return { ok: false, error: `正文包含禁止内容:${pattern}` }
152
+ }
153
+ if (Number.isFinite(cap) && body.length > cap) {
154
+ return { ok: false, error: `正文超过上限 ${cap} 字(实际 ${body.length} 字)`, length: body.length }
155
+ }
156
+ for (const heading of headings) {
157
+ if (!body.includes(heading)) return { ok: false, error: `缺少标题:${heading}` }
158
+ }
159
+ return { ok: true, text: body, length: body.length }
160
+ }
161
+
162
+ function delay(ms, signal) {
163
+ return new Promise((resolve, reject) => {
164
+ if (signal?.aborted) {
165
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))
166
+ return
167
+ }
168
+ const timer = setTimeout(resolve, Math.max(0, ms))
169
+ signal?.addEventListener?.('abort', () => {
170
+ clearTimeout(timer)
171
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))
172
+ }, { once: true })
173
+ })
174
+ }
175
+
176
+ function isRetryableCode(code, retryPolicy) {
177
+ if (!code) return false
178
+ if (TRANSIENT_SETUP_CODES.includes(code)) return true
179
+ const codes = retryPolicy?.retryableCodes ?? ['EMPTY_RESPONSE', 'RATE_LIMIT', 'SERVER', 'TIMEOUT', 'TRANSPORT']
180
+ return codes.includes(code)
181
+ }
182
+
183
+ function backoffMs(retryPolicy, attempt, retryAfterMs) {
184
+ if (Number.isFinite(retryAfterMs) && retryAfterMs > 0) return Math.min(retryAfterMs, 60_000)
185
+ const policy = { ...DEFAULT_BACKOFF, ...(retryPolicy ?? {}) }
186
+ const base = Math.min(policy.initialDelayMs * (2 ** (attempt - 1)), policy.maxDelayMs)
187
+ const jitter = 1 + (Math.random() * 2 - 1) * policy.jitterRatio
188
+ return Math.round(base * jitter)
189
+ }
190
+
191
+ function timeoutError() {
192
+ const error = new Error('维护调用超时')
193
+ error.name = 'TimeoutError'
194
+ error.code = 'TIMEOUT'
195
+ return error
196
+ }
197
+
198
+ export class MaintenanceLlm {
199
+ constructor({ ctx, config, logger } = {}) {
200
+ this.ctx = ctx
201
+ this.config = config
202
+ this.logger = logger
203
+ this.selection = null
204
+ }
205
+
206
+ /** 当前默认模型;服务缺失时返回 null,维护整体跳过。 */
207
+ available() {
208
+ try {
209
+ const selection = this.ctx?.get?.('agentDefaultModel')?.currentSelection?.()
210
+ if (selection && typeof selection.provider === 'string' && typeof selection.model === 'string') {
211
+ this.selection = selection
212
+ return selection
213
+ }
214
+ } catch {
215
+ /* 服务缺失按不可用处理 */
216
+ }
217
+ return null
218
+ }
219
+
220
+ useSelection(selection) {
221
+ if (selection) this.selection = selection
222
+ }
223
+
224
+ recordUsage({ runId, stage, attempt, model, tokens }) {
225
+ if (!tokens) return null
226
+ const dateText = localDateText(this.config)
227
+ try {
228
+ return appendUsageRecord(this.config, {
229
+ sessionId: 'maintenance',
230
+ turn: runId,
231
+ callId: `${runId}:${stage}:${attempt}`,
232
+ category: 'maintenance',
233
+ model,
234
+ tokens,
235
+ ts: zonedIso(this.config),
236
+ dateText,
237
+ })
238
+ } catch (error) {
239
+ this.logger?.warn?.(`[dsh-ta] usage 记录失败:${error?.message ?? error}`)
240
+ return null
241
+ }
242
+ }
243
+
244
+ /**
245
+ * 执行一次维护调用(含重试)。
246
+ * 返回 { ok, text, usage, finishKind, code, message, attempts, callIds },不抛错。
247
+ */
248
+ async call({
249
+ runId, stage, system, input, maxTokens = 1000, timeoutMs = 60_000,
250
+ reasoningEffort, signal, purpose = 'ta-maintenance', attemptLimit = MAX_ATTEMPTS,
251
+ } = {}) {
252
+ const llm = this.ctx?.get?.('llm')
253
+ const selection = this.selection ?? this.available()
254
+ if (!llm || typeof llm.prepareCall !== 'function') {
255
+ return { ok: false, code: 'LLM_UNAVAILABLE', message: 'llm 服务不可用', attempts: 0, callIds: [] }
256
+ }
257
+ if (!selection) {
258
+ return { ok: false, code: 'MODEL_UNAVAILABLE', message: '没有可用的默认模型', attempts: 0, callIds: [] }
259
+ }
260
+ const effort = reasoningEffort ?? this.config?.maintenanceReasoningEffort ?? 'low'
261
+ const callIds = []
262
+ let totalUsage = null
263
+ let lastFailure = null
264
+ let retryPolicy = null
265
+
266
+ for (let attempt = 1; attempt <= Math.max(1, attemptLimit); attempt += 1) {
267
+ if (signal?.aborted) {
268
+ return { ok: false, code: 'ABORTED', message: '运行已取消', attempts: attempt - 1, callIds, usage: totalUsage }
269
+ }
270
+ const callId = `${runId ?? 'run'}:${stage ?? 'stage'}:${attempt}`
271
+ callIds.push(callId)
272
+ const controller = new AbortController()
273
+ let timedOut = false
274
+ const onAbort = () => controller.abort()
275
+ signal?.addEventListener?.('abort', onAbort, { once: true })
276
+ const timer = setTimeout(() => {
277
+ timedOut = true
278
+ controller.abort(timeoutError())
279
+ }, Math.max(1, timeoutMs))
280
+ let usage = null
281
+ let finish = null
282
+ let text = ''
283
+ let thrown = null
284
+ try {
285
+ const prepared = await llm.prepareCall({
286
+ provider: selection.provider,
287
+ model: selection.model,
288
+ reasoningEffort: effort,
289
+ maxTokens,
290
+ }, controller.signal)
291
+ retryPolicy = prepared.retryPolicy ?? retryPolicy
292
+ const assembler = createTextAssembler()
293
+ for await (const chunk of prepared.stream({
294
+ ...prepared.config,
295
+ system,
296
+ messages: [{ role: 'user', content: [{ type: 'text', text: input }] }],
297
+ purpose,
298
+ signal: controller.signal,
299
+ })) {
300
+ assembler.push(chunk)
301
+ }
302
+ const result = assembler.result()
303
+ text = result.text
304
+ usage = result.usage
305
+ finish = result.finish
306
+ } catch (error) {
307
+ thrown = error
308
+ } finally {
309
+ clearTimeout(timer)
310
+ signal?.removeEventListener?.('abort', onAbort)
311
+ }
312
+
313
+ if (usage) {
314
+ totalUsage = {
315
+ uncachedInput: (totalUsage?.uncachedInput ?? 0) + usage.uncachedInput,
316
+ cacheRead: (totalUsage?.cacheRead ?? 0) + usage.cacheRead,
317
+ cacheWrite: (totalUsage?.cacheWrite ?? 0) + usage.cacheWrite,
318
+ output: (totalUsage?.output ?? 0) + usage.output,
319
+ }
320
+ this.recordUsage({ runId, stage, attempt, model: selection.model, tokens: usage })
321
+ }
322
+
323
+ if (thrown) {
324
+ const abortedByUser = signal?.aborted === true
325
+ const code = abortedByUser
326
+ ? 'ABORTED'
327
+ : (timedOut ? 'TIMEOUT' : (thrown?.code ?? (controller.signal.aborted ? 'TIMEOUT' : 'UNKNOWN')))
328
+ lastFailure = {
329
+ code: abortedByUser ? 'ABORTED' : code,
330
+ message: String(thrown?.message ?? thrown),
331
+ }
332
+ if (abortedByUser) {
333
+ return { ok: false, ...lastFailure, attempts: attempt, callIds, usage: totalUsage, finishKind: 'aborted' }
334
+ }
335
+ if (isRetryableCode(code, retryPolicy) && attempt < attemptLimit) {
336
+ try {
337
+ await delay(backoffMs(retryPolicy, attempt), signal)
338
+ } catch {
339
+ return { ok: false, code: 'ABORTED', message: '运行已取消', attempts: attempt, callIds, usage: totalUsage }
340
+ }
341
+ continue
342
+ }
343
+ return { ok: false, ...lastFailure, attempts: attempt, callIds, usage: totalUsage, finishKind: 'error' }
344
+ }
345
+
346
+ const classified = classifyFinish(finish)
347
+ if (classified.ok) {
348
+ return {
349
+ ok: true,
350
+ text,
351
+ usage: totalUsage,
352
+ finishKind: classified.kind,
353
+ attempts: attempt,
354
+ callIds,
355
+ }
356
+ }
357
+ const abortedByUser = signal?.aborted === true
358
+ const normalizedCode = classified.kind === 'aborted' && !abortedByUser && timedOut
359
+ ? 'TIMEOUT'
360
+ : (classified.kind === 'aborted' ? 'ABORTED' : classified.code)
361
+ lastFailure = { code: normalizedCode, message: classified.message }
362
+ if (normalizedCode === 'ABORTED') {
363
+ return { ok: false, ...lastFailure, attempts: attempt, callIds, usage: totalUsage, finishKind: classified.kind }
364
+ }
365
+ if (classified.code === 'MAX_TOKENS') {
366
+ // 预算不够不是网络问题:重试同一提示词只会再被截断,交给上层处理(保留旧文件)。
367
+ return { ok: false, ...lastFailure, attempts: attempt, callIds, usage: totalUsage, finishKind: classified.kind }
368
+ }
369
+ if (isRetryableCode(normalizedCode, retryPolicy) && attempt < attemptLimit) {
370
+ try {
371
+ await delay(backoffMs(retryPolicy, attempt, classified.retryAfterMs), signal)
372
+ } catch {
373
+ return { ok: false, code: 'ABORTED', message: '运行已取消', attempts: attempt, callIds, usage: totalUsage }
374
+ }
375
+ continue
376
+ }
377
+ return { ok: false, ...lastFailure, attempts: attempt, callIds, usage: totalUsage, finishKind: classified.kind }
378
+ }
379
+ return { ok: false, code: lastFailure?.code ?? 'UNKNOWN', message: lastFailure?.message ?? '未知失败', attempts: attemptLimit, callIds, usage: totalUsage }
380
+ }
381
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * 维护互斥锁:openSync(path, 'wx') 原子创建。
3
+ *
4
+ * 陈旧锁判定:pid 不存在(ESRCH)、锁内容损坏、或开始时间超过 2 小时。
5
+ * EPERM 表示进程存在但不可发信号,按存活处理,不能误删。
6
+ */
7
+
8
+ import { closeSync, openSync, readFileSync, unlinkSync, writeSync } from 'node:fs'
9
+ import { resolve } from 'node:path'
10
+
11
+ export const LOCK_FILE = 'state/maintenance.lock'
12
+ export const LOCK_STALE_MS = 2 * 60 * 60 * 1000
13
+
14
+ export function maintenanceLockPath(config) {
15
+ return resolve(config.taHome, LOCK_FILE)
16
+ }
17
+
18
+ export function readMaintenanceLock(config) {
19
+ try {
20
+ const value = JSON.parse(readFileSync(maintenanceLockPath(config), 'utf8'))
21
+ if (!value || typeof value !== 'object') return null
22
+ return value
23
+ } catch {
24
+ return null
25
+ }
26
+ }
27
+
28
+ function pidAlive(pid) {
29
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false
30
+ try {
31
+ process.kill(pid, 0)
32
+ return true
33
+ } catch (error) {
34
+ // ESRCH: 进程不存在;EPERM: 进程存在但当前用户不能发信号。
35
+ return error?.code !== 'ESRCH'
36
+ }
37
+ }
38
+
39
+ function staleReason(lock, nowMs) {
40
+ if (!lock) return 'unreadable'
41
+ if (lock.pid === process.pid) return null
42
+ if (!pidAlive(lock.pid)) return 'pid-dead'
43
+ const started = Date.parse(lock.startedAt ?? '')
44
+ if (!Number.isFinite(started)) return 'invalid-started-at'
45
+ if (nowMs - started > LOCK_STALE_MS) return 'too-old'
46
+ return null
47
+ }
48
+
49
+ function writeLockFile(config, payload) {
50
+ const fd = openSync(maintenanceLockPath(config), 'wx', 0o600)
51
+ try {
52
+ writeSync(fd, JSON.stringify(payload) + '\n')
53
+ } finally {
54
+ closeSync(fd)
55
+ }
56
+ }
57
+
58
+ function removeLockFile(config) {
59
+ try {
60
+ unlinkSync(maintenanceLockPath(config))
61
+ } catch {
62
+ /* already gone */
63
+ }
64
+ }
65
+
66
+ /**
67
+ * 尝试获取维护锁。
68
+ * 返回 { acquired, lock, staleRemoved, reason },不抛错。
69
+ */
70
+ export function acquireMaintenanceLock(config, {
71
+ runId, runDate, nowMs = Date.now(), home = config.taHome,
72
+ } = {}) {
73
+ const payload = {
74
+ pid: process.pid,
75
+ runId,
76
+ runDate,
77
+ home,
78
+ startedAt: new Date(nowMs).toISOString(),
79
+ }
80
+ try {
81
+ writeLockFile(config, payload)
82
+ return { acquired: true, lock: payload, staleRemoved: false }
83
+ } catch (error) {
84
+ if (error?.code !== 'EEXIST') return { acquired: false, reason: `open-${error?.code ?? 'failed'}` }
85
+ }
86
+ const existing = readMaintenanceLock(config)
87
+ const stale = staleReason(existing, nowMs)
88
+ if (!stale) return { acquired: false, lock: existing, staleRemoved: false, reason: 'held' }
89
+ removeLockFile(config)
90
+ try {
91
+ writeLockFile(config, payload)
92
+ return { acquired: true, lock: payload, staleRemoved: true, stale, reason: 'stale-recovered' }
93
+ } catch {
94
+ return { acquired: false, lock: readMaintenanceLock(config), staleRemoved: true, reason: 'race' }
95
+ }
96
+ }
97
+
98
+ /** 只释放自己的锁:runId 不一致时保持原锁。 */
99
+ export function releaseMaintenanceLock(config, runId) {
100
+ const existing = readMaintenanceLock(config)
101
+ if (!existing) return true
102
+ if (existing.runId !== runId) return false
103
+ removeLockFile(config)
104
+ return true
105
+ }