pi-ext
bugabingas pi extensions
owned by bugabinga
fix(web): group search fallback warnings
f8bacfb02cbb13b1aa566c7d2c25977e6c828d0d
Review <review@example.invalid> ·
unsigned
Browse filesCompare with HEAD
Changed files (6)
.pi/prompts/live-extension-test.md
Modified275 275 - Independently inspect browser/terminal screenshots for UI claims.
276 276 - **Model/provider gotcha**:
277 277 when an extension frontmatter says `model:
278 - kimi/kimi-for-coding`, verify the exact provider name with `pi --list-models`
278 + openai-codex/gpt-5.5`, verify the exact provider name with `pi --list-models`
279 279 and with `getModel(provider, id)` from `@earendil-works/pi-ai`.
280 280 Invalid provider strings often return `undefined`, and `createAgentSession`
281 281 may silently fall back to the parent session's default model.
146 146 Unix `which`, handle Windows `.cmd`/`.bat` shims with spaces, avoid stale
147 147 negative PATH cache entries, notify missing required/optional tools at the
148 148 right severity, and add coverage
149 +- In `web` search, aggregate all backend failures into a single `info`-level
150 + notification instead of noisy per-fallback warnings; only notify when every
152 +- Preserve original `web` search backend failures with `AggregateError` and
153 + sanitize/truncate aggregate notification text
154 +- Add `web` search fallback regression coverage for silent fallback success,
155 + all-backend failure notification, DDG captcha handling, and preserved errors
156 +- Simplify Z.AI web search API errors to preserve code, status, and raw message
157 + without provider-specific classification buckets
158 +- Replace `zai/glm-5.1` and `kimi/kimi-for-coding` example references with
159 + `openai-codex/gpt-5.5`
149 160 - Make web and super tool widgets compact by default, gate previews, analyses,
150 161 and result lists behind expansion, and use `app.tools.expand` key hints
151 162 - Handle benign stdin `EPIPE` when web extension helper commands exit before
extensions/llmiterate/README.md
Modifiedextensions/web/__tests__/zai.test.ts
Modified209 209 expect(requestUrl).
toBe(
"https://api.z.ai/api/mcp/web_search_prime/mcp");
212 - test(
"classifies auth errors",
async ()
=> {
212 + test(
"preserves JSON API error code, status, and raw message",
async ()
=> {
213 213 process.
env.ZAI_API_KEY
= "test-key";
214 214 globalThis.fetch
= (
async ()
=> 222 222 throw new Error(
"expected failure");
224 224 expect(err).
toBeInstanceOf(ZaiApiError);
225 - expect((err
as ZaiApiError).kind).
toBe(
"auth");
225 + expect(
"kind" in (err
as object)).
toBe(
false);
226 226 expect((err
as ZaiApiError).
code).
toBe(
"1002");
227 - expect((err
as Error).message).
toBe(
"Z.AI auth failed (1002): bad key");
227 + expect((err
as ZaiApiError).
status).
toBe(
401);
228 + expect((err
as ZaiApiError).rawMessage).
toBe(
"bad key");
229 + expect((err
as Error).message).
toBe(
"Z.AI API error (1002): bad key");
231 - test(
"classifies quota/package errors",
async ()
=> {
232 - process.
env.ZAI_API_KEY
= "test-key";
233 - globalThis.fetch
= (
async ()
=> 239 - "Insufficient balance or no resource package. Please recharge.",
242 - { status:
429, statusText:
"Too Many Requests" },
243 - ))
as typeof fetch;
246 - await zaiSearch(
"example",
undefined);
247 - throw new Error(
"expected failure");
249 - expect(err).
toBeInstanceOf(ZaiApiError);
250 - expect((err
as ZaiApiError).kind).
toBe(
"quota");
251 - expect((err
as ZaiApiError).
code).
toBe(
"1113");
252 - expect((err
as Error).message).
toContain(
253 - "Z.AI quota/package unavailable (1113)",
258 - test(
"classifies endpoint/base URL errors",
async ()
=> {
233 + test(
"preserves HTTP plaintext errors",
async ()
=> {
259 234 process.
env.ZAI_API_KEY
= "test-key";
260 235 globalThis.fetch
= (
async ()
=> 261 236 new Response(
"Not Found", {
268 243 throw new Error(
"expected failure");
270 245 expect(err).
toBeInstanceOf(ZaiApiError);
271 - expect((err
as ZaiApiError).kind).
toBe(
"endpoint");
272 - expect((err
as Error).message).
toContain(
273 - "Z.AI endpoint/base URL not found (HTTP 404)",
246 + expect(
"kind" in (err
as object)).
toBe(
false);
247 + expect((err
as ZaiApiError).
code).
toBeUndefined();
248 + expect((err
as ZaiApiError).
status).
toBe(
404);
249 + expect((err
as ZaiApiError).rawMessage).
toBe(
"Not Found: Not Found");
250 + expect((err
as Error).message).
toBe(
251 + "Z.AI API error (HTTP 404): Not Found: Not Found",
278 - test(
"classifies policy blocks",
async ()
=> {
256 + test(
"preserves MCP JSON-RPC errors",
async ()
=> {
279 257 process.
env.ZAI_API_KEY
= "test-key";
280 - globalThis.fetch
= (
async ()
=> 283 - error: { code:
"1301", message:
"unsafe or sensitive content" },
258 + globalThis.fetch
= (
async (_input, init)
=> {
259 + const body
= JSON.
parse(
String(init?.
body));
260 + if (body.
method === "initialize")
261 + return new Response(
sse({ jsonrpc:
"2.0", id:
1, result: {} }), {
263 + headers: {
"mcp-session-id":
"s" },
265 + if (body.
method === "notifications/initialized")
266 + return new Response(
"", { status:
200 });
267 + return new Response(
271 + error: { code:
-32602, message:
"bad params" },
286 - ))
as typeof fetch;
275 + })
as typeof fetch;
289 278 await zaiSearch(
"example",
undefined);
290 279 throw new Error(
"expected failure");
292 281 expect(err).
toBeInstanceOf(ZaiApiError);
293 - expect((err
as ZaiApiError).kind).
toBe(
"policy");
294 - expect((err
as Error).message).
toContain(
295 - "Z.AI blocked sensitive/policy content (1301)",
282 + expect(
"kind" in (err
as object)).
toBe(
false);
283 + expect((err
as ZaiApiError).
code).
toBe(
"-32602");
284 + expect((err
as ZaiApiError).
status).
toBe(
200);
285 + expect((err
as ZaiApiError).rawMessage).
toBe(
"bad params");
286 + expect((err
as Error).message).
toBe(
287 + "Z.AI API error (-32602): bad params",
292 + test(
"preserves MCP tool errors without fake HTTP 200 label",
async ()
=> {
293 + process.
env.ZAI_API_KEY
= "test-key";
294 + globalThis.fetch
= (
async (_input, init)
=> {
295 + const body
= JSON.
parse(
String(init?.
body));
296 + if (body.
method === "initialize")
297 + return new Response(
sse({ jsonrpc:
"2.0", id:
1, result: {} }), {
299 + headers: {
"mcp-session-id":
"s" },
301 + if (body.
method === "notifications/initialized")
302 + return new Response(
"", { status:
200 });
303 + return new Response(
308 + content: [{ type:
"text", text:
"MCP denied" }],
314 + })
as typeof fetch;
317 + await zaiSearch(
"example",
undefined);
318 + throw new Error(
"expected failure");
320 + expect(err).
toBeInstanceOf(ZaiApiError);
321 + expect(
"kind" in (err
as object)).
toBe(
false);
322 + expect((err
as ZaiApiError).
code).
toBeUndefined();
323 + expect((err
as ZaiApiError).
status).
toBe(
200);
324 + expect((err
as ZaiApiError).rawMessage).
toBe(
"MCP denied");
325 + expect((err
as Error).message).
toBe(
"Z.AI API error: MCP denied");
extensions/web/search.ts
Modified 10 10 export type SearchSource = "codex" | "zai" | "minimax" | "ddg";
12 -type Notify = (message
: string, level
: "warning" | "info")
=> void;
12 +type Notify = (message
: string, level
: "info")
=> void;
14 14 interface SearchProvider {
15 15 source
: SearchSource;
17 17 search():
Promise<SearchResult[]
>;
20 +interface SearchFailure {
21 + label
: SearchProvider[
"label"];
26 +const MAX_ERROR_TEXT
= 240;
28 +function displayError(err
: unknown)
: string {
29 + const message
= (err
instanceof Error ? err.message
: String(err))
30 + .
replace(
/\s+/g,
" ")
32 + if (
!message)
return "unknown error";
33 + if (message.
length <= MAX_ERROR_TEXT)
return message;
34 + return `${message.slice(0, MAX_ERROR_TEXT - 1)}…`;
20 37 export interface WebSearchOptions {
35 52 options: WebSearchOptions,
36 53 ):
Promise<WebSearchOutcome
> {
37 54 const providers
= await buildProviders(options);
55 + const failures: SearchFailure[]
= [];
39 - for (let i
= 0; i < providers.length; i++) {
40 - const provider
= providers[i];
57 + for (const provider
of providers) {
42 59 return { results:
await provider.
search(), source: provider.
source };
44 - const next
= providers[i
+ 1];
45 - if (
!next)
throw err;
47 - fallbackNotice(provider.
label, err, next.
label),
62 + label: provider.
label,
64 + message:
displayError(err),
53 - return { results: [], source:
"ddg" };
69 + const summary
= failures
70 + .
map((failure)
=> `${failure.label}: ${failure.message}`)
72 + options.
notify?.(
`Search unavailable: ${summary}`,
"info");
74 + throw new AggregateError(
75 + failures.
map((failure)
=> failure.err),
76 + `Search unavailable: ${summary}`,
56 80 async function buildProviders(
136 160 markSearchTime();
138 162 const parsed
= parseDdgResults(html);
139 - if (parsed.diagnostics.captcha) {
140 - ctx?.ui?.
notify(
"DDG captcha detected — try again later",
"warning");
143 - const d
= parsed.diagnostics;
144 - if (d.rawBlockCount
> 0 || d.resultsSkipped
> 0) {
146 - `DDG: ${d.resultsFound} results from ${d.rawBlockCount} blocks` + 147 - (d.resultsSkipped
> 0 ? ` (${d.resultsSkipped} deduped)` : ""),
152 163 if (parsed.error)
throw new Error(parsed.error);
153 164 return parsed.results.
map((r)
=> ({
156 167 snippet: r.snippet,
160 -function fallbackNotice(
161 - provider
: SearchProvider[
"label"],
163 - nextProvider
: SearchProvider[
"label"],
165 - const suffix
= `trying ${nextProvider}`;
166 - const msg
= err
instanceof Error ? err.message
: String(err);
168 - if (provider
=== "Z.AI")
return zaiNotice(err, suffix, msg);
169 - if (provider
=== "MiniMax")
return minimaxNotice(msg, suffix);
170 - if (provider
=== "Codex")
return `Codex search failed; ${suffix}: ${msg}`;
171 - return `${provider} search failed; ${suffix}: ${msg}`;
174 -function zaiNotice(err
: unknown, suffix
: string, msg
: string)
: string {
175 - const code
= (err
as { code
?: string }
| undefined)?.
code;
176 - const kind
= (err
as { kind
?: string }
| undefined)?.kind;
177 - const codeText
= code
? ` (${code})` : "";
179 - if (kind
=== "quota")
180 - return `Z.AI quota/package unavailable${codeText}; ${suffix}`;
181 - if (kind
=== "auth")
return `Z.AI auth failed${codeText}; ${suffix}`;
182 - if (kind
=== "rate_limit")
183 - return `Z.AI rate/concurrency limit${codeText}; ${suffix}`;
184 - if (kind
=== "policy")
185 - return `Z.AI blocked sensitive/policy content${codeText}; ${suffix}`;
186 - if (kind
=== "permission")
187 - return `Z.AI API permission missing${codeText}; ${suffix}`;
188 - if (kind
=== "endpoint")
return `Z.AI endpoint/base URL not found; ${suffix}`;
190 - return `Z.AI search failed; ${suffix}: ${msg}`;
193 -function minimaxNotice(msg
: string, suffix
: string)
: string {
194 - if (
/\b1027\b/.
test(msg)
|| /output\s+new_?sensitive/i.
test(msg)) {
195 - return `MiniMax blocked search result/snippet as sensitive (1027 output); ${suffix}`;
197 - if (
/\b1026\b/.
test(msg)
|| /input\s+new_?sensitive/i.
test(msg)) {
198 - return `MiniMax blocked search query as sensitive (1026 input); ${suffix}`;
200 - return `MiniMax search failed; ${suffix}: ${msg}`;
extensions/web/zai.ts
Modified 55 -export type ZaiErrorKind = 67 55 export class ZaiApiError extends Error {
70 - public readonly kind
: ZaiErrorKind,
71 58 public readonly code
?: string,
72 59 public readonly status
?: number,
73 - public readonly rawMessage
?: string,
60 + public readonly rawMessage
= "unknown error",
76 63 this.
name = "ZaiApiError";
93 -const ERROR_LABEL
: Record<
ZaiErrorKind,
string>
= {
94 - auth:
"auth failed",
95 - quota:
"quota/package unavailable",
96 - rate_limit:
"rate/concurrency limit",
97 - policy:
"blocked sensitive/policy content",
98 - permission:
"API permission missing",
99 - endpoint:
"endpoint/base URL not found",
100 - params:
"request parameter error",
101 - server:
"server error",
102 - account:
"account problem",
103 - unknown:
"API error",
106 -const QUOTA_CODES
= new Set([
"1113",
"1304",
"1308",
"1309",
"1310",
"1311"]);
107 -const RATE_LIMIT_CODES
= new Set([
"1302",
"1303",
"1305",
"1312"]);
108 -const PERMISSION_CODES
= new Set([
"1220",
"434"]);
110 80 function resolveDefaultFreshness()
: ZaiSearchFreshness | undefined {
111 81 const value
= process.
env.ZAI_SEARCH_FRESHNESS?.
trim().
toLowerCase()
?? "";
112 82 if (ZAI_NO_FRESHNESS.
has(value))
return undefined;
154 124 :
`${value}/api/mcp/web_search_prime/mcp`;
157 -function classifyZaiError(
158 - code
: string | undefined,
159 - status
: number | undefined,
162 - if (code
&& /^100[0-4]$/.
test(code))
return "auth";
163 - if (QUOTA_CODES.
has(code
?? ""))
return "quota";
164 - if (RATE_LIMIT_CODES.
has(code
?? "")
|| status
=== 429)
return "rate_limit";
165 - if (code
=== "1301" || /sensitive|unsafe|policy/i.
test(message))
167 - if (PERMISSION_CODES.
has(code
?? ""))
return "permission";
168 - if (status
=== 404)
return "endpoint";
169 - if (code
&& /^121\d$|^1261$/.
test(code))
return "params";
170 - if (code
&& /^111\d$|^112\d$/.
test(code))
return "account";
171 - if (status
!== undefined && status
>= 500)
return "server";
175 -function describeZaiError(
176 - kind
: ZaiErrorKind,
177 - code
: string | undefined,
181 - const tag
= code
? ` (${code})` : status
? ` (HTTP ${status})` : "";
182 - return `Z.AI ${ERROR_LABEL[kind]}${tag}: ${message}`;
185 127 function makeZaiApiError(
186 128 status
: number | undefined,
191 133 code
=== undefined || code
=== null ? undefined : String(code);
192 134 const rawMessage
= 193 135 typeof message
=== "string" && message
? message
: "unknown error";
194 - const kind
= classifyZaiError(codeText, status, rawMessage);
136 + const tag
= codeText
138 + : status
!== undefined && status
>= 400 139 + ? ` (HTTP ${status})` 195 141 return new ZaiApiError(
196 - describeZaiError(kind, codeText, rawMessage, status),
142 + `Z.AI API error${tag}: ${rawMessage}`,