@chen_hu_hu/pi-qq 1.0.0 → 1.0.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/README.md +70 -104
- package/doc/{features.md → features-v1.md} +55 -92
- package/doc/{plan.md → plan-v1.md} +38 -43
- package/index.ts +111 -159
- package/package.json +2 -2
- package/src/append-stream.ts +21 -20
- package/src/bot.ts +23 -23
- package/src/budget-status.ts +9 -9
- package/src/config.ts +22 -80
- package/src/download.ts +3 -3
- package/src/files.ts +9 -9
- package/src/format.ts +6 -1
- package/src/images.ts +6 -6
- package/src/inbound.ts +12 -19
- package/src/login.ts +19 -20
- package/src/outbound.ts +22 -22
- package/src/qrcode-terminal.d.ts +1 -1
- package/src/reply-budget.ts +15 -15
- package/src/run-feedback.ts +70 -75
- package/src/usage.ts +0 -93
package/index.ts
CHANGED
|
@@ -1,13 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
3
|
-
clearCredentials,
|
|
4
|
-
getCredentials,
|
|
5
|
-
getSettings,
|
|
6
|
-
readConfig,
|
|
7
|
-
saveCredentials,
|
|
8
|
-
type Credentials,
|
|
9
|
-
type PiQQConfig,
|
|
10
|
-
} from "./src/config";
|
|
2
|
+
import { getSettings, readConfig, type Credentials } from "./src/config";
|
|
11
3
|
import { startBot, type BotState, type RunningBot } from "./src/bot";
|
|
12
4
|
import { runQrLogin } from "./src/login";
|
|
13
5
|
import { createInboundHandler } from "./src/inbound";
|
|
@@ -15,16 +7,34 @@ import { markdownToPlain, sendReply } from "./src/outbound";
|
|
|
15
7
|
import { ReplyBudget } from "./src/reply-budget";
|
|
16
8
|
import { RunFeedback } from "./src/run-feedback";
|
|
17
9
|
import { AppendStream } from "./src/append-stream";
|
|
18
|
-
import { formatTokenCount
|
|
10
|
+
import { formatTokenCount } from "./src/format";
|
|
19
11
|
import { formatBudgetStatus } from "./src/budget-status";
|
|
20
12
|
|
|
21
13
|
/**
|
|
22
|
-
* pi-qq
|
|
23
|
-
*
|
|
24
|
-
* - M2:QQ 单人聊天注入 pi(inbound)+ assistant 消息非流式回传(message_end)
|
|
14
|
+
* pi-qq extension entry.
|
|
15
|
+
* QR login only; credentials live in process memory and are never persisted.
|
|
25
16
|
*/
|
|
26
17
|
|
|
27
|
-
/**
|
|
18
|
+
/** In-memory login state; survives extension reload/session replacement in one process. */
|
|
19
|
+
interface LoginState {
|
|
20
|
+
credentials: Credentials;
|
|
21
|
+
allowedOpenid: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const LOGIN_STATE_KEY = "__piQQLoginState";
|
|
25
|
+
type GlobalWithLogin = typeof globalThis & { [LOGIN_STATE_KEY]?: LoginState };
|
|
26
|
+
|
|
27
|
+
function getLoginState(): LoginState | undefined {
|
|
28
|
+
return (globalThis as GlobalWithLogin)[LOGIN_STATE_KEY];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function setLoginState(state: LoginState | undefined): void {
|
|
32
|
+
const store = globalThis as GlobalWithLogin;
|
|
33
|
+
if (state) store[LOGIN_STATE_KEY] = state;
|
|
34
|
+
else delete store[LOGIN_STATE_KEY];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Session-level runtime state; rebuilt by a new runtime after reload/session switch. */
|
|
28
38
|
let running: RunningBot | undefined;
|
|
29
39
|
let lastState: BotState = "stopped";
|
|
30
40
|
let stateDetail: string | undefined;
|
|
@@ -33,7 +43,7 @@ const budget = new ReplyBudget();
|
|
|
33
43
|
const runFeedback = new RunFeedback({
|
|
34
44
|
bot: () => running?.bot,
|
|
35
45
|
budget,
|
|
36
|
-
boundOpenid: () =>
|
|
46
|
+
boundOpenid: () => getLoginState()?.allowedOpenid,
|
|
37
47
|
getHeartbeatMinutes: () => getSettings(readConfig().config).heartbeatMinutes,
|
|
38
48
|
getHeartbeatMaxMessages: () => getSettings(readConfig().config).heartbeatMaxMessages,
|
|
39
49
|
getStreamRelay: () => getSettings(readConfig().config).streamRelay,
|
|
@@ -41,77 +51,54 @@ const runFeedback = new RunFeedback({
|
|
|
41
51
|
getDebug: () => getSettings(readConfig().config).debug,
|
|
42
52
|
makeChannel: () => ({
|
|
43
53
|
budget,
|
|
44
|
-
boundOpenid:
|
|
54
|
+
boundOpenid: getLoginState()?.allowedOpenid ?? "",
|
|
45
55
|
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
46
56
|
}),
|
|
47
57
|
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
48
58
|
});
|
|
49
59
|
|
|
50
|
-
const fmtTokens = (n: number | null): string => (n === null ? "
|
|
60
|
+
const fmtTokens = (n: number | null): string => (n === null ? "unknown" : formatTokenCount(n));
|
|
51
61
|
|
|
52
62
|
export default function (pi: ExtensionAPI) {
|
|
53
63
|
const maskAppId = (appId: string) => `${appId.slice(0, 4)}****`;
|
|
54
64
|
|
|
55
|
-
//
|
|
65
|
+
// Live settings reader (binding/settings changes apply immediately).
|
|
56
66
|
|
|
57
|
-
const getAllowedOpenid = () =>
|
|
67
|
+
const getAllowedOpenid = () => getLoginState()?.allowedOpenid;
|
|
58
68
|
const getBoundOpenid = getAllowedOpenid;
|
|
59
69
|
const getDeliverAs = () => getSettings(readConfig().config).deliverAs;
|
|
60
70
|
|
|
61
71
|
const onWarn = (ctx: ExtensionContext) => (msg: string) => ctx.ui.notify(`pi-qq ${msg}`, "warning");
|
|
62
72
|
|
|
63
|
-
/** F5/F6:在 agent_end 时快照本次 run 用量,返回发送函数(等时间线封口后再调用) */
|
|
64
|
-
const prepareUsageSummary = (ctx: ExtensionContext, usage: UsageTotals): (() => void) | null => {
|
|
65
|
-
const { config } = readConfig();
|
|
66
|
-
const settings = getSettings(config);
|
|
67
|
-
if (!settings.usageRelay) return null;
|
|
68
|
-
|
|
69
|
-
const bound = config.allowedOpenid;
|
|
70
|
-
const bot = running?.bot;
|
|
71
|
-
const hasUsage = usage.input + usage.output + usage.cacheRead + usage.cacheWrite > 0;
|
|
72
|
-
if (!bound || !bot || !hasUsage) return null;
|
|
73
|
-
|
|
74
|
-
const summary = formatUsageSummary({
|
|
75
|
-
usage,
|
|
76
|
-
context: ctx.getContextUsage(),
|
|
77
|
-
});
|
|
78
|
-
// 快照文本,避免等待时间线封口期间新 run 覆盖本次数据
|
|
79
|
-
return () => {
|
|
80
|
-
if (running?.bot !== bot) return;
|
|
81
|
-
void sendReply(bot, summary, {
|
|
82
|
-
budget,
|
|
83
|
-
boundOpenid: bound,
|
|
84
|
-
onWarn: onWarn(ctx),
|
|
85
|
-
});
|
|
86
|
-
};
|
|
87
|
-
};
|
|
88
|
-
|
|
89
73
|
const getStatusLines = (): string[] => {
|
|
90
|
-
const
|
|
74
|
+
const login = getLoginState();
|
|
91
75
|
const usage = sessionCtx?.getContextUsage();
|
|
92
76
|
const model = sessionCtx?.model;
|
|
93
77
|
return [
|
|
94
|
-
"pi-qq
|
|
95
|
-
|
|
96
|
-
|
|
78
|
+
"pi-qq status",
|
|
79
|
+
`Login: ${login ? `QR login, in memory (AppID ${maskAppId(login.credentials.appId)})` : "not logged in"}`,
|
|
80
|
+
`Connection: ${lastState}${stateDetail ? ` (${stateDetail})` : ""}`,
|
|
81
|
+
`Model: ${model?.name ?? "none"}`,
|
|
97
82
|
usage
|
|
98
|
-
?
|
|
99
|
-
: "
|
|
100
|
-
|
|
83
|
+
? `Context: ${fmtTokens(usage.tokens)}/${fmtTokens(usage.contextWindow)} (${usage.percent?.toFixed(1) ?? "?"}%)`
|
|
84
|
+
: "Context: unknown",
|
|
85
|
+
`Bound user: ${login?.allowedOpenid ?? "none"}`,
|
|
86
|
+
`Settings: ~/.pi/agent/pi-qq.json`,
|
|
101
87
|
];
|
|
102
88
|
};
|
|
103
89
|
|
|
104
|
-
// ——
|
|
90
|
+
// —— Login and connection ——
|
|
105
91
|
|
|
106
|
-
const startWithCredentials = (ctx: ExtensionContext, creds: Credentials,
|
|
92
|
+
const startWithCredentials = (ctx: ExtensionContext, creds: Credentials, allowedOpenid: string) => {
|
|
93
|
+
const settings = getSettings(readConfig().config);
|
|
107
94
|
running?.stop();
|
|
108
95
|
stateDetail = undefined;
|
|
109
96
|
sessionCtx = ctx;
|
|
110
97
|
running = startBot({
|
|
111
98
|
credentials: creds,
|
|
112
|
-
allowedOpenid
|
|
113
|
-
markdownSupport:
|
|
114
|
-
debug:
|
|
99
|
+
allowedOpenid,
|
|
100
|
+
markdownSupport: settings.markdownSupport,
|
|
101
|
+
debug: settings.debug,
|
|
115
102
|
onMessage: createInboundHandler({
|
|
116
103
|
pi,
|
|
117
104
|
ctx,
|
|
@@ -128,13 +115,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
128
115
|
onStateChange: (state, detail) => {
|
|
129
116
|
lastState = state;
|
|
130
117
|
stateDetail = detail;
|
|
131
|
-
|
|
132
|
-
if (state === "
|
|
133
|
-
else if (state === "blocked") ctx.ui.notify(`pi-qq ${detail ?? "连接被致命关闭"}`, "error");
|
|
118
|
+
if (state === "connected") ctx.ui.notify("pi-qq connected", "info");
|
|
119
|
+
else if (state === "blocked") ctx.ui.notify(`pi-qq ${detail ?? "connection blocked"}`, "error");
|
|
134
120
|
else if (state === "stopped" && detail) ctx.ui.notify(`pi-qq ${detail}`, "warning");
|
|
135
121
|
},
|
|
136
122
|
onRecoverableError: () => {
|
|
137
|
-
//
|
|
123
|
+
// Recoverable errors are handled by the SDK reconnect loop.
|
|
138
124
|
},
|
|
139
125
|
});
|
|
140
126
|
};
|
|
@@ -143,24 +129,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
143
129
|
running?.stop();
|
|
144
130
|
running = undefined;
|
|
145
131
|
lastState = "stopped";
|
|
132
|
+
stateDetail = undefined;
|
|
146
133
|
};
|
|
147
134
|
|
|
148
|
-
// ——
|
|
135
|
+
// —— Lifecycle ——
|
|
149
136
|
|
|
150
137
|
pi.on("session_start", (_event, ctx) => {
|
|
151
|
-
const {
|
|
152
|
-
if (error) {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if (creds) {
|
|
158
|
-
startWithCredentials(ctx, creds, config, "配置直连");
|
|
138
|
+
const { error } = readConfig();
|
|
139
|
+
if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
140
|
+
|
|
141
|
+
const login = getLoginState();
|
|
142
|
+
if (login) {
|
|
143
|
+
startWithCredentials(ctx, login.credentials, login.allowedOpenid);
|
|
159
144
|
} else if (ctx.hasUI) {
|
|
160
|
-
ctx.ui.notify(
|
|
161
|
-
"pi-qq 未配置机器人凭据:执行 /qq-login 扫码登录,或在 ~/.pi/agent/pi-qq.json 写入 { AppID, AppSecret } 后重启会话",
|
|
162
|
-
"warning",
|
|
163
|
-
);
|
|
145
|
+
ctx.ui.notify("pi-qq: run /qq-login to scan a QR code.", "warning");
|
|
164
146
|
}
|
|
165
147
|
});
|
|
166
148
|
|
|
@@ -170,28 +152,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
170
152
|
runFeedback.dispose();
|
|
171
153
|
});
|
|
172
154
|
|
|
173
|
-
//
|
|
155
|
+
// F7 run feedback: agent lifecycle / tool counts / text streaming.
|
|
174
156
|
|
|
175
157
|
pi.on("agent_start", () => {
|
|
176
158
|
runFeedback.onAgentStart();
|
|
177
159
|
});
|
|
178
160
|
|
|
179
|
-
pi.on("agent_end", (
|
|
180
|
-
|
|
181
|
-
// 错误/中止的 run 不发摘要:自动重试时避免每轮失败都刷一条消息
|
|
182
|
-
const completed =
|
|
183
|
-
lastAssistant !== undefined && lastAssistant.stopReason !== "error" && lastAssistant.stopReason !== "aborted";
|
|
184
|
-
const wasQQRun = runFeedback.isQQTriggeredRun();
|
|
185
|
-
// 在异步封口时间线前快照本次 run 的用量,避免新 run 覆盖
|
|
186
|
-
const runUsage = sumUsageMessages(event.messages);
|
|
187
|
-
const sendSummary = wasQQRun && completed ? prepareUsageSummary(ctx, runUsage) : null;
|
|
188
|
-
// 先封口时间线气泡,再发用量摘要(保证 QQ 消息顺序)
|
|
189
|
-
void runFeedback
|
|
190
|
-
.onAgentEnd()
|
|
191
|
-
.then(() => {
|
|
192
|
-
sendSummary?.();
|
|
193
|
-
})
|
|
194
|
-
.catch(() => {});
|
|
161
|
+
pi.on("agent_end", () => {
|
|
162
|
+
void runFeedback.onAgentEnd();
|
|
195
163
|
});
|
|
196
164
|
|
|
197
165
|
pi.on("tool_execution_start", (event) => {
|
|
@@ -216,7 +184,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
216
184
|
void runFeedback.onAssistantDelta(snapshot, thinking);
|
|
217
185
|
});
|
|
218
186
|
|
|
219
|
-
//
|
|
187
|
+
// pi → QQ: assistant message relay (non-streaming path + F7 stream takeover).
|
|
220
188
|
|
|
221
189
|
pi.on("message_end", async (event, ctx) => {
|
|
222
190
|
const msg = event.message;
|
|
@@ -237,20 +205,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
237
205
|
.trim();
|
|
238
206
|
}
|
|
239
207
|
if (!text) {
|
|
240
|
-
//
|
|
241
|
-
//
|
|
208
|
+
// Textless assistant messages also end the feedback turn: reset thinking state
|
|
209
|
+
// and flush pending thinking rows so the next message does not swallow them.
|
|
242
210
|
await runFeedback.onAssistantFinal("", isError);
|
|
243
211
|
return;
|
|
244
212
|
}
|
|
245
213
|
|
|
246
|
-
// F7
|
|
214
|
+
// F7 stream takeover: stream frames render Markdown; send raw text so lengths match.
|
|
247
215
|
if (await runFeedback.onAssistantFinal(text, isError)) return;
|
|
248
216
|
|
|
249
217
|
const payload = settings.markdownSupport ? text : markdownToPlain(text);
|
|
250
218
|
|
|
251
|
-
const bound =
|
|
219
|
+
const bound = getLoginState()?.allowedOpenid;
|
|
252
220
|
if (!bound) {
|
|
253
|
-
ctx.ui.notify("pi-qq
|
|
221
|
+
ctx.ui.notify("pi-qq: no bound QQ user; skipping reply.", "warning");
|
|
254
222
|
return;
|
|
255
223
|
}
|
|
256
224
|
|
|
@@ -261,142 +229,126 @@ export default function (pi: ExtensionAPI) {
|
|
|
261
229
|
});
|
|
262
230
|
});
|
|
263
231
|
|
|
264
|
-
// ——
|
|
232
|
+
// —— Commands ——
|
|
265
233
|
|
|
266
234
|
pi.registerCommand("qq-login", {
|
|
267
|
-
description: "pi-qq
|
|
235
|
+
description: "pi-qq: log in with a QR code and bind the scanning QQ user",
|
|
268
236
|
handler: async (_args, ctx) => {
|
|
269
|
-
const {
|
|
270
|
-
if (error) {
|
|
271
|
-
|
|
237
|
+
const { error } = readConfig();
|
|
238
|
+
if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
239
|
+
|
|
240
|
+
stopIfRunning();
|
|
241
|
+
setLoginState(undefined);
|
|
242
|
+
const result = await runQrLogin(ctx);
|
|
243
|
+
if (!result) return;
|
|
244
|
+
if (!result.userOpenid) {
|
|
245
|
+
ctx.ui.notify("pi-qq: QR login did not return a user openid; cannot bind.", "error");
|
|
272
246
|
return;
|
|
273
247
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const creds = await runQrLogin(ctx);
|
|
279
|
-
if (!creds) return; // 取消或失败,原因已提示
|
|
280
|
-
saveCredentials(creds, { userOpenid: creds.userOpenid });
|
|
281
|
-
startWithCredentials(
|
|
282
|
-
ctx,
|
|
283
|
-
creds,
|
|
284
|
-
{ ...config, allowedOpenid: creds.userOpenid ?? config.allowedOpenid },
|
|
285
|
-
"扫码登录",
|
|
286
|
-
);
|
|
248
|
+
|
|
249
|
+
const credentials: Credentials = { appId: result.appId, appSecret: result.appSecret };
|
|
250
|
+
setLoginState({ credentials, allowedOpenid: result.userOpenid });
|
|
251
|
+
startWithCredentials(ctx, credentials, result.userOpenid);
|
|
287
252
|
},
|
|
288
253
|
});
|
|
289
254
|
|
|
290
255
|
pi.registerCommand("qq-status", {
|
|
291
|
-
description: "pi-qq
|
|
256
|
+
description: "pi-qq: show login, connection, and bound QQ user",
|
|
292
257
|
handler: async (_args, ctx) => {
|
|
293
|
-
|
|
294
|
-
const creds = error ? null : getCredentials(config);
|
|
295
|
-
const source = creds ? (config.AppID ? "配置文件(AppID)" : "扫码写入") : "未配置";
|
|
296
|
-
const lines = [
|
|
297
|
-
"pi-qq 状态",
|
|
298
|
-
`连接:${lastState}${stateDetail ? `(${stateDetail})` : ""}`,
|
|
299
|
-
creds ? `凭据:${maskAppId(creds.appId)}(来源:${source})` : "凭据:未配置",
|
|
300
|
-
`绑定用户:${config.allowedOpenid ?? "未绑定"}`,
|
|
301
|
-
"配置文件:~/.pi/agent/pi-qq.json",
|
|
302
|
-
];
|
|
303
|
-
ctx.ui.notify(lines.join("\n"), error ? "warning" : "info");
|
|
258
|
+
ctx.ui.notify(getStatusLines().join("\n"), "info");
|
|
304
259
|
},
|
|
305
260
|
});
|
|
306
261
|
|
|
307
|
-
pi.registerCommand("qq-budget", {
|
|
308
|
-
description: "pi-qq
|
|
262
|
+
pi.registerCommand("qq-test-budget", {
|
|
263
|
+
description: "pi-qq: show passive reply budget, stream bubbles, and last inbound target",
|
|
309
264
|
handler: async (_args, ctx) => {
|
|
310
265
|
ctx.ui.notify(formatBudgetStatus(budget.snapshot(), budget.lastTarget).join("\n"), "info");
|
|
311
266
|
},
|
|
312
267
|
});
|
|
313
268
|
|
|
314
269
|
pi.registerCommand("qq-logout", {
|
|
315
|
-
description: "pi-qq
|
|
270
|
+
description: "pi-qq: log out and clear in-memory credentials",
|
|
316
271
|
handler: async (_args, ctx) => {
|
|
317
272
|
stopIfRunning();
|
|
318
|
-
|
|
319
|
-
ctx.ui.notify("pi-qq
|
|
273
|
+
setLoginState(undefined);
|
|
274
|
+
ctx.ui.notify("pi-qq logged out. Credentials cleared from memory; run /qq-login to scan again.", "info");
|
|
320
275
|
},
|
|
321
276
|
});
|
|
322
277
|
|
|
323
278
|
pi.registerCommand("qq-new", {
|
|
324
|
-
description: "pi-qq
|
|
279
|
+
description: "pi-qq: reset the current session (used by QQ /new)",
|
|
325
280
|
handler: async (_args, ctx) => {
|
|
326
281
|
if (!ctx.isIdle()) {
|
|
327
|
-
ctx.ui.notify("
|
|
282
|
+
ctx.ui.notify("pi-qq: the agent is busy; run /stop before resetting the session.", "warning");
|
|
328
283
|
return;
|
|
329
284
|
}
|
|
330
285
|
const { cancelled } = await ctx.newSession();
|
|
331
|
-
if (cancelled) ctx.ui.notify("
|
|
286
|
+
if (cancelled) ctx.ui.notify("pi-qq: session reset cancelled.", "warning");
|
|
332
287
|
},
|
|
333
288
|
});
|
|
334
289
|
|
|
335
|
-
// ——
|
|
290
|
+
// —— Diagnostic commands ——
|
|
336
291
|
|
|
337
292
|
const diagTarget = () => {
|
|
338
293
|
const last = budget.lastTarget;
|
|
339
294
|
if (last) return { scope: "c2c" as const, targetId: last.openid, msgId: last.msgId };
|
|
340
|
-
const bound =
|
|
295
|
+
const bound = getLoginState()?.allowedOpenid;
|
|
341
296
|
return bound ? { scope: "c2c" as const, targetId: bound } : undefined;
|
|
342
297
|
};
|
|
343
298
|
|
|
344
|
-
pi.registerCommand("qq-md", {
|
|
345
|
-
description: "pi-qq
|
|
299
|
+
pi.registerCommand("qq-test-md", {
|
|
300
|
+
description: "pi-qq: send a Markdown message to verify QQ C2C Markdown rendering",
|
|
346
301
|
handler: async (args, ctx) => {
|
|
347
302
|
if (!running) {
|
|
348
|
-
ctx.ui.notify("pi-qq
|
|
303
|
+
ctx.ui.notify("pi-qq is not connected.", "warning");
|
|
349
304
|
return;
|
|
350
305
|
}
|
|
351
306
|
const target = diagTarget();
|
|
352
307
|
if (!target) {
|
|
353
|
-
ctx.ui.notify("pi-qq
|
|
308
|
+
ctx.ui.notify("pi-qq: no send target. Send a QQ message first.", "warning");
|
|
354
309
|
return;
|
|
355
310
|
}
|
|
356
|
-
const content = args?.trim() || "**Markdown
|
|
311
|
+
const content = args?.trim() || "**Markdown test**\n# Heading\n- Item one\n- Item two\n[Link](https://qq.com)";
|
|
357
312
|
try {
|
|
358
313
|
await running.bot.sendMarkdown(target, content);
|
|
359
|
-
ctx.ui.notify(
|
|
360
|
-
"已发送 Markdown 测试消息:若 QQ 中渲染为富文本 → C2C markdown 可用;若显示原文/报错 → 记录现象",
|
|
361
|
-
"info",
|
|
362
|
-
);
|
|
314
|
+
ctx.ui.notify("Markdown test sent. Check whether QQ renders it as rich text.", "info");
|
|
363
315
|
} catch (err) {
|
|
364
|
-
ctx.ui.notify(`Markdown
|
|
316
|
+
ctx.ui.notify(`Markdown send failed: ${(err as Error).message}`, "error");
|
|
365
317
|
}
|
|
366
318
|
},
|
|
367
319
|
});
|
|
368
320
|
|
|
369
|
-
pi.registerCommand("qq-stream
|
|
370
|
-
description: "pi-qq
|
|
321
|
+
pi.registerCommand("qq-test-stream", {
|
|
322
|
+
description: "pi-qq: run a streamed timeline diagnostic (thinking/tools/text)",
|
|
371
323
|
handler: async (_args, ctx) => {
|
|
372
324
|
if (!running) {
|
|
373
|
-
ctx.ui.notify("pi-qq
|
|
325
|
+
ctx.ui.notify("pi-qq is not connected.", "warning");
|
|
374
326
|
return;
|
|
375
327
|
}
|
|
376
328
|
const last = budget.lastTarget;
|
|
377
329
|
if (!last) {
|
|
378
|
-
ctx.ui.notify("pi-qq
|
|
330
|
+
ctx.ui.notify("pi-qq: send a QQ message first (streaming needs a msgId).", "warning");
|
|
379
331
|
return;
|
|
380
332
|
}
|
|
381
333
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
382
334
|
try {
|
|
383
335
|
const stream = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
|
|
384
|
-
await stream.append("
|
|
336
|
+
await stream.append("[💭] Thinking...\n[🔧] [3] bash\n[🔧] [2] read\n");
|
|
385
337
|
await sleep(1200);
|
|
386
|
-
await stream.append("\n
|
|
338
|
+
await stream.append("\n**Intermediate message**: first-turn reply.\n");
|
|
387
339
|
await sleep(1200);
|
|
388
|
-
await stream.append("[1]
|
|
340
|
+
await stream.append("[🔧] [1] edit\n");
|
|
389
341
|
await sleep(800);
|
|
390
|
-
await stream.append("\n
|
|
391
|
-
let doneNote = "DONE
|
|
342
|
+
await stream.append("\n**Final reply** (streamed append)");
|
|
343
|
+
let doneNote = "DONE succeeded";
|
|
392
344
|
try {
|
|
393
345
|
await stream.done();
|
|
394
346
|
} catch (doneErr) {
|
|
395
|
-
doneNote = `DONE
|
|
347
|
+
doneNote = `DONE rejected: ${(doneErr as Error).message}`;
|
|
396
348
|
}
|
|
397
|
-
ctx.ui.notify(
|
|
349
|
+
ctx.ui.notify(`Stream timeline test: frames sent, ${doneNote}. Check the QQ activity timeline.`, "info");
|
|
398
350
|
} catch (err) {
|
|
399
|
-
ctx.ui.notify(
|
|
351
|
+
ctx.ui.notify(`Stream timeline test failed: ${(err as Error).message}`, "error");
|
|
400
352
|
}
|
|
401
353
|
},
|
|
402
354
|
});
|
package/package.json
CHANGED
package/src/append-stream.ts
CHANGED
|
@@ -7,16 +7,17 @@ import type {
|
|
|
7
7
|
} from "@tencent-connect/qqbot-nodejs/protocol";
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
10
|
+
* Minimal append-mode (input_mode="append") stream sender.
|
|
11
11
|
*
|
|
12
|
-
* SDK
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* The SDK StreamSession hardcodes input_mode="replace"; in 2026-10 the platform
|
|
13
|
+
* rejected it with "submitted message content cannot be modified". In append mode
|
|
14
|
+
* each content_raw frame carries only the **new** text, matching the platform rule
|
|
15
|
+
* that already-submitted content is immutable.
|
|
15
16
|
*
|
|
16
|
-
*
|
|
17
|
-
* 1.
|
|
18
|
-
*
|
|
19
|
-
* 2.
|
|
17
|
+
* Two built-in safeguards (aligned with SDK StreamSession best practices):
|
|
18
|
+
* 1. Throttle: token increments are buffered and merged into frames per throttle
|
|
19
|
+
* window (default 500ms, minimum 300ms) to avoid flooding the API.
|
|
20
|
+
* 2. Rate-limit backoff: 429 / err_code 50002 retry exponentially (1s→2s→4s, max 3).
|
|
20
21
|
*/
|
|
21
22
|
|
|
22
23
|
const MIN_INTERVAL_MS = 300;
|
|
@@ -24,13 +25,13 @@ const RATE_LIMIT_BASE_MS = 1000;
|
|
|
24
25
|
const MAX_RETRIES = 3;
|
|
25
26
|
|
|
26
27
|
export interface AppendStreamOptions {
|
|
27
|
-
/**
|
|
28
|
+
/** Minimum interval between frames; increments are merged during the window. */
|
|
28
29
|
throttleMs?: number;
|
|
29
|
-
/**
|
|
30
|
+
/** Rate-limit backoff base in ms (for tests). */
|
|
30
31
|
retryBaseMs?: number;
|
|
31
|
-
/**
|
|
32
|
+
/** Background throttle flush failure (stream is no longer trusted). */
|
|
32
33
|
onError?: (err: Error) => void;
|
|
33
|
-
/**
|
|
34
|
+
/** Diagnostic log (debug mode): rate-limit retries/final failures. */
|
|
34
35
|
onDebug?: (message: string) => void;
|
|
35
36
|
}
|
|
36
37
|
|
|
@@ -56,12 +57,12 @@ export class AppendStream {
|
|
|
56
57
|
return Math.max(this.opts.throttleMs ?? 500, MIN_INTERVAL_MS);
|
|
57
58
|
}
|
|
58
59
|
|
|
59
|
-
/**
|
|
60
|
+
/** Append text; frames are merged by throttle window and sent in the background. */
|
|
60
61
|
async append(delta: string): Promise<void> {
|
|
61
62
|
if (this.doneSent || !delta) return;
|
|
62
63
|
this.buffer += delta;
|
|
63
64
|
const elapsed = Date.now() - this.lastFlushAt;
|
|
64
|
-
if (this.flushing) return; //
|
|
65
|
+
if (this.flushing) return; // The in-flight flush trailing logic will pick up the buffer.
|
|
65
66
|
if (elapsed >= this.throttleMs()) {
|
|
66
67
|
await this.doFlush("generating");
|
|
67
68
|
return;
|
|
@@ -74,7 +75,7 @@ export class AppendStream {
|
|
|
74
75
|
}
|
|
75
76
|
}
|
|
76
77
|
|
|
77
|
-
/**
|
|
78
|
+
/** Flush remaining text and send DONE. Errors propagate to the caller. */
|
|
78
79
|
async done(): Promise<void> {
|
|
79
80
|
if (this.doneSent) return;
|
|
80
81
|
if (this.flushTimer) {
|
|
@@ -85,11 +86,11 @@ export class AppendStream {
|
|
|
85
86
|
await new Promise((r) => setTimeout(r, 20));
|
|
86
87
|
}
|
|
87
88
|
if (this.buffer) await this.doFlush("generating");
|
|
88
|
-
await this.doFlush("done"); // DONE
|
|
89
|
+
await this.doFlush("done"); // DONE frames carry empty content_raw (verified).
|
|
89
90
|
this.doneSent = true;
|
|
90
91
|
}
|
|
91
92
|
|
|
92
|
-
/**
|
|
93
|
+
/** Stop background timers only; no DONE (for shutdown/error paths). */
|
|
93
94
|
dispose(): void {
|
|
94
95
|
if (this.flushTimer) {
|
|
95
96
|
clearTimeout(this.flushTimer);
|
|
@@ -101,13 +102,13 @@ export class AppendStream {
|
|
|
101
102
|
private async doFlush(state: "generating" | "done"): Promise<void> {
|
|
102
103
|
if (this.flushing) return;
|
|
103
104
|
const content = state === "done" ? "" : this.buffer;
|
|
104
|
-
// DONE
|
|
105
|
+
// DONE frames may be empty (generation finished); empty generating frames are skipped.
|
|
105
106
|
if (!content && state === "generating") return;
|
|
106
107
|
this.flushing = true;
|
|
107
108
|
let failed = false;
|
|
108
109
|
try {
|
|
109
110
|
if (this.msgSeq === null) this.msgSeq = getNextMsgSeq(this.msgId);
|
|
110
|
-
// input_mode
|
|
111
|
+
// input_mode is outside the SDK type (replace only); the platform defines its runtime meaning.
|
|
111
112
|
const req = {
|
|
112
113
|
input_mode: "append",
|
|
113
114
|
input_state: state === "done" ? StreamInputState.DONE : StreamInputState.GENERATING,
|
|
@@ -128,7 +129,7 @@ export class AppendStream {
|
|
|
128
129
|
throw err;
|
|
129
130
|
} finally {
|
|
130
131
|
this.flushing = false;
|
|
131
|
-
//
|
|
132
|
+
// Trailing: new data arrived during flush; schedule the next frame.
|
|
132
133
|
if (!failed && state === "generating" && this.buffer && !this.doneSent && !this.flushTimer) {
|
|
133
134
|
this.flushTimer = setTimeout(() => {
|
|
134
135
|
this.flushTimer = null;
|