Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(runtime): stop injecting a custom fetch into the Google adapters

vastsa585e1e1da1eb
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.md
index 4d8c113cd..66c69f732 100644
--- a/docs/project/unreleased.md
+++ b/docs/project/unreleased.md
@@ -1,5 +1,11 @@
# Unreleased changes
+- Google Gemini rows send requests again. A provider row on the native
+ generative-AI endpoint no longer hands pi-ai's Google adapter the internal
+ response-capture `fetch` it refuses before the request leaves, custom provider
+ headers still reach Google, and an adapter refusal now fails the turn instead
+ of spending all ten transient retries on it (issue #1072).
+
- Deleting a provider no longer leaves a dangling image-generation default.
An image default or marked candidate whose provider row is gone is dropped
on the next settings read or write, instead of staying stored as a binding
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 829b7efe2..2627266ef 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1224,7 +1224,9 @@ Caller-supplied headers override the client and User-Agent defaults. An empty
session header is restored from the conversation id so OpenCode Go cannot
return `MissingSessionID`. A provider-row `headers` map is applied after this
merge (headers plus a fetch wrapper) so custom values win over the OpenCode
-default and over adapter last-writes. Reserved keys cannot smash
+default and over adapter last-writes. The Google adapters take the merged
+`headers` without the wrapper, because they reject any other `fetch`
+(issue #1072). Reserved keys cannot smash
`x-opencode-session`. This is an agent-runtime concern, matching the
official Pi coding-agent attribution layer; pi-ai's `sessionId` stream option
does not emit `x-opencode-session`.
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index be09cb0b7..aacc76919 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -97,7 +97,7 @@ does not turn temporary thread pressure into a host process exit.
| `TURN_NOT_FOUND` | no | turn id invalid |
| `TURN_ABORTED` | no | turn aborted by user/system |
| `MODEL_NOT_CONFIGURED` | no | no usable model selected, or provider rejects the selected model as unknown |
-| `PROVIDER_ERROR` | yes | upstream provider failure; a retryable one (5xx gateway) gets up to ten same-turn retries, a malformed 400/422 request is terminal |
+| `PROVIDER_ERROR` | yes | upstream provider failure; a retryable one (5xx gateway) gets up to ten same-turn retries, while a malformed 400/422 request or a request option the adapter itself refuses (a custom `fetch` for the Google adapters, issue #1072) is terminal |
| `PROVIDER_UNAUTHORIZED` | no | bad/missing provider credentials |
| `PROVIDER_RATE_LIMITED` | yes | provider rate limited; runtime silently retries up to ten times across setup/stream before the terminal event |
| `CONTEXT_TOO_LARGE` | no | prompt/context still exceeds the safe model budget after recovery, the second provider overflow occurred, or automatic recovery is disabled |
@@ -368,7 +368,10 @@ phase: the fault is reported as `phase: request` because no response ever
arrived, which is what distinguishes it from a stream that ended mid-response.
`networkRoute` (`direct`, `environment-proxy`, `http-proxy`, `socks5-proxy`)
names the hop the request was taking, so a failure at the proxy is readable
-without guessing from an errno.
+without guessing from an errno. A request bound for pi-ai's Google adapters
+carries no fetch wrapper and never reaches `onResponse` (issue #1072), so it
+reports neither field: it keeps the provider's own message, its `Retry-After`
+falls back to the bounded ladder, and the rebuild below does not fire for it.
When one origin fails this way repeatedly inside a turn — twice in a row,
without any response — the provider transport is rebuilt before the next attempt
diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.md
index b91712eea..7e4c8eb95 100644
--- a/docs/spec/03-runtime/11-provider-model-system.md
+++ b/docs/spec/03-runtime/11-provider-model-system.md
@@ -76,7 +76,14 @@ conversation id (or a per-call UUID when the caller has no session),
host is `opencode.ai` receives the same headers. pi-ai is not relied on to
emit `x-opencode-session`. Each provider row (AI service or OAuth account)
may set optional `headers`; empty keeps adapter defaults. A fetch wrapper is
-the last writer so Codex and Anthropic cannot overwrite them.
+the last writer so Codex and Anthropic cannot overwrite them. pi-ai's Google
+adapters (`google-generative-ai`, `google-vertex`) reject any `fetch` that is
+not `globalThis.fetch`, so a request bound for them carries none — the merged
+`headers` still reach the SDK client — and a caller-supplied `fetch` is cleared
+rather than wrapped (issue #1072). Because those adapters never see the wrapper and never call
+`onResponse`, such a row reports no captured HTTP status and no captured
+transport cause: `Retry-After` falls back to the bounded backoff ladder, and
+the issue-234 transport diagnostics and rebuild do not fire for it.
When an OAuth vendor is rebuilt around a local provider-row id, runtime keeps
the native pi-ai transport metadata instead of treating the row as a generic
diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.md
index 7479e95e4..59a884463 100644
--- a/docs/spec/03-runtime/12-provider-config-schema.md
+++ b/docs/spec/03-runtime/12-provider-config-schema.md
@@ -253,7 +253,9 @@ Anthropic OAuth's `claude-cli/<version>`, or OpenCode's
outbound HTTP — session turns, subagents, prompt enhancement, plugin one-shots,
`/models` discovery (including unsaved form values), connection tests, and
OAuth token refresh. A fetch wrapper is the last writer so Codex and the
-Anthropic SDK cannot overwrite it. The same values are also placed on stream-
+Anthropic SDK cannot overwrite it; pi-ai's Google adapters receive the same
+values on stream-option headers instead, because they reject any other `fetch`
+(issue #1072). The same values are also placed on stream-
option headers so OpenCode's caller-wins rule stays true. Keys are
case-insensitive unique, at most 32 entries, name ≤ 256 bytes, value ≤ 4096
bytes, no CR/LF, names alphanumeric plus hyphen. Values are folded to
diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index a9b1ccc20..e38e0c540 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -877,7 +877,9 @@ Composer 增强使用与 agent 请求相同的已解析提供商绑定和重试
调用方自带的标头会覆盖 client 与 User-Agent 默认值。空的会话标头会由对话 id
补回,使 OpenCode Go 不会返回 `MissingSessionID`。提供商行上的 `headers` 映射
在这次合并之后应用(标头加上一层 fetch 包装),因此自定义值优先于 OpenCode
-默认值,也优先于适配器的最后写入。保留键无法冲掉 `x-opencode-session`。这属于
+默认值,也优先于适配器的最后写入。Google 适配器只接收合并后的 `headers`、
+不带该包装,因为它们会拒绝任何其他 `fetch`(issue #1072)。保留键无法冲掉
+`x-opencode-session`。这属于
agent 运行时的职责,与官方 Pi 编码 agent 的归属层保持一致;pi-ai 的 `sessionId`
流选项并不会发出 `x-opencode-session`。
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 1471e292e..407ca0516 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -98,7 +98,7 @@ stdio 与 Tokio 的动态阻塞池隔离,因此后一种情况
| `TURN_NOT_FOUND` | 不 | 使 id 无效 |
| `TURN_ABORTED` | 不 | 回合被 user/system 中止 |
| `MODEL_NOT_CONFIGURED` | 不 | 未选择可用模型,或提供商因未知而拒绝所选模型 |
-| `PROVIDER_ERROR` | 是的 | 上游提供商故障;可重试的故障(5xx 网关)最多获得四次同回合重试,格式错误的 400/422 请求是终止的 |
+| `PROVIDER_ERROR` | 是的 | 上游提供商故障;可重试的故障(5xx 网关)最多获得四次同回合重试,而格式错误的 400/422 请求,以及适配器自身拒绝的请求选项(Google 适配器遇到自定义 `fetch`,issue #1072)都是终止的 |
| `PROVIDER_UNAUTHORIZED` | 不 | bad/missing 提供商凭证 |
| `PROVIDER_RATE_LIMITED` | 是的 | 供应商费率有限 |
| `CONTEXT_TOO_LARGE` | 不 | 恢复后 prompt/context 仍超出安全模型预算、发生第二个提供程序溢出或禁用自动恢复 |
@@ -354,7 +354,9 @@ Exhaustion reports `retryAttempt: 10` from the relevant budget counter.
里的 errno 已经消失,裸 `fetch failed` 只能被记为 `networkCategory: unknown`;
而 fetch 包装层仍持有原始 Error,并从它给出同一组经过校验的字段。捕获到的
cause 同时确定了阶段:没有任何响应到达时故障记为 `phase: request`,这正是它
-与「响应中途断流」的区别。`networkRoute`(`direct`、`environment-proxy`、
+与「响应中途断流」的区别。发往 pi-ai Google 适配器的请求不带 fetch 包装、也不会到达 `onResponse`(issue #1072),因此这两个字段都不会上报:它只保留提供商自己的消息,`Retry-After` 退回有界阶梯,下面的重建对它不生效。
+
+`networkRoute`(`direct`、`environment-proxy`、
`http-proxy`、`socks5-proxy`)指出请求实际走的链路,代理这一跳失败无需再从
errno 猜测。
diff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
index 3cc5c6a55..482d6ade1 100644
--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
@@ -77,7 +77,12 @@ OpenCode Go 以一个名为 `opencode_go` 的 API 风格预设暴露。它仍然
主机为 `opencode.ai` 的自定义 OpenAI 兼容行也会收到同样的标头。系统不依赖
pi-ai 去发出 `x-opencode-session`。每个提供商行(AI 服务或 OAuth 账户)都可以
设置可选的 `headers`;留空则保持适配器默认值。一层 fetch 包装是最后的写入方,
-因此 Codex 与 Anthropic 无法覆盖它们。
+因此 Codex 与 Anthropic 无法覆盖它们。pi-ai 的 Google 适配器
+(`google-generative-ai`、`google-vertex`)会拒绝任何不是 `globalThis.fetch`
+的 `fetch`,因此发往它们的请求不带 fetch,只通过合并后的 `headers` 送达 SDK
+客户端;调用方传入的 `fetch` 会被清除而非包装(issue #1072)。由于这些适配器既看不到包装、也从不调用
+`onResponse`,这样的行不上报捕获到的 HTTP 状态与传输原因:`Retry-After`
+退回有界退避阶梯,issue-234 的传输诊断与重建对它不生效。
当 OAuth 厂商围绕本地 provider 行 id 重建运行时模型时,运行时仍保留 pi-ai
原生传输元数据,不会把该行当作普通 OpenAI 端点。GitHub Copilot 请求会保留
diff --git a/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md b/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md
index 681ad73fd..e3433a90a 100644
--- a/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md
+++ b/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md
@@ -229,7 +229,7 @@ OpenCode Go(以及任何 `opencode.ai` 主机)的 LLM 请求必须带稳定
上发送该头,并附带 `x-opencode-client: pi-desktop` 与
`User-Agent: pi-desktop/<APP_VERSION>`。行上可选的 `headers` 会覆盖这些默认值;留空则保持适配器默认。
-每行(AI 服务或 OAuth 账户)可在高级选项中用键值行编辑自定义请求头。空映射保持 pi-ai / `claude-cli` / OpenCode 默认。fetch 包装器是最后写入者,因此 Codex 与 Anthropic SDK 无法覆盖。禁止 `Authorization` / `Host` / `Content-Type` 等保留头。遗留的 `userAgent` 读取时迁入 `headers["User-Agent"]`。首次 OAuth 登录不收集请求头,登录后再编辑。覆盖 Anthropic OAuth 的 `claude-cli/…` 可能导致 Claude Pro/Max 拒绝请求。
+每行(AI 服务或 OAuth 账户)可在高级选项中用键值行编辑自定义请求头。空映射保持 pi-ai / `claude-cli` / OpenCode 默认。fetch 包装器是最后写入者,因此 Codex 与 Anthropic SDK 无法覆盖。pi-ai 的 Google 适配器改为通过流选项标头接收同样的值,因为它们会拒绝任何其他 `fetch`(issue #1072)。禁止 `Authorization` / `Host` / `Content-Type` 等保留头。遗留的 `userAgent` 读取时迁入 `headers["User-Agent"]`。首次 OAuth 登录不收集请求头,登录后再编辑。覆盖 Anthropic OAuth 的 `claude-cli/…` 可能导致 Claude Pro/Max 拒绝请求。
键不区分大小写且唯一,最多 32 条,名称 ≤ 256 字节,值 ≤ 4096 字节,名称只允许字母数字与连字符,且不得含 CR/LF。值先做半角化——全角块(U+FF01–U+FF5E)与表意空格(U+3000)换成对应 ASCII——再修剪,再校验:HTAB、可打印 ASCII 与 Latin-1 补充区可以随请求发出,汉字、emoji、弯引号、NUL 及其它控制字符则以 `HEADERS_INVALID` 拒绝,并指出具体字符与字符下标。半角化覆盖的正是用户真正会撞上的情况:全角字符来自输入法或全角排版的网页,若不处理,`Headers.set` 会在回合中途抛 `Cannot convert argument to a ByteString`。这里刻意不做完整 NFKC:它会把半角片假名改写成 U+00FF 以上的码位并产生组合字符。高级编辑器也会在行旁提示哪些值会被半角化、哪些会被拒绝。
diff --git a/packages/agent-runtime/src/agent-errors.test.ts b/packages/agent-runtime/src/agent-errors.test.ts
index 9d3db7808..427606724 100644
--- a/packages/agent-runtime/src/agent-errors.test.ts
+++ b/packages/agent-runtime/src/agent-errors.test.ts
@@ -249,6 +249,26 @@ describe("classifyAgentError", () => {
.toMatchObject({ code: "PROVIDER_ERROR", retriable: false });
});
+ it("treats a request option an adapter refuses as non-retriable", () => {
+ expect(
+ classifyAgentError(
+ "Custom fetch is not supported by the Google Generative AI adapter",
+ ),
+ ).toMatchObject({ code: "PROVIDER_ERROR", retriable: false });
+ expect(
+ classifyAgentError(
+ "Custom fetch is not supported by the Google Vertex adapter",
+ ),
+ ).toMatchObject({ code: "PROVIDER_ERROR", retriable: false });
+ // A status some layer attached to the same message must not re-arm the
+ // transient retry budget for a request the adapter will refuse again.
+ expect(
+ classifyAgentError(
+ "502: Custom fetch is not supported by the Google Generative AI adapter",
+ ),
+ ).toMatchObject({ code: "PROVIDER_ERROR", retriable: false });
+ });
+
it("detects context overflow from 400 bodies and bare messages", () => {
expect(
classifyAgentError(
diff --git a/packages/agent-runtime/src/agent-errors.ts b/packages/agent-runtime/src/agent-errors.ts
index f85aa7fee..23be7093c 100644
--- a/packages/agent-runtime/src/agent-errors.ts
+++ b/packages/agent-runtime/src/agent-errors.ts
@@ -33,6 +33,10 @@ const CONTEXT_PATTERN =
const STREAM_TERMINATION_PATTERN =
/\bterminated\b|stream ended without finish_reason|premature(?:ly)?\s+(?:closed|ended)|(?:stream|response).*(?:closed|interrupted)/i;
+/** An adapter refusing a request option, e.g. "Custom fetch is not supported
+ * by the Google Generative AI adapter" (issue #1072). */
+const UNSUPPORTED_ADAPTER_OPTION_PATTERN = /is not supported by the .{0,60}adapter/i;
+
function redactSensitiveErrorText(message: string): string {
return message
.replace(
@@ -444,6 +448,13 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {
);
}
+ // The adapter itself refuses how the request was built, so re-sending it
+ // produces the identical failure. Probed before the status table so a status
+ // some layer attached to the same message cannot re-arm the retry budget.
+ if (UNSUPPORTED_ADAPTER_OPTION_PATTERN.test(rawMessage)) {
+ return result("PROVIDER_ERROR", false);
+ }
+
if (status !== undefined) {
if (status === 401 || status === 403) return result("PROVIDER_UNAUTHORIZED", false);
if (status === 408) return result("TIMEOUT", true);
diff --git a/packages/agent-runtime/src/compaction-request.test.ts b/packages/agent-runtime/src/compaction-request.test.ts
index bca8c6a9a..989577761 100644
--- a/packages/agent-runtime/src/compaction-request.test.ts
+++ b/packages/agent-runtime/src/compaction-request.test.ts
@@ -73,6 +73,45 @@ describe("compactionRequestOptions", () => {
});
expect(options.headers).toEqual({ "X-Team": "platform" });
});
+
+ it("clears a caller-supplied fetch for a Google model, with or without row headers", () => {
+ const callerFetch = vi.fn(async () => new Response("ok"));
+ const googleModel = {
+ ...model,
+ provider: "google",
+ api: "google-generative-ai",
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",
+ } as Model<Api>;
+ const googleProvider: RuntimeProviderConfig = {
+ ...provider,
+ id: "google",
+ name: "Google Gemini",
+ vendorKey: "google",
+ apiStyle: "google_generative_ai",
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",
+ modelId: "gemini-3.8-flash",
+ };
+
+ const withRowHeaders = compactionRequestOptions({
+ provider: { ...googleProvider, headers: { "X-Team": "platform" } },
+ sessionId: "session-1",
+ model: googleModel,
+ context,
+ options: { fetch: callerFetch },
+ });
+ const withoutRowHeaders = compactionRequestOptions({
+ provider: googleProvider,
+ sessionId: "session-1",
+ model: googleModel,
+ context,
+ options: { fetch: callerFetch },
+ });
+
+ expect(withRowHeaders.fetch).toBeUndefined();
+ expect(withRowHeaders.headers).toMatchObject({ "X-Team": "platform" });
+ expect(withoutRowHeaders.fetch).toBeUndefined();
+ expect(callerFetch).not.toHaveBeenCalled();
+ });
});
describe("withCompactionRequestHeaders", () => {
diff --git a/packages/agent-runtime/src/compaction-request.ts b/packages/agent-runtime/src/compaction-request.ts
index 2cae90983..99247f402 100644
--- a/packages/agent-runtime/src/compaction-request.ts
+++ b/packages/agent-runtime/src/compaction-request.ts
@@ -52,6 +52,7 @@ export function compactionRequestOptions(input: {
copilotRequestHeaders(provider, context),
provider.headers,
),
+ model.api,
);
}
diff --git a/packages/agent-runtime/src/google-adapter-fetch.test.ts b/packages/agent-runtime/src/google-adapter-fetch.test.ts
new file mode 100644
index 000000000..7788052bd
--- /dev/null
+++ b/packages/agent-runtime/src/google-adapter-fetch.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it, vi } from "vitest";
+import { normalizeContext } from "@earendil-works/pi-ai";
+import { completeOneShot } from "./one-shot-complete.js";
+import { subagentModelBinding } from "./subagent-model-binding.js";
+import type { RuntimeProviderConfig } from "./provider-binding.js";
+
+/**
+ * The Google adapter refuses any `fetch` that is not `globalThis.fetch`
+ * (issue #1072). Every request path must therefore reach it without one, while
+ * the request still carries the provider's own headers.
+ */
+const googleProvider: RuntimeProviderConfig = {
+ id: "google",
+ name: "Google Gemini",
+ vendorKey: "google",
+ apiStyle: "google_generative_ai",
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",
+ modelId: "gemini-3.8-flash",
+ apiKey: "AIza-test",
+ authKind: "api_key",
+ supportsReasoning: true,
+ supportedThinkingLevels: ["off", "high"],
+ headers: { "X-Team": "platform" },
+};
+
+type Captured = { url: string; headers: Record<string, string> };
+
+function googleStreamResponse(): Response {
+ const chunk = (body: unknown) => `data: ${JSON.stringify(body)}\n\n`;
+ return new Response(
+ chunk({ candidates: [{ content: { role: "model", parts: [{ text: "hello" }] }, index: 0 }] }) +
+ chunk({
+ candidates: [{ content: { role: "model", parts: [] }, finishReason: "STOP", index: 0 }],
+ usageMetadata: { promptTokenCount: 3, candidatesTokenCount: 1, totalTokenCount: 4 },
+ }),
+ { status: 200, headers: { "content-type": "text/event-stream" } },
+ );
+}
+
+async function withStubbedGoogle<T>(
+ run: (captured: Captured[]) => Promise<T>,
+): Promise<T> {
+ const captured: Captured[] = [];
+ vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
+ const headers: Record<string, string> = {};
+ new Headers(init?.headers).forEach((value, key) => {
+ headers[key.toLowerCase()] = value;
+ });
+ captured.push({ url: input instanceof Request ? input.url : String(input), headers });
+ return googleStreamResponse();
+ });
+ try {
+ return await run(captured);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+}
+
+describe("Google Generative AI requests", () => {
+ it("completes a one-shot completion through the native endpoint", async () => {
+ const result = await withStubbedGoogle(async (captured) => {
+ const oneShot = await completeOneShot(
+ googleProvider,
+ { systemPrompt: "s", messages: [{ role: "user", content: "hi", timestamp: Date.now() }] },
+ "off",
+ );
+ return { oneShot, captured };
+ });
+
+ expect(result.oneShot.text).toBe("hello");
+ expect(result.captured).toHaveLength(1);
+ expect(result.captured[0].url).toBe(
+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse",
+ );
+ expect(result.captured[0].headers["x-team"]).toBe("platform");
+ });
+
+ it("streams a subagent turn through the native endpoint", async () => {
+ const binding = subagentModelBinding(
+ { provider: googleProvider, thinkingLevel: "off", sessionId: "session-1" },
+ { claim: () => undefined },
+ );
+
+ const text = await withStubbedGoogle(async (captured) => {
+ const result = await binding
+ .streamFn(
+ binding.model,
+ normalizeContext({
+ messages: [{ role: "user", content: "hi", timestamp: Date.now() }],
+ }),
+ {},
+ )
+ .result();
+ expect(captured).toHaveLength(1);
+ return result.content;
+ });
+
+ expect(text).toEqual([{ type: "text", text: "hello" }]);
+ });
+});
diff --git a/packages/agent-runtime/src/one-shot-complete.ts b/packages/agent-runtime/src/one-shot-complete.ts
index ead1138bd..ba05bc5c0 100644
--- a/packages/agent-runtime/src/one-shot-complete.ts
+++ b/packages/agent-runtime/src/one-shot-complete.ts
@@ -19,6 +19,7 @@ import {
buildProviderModel,
copilotRequestHeaders,
createProviderModels,
+ providerRequestFetch,
type RuntimeProviderConfig,
} from "./provider-binding.js";
import {
@@ -99,11 +100,14 @@ export async function completeOneShot(
...(options.signal ? { signal: options.signal } : {}),
maxRetries: 0,
...(thinkingLevel !== "off" ? { reasoning: thinkingLevel } : {}),
- fetch: captureProviderResponse(undefined, (response, _requestBytes, failure) => {
- providerStatus = response?.status;
- providerHeaders = response?.headers;
- providerFailure = failure;
- }),
+ fetch: providerRequestFetch(
+ model.api,
+ captureProviderResponse(undefined, (response, _requestBytes, failure) => {
+ providerStatus = response?.status;
+ providerHeaders = response?.headers;
+ providerFailure = failure;
+ }),
+ ),
},
{
...openCodeEndpointFromProvider(provider, model),
@@ -114,6 +118,7 @@ export async function completeOneShot(
copilotRequestHeaders(provider, context),
provider.headers,
),
+ model.api,
);
const stream = createProviderRetryStream(
model,
diff --git a/packages/agent-runtime/src/provider-binding.test.ts b/packages/agent-runtime/src/provider-binding.test.ts
index 1ed5bac3c..bfef94b6a 100644
--- a/packages/agent-runtime/src/provider-binding.test.ts
+++ b/packages/agent-runtime/src/provider-binding.test.ts
@@ -5,10 +5,12 @@ import { convertMessages } from "@earendil-works/pi-ai/api/openai-completions";
import { genericModelConfig, modelConfigWithBinding } from "./model-capabilities.js";
import type { ModelConfig } from "./thinking-level.js";
import {
+ adapterAcceptsCustomFetch,
apiBindingForStyle,
buildProviderModel,
copilotRequestHeaders,
createProviderModels,
+ providerRequestFetch,
runtimeBaseUrlForApi,
type RuntimeProviderConfig,
} from "./provider-binding.js";
@@ -47,6 +49,26 @@ describe("apiBindingForStyle", () => {
});
});
+describe("custom fetch injection", () => {
+ const wrapper = async () => new Response("ok");
+
+ it("withholds the fetch from the adapters that reject one", () => {
+ expect(adapterAcceptsCustomFetch("google-generative-ai")).toBe(false);
+ expect(adapterAcceptsCustomFetch("google-vertex")).toBe(false);
+ expect(providerRequestFetch("google-generative-ai", wrapper)).toBeUndefined();
+ expect(providerRequestFetch("google-vertex", wrapper)).toBeUndefined();
+ });
+
+ it("passes the caller's fetch to every other adapter", () => {
+ expect(adapterAcceptsCustomFetch("openai-completions")).toBe(true);
+ expect(adapterAcceptsCustomFetch("anthropic-messages")).toBe(true);
+ expect(adapterAcceptsCustomFetch(undefined)).toBe(true);
+ expect(providerRequestFetch("openai-completions", wrapper)).toBe(wrapper);
+ expect(providerRequestFetch("anthropic-messages", wrapper)).toBe(wrapper);
+ expect(providerRequestFetch(undefined, wrapper)).toBe(wrapper);
+ });
+});
+
describe("Anthropic runtime endpoint", () => {
it("removes a trailing /v1 before pi-ai appends its version path", () => {
expect(runtimeBaseUrlForApi("anthropic-messages", "https://gw.example/v1/")).toBe(
diff --git a/packages/agent-runtime/src/provider-binding.ts b/packages/agent-runtime/src/provider-binding.ts
index 1a81f6f54..64fd7cb8a 100644
--- a/packages/agent-runtime/src/provider-binding.ts
+++ b/packages/agent-runtime/src/provider-binding.ts
@@ -12,6 +12,7 @@ import {
createProvider,
type Api,
type Context,
+ type FetchFunction,
type Model,
type ModelAuth,
type Models,
@@ -95,6 +96,32 @@ export function runtimeBaseUrlForApi(api: Api, baseUrl: string): string {
return withoutVersion || withoutTrailingSlash;
}
+/**
+ * Whether `api`'s pi-ai adapter accepts a caller-supplied `fetch`.
+ *
+ * The Google adapters throw unless `options.fetch` is `globalThis.fetch`
+ * itself, and every wrapper this runtime builds is a different function, so a
+ * request bound for them must carry no `fetch` at all (issue #1072). An
+ * unknown wire API is treated as accepting one: only these two are known to
+ * refuse, and the default must stay "inject" for everything else.
+ */
+export function adapterAcceptsCustomFetch(api: Api | undefined): boolean {
+ return api !== "google-generative-ai" && api !== "google-vertex";
+}
+
+/**
+ * The `fetch` one request may hand to `api`'s adapter: the caller's wrapper
+ * where the adapter accepts one, otherwise nothing. Callers keep building the
+ * wrapper (response capture, header override); this only decides whether it
+ * reaches the adapter.
+ */
+export function providerRequestFetch(
+ api: Api | undefined,
+ fetchFn: FetchFunction | undefined,
+): FetchFunction | undefined {
+ return adapterAcceptsCustomFetch(api) ? fetchFn : undefined;
+}
+
/** Map a stored provider apiStyle onto a pi-ai wire API. Unknown styles fall
* back to OpenAI Chat Completions, the pre-apiStyle behavior. */
export function apiBindingForStyle(apiStyle?: string): ApiBinding {
diff --git a/packages/agent-runtime/src/provider-headers.test.ts b/packages/agent-runtime/src/provider-headers.test.ts
index d120f5aa6..1a73490d6 100644
--- a/packages/agent-runtime/src/provider-headers.test.ts
+++ b/packages/agent-runtime/src/provider-headers.test.ts
@@ -137,6 +137,39 @@ describe("withProviderHeaders", () => {
});
expect(base).toHaveBeenCalledOnce();
});
+
+ it("keeps the headers but drops the fetch for the Google adapters", () => {
+ const base = vi.fn(async () => new Response("ok"));
+ const result = withProviderHeaders(
+ { headers: { "User-Agent": "pi-desktop/0.0.0" }, fetch: base },
+ { "X-Gateway": "1" },
+ "google-generative-ai",
+ );
+
+ expect(result.headers).toMatchObject({
+ "User-Agent": "pi-desktop/0.0.0",
+ "X-Gateway": "1",
+ });
+ expect(result.fetch).toBeUndefined();
+ expect(base).not.toHaveBeenCalled();
+ });
+
+ it("clears an inherited fetch for a Google adapter with no header override", () => {
+ const base = vi.fn(async () => new Response("ok"));
+
+ const result = withProviderHeaders({ fetch: base }, undefined, "google-generative-ai");
+
+ expect(result.fetch).toBeUndefined();
+ expect(base).not.toHaveBeenCalled();
+ });
+
+ it("returns the caller's options untouched for every other adapter", () => {
+ const base = vi.fn(async () => new Response("ok"));
+ const options = { fetch: base };
+
+ expect(withProviderHeaders(options, undefined, "openai-completions")).toBe(options);
+ expect(withProviderHeaders(options, {}, "anthropic-messages")).toBe(options);
+ });
});
describe("runWithProviderHeaders", () => {
diff --git a/packages/agent-runtime/src/provider-headers.ts b/packages/agent-runtime/src/provider-headers.ts
index db71ad85d..1de2d41f0 100644
--- a/packages/agent-runtime/src/provider-headers.ts
+++ b/packages/agent-runtime/src/provider-headers.ts
@@ -18,7 +18,13 @@
import { AsyncLocalStorage } from "node:async_hooks";
import { HEADER_VALUE_MAX_BYTES, inspectHeaderValue } from "@pi-desktop/shared";
-import type { FetchFunction, ProviderHeaders, SimpleStreamOptions } from "@earendil-works/pi-ai";
+import type {
+ Api,
+ FetchFunction,
+ ProviderHeaders,
+ SimpleStreamOptions,
+} from "@earendil-works/pi-ai";
+import { adapterAcceptsCustomFetch } from "./provider-binding.js";
export const PROVIDER_HEADERS_MAX = 32;
export const PROVIDER_HEADER_KEY_MAX_BYTES = 256;
@@ -183,15 +189,29 @@ export function withProviderHeadersFetch(
export function withProviderHeaders(
options: SimpleStreamOptions | undefined,
headers: Record<string, string> | undefined,
+ api?: Api,
): SimpleStreamOptions {
+ const acceptsFetch = adapterAcceptsCustomFetch(api);
const normalized = normalizeProviderHeaders(headers);
- if (!normalized) return options ?? {};
+ if (!normalized) {
+ // The refusal is about the `fetch` alone, so it holds even when this row
+ // has no header override to merge.
+ if (acceptsFetch || !options || options.fetch === undefined) return options ?? {};
+ return { ...options, fetch: undefined };
+ }
const merged = mergeProviderHeaders(options?.headers, normalized);
- const fetch = withProviderHeadersFetch(options?.fetch, normalized);
+ // The wrapper is the last writer for adapters that read their headers from
+ // the request, but pi-ai's Google adapters reject any `fetch` that is not
+ // `globalThis.fetch` (issue #1072). They keep the merged `headers` above —
+ // which their adapter forwards to the SDK client verbatim — and inherit no
+ // fetch at all, so a caller-supplied one is cleared instead of wrapped.
+ const fetch = acceptsFetch
+ ? withProviderHeadersFetch(options?.fetch, normalized)
+ : undefined;
return {
...(options ?? {}),
...(merged ? { headers: merged } : {}),
- ...(fetch ? { fetch } : {}),
+ ...(acceptsFetch ? (fetch ? { fetch } : {}) : { fetch: undefined }),
};
}
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 04836eaba..8339bd109 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -10070,3 +10070,85 @@ describe("DesktopAgentRuntime delegation wait settlement safety", () => {
}
}, 1_000);
});
+
+/**
+ * The Google adapters reject any `fetch` that is not `globalThis.fetch`, so a
+ * turn bound for them must reach the adapter without one while still carrying
+ * the provider's own headers (issue #1072).
+ */
+describe("DesktopAgentRuntime Google Generative AI transport (#1072)", () => {
+ it("streams a turn through the native endpoint with the provider's headers", async () => {
+ const googleProvider: RuntimeProviderConfig = {
+ ...provider,
+ id: "google",
+ name: "Google Gemini",
+ vendorKey: "google",
+ apiStyle: "google_generative_ai",
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",
+ modelId: "gemini-3.8-flash",
+ apiKey: "AIza-test",
+ authKind: "api_key",
+ headers: { "X-Team": "platform" },
+ modelConfig: {
+ source: "generic",
+ name: "Gemini 3.8 Flash",
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",
+ reasoning: true,
+ input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 1_000_000,
+ maxTokens: 65_536,
+ },
+ };
+ const runtime = createRuntime({ provider: googleProvider, thinkingLevel: "off" });
+ const agent = (runtime as any).agent;
+ const requests: Array<{ url: string; headers: Record<string, string> }> = [];
+ vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
+ const headers: Record<string, string> = {};
+ new Headers(init?.headers).forEach((value, key) => {
+ headers[key.toLowerCase()] = value;
+ });
+ requests.push({
+ url: input instanceof Request ? input.url : String(input),
+ headers,
+ });
+ const chunk = (body: unknown) => `data: ${JSON.stringify(body)}\n\n`;
+ return new Response(
+ chunk({
+ candidates: [{ content: { role: "model", parts: [{ text: "hello" }] }, index: 0 }],
+ }) +
+ chunk({
+ candidates: [
+ { content: { role: "model", parts: [] }, finishReason: "STOP", index: 0 },
+ ],
+ usageMetadata: { promptTokenCount: 3, candidatesTokenCount: 1, totalTokenCount: 4 },
+ }),
+ { status: 200, headers: { "content-type": "text/event-stream" } },
+ );
+ });
+
+ try {
+ const stream = agent.streamFunction(
+ agent.state.model,
+ {
+ systemPrompt: "system",
+ messages: [{ role: "user", content: "hello", timestamp: Date.now() }],
+ tools: [],
+ },
+ {},
+ );
+ const result = await stream.result();
+
+ expect(result.stopReason).toBe("stop");
+ expect(result.content).toEqual([{ type: "text", text: "hello" }]);
+ expect(requests).toHaveLength(1);
+ expect(requests[0].url).toBe(
+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse",
+ );
+ expect(requests[0].headers["x-team"]).toBe("platform");
+ } finally {
+ vi.unstubAllGlobals();
+ await runtime.dispose();
+ }
+ }, 20_000);
+});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 6165034cd..7ce1a2cf6 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -147,6 +147,7 @@ import {
createExtensionAgentModels,
createProviderModels,
DEFAULT_CONTEXT_WINDOW,
+ providerRequestFetch,
providerRequestKey,
type RuntimeProviderConfig,
} from "./provider-binding.js";
@@ -1897,21 +1898,24 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// failed response separately so a 429 can honor Retry-After headers,
// and capture the transport cause of a rejection while the original
// Error still exists (issue #234).
- fetch: captureProviderResponse(
- options?.fetch,
- (response, requestBytes, failure) => {
- this.providerResponseStatus = response?.status;
- this.providerRequestBytes = requestBytes;
- this.providerFetchFailure = failure;
- if (failure) this.recoverProviderTransport(failure);
- // A gateway 502/503 can also state Retry-After, so keep headers
- // for every status whose delay is usable, not only for 429.
- this.providerRetryHeaders = carriesRetryDelayHeaders(
- response?.status,
- )
- ? response?.headers
- : undefined;
- },
+ fetch: providerRequestFetch(
+ m.api,
+ captureProviderResponse(
+ options?.fetch,
+ (response, requestBytes, failure) => {
+ this.providerResponseStatus = response?.status;
+ this.providerRequestBytes = requestBytes;
+ this.providerFetchFailure = failure;
+ if (failure) this.recoverProviderTransport(failure);
+ // A gateway 502/503 can also state Retry-After, so keep headers
+ // for every status whose delay is usable, not only for 429.
+ this.providerRetryHeaders = carriesRetryDelayHeaders(
+ response?.status,
+ )
+ ? response?.headers
+ : undefined;
+ },
+ ),
),
onResponse: async (response, responseModel) => {
this.providerResponseStatus = response.status;
@@ -1927,6 +1931,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
copilotRequestHeaders(this.provider, context),
this.provider.headers,
),
+ m.api,
);
const hookedOptions = this.withExtensionProviderHooks(requestOptions, m);
// The watchdog must be able to *stop* what it abandons. It wraps the
diff --git a/packages/agent-runtime/src/subagent-model-binding.ts b/packages/agent-runtime/src/subagent-model-binding.ts
index 2a02857d6..4f2448704 100644
--- a/packages/agent-runtime/src/subagent-model-binding.ts
+++ b/packages/agent-runtime/src/subagent-model-binding.ts
@@ -2,6 +2,7 @@ import {
buildProviderModel,
copilotRequestHeaders,
createProviderModels,
+ providerRequestFetch,
providerRequestKey,
type RuntimeProviderConfig,
} from "./provider-binding.js";
@@ -71,15 +72,18 @@ export function subagentModelBinding(opts: {
maxTokens: clampOutputToContext(m, context, options?.maxTokens),
maxRetries: 0,
sessionId: opts.sessionId,
- fetch: captureProviderResponse(options?.fetch, (response, _bytes, failure) => {
- retry.failure = failure;
- retry.status = response?.status;
- retry.headers = carriesRetryDelayHeaders(
- response?.status,
- )
- ? response?.headers
- : undefined;
- }),
+ fetch: providerRequestFetch(
+ m.api,
+ captureProviderResponse(options?.fetch, (response, _bytes, failure) => {
+ retry.failure = failure;
+ retry.status = response?.status;
+ retry.headers = carriesRetryDelayHeaders(
+ response?.status,
+ )
+ ? response?.headers
+ : undefined;
+ }),
+ ),
},
{
...openCodeEndpointFromProvider(opts.provider, m),
@@ -90,6 +94,7 @@ export function subagentModelBinding(opts: {
copilotRequestHeaders(opts.provider, context),
opts.provider.headers,
),
+ m.api,
);
return createProviderRetryStream(
m,