@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/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, formatUsageSummary, sumUsageMessages, type UsageTotals } from "./src/usage";
10
+ import { formatTokenCount } from "./src/format";
19
11
  import { formatBudgetStatus } from "./src/budget-status";
20
12
 
21
13
  /**
22
- * pi-qq 扩展入口:
23
- * - M1:登录接入(配置直连 / 扫码)、/qq-login /qq-status /qq-logout、生命周期
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
- /** 会话级状态;reload/会话切换后由新 runtime 重建 */
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: () => readConfig().config.allowedOpenid,
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: readConfig().config.allowedOpenid ?? "",
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 ? "未知" : formatTokenCount(n));
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 = () => readConfig().config.allowedOpenid;
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 { config } = readConfig();
74
+ const login = getLoginState();
91
75
  const usage = sessionCtx?.getContextUsage();
92
76
  const model = sessionCtx?.model;
93
77
  return [
94
- "pi-qq 状态",
95
- `连接:${lastState}${stateDetail ? `(${stateDetail})` : ""}`,
96
- `模型:${model?.name ?? "未选择"}`,
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
- ? `上下文:${fmtTokens(usage.tokens)}/${fmtTokens(usage.contextWindow)}(${usage.percent?.toFixed(1) ?? "?"}%)`
99
- : "上下文:未知",
100
- `绑定用户:${config.allowedOpenid ?? "未绑定(首个私聊用户将自动绑定)"}`,
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
- // —— 登录与连接(M1)——
90
+ // —— Login and connection ——
105
91
 
106
- const startWithCredentials = (ctx: ExtensionContext, creds: Credentials, config: PiQQConfig, source: string) => {
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: config.allowedOpenid,
113
- markdownSupport: config.markdownSupport,
114
- debug: config.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
- // 只对用户需要知道的状态发通知;reconnecting 高频且 SDK 会自愈,不打扰
132
- if (state === "connected") ctx.ui.notify(`pi-qq 已连接(${source})`, "info");
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
- // 可恢复错误由 SDK 自动重连;长时间故障约每分钟一次,M1 不告警
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 { config, error } = readConfig();
152
- if (error) {
153
- ctx.ui.notify(`pi-qq ${error}`, "error");
154
- return;
155
- }
156
- const creds = getCredentials(config);
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
- // —— F7 run 级反馈:agent 生命周期 / 工具计数 / 文本流式 ——
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", (event, ctx) => {
180
- const lastAssistant = [...event.messages].reverse().find((message) => message.role === "assistant");
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
- // —— pi → QQ:assistant 消息回传(非流式路径 + F7 流接管)——
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
- // 无文本的 assistant 消息同样结束本轮反馈状态:重置 thinking 标记/快照,
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 流接管:流式帧按 markdown 渲染(实测表格/代码块正常),传原始文本保证增量长度一致
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 = config.allowedOpenid;
219
+ const bound = getLoginState()?.allowedOpenid;
252
220
  if (!bound) {
253
- ctx.ui.notify("pi-qq:未绑定用户,跳过回传", "warning");
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
- // —— 命令(M1)——
232
+ // —— Commands ——
265
233
 
266
234
  pi.registerCommand("qq-login", {
267
- description: "pi-qq:扫码登录/换绑 QQ 机器人(凭据写入 ~/.pi/agent/pi-qq.json)",
235
+ description: "pi-qq: log in with a QR code and bind the scanning QQ user",
268
236
  handler: async (_args, ctx) => {
269
- const { config, error } = readConfig();
270
- if (error) {
271
- ctx.ui.notify(`pi-qq ${error}`, "error");
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
- if (getCredentials(config) && running) {
275
- stopIfRunning();
276
- ctx.ui.notify("已断开当前连接,开始扫码换绑…", "info");
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
- const { config, error } = readConfig();
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
- clearCredentials();
319
- ctx.ui.notify("pi-qq 已断开并清除凭据(绑定与设置保留)", "info");
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:重置当前会话(供 QQ 侧 /new 调用)",
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("任务运行中,无法重置会话;请先 /stop", "warning");
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("会话重置已取消", "warning");
286
+ if (cancelled) ctx.ui.notify("pi-qq: session reset cancelled.", "warning");
332
287
  },
333
288
  });
334
289
 
335
- // —— 诊断命令(markdown / 流式能力实证)——
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 = readConfig().config.allowedOpenid;
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 诊断:发送一条 Markdown 消息(验证 C2C markdown 渲染能力)",
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 未连接", "warning");
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:无可用发送目标(请先在 QQ 发一条消息,或配置 allowedOpenid)", "warning");
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 测试**\n# 一级标题\n- 列表项一\n- 列表项二\n[链接](https://qq.com)";
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 发送失败:${(err as Error).message}`, "error");
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-test", {
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 未连接", "warning");
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:请先在 QQ 给机器人发一条消息(流式需要锚定 msgId)", "warning");
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("思考中...\n[3] 🔧 bash\n[2] 🔧 read\n");
336
+ await stream.append("[💭] Thinking...\n[🔧] [3] bash\n[🔧] [2] read\n");
385
337
  await sleep(1200);
386
- await stream.append("\n**中间消息原文**:第一回合回复。\n");
338
+ await stream.append("\n**Intermediate message**: first-turn reply.\n");
387
339
  await sleep(1200);
388
- await stream.append("[1] 🔧 edit\n");
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 帧被拒:${(doneErr as Error).message}`;
347
+ doneNote = `DONE rejected: ${(doneErr as Error).message}`;
396
348
  }
397
- ctx.ui.notify(`时间线流式测试:各帧成功、${doneNote}。请看 QQ:气泡应为 💭/🔧/消息文本 的时间线形态`, "info");
349
+ ctx.ui.notify(`Stream timeline test: frames sent, ${doneNote}. Check the QQ activity timeline.`, "info");
398
350
  } catch (err) {
399
- ctx.ui.notify(`汇总帧测试失败:${(err as Error).message}`, "error");
351
+ ctx.ui.notify(`Stream timeline test failed: ${(err as Error).message}`, "error");
400
352
  }
401
353
  },
402
354
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.0.0",
4
- "description": "pi 扩展:通过 QQ 机器人把 pi 接入 QQ 单人私聊(C2C)",
3
+ "version": "1.0.2",
4
+ "description": "Connect pi to QQ private chats.",
5
5
  "license": "MIT",
6
6
  "author": "CQ-Developer",
7
7
  "repository": {
@@ -7,16 +7,17 @@ import type {
7
7
  } from "@tencent-connect/qqbot-nodejs/protocol";
8
8
 
9
9
  /**
10
- * 追加模式(input_mode="append")的最小流式发送器。
10
+ * Minimal append-mode (input_mode="append") stream sender.
11
11
  *
12
- * SDK 内置 StreamSession 硬编码 input_mode="replace",2026-10 实测平台返回
13
- * 「已经提交的消息内容不可修改」拒绝 replace。追加语义下每帧 content_raw
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
- * 内建两项保护(对齐 SDK StreamSession 的最佳实践):
17
- * 1. 节流:token 级增量先入缓冲,按节流窗口(默认 500ms,最小 300ms)合并成帧,
18
- * 避免高频 message_update 打爆 API。
19
- * 2. 限流退避:429 / err_code 50002 按指数退避重试(1s→2s→4s,最多 3 次)。
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
- /** 限流退避基数(ms),测试用 */
30
+ /** Rate-limit backoff base in ms (for tests). */
30
31
  retryBaseMs?: number;
31
- /** 后台节流 flush 失败回调(此时流已不可信,调用方应标记降级) */
32
+ /** Background throttle flush failure (stream is no longer trusted). */
32
33
  onError?: (err: Error) => void;
33
- /** 诊断日志(debug 模式):限流重试/最终失败 */
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; // 在途 flush 的 trailing 逻辑会接手缓冲
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
- /** 发送剩余增量并收尾(DONE 帧)。错误向上抛给调用方。 */
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 帧 content_raw 为空(已实测接受)
89
+ await this.doFlush("done"); // DONE frames carry empty content_raw (verified).
89
90
  this.doneSent = true;
90
91
  }
91
92
 
92
- /** 仅停止后台定时器(不发送 DONE;用于会话关闭等异常路径) */
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 帧允许空内容(表示生成结束),generating 无内容则无需发送
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 超出 SDK 类型定义(仅 replace),运行时值由平台语义决定
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
- // trailing:flush 期间又有新增量 → 排下一帧
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;