@oyasmi/pipiclaw 0.9.6-beta.2 → 0.9.6-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +2 -2
- package/README.md +2 -2
- package/dist/agent/channel-runner.js +2 -0
- package/dist/agent/maintenance-context.js +21 -2
- package/dist/agent/turn/turn-context.js +10 -6
- package/dist/config/settings.d.ts +0 -2
- package/dist/config/settings.js +0 -2
- package/dist/config/tools.d.ts +8 -2
- package/dist/config/tools.js +35 -19
- package/dist/memory/anchors.d.ts +5 -0
- package/dist/memory/anchors.js +49 -0
- package/dist/memory/boundary-work.d.ts +1 -0
- package/dist/memory/boundary-work.js +1 -0
- package/dist/memory/commands.js +23 -6
- package/dist/memory/index-budget.d.ts +16 -0
- package/dist/memory/index-budget.js +24 -2
- package/dist/memory/journal.d.ts +7 -12
- package/dist/memory/journal.js +9 -41
- package/dist/memory/lifecycle.d.ts +1 -0
- package/dist/memory/lifecycle.js +2 -0
- package/dist/memory/reflect-job.d.ts +1 -0
- package/dist/memory/reflect-job.js +1 -0
- package/dist/memory/reflect.d.ts +10 -0
- package/dist/memory/reflect.js +103 -20
- package/dist/memory/render.d.ts +4 -1
- package/dist/memory/render.js +6 -4
- package/dist/memory/review-log.d.ts +2 -2
- package/dist/memory/scheduler.d.ts +7 -0
- package/dist/memory/scheduler.js +70 -3
- package/dist/memory/search-index-db.d.ts +15 -0
- package/dist/memory/search-index-db.js +247 -0
- package/dist/memory/search-index-files.d.ts +11 -0
- package/dist/memory/search-index-files.js +26 -0
- package/dist/memory/search-index-notes.d.ts +11 -0
- package/dist/memory/search-index-notes.js +155 -0
- package/dist/memory/search-index-sync.d.ts +19 -0
- package/dist/memory/search-index-sync.js +267 -0
- package/dist/memory/search-terms.d.ts +12 -0
- package/dist/memory/search-terms.js +185 -0
- package/dist/memory/search.d.ts +8 -28
- package/dist/memory/search.js +18 -278
- package/dist/memory/session-corpus.d.ts +15 -26
- package/dist/memory/session-corpus.js +120 -327
- package/dist/memory/session-search.d.ts +5 -3
- package/dist/memory/session-search.js +119 -171
- package/dist/memory/sidecar-worker.d.ts +2 -0
- package/dist/memory/sidecar-worker.js +25 -1
- package/dist/memory/store.d.ts +4 -0
- package/dist/memory/store.js +22 -1
- package/dist/memory/task-archive-digest.d.ts +61 -0
- package/dist/memory/task-archive-digest.js +366 -0
- package/dist/models/provider-login.d.ts +1 -1
- package/dist/models/provider-login.js +1 -1
- package/dist/playbooks/memory-operations.md +2 -2
- package/dist/shared/text-utils.d.ts +0 -1
- package/dist/shared/text-utils.js +0 -1
- package/dist/subagents/runs.d.ts +1 -1
- package/dist/subagents/task-envelope.js +6 -8
- package/dist/tools/memory-manage.d.ts +1 -0
- package/dist/tools/memory-manage.js +9 -23
- package/dist/tools/registry.js +2 -0
- package/dist/tools/session-search.d.ts +1 -0
- package/dist/tools/session-search.js +12 -6
- package/dist/tools/web-search.d.ts +13 -7
- package/dist/tools/web-search.js +62 -19
- package/dist/web/client.d.ts +2 -0
- package/dist/web/client.js +7 -3
- package/dist/web/config.d.ts +17 -4
- package/dist/web/config.js +42 -4
- package/dist/web/format.d.ts +2 -1
- package/dist/web/format.js +7 -3
- package/dist/web/search-providers.d.ts +15 -8
- package/dist/web/search-providers.js +208 -139
- package/dist/web/search.d.ts +13 -3
- package/dist/web/search.js +86 -40
- package/package.json +1 -1
- package/dist/memory/chinese-words.d.ts +0 -1
- package/dist/memory/chinese-words.js +0 -273
|
@@ -1,166 +1,235 @@
|
|
|
1
|
+
import { isAxiosError } from "axios";
|
|
1
2
|
import { JSDOM } from "jsdom";
|
|
3
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
4
|
+
import { WebResponseError } from "./client.js";
|
|
5
|
+
import { hasSearchFilters, isSearchDate } from "./config.js";
|
|
2
6
|
export class WebSearchProviderError extends Error {
|
|
3
7
|
constructor(kind, message) {
|
|
4
8
|
super(message);
|
|
5
|
-
this.name = "WebSearchProviderError";
|
|
6
9
|
this.kind = kind;
|
|
10
|
+
this.name = "WebSearchProviderError";
|
|
7
11
|
}
|
|
8
12
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
14
|
+
const MAX_SNIPPET_CHARS = 1_500;
|
|
15
|
+
const DUCKDUCKGO_URL = "https://html.duckduckgo.com/html/";
|
|
16
|
+
function responseError(provider, status) {
|
|
17
|
+
const prefix = `${provider} search returned HTTP ${status}.`;
|
|
18
|
+
if (status === 429)
|
|
19
|
+
return new WebSearchProviderError("rate_limit", `${prefix} Wait before retrying or use another source.`);
|
|
20
|
+
if (status === 408 || status === 504) {
|
|
21
|
+
return new WebSearchProviderError("timeout", `${prefix} Retry once or narrow the search.`);
|
|
15
22
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
23
|
+
if ([401, 402, 403, 404].includes(status)) {
|
|
24
|
+
return new WebSearchProviderError("configuration", `${prefix} Ask the operator to check the provider settings and account access.`);
|
|
25
|
+
}
|
|
26
|
+
if (status === 400 || status === 422) {
|
|
27
|
+
return new WebSearchProviderError("invalid_request", `${prefix} Check the query and filters and retry once.`);
|
|
28
|
+
}
|
|
29
|
+
return new WebSearchProviderError("unavailable", `${prefix} Retry later or use another source.`);
|
|
21
30
|
}
|
|
22
|
-
function
|
|
23
|
-
return
|
|
31
|
+
function invalidResponse(provider) {
|
|
32
|
+
return new WebSearchProviderError("invalid_response", `${provider} search returned an unexpected response. Use another source or retry later.`);
|
|
24
33
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
34
|
+
async function requestSearchText(context, options) {
|
|
35
|
+
const { client, backend, signal, timeoutMs } = context;
|
|
36
|
+
const { provider } = backend;
|
|
37
|
+
let payload;
|
|
38
|
+
try {
|
|
39
|
+
payload = await client.requestText({ ...options, timeoutMs, signal, maxResponseBytes: MAX_RESPONSE_BYTES });
|
|
28
40
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
Authorization: `Bearer ${this.context.config.apiKey}`,
|
|
38
|
-
"Content-Type": "application/json",
|
|
39
|
-
Accept: "application/json",
|
|
40
|
-
},
|
|
41
|
-
data: { query, max_results: count },
|
|
42
|
-
timeoutMs: this.context.config.timeoutMs,
|
|
43
|
-
signal,
|
|
44
|
-
});
|
|
45
|
-
if (response.status < 200 || response.status >= 300) {
|
|
46
|
-
throw new WebSearchProviderError(isProviderConfigStatus(response.status) ? "config" : "provider", `Tavily search failed with HTTP ${response.status}`);
|
|
41
|
+
catch (error) {
|
|
42
|
+
signal.throwIfAborted();
|
|
43
|
+
if (error instanceof WebResponseError)
|
|
44
|
+
throw invalidResponse(provider);
|
|
45
|
+
if (!isAxiosError(error))
|
|
46
|
+
throw error;
|
|
47
|
+
if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT") {
|
|
48
|
+
throw new WebSearchProviderError("timeout", `${provider} search timed out. Retry once or narrow the search.`);
|
|
47
49
|
}
|
|
48
|
-
|
|
49
|
-
.map((item) => normalizeResult({
|
|
50
|
-
title: item.title,
|
|
51
|
-
url: item.url,
|
|
52
|
-
snippet: item.content,
|
|
53
|
-
}))
|
|
54
|
-
.filter((item) => item !== null)
|
|
55
|
-
.slice(0, count);
|
|
50
|
+
throw new WebSearchProviderError("unavailable", `${provider} search could not reach the server. Use another source or retry later.`);
|
|
56
51
|
}
|
|
52
|
+
const { status } = payload.response;
|
|
53
|
+
if (provider === "duckduckgo" && status === 202)
|
|
54
|
+
throw duckDuckGoChallenge();
|
|
55
|
+
if (status !== 200)
|
|
56
|
+
throw responseError(provider, status);
|
|
57
|
+
return payload.text;
|
|
57
58
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
59
|
+
function decodeSearchJson(text, provider) {
|
|
60
|
+
let data;
|
|
61
|
+
try {
|
|
62
|
+
data = JSON.parse(text);
|
|
61
63
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
throw new WebSearchProviderError("config", "Jina search requires tools.web.search.apiKey");
|
|
65
|
-
}
|
|
66
|
-
const { response, data } = await this.context.client.requestJson({
|
|
67
|
-
url: `https://s.jina.ai/${encodeURIComponent(query)}`,
|
|
68
|
-
headers: {
|
|
69
|
-
Authorization: `Bearer ${this.context.config.apiKey}`,
|
|
70
|
-
Accept: "application/json",
|
|
71
|
-
},
|
|
72
|
-
timeoutMs: this.context.config.timeoutMs,
|
|
73
|
-
signal,
|
|
74
|
-
});
|
|
75
|
-
if (response.status < 200 || response.status >= 300) {
|
|
76
|
-
throw new WebSearchProviderError(isProviderConfigStatus(response.status) ? "config" : "provider", `Jina search failed with HTTP ${response.status}`);
|
|
77
|
-
}
|
|
78
|
-
return (data.data ?? [])
|
|
79
|
-
.map((item) => normalizeResult({
|
|
80
|
-
title: item.title,
|
|
81
|
-
url: item.url,
|
|
82
|
-
snippet: item.content,
|
|
83
|
-
}))
|
|
84
|
-
.filter((item) => item !== null)
|
|
85
|
-
.slice(0, count);
|
|
64
|
+
catch {
|
|
65
|
+
throw invalidResponse(provider);
|
|
86
66
|
}
|
|
67
|
+
if (!isRecord(data))
|
|
68
|
+
throw invalidResponse(provider);
|
|
69
|
+
return data;
|
|
87
70
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
.filter((item) => item !== null)
|
|
113
|
-
.slice(0, count);
|
|
71
|
+
function buildResult(title, href, excerpt, date) {
|
|
72
|
+
if (typeof href !== "string")
|
|
73
|
+
return null;
|
|
74
|
+
const url = URL.parse(href.trim());
|
|
75
|
+
if (!url || !["https:", "http:"].includes(url.protocol) || url.username || url.password)
|
|
76
|
+
return null;
|
|
77
|
+
const publishedDate = typeof date === "string" ? /^\d{4}-\d{2}-\d{2}(?=$|T)/.exec(date)?.[0] : undefined;
|
|
78
|
+
return {
|
|
79
|
+
title: (typeof title === "string" ? title.trim().slice(0, 300) : "") || url.href,
|
|
80
|
+
url: url.href,
|
|
81
|
+
snippet: typeof excerpt === "string" ? excerpt.trim().slice(0, MAX_SNIPPET_CHARS) : "",
|
|
82
|
+
...(publishedDate && isSearchDate(publishedDate) ? { publishedDate } : {}),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function resultList(data, context, count, parse) {
|
|
86
|
+
if (!Array.isArray(data))
|
|
87
|
+
throw invalidResponse(context.backend.provider);
|
|
88
|
+
const results = [];
|
|
89
|
+
for (const row of data) {
|
|
90
|
+
const result = isRecord(row) ? parse(row) : null;
|
|
91
|
+
if (result)
|
|
92
|
+
results.push(result);
|
|
93
|
+
if (results.length >= count)
|
|
94
|
+
break;
|
|
114
95
|
}
|
|
96
|
+
if (data.length > 0 && results.length === 0)
|
|
97
|
+
throw invalidResponse(context.backend.provider);
|
|
98
|
+
return results;
|
|
99
|
+
}
|
|
100
|
+
function requireApiKey(context) {
|
|
101
|
+
const { provider, apiKey } = context.backend;
|
|
102
|
+
const key = apiKey || (provider === "parallel" ? process.env.PARALLEL_API_KEY?.trim() : undefined);
|
|
103
|
+
if (key)
|
|
104
|
+
return key;
|
|
105
|
+
const envHint = provider === "parallel" ? " or set PARALLEL_API_KEY" : "";
|
|
106
|
+
throw new WebSearchProviderError("configuration", `${provider} search requires an API key. Ask the operator to set the apiKey for this search provider in tools.json${envHint}.`);
|
|
115
107
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
108
|
+
async function searchParallel(context, request) {
|
|
109
|
+
const { objective, queries, count, includeDomains, excludeDomains, publishedAfter } = request;
|
|
110
|
+
const text = await requestSearchText(context, {
|
|
111
|
+
method: "POST",
|
|
112
|
+
url: "https://api.parallel.ai/v1/search",
|
|
113
|
+
headers: { "x-api-key": requireApiKey(context), "Content-Type": "application/json", Accept: "application/json" },
|
|
114
|
+
data: {
|
|
115
|
+
objective,
|
|
116
|
+
search_queries: queries,
|
|
117
|
+
mode: context.parallelMode,
|
|
118
|
+
max_chars_total: count * MAX_SNIPPET_CHARS,
|
|
119
|
+
advanced_settings: {
|
|
120
|
+
max_results: count,
|
|
121
|
+
...(hasSearchFilters(request)
|
|
122
|
+
? {
|
|
123
|
+
source_policy: {
|
|
124
|
+
include_domains: includeDomains.length ? includeDomains : undefined,
|
|
125
|
+
exclude_domains: excludeDomains.length ? excludeDomains : undefined,
|
|
126
|
+
after_date: publishedAfter,
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
: {}),
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
const data = decodeSearchJson(text, context.backend.provider);
|
|
134
|
+
return {
|
|
135
|
+
searchId: typeof data.search_id === "string" ? data.search_id : undefined,
|
|
136
|
+
results: resultList(data.results, context, count, (row) => buildResult(row.title, row.url, Array.isArray(row.excerpts) ? row.excerpts.filter((part) => typeof part === "string").join("\n\n") : "", row.publish_date)),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
async function searchTavily(context, request) {
|
|
140
|
+
const { query, count, includeDomains, excludeDomains, publishedAfter } = request;
|
|
141
|
+
const text = await requestSearchText(context, {
|
|
142
|
+
method: "POST",
|
|
143
|
+
url: "https://api.tavily.com/search",
|
|
144
|
+
headers: {
|
|
145
|
+
Authorization: `Bearer ${requireApiKey(context)}`,
|
|
146
|
+
"Content-Type": "application/json",
|
|
147
|
+
Accept: "application/json",
|
|
148
|
+
},
|
|
149
|
+
data: {
|
|
150
|
+
query,
|
|
151
|
+
max_results: count,
|
|
152
|
+
include_published_date: true,
|
|
153
|
+
...(includeDomains.length ? { include_domains: includeDomains } : {}),
|
|
154
|
+
...(excludeDomains.length ? { exclude_domains: excludeDomains } : {}),
|
|
155
|
+
...(publishedAfter ? { start_date: publishedAfter, filter_by_published_date: true } : {}),
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
const data = decodeSearchJson(text, context.backend.provider);
|
|
159
|
+
return {
|
|
160
|
+
results: resultList(data.results, context, count, (row) => buildResult(row.title, row.url, row.content, row.published_date)),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
async function searchJina(context, { query, count }) {
|
|
164
|
+
const text = await requestSearchText(context, {
|
|
165
|
+
url: `https://s.jina.ai/${encodeURIComponent(query)}`,
|
|
166
|
+
headers: { Authorization: `Bearer ${requireApiKey(context)}`, Accept: "application/json" },
|
|
167
|
+
});
|
|
168
|
+
const data = decodeSearchJson(text, context.backend.provider);
|
|
169
|
+
return { results: resultList(data.data, context, count, (row) => buildResult(row.title, row.url, row.content)) };
|
|
170
|
+
}
|
|
171
|
+
async function searchSearxng(context, { query, count }) {
|
|
172
|
+
const base = URL.parse(context.backend.baseUrl);
|
|
173
|
+
if (!base || !["http:", "https:"].includes(base.protocol)) {
|
|
174
|
+
throw new WebSearchProviderError("configuration", "SearXNG search requires an HTTP(S) baseUrl. Ask the operator to set the URL in tools.json.");
|
|
119
175
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
176
|
+
const text = await requestSearchText(context, {
|
|
177
|
+
url: new URL("/search", base).href,
|
|
178
|
+
params: { q: query, format: "json" },
|
|
179
|
+
headers: { Accept: "application/json" },
|
|
180
|
+
});
|
|
181
|
+
const data = decodeSearchJson(text, context.backend.provider);
|
|
182
|
+
return { results: resultList(data.results, context, count, (row) => buildResult(row.title, row.url, row.content)) };
|
|
183
|
+
}
|
|
184
|
+
function duckDuckGoChallenge() {
|
|
185
|
+
return new WebSearchProviderError("challenge", "DuckDuckGo returned a verification page. Use another search source or open the official site directly.");
|
|
186
|
+
}
|
|
187
|
+
function duckDuckGoResultUrl(href) {
|
|
188
|
+
const url = URL.parse(href, DUCKDUCKGO_URL);
|
|
189
|
+
if (url?.hostname === "duckduckgo.com" && url.pathname === "/l/")
|
|
190
|
+
return url.searchParams.get("uddg");
|
|
191
|
+
return url?.href ?? null;
|
|
192
|
+
}
|
|
193
|
+
async function searchDuckDuckGo(context, { query, count }) {
|
|
194
|
+
const text = await requestSearchText(context, {
|
|
195
|
+
url: DUCKDUCKGO_URL,
|
|
196
|
+
params: { q: query },
|
|
197
|
+
headers: { Accept: "text/html" },
|
|
198
|
+
});
|
|
199
|
+
const { window } = new JSDOM(text);
|
|
200
|
+
try {
|
|
201
|
+
const document = window.document;
|
|
202
|
+
if (document.querySelector("#challenge-form, #anomaly-modal, .anomaly-modal"))
|
|
203
|
+
throw duckDuckGoChallenge();
|
|
204
|
+
if (document.querySelector(".no-results, .result--no-result"))
|
|
205
|
+
return { results: [] };
|
|
133
206
|
const results = [];
|
|
134
|
-
for (const item of
|
|
135
|
-
const link = item.querySelector(".result__title a
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
if (!href) {
|
|
207
|
+
for (const item of document.querySelectorAll(".result")) {
|
|
208
|
+
const link = item.querySelector(".result__title a, a.result__a");
|
|
209
|
+
const href = link?.getAttribute("href");
|
|
210
|
+
if (!link || !href)
|
|
139
211
|
continue;
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
snippet: snippet?.textContent?.trim() || "",
|
|
145
|
-
});
|
|
146
|
-
if (results.length >= count) {
|
|
212
|
+
const result = buildResult(link.textContent, duckDuckGoResultUrl(href), item.querySelector(".result__snippet")?.textContent);
|
|
213
|
+
if (result)
|
|
214
|
+
results.push(result);
|
|
215
|
+
if (results.length >= count)
|
|
147
216
|
break;
|
|
148
|
-
}
|
|
149
217
|
}
|
|
150
|
-
|
|
218
|
+
if (results.length === 0)
|
|
219
|
+
throw invalidResponse(context.backend.provider);
|
|
220
|
+
return { results };
|
|
151
221
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
switch (provider) {
|
|
155
|
-
case "tavily":
|
|
156
|
-
return new TavilySearchProvider(context);
|
|
157
|
-
case "jina":
|
|
158
|
-
return new JinaSearchProvider(context);
|
|
159
|
-
case "searxng":
|
|
160
|
-
return new SearxngSearchProvider(context);
|
|
161
|
-
case "duckduckgo":
|
|
162
|
-
return new DuckDuckGoSearchProvider(context);
|
|
163
|
-
default:
|
|
164
|
-
throw new WebSearchProviderError("config", `Unknown search provider: ${provider}`);
|
|
222
|
+
finally {
|
|
223
|
+
window.close();
|
|
165
224
|
}
|
|
166
225
|
}
|
|
226
|
+
const providers = {
|
|
227
|
+
parallel: searchParallel,
|
|
228
|
+
tavily: searchTavily,
|
|
229
|
+
jina: searchJina,
|
|
230
|
+
searxng: searchSearxng,
|
|
231
|
+
duckduckgo: searchDuckDuckGo,
|
|
232
|
+
};
|
|
233
|
+
export function searchByProvider(context, request) {
|
|
234
|
+
return providers[context.backend.provider](context, request);
|
|
235
|
+
}
|
package/dist/web/search.d.ts
CHANGED
|
@@ -1,19 +1,29 @@
|
|
|
1
|
-
import type { PipiclawWebToolsConfig } from "../config/tools.js";
|
|
1
|
+
import type { PipiclawWebToolsConfig, WebSearchProvider } from "../config/tools.js";
|
|
2
2
|
import type { SecurityConfig } from "../security/types.js";
|
|
3
|
+
import { type ResolvedWebSearchRequest } from "./config.js";
|
|
3
4
|
import { type WebSearchResultItem } from "./format.js";
|
|
5
|
+
import { WebSearchProviderError } from "./search-providers.js";
|
|
4
6
|
export interface WebSearchExecutionContext {
|
|
5
7
|
webConfig: PipiclawWebToolsConfig;
|
|
6
8
|
securityConfig: SecurityConfig;
|
|
7
9
|
workspaceDir: string;
|
|
8
10
|
channelId?: string;
|
|
9
11
|
}
|
|
12
|
+
interface SearchFallback {
|
|
13
|
+
from: WebSearchProvider;
|
|
14
|
+
reason: WebSearchProviderError["kind"];
|
|
15
|
+
}
|
|
10
16
|
export interface WebSearchOutput {
|
|
11
17
|
content: string;
|
|
12
18
|
details: {
|
|
13
|
-
provider:
|
|
19
|
+
provider: WebSearchProvider;
|
|
14
20
|
query: string;
|
|
15
21
|
count: number;
|
|
16
22
|
results: WebSearchResultItem[];
|
|
23
|
+
durationMs: number;
|
|
24
|
+
searchId?: string;
|
|
25
|
+
fallback?: SearchFallback;
|
|
17
26
|
};
|
|
18
27
|
}
|
|
19
|
-
export declare function runWebSearch(context: WebSearchExecutionContext,
|
|
28
|
+
export declare function runWebSearch(context: WebSearchExecutionContext, request: ResolvedWebSearchRequest, signal?: AbortSignal): Promise<WebSearchOutput>;
|
|
29
|
+
export {};
|
package/dist/web/search.js
CHANGED
|
@@ -1,52 +1,98 @@
|
|
|
1
|
+
import { addAbortListener } from "node:events";
|
|
2
|
+
import * as log from "../log.js";
|
|
3
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
1
4
|
import { createWebHttpClient } from "./client.js";
|
|
5
|
+
import { hasSearchFilters, supportsSearchFilters } from "./config.js";
|
|
2
6
|
import { formatWebSearchText } from "./format.js";
|
|
3
|
-
import {
|
|
4
|
-
async function
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
import { searchByProvider, WebSearchProviderError } from "./search-providers.js";
|
|
8
|
+
async function runAttempt(search, provider, timeoutMs, callerSignal) {
|
|
9
|
+
callerSignal?.throwIfAborted();
|
|
10
|
+
const deadline = new AbortController();
|
|
11
|
+
const signal = callerSignal ? AbortSignal.any([callerSignal, deadline.signal]) : deadline.signal;
|
|
12
|
+
const timer = setTimeout(() => {
|
|
13
|
+
deadline.abort(new WebSearchProviderError("timeout", `${provider} search timed out. Retry once or narrow the search.`));
|
|
14
|
+
}, timeoutMs);
|
|
15
|
+
// DNS validation can still be awaiting a lookup while the signal is aborted.
|
|
16
|
+
// Race it here, and pass the same signal down so it cannot start HTTP afterward.
|
|
17
|
+
let listener;
|
|
18
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
19
|
+
listener = addAbortListener(signal, () => reject(signal.reason));
|
|
10
20
|
});
|
|
11
|
-
const provider = createSearchProvider(config.provider, { client, config });
|
|
12
|
-
return {
|
|
13
|
-
provider: config.provider,
|
|
14
|
-
results: await provider.search(query, count, signal),
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
export async function runWebSearch(context, query, count, signal) {
|
|
18
|
-
const searchConfig = context.webConfig.search;
|
|
19
21
|
try {
|
|
20
|
-
|
|
21
|
-
return {
|
|
22
|
-
content: formatWebSearchText(query, primary.results),
|
|
23
|
-
details: {
|
|
24
|
-
provider: primary.provider,
|
|
25
|
-
query,
|
|
26
|
-
count,
|
|
27
|
-
results: primary.results,
|
|
28
|
-
},
|
|
29
|
-
};
|
|
22
|
+
return await Promise.race([search(signal), aborted]);
|
|
30
23
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
24
|
+
finally {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
listener?.[Symbol.dispose]();
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function canSwitchProvider(error) {
|
|
30
|
+
return error instanceof WebSearchProviderError && error.kind !== "configuration" && error.kind !== "invalid_request";
|
|
31
|
+
}
|
|
32
|
+
export async function runWebSearch(context, request, signal) {
|
|
33
|
+
signal?.throwIfAborted();
|
|
34
|
+
const config = context.webConfig.search;
|
|
35
|
+
const filtered = hasSearchFilters(request);
|
|
36
|
+
if (filtered && !supportsSearchFilters(config.provider)) {
|
|
37
|
+
throw new RecoverableToolError("The configured search provider does not support source filters. Omit the filters or ask the operator to use Parallel or Tavily.");
|
|
38
|
+
}
|
|
39
|
+
const fallback = config.fallback &&
|
|
40
|
+
config.fallback.provider !== config.provider &&
|
|
41
|
+
(!filtered || supportsSearchFilters(config.fallback.provider))
|
|
42
|
+
? config.fallback
|
|
43
|
+
: null;
|
|
44
|
+
const startedAt = performance.now();
|
|
45
|
+
const client = createWebHttpClient(context);
|
|
46
|
+
async function execute(backend, timeoutMs, switched) {
|
|
47
|
+
const attemptStartedAt = performance.now();
|
|
48
|
+
try {
|
|
49
|
+
const { results, searchId } = await runAttempt((attemptSignal) => searchByProvider({ client, backend, parallelMode: config.parallelMode, timeoutMs, signal: attemptSignal }, request), backend.provider, timeoutMs, signal);
|
|
50
|
+
signal?.throwIfAborted();
|
|
51
|
+
const durationMs = Math.round(performance.now() - startedAt);
|
|
52
|
+
log.logInfoEvent("web.search.completed", "Web search completed", {
|
|
53
|
+
channelId: context.channelId,
|
|
54
|
+
fields: {
|
|
55
|
+
provider: backend.provider,
|
|
56
|
+
durationMs,
|
|
57
|
+
resultCount: results.length,
|
|
58
|
+
fallbackFrom: switched?.from,
|
|
59
|
+
},
|
|
60
|
+
});
|
|
40
61
|
return {
|
|
41
|
-
content: formatWebSearchText(query,
|
|
62
|
+
content: formatWebSearchText(request.query, backend.provider, results, switched?.from),
|
|
42
63
|
details: {
|
|
43
|
-
provider:
|
|
44
|
-
query,
|
|
45
|
-
count,
|
|
46
|
-
results
|
|
64
|
+
provider: backend.provider,
|
|
65
|
+
query: request.query,
|
|
66
|
+
count: request.count,
|
|
67
|
+
results,
|
|
68
|
+
durationMs,
|
|
69
|
+
...(searchId ? { searchId } : {}),
|
|
70
|
+
...(switched ? { fallback: switched } : {}),
|
|
47
71
|
},
|
|
48
72
|
};
|
|
49
73
|
}
|
|
50
|
-
|
|
74
|
+
catch (error) {
|
|
75
|
+
signal?.throwIfAborted();
|
|
76
|
+
if (error instanceof WebSearchProviderError) {
|
|
77
|
+
log.logWarn("web.search.failed", "Web search failed", {
|
|
78
|
+
channelId: context.channelId,
|
|
79
|
+
reason: error.kind,
|
|
80
|
+
fields: { provider: backend.provider, durationMs: Math.round(performance.now() - attemptStartedAt) },
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// Leave a third of the total budget for a second provider when one can honor the request.
|
|
87
|
+
const primaryBudget = fallback ? Math.max(1, Math.floor((config.timeoutMs * 2) / 3)) : config.timeoutMs;
|
|
88
|
+
try {
|
|
89
|
+
return await execute(config, primaryBudget);
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
signal?.throwIfAborted();
|
|
93
|
+
const remainingMs = Math.floor(config.timeoutMs - (performance.now() - startedAt));
|
|
94
|
+
if (!fallback || !canSwitchProvider(error) || remainingMs < 1)
|
|
95
|
+
throw error;
|
|
96
|
+
return execute(fallback, remainingMs, { from: config.provider, reason: error.kind });
|
|
51
97
|
}
|
|
52
98
|
}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const COMMON_CHINESE_WORDS: Set<string>;
|