@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.
Files changed (78) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/dist/agent/channel-runner.js +2 -0
  4. package/dist/agent/maintenance-context.js +21 -2
  5. package/dist/agent/turn/turn-context.js +10 -6
  6. package/dist/config/settings.d.ts +0 -2
  7. package/dist/config/settings.js +0 -2
  8. package/dist/config/tools.d.ts +8 -2
  9. package/dist/config/tools.js +35 -19
  10. package/dist/memory/anchors.d.ts +5 -0
  11. package/dist/memory/anchors.js +49 -0
  12. package/dist/memory/boundary-work.d.ts +1 -0
  13. package/dist/memory/boundary-work.js +1 -0
  14. package/dist/memory/commands.js +23 -6
  15. package/dist/memory/index-budget.d.ts +16 -0
  16. package/dist/memory/index-budget.js +24 -2
  17. package/dist/memory/journal.d.ts +7 -12
  18. package/dist/memory/journal.js +9 -41
  19. package/dist/memory/lifecycle.d.ts +1 -0
  20. package/dist/memory/lifecycle.js +2 -0
  21. package/dist/memory/reflect-job.d.ts +1 -0
  22. package/dist/memory/reflect-job.js +1 -0
  23. package/dist/memory/reflect.d.ts +10 -0
  24. package/dist/memory/reflect.js +103 -20
  25. package/dist/memory/render.d.ts +4 -1
  26. package/dist/memory/render.js +6 -4
  27. package/dist/memory/review-log.d.ts +2 -2
  28. package/dist/memory/scheduler.d.ts +7 -0
  29. package/dist/memory/scheduler.js +70 -3
  30. package/dist/memory/search-index-db.d.ts +15 -0
  31. package/dist/memory/search-index-db.js +247 -0
  32. package/dist/memory/search-index-files.d.ts +11 -0
  33. package/dist/memory/search-index-files.js +26 -0
  34. package/dist/memory/search-index-notes.d.ts +11 -0
  35. package/dist/memory/search-index-notes.js +155 -0
  36. package/dist/memory/search-index-sync.d.ts +19 -0
  37. package/dist/memory/search-index-sync.js +267 -0
  38. package/dist/memory/search-terms.d.ts +12 -0
  39. package/dist/memory/search-terms.js +185 -0
  40. package/dist/memory/search.d.ts +8 -28
  41. package/dist/memory/search.js +18 -278
  42. package/dist/memory/session-corpus.d.ts +15 -26
  43. package/dist/memory/session-corpus.js +120 -327
  44. package/dist/memory/session-search.d.ts +5 -3
  45. package/dist/memory/session-search.js +119 -171
  46. package/dist/memory/sidecar-worker.d.ts +2 -0
  47. package/dist/memory/sidecar-worker.js +25 -1
  48. package/dist/memory/store.d.ts +4 -0
  49. package/dist/memory/store.js +22 -1
  50. package/dist/memory/task-archive-digest.d.ts +61 -0
  51. package/dist/memory/task-archive-digest.js +366 -0
  52. package/dist/models/provider-login.d.ts +1 -1
  53. package/dist/models/provider-login.js +1 -1
  54. package/dist/playbooks/memory-operations.md +2 -2
  55. package/dist/shared/text-utils.d.ts +0 -1
  56. package/dist/shared/text-utils.js +0 -1
  57. package/dist/subagents/runs.d.ts +1 -1
  58. package/dist/subagents/task-envelope.js +6 -8
  59. package/dist/tools/memory-manage.d.ts +1 -0
  60. package/dist/tools/memory-manage.js +9 -23
  61. package/dist/tools/registry.js +2 -0
  62. package/dist/tools/session-search.d.ts +1 -0
  63. package/dist/tools/session-search.js +12 -6
  64. package/dist/tools/web-search.d.ts +13 -7
  65. package/dist/tools/web-search.js +62 -19
  66. package/dist/web/client.d.ts +2 -0
  67. package/dist/web/client.js +7 -3
  68. package/dist/web/config.d.ts +17 -4
  69. package/dist/web/config.js +42 -4
  70. package/dist/web/format.d.ts +2 -1
  71. package/dist/web/format.js +7 -3
  72. package/dist/web/search-providers.d.ts +15 -8
  73. package/dist/web/search-providers.js +208 -139
  74. package/dist/web/search.d.ts +13 -3
  75. package/dist/web/search.js +86 -40
  76. package/package.json +1 -1
  77. package/dist/memory/chinese-words.d.ts +0 -1
  78. 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
- function normalizeResult(item) {
10
- const title = item.title?.trim() ?? "";
11
- const url = item.url?.trim() ?? "";
12
- const snippet = item.snippet?.trim() ?? "";
13
- if (!url) {
14
- return null;
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
- return {
17
- title: title || url,
18
- url,
19
- snippet,
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 isProviderConfigStatus(status) {
23
- return status === 400 || status === 401 || status === 403 || status === 422 || status === 429;
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
- class TavilySearchProvider {
26
- constructor(context) {
27
- this.context = context;
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
- async search(query, count, signal) {
30
- if (!this.context.config.apiKey) {
31
- throw new WebSearchProviderError("config", "Tavily search requires tools.web.search.apiKey");
32
- }
33
- const { response, data } = await this.context.client.requestJson({
34
- method: "POST",
35
- url: "https://api.tavily.com/search",
36
- headers: {
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
- return (data.results ?? [])
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
- class JinaSearchProvider {
59
- constructor(context) {
60
- this.context = context;
59
+ function decodeSearchJson(text, provider) {
60
+ let data;
61
+ try {
62
+ data = JSON.parse(text);
61
63
  }
62
- async search(query, count, signal) {
63
- if (!this.context.config.apiKey) {
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
- class SearxngSearchProvider {
89
- constructor(context) {
90
- this.context = context;
91
- }
92
- async search(query, count, signal) {
93
- if (!this.context.config.baseUrl) {
94
- throw new WebSearchProviderError("config", "SearXNG search requires tools.web.search.baseUrl");
95
- }
96
- const baseUrl = new URL("/search", this.context.config.baseUrl).toString();
97
- const { response, data } = await this.context.client.requestJson({
98
- url: baseUrl,
99
- params: { q: query, format: "json" },
100
- timeoutMs: this.context.config.timeoutMs,
101
- signal,
102
- });
103
- if (response.status < 200 || response.status >= 300) {
104
- throw new WebSearchProviderError("provider", `SearXNG search failed with HTTP ${response.status}`);
105
- }
106
- return (data.results ?? [])
107
- .map((item) => normalizeResult({
108
- title: item.title,
109
- url: item.url,
110
- snippet: item.content,
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
- class DuckDuckGoSearchProvider {
117
- constructor(context) {
118
- this.context = context;
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
- async search(query, count, signal) {
121
- const { response, text } = await this.context.client.requestText({
122
- url: "https://html.duckduckgo.com/html/",
123
- params: { q: query },
124
- headers: { Accept: "text/html" },
125
- timeoutMs: this.context.config.timeoutMs,
126
- signal,
127
- });
128
- if (response.status < 200 || response.status >= 300) {
129
- throw new WebSearchProviderError("provider", `DuckDuckGo search failed with HTTP ${response.status}`);
130
- }
131
- const dom = new JSDOM(text);
132
- const items = Array.from(dom.window.document.querySelectorAll(".result"));
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 items) {
135
- const link = item.querySelector(".result__title a") ?? item.querySelector("a.result__a");
136
- const snippet = item.querySelector(".result__snippet");
137
- const href = link?.getAttribute("href")?.trim() ?? "";
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
- results.push({
142
- title: link?.textContent?.trim() || href,
143
- url: href,
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
- return results;
218
+ if (results.length === 0)
219
+ throw invalidResponse(context.backend.provider);
220
+ return { results };
151
221
  }
152
- }
153
- export function createSearchProvider(provider, context) {
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
+ }
@@ -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: string;
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, query: string, count: number, signal?: AbortSignal): Promise<WebSearchOutput>;
28
+ export declare function runWebSearch(context: WebSearchExecutionContext, request: ResolvedWebSearchRequest, signal?: AbortSignal): Promise<WebSearchOutput>;
29
+ export {};
@@ -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 { createSearchProvider, WebSearchProviderError } from "./search-providers.js";
4
- async function executeProviderSearch(config, context, query, count, signal) {
5
- const client = createWebHttpClient({
6
- webConfig: context.webConfig,
7
- securityConfig: context.securityConfig,
8
- workspaceDir: context.workspaceDir,
9
- channelId: context.channelId,
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
- const primary = await executeProviderSearch(searchConfig, context, query, count, signal);
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
- catch (error) {
32
- if (searchConfig.provider !== "duckduckgo" &&
33
- error instanceof WebSearchProviderError &&
34
- error.kind === "provider") {
35
- const fallbackConfig = {
36
- ...searchConfig,
37
- provider: "duckduckgo",
38
- };
39
- const fallback = await executeProviderSearch(fallbackConfig, context, query, count, signal);
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, fallback.results),
62
+ content: formatWebSearchText(request.query, backend.provider, results, switched?.from),
42
63
  details: {
43
- provider: fallback.provider,
44
- query,
45
- count,
46
- results: fallback.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
- throw error;
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.9.6-beta.2",
3
+ "version": "0.9.6-beta.3",
4
4
  "description": "A DingTalk-first AI coding assistant runtime for individual developers, with background work, delegation, and memory.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +0,0 @@
1
- export declare const COMMON_CHINESE_WORDS: Set<string>;