gemini-web 0.1.0: the Gemini web app, one streamed call to its own endpoint per request
@jtbbtnt54249 on X (11-18) asked for a Gemini web plugin: the community
@dorokuma/magpie-gemini-web is "太慢了根本用不了". The MCP in their
screenshot is a Gemini web "custom app" remote connector: Google's servers
call a public MCP URL, so it can't serve a local agent and is not a route.
Why the existing one is slow: it goes through a separate local Go backend
that fetches the XSRF token before every request, uploads prompts over
128KB as a file, sleeps 2s between retries, and holds replies behind a
tool-fence gate and a slot limiter.
This package calls gemini.google.com the way the app's page does:
- the page's tokens (SNlM0e, cfb2h, FdrFJe) are read from /app once and
kept 15 minutes;
- each request is one POST to StreamGenerate, the whole request inline in
a temporary chat (slot 45, nothing kept in history), read as it
streams and given back as SSE or a whole completion;
- tools are asked for as <tool_call> text (prompt.mjs and openai.mjs from
doubao-work) and given back as tool_calls;
- signed in: a Chrome profile of the plugin's own opens at Google's
sign-in, the user signs in themselves, the google.com cookies are read
with Storage.getCookies on the browser target (nothing attached to the
page) and the window closes. Set-Cookie renewals are saved back with
client.auth.set; RotateCookies every ten minutes; signed out, rotate,
then reopen the profile headless, then ask for a sign-in;
- a visitor (no account) gets Google's visitor model;
- models from the account's own picker (otAQ7b), fallback marked;
- prompts over 600K characters get 413 before they are sent (measured:
315K fine, 900K ignored the request, 1.8M refused with error 3); error 3
is named as a refusal with its likely causes.
Run:
- HOME=$(mktemp -d) bun test packages/gemini-web on mote: 28 pass. The
fixtures are real StreamGenerate replies (a signed-in "pong" served as
4 Hydrogen, a visitor's rivers text with its real chunks) and a real
otAQ7b list, with the location Google guessed scrubbed.
- Broken by hand: not sending `at` turns two tests red.
- Full suite on mote, HOME=$(mktemp -d) bun test at ea805ecc plus this change (before the root README line): 9091 pass, 20 skip, 0 fail.
- bun scripts/check.mjs: registry.json and gemini-web ok.
- Real, through the plugin's fetch from Bun on mote, as a visitor: three
"pong" requests, first text at 14.0s (reads the page), 7.9s, 6.9s; a
tool request came back as Echo {"text":"391"} with finish tool_calls.
Signed in, in the app's own page: first text about 3.5s.
Not tried: a real Google sign-in through the plugin's window (Google may
refuse a browser with a DevTools port open), whether DBSC stops
RotateCookies, thinking output, paid models (4 Carbon, 4 Neon). Said in
the README.
First publish of a new package: publish.yml can't publish it (no trusted
publisher yet), so magpie installs it from the dist branch until the
owner publishes it once and adds the trust.
This commit is contained in:
@@ -31,6 +31,7 @@ vendor service and makes its requests. The packages work in OpenCode and in
|
||||
| [inkstone](packages/inkstone) | (Unofficial) 书生·端砚 Token Plan: browser sign-in gives the ink-credit balance, the 5-hour and 7-day windows and the credit packs, and creates an `ink-*` API key to serve the plan's models for chat | `intern-inkstone` |
|
||||
| [joycode](packages/joycode) | JoyCode IDE credits with JD account browser sign-in, live models and credit multipliers (unofficial) | `joycode` |
|
||||
| [doubao-work](packages/doubao-work) | Doubao Work (豆包工作), whose agent runs in the cloud with no API, through the Doubao desktop app driven the way a person uses it (macOS, Windows) | `doubao-work` |
|
||||
| [gemini-web](packages/gemini-web) | The Gemini web app (gemini.google.com), not Google's API: your Google account signed in through a browser window of its own, or as a visitor; one streamed call to the app's own endpoint per request | `gemini-web` |
|
||||
| [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in; separate from Kimi Code | `kimi-work` |
|
||||
| [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` |
|
||||
| [loomy](packages/loomy) | iFlytek's Loomy (loomyad.xunfei.cn), with SMS sign-in | `loomy` |
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 magpie-community contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Gemini 网页版 (Gemini web app)
|
||||
|
||||
**This is not Google's Gemini API.** It is the Gemini web app,
|
||||
gemini.google.com, on your Google account (or on none), used the way the
|
||||
app's own page uses it. Text only; the client's tools are asked for as
|
||||
text. Unofficial: Google can change or stop it at any time.
|
||||
|
||||
## How it works
|
||||
|
||||
1. **Sign in.** "在单独的浏览器窗口登录 Google 账号" opens Chrome (or Edge,
|
||||
Chromium, Brave) with a profile of the plugin's own, under
|
||||
`~/.config/magpie/gemini-web-browser/<id>` (`%LOCALAPPDATA%\magpie\gemini-web-browser`
|
||||
on Windows), at Google's sign-in page. You sign in there yourself; the
|
||||
plugin never sees your password. Once the profile holds Google's
|
||||
session cookies (`__Secure-1PSID`, `__Secure-1PSIDTS`), the plugin reads
|
||||
the google.com cookies through that browser's DevTools endpoint on
|
||||
127.0.0.1 and closes the window. Your everyday browser is not touched.
|
||||
|
||||
"不登录使用" needs no account: Google then serves the model it gives
|
||||
visitors (3.5 Flash-Lite on 2026-11-19).
|
||||
2. **Each request** is one POST to the app's own `StreamGenerate`
|
||||
endpoint, with the whole request (system prompt, tools, every turn)
|
||||
inline as one message, in a temporary chat, so nothing is kept in your
|
||||
Gemini history. The reply is read as it streams and given back as an
|
||||
OpenAI chat completion (SSE or whole). The page's tokens (`SNlM0e`,
|
||||
`cfb2h`, `FdrFJe`) are read from `/app` once and kept for 15 minutes,
|
||||
not fetched before every request.
|
||||
3. **Tools** are asked for as `<tool_call>{"name": …, "arguments": …}</tool_call>`
|
||||
blocks and given back as `tool_calls`.
|
||||
4. **Keeping the sign-in.** Cookies Google renews on its replies are saved
|
||||
back to the account. Every ten minutes the short-lived cookie is renewed
|
||||
the way the app's page does it (`RotateCookies`). When Google takes the
|
||||
cookies as signed out, the plugin renews them once more, and then opens
|
||||
the same profile again without a window, where Chrome renews them
|
||||
itself. Only when that fails too are you asked to sign in again.
|
||||
|
||||
## Models
|
||||
|
||||
Signed in, the list is your account's own model picker (the `otAQ7b` call
|
||||
the page makes), named `gemini-` plus the picker's name: `gemini-auto`,
|
||||
`gemini-3.6-flash`, `gemini-3.1-pro`, and whatever your plan shows. Before
|
||||
it has been read the plugin offers Auto, 3.6 Flash and 3.1 Pro. A visitor
|
||||
gets `gemini-auto` only.
|
||||
|
||||
Google decides what is served: on a free account Auto was served as
|
||||
"4 Hydrogen" whichever model was asked for.
|
||||
|
||||
## Why it is faster than going through a local backend
|
||||
|
||||
There is no second process, no file upload and no retry sleep: one HTTPS
|
||||
request per chat request, streamed straight back. Measured on 2026-11-19:
|
||||
the first text came about 3.5 s after the request signed in (in the app's
|
||||
own page), and 7 to 8 s as a visitor through this plugin (14 s for the
|
||||
first request, which also reads the page). Most of that is Google's own
|
||||
time to start answering.
|
||||
|
||||
## Limits
|
||||
|
||||
- Prompts over 600,000 characters are refused with HTTP 413 before they are
|
||||
sent. Measured: 315K characters were answered in full, 900K came back but
|
||||
ignored the request, and 1.8M was refused by Google (error 3).
|
||||
- Google's refusal (error 3) also comes back when the model is not on your
|
||||
plan or requests come too fast; the message says so.
|
||||
- Two requests at a time per account.
|
||||
- Text only: images and files in a request are left out.
|
||||
|
||||
## Not tried
|
||||
|
||||
- A real Google sign-in through the plugin's window. The flow, the cookie
|
||||
read and the request are tested with Google's real replies; a sign-in
|
||||
itself was not made, and Google may refuse to sign in a browser that
|
||||
has a DevTools port open ("This browser or app may not be secure"). If
|
||||
it does, say so in an issue.
|
||||
- Whether Chrome's device-bound sessions (DBSC) stop `RotateCookies`; the
|
||||
windowless renewal is there for that case.
|
||||
- Thinking output and paid-plan models (4 Carbon, 4 Neon).
|
||||
|
||||
## Settings
|
||||
|
||||
- `GEMINI_WEB_BROWSER`: the browser to open, when it isn't found.
|
||||
- `GEMINI_WEB_PROFILE`: where the plugin keeps its browser profiles.
|
||||
|
||||
---
|
||||
|
||||
## 中文
|
||||
|
||||
**这不是 Google 的 Gemini API**,而是 Gemini 网页版(gemini.google.com),按网页自己的方式调用。只支持文本,客户端的工具以文本方式调用。非官方,Google 随时可能改动。
|
||||
|
||||
- **登录**:在插件自己的 Chrome 配置(不影响你平时的浏览器)里,由你自己登录 Google 账号;插件不接触密码,登录后通过本机 127.0.0.1 的 DevTools 读取 google.com 的 Cookie 并关闭窗口。也可以不登录,以访客使用(目前是 3.5 Flash-Lite)。
|
||||
- **请求**:每个请求是对网页版 `StreamGenerate` 的一次 POST,整段请求放进一条消息,用临时对话(不进 Gemini 历史),边生成边返回。页面令牌缓存 15 分钟,不会每次请求都去取。没有本地后端、没有文件上传、没有重试等待。
|
||||
- **保持登录**:Google 回复里更新的 Cookie 会存回账号;每十分钟按网页的方式续期;失效时先续期,再无窗口地打开同一个配置让 Chrome 自己续期,都不行才请你重新登录。
|
||||
- **模型**:登录后读取你账号自己的模型选择器(`otAQ7b`)。
|
||||
- **限制**:超过 60 万字符的请求直接返回 413;每个账号同时两个请求;图片和文件不会发出。
|
||||
- **没试过**:用插件的窗口真实登录 Google(Google 可能拒绝开着 DevTools 端口的浏览器登录,遇到请提 issue);DBSC 是否会挡住续期;思考输出和付费模型。
|
||||
@@ -0,0 +1,206 @@
|
||||
// Sign-in through a browser window of the plugin's own: Chrome (or Edge,
|
||||
// Chromium, Brave) with a private profile, opened at Google's sign-in page.
|
||||
// The user signs in there themselves; the plugin never sees a password.
|
||||
// It reads the profile's google.com cookies through the browser's own
|
||||
// DevTools endpoint (Storage.getCookies on the browser target: nothing is
|
||||
// attached to the page the user types into) and closes the window. The
|
||||
// profile is kept: when the cookies stop working, the same profile is
|
||||
// opened again without a window and the browser renews them itself.
|
||||
import { spawn } from "node:child_process"
|
||||
import { chmodSync, existsSync, mkdirSync } from "node:fs"
|
||||
import { createServer } from "node:net"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
export const SIGN_IN = "https://accounts.google.com/ServiceLogin?continue=" + encodeURIComponent("https://gemini.google.com/app")
|
||||
const GEMINI = "https://gemini.google.com/app"
|
||||
const NEED = ["__Secure-1PSID", "__Secure-1PSIDTS"]
|
||||
|
||||
export function profileRoot(env = process.env, platform = process.platform) {
|
||||
if (env.GEMINI_WEB_PROFILE) return env.GEMINI_WEB_PROFILE
|
||||
if (platform === "win32") return join(env.LOCALAPPDATA || env.APPDATA || tmpdir(), "magpie", "gemini-web-browser")
|
||||
return join(env.XDG_CONFIG_HOME || join(env.HOME || tmpdir(), ".config"), "magpie", "gemini-web-browser")
|
||||
}
|
||||
|
||||
export function findBrowser(platform = process.platform, env = process.env) {
|
||||
if (env.GEMINI_WEB_BROWSER && existsSync(env.GEMINI_WEB_BROWSER)) return env.GEMINI_WEB_BROWSER
|
||||
const home = env.HOME || ""
|
||||
const candidates =
|
||||
platform === "darwin"
|
||||
? [
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
||||
"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
|
||||
]
|
||||
: platform === "win32"
|
||||
? [
|
||||
join(env.PROGRAMFILES || "", "Google/Chrome/Application/chrome.exe"),
|
||||
join(env["PROGRAMFILES(X86)"] || "", "Google/Chrome/Application/chrome.exe"),
|
||||
join(env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
|
||||
join(env.PROGRAMFILES || "", "Microsoft/Edge/Application/msedge.exe"),
|
||||
join(env["PROGRAMFILES(X86)"] || "", "Microsoft/Edge/Application/msedge.exe"),
|
||||
]
|
||||
: ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium", "/usr/bin/chromium-browser", "/snap/bin/chromium", "/usr/bin/microsoft-edge"]
|
||||
return candidates.find((p) => p && existsSync(p)) ?? ""
|
||||
}
|
||||
|
||||
export function browserArgs(profile, port, url, { headless = false } = {}) {
|
||||
return [
|
||||
`--user-data-dir=${profile}`,
|
||||
`--remote-debugging-port=${port}`,
|
||||
"--remote-debugging-address=127.0.0.1",
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
"--disable-sync",
|
||||
"--disable-default-apps",
|
||||
"--disable-background-mode",
|
||||
...(headless ? ["--headless=new"] : ["--new-window"]),
|
||||
url,
|
||||
]
|
||||
}
|
||||
|
||||
function freePort() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const s = createServer()
|
||||
s.on("error", reject)
|
||||
s.listen(0, "127.0.0.1", () => {
|
||||
const { port } = s.address()
|
||||
s.close(() => resolve(port))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// cdp sends one command to the browser target and answers its result
|
||||
async function cdp(port, method, params = {}, timeout = 3000) {
|
||||
const v = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1500) }).then((r) => r.json())
|
||||
const url = v?.webSocketDebuggerUrl
|
||||
if (!url) throw new Error("no DevTools endpoint")
|
||||
return await new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(url)
|
||||
const timer = setTimeout(() => {
|
||||
try { ws.close() } catch {}
|
||||
reject(new Error("DevTools timed out"))
|
||||
}, timeout)
|
||||
ws.onopen = () => ws.send(JSON.stringify({ id: 1, method, params }))
|
||||
ws.onerror = () => {
|
||||
clearTimeout(timer)
|
||||
reject(new Error("DevTools connection failed"))
|
||||
}
|
||||
ws.onmessage = (ev) => {
|
||||
let m
|
||||
try { m = JSON.parse(String(ev.data)) } catch { return }
|
||||
if (m.id !== 1) return
|
||||
clearTimeout(timer)
|
||||
try { ws.close() } catch {}
|
||||
if (m.error) reject(new Error(m.error.message || method + " failed"))
|
||||
else resolve(m.result)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// googleCookies keeps the cookies a request to gemini.google.com carries
|
||||
export function googleCookies(list) {
|
||||
const out = {}
|
||||
for (const c of list ?? []) {
|
||||
const d = String(c?.domain ?? "").replace(/^\./, "")
|
||||
if (d !== "google.com" && d !== "gemini.google.com") continue
|
||||
if ((c.path ?? "/") !== "/") continue
|
||||
if (typeof c.name === "string" && typeof c.value === "string") out[c.name] = c.value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const hasSession = (cookies) => NEED.every((n) => cookies[n])
|
||||
|
||||
function waitExit(child, ms) {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
|
||||
return new Promise((r) => {
|
||||
const t = setTimeout(r, ms)
|
||||
child.once("exit", () => {
|
||||
clearTimeout(t)
|
||||
r()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
// open starts the browser on profile and answers a handle that reads its
|
||||
// cookies and closes it
|
||||
export async function open(profile, url, { headless = false, browser = findBrowser() } = {}) {
|
||||
if (!browser) throw Object.assign(new Error("没有找到 Chrome、Edge、Chromium 或 Brave。请先安装 Chrome,或用 GEMINI_WEB_BROWSER 指定浏览器。"), { code: "browser_missing" })
|
||||
mkdirSync(profile, { recursive: true, mode: 0o700 })
|
||||
try { chmodSync(profile, 0o700) } catch {}
|
||||
const port = await freePort()
|
||||
const child = spawn(browser, browserArgs(profile, port, url, { headless }), { stdio: "ignore", detached: false })
|
||||
let exited = false
|
||||
child.once("error", () => (exited = true))
|
||||
child.once("exit", () => (exited = true))
|
||||
return {
|
||||
get exited() {
|
||||
return exited
|
||||
},
|
||||
async cookies() {
|
||||
const r = await cdp(port, "Storage.getCookies")
|
||||
return googleCookies(r?.cookies)
|
||||
},
|
||||
async close() {
|
||||
if (!exited) {
|
||||
try { child.kill("SIGTERM") } catch {}
|
||||
await waitExit(child, 2000)
|
||||
}
|
||||
if (!exited) {
|
||||
try { child.kill("SIGKILL") } catch {}
|
||||
await waitExit(child, 1000)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// signIn opens the window and waits (up to timeout) for the user to sign
|
||||
// in, then answers the cookies. It answers null when the window was
|
||||
// closed or the time ran out.
|
||||
export async function signIn(profile, { timeout = 5 * 60_000, poll = 1000, settle = 2500, opener = open } = {}) {
|
||||
const b = await opener(profile, SIGN_IN)
|
||||
try {
|
||||
const end = Date.now() + timeout
|
||||
while (Date.now() < end && !b.exited) {
|
||||
const c = await b.cookies().catch(() => null)
|
||||
if (c && hasSession(c)) {
|
||||
// let the redirect to gemini.google.com finish, so the cookies it
|
||||
// sets are in the jar too
|
||||
await sleep(settle)
|
||||
return (await b.cookies().catch(() => null)) ?? c
|
||||
}
|
||||
await sleep(poll)
|
||||
}
|
||||
return null
|
||||
} finally {
|
||||
await b.close()
|
||||
}
|
||||
}
|
||||
|
||||
// renew opens the profile without a window at gemini.google.com, where
|
||||
// the page's own scripts renew __Secure-1PSIDTS, and answers the cookies
|
||||
// once it has changed (or what the profile holds after the wait).
|
||||
export async function renew(profile, { before = {}, timeout = 20_000, poll = 700, opener = open } = {}) {
|
||||
if (!profile || !existsSync(profile)) return null
|
||||
const b = await opener(profile, GEMINI, { headless: true })
|
||||
try {
|
||||
const end = Date.now() + timeout
|
||||
let last = null
|
||||
while (Date.now() < end && !b.exited) {
|
||||
const c = await b.cookies().catch(() => null)
|
||||
if (c && hasSession(c)) {
|
||||
last = c
|
||||
if (c["__Secure-1PSIDTS"] !== before["__Secure-1PSIDTS"]) return c
|
||||
}
|
||||
await sleep(poll)
|
||||
}
|
||||
return last
|
||||
} finally {
|
||||
await b.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
import { test, expect } from "bun:test"
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
import { Frames, GeminiError, MAX_PROMPT, MODELS, Session, clean, innerRequest, mergeSetCookie, modelHeader, outcome, pageTokens, parseModels, slug } from "./gemini.mjs"
|
||||
import { browserArgs, googleCookies, renew, signIn } from "./browser.mjs"
|
||||
import { _internal as I, cookiesOf } from "./index.mjs"
|
||||
import plugin from "./opencode.mjs"
|
||||
|
||||
const dir = path.join(import.meta.dir, "testdata")
|
||||
// real StreamGenerate replies, read from gemini.google.com on 2026-11-19
|
||||
// (the location Google guessed from the address is scrubbed): "pong" from
|
||||
// a signed-in account, served as 4 Hydrogen; a short text about rivers
|
||||
// from no account, served as 3.5 Flash-Lite, with the chunks as they came
|
||||
const PONG = fs.readFileSync(path.join(dir, "pong.raw"), "utf8")
|
||||
const RIVERS = fs.readFileSync(path.join(dir, "rivers.raw"), "utf8")
|
||||
const RIVER_CHUNKS = JSON.parse(fs.readFileSync(path.join(dir, "rivers.chunks.json"), "utf8")).chunks
|
||||
// the model picker's list (otAQ7b) for a free account
|
||||
const OTAQ7B = fs.readFileSync(path.join(dir, "otaq7b.raw"), "utf8")
|
||||
|
||||
// reply rewrites the text of every content frame of a real reply,
|
||||
// keeping the rest of its bytes and the length lines right
|
||||
function reply(raw, text) {
|
||||
const lines = raw.split("\n")
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (!lines[i].startsWith("[")) continue
|
||||
const rows = JSON.parse(lines[i])
|
||||
let changed = false
|
||||
for (const e of rows) {
|
||||
if (e[0] !== "wrb.fr" || typeof e[2] !== "string") continue
|
||||
const b = JSON.parse(e[2])
|
||||
if (!Array.isArray(b?.[4]?.[0]?.[1])) continue
|
||||
b[4][0][1][0] = text
|
||||
e[2] = JSON.stringify(b)
|
||||
changed = true
|
||||
}
|
||||
if (changed) {
|
||||
lines[i] = JSON.stringify(rows)
|
||||
lines[i - 1] = String(lines[i].length + 2)
|
||||
}
|
||||
}
|
||||
return lines.join("\n")
|
||||
}
|
||||
|
||||
const REFUSED = ')]}\'\n\n41\n[["wrb.fr",null,null,null,null,[3]]]\n25\n[["e",4,null,null,141]]\n'
|
||||
|
||||
const PAGE = (at = "AJvLN6Mtoken") =>
|
||||
`<html><script>WIZ_global_data = {"SNlM0e":"${at}","cfb2h":"boq_assistant-bard-web-server_20261117.06_p0","FdrFJe":"-4096","oPEP7c":"${at ? "someone@example.com" : ""}"};</script></html>`
|
||||
|
||||
const enc = new TextEncoder()
|
||||
const streamOf = (chunks) =>
|
||||
new ReadableStream({
|
||||
start(c) {
|
||||
for (const x of chunks) c.enqueue(enc.encode(x))
|
||||
c.close()
|
||||
},
|
||||
})
|
||||
|
||||
// fakeGoogle answers /app, StreamGenerate, batchexecute and RotateCookies
|
||||
// as Google does, and records what was asked
|
||||
function fakeGoogle({ page = () => PAGE(), generate = () => [PONG], status = () => 200, setCookie = [], models = OTAQ7B, rotate = 200 } = {}) {
|
||||
const calls = []
|
||||
const f = async (url, init = {}) => {
|
||||
const u = new URL(String(url))
|
||||
const body = init.body instanceof URLSearchParams ? Object.fromEntries(init.body) : init.body
|
||||
calls.push({ path: u.pathname, query: Object.fromEntries(u.searchParams), headers: init.headers ?? {}, body })
|
||||
const h = new Headers()
|
||||
for (const c of setCookie) h.append("set-cookie", c)
|
||||
if (u.pathname === "/app") return new Response(page(), { status: 200, headers: h })
|
||||
if (u.pathname === "/RotateCookies") return new Response("", { status: rotate, headers: h })
|
||||
if (u.pathname.endsWith("/batchexecute")) return new Response(models, { status: 200, headers: h })
|
||||
if (u.pathname.endsWith("/StreamGenerate")) {
|
||||
const s = status(calls)
|
||||
if (s !== 200) return new Response("nope", { status: s, headers: h })
|
||||
return new Response(streamOf(generate(calls)), { status: 200, headers: h })
|
||||
}
|
||||
return new Response("?", { status: 404 })
|
||||
}
|
||||
f.calls = calls
|
||||
f.generates = () => calls.filter((c) => c.path.endsWith("/StreamGenerate"))
|
||||
return f
|
||||
}
|
||||
|
||||
const COOKIES = { "__Secure-1PSID": "psid", "__Secure-1PSIDTS": "ts1", NID: "nid" }
|
||||
|
||||
// ---- the reply ----
|
||||
|
||||
test("Frames reads a real signed-in reply: text, model, end", () => {
|
||||
const f = new Frames()
|
||||
f.push(PONG)
|
||||
f.end()
|
||||
expect(outcome(f)).toEqual({ text: "pong", reasoning: "", model: "4 Hydrogen" })
|
||||
expect(f.done).toBe(true)
|
||||
})
|
||||
|
||||
test("Frames reads the same reply however it is cut, and only grows", () => {
|
||||
const whole = new Frames()
|
||||
whole.push(RIVERS)
|
||||
whole.end()
|
||||
expect(whole.text.length).toBe(233)
|
||||
expect(whole.text.startsWith("Rivers carve winding paths")).toBe(true)
|
||||
expect(whole.model).toBe("3.5 Flash-Lite")
|
||||
for (const size of [1, 7, 64, 1000, 4096]) {
|
||||
const f = new Frames()
|
||||
let last = ""
|
||||
for (let i = 0; i < RIVERS.length; i += size) {
|
||||
f.push(RIVERS.slice(i, i + size))
|
||||
expect(f.text.startsWith(last)).toBe(true)
|
||||
last = f.text
|
||||
}
|
||||
f.end()
|
||||
expect(f.text).toBe(whole.text)
|
||||
}
|
||||
})
|
||||
|
||||
test("Session.ask streams the real chunks as the reply grows", async () => {
|
||||
const g = fakeGoogle({ generate: () => RIVER_CHUNKS, page: () => PAGE("") })
|
||||
const s = new Session({ fetchImpl: g })
|
||||
const seen = []
|
||||
const r = await s.ask("Write two sentences about rivers.", { onUpdate: (u) => seen.push(u.text.length) })
|
||||
expect(seen).toEqual([83, 226, 233])
|
||||
expect(r.text.length).toBe(233)
|
||||
})
|
||||
|
||||
test("a refusal with no content says why, not 'no content'", () => {
|
||||
const f = new Frames()
|
||||
f.push(REFUSED)
|
||||
expect(() => outcome(f)).toThrow(/拒绝了这个请求(错误 3)/)
|
||||
const empty = new Frames()
|
||||
empty.push(")]}'\n")
|
||||
expect(() => outcome(empty)).toThrow(GeminiError)
|
||||
})
|
||||
|
||||
test("code-run artifacts are taken out of the text", () => {
|
||||
expect(clean("a\n```python?code_reference&code_event_index=2\nprint(1)\n```\nb")).toBe("a\nb")
|
||||
expect(clean("```python\nprint(1)\n```")).toBe("```python\nprint(1)\n```")
|
||||
})
|
||||
|
||||
// ---- the request ----
|
||||
|
||||
test("the request is a temporary chat with the prompt inline", () => {
|
||||
const r = innerRequest("hello")
|
||||
expect(r.length).toBe(99)
|
||||
expect(r[0][0]).toBe("hello")
|
||||
expect(r[45]).toBe(1)
|
||||
expect(r[59]).toMatch(/^[0-9A-F-]{36}$/)
|
||||
// 4 Carbon needs the slots the app sends for it
|
||||
const c = innerRequest("x", { hex: "95a4c0abcba24364", mode: 8 })
|
||||
expect([c[6], c[30], c[49], c[68], c[98]]).toEqual([[1], [], 40, 2, 1])
|
||||
expect(modelHeader({})).toBe(null)
|
||||
const h = JSON.parse(modelHeader(MODELS["gemini-3.1-pro"]))
|
||||
expect([h[4], h[14]]).toEqual(["9d8ca3786ebdfbea", 3])
|
||||
})
|
||||
|
||||
test("Session.ask sends the page's tokens, cookies and the picked model, and reads /app once", async () => {
|
||||
const g = fakeGoogle()
|
||||
const s = new Session({ cookies: COOKIES, fetchImpl: g })
|
||||
expect((await s.ask("ping", { model: MODELS["gemini-3.6-flash"] })).text).toBe("pong")
|
||||
await s.ask("ping again")
|
||||
expect(g.calls.filter((c) => c.path === "/app").length).toBe(1)
|
||||
const [first, second] = g.generates()
|
||||
expect(first.body.at).toBe("AJvLN6Mtoken")
|
||||
expect(JSON.parse(JSON.parse(first.body["f.req"])[1])[0][0]).toBe("ping")
|
||||
expect(first.query).toMatchObject({ bl: "boq_assistant-bard-web-server_20261117.06_p0", "f.sid": "-4096", rt: "c" })
|
||||
expect(first.headers.cookie).toBe("__Secure-1PSID=psid; __Secure-1PSIDTS=ts1; NID=nid")
|
||||
expect(first.headers["x-same-domain"]).toBe("1")
|
||||
expect(JSON.parse(first.headers["x-goog-ext-525001261-jspb"])[4]).toBe("fbb127bbb056c959")
|
||||
expect(second.headers["x-goog-ext-525001261-jspb"]).toBeUndefined()
|
||||
})
|
||||
|
||||
test("no account sends no at and no cookie", async () => {
|
||||
const g = fakeGoogle({ page: () => PAGE("") })
|
||||
await new Session({ fetchImpl: g }).ask("ping")
|
||||
const [r] = g.generates()
|
||||
expect(r.body.at).toBeUndefined()
|
||||
expect(r.headers.cookie).toBeUndefined()
|
||||
})
|
||||
|
||||
test("a 400 reads the page again and tries once more", async () => {
|
||||
const g = fakeGoogle({ status: (calls) => (calls.filter((c) => c.path.endsWith("/StreamGenerate")).length === 1 ? 400 : 200) })
|
||||
const s = new Session({ cookies: COOKIES, fetchImpl: g })
|
||||
expect((await s.ask("ping")).text).toBe("pong")
|
||||
expect(g.calls.filter((c) => c.path === "/app").length).toBe(2)
|
||||
const always = fakeGoogle({ status: () => 429 })
|
||||
await expect(new Session({ fetchImpl: always }).ask("ping")).rejects.toMatchObject({ code: "rate_limited", status: 429 })
|
||||
})
|
||||
|
||||
test("a prompt past what the app reads is refused before it is sent", async () => {
|
||||
const g = fakeGoogle()
|
||||
await expect(new Session({ fetchImpl: g }).ask("x".repeat(MAX_PROMPT + 1))).rejects.toMatchObject({ status: 413, code: "context_length_exceeded" })
|
||||
expect(g.calls.length).toBe(0)
|
||||
})
|
||||
|
||||
// ---- the sign-in ----
|
||||
|
||||
test("pageTokens reads SNlM0e, cfb2h, FdrFJe and the account's email", () => {
|
||||
expect(pageTokens(PAGE())).toEqual({ at: "AJvLN6Mtoken", bl: "boq_assistant-bard-web-server_20261117.06_p0", sid: "-4096", email: "someone@example.com" })
|
||||
expect(pageTokens("<html></html>").at).toBe("")
|
||||
})
|
||||
|
||||
test("mergeSetCookie keeps google.com's renewed cookies and drops others and deletions", () => {
|
||||
const c = { ...COOKIES }
|
||||
expect(mergeSetCookie(c, ["__Secure-1PSIDTS=ts2; Domain=.google.com; Path=/; Secure; HttpOnly", "x=1; Domain=.youtube.com", "NID=EXPIRED; Domain=.google.com; Max-Age=0"])).toBe(true)
|
||||
expect(c).toEqual({ ...COOKIES, "__Secure-1PSIDTS": "ts2" })
|
||||
expect(mergeSetCookie(c, ["__Secure-1PSIDTS=ts2; Domain=.google.com"])).toBe(false)
|
||||
})
|
||||
|
||||
test("cookies Google renews on a reply are saved", async () => {
|
||||
const saved = []
|
||||
const g = fakeGoogle({ setCookie: ["__Secure-1PSIDTS=ts9; Domain=.google.com; Path=/"] })
|
||||
const s = new Session({ cookies: COOKIES, fetchImpl: g, onCookies: (c) => saved.push(c) })
|
||||
await s.ask("ping")
|
||||
expect(saved.length).toBe(1)
|
||||
expect(saved[0]["__Secure-1PSIDTS"]).toBe("ts9")
|
||||
})
|
||||
|
||||
test("signed out: the cookies are rotated, then the profile renews them, then it asks for a sign-in", async () => {
|
||||
let pages = 0
|
||||
// the page is signed out until the profile gives fresh cookies
|
||||
const g = fakeGoogle({ page: () => (pages++, g.calls.at(-1).headers.cookie?.includes("ts-fresh") ? PAGE() : PAGE("")), rotate: 401 })
|
||||
let renewed = 0
|
||||
const s = new Session({ cookies: COOKIES, fetchImpl: g, renew: async () => (renewed++, { "__Secure-1PSIDTS": "ts-fresh" }) })
|
||||
expect((await s.ask("ping")).text).toBe("pong")
|
||||
expect(renewed).toBe(1)
|
||||
expect(g.calls.some((c) => c.path === "/RotateCookies")).toBe(true)
|
||||
expect(g.generates()[0].body.at).toBe("AJvLN6Mtoken")
|
||||
|
||||
const dead = fakeGoogle({ page: () => PAGE(""), rotate: 401 })
|
||||
await expect(new Session({ cookies: COOKIES, fetchImpl: dead, renew: async () => null }).ask("ping")).rejects.toMatchObject({ signIn: true, status: 401 })
|
||||
})
|
||||
|
||||
test("RotateCookies is sent only the session pair", async () => {
|
||||
const g = fakeGoogle({ setCookie: ["__Secure-1PSIDTS=ts3; Domain=.google.com"] })
|
||||
const s = new Session({ cookies: COOKIES, fetchImpl: g })
|
||||
expect(await s.rotate()).toBe(true)
|
||||
const r = g.calls.find((c) => c.path === "/RotateCookies")
|
||||
expect(r.headers.cookie).toBe("__Secure-1PSID=psid; __Secure-1PSIDTS=ts1")
|
||||
expect(r.body).toBe('[000,"-0000000000000000000"]')
|
||||
expect(s.cookies["__Secure-1PSIDTS"]).toBe("ts3")
|
||||
})
|
||||
|
||||
test("googleCookies keeps google.com and gemini.google.com cookies at /", () => {
|
||||
expect(
|
||||
googleCookies([
|
||||
{ name: "__Secure-1PSID", value: "a", domain: ".google.com", path: "/" },
|
||||
{ name: "S", value: "b", domain: "gemini.google.com", path: "/" },
|
||||
{ name: "LSID", value: "c", domain: "accounts.google.com", path: "/" },
|
||||
{ name: "x", value: "d", domain: ".youtube.com", path: "/" },
|
||||
{ name: "y", value: "e", domain: ".google.com", path: "/u/0" },
|
||||
]),
|
||||
).toEqual({ "__Secure-1PSID": "a", S: "b" })
|
||||
})
|
||||
|
||||
test("browserArgs: a private profile, DevTools on loopback, headless for a renewal", () => {
|
||||
const a = browserArgs("/p", 9000, "https://x")
|
||||
expect(a).toContain("--user-data-dir=/p")
|
||||
expect(a).toContain("--remote-debugging-address=127.0.0.1")
|
||||
expect(a).toContain("--new-window")
|
||||
expect(browserArgs("/p", 9000, "https://x", { headless: true })).toContain("--headless=new")
|
||||
})
|
||||
|
||||
const fakeBrowser = (reads) => {
|
||||
let closed = 0
|
||||
const opener = async () => {
|
||||
let i = 0
|
||||
return { exited: false, cookies: async () => reads[Math.min(i++, reads.length - 1)], close: async () => void closed++ }
|
||||
}
|
||||
opener.closed = () => closed
|
||||
return opener
|
||||
}
|
||||
|
||||
test("signIn waits for the session cookies and closes the window; it gives up at the timeout", async () => {
|
||||
const o = fakeBrowser([{}, { NID: "n" }, { ...COOKIES }])
|
||||
expect(await signIn("/p", { opener: o, poll: 1, settle: 1, timeout: 10_000 })).toEqual(COOKIES)
|
||||
expect(o.closed()).toBe(1)
|
||||
const never = fakeBrowser([{}])
|
||||
expect(await signIn("/p", { opener: never, poll: 1, timeout: 20 })).toBe(null)
|
||||
expect(never.closed()).toBe(1)
|
||||
})
|
||||
|
||||
test("renew answers once the profile's 1PSIDTS changed", async () => {
|
||||
const o = fakeBrowser([{ ...COOKIES }, { ...COOKIES, "__Secure-1PSIDTS": "ts2" }])
|
||||
expect((await renew(import.meta.dir, { before: COOKIES, opener: o, poll: 1 }))["__Secure-1PSIDTS"]).toBe("ts2")
|
||||
expect(await renew(path.join(dir, "no-such-profile"), { opener: o })).toBe(null)
|
||||
})
|
||||
|
||||
// ---- models ----
|
||||
|
||||
test("parseModels reads the picker's list", () => {
|
||||
expect(parseModels(OTAQ7B)).toEqual({ "gemini-auto": { name: "Auto", hex: "cf41b0e0dd7d53e5", mode: 6 } })
|
||||
expect(slug("3.1 Pro")).toBe("gemini-3.1-pro")
|
||||
expect(slug("Gemini 3.6 Flash")).toBe("gemini-3.6-flash")
|
||||
})
|
||||
|
||||
// ---- the plugin ----
|
||||
|
||||
const SIGNED_IN = { type: "oauth", access: JSON.stringify({ cookies: COOKIES }), refresh: "/profile", expires: 0, accountId: "someone@example.com" }
|
||||
const VISITOR = { type: "oauth", access: "anonymous", refresh: "", expires: 0, accountId: "anonymous" }
|
||||
|
||||
async function load(g, auth, extra = {}) {
|
||||
const p = I.createPlugin({ fetchImpl: g, newId: () => "call_1", ...extra })
|
||||
const l = await p.auth.loader(async () => auth)
|
||||
const ask = (body) => l.fetch(I.BASE + "/chat/completions", { method: "POST", body: JSON.stringify(body) })
|
||||
return { p, l, ask }
|
||||
}
|
||||
|
||||
test("the plugin streams a chat completion", async () => {
|
||||
const { ask } = await load(fakeGoogle(), SIGNED_IN)
|
||||
const res = await ask({ model: "gemini-3.6-flash", stream: true, messages: [{ role: "user", content: "ping" }] })
|
||||
expect(res.headers.get("content-type")).toBe("text/event-stream")
|
||||
const text = await res.text()
|
||||
const deltas = text
|
||||
.split("\n\n")
|
||||
.filter((l) => l.startsWith("data: {"))
|
||||
.map((l) => JSON.parse(l.slice(6)))
|
||||
expect(deltas.map((d) => d.choices[0]?.delta?.content ?? "").join("")).toBe("pong")
|
||||
expect(deltas.some((d) => d.choices[0]?.finish_reason === "stop")).toBe(true)
|
||||
expect(text.trimEnd().endsWith("data: [DONE]")).toBe(true)
|
||||
})
|
||||
|
||||
test("the plugin gives tool calls back as tool_calls", async () => {
|
||||
const g = fakeGoogle({ generate: () => [reply(PONG, 'Reading it.\n<tool_call>{"name":"Read","arguments":{"path":"a.go"}}</tool_call>')] })
|
||||
const { ask } = await load(g, SIGNED_IN)
|
||||
const res = await ask({
|
||||
model: "gemini-auto",
|
||||
messages: [{ role: "user", content: "read a.go" }],
|
||||
tools: [{ type: "function", function: { name: "Read", parameters: { type: "object" } } }],
|
||||
})
|
||||
const j = await res.json()
|
||||
expect(j.choices[0].finish_reason).toBe("tool_calls")
|
||||
expect(j.choices[0].message.tool_calls[0].function).toEqual({ name: "Read", arguments: '{"path":"a.go"}' })
|
||||
expect(JSON.parse(JSON.parse(g.generates()[0].body["f.req"])[1])[0][0]).toContain("## Read")
|
||||
})
|
||||
|
||||
test("a visitor gets the visitor's model and no picker header", async () => {
|
||||
const g = fakeGoogle({ page: () => PAGE("") })
|
||||
const { ask, p } = await load(g, VISITOR)
|
||||
expect((await ask({ model: "gemini-3.1-pro", messages: [{ role: "user", content: "x" }] })).status).toBe(404)
|
||||
const res = await ask({ model: "gemini-auto", messages: [{ role: "user", content: "ping" }] })
|
||||
expect((await res.json()).choices[0].message.content).toBe("pong")
|
||||
expect(g.generates()[0].headers["x-goog-ext-525001261-jspb"]).toBeUndefined()
|
||||
expect(Object.keys(await p.provider.models({}, { auth: VISITOR }))).toEqual(["gemini-auto"])
|
||||
})
|
||||
|
||||
test("a refusal goes back as an HTTP error, not a 200 stream", async () => {
|
||||
const { ask } = await load(fakeGoogle({ generate: () => [REFUSED] }), SIGNED_IN)
|
||||
const res = await ask({ model: "gemini-auto", stream: true, messages: [{ role: "user", content: "ping" }] })
|
||||
expect(res.status).toBe(502)
|
||||
expect((await res.json()).error.type).toBe("gemini_refused")
|
||||
})
|
||||
|
||||
test("models: the account's picker list, or the built-in list marked as a fallback", async () => {
|
||||
const { p } = await load(fakeGoogle(), SIGNED_IN)
|
||||
const read = await p.provider.models({}, { auth: SIGNED_IN })
|
||||
expect(Object.keys(read)).toEqual(["gemini-auto"])
|
||||
expect(read[Symbol.for("magpie.fellBack")]).toBeUndefined()
|
||||
const broken = fakeGoogle({ models: "<html>500</html>" })
|
||||
const { p: p2 } = await load(broken, SIGNED_IN)
|
||||
const fell = await p2.provider.models({}, { auth: SIGNED_IN })
|
||||
expect(Object.keys(fell)).toEqual(Object.keys(MODELS))
|
||||
expect(fell[Symbol.for("magpie.fellBack")]).toBe(true)
|
||||
})
|
||||
|
||||
test("renewed cookies are written back to the account", async () => {
|
||||
const sets = []
|
||||
const client = { auth: { set: async (x) => void sets.push(x) } }
|
||||
const g = fakeGoogle({ setCookie: ["__Secure-1PSIDTS=ts7; Domain=.google.com; Path=/"] })
|
||||
const { ask } = await load(g, SIGNED_IN, { client })
|
||||
await ask({ model: "gemini-auto", messages: [{ role: "user", content: "ping" }] })
|
||||
expect(sets.length).toBeGreaterThan(0)
|
||||
const last = sets.at(-1)
|
||||
expect(last.path).toEqual({ id: "gemini-web" })
|
||||
expect(last.body).toMatchObject({ type: "oauth", refresh: "/profile", accountId: "someone@example.com" })
|
||||
expect(cookiesOf(last.body)["__Secure-1PSIDTS"]).toBe("ts7")
|
||||
})
|
||||
|
||||
test("the sign-in method signs in through the browser and names the account by its email", async () => {
|
||||
const g = fakeGoogle()
|
||||
const browser = { profileRoot: () => "/root", signIn: async () => ({ ...COOKIES }), renew: async () => null }
|
||||
const p = I.createPlugin({ fetchImpl: g, browser })
|
||||
const [google, visitor] = p.auth.methods
|
||||
const ok = await (await google.authorize()).callback()
|
||||
expect(ok).toMatchObject({ type: "success", accountId: "someone@example.com" })
|
||||
expect(ok.refresh.startsWith("/root/")).toBe(true)
|
||||
expect(cookiesOf(ok)).toEqual(COOKIES)
|
||||
const none = I.createPlugin({ fetchImpl: g, browser: { ...browser, signIn: async () => null } })
|
||||
expect((await (await none.auth.methods[0].authorize()).callback()).type).toBe("failed")
|
||||
const out = I.createPlugin({ fetchImpl: fakeGoogle({ page: () => PAGE("") }), browser })
|
||||
expect(await (await out.auth.methods[0].authorize()).callback()).toMatchObject({ type: "failed" })
|
||||
expect(await (await visitor.authorize()).callback()).toMatchObject({ type: "success", access: "anonymous" })
|
||||
})
|
||||
|
||||
test("the package's default export is the plugin", async () => {
|
||||
const p = await plugin({ client: {} })
|
||||
expect(p.auth.provider).toBe("gemini-web")
|
||||
const cfg = {}
|
||||
await p.config(cfg)
|
||||
expect(cfg.provider["gemini-web"].api).toBe(I.BASE)
|
||||
})
|
||||
@@ -0,0 +1,444 @@
|
||||
// The Gemini web app's own endpoints, called the way gemini.google.com
|
||||
// calls them: GET /app for the page's tokens, then one POST to
|
||||
// StreamGenerate per request, read as it streams. No other process sits in
|
||||
// between, and no file is uploaded: the whole prompt goes inline.
|
||||
|
||||
export const APP = "https://gemini.google.com"
|
||||
const GENERATE = APP + "/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate"
|
||||
const BATCH = APP + "/_/BardChatUi/data/batchexecute"
|
||||
const ROTATE = "https://accounts.google.com/RotateCookies"
|
||||
|
||||
// what Chrome sends; Google answers a bare client with the same page, but
|
||||
// the request should look like the browser the cookies came from
|
||||
const CHROME = "146.0.0.0"
|
||||
export function userAgent(platform = process.platform) {
|
||||
const os =
|
||||
platform === "darwin" ? "Macintosh; Intel Mac OS X 10_15_7" : platform === "win32" ? "Windows NT 10.0; Win64; x64" : "X11; Linux x86_64"
|
||||
return `Mozilla/5.0 (${os}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${CHROME} Safari/537.36`
|
||||
}
|
||||
|
||||
// The prompt is sent inline. Measured on 2026-11-19: 315K characters were
|
||||
// answered in full, 900K came back but the reply ignored the request, and
|
||||
// 1.8M was refused with error [3]. Past this the plugin says so itself.
|
||||
export const MAX_PROMPT = 600_000
|
||||
|
||||
export class GeminiError extends Error {
|
||||
constructor(message, { code = "gemini_error", status = 502, signIn = false } = {}) {
|
||||
super(message)
|
||||
this.name = "GeminiError"
|
||||
this.code = code
|
||||
this.status = status
|
||||
this.signIn = signIn
|
||||
}
|
||||
}
|
||||
|
||||
// The models Gemini's picker can name. hex is the id the picker sends in
|
||||
// the x-goog-ext-525001261-jspb header, mode the slot beside it. auto
|
||||
// sends no header: Google picks, as the app does for a new chat. The
|
||||
// list an account really has comes from otAQ7b (parseModels); this is
|
||||
// what's offered before it has been read.
|
||||
export const MODELS = {
|
||||
"gemini-auto": { name: "Auto", hex: "" },
|
||||
"gemini-3.6-flash": { name: "3.6 Flash", hex: "fbb127bbb056c959", mode: 1 },
|
||||
"gemini-3.1-pro": { name: "3.1 Pro", hex: "9d8ca3786ebdfbea", mode: 3 },
|
||||
}
|
||||
|
||||
// 4 Carbon (a paid plan's) is refused unless the request carries these
|
||||
// slots too, as the app sends them for it
|
||||
const CARBON = "95a4c0abcba24364"
|
||||
const CARBON_SLOTS = { 6: [1], 30: [], 49: 40, 68: 2, 83: 1, 91: 1, 96: 1, 98: 1 }
|
||||
|
||||
export const slug = (name) =>
|
||||
"gemini-" +
|
||||
String(name)
|
||||
.toLowerCase()
|
||||
.replace(/^gemini\s*/, "")
|
||||
.replace(/[^a-z0-9.]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
|
||||
const uuid = () => crypto.randomUUID().toUpperCase()
|
||||
|
||||
// innerRequest is the StreamGenerate request as the app builds it for a
|
||||
// temporary chat (slot 45): it is not kept in the account's history.
|
||||
export function innerRequest(prompt, model = {}) {
|
||||
const inner = new Array(99).fill(null)
|
||||
inner[0] = [prompt, 0, null, null, null, null, 0]
|
||||
inner[1] = ["en"]
|
||||
inner[2] = ["", "", "", null, null, null, null, null, null, ""]
|
||||
inner[6] = [0]
|
||||
inner[7] = 1
|
||||
inner[10] = 1
|
||||
inner[11] = 0
|
||||
inner[17] = [[0]]
|
||||
inner[18] = 0
|
||||
inner[27] = 1
|
||||
inner[30] = [4]
|
||||
inner[41] = [1]
|
||||
inner[45] = 1
|
||||
inner[53] = 0
|
||||
inner[59] = uuid()
|
||||
inner[61] = []
|
||||
inner[68] = 1
|
||||
if (model.hex === CARBON) for (const [k, v] of Object.entries(CARBON_SLOTS)) inner[k] = v
|
||||
return inner
|
||||
}
|
||||
|
||||
export function modelHeader(model = {}) {
|
||||
if (!model.hex) return null
|
||||
return JSON.stringify([1, null, null, null, model.hex, null, null, 0, [4, 5, 6, 8], null, null, 1, null, null, model.mode ?? 1, 1, uuid()])
|
||||
}
|
||||
|
||||
// Replies drop code-run artifacts into the text (a fenced block naming
|
||||
// code_reference or code_stdout); they are not what the model wrote.
|
||||
const ARTIFACT = /```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n[\s\S]*?```\n?/g
|
||||
export const clean = (t) => t.replace(ARTIFACT, "")
|
||||
|
||||
// Frames reads StreamGenerate's reply as it arrives: `)]}'`, then lines of
|
||||
// a length and a JSON array of ["wrb.fr", null, "<json>"] entries. Every
|
||||
// content entry carries the reply so far, not what is new; the longest is
|
||||
// kept. An entry with no payload and a code in slot 5 is a refusal.
|
||||
export class Frames {
|
||||
constructor() {
|
||||
this.buf = ""
|
||||
this.text = ""
|
||||
this.reasoning = ""
|
||||
this.model = ""
|
||||
this.frames = 0
|
||||
this.content = false
|
||||
this.refusal = null
|
||||
this.done = false
|
||||
}
|
||||
|
||||
push(chunk) {
|
||||
this.buf += chunk
|
||||
let i
|
||||
let changed = false
|
||||
while ((i = this.buf.indexOf("\n")) >= 0) {
|
||||
const line = this.buf.slice(0, i)
|
||||
this.buf = this.buf.slice(i + 1)
|
||||
changed = this.line(line) || changed
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
end() {
|
||||
const changed = this.buf ? this.line(this.buf) : false
|
||||
this.buf = ""
|
||||
return changed
|
||||
}
|
||||
|
||||
line(line) {
|
||||
line = line.trim()
|
||||
if (!line.startsWith("[")) return false
|
||||
let rows
|
||||
try {
|
||||
rows = JSON.parse(line)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
let changed = false
|
||||
for (const e of Array.isArray(rows) ? rows : []) {
|
||||
if (!Array.isArray(e) || e[0] !== "wrb.fr") continue
|
||||
this.frames++
|
||||
if (typeof e[2] !== "string") {
|
||||
if (Array.isArray(e[5])) this.refusal = e[5][0] ?? "unknown"
|
||||
continue
|
||||
}
|
||||
let b
|
||||
try {
|
||||
b = JSON.parse(e[2])
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (typeof b?.[42] === "string" && b[42]) this.model = b[42]
|
||||
const r = b?.[2]
|
||||
if (r && typeof r === "object" && !Array.isArray(r) && r["46"]) this.done = true
|
||||
const c = b?.[4]?.[0]
|
||||
if (!Array.isArray(c)) continue
|
||||
const t = c[1]?.[0]
|
||||
if (typeof t === "string") {
|
||||
this.content = true
|
||||
const ct = clean(t)
|
||||
if (ct.length >= this.text.length && ct !== this.text) {
|
||||
this.text = ct
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
const th = c[37]?.[0]?.[0]
|
||||
if (typeof th === "string" && th.length > this.reasoning.length) {
|
||||
this.reasoning = th
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
}
|
||||
|
||||
// tokens reads what a request needs from the /app page: SNlM0e (the XSRF
|
||||
// token, only when signed in), cfb2h (the build) and FdrFJe (the session).
|
||||
export function pageTokens(html) {
|
||||
const g = (k) => html.match(new RegExp(`"${k}":"([^"]*)"`))?.[1] ?? ""
|
||||
return { at: g("SNlM0e"), bl: g("cfb2h"), sid: g("FdrFJe"), email: g("oPEP7c") }
|
||||
}
|
||||
|
||||
export const cookieHeader = (cookies) =>
|
||||
Object.entries(cookies ?? {})
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join("; ")
|
||||
|
||||
// mergeSetCookie takes the cookies a reply set (Google renews them on its
|
||||
// replies) into the jar, and says whether anything changed
|
||||
export function mergeSetCookie(cookies, setCookies = []) {
|
||||
let changed = false
|
||||
for (const sc of setCookies) {
|
||||
const first = String(sc).split(";")[0]
|
||||
const eq = first.indexOf("=")
|
||||
if (eq <= 0) continue
|
||||
const name = first.slice(0, eq).trim()
|
||||
const value = first.slice(eq + 1).trim()
|
||||
const attrs = String(sc).toLowerCase()
|
||||
// only what the app's requests carry: google.com's own cookies
|
||||
if (/domain=/.test(attrs) && !/domain=\.?(gemini\.)?google\.com(;|$)/.test(attrs)) continue
|
||||
if (/max-age=0|expires=thu, 01 jan 1970/.test(attrs) || value === "EXPIRED") continue
|
||||
if (cookies[name] !== value) {
|
||||
cookies[name] = value
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
const setCookiesOf = (res) => (typeof res.headers.getSetCookie === "function" ? res.headers.getSetCookie() : [])
|
||||
|
||||
const TOKENS_FOR = 15 * 60_000
|
||||
const ROTATE_AFTER = 10 * 60_000
|
||||
|
||||
// Session is one account (or no account: cookies null). It keeps the page
|
||||
// tokens for a while instead of fetching /app before every request, keeps
|
||||
// the cookies current from what Google sets, and when they stop working
|
||||
// renews them: first the way the app's own page does (RotateCookies), then
|
||||
// through renew(), which reopens the account's browser profile.
|
||||
export class Session {
|
||||
constructor({ cookies = null, fetchImpl = globalThis.fetch, renew = null, onCookies = null, now = Date.now, platform = process.platform } = {}) {
|
||||
this.cookies = cookies ? { ...cookies } : null
|
||||
this.fetch = fetchImpl
|
||||
this.renewProfile = renew
|
||||
this.onCookies = onCookies
|
||||
this.now = now
|
||||
this.ua = userAgent(platform)
|
||||
this.tok = null
|
||||
this.tokAt = 0
|
||||
this.rotatedAt = now()
|
||||
this.renewing = null
|
||||
}
|
||||
|
||||
get signedIn() {
|
||||
return !!this.cookies
|
||||
}
|
||||
|
||||
headers(extra = {}) {
|
||||
const h = { "user-agent": this.ua, "accept-language": "en-US,en;q=0.9", accept: "*/*", ...extra }
|
||||
if (this.cookies) h.cookie = cookieHeader(this.cookies)
|
||||
return h
|
||||
}
|
||||
|
||||
took(res) {
|
||||
if (this.cookies && mergeSetCookie(this.cookies, setCookiesOf(res))) this.saved()
|
||||
}
|
||||
|
||||
saved() {
|
||||
try {
|
||||
this.onCookies?.({ ...this.cookies })
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async page(signal) {
|
||||
const res = await this.fetch(APP + "/app", { headers: this.headers({ accept: "text/html" }), redirect: "manual", signal })
|
||||
this.took(res)
|
||||
if (res.status >= 300 && res.status < 400) {
|
||||
const to = res.headers.get("location") ?? ""
|
||||
if (/\/sorry\//.test(to)) throw new GeminiError("Google 把这个网络出口当成了自动流量(/sorry)。换个网络或代理再试。", { code: "gemini_blocked", status: 503 })
|
||||
return { at: "", bl: "", sid: "", email: "", moved: to }
|
||||
}
|
||||
if (!res.ok) throw new GeminiError(`gemini.google.com/app 回复 HTTP ${res.status}`, { status: 502 })
|
||||
return pageTokens(await res.text())
|
||||
}
|
||||
|
||||
// tokens answers the page's tokens; signed in, a page with no SNlM0e
|
||||
// means the cookies were taken as signed out, so they are renewed once
|
||||
async tokens({ signal, force = false } = {}) {
|
||||
if (!force && this.tok && this.now() - this.tokAt < TOKENS_FOR) return this.tok
|
||||
let t = await this.page(signal)
|
||||
if (this.cookies && !t.at) {
|
||||
await this.renew(signal)
|
||||
t = await this.page(signal)
|
||||
if (!t.at) throw new GeminiError("Google 账号的登录已失效,请在 magpie 里重新登录 Gemini 网页版。", { code: "gemini_signed_out", status: 401, signIn: true })
|
||||
}
|
||||
if (!t.bl) throw new GeminiError("gemini.google.com/app 的页面里没有 cfb2h,Gemini 网页版可能改版了。", { code: "gemini_page_changed" })
|
||||
this.tok = t
|
||||
this.tokAt = this.now()
|
||||
return t
|
||||
}
|
||||
|
||||
// rotate is the page's own keep-alive: a POST that renews
|
||||
// __Secure-1PSIDTS. It fails for a session Chrome bound to its device;
|
||||
// renew then takes fresh cookies from the profile itself.
|
||||
async rotate(signal) {
|
||||
if (!this.cookies?.["__Secure-1PSID"]) return false
|
||||
const pair = { "__Secure-1PSID": this.cookies["__Secure-1PSID"] }
|
||||
if (this.cookies["__Secure-1PSIDTS"]) pair["__Secure-1PSIDTS"] = this.cookies["__Secure-1PSIDTS"]
|
||||
try {
|
||||
const res = await this.fetch(ROTATE, {
|
||||
method: "POST",
|
||||
headers: { "user-agent": this.ua, "content-type": "application/json", origin: "https://accounts.google.com", cookie: cookieHeader(pair) },
|
||||
body: '[000,"-0000000000000000000"]',
|
||||
signal,
|
||||
})
|
||||
if (!res.ok) return false
|
||||
this.rotatedAt = this.now()
|
||||
this.took(res)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async renew(signal) {
|
||||
if (this.renewing) return this.renewing
|
||||
this.renewing = (async () => {
|
||||
if (await this.rotate(signal)) {
|
||||
const t = await this.page(signal).catch(() => null)
|
||||
if (t?.at) return
|
||||
}
|
||||
if (!this.renewProfile) return
|
||||
const fresh = await this.renewProfile()
|
||||
if (fresh && typeof fresh === "object") {
|
||||
this.cookies = { ...this.cookies, ...fresh }
|
||||
this.rotatedAt = this.now()
|
||||
this.saved()
|
||||
}
|
||||
})().finally(() => (this.renewing = null))
|
||||
return this.renewing
|
||||
}
|
||||
|
||||
// keepAlive renews the short-lived cookie in the background once it is
|
||||
// ten minutes old, as the app's page does while it is open
|
||||
keepAlive() {
|
||||
if (this.cookies && !this.renewing && this.now() - this.rotatedAt > ROTATE_AFTER) {
|
||||
this.rotatedAt = this.now()
|
||||
this.rotate().catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
// ask sends prompt and calls onUpdate({text, reasoning}) as the reply
|
||||
// grows. It answers the whole reply once Gemini ends it.
|
||||
async ask(prompt, { model = {}, signal, onUpdate } = {}) {
|
||||
if (prompt.length > MAX_PROMPT)
|
||||
throw new GeminiError(
|
||||
`请求有 ${prompt.length} 个字符,超过 Gemini 网页版能可靠读完的 ${MAX_PROMPT}。请压缩上下文(如 /compact)后再试。`,
|
||||
{ code: "context_length_exceeded", status: 413 },
|
||||
)
|
||||
this.keepAlive()
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const t = await this.tokens({ signal, force: attempt > 0 })
|
||||
const res = await this.post(prompt, model, t, signal)
|
||||
if (res.ok) return await this.read(res, onUpdate)
|
||||
const body = await res.text().catch(() => "")
|
||||
// a stale XSRF token or session: fetch the page again, once
|
||||
if (attempt === 0 && (res.status === 400 || res.status === 401 || res.status === 403)) {
|
||||
if (this.cookies && res.status !== 400) await this.renew(signal)
|
||||
continue
|
||||
}
|
||||
if (res.status === 429)
|
||||
throw new GeminiError("Gemini 网页版说请求太多(HTTP 429),过一会儿再试。", { code: "rate_limited", status: 429 })
|
||||
throw new GeminiError(`StreamGenerate 回复 HTTP ${res.status}:${body.slice(0, 200)}`, { status: 502 })
|
||||
}
|
||||
}
|
||||
|
||||
post(prompt, model, t, signal) {
|
||||
const q = new URLSearchParams({ bl: t.bl, "f.sid": t.sid, hl: "en", _reqid: String(10000 + Math.floor(Math.random() * 90000)), rt: "c" })
|
||||
const form = { "f.req": JSON.stringify([null, JSON.stringify(innerRequest(prompt, model))]) }
|
||||
if (t.at) form.at = t.at
|
||||
const h = this.headers({
|
||||
"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
|
||||
"x-same-domain": "1",
|
||||
origin: APP,
|
||||
referer: APP + "/",
|
||||
"x-goog-ext-525005358-jspb": JSON.stringify([uuid(), 1]),
|
||||
})
|
||||
const mh = modelHeader(model)
|
||||
if (mh) h["x-goog-ext-525001261-jspb"] = mh
|
||||
return this.fetch(GENERATE + "?" + q, { method: "POST", headers: h, body: new URLSearchParams(form), signal })
|
||||
}
|
||||
|
||||
async read(res, onUpdate) {
|
||||
this.took(res)
|
||||
const f = new Frames()
|
||||
const dec = new TextDecoder()
|
||||
const update = () => onUpdate?.({ text: f.text, reasoning: f.reasoning })
|
||||
for await (const chunk of res.body) if (f.push(dec.decode(chunk, { stream: true }))) update()
|
||||
const tail = f.push(dec.decode())
|
||||
if (f.end() || tail) update()
|
||||
return outcome(f)
|
||||
}
|
||||
|
||||
// models lists what the account's model picker shows (otAQ7b)
|
||||
async models({ signal } = {}) {
|
||||
const t = await this.tokens({ signal })
|
||||
const form = { "f.req": JSON.stringify([[["otAQ7b", "[]", null, "generic"]]]) }
|
||||
if (t.at) form.at = t.at
|
||||
const q = new URLSearchParams({ rpcids: "otAQ7b", "source-path": "/app", bl: t.bl, "f.sid": t.sid, hl: "en", _reqid: String(10000 + Math.floor(Math.random() * 90000)), rt: "c" })
|
||||
const res = await this.fetch(BATCH + "?" + q, {
|
||||
method: "POST",
|
||||
headers: this.headers({ "content-type": "application/x-www-form-urlencoded;charset=UTF-8", "x-same-domain": "1", origin: APP, referer: APP + "/" }),
|
||||
body: new URLSearchParams(form),
|
||||
signal,
|
||||
})
|
||||
if (!res.ok) throw new GeminiError(`otAQ7b 回复 HTTP ${res.status}`)
|
||||
return parseModels(await res.text())
|
||||
}
|
||||
}
|
||||
|
||||
// outcome is what a finished reply says: its text, or why there is none
|
||||
export function outcome(f) {
|
||||
if (!f.content) {
|
||||
if (f.refusal != null)
|
||||
throw new GeminiError(
|
||||
`Gemini 网页版拒绝了这个请求(错误 ${JSON.stringify(f.refusal)})。常见原因:上下文太长、账号的套餐没有所选模型,或请求太频繁。`,
|
||||
{ code: "gemini_refused", status: 502 },
|
||||
)
|
||||
throw new GeminiError(`Gemini 网页版的回复里没有内容(${f.frames} 帧)。`, { code: "no_content" })
|
||||
}
|
||||
return { text: f.text, reasoning: f.reasoning, model: f.model }
|
||||
}
|
||||
|
||||
// parseModels reads otAQ7b's reply: slot 15 of its payload lists the
|
||||
// picker's entries as [hex, name, description, …, mode at 17].
|
||||
export function parseModels(raw) {
|
||||
const out = {}
|
||||
for (const line of raw.split("\n")) {
|
||||
if (!line.startsWith("[")) continue
|
||||
let rows
|
||||
try {
|
||||
rows = JSON.parse(line)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const e of rows) {
|
||||
if (!Array.isArray(e) || e[0] !== "wrb.fr" || e[1] !== "otAQ7b" || typeof e[2] !== "string") continue
|
||||
let b
|
||||
try {
|
||||
b = JSON.parse(e[2])
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const m of Array.isArray(b?.[15]) ? b[15] : []) {
|
||||
const [hex, name] = m ?? []
|
||||
if (typeof hex !== "string" || !/^[0-9a-f]{16}$/.test(hex) || typeof name !== "string" || !name) continue
|
||||
const mode = Number.isInteger(m[17]) ? m[17] : 1
|
||||
out[slug(name)] = { name, hex, mode }
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
// The Gemini web app (gemini.google.com) as a model provider. Each request
|
||||
// is one POST to the app's own StreamGenerate endpoint, read as it
|
||||
// streams: no local server, no browser per request, no file upload. A
|
||||
// Google account is signed in through a browser window of the plugin's
|
||||
// own; without one the app still answers, with the model Google gives
|
||||
// visitors. The client's tools are asked for as <tool_call> text blocks
|
||||
// and given back as OpenAI tool_calls. See README.md.
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { join } from "node:path"
|
||||
import { renew, profileRoot, signIn } from "./browser.mjs"
|
||||
import { GeminiError, MODELS, Session } from "./gemini.mjs"
|
||||
import { completion, sse } from "./openai.mjs"
|
||||
import { flatten } from "./prompt.mjs"
|
||||
|
||||
const ID = "gemini-web"
|
||||
const BASE = "https://gemini-web.invalid/v1"
|
||||
const ANONYMOUS = "anonymous"
|
||||
const VISITOR = { "gemini-auto": MODELS["gemini-auto"] }
|
||||
|
||||
const json = (status, message, type) =>
|
||||
new Response(JSON.stringify({ error: { message, type } }), { status, headers: { "Content-Type": "application/json" } })
|
||||
|
||||
// models are offered as text-only, or magpie would ask models.dev about
|
||||
// Google's API models of similar ids
|
||||
function models(table) {
|
||||
const out = {}
|
||||
for (const [id, m] of Object.entries(table))
|
||||
out[id] = {
|
||||
name: m.name,
|
||||
limit: { context: 128000, output: 32768 },
|
||||
tool_call: true,
|
||||
reasoning: false,
|
||||
attachment: false,
|
||||
modalities: { input: ["text"], output: ["text"] },
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// cookiesOf reads an account's stored sign-in; anonymous has none
|
||||
export function cookiesOf(auth) {
|
||||
if (!auth?.access || auth.access === ANONYMOUS) return null
|
||||
try {
|
||||
const v = JSON.parse(auth.access)
|
||||
return v?.cookies && typeof v.cookies === "object" ? v.cookies : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function createPlugin({ client, fetchImpl = globalThis.fetch, newId, browser = { signIn, renew, profileRoot } } = {}) {
|
||||
// one Session per account, kept across requests so the page's tokens
|
||||
// and the account's model list are read once, not per request
|
||||
const sessions = new Map()
|
||||
const tables = new Map()
|
||||
|
||||
const sessionFor = (auth) => {
|
||||
const key = auth?.accountId || (cookiesOf(auth) ? auth.refresh : ANONYMOUS) || ANONYMOUS
|
||||
const cookies = cookiesOf(auth)
|
||||
let s = sessions.get(key)
|
||||
// a new sign-in of the same account replaces the one in memory
|
||||
if (s && s.storedAccess !== auth?.access && s.writtenAccess !== auth?.access) s = null
|
||||
if (!s) {
|
||||
s = new Session({
|
||||
cookies,
|
||||
fetchImpl,
|
||||
renew: cookies && auth?.refresh ? () => browser.renew(auth.refresh, { before: s.cookies ?? {} }) : null,
|
||||
onCookies: (c) => {
|
||||
const access = JSON.stringify({ cookies: c })
|
||||
s.writtenAccess = access
|
||||
client?.auth
|
||||
?.set?.({ path: { id: ID }, body: { type: "oauth", access, refresh: auth?.refresh ?? "", expires: 0, accountId: auth?.accountId } })
|
||||
?.catch?.(() => {})
|
||||
},
|
||||
})
|
||||
s.storedAccess = auth?.access
|
||||
sessions.set(key, s)
|
||||
}
|
||||
return { key, s }
|
||||
}
|
||||
|
||||
const tableFor = (key, s) => (s.signedIn ? tables.get(key) ?? MODELS : VISITOR)
|
||||
|
||||
const listFor = async (auth) => {
|
||||
const { key, s } = sessionFor(auth)
|
||||
if (!s.signedIn) return { table: VISITOR, read: true }
|
||||
try {
|
||||
const read = await s.models({ signal: AbortSignal.timeout(20000) })
|
||||
if (Object.keys(read).length) {
|
||||
tables.set(key, read)
|
||||
return { table: read, read: true }
|
||||
}
|
||||
} catch {}
|
||||
return { table: tables.get(key) ?? MODELS, read: tables.has(key) }
|
||||
}
|
||||
|
||||
const failed = (e) => {
|
||||
if (e?.name === "AbortError" || e?.name === "TimeoutError") throw e
|
||||
if (e?.signIn) throw Object.assign(new Error(e.message), { signIn: "expired" })
|
||||
return json(e?.status ?? 502, String(e?.message ?? e), e?.code ?? "gemini_error")
|
||||
}
|
||||
|
||||
return {
|
||||
config: async (cfg) => {
|
||||
cfg.provider ??= {}
|
||||
cfg.provider[ID] ??= { name: "Gemini 网页版", npm: "@ai-sdk/openai-compatible", api: BASE }
|
||||
cfg.provider[ID].models = { ...models(MODELS), ...(cfg.provider[ID].models ?? {}) }
|
||||
},
|
||||
// each account is offered what its own model picker shows
|
||||
provider: {
|
||||
id: ID,
|
||||
async models(_given, { auth } = {}) {
|
||||
const { table, read } = await listFor(auth)
|
||||
const out = models(table)
|
||||
if (!read) out[Symbol.for("magpie.fellBack")] = true
|
||||
return out
|
||||
},
|
||||
},
|
||||
auth: {
|
||||
provider: ID,
|
||||
maxConcurrency: 2,
|
||||
methods: [
|
||||
{
|
||||
type: "oauth",
|
||||
label: "在单独的浏览器窗口登录 Google 账号",
|
||||
authorize: async () => ({
|
||||
url: "",
|
||||
method: "auto",
|
||||
instructions: "将打开一个单独的 Chrome 窗口(独立的配置,不影响你平时的浏览器)。请在其中登录 Google 账号,打开 Gemini 后窗口会自动关闭。",
|
||||
callback: async () => {
|
||||
const profile = join(browser.profileRoot(), randomBytes(6).toString("hex"))
|
||||
let cookies
|
||||
try {
|
||||
cookies = await browser.signIn(profile)
|
||||
} catch (e) {
|
||||
return { type: "failed", error: "打开浏览器失败:" + String(e?.message ?? e) }
|
||||
}
|
||||
if (!cookies) return { type: "failed", error: "五分钟内没有在窗口里登录 Google 账号,请再试一次。" }
|
||||
let t
|
||||
try {
|
||||
t = await new Session({ cookies, fetchImpl }).tokens({ signal: AbortSignal.timeout(20000) })
|
||||
} catch (e) {
|
||||
return { type: "failed", error: "登录后打开 Gemini 失败:" + String(e?.message ?? e) }
|
||||
}
|
||||
if (!t?.at) return { type: "failed", error: "Gemini 没有把这个窗口当成已登录,请再试一次。" }
|
||||
const who = t.email || "Google 账号"
|
||||
return { type: "success", access: JSON.stringify({ cookies }), refresh: profile, expires: 0, accountId: who, name: who }
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
type: "oauth",
|
||||
label: "不登录使用",
|
||||
authorize: async () => ({
|
||||
url: "",
|
||||
method: "auto",
|
||||
instructions: "不登录时,Gemini 网页版只给访客的模型(目前是 3.5 Flash-Lite)。",
|
||||
callback: async () => ({ type: "success", access: ANONYMOUS, refresh: "", expires: 0, accountId: ANONYMOUS, name: "访客(未登录)" }),
|
||||
}),
|
||||
},
|
||||
],
|
||||
loader: async (getAuth) => ({
|
||||
baseURL: BASE,
|
||||
apiKey: "gemini-web",
|
||||
async fetch(input, init = {}) {
|
||||
const request = input instanceof Request ? new Request(input, init) : null
|
||||
const url = new URL(request ? request.url : String(input))
|
||||
const method = request ? request.method : init.method ?? "GET"
|
||||
if (url.origin !== new URL(BASE).origin || !url.pathname.endsWith("/chat/completions") || method !== "POST")
|
||||
return json(404, "Gemini 网页版只提供 chat/completions。", "not_found")
|
||||
const signal = request ? request.signal : init.signal
|
||||
let body
|
||||
try {
|
||||
body = JSON.parse(request ? await request.text() : typeof init.body === "string" ? init.body : await new Response(init.body).text())
|
||||
} catch {
|
||||
return json(400, "请求不是 JSON。", "invalid_request_error")
|
||||
}
|
||||
const auth = await getAuth()
|
||||
const { key, s } = sessionFor(auth)
|
||||
const model = String(body.model ?? "gemini-auto").replace(/^gemini-web\//, "")
|
||||
let table = tableFor(key, s)
|
||||
if (!table[model] && s.signedIn && !tables.has(key)) table = (await listFor(auth)).table
|
||||
const m = table[model]
|
||||
if (!m) return json(404, `没有模型 ${model}。这个账号的 Gemini 网页版模型有:${Object.keys(table).join("、")}。`, "model_not_found")
|
||||
const prompt = flatten(body)
|
||||
const id = "chatcmpl-" + Math.random().toString(36).slice(2)
|
||||
const promptTokens = () => Math.ceil(prompt.length / 3)
|
||||
// a visitor is given what Google gives visitors: no picker header
|
||||
const pick = s.signedIn ? m : {}
|
||||
try {
|
||||
if (body.stream)
|
||||
return await sse({ id, model, signal, newId, promptTokens, ask: (onUpdate, sig) => s.ask(prompt, { model: pick, signal: sig, onUpdate }) })
|
||||
const final = await s.ask(prompt, { model: pick, signal })
|
||||
return Response.json(completion({ id, model, final, promptTokens: promptTokens(), newId }))
|
||||
} catch (e) {
|
||||
return failed(e)
|
||||
}
|
||||
},
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default async function GeminiWebProvider({ client } = {}) {
|
||||
return createPlugin({ client })
|
||||
}
|
||||
|
||||
export const _internal = { createPlugin, models, BASE, ID, GeminiError }
|
||||
@@ -0,0 +1,134 @@
|
||||
// What the plugin answers: an OpenAI chat completion, streamed as SSE or
|
||||
// whole, built from the reads of Gemini's reply.
|
||||
import { heldFrom, parse } from "./prompt.mjs"
|
||||
|
||||
const enc = new TextEncoder()
|
||||
|
||||
// Streamer turns successive reads of a growing reply into chunk deltas.
|
||||
// Text after the first <tool_call> (or a tail that may start one) is held,
|
||||
// and becomes tool_calls when the reply ends. A read that isn't the last
|
||||
// one grown (Gemini rewrote what it showed) adds nothing until it is again.
|
||||
export class Streamer {
|
||||
constructor() {
|
||||
this.text = ""
|
||||
this.shown = 0
|
||||
this.reasoning = ""
|
||||
}
|
||||
|
||||
update({ text = "", reasoning = "" }) {
|
||||
const out = {}
|
||||
if (reasoning.startsWith(this.reasoning) && reasoning.length > this.reasoning.length) {
|
||||
out.reasoning = reasoning.slice(this.reasoning.length)
|
||||
this.reasoning = reasoning
|
||||
}
|
||||
if (text.startsWith(this.text.slice(0, this.shown))) {
|
||||
this.text = text
|
||||
const upto = heldFrom(text)
|
||||
if (upto > this.shown) {
|
||||
out.content = text.slice(this.shown, upto)
|
||||
this.shown = upto
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// finish gives what is left of the text and the tool calls. What was
|
||||
// shown stopped before the first call, so the text with its calls taken
|
||||
// out still starts with it.
|
||||
finish(final, newId) {
|
||||
const p = parse(final?.text ?? this.text, newId)
|
||||
const shown = this.text.slice(0, this.shown)
|
||||
let content = p.raw.startsWith(shown) ? p.raw.slice(shown.length) : ""
|
||||
if (p.calls.length) content = content.replace(/```[a-z]*\s*```/gi, "").trim() ? content.replace(/```[a-z]*\s*```/gi, "").trimEnd() : ""
|
||||
return { content, calls: p.calls }
|
||||
}
|
||||
}
|
||||
|
||||
export function usage(promptTokens, text, reasoning = "") {
|
||||
// the web app counts nothing; the reply is estimated at one token for
|
||||
// three characters
|
||||
const completion = Math.ceil(((text ?? "").length + (reasoning ?? "").length) / 3)
|
||||
return { prompt_tokens: promptTokens, completion_tokens: completion, total_tokens: promptTokens + completion }
|
||||
}
|
||||
|
||||
const chunk = (id, model, delta, finish = null, extra = {}) =>
|
||||
enc.encode(
|
||||
"data: " +
|
||||
JSON.stringify({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra }) +
|
||||
"\n\n",
|
||||
)
|
||||
|
||||
// sse runs ask(onUpdate, signal) and streams what it reads. It resolves
|
||||
// once the reply has begun, so a failure before that (signed out, the
|
||||
// model refused, a 429) throws here and goes back as an
|
||||
// HTTP error, not as a 200 stream.
|
||||
export async function sse({ id, model, ask, signal, promptTokens = () => 0, newId }) {
|
||||
const st = new Streamer()
|
||||
const abort = new AbortController()
|
||||
const both = signal ? AbortSignal.any([signal, abort.signal]) : abort.signal
|
||||
const buf = []
|
||||
let ctl = null
|
||||
let ended = false
|
||||
let failure = null
|
||||
let begun = false
|
||||
let onFirst
|
||||
const first = new Promise((r) => (onFirst = r))
|
||||
const push = (b) => (ctl ? ctl.enqueue(b) : buf.push(b))
|
||||
const deltas = (d) => {
|
||||
if (d.reasoning) push(chunk(id, model, { reasoning_content: d.reasoning }))
|
||||
if (d.content) push(chunk(id, model, { content: d.content }))
|
||||
}
|
||||
push(chunk(id, model, { role: "assistant", content: "" }))
|
||||
;(async () => {
|
||||
try {
|
||||
const final = await ask((r) => {
|
||||
begun = true
|
||||
onFirst()
|
||||
deltas(st.update(r))
|
||||
}, both)
|
||||
begun = true
|
||||
deltas(st.update(final))
|
||||
const { content, calls } = st.finish(final, newId)
|
||||
if (content) push(chunk(id, model, { content }))
|
||||
if (calls.length) push(chunk(id, model, { tool_calls: calls.map((x, index) => ({ index, id: x.id, type: "function", function: x.function })) }))
|
||||
push(chunk(id, model, {}, calls.length ? "tool_calls" : "stop"))
|
||||
push(chunk(id, model, {}, null, { choices: [], usage: usage(promptTokens(final), final.text, final.reasoning) }))
|
||||
push(enc.encode("data: [DONE]\n\n"))
|
||||
} catch (e) {
|
||||
failure = e
|
||||
if (begun && !both.aborted) push(enc.encode("data: " + JSON.stringify({ error: { message: String(e?.message ?? e), type: e?.code ?? "gemini_error" } }) + "\n\n"))
|
||||
} finally {
|
||||
ended = true
|
||||
onFirst()
|
||||
if (ctl) try { ctl.close() } catch {}
|
||||
}
|
||||
})()
|
||||
await first
|
||||
if (failure && !begun) throw failure
|
||||
const stream = new ReadableStream({
|
||||
start(c) {
|
||||
ctl = c
|
||||
for (const b of buf.splice(0)) c.enqueue(b)
|
||||
if (ended) c.close()
|
||||
},
|
||||
cancel() {
|
||||
abort.abort()
|
||||
},
|
||||
})
|
||||
return new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
|
||||
}
|
||||
|
||||
export function completion({ id, model, final, promptTokens, newId }) {
|
||||
const { text, calls } = parse(final.text ?? "", newId)
|
||||
const message = { role: "assistant", content: text || (calls.length ? null : "") }
|
||||
if (final.reasoning) message.reasoning_content = final.reasoning
|
||||
if (calls.length) message.tool_calls = calls
|
||||
return {
|
||||
id,
|
||||
object: "chat.completion",
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model,
|
||||
choices: [{ index: 0, message, finish_reason: calls.length ? "tool_calls" : "stop" }],
|
||||
usage: usage(promptTokens, final.text, final.reasoning),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// The package's OpenCode 1.x plugins, as OpenCode 1.x and magpie's host
|
||||
// load them: its plugin functions and nothing else (1.x refuses a
|
||||
// package whose exports include anything but plugins). OpenCode 2.x
|
||||
// loads opencode2.mjs, which runs these.
|
||||
export { default } from "./index.mjs"
|
||||
@@ -0,0 +1,620 @@
|
||||
// The OpenCode 2.x face of a package whose plugins are written for
|
||||
// OpenCode 1.x (and magpie's plugin host).
|
||||
//
|
||||
// OpenCode 2.x loads a package's `exports["."]` and wants its default to be
|
||||
// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions
|
||||
// (plugins#657). This file is that default. It runs each 1.x plugin the
|
||||
// package's opencode.mjs exports and hands 2.x what the plugin's hooks say:
|
||||
//
|
||||
// auth.methods → the integration's sign-in methods
|
||||
// config() → the provider, its package, base URL and models
|
||||
// provider.models → the signed-in account's own model list
|
||||
// auth.loader → each request's base URL, key, headers and fetch
|
||||
//
|
||||
// What 2.x has no place for is left out: chat.headers and chat.params
|
||||
// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin,
|
||||
// tools and events.
|
||||
//
|
||||
// scripts/opencode2.mjs is the one copy that is edited. Every package that
|
||||
// has it carries the same bytes as packages/<name>/opencode2.mjs, and
|
||||
// scripts/check.mjs fails when a copy differs.
|
||||
|
||||
import { readFileSync } from "node:fs"
|
||||
import * as v1 from "./opencode.mjs"
|
||||
|
||||
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"))
|
||||
|
||||
// The key the SDK is made with: the account's own goes on each request in
|
||||
// its place (see wrapFetch), so a key read when the SDK was made can't go
|
||||
// out after the account changed.
|
||||
const PLACEHOLDER = "opencode2-v1-key"
|
||||
|
||||
// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from
|
||||
// swapping @ai-sdk/* for its native providers, which never call the sdk
|
||||
// hook below; openai-compatible's is the one 2.x ships, the others are AI
|
||||
// SDK v6's dist-tag, the line 2.x's bridge runs.
|
||||
export function packageOf(npm) {
|
||||
const name = npm || "@ai-sdk/openai-compatible"
|
||||
if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41"
|
||||
if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6`
|
||||
return `aisdk:${name}`
|
||||
}
|
||||
|
||||
// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read
|
||||
// them: a default {server} is the one plugin, else every function export
|
||||
// and every {server} object.
|
||||
export function pluginsOf(mod) {
|
||||
const d = mod?.default
|
||||
if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d))
|
||||
return typeof d.server === "function" ? [d.server] : []
|
||||
const out = []
|
||||
for (const value of Object.values(mod ?? {})) {
|
||||
const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null
|
||||
if (fn && !out.includes(fn)) out.push(fn)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const int = (n, fallback = 0) => {
|
||||
const v = Math.trunc(Number(n))
|
||||
return Number.isFinite(v) && v >= 0 ? v : fallback
|
||||
}
|
||||
const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0)
|
||||
const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {})
|
||||
const json = (v) => {
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(v ?? null))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string"))
|
||||
const nonEmpty = (o) => (Object.keys(o).length ? o : undefined)
|
||||
|
||||
// connKey names a connection the way 2.x does.
|
||||
const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`)
|
||||
|
||||
// ---- sign-in ------------------------------------------------------------
|
||||
|
||||
// fields is a 1.x method's prompts as a 2.x form.
|
||||
export function fieldsOf(prompts) {
|
||||
const out = []
|
||||
for (const p of prompts ?? []) {
|
||||
if (!p?.key) continue
|
||||
const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) }
|
||||
if (p.placeholder) f.placeholder = String(p.placeholder)
|
||||
if (p.type === "select" && Array.isArray(p.options))
|
||||
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
|
||||
// a prompt shown only when another answer says so can't be required, and
|
||||
// neither can one whose own validate() accepts an empty answer (the
|
||||
// browser sign-in's optional API key)
|
||||
if (!p.condition && p.required !== false) f.required = true
|
||||
out.push(f)
|
||||
}
|
||||
return out.length ? out : undefined
|
||||
}
|
||||
|
||||
// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes
|
||||
// auth.json: the result without its type and provider.
|
||||
function v1Saved(r) {
|
||||
const { type: _t, provider: _p, ...rest } = r
|
||||
if ("key" in r) return { type: "api", ...rest }
|
||||
return { type: "oauth", ...rest }
|
||||
}
|
||||
|
||||
// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for
|
||||
// both kinds, the 1.x auth kept whole in its metadata. No refresh is
|
||||
// registered, so 2.x hands the credential over as it is and the plugin's
|
||||
// own loader renews it, as it does on 1.x.
|
||||
export function credentialOf(methodID, r) {
|
||||
if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed")
|
||||
const saved = json(v1Saved(r))
|
||||
if (saved.type === "api")
|
||||
return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } }
|
||||
return {
|
||||
type: "oauth",
|
||||
methodID,
|
||||
access: String(saved.access ?? ""),
|
||||
refresh: String(saved.refresh ?? ""),
|
||||
expires: int(saved.expires),
|
||||
metadata: { v1: saved },
|
||||
}
|
||||
}
|
||||
|
||||
// authOfValue is the 1.x auth a 2.x credential stands for.
|
||||
export function authOfValue(value) {
|
||||
if (!value) return null
|
||||
if (value.type === "oauth") {
|
||||
const v1 = record(value.metadata).v1
|
||||
if (v1 && typeof v1 === "object") return v1
|
||||
return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires }
|
||||
}
|
||||
if (value.type === "key") {
|
||||
const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {}
|
||||
return { type: "api", key: value.key, ...meta }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""])
|
||||
|
||||
// ---- models -------------------------------------------------------------
|
||||
|
||||
const MODALITIES = ["text", "audio", "image", "video", "pdf"]
|
||||
|
||||
// internalOf is a config model as 1.x hands it to provider.models: what
|
||||
// fromModelsDevModel makes of it, with the config's own variants.
|
||||
export function internalOf(providerID, conf, key, m) {
|
||||
const mods = record(m.modalities)
|
||||
const has = (list, k) => Array.isArray(list) && list.includes(k)
|
||||
const cost = record(m.cost)
|
||||
return {
|
||||
...m,
|
||||
id: key,
|
||||
providerID,
|
||||
name: m.name ?? key,
|
||||
api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" },
|
||||
status: m.status ?? "active",
|
||||
headers: m.headers ?? {},
|
||||
options: m.options ?? {},
|
||||
cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } },
|
||||
limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) },
|
||||
capabilities: {
|
||||
temperature: m.temperature ?? false,
|
||||
reasoning: m.reasoning ?? false,
|
||||
attachment: m.attachment ?? false,
|
||||
toolcall: m.tool_call ?? true,
|
||||
input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])),
|
||||
output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])),
|
||||
interleaved: m.interleaved ?? false,
|
||||
},
|
||||
release_date: m.release_date ?? "",
|
||||
variants: record(m.variants),
|
||||
}
|
||||
}
|
||||
|
||||
// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info.
|
||||
export function modelOf(providerID, provider, key, m) {
|
||||
const caps = record(m.capabilities)
|
||||
const listFrom = (obj, list) => {
|
||||
if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k])
|
||||
if (Array.isArray(list)) return list.map(String)
|
||||
return ["text"]
|
||||
}
|
||||
const input = listFrom(caps.input, m.modalities?.input)
|
||||
const output = listFrom(caps.output, m.modalities?.output)
|
||||
const c = record(m.cost)
|
||||
const cache = record(c.cache)
|
||||
const npm = m.api?.npm ?? m.provider?.npm
|
||||
const url = m.api?.url ?? m.provider?.api
|
||||
const settings = { ...record(json(m.options)) }
|
||||
if (url && url !== provider.baseURL) settings.baseURL = url
|
||||
const variants = Object.entries(record(m.variants))
|
||||
.filter(([, v]) => !record(v).disabled)
|
||||
.map(([id, v]) => {
|
||||
const { disabled: _d, ...rest } = record(json(v))
|
||||
return nonEmpty(rest) ? { id, settings: rest } : { id }
|
||||
})
|
||||
const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active"
|
||||
const out = {
|
||||
id: key,
|
||||
modelID: String(m.api?.id ?? m.id ?? key),
|
||||
providerID,
|
||||
name: String(m.name ?? key),
|
||||
capabilities: {
|
||||
tools: caps.toolcall ?? m.tool_call ?? true,
|
||||
input: input.length ? input : ["text"],
|
||||
output: output.length ? output : ["text"],
|
||||
...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}),
|
||||
},
|
||||
variants,
|
||||
time: { released: Date.parse(m.release_date ?? "") || 0 },
|
||||
cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }],
|
||||
status,
|
||||
enabled: true,
|
||||
limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 },
|
||||
}
|
||||
if (m.limit?.input) out.limit.input = int(m.limit.input)
|
||||
if (npm && npm !== provider.npm) out.package = packageOf(npm)
|
||||
if (nonEmpty(settings)) out.settings = settings
|
||||
const headers = strings(m.headers)
|
||||
if (nonEmpty(headers)) out.headers = headers
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- requests -----------------------------------------------------------
|
||||
|
||||
const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input))
|
||||
|
||||
// wrapFetch sends a request the SDK made from the provider's settings the
|
||||
// way 1.x would have sent it with the loader's options: the loader's base
|
||||
// URL in place of the configured one, the account's key in place of the
|
||||
// placeholder, the loader's headers added, through the loader's fetch.
|
||||
export function wrapFetch(next, base, options) {
|
||||
return async (input, init = {}) => {
|
||||
const o = await options()
|
||||
let url = urlOf(input)
|
||||
const from = String(base ?? "").replace(/\/+$/, "")
|
||||
const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : ""
|
||||
if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length)
|
||||
const req = input instanceof Request ? input : null
|
||||
const headers = new Headers(init.headers ?? req?.headers ?? undefined)
|
||||
for (const [k, v] of [...headers.entries()]) {
|
||||
if (!v.includes(PLACEHOLDER)) continue
|
||||
if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key))
|
||||
else headers.delete(k)
|
||||
}
|
||||
for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v)
|
||||
const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch
|
||||
if (req && init.body === undefined) {
|
||||
const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text()
|
||||
return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal })
|
||||
}
|
||||
return send(url, { ...init, headers })
|
||||
}
|
||||
}
|
||||
|
||||
// ---- one plugin ---------------------------------------------------------
|
||||
|
||||
async function setupPlugin(ctx, fn, live) {
|
||||
const directory = ctx?.location?.directory ?? process.cwd()
|
||||
// the active account each provider was last read for, and the renewed
|
||||
// auth a plugin saved for it (2.x has no way for a plugin to write a
|
||||
// credential back, so it is kept in the plugin's storage, under the
|
||||
// credential it renews and the token it was renewed from)
|
||||
const current = new Map()
|
||||
const saved = new Map()
|
||||
const signingIn = new Map()
|
||||
const storeKey = (id, key) => `v1auth/${id}/${key}`
|
||||
|
||||
const client = {
|
||||
auth: {
|
||||
async set(arg) {
|
||||
const id = arg?.path?.id
|
||||
const body = json(arg?.body)
|
||||
const cur = id && current.get(id)
|
||||
// a sign-in's own saves belong to the credential it is about to
|
||||
// make, not the one that was active when it started
|
||||
if (!cur || !body || signingIn.get(id) > 0) return { data: true }
|
||||
const entry = { fp: cur.fp, auth: body }
|
||||
saved.set(storeKey(id, cur.key), entry)
|
||||
await Promise.resolve()
|
||||
.then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry))
|
||||
.catch(() => {})
|
||||
return { data: true }
|
||||
},
|
||||
async get() {
|
||||
return { data: undefined }
|
||||
},
|
||||
},
|
||||
app: { log: async () => ({ data: true }) },
|
||||
}
|
||||
|
||||
const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {}
|
||||
const cfg = { provider: {} }
|
||||
try {
|
||||
await hooks.config?.(cfg)
|
||||
} catch {}
|
||||
const auth = hooks.auth
|
||||
const authID = auth?.provider ? String(auth.provider) : undefined
|
||||
const providers = record(cfg.provider)
|
||||
|
||||
// getAuth reads the active account: the credential 2.x holds, or what the
|
||||
// plugin last saved renewing it.
|
||||
const getAuth = async (id) => {
|
||||
const connection = await ctx.integration.connection.active(id).catch(() => undefined)
|
||||
if (!connection) {
|
||||
current.delete(id)
|
||||
return undefined
|
||||
}
|
||||
const value = await ctx.integration.connection.resolve(connection).catch(() => undefined)
|
||||
const base = authOfValue(value)
|
||||
if (!base) {
|
||||
current.delete(id)
|
||||
return undefined
|
||||
}
|
||||
const key = connKey(connection)
|
||||
const fp = fingerprint(base)
|
||||
// ours: a credential one of this plugin's own sign-ins made
|
||||
const ours = value?.type === "oauth" && !!record(value.metadata).v1
|
||||
current.set(id, { key, fp, ours })
|
||||
const sk = storeKey(id, key)
|
||||
let entry = saved.get(sk)
|
||||
if (!entry) {
|
||||
entry = await Promise.resolve()
|
||||
.then(() => ctx.storage?.get?.(sk))
|
||||
.catch(() => undefined)
|
||||
if (entry) saved.set(sk, entry)
|
||||
}
|
||||
return entry && entry.fp === fp && entry.auth ? entry.auth : base
|
||||
}
|
||||
|
||||
// the sign-in methods
|
||||
if (authID && Array.isArray(auth.methods) && auth.methods.length) {
|
||||
const label = (c) => {
|
||||
const a = authOfValue(c)
|
||||
const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account
|
||||
return typeof name === "string" && name ? name : undefined
|
||||
}
|
||||
const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1)
|
||||
const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1))
|
||||
const title = record(providers[authID]).name
|
||||
// 2.x runs a transform again on every reload, from nothing
|
||||
await ctx.integration.transform((editor) => {
|
||||
let keyed = false
|
||||
// the integration 2.x makes for an id it doesn't know is named by the
|
||||
// id; the provider's own name reads better in the sign-in list
|
||||
if (typeof title === "string" && title)
|
||||
try {
|
||||
editor.update?.(authID, (i) => {
|
||||
if (i && (!i.name || i.name === authID)) i.name = title
|
||||
})
|
||||
} catch {}
|
||||
auth.methods.forEach((m, i) => {
|
||||
if (!m) return
|
||||
const methodID = `v1-${i}`
|
||||
const form = fieldsOf(m.prompts)
|
||||
if (m.type === "api" && typeof m.authorize !== "function") {
|
||||
if (keyed) return
|
||||
keyed = true
|
||||
editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } })
|
||||
return
|
||||
}
|
||||
if (typeof m.authorize !== "function") return
|
||||
editor.method.update({
|
||||
integrationID: authID,
|
||||
method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) },
|
||||
async authorize(answer) {
|
||||
begin()
|
||||
let ended = false
|
||||
const done = () => {
|
||||
if (!ended) end()
|
||||
ended = true
|
||||
}
|
||||
try {
|
||||
const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)]))
|
||||
const r = await m.authorize(inputs)
|
||||
if (m.type === "api") {
|
||||
done()
|
||||
return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) }
|
||||
}
|
||||
if (r?.method === "code")
|
||||
return {
|
||||
url: String(r.url ?? ""),
|
||||
instructions: String(r.instructions ?? ""),
|
||||
mode: "code",
|
||||
callback: async (code) => {
|
||||
try {
|
||||
return credentialOf(methodID, await r.callback(code))
|
||||
} finally {
|
||||
done()
|
||||
}
|
||||
},
|
||||
}
|
||||
const callback = Promise.resolve()
|
||||
.then(() => r.callback())
|
||||
.then((res) => credentialOf(methodID, res))
|
||||
.finally(done)
|
||||
callback.catch(() => {})
|
||||
return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback }
|
||||
} catch (e) {
|
||||
done()
|
||||
throw e
|
||||
}
|
||||
},
|
||||
label,
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// the loader's options for the account signed in now, read again when
|
||||
// the account changes
|
||||
let loaded = null
|
||||
const loaderOptions = async (id) => {
|
||||
if (id !== authID || typeof auth?.loader !== "function") {
|
||||
const a = authID === id ? await getAuth(id) : undefined
|
||||
return { key: a?.type === "api" ? a.key : undefined }
|
||||
}
|
||||
const a = await getAuth(id)
|
||||
if (!a) return {}
|
||||
const fp = current.get(id)?.key + "\0" + fingerprint(a)
|
||||
if (loaded?.fp !== fp) {
|
||||
const p = Promise.resolve()
|
||||
.then(() => auth.loader(() => getAuth(id), providerOf(id)))
|
||||
.then((o) => record(o))
|
||||
loaded = { fp, p }
|
||||
p.catch(() => {
|
||||
if (loaded?.fp === fp) loaded = null
|
||||
})
|
||||
}
|
||||
const o = await loaded.p
|
||||
const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined
|
||||
return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch }
|
||||
}
|
||||
|
||||
// the providers, with the list the account's own read last gave each
|
||||
const source = new Map()
|
||||
// providerOf is a provider as 1.x hands it to provider.models and
|
||||
// auth.loader
|
||||
const providerOf = (id) => {
|
||||
const conf = record(providers[id])
|
||||
const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))]))
|
||||
return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models }
|
||||
}
|
||||
const listed = new Set()
|
||||
for (const [id, conf0] of Object.entries(providers)) {
|
||||
const conf = record(conf0)
|
||||
// a provider entry that only names the sign-in (no package, no models)
|
||||
// is not a provider of models
|
||||
if (!conf.npm && !Object.keys(record(conf.models)).length) continue
|
||||
const options = record(conf.options)
|
||||
const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options
|
||||
// with no base URL the config leaves it to the loader: a name that
|
||||
// can't resolve stands in for it, and each request swaps in the
|
||||
// loader's (wrapFetch)
|
||||
const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid`
|
||||
const npm = conf.npm ?? "@ai-sdk/openai-compatible"
|
||||
const info = {
|
||||
id,
|
||||
...(id === authID ? { integrationID: id } : {}),
|
||||
name: String(conf.name ?? id),
|
||||
activation: "auto",
|
||||
package: packageOf(npm),
|
||||
settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) },
|
||||
}
|
||||
const headers = { ...strings(conf.headers), ...strings(optHeaders) }
|
||||
if (nonEmpty(headers)) info.headers = headers
|
||||
const prov = { baseURL, npm }
|
||||
const fromConfig = () =>
|
||||
Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m))))
|
||||
listed.add(id)
|
||||
await ctx.provider.transform((editor) => {
|
||||
const s = source.get(id)
|
||||
editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection })
|
||||
})
|
||||
source.set(id, { conf, prov, models: null, connection: undefined })
|
||||
}
|
||||
|
||||
// each request: the placeholder key, and the fetch that swaps in the
|
||||
// account's. A provider the package doesn't list (one 2.x has built in
|
||||
// that the plugin only signs in to) is left to 2.x unless the plugin's
|
||||
// loader serves it and one of the plugin's own sign-ins is active.
|
||||
const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : []
|
||||
for (const id of new Set([...listed, ...own])) {
|
||||
const base = source.get(id)?.prov.baseURL
|
||||
await ctx.aisdk.hook(
|
||||
"sdk",
|
||||
async (evt) => {
|
||||
const opts = evt.options
|
||||
if (!opts || opts.__opencode2) return
|
||||
if (!listed.has(id)) {
|
||||
await getAuth(id)
|
||||
if (!current.get(id)?.ours) return
|
||||
}
|
||||
opts.__opencode2 = true
|
||||
opts.apiKey = PLACEHOLDER
|
||||
opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id))
|
||||
},
|
||||
{ providerID: id },
|
||||
)
|
||||
}
|
||||
|
||||
// refresh reads the account's own list after a sign-in or a switch
|
||||
const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined
|
||||
let refreshing = null
|
||||
let again = false
|
||||
// the account the list was last read for: a credential.updated that
|
||||
// leaves it as it was reads nothing again
|
||||
let readFor = null
|
||||
const stateOf = async () => {
|
||||
const c = await ctx.integration.connection.active(authID).catch(() => undefined)
|
||||
const a = c ? await getAuth(authID) : undefined
|
||||
return connKey(c) + "\0" + (a ? fingerprint(a) : "")
|
||||
}
|
||||
const refresh = () => {
|
||||
if (refreshing) {
|
||||
again = true
|
||||
return refreshing
|
||||
}
|
||||
refreshing = (async () => {
|
||||
try {
|
||||
if (!authID || !source.has(authID)) return
|
||||
const s = source.get(authID)
|
||||
const connection = await ctx.integration.connection.active(authID).catch(() => undefined)
|
||||
const a = connection ? await getAuth(authID) : undefined
|
||||
readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "")
|
||||
if (!a || listID !== authID || typeof hooks.provider?.models !== "function") {
|
||||
if (s.connection || s.models) {
|
||||
s.connection = undefined
|
||||
s.models = null
|
||||
await ctx.provider.reload()
|
||||
}
|
||||
return
|
||||
}
|
||||
const provider = providerOf(authID)
|
||||
let got
|
||||
try {
|
||||
got = await hooks.provider.models(provider, { auth: a })
|
||||
} catch {
|
||||
got = null
|
||||
}
|
||||
if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) {
|
||||
again = true
|
||||
return
|
||||
}
|
||||
s.connection = connection
|
||||
s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null
|
||||
await ctx.provider.reload()
|
||||
await ctx.model?.reload?.()
|
||||
} finally {
|
||||
refreshing = null
|
||||
if (again && live.on) {
|
||||
again = false
|
||||
void refresh()
|
||||
}
|
||||
}
|
||||
})()
|
||||
return refreshing
|
||||
}
|
||||
|
||||
if (authID && ctx.event?.subscribe)
|
||||
void (async () => {
|
||||
try {
|
||||
// a switch names the integration; an update (a sign-in, a removal)
|
||||
// names nothing, so it reads again only when this account changed
|
||||
const types = ["credential.switched", "credential.updated"]
|
||||
for await (const event of ctx.event.subscribe({ types })) {
|
||||
if (!live.on) return
|
||||
if (event?.type === "credential.switched" && event?.data?.integrationID === authID) {
|
||||
loaded = null
|
||||
await refresh()
|
||||
} else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) {
|
||||
await refresh()
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
})()
|
||||
// A plugin still reading its list in the background when the first read
|
||||
// returned (agy-cli: `agy models` and a session probe take seconds, and
|
||||
// the first read gets its static list) says so through
|
||||
// provider.warming(): the list is read once more when that ends, once,
|
||||
// and no later than a minute on.
|
||||
const warmed = async () => {
|
||||
let w
|
||||
try {
|
||||
w = typeof hooks.provider?.warming === "function" ? hooks.provider.warming() : null
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (!w || typeof w.then !== "function") return
|
||||
let timer
|
||||
await Promise.race([
|
||||
Promise.resolve(w).catch(() => {}),
|
||||
new Promise((r) => {
|
||||
timer = setTimeout(r, 60_000)
|
||||
timer.unref?.()
|
||||
}),
|
||||
])
|
||||
clearTimeout(timer)
|
||||
if (live.on) await refresh()
|
||||
}
|
||||
void refresh().then(warmed, () => {})
|
||||
}
|
||||
|
||||
export async function setup(ctx, mod = v1) {
|
||||
const live = { on: true }
|
||||
for (const fn of pluginsOf(mod)) {
|
||||
try {
|
||||
await setupPlugin(ctx, fn, live)
|
||||
} catch (e) {
|
||||
// one plugin failing to start leaves the package's others working
|
||||
console.error(`${pkg.name}: ${e?.message ?? e}`)
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
live.on = false
|
||||
}
|
||||
}
|
||||
|
||||
export default { id: pkg.name, setup: (ctx) => setup(ctx) }
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-gemini-web-auth",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"gemini.mjs",
|
||||
"browser.mjs",
|
||||
"openai.mjs",
|
||||
"prompt.mjs",
|
||||
"opencode.mjs",
|
||||
"opencode2.mjs",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"description": "The Gemini web app (gemini.google.com) as a model provider: your Google account signed in through a browser window of its own, each request one streamed call to the app's own endpoint",
|
||||
"magpie": {
|
||||
"icon": "gemini-color",
|
||||
"maxConcurrency": 2
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/gemini-web"
|
||||
},
|
||||
"keywords": ["magpie", "magpie-plugin", "opencode-plugin", "gemini", "gemini-web"],
|
||||
"license": "MIT",
|
||||
"exports": {
|
||||
".": "./opencode2.mjs"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// The Gemini web app takes one message, not a chat request. To serve a
|
||||
// client's chat request through it, the whole request
|
||||
// (system prompt, tools, every turn) is written into one message, and the
|
||||
// client's tools are asked for as text: <tool_call>{json}</tool_call>
|
||||
// blocks, which are read back into OpenAI tool_calls.
|
||||
|
||||
const OPEN = "<tool_call>"
|
||||
const CLOSE = "</tool_call>"
|
||||
|
||||
function partText(content) {
|
||||
if (content == null) return ""
|
||||
if (typeof content === "string") return content
|
||||
if (!Array.isArray(content)) return typeof content === "object" ? JSON.stringify(content) : String(content)
|
||||
return content
|
||||
.map((p) => {
|
||||
if (typeof p === "string") return p
|
||||
if (p?.type === "text" || p?.type === "input_text") return p.text ?? ""
|
||||
if (p?.type === "image_url" || p?.type === "input_image" || p?.type === "image") return "[image omitted: only text reaches this model]"
|
||||
if (p?.type === "file" || p?.type === "input_file") return "[file omitted: only text reaches this model]"
|
||||
return p?.text ?? ""
|
||||
})
|
||||
.join("")
|
||||
}
|
||||
|
||||
function toolLine(t) {
|
||||
const f = t?.function ?? t
|
||||
if (!f?.name) return null
|
||||
const desc = String(f.description ?? "").trim()
|
||||
const params = f.parameters ? JSON.stringify(f.parameters) : "{}"
|
||||
return `## ${f.name}\n${desc ? desc + "\n" : ""}Arguments (JSON Schema): ${params}`
|
||||
}
|
||||
|
||||
function callText(c) {
|
||||
const f = c?.function ?? c
|
||||
let args = f?.arguments ?? {}
|
||||
if (typeof args === "string") {
|
||||
try { args = JSON.parse(args || "{}") } catch {}
|
||||
}
|
||||
return OPEN + JSON.stringify({ name: f?.name, arguments: args }) + CLOSE
|
||||
}
|
||||
|
||||
// choice reads tool_choice into what the prompt asks of the model.
|
||||
function choice(body, names) {
|
||||
const c = body.tool_choice
|
||||
if (c === "none") return { off: true }
|
||||
if (c === "required") return { must: true }
|
||||
const name = c?.function?.name ?? c?.name
|
||||
if (name && names.includes(name)) return { must: true, only: name }
|
||||
return {}
|
||||
}
|
||||
|
||||
// flatten writes an OpenAI chat request as one message.
|
||||
export function flatten(body) {
|
||||
const messages = Array.isArray(body?.messages) ? body.messages : []
|
||||
const tools = (Array.isArray(body?.tools) ? body.tools : []).map((t) => ({ line: toolLine(t), name: (t?.function ?? t)?.name })).filter((t) => t.line)
|
||||
const ch = choice(body ?? {}, tools.map((t) => t.name))
|
||||
const useTools = tools.length > 0 && !ch.off
|
||||
const out = []
|
||||
out.push("You are the language model behind a client application. You cannot run anything yourself and must not use your own tools, web search, files or computer: you only write text.")
|
||||
if (useTools) {
|
||||
out.push(
|
||||
`When an action is needed, reply with one or more blocks of exactly\n${OPEN}{"name": "<tool>", "arguments": {...}}${CLOSE}\nand nothing after them. The caller runs them and sends you the results in the next message. When no action is needed, answer in plain text with no ${OPEN} block.`,
|
||||
)
|
||||
if (ch.only) out.push(`You must call the tool ${ch.only} now.`)
|
||||
else if (ch.must) out.push("You must call at least one tool now.")
|
||||
}
|
||||
const system = messages.filter((m) => m?.role === "system" || m?.role === "developer").map((m) => partText(m.content).trim()).filter(Boolean)
|
||||
if (system.length) out.push("# Instructions from the client\n\n" + system.join("\n\n"))
|
||||
if (useTools) out.push("# Tools\n\n" + tools.map((t) => t.line).join("\n\n"))
|
||||
if (body?.response_format?.type === "json_object" || body?.response_format?.type === "json_schema") {
|
||||
const schema = body.response_format.json_schema?.schema
|
||||
out.push("Answer with one JSON value and nothing else." + (schema ? " It must match this JSON Schema: " + JSON.stringify(schema) : ""))
|
||||
}
|
||||
const names = new Map()
|
||||
const turns = []
|
||||
for (const m of messages) {
|
||||
if (!m || m.role === "system" || m.role === "developer") continue
|
||||
if (m.role === "user") turns.push("[user]\n" + partText(m.content))
|
||||
else if (m.role === "assistant") {
|
||||
const parts = []
|
||||
const text = partText(m.content)
|
||||
if (text.trim()) parts.push(text)
|
||||
for (const c of m.tool_calls ?? []) {
|
||||
names.set(c.id, c.function?.name)
|
||||
parts.push(callText(c))
|
||||
}
|
||||
if (parts.length) turns.push("[assistant]\n" + parts.join("\n"))
|
||||
} else if (m.role === "tool" || m.role === "function") {
|
||||
const n = m.name ?? names.get(m.tool_call_id)
|
||||
turns.push(`[tool result${n ? " of " + n : ""}]\n` + partText(m.content))
|
||||
}
|
||||
}
|
||||
out.push("# Conversation so far\n\n" + turns.join("\n\n"))
|
||||
out.push("Write the next [assistant] turn now, without the [assistant] label.")
|
||||
return out.join("\n\n")
|
||||
}
|
||||
|
||||
// plugins#1114 (qoder's #1113): a reply may write its calls as one JSON
|
||||
// object in OpenAI's own wire shape, {"tool_calls":[{"name","arguments"}]}.
|
||||
// It is told apart from text by where it starts: a line of its own whose
|
||||
// object opens with the "tool_calls" key, outside code.
|
||||
const JSON_KEY = '{"tool_calls"'
|
||||
const JSON_AT = /(^|\n)[ \t]*\{\s*"tool_calls"\s*:/g
|
||||
|
||||
// inCode says whether at is inside a ``` fence
|
||||
const inCode = (text, at) => (text.slice(0, at).match(/```/g)?.length ?? 0) % 2 === 1
|
||||
|
||||
// jsonStarts are where each such object's "{" is, outside code
|
||||
function jsonStarts(text) {
|
||||
const out = []
|
||||
for (const m of text.matchAll(JSON_AT)) {
|
||||
const at = text.indexOf("{", m.index)
|
||||
if (!inCode(text, at)) out.push(at)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// jsonEnd is where the JSON value at the start of v ends, -1 while it is
|
||||
// not whole yet
|
||||
function jsonEnd(v) {
|
||||
let depth = 0
|
||||
let str = false
|
||||
for (let k = 0; k < v.length; k++) {
|
||||
const c = v[k]
|
||||
if (str) {
|
||||
if (c === "\\") k++
|
||||
else if (c === '"') str = false
|
||||
} else if (c === '"') str = true
|
||||
else if (c === "{" || c === "[") depth++
|
||||
else if (c === "}" || c === "]") {
|
||||
if (--depth === 0) return k + 1
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// jsonCalls reads a whole {"tool_calls": [...]} object as its calls, or
|
||||
// null when it isn't one the plugin can read whole (it stays text)
|
||||
function jsonCalls(v) {
|
||||
let f
|
||||
try { f = JSON.parse(v) } catch { return null }
|
||||
const list = f?.tool_calls
|
||||
if (!Array.isArray(list) || !list.length) return null
|
||||
const calls = []
|
||||
for (const e of list) {
|
||||
const fn = e?.function ?? e
|
||||
let args = fn?.arguments ?? {}
|
||||
if (typeof args === "string") {
|
||||
try { args = JSON.parse(args) } catch { return null }
|
||||
}
|
||||
const name = String(fn?.name ?? "").trim()
|
||||
if (!name || !args || typeof args !== "object" || Array.isArray(args)) return null
|
||||
calls.push({ name, arguments: JSON.stringify(args) })
|
||||
}
|
||||
return calls
|
||||
}
|
||||
|
||||
// heldFrom is where text stops being safe to show while it streams: the
|
||||
// first <tool_call> or {"tool_calls" line, or a tail that could be the
|
||||
// start of one.
|
||||
export function heldFrom(text) {
|
||||
let at = text.indexOf(OPEN)
|
||||
const j = jsonStarts(text)[0]
|
||||
if (j !== undefined && (at < 0 || j < at)) at = text.lastIndexOf("\n", j) + 1
|
||||
if (at >= 0) return at
|
||||
const nl = text.lastIndexOf("\n")
|
||||
const line = text.slice(nl + 1)
|
||||
const bare = line.replace(/\s+/g, "")
|
||||
if (bare && JSON_KEY.startsWith(bare) && !inCode(text, nl + 1)) return nl + 1
|
||||
for (let n = Math.min(OPEN.length - 1, text.length); n > 0; n--) if (OPEN.startsWith(text.slice(-n))) return text.length - n
|
||||
return text.length
|
||||
}
|
||||
|
||||
function parseCall(raw) {
|
||||
let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "").trim()
|
||||
let v
|
||||
try { v = JSON.parse(s) } catch { return null }
|
||||
if (Array.isArray(v)) v = v[0]
|
||||
const name = v?.name ?? v?.function?.name ?? v?.tool
|
||||
if (typeof name !== "string" || !name) return null
|
||||
let args = v.arguments ?? v.parameters ?? v.input ?? v.args ?? v.function?.arguments ?? {}
|
||||
if (typeof args === "string") {
|
||||
try { args = JSON.parse(args) } catch {}
|
||||
}
|
||||
return { name, arguments: typeof args === "string" ? args : JSON.stringify(args ?? {}) }
|
||||
}
|
||||
|
||||
// parse splits a finished reply into its text and tool calls. A block that
|
||||
// isn't a call it can read stays in the text, so nothing the model wrote is
|
||||
// lost. An unclosed last block is read to the end.
|
||||
export function parse(text, newId = () => "call_" + Math.random().toString(36).slice(2, 14)) {
|
||||
const calls = []
|
||||
const lifted = []
|
||||
let rest = ""
|
||||
let i = 0
|
||||
while (i < text.length) {
|
||||
const at = text.indexOf(OPEN, i)
|
||||
if (at < 0) { rest += text.slice(i); break }
|
||||
rest += text.slice(i, at)
|
||||
const end = text.indexOf(CLOSE, at + OPEN.length)
|
||||
const raw = text.slice(at + OPEN.length, end < 0 ? text.length : end)
|
||||
const call = parseCall(raw)
|
||||
if (call) calls.push({ id: newId(), type: "function", function: call })
|
||||
else rest += text.slice(at, end < 0 ? text.length : end + CLOSE.length)
|
||||
i = end < 0 ? text.length : end + CLOSE.length
|
||||
}
|
||||
// a whole {"tool_calls":[…]} object on a line of its own is its calls
|
||||
for (const at of jsonStarts(rest).reverse()) {
|
||||
const end = jsonEnd(rest.slice(at))
|
||||
const got = end < 0 ? null : jsonCalls(rest.slice(at, at + end))
|
||||
if (!got) continue
|
||||
lifted.unshift(...got)
|
||||
rest = rest.slice(0, at) + rest.slice(at + end)
|
||||
}
|
||||
for (const c of lifted) calls.push({ id: newId(), type: "function", function: c })
|
||||
// fences left empty around a call (```xml … ```) are not text
|
||||
const cleaned = calls.length ? rest.replace(/```[a-z]*\s*```/gi, "") : rest
|
||||
return { text: calls.length ? cleaned.trim() : rest, calls, raw: rest }
|
||||
}
|
||||
+8
File diff suppressed because one or more lines are too long
+20
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+24
File diff suppressed because one or more lines are too long
@@ -28,6 +28,7 @@
|
||||
{ "package": "@magpie-community/opencode-joycode-auth", "name": "JoyCode", "providers": ["joycode"], "community": true,
|
||||
"summary": { "en": "Unofficial JoyCode provider: JD account browser sign-in, live models and credit multipliers, plan credits and streaming tool calls.", "zh": "非官方 JoyCode 插件:京东账号浏览器登录,动态模型与积分倍率、套餐额度及流式工具调用。" } },
|
||||
{"package": "@magpie-community/opencode-doubao-work-auth", "name": "豆包工作", "icon": "doubao-color", "providers": ["doubao-work"], "community": true, "summary": {"en": "Not a model API: Doubao Work has none for other clients. This drives its desktop app (or Doubao's) the way a person does, so each request is one run of Doubao's cloud agent in a new task, with the client's tools asked for as text. macOS and Windows; unofficial.", "zh": "不是模型接口:豆包工作没有给第三方客户端用的模型接口。本插件像人一样操作豆包工作(或豆包)桌面版,每个请求是豆包云端智能体在一个新任务里的一次执行,客户端的工具以文本方式调用。macOS 和 Windows;非官方。"}},
|
||||
{"package": "@magpie-community/opencode-gemini-web-auth", "name": "Gemini 网页版", "icon": "gemini-color", "providers": ["gemini-web"], "community": true, "summary": {"en": "Not Google's API: the Gemini web app (gemini.google.com), with your Google account signed in through a browser window of its own, or as a visitor without one. Each request is one streamed call to the app's own endpoint, in a temporary chat, with the client's tools asked for as text. Unofficial.", "zh": "不是 Google 的 API:Gemini 网页版(gemini.google.com),在插件自己的浏览器窗口里登录 Google 账号,或不登录以访客使用。每个请求是对网页版自己接口的一次流式调用(临时对话,不进历史),客户端的工具以文本方式调用。非官方。"}},
|
||||
{"package": "@magpie-community/opencode-kimi-work-auth", "name": "Kimi Work", "icon": "kimi", "providers": ["kimi-work"], "community": true, "summary": {"en": "Kimi desktop Work subscription through its local sign-in, with live Work models and shared membership usage. Separate from Kimi Code.", "zh": "使用本机普通 Kimi 桌面版的 Work 登录,自动读取 Work 模型和会员共享用量;独立于 Kimi Code。"}},
|
||||
{ "package": "@magpie-community/opencode-zen-free-auth", "name": "OpenCode Zen Free", "icon": "opencode", "providers": ["opencode-zen-free"], "community": true,
|
||||
"summary": { "en": "OpenCode Zen's free models with the public credential, automatic discovery and native streaming protocols.", "zh": "使用 public 凭证接入 OpenCode Zen 免费模型,自动发现模型并支持原生流式协议。" } },
|
||||
|
||||
Reference in New Issue
Block a user