@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.
135 lines
5.1 KiB
JavaScript
135 lines
5.1 KiB
JavaScript
// 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),
|
|
}
|
|
}
|