@oh-my-pi/pi-coding-agent 14.4.3 → 14.5.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.
@@ -0,0 +1,238 @@
1
+ /**
2
+ * SearXNG Web Search Provider
3
+ *
4
+ * Calls a SearXNG instance's JSON search API and maps results into the unified
5
+ * SearchResponse shape used by the web search tool.
6
+ *
7
+ * SearXNG is a free, open-source metasearch engine that aggregates results from
8
+ * multiple sources without tracking users. It supports self-hosted instances
9
+ * and various authentication methods (bearer token, basic auth, or none).
10
+ *
11
+ * Configuration via settings:
12
+ * searxng.endpoint - Base URL of the SearXNG instance (e.g. https://searx.example.org)
13
+ * searxng.token - Optional bearer token for authentication
14
+ * searxng.categories - Optional comma-separated categories filter
15
+ * searxng.language - Optional language code (e.g. en, zh-CN)
16
+ *
17
+ * Environment variable fallbacks:
18
+ * SEARXNG_ENDPOINT - Base URL of the SearXNG instance
19
+ * SEARXNG_TOKEN - Optional bearer token
20
+ *
21
+ * Reference: https://docs.searxng.org/dev/search_api.html
22
+ */
23
+
24
+ import { settings } from "../../../config/settings";
25
+ import type { SearchResponse, SearchSource } from "../../../web/search/types";
26
+ import { SearchProviderError } from "../../../web/search/types";
27
+ import { clampNumResults, dateToAgeSeconds } from "../utils";
28
+ import type { SearchParams } from "./base";
29
+ import { SearchProvider } from "./base";
30
+
31
+ const DEFAULT_NUM_RESULTS = 10;
32
+ const MAX_NUM_RESULTS = 20;
33
+
34
+ /** Map our recency filter to SearXNG time_range parameter.
35
+ * SearXNG only supports day/month/year, so week maps to month. */
36
+ const RECENCY_MAP: Record<"day" | "week" | "month" | "year", string> = {
37
+ day: "day",
38
+ week: "month",
39
+ month: "month",
40
+ year: "year",
41
+ };
42
+
43
+ /** SearXNG JSON API response types */
44
+ interface SearXNGResult {
45
+ title?: string;
46
+ url?: string;
47
+ content?: string;
48
+ engine?: string;
49
+ publishedDate?: string;
50
+ /** SearXNG sometimes uses publishedDate, sometimes just date */
51
+ published_date?: string;
52
+ score?: number;
53
+ }
54
+
55
+ interface SearXNGResponse {
56
+ query?: string;
57
+ number_of_results?: number;
58
+ results?: SearXNGResult[];
59
+ suggestions?: string[];
60
+ corrections?: string[];
61
+ unresponsive_engines?: Array<[string, string]>;
62
+ }
63
+
64
+ /** Find SearXNG endpoint from settings or environment. */
65
+ function findEndpoint(): string | null {
66
+ try {
67
+ const endpoint = settings.get("searxng.endpoint");
68
+ if (endpoint) return endpoint;
69
+ } catch {
70
+ // Settings not initialized yet
71
+ }
72
+ return process.env.SEARXNG_ENDPOINT ?? null;
73
+ }
74
+
75
+ /** Find SearXNG bearer token from settings or environment. */
76
+ function findToken(): string | null {
77
+ try {
78
+ const token = settings.get("searxng.token");
79
+ if (token) return token;
80
+ } catch {
81
+ // Settings not initialized yet
82
+ }
83
+ return process.env.SEARXNG_TOKEN ?? null;
84
+ }
85
+
86
+ /** Build the search URL and headers for a SearXNG request */
87
+ function buildRequest(
88
+ endpoint: string,
89
+ params: {
90
+ query: string;
91
+ num_results?: number;
92
+ recency?: "day" | "week" | "month" | "year";
93
+ categories?: string;
94
+ language?: string;
95
+ signal?: AbortSignal;
96
+ },
97
+ token: string | null,
98
+ ): { url: URL; headers: Record<string, string> } {
99
+ const base = endpoint.replace(/\/+$/, "");
100
+ const url = new URL(`${base}/search`);
101
+
102
+ url.searchParams.set("q", params.query);
103
+ url.searchParams.set("format", "json");
104
+
105
+ if (params.num_results) {
106
+ url.searchParams.set("pageno", "1");
107
+ }
108
+
109
+ if (params.recency) {
110
+ url.searchParams.set("time_range", RECENCY_MAP[params.recency]);
111
+ }
112
+
113
+ if (params.categories) {
114
+ url.searchParams.set("categories", params.categories);
115
+ }
116
+
117
+ if (params.language) {
118
+ url.searchParams.set("language", params.language);
119
+ }
120
+
121
+ const headers: Record<string, string> = {
122
+ Accept: "application/json",
123
+ };
124
+
125
+ if (token) {
126
+ headers.Authorization = `Bearer ${token}`;
127
+ }
128
+
129
+ return { url, headers };
130
+ }
131
+
132
+ async function callSearXNGSearch(
133
+ endpoint: string,
134
+ params: {
135
+ query: string;
136
+ num_results?: number;
137
+ recency?: "day" | "week" | "month" | "year";
138
+ categories?: string;
139
+ language?: string;
140
+ signal?: AbortSignal;
141
+ },
142
+ token: string | null,
143
+ ): Promise<SearXNGResponse> {
144
+ const { url, headers } = buildRequest(endpoint, params, token);
145
+
146
+ const response = await fetch(url, {
147
+ headers,
148
+ signal: params.signal,
149
+ });
150
+
151
+ if (!response.ok) {
152
+ const errorText = await response.text();
153
+ throw new SearchProviderError("searxng", `SearXNG API error (${response.status}): ${errorText}`, response.status);
154
+ }
155
+
156
+ return (await response.json()) as SearXNGResponse;
157
+ }
158
+
159
+ /** Execute SearXNG web search. */
160
+ export async function searchSearXNG(params: {
161
+ query: string;
162
+ num_results?: number;
163
+ recency?: "day" | "week" | "month" | "year";
164
+ signal?: AbortSignal;
165
+ }): Promise<SearchResponse> {
166
+ const numResults = clampNumResults(params.num_results, DEFAULT_NUM_RESULTS, MAX_NUM_RESULTS);
167
+
168
+ const endpoint = findEndpoint();
169
+ if (!endpoint) {
170
+ throw new Error(
171
+ "SearXNG endpoint not configured. Set searxng.endpoint in settings or SEARXNG_ENDPOINT in environment.",
172
+ );
173
+ }
174
+
175
+ const token = findToken();
176
+
177
+ let categories: string | undefined;
178
+ let language: string | undefined;
179
+ try {
180
+ categories = settings.get("searxng.categories") ?? undefined;
181
+ language = settings.get("searxng.language") ?? undefined;
182
+ } catch {
183
+ // Settings not initialized yet
184
+ }
185
+
186
+ const response = await callSearXNGSearch(
187
+ endpoint,
188
+ {
189
+ ...params,
190
+ categories,
191
+ language,
192
+ },
193
+ token,
194
+ );
195
+
196
+ const sources: SearchSource[] = [];
197
+
198
+ for (const result of response.results ?? []) {
199
+ if (!result.url) continue;
200
+ const publishedDate = result.publishedDate ?? result.published_date;
201
+ sources.push({
202
+ title: result.title ?? result.url,
203
+ url: result.url,
204
+ snippet: result.content?.trim() || undefined,
205
+ publishedDate: publishedDate ?? undefined,
206
+ ageSeconds: dateToAgeSeconds(publishedDate),
207
+ });
208
+ }
209
+
210
+ return {
211
+ provider: "searxng",
212
+ sources: sources.slice(0, numResults),
213
+ relatedQuestions: response.suggestions?.length ? response.suggestions : undefined,
214
+ };
215
+ }
216
+
217
+ /** Search provider for SearXNG web search. */
218
+ export class SearXNGProvider extends SearchProvider {
219
+ readonly id = "searxng";
220
+ readonly label = "SearXNG";
221
+
222
+ isAvailable() {
223
+ try {
224
+ return !!findEndpoint();
225
+ } catch {
226
+ return false;
227
+ }
228
+ }
229
+
230
+ search(params: SearchParams): Promise<SearchResponse> {
231
+ return searchSearXNG({
232
+ query: params.query,
233
+ num_results: params.numSearchResults ?? params.limit,
234
+ recency: params.recency,
235
+ signal: params.signal,
236
+ });
237
+ }
238
+ }
@@ -18,7 +18,8 @@ export type SearchProviderId =
18
18
  | "tavily"
19
19
  | "parallel"
20
20
  | "kagi"
21
- | "synthetic";
21
+ | "synthetic"
22
+ | "searxng";
22
23
 
23
24
  export function isSearchProviderId(value: string): value is SearchProviderId {
24
25
  return [
@@ -35,6 +36,7 @@ export function isSearchProviderId(value: string): value is SearchProviderId {
35
36
  "parallel",
36
37
  "kagi",
37
38
  "synthetic",
39
+ "searxng",
38
40
  ].includes(value);
39
41
  }
40
42