/** * @license * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ import { GeminiWebClient } from "../google/gemini-web.ts"; import { GeminiSessionPool, isGeminiStaleError, GEMINI_STALE_MESSAGE } from "../google/gemini-session.ts"; import { loadCookieJar } from "../cookies/cookie-loader.ts"; import { resolveCookiePath } from "../utils/paths.ts"; import type { GeminiAskOptions, GeminiChatResponse } from "./types.ts"; export class GeminiWebAdapter { private pool: GeminiSessionPool; private defaultClient: GeminiWebClient | null = null; private cookiePath: string; constructor(cookiePath?: string) { this.cookiePath = cookiePath ? resolveCookiePath(cookiePath) : resolveCookiePath("gemini"); this.pool = new GeminiSessionPool(); } async isAvailable(): Promise { try { const cookies = await loadCookieJar(this.cookiePath); return cookies.some(c => c.name === "__Secure-1PSID"); } catch { return false; } } async ask(prompt: string, opts: GeminiAskOptions = {}): Promise { const model = (opts.model as string) ?? "flash"; const targetCookiePath = opts.cookiePath ? resolveCookiePath(opts.cookiePath) : this.cookiePath; const cookies = await loadCookieJar(targetCookiePath); const client = new GeminiWebClient({ model, cookies, }); await client.init(); try { const text = await client.generate(prompt); return { text, engine: "web", model, }; } catch (err: any) { if (isGeminiStaleError(err.message)) { throw new Error(`${GEMINI_STALE_MESSAGE} (${err.message})`); } throw err; } } async chat(conversationKey: string, prompt: string, opts: GeminiAskOptions = {}): Promise { const model = (opts.model as string) ?? "flash"; try { const text = await this.pool.generate(conversationKey, prompt, { model }); return { text, conversationId: conversationKey, engine: "web", model, }; } catch (err: any) { if (isGeminiStaleError(err.message)) { throw new Error(`${GEMINI_STALE_MESSAGE} (${err.message})`); } throw err; } } async getConversations(cookiePath?: string) { const targetCookiePath = cookiePath ? resolveCookiePath(cookiePath) : this.cookiePath; const cookies = await loadCookieJar(targetCookiePath); const client = new GeminiWebClient({ cookies }); await client.init(); return await client.listConversations(); } }