@chen_hu_hu/pi-qq 1.7.0 → 1.7.2
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 +34 -1
- package/README-zh.md +9 -7
- package/README.md +9 -7
- package/doc/archive/delivery.1.7.1.md +215 -0
- package/doc/archive/delivery.1.7.2.md +163 -0
- package/doc/todo.md +23 -196
- package/index.ts +28 -20
- package/package.json +1 -1
- package/src/infra/file-logger.ts +80 -29
- package/src/infra/i18n.ts +4 -4
- package/src/infra/log-message-keys.ts +1 -0
- package/src/infra/power-status.ts +51 -28
- package/src/infra/short-id.ts +15 -0
- package/src/qq/inbound-command.ts +17 -7
- package/src/qq/qq-bot.ts +3 -9
- package/src/qq/qq-message-handler.ts +6 -18
- package/src/qq/qr-login.ts +1 -1
- package/src/qq/reply-sender.ts +2 -2
- package/src/quota/reply-quota-report.ts +2 -1
- package/src/relay/bubble-writer.ts +67 -19
- package/src/relay/run-stream-relay.ts +80 -41
- package/src/relay/run-timeline.ts +1 -1
- package/src/relay/stream-session.ts +81 -28
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
2
|
import { readFileSync, readdirSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
+
import { log } from "./file-logger";
|
|
4
5
|
|
|
5
6
|
export interface PowerStatus {
|
|
6
7
|
percent?: number;
|
|
@@ -8,6 +9,10 @@ export interface PowerStatus {
|
|
|
8
9
|
}
|
|
9
10
|
|
|
10
11
|
const CACHE_MS = 30_000;
|
|
12
|
+
const MACOS_TIMEOUT_MS = 500;
|
|
13
|
+
// PowerShell cold start plus the CIM query takes about 0.7 s on a warm cache
|
|
14
|
+
// and longer on a cold one; 500 ms killed the process before it could answer.
|
|
15
|
+
const WINDOWS_TIMEOUT_MS = 3000;
|
|
11
16
|
let cache: { at: number; value: PowerStatus | undefined } | undefined;
|
|
12
17
|
|
|
13
18
|
function clampPercent(value: number): number | undefined {
|
|
@@ -67,38 +72,56 @@ export function readLinuxBattery(root = "/sys/class/power_supply"): PowerStatus
|
|
|
67
72
|
return undefined;
|
|
68
73
|
}
|
|
69
74
|
|
|
70
|
-
function
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
return
|
|
75
|
+
function run(file: string, args: string[], timeoutMs: number): Promise<string> {
|
|
76
|
+
return new Promise((resolve, reject) => {
|
|
77
|
+
execFile(file, args, { encoding: "utf8", timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
|
|
78
|
+
if (err) reject(err);
|
|
79
|
+
else resolve(stdout);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function readPowerStatus(): Promise<PowerStatus | undefined> {
|
|
85
|
+
if (process.platform === "linux") return readLinuxBattery();
|
|
86
|
+
if (process.platform === "darwin") {
|
|
87
|
+
return parsePmsetOutput(await run("pmset", ["-g", "batt"], MACOS_TIMEOUT_MS));
|
|
88
|
+
}
|
|
89
|
+
if (process.platform === "win32") {
|
|
90
|
+
const output = await run(
|
|
91
|
+
"powershell",
|
|
92
|
+
[
|
|
93
|
+
"-NoProfile",
|
|
94
|
+
"-Command",
|
|
95
|
+
"Get-CimInstance Win32_Battery | Select-Object -First 1 EstimatedChargeRemaining,BatteryStatus | ConvertTo-Json -Compress",
|
|
96
|
+
],
|
|
97
|
+
WINDOWS_TIMEOUT_MS,
|
|
98
|
+
);
|
|
99
|
+
return parseWindowsBattery(output);
|
|
95
100
|
}
|
|
96
101
|
return undefined;
|
|
97
102
|
}
|
|
98
103
|
|
|
99
|
-
export function
|
|
104
|
+
export function resetPowerStatusCache(): void {
|
|
105
|
+
cache = undefined;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function getPowerStatus(
|
|
109
|
+
now = Date.now(),
|
|
110
|
+
read: () => Promise<PowerStatus | undefined> = readPowerStatus,
|
|
111
|
+
): Promise<PowerStatus | undefined> {
|
|
100
112
|
if (cache && now - cache.at < CACHE_MS) return cache.value;
|
|
101
|
-
|
|
113
|
+
let value: PowerStatus | undefined;
|
|
114
|
+
try {
|
|
115
|
+
value = await read();
|
|
116
|
+
} catch (err) {
|
|
117
|
+
const e = err as { code?: string | number; killed?: boolean; signal?: string };
|
|
118
|
+
log.debug("power", "power status read failed", {
|
|
119
|
+
platform: process.platform,
|
|
120
|
+
code: e?.code ?? null,
|
|
121
|
+
killed: e?.killed ?? null,
|
|
122
|
+
signal: e?.signal ?? null,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
102
125
|
cache = { at: now, value };
|
|
103
126
|
return value;
|
|
104
127
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
const SHORT_ID_LENGTH = 8;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Derive a stable, non-reversible short identifier for logs.
|
|
7
|
+
*
|
|
8
|
+
* QQ message IDs share a long constant head and tail, and only the middle
|
|
9
|
+
* varies. Slicing either edge therefore maps different messages to the same
|
|
10
|
+
* short ID; hashing keeps them distinguishable and hides the raw identifier.
|
|
11
|
+
*/
|
|
12
|
+
export function shortId(id: string | null | undefined): string {
|
|
13
|
+
if (!id) return "?";
|
|
14
|
+
return createHash("sha256").update(id).digest("hex").slice(0, SHORT_ID_LENGTH);
|
|
15
|
+
}
|
|
@@ -15,7 +15,7 @@ export type InboundPi = Pick<ExtensionAPI, "sendUserMessage">;
|
|
|
15
15
|
export interface InboundCommandDeps {
|
|
16
16
|
pi: InboundPi;
|
|
17
17
|
ctx: InboundContext;
|
|
18
|
-
getStatusLines: () => string[]
|
|
18
|
+
getStatusLines: () => string[] | Promise<string[]>;
|
|
19
19
|
getLastMessage?: () => string | undefined;
|
|
20
20
|
onStop?: () => void;
|
|
21
21
|
waitForEnd?: () => Promise<void>;
|
|
@@ -60,12 +60,22 @@ export async function handleInboundCommand(
|
|
|
60
60
|
deps.ctx.abort();
|
|
61
61
|
const waitStartedAt = Date.now();
|
|
62
62
|
log.debug("inbound", "stream timing", { phase: "/stop wait start" });
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
63
|
+
const waiting = Promise.resolve()
|
|
64
|
+
.then(() => deps.waitForEnd?.())
|
|
65
|
+
.then(() => {
|
|
66
|
+
log.debug("inbound", "stream timing", {
|
|
67
|
+
phase: "/stop wait done",
|
|
68
|
+
waitedMs: Date.now() - waitStartedAt,
|
|
69
|
+
});
|
|
70
|
+
})
|
|
71
|
+
.catch((err) => {
|
|
72
|
+
log.warn("inbound", "/stop wait failed", {
|
|
73
|
+
waitedMs: Date.now() - waitStartedAt,
|
|
74
|
+
err,
|
|
75
|
+
});
|
|
76
|
+
});
|
|
68
77
|
await reply(t("commands.stop.abort"));
|
|
78
|
+
void waiting;
|
|
69
79
|
}
|
|
70
80
|
break;
|
|
71
81
|
case "/compact":
|
|
@@ -77,7 +87,7 @@ export async function handleInboundCommand(
|
|
|
77
87
|
}
|
|
78
88
|
break;
|
|
79
89
|
case "/status":
|
|
80
|
-
await reply(deps.getStatusLines().join("\n"));
|
|
90
|
+
await reply((await deps.getStatusLines()).join("\n"));
|
|
81
91
|
break;
|
|
82
92
|
case "/last": {
|
|
83
93
|
if (!deps.ctx.isIdle()) {
|
package/src/qq/qq-bot.ts
CHANGED
|
@@ -65,18 +65,12 @@ export function startBot(opts: StartBotOptions): RunningBot {
|
|
|
65
65
|
rawEventType: msg.rawEventType,
|
|
66
66
|
messageId: msg.messageId,
|
|
67
67
|
senderId: msg.senderId,
|
|
68
|
-
senderName: msg.senderName,
|
|
69
68
|
senderIsBot: msg.senderIsBot,
|
|
70
|
-
content: msg.content,
|
|
71
69
|
msgType: msg.msgType,
|
|
72
70
|
timestamp: msg.timestamp,
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
messageScene: msg.messageScene,
|
|
77
|
-
attachments: msg.attachments,
|
|
78
|
-
msgElements: msg.msgElements,
|
|
79
|
-
raw: msg.raw,
|
|
71
|
+
contentLength: (msg.content ?? "").length,
|
|
72
|
+
attachmentCount: (msg.attachments ?? []).length,
|
|
73
|
+
elementCount: (msg.msgElements ?? []).length,
|
|
80
74
|
});
|
|
81
75
|
try {
|
|
82
76
|
await opts.onMessage?.(bot, msg);
|
|
@@ -31,24 +31,6 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
31
31
|
const pending = new PendingAttachments();
|
|
32
32
|
|
|
33
33
|
return async (bot: QQBot, msg: QQBotInboundMessage): Promise<void> => {
|
|
34
|
-
log.debug("inbound", "message received", {
|
|
35
|
-
kind: msg.kind,
|
|
36
|
-
rawEventType: msg.rawEventType,
|
|
37
|
-
messageId: msg.messageId,
|
|
38
|
-
senderId: msg.senderId,
|
|
39
|
-
senderName: msg.senderName,
|
|
40
|
-
senderIsBot: msg.senderIsBot,
|
|
41
|
-
content: msg.content,
|
|
42
|
-
msgType: msg.msgType,
|
|
43
|
-
timestamp: msg.timestamp,
|
|
44
|
-
msgIdx: msg.msgIdx,
|
|
45
|
-
refMsgIdx: msg.refMsgIdx,
|
|
46
|
-
messageScene: msg.messageScene,
|
|
47
|
-
attachments: msg.attachments,
|
|
48
|
-
msgElements: msg.msgElements,
|
|
49
|
-
raw: msg.raw,
|
|
50
|
-
});
|
|
51
|
-
|
|
52
34
|
if (msg.kind !== "c2c") {
|
|
53
35
|
log.debug("inbound", "skipped non-c2c message", { kind: msg.kind });
|
|
54
36
|
return;
|
|
@@ -63,10 +45,16 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
63
45
|
deps.reloadSettings();
|
|
64
46
|
deps.budget.observeInbound(msg.senderId, msg.messageId);
|
|
65
47
|
log.info("inbound", "message received", {
|
|
48
|
+
kind: msg.kind,
|
|
49
|
+
rawEventType: msg.rawEventType,
|
|
66
50
|
messageId: msg.messageId,
|
|
67
51
|
senderId: msg.senderId,
|
|
52
|
+
senderIsBot: msg.senderIsBot,
|
|
53
|
+
msgType: msg.msgType,
|
|
54
|
+
timestamp: msg.timestamp,
|
|
68
55
|
contentLength: (msg.content ?? "").length,
|
|
69
56
|
attachmentCount: (msg.attachments ?? []).length,
|
|
57
|
+
elementCount: (msg.msgElements ?? []).length,
|
|
70
58
|
});
|
|
71
59
|
|
|
72
60
|
const channel: ReplyChannel = {
|
package/src/qq/qr-login.ts
CHANGED
|
@@ -47,7 +47,7 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
|
|
|
47
47
|
causeCode: cause && typeof cause === "object" ? (cause as NodeJS.ErrnoException).code : undefined,
|
|
48
48
|
causeMessage: cause instanceof Error ? cause.message : undefined,
|
|
49
49
|
});
|
|
50
|
-
ctx.ui.notify(t("login.failed")
|
|
50
|
+
ctx.ui.notify(`${t("login.failed")}: ${err.message}`, "error");
|
|
51
51
|
finish();
|
|
52
52
|
closeOverlay?.();
|
|
53
53
|
},
|
package/src/qq/reply-sender.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { ReplyBudget } from "../quota/reply-quota";
|
|
|
3
3
|
import { AppendStream } from "../relay/stream-session";
|
|
4
4
|
import { sendWithMsgSeq } from "./msg-seq-send";
|
|
5
5
|
import { log } from "../infra/file-logger";
|
|
6
|
+
import { shortId } from "../infra/short-id";
|
|
6
7
|
import { t } from "../infra/i18n";
|
|
7
8
|
|
|
8
9
|
export const TEXT_CHUNK_LIMIT = 4500;
|
|
@@ -96,7 +97,7 @@ export async function sendStreamReply(
|
|
|
96
97
|
): Promise<void> {
|
|
97
98
|
log.debug("stream", "stream timing", {
|
|
98
99
|
phase: "last reply stream",
|
|
99
|
-
msgId: target.msgId
|
|
100
|
+
msgId: shortId(target.msgId),
|
|
100
101
|
textLength: text.length,
|
|
101
102
|
});
|
|
102
103
|
const stream = new AppendStream(bot.messageApi, bot.getCredentials(), target.openid, target.msgId);
|
|
@@ -121,7 +122,6 @@ export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Pro
|
|
|
121
122
|
targetId,
|
|
122
123
|
msgId: msgId ?? null,
|
|
123
124
|
length: chunk.length,
|
|
124
|
-
text: chunk,
|
|
125
125
|
});
|
|
126
126
|
await sendWithMsgSeq(bot, { target: replyTarget, content: chunk });
|
|
127
127
|
if (mode === "passive" && msgId) ch.budget.commitPassive(msgId);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { t } from "../infra/i18n";
|
|
2
|
+
import { shortId } from "../infra/short-id";
|
|
2
3
|
import type { BudgetSnapshot } from "./reply-quota";
|
|
3
4
|
|
|
4
5
|
interface BudgetTarget {
|
|
@@ -22,7 +23,7 @@ export function formatBudgetStatus(
|
|
|
22
23
|
const lastLine = last
|
|
23
24
|
? t("diagnostics.budget.lastInbound", {
|
|
24
25
|
openid: mask(last.openid),
|
|
25
|
-
msgId:
|
|
26
|
+
msgId: shortId(last.msgId),
|
|
26
27
|
age: ageSec ?? 0,
|
|
27
28
|
})
|
|
28
29
|
: t("diagnostics.budget.lastInboundNone");
|
|
@@ -10,8 +10,10 @@ import {
|
|
|
10
10
|
thinkingHeader,
|
|
11
11
|
} from "./stream-block-format";
|
|
12
12
|
import { t } from "../infra/i18n";
|
|
13
|
+
import { shortId } from "../infra/short-id";
|
|
13
14
|
|
|
14
15
|
type BlockKind = "none" | "thinking" | "tool" | "text";
|
|
16
|
+
type RotateReason = "restart" | "thinking" | "text" | "tool" | "skill" | "split";
|
|
15
17
|
|
|
16
18
|
const MAX_RESUME_ATTEMPTS = 2;
|
|
17
19
|
const MAX_BUBBLE_CHARS = 12_000;
|
|
@@ -26,6 +28,15 @@ function isDuplicateMsgSeqError(err: unknown): boolean {
|
|
|
26
28
|
);
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
function errorCode(err: unknown): number | undefined {
|
|
32
|
+
const e = err as { code?: number; err_code?: number; bizCode?: number };
|
|
33
|
+
return e?.code ?? e?.err_code ?? e?.bizCode;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function isExpiredStreamError(err: unknown): boolean {
|
|
37
|
+
return errorCode(err) === 40034020 || /40034020|超过时间限制|time limit/i.test(String((err as Error)?.message ?? ""));
|
|
38
|
+
}
|
|
39
|
+
|
|
29
40
|
export interface RepushTool {
|
|
30
41
|
name: string;
|
|
31
42
|
args?: unknown;
|
|
@@ -63,6 +74,8 @@ export class BubbleWriter {
|
|
|
63
74
|
private toolOpen = false;
|
|
64
75
|
private queue: Promise<void> = Promise.resolve();
|
|
65
76
|
private disposed = false;
|
|
77
|
+
private terminalCode?: number;
|
|
78
|
+
private lastErrorCode?: number;
|
|
66
79
|
|
|
67
80
|
constructor(private readonly deps: BubbleWriterDeps) {}
|
|
68
81
|
|
|
@@ -74,6 +87,14 @@ export class BubbleWriter {
|
|
|
74
87
|
return this.streamDead;
|
|
75
88
|
}
|
|
76
89
|
|
|
90
|
+
get deadCode(): number | undefined {
|
|
91
|
+
return this.terminalCode;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
get hasActiveStream(): boolean {
|
|
95
|
+
return Boolean(this.cur) && !this.streamDead && !this.disposed;
|
|
96
|
+
}
|
|
97
|
+
|
|
77
98
|
stats(now = Date.now()): {
|
|
78
99
|
dead: boolean;
|
|
79
100
|
disposed: boolean;
|
|
@@ -109,14 +130,19 @@ export class BubbleWriter {
|
|
|
109
130
|
const newBubble = this.startsNewBlock("thinking");
|
|
110
131
|
const prefix = this.beginBlock("thinking", newBubble);
|
|
111
132
|
this.thinkingAtLineStart = delta.endsWith("\n");
|
|
112
|
-
this.push(`${prefix}${delta}`, {
|
|
133
|
+
this.push(`${prefix}${delta}`, {
|
|
134
|
+
blockBoundary: prefix.length > 0 || newBubble,
|
|
135
|
+
newBubble,
|
|
136
|
+
reason: "thinking",
|
|
137
|
+
thinking: true,
|
|
138
|
+
});
|
|
113
139
|
}
|
|
114
140
|
|
|
115
141
|
pushText(text: string): void {
|
|
116
142
|
if (this.streamDead || this.disposed) return;
|
|
117
143
|
const newBubble = this.startsNewBlock("text");
|
|
118
144
|
const prefix = this.beginBlock("text", newBubble);
|
|
119
|
-
this.push(`${prefix}${text}`, { blockBoundary: prefix.length > 0 || newBubble, newBubble });
|
|
145
|
+
this.push(`${prefix}${text}`, { blockBoundary: prefix.length > 0 || newBubble, newBubble, reason: "text" });
|
|
120
146
|
}
|
|
121
147
|
|
|
122
148
|
pushTool(name: string, args: unknown): void {
|
|
@@ -137,6 +163,7 @@ export class BubbleWriter {
|
|
|
137
163
|
this.push(`${prefix}${formatToolLine(name, args)}\n\n`, {
|
|
138
164
|
blockBoundary: prefix.length > 0 || newBubble,
|
|
139
165
|
newBubble,
|
|
166
|
+
reason: "tool",
|
|
140
167
|
trace: "tool",
|
|
141
168
|
});
|
|
142
169
|
}
|
|
@@ -149,6 +176,7 @@ export class BubbleWriter {
|
|
|
149
176
|
this.push(`${prefix}${formatSkillBlock(name)}`, {
|
|
150
177
|
blockBoundary: prefix.length > 0 || newBubble,
|
|
151
178
|
newBubble,
|
|
179
|
+
reason: "skill",
|
|
152
180
|
trace: "skill",
|
|
153
181
|
});
|
|
154
182
|
}
|
|
@@ -168,7 +196,7 @@ export class BubbleWriter {
|
|
|
168
196
|
void this.enqueue(async () => {
|
|
169
197
|
if (this.disposed) return;
|
|
170
198
|
if (this.fenceOpen) await this.closeOpenFence();
|
|
171
|
-
if (this.cur) await this.rotateStream();
|
|
199
|
+
if (this.cur) await this.rotateStream("restart");
|
|
172
200
|
|
|
173
201
|
if (target) {
|
|
174
202
|
this.deps.openid = target.openid;
|
|
@@ -202,6 +230,8 @@ export class BubbleWriter {
|
|
|
202
230
|
this.streamDead = false;
|
|
203
231
|
this.pendingResume = undefined;
|
|
204
232
|
this.resumeAttempts = 0;
|
|
233
|
+
this.terminalCode = undefined;
|
|
234
|
+
this.lastErrorCode = undefined;
|
|
205
235
|
this.lastKind = "none";
|
|
206
236
|
this.blockClosed = false;
|
|
207
237
|
this.toolOpen = false;
|
|
@@ -225,13 +255,14 @@ export class BubbleWriter {
|
|
|
225
255
|
await this.queue;
|
|
226
256
|
if (this.streamDead) return false;
|
|
227
257
|
if (this.cur !== stream) continue;
|
|
258
|
+
this.lastErrorCode = undefined;
|
|
228
259
|
return true;
|
|
229
260
|
} catch (err) {
|
|
230
261
|
this.handleStreamError(err as Error);
|
|
231
262
|
if (this.streamDead) return false;
|
|
232
263
|
}
|
|
233
264
|
}
|
|
234
|
-
this.killStream("resume attempts exhausted");
|
|
265
|
+
this.killStream("resume attempts exhausted", this.lastErrorCode);
|
|
235
266
|
return false;
|
|
236
267
|
}
|
|
237
268
|
|
|
@@ -251,7 +282,7 @@ export class BubbleWriter {
|
|
|
251
282
|
}
|
|
252
283
|
|
|
253
284
|
private logMsgId(): string {
|
|
254
|
-
return this.deps.msgId
|
|
285
|
+
return shortId(this.deps.msgId);
|
|
255
286
|
}
|
|
256
287
|
|
|
257
288
|
private beginBlock(kind: BlockKind, newBubble = false): string {
|
|
@@ -303,11 +334,12 @@ export class BubbleWriter {
|
|
|
303
334
|
blockBoundary?: boolean;
|
|
304
335
|
endTool?: boolean;
|
|
305
336
|
newBubble?: boolean;
|
|
337
|
+
reason?: RotateReason;
|
|
306
338
|
thinking?: boolean;
|
|
307
339
|
trace?: string;
|
|
308
340
|
} = {},
|
|
309
341
|
): void {
|
|
310
|
-
const { blockBoundary = false, endTool = false, newBubble = false, thinking = false, trace } = options;
|
|
342
|
+
const { blockBoundary = false, endTool = false, newBubble = false, reason, thinking = false, trace } = options;
|
|
311
343
|
if (!text || this.streamDead || this.disposed) return;
|
|
312
344
|
const queuedAt = trace ? Date.now() : 0;
|
|
313
345
|
void this.enqueue(async () => {
|
|
@@ -324,14 +356,14 @@ export class BubbleWriter {
|
|
|
324
356
|
}
|
|
325
357
|
if (blockBoundary && !(await this.closeOpenFence())) return;
|
|
326
358
|
if (newBubble && this.cur && this.bubbleChars > 0 && !this.pendingResume) {
|
|
327
|
-
await this.rotateStream();
|
|
359
|
+
await this.rotateStream(reason ?? "text");
|
|
328
360
|
if (this.streamDead || this.disposed) return;
|
|
329
361
|
}
|
|
330
362
|
const cut = this.splitPoint(text, newBubble);
|
|
331
363
|
if (cut >= 0) {
|
|
332
364
|
await this.appendChunk(text.slice(0, cut + 1), { thinking, endTool, trace, queuedAt });
|
|
333
365
|
if (this.streamDead || this.disposed) return;
|
|
334
|
-
await this.rotateStream();
|
|
366
|
+
await this.rotateStream("split");
|
|
335
367
|
if (this.streamDead || this.disposed) return;
|
|
336
368
|
await this.appendChunk(text.slice(cut + 1), { thinking, endTool, trace, queuedAt });
|
|
337
369
|
return;
|
|
@@ -361,6 +393,7 @@ export class BubbleWriter {
|
|
|
361
393
|
const outgoing = opts.thinking && (!this.cur || this.bubbleChars === 0) ? `${thinkingHeader()}${text}` : text;
|
|
362
394
|
try {
|
|
363
395
|
await stream.append(outgoing);
|
|
396
|
+
this.lastErrorCode = undefined;
|
|
364
397
|
this.bubbleChars += outgoing.length;
|
|
365
398
|
this.lastFrameAt = Date.now();
|
|
366
399
|
this.trackFences(outgoing);
|
|
@@ -400,9 +433,12 @@ export class BubbleWriter {
|
|
|
400
433
|
}
|
|
401
434
|
}
|
|
402
435
|
|
|
403
|
-
private async rotateStream(): Promise<void> {
|
|
436
|
+
private async rotateStream(reason: RotateReason): Promise<void> {
|
|
404
437
|
const stream = this.cur;
|
|
405
438
|
if (!stream) return;
|
|
439
|
+
const bubbleChars = this.bubbleChars;
|
|
440
|
+
const lastKind = this.lastKind;
|
|
441
|
+
const endedWithNewline = this.lastChar === "\n";
|
|
406
442
|
try {
|
|
407
443
|
if (this.lastChar && this.lastChar !== "\n") {
|
|
408
444
|
await stream.append("\n");
|
|
@@ -428,8 +464,12 @@ export class BubbleWriter {
|
|
|
428
464
|
if (isLogEnabled("debug")) {
|
|
429
465
|
log.debug("stream", "bubble split", {
|
|
430
466
|
msgId: this.logMsgId(),
|
|
467
|
+
reason,
|
|
431
468
|
elapsedMs: Date.now() - this.deps.startedAt,
|
|
432
|
-
|
|
469
|
+
bubbleChars,
|
|
470
|
+
lastKind,
|
|
471
|
+
endedWithNewline,
|
|
472
|
+
hasPushed: this.pushedAny,
|
|
433
473
|
});
|
|
434
474
|
}
|
|
435
475
|
}
|
|
@@ -457,6 +497,7 @@ export class BubbleWriter {
|
|
|
457
497
|
if (!bot || !this.deps.msgId) return null;
|
|
458
498
|
const resume = this.pendingResume;
|
|
459
499
|
this.pendingResume = undefined;
|
|
500
|
+
const fresh = !resume || (resume.msgSeq === undefined && !resume.streamMsgId);
|
|
460
501
|
const stream = new AppendStream(bot.messageApi, bot.getCredentials(), this.deps.openid, this.deps.msgId, {
|
|
461
502
|
resume,
|
|
462
503
|
onError: (err) => {
|
|
@@ -484,7 +525,7 @@ export class BubbleWriter {
|
|
|
484
525
|
onDebug: (message) => log.debug("stream", message, { msgId: this.logMsgId() }),
|
|
485
526
|
});
|
|
486
527
|
this.cur = stream;
|
|
487
|
-
if (
|
|
528
|
+
if (fresh) this.deps.budget.noteStreamBubble(this.deps.msgId);
|
|
488
529
|
if (isLogEnabled("debug")) {
|
|
489
530
|
log.debug("stream", "stream timing", {
|
|
490
531
|
phase: "stream open",
|
|
@@ -510,11 +551,15 @@ export class BubbleWriter {
|
|
|
510
551
|
const checkpoint = stream?.checkpoint() ?? null;
|
|
511
552
|
stream?.dispose();
|
|
512
553
|
this.cur = null;
|
|
554
|
+
const code = errorCode(err);
|
|
513
555
|
const resetSeq = isDuplicateMsgSeqError(err);
|
|
556
|
+
const expired = isExpiredStreamError(err);
|
|
557
|
+
this.lastErrorCode = code;
|
|
514
558
|
log.warn("stream", "stream error", {
|
|
515
559
|
msgId: this.logMsgId(),
|
|
516
560
|
elapsedMs: Date.now() - this.deps.startedAt,
|
|
517
561
|
resetSeq,
|
|
562
|
+
expired,
|
|
518
563
|
checkpoint: checkpoint
|
|
519
564
|
? {
|
|
520
565
|
index: checkpoint.index,
|
|
@@ -528,26 +573,29 @@ export class BubbleWriter {
|
|
|
528
573
|
});
|
|
529
574
|
if (checkpoint && this.resumeAttempts < MAX_RESUME_ATTEMPTS) {
|
|
530
575
|
this.resumeAttempts += 1;
|
|
531
|
-
this.pendingResume =
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
576
|
+
this.pendingResume =
|
|
577
|
+
resetSeq || expired
|
|
578
|
+
? {
|
|
579
|
+
index: 0,
|
|
580
|
+
...(checkpoint.buffer ? { buffer: checkpoint.buffer } : {}),
|
|
581
|
+
}
|
|
582
|
+
: checkpoint;
|
|
537
583
|
return;
|
|
538
584
|
}
|
|
539
|
-
this.killStream(err.message);
|
|
585
|
+
this.killStream(err.message, code);
|
|
540
586
|
}
|
|
541
587
|
|
|
542
|
-
private killStream(reason: string): void {
|
|
588
|
+
private killStream(reason: string, code = this.lastErrorCode): void {
|
|
543
589
|
if (this.streamDead) return;
|
|
544
590
|
this.streamDead = true;
|
|
591
|
+
this.terminalCode = code;
|
|
545
592
|
this.pendingResume = undefined;
|
|
546
593
|
this.cur?.dispose();
|
|
547
594
|
this.cur = null;
|
|
548
595
|
log.warn("stream", "stream unavailable", {
|
|
549
596
|
msgId: this.logMsgId(),
|
|
550
597
|
reason,
|
|
598
|
+
code: code ?? null,
|
|
551
599
|
stats: this.stats(),
|
|
552
600
|
budget: this.deps.budget.snapshot(),
|
|
553
601
|
});
|