Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.
TypeScript agentai-agentai-agentsai-assistantandroidautomationchatgptcoding-agentcomputer-usedesktop-appelectronllmlocal-firstmcpmulti-agentollamaopenaiprivacyself-hostedtypescript
fix(agent): surface Google gateway errors during streaming
juemimgcd453675f3ddd2
diff --git a/packages/agent/test/google-stream-error.test.ts b/packages/agent/test/google-stream-error.test.tsnew file mode 100644index 0000000..57b02c7--- /dev/null+++ b/packages/agent/test/google-stream-error.test.ts@@ -0,0 +1,20 @@+import { GoogleGenAI } from "@google/genai";+import { afterEach, expect, it, vi } from "vitest";++afterEach(() => vi.unstubAllGlobals());++it.each([+ 'data: {"error":{"code":400,"message":"Unexpected message role."}}',+ 'event: error\ndata: {"message":"Unexpected message role."}',+])("surfaces a Google gateway error inside an HTTP 200 stream: %s", async (event) => {+ vi.stubGlobal(+ "fetch",+ async () => new Response(`${event}\n\n`, { headers: { "content-type": "text/event-stream" } }),+ );+ const sdk = new GoogleGenAI({ apiKey: "test-key" });+ const stream = await sdk.models.generateContentStream({ model: "gemini-test", contents: "hi" });+ await expect(stream.next()).rejects.toMatchObject({+ status: 200,+ message: "HTTP 200: Unexpected message role.",+ });+});diff --git a/patches/@[email protected] b/patches/@[email protected]new file mode 100644index 0000000..5c28571--- /dev/null+++ b/patches/@[email protected]@@ -0,0 +1,210 @@+diff --git a/dist/index.cjs b/dist/index.cjs+--- a/dist/index.cjs++++ b/dist/index.cjs+@@ -8434,6 +8434,14 @@+ const eventString = buffer.substring(0, delimiterIndex);+ buffer = buffer.substring(delimiterIndex + delimiterLength);+ const trimmedEvent = eventString.trim();++ // Gateways may send an explicit SSE error event, with a nested or flat JSON payload.++ if (/^event: ?error[ \t]*\r?$/m.test(eventString)) {++ const data = eventString.split(/\r\n|[\r\n]/).filter(line => line.startsWith(dataPrefix))++ .map(line => line.slice(dataPrefix.length).replace(/^ /, '')).join('\n');++ let payload;++ try { payload = JSON.parse(data); } catch { /* Keep malformed error payloads out of diagnostics. */ }++ throw googleStreamError(response.status, payload?.error ?? payload);++ }+ if (trimmedEvent.startsWith(dataPrefix)) {+ const processedChunkString = trimmedEvent+ .substring(dataPrefix.length)+@@ -8657,6 +8665,11 @@+ }+ return uploadUrl;+ }++}++// Preserve the HTTP status of the stream rather than treating a provider's application code as HTTP.++function googleStreamError(status, error) {++ const message = typeof error?.message === 'string' ? error.message : 'Provider stream error';++ return new ApiError({ status, message: `HTTP ${status}: ${message}` });+ }+ async function throwErrorIfNotOK(response) {+ var _a;+@@ -22102,7 +22115,10 @@+ _c = apiResponse_2_1.value;+ _d = false;+ const chunk = _c;+- const resp = generateContentResponseFromMldev((yield __await(chunk.json())), params);++ const data = yield __await(chunk.json());++ // The generated model-response converter drops error envelopes as unknown fields.++ if (data?.error) throw googleStreamError(chunk.responseInternal.status, data.error);++ const resp = generateContentResponseFromMldev(data, params);+ resp['sdkHttpResponse'] = {+ headers: chunk.headers,+ };+diff --git a/dist/index.mjs b/dist/index.mjs+--- a/dist/index.mjs++++ b/dist/index.mjs+@@ -8432,6 +8432,14 @@+ const eventString = buffer.substring(0, delimiterIndex);+ buffer = buffer.substring(delimiterIndex + delimiterLength);+ const trimmedEvent = eventString.trim();++ // Gateways may send an explicit SSE error event, with a nested or flat JSON payload.++ if (/^event: ?error[ \t]*\r?$/m.test(eventString)) {++ const data = eventString.split(/\r\n|[\r\n]/).filter(line => line.startsWith(dataPrefix))++ .map(line => line.slice(dataPrefix.length).replace(/^ /, '')).join('\n');++ let payload;++ try { payload = JSON.parse(data); } catch { /* Keep malformed error payloads out of diagnostics. */ }++ throw googleStreamError(response.status, payload?.error ?? payload);++ }+ if (trimmedEvent.startsWith(dataPrefix)) {+ const processedChunkString = trimmedEvent+ .substring(dataPrefix.length)+@@ -8655,6 +8663,11 @@+ }+ return uploadUrl;+ }++}++// Preserve the HTTP status of the stream rather than treating a provider's application code as HTTP.++function googleStreamError(status, error) {++ const message = typeof error?.message === 'string' ? error.message : 'Provider stream error';++ return new ApiError({ status, message: `HTTP ${status}: ${message}` });+ }+ async function throwErrorIfNotOK(response) {+ var _a;+@@ -22100,7 +22113,10 @@+ _c = apiResponse_2_1.value;+ _d = false;+ const chunk = _c;+- const resp = generateContentResponseFromMldev((yield __await(chunk.json())), params);++ const data = yield __await(chunk.json());++ // The generated model-response converter drops error envelopes as unknown fields.++ if (data?.error) throw googleStreamError(chunk.responseInternal.status, data.error);++ const resp = generateContentResponseFromMldev(data, params);+ resp['sdkHttpResponse'] = {+ headers: chunk.headers,+ };+diff --git a/dist/node/index.cjs b/dist/node/index.cjs+--- a/dist/node/index.cjs++++ b/dist/node/index.cjs+@@ -13863,6 +13863,14 @@+ const eventString = buffer.substring(0, delimiterIndex);+ buffer = buffer.substring(delimiterIndex + delimiterLength);+ const trimmedEvent = eventString.trim();++ // Gateways may send an explicit SSE error event, with a nested or flat JSON payload.++ if (/^event: ?error[ \t]*\r?$/m.test(eventString)) {++ const data = eventString.split(/\r\n|[\r\n]/).filter(line => line.startsWith(dataPrefix))++ .map(line => line.slice(dataPrefix.length).replace(/^ /, '')).join('\n');++ let payload;++ try { payload = JSON.parse(data); } catch { /* Keep malformed error payloads out of diagnostics. */ }++ throw googleStreamError(response.status, payload?.error ?? payload);++ }+ if (trimmedEvent.startsWith(dataPrefix)) {+ const processedChunkString = trimmedEvent+ .substring(dataPrefix.length)+@@ -14086,6 +14094,11 @@+ }+ return uploadUrl;+ }++}++// Preserve the HTTP status of the stream rather than treating a provider's application code as HTTP.++function googleStreamError(status, error) {++ const message = typeof error?.message === 'string' ? error.message : 'Provider stream error';++ return new ApiError({ status, message: `HTTP ${status}: ${message}` });+ }+ async function throwErrorIfNotOK(response) {+ var _a;+@@ -15857,7 +15870,10 @@+ _c = apiResponse_2_1.value;+ _d = false;+ const chunk = _c;+- const resp = generateContentResponseFromMldev((yield __await(chunk.json())), params);++ const data = yield __await(chunk.json());++ // The generated model-response converter drops error envelopes as unknown fields.++ if (data?.error) throw googleStreamError(chunk.responseInternal.status, data.error);++ const resp = generateContentResponseFromMldev(data, params);+ resp['sdkHttpResponse'] = {+ headers: chunk.headers,+ };+diff --git a/dist/node/index.mjs b/dist/node/index.mjs+--- a/dist/node/index.mjs++++ b/dist/node/index.mjs+@@ -13841,6 +13841,14 @@+ const eventString = buffer.substring(0, delimiterIndex);+ buffer = buffer.substring(delimiterIndex + delimiterLength);+ const trimmedEvent = eventString.trim();++ // Gateways may send an explicit SSE error event, with a nested or flat JSON payload.++ if (/^event: ?error[ \t]*\r?$/m.test(eventString)) {++ const data = eventString.split(/\r\n|[\r\n]/).filter(line => line.startsWith(dataPrefix))++ .map(line => line.slice(dataPrefix.length).replace(/^ /, '')).join('\n');++ let payload;++ try { payload = JSON.parse(data); } catch { /* Keep malformed error payloads out of diagnostics. */ }++ throw googleStreamError(response.status, payload?.error ?? payload);++ }+ if (trimmedEvent.startsWith(dataPrefix)) {+ const processedChunkString = trimmedEvent+ .substring(dataPrefix.length)+@@ -14064,6 +14072,11 @@+ }+ return uploadUrl;+ }++}++// Preserve the HTTP status of the stream rather than treating a provider's application code as HTTP.++function googleStreamError(status, error) {++ const message = typeof error?.message === 'string' ? error.message : 'Provider stream error';++ return new ApiError({ status, message: `HTTP ${status}: ${message}` });+ }+ async function throwErrorIfNotOK(response) {+ var _a;+@@ -15835,7 +15848,10 @@+ _c = apiResponse_2_1.value;+ _d = false;+ const chunk = _c;+- const resp = generateContentResponseFromMldev((yield __await(chunk.json())), params);++ const data = yield __await(chunk.json());++ // The generated model-response converter drops error envelopes as unknown fields.++ if (data?.error) throw googleStreamError(chunk.responseInternal.status, data.error);++ const resp = generateContentResponseFromMldev(data, params);+ resp['sdkHttpResponse'] = {+ headers: chunk.headers,+ };+diff --git a/dist/web/index.mjs b/dist/web/index.mjs+--- a/dist/web/index.mjs++++ b/dist/web/index.mjs+@@ -13833,6 +13833,14 @@+ const eventString = buffer.substring(0, delimiterIndex);+ buffer = buffer.substring(delimiterIndex + delimiterLength);+ const trimmedEvent = eventString.trim();++ // Gateways may send an explicit SSE error event, with a nested or flat JSON payload.++ if (/^event: ?error[ \t]*\r?$/m.test(eventString)) {++ const data = eventString.split(/\r\n|[\r\n]/).filter(line => line.startsWith(dataPrefix))++ .map(line => line.slice(dataPrefix.length).replace(/^ /, '')).join('\n');++ let payload;++ try { payload = JSON.parse(data); } catch { /* Keep malformed error payloads out of diagnostics. */ }++ throw googleStreamError(response.status, payload?.error ?? payload);++ }+ if (trimmedEvent.startsWith(dataPrefix)) {+ const processedChunkString = trimmedEvent+ .substring(dataPrefix.length)+@@ -14056,6 +14064,11 @@+ }+ return uploadUrl;+ }++}++// Preserve the HTTP status of the stream rather than treating a provider's application code as HTTP.++function googleStreamError(status, error) {++ const message = typeof error?.message === 'string' ? error.message : 'Provider stream error';++ return new ApiError({ status, message: `HTTP ${status}: ${message}` });+ }+ async function throwErrorIfNotOK(response) {+ var _a;+@@ -15827,7 +15840,10 @@+ _c = apiResponse_2_1.value;+ _d = false;+ const chunk = _c;+- const resp = generateContentResponseFromMldev((yield __await(chunk.json())), params);++ const data = yield __await(chunk.json());++ // The generated model-response converter drops error envelopes as unknown fields.++ if (data?.error) throw googleStreamError(chunk.responseInternal.status, data.error);++ const resp = generateContentResponseFromMldev(data, params);+ resp['sdkHttpResponse'] = {+ headers: chunk.headers,+ };diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 06d0997..7ce294b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -166,6 +166,7 @@ patchedDependencies:'@anthropic-ai/[email protected]': b30ed35336aede795bedd4e651cc54d3c93b818bd38dd5051c778daae26a9f12'@earendil-works/[email protected]': 3691afa4875910ec216409e7896bf3859b8041e517e37339facd2b00194b417f'@earendil-works/[email protected]': 2e7563dfdc2703ef056fe67014c68e7417d2c6065c6ef0e2bc785bd111cffe58+ '@google/[email protected]': 6d817f39ca09a0815eded16f5cb38c25074a80642029e60b17dbd730693d383b[email protected]: 27113f8e7a6de1306d9235b43dd257cb22e07d63bbe0b85c9bbe25fef00d34ccimporters:@@ -237,7 +238,7 @@ importers:version: 1.4.0(patch_hash=2e7563dfdc2703ef056fe67014c68e7417d2c6065c6ef0e2bc785bd111cffe58)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])'@google/genai':specifier: 2.21.0- version: 2.21.0([email protected])+ version: 2.21.0(patch_hash=6d817f39ca09a0815eded16f5cb38c25074a80642029e60b17dbd730693d383b)([email protected])'@modelcontextprotocol/client':specifier: 2.3.1version: 2.3.1@@ -805,7 +806,7 @@ importers:version: 1.4.0(patch_hash=2e7563dfdc2703ef056fe67014c68e7417d2c6065c6ef0e2bc785bd111cffe58)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])'@google/genai':specifier: 2.21.0- version: 2.21.0([email protected])+ version: 2.21.0(patch_hash=6d817f39ca09a0815eded16f5cb38c25074a80642029e60b17dbd730693d383b)([email protected])'@modelcontextprotocol/client':specifier: 2.3.1version: 2.3.1@@ -9909,7 +9910,7 @@ snapshots:'@anthropic-ai/sdk': 0.129.0([email protected])'@aws-sdk/client-bedrock-runtime': 3.1127.0'@earendil-works/pi-telemetry': 1.4.0- '@google/genai': 2.21.0([email protected])+ '@google/genai': 2.21.0(patch_hash=6d817f39ca09a0815eded16f5cb38c25074a80642029e60b17dbd730693d383b)([email protected])'@smithy/node-http-handler': 4.12.1http-proxy-agent: 9.1.0([email protected])https-proxy-agent: 9.1.0([email protected])@@ -10720,7 +10721,7 @@ snapshots:lodash.isundefined: 3.0.1lodash.uniq: 4.5.0- '@google/[email protected]([email protected])':+ '@google/[email protected](patch_hash=6d817f39ca09a0815eded16f5cb38c25074a80642029e60b17dbd730693d383b)([email protected])':dependencies:google-auth-library: 10.9.1([email protected])p-retry: 4.6.2diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 31c98b0..9905923 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -27,6 +27,7 @@ ignoredOptionalDependencies:- '@napi-rs/canvas'patchedDependencies:+ '@google/[email protected]': patches/@[email protected]'@earendil-works/[email protected]': patches/@[email protected]'@anthropic-ai/[email protected]': patches/@[email protected]'@earendil-works/[email protected]': patches/@[email protected]