@aspalagin/openclaw-yandex-search 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Multi-Search: Yandex + Brave параллельно, дедупликация по нормализованному URL.
3
+ *
4
+ * Порядок выдачи: сначала ссылки, найденные обоими движками, затем чередование остальных.
5
+ * Один упавший движок не ломает запрос: отдаём результаты живого и пишем warn в лог.
6
+ * Если упали оба — возвращаем ошибку, а не пустой список.
7
+ */
8
+ import { searchBrave } from "./brave.js";
9
+ import { resolveYandexPeriod, searchYandex } from "./yandex.js";
10
+ import { abortReason, errorMessage, isHttpUrl, silentLogger, truncate } from "./util.js";
11
+ const TRACKING_PARAM_RE = /^(utm_\w*|fbclid|gclid|dclid|yclid|ysclid|msclkid|igshid|mc_cid|mc_eid|_openstat|ref|_ga|_gl)$/i;
12
+ /**
13
+ * Ключ дедупликации: без схемы, www./m., завершающего слэша, index.html и трекинговых параметров;
14
+ * оставшиеся параметры отсортированы.
15
+ */
16
+ export function normalizeUrlForDedup(raw) {
17
+ try {
18
+ const url = new URL(raw.trim());
19
+ const host = url.hostname.toLowerCase().replace(/^(www|m)\./, "");
20
+ const path = url.pathname.replace(/\/+$/, "").replace(/\/index\.(html?|php)$/i, "");
21
+ const params = [...url.searchParams.entries()]
22
+ .filter(([key]) => !TRACKING_PARAM_RE.test(key))
23
+ .sort(([a], [b]) => a.localeCompare(b));
24
+ const query = params.length ? `?${new URLSearchParams(params).toString()}` : "";
25
+ return `${host}${path}${query}`;
26
+ }
27
+ catch {
28
+ return raw.trim().toLowerCase();
29
+ }
30
+ }
31
+ /** Склеивает выдачи: both → чередование yandex/brave. Невалидные URL отбрасываются. */
32
+ export function mergeRows(yandexRows, braveRows) {
33
+ const byKey = new Map();
34
+ const add = (row, engine) => {
35
+ if (!isHttpUrl(row.url)) {
36
+ return;
37
+ }
38
+ const key = normalizeUrlForDedup(row.url);
39
+ const existing = byKey.get(key);
40
+ if (!existing) {
41
+ byKey.set(key, { row: { ...row }, engines: new Set([engine]) });
42
+ return;
43
+ }
44
+ existing.engines.add(engine);
45
+ existing.row.title = existing.row.title || row.title;
46
+ if (row.snippet.length > existing.row.snippet.length) {
47
+ existing.row.snippet = row.snippet;
48
+ }
49
+ // Brave отдаёт дату публикации, Яндекс — дату изменения страницы; публикация точнее.
50
+ if (engine === "brave" && row.published) {
51
+ existing.row.published = row.published;
52
+ }
53
+ else if (!existing.row.published && row.published) {
54
+ existing.row.published = row.published;
55
+ }
56
+ if (!existing.row.siteName && row.siteName) {
57
+ existing.row.siteName = row.siteName;
58
+ }
59
+ };
60
+ for (const row of yandexRows) {
61
+ add(row, "yandex");
62
+ }
63
+ for (const row of braveRows) {
64
+ add(row, "brave");
65
+ }
66
+ const both = [];
67
+ const yandexOnly = [];
68
+ const braveOnly = [];
69
+ for (const entry of byKey.values()) {
70
+ if (entry.engines.size > 1) {
71
+ both.push(entry.row);
72
+ }
73
+ else if (entry.engines.has("yandex")) {
74
+ yandexOnly.push(entry.row);
75
+ }
76
+ else {
77
+ braveOnly.push(entry.row);
78
+ }
79
+ }
80
+ const interleaved = [];
81
+ const longest = Math.max(yandexOnly.length, braveOnly.length);
82
+ for (let i = 0; i < longest; i++) {
83
+ if (i < yandexOnly.length) {
84
+ interleaved.push(yandexOnly[i]);
85
+ }
86
+ if (i < braveOnly.length) {
87
+ interleaved.push(braveOnly[i]);
88
+ }
89
+ }
90
+ return [...both, ...interleaved];
91
+ }
92
+ const ENGINE_LABEL = { yandex: "Yandex", brave: "Brave" };
93
+ function describeStatus(status) {
94
+ if (status.state === "skipped") {
95
+ return "skip";
96
+ }
97
+ return `${status.state === "ok" ? status.count : "fail"}/${status.tookMs}ms`;
98
+ }
99
+ export async function runMultiSearch(input) {
100
+ const startedAt = Date.now();
101
+ const logger = input.logger ?? silentLogger;
102
+ const { params, credentials } = input;
103
+ const engines = {
104
+ yandex: { state: "skipped", count: 0, tookMs: 0 },
105
+ brave: { state: "skipped", count: 0, tookMs: 0 },
106
+ };
107
+ const yandexReady = Boolean(credentials.yandexApiKey && credentials.yandexFolderId);
108
+ const braveReady = Boolean(credentials.braveApiKey);
109
+ if (!yandexReady) {
110
+ engines.yandex.detail = "нет YC_API_KEY или YC_FOLDER_ID";
111
+ }
112
+ if (!braveReady) {
113
+ engines.brave.detail = "нет BRAVE_SEARCH_API_KEY";
114
+ }
115
+ if (!yandexReady && !braveReady) {
116
+ return {
117
+ ok: false,
118
+ rows: [],
119
+ tookMs: Date.now() - startedAt,
120
+ engines,
121
+ complete: false,
122
+ error: "missing_api_key",
123
+ message: "web_search (multi): не настроен ни один поисковый движок. Нужны YC_API_KEY и YC_FOLDER_ID для Яндекса " +
124
+ "и/или BRAVE_SEARCH_API_KEY для Brave: в окружении Gateway или в plugins.entries.openclaw-yandex-search.config.",
125
+ };
126
+ }
127
+ // Яндекс фильтрует по дате только периодами; если диапазон он выразить не может, отвечает один Brave.
128
+ const period = resolveYandexPeriod({
129
+ freshness: params.freshness,
130
+ dateAfter: params.dateAfter,
131
+ dateBefore: params.dateBefore,
132
+ now: input.now,
133
+ });
134
+ let runYandex = yandexReady;
135
+ if (runYandex && period.coverage === "none") {
136
+ if (braveReady) {
137
+ runYandex = false;
138
+ engines.yandex.detail = `фильтр по дате не выражается периодами Яндекса (${period.note}); отвечает Brave`;
139
+ }
140
+ else {
141
+ logger.warn(`[multi-search] yandex: фильтр по дате не применён (${period.note}), Brave не настроен, выдача без фильтра`);
142
+ }
143
+ }
144
+ else if (runYandex && period.note) {
145
+ logger.debug?.(`[multi-search] yandex: period=${period.period} (${period.note})`);
146
+ }
147
+ const timed = async (engine, run) => {
148
+ const t0 = Date.now();
149
+ try {
150
+ const rows = await run();
151
+ engines[engine] = { state: "ok", count: rows.length, tookMs: Date.now() - t0 };
152
+ return rows;
153
+ }
154
+ catch (err) {
155
+ engines[engine] = { state: "failed", count: 0, tookMs: Date.now() - t0, detail: errorMessage(err) };
156
+ throw err;
157
+ }
158
+ };
159
+ const [yandexSettled, braveSettled] = await Promise.allSettled([
160
+ runYandex
161
+ ? timed("yandex", () => searchYandex(params, {
162
+ ...input.yandex,
163
+ apiKey: credentials.yandexApiKey,
164
+ folderId: credentials.yandexFolderId,
165
+ fetchImpl: input.fetchImpl,
166
+ logger,
167
+ period: period.period,
168
+ }))
169
+ : Promise.resolve([]),
170
+ braveReady
171
+ ? timed("brave", () => searchBrave(params, {
172
+ ...input.brave,
173
+ apiKey: credentials.braveApiKey,
174
+ fetchImpl: input.fetchImpl,
175
+ logger,
176
+ }))
177
+ : Promise.resolve([]),
178
+ ]);
179
+ if (params.signal?.aborted) {
180
+ throw abortReason(params.signal);
181
+ }
182
+ const tookMs = Date.now() - startedAt;
183
+ const queryLabel = truncate(params.query, 80);
184
+ const engineIds = ["yandex", "brave"];
185
+ for (const engine of engineIds) {
186
+ const status = engines[engine];
187
+ if (status.state === "failed") {
188
+ logger.warn(`[multi-search] ${engine} упал за ${status.tookMs} мс: ${status.detail} | запрос: «${queryLabel}»`);
189
+ }
190
+ }
191
+ const executed = engineIds.filter((engine) => engines[engine].state !== "skipped");
192
+ const failed = executed.filter((engine) => engines[engine].state === "failed");
193
+ if (executed.length > 0 && failed.length === executed.length) {
194
+ const message = failed.map((engine) => `${ENGINE_LABEL[engine]}: ${engines[engine].detail}`).join("; ");
195
+ logger.error(`[multi-search] все движки упали (${tookMs} мс): ${message}`);
196
+ return {
197
+ ok: false,
198
+ rows: [],
199
+ tookMs,
200
+ engines,
201
+ complete: false,
202
+ error: "provider_error",
203
+ message: `web_search (multi): ${message}`,
204
+ };
205
+ }
206
+ const yandexRows = yandexSettled.status === "fulfilled" ? yandexSettled.value : [];
207
+ const braveRows = braveSettled.status === "fulfilled" ? braveSettled.value : [];
208
+ const merged = mergeRows(yandexRows, braveRows);
209
+ const rows = merged.slice(0, Math.max(1, input.returnCount));
210
+ logger.info(`[multi-search] yandex=${describeStatus(engines.yandex)} brave=${describeStatus(engines.brave)} ` +
211
+ `merged=${merged.length} returned=${rows.length} tookMs=${tookMs}`);
212
+ return { ok: true, rows, tookMs, engines, complete: failed.length === 0 };
213
+ }
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Провайдеры web_search для OpenClaw: `yandex` и `multi`.
3
+ *
4
+ * Контракт ответа ядра (normalizeWebSearchOutput в OpenClaw 2026.9.x):
5
+ * - успех: { results: [{ title, url, snippet, published?, siteName? }], count, tookMs, cached? }
6
+ * - ошибка: { error, message, docs? } → ядро отдаёт модели kind: "error"
7
+ * Всё остальное ядро отбрасывает, поэтому пометки источника здесь нет.
8
+ */
9
+ import { PLUGIN_ID, pluginEntryConfig, pluginMaxResults, resolveCredentials } from "./env.js";
10
+ import { runMultiSearch } from "./multi.js";
11
+ import { loadWebSearchSdk, localWebSearchSdk } from "./sdk.js";
12
+ import { abortReason, errorMessage, silentLogger, truncate } from "./util.js";
13
+ import { resolveYandexPeriod, searchYandex } from "./yandex.js";
14
+ /** Сколько строк отдаём модели по умолчанию (ядро всё равно режет до 10). */
15
+ export const DEFAULT_RETURN_COUNT = 10;
16
+ /** Сколько просим у каждого движка: больше, чем отдаём, чтобы дедупликация и ранжирование были качественнее. */
17
+ export const ENGINE_FETCH_COUNT = 10;
18
+ const DOCS_URL = "https://docs.openclaw.ai/tools/web";
19
+ const YANDEX_DOCS_URL = "https://yandex.cloud/ru/docs/search-api/concepts/web-search";
20
+ const YANDEX_SIGNUP_URL = "https://yandex.cloud/ru/docs/search-api/";
21
+ const YANDEX_CREDENTIAL_PATH = `plugins.entries.${PLUGIN_ID}.config.yandex.apiKey`;
22
+ const BRAVE_CREDENTIAL_PATH = `plugins.entries.${PLUGIN_ID}.config.brave.apiKey`;
23
+ export const WEB_SEARCH_PARAMETERS = {
24
+ type: "object",
25
+ properties: {
26
+ query: { type: "string", description: "Search query string (поисковый запрос)." },
27
+ count: { type: "integer", description: "Number of results to return (1-10).", minimum: 1, maximum: 10 },
28
+ country: {
29
+ type: "string",
30
+ description: "2-letter country code (RU, US, DE, ALL). Yandex: RU/TR/KZ/BY/UZ choose the search domain, other codes use yandex.com.",
31
+ },
32
+ language: { type: "string", description: "ISO 639-1 language code (ru, en, ...)." },
33
+ freshness: { type: "string", description: "Time filter: day, week, month or year." },
34
+ date_after: { type: "string", description: "Only results published after this date (YYYY-MM-DD)." },
35
+ date_before: { type: "string", description: "Only results published before this date (YYYY-MM-DD)." },
36
+ search_lang: { type: "string", description: "Brave result language code (en, en-gb, ru, ...)." },
37
+ ui_lang: { type: "string", description: "Brave UI locale in language-region form (en-US)." },
38
+ },
39
+ required: ["query"],
40
+ };
41
+ /** Разбирает аргументы инструмента (snake_case, как их передаёт ядро) и фильтры времени. */
42
+ export function parseSearchArgs(args, defaults, sdk = localWebSearchSdk) {
43
+ const query = sdk.readStringParam(args, "query", { required: true }) ?? "";
44
+ const rawCount = sdk.readPositiveIntegerParam(args, "count", { max: 10, message: "count must be an integer from 1 to 10." });
45
+ const count = sdk.resolveSearchCount(rawCount, defaults.count);
46
+ const time = sdk.parseWebSearchTimeFilters({
47
+ rawDateAfter: sdk.readStringParam(args, "date_after"),
48
+ rawDateBefore: sdk.readStringParam(args, "date_before"),
49
+ rawFreshness: sdk.readStringParam(args, "freshness"),
50
+ freshnessProvider: "brave",
51
+ docs: DOCS_URL,
52
+ invalidFreshnessMessage: "freshness must be day, week, month, or year.",
53
+ invalidDateAfterMessage: "date_after must be YYYY-MM-DD format.",
54
+ invalidDateBeforeMessage: "date_before must be YYYY-MM-DD format.",
55
+ invalidDateRangeMessage: "date_after must be before date_before.",
56
+ });
57
+ if ("error" in time) {
58
+ return time;
59
+ }
60
+ return {
61
+ query,
62
+ count,
63
+ country: sdk.readStringParam(args, "country"),
64
+ language: sdk.readStringParam(args, "language"),
65
+ searchLang: sdk.readStringParam(args, "search_lang"),
66
+ uiLang: sdk.readStringParam(args, "ui_lang"),
67
+ freshness: time.freshness,
68
+ dateAfter: time.dateAfter,
69
+ dateBefore: time.dateBefore,
70
+ };
71
+ }
72
+ function resolveReturnCount(sdk, ctx, pluginConfig) {
73
+ const fromSearch = ctx.searchConfig?.maxResults;
74
+ if (typeof fromSearch === "number" && Number.isFinite(fromSearch)) {
75
+ return sdk.resolveSearchCount(fromSearch, DEFAULT_RETURN_COUNT);
76
+ }
77
+ return pluginMaxResults(ctx.config, pluginConfig) ?? DEFAULT_RETURN_COUNT;
78
+ }
79
+ function toEngineParams(parsed, extra) {
80
+ return {
81
+ query: parsed.query,
82
+ count: ENGINE_FETCH_COUNT,
83
+ country: parsed.country,
84
+ language: parsed.language,
85
+ searchLang: parsed.searchLang,
86
+ uiLang: parsed.uiLang,
87
+ freshness: parsed.freshness,
88
+ dateAfter: parsed.dateAfter,
89
+ dateBefore: parsed.dateBefore,
90
+ signal: extra.signal,
91
+ timeoutMs: extra.timeoutMs,
92
+ };
93
+ }
94
+ function cacheKeyFor(sdk, prefix, parsed) {
95
+ return sdk.buildSearchCacheKey([
96
+ prefix,
97
+ parsed.query,
98
+ parsed.count,
99
+ parsed.country,
100
+ parsed.language,
101
+ parsed.searchLang,
102
+ parsed.uiLang,
103
+ parsed.freshness,
104
+ parsed.dateAfter,
105
+ parsed.dateBefore,
106
+ ]);
107
+ }
108
+ const warnedOnce = new Set();
109
+ function warnOnce(logger, key, message) {
110
+ if (warnedOnce.has(key)) {
111
+ return;
112
+ }
113
+ warnedOnce.add(key);
114
+ logger.warn(message);
115
+ }
116
+ /** Для тестов: сбросить одноразовые предупреждения. */
117
+ export function resetWarnings() {
118
+ warnedOnce.clear();
119
+ }
120
+ function asRecord(value) {
121
+ return value !== null && typeof value === "object" && !Array.isArray(value)
122
+ ? value
123
+ : undefined;
124
+ }
125
+ /** Ключ Яндекса как «основной» credential обоих провайдеров: tools.web.search.yandex.apiKey ↔ plugins.entries.<id>.config.yandex.apiKey. */
126
+ function credentialAccessors() {
127
+ return {
128
+ credentialPath: YANDEX_CREDENTIAL_PATH,
129
+ getCredentialValue: (searchConfig) => asRecord(searchConfig?.yandex)?.apiKey,
130
+ setCredentialValue: (target, value) => {
131
+ const yandex = (asRecord(target.yandex) ?? (target.yandex = {}));
132
+ yandex.apiKey = value;
133
+ },
134
+ getConfiguredCredentialValue: (config) => asRecord(pluginEntryConfig(config)?.yandex)?.apiKey,
135
+ setConfiguredCredentialValue: (configTarget, value) => {
136
+ const plugins = (asRecord(configTarget.plugins) ?? (configTarget.plugins = {}));
137
+ const entries = (asRecord(plugins.entries) ?? (plugins.entries = {}));
138
+ const entry = (asRecord(entries[PLUGIN_ID]) ?? (entries[PLUGIN_ID] = {}));
139
+ const config = (asRecord(entry.config) ?? (entry.config = {}));
140
+ const yandex = (asRecord(config.yandex) ?? (config.yandex = {}));
141
+ yandex.apiKey = value;
142
+ },
143
+ };
144
+ }
145
+ // =============================================================================
146
+ // multi
147
+ // =============================================================================
148
+ export function createMultiSearchProviderPlugin(deps = {}) {
149
+ const logger = deps.logger ?? silentLogger;
150
+ return {
151
+ id: "multi",
152
+ label: "Multi-Search (Yandex + Brave)",
153
+ hint: "Параллельный поиск Yandex Search API + Brave Search с дедупликацией; работает, если настроен хотя бы один движок.",
154
+ requiresCredential: false,
155
+ credentialLabel: "Yandex Cloud API Key",
156
+ // Только имя ключа Яндекса: ядро подставляет первую найденную переменную из этого списка
157
+ // в credential провайдера (yandex.apiKey), поэтому *_FILE и ключи Brave здесь недопустимы.
158
+ envVars: ["YC_API_KEY"],
159
+ placeholder: "AQVN...",
160
+ signupUrl: YANDEX_SIGNUP_URL,
161
+ docsUrl: YANDEX_DOCS_URL,
162
+ autoDetectOrder: 20,
163
+ inactiveSecretPaths: [],
164
+ ...credentialAccessors(),
165
+ createTool: (ctx) => ({
166
+ description: "Параллельный веб-поиск через Yandex Search API и Brave Search; результаты объединены и дедуплицированы. " +
167
+ "Поддерживает count, country, language, freshness, date_after/date_before.",
168
+ parameters: WEB_SEARCH_PARAMETERS,
169
+ execute: async (args, context) => {
170
+ const sdk = deps.sdk ?? (await loadWebSearchSdk(logger));
171
+ const parsed = parseSearchArgs(args, { count: resolveReturnCount(sdk, ctx, deps.pluginConfig) }, sdk);
172
+ if ("error" in parsed) {
173
+ return parsed;
174
+ }
175
+ const timeoutMs = sdk.resolveSearchTimeoutSeconds(ctx.searchConfig) * 1000;
176
+ const cacheTtlMs = sdk.resolveSearchCacheTtlMs(ctx.searchConfig);
177
+ const cacheKey = cacheKeyFor(sdk, "multi", parsed);
178
+ if (cacheTtlMs > 0) {
179
+ const cached = sdk.readCachedSearchPayload(cacheKey, cacheTtlMs);
180
+ if (cached) {
181
+ return cached;
182
+ }
183
+ }
184
+ const credentials = resolveCredentials({
185
+ config: ctx.config,
186
+ searchConfig: ctx.searchConfig,
187
+ pluginConfig: deps.pluginConfig,
188
+ logger,
189
+ sdk,
190
+ });
191
+ if (!credentials.yandexApiKey || !credentials.yandexFolderId) {
192
+ warnOnce(logger, "multi:yandex", `[multi-search] Яндекс отключён: нет YC_API_KEY/YC_FOLDER_ID (или ${YANDEX_CREDENTIAL_PATH})`);
193
+ }
194
+ if (!credentials.braveApiKey) {
195
+ warnOnce(logger, "multi:brave", `[multi-search] Brave отключён: нет BRAVE_SEARCH_API_KEY (или ${BRAVE_CREDENTIAL_PATH})`);
196
+ }
197
+ const outcome = await runMultiSearch({
198
+ params: toEngineParams(parsed, { signal: context?.signal, timeoutMs }),
199
+ returnCount: parsed.count,
200
+ credentials,
201
+ logger,
202
+ fetchImpl: deps.fetchImpl,
203
+ now: deps.now?.(),
204
+ });
205
+ if (!outcome.ok) {
206
+ return {
207
+ error: outcome.error ?? "provider_error",
208
+ message: outcome.message ?? "web_search (multi): поиск не удался",
209
+ docs: DOCS_URL,
210
+ };
211
+ }
212
+ const payload = { results: outcome.rows, count: outcome.rows.length, tookMs: outcome.tookMs };
213
+ if (outcome.complete && cacheTtlMs > 0) {
214
+ sdk.writeCachedSearchPayload(cacheKey, payload, cacheTtlMs);
215
+ }
216
+ return payload;
217
+ },
218
+ }),
219
+ };
220
+ }
221
+ // =============================================================================
222
+ // yandex
223
+ // =============================================================================
224
+ export function createYandexSearchProviderPlugin(deps = {}) {
225
+ const logger = deps.logger ?? silentLogger;
226
+ return {
227
+ id: "yandex",
228
+ label: "Yandex Search",
229
+ hint: "Поиск через Yandex Search API v2 (отложенный режим): российские и мировые результаты.",
230
+ requiresCredential: true,
231
+ credentialLabel: "Yandex Cloud API Key",
232
+ // См. комментарий у multi: YC_API_KEY_FILE плагин читает сам, ядру его показывать нельзя.
233
+ envVars: ["YC_API_KEY"],
234
+ placeholder: "AQVN...",
235
+ signupUrl: YANDEX_SIGNUP_URL,
236
+ docsUrl: YANDEX_DOCS_URL,
237
+ autoDetectOrder: 5,
238
+ inactiveSecretPaths: [],
239
+ ...credentialAccessors(),
240
+ createTool: (ctx) => ({
241
+ description: "Веб-поиск через Yandex Search API v2. Возвращает заголовки, URL, сниппеты и даты документов.",
242
+ parameters: WEB_SEARCH_PARAMETERS,
243
+ execute: async (args, context) => {
244
+ const sdk = deps.sdk ?? (await loadWebSearchSdk(logger));
245
+ const parsed = parseSearchArgs(args, { count: resolveReturnCount(sdk, ctx, deps.pluginConfig) }, sdk);
246
+ if ("error" in parsed) {
247
+ return parsed;
248
+ }
249
+ const credentials = resolveCredentials({
250
+ config: ctx.config,
251
+ searchConfig: ctx.searchConfig,
252
+ pluginConfig: deps.pluginConfig,
253
+ logger,
254
+ sdk,
255
+ });
256
+ if (!credentials.yandexApiKey || !credentials.yandexFolderId) {
257
+ return {
258
+ error: "missing_yandex_api_key",
259
+ message: "web_search (yandex): нужны YC_API_KEY (или YC_API_KEY_FILE) и YC_FOLDER_ID в окружении Gateway " +
260
+ `либо ${YANDEX_CREDENTIAL_PATH} и plugins.entries.${PLUGIN_ID}.config.yandex.folderId.`,
261
+ docs: DOCS_URL,
262
+ };
263
+ }
264
+ const timeoutMs = sdk.resolveSearchTimeoutSeconds(ctx.searchConfig) * 1000;
265
+ const cacheTtlMs = sdk.resolveSearchCacheTtlMs(ctx.searchConfig);
266
+ const cacheKey = cacheKeyFor(sdk, "yandex", parsed);
267
+ if (cacheTtlMs > 0) {
268
+ const cached = sdk.readCachedSearchPayload(cacheKey, cacheTtlMs);
269
+ if (cached) {
270
+ return cached;
271
+ }
272
+ }
273
+ const period = resolveYandexPeriod({
274
+ freshness: parsed.freshness,
275
+ dateAfter: parsed.dateAfter,
276
+ dateBefore: parsed.dateBefore,
277
+ now: deps.now?.(),
278
+ });
279
+ if (period.coverage === "none") {
280
+ logger.warn(`[yandex-search] фильтр по дате не применён: ${period.note}`);
281
+ }
282
+ else if (period.note) {
283
+ logger.debug?.(`[yandex-search] period=${period.period} (${period.note})`);
284
+ }
285
+ const startedAt = Date.now();
286
+ try {
287
+ const rows = (await searchYandex(toEngineParams(parsed, { signal: context?.signal, timeoutMs }), {
288
+ apiKey: credentials.yandexApiKey,
289
+ folderId: credentials.yandexFolderId,
290
+ fetchImpl: deps.fetchImpl,
291
+ logger,
292
+ period: period.period,
293
+ })).slice(0, parsed.count);
294
+ const payload = { results: rows, count: rows.length, tookMs: Date.now() - startedAt };
295
+ logger.info(`[yandex-search] results=${rows.length} tookMs=${payload.tookMs}`);
296
+ if (cacheTtlMs > 0) {
297
+ sdk.writeCachedSearchPayload(cacheKey, payload, cacheTtlMs);
298
+ }
299
+ return payload;
300
+ }
301
+ catch (err) {
302
+ if (context?.signal?.aborted) {
303
+ throw abortReason(context.signal);
304
+ }
305
+ const message = errorMessage(err);
306
+ logger.warn(`[yandex-search] упал за ${Date.now() - startedAt} мс: ${message} | запрос: «${truncate(parsed.query, 80)}»`);
307
+ return { error: "provider_error", message: `web_search (yandex): ${message}`, docs: DOCS_URL };
308
+ }
309
+ },
310
+ }),
311
+ };
312
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Хелперы `openclaw/plugin-sdk/provider-web-search` с локальным запасным вариантом.
3
+ *
4
+ * Внутри Gateway модуль SDK есть всегда (node_modules/openclaw → установленный OpenClaw), и тогда кэш
5
+ * поиска общий с ядром, а сообщения об ошибках параметров совпадают с официальными провайдерами.
6
+ * Вне Gateway (CI, тесты без OpenClaw, `npm ci --omit=peer`) используется встроенная реализация
7
+ * с той же семантикой, что и в OpenClaw 2026.9.x.
8
+ */
9
+ import { errorMessage } from "./util.js";
10
+ const LOCAL_CACHE = new Map();
11
+ const MINUTE_MS = 60_000;
12
+ const DEFAULT_CACHE_TTL_MINUTES = 15;
13
+ const DEFAULT_TIMEOUT_SECONDS = 30;
14
+ const MAX_SEARCH_COUNT = 10;
15
+ const FRESHNESS_CODES = {
16
+ day: "pd",
17
+ week: "pw",
18
+ month: "pm",
19
+ year: "py",
20
+ pd: "pd",
21
+ pw: "pw",
22
+ pm: "pm",
23
+ py: "py",
24
+ };
25
+ const ISO_DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
26
+ const DEFAULT_DOCS = "https://docs.openclaw.ai/tools/web";
27
+ function isValidIsoDay(value) {
28
+ if (!ISO_DAY_RE.test(value)) {
29
+ return false;
30
+ }
31
+ const parsed = new Date(`${value}T00:00:00Z`);
32
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
33
+ }
34
+ function finiteNumber(value) {
35
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
36
+ }
37
+ export const localWebSearchSdk = {
38
+ buildSearchCacheKey(parts) {
39
+ return parts.map((part) => (part === undefined || part === null ? "default" : String(part))).join(":").toLowerCase();
40
+ },
41
+ readCachedSearchPayload(cacheKey, ttlMs) {
42
+ const entry = LOCAL_CACHE.get(cacheKey);
43
+ if (!entry) {
44
+ return undefined;
45
+ }
46
+ const expiresAt = ttlMs === undefined ? entry.expiresAt : Math.min(entry.expiresAt, entry.storedAt + ttlMs);
47
+ if (Date.now() >= expiresAt) {
48
+ LOCAL_CACHE.delete(cacheKey);
49
+ return undefined;
50
+ }
51
+ return { ...entry.value, cached: true };
52
+ },
53
+ writeCachedSearchPayload(cacheKey, payload, ttlMs) {
54
+ if (!(ttlMs > 0)) {
55
+ return;
56
+ }
57
+ const now = Date.now();
58
+ LOCAL_CACHE.set(cacheKey, { value: payload, storedAt: now, expiresAt: now + ttlMs });
59
+ },
60
+ resolveSearchCacheTtlMs(searchConfig) {
61
+ const minutes = finiteNumber(searchConfig?.cacheTtlMinutes);
62
+ return (minutes !== undefined && minutes >= 0 ? minutes : DEFAULT_CACHE_TTL_MINUTES) * MINUTE_MS;
63
+ },
64
+ resolveSearchTimeoutSeconds(searchConfig) {
65
+ const seconds = finiteNumber(searchConfig?.timeoutSeconds);
66
+ return seconds !== undefined && seconds > 0 ? seconds : DEFAULT_TIMEOUT_SECONDS;
67
+ },
68
+ resolveSearchCount(value, fallback) {
69
+ const candidate = finiteNumber(value) ?? fallback;
70
+ return Math.max(1, Math.min(MAX_SEARCH_COUNT, Math.floor(candidate)));
71
+ },
72
+ readConfiguredSecretString(value, path) {
73
+ if (value === undefined || value === null) {
74
+ return undefined;
75
+ }
76
+ if (typeof value === "string") {
77
+ return value.trim() || undefined;
78
+ }
79
+ if (typeof value === "object") {
80
+ throw new Error(`${path}: значение задано объектом (SecretRef?), а не строкой; Gateway не подставил секрет`);
81
+ }
82
+ return String(value).trim() || undefined;
83
+ },
84
+ readStringParam(params, key, options) {
85
+ const raw = params[key];
86
+ const value = typeof raw === "string" ? raw.trim() : "";
87
+ if (!value) {
88
+ if (options?.required) {
89
+ throw new Error(`${key} required`);
90
+ }
91
+ return undefined;
92
+ }
93
+ return value;
94
+ },
95
+ readPositiveIntegerParam(params, key, options) {
96
+ const raw = params[key];
97
+ if (raw === undefined || raw === null || raw === "") {
98
+ return undefined;
99
+ }
100
+ const value = typeof raw === "number" ? raw : Number(String(raw).trim());
101
+ if (!Number.isInteger(value) || value <= 0 || (options?.max !== undefined && value > options.max)) {
102
+ throw new Error(options?.message ?? `${key} must be a positive integer`);
103
+ }
104
+ return value;
105
+ },
106
+ parseWebSearchTimeFilters(params) {
107
+ const docs = params.docs ?? DEFAULT_DOCS;
108
+ const rawFreshness = params.rawFreshness?.trim();
109
+ const freshness = rawFreshness ? FRESHNESS_CODES[rawFreshness.toLowerCase()] : undefined;
110
+ if (rawFreshness && !freshness) {
111
+ return { error: "invalid_freshness", message: params.invalidFreshnessMessage ?? "freshness must be day, week, month, or year.", docs };
112
+ }
113
+ const dateAfter = params.rawDateAfter?.trim() || undefined;
114
+ const dateBefore = params.rawDateBefore?.trim() || undefined;
115
+ if (rawFreshness && (dateAfter || dateBefore)) {
116
+ return {
117
+ error: "conflicting_time_filters",
118
+ message: params.conflictingTimeFiltersMessage ?? "freshness and date_after/date_before cannot be used together.",
119
+ docs,
120
+ };
121
+ }
122
+ if (dateAfter && !isValidIsoDay(dateAfter)) {
123
+ return { error: "invalid_date_after", message: params.invalidDateAfterMessage ?? "date_after must be YYYY-MM-DD format.", docs };
124
+ }
125
+ if (dateBefore && !isValidIsoDay(dateBefore)) {
126
+ return { error: "invalid_date_before", message: params.invalidDateBeforeMessage ?? "date_before must be YYYY-MM-DD format.", docs };
127
+ }
128
+ if (dateAfter && dateBefore && dateAfter > dateBefore) {
129
+ return { error: "invalid_date_range", message: params.invalidDateRangeMessage ?? "date_after must be before date_before.", docs };
130
+ }
131
+ return freshness ? { freshness } : { dateAfter, dateBefore };
132
+ },
133
+ };
134
+ // =============================================================================
135
+ // Загрузка настоящего SDK
136
+ // =============================================================================
137
+ let sdkPromise;
138
+ /** Настоящий SDK OpenClaw, если он доступен; иначе встроенная реализация (с одним предупреждением в лог). */
139
+ export function loadWebSearchSdk(logger) {
140
+ sdkPromise ??= import("openclaw/plugin-sdk/provider-web-search")
141
+ .then((module) => module)
142
+ .catch((err) => {
143
+ logger?.warn(`[openclaw-yandex-search] SDK provider-web-search недоступен (${errorMessage(err)}); ` +
144
+ "используется встроенная реализация кэша и разбора параметров");
145
+ return localWebSearchSdk;
146
+ });
147
+ return sdkPromise;
148
+ }
149
+ /** Для тестов: сбросить загруженный SDK и локальный кэш. */
150
+ export function resetWebSearchSdk() {
151
+ sdkPromise = undefined;
152
+ LOCAL_CACHE.clear();
153
+ }