@chen_hu_hu/pi-qq 1.5.1 → 1.6.1
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 +33 -3
- package/README-zh.md +61 -29
- package/README.md +61 -29
- package/doc/archive/{delivery-v1.md → delivery.1.0.0.md} +1 -1
- package/doc/archive/{delivery-v2.md → delivery.1.2.0.md} +1 -1
- package/doc/archive/{delivery-v3.md → delivery.1.3.0.md} +1 -1
- package/doc/archive/{delivery-v4.md → delivery.1.4.0.md} +1 -1
- package/doc/archive/{delivery-v5.md → delivery.1.5.0.md} +2 -2
- package/doc/archive/delivery.1.6.0.md +263 -0
- package/doc/archive/delivery.1.6.1.md +150 -0
- package/doc/todo.md +66 -38
- package/index.ts +50 -16
- package/package.json +1 -1
- package/src/infra/i18n.ts +6 -2
- package/src/infra/reply-type.ts +9 -0
- package/src/infra/settings.ts +7 -6
- package/src/qq/inbound-command.ts +6 -0
- package/src/qq/qq-message-handler.ts +4 -0
- package/src/qq/status-report.ts +4 -0
- package/src/relay/bubble-writer.ts +47 -32
- package/src/relay/reply-policy.ts +37 -0
- package/src/relay/run-stream-relay.ts +89 -16
package/index.ts
CHANGED
|
@@ -40,12 +40,27 @@ let stateDetail: string | undefined;
|
|
|
40
40
|
let sessionCtx: ExtensionContext | undefined;
|
|
41
41
|
let mediaTool: MediaToolController | undefined;
|
|
42
42
|
let activeSettings: ResolvedSettings = getSettings({});
|
|
43
|
+
let lastConfigError: string | undefined;
|
|
43
44
|
const budget = new ReplyBudget();
|
|
44
45
|
const runFeedback = new RunFeedback({
|
|
45
46
|
bot: () => running?.bot,
|
|
46
47
|
budget,
|
|
47
|
-
|
|
48
|
+
getReplyType: () => activeSettings.replyType,
|
|
48
49
|
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
50
|
+
onFallbackReply: (text) => {
|
|
51
|
+
const bot = running?.bot;
|
|
52
|
+
const bound = getLoginState()?.allowedOpenid;
|
|
53
|
+
if (!bot || !bound) {
|
|
54
|
+
log.warn("pi", "fallback reply skipped: no bot or bound user");
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
log.info("pi", "sending fallback reply", { textLength: text.length });
|
|
58
|
+
void sendReply(bot, markdownToPlain(text), {
|
|
59
|
+
budget,
|
|
60
|
+
boundOpenid: bound,
|
|
61
|
+
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
62
|
+
});
|
|
63
|
+
},
|
|
49
64
|
});
|
|
50
65
|
|
|
51
66
|
const eventLoopDelay = monitorEventLoopDelay({ resolution: 100 });
|
|
@@ -99,6 +114,29 @@ function stopEventLoopMonitor(): void {
|
|
|
99
114
|
export default function (pi: ExtensionAPI) {
|
|
100
115
|
setLogGate(() => Boolean(getLoginState()) && runFeedback.isQQRunActive());
|
|
101
116
|
|
|
117
|
+
const notifyConfigError = (ctx: ExtensionContext, error: string | undefined, dedupe: boolean) => {
|
|
118
|
+
if (!error) {
|
|
119
|
+
lastConfigError = undefined;
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (dedupe && error === lastConfigError) return;
|
|
123
|
+
lastConfigError = error;
|
|
124
|
+
ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const applyConfig = (ctx?: ExtensionContext, options: { dedupeError?: boolean } = {}) => {
|
|
128
|
+
const { config, error } = readConfig();
|
|
129
|
+
activeSettings = getSettings(config);
|
|
130
|
+
configureI18n(activeSettings.language);
|
|
131
|
+
if (ctx) {
|
|
132
|
+
configureLogger(activeSettings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
|
|
133
|
+
notifyConfigError(ctx, error, options.dedupeError ?? false);
|
|
134
|
+
}
|
|
135
|
+
return { settings: activeSettings, error };
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
let pendingConfigError = applyConfig().error;
|
|
139
|
+
|
|
102
140
|
mediaTool = registerMediaTool(pi, {
|
|
103
141
|
getBot: () => running?.bot,
|
|
104
142
|
getLogin: () => getLoginState(),
|
|
@@ -106,22 +144,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
106
144
|
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
107
145
|
});
|
|
108
146
|
|
|
109
|
-
activeSettings = getSettings(readConfig().config);
|
|
110
|
-
configureI18n(activeSettings.language);
|
|
111
|
-
|
|
112
147
|
const getAllowedOpenid = () => getLoginState()?.allowedOpenid;
|
|
113
148
|
const getDeliverAs = () => activeSettings.deliverAs;
|
|
149
|
+
const getReplyType = () => activeSettings.replyType;
|
|
114
150
|
|
|
115
151
|
const onWarn = (ctx: ExtensionContext) => (msg: string) => ctx.ui.notify(`pi-qq ${msg}`, "warning");
|
|
116
152
|
|
|
117
|
-
const applyConfig = (ctx: ExtensionContext) => {
|
|
118
|
-
const { config, error } = readConfig();
|
|
119
|
-
activeSettings = getSettings(config);
|
|
120
|
-
configureI18n(activeSettings.language);
|
|
121
|
-
if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
122
|
-
return { settings: activeSettings, error };
|
|
123
|
-
};
|
|
124
|
-
|
|
125
153
|
const getStatusLines = (ctx: ExtensionContext | undefined = sessionCtx): string[] => {
|
|
126
154
|
const login = getLoginState();
|
|
127
155
|
const usage = ctx?.getContextUsage();
|
|
@@ -141,6 +169,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
141
169
|
}
|
|
142
170
|
: undefined,
|
|
143
171
|
power: getPowerStatus(),
|
|
172
|
+
replyType: activeSettings.replyType,
|
|
144
173
|
});
|
|
145
174
|
};
|
|
146
175
|
|
|
@@ -171,6 +200,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
171
200
|
cwd: ctx.cwd,
|
|
172
201
|
model: ctx.model?.name ?? null,
|
|
173
202
|
logLevel: settings.logLevel,
|
|
203
|
+
replyType: settings.replyType,
|
|
174
204
|
uploadDir,
|
|
175
205
|
indexedFiles: Object.keys(uploadIndex).length,
|
|
176
206
|
});
|
|
@@ -182,7 +212,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
182
212
|
ctx,
|
|
183
213
|
budget,
|
|
184
214
|
getAllowedOpenid,
|
|
215
|
+
reloadSettings: () => applyConfig(ctx, { dedupeError: true }),
|
|
185
216
|
getDeliverAs,
|
|
217
|
+
getReplyType,
|
|
186
218
|
getFileMaxSize: () => activeSettings.fileMaxSize,
|
|
187
219
|
getStatusLines,
|
|
188
220
|
getLastMessage: () => runFeedback.getLastMessage(),
|
|
@@ -204,8 +236,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
204
236
|
};
|
|
205
237
|
|
|
206
238
|
pi.on("session_start", async (_event, ctx) => {
|
|
207
|
-
const
|
|
208
|
-
|
|
239
|
+
const settings = activeSettings;
|
|
240
|
+
const configError = pendingConfigError;
|
|
241
|
+
pendingConfigError = undefined;
|
|
242
|
+
notifyConfigError(ctx, configError, false);
|
|
209
243
|
|
|
210
244
|
const login = getLoginState();
|
|
211
245
|
log.info("session", "started", {
|
|
@@ -213,8 +247,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
213
247
|
hasUI: ctx.hasUI,
|
|
214
248
|
model: ctx.model?.name ?? null,
|
|
215
249
|
logLevel: settings.logLevel,
|
|
250
|
+
replyType: settings.replyType,
|
|
216
251
|
login: login ? { appId: login.credentials.appId, allowedOpenid: login.allowedOpenid } : null,
|
|
217
|
-
configError:
|
|
252
|
+
configError: configError ?? null,
|
|
218
253
|
});
|
|
219
254
|
if (login) {
|
|
220
255
|
await startWithCredentials(ctx, login.credentials, login.allowedOpenid);
|
|
@@ -402,7 +437,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
402
437
|
pi.registerCommand("qq-login", {
|
|
403
438
|
description: t("commands.descQqLogin"),
|
|
404
439
|
handler: async (_args, ctx) => {
|
|
405
|
-
applyConfig(ctx);
|
|
406
440
|
stopIfRunning();
|
|
407
441
|
setLoginState(undefined);
|
|
408
442
|
let result: QrLoginResult | undefined;
|
package/package.json
CHANGED
package/src/infra/i18n.ts
CHANGED
|
@@ -36,6 +36,7 @@ const enUS = {
|
|
|
36
36
|
"status.batteryChargingNoPercent": "charging",
|
|
37
37
|
"status.batteryDischargingNoPercent": "discharging",
|
|
38
38
|
"status.settings": "Settings",
|
|
39
|
+
"status.replyType": "Reply type",
|
|
39
40
|
"status.none": "none",
|
|
40
41
|
|
|
41
42
|
"commands.descQqLogin": "pi-qq: log in with a QR code and bind the scanning QQ user",
|
|
@@ -55,6 +56,7 @@ const enUS = {
|
|
|
55
56
|
"commands.compact.done": "Context compaction triggered.",
|
|
56
57
|
"commands.compact.busy": "Task is running; use /stop before /compact.",
|
|
57
58
|
"commands.last.none": "No completed message yet.",
|
|
59
|
+
"commands.last.running": "The task is still running; the final reply will be sent when it finishes.",
|
|
58
60
|
"commands.new.busy": "Task is running; use /stop before resetting.",
|
|
59
61
|
"commands.new.resetting": "Resetting the session…",
|
|
60
62
|
"commands.unknown": "Unknown command {cmd}; use /help.",
|
|
@@ -164,8 +166,8 @@ const enUS = {
|
|
|
164
166
|
"settings.invalidRoot": "Invalid config file ({path}): expected a JSON object; using defaults.",
|
|
165
167
|
"settings.invalidFields": "Invalid config file ({path}): {errors}; invalid values were ignored.",
|
|
166
168
|
"settings.parseFailed": "Failed to parse config file ({path}): {message}",
|
|
167
|
-
"settings.thinkingRelay": "thinkingRelay must be a boolean",
|
|
168
169
|
"settings.deliverAs": 'deliverAs must be "steer" or "followUp"',
|
|
170
|
+
"settings.replyType": 'replyType must be "full", "simple", or "last"',
|
|
169
171
|
"settings.fileMaxSize": "fileMaxSize must be a positive finite number",
|
|
170
172
|
"settings.logLevel": 'logLevel must be "silent", "error", "warn", "info", or "debug"',
|
|
171
173
|
"settings.language": 'language must be "zh-cn" or "en-us"',
|
|
@@ -266,6 +268,7 @@ const zhCN: Record<TranslationKey, string> = {
|
|
|
266
268
|
"status.batteryChargingNoPercent": "充电中",
|
|
267
269
|
"status.batteryDischargingNoPercent": "放电中",
|
|
268
270
|
"status.settings": "设置",
|
|
271
|
+
"status.replyType": "回复模式",
|
|
269
272
|
"status.none": "无",
|
|
270
273
|
|
|
271
274
|
"commands.descQqLogin": "pi-qq:扫码登录并绑定扫码的 QQ 用户",
|
|
@@ -285,6 +288,7 @@ const zhCN: Record<TranslationKey, string> = {
|
|
|
285
288
|
"commands.compact.done": "已触发上下文压缩。",
|
|
286
289
|
"commands.compact.busy": "任务正在运行;请先使用 /stop 再执行 /compact。",
|
|
287
290
|
"commands.last.none": "还没有已完成的消息。",
|
|
291
|
+
"commands.last.running": "任务仍在进行中,完成后会自动推送最终回复。",
|
|
288
292
|
"commands.new.busy": "任务正在运行;请先使用 /stop 再重置会话。",
|
|
289
293
|
"commands.new.resetting": "正在重置会话…",
|
|
290
294
|
"commands.unknown": "未知命令 {cmd};请使用 /help。",
|
|
@@ -394,8 +398,8 @@ const zhCN: Record<TranslationKey, string> = {
|
|
|
394
398
|
"settings.invalidRoot": "配置文件无效({path}):应为 JSON 对象;使用默认值。",
|
|
395
399
|
"settings.invalidFields": "配置文件无效({path}):{errors};无效值已忽略。",
|
|
396
400
|
"settings.parseFailed": "解析配置文件失败({path}):{message}",
|
|
397
|
-
"settings.thinkingRelay": "thinkingRelay 必须是布尔值",
|
|
398
401
|
"settings.deliverAs": 'deliverAs 必须是 "steer" 或 "followUp"',
|
|
402
|
+
"settings.replyType": 'replyType 必须是 "full"、"simple" 或 "last"',
|
|
399
403
|
"settings.fileMaxSize": "fileMaxSize 必须是正有限数",
|
|
400
404
|
"settings.logLevel": 'logLevel 必须是 "silent"、"error"、"warn"、"info" 或 "debug"',
|
|
401
405
|
"settings.language": 'language 必须是 "zh-cn" 或 "en-us"',
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const REPLY_TYPES = ["full", "simple", "last"] as const;
|
|
2
|
+
|
|
3
|
+
export type ReplyType = (typeof REPLY_TYPES)[number];
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_REPLY_TYPE: ReplyType = "full";
|
|
6
|
+
|
|
7
|
+
export function isReplyType(value: unknown): value is ReplyType {
|
|
8
|
+
return typeof value === "string" && (REPLY_TYPES as readonly string[]).includes(value);
|
|
9
|
+
}
|
package/src/infra/settings.ts
CHANGED
|
@@ -3,10 +3,11 @@ import { homedir } from "node:os";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { normalizeLogLevel, type LogLevel } from "./file-logger";
|
|
5
5
|
import { DEFAULT_LANGUAGE, getLanguage, isLanguage, translate, type Language } from "./i18n";
|
|
6
|
+
import { DEFAULT_REPLY_TYPE, isReplyType, type ReplyType } from "./reply-type";
|
|
6
7
|
|
|
7
8
|
export interface PiQQSettings {
|
|
8
|
-
thinkingRelay?: boolean;
|
|
9
9
|
deliverAs?: "steer" | "followUp";
|
|
10
|
+
replyType?: ReplyType;
|
|
10
11
|
fileMaxSize?: number;
|
|
11
12
|
logLevel?: LogLevel;
|
|
12
13
|
language?: Language;
|
|
@@ -53,14 +54,14 @@ export function parseConfig(raw: unknown): ReadConfigResult {
|
|
|
53
54
|
if (isLanguage(raw.language)) config.language = raw.language;
|
|
54
55
|
else errors.push(translate(language, "settings.language"));
|
|
55
56
|
}
|
|
56
|
-
if (raw.thinkingRelay !== undefined) {
|
|
57
|
-
if (typeof raw.thinkingRelay === "boolean") config.thinkingRelay = raw.thinkingRelay;
|
|
58
|
-
else errors.push(translate(language, "settings.thinkingRelay"));
|
|
59
|
-
}
|
|
60
57
|
if (raw.deliverAs !== undefined) {
|
|
61
58
|
if (raw.deliverAs === "steer" || raw.deliverAs === "followUp") config.deliverAs = raw.deliverAs;
|
|
62
59
|
else errors.push(translate(language, "settings.deliverAs"));
|
|
63
60
|
}
|
|
61
|
+
if (raw.replyType !== undefined) {
|
|
62
|
+
if (isReplyType(raw.replyType)) config.replyType = raw.replyType;
|
|
63
|
+
else errors.push(translate(language, "settings.replyType"));
|
|
64
|
+
}
|
|
64
65
|
if (raw.fileMaxSize !== undefined) {
|
|
65
66
|
if (isPositiveSize(raw.fileMaxSize)) config.fileMaxSize = raw.fileMaxSize;
|
|
66
67
|
else errors.push(translate(language, "settings.fileMaxSize"));
|
|
@@ -110,8 +111,8 @@ export type ResolvedSettings = Required<Omit<PiQQSettings, "debug">>;
|
|
|
110
111
|
export function getSettings(config: PiQQSettings): ResolvedSettings {
|
|
111
112
|
const logLevel = normalizeLogLevel(config.logLevel ?? (config.debug ? "debug" : undefined));
|
|
112
113
|
return {
|
|
113
|
-
thinkingRelay: config.thinkingRelay ?? true,
|
|
114
114
|
deliverAs: config.deliverAs ?? "steer",
|
|
115
|
+
replyType: config.replyType ?? DEFAULT_REPLY_TYPE,
|
|
115
116
|
fileMaxSize: config.fileMaxSize ?? 50 * 1024 * 1024,
|
|
116
117
|
logLevel,
|
|
117
118
|
language: config.language ?? DEFAULT_LANGUAGE,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ReplyType } from "../infra/reply-type";
|
|
2
3
|
import { log } from "../infra/file-logger";
|
|
3
4
|
import { t } from "../infra/i18n";
|
|
4
5
|
|
|
@@ -17,6 +18,7 @@ export interface InboundCommandDeps {
|
|
|
17
18
|
ctx: InboundContext;
|
|
18
19
|
getStatusLines: () => string[];
|
|
19
20
|
getLastMessage?: () => string | undefined;
|
|
21
|
+
getReplyType?: () => ReplyType;
|
|
20
22
|
onStop?: () => void;
|
|
21
23
|
waitForEnd?: () => Promise<void>;
|
|
22
24
|
}
|
|
@@ -77,6 +79,10 @@ export async function handleInboundCommand(
|
|
|
77
79
|
break;
|
|
78
80
|
case "/last": {
|
|
79
81
|
if (!deps.ctx.isIdle()) {
|
|
82
|
+
if (deps.getReplyType?.() === "last") {
|
|
83
|
+
await reply(t("commands.last.running"));
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
80
86
|
extras.restartPush?.();
|
|
81
87
|
} else {
|
|
82
88
|
const text = deps.getLastMessage?.();
|
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
type SavedFile,
|
|
10
10
|
} from "../attachments/file-attachments";
|
|
11
11
|
import { log } from "../infra/file-logger";
|
|
12
|
+
import type { ReplyType } from "../infra/reply-type";
|
|
12
13
|
import { t } from "../infra/i18n";
|
|
13
14
|
import { handleInboundCommand, type InboundCommandDeps } from "./inbound-command";
|
|
14
15
|
import { PendingAttachments, resolveInboundContent } from "./inbound-attachments";
|
|
@@ -16,7 +17,9 @@ import { PendingAttachments, resolveInboundContent } from "./inbound-attachments
|
|
|
16
17
|
export interface InboundDeps extends InboundCommandDeps {
|
|
17
18
|
budget: ReplyBudget;
|
|
18
19
|
getAllowedOpenid: () => string | undefined;
|
|
20
|
+
reloadSettings: () => void;
|
|
19
21
|
getDeliverAs: () => "steer" | "followUp";
|
|
22
|
+
getReplyType: () => ReplyType;
|
|
20
23
|
getFileMaxSize: () => number;
|
|
21
24
|
saveFiles?: typeof saveInboundFiles;
|
|
22
25
|
streamReply?: typeof sendStreamReply;
|
|
@@ -58,6 +61,7 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
58
61
|
return;
|
|
59
62
|
}
|
|
60
63
|
|
|
64
|
+
deps.reloadSettings();
|
|
61
65
|
deps.budget.observeInbound(msg.senderId, msg.messageId);
|
|
62
66
|
log.info("inbound", "message received", {
|
|
63
67
|
messageId: msg.messageId,
|
package/src/qq/status-report.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { PowerStatus } from "../infra/power-status";
|
|
2
2
|
import { formatTokenCount } from "../infra/display-format";
|
|
3
|
+
import type { ReplyType } from "../infra/reply-type";
|
|
3
4
|
import { t, type TranslationKey } from "../infra/i18n";
|
|
4
5
|
import type { BotState } from "./qq-bot";
|
|
5
6
|
|
|
@@ -10,6 +11,7 @@ export interface StatusReportInput {
|
|
|
10
11
|
model?: { name: string };
|
|
11
12
|
usage?: { tokens: number | null; contextWindow: number | null; percent?: number | null };
|
|
12
13
|
power?: PowerStatus;
|
|
14
|
+
replyType?: ReplyType;
|
|
13
15
|
}
|
|
14
16
|
|
|
15
17
|
const STATE_ICONS: Record<BotState, string> = {
|
|
@@ -45,6 +47,7 @@ function label(
|
|
|
45
47
|
| "status.connection"
|
|
46
48
|
| "status.qqUser"
|
|
47
49
|
| "status.battery"
|
|
50
|
+
| "status.replyType"
|
|
48
51
|
| "status.settings",
|
|
49
52
|
value: string,
|
|
50
53
|
): string {
|
|
@@ -107,6 +110,7 @@ export function formatStatusReport(input: StatusReportInput): string[] {
|
|
|
107
110
|
|
|
108
111
|
const battery = batteryLine(input.power);
|
|
109
112
|
if (battery) lines.push(battery);
|
|
113
|
+
if (input.replyType) lines.push(`💬 ${label("status.replyType", input.replyType)}`);
|
|
110
114
|
lines.push(`⚙️ ${label("status.settings", "~/.pi/agent/pi-qq.json")}`);
|
|
111
115
|
return lines;
|
|
112
116
|
}
|
|
@@ -288,44 +288,59 @@ export class BubbleWriter {
|
|
|
288
288
|
await this.rotateStream();
|
|
289
289
|
if (this.streamDead || this.disposed) return;
|
|
290
290
|
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
this.
|
|
294
|
-
this.
|
|
295
|
-
!this.pendingResume &&
|
|
296
|
-
!this.fenceOpen &&
|
|
297
|
-
!this.toolOpen &&
|
|
298
|
-
(blockBoundary || this.lastChar === "\n")
|
|
299
|
-
) {
|
|
291
|
+
const cut = this.splitPoint(text, newBubble);
|
|
292
|
+
if (cut >= 0) {
|
|
293
|
+
await this.appendChunk(text.slice(0, cut + 1), { thinking, endTool, trace, queuedAt });
|
|
294
|
+
if (this.streamDead || this.disposed) return;
|
|
300
295
|
await this.rotateStream();
|
|
301
296
|
if (this.streamDead || this.disposed) return;
|
|
297
|
+
await this.appendChunk(text.slice(cut + 1), { thinking, endTool, trace, queuedAt });
|
|
298
|
+
return;
|
|
302
299
|
}
|
|
303
|
-
|
|
304
|
-
if (!stream) return;
|
|
305
|
-
this.pushedAny = true;
|
|
306
|
-
const outgoing = thinking && (!this.cur || this.bubbleChars === 0) ? `${thinkingHeader()}${text}` : text;
|
|
307
|
-
try {
|
|
308
|
-
await stream.append(outgoing);
|
|
309
|
-
this.bubbleChars += outgoing.length;
|
|
310
|
-
this.lastFrameAt = Date.now();
|
|
311
|
-
this.trackFences(outgoing);
|
|
312
|
-
this.lastChar = outgoing.slice(-1);
|
|
313
|
-
if (endTool) this.toolOpen = false;
|
|
314
|
-
if (trace && isLogEnabled("debug")) {
|
|
315
|
-
log.debug("stream", "stream timing", {
|
|
316
|
-
phase: "append done",
|
|
317
|
-
trace,
|
|
318
|
-
msgId: this.logMsgId(),
|
|
319
|
-
totalMs: Date.now() - queuedAt,
|
|
320
|
-
stats: this.stats(),
|
|
321
|
-
});
|
|
322
|
-
}
|
|
323
|
-
} catch (err) {
|
|
324
|
-
if (this.cur === stream) this.handleStreamError(err as Error);
|
|
325
|
-
}
|
|
300
|
+
await this.appendChunk(text, { thinking, endTool, trace, queuedAt });
|
|
326
301
|
});
|
|
327
302
|
}
|
|
328
303
|
|
|
304
|
+
private splitPoint(text: string, newBubble: boolean): number {
|
|
305
|
+
if (newBubble) return -1;
|
|
306
|
+
if (!this.cur) return -1;
|
|
307
|
+
if (this.pendingResume) return -1;
|
|
308
|
+
if (this.fenceOpen) return -1;
|
|
309
|
+
if (this.toolOpen) return -1;
|
|
310
|
+
if (this.bubbleChars < MAX_BUBBLE_CHARS) return -1;
|
|
311
|
+
return text.indexOf("\n");
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private async appendChunk(
|
|
315
|
+
text: string,
|
|
316
|
+
opts: { thinking?: boolean; endTool?: boolean; trace?: string; queuedAt?: number },
|
|
317
|
+
): Promise<void> {
|
|
318
|
+
if (!text || this.streamDead || this.disposed) return;
|
|
319
|
+
const stream = this.ensureStream();
|
|
320
|
+
if (!stream) return;
|
|
321
|
+
this.pushedAny = true;
|
|
322
|
+
const outgoing = opts.thinking && (!this.cur || this.bubbleChars === 0) ? `${thinkingHeader()}${text}` : text;
|
|
323
|
+
try {
|
|
324
|
+
await stream.append(outgoing);
|
|
325
|
+
this.bubbleChars += outgoing.length;
|
|
326
|
+
this.lastFrameAt = Date.now();
|
|
327
|
+
this.trackFences(outgoing);
|
|
328
|
+
this.lastChar = outgoing.slice(-1);
|
|
329
|
+
if (opts.endTool) this.toolOpen = false;
|
|
330
|
+
if (opts.trace && isLogEnabled("debug")) {
|
|
331
|
+
log.debug("stream", "stream timing", {
|
|
332
|
+
phase: "append done",
|
|
333
|
+
trace: opts.trace,
|
|
334
|
+
msgId: this.logMsgId(),
|
|
335
|
+
totalMs: Date.now() - (opts.queuedAt ?? 0),
|
|
336
|
+
stats: this.stats(),
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
} catch (err) {
|
|
340
|
+
if (this.cur === stream) this.handleStreamError(err as Error);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
329
344
|
private trackFences(text: string): void {
|
|
330
345
|
const previousChar = this.lastChar;
|
|
331
346
|
for (const match of text.matchAll(/(?:^|\n)[ \t>]*(`{3,})/g)) {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { ReplyType } from "../infra/reply-type";
|
|
2
|
+
|
|
3
|
+
export interface ReplyPolicy {
|
|
4
|
+
relayThinking: boolean;
|
|
5
|
+
relayTools: boolean;
|
|
6
|
+
relayTextLive: boolean;
|
|
7
|
+
deferTextWhileToolsPending: boolean;
|
|
8
|
+
deliverLastAtEnd: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const POLICIES: Record<ReplyType, ReplyPolicy> = {
|
|
12
|
+
full: {
|
|
13
|
+
relayThinking: true,
|
|
14
|
+
relayTools: true,
|
|
15
|
+
relayTextLive: true,
|
|
16
|
+
deferTextWhileToolsPending: true,
|
|
17
|
+
deliverLastAtEnd: false,
|
|
18
|
+
},
|
|
19
|
+
simple: {
|
|
20
|
+
relayThinking: false,
|
|
21
|
+
relayTools: false,
|
|
22
|
+
relayTextLive: true,
|
|
23
|
+
deferTextWhileToolsPending: false,
|
|
24
|
+
deliverLastAtEnd: false,
|
|
25
|
+
},
|
|
26
|
+
last: {
|
|
27
|
+
relayThinking: false,
|
|
28
|
+
relayTools: false,
|
|
29
|
+
relayTextLive: false,
|
|
30
|
+
deferTextWhileToolsPending: false,
|
|
31
|
+
deliverLastAtEnd: true,
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export function policyFor(type: ReplyType): ReplyPolicy {
|
|
36
|
+
return POLICIES[type];
|
|
37
|
+
}
|
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import type { QQBot } from "@tencent-connect/qqbot-nodejs";
|
|
2
2
|
import { BubbleWriter } from "./bubble-writer";
|
|
3
|
+
import { policyFor, type ReplyPolicy } from "./reply-policy";
|
|
3
4
|
import type { ReplyBudget } from "../quota/reply-quota";
|
|
5
|
+
import type { ReplyType } from "../infra/reply-type";
|
|
4
6
|
import { isLogEnabled, log } from "../infra/file-logger";
|
|
5
7
|
import { detectSkillRead } from "./stream-block-format";
|
|
6
8
|
|
|
7
9
|
export interface RunFeedbackDeps {
|
|
8
10
|
bot: () => QQBot | undefined;
|
|
9
11
|
budget: ReplyBudget;
|
|
10
|
-
|
|
12
|
+
getReplyType: () => ReplyType;
|
|
11
13
|
onWarn: (msg: string) => void;
|
|
14
|
+
onFallbackReply?: (text: string) => void;
|
|
12
15
|
}
|
|
13
16
|
|
|
14
17
|
interface ToolCall {
|
|
@@ -34,10 +37,16 @@ interface RunState {
|
|
|
34
37
|
deferredThinking: string;
|
|
35
38
|
deferredText: string;
|
|
36
39
|
hadError: boolean;
|
|
40
|
+
lastText: string;
|
|
37
41
|
writer: BubbleWriter;
|
|
38
42
|
typingTimer?: ReturnType<typeof setInterval>;
|
|
39
43
|
}
|
|
40
44
|
|
|
45
|
+
interface LastDelivery {
|
|
46
|
+
text: string;
|
|
47
|
+
streamed: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
41
50
|
const TYPING_INTERVAL_MS = 50_000;
|
|
42
51
|
const PENDING_TTL_MS = 15_000;
|
|
43
52
|
const RECOVERY_TTL_MS = 60_000;
|
|
@@ -150,6 +159,7 @@ export class RunFeedback {
|
|
|
150
159
|
deferredThinking: "",
|
|
151
160
|
deferredText: "",
|
|
152
161
|
hadError: false,
|
|
162
|
+
lastText: "",
|
|
153
163
|
writer,
|
|
154
164
|
};
|
|
155
165
|
this.run = run;
|
|
@@ -158,6 +168,7 @@ export class RunFeedback {
|
|
|
158
168
|
msgId: run.msgId?.slice(0, 8) ?? "?",
|
|
159
169
|
source: target === pending ? "pending" : "recovery",
|
|
160
170
|
targetAgeMs: now - target.at,
|
|
171
|
+
replyType: this.deps.getReplyType(),
|
|
161
172
|
budget: this.deps.budget.snapshot(),
|
|
162
173
|
});
|
|
163
174
|
}
|
|
@@ -242,6 +253,16 @@ export class RunFeedback {
|
|
|
242
253
|
const run = this.run;
|
|
243
254
|
if (!run) return;
|
|
244
255
|
|
|
256
|
+
const policy = this.policy();
|
|
257
|
+
|
|
258
|
+
if (!policy.relayTextLive) {
|
|
259
|
+
if (snapshotText.trim()) {
|
|
260
|
+
run.currentText = snapshotText;
|
|
261
|
+
run.lastText = snapshotText;
|
|
262
|
+
}
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
|
|
245
266
|
const full = [run.finalizedText, snapshotText].filter((part) => part.trim()).join("\n\n");
|
|
246
267
|
if (full.trim()) run.currentText = full;
|
|
247
268
|
|
|
@@ -250,7 +271,7 @@ export class RunFeedback {
|
|
|
250
271
|
if (snapshotThinking.length > run.thinkingSentLen) {
|
|
251
272
|
const thinkingDelta = snapshotThinking.slice(run.thinkingSentLen);
|
|
252
273
|
run.thinkingSentLen = snapshotThinking.length;
|
|
253
|
-
if (
|
|
274
|
+
if (policy.relayThinking) {
|
|
254
275
|
if (this.hasPendingTools(run)) {
|
|
255
276
|
run.deferredThinking += thinkingDelta;
|
|
256
277
|
} else {
|
|
@@ -262,7 +283,7 @@ export class RunFeedback {
|
|
|
262
283
|
const delta = full.slice(run.resultSentLen);
|
|
263
284
|
if (!delta) return;
|
|
264
285
|
run.resultSentLen = full.length;
|
|
265
|
-
if (this.hasPendingTools(run)) {
|
|
286
|
+
if (policy.deferTextWhileToolsPending && this.hasPendingTools(run)) {
|
|
266
287
|
run.deferredText += delta;
|
|
267
288
|
return;
|
|
268
289
|
}
|
|
@@ -280,12 +301,32 @@ export class RunFeedback {
|
|
|
280
301
|
return false;
|
|
281
302
|
}
|
|
282
303
|
|
|
304
|
+
const policy = this.policy();
|
|
305
|
+
|
|
306
|
+
if (!policy.relayTextLive) {
|
|
307
|
+
run.finalizedText = "";
|
|
308
|
+
run.resultSentLen = 0;
|
|
309
|
+
run.thinkingSentLen = 0;
|
|
310
|
+
if (isError) {
|
|
311
|
+
run.hadError = true;
|
|
312
|
+
this.recovery = { openid: run.openid, msgId: run.msgId ?? "", at: Date.now() };
|
|
313
|
+
log.debug("run", "last buffered", { textLength: 0, isError: true });
|
|
314
|
+
return false;
|
|
315
|
+
}
|
|
316
|
+
if (text.trim()) {
|
|
317
|
+
run.lastText = text;
|
|
318
|
+
run.currentText = text;
|
|
319
|
+
}
|
|
320
|
+
log.debug("run", "last buffered", { textLength: run.lastText.length, isError: false });
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
|
|
283
324
|
run.finalizedText = [run.finalizedText, text].filter((part) => part.trim()).join("\n\n");
|
|
284
325
|
if (text.trim()) run.currentText = text;
|
|
285
326
|
const delta = run.finalizedText.slice(run.resultSentLen);
|
|
286
327
|
run.resultSentLen = run.finalizedText.length;
|
|
287
328
|
if (!isError && text && delta) {
|
|
288
|
-
if (this.hasPendingTools(run)) {
|
|
329
|
+
if (policy.deferTextWhileToolsPending && this.hasPendingTools(run)) {
|
|
289
330
|
run.deferredText += delta;
|
|
290
331
|
} else {
|
|
291
332
|
run.writer.pushText(delta);
|
|
@@ -327,6 +368,7 @@ export class RunFeedback {
|
|
|
327
368
|
this.finishEnd();
|
|
328
369
|
return;
|
|
329
370
|
}
|
|
371
|
+
const lastDelivery = this.planLastDelivery(run);
|
|
330
372
|
await run.writer.whenIdle();
|
|
331
373
|
const hasPendingTools = this.hasPendingTools(run);
|
|
332
374
|
if (!hasPendingTools) this.flushDeferred(run);
|
|
@@ -348,15 +390,17 @@ export class RunFeedback {
|
|
|
348
390
|
msgId: run.msgId?.slice(0, 8) ?? "?",
|
|
349
391
|
elapsedMs: Date.now() - run.startedAt,
|
|
350
392
|
});
|
|
351
|
-
|
|
352
|
-
if (
|
|
353
|
-
run.writer.
|
|
354
|
-
|
|
355
|
-
|
|
393
|
+
let delivered = false;
|
|
394
|
+
if (run.writer.hasPushed) {
|
|
395
|
+
const ok = await run.writer.flush();
|
|
396
|
+
if (ok) {
|
|
397
|
+
await run.writer.done();
|
|
398
|
+
delivered = true;
|
|
399
|
+
}
|
|
356
400
|
}
|
|
357
|
-
const ok = await run.writer.flush();
|
|
358
|
-
if (ok) await run.writer.done();
|
|
359
401
|
run.writer.dispose();
|
|
402
|
+
this.settleLastDelivery(lastDelivery, delivered);
|
|
403
|
+
if (this.run === run) this.run = null;
|
|
360
404
|
this.finishEnd();
|
|
361
405
|
}
|
|
362
406
|
|
|
@@ -379,6 +423,33 @@ export class RunFeedback {
|
|
|
379
423
|
this.endResolve = undefined;
|
|
380
424
|
}
|
|
381
425
|
|
|
426
|
+
private policy(): ReplyPolicy {
|
|
427
|
+
return policyFor(this.deps.getReplyType());
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
private planLastDelivery(run: RunState): LastDelivery | undefined {
|
|
431
|
+
if (!this.policy().deliverLastAtEnd) return undefined;
|
|
432
|
+
const text = run.lastText.trim() ? run.lastText : "";
|
|
433
|
+
if (!text) return undefined;
|
|
434
|
+
const fresh = this.deps.budget.snapshot().fresh;
|
|
435
|
+
if (fresh) {
|
|
436
|
+
run.writer.closeBlock();
|
|
437
|
+
run.writer.pushText(text);
|
|
438
|
+
}
|
|
439
|
+
return { text, streamed: fresh };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
private settleLastDelivery(delivery: LastDelivery | undefined, delivered: boolean): void {
|
|
443
|
+
if (!delivery) return;
|
|
444
|
+
const ok = delivered && delivery.streamed;
|
|
445
|
+
log.debug("run", "last delivered", {
|
|
446
|
+
delivered: ok,
|
|
447
|
+
fallback: !ok,
|
|
448
|
+
textLength: delivery.text.length,
|
|
449
|
+
});
|
|
450
|
+
if (!ok) this.deps.onFallbackReply?.(delivery.text);
|
|
451
|
+
}
|
|
452
|
+
|
|
382
453
|
private hasPendingTools(run: RunState): boolean {
|
|
383
454
|
return Boolean(run.activeTool) || run.tools.some((tool) => !tool.finished);
|
|
384
455
|
}
|
|
@@ -410,10 +481,12 @@ export class RunFeedback {
|
|
|
410
481
|
skillName: tool.skillName ?? null,
|
|
411
482
|
...this.diagnostics(run),
|
|
412
483
|
});
|
|
413
|
-
if (
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
484
|
+
if (this.policy().relayTools) {
|
|
485
|
+
if (tool.skillName) {
|
|
486
|
+
run.writer.pushSkill(tool.skillName);
|
|
487
|
+
} else {
|
|
488
|
+
run.writer.pushTool(tool.name, tool.args);
|
|
489
|
+
}
|
|
417
490
|
}
|
|
418
491
|
if (tool.result) this.finishTool(run, tool);
|
|
419
492
|
}
|
|
@@ -428,7 +501,7 @@ export class RunFeedback {
|
|
|
428
501
|
isError: tool.result.isError,
|
|
429
502
|
...this.diagnostics(run),
|
|
430
503
|
});
|
|
431
|
-
if (!tool.skillName) {
|
|
504
|
+
if (this.policy().relayTools && !tool.skillName) {
|
|
432
505
|
run.writer.pushToolResult(tool.result.result, tool.result.isError, tool.name, tool.args);
|
|
433
506
|
}
|
|
434
507
|
run.writer.schedule(() => {
|