@chen_hu_hu/pi-qq 1.3.5 → 1.4.0

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.
@@ -6,7 +6,7 @@ export function thinkingHeader(): string {
6
6
  const ARG_MAX_CHARS = 200;
7
7
  const RESULT_MAX_CHARS = 600;
8
8
  const RESULT_MAX_LINES = 8;
9
- const ARG_KEYS = ["command", "path", "file_path", "filename", "pattern", "query", "url"];
9
+ const ARG_KEYS = ["command", "path", "file_path", "filename", "pattern", "query", "url"] as const;
10
10
  const TOOL_ICONS: Record<string, string> = {
11
11
  bash: "💻",
12
12
  read: "📖",
@@ -51,24 +51,32 @@ function truncateText(text: string, maxChars: number, maxLines: number): string
51
51
  return truncated ? `${out}…` : out;
52
52
  }
53
53
 
54
- function primaryArg(args: unknown): string {
55
- let value: string | undefined;
56
- if (typeof args === "string") {
57
- value = args;
58
- } else if (args && typeof args === "object") {
54
+ function stringArg(args: unknown, keys: readonly string[]): string | undefined {
55
+ if (typeof args === "string") return args;
56
+ if (args && typeof args === "object") {
59
57
  const record = args as Record<string, unknown>;
60
- value = ARG_KEYS.map((key) => record[key]).find(
61
- (candidate): candidate is string => typeof candidate === "string" && candidate.length > 0,
62
- );
63
- if (!value) {
64
- try {
65
- value = JSON.stringify(args);
66
- } catch {
67
- value = String(args);
68
- }
58
+ for (const key of keys) {
59
+ const candidate = record[key];
60
+ if (typeof candidate === "string" && candidate.length > 0) return candidate;
61
+ }
62
+ return undefined;
63
+ }
64
+ if (args !== undefined && args !== null) return String(args);
65
+ return undefined;
66
+ }
67
+
68
+ function rawPrimaryArg(args: unknown, keys: readonly string[] = ARG_KEYS): string | undefined {
69
+ return stringArg(args, keys);
70
+ }
71
+
72
+ function primaryArg(args: unknown): string {
73
+ let value = rawPrimaryArg(args);
74
+ if (!value && args && typeof args === "object") {
75
+ try {
76
+ value = JSON.stringify(args);
77
+ } catch {
78
+ value = String(args);
69
79
  }
70
- } else if (args !== undefined && args !== null) {
71
- value = String(args);
72
80
  }
73
81
  const normalized = (value ?? "").replace(/\s+/g, " ").trim();
74
82
  return normalized.length > ARG_MAX_CHARS ? `${normalized.slice(0, ARG_MAX_CHARS)}…` : normalized;
@@ -99,9 +107,114 @@ export function formatSkillBlock(name: string): string {
99
107
  }
100
108
 
101
109
  export function formatToolLine(name: string, args: unknown): string {
110
+ const lowerName = name.toLowerCase();
111
+ const label = `${TOOL_ICONS[lowerName] ?? "🔧"} ${name}`;
112
+ const header = `## ${label}`;
113
+
114
+ if (lowerName === "bash") {
115
+ const command = rawPrimaryArg(args, ["command"]);
116
+ const formatted = command ? formatBashCommand(command) : "";
117
+ return formatted ? `${header}\n\n${formatted}` : header;
118
+ }
119
+
102
120
  const primary = primaryArg(args);
103
- const label = `${TOOL_ICONS[name.toLowerCase()] ?? "🔧"} ${name}`;
104
- return primary ? `**${label}**\n\n${inlineCode(primary)}` : `**${label}**`;
121
+ return primary ? `${header}\n\n${inlineCode(primary)}` : header;
122
+ }
123
+
124
+ function formatBashCommand(command: string): string {
125
+ const normalized = command
126
+ .replace(/\r\n?/g, "\n")
127
+ .replace(/[ \t]+$/gm, "")
128
+ .trim();
129
+ if (!normalized) return "";
130
+ const fence = backtickFence(normalized, 3);
131
+ return `${fence}bash\n${normalized}\n${fence}`;
132
+ }
133
+
134
+ const EXTENSION_LANGUAGES: Record<string, string> = {
135
+ md: "markdown",
136
+ markdown: "markdown",
137
+ mdx: "markdown",
138
+ html: "html",
139
+ htm: "html",
140
+ xml: "xml",
141
+ svg: "xml",
142
+ tex: "latex",
143
+ rst: "rst",
144
+ css: "css",
145
+ scss: "scss",
146
+ less: "less",
147
+ vue: "vue",
148
+ svelte: "svelte",
149
+ json: "json",
150
+ jsonc: "json",
151
+ json5: "json",
152
+ ipynb: "json",
153
+ yaml: "yaml",
154
+ yml: "yaml",
155
+ toml: "toml",
156
+ ini: "ini",
157
+ cfg: "ini",
158
+ conf: "ini",
159
+ sql: "sql",
160
+ graphql: "graphql",
161
+ gql: "graphql",
162
+ proto: "protobuf",
163
+ ts: "typescript",
164
+ mts: "typescript",
165
+ cts: "typescript",
166
+ tsx: "tsx",
167
+ js: "javascript",
168
+ mjs: "javascript",
169
+ cjs: "javascript",
170
+ jsx: "jsx",
171
+ py: "python",
172
+ pyw: "python",
173
+ sh: "bash",
174
+ bash: "bash",
175
+ zsh: "bash",
176
+ fish: "fish",
177
+ ps1: "powershell",
178
+ bat: "bat",
179
+ cmd: "bat",
180
+ go: "go",
181
+ rs: "rust",
182
+ java: "java",
183
+ kt: "kotlin",
184
+ kts: "kotlin",
185
+ c: "c",
186
+ h: "c",
187
+ cpp: "cpp",
188
+ cc: "cpp",
189
+ cxx: "cpp",
190
+ hpp: "cpp",
191
+ cs: "csharp",
192
+ rb: "ruby",
193
+ php: "php",
194
+ swift: "swift",
195
+ dart: "dart",
196
+ lua: "lua",
197
+ r: "r",
198
+ pl: "perl",
199
+ diff: "diff",
200
+ patch: "diff",
201
+ };
202
+
203
+ function languageForPath(filePath: string): string {
204
+ const base = filePath.trim().split(/[\\/]/).pop()?.toLowerCase() ?? "";
205
+ if (base === "dockerfile") return "dockerfile";
206
+ if (base === "makefile") return "makefile";
207
+ if (base === "cmakelists.txt") return "cmake";
208
+ if (base === "readme") return "markdown";
209
+ const ext = base.includes(".") ? base.slice(base.lastIndexOf(".") + 1) : "";
210
+ return EXTENSION_LANGUAGES[ext] ?? "text";
211
+ }
212
+
213
+ export function resultLanguage(toolName: string, args: unknown, isError: boolean): string {
214
+ if (isError) return "text";
215
+ if (toolName.toLowerCase() !== "read") return "text";
216
+ const path = rawPrimaryArg(args, ["path", "file_path"]);
217
+ return path ? languageForPath(path) : "text";
105
218
  }
106
219
 
107
220
  function resultText(result: unknown): string {
@@ -134,12 +247,16 @@ function resultText(result: unknown): string {
134
247
  }
135
248
  }
136
249
 
137
- export function formatToolResult(result: unknown, isError: boolean): string {
250
+ export function formatToolResult(result: unknown, isError: boolean, language = "text"): string {
138
251
  let text = resultText(result);
139
252
  text = text.replace(/\r\n/g, "\n").replace(/\s+$/, "");
140
- if (!text) text = t("stream.noOutput");
253
+ if (!text) {
254
+ text = t("stream.noOutput");
255
+ language = "text";
256
+ }
141
257
  text = truncateText(text, RESULT_MAX_CHARS, RESULT_MAX_LINES);
142
258
  if (isError) text = `❌ ${text}`;
259
+ language = isError || !/^[a-z0-9+#.-]+$/i.test(language) ? "text" : language;
143
260
  const fence = backtickFence(text, 3);
144
- return `${fence}text\n${text}\n${fence}\n`;
261
+ return `${fence}${language}\n${text}\n${fence}\n`;
145
262
  }
@@ -18,12 +18,21 @@ export interface AppendStreamCheckpoint {
18
18
  buffer?: string;
19
19
  }
20
20
 
21
+ export interface AppendStreamFrameInfo {
22
+ index: number;
23
+ state: "generating" | "done";
24
+ msgSeq: number | null;
25
+ streamMsgId?: string;
26
+ bufferLength: number;
27
+ }
28
+
21
29
  export interface AppendStreamOptions {
22
30
  throttleMs?: number;
23
31
  retryBaseMs?: number;
24
32
  resume?: AppendStreamCheckpoint;
25
33
  onError?: (err: Error) => void;
26
34
  onDebug?: (message: string) => void;
35
+ onFrameError?: (err: unknown, info: AppendStreamFrameInfo) => void;
27
36
  }
28
37
 
29
38
  export class AppendStream {
@@ -83,16 +92,24 @@ export class AppendStream {
83
92
  if (this.doneSent || !delta) return;
84
93
  this.buffer += delta;
85
94
  const elapsed = Date.now() - this.lastFlushAt;
86
- if (this.flushing) return;
87
- if (elapsed >= this.throttleMs()) {
95
+ const throttle = this.throttleMs();
96
+ if (this.flushing) {
97
+ this.opts.onDebug?.(`append: while flushing, buffer=${this.buffer.length}`);
98
+ return;
99
+ }
100
+ if (elapsed >= throttle) {
101
+ this.opts.onDebug?.(`append: immediate, elapsed=${elapsed}, buffer=${this.buffer.length}`);
88
102
  await this.doFlush("generating");
89
103
  return;
90
104
  }
91
105
  if (!this.flushTimer) {
106
+ const waitMs = throttle - elapsed;
107
+ this.opts.onDebug?.(`append: buffered, elapsed=${elapsed}, wait=${waitMs}, buffer=${this.buffer.length}`);
92
108
  this.flushTimer = setTimeout(() => {
93
109
  this.flushTimer = null;
110
+ this.opts.onDebug?.(`timer: fired after ${waitMs}, buffer=${this.buffer.length}`);
94
111
  void this.doFlush("generating").catch((err) => this.opts.onError?.(err as Error));
95
- }, this.throttleMs() - elapsed);
112
+ }, waitMs);
96
113
  }
97
114
  }
98
115
 
@@ -123,6 +140,9 @@ export class AppendStream {
123
140
  if (this.flushing) return;
124
141
  const content = state === "done" ? "" : this.buffer;
125
142
  if (!content && state === "generating") return;
143
+ this.opts.onDebug?.(
144
+ `flush: start state=${state}, content=${content.length}, index=${this.index}, msgSeq=${this.msgSeq ?? "none"}, streamMsgId=${this.streamMsgId ?? "none"}`,
145
+ );
126
146
  this.flushing = true;
127
147
  let failed = false;
128
148
  try {
@@ -139,10 +159,13 @@ export class AppendStream {
139
159
  index,
140
160
  ...(this.streamMsgId ? { stream_msg_id: this.streamMsgId } : {}),
141
161
  } as unknown as StreamMessageRequest;
142
- const resp = await this.sendWithRetry(req);
162
+ const resp = await this.sendWithRetry(req, state);
143
163
  if (resp?.id && !this.streamMsgId) this.streamMsgId = resp.id;
144
164
  if (state === "generating") this.buffer = this.buffer.slice(content.length);
145
165
  this.lastFlushAt = Date.now();
166
+ this.opts.onDebug?.(
167
+ `flush: done state=${state}, remaining=${this.buffer.length}, streamMsgId=${this.streamMsgId ?? "none"}`,
168
+ );
146
169
  } catch (err) {
147
170
  failed = true;
148
171
  throw err;
@@ -157,7 +180,10 @@ export class AppendStream {
157
180
  }
158
181
  }
159
182
 
160
- private async sendWithRetry(req: StreamMessageRequest): Promise<MessageResponse | undefined> {
183
+ private async sendWithRetry(
184
+ req: StreamMessageRequest,
185
+ state: "generating" | "done",
186
+ ): Promise<MessageResponse | undefined> {
161
187
  const base = this.opts.retryBaseMs ?? RATE_LIMIT_BASE_MS;
162
188
  for (let attempt = 0; ; attempt++) {
163
189
  try {
@@ -165,6 +191,13 @@ export class AppendStream {
165
191
  } catch (err) {
166
192
  const reason = err instanceof Error ? err.message : String(err);
167
193
  if (attempt >= MAX_RETRIES || !this.isRateLimitError(err)) {
194
+ this.opts.onFrameError?.(err, {
195
+ index: req.index,
196
+ state,
197
+ msgSeq: this.msgSeq,
198
+ ...(this.streamMsgId ? { streamMsgId: this.streamMsgId } : {}),
199
+ bufferLength: this.buffer.length,
200
+ });
168
201
  this.opts.onDebug?.(t("log.streamFrameFailed", { index: req.index, attempts: attempt + 1, reason }));
169
202
  throw err;
170
203
  }