pi-auto-web-search 0.1.1 → 0.1.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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2
4
+
5
+ - `web-search`、`web-fetch`、`web-map` 不再接受 `instance` 或 `chain`。默认沿用配置顺序;点名供应商时传 `provider`,只在当前链上同供应商的实例间切换。`/search test <实例ID>` 保留。
6
+ - 三个工具的公共结果只报告供应商、任务说明与实际请求的错误分类。实例 ID、跳过原因和上游原始错误保留在本地诊断中;成功切换后也保留前一跳的失败记录。
7
+ - 搜索会在请求前跳过不能兑现域名过滤或 Markdown 正文的实例。xAI 不再截断超过 5 个域名的列表;带域名过滤的请求会跳过固定启用 `x_search` 的实例。
8
+ - `web-fetch` 保留 Tavily 原生纯文本,只转换 Markdown。`json` 和 `links` 序列化后超过 12,000 字符会报本地输出错误,不返回残缺内容或切换供应商。
9
+ - `failover.maxAttempts` 默认 3,不再用当前链长校验;超时默认在 `stopOn` 中。Cloudflare 按实际端点检查账号,缺账号的操作不发请求。`limits.maxPages` 保留为配置字段,三个工具都不使用。
10
+ - 多个进程共用同一 `search-usage.json` 时,发送前在 SQLite 旁文件锁内持久预占。校准和清零只修改已确认次数;崩溃遗留的预占保留至周期结束,旧计数保留;本地结算失败不重发请求。
11
+ - Cloudflare OAuth 登录只回填使用该身份且未绑定账号的启用实例;保留账号变量引用,静态凭据失效时不改用 OAuth。
12
+
3
13
  ## 0.1.1
4
14
 
5
15
  - 版本号递增,包内容与 0.1.0 相同
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  | 能力 | 说明 |
12
12
  | --- | --- |
13
13
  | 统一搜索、抓取与站点地图 | 提供 `web-search`(联网搜索)、`web-fetch`(单页正文提取,支持 Markdown、纯文本、html、json 与 links)和 `web-map`(遍历站点发现 URL) |
14
- | 多实例自动故障切换 | 按默认优先级或自定义顺序依次尝试,遇到限流、额度不足、超时或服务异常自动切到下一个实例 |
14
+ | 多实例自动故障切换 | 默认遇到限流、额度不足、认证、网络或服务端错误时尝试下一实例;超时属于 `stopOn`,不会继续切换 |
15
15
  | 多 Key 轮换与冷却 | 单实例可配置多个 API Key,失败自动冷却并切换,支持按密钥调用次数硬限额与并发控制 |
16
16
  | 多种接入方式 | 支持直连官方(`sdk`)、上游密钥池网关(`pool`)和自定义代理转发(`proxy`) |
17
17
  | 实时正文策略 | 搜索和抓取正文默认优先获取最新页面内容,避免返回过时缓存 |
@@ -31,7 +31,7 @@
31
31
  | DeepSeek | `deepseek` | 支持 | 支持 | 不支持 | 支持官方 Search 与 Fetch 接口 |
32
32
  | xAI | `xai` | 支持 | 不支持 | 不支持 | 基于 Responses API `web_search`,实例配置 `xSearch: true` 时固定附加 `x_search` |
33
33
 
34
- `web-fetch` 支持输出 `markdown`(默认)、`text`、`html`、`json` 与 `links`;超过 12,000 字符的正文会自动截断并附带提示。
34
+ `web-fetch` 的正文输出上限为 12,000 字符(按 JavaScript 字符串长度计算)。`markdown`、`text`、`html` 超限时返回带截断提示的预览;`json` 和 `links` 只返回完整结果,序列化后超限会报本地输出错误,不重试或切换供应商。
35
35
 
36
36
  ## 安装
37
37
 
@@ -94,19 +94,27 @@ pi -e .
94
94
  - `pool`:接入自带 Key 池的上游中转网关(需填写 `baseUrl`),插件侧只发一把网关 Key,轮换交给上游。
95
95
  - `proxy`:通过自定义代理转发请求(需填写 `baseUrl`),仍由插件本地做多 Key 轮换与冷却(支持添加或逐条移除多个 Key)。
96
96
  - **`baseUrl` 填写层级**:只需填到域名或反代前缀(例如 `https://proxy.example.com`),不要包含 `/search`、`/extract`、`/responses` 等具体接口路径;结尾的 `/v1`、`/v2`、`/v4` 版本段会自动归一化处理。Cloudflare 可填到 `/client` 或 `/client/v4`。
97
- - **凭证与环境变量**:腾讯云元宝搜索采用服务 API KEY 兼容模式(`api.wsa.cloud.tencent.com/SearchPro`,在控制台「概览 > 服务 API KEY 方式」创建 `sk-...` 密钥,推荐使用 `${TENCENTCLOUD_WSA_APIKEY}`)。当环境变量缺失时,对应实例会被标记为“未配置”并自动跳过,不影响其他实例。
97
+ - **凭证与环境变量**:腾讯云元宝搜索采用服务 API KEY 兼容模式(`api.wsa.cloud.tencent.com/SearchPro`,在控制台「概览 > 服务 API KEY 方式」创建 `sk-...` 密钥,推荐使用 `${TENCENTCLOUD_WSA_APIKEY}`)。没有可用凭据的实例会标为“未配置”并跳过。
98
+ - **Cloudflare OAuth**:只有启用的 Cloudflare `sdk` 实例在使用 `bearer` 且没有配置静态 `keys` 时才使用 OAuth。静态 key 变量失效不会改用 OAuth。登录只回填这些实例中缺省或留空的 `accountId`;读取配置和测试连接都不回填。
99
+ - **Cloudflare 账号**:未绑定账号的 OAuth 实例可使用令牌中的账号。显式账号或变量引用优先;如果账号变量未设置,就只能使用不含 `{accountId}` 的自定义端点。面板会区分“未配置”和“部分可用”,连通性测试使用 Markdown 抓取端点。
98
100
  - **按密钥调用次数限额(`keyQuota`)**:支持为任意实例配置 `{ "limit": 2000, "period": "month" }`,周期支持自然周期(`day`、`week`、`month`、`year`)与固定时长(`24h`、`7d`、`30d`、`2w` 等),用量以密钥 SHA-256 指纹持久化在配置同目录的 `search-usage.json`(权限 `0600`)。由于腾讯云元宝搜索属于后付费服务且超出免费额度不会自动停服,`tencent` 实例默认启用单密钥每自然月 `2000` 次硬拦截(可设为 `keyQuota: false` 关闭或在 `/search` 面板修改/校准);单密钥达到上限后自动切换到池内下一把未满密钥,全部用满时直接停止发请求并触发故障切换。
101
+ - **多进程共用配额**:所有客户端都应升级,共用同一个本地 `search-usage.json`,并为同一密钥设置一致的周期。已有 v1 计数继续有效;同目录的 `search-usage.json.lock.sqlite` 只用于互斥,不保存用量,不要删除。锁竞争最多等待 1 秒,网络请求期间不持锁。请求发送前先持久预占;成功或超时保留计数,明确失败或取消退回。锁或台账不可用时停止请求;本地结算失败不会触发重发。
102
+ - **核对与校准**:本地台账不是供应商账单。`/search` 的校准和清零只调整当前周期已确认的次数,不释放未结算预占。在途请求按实际结果结算;如果进程在结算前退出,遗留的预占会一直占用名额,直到周期结束。
99
103
  - **高级选项**:可通过 `defaultChain` / `fetchChain` 指定搜索与抓取的回退顺序,也可配置 `limits`、`failover`、`priority`、`concurrency`、`cooldownSeconds` 与 `enabled`。xAI 实例支持配置 `model`(默认 `grok-4.7`)以及 `xSearch: true` 固定启用 `x_search`(默认关闭,不受 `quality` 影响)。
104
+ - **尝试次数与页数**:`failover.maxAttempts` 是正整数,默认 3,不随实例就绪状态改变;如果本次候选数小于该值,就只尝试这些候选实例。`limits.maxPages` 可保留在配置中,但三个工具均不使用它。
100
105
 
101
106
  ## 工具说明
102
107
 
108
+ 三个工具默认使用你配置的有效链:搜索用搜索链,抓取和站点地图用抓取链。只有点名供应商时才传 `provider`(供应商的 `preset` 值)。工具只按原顺序尝试链上该供应商的可用实例,并遵守现有故障切换设置;如果没有实例支持本次请求,工具会直接报错,不发请求。
109
+
110
+ 旧调用请移除 `instance` 和 `chain`,这两个输入都会被拒绝。要测试指定实例,请用 `/search test <实例ID>`。
111
+
103
112
  ### `web-search`
104
113
 
105
114
  | 参数 | 说明 |
106
115
  | --- | --- |
107
116
  | `query` | 必填,搜索关键词 |
108
- | `instance` | 指定单个实例 ID,跳过默认回退顺序 |
109
- | `chain` | 仅本次调用覆盖实例尝试顺序 |
117
+ | `provider` | 可选,支持上表中的八家供应商 |
110
118
  | `limit` | 结果条数,范围 1–20,默认 10 |
111
119
  | `domains` | 仅保留指定域名下的结果 |
112
120
  | `excludeDomains` | 排除指定域名下的结果 |
@@ -120,6 +128,9 @@ pi -e .
120
128
 
121
129
  #### 跨供应商参数映射
122
130
 
131
+ - **域名过滤**:Firecrawl、xAI 和腾讯云不支持同时使用 `domains` 和 `excludeDomains`。xAI 每个列表最多 5 个域名,不会截断;腾讯云最多包含 1 个或排除 5 个。请求带有任一域名列表时,工具会跳过启用 `xSearch` 的 xAI 实例,因为 X 搜索不支持网站域名过滤;链内未启用 `xSearch` 的实例仍可用。
132
+ - **搜索正文**:`contents=markdown` 会跳过只返回网页摘要的 Cloudflare Web Search,不会额外发起抓取。以上硬条件都在发送请求前检查。
133
+
123
134
  - **搜索质量(`quality`)**:
124
135
 
125
136
  | `quality` | Exa `type` | Tavily `search_depth` | xAI `reasoning.effort` |
@@ -143,9 +154,9 @@ pi -e .
143
154
  | 参数 | 说明 |
144
155
  | --- | --- |
145
156
  | `url` | 必填,要抓取的 HTTP(S) 地址 |
146
- | `format` | `markdown`(默认)、`text`、`html`、`json`、`links`。`text` 由 Tavily 原生 `format=text` 兑现,其余实例抓 markdown 再本地转换;`html` / `json` / `links` 仅 Firecrawl 与 Cloudflare 兑现,链上其余实例跳过 |
157
+ | `format` | `markdown`(默认)、`text`、`html`、`json`、`links`。Tavily 的原生纯文本保留字面 Markdown 符号和空白;其他实例返回的 Markdown 在请求 `text` 时转为纯文本;`html` / `json` / `links` 仅 Firecrawl 与 Cloudflare 兑现,链上其余实例跳过 |
147
158
  | `schema` | JSON 抓取结构;单独出现时当作 `json`。仅 Firecrawl、Cloudflare |
148
- | `instance` | 指定单个实例 ID,跳过默认抓取顺序 |
159
+ | `provider` | 可选:`tavily`、`exa`、`firecrawl`、`deepseek`、`cloudflare`、`anysearch` |
149
160
 
150
161
  ### `web-map`
151
162
 
@@ -154,14 +165,15 @@ pi -e .
154
165
  | `url` | 必填,要遍历的 HTTP(S) 地址 |
155
166
  | `instructions` | 站点地图指引,仅 Tavily 兑现;Firecrawl 跳过并写 notes |
156
167
  | `limit` | 返回条数,范围 1–100,默认 50 |
157
- | `instance` | 指定单个实例 ID,跳过默认顺序 |
168
+ | `provider` | 可选:`tavily`、`firecrawl` |
158
169
 
159
170
  ## 返回格式与失败排查
160
171
 
161
172
  三个工具都返回 `content`(模型可读文本)、`details`(TUI 摘要)和 `structuredContent`(结构化数据):
162
173
 
163
- - **成功时**:`structuredContent` 与 `details` 都包含实际响应的 `instance` 与 `providerUsed`,每条搜索结果同样带有这两个字段;`degraded` 标明是否发生过实例切换,`notes` 记录参数降级说明。
164
- - **失败时**:返回 `isError: true`,文本以“尝试链”按顺序展示每次尝试的实例、供应商与错误分类,`structuredContent` 提供 `error`、`attempts`(`instance`、`provider`、`code`、`status`、`message`)与未尝试的 `unattempted`(`instance`、`provider`)。配置或参数错误不会发出请求,`attempts` 为空;取消请求仅返回“请求已取消”,不计入尝试链。
174
+ - **成功时**:`providerUsed` 标明供应商,搜索条目也保留来源。候选实例失败后切换成功时,`degraded` 为 `true`,包括本地密钥配额拦截后切换;能力预筛和搜索质量调整不算切换。`notes` 说明搜索深度、结果条数等调整。
175
+ - **失败时**:`error` 给出可公开的原因;`attempts` 按顺序列出已请求且失败的供应商(`provider`、`code`、可选 `status`),同一供应商可以出现多次。`unattempted` 列出候选链中没有发出请求的项(`provider`)。预筛、请求前拦截和取消本身不计入失败尝试。取消时模型文本只显示“请求已取消”,结构化结果保留此前的失败请求。
176
+ - **本地排查**:实例 ID、预筛原因和上游错误详情保留在 `details` 和 TUI 中;展开成功结果可查看此前的失败记录。`/search` 面板和 `/search status` 显示上次命中的实例和各实例的上次错误。
165
177
 
166
178
  ## 命令
167
179
 
package/README_EN.md CHANGED
@@ -11,7 +11,7 @@ Connect multiple search and scraping services behind one interface with automati
11
11
  | Capability | Description |
12
12
  | --- | --- |
13
13
  | Unified search, fetch & map | Provides `web-search` for web queries, `web-fetch` for single-page Markdown, plain text, html, json, or links extraction, and `web-map` to discover URLs on a site |
14
- | Automatic failover | Tries configured instances in priority or custom order and switches on rate limits, quota errors, timeouts, or server failures |
14
+ | Automatic failover | By default, rate limits, quota, authentication, network, and server errors allow failover. A timeout is in `stopOn` and stops the chain. |
15
15
  | Key rotation & quotas | Supports multiple API keys per instance with failure cooldowns, per-key call quota hard limits, and concurrency limits |
16
16
  | Flexible connection modes | Supports direct vendor APIs (`sdk`), upstream key-pool gateways (`pool`), and custom proxies (`proxy`) |
17
17
  | Live content by default | Requests fresh page content instead of stale cached copies whenever providers expose freshness controls |
@@ -31,7 +31,7 @@ Connect multiple search and scraping services behind one interface with automati
31
31
  | DeepSeek | `deepseek` | Yes | Yes | No | Official Search and Fetch endpoints |
32
32
  | xAI | `xai` | Yes | No | No | Responses API `web_search`; set `xSearch: true` on an instance to also enable `x_search` |
33
33
 
34
- `web-fetch` supports `markdown` (default), `text`, `html`, `json`, and `links`. Responses longer than 12,000 characters are truncated with a marker.
34
+ `web-fetch` limits the returned content to 12,000 characters (JavaScript string length). Oversized `markdown`, `text`, and `html` responses return a marked preview. `json` and `links` are returned only in full: exceeding the limit after serialization produces a local output error without retrying or switching providers.
35
35
 
36
36
  ## Installation
37
37
 
@@ -94,19 +94,27 @@ When no configuration file exists yet, the extension includes an anonymous `anys
94
94
  - `pool`: Connects to an upstream key-pool gateway (`baseUrl` required); the extension sends a single gateway key and delegates rotation upstream.
95
95
  - `proxy`: Routes requests through a custom proxy (`baseUrl` required) while keeping local multi-key rotation and cooldowns (supports adding and removing multiple keys in `/search`).
96
96
  - **`baseUrl` path level**: Provide only the origin or proxy prefix (for example `https://proxy.example.com`) without endpoint paths such as `/search`, `/extract`, or `/responses`; trailing version segments (`/v1`, `/v2`, `/v4`) are normalized automatically. For Cloudflare, point to the origin or `/client` (or `/client/v4`).
97
- - **Credentials & environment variables**: Tencent Yuanbao uses the Service API KEY compatibility mode (`api.wsa.cloud.tencent.com/SearchPro`, Bearer `sk-...` key created under Console → Overview → Service API KEY, e.g. `${TENCENTCLOUD_WSA_APIKEY}`). Instances with missing environment variables are marked as unconfigured and skipped automatically.
97
+ - **Credentials & environment variables**: Tencent Yuanbao uses the Service API KEY compatibility mode (`api.wsa.cloud.tencent.com/SearchPro`, Bearer `sk-...` key created under Console → Overview → Service API KEY, e.g. `${TENCENTCLOUD_WSA_APIKEY}`). Instances without usable credentials are marked as unconfigured and skipped automatically.
98
+ - **Cloudflare OAuth:** Only enabled Cloudflare `sdk` instances with `bearer` auth and no configured static `keys` use OAuth. An unresolved static key never falls back to OAuth. Login fills `accountId` only when omitted or blank on those instances. Reading the configuration and testing connectivity do not fill it.
99
+ - **Cloudflare account:** An OAuth instance with no account binding can use the account from its token. An explicit account or variable reference takes precedence. If the variable is unset, only custom endpoints without `{accountId}` are usable. The panel distinguishes unconfigured from partially available instances; connectivity tests use Markdown fetch.
98
100
  - **Per-key call quota (`keyQuota`)**: Any instance can enforce a client-side per-key hard limit via `{ "limit": 2000, "period": "month" }`. Supported periods are calendar cycles (`day`, `week`, `month`, `year`) and fixed durations (`24h`, `7d`, `30d`, `2w`, etc.). Counters are persisted by SHA-256 key fingerprint in `search-usage.json` (mode `0600`) next to `search.json`. Because Tencent Yuanbao Search is postpaid and keeps billing past its free tier, `tencent` enables a default limit of `2000` calls per key per calendar month (set `keyQuota: false` to disable, or adjust/calibrate in `/search`). Exhausted keys are skipped for other keys in the pool; once all keys reach their limit, no upstream request is sent and failover advances to the next provider.
101
+ - **Shared quotas:** Upgrade every client, use the same local `search-usage.json`, and configure the same period for each shared key. Existing v1 counters remain valid. The private sibling `search-usage.json.lock.sqlite` is a lock file, not a usage database; leave it in place. Lock contention waits at most one second, and no lock is held across a network request. Each request reserves capacity on disk before dispatch. Success and timeout consume it; explicit failure and cancellation refund it. Storage or lock failures stop dispatch, and a local settlement failure never triggers a resend.
102
+ - **Reconciliation:** The local ledger is not a provider bill. Calibration and reset in `/search` change only the confirmed usage for the current window; they do not release pending reservations. In-flight requests settle normally. If a client exits before settlement, its reservation occupies capacity until the window ends.
99
103
  - **Advanced options**: Set `defaultChain` and `fetchChain` to customize fallback order, or configure `limits`, `failover`, `priority`, `concurrency`, `cooldownSeconds`, and `enabled`. An xAI instance supports setting `model` (default `grok-4.7`) and `xSearch: true` to always include `x_search` (disabled by default, independent of `quality`).
104
+ - **Attempt and page limits:** `failover.maxAttempts` is a positive integer (default `3`), independent of instance readiness. Each call tries at most the smaller of that limit and its candidate count. `limits.maxPages` is accepted in the configuration but is not used by any of the three tools.
100
105
 
101
106
  ## Tools
102
107
 
108
+ All three tools use your effective chain by default: the search chain for searches, and the fetch chain for fetches and site maps. Set `provider` (a provider `preset` ID) only when requesting a particular provider. Only its available instances on that chain are tried, in order and under your failover settings. If none supports the request, the tool returns an error without sending a request.
109
+
110
+ Remove `instance` and `chain` from existing tool calls; both inputs are rejected. To test a specific instance, use `/search test <instance-id>`.
111
+
103
112
  ### `web-search`
104
113
 
105
114
  | Parameter | Description |
106
115
  | --- | --- |
107
116
  | `query` | Required search query |
108
- | `instance` | Target a single instance ID and bypass the default chain |
109
- | `chain` | Override the fallback instance order for one call |
117
+ | `provider` | Optional; accepts any of the eight preset IDs listed above |
110
118
  | `limit` | Number of results, 1–20, default `10` |
111
119
  | `domains` | Restrict results to these domains |
112
120
  | `excludeDomains` | Exclude results from these domains |
@@ -120,6 +128,9 @@ When no configuration file exists yet, the extension includes an anonymous `anys
120
128
 
121
129
  #### Cross-provider parameter mapping
122
130
 
131
+ - **Domain filters:** Firecrawl, xAI, and Tencent cannot combine `domains` with `excludeDomains`. xAI accepts up to five domains in either list without truncation; Tencent accepts one included domain or up to five excluded domains. When a domain filter is set, xAI instances with `xSearch` enabled are skipped because X results cannot be filtered by website domain. Other xAI instances on the chain remain eligible.
132
+ - **Search content:** `contents=markdown` skips Cloudflare Web Search, which returns page descriptions rather than full text. These requirements are checked before sending a request; no extra fetch is made.
133
+
123
134
  - **Quality (`quality`)**:
124
135
 
125
136
  | `quality` | Exa `type` | Tavily `search_depth` | xAI `reasoning.effort` |
@@ -143,9 +154,9 @@ When no configuration file exists yet, the extension includes an anonymous `anys
143
154
  | Parameter | Description |
144
155
  | --- | --- |
145
156
  | `url` | Required HTTP(S) URL to fetch |
146
- | `format` | `markdown` (default), `text`, `html`, `json`, `links`. `text` is fulfilled by Tavily's native `format=text`; other instances fetch markdown and convert locally; `html` / `json` / `links` are fulfilled only by Firecrawl and Cloudflare, other instances on the chain are skipped |
157
+ | `format` | `markdown` (default), `text`, `html`, `json`, `links`. Tavily's native text preserves literal Markdown characters and whitespace; Markdown returned by other instances is converted locally when `text` is requested; `html` / `json` / `links` are fulfilled only by Firecrawl and Cloudflare, other instances on the chain are skipped |
147
158
  | `schema` | JSON scrape schema; treated as `json` when given alone. Firecrawl and Cloudflare only |
148
- | `instance` | Target a single instance ID and bypass the default fetch chain |
159
+ | `provider` | Optional: `tavily`, `exa`, `firecrawl`, `deepseek`, `cloudflare`, `anysearch` |
149
160
 
150
161
  ### `web-map`
151
162
 
@@ -154,14 +165,15 @@ When no configuration file exists yet, the extension includes an anonymous `anys
154
165
  | `url` | Required HTTP(S) URL to map |
155
166
  | `instructions` | Mapping guidance; Tavily only. Firecrawl skips it and records a note |
156
167
  | `limit` | Number of URLs, 1–100, default `50` |
157
- | `instance` | Target a single instance ID and bypass the default chain |
168
+ | `provider` | Optional: `tavily`, `firecrawl` |
158
169
 
159
170
  ## Output & Failure Diagnostics
160
171
 
161
172
  All three tools return `content` (model-facing text), `details` (TUI summary), and `structuredContent` (typed payload):
162
173
 
163
- - **On success**: `structuredContent` and `details` report the actual `instance` and `providerUsed`, and every search result carries both fields. `degraded` indicates that failover occurred; `notes` records parameter downgrades.
164
- - **On failure**: Returns `isError: true`. The text includes an ordered attempt chain with instance, provider, and error class, while `structuredContent` returns `error`, ordered `attempts` (`instance`, `provider`, `code`, `status`, `message`), and `unattempted` (`instance`, `provider`). Config or parameter validation errors send no network request and keep `attempts` empty; cancelled requests report cancellation only and never appear in the attempt chain.
174
+ - **Success:** `providerUsed` identifies the provider, including on each search result. `degraded` is true when a candidate fails and another instance succeeds, even if a local key quota blocked the first request. Capability preselection and search quality adjustments are not failover. `notes` describes adjustments to search depth, result limits, and similar parameters.
175
+ - **Failure:** `error` gives a public explanation. Ordered `attempts` contain only failed requests (`provider`, `code`, optional `status`); a provider may occur more than once. `unattempted` lists candidates for which no request was sent (`provider`). Preselection, local blocks, and cancellation itself do not count as failed requests. On cancellation the text only reports cancellation; the structured result retains earlier failures.
176
+ - **Local diagnostics:** Instance IDs, skipped capabilities, and upstream error details stay in `details` and the TUI. Expand a successful result to inspect earlier failures, or use `/search` or `/search status` to see the last successful instance and each instance’s last error.
165
177
 
166
178
  ## Commands
167
179
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-auto-web-search",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Multi-provider web search and page fetch extension for pi coding agent — failover, key pools, proxy support, and TUI settings",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -92,7 +92,7 @@ export const anysearchAdapter: SearchAdapter = {
92
92
 
93
93
  mapExtract(response: ProviderResponse): ExtractOutput {
94
94
  const data = envelope(response);
95
- return { title: asString(data.title), content: asString(data.content) ?? "" };
95
+ return { format: "markdown", title: asString(data.title), content: asString(data.content) ?? "" };
96
96
  },
97
97
 
98
98
  unsupportedExtract: markdownOnlyExtract,
@@ -1,28 +1,22 @@
1
1
  import type { ResolvedInstance } from "../config.ts";
2
+ import { CLOUDFLARE_TOOL_PATHS } from "../presets.ts";
2
3
  import type { ProviderResponse, RequestSpec } from "../http.ts";
3
4
  import type { ExtractOutput, ExtractParams, SearchAdapter, SearchHit, SearchOutput, SearchParams } from "./types.ts";
4
- import { asArray, asRecord, asString, businessFailure, countryGapNote, qualityGapNote, rejectNoMap, rejectUnsupported, sourceModeGapNote, topicGapNote } from "./util.ts";
5
+ import { asArray, asRecord, asString, businessFailure, countryGapNote, markdownForText, qualityGapNote, rejectNoMap, rejectUnsupported, sourceModeGapNote, topicGapNote } from "./util.ts";
5
6
 
6
7
  const MAX_RESULTS = 10;
7
8
 
8
9
  /** 请求体必须带网关 id;每个账号有名为 default 的网关。 */
9
10
  const GATEWAY_ID = "default";
10
11
 
11
- const EXTRACT_PATH = {
12
- markdown: "markdown",
13
- text: "markdown",
14
- html: "content",
15
- json: "json",
16
- links: "links",
17
- } as const;
18
-
19
- /** 域名、时间与答案过滤都没有对应请求字段。 */
12
+ /** Web Search 返回网页摘要,不返回 Markdown 正文。 */
20
13
  function unsupportedParams(params: SearchParams): string[] {
21
14
  const names: string[] = [];
22
15
  if (params.domains?.length) names.push("domains");
23
16
  if (params.excludeDomains?.length) names.push("excludeDomains");
24
17
  if (params.freshness) names.push("freshness");
25
18
  if (params.answer) names.push("answer");
19
+ if (params.contents === "markdown") names.push("contents=markdown");
26
20
  return names;
27
21
  }
28
22
 
@@ -80,7 +74,7 @@ export const cloudflareAdapter: SearchAdapter = {
80
74
  limit: Math.min(params.limit, MAX_RESULTS),
81
75
  options: { gateway: { id: GATEWAY_ID } },
82
76
  };
83
- return { instance, path: "search", method: "POST", body };
77
+ return { instance, path: CLOUDFLARE_TOOL_PATHS.search, method: "POST", body };
84
78
  },
85
79
 
86
80
  checkSearch(response: ProviderResponse): void {
@@ -111,7 +105,7 @@ export const cloudflareAdapter: SearchAdapter = {
111
105
  if (params.format === "json") {
112
106
  body.response_format = { type: "json_schema", json_schema: params.schema };
113
107
  }
114
- return { instance, path: EXTRACT_PATH[params.format], method: "POST", body };
108
+ return { instance, path: CLOUDFLARE_TOOL_PATHS[params.format], method: "POST", body };
115
109
  },
116
110
 
117
111
  checkExtract(response: ProviderResponse, params: ExtractParams): void {
@@ -121,7 +115,8 @@ export const cloudflareAdapter: SearchAdapter = {
121
115
  },
122
116
 
123
117
  mapExtract(response: ProviderResponse, params: ExtractParams): ExtractOutput {
124
- return { content: extractContent(resultOf(response), params) ?? "" };
118
+ const format = markdownForText(params.format);
119
+ return { format, content: extractContent(resultOf(response), params) ?? "" };
125
120
  },
126
121
 
127
122
  /** 已兑现 markdown、html、json 与 links,不按格式裁链。 */
@@ -93,7 +93,7 @@ export const deepseekAdapter: SearchAdapter = {
93
93
 
94
94
  mapExtract(response: ProviderResponse): ExtractOutput {
95
95
  const data = asRecord(response.data) ?? {};
96
- return { title: asString(data.title), content: asString(data.content) ?? "" };
96
+ return { format: "markdown", title: asString(data.title), content: asString(data.content) ?? "" };
97
97
  },
98
98
 
99
99
  unsupportedExtract: markdownOnlyExtract,
@@ -146,7 +146,7 @@ export const exaAdapter: SearchAdapter = {
146
146
  mapExtract(response: ProviderResponse): ExtractOutput {
147
147
  const data = asRecord(response.data) ?? {};
148
148
  const first = asRecord(asArray(data.results)[0]) ?? {};
149
- return { title: asString(first.title), content: asString(first.text) ?? "" };
149
+ return { format: "markdown", title: asString(first.title), content: asString(first.text) ?? "" };
150
150
  },
151
151
 
152
152
  unsupportedExtract: markdownOnlyExtract,
@@ -1,5 +1,5 @@
1
1
  import type { ResolvedInstance } from "../config.ts";
2
- import { ProviderError, type ProviderResponse, type RequestSpec } from "../http.ts";
2
+ import type { ProviderResponse, RequestSpec } from "../http.ts";
3
3
  import type {
4
4
  ExtractOutput,
5
5
  ExtractParams,
@@ -11,16 +11,17 @@ import type {
11
11
  SearchOutput,
12
12
  SearchParams,
13
13
  } from "./types.ts";
14
- import { asArray, asRecord, asString, businessFailure, qualityGapNote, rejectUnsupported, sourceModeGapNote } from "./util.ts";
14
+ import { asArray, asRecord, asString, businessFailure, exclusiveDomainGaps, markdownForText, qualityGapNote, rejectUnsupported, sourceModeGapNote } from "./util.ts";
15
15
 
16
16
  const MAX_RESULTS = 100;
17
17
 
18
18
  /** 官方 tbs 的预置时间范围。 */
19
19
  const FRESHNESS_TBS = { day: "qdr:d", week: "qdr:w", month: "qdr:m", year: "qdr:y" } as const;
20
20
 
21
- /** 搜索响应里没有 answer 字段。 */
22
21
  function unsupportedParams(params: SearchParams): string[] {
23
- return params.answer ? ["answer"] : [];
22
+ const names = exclusiveDomainGaps(params);
23
+ if (params.answer) names.push("answer");
24
+ return names;
24
25
  }
25
26
 
26
27
  /** 上游用 success 判成败,错误在 error 与 code 里。 */
@@ -102,13 +103,6 @@ export const firecrawlAdapter: SearchAdapter = {
102
103
 
103
104
  buildSearch(instance: ResolvedInstance, params: SearchParams): RequestSpec {
104
105
  rejectUnsupported(instance, "firecrawl", unsupportedParams(params));
105
- if (params.domains?.length && params.excludeDomains?.length) {
106
- throw new ProviderError({
107
- instance: instance.id,
108
- code: "invalidRequest",
109
- message: "firecrawl 不能同时指定 domains 与 excludeDomains",
110
- });
111
- }
112
106
 
113
107
  const body: Record<string, unknown> = {
114
108
  query: params.query,
@@ -150,7 +144,7 @@ export const firecrawlAdapter: SearchAdapter = {
150
144
  const formats =
151
145
  params.format === "json"
152
146
  ? [{ type: "json", schema: params.schema }]
153
- : [params.format === "text" ? "markdown" : params.format];
147
+ : [markdownForText(params.format)];
154
148
  return { instance, path: "scrape", method: "POST", body: { url: params.url, formats, maxAge: 0 } };
155
149
  },
156
150
 
@@ -164,7 +158,8 @@ export const firecrawlAdapter: SearchAdapter = {
164
158
  mapExtract(response: ProviderResponse, params: ExtractParams): ExtractOutput {
165
159
  const data = envelope(response);
166
160
  const metadata = asRecord(data.metadata) ?? {};
167
- return { title: asString(metadata.title), content: extractContent(data, params) ?? "" };
161
+ const format = markdownForText(params.format);
162
+ return { format, title: asString(metadata.title), content: extractContent(data, params) ?? "" };
168
163
  },
169
164
 
170
165
  /** 已兑现 markdown、html、json 与 links,不按格式裁链。 */
@@ -44,6 +44,12 @@ function hitOf(value: unknown, params: SearchParams): SearchHit | undefined {
44
44
  return hit;
45
45
  }
46
46
 
47
+ function extractedBody(data: Record<string, unknown>, params: ExtractParams): string | undefined {
48
+ const raw = asRecord(asArray(data.results)[0])?.raw_content;
49
+ if (params.format === "text") return typeof raw === "string" && raw.length > 0 ? raw : undefined;
50
+ return asString(raw);
51
+ }
52
+
47
53
  /** Tavily:Bearer 鉴权,search 与 extract 都是 POST;结果字段见官方 API 参考。 */
48
54
  export const tavilyAdapter: SearchAdapter = {
49
55
  preset: "tavily",
@@ -99,7 +105,7 @@ export const tavilyAdapter: SearchAdapter = {
99
105
  return { instance, path: "extract", method: "POST", body };
100
106
  },
101
107
 
102
- checkExtract(response: ProviderResponse): void {
108
+ checkExtract(response: ProviderResponse, params: ExtractParams): void {
103
109
  const data = asRecord(response.data);
104
110
  if (!data) throw businessFailure(response, "tavily 响应格式无法解析");
105
111
 
@@ -110,14 +116,13 @@ export const tavilyAdapter: SearchAdapter = {
110
116
  const reason = asString(first?.error) ?? "未知原因";
111
117
  throw businessFailure(response, `tavily 提取失败:${url}(${reason})`, "network");
112
118
  }
113
- const raw = asString(asRecord(asArray(data.results)[0])?.raw_content);
114
- if (!raw) throw businessFailure(response, "tavily 提取未返回正文", "network");
119
+ if (extractedBody(data, params) === undefined) throw businessFailure(response, "tavily 提取未返回正文", "network");
115
120
  },
116
121
 
117
- mapExtract(response: ProviderResponse): ExtractOutput {
122
+ mapExtract(response: ProviderResponse, params: ExtractParams): ExtractOutput {
118
123
  const data = asRecord(response.data) ?? {};
119
- const content = asString(asRecord(asArray(data.results)[0])?.raw_content) ?? "";
120
- return { content };
124
+ const format = params.format === "text" ? "text" : "markdown";
125
+ return { format, content: extractedBody(data, params) ?? "" };
121
126
  },
122
127
 
123
128
  unsupportedExtract(params) {
@@ -8,7 +8,7 @@ import type {
8
8
  SearchParams,
9
9
  SourceMode,
10
10
  } from "./types.ts";
11
- import { asArray, asNumber, asRecord, asString, businessFailure, countryGapNote, qualityGapNote, rejectNoMap, rejectUnsupported } from "./util.ts";
11
+ import { asArray, asNumber, asRecord, asString, businessFailure, countryGapNote, exclusiveDomainGaps, qualityGapNote, rejectNoMap, rejectUnsupported } from "./util.ts";
12
12
 
13
13
  /** SearchPro 只按 10/20 条档位返回,超出 10 条的一律请求 20 条。 */
14
14
  const CNT_TIERS = [10, 20] as const;
@@ -31,7 +31,7 @@ function unsupportedParams(params: SearchParams): string[] {
31
31
  const domains = params.domains ?? [];
32
32
  const excluded = params.excludeDomains ?? [];
33
33
  if (domains.length > 1) names.push("多个 domains");
34
- if (domains.length > 0 && excluded.length > 0) names.push("domains 与 excludeDomains 同时使用");
34
+ names.push(...exclusiveDomainGaps(params));
35
35
  if (excluded.length > MAX_EXCLUDE_DOMAINS) names.push(`超过 ${MAX_EXCLUDE_DOMAINS} 个 excludeDomains`);
36
36
  if (params.answer) names.push("answer");
37
37
  if (params.contents === "markdown") names.push("contents=markdown");
@@ -61,8 +61,10 @@ export interface SearchOutput {
61
61
  rateLimit?: RateLimitInfo;
62
62
  }
63
63
 
64
- /** 供应商抓取正文格式;text 由 Tavily 原生兑现,其余供应商抓 markdown 再由工具层转纯文本。 */
65
- export type FetchOutputFormat = "markdown" | "text" | "html" | "json" | "links";
64
+ /** web-fetch 可请求的输出格式。 */
65
+ export const FETCH_FORMATS = ["markdown", "text", "html", "json", "links"] as const;
66
+
67
+ export type FetchOutputFormat = (typeof FETCH_FORMATS)[number];
66
68
 
67
69
  /** 与供应商无关的抓取参数;url、format 与 schema 已由 search-service 规范化。 */
68
70
  export interface ExtractParams {
@@ -72,6 +74,8 @@ export interface ExtractParams {
72
74
  }
73
75
 
74
76
  export interface ExtractOutput {
77
+ /** 供应商实际返回的正文格式。 */
78
+ format: FetchOutputFormat;
75
79
  title?: string;
76
80
  content: string;
77
81
  }
@@ -105,8 +109,8 @@ export interface AdapterCapabilities {
105
109
  export interface SearchAdapter {
106
110
  readonly preset: PresetId;
107
111
  readonly capabilities: AdapterCapabilities;
108
- /** 该供应商无法兑现的搜索参数;search-service 据此跳过实例。 */
109
- unsupported(params: SearchParams): string[];
112
+ /** 当前实例无法兑现的搜索参数;search-service 据此跳过实例。 */
113
+ unsupported(params: SearchParams, instance: ResolvedInstance): string[];
110
114
  buildSearch(instance: ResolvedInstance, params: SearchParams): RequestSpec;
111
115
  /** HTTP 200 里的业务失败在这里抛 ProviderError。 */
112
116
  checkSearch?(response: ProviderResponse, params: SearchParams): void;
@@ -1,7 +1,7 @@
1
1
  import type { ErrorClass, ResolvedInstance } from "../config.ts";
2
2
  import { ProviderError, type ProviderResponse } from "../http.ts";
3
3
  import type { PresetId } from "../presets.ts";
4
- import type { ExtractParams, SearchQuality, SourceMode, Topic } from "./types.ts";
4
+ import type { ExtractParams, FetchOutputFormat, SearchParams, SearchQuality, SourceMode, Topic } from "./types.ts";
5
5
 
6
6
  export function asRecord(value: unknown): Record<string, unknown> | undefined {
7
7
  return typeof value === "object" && value !== null && !Array.isArray(value)
@@ -36,7 +36,12 @@ export function businessFailure(
36
36
  });
37
37
  }
38
38
 
39
- /** 显式指定实例时不经链过滤,在请求构造处拦住该供应商兑现不了的参数。 */
39
+ /** 仅用于不能同时接收包含和排除列表的搜索接口。 */
40
+ export function exclusiveDomainGaps(params: SearchParams): string[] {
41
+ return params.domains?.length && params.excludeDomains?.length ? ["domains 与 excludeDomains 同时使用"] : [];
42
+ }
43
+
44
+ /** 请求构造与服务预筛使用同一份不支持参数清单。 */
40
45
  export function rejectUnsupported(
41
46
  instance: ResolvedInstance,
42
47
  preset: PresetId,
@@ -59,7 +64,12 @@ export function rejectNoMap(instanceId: string, preset: string): never {
59
64
  });
60
65
  }
61
66
 
62
- /** markdown 与 text 都视为可兑现;text 由工具层从 markdown 转出。其余 format 原样交给 search-service 裁链。 */
67
+ /** 没有原生纯文本的多格式抓取接口用 Markdown 兑现 text。 */
68
+ export function markdownForText(format: FetchOutputFormat) {
69
+ return format === "text" ? "markdown" : format;
70
+ }
71
+
72
+ /** 只返回 Markdown 的接口也能满足 text 请求,其他格式在预筛时跳过。 */
63
73
  export function markdownOnlyExtract(params: ExtractParams): string[] {
64
74
  return params.format === "markdown" || params.format === "text" ? [] : [params.format];
65
75
  }
@@ -11,7 +11,7 @@ import type {
11
11
  SourceMode,
12
12
  Topic,
13
13
  } from "./types.ts";
14
- import { asArray, asRecord, asString, businessFailure, rejectNoMap, rejectUnsupported } from "./util.ts";
14
+ import { asArray, asRecord, asString, businessFailure, exclusiveDomainGaps, rejectNoMap, rejectUnsupported } from "./util.ts";
15
15
 
16
16
  /** Responses API 必须带模型名;官方示例用 grok-4.7,实例可用 model 覆盖。 */
17
17
  export const DEFAULT_XAI_MODEL = "grok-4.7";
@@ -28,9 +28,15 @@ const QUALITY_EFFORT: Record<SearchQuality, string> = {
28
28
 
29
29
  const NO_FETCH = "xai 没有独立抓取接口";
30
30
 
31
- /** 没有正文返回,contents 只能取 none;官方没有发布时间字段,freshness 走提示词软约束。 */
32
- function unsupportedParams(params: SearchParams): string[] {
33
- return params.contents !== undefined && params.contents !== "none" ? ["contents"] : [];
31
+ function unsupportedParams(params: SearchParams, instance: ResolvedInstance): string[] {
32
+ const names = exclusiveDomainGaps(params);
33
+ const included = params.domains?.length ?? 0;
34
+ const excluded = params.excludeDomains?.length ?? 0;
35
+ if (included > MAX_DOMAINS) names.push(`超过 ${MAX_DOMAINS} 个 domains`);
36
+ if (excluded > MAX_DOMAINS) names.push(`超过 ${MAX_DOMAINS} 个 excludeDomains`);
37
+ if (instance.xSearch && (included > 0 || excluded > 0)) names.push("同时搜索 X 并按网站域名过滤");
38
+ if (params.contents !== undefined && params.contents !== "none") names.push("contents");
39
+ return names;
34
40
  }
35
41
 
36
42
  /** freshness 在官方参数里没有对应字段,只能写进提示词。 */
@@ -69,27 +75,22 @@ function invalid(instance: ResolvedInstance, message: string): ProviderError {
69
75
  }
70
76
 
71
77
  /** 域名过滤放在 web_search 工具的 filters 里,两者官方互斥。 */
72
- function toolOf(instance: ResolvedInstance, params: SearchParams): Record<string, unknown> {
78
+ function toolOf(params: SearchParams): Record<string, unknown> {
73
79
  const tool: Record<string, unknown> = { type: "web_search" };
74
- const domains = params.domains?.slice(0, MAX_DOMAINS);
75
- const excluded = params.excludeDomains?.slice(0, MAX_DOMAINS);
76
- if (domains?.length && excluded?.length) {
77
- throw invalid(instance, "xai 不能同时指定 domains 与 excludeDomains");
78
- }
79
- if (domains?.length) tool.filters = { allowed_domains: domains };
80
- else if (excluded?.length) tool.filters = { excluded_domains: excluded };
80
+ if (params.domains?.length) tool.filters = { allowed_domains: params.domains };
81
+ else if (params.excludeDomains?.length) tool.filters = { excluded_domains: params.excludeDomains };
81
82
  return tool;
82
83
  }
83
84
 
84
85
  /** x_search 由实例固定开关决定;域名过滤只作用于 web_search。 */
85
86
  function toolsOf(instance: ResolvedInstance, params: SearchParams): Record<string, unknown>[] {
86
- const tools: Record<string, unknown>[] = [toolOf(instance, params)];
87
+ const tools: Record<string, unknown>[] = [toolOf(params)];
87
88
  if (instance.xSearch) tools.push({ type: "x_search" });
88
89
  return tools;
89
90
  }
90
91
 
91
92
  /** 正文在 output 的 output_text 里,来源在 annotations 与 citations 里。 */
92
- function collect(data: Record<string, unknown>, params: SearchParams): SearchOutput {
93
+ function collect(data: Record<string, unknown>): SearchOutput {
93
94
  const texts: string[] = [];
94
95
  const hits: SearchHit[] = [];
95
96
  const seen = new Set<string>();
@@ -120,11 +121,7 @@ function collect(data: Record<string, unknown>, params: SearchParams): SearchOut
120
121
  addHit(typeof citation === "string" ? citation : asRecord(citation)?.url);
121
122
  }
122
123
 
123
- const notes: string[] = [];
124
- if ((params.domains?.length ?? 0) > MAX_DOMAINS || (params.excludeDomains?.length ?? 0) > MAX_DOMAINS) {
125
- notes.push(`xai 每次最多过滤 ${MAX_DOMAINS} 个域名,超出的已忽略`);
126
- }
127
- return { hits, answer: texts.join("\n\n") || undefined, notes };
124
+ return { hits, answer: texts.join("\n\n") || undefined };
128
125
  }
129
126
 
130
127
  /** xAI:走 Responses API 的 web_search 工具,返回答案与引用来源。 */
@@ -135,7 +132,7 @@ export const xaiAdapter: SearchAdapter = {
135
132
  unsupported: unsupportedParams,
136
133
 
137
134
  buildSearch(instance: ResolvedInstance, params: SearchParams): RequestSpec {
138
- rejectUnsupported(instance, "xai", unsupportedParams(params));
135
+ rejectUnsupported(instance, "xai", unsupportedParams(params, instance));
139
136
 
140
137
  const body: Record<string, unknown> = {
141
138
  model: instance.model ?? DEFAULT_XAI_MODEL,
@@ -153,9 +150,9 @@ export const xaiAdapter: SearchAdapter = {
153
150
  }
154
151
  },
155
152
 
156
- mapSearch(response: ProviderResponse, params: SearchParams): SearchOutput {
153
+ mapSearch(response: ProviderResponse): SearchOutput {
157
154
  const data = asRecord(response.data) ?? {};
158
- return { ...collect(data, params), rateLimit: response.rateLimit };
155
+ return { ...collect(data), rateLimit: response.rateLimit };
159
156
  },
160
157
 
161
158
  buildExtract(instance: ResolvedInstance): RequestSpec {