@linjz/opencode-qqbot 0.3.15 → 0.3.16
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/README.md +42 -5
- package/bin/openqq.js +13 -0
- package/dist/notify-cli.js +28 -14
- package/dist/opencode-qqbot-plugin.js +934 -64
- package/dist/openqq-bot.js +3095 -677
- package/dist/openqq-cli.js +791 -0
- package/dist/openqq-watchdog.js +1063 -0
- package/package.json +8 -5
- package/src/bridge.ts +1310 -150
- package/src/cli/notify.ts +167 -158
- package/src/cli/openqq-main.ts +95 -0
- package/src/cli/service-main.ts +302 -0
- package/src/cli/watchdog-main.ts +77 -0
- package/src/commands.ts +644 -554
- package/src/config.ts +85 -0
- package/src/core/bot-control.ts +148 -0
- package/src/core/bot-launcher.ts +106 -13
- package/src/core/card-approval.ts +20 -9
- package/src/core/delivery.ts +145 -54
- package/src/core/discovery.ts +22 -4
- package/src/core/file-log.ts +35 -3
- package/src/core/form-bridge.ts +14 -5
- package/src/core/form-journal.ts +4 -4
- package/src/core/gateway-state.ts +3 -3
- package/src/core/inflight-journal.ts +214 -36
- package/src/core/instance-lock.ts +10 -2
- package/src/core/linkwatch.ts +3 -4
- package/src/core/markdown.ts +117 -0
- package/src/core/message-queue.ts +242 -91
- package/src/core/mirror.ts +222 -182
- package/src/core/notify-sink.ts +93 -96
- package/src/core/outbox.ts +10 -9
- package/src/core/permission.ts +627 -303
- package/src/core/question-form.ts +230 -0
- package/src/core/queue-view.ts +661 -0
- package/src/core/send-media.ts +32 -0
- package/src/core/storage.ts +34 -0
- package/src/core/watchdog.ts +513 -0
- package/src/core/zombie-reaper.ts +127 -0
- package/src/index.ts +140 -52
- package/src/opencode/client.ts +206 -27
- package/src/opencode/eventstream.ts +94 -12
- package/src/opencode/history.ts +4 -2
- package/src/opencode/mirror.ts +15 -2
- package/src/opencode/sessions.ts +135 -37
- package/src/plugin-entry.ts +120 -115
- package/src/qq/api.ts +165 -61
- package/src/qq/gateway.ts +79 -16
- package/src/qq/sender.ts +30 -18
- package/src/qq/types.ts +7 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// @input: fs/path/os(台账落盘)
|
|
1
|
+
// @input: fs/path/os(台账落盘)
|
|
2
2
|
// @output: claimInflight, recordInflight, settleInflight, pendingInflight, classifyInflight(纯函数供测试),
|
|
3
|
-
// pruneInflightEntries(保留策略纯函数), newInflightAttemptId,
|
|
3
|
+
// markInflightStage, listInflightView, pruneInflightEntries(保留策略纯函数), newInflightAttemptId,
|
|
4
4
|
// resetInflightJournal(测试用),
|
|
5
5
|
// INFLIGHT_MAX_AGE_MS, SETTLED_RETENTION_MS, SETTLED_RETENTION_LIMIT, redispatchMaxAgeMs
|
|
6
6
|
// @pos: core - 在途台账(重启换代丢消息修复:QQ 消息派发落账、答复送达销账、启动对账)
|
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
// 事故背景(2026-10-30,用户实证):bot 重启/网关静默死亡窗口内到达的 QQ 消息
|
|
9
9
|
// 丢失无反馈——在途回合状态全在内存,进程换代即蒸发。本模块把"派发→送达"责任
|
|
10
10
|
// 落盘到 ~/.openqq/inflight.json,启动时对账恢复(bridge.recoverInflightRounds)。
|
|
11
|
+
import { storageFile } from "./storage.js"
|
|
11
12
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, unlinkSync, statSync } from "fs"
|
|
12
13
|
import { join } from "path"
|
|
13
|
-
import { homedir } from "os"
|
|
14
14
|
import { admissionDecision } from "./inbound-dedupe.js"
|
|
15
15
|
|
|
16
16
|
export interface InflightEntry {
|
|
@@ -31,6 +31,48 @@ export interface InflightEntry {
|
|
|
31
31
|
fingerprint?: string
|
|
32
32
|
/** 本回合的 prompt 用户消息 id(修复⑧直答归属的回合边界锚点) */
|
|
33
33
|
promptId?: string
|
|
34
|
+
/**
|
|
35
|
+
* 可观测细化阶段(2026-11-05 队列/台账可观测性):
|
|
36
|
+
* claimed=已受理未入队 | queued=已入队 | dispatched=已派发未落 promptId
|
|
37
|
+
* running=执行中 | background=后台等待 | settled=已结清。
|
|
38
|
+
* state 仍是权威二元态;stage 只做诊断,缺失时按 sessionId/promptId 推导。
|
|
39
|
+
*/
|
|
40
|
+
stage?: InflightStage
|
|
41
|
+
/** 与内存队列 #id 对齐(重启恢复 FIFO 顺序用) */
|
|
42
|
+
queueId?: number
|
|
43
|
+
/** 入队时刻(重启按此排序重建队列) */
|
|
44
|
+
enqueuedAt?: number
|
|
45
|
+
/** 最后一次状态变更时刻 */
|
|
46
|
+
updatedAt?: number
|
|
47
|
+
/** 结清原因(诊断"为什么没答") */
|
|
48
|
+
settleReason?: SettleReason
|
|
49
|
+
/** 受理/更新所属进程(跨进程归属诊断) */
|
|
50
|
+
ownerPid?: number
|
|
51
|
+
/** 最近一次失败摘要(截 200 字) */
|
|
52
|
+
lastError?: string
|
|
53
|
+
/** 死回合自动续作已消耗次数(2026-11-19 owner 裁定:单任务续作上限 3 次,落盘防重启洗白) */
|
|
54
|
+
resumeCount?: number
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type InflightStage = "claimed" | "queued" | "dispatched" | "running" | "background" | "settled"
|
|
58
|
+
|
|
59
|
+
export type SettleReason =
|
|
60
|
+
| "answered"
|
|
61
|
+
| "error"
|
|
62
|
+
| "queue-full"
|
|
63
|
+
| "duplicate-msgid"
|
|
64
|
+
| "duplicate-intent"
|
|
65
|
+
| "cancelled"
|
|
66
|
+
| "dropped"
|
|
67
|
+
| "blocked"
|
|
68
|
+
| "superseded"
|
|
69
|
+
| "expired"
|
|
70
|
+
| "redispatch"
|
|
71
|
+
| "manual"
|
|
72
|
+
|
|
73
|
+
export interface InflightView {
|
|
74
|
+
inflight: InflightEntry[]
|
|
75
|
+
settled: InflightEntry[]
|
|
34
76
|
}
|
|
35
77
|
|
|
36
78
|
/** 生成新的投递代次 ID(bridge 显式新回合/显式重投时调用) */
|
|
@@ -71,16 +113,17 @@ export function redispatchMaxAgeMs(): number {
|
|
|
71
113
|
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7_200_000
|
|
72
114
|
}
|
|
73
115
|
|
|
74
|
-
//
|
|
75
|
-
function journalPath(): string {
|
|
76
|
-
return process.env.QQ_INFLIGHT_FILE ||
|
|
116
|
+
// 路径解析:显式注入(多角色 createInflightJournal(file))> env 覆盖(测试)> legacy 全局。
|
|
117
|
+
function journalPath(file?: string): string {
|
|
118
|
+
return file || process.env.QQ_INFLIGHT_FILE || storageFile("inflight.json")
|
|
77
119
|
}
|
|
78
120
|
|
|
79
|
-
function load(): InflightEntry[] {
|
|
121
|
+
function load(file?: string): InflightEntry[] {
|
|
80
122
|
let entries: InflightEntry[] = []
|
|
123
|
+
const path = journalPath(file)
|
|
81
124
|
try {
|
|
82
|
-
if (existsSync(
|
|
83
|
-
const raw = JSON.parse(readFileSync(
|
|
125
|
+
if (existsSync(path)) {
|
|
126
|
+
const raw = JSON.parse(readFileSync(path, "utf-8"))
|
|
84
127
|
if (Array.isArray(raw)) entries = raw
|
|
85
128
|
}
|
|
86
129
|
} catch {
|
|
@@ -90,8 +133,8 @@ function load(): InflightEntry[] {
|
|
|
90
133
|
return pruneInflightEntries(entries)
|
|
91
134
|
}
|
|
92
135
|
|
|
93
|
-
function save(entries: InflightEntry[]): void {
|
|
94
|
-
const path = journalPath()
|
|
136
|
+
function save(file: string | undefined, entries: InflightEntry[]): void {
|
|
137
|
+
const path = journalPath(file)
|
|
95
138
|
mkdirSync(join(path, ".."), { recursive: true })
|
|
96
139
|
const retained = pruneInflightEntries(entries)
|
|
97
140
|
// 临时文件带进程与随机后缀:并发执行体不会互相覆盖对方的 tmp。
|
|
@@ -111,8 +154,8 @@ const JOURNAL_LOCK_STALE_MS = 30_000
|
|
|
111
154
|
const JOURNAL_LOCK_WAIT_MS = 5_000
|
|
112
155
|
const sleepArray = new Int32Array(new SharedArrayBuffer(4))
|
|
113
156
|
|
|
114
|
-
function withJournalLock<T>(fn: () => T): T {
|
|
115
|
-
const path = journalPath()
|
|
157
|
+
function withJournalLock<T>(file: string | undefined, fn: () => T): T {
|
|
158
|
+
const path = journalPath(file)
|
|
116
159
|
mkdirSync(join(path, ".."), { recursive: true })
|
|
117
160
|
const lockPath = `${path}.lock`
|
|
118
161
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`
|
|
@@ -147,11 +190,11 @@ function withJournalLock<T>(fn: () => T): T {
|
|
|
147
190
|
}
|
|
148
191
|
}
|
|
149
192
|
|
|
150
|
-
function mutate<T>(fn: (entries: InflightEntry[]) => T): T {
|
|
151
|
-
return withJournalLock(() => {
|
|
152
|
-
const entries = load()
|
|
193
|
+
function mutate<T>(file: string | undefined, fn: (entries: InflightEntry[]) => T): T {
|
|
194
|
+
return withJournalLock(file, () => {
|
|
195
|
+
const entries = load(file)
|
|
153
196
|
const result = fn(entries)
|
|
154
|
-
save(entries)
|
|
197
|
+
save(file, entries)
|
|
155
198
|
return result
|
|
156
199
|
})
|
|
157
200
|
}
|
|
@@ -169,8 +212,8 @@ export type ClaimOutcome = "ok" | "duplicate-msgid" | "duplicate-intent"
|
|
|
169
212
|
* attemptId;未传则生成新代次);不另建去重文件。
|
|
170
213
|
* 被 24h/20 条保留策略裁掉的旧 msgId 也可正常认领。
|
|
171
214
|
*/
|
|
172
|
-
export function claimInflightDetailed(entry: Omit<InflightEntry, "state">, opts?: { fingerprint?: string }): ClaimOutcome {
|
|
173
|
-
return mutate((entries) => {
|
|
215
|
+
export function claimInflightDetailed(entry: Omit<InflightEntry, "state">, opts?: { fingerprint?: string; file?: string }): ClaimOutcome {
|
|
216
|
+
return mutate(opts?.file, (entries) => {
|
|
174
217
|
const fingerprint = opts?.fingerprint ?? entry.fingerprint ?? ""
|
|
175
218
|
const decision = admissionDecision({
|
|
176
219
|
hasSameMsgIdInflight: entries.some((e) => e.msgId === entry.msgId && e.state === "inflight"),
|
|
@@ -181,19 +224,35 @@ export function claimInflightDetailed(entry: Omit<InflightEntry, "state">, opts?
|
|
|
181
224
|
})
|
|
182
225
|
if (decision !== "ok") return decision
|
|
183
226
|
const attempt = entry.attemptId ?? newInflightAttemptId()
|
|
227
|
+
const now = Date.now()
|
|
184
228
|
const existing = entries.find((e) => e.msgId === entry.msgId)
|
|
185
229
|
if (existing) {
|
|
186
|
-
Object.assign(existing, entry, {
|
|
230
|
+
Object.assign(existing, entry, {
|
|
231
|
+
fingerprint,
|
|
232
|
+
attemptId: attempt,
|
|
233
|
+
state: "inflight" as const,
|
|
234
|
+
stage: entry.stage ?? "claimed",
|
|
235
|
+
updatedAt: now,
|
|
236
|
+
ownerPid: entry.ownerPid ?? process.pid,
|
|
237
|
+
})
|
|
187
238
|
} else {
|
|
188
|
-
entries.push({
|
|
239
|
+
entries.push({
|
|
240
|
+
...entry,
|
|
241
|
+
fingerprint,
|
|
242
|
+
attemptId: attempt,
|
|
243
|
+
state: "inflight" as const,
|
|
244
|
+
stage: entry.stage ?? "claimed",
|
|
245
|
+
updatedAt: now,
|
|
246
|
+
ownerPid: entry.ownerPid ?? process.pid,
|
|
247
|
+
})
|
|
189
248
|
}
|
|
190
249
|
return "ok"
|
|
191
250
|
})
|
|
192
251
|
}
|
|
193
252
|
|
|
194
253
|
/** 兼容旧布尔签名的认领(测试与既有调用方) */
|
|
195
|
-
export function claimInflight(entry: Omit<InflightEntry, "state"
|
|
196
|
-
return claimInflightDetailed(entry) === "ok"
|
|
254
|
+
export function claimInflight(entry: Omit<InflightEntry, "state">, file?: string): boolean {
|
|
255
|
+
return claimInflightDetailed(entry, { file }) === "ok"
|
|
197
256
|
}
|
|
198
257
|
|
|
199
258
|
/**
|
|
@@ -203,22 +262,41 @@ export function claimInflight(entry: Omit<InflightEntry, "state">): boolean {
|
|
|
203
262
|
* - 已 settled:显式重投重新激活(换新代次与新的 at/user/session/text);
|
|
204
263
|
* - 无记录:新增在途。
|
|
205
264
|
*/
|
|
206
|
-
export function recordInflight(entry: Omit<InflightEntry, "state"
|
|
207
|
-
mutate((entries) => {
|
|
265
|
+
export function recordInflight(entry: Omit<InflightEntry, "state">, file?: string): void {
|
|
266
|
+
mutate(file, (entries) => {
|
|
267
|
+
const now = Date.now()
|
|
208
268
|
const existing = entries.find((e) => e.msgId === entry.msgId)
|
|
209
269
|
if (existing) {
|
|
210
270
|
if (existing.state === "inflight") {
|
|
211
271
|
if (entry.attemptId && existing.attemptId && entry.attemptId !== existing.attemptId) return
|
|
212
272
|
if (!existing.sessionId && entry.sessionId) existing.sessionId = entry.sessionId
|
|
213
273
|
if (!existing.promptId && entry.promptId) existing.promptId = entry.promptId
|
|
274
|
+
// 派发落账 = 已进入会话;stage 只前进不回退(queued → dispatched)
|
|
275
|
+
if (entry.sessionId) existing.stage = existing.stage === "running" || existing.stage === "background" ? existing.stage : "dispatched"
|
|
276
|
+
existing.updatedAt = now
|
|
277
|
+
if (!existing.ownerPid) existing.ownerPid = process.pid
|
|
214
278
|
return
|
|
215
279
|
}
|
|
216
280
|
// settled:视为显式重投,重新激活为新在途回合
|
|
217
281
|
const attempt = entry.attemptId ?? newInflightAttemptId()
|
|
218
|
-
Object.assign(existing, entry, {
|
|
282
|
+
Object.assign(existing, entry, {
|
|
283
|
+
attemptId: attempt,
|
|
284
|
+
state: "inflight" as const,
|
|
285
|
+
stage: entry.stage ?? (entry.sessionId ? "dispatched" : "claimed"),
|
|
286
|
+
updatedAt: now,
|
|
287
|
+
settleReason: undefined,
|
|
288
|
+
ownerPid: entry.ownerPid ?? process.pid,
|
|
289
|
+
})
|
|
219
290
|
return
|
|
220
291
|
}
|
|
221
|
-
entries.push({
|
|
292
|
+
entries.push({
|
|
293
|
+
...entry,
|
|
294
|
+
attemptId: entry.attemptId ?? newInflightAttemptId(),
|
|
295
|
+
state: "inflight" as const,
|
|
296
|
+
stage: entry.stage ?? (entry.sessionId ? "dispatched" : "claimed"),
|
|
297
|
+
updatedAt: now,
|
|
298
|
+
ownerPid: entry.ownerPid ?? process.pid,
|
|
299
|
+
})
|
|
222
300
|
})
|
|
223
301
|
}
|
|
224
302
|
|
|
@@ -226,38 +304,104 @@ export function recordInflight(entry: Omit<InflightEntry, "state">): void {
|
|
|
226
304
|
* 销账:答复已送达(或已转入有接管的后台等待/已给用户终态反馈)。
|
|
227
305
|
* 传入 attemptId 时必须 msgId + attemptId 双匹配才销账——settled 重新认领后,
|
|
228
306
|
* 旧代次的迟到 settle 不得把新在途回合误销。返回是否实际销账。
|
|
307
|
+
* reason 记录"为什么结束",供 /ledger 区分 answered 与 rejected。
|
|
229
308
|
*/
|
|
230
|
-
export function settleInflight(msgId: string, attemptId?: string): boolean {
|
|
231
|
-
return mutate((entries) => {
|
|
309
|
+
export function settleInflight(msgId: string, attemptId?: string, reason: SettleReason = "answered", file?: string): boolean {
|
|
310
|
+
return mutate(file, (entries) => {
|
|
232
311
|
const entry = entries.find(
|
|
233
312
|
(e) => e.msgId === msgId && e.state === "inflight" && (!attemptId || !e.attemptId || e.attemptId === attemptId),
|
|
234
313
|
)
|
|
235
314
|
if (!entry) return false
|
|
236
315
|
entry.state = "settled"
|
|
316
|
+
entry.stage = "settled"
|
|
317
|
+
entry.settleReason = reason
|
|
318
|
+
entry.updatedAt = Date.now()
|
|
237
319
|
return true
|
|
238
320
|
})
|
|
239
321
|
}
|
|
240
322
|
|
|
241
323
|
/** 待对账清单(启动恢复用) */
|
|
242
|
-
export function pendingInflight(): InflightEntry[] {
|
|
243
|
-
return load().filter((e) => e.state === "inflight")
|
|
324
|
+
export function pendingInflight(file?: string): InflightEntry[] {
|
|
325
|
+
return load(file).filter((e) => e.state === "inflight")
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** 台账快照(/queue 与 /ledger 派生视图的数据源;不做用户过滤) */
|
|
329
|
+
export function listInflightView(file?: string): InflightView {
|
|
330
|
+
const entries = load(file)
|
|
331
|
+
return {
|
|
332
|
+
inflight: entries.filter((e) => e.state === "inflight").sort((a, b) => a.at - b.at),
|
|
333
|
+
settled: entries.filter((e) => e.state === "settled").sort((a, b) => b.at - a.at),
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* 阶段推进(可观测性):只对在途账生效,默认只前进不回退。
|
|
339
|
+
* patch 用于回填 queueId/enqueuedAt/sessionId/promptId/lastError。
|
|
340
|
+
* opts.force:重启恢复排队时允许回退到 queued(进程换代后旧 stage 不再可信)。
|
|
341
|
+
*/
|
|
342
|
+
export function markInflightStage(
|
|
343
|
+
msgId: string,
|
|
344
|
+
stage: InflightStage,
|
|
345
|
+
patch?: Partial<Pick<InflightEntry, "queueId" | "enqueuedAt" | "sessionId" | "promptId" | "lastError">>,
|
|
346
|
+
opts?: { force?: boolean; file?: string },
|
|
347
|
+
): boolean {
|
|
348
|
+
const rank: Record<InflightStage, number> = {
|
|
349
|
+
claimed: 0,
|
|
350
|
+
queued: 1,
|
|
351
|
+
dispatched: 2,
|
|
352
|
+
running: 3,
|
|
353
|
+
background: 4,
|
|
354
|
+
settled: 5,
|
|
355
|
+
}
|
|
356
|
+
return mutate(opts?.file, (entries) => {
|
|
357
|
+
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight")
|
|
358
|
+
if (!entry) return false
|
|
359
|
+
if (opts?.force || !entry.stage || rank[stage] >= rank[entry.stage]) entry.stage = stage
|
|
360
|
+
if (patch?.queueId !== undefined) entry.queueId = patch.queueId
|
|
361
|
+
if (patch?.enqueuedAt !== undefined) entry.enqueuedAt = patch.enqueuedAt
|
|
362
|
+
if (patch?.sessionId && !entry.sessionId) entry.sessionId = patch.sessionId
|
|
363
|
+
if (patch?.promptId && !entry.promptId) entry.promptId = patch.promptId
|
|
364
|
+
if (patch?.lastError !== undefined) entry.lastError = patch.lastError.slice(0, 200)
|
|
365
|
+
entry.updatedAt = Date.now()
|
|
366
|
+
return true
|
|
367
|
+
})
|
|
244
368
|
}
|
|
245
369
|
|
|
246
370
|
/**
|
|
247
371
|
* 回合 prompt 落库后回填 promptId(修复⑧):后台等待/重启重挂的直答归属
|
|
248
372
|
* 需要「这是哪个回合」的边界锚点,taskId 台账是跨进程唯一可靠载体。
|
|
373
|
+
* 2026-11-05:同时把 stage 推进到 running(可观测性)。
|
|
249
374
|
*/
|
|
250
|
-
export function markInflightPromptId(msgId: string, promptId: string): void {
|
|
375
|
+
export function markInflightPromptId(msgId: string, promptId: string, file?: string): void {
|
|
251
376
|
if (!promptId) return
|
|
252
|
-
mutate((entries) => {
|
|
377
|
+
mutate(file, (entries) => {
|
|
253
378
|
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight")
|
|
254
|
-
if (
|
|
379
|
+
if (!entry) return
|
|
380
|
+
if (!entry.promptId) entry.promptId = promptId
|
|
381
|
+
entry.stage = "running"
|
|
382
|
+
entry.updatedAt = Date.now()
|
|
383
|
+
})
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* 续作锚点更新(2026-11-19 死回合自动续作):新回合的 promptId 必须强制覆盖旧锚点
|
|
388
|
+
* (markPromptId/markStage 的「只补空」语义不适用——旧锚点已存在),
|
|
389
|
+
* resumeCount 同步落盘:bot 重启后启动对账重挂按已消耗次数续算,上限不洗白。
|
|
390
|
+
*/
|
|
391
|
+
export function markInflightResume(msgId: string, promptId: string, resumeCount: number, file?: string): void {
|
|
392
|
+
if (!promptId) return
|
|
393
|
+
mutate(file, (entries) => {
|
|
394
|
+
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight")
|
|
395
|
+
if (!entry) return
|
|
396
|
+
entry.promptId = promptId
|
|
397
|
+
entry.resumeCount = resumeCount
|
|
398
|
+
entry.updatedAt = Date.now()
|
|
255
399
|
})
|
|
256
400
|
}
|
|
257
401
|
|
|
258
402
|
/** 测试用:清空台账文件状态 */
|
|
259
|
-
export function resetInflightJournal(): void {
|
|
260
|
-
withJournalLock(() => save([]))
|
|
403
|
+
export function resetInflightJournal(file?: string): void {
|
|
404
|
+
withJournalLock(file, () => save(file, []))
|
|
261
405
|
}
|
|
262
406
|
|
|
263
407
|
// —— 对账分类(纯函数)——
|
|
@@ -380,3 +524,37 @@ export function classifyInflight(
|
|
|
380
524
|
}
|
|
381
525
|
return { kind: "running" }
|
|
382
526
|
}
|
|
527
|
+
|
|
528
|
+
// ── 多角色绑定实例(2026-11-17,owner 裁定单进程多 bot 身份)──
|
|
529
|
+
// 单进程多角色时,各角色的台账必须物理隔离(否则重启对账跨角色误补/误派)。
|
|
530
|
+
// createInflightJournal(file) 返回绑定到指定文件的实例;模块级具名导出 =
|
|
531
|
+
// 默认实例(路径解析照旧:env 覆盖 > legacy 全局),既有调用方/测试零改动。
|
|
532
|
+
export interface InflightJournal {
|
|
533
|
+
readonly file: string
|
|
534
|
+
claim: typeof claimInflight
|
|
535
|
+
claimDetailed: typeof claimInflightDetailed
|
|
536
|
+
record: typeof recordInflight
|
|
537
|
+
settle: typeof settleInflight
|
|
538
|
+
pending: typeof pendingInflight
|
|
539
|
+
view: typeof listInflightView
|
|
540
|
+
markStage: typeof markInflightStage
|
|
541
|
+
markPromptId: typeof markInflightPromptId
|
|
542
|
+
markResume: typeof markInflightResume
|
|
543
|
+
reset: typeof resetInflightJournal
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
export function createInflightJournal(file?: string): InflightJournal {
|
|
547
|
+
return {
|
|
548
|
+
file: journalPath(file),
|
|
549
|
+
claim: (entry) => claimInflight(entry, file),
|
|
550
|
+
claimDetailed: (entry, opts) => claimInflightDetailed(entry, { ...opts, file }),
|
|
551
|
+
record: (entry) => recordInflight(entry, file),
|
|
552
|
+
settle: (msgId, attemptId, reason) => settleInflight(msgId, attemptId, reason, file),
|
|
553
|
+
pending: () => pendingInflight(file),
|
|
554
|
+
view: () => listInflightView(file),
|
|
555
|
+
markStage: (msgId, stage, patch, opts) => markInflightStage(msgId, stage, patch, { ...opts, file }),
|
|
556
|
+
markPromptId: (msgId, promptId) => markInflightPromptId(msgId, promptId, file),
|
|
557
|
+
markResume: (msgId, promptId, resumeCount) => markInflightResume(msgId, promptId, resumeCount, file),
|
|
558
|
+
reset: () => resetInflightJournal(file),
|
|
559
|
+
}
|
|
560
|
+
}
|
|
@@ -22,6 +22,9 @@ const LOCK_RETRY_MS = 5_000 // 待命抢锁间隔
|
|
|
22
22
|
// 心跳 touch 失败是静默的(锁文件被新实例接管/删除后自己并不知道),双 believer
|
|
23
23
|
// 并存造成同 msgId 并发受理(主链)。自检看锁文件里的 pid:不是自己且进程存活
|
|
24
24
|
// → 本实例是残留,自杀退出;锁文件消失同样说明被强抢 → 自杀。待命态无锁不检。
|
|
25
|
+
// P2-10(2026-11-09):自杀判定加锁 mtime 新鲜度——真 holder 每 10s 心跳 touch;
|
|
26
|
+
// holder pid 存活但锁已陈旧 = 高度疑似 PID 复用(Windows pid 回收快),此时不自杀,
|
|
27
|
+
// 交由 stale 强抢流程正常接管(误自杀比双跑代价大,宽进严出)。
|
|
25
28
|
const LOCK_SELF_CHECK_MS = 60_000
|
|
26
29
|
|
|
27
30
|
export interface InstanceLock {
|
|
@@ -87,8 +90,13 @@ export function acquireInstanceLockAt(
|
|
|
87
90
|
if (holder === process.pid) return
|
|
88
91
|
try {
|
|
89
92
|
process.kill(holder!, 0)
|
|
90
|
-
|
|
91
|
-
|
|
93
|
+
// P2-10:holder 存活时分两种情况——锁新鲜=真双 believer(自杀);锁陈旧=疑 PID 复用(不自杀)
|
|
94
|
+
const lockFresh = Date.now() - statSync(path).mtimeMs <= LOCK_STALE_MS
|
|
95
|
+
if (lockFresh) {
|
|
96
|
+
console.error(`[instance-lock] 自检:锁已被 pid=${holder} 持有且进程存活(锁新鲜),本实例为残留 believer,自杀退出`)
|
|
97
|
+
process.exit(1)
|
|
98
|
+
}
|
|
99
|
+
console.warn(`[instance-lock] 自检:holder pid=${holder} 存活但锁已陈旧(疑 PID 复用),不自杀,交由 stale 强抢接管`)
|
|
92
100
|
} catch {
|
|
93
101
|
/* holder 已死:等待其锁被 stale 逻辑回收,本实例继续自检 */
|
|
94
102
|
}
|
package/src/core/linkwatch.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// HC2(2026-10-26):运行中链路自愈巡检。
|
|
1
|
+
// HC2(2026-10-26):运行中链路自愈巡检。
|
|
2
2
|
// 复盘3 教训:bot 与 opencode 平时零流量 + 看门狗只验进程心跳 → 下游死亡
|
|
3
3
|
// 不可观测(2026-10-26 实证:端口漂移后黑暗 3 天,直到用户消息撞上)。
|
|
4
4
|
// 本模块给链路装独立心跳:
|
|
@@ -11,9 +11,8 @@
|
|
|
11
11
|
// @input: client(healthCheck/rebase)、discoverOpencode、alarm 回调、fs
|
|
12
12
|
// @output: startLinkWatch, LinkWatchDeps, IncidentRecord, incidentPath
|
|
13
13
|
// @pos: core - 链路巡检(HC2)
|
|
14
|
+
import { storageFile } from "./storage.js"
|
|
14
15
|
import { existsSync, readFileSync, writeFileSync } from "fs"
|
|
15
|
-
import { join } from "path"
|
|
16
|
-
import { homedir } from "os"
|
|
17
16
|
import { discoverOpencode, persistDiscovery, type OpencodeDiscovery } from "./discovery.js"
|
|
18
17
|
import { healthCheck, type OpencodeClient } from "../opencode/client.js"
|
|
19
18
|
|
|
@@ -40,7 +39,7 @@ export interface IncidentRecord {
|
|
|
40
39
|
}
|
|
41
40
|
|
|
42
41
|
export function incidentPath(): string {
|
|
43
|
-
return
|
|
42
|
+
return storageFile("incident.json")
|
|
44
43
|
}
|
|
45
44
|
|
|
46
45
|
function saveIncident(path: string, rec: IncidentRecord): void {
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// @input: (纯文本工具,无依赖)
|
|
2
|
+
// @output: startsWithBlockSyntax, labelBlock, matchFence, balanceFences, FenceToken
|
|
3
|
+
// @pos: 根层/core - QQ markdown 安全层(标签↔块级语法隔离、围栏配对兜底)
|
|
4
|
+
//
|
|
5
|
+
// 背景(2026-11-10 用户截图实证):摘要卡正文以 ``` 开头时,标签行
|
|
6
|
+
// `🤖 \`\`\`` 让开围栏不顶格(CommonMark 要求行首 ≤3 空格),开栏失效;而结尾
|
|
7
|
+
// 顶格的 ``` 反而被当成开栏 → QQ 渲染出一张空代码卡、正文外泄成普通段落。
|
|
8
|
+
// 同类风险还有:/history 的 🧑/🤖 标签 + 块级正文、clipBlock 截断切断围栏、
|
|
9
|
+
// 分条器只认 ``` 不认 ~~~。本模块把「标签拼接」与「围栏配对」收敛成两个纯函数,
|
|
10
|
+
// 供摘要、历史、分条与出站兜底共用。
|
|
11
|
+
|
|
12
|
+
/** 一行里识别到的围栏标记(含信息串,如 ```ts 的 ts) */
|
|
13
|
+
export interface FenceToken {
|
|
14
|
+
/** 围栏字符:反引号或波浪线 */
|
|
15
|
+
ch: "`" | "~"
|
|
16
|
+
/** 连续标记长度(CommonMark 允许 ≥3,闭合须 ≥ 开启长度) */
|
|
17
|
+
len: number
|
|
18
|
+
/** 信息串(语言标签);闭合围栏的信息串必须为空 */
|
|
19
|
+
info: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// CommonMark:围栏前最多 3 空格;反引号围栏的信息串不得含反引号。
|
|
23
|
+
const FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/
|
|
24
|
+
|
|
25
|
+
/** 判断整行是否为围栏行;返回标记,非围栏返回 null。 */
|
|
26
|
+
export function matchFence(line: string): FenceToken | null {
|
|
27
|
+
const m = FENCE_LINE.exec(line)
|
|
28
|
+
if (!m) return null
|
|
29
|
+
const run = m[1]
|
|
30
|
+
const ch = run[0] as "`" | "~"
|
|
31
|
+
const info = m[2].trim()
|
|
32
|
+
if (ch === "`" && info.includes("`")) return null
|
|
33
|
+
return { ch, len: run.length, info }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// 正文首个非空行落在这些块级构造上时,标签必须独占一行——否则 "🤖 " 前缀会把
|
|
37
|
+
// 围栏/标题/列表/引用/表格降级成普通段落(最坏情况即空代码卡 + 内容外泄)。
|
|
38
|
+
const BLOCK_START = [
|
|
39
|
+
/^ {0,3}(`{3,}|~{3,})/, // 围栏代码块
|
|
40
|
+
/^ {0,3}#{1,6}(\s|$)/, // ATX 标题
|
|
41
|
+
/^ {0,3}>/, // 引用
|
|
42
|
+
/^ {0,3}([-*+]|\d{1,9}[.)])\s+/, // 无序/有序列表
|
|
43
|
+
/^ {0,3}\|/, // GFM 表格
|
|
44
|
+
/^ {0,3}((-\s*){3,}|(\*\s*){3,}|(_\s*){3,})$/, // 分隔线
|
|
45
|
+
/^ {0,3}</, // HTML 块
|
|
46
|
+
/^ {4,}\S/, // 缩进代码块
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
/** 正文首个非空行是否以块级语法开头(决定标签能否内联)。 */
|
|
50
|
+
export function startsWithBlockSyntax(text: string): boolean {
|
|
51
|
+
const first = text.split("\n").find((line) => line.trim() !== "") ?? ""
|
|
52
|
+
return BLOCK_START.some((re) => re.test(first))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 给正文加标签(如 "🤖"):普通段落保持 "标签 正文" 内联;块级正文让标签独占一行,
|
|
57
|
+
* 保住块级语法与围栏顶格。空正文只返回标签。
|
|
58
|
+
*/
|
|
59
|
+
export function labelBlock(label: string, body: string): string {
|
|
60
|
+
if (!body.trim()) return label
|
|
61
|
+
return startsWithBlockSyntax(body) ? `${label}\n${body}` : `${label} ${body}`
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 出站兜底(补):去掉「空围栏对」——开栏下一行就是同字符同长度闭栏。
|
|
66
|
+
* 嵌套围栏/套娃预览时,多余的成对围栏会在 QQ 里渲染成一张空白代码卡
|
|
67
|
+
* (2026-11-10 第二轮截图实证),而空代码块本身没有任何信息量。
|
|
68
|
+
* 含空白的空块同样去除;非空块逐字保留。
|
|
69
|
+
*/
|
|
70
|
+
export function stripEmptyFences(text: string): string {
|
|
71
|
+
const lines = text.split("\n")
|
|
72
|
+
const out: string[] = []
|
|
73
|
+
for (let i = 0; i < lines.length; i++) {
|
|
74
|
+
const open = matchFence(lines[i])
|
|
75
|
+
if (open) {
|
|
76
|
+
const next = i + 1 < lines.length ? matchFence(lines[i + 1]) : null
|
|
77
|
+
const empty = next !== null && next.ch === open.ch && next.len >= open.len && next.info === ""
|
|
78
|
+
if (empty) {
|
|
79
|
+
i += 1
|
|
80
|
+
continue
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
out.push(lines[i])
|
|
84
|
+
}
|
|
85
|
+
return out.join("\n")
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 出站兜底:补齐未闭合的围栏。QQ 渲染器把未闭合围栏吞到消息末尾并渲染成空卡片,
|
|
90
|
+
* 因此在发送前把「开栏无闭栏」补成配对(内容仍是原文,只是补一个闭合标记)。
|
|
91
|
+
* 已配对的文本逐字返回,幂等。
|
|
92
|
+
*/
|
|
93
|
+
export function balanceFences(text: string): string {
|
|
94
|
+
let open: FenceToken | null = null
|
|
95
|
+
for (const line of text.split("\n")) {
|
|
96
|
+
const f = matchFence(line)
|
|
97
|
+
if (!f) continue
|
|
98
|
+
if (!open) {
|
|
99
|
+
open = f
|
|
100
|
+
} else if (f.ch === open.ch && f.len >= open.len && f.info === "") {
|
|
101
|
+
open = null
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (!open) return text
|
|
105
|
+
const closer = open.ch.repeat(open.len)
|
|
106
|
+
return text.endsWith("\n") ? `${text}${closer}` : `${text}\n${closer}`
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 出站 markdown 归一:先补配对、再清空块(顺序不可换——配对本就会造出新的空对)。
|
|
111
|
+
* 归一后为空则回退到只配对的结果,避免整条消息被清空。
|
|
112
|
+
*/
|
|
113
|
+
export function normalizeOutboundMarkdown(text: string): string {
|
|
114
|
+
const balanced = balanceFences(text)
|
|
115
|
+
const stripped = stripEmptyFences(balanced)
|
|
116
|
+
return stripped.trim() ? stripped : balanced
|
|
117
|
+
}
|