@linjz/opencode-qqbot 0.3.20 → 0.3.21
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 +10 -2
- package/README.zh-CN.md +11 -3
- package/bin/openqq.js +1 -1
- package/dist/opencode-qqbot-plugin.js +124 -6
- package/dist/openqq-bot.js +560 -93
- package/dist/openqq-cli.js +152 -16
- package/dist/openqq-watchdog.js +72 -2
- package/package.json +2 -2
- package/src/bridge.ts +26 -6
- package/src/cli/openqq-main.ts +33 -5
- package/src/core/bot-control.ts +73 -8
- package/src/core/card-approval.ts +10 -0
- package/src/core/office-text.ts +234 -0
- package/src/core/permission.ts +157 -26
- package/src/core/watchdog.ts +108 -5
- package/src/qq/media.ts +153 -54
package/src/core/watchdog.ts
CHANGED
|
@@ -360,11 +360,12 @@ export interface SuperviseDeps {
|
|
|
360
360
|
policy?: SupervisorPolicy
|
|
361
361
|
/**
|
|
362
362
|
* 触发形态:health-check=周期巡检(默认);manual-restart=openqq restart
|
|
363
|
-
*
|
|
364
|
-
* manual-restart
|
|
365
|
-
*
|
|
363
|
+
* 人工请求;manual-stop=openqq stop 人工停止(design §3.9.1:restart/stop 都是
|
|
364
|
+
* superviseOnce 的调用方而非独立实现)。manual-restart 下健康实例也会被优雅杀后拉起;
|
|
365
|
+
* manual-stop 下健康实例优雅杀后不拉起、不计重启强度账。两者都跳过「杀前复核」
|
|
366
|
+
* (人工意图即权威,复核只防监督者误杀);认领互斥/审计分家全部照旧。
|
|
366
367
|
*/
|
|
367
|
-
request?: "health-check" | "manual-restart"
|
|
368
|
+
request?: "health-check" | "manual-restart" | "manual-stop"
|
|
368
369
|
now?: () => number
|
|
369
370
|
kill?: (pid: number, signal?: "SIGTERM" | "SIGKILL") => void
|
|
370
371
|
isAlive?: (pid: number) => boolean
|
|
@@ -374,6 +375,8 @@ export interface SuperviseDeps {
|
|
|
374
375
|
alert?: (message: string) => void
|
|
375
376
|
statePath?: string
|
|
376
377
|
claimPath?: string
|
|
378
|
+
/** manual-stop 持有标记路径(测试注入临时文件;缺省 ~/.openqq/supervisor-hold.json) */
|
|
379
|
+
holdPath?: string
|
|
377
380
|
/** 监督动作审计日志路径(测试注入临时文件,避免污染真实 watchdog.log) */
|
|
378
381
|
auditLogPath?: string
|
|
379
382
|
/**
|
|
@@ -408,6 +411,47 @@ function readJson<T>(path: string, fallback: T): T {
|
|
|
408
411
|
}
|
|
409
412
|
}
|
|
410
413
|
|
|
414
|
+
export interface SupervisorHold {
|
|
415
|
+
version: 1
|
|
416
|
+
reason: string
|
|
417
|
+
by: string
|
|
418
|
+
at: number
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function defaultHoldPath(): string {
|
|
422
|
+
return join(homedir(), ".openqq", "supervisor-hold.json")
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
export function readSupervisorHold(path = defaultHoldPath()): SupervisorHold | null {
|
|
426
|
+
try {
|
|
427
|
+
const raw = JSON.parse(readFileSync(path, "utf-8")) as Partial<SupervisorHold>
|
|
428
|
+
if (raw?.version === 1 && typeof raw.reason === "string" && typeof raw.by === "string" && typeof raw.at === "number") {
|
|
429
|
+
return raw as SupervisorHold
|
|
430
|
+
}
|
|
431
|
+
} catch {
|
|
432
|
+
/* 缺失/损坏视为无 hold */
|
|
433
|
+
}
|
|
434
|
+
return null
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export function writeSupervisorHold(path: string, reason: string, by: string): void {
|
|
438
|
+
try {
|
|
439
|
+
writeFileSync(path, JSON.stringify({ version: 1, reason, by, at: Date.now() } satisfies SupervisorHold))
|
|
440
|
+
} catch {
|
|
441
|
+
/* hold 落盘失败不阻断停止动作本身;下次巡检仍可能拉起,日志已留痕 */
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
export function clearSupervisorHold(path: string): boolean {
|
|
446
|
+
try {
|
|
447
|
+
if (!existsSync(path)) return false
|
|
448
|
+
unlinkSync(path)
|
|
449
|
+
return true
|
|
450
|
+
} catch {
|
|
451
|
+
return false
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
411
455
|
/**
|
|
412
456
|
* 单次监督:认领锁 → 判健康 → 决策 → 执行(优雅杀/拉起/放弃上报)→ 记强度账。
|
|
413
457
|
* 插件引导器与计划任务共用本函数,互斥靠 claim 文件,杜绝双开竞争。
|
|
@@ -454,8 +498,36 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
|
|
|
454
498
|
try {
|
|
455
499
|
const health = readBotHealth(deps.paths, now)
|
|
456
500
|
const state = readJson<SupervisorState>(statePath, { restartLog: [] })
|
|
501
|
+
const holdPath = deps.holdPath ?? defaultHoldPath()
|
|
502
|
+
const hold = readSupervisorHold(holdPath)
|
|
503
|
+
|
|
504
|
+
// manual-stop 持有标记:stop 是耐久停止,不是“停到下次巡检前”。健康巡检见 hold 且
|
|
505
|
+
// bot 未运行即让贤;bot 已在运行说明 hold 已陈旧(人工/外部已拉起),自动失效恢复监督。
|
|
506
|
+
if (hold && (!deps.request || deps.request === "health-check")) {
|
|
507
|
+
if (health.lockPid === null || health.pidAlive === false) {
|
|
508
|
+
log(`[supervisor] manual-stop hold 生效(${hold.reason}),跳过拉起`)
|
|
509
|
+
return { action: "yield", detail: `manual-stop hold 生效:${hold.reason}`, killedPid: null, spawnedPid: null }
|
|
510
|
+
}
|
|
511
|
+
if (clearSupervisorHold(holdPath)) {
|
|
512
|
+
log(`[supervisor] manual-stop hold 失效:bot 已在运行,恢复常规监督`)
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
// 人工重启是 hold 的显式解除入口:先清 hold 再走重启,避免“stop 后永远拉不起”。
|
|
516
|
+
if (deps.request === "manual-restart" && hold) {
|
|
517
|
+
if (clearSupervisorHold(holdPath)) log(`[supervisor] manual-stop hold 已解除(openqq restart)`)
|
|
518
|
+
}
|
|
519
|
+
|
|
457
520
|
let action = decideSupervise(health, state, now, policy)
|
|
458
521
|
|
|
522
|
+
// 人工请求停止(design §3.9.1 生命周期入口):停止是用户显式意图,必须可执行——
|
|
523
|
+
// 不被重启强度/冷却拦截(give-up 场景恰恰需要能停下来);bot 未运行/已死则只清锁不拉起。
|
|
524
|
+
if (deps.request === "manual-stop") {
|
|
525
|
+
action =
|
|
526
|
+
health.lockPid !== null && health.pidAlive !== false
|
|
527
|
+
? { kind: "grace-kill-spawn", killPid: health.lockPid, reason: "人工请求停止(openqq stop)" }
|
|
528
|
+
: { kind: "spawn", reason: "人工请求停止(bot 未运行,仅清锁)" }
|
|
529
|
+
}
|
|
530
|
+
|
|
459
531
|
// 人工请求重启(design §3.9.1 入口 3):健康实例也要优雅杀后拉起;
|
|
460
532
|
// bot 未运行/已死则只拉起。强度与冷却约束在 decideSupervise 内已经生效
|
|
461
533
|
//(needsRestart 为 false 时同样先查 give-up/cooldown,再走到这里覆盖动作)。
|
|
@@ -518,7 +590,7 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
|
|
|
518
590
|
// 若有心跳落盘必须被看见;随后重读一次,转新鲜即改判 ok、放弃本轮,全程审计留痕。
|
|
519
591
|
// 心跳「缺失」不豁免(语义同 decide:缺失视为未恢复,维持原判)。——
|
|
520
592
|
// 例外:manual-restart(人工意图即权威,不存在"误杀")。——
|
|
521
|
-
if (deps.request !== "manual-restart") {
|
|
593
|
+
if (deps.request !== "manual-restart" && deps.request !== "manual-stop") {
|
|
522
594
|
await sleep(300)
|
|
523
595
|
const recheck = readBotHealth(deps.paths, Date.now())
|
|
524
596
|
const recheckFresh =
|
|
@@ -582,6 +654,37 @@ export async function superviseOnce(deps: SuperviseDeps): Promise<SuperviseResul
|
|
|
582
654
|
} catch {
|
|
583
655
|
/* 清锁失败不阻断拉起 */
|
|
584
656
|
}
|
|
657
|
+
|
|
658
|
+
// 人工停止:与重启共用认领互斥/优雅杀/清锁/审计,但不拉起、不计重启强度账。
|
|
659
|
+
// bot 独立存活是故障隔离语义,不是脱离用户控制;stop 是显式生命周期终点。
|
|
660
|
+
if (deps.request === "manual-stop") {
|
|
661
|
+
writeSupervisorHold(holdPath, action.reason, "openqq stop")
|
|
662
|
+
const detail = killedPid
|
|
663
|
+
? `${action.reason};已优雅停 pid=${killedPid};锁已清;hold 已立(巡检不拉起)`
|
|
664
|
+
: `${action.reason};锁已清;hold 已立(巡检不拉起)`
|
|
665
|
+
if (killedPid !== null) {
|
|
666
|
+
appendKillLog({
|
|
667
|
+
kind: "decision",
|
|
668
|
+
reason: action.reason,
|
|
669
|
+
health: {
|
|
670
|
+
lockPid: health.lockPid,
|
|
671
|
+
pidAlive: health.pidAlive,
|
|
672
|
+
heartbeatAgeMs: health.heartbeatAgeMs,
|
|
673
|
+
lockAgeMs: health.lockAgeMs,
|
|
674
|
+
},
|
|
675
|
+
killedPid,
|
|
676
|
+
killEscalation: "TERM",
|
|
677
|
+
spawnedPid: null,
|
|
678
|
+
restartIntensity: `${state.restartLog.length}/${policy.maxRestarts}`,
|
|
679
|
+
livenessVerdict: "stopped",
|
|
680
|
+
at: Date.now(),
|
|
681
|
+
})
|
|
682
|
+
}
|
|
683
|
+
audit(`主动停:${detail}`)
|
|
684
|
+
log(`[supervisor] 主动停:${detail}`)
|
|
685
|
+
return { action: "stopped", detail, killedPid, spawnedPid: null }
|
|
686
|
+
}
|
|
687
|
+
|
|
585
688
|
const spawnedPid = deps.spawn()
|
|
586
689
|
state.restartLog.push(Date.now())
|
|
587
690
|
state.restartLog = state.restartLog.filter((t) => t > Date.now() - policy.windowMs * 2)
|
package/src/qq/media.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// @input: ./api (getAccessToken), ./types (MessageAttachment), node:fs/os/path
|
|
2
|
-
// @output: extForImageMime, isAllowedDownloadHost, MAX_IMAGE_BYTES,
|
|
3
|
-
//
|
|
4
|
-
// augmentPromptWithAttachments,
|
|
5
|
-
//
|
|
2
|
+
// @output: extForImageMime, isAllowedDownloadHost, MAX_IMAGE_BYTES, MAX_FILE_BYTES,
|
|
3
|
+
// imageDir, fileDir, classifyFileAttachment, downloadQQAttachment,
|
|
4
|
+
// prepareQQAttachments, groupOutcomes, augmentPromptWithAttachments,
|
|
5
|
+
// purgeOldQQImages, purgeOldQQFiles
|
|
6
|
+
// @pos: qq层 - QQ 图片/文件下载落盘 + prompt 文本/附件合成(原生附件接入 2026-10-14)
|
|
6
7
|
//
|
|
7
8
|
// QQ 图片消息到网关只有 URL(MessageAttachment.url);本模块下载落盘成文件,
|
|
8
9
|
// 再转成 prompt body 的 files({uri, name},v2 PromptInput schema 内字段)。
|
|
@@ -14,6 +15,7 @@ import { join } from "node:path"
|
|
|
14
15
|
import { tmpdir } from "node:os"
|
|
15
16
|
import type { MessageAttachment } from "./types.js"
|
|
16
17
|
import { sttConfigured, sttTranscribe } from "../core/stt.js"
|
|
18
|
+
import { extractOfficeTextFromFile, isLegacyOfficePath, officeKindForPath } from "../core/office-text.js"
|
|
17
19
|
|
|
18
20
|
export interface PromptFile {
|
|
19
21
|
uri: string
|
|
@@ -27,7 +29,7 @@ export interface PreparedAttachments {
|
|
|
27
29
|
|
|
28
30
|
/** 下载结果(纯数据,便于单测分组逻辑) */
|
|
29
31
|
export type AttachmentOutcome =
|
|
30
|
-
| { path: string; name: string }
|
|
32
|
+
| { path: string; name: string; kind?: "image" | "text" | "pdf" | "office-text"; sourceName?: string }
|
|
31
33
|
| { failed: string }
|
|
32
34
|
| { unsupported: string }
|
|
33
35
|
/** 语音消息:QQ 内置 ASR 免费给 asr_refer_text,零下载零 STT 调用直接转文字(生态观察缺口 2) */
|
|
@@ -41,6 +43,7 @@ export function extForImageMime(mime: string): string | null {
|
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
export const MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
|
46
|
+
export const MAX_FILE_BYTES = 20 * 1024 * 1024
|
|
44
47
|
const ALLOWED_HOST_SUFFIXES = [".qpic.cn", ".qq.com", ".qq.com.cn"]
|
|
45
48
|
|
|
46
49
|
/** 下载域白名单(R2-P1-2):只信 QQ 自家 CDN 且必须 https——在 fetch 之前
|
|
@@ -61,6 +64,10 @@ export function imageDir(): string {
|
|
|
61
64
|
return join(tmpdir(), "opencode", "qq-images")
|
|
62
65
|
}
|
|
63
66
|
|
|
67
|
+
export function fileDir(): string {
|
|
68
|
+
return join(tmpdir(), "opencode", "qq-files")
|
|
69
|
+
}
|
|
70
|
+
|
|
64
71
|
async function fetchWithTimeout(url: string, ms: number, auth?: string): Promise<Response> {
|
|
65
72
|
const ctrl = new AbortController()
|
|
66
73
|
const timer = setTimeout(() => ctrl.abort(), ms)
|
|
@@ -74,8 +81,80 @@ async function fetchWithTimeout(url: string, ms: number, auth?: string): Promise
|
|
|
74
81
|
}
|
|
75
82
|
}
|
|
76
83
|
|
|
84
|
+
export type IncomingFileKind = "text" | "pdf" | "office"
|
|
85
|
+
|
|
86
|
+
const TEXT_FILE_EXTENSIONS = new Set([
|
|
87
|
+
"txt", "md", "markdown", "json", "jsonc", "log", "csv", "tsv", "xml", "yaml", "yml",
|
|
88
|
+
"toml", "ini", "cfg", "conf", "js", "mjs", "cjs", "ts", "tsx", "jsx", "py", "java",
|
|
89
|
+
"go", "rs", "c", "h", "cpp", "hpp", "cs", "sql", "sh", "ps1", "bat", "cmd", "html",
|
|
90
|
+
"htm", "css", "scss", "less", "vue", "svelte",
|
|
91
|
+
])
|
|
92
|
+
|
|
93
|
+
/** QQ file 附件分类:按官方 content_type=file 为入口,文件名扩展名决定可处理形态。 */
|
|
94
|
+
export function classifyFileAttachment(att: MessageAttachment): IncomingFileKind | null {
|
|
95
|
+
const filename = (att.filename || "").toLowerCase()
|
|
96
|
+
const contentType = (att.content_type || "").toLowerCase().split(";")[0].trim()
|
|
97
|
+
if (isLegacyOfficePath(filename)) return null // 由调用方给出专门的 legacy 指引
|
|
98
|
+
if (officeKindForPath(filename)) return "office"
|
|
99
|
+
if (filename.endsWith(".pdf") || contentType === "application/pdf") return "pdf"
|
|
100
|
+
const ext = filename.match(/\.([a-z0-9]+)$/)?.[1] ?? ""
|
|
101
|
+
if (contentType.startsWith("text/") || TEXT_FILE_EXTENSIONS.has(ext)) return "text"
|
|
102
|
+
return null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function safeAttachmentName(name: string): string {
|
|
106
|
+
const cleaned = name.replace(/[\\/:*?"<>|\x00-\x1f]/g, "_").trim() || "attachment"
|
|
107
|
+
if (cleaned.length <= 80) return cleaned
|
|
108
|
+
const ext = cleaned.match(/\.[a-z0-9]+$/i)?.[0] ?? ""
|
|
109
|
+
return `${cleaned.slice(0, Math.max(1, 80 - ext.length))}${ext}`
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function downloadToBuffer(
|
|
113
|
+
att: MessageAttachment,
|
|
114
|
+
getAuth: (() => Promise<string>) | undefined,
|
|
115
|
+
maxBytes: number,
|
|
116
|
+
tooLargeMessage: string,
|
|
117
|
+
): Promise<{ data: Buffer } | { failed: string }> {
|
|
118
|
+
if (!isAllowedDownloadHost(att.url)) return { failed: "下载域不在白名单" }
|
|
119
|
+
try {
|
|
120
|
+
let res = await fetchWithTimeout(att.url, 15000)
|
|
121
|
+
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
122
|
+
try {
|
|
123
|
+
res = await fetchWithTimeout(att.url, 15000, await getAuth())
|
|
124
|
+
} catch {
|
|
125
|
+
/* 鉴权兜底失败:保持原状态,走下方 !res.ok 归 failed */
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (!res.ok) {
|
|
129
|
+
console.log("[media] 下载失败:", res.status, att.url) // 原始 URL 只进本机日志(B7 校准)
|
|
130
|
+
return { failed: `HTTP ${res.status}` }
|
|
131
|
+
}
|
|
132
|
+
const len = Number(res.headers.get("content-length") || 0)
|
|
133
|
+
if (len > maxBytes) return { failed: tooLargeMessage }
|
|
134
|
+
const reader = res.body?.getReader()
|
|
135
|
+
if (!reader) return { failed: "无响应体" }
|
|
136
|
+
const chunks: Uint8Array[] = []
|
|
137
|
+
let total = 0
|
|
138
|
+
for (;;) {
|
|
139
|
+
const { done, value } = await reader.read()
|
|
140
|
+
if (done) break
|
|
141
|
+
total += value.byteLength
|
|
142
|
+
if (total > maxBytes) {
|
|
143
|
+
await reader.cancel()
|
|
144
|
+
return { failed: tooLargeMessage }
|
|
145
|
+
}
|
|
146
|
+
chunks.push(value)
|
|
147
|
+
}
|
|
148
|
+
if (total === 0) return { failed: "空响应" }
|
|
149
|
+
return { data: Buffer.concat(chunks) }
|
|
150
|
+
} catch (e) {
|
|
151
|
+
console.log("[media] 下载失败:", att.url, e instanceof Error ? e.message : e)
|
|
152
|
+
return { failed: "网络错误或超时" }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
77
156
|
/**
|
|
78
|
-
* 下载 QQ
|
|
157
|
+
* 下载 QQ 图片/文件附件到本地。非支持类型返回 unsupported;下载失败返回 failed
|
|
79
158
|
* (脱敏短语,原始 URL/错误只进本机日志)。fetch 前过域白名单(R2-P1-2);
|
|
80
159
|
* 401/403 时带 access_token 重试一次(此时目标必为 QQ 自家域,token 不出站);
|
|
81
160
|
* 10MB 流式上限,超限 cancel 熔断。
|
|
@@ -113,52 +192,48 @@ export async function downloadQQAttachment(
|
|
|
113
192
|
return { failed: "语音转写失败(外部 STT 未响应或识别为空)" }
|
|
114
193
|
}
|
|
115
194
|
}
|
|
195
|
+
const fileKind = classifyFileAttachment(att)
|
|
196
|
+
if (fileKind) {
|
|
197
|
+
const downloaded = await downloadToBuffer(att, getAuth, MAX_FILE_BYTES, "超过20MB")
|
|
198
|
+
if ("failed" in downloaded) return downloaded
|
|
199
|
+
const dir = fileDir()
|
|
200
|
+
mkdirSync(dir, { recursive: true })
|
|
201
|
+
const safeName = safeAttachmentName(att.filename || `attachment-${Date.now()}`)
|
|
202
|
+
const storedName = `qq-file-${Date.now()}-${Math.random().toString(36).slice(2, 8)}-${safeName}`
|
|
203
|
+
const storedPath = join(dir, storedName)
|
|
204
|
+
try {
|
|
205
|
+
writeFileSync(storedPath, downloaded.data)
|
|
206
|
+
if (fileKind === "text") return { path: storedPath, name: safeName, kind: "text" }
|
|
207
|
+
if (fileKind === "pdf") return { path: storedPath, name: safeName, kind: "pdf" }
|
|
208
|
+
const extracted = extractOfficeTextFromFile(storedPath)
|
|
209
|
+
const textPath = `${storedPath}.extracted.txt`
|
|
210
|
+
writeFileSync(textPath, extracted, "utf8")
|
|
211
|
+
return { path: textPath, name: `${safeName}.txt`, kind: "office-text", sourceName: safeName }
|
|
212
|
+
} catch (error) {
|
|
213
|
+
console.log("[media] 文件处理失败:", safeName, error instanceof Error ? error.message : error)
|
|
214
|
+
return { failed: fileKind === "office" ? "Office 文档解析失败" : "文件处理失败" }
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
116
218
|
const ext = extForImageMime(att.content_type || "")
|
|
117
|
-
if (!ext)
|
|
118
|
-
|
|
219
|
+
if (!ext) {
|
|
220
|
+
if (isLegacyOfficePath(att.filename || "")) {
|
|
221
|
+
return { unsupported: "旧版 Office 二进制(请另存为 docx/xlsx/pptx 或导出文本/PDF)" }
|
|
222
|
+
}
|
|
223
|
+
return { unsupported: att.content_type || att.filename || "未知类型" }
|
|
224
|
+
}
|
|
225
|
+
const downloaded = await downloadToBuffer(att, getAuth, MAX_IMAGE_BYTES, "超过10MB")
|
|
226
|
+
if ("failed" in downloaded) return downloaded
|
|
119
227
|
try {
|
|
120
228
|
const dir = imageDir()
|
|
121
229
|
mkdirSync(dir, { recursive: true })
|
|
122
230
|
const name = `qq-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`
|
|
123
|
-
let res = await fetchWithTimeout(att.url, 15000)
|
|
124
|
-
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
125
|
-
try {
|
|
126
|
-
const tok = await getAuth()
|
|
127
|
-
res = await fetchWithTimeout(att.url, 15000, tok)
|
|
128
|
-
} catch {
|
|
129
|
-
/* 鉴权兜底失败:保持原状态,走下方 !res.ok 归 failed */
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
if (!res.ok) {
|
|
133
|
-
console.log("[media] 下载失败:", res.status, att.url) // 原始 URL 只进本机日志(B7 校准)
|
|
134
|
-
return { failed: `HTTP ${res.status}` }
|
|
135
|
-
}
|
|
136
|
-
// R2-P1-2:10MB 上限——Content-Length 预检 + 流式逐块计数熔断
|
|
137
|
-
//(无 Content-Length 的分块响应同样有界;超限即 cancel,内存不涨)
|
|
138
|
-
const len = Number(res.headers.get("content-length") || 0)
|
|
139
|
-
if (len > MAX_IMAGE_BYTES) return { failed: "超过10MB" }
|
|
140
|
-
const reader = res.body?.getReader()
|
|
141
|
-
if (!reader) return { failed: "无响应体" }
|
|
142
|
-
const chunks: Uint8Array[] = []
|
|
143
|
-
let total = 0
|
|
144
|
-
for (;;) {
|
|
145
|
-
const { done, value } = await reader.read()
|
|
146
|
-
if (done) break
|
|
147
|
-
total += value.byteLength
|
|
148
|
-
if (total > MAX_IMAGE_BYTES) {
|
|
149
|
-
await reader.cancel()
|
|
150
|
-
return { failed: "超过10MB" }
|
|
151
|
-
}
|
|
152
|
-
chunks.push(value)
|
|
153
|
-
}
|
|
154
|
-
if (total === 0) return { failed: "空响应" }
|
|
155
231
|
const full = join(dir, name)
|
|
156
|
-
writeFileSync(full,
|
|
157
|
-
return { path: full, name }
|
|
232
|
+
writeFileSync(full, downloaded.data)
|
|
233
|
+
return { path: full, name, kind: "image" }
|
|
158
234
|
} catch (e) {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
return { failed: "网络错误或超时" }
|
|
235
|
+
console.log("[media] 图片落盘失败:", e instanceof Error ? e.message : e)
|
|
236
|
+
return { failed: "文件落盘失败" }
|
|
162
237
|
}
|
|
163
238
|
}
|
|
164
239
|
|
|
@@ -179,14 +254,21 @@ export function groupOutcomes(outcomes: AttachmentOutcome[]): PreparedAttachment
|
|
|
179
254
|
const notes: string[] = []
|
|
180
255
|
for (const o of outcomes) {
|
|
181
256
|
if ("path" in o) {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
257
|
+
const kind = o.kind ?? "image"
|
|
258
|
+
if (kind === "image") {
|
|
259
|
+
// 桌面 TUI 预览实证通道:≤2MB 的图片用 data: URL(opencode 对 data: 内嵌预览友好);
|
|
260
|
+
// 大图保留 file:// 路径(避免 base64 膨胀)。
|
|
261
|
+
const dataUrl = tryImageDataUrl(o.path, 2 * 1024 * 1024)
|
|
262
|
+
files.push(dataUrl ? { uri: dataUrl, name: o.name } : { uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name })
|
|
263
|
+
} else {
|
|
264
|
+
files.push({ uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name })
|
|
265
|
+
if (kind === "pdf") notes.push(`(PDF 附件已注入:${o.name};需要模型支持 PDF 输入)`)
|
|
266
|
+
if (kind === "office-text") notes.push(`(Office 文档已提取为文本:${o.sourceName ?? o.name})`)
|
|
267
|
+
}
|
|
186
268
|
} else if ("voice" in o) {
|
|
187
269
|
notes.push(`(语音转写:${o.voice})`)
|
|
188
270
|
} else if ("failed" in o) {
|
|
189
|
-
notes.push(
|
|
271
|
+
notes.push(`(附件下载失败:${o.failed})`)
|
|
190
272
|
} else {
|
|
191
273
|
notes.push(`(暂不支持的附件类型:${o.unsupported})`)
|
|
192
274
|
}
|
|
@@ -212,6 +294,11 @@ function tryImageDataUrl(path: string, maxBytes: number): string | null {
|
|
|
212
294
|
* - 纯图(无文字):占位文字,模型经 files 直接看到图
|
|
213
295
|
* - 纯失败(图没下下来):备注即正文,QQ 端可见而不是静默
|
|
214
296
|
*/
|
|
297
|
+
function isImagePromptFile(file: PromptFile): boolean {
|
|
298
|
+
if (file.uri.startsWith("data:image/")) return true
|
|
299
|
+
return /\.(png|jpe?g|gif|webp|bmp)$/i.test(file.name ?? "")
|
|
300
|
+
}
|
|
301
|
+
|
|
215
302
|
export function augmentPromptWithAttachments(
|
|
216
303
|
rawContent: string,
|
|
217
304
|
prepared: PreparedAttachments,
|
|
@@ -219,16 +306,18 @@ export function augmentPromptWithAttachments(
|
|
|
219
306
|
const base = rawContent.trim()
|
|
220
307
|
const { files, notes } = prepared
|
|
221
308
|
let text = base
|
|
222
|
-
if (!text && files.length > 0)
|
|
309
|
+
if (!text && files.length > 0) {
|
|
310
|
+
text = files.some(isImagePromptFile)
|
|
311
|
+
? "(用户通过 QQ 发来了图片,未附文字)"
|
|
312
|
+
: "(用户通过 QQ 发来了文件,未附文字)"
|
|
313
|
+
}
|
|
223
314
|
if (!text && notes.length > 0) text = "(用户通过 QQ 发来了内容,但无法处理)"
|
|
224
315
|
if (notes.length > 0) text = text ? `${text}\n\n${notes.join("\n")}` : notes.join("\n")
|
|
225
316
|
return { text, files }
|
|
226
317
|
}
|
|
227
318
|
|
|
228
|
-
|
|
229
|
-
export function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
|
|
319
|
+
function purgeOldFilesIn(dir: string, maxAgeMs: number): void {
|
|
230
320
|
try {
|
|
231
|
-
const dir = imageDir()
|
|
232
321
|
const now = Date.now()
|
|
233
322
|
for (const f of readdirSync(dir)) {
|
|
234
323
|
const full = join(dir, f)
|
|
@@ -242,3 +331,13 @@ export function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
|
|
|
242
331
|
/* 目录不存在等忽略 */
|
|
243
332
|
}
|
|
244
333
|
}
|
|
334
|
+
|
|
335
|
+
/** 启动清理:删掉 7 天前的落盘图片(只在自己的子目录内操作) */
|
|
336
|
+
export function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
|
|
337
|
+
purgeOldFilesIn(imageDir(), maxAgeMs)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** 启动清理:删掉 7 天前的落盘文件附件与 Office 提取文本。 */
|
|
341
|
+
export function purgeOldQQFiles(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
|
|
342
|
+
purgeOldFilesIn(fileDir(), maxAgeMs)
|
|
343
|
+
}
|