opencode-querit 1.0.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.
- package/LICENSE +21 -0
- package/README-zh.md +126 -0
- package/README.md +126 -0
- package/lib/client.d.ts +94 -0
- package/lib/client.js +265 -0
- package/lib/config.d.ts +95 -0
- package/lib/config.js +172 -0
- package/lib/format.d.ts +13 -0
- package/lib/format.js +96 -0
- package/lib/index.d.ts +30 -0
- package/lib/index.js +200 -0
- package/lib/sanitize.d.ts +7 -0
- package/lib/sanitize.js +98 -0
- package/package.json +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Opencode-querit contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README-zh.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# opencode-querit
|
|
2
|
+
|
|
3
|
+
[](./LICENSE)
|
|
4
|
+
|
|
5
|
+
为 [OpenCode](https://opencode.ai) 提供基于 Querit 的 `web_search` 和 `web_fetch` 自定义工具。它是 [`pi-querit`](https://www.npmjs.com/package/pi-querit) 和 [`dsh-querit`](https://www.npmjs.com/package/dsh-querit) 的 OpenCode 对应版本:插件注册两个面向模型的工具,通过 [Querit](https://www.querit.ai) 完成实时网页搜索与干净的页面内容抓取(`POST https://api.querit.ai/v1/search` 与 `/v1/contents`)。
|
|
6
|
+
|
|
7
|
+
在 [Querit.ai](https://www.querit.ai) 注册即可获得 API key,**每月免费 1,000 次 API 调用** — 无需信用卡。
|
|
8
|
+
|
|
9
|
+
## 快速开始
|
|
10
|
+
|
|
11
|
+
### 发布前本地测试
|
|
12
|
+
|
|
13
|
+
在包发布之前(或迭代期间),可以在任意 OpenCode 项目中直接加载本仓库编译好的插件:
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"$schema": "https://opencode.ai/config.json",
|
|
18
|
+
"plugin": ["file:///D:/work/queirt/querit-plugins/opencode-querit/lib/index.js"]
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
把 `file://` URL 指向你的检出目录,重启 OpenCode 即可。快速验证:调用一次 `web_search` —— 未配置 key 时它会报出 "Querit is not configured" 的可操作错误,这正说明插件已加载、工具已生效。
|
|
23
|
+
|
|
24
|
+
1. 从 npm 安装插件并添加到 `opencode.json`:
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"$schema": "https://opencode.ai/config.json",
|
|
29
|
+
"plugin": ["opencode-querit"]
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
2. 按优先级配置 Querit API key:
|
|
34
|
+
- 插件选项元组中的 `apiKey`(`["opencode-querit", { "apiKey": "..." }]`;最不推荐,密钥不应写入配置文件),或
|
|
35
|
+
- `QUERIT_API_KEY` 环境变量(默认;可通过 `apiKeyEnv` 修改变量名)。
|
|
36
|
+
3. 重启 OpenCode。未配置 key 时工具调用会失败,并给出两种配置方式的提示。
|
|
37
|
+
|
|
38
|
+
两个工具为 `web_search`(带引用的实时搜索)和 `web_fetch`(抓取最多 10 个 URL 的完整页面内容)。它们是新增工具,不会覆盖 OpenCode 自带的 `websearch`/`webfetch`;如需引导模型使用 Querit,可在 [权限](https://opencode.ai/docs/permissions/) 中限制内置工具。
|
|
39
|
+
|
|
40
|
+
## 选项
|
|
41
|
+
|
|
42
|
+
选项写在 `opencode.json` 的插件元组中:
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
{
|
|
46
|
+
"$schema": "https://opencode.ai/config.json",
|
|
47
|
+
"plugin": [
|
|
48
|
+
["opencode-querit", {
|
|
49
|
+
"count": 8,
|
|
50
|
+
"timeRange": "m3",
|
|
51
|
+
"languages": ["english"],
|
|
52
|
+
"excludeDomains": ["pinterest.com", "facebook.com", "instagram.com", "tiktok.com"]
|
|
53
|
+
}]
|
|
54
|
+
]
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
| Key | 默认值 | 含义 |
|
|
59
|
+
|---|---|---|
|
|
60
|
+
| `apiKey` | 无 | 字面量 Querit API key。优先使用 `apiKeyEnv`,密钥不要写进配置;非空字面量优先。 |
|
|
61
|
+
| `apiKeyEnv` | `QUERIT_API_KEY` | 存放 Querit API key 的环境变量名。未配置时工具调用失败并给出提示。 |
|
|
62
|
+
| `baseURL` | `https://api.querit.ai` | Querit API 基础地址;自动追加 `/v1/search` 与 `/v1/contents`。也支持 `$QUERIT_BASE_URL` 环境变量回退。 |
|
|
63
|
+
| `timeoutMs` | `70000` | 单次请求超时(毫秒,最小 1000)。 |
|
|
64
|
+
| `count` | `5` | 每次搜索的默认结果数(1–20;API 上限 20)。单次调用传入的 `count` 优先生效。 |
|
|
65
|
+
| `timeRange` | 无 | 相对(`d7`、`w2`、`m3`、`y1` 或任意 `dN`/`wN`/`mN`/`yN`)或 `YYYY-MM-DDtoYYYY-MM-DD` 日期范围。 |
|
|
66
|
+
| `countries` | 无 | 国家/地区偏向。合法值:`argentina`、`australia`、`brazil`、`canada`、`colombia`、`france`、`germany`、`india`、`indonesia`、`japan`、`mexico`、`nigeria`、`philippines`、`south korea`、`spain`、`united kingdom`、`united states`。 |
|
|
67
|
+
| `languages` | 无 | 语言过滤。合法值:`english`、`japanese`、`korean`、`german`、`french`、`spanish`、`portuguese`。 |
|
|
68
|
+
| `includeDomains` | 无 | **白名单**域名;仅这些域名返回结果。 |
|
|
69
|
+
| `excludeDomains` | 无 | **黑名单**域名;这些域名永不返回结果。 |
|
|
70
|
+
| `includeContent` | `false` | 请求句子级内容摘录(`needContent`);摘录追加到每个来源的 snippet 之后。 |
|
|
71
|
+
| `chunksPerDoc` | `1` | 每个结果的文本块数(1–3)。 |
|
|
72
|
+
| `fetchFormat` | `markdown` | 抓取调用的默认内容格式:`markdown`、`text` 或 `html`。单次调用的 `format` 优先生效。 |
|
|
73
|
+
| `fetchCrawlTimeout` | `10` | 每页抓取超时(秒,1–60)。单次调用的 `crawl_timeout` 优先生效。 |
|
|
74
|
+
| `fetchMaxChars` | `8000` | 单页正文最大字符数;被截断的页面会在工具元数据中标记 `truncated`。 |
|
|
75
|
+
| `maxOutputChars` | `200000` | 单次工具输出最大字符数。 |
|
|
76
|
+
|
|
77
|
+
## 工具
|
|
78
|
+
|
|
79
|
+
### web_search
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
query: 搜索查询。
|
|
83
|
+
count: 最大返回结果数(默认 5)。
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
搜索过滤(域名、时间范围、地区、语言、内容细节)均为插件选项中的持久默认值;单次调用参数仅限 `query` 与 `count`。返回带引用的原始结果。工具描述会提示模型:返回内容均为不可信网络数据,最终回答中应引用返回的 URL。
|
|
87
|
+
|
|
88
|
+
### web_fetch
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
url: 单个 HTTP(S) URL。
|
|
92
|
+
urls: 要抓取的 HTTP(S) URL 列表,单次最多 10 个。
|
|
93
|
+
format: 返回内容格式(默认 markdown)。
|
|
94
|
+
crawl_timeout: 每页抓取超时秒数(默认 10)。
|
|
95
|
+
include_metadata: 是否返回页面元数据(如标题、发布时间;默认 true)。
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
抓取最多 10 个 HTTP(S) URL 的完整页面内容。包含内嵌凭据的 URL 会被拒绝;每页正文上限为 `fetchMaxChars` 字符。
|
|
99
|
+
|
|
100
|
+
## 映射关系
|
|
101
|
+
|
|
102
|
+
搜索结果成为可引用的来源:`url` ← `url`,`title` ← `title`,`snippet` ← `snippet` 及可选的句子摘录,`publishedAt` ← `page_age`。结果按 URL 去重并规范化为 HTTP(S)。抓取按 `format` 返回每页内容(`text`/`markdown`/`html`);没有返回内容的页面会列在输出末尾,而不会让整个调用失败。
|
|
103
|
+
|
|
104
|
+
失败以工具错误形式呈现,API key 一律脱敏;响应有大小限制(搜索 2 MiB、内容 10 MiB),返回给模型的文本会剥离终端转义/控制序列与双向文本控制符。
|
|
105
|
+
|
|
106
|
+
## 安全
|
|
107
|
+
|
|
108
|
+
将所有搜索结果与抓取页面视为不可信的外部数据。每次调用时工具都会在输出开头提示不可信数据警告,插件也绝不执行抓取内容中的任何指令。
|
|
109
|
+
|
|
110
|
+
## 开发
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
npm install
|
|
114
|
+
npm run check # 类型检查 src + tests
|
|
115
|
+
npm test # vitest 单元测试
|
|
116
|
+
npm run build # tsc -> lib/
|
|
117
|
+
npm run test:live # 真实 API 冒烟测试(需要 QUERIT_API_KEY)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## 打包说明
|
|
121
|
+
|
|
122
|
+
`lib/` 会被提交:OpenCode 直接加载 npm 插件的编译产物,提交 lib 可让用户无需构建工具链即可从 GitHub Release 压缩包安装。`@opencode-ai/plugin` 为(可选的)peer 依赖 — OpenCode 在加载插件时解析它;本地构建时以 dev 依赖安装。
|
|
123
|
+
|
|
124
|
+
## License
|
|
125
|
+
|
|
126
|
+
MIT
|
package/README.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# opencode-querit
|
|
2
|
+
|
|
3
|
+
[](./LICENSE)
|
|
4
|
+
|
|
5
|
+
Querit-backed `web_search` and `web_fetch` custom tools for [OpenCode](https://opencode.ai). It is the OpenCode counterpart of [`pi-querit`](https://www.npmjs.com/package/pi-querit) and [`dsh-querit`](https://www.npmjs.com/package/dsh-querit): the plugin registers two model-facing tools that route through [Querit](https://www.querit.ai) — live web search and clean page content through `POST https://api.querit.ai/v1/search` and `/v1/contents`.
|
|
6
|
+
|
|
7
|
+
Sign up on [Querit.ai](https://www.querit.ai) to get an API key with **1,000 free API calls per month** — no credit card required.
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
1. Install the plugin from npm and add it to `opencode.json`:
|
|
12
|
+
|
|
13
|
+
```json
|
|
14
|
+
{
|
|
15
|
+
"$schema": "https://opencode.ai/config.json",
|
|
16
|
+
"plugin": ["opencode-querit"]
|
|
17
|
+
}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
2. Configure your Querit API key in priority order:
|
|
21
|
+
- `apiKey` in the plugin options tuple (`["opencode-querit", { "apiKey": "..." }]`; least preferred — secrets should not live in config files), or
|
|
22
|
+
- the `QUERIT_API_KEY` environment variable (default; override the name with `apiKeyEnv`).
|
|
23
|
+
3. Restart OpenCode. A tool call without a key fails with a message that spells out both options.
|
|
24
|
+
|
|
25
|
+
The two tools are `web_search` (live web search with cited results) and `web_fetch` (full page content for up to 10 URLs). They are additive: OpenCode's built-in `websearch`/`webfetch` tools stay available. To steer the model to Querit, mention the tools or restrict the built-ins through [permissions](https://opencode.ai/docs/permissions/).
|
|
26
|
+
|
|
27
|
+
### Test locally before publishing
|
|
28
|
+
|
|
29
|
+
Until the package is published (or to iterate on it), load the compiled plugin straight from this repository in any OpenCode project:
|
|
30
|
+
|
|
31
|
+
```json
|
|
32
|
+
{
|
|
33
|
+
"$schema": "https://opencode.ai/config.json",
|
|
34
|
+
"plugin": ["file:///D:/work/queirt/querit-plugins/opencode-querit/lib/index.js"]
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Point the `file://` URL at your checkout and restart OpenCode; the tools appear alongside the built-ins. Verify quickly with a `web_search` call — without a configured key it fails with the actionable "Querit is not configured" message, which confirms the plugin loaded and the tools are wired.
|
|
39
|
+
|
|
40
|
+
## Options
|
|
41
|
+
|
|
42
|
+
Options go in the plugin tuple in `opencode.json`:
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
{
|
|
46
|
+
"$schema": "https://opencode.ai/config.json",
|
|
47
|
+
"plugin": [
|
|
48
|
+
["opencode-querit", {
|
|
49
|
+
"count": 8,
|
|
50
|
+
"timeRange": "m3",
|
|
51
|
+
"languages": ["english"],
|
|
52
|
+
"excludeDomains": ["pinterest.com", "facebook.com", "instagram.com", "tiktok.com"]
|
|
53
|
+
}]
|
|
54
|
+
]
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
| Key | Default | Meaning |
|
|
59
|
+
|---|---|---|
|
|
60
|
+
| `apiKey` | omitted | Literal Querit API key. Prefer `apiKeyEnv` so no secret enters configuration; a non-empty literal wins. |
|
|
61
|
+
| `apiKeyEnv` | `QUERIT_API_KEY` | Environment variable holding the Querit API key. A missing value fails the tool call with an actionable message. |
|
|
62
|
+
| `baseURL` | `https://api.querit.ai` | Querit API base; `/v1/search` and `/v1/contents` are appended. Falls back to `$QUERIT_BASE_URL`. |
|
|
63
|
+
| `timeoutMs` | `70000` | Per-request timeout in ms (minimum 1000). |
|
|
64
|
+
| `count` | `5` | Default result count per search (1–20; the API caps at 20). Per-call `count` overrides it. |
|
|
65
|
+
| `timeRange` | none | Relative (`d7`, `w2`, `m3`, `y1`, or any `dN`/`wN`/`mN`/`yN`) or `YYYY-MM-DDtoYYYY-MM-DD` date range. |
|
|
66
|
+
| `countries` | none | Country bias. Valid values: `argentina`, `australia`, `brazil`, `canada`, `colombia`, `france`, `germany`, `india`, `indonesia`, `japan`, `mexico`, `nigeria`, `philippines`, `south korea`, `spain`, `united kingdom`, `united states`. |
|
|
67
|
+
| `languages` | none | Language filter. Valid values: `english`, `japanese`, `korean`, `german`, `french`, `spanish`, `portuguese`. |
|
|
68
|
+
| `includeDomains` | none | **Whitelist** hostnames; only these domains return results. |
|
|
69
|
+
| `excludeDomains` | none | **Blacklist** hostnames; these domains never return results. |
|
|
70
|
+
| `includeContent` | `false` | Request sentence-level content excerpts (`needContent`); excerpts are appended to each source's snippet. |
|
|
71
|
+
| `chunksPerDoc` | `1` | Content chunks per result (1–3). |
|
|
72
|
+
| `fetchFormat` | `markdown` | Default format requested from `/v1/contents` for fetch calls: `markdown`, `text`, or `html`. Per-call `format` overrides it. |
|
|
73
|
+
| `fetchCrawlTimeout` | `10` | Per-page crawl timeout in seconds (1–60). Per-call `crawl_timeout` overrides it. |
|
|
74
|
+
| `fetchMaxChars` | `8000` | Cap applied to one fetched page's decoded body, in chars; a cut page is flagged `truncated` in the tool metadata. |
|
|
75
|
+
| `maxOutputChars` | `200000` | Cap on one tool's rendered output, in chars. |
|
|
76
|
+
|
|
77
|
+
## Tools
|
|
78
|
+
|
|
79
|
+
### web_search
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
query: The web search query.
|
|
83
|
+
count: Maximum results to return (default: 5).
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Search filters (domains, time range, region, language, content detail) are persistent defaults from the plugin options; per-call parameters are limited to `query` and `count`. Returns raw cited results. The tool description instructs the model to treat everything returned as untrusted web data and to cite the returned URLs.
|
|
87
|
+
|
|
88
|
+
### web_fetch
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
url: A single HTTP(S) URL to fetch.
|
|
92
|
+
urls: HTTP(S) URLs to fetch. At most 10 URLs per call.
|
|
93
|
+
format: Returned content format (default: markdown).
|
|
94
|
+
crawl_timeout: Per-page crawl timeout in seconds (default: 10).
|
|
95
|
+
include_metadata: Include page metadata such as title and publication time (default: true).
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Fetches full page content for up to 10 HTTP(S) URLs. URLs with embedded credentials are rejected, and every fetched page is capped at `fetchMaxChars` chars.
|
|
99
|
+
|
|
100
|
+
## Mapping
|
|
101
|
+
|
|
102
|
+
Search results become citeable sources: `url` ← `url`, `title` ← `title`, `snippet` ← `snippet` plus requested sentence excerpts, `publishedAt` ← `page_age`. Results are deduplicated by URL and normalized to HTTP(S). Fetch maps each crawled page to its content (`text`/`markdown`/`html` per `format`); pages without returned content are listed at the end of the output instead of failing the whole call.
|
|
103
|
+
|
|
104
|
+
Failures surface as tool errors with the API key redacted; responses are size-limited (2 MiB search, 10 MiB contents) and retrieved text is stripped of terminal escape/control sequences and bidi controls before the model sees it.
|
|
105
|
+
|
|
106
|
+
## Safety
|
|
107
|
+
|
|
108
|
+
Treat every search result and retrieved page as untrusted external data. The tools tell the model this on every call (the rendered output always opens with an untrusted-data warning), and the plugin never follows instructions found in retrieved content.
|
|
109
|
+
|
|
110
|
+
## Development
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
npm install
|
|
114
|
+
npm run check # typecheck src + tests
|
|
115
|
+
npm test # vitest unit tests
|
|
116
|
+
npm run build # tsc -> lib/
|
|
117
|
+
npm run test:live # live smoke test against the real API (needs QUERIT_API_KEY)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Packaging notes
|
|
121
|
+
|
|
122
|
+
`lib/` is committed: OpenCode loads npm plugins directly from the compiled package, and committing it lets users install from GitHub Release tarballs without a build toolchain. `@opencode-ai/plugin` is an (optional) peer dependency — OpenCode resolves it at plugin load time; install it as a dev dependency for local builds.
|
|
123
|
+
|
|
124
|
+
## License
|
|
125
|
+
|
|
126
|
+
MIT
|
package/lib/client.d.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
export declare const QUERIT_API_BASE_URL = "https://api.querit.ai";
|
|
2
|
+
export declare const DEFAULT_REQUEST_TIMEOUT_MS = 70000;
|
|
3
|
+
export interface QueritSearchRequest {
|
|
4
|
+
query: string;
|
|
5
|
+
count: number;
|
|
6
|
+
chunksPerDoc?: number;
|
|
7
|
+
needContent?: boolean;
|
|
8
|
+
filters?: {
|
|
9
|
+
sites?: {
|
|
10
|
+
include?: string[];
|
|
11
|
+
exclude?: string[];
|
|
12
|
+
};
|
|
13
|
+
timeRange?: {
|
|
14
|
+
date: string;
|
|
15
|
+
};
|
|
16
|
+
geo?: {
|
|
17
|
+
countries: {
|
|
18
|
+
include: string[];
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
languages?: {
|
|
22
|
+
include: string[];
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export interface QueritContentsRequest {
|
|
27
|
+
urls: string[];
|
|
28
|
+
format: "text" | "markdown" | "html";
|
|
29
|
+
crawlTimeout: number;
|
|
30
|
+
extrasMeta: boolean;
|
|
31
|
+
}
|
|
32
|
+
export interface QueritSearchResult {
|
|
33
|
+
title: string;
|
|
34
|
+
url: string;
|
|
35
|
+
snippet: string;
|
|
36
|
+
pageAge?: string;
|
|
37
|
+
siteName?: string;
|
|
38
|
+
siteIcon?: string;
|
|
39
|
+
sentences: string[];
|
|
40
|
+
}
|
|
41
|
+
export interface QueritSearchResponse {
|
|
42
|
+
searchId?: string;
|
|
43
|
+
took?: string;
|
|
44
|
+
query: string;
|
|
45
|
+
results: QueritSearchResult[];
|
|
46
|
+
}
|
|
47
|
+
export interface QueritContentMetadata {
|
|
48
|
+
title?: string;
|
|
49
|
+
url?: string;
|
|
50
|
+
publishTime?: string;
|
|
51
|
+
siteName?: string;
|
|
52
|
+
siteIcon?: string;
|
|
53
|
+
}
|
|
54
|
+
export interface QueritContentResult {
|
|
55
|
+
id?: string;
|
|
56
|
+
url: string;
|
|
57
|
+
content: string;
|
|
58
|
+
metadata?: QueritContentMetadata;
|
|
59
|
+
}
|
|
60
|
+
export interface QueritContentStatus {
|
|
61
|
+
id?: string;
|
|
62
|
+
status?: string;
|
|
63
|
+
}
|
|
64
|
+
export interface QueritContentsResponse {
|
|
65
|
+
searchId?: string;
|
|
66
|
+
results: QueritContentResult[];
|
|
67
|
+
statuses: QueritContentStatus[];
|
|
68
|
+
searchTime?: number;
|
|
69
|
+
}
|
|
70
|
+
export interface QueritClientOptions {
|
|
71
|
+
apiKey: string;
|
|
72
|
+
fetchImpl?: typeof fetch;
|
|
73
|
+
baseUrl?: string;
|
|
74
|
+
timeoutMs?: number;
|
|
75
|
+
}
|
|
76
|
+
export declare class QueritApiError extends Error {
|
|
77
|
+
readonly status?: number;
|
|
78
|
+
readonly searchId?: string;
|
|
79
|
+
constructor(message: string, options?: {
|
|
80
|
+
status?: number;
|
|
81
|
+
searchId?: string;
|
|
82
|
+
cause?: unknown;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
export declare class QueritClient {
|
|
86
|
+
private readonly apiKey;
|
|
87
|
+
private readonly fetchImpl;
|
|
88
|
+
private readonly baseUrl;
|
|
89
|
+
private readonly timeoutMs;
|
|
90
|
+
constructor(options: QueritClientOptions);
|
|
91
|
+
search(request: QueritSearchRequest, signal?: AbortSignal): Promise<QueritSearchResponse>;
|
|
92
|
+
contents(request: QueritContentsRequest, signal?: AbortSignal): Promise<QueritContentsResponse>;
|
|
93
|
+
private postJson;
|
|
94
|
+
}
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential-safe client for the public Querit API
|
|
3
|
+
* (`POST https://api.querit.ai/v1/search` and `/v1/contents`).
|
|
4
|
+
* Structure follows the client shipped by pi-querit / dsh-querit (MIT):
|
|
5
|
+
* response-size limits, deduplication, URL normalization, and API-key
|
|
6
|
+
* redaction from every error surface.
|
|
7
|
+
* @module opencode-querit/client
|
|
8
|
+
*/
|
|
9
|
+
import { sanitizeUntrustedText } from "./sanitize.js";
|
|
10
|
+
export const QUERIT_API_BASE_URL = "https://api.querit.ai";
|
|
11
|
+
export const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
|
|
12
|
+
const SEARCH_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
13
|
+
const CONTENTS_RESPONSE_MAX_BYTES = 10 * 1024 * 1024;
|
|
14
|
+
const ERROR_RESPONSE_MAX_BYTES = 8 * 1024;
|
|
15
|
+
export class QueritApiError extends Error {
|
|
16
|
+
status;
|
|
17
|
+
searchId;
|
|
18
|
+
constructor(message, options = {}) {
|
|
19
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
20
|
+
this.name = "QueritApiError";
|
|
21
|
+
this.status = options.status;
|
|
22
|
+
this.searchId = options.searchId;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export class QueritClient {
|
|
26
|
+
apiKey;
|
|
27
|
+
fetchImpl;
|
|
28
|
+
baseUrl;
|
|
29
|
+
timeoutMs;
|
|
30
|
+
constructor(options) {
|
|
31
|
+
const apiKey = options.apiKey.trim();
|
|
32
|
+
if (!apiKey) {
|
|
33
|
+
throw new QueritApiError("A Querit API key is required.");
|
|
34
|
+
}
|
|
35
|
+
this.apiKey = apiKey;
|
|
36
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
37
|
+
this.baseUrl = (options.baseUrl ?? QUERIT_API_BASE_URL).replace(/\/+$/, "");
|
|
38
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
39
|
+
}
|
|
40
|
+
async search(request, signal) {
|
|
41
|
+
const response = await this.postJson("/v1/search", request, SEARCH_RESPONSE_MAX_BYTES, signal);
|
|
42
|
+
return normalizeSearchResponse(response.body, response.searchId, request.query);
|
|
43
|
+
}
|
|
44
|
+
async contents(request, signal) {
|
|
45
|
+
const response = await this.postJson("/v1/contents", request, CONTENTS_RESPONSE_MAX_BYTES, signal);
|
|
46
|
+
return normalizeContentsResponse(response.body, response.searchId);
|
|
47
|
+
}
|
|
48
|
+
async postJson(path, requestBody, responseLimit, callerSignal) {
|
|
49
|
+
const timeoutSignal = AbortSignal.timeout(this.timeoutMs);
|
|
50
|
+
const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
|
|
51
|
+
let response;
|
|
52
|
+
try {
|
|
53
|
+
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
54
|
+
method: "POST",
|
|
55
|
+
headers: {
|
|
56
|
+
Accept: "application/json",
|
|
57
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
58
|
+
"Content-Type": "application/json",
|
|
59
|
+
},
|
|
60
|
+
body: JSON.stringify(requestBody),
|
|
61
|
+
signal,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (callerSignal?.aborted) {
|
|
66
|
+
throw new QueritApiError("Querit request was cancelled.", { cause: error });
|
|
67
|
+
}
|
|
68
|
+
if (timeoutSignal.aborted) {
|
|
69
|
+
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, { cause: error });
|
|
70
|
+
}
|
|
71
|
+
throw new QueritApiError(`Querit request failed: ${errorMessage(error)}`, { cause: error });
|
|
72
|
+
}
|
|
73
|
+
const bodyLimit = response.ok ? responseLimit : ERROR_RESPONSE_MAX_BYTES;
|
|
74
|
+
let text;
|
|
75
|
+
try {
|
|
76
|
+
text = await readResponseText(response, bodyLimit);
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
if (callerSignal?.aborted) {
|
|
80
|
+
throw new QueritApiError("Querit request was cancelled.", { status: response.status, cause: error });
|
|
81
|
+
}
|
|
82
|
+
if (timeoutSignal.aborted) {
|
|
83
|
+
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, {
|
|
84
|
+
status: response.status,
|
|
85
|
+
cause: error,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
throw new QueritApiError(`Could not read the Querit response: ${errorMessage(error)}`, {
|
|
89
|
+
status: response.status,
|
|
90
|
+
cause: error,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
const searchId = extractSearchId(text);
|
|
94
|
+
let payload;
|
|
95
|
+
try {
|
|
96
|
+
payload = JSON.parse(text);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
const excerpt = redactSecret(text.slice(0, 500), this.apiKey);
|
|
100
|
+
if (!response.ok) {
|
|
101
|
+
throw new QueritApiError(`Querit API request failed with HTTP ${response.status}${excerpt ? `: ${excerpt}` : "."}`, { status: response.status, searchId, cause: error });
|
|
102
|
+
}
|
|
103
|
+
throw new QueritApiError(`Querit returned invalid JSON${excerpt ? `: ${excerpt}` : "."}`, { status: response.status, searchId, cause: error });
|
|
104
|
+
}
|
|
105
|
+
if (!isRecord(payload)) {
|
|
106
|
+
throw new QueritApiError("Querit returned an invalid response object.", {
|
|
107
|
+
status: response.status,
|
|
108
|
+
searchId,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const apiErrorCode = optionalString(payload.error_code);
|
|
112
|
+
const apiErrorMessage = optionalString(payload.error_msg);
|
|
113
|
+
const numericErrorCode = apiErrorCode === undefined ? undefined : Number(apiErrorCode);
|
|
114
|
+
if (!response.ok || (Number.isFinite(numericErrorCode) && numericErrorCode !== 200)) {
|
|
115
|
+
const message = redactSecret(apiErrorMessage ?? `Querit API request failed with HTTP ${response.status}.`, this.apiKey);
|
|
116
|
+
throw new QueritApiError(message, { status: response.status, searchId });
|
|
117
|
+
}
|
|
118
|
+
return { body: payload, searchId };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
async function readResponseText(response, maxBytes) {
|
|
122
|
+
const contentLength = response.headers.get("content-length");
|
|
123
|
+
if (contentLength !== null) {
|
|
124
|
+
const declaredLength = Number(contentLength);
|
|
125
|
+
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
|
|
126
|
+
throw new Error(`response exceeds the ${maxBytes}-byte limit`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (!response.body) {
|
|
130
|
+
return "";
|
|
131
|
+
}
|
|
132
|
+
const reader = response.body.getReader();
|
|
133
|
+
const decoder = new TextDecoder();
|
|
134
|
+
const chunks = [];
|
|
135
|
+
let totalBytes = 0;
|
|
136
|
+
try {
|
|
137
|
+
while (true) {
|
|
138
|
+
const { done, value } = await reader.read();
|
|
139
|
+
if (done)
|
|
140
|
+
break;
|
|
141
|
+
totalBytes += value.byteLength;
|
|
142
|
+
if (totalBytes > maxBytes) {
|
|
143
|
+
await reader.cancel("response size limit exceeded");
|
|
144
|
+
throw new Error(`response exceeds the ${maxBytes}-byte limit`);
|
|
145
|
+
}
|
|
146
|
+
chunks.push(decoder.decode(value, { stream: true }));
|
|
147
|
+
}
|
|
148
|
+
chunks.push(decoder.decode());
|
|
149
|
+
return chunks.join("");
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
reader.releaseLock();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function normalizeSearchResponse(payload, searchId, requestedQuery) {
|
|
156
|
+
const resultsContainer = payload.results;
|
|
157
|
+
if (!isRecord(resultsContainer) || !Array.isArray(resultsContainer.result)) {
|
|
158
|
+
throw new QueritApiError("Querit search response is missing results.result.", { searchId });
|
|
159
|
+
}
|
|
160
|
+
const deduplicated = new Map();
|
|
161
|
+
for (const rawItem of resultsContainer.result) {
|
|
162
|
+
if (!isRecord(rawItem))
|
|
163
|
+
continue;
|
|
164
|
+
const url = normalizeHttpUrl(rawItem.url);
|
|
165
|
+
if (!url || deduplicated.has(url))
|
|
166
|
+
continue;
|
|
167
|
+
deduplicated.set(url, {
|
|
168
|
+
title: optionalString(rawItem.title) ?? url,
|
|
169
|
+
url,
|
|
170
|
+
snippet: optionalString(rawItem.snippet) ?? "",
|
|
171
|
+
pageAge: optionalString(rawItem.page_age),
|
|
172
|
+
siteName: optionalString(rawItem.site_name),
|
|
173
|
+
siteIcon: optionalString(rawItem.site_icon),
|
|
174
|
+
sentences: Array.isArray(rawItem.sentence)
|
|
175
|
+
? rawItem.sentence.filter((value) => typeof value === "string")
|
|
176
|
+
: [],
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
const queryContext = isRecord(payload.query_context) ? payload.query_context : undefined;
|
|
180
|
+
return {
|
|
181
|
+
searchId,
|
|
182
|
+
took: optionalString(payload.took),
|
|
183
|
+
query: queryContext ? optionalString(queryContext.query) ?? requestedQuery : requestedQuery,
|
|
184
|
+
results: [...deduplicated.values()],
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
function normalizeContentsResponse(payload, searchId) {
|
|
188
|
+
if (!Array.isArray(payload.results) || !Array.isArray(payload.statuses)) {
|
|
189
|
+
throw new QueritApiError("Querit contents response is missing results or statuses.", { searchId });
|
|
190
|
+
}
|
|
191
|
+
const deduplicated = new Map();
|
|
192
|
+
for (const rawResult of payload.results) {
|
|
193
|
+
if (!isRecord(rawResult))
|
|
194
|
+
continue;
|
|
195
|
+
const url = normalizeHttpUrl(rawResult.url);
|
|
196
|
+
if (!url || deduplicated.has(url))
|
|
197
|
+
continue;
|
|
198
|
+
const rawMetadata = isRecord(rawResult.extrasMeta) ? rawResult.extrasMeta : undefined;
|
|
199
|
+
const metadata = rawMetadata
|
|
200
|
+
? {
|
|
201
|
+
title: optionalString(rawMetadata.title),
|
|
202
|
+
url: normalizeHttpUrl(rawMetadata.url),
|
|
203
|
+
publishTime: optionalString(rawMetadata.publishTime),
|
|
204
|
+
siteName: optionalString(rawMetadata.siteName),
|
|
205
|
+
siteIcon: normalizeHttpUrl(rawMetadata.siteIcon),
|
|
206
|
+
}
|
|
207
|
+
: undefined;
|
|
208
|
+
deduplicated.set(url, {
|
|
209
|
+
id: optionalString(rawResult.id),
|
|
210
|
+
url,
|
|
211
|
+
content: optionalString(rawResult.content) ?? "",
|
|
212
|
+
metadata,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
const statuses = payload.statuses
|
|
216
|
+
.filter(isRecord)
|
|
217
|
+
.map((status) => ({
|
|
218
|
+
id: optionalString(status.id),
|
|
219
|
+
status: optionalString(status.status),
|
|
220
|
+
}));
|
|
221
|
+
return {
|
|
222
|
+
searchId,
|
|
223
|
+
results: [...deduplicated.values()],
|
|
224
|
+
statuses,
|
|
225
|
+
searchTime: optionalNumber(payload.searchTime),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
function extractSearchId(text) {
|
|
229
|
+
const match = /"search_id"\s*:\s*(?:"([^"]+)"|(-?\d+))/.exec(text);
|
|
230
|
+
const value = match?.[1] ?? match?.[2];
|
|
231
|
+
return value && /^-?\d+$/.test(value) ? value : undefined;
|
|
232
|
+
}
|
|
233
|
+
function normalizeHttpUrl(value) {
|
|
234
|
+
if (typeof value !== "string")
|
|
235
|
+
return undefined;
|
|
236
|
+
try {
|
|
237
|
+
const url = new URL(value);
|
|
238
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
239
|
+
return undefined;
|
|
240
|
+
return url.toString();
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
return undefined;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function redactSecret(text, secret) {
|
|
247
|
+
const redacted = secret ? text.split(secret).join("[REDACTED]") : text;
|
|
248
|
+
return sanitizeUntrustedText(redacted);
|
|
249
|
+
}
|
|
250
|
+
function optionalString(value) {
|
|
251
|
+
if (typeof value === "string")
|
|
252
|
+
return value;
|
|
253
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
254
|
+
return String(value);
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
function optionalNumber(value) {
|
|
258
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
259
|
+
}
|
|
260
|
+
function isRecord(value) {
|
|
261
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
262
|
+
}
|
|
263
|
+
function errorMessage(error) {
|
|
264
|
+
return sanitizeUntrustedText(error instanceof Error ? error.message : String(error));
|
|
265
|
+
}
|