@chen_hu_hu/pi-qq 1.2.3 → 1.3.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/README-zh.md +76 -46
- package/README.md +79 -49
- package/doc/delivery-v1-zh.md +160 -0
- package/doc/delivery-v1.md +160 -0
- package/doc/delivery-v2-zh.md +100 -0
- package/doc/delivery-v2.md +98 -0
- package/doc/delivery-v3-zh.md +189 -0
- package/doc/delivery-v3.md +189 -0
- package/index.ts +66 -156
- package/package.json +6 -3
- package/src/{download.ts → attachments/attachment-download.ts} +1 -4
- package/src/attachments/attachment-failure.ts +12 -0
- package/src/{files.ts → attachments/file-attachments.ts} +19 -33
- package/src/{voice.ts → attachments/voice-transcript.ts} +1 -7
- package/src/{format.ts → infra/display-format.ts} +0 -2
- package/src/{logger.ts → infra/file-logger.ts} +6 -31
- package/src/infra/settings.ts +103 -0
- package/src/{bot.ts → qq/qq-bot.ts} +6 -31
- package/src/qq/qq-diagnostics.ts +129 -0
- package/src/{inbound.ts → qq/qq-message-handler.ts} +58 -94
- package/src/{login.ts → qq/qr-login.ts} +24 -17
- package/src/{outbound.ts → qq/reply-sender.ts} +7 -37
- package/src/qrcode-terminal.d.ts +0 -2
- package/src/{budget-status.ts → quota/reply-quota-report.ts} +2 -3
- package/src/{reply-budget.ts → quota/reply-quota.ts} +0 -21
- package/src/relay/run-stream-relay.ts +576 -0
- package/src/relay/stream-block-format.ts +117 -0
- package/src/{append-stream.ts → relay/stream-session.ts} +46 -29
- package/doc/features-v1.md +0 -239
- package/doc/features-v2.md +0 -210
- package/doc/plan-v1.md +0 -190
- package/doc/plan-v2.md +0 -332
- package/src/config.ts +0 -82
- package/src/images.ts +0 -149
- package/src/run-feedback.ts +0 -409
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
# pi-qq delivery-v3
|
|
2
|
+
|
|
3
|
+
> Status: v3 implemented and the main path has been verified on real QQ. Final details such as long-list splitting and recovery edge cases still need one complete pass on the target client.
|
|
4
|
+
> Note: later changes removed the image-specific pipeline; images now use the same save/pending path as files. See [README](../README.md) for current behavior.
|
|
5
|
+
> Previous: [delivery-v1.md](./delivery-v1.md), [delivery-v2.md](./delivery-v2.md).
|
|
6
|
+
|
|
7
|
+
## 1. Scope
|
|
8
|
+
|
|
9
|
+
v3 consolidates long-run relay and configuration:
|
|
10
|
+
|
|
11
|
+
- F12: event-driven relay of thinking, tools, and text by content block;
|
|
12
|
+
- F13: remove message heartbeats;
|
|
13
|
+
- F14: consolidate settings.
|
|
14
|
+
|
|
15
|
+
## 2. Output model
|
|
16
|
+
|
|
17
|
+
### 2.1 One bubble per content block
|
|
18
|
+
|
|
19
|
+
In chronological order:
|
|
20
|
+
|
|
21
|
+
1. thinking block;
|
|
22
|
+
2. each tool call + result;
|
|
23
|
+
3. text block;
|
|
24
|
+
4. final message.
|
|
25
|
+
|
|
26
|
+
While tools are pending, later thinking/text is deferred so it cannot appear between two tool bubbles. Parallel tools are shown one at a time in start order; results are correlated by `toolCallId`.
|
|
27
|
+
|
|
28
|
+
### 2.2 Thinking format
|
|
29
|
+
|
|
30
|
+
The first line of every thinking bubble:
|
|
31
|
+
|
|
32
|
+
```text
|
|
33
|
+
**💭 思考**
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The body is plain text with no `>` quote prefix; blank lines and newlines are preserved. At the 12k safety boundary the relay starts a new bubble and repeats the header.
|
|
37
|
+
|
|
38
|
+
Blockquotes are not used because QQ renders single-line/blank-line quote blocks as unsupported messages; plain text plus a header renders reliably.
|
|
39
|
+
|
|
40
|
+
### 2.3 Tool format
|
|
41
|
+
|
|
42
|
+
````text
|
|
43
|
+
**<icon> <tool>**
|
|
44
|
+
|
|
45
|
+
`argument`
|
|
46
|
+
|
|
47
|
+
```text
|
|
48
|
+
output
|
|
49
|
+
````
|
|
50
|
+
|
|
51
|
+
````
|
|
52
|
+
|
|
53
|
+
Failed results start with:
|
|
54
|
+
|
|
55
|
+
```text
|
|
56
|
+
❌ ...
|
|
57
|
+
````
|
|
58
|
+
|
|
59
|
+
Each tool call gets its own bubble; the tool header, argument, and result are never split.
|
|
60
|
+
|
|
61
|
+
Fixed icon map:
|
|
62
|
+
|
|
63
|
+
| Tool | Icon | Tool | Icon |
|
|
64
|
+
| -------- | ---- | ------------ | ---- |
|
|
65
|
+
| `bash` | 💻 | `read` | 📖 |
|
|
66
|
+
| `write` | 📝 | `edit` | ✏️ |
|
|
67
|
+
| `grep` | 🔎 | `search` | 🔍 |
|
|
68
|
+
| `find` | 🗂️ | `ls` | 📁 |
|
|
69
|
+
| `list` | 📋 | `web` | 🌐 |
|
|
70
|
+
| `fetch` | 📡 | `delete` | 🗑️ |
|
|
71
|
+
| `remove` | ❌ | `todo` | ✅ |
|
|
72
|
+
| `test` | 🧪 | unconfigured | 🔧 |
|
|
73
|
+
|
|
74
|
+
Icons are hard-coded in `src/relay/stream-block-format.ts`; no setting is added.
|
|
75
|
+
|
|
76
|
+
### 2.4 Text and ordinary messages
|
|
77
|
+
|
|
78
|
+
Assistant text is appended as-is and has no extra header. Text and tool blocks are separated by bubble boundaries.
|
|
79
|
+
|
|
80
|
+
## 3. Bubble splitting and streaming
|
|
81
|
+
|
|
82
|
+
- A run normally produces multiple bubbles, but each bubble carries one content block.
|
|
83
|
+
- When one block reaches `MAX_BUBBLE_CHARS = 12_000`, split at a safe boundary:
|
|
84
|
+
- block boundary or line start;
|
|
85
|
+
- no open code fence;
|
|
86
|
+
- no pending resume checkpoint;
|
|
87
|
+
- no active tool.
|
|
88
|
+
- Thinking splits favor line/list structure and do not truncate mid-line.
|
|
89
|
+
- Tool header/argument and result always stay in the same bubble.
|
|
90
|
+
- `AppendStream` enforces the 300ms platform floor, 500ms default batching, 429/50002 backoff, and same-bubble resume.
|
|
91
|
+
- `index` advances after every send attempt; an unconfirmed failed frame is retried with the next index.
|
|
92
|
+
- After five minutes or a platform rejection, the final text falls back to the normal message path.
|
|
93
|
+
|
|
94
|
+
## 4. Abort and error recovery
|
|
95
|
+
|
|
96
|
+
### 4.1 `/stop`
|
|
97
|
+
|
|
98
|
+
The `/stop` flow:
|
|
99
|
+
|
|
100
|
+
1. cancel the recovery target;
|
|
101
|
+
2. abort the agent;
|
|
102
|
+
3. wait for `agent_end` to finish the current stream, tool results, and DONE;
|
|
103
|
+
4. reply `Abort requested.`
|
|
104
|
+
|
|
105
|
+
Started tool results are therefore not lost, and queued tool bubbles do not appear after the abort reply.
|
|
106
|
+
|
|
107
|
+
### 4.2 Model error recovery
|
|
108
|
+
|
|
109
|
+
- After a model error, keep the original QQ target for 60 seconds.
|
|
110
|
+
- New runs created by pi's automatic recovery/retry reuse the same `msgId`.
|
|
111
|
+
- An empty retry that produces no output does not consume the recovery target; the next retry can still attach.
|
|
112
|
+
- A new QQ message or `/stop` cancels recovery.
|
|
113
|
+
- A local run inside the recovery window can also be relayed. This is an explicit trade-off to preserve pi's automatic recovery.
|
|
114
|
+
|
|
115
|
+
## 5. Settings
|
|
116
|
+
|
|
117
|
+
`~/.pi/agent/pi-qq.json` stores settings only; credentials are never written there.
|
|
118
|
+
|
|
119
|
+
| Setting | Default | Description |
|
|
120
|
+
| --------------- | -------------- | ----------------------------------------- |
|
|
121
|
+
| `thinkingRelay` | `true` | Relay plain-text thinking blocks |
|
|
122
|
+
| `deliverAs` | `"steer"` | Queue behavior while busy |
|
|
123
|
+
| `imageMaxSize` | 10MB | Image download limit |
|
|
124
|
+
| `fileMaxSize` | 50MB | File download limit |
|
|
125
|
+
| `logLevel` | `"silent"` | Log threshold |
|
|
126
|
+
| `debug` | migration only | `debug: true` maps to `logLevel: "debug"` |
|
|
127
|
+
|
|
128
|
+
Removed settings: `streamRelay`, `streamFlushMs`, `streamAssistant`, `markdownSupport`, `heartbeatMinutes`, `heartbeatMaxMessages`. Old keys are ignored and not written back.
|
|
129
|
+
|
|
130
|
+
## 6. Modules and boundaries
|
|
131
|
+
|
|
132
|
+
The code is layered by responsibility:
|
|
133
|
+
|
|
134
|
+
<!-- prettier-ignore -->
|
|
135
|
+
| Module | Responsibility |
|
|
136
|
+
| ---------------------------- | ------------------------------------------------------------------------- |
|
|
137
|
+
| `index.ts` | Extension wiring, pi event subscriptions, login/session commands |
|
|
138
|
+
| `src/qq/qq-diagnostics.ts` | Terminal protocol diagnostics (`/qq-test-*`) |
|
|
139
|
+
| `src/qq/qq-message-handler.ts` | QQ inbound routing, commands, attachments, injection into pi |
|
|
140
|
+
| `src/qq/reply-sender.ts` | Markdown-to-text conversion, chunking, sending |
|
|
141
|
+
| `src/relay/run-stream-relay.ts` | Content-block orchestration, bubble lifecycle, tool queue, recovery |
|
|
142
|
+
| `src/relay/stream-block-format.ts` | Thinking header, tool icons, argument/result formatting |
|
|
143
|
+
| `src/relay/stream-session.ts` | Stream frames, batching, retries, resume checkpoints |
|
|
144
|
+
| `src/quota/reply-quota.ts` | Passive reply quota and `msgId` window |
|
|
145
|
+
| `src/quota/reply-quota-report.ts` | Quota diagnostic text |
|
|
146
|
+
| `src/infra/settings.ts` | Settings reading and legacy-key migration |
|
|
147
|
+
| `src/qq/qq-bot.ts` | QQBot/Gateway lifecycle and middleware |
|
|
148
|
+
| `src/qq/qr-login.ts` | QR login |
|
|
149
|
+
| `src/attachments/file-attachments.ts` | File storage, index, deduplication, pending files |
|
|
150
|
+
| `src/attachments/image-attachments.ts` | Image validation and vision input |
|
|
151
|
+
| `src/attachments/attachment-download.ts` | Shared limited download for images/files |
|
|
152
|
+
| `src/attachments/voice-transcript.ts` | QQ ASR text extraction |
|
|
153
|
+
| `src/infra/file-logger.ts` | Structured file logging |
|
|
154
|
+
| `src/infra/display-format.ts` | Byte/token display formatting |
|
|
155
|
+
|
|
156
|
+
Boundary rules:
|
|
157
|
+
|
|
158
|
+
- `index.ts` does not own the relay state machine.
|
|
159
|
+
- `stream-block-format.ts` is pure formatting and does not depend on streams.
|
|
160
|
+
- `run-stream-relay.ts` orchestrates and does not build Markdown details.
|
|
161
|
+
- `stream-session.ts` does not know content-block semantics.
|
|
162
|
+
- `qq-message-handler.ts` does not implement download, storage, or quota.
|
|
163
|
+
- All configuration goes through `settings.ts`.
|
|
164
|
+
- Modules are independently testable or receive dependencies from the entrypoint.
|
|
165
|
+
|
|
166
|
+
## 7. Verification
|
|
167
|
+
|
|
168
|
+
- Unit tests at v3 delivery: **135 passed** across 14 test files.
|
|
169
|
+
- TypeScript, ESLint, and Prettier checks pass.
|
|
170
|
+
- Verified on real QQ:
|
|
171
|
+
- C2C login, text, images, and files;
|
|
172
|
+
- thinking/tool/text rendered as separate blocks;
|
|
173
|
+
- tool header/result in the same bubble;
|
|
174
|
+
- 12k split with repeated header;
|
|
175
|
+
- `/stop` teardown and automatic recovery after model errors.
|
|
176
|
+
- Still worth a final pass:
|
|
177
|
+
- long list splitting on the target client;
|
|
178
|
+
- extremely long unclosed code fences;
|
|
179
|
+
- recovery near the TTL boundary;
|
|
180
|
+
- message quota with many parallel tools.
|
|
181
|
+
|
|
182
|
+
## 8. Risks and limitations
|
|
183
|
+
|
|
184
|
+
- One bubble per block increases message count; long runs need quota monitoring.
|
|
185
|
+
- 12k splitting is stateful; extreme single-line or unclosed-fence content may still fall back to platform splitting.
|
|
186
|
+
- Tool icons are hard-coded Emoji; rendering may vary by QQ client font.
|
|
187
|
+
- Recovery has a 60-second TTL; it stops after the window.
|
|
188
|
+
- C2C private chat only; credentials live in process memory.
|
|
189
|
+
- If streaming fails, the final text uses the normal message path and may duplicate already-visible content. Completeness is prioritized.
|
package/index.ts
CHANGED
|
@@ -1,24 +1,17 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import { getSettings, readConfig, type Credentials } from "./src/
|
|
4
|
-
import { startBot, type BotState, type RunningBot } from "./src/bot";
|
|
5
|
-
import { runQrLogin } from "./src/login";
|
|
6
|
-
import { createInboundHandler } from "./src/
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { formatTokenCount } from "./src/format";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* pi-qq extension entry.
|
|
18
|
-
* QR login only; credentials live in process memory and are never persisted.
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
/** In-memory login state; survives extension reload/session replacement in one process. */
|
|
3
|
+
import { getSettings, readConfig, type Credentials, type ResolvedSettings } from "./src/infra/settings";
|
|
4
|
+
import { startBot, type BotState, type RunningBot } from "./src/qq/qq-bot";
|
|
5
|
+
import { runQrLogin, type QrLoginResult } from "./src/qq/qr-login";
|
|
6
|
+
import { createInboundHandler } from "./src/qq/qq-message-handler";
|
|
7
|
+
import { registerQQDiagnostics } from "./src/qq/qq-diagnostics";
|
|
8
|
+
import { markdownToPlain, sendReply } from "./src/qq/reply-sender";
|
|
9
|
+
import { ReplyBudget } from "./src/quota/reply-quota";
|
|
10
|
+
import { RunFeedback } from "./src/relay/run-stream-relay";
|
|
11
|
+
import { formatTokenCount } from "./src/infra/display-format";
|
|
12
|
+
import { configureLogger, log, previewForLog } from "./src/infra/file-logger";
|
|
13
|
+
import { pruneUploadIndex, sessionUploadDir } from "./src/attachments/file-attachments";
|
|
14
|
+
|
|
22
15
|
interface LoginState {
|
|
23
16
|
credentials: Credentials;
|
|
24
17
|
allowedOpenid: string;
|
|
@@ -37,25 +30,16 @@ function setLoginState(state: LoginState | undefined): void {
|
|
|
37
30
|
else delete store[LOGIN_STATE_KEY];
|
|
38
31
|
}
|
|
39
32
|
|
|
40
|
-
/** Session-level runtime state; rebuilt by a new runtime after reload/session switch. */
|
|
41
33
|
let running: RunningBot | undefined;
|
|
42
34
|
let lastState: BotState = "stopped";
|
|
43
35
|
let stateDetail: string | undefined;
|
|
44
36
|
let sessionCtx: ExtensionContext | undefined;
|
|
37
|
+
let activeSettings: ResolvedSettings = getSettings({});
|
|
45
38
|
const budget = new ReplyBudget();
|
|
46
39
|
const runFeedback = new RunFeedback({
|
|
47
40
|
bot: () => running?.bot,
|
|
48
41
|
budget,
|
|
49
|
-
|
|
50
|
-
getHeartbeatMinutes: () => getSettings(readConfig().config).heartbeatMinutes,
|
|
51
|
-
getHeartbeatMaxMessages: () => getSettings(readConfig().config).heartbeatMaxMessages,
|
|
52
|
-
getStreamRelay: () => getSettings(readConfig().config).streamRelay,
|
|
53
|
-
getStreamFlushMs: () => getSettings(readConfig().config).streamFlushMs,
|
|
54
|
-
makeChannel: () => ({
|
|
55
|
-
budget,
|
|
56
|
-
boundOpenid: getLoginState()?.allowedOpenid ?? "",
|
|
57
|
-
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
58
|
-
}),
|
|
42
|
+
getThinkingRelay: () => activeSettings.thinkingRelay,
|
|
59
43
|
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
60
44
|
});
|
|
61
45
|
|
|
@@ -64,18 +48,22 @@ const fmtTokens = (n: number | null): string => (n === null ? "unknown" : format
|
|
|
64
48
|
export default function (pi: ExtensionAPI) {
|
|
65
49
|
const maskAppId = (appId: string) => `${appId.slice(0, 4)}****`;
|
|
66
50
|
|
|
67
|
-
// Live settings reader (binding/settings changes apply immediately).
|
|
68
|
-
|
|
69
51
|
const getAllowedOpenid = () => getLoginState()?.allowedOpenid;
|
|
70
|
-
const
|
|
71
|
-
const getDeliverAs = () => getSettings(readConfig().config).deliverAs;
|
|
52
|
+
const getDeliverAs = () => activeSettings.deliverAs;
|
|
72
53
|
|
|
73
54
|
const onWarn = (ctx: ExtensionContext) => (msg: string) => ctx.ui.notify(`pi-qq ${msg}`, "warning");
|
|
74
55
|
|
|
75
|
-
const
|
|
56
|
+
const applyConfig = (ctx: ExtensionContext) => {
|
|
57
|
+
const { config, error } = readConfig();
|
|
58
|
+
activeSettings = getSettings(config);
|
|
59
|
+
if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
60
|
+
return { settings: activeSettings, error };
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const getStatusLines = (ctx: ExtensionContext | undefined = sessionCtx): string[] => {
|
|
76
64
|
const login = getLoginState();
|
|
77
|
-
const usage =
|
|
78
|
-
const model =
|
|
65
|
+
const usage = ctx?.getContextUsage();
|
|
66
|
+
const model = ctx?.model;
|
|
79
67
|
return [
|
|
80
68
|
"pi-qq status",
|
|
81
69
|
`Login: ${login ? `QR login, in memory (AppID ${maskAppId(login.credentials.appId)})` : "not logged in"}`,
|
|
@@ -89,12 +77,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
89
77
|
];
|
|
90
78
|
};
|
|
91
79
|
|
|
92
|
-
|
|
80
|
+
const stopIfRunning = () => {
|
|
81
|
+
running?.stop();
|
|
82
|
+
running = undefined;
|
|
83
|
+
lastState = "stopped";
|
|
84
|
+
stateDetail = undefined;
|
|
85
|
+
sessionCtx = undefined;
|
|
86
|
+
runFeedback.dispose();
|
|
87
|
+
};
|
|
93
88
|
|
|
94
89
|
const startWithCredentials = async (ctx: ExtensionContext, creds: Credentials, allowedOpenid: string) => {
|
|
95
|
-
const settings =
|
|
90
|
+
const settings = activeSettings;
|
|
96
91
|
configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
|
|
97
|
-
|
|
92
|
+
stopIfRunning();
|
|
98
93
|
stateDetail = undefined;
|
|
99
94
|
sessionCtx = ctx;
|
|
100
95
|
const uploadDir = sessionUploadDir(ctx.cwd, ctx.sessionManager.getSessionId());
|
|
@@ -104,7 +99,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
104
99
|
allowedOpenid,
|
|
105
100
|
cwd: ctx.cwd,
|
|
106
101
|
model: ctx.model?.name ?? null,
|
|
107
|
-
markdownSupport: settings.markdownSupport,
|
|
108
102
|
logLevel: settings.logLevel,
|
|
109
103
|
uploadDir,
|
|
110
104
|
indexedFiles: Object.keys(uploadIndex).length,
|
|
@@ -112,19 +106,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
112
106
|
running = startBot({
|
|
113
107
|
credentials: creds,
|
|
114
108
|
allowedOpenid,
|
|
115
|
-
markdownSupport: settings.markdownSupport,
|
|
116
109
|
onMessage: createInboundHandler({
|
|
117
110
|
pi,
|
|
118
111
|
ctx,
|
|
119
112
|
budget,
|
|
120
113
|
getAllowedOpenid,
|
|
121
|
-
getBoundOpenid,
|
|
122
114
|
getDeliverAs,
|
|
123
|
-
|
|
124
|
-
getFileMaxSize: () => getSettings(readConfig().config).fileMaxSize,
|
|
115
|
+
getFileMaxSize: () => activeSettings.fileMaxSize,
|
|
125
116
|
getStatusLines,
|
|
126
117
|
onWarn: onWarn(ctx),
|
|
127
118
|
markQQTrigger: (openid, msgId) => runFeedback.markQQTrigger(openid, msgId),
|
|
119
|
+
waitForEnd: () => runFeedback.waitForEnd(),
|
|
120
|
+
onStop: () => runFeedback.cancelRecovery(),
|
|
128
121
|
}),
|
|
129
122
|
onStateChange: (state, detail) => {
|
|
130
123
|
lastState = state;
|
|
@@ -133,26 +126,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
133
126
|
else if (state === "blocked") ctx.ui.notify(`pi-qq ${detail ?? "connection blocked"}`, "error");
|
|
134
127
|
else if (state === "stopped" && detail) ctx.ui.notify(`pi-qq ${detail}`, "warning");
|
|
135
128
|
},
|
|
136
|
-
onRecoverableError: () => {
|
|
137
|
-
// Recoverable errors are handled by the SDK reconnect loop.
|
|
138
|
-
},
|
|
139
129
|
});
|
|
140
130
|
};
|
|
141
131
|
|
|
142
|
-
const stopIfRunning = () => {
|
|
143
|
-
running?.stop();
|
|
144
|
-
running = undefined;
|
|
145
|
-
lastState = "stopped";
|
|
146
|
-
stateDetail = undefined;
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
// —— Lifecycle ——
|
|
150
|
-
|
|
151
132
|
pi.on("session_start", async (_event, ctx) => {
|
|
152
|
-
const {
|
|
153
|
-
const settings = getSettings(config);
|
|
133
|
+
const { settings, error } = applyConfig(ctx);
|
|
154
134
|
configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
|
|
155
|
-
if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
156
135
|
|
|
157
136
|
const login = getLoginState();
|
|
158
137
|
log.info("session", "started", {
|
|
@@ -173,12 +152,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
173
152
|
pi.on("session_shutdown", () => {
|
|
174
153
|
log.info("session", "shutting down");
|
|
175
154
|
stopIfRunning();
|
|
176
|
-
sessionCtx = undefined;
|
|
177
|
-
runFeedback.dispose();
|
|
178
155
|
});
|
|
179
156
|
|
|
180
|
-
// F7 run feedback: agent lifecycle / tool counts / text streaming.
|
|
181
|
-
|
|
182
157
|
pi.on("agent_start", () => {
|
|
183
158
|
log.info("agent", "run started");
|
|
184
159
|
runFeedback.onAgentStart();
|
|
@@ -195,7 +170,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
195
170
|
toolCallId: event.toolCallId,
|
|
196
171
|
args: previewForLog(event.args),
|
|
197
172
|
});
|
|
198
|
-
void runFeedback.onToolStart(event.toolName);
|
|
173
|
+
void runFeedback.onToolStart(event.toolName, event.args, event.toolCallId);
|
|
199
174
|
});
|
|
200
175
|
|
|
201
176
|
pi.on("tool_execution_end", (event) => {
|
|
@@ -205,7 +180,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
205
180
|
isError: event.isError,
|
|
206
181
|
result: previewForLog(event.result),
|
|
207
182
|
});
|
|
208
|
-
runFeedback.onToolEnd(event.toolName, event.isError);
|
|
183
|
+
runFeedback.onToolEnd(event.toolName, event.isError, event.result, event.toolCallId);
|
|
209
184
|
});
|
|
210
185
|
|
|
211
186
|
pi.on("message_update", (event) => {
|
|
@@ -214,16 +189,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
214
189
|
const snapshot = msg.content
|
|
215
190
|
.filter((b) => b.type === "text")
|
|
216
191
|
.map((b) => b.text)
|
|
217
|
-
.join("");
|
|
192
|
+
.join("\n");
|
|
218
193
|
const thinking = msg.content
|
|
219
194
|
.filter((b) => b.type === "thinking")
|
|
220
195
|
.map((b) => b.thinking)
|
|
221
|
-
.join("");
|
|
196
|
+
.join("\n");
|
|
222
197
|
void runFeedback.onAssistantDelta(snapshot, thinking);
|
|
223
198
|
});
|
|
224
199
|
|
|
225
|
-
// pi → QQ: assistant message relay (QQ-triggered runs only).
|
|
226
|
-
|
|
227
200
|
pi.on("message_end", async (event, ctx) => {
|
|
228
201
|
const msg = event.message;
|
|
229
202
|
if (msg.role !== "assistant" || !running) return;
|
|
@@ -242,8 +215,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
242
215
|
});
|
|
243
216
|
if (!fromQQ) return;
|
|
244
217
|
|
|
245
|
-
const { config } = readConfig();
|
|
246
|
-
const settings = getSettings(config);
|
|
247
218
|
const isError = msg.stopReason === "error";
|
|
248
219
|
|
|
249
220
|
let text: string;
|
|
@@ -258,18 +229,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
258
229
|
}
|
|
259
230
|
if (!text) {
|
|
260
231
|
log.debug("pi", "assistant message has no text", { isError });
|
|
261
|
-
// Textless assistant messages also end the feedback turn: reset thinking state
|
|
262
|
-
// and flush pending thinking rows so the next message does not swallow them.
|
|
263
232
|
await runFeedback.onAssistantFinal("", isError);
|
|
264
233
|
return;
|
|
265
234
|
}
|
|
266
235
|
|
|
267
|
-
// F7 stream takeover: stream frames render Markdown; send raw text so lengths match.
|
|
268
236
|
const streamTookOver = await runFeedback.onAssistantFinal(text, isError);
|
|
269
237
|
log.debug("pi", "stream takeover decision", { streamTookOver, isError, textPreview: previewForLog(text) });
|
|
270
238
|
if (streamTookOver) return;
|
|
271
239
|
|
|
272
|
-
const payload =
|
|
240
|
+
const payload = markdownToPlain(text);
|
|
273
241
|
|
|
274
242
|
const bound = getLoginState()?.allowedOpenid;
|
|
275
243
|
if (!bound) {
|
|
@@ -286,40 +254,42 @@ export default function (pi: ExtensionAPI) {
|
|
|
286
254
|
});
|
|
287
255
|
});
|
|
288
256
|
|
|
289
|
-
// —— Commands ——
|
|
290
|
-
|
|
291
257
|
pi.registerCommand("qq-login", {
|
|
292
258
|
description: "pi-qq: log in with a QR code and bind the scanning QQ user",
|
|
293
259
|
handler: async (_args, ctx) => {
|
|
294
|
-
|
|
295
|
-
if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
296
|
-
|
|
260
|
+
applyConfig(ctx);
|
|
297
261
|
stopIfRunning();
|
|
298
262
|
setLoginState(undefined);
|
|
299
|
-
|
|
263
|
+
let result: QrLoginResult | undefined;
|
|
264
|
+
try {
|
|
265
|
+
result = await runQrLogin(ctx);
|
|
266
|
+
} catch (err) {
|
|
267
|
+
log.error("login", "QR login command failed", { err });
|
|
268
|
+
ctx.ui.notify("Error: QR login failed", "error");
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
300
271
|
if (!result) return;
|
|
301
272
|
if (!result.userOpenid) {
|
|
302
|
-
|
|
273
|
+
log.error("login", "QR login did not return a user openid");
|
|
274
|
+
ctx.ui.notify("Error: QR login failed", "error");
|
|
303
275
|
return;
|
|
304
276
|
}
|
|
305
277
|
|
|
306
278
|
const credentials: Credentials = { appId: result.appId, appSecret: result.appSecret };
|
|
307
279
|
setLoginState({ credentials, allowedOpenid: result.userOpenid });
|
|
308
|
-
|
|
280
|
+
try {
|
|
281
|
+
await startWithCredentials(ctx, credentials, result.userOpenid);
|
|
282
|
+
} catch (err) {
|
|
283
|
+
log.error("login", "starting bot after login failed", { err });
|
|
284
|
+
ctx.ui.notify("Error: QQ bot start failed", "error");
|
|
285
|
+
}
|
|
309
286
|
},
|
|
310
287
|
});
|
|
311
288
|
|
|
312
289
|
pi.registerCommand("qq-status", {
|
|
313
290
|
description: "pi-qq: show login, connection, and bound QQ user",
|
|
314
291
|
handler: async (_args, ctx) => {
|
|
315
|
-
ctx.ui.notify(getStatusLines().join("\n"), "info");
|
|
316
|
-
},
|
|
317
|
-
});
|
|
318
|
-
|
|
319
|
-
pi.registerCommand("qq-test-budget", {
|
|
320
|
-
description: "pi-qq: show passive reply budget, stream bubbles, and last inbound target",
|
|
321
|
-
handler: async (_args, ctx) => {
|
|
322
|
-
ctx.ui.notify(formatBudgetStatus(budget.snapshot(), budget.lastTarget).join("\n"), "info");
|
|
292
|
+
ctx.ui.notify(getStatusLines(ctx).join("\n"), "info");
|
|
323
293
|
},
|
|
324
294
|
});
|
|
325
295
|
|
|
@@ -344,69 +314,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
344
314
|
},
|
|
345
315
|
});
|
|
346
316
|
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
if (last) return { scope: "c2c" as const, targetId: last.openid, msgId: last.msgId };
|
|
352
|
-
const bound = getLoginState()?.allowedOpenid;
|
|
353
|
-
return bound ? { scope: "c2c" as const, targetId: bound } : undefined;
|
|
354
|
-
};
|
|
355
|
-
|
|
356
|
-
pi.registerCommand("qq-test-md", {
|
|
357
|
-
description: "pi-qq: send a Markdown message to verify QQ C2C Markdown rendering",
|
|
358
|
-
handler: async (args, ctx) => {
|
|
359
|
-
if (!running) {
|
|
360
|
-
ctx.ui.notify("pi-qq is not connected.", "warning");
|
|
361
|
-
return;
|
|
362
|
-
}
|
|
363
|
-
const target = diagTarget();
|
|
364
|
-
if (!target) {
|
|
365
|
-
ctx.ui.notify("pi-qq: no send target. Send a QQ message first.", "warning");
|
|
366
|
-
return;
|
|
367
|
-
}
|
|
368
|
-
const content = args?.trim() || "**Markdown test**\n# Heading\n- Item one\n- Item two\n[Link](https://qq.com)";
|
|
369
|
-
try {
|
|
370
|
-
await running.bot.sendMarkdown(target, content);
|
|
371
|
-
ctx.ui.notify("Markdown test sent. Check whether QQ renders it as rich text.", "info");
|
|
372
|
-
} catch (err) {
|
|
373
|
-
ctx.ui.notify(`Markdown send failed: ${(err as Error).message}`, "error");
|
|
374
|
-
}
|
|
375
|
-
},
|
|
376
|
-
});
|
|
377
|
-
|
|
378
|
-
pi.registerCommand("qq-test-stream", {
|
|
379
|
-
description: "pi-qq: run a streamed timeline diagnostic (thinking/tools/text)",
|
|
380
|
-
handler: async (_args, ctx) => {
|
|
381
|
-
if (!running) {
|
|
382
|
-
ctx.ui.notify("pi-qq is not connected.", "warning");
|
|
383
|
-
return;
|
|
384
|
-
}
|
|
385
|
-
const last = budget.lastTarget;
|
|
386
|
-
if (!last) {
|
|
387
|
-
ctx.ui.notify("pi-qq: send a QQ message first (streaming needs a msgId).", "warning");
|
|
388
|
-
return;
|
|
389
|
-
}
|
|
390
|
-
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
391
|
-
try {
|
|
392
|
-
const stream = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
|
|
393
|
-
await stream.append("[💭] Thinking...\n[🔧] [3] bash\n[🔧] [2] read\n");
|
|
394
|
-
await sleep(1200);
|
|
395
|
-
await stream.append("\n**Intermediate message**: first-turn reply.\n");
|
|
396
|
-
await sleep(1200);
|
|
397
|
-
await stream.append("[🔧] [1] edit\n");
|
|
398
|
-
await sleep(800);
|
|
399
|
-
await stream.append("\n**Final reply** (streamed append)");
|
|
400
|
-
let doneNote = "DONE succeeded";
|
|
401
|
-
try {
|
|
402
|
-
await stream.done();
|
|
403
|
-
} catch (doneErr) {
|
|
404
|
-
doneNote = `DONE rejected: ${(doneErr as Error).message}`;
|
|
405
|
-
}
|
|
406
|
-
ctx.ui.notify(`Stream timeline test: frames sent, ${doneNote}. Check the QQ activity timeline.`, "info");
|
|
407
|
-
} catch (err) {
|
|
408
|
-
ctx.ui.notify(`Stream timeline test failed: ${(err as Error).message}`, "error");
|
|
409
|
-
}
|
|
410
|
-
},
|
|
317
|
+
registerQQDiagnostics(pi, {
|
|
318
|
+
getRunning: () => running,
|
|
319
|
+
budget,
|
|
320
|
+
getBoundOpenid: () => getLoginState()?.allowedOpenid,
|
|
411
321
|
});
|
|
412
322
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chen_hu_hu/pi-qq",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.1",
|
|
4
4
|
"description": "Connect pi to QQ private chats.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "CQ-Developer",
|
|
@@ -22,6 +22,9 @@
|
|
|
22
22
|
"tencent"
|
|
23
23
|
],
|
|
24
24
|
"type": "module",
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22.19.0"
|
|
27
|
+
},
|
|
25
28
|
"publishConfig": {
|
|
26
29
|
"access": "public"
|
|
27
30
|
},
|
|
@@ -40,8 +43,8 @@
|
|
|
40
43
|
],
|
|
41
44
|
"scripts": {
|
|
42
45
|
"typecheck": "tsc --noEmit",
|
|
43
|
-
"lint": "
|
|
44
|
-
"lint:fix": "
|
|
46
|
+
"lint": "node --experimental-strip-types node_modules/eslint/bin/eslint.js --flag unstable_native_nodejs_ts_config .",
|
|
47
|
+
"lint:fix": "node --experimental-strip-types node_modules/eslint/bin/eslint.js --flag unstable_native_nodejs_ts_config . --fix",
|
|
45
48
|
"test": "vitest run",
|
|
46
49
|
"format": "prettier --write .",
|
|
47
50
|
"format:check": "prettier --check ."
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { formatBytes } from "
|
|
1
|
+
import { formatBytes } from "../infra/display-format";
|
|
2
2
|
|
|
3
|
-
/** Minimal QQ inbound attachment shape shared by images and files. */
|
|
4
3
|
export interface InboundAttachmentLike {
|
|
5
4
|
content_type: string;
|
|
6
5
|
url: string;
|
|
@@ -12,7 +11,6 @@ export interface DownloadOptions {
|
|
|
12
11
|
url: string;
|
|
13
12
|
maxSize: number;
|
|
14
13
|
timeoutMs: number;
|
|
15
|
-
/** Kind label used in errors, e.g. "image" or "file". */
|
|
16
14
|
kind: string;
|
|
17
15
|
fetchImpl?: typeof fetch;
|
|
18
16
|
}
|
|
@@ -48,7 +46,6 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
|
|
|
48
46
|
return Buffer.concat(chunks, total);
|
|
49
47
|
}
|
|
50
48
|
|
|
51
|
-
/** Download an attachment with a timeout and streaming size cap. */
|
|
52
49
|
export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
|
|
53
50
|
const limit = Math.max(1, opts.maxSize);
|
|
54
51
|
let parsed: URL;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface AttachmentFailure {
|
|
2
|
+
filename: string;
|
|
3
|
+
reason: string;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export function formatAttachmentFailures(failures: readonly AttachmentFailure[], successCount: number): string {
|
|
7
|
+
const title =
|
|
8
|
+
successCount > 0
|
|
9
|
+
? `⚠️ ${failures.length} attachment(s) failed (${successCount} succeeded):`
|
|
10
|
+
: "⚠️ Attachment failed:";
|
|
11
|
+
return [title, ...failures.map((failure) => `• ${failure.filename}: ${failure.reason}`)].join("\n");
|
|
12
|
+
}
|