UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

254 lines (253 loc) • 10.2 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { f as normalizeResolvedSecretInputString } from "./types.secrets-BmNLLnHp.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { m as readToolStringParam, u as readPositiveIntegerParam } from "./common-njQNtpnW.mjs"; import { n as readProviderEnvValue } from "./provider-credential-values-pLjdcwQh.mjs"; import { d as formatProviderHttpErrorMessage, m as readProviderJsonObjectResponse, s as createProviderHttpError, t as ProviderHttpError, y as truncateErrorDetail } from "./provider-http-errors-Dtgw3x-5.mjs"; import { a as redactProviderResponseErrorText } from "./provider-request-header-redaction-Ckk_UIqk.mjs"; import { o as wrapWebContent } from "./external-content-CGL7l-3s.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import { C as withTrustedWebSearchEndpoint, _ as resolveSearchCacheTtlMs, a as buildUnsupportedSearchFilterResponse, d as parseWebSearchTimeFilters, i as buildSearchCacheKey, m as readConfiguredSecretString, o as externalContentStamp, p as readCachedSearchPayload, r as MAX_SEARCH_COUNT, w as writeCachedSearchPayload, y as resolveSearchTimeoutSeconds } from "./web-search-provider-common-BIurMuHZ.mjs"; import "./provider-http-LcawLneq.mjs"; import { n as resolveCitationRedirectUrl } from "./provider-web-search-hr4kzF3y.mjs"; import "./secret-input-runtime-BgioUt_I.mjs"; import { o as normalizeGoogleApiBaseUrl } from "./google-api-base-url-CSlG5eZd.mjs"; import { t as resolveGoogleApiClientHeaders } from "./google-api-client-header-YL-v53wl.mjs"; //#region extensions/google/src/gemini-web-search-provider.runtime.ts const DEFAULT_GEMINI_WEB_SEARCH_MODEL = "gemini-3.6-flash"; const GEMINI_PROVIDER_OWNED_HEADER_NAMES = /* @__PURE__ */ new Set([ "content-type", "x-goog-api-client", "x-goog-api-key" ]); const GEMINI_UNSAFE_REQUEST_HEADER_NAMES = /* @__PURE__ */ new Set([ "connection", "content-length", "expect", "host", "keep-alive", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade" ]); function throwMalformedGeminiResponse() { throw new Error("Gemini API error: malformed JSON response"); } const GEMINI_FRESHNESS_DAYS = { day: 1, week: 7, month: 30, year: 365 }; const GEMINI_DAY_FRESHNESS_HINT = "Prioritize web sources published in the last 24 hours."; function toGeminiTimeRangeTimestamp(e) { return e.toISOString().replace(/\.\d+Z$/, "Z"); } function isoDateExclusiveEnd(e) { const t = /* @__PURE__ */ new Date(`${e}T00:00:00Z`); t.setUTCDate(t.getUTCDate() + 1); return toGeminiTimeRangeTimestamp(t); } function resolveGeminiRuntimeApiKey(e) { return readConfiguredSecretString(e?.apiKey, "plugins.entries.google.config.webSearch.apiKey") ?? readProviderEnvValue(["GEMINI_API_KEY"]) ?? readConfiguredSecretString(e?.providerApiKey, "models.providers.google.apiKey"); } function resolveGeminiWebSearchHeaders(e) { if (!isRecord(e?.headers)) return; const t = new Headers(); for (const [n, r] of Object.entries(e.headers)) { const e = `plugins.entries.google.config.webSearch.headers[${JSON.stringify(n)}]`; const i = typeof r === "string" ? r : normalizeResolvedSecretInputString({ value: r, path: e }); if (i === void 0) throw new Error(`${e} must be a string or resolved SecretRef.`); let a; let o; try { const [e] = new Headers([[n, i]]).entries(); if (!e) throw new Error("missing normalized header entry"); [a, o] = e; } catch { throw new Error(`${e} is not a valid HTTP header.`); } if (GEMINI_UNSAFE_REQUEST_HEADER_NAMES.has(a)) throw new Error(`${e} uses a reserved or framing HTTP header.`); if (GEMINI_PROVIDER_OWNED_HEADER_NAMES.has(a)) continue; t.set(a, o); } const n = [...t.entries()]; return n.length > 0 ? Object.fromEntries(n) : void 0; } async function executeGeminiSearch(e, t, n) { n?.signal?.throwIfAborted(); const r = buildUnsupportedSearchFilterResponse({ country: e.country, language: e.language }, "gemini"); if (r) return r; const i = /* @__PURE__ */ new Date(); const a = readToolStringParam(e, "freshness"); const o = readToolStringParam(e, "date_after"); const s = readToolStringParam(e, "date_before"); const c = parseWebSearchTimeFilters({ rawDateAfter: o, rawDateBefore: s, rawFreshness: a, freshnessProvider: "perplexity", invalidFreshnessMessage: "freshness must be day, week, month, year, or the shortcuts pd, pw, pm, py.", invalidDateAfterMessage: "date_after must be YYYY-MM-DD format.", invalidDateBeforeMessage: "date_before must be YYYY-MM-DD format.", invalidDateRangeMessage: "date_after must be before date_before." }); if ("error" in c) return c; const { freshness: l, dateAfter: u, dateBefore: d } = c; let f; if (l && l !== "day") { const e = new Date(i); e.setUTCDate(e.getUTCDate() - GEMINI_FRESHNESS_DAYS[l]); f = { startTime: toGeminiTimeRangeTimestamp(e), endTime: toGeminiTimeRangeTimestamp(i) }; } else if (!l && (u || d)) f = { startTime: u ? `${u}T00:00:00Z` : "1970-01-01T00:00:00Z", endTime: d ? isoDateExclusiveEnd(d) : toGeminiTimeRangeTimestamp(i) }; const p = t?.gemini; const m = isRecord(p) ? p : {}; const h = resolveGeminiRuntimeApiKey(m); if (!h) return { error: "missing_gemini_api_key", message: "web_search (gemini) needs an API key. Set GEMINI_API_KEY in the Gateway environment, configure plugins.entries.google.config.webSearch.apiKey, or reuse models.providers.google.apiKey. If you do not want to configure a search API key, use web_fetch for a specific URL or the browser tool for interactive pages.", docs: "https://docs.openclaw.ai/tools/web" }; const g = readToolStringParam(e, "query", { required: true }); readPositiveIntegerParam(e, "count", { max: 10, message: `count must be an integer from 1 to ${10}.` }); const _ = normalizeOptionalString(m?.model) ?? DEFAULT_GEMINI_WEB_SEARCH_MODEL; const v = normalizeGoogleApiBaseUrl(normalizeOptionalString(m?.baseUrl) ?? normalizeOptionalString(m?.providerBaseUrl)); const y = resolveGeminiWebSearchHeaders(m); const b = sha256Hex(JSON.stringify([h, y])); const x = buildSearchCacheKey([ "gemini", g, v, _, l, u, d, b ]); const S = resolveSearchCacheTtlMs(t); const C = readCachedSearchPayload(x, S); if (C) return C; const w = Date.now(); const T = l === "day" ? `${g}\n\nSearch recency instruction: ${GEMINI_DAY_FRESHNESS_HINT} If no matching recent sources are available, state that limitation and use the most relevant available sources.` : g; const E = resolveSearchTimeoutSeconds(t); const D = n?.signal; const O = `${v}/models/${_}:generateContent`; const k = f === void 0 ? {} : { timeRangeFilter: f }; const A = { "Content-Type": "application/json", "x-goog-api-key": h, ...resolveGoogleApiClientHeaders({ baseUrl: v, api: "google-generative-ai", capability: "other", transport: "http" }) }; let j = A; if (y) { const e = new Headers(y); for (const [t, n] of Object.entries(A)) e.set(t, n); j = e; } const M = await withTrustedWebSearchEndpoint({ url: O, timeoutSeconds: E, signal: D, init: { method: "POST", headers: j, body: JSON.stringify({ contents: [{ parts: [{ text: T }] }], tools: [{ google_search: k }] }) } }, async (e) => { if (!e.ok) { const t = await createProviderHttpError(e, "Gemini API error", { signal: D, requestHeaders: j }); t.message = t.message.replace(/key=[^&\s]+/giu, "key=***"); throw t; } const t = await readProviderJsonObjectResponse(e, "Gemini API error"); if (t.error !== void 0) { if (!isRecord(t.error)) throwMalformedGeminiResponse(); const e = normalizeOptionalString(t.error.message) ?? normalizeOptionalString(t.error.status) ?? "unknown"; const n = typeof t.error.code === "number" ? t.error.code : 0; throw new ProviderHttpError(formatProviderHttpErrorMessage({ label: "Gemini API error", status: n, detail: redactProviderResponseErrorText(e, j).replace(/key=[^&\s]+/giu, "key=***") }), { status: n }); } if (t.candidates !== void 0 && !Array.isArray(t.candidates) || t.promptFeedback !== void 0 && !isRecord(t.promptFeedback)) throwMalformedGeminiResponse(); const n = t.candidates?.[0]; if (n !== void 0 && !isRecord(n)) throwMalformedGeminiResponse(); const r = n?.content; if (r !== void 0 && !isRecord(r)) throwMalformedGeminiResponse(); const i = r?.parts; if (i !== void 0 && !Array.isArray(i)) throwMalformedGeminiResponse(); const a = (i ?? []).map((e) => isRecord(e) && typeof e.text === "string" ? e.text : void 0).filter((e) => Boolean(e)).join("\n"); const o = n?.groundingMetadata; if (o !== void 0 && !isRecord(o)) throwMalformedGeminiResponse(); const s = o?.groundingChunks; if (s !== void 0 && !Array.isArray(s)) throwMalformedGeminiResponse(); if (!a) { const e = [t.promptFeedback?.blockReason, n?.finishReason]; if (e.some((e) => e !== void 0 && typeof e !== "string") || i?.some((e) => !isRecord(e) || e.text !== void 0 && typeof e.text !== "string")) throwMalformedGeminiResponse(); const r = e.map((e) => normalizeOptionalString(e)).find(Boolean); const a = r ? ` (${truncateErrorDetail(r, 120)})` : ""; throw new Error(`Gemini search returned no final answer${a}.`); } const c = (s ?? []).flatMap((e) => { if (!isRecord(e) || !isRecord(e.web) || typeof e.web.uri !== "string") return []; return [{ url: e.web.uri, title: typeof e.web.title === "string" ? e.web.title : void 0 }]; }); const l = []; for (let e = 0; e < c.length; e += 10) { const t = c.slice(e, e + 10); const n = await Promise.all(t.map(async (e) => Object.assign({}, e, { url: await resolveCitationRedirectUrl(e.url) }))); l.push(...n); } return { content: a, citations: l }; }); n?.signal?.throwIfAborted(); const N = { query: g, provider: "gemini", model: _, tookMs: Date.now() - w, externalContent: externalContentStamp("gemini"), content: wrapWebContent(M.content), citations: M.citations }; writeCachedSearchPayload(x, N, S); return N; } //#endregion export { executeGeminiSearch };