@chen_hu_hu/pi-qq 1.3.2 → 1.3.4

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.
@@ -0,0 +1,112 @@
1
+ import type { PowerStatus } from "../infra/power-status";
2
+ import { formatTokenCount } from "../infra/display-format";
3
+ import { t, type TranslationKey } from "../infra/i18n";
4
+ import type { BotState } from "./qq-bot";
5
+
6
+ export interface StatusReportInput {
7
+ login?: { appId: string; openid: string };
8
+ connection: { state: BotState; detail?: string };
9
+ agent: { running: boolean; qq: boolean };
10
+ model?: { name: string };
11
+ usage?: { tokens: number | null; contextWindow: number | null; percent?: number | null };
12
+ power?: PowerStatus;
13
+ }
14
+
15
+ const STATE_ICONS: Record<BotState, string> = {
16
+ connected: "🌐",
17
+ reconnecting: "🔄",
18
+ stopped: "⛔",
19
+ starting: "⏳",
20
+ blocked: "🚫",
21
+ };
22
+
23
+ const STATE_LABELS: Record<BotState, TranslationKey> = {
24
+ connected: "status.state.connected",
25
+ reconnecting: "status.state.reconnecting",
26
+ stopped: "status.state.stopped",
27
+ starting: "status.state.starting",
28
+ blocked: "status.state.blocked",
29
+ };
30
+
31
+ function maskAppId(appId: string): string {
32
+ return `${appId.slice(0, 4)}****`;
33
+ }
34
+
35
+ function maskOpenid(openid: string): string {
36
+ return `${openid.slice(0, 8)}…`;
37
+ }
38
+
39
+ function label(
40
+ key:
41
+ | "status.agent"
42
+ | "status.context"
43
+ | "status.model"
44
+ | "status.login"
45
+ | "status.connection"
46
+ | "status.qqUser"
47
+ | "status.battery"
48
+ | "status.settings",
49
+ value: string,
50
+ ): string {
51
+ return `${t(key)}${t("status.separator")}${value}`;
52
+ }
53
+
54
+ function agentLine(agent: StatusReportInput["agent"]): string {
55
+ if (!agent.running) return `✅ ${label("status.agent", t("status.agent.completed"))}`;
56
+ const value = agent.qq ? t("status.agent.runningQQ") : t("status.agent.runningLocal");
57
+ return `🏃 ${label("status.agent", value)}`;
58
+ }
59
+
60
+ function contextLine(usage: StatusReportInput["usage"]): string {
61
+ if (!usage) return `📊 ${label("status.context", t("status.unknown"))}`;
62
+ const percent = usage.percent?.toFixed(1) ?? "?";
63
+ const tokens = usage.tokens === null ? t("status.unknown") : formatTokenCount(usage.tokens);
64
+ const window = usage.contextWindow === null ? t("status.unknown") : formatTokenCount(usage.contextWindow);
65
+ return `📊 ${label("status.context", t("status.contextValue", { tokens, window, percent }))}`;
66
+ }
67
+
68
+ function batteryLine(power: PowerStatus | undefined): string | undefined {
69
+ if (!power) return undefined;
70
+ const icon = power.state === "charging" ? "🔌" : power.state === "discharging" ? "🔋" : "⚡";
71
+ const value =
72
+ power.percent === undefined
73
+ ? t(
74
+ power.state === "charging"
75
+ ? "status.batteryChargingNoPercent"
76
+ : power.state === "discharging"
77
+ ? "status.batteryDischargingNoPercent"
78
+ : "status.batteryAcNoPercent",
79
+ )
80
+ : t(
81
+ power.state === "charging"
82
+ ? "status.batteryCharging"
83
+ : power.state === "discharging"
84
+ ? "status.batteryDischarging"
85
+ : "status.batteryAc",
86
+ { percent: power.percent },
87
+ );
88
+ return `${icon} ${label("status.battery", value)}`;
89
+ }
90
+
91
+ export function formatStatusReport(input: StatusReportInput): string[] {
92
+ const stateLabel = t(STATE_LABELS[input.connection.state]);
93
+ const detail = input.connection.detail ? t("status.detail", { detail: input.connection.detail }) : "";
94
+ const loginLine = input.login
95
+ ? `🔐 ${label("status.login", t("status.loginValue", { appId: maskAppId(input.login.appId) }))}`
96
+ : `⚪ ${label("status.login", t("status.notLoggedIn"))}`;
97
+
98
+ const lines = [
99
+ `🖥️ ${t("status.title")}`,
100
+ loginLine,
101
+ `${STATE_ICONS[input.connection.state]} ${label("status.connection", `${stateLabel}${detail}`)}`,
102
+ agentLine(input.agent),
103
+ `🧠 ${label("status.model", input.model?.name ?? t("status.none"))}`,
104
+ contextLine(input.usage),
105
+ `👤 ${label("status.qqUser", input.login ? maskOpenid(input.login.openid) : t("status.none"))}`,
106
+ ];
107
+
108
+ const battery = batteryLine(input.power);
109
+ if (battery) lines.push(battery);
110
+ lines.push(`⚙️ ${label("status.settings", "~/.pi/agent/pi-qq.json")}`);
111
+ return lines;
112
+ }
@@ -1,3 +1,4 @@
1
+ import { t } from "../infra/i18n";
1
2
  import type { BudgetSnapshot } from "./reply-quota";
2
3
 
3
4
  interface BudgetTarget {
@@ -18,14 +19,41 @@ export function formatBudgetStatus(
18
19
  const ageSec = last ? Math.max(0, Math.floor((now - last.arrivedAt) / 1000)) : null;
19
20
  const estimated = snapshot.hasTarget ? Math.max(0, snapshot.remaining - snapshot.streamBubbles) : null;
20
21
 
22
+ const lastLine = last
23
+ ? t("diagnostics.budget.lastInbound", {
24
+ openid: mask(last.openid),
25
+ msgId: mask(last.msgId),
26
+ age: ageSec ?? 0,
27
+ })
28
+ : t("diagnostics.budget.lastInboundNone");
29
+
30
+ const remainingLine = snapshot.hasTarget
31
+ ? t("diagnostics.budget.passiveRemaining", { remaining: snapshot.remaining })
32
+ : t("diagnostics.budget.passiveRemainingNone");
33
+
34
+ const estimatedLine =
35
+ estimated === null
36
+ ? t("diagnostics.budget.estimatedNone")
37
+ : t("diagnostics.budget.estimated", { remaining: estimated });
38
+
39
+ const windowLine = snapshot.hasTarget
40
+ ? t("diagnostics.budget.window", {
41
+ window: snapshot.fresh ? t("diagnostics.budget.valid") : t("diagnostics.budget.expired"),
42
+ })
43
+ : t("diagnostics.budget.windowNone");
44
+
21
45
  return [
22
- "pi-qq passive reply budget",
23
- `Limit: ${snapshot.limit}/msg (${snapshot.ttlHours}h)`,
24
- `Last inbound: ${last ? `${mask(last.openid)} / ${mask(last.msgId)}, ${ageSec}s ago` : "none"}`,
25
- `Passive remaining: ${snapshot.hasTarget ? snapshot.remaining : "—"}`,
26
- `Stream bubbles: ${snapshot.streamBubbles} (current msgId)`,
27
- `Estimated remaining: ${estimated ?? "—"} (diagnostic only)`,
28
- `msgId window: ${snapshot.hasTarget ? (snapshot.fresh ? "valid" : "expired") : "—"}`,
29
- `Recorded: passive ${snapshot.totalReplies} / stream ${snapshot.streamBubblesTotal} / ${snapshot.trackedMessages} msgId(s)`,
46
+ t("diagnostics.budget.title"),
47
+ t("diagnostics.budget.limit", { limit: snapshot.limit, hours: snapshot.ttlHours }),
48
+ lastLine,
49
+ remainingLine,
50
+ t("diagnostics.budget.streamBubbles", { count: snapshot.streamBubbles }),
51
+ estimatedLine,
52
+ windowLine,
53
+ t("diagnostics.budget.recorded", {
54
+ passive: snapshot.totalReplies,
55
+ stream: snapshot.streamBubblesTotal,
56
+ tracked: snapshot.trackedMessages,
57
+ }),
30
58
  ];
31
59
  }
@@ -2,7 +2,8 @@ import type { QQBot } from "@tencent-connect/qqbot-nodejs";
2
2
  import { AppendStream, type AppendStreamCheckpoint } from "./stream-session";
3
3
  import type { ReplyBudget } from "../quota/reply-quota";
4
4
  import { log } from "../infra/file-logger";
5
- import { THINKING_HEADER, formatToolLine, formatToolResult } from "./stream-block-format";
5
+ import { formatToolLine, formatToolResult, thinkingHeader } from "./stream-block-format";
6
+ import { t } from "../infra/i18n";
6
7
 
7
8
  type BlockKind = "none" | "thinking" | "tool" | "text";
8
9
 
@@ -93,6 +94,37 @@ export class BubbleWriter {
93
94
  });
94
95
  }
95
96
 
97
+ /**
98
+ * Start a fresh bubble and push the current text again, reviving a stream
99
+ * that died while the phone was offline. Later deltas continue in this bubble.
100
+ */
101
+ restartText(text: string, target?: { openid: string; msgId: string }): void {
102
+ if (!text || this.disposed) return;
103
+ void this.enqueue(async () => {
104
+ if (this.disposed) return;
105
+ if (this.fenceOpen) await this.closeOpenFence();
106
+ if (this.cur) await this.rotateStream();
107
+
108
+ if (target) {
109
+ this.deps.openid = target.openid;
110
+ this.deps.msgId = target.msgId;
111
+ }
112
+ this.streamDead = false;
113
+ this.pendingResume = undefined;
114
+ this.resumeAttempts = 0;
115
+ this.lastKind = "none";
116
+ this.blockClosed = false;
117
+ this.toolOpen = false;
118
+ this.fenceOpen = false;
119
+ this.fenceLen = 0;
120
+ this.fenceQuoted = false;
121
+ this.lastChar = "";
122
+ this.thinkingAtLineStart = true;
123
+ this.bubbleChars = 0;
124
+ this.pushText(text);
125
+ });
126
+ }
127
+
96
128
  async whenIdle(): Promise<void> {
97
129
  await this.drainQueue();
98
130
  }
@@ -205,7 +237,7 @@ export class BubbleWriter {
205
237
  const stream = this.ensureStream();
206
238
  if (!stream) return;
207
239
  this.pushedAny = true;
208
- const outgoing = thinking && (!this.cur || this.bubbleChars === 0) ? `${THINKING_HEADER}${text}` : text;
240
+ const outgoing = thinking && (!this.cur || this.bubbleChars === 0) ? `${thinkingHeader()}${text}` : text;
209
241
  try {
210
242
  await stream.append(outgoing);
211
243
  this.bubbleChars += outgoing.length;
@@ -333,6 +365,6 @@ export class BubbleWriter {
333
365
  this.cur?.dispose();
334
366
  this.cur = null;
335
367
  log.warn("stream", "stream unavailable", { msgId: this.logMsgId(), reason });
336
- this.deps.onWarn(`Stream unavailable; falling back to text (${reason}).`);
368
+ this.deps.onWarn(t("stream.unavailable", { reason }));
337
369
  }
338
370
  }
@@ -25,6 +25,8 @@ interface RunState {
25
25
  msgId?: string;
26
26
  thinkingSentLen: number;
27
27
  finalizedText: string;
28
+ /** Latest text of the current run, kept for the QQ /last command. */
29
+ currentText: string;
28
30
  resultSentLen: number;
29
31
  tools: ToolCall[];
30
32
  activeTool?: string;
@@ -49,6 +51,7 @@ export class RunFeedback {
49
51
  private pending: { openid: string; msgId: string; at: number } | null = null;
50
52
  private recovery: { openid: string; msgId: string; at: number } | null = null;
51
53
  private run: RunState | null = null;
54
+ private lastCompletedText: string | undefined;
52
55
  private endPromise: Promise<void> = Promise.resolve();
53
56
  private endResolve?: () => void;
54
57
 
@@ -73,6 +76,32 @@ export class RunFeedback {
73
76
  return this.run ? this.endPromise : Promise.resolve();
74
77
  }
75
78
 
79
+ /**
80
+ * The final assistant text of the most recently completed QQ run.
81
+ * No transcript is retained.
82
+ */
83
+ getLastMessage(): string | undefined {
84
+ return this.lastCompletedText;
85
+ }
86
+
87
+ /**
88
+ * Restart the current run's push with its latest text. This revives a stream
89
+ * that may have died while the phone was offline; later deltas continue.
90
+ */
91
+ repushCurrent(openid: string, msgId: string): boolean {
92
+ const run = this.run;
93
+ const text = run?.currentText;
94
+ if (!run || !text?.trim()) return false;
95
+ // Rebind to the /last message so the new stream has a fresh passive window.
96
+ run.openid = openid;
97
+ run.msgId = msgId;
98
+ // Push the current text in full. Do not rewrite resultSentLen: it belongs to
99
+ // the assistant message currently being diffed, and changing it could drop
100
+ // the beginning of the next message.
101
+ run.writer.restartText(text, { openid, msgId });
102
+ return true;
103
+ }
104
+
76
105
  onAgentStart(): void {
77
106
  this.endPromise = new Promise((resolve) => {
78
107
  this.endResolve = resolve;
@@ -105,6 +134,7 @@ export class RunFeedback {
105
134
  msgId: target.msgId,
106
135
  thinkingSentLen: 0,
107
136
  finalizedText: "",
137
+ currentText: "",
108
138
  resultSentLen: 0,
109
139
  tools: [],
110
140
  deferredThinking: "",
@@ -113,7 +143,7 @@ export class RunFeedback {
113
143
  writer,
114
144
  };
115
145
  this.run = run;
116
- log.debug("run", "started", { msgId: run.msgId?.slice(0, 8) ?? "?" });
146
+ log.debug("run", "run started", { msgId: run.msgId?.slice(0, 8) ?? "?" });
117
147
 
118
148
  const keepTyping = () => {
119
149
  void bot.sendTyping({ scope: "c2c", targetId: run.openid }, 60).catch(() => {});
@@ -143,21 +173,25 @@ export class RunFeedback {
143
173
 
144
174
  onAssistantDelta(snapshotText: string, snapshotThinking: string): void {
145
175
  const run = this.run;
146
- if (!run || run.writer.dead) return;
176
+ if (!run) return;
177
+
178
+ const full = [run.finalizedText, snapshotText].filter((part) => part.trim()).join("\n\n");
179
+ if (full.trim()) run.currentText = full;
180
+
181
+ if (run.writer.dead) return;
147
182
 
148
183
  if (snapshotThinking.length > run.thinkingSentLen) {
149
- const delta = snapshotThinking.slice(run.thinkingSentLen);
184
+ const thinkingDelta = snapshotThinking.slice(run.thinkingSentLen);
150
185
  run.thinkingSentLen = snapshotThinking.length;
151
186
  if (this.deps.getThinkingRelay()) {
152
187
  if (this.hasPendingTools(run)) {
153
- run.deferredThinking += delta;
188
+ run.deferredThinking += thinkingDelta;
154
189
  } else {
155
- run.writer.pushThinking(delta);
190
+ run.writer.pushThinking(thinkingDelta);
156
191
  }
157
192
  }
158
193
  }
159
194
 
160
- const full = [run.finalizedText, snapshotText].filter((part) => part.trim()).join("\n\n");
161
195
  const delta = full.slice(run.resultSentLen);
162
196
  if (!delta) return;
163
197
  run.resultSentLen = full.length;
@@ -173,6 +207,7 @@ export class RunFeedback {
173
207
  if (!run) return false;
174
208
 
175
209
  run.finalizedText = [run.finalizedText, text].filter((part) => part.trim()).join("\n\n");
210
+ if (text.trim()) run.currentText = text;
176
211
  const delta = run.finalizedText.slice(run.resultSentLen);
177
212
  run.resultSentLen = run.finalizedText.length;
178
213
  if (!isError && text && delta) {
@@ -207,9 +242,10 @@ export class RunFeedback {
207
242
  if (!this.hasPendingTools(run)) this.flushDeferred(run);
208
243
  await run.writer.whenIdle();
209
244
  this.clearTimers();
245
+ if (run.currentText.trim()) this.lastCompletedText = run.currentText;
210
246
  if (!run.hadError && run.writer.hasPushed) this.recovery = null;
211
247
  this.run = null;
212
- log.debug("run", "ended", {
248
+ log.debug("run", "run ended", {
213
249
  msgId: run.msgId?.slice(0, 8) ?? "?",
214
250
  elapsedMs: Date.now() - run.startedAt,
215
251
  });
@@ -230,6 +266,7 @@ export class RunFeedback {
230
266
  this.run = null;
231
267
  this.pending = null;
232
268
  this.recovery = null;
269
+ this.lastCompletedText = undefined;
233
270
  this.finishEnd();
234
271
  }
235
272
 
@@ -1,4 +1,8 @@
1
- export const THINKING_HEADER = "**💭 思考**\n\n";
1
+ import { t } from "../infra/i18n";
2
+
3
+ export function thinkingHeader(): string {
4
+ return `**💭 ${t("stream.thinking")}**\n\n`;
5
+ }
2
6
  const ARG_MAX_CHARS = 200;
3
7
  const RESULT_MAX_CHARS = 600;
4
8
  const RESULT_MAX_LINES = 8;
@@ -109,7 +113,7 @@ function resultText(result: unknown): string {
109
113
  export function formatToolResult(result: unknown, isError: boolean): string {
110
114
  let text = resultText(result);
111
115
  text = text.replace(/\r\n/g, "\n").replace(/\s+$/, "");
112
- if (!text) text = "(no output)";
116
+ if (!text) text = t("stream.noOutput");
113
117
  text = truncateText(text, RESULT_MAX_CHARS, RESULT_MAX_LINES);
114
118
  if (isError) text = `❌ ${text}`;
115
119
  const fence = backtickFence(text, 3);
@@ -1,4 +1,5 @@
1
1
  import { getNextMsgSeq, StreamContentType, StreamInputState } from "@tencent-connect/qqbot-nodejs/protocol";
2
+ import { t } from "../infra/i18n";
2
3
  import type {
3
4
  Credentials,
4
5
  MessageApi,
@@ -164,13 +165,11 @@ export class AppendStream {
164
165
  } catch (err) {
165
166
  const reason = err instanceof Error ? err.message : String(err);
166
167
  if (attempt >= MAX_RETRIES || !this.isRateLimitError(err)) {
167
- this.opts.onDebug?.(`frame index=${req.index} failed after ${attempt + 1} attempt(s): ${reason}`);
168
+ this.opts.onDebug?.(t("log.streamFrameFailed", { index: req.index, attempts: attempt + 1, reason }));
168
169
  throw err;
169
170
  }
170
171
  const delay = base * 2 ** attempt;
171
- this.opts.onDebug?.(
172
- `frame index=${req.index} rate limited (attempt ${attempt + 1}), retry in ${delay}ms: ${reason}`,
173
- );
172
+ this.opts.onDebug?.(t("log.streamFrameRateLimited", { index: req.index, attempt: attempt + 1, delay, reason }));
174
173
  await new Promise((r) => setTimeout(r, delay));
175
174
  }
176
175
  }