pi-gemini-app 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # `pi-gemini-app` — Google Gemini App Provider for Pi
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/pi-gemini-app?logo=npm&label=pi-gemini-app)](https://www.npmjs.com/package/pi-gemini-app)
4
+ [![Pi Packages](https://img.shields.io/badge/Pi%20Packages-pi--gemini--app-6366F1)](https://pi.dev/packages/pi-gemini-app?name=pi-gemini-app)
5
+
3
6
  ![pi-gemini-app — Native Pi Extension for Gemini Neon over Direct HTTP/2](https://raw.githubusercontent.com/ShawTim/gemini-app2api/main/docs/assets/pi-extension.jpg)
4
7
 
5
8
  Native in-process provider extension for `@earendil-works/pi-coding-agent` (`pi`) and GooeyPi. Connects directly to Gemini's native HTTP/2 endpoint (`ProcessQuery`) inside the Pi process—no separate HTTP gateway server, Docker container, or extra npm runtime dependencies required.
@@ -1,5 +1,6 @@
1
1
  import { createGeminiOAuthAuth } from './auth.js';
2
2
  import { createGeminiStreamHandler } from './stream.js';
3
+ import { MODEL_SPECS } from '../../src/openai-contract.mjs';
3
4
  import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
4
5
  import { decodeUsageInfo as defaultDecodeUsageInfo } from '../../src/gateway/quota.mjs';
5
6
  import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
@@ -25,81 +26,30 @@ export function filterGeminiModels(models, credential) {
25
26
  return models;
26
27
  }
27
28
 
28
- export const MODELS = Object.freeze([
29
- {
30
- id: 'gemini-neon',
31
- name: 'Gemini Neon',
32
- api: API_ID,
33
- provider: PROVIDER_ID,
34
- baseUrl: BASE_URL,
35
- type: 'chat',
36
- contextWindow: 512000,
37
- maxTokens: 16384,
38
- input: ['text', 'image'],
39
- reasoning: true,
40
- thinkingLevelMap: {
41
- minimal: 'minimal',
42
- low: 'low',
43
- medium: 'medium',
44
- high: 'high',
45
- xhigh: 'xhigh',
46
- },
47
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
48
- },
49
- {
50
- id: 'gemini-hydrogen',
51
- name: 'Gemini Hydrogen',
52
- api: API_ID,
53
- provider: PROVIDER_ID,
54
- baseUrl: BASE_URL,
55
- type: 'chat',
56
- contextWindow: 512000,
57
- maxTokens: 16384,
58
- input: ['text', 'image'],
59
- reasoning: true,
60
- thinkingLevelMap: {
61
- minimal: 'minimal',
62
- low: 'low',
63
- medium: 'medium',
64
- high: 'high',
65
- xhigh: 'xhigh',
66
- },
67
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
68
- },
69
- {
70
- id: 'gemini-flash-lite',
71
- name: 'Gemini Flash Lite',
72
- api: API_ID,
73
- provider: PROVIDER_ID,
74
- baseUrl: BASE_URL,
75
- type: 'chat',
76
- contextWindow: 128000,
77
- maxTokens: 8192,
78
- input: ['text', 'image'],
79
- reasoning: true,
80
- thinkingLevelMap: {
81
- minimal: 'minimal',
82
- low: 'low',
83
- medium: 'medium',
84
- high: 'high',
85
- xhigh: 'xhigh',
86
- },
87
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
88
- },
89
- {
90
- id: 'gemini-auto',
91
- name: 'Gemini Auto',
29
+ const PI_THINKING_LEVEL_MAP = Object.freeze({
30
+ minimal: 'minimal',
31
+ low: 'low',
32
+ medium: 'medium',
33
+ high: 'high',
34
+ xhigh: 'xhigh',
35
+ });
36
+
37
+ export const MODELS = Object.freeze(
38
+ Object.entries(MODEL_SPECS).map(([id, spec]) => ({
39
+ id,
40
+ name: spec.name,
92
41
  api: API_ID,
93
42
  provider: PROVIDER_ID,
94
43
  baseUrl: BASE_URL,
95
44
  type: 'chat',
96
- contextWindow: 128000,
97
- maxTokens: 8192,
45
+ contextWindow: spec.contextWindow,
46
+ maxTokens: spec.maxTokens,
98
47
  input: ['text', 'image'],
99
- reasoning: false,
48
+ reasoning: spec.reasoning,
49
+ ...(spec.reasoning ? { thinkingLevelMap: { ...PI_THINKING_LEVEL_MAP } } : {}),
100
50
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
101
- },
102
- ]);
51
+ })),
52
+ );
103
53
 
104
54
  export function formatQuotaDisplay(usageInfo, subscriptionInfo) {
105
55
  const tier = subscriptionInfo?.tier;
@@ -3,7 +3,7 @@ import { createImageBlobCache } from '../../src/gateway/image-upload.mjs';
3
3
  import { NativeDirectProvider as DefaultNativeDirectProvider } from '../../src/native-provider.mjs';
4
4
  import { automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
5
5
  import { buildChatPayload as defaultBuildChatPayload } from './transcript.js';
6
- import { estimateUsage as defaultEstimateUsage } from '../../src/openai-usage.mjs';
6
+ import { estimateUsage as defaultEstimateUsage, measurePromptImagePayload } from '../../src/openai-usage.mjs';
7
7
 
8
8
  const PREFIX_BYTES = 2048;
9
9
 
@@ -239,6 +239,7 @@ export function createGeminiStreamHandler({
239
239
  let hasToolCalls = false;
240
240
 
241
241
  let promptChars = 0;
242
+ let imageCount = 0;
242
243
 
243
244
  function ensureTextBlock() {
244
245
  if (!textBlock) {
@@ -335,6 +336,7 @@ export function createGeminiStreamHandler({
335
336
  promptChars = Array.isArray(body?.messages)
336
337
  ? body.messages.reduce((n, m) => n + contentChars(m?.content), 0)
337
338
  : 0;
339
+ ({ imageCount } = measurePromptImagePayload(body));
338
340
 
339
341
  const authManager = {
340
342
  getValidAccessToken: async () => {
@@ -480,7 +482,7 @@ export function createGeminiStreamHandler({
480
482
  await startOutput({ flushAll: true });
481
483
  endTextBlock();
482
484
 
483
- const est = estimateUsage({ promptChars, outputBytes: publishedBytes });
485
+ const est = estimateUsage({ promptChars, imageCount, outputBytes: publishedBytes });
484
486
  partial.usage = {
485
487
  input: est.prompt_tokens,
486
488
  output: est.completion_tokens,
@@ -502,8 +504,8 @@ export function createGeminiStreamHandler({
502
504
  error?.code === 'NATIVE_TURN_ABORTED' ||
503
505
  error?.code === 'REQUEST_CANCELLED';
504
506
  const stopReason = isAborted ? 'aborted' : 'error';
505
- if (publishedBytes > 0 || promptChars > 0) {
506
- const est = estimateUsage({ promptChars, outputBytes: publishedBytes });
507
+ if (publishedBytes > 0 || promptChars > 0 || imageCount > 0) {
508
+ const est = estimateUsage({ promptChars, imageCount, outputBytes: publishedBytes });
507
509
  partial.usage = {
508
510
  input: est.prompt_tokens,
509
511
  output: est.completion_tokens,
@@ -4,7 +4,8 @@
4
4
  import { lengthDelimited as message, varintField, varint, parse, MAX_MESSAGE_BYTES } from './protobuf.mjs';
5
5
  import { TextDecoder } from 'node:util';
6
6
 
7
- export const NATIVE_VERSION = '1.131.4.1198';
7
+ export const NATIVE_VERSION = '1.135.1.1291';
8
+ export const GATEWAY_USER_AGENT = 'gemini-app2api/1.0';
8
9
  const utf8 = new TextDecoder('utf-8', { fatal: true });
9
10
  function text(value) {
10
11
  if (typeof value !== 'string') throw new TypeError('Expected string');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "In-process Google Gemini App provider extension for Pi (direct native HTTP/2, /login gemini-app, /gemini-quota, zero runtime dependencies).",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -2,7 +2,7 @@
2
2
  import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
3
3
  import { isVerifiedEmptyResponse } from './output-recovery.mjs';
4
4
  import { isExplicitQuotaFailure } from './quota-failover.mjs';
5
- const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON', 'TRUNCATED_TOOL_CALL', 'INVALID_TOOL_CALL',
5
+ export const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON', 'TRUNCATED_TOOL_CALL', 'INVALID_TOOL_CALL',
6
6
  'INVALID_TOOL_ARGUMENTS', 'UNDECLARED_TOOL', 'TOOL_ARGUMENT_SCHEMA_MISMATCH', 'TOOL_CHOICE_NOT_SATISFIED',
7
7
  'TOOL_CHOICE_MISMATCH', 'TOOL_CALL_NOT_ALLOWED', 'PARALLEL_TOOL_CALLS_DISABLED']);
8
8
  const STRUCTURED_OUTPUT_ERRORS = new Set(['INVALID_STRUCTURED_OUTPUT_JSON', 'STRUCTURED_OUTPUT_SCHEMA_MISMATCH']);
@@ -10,7 +10,7 @@ const TRANSPORT_ERRORS = new Set(['NATIVE_STREAM_RESET', 'NATIVE_CONNECTION_FAIL
10
10
  export function toolRecoveryInstruction(code) {
11
11
  if (TOOL_ERRORS.has(code)) {
12
12
  return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered and no caller tool was executed.]\n' +
13
- 'Answer the latest user request using the complete history. If a tool is needed and permitted, emit a complete tool_call block with exactly the keys "name" and "arguments" as valid JSON. Use only declared names and actual JSON-object arguments matching the original schema. Respect the selected tool choice and parallel-call restriction. Put both fences on separate lines. Do not invent tool results, duplicate already completed work, or discuss this recovery instruction. If tools are prohibited, answer normally without tool_call blocks.';
13
+ 'Answer the latest user request using the complete history. If a tool is needed and permitted, emit a complete tool_call block with exactly the keys "name" and "arguments" as valid JSON. Emit one strict JSON object per tool_call block with properly escaped strings (no raw newlines, invalid escapes, or trailing commas). Use only declared names and actual JSON-object arguments matching the original schema. Respect the selected tool choice and parallel-call restriction. Put both fences on separate lines. Do not invent tool results, duplicate already completed work, or discuss this recovery instruction. If tools are prohibited, answer normally without tool_call blocks.';
14
14
  }
15
15
  if (STRUCTURED_OUTPUT_ERRORS.has(code)) {
16
16
  return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered because it did not satisfy the required JSON output format.]\n' +
@@ -50,11 +50,17 @@ export function automaticRecoveryKind(error, model, { allowAutoModel = false } =
50
50
  if (error.status !== 502) return null;
51
51
  if (TRANSPORT_ERRORS.has(error.code) && ['open', 'read', 'decode', 'end'].includes(e.phase) &&
52
52
  (e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) && (e.grpcStatus === null || e.grpcStatus === 0)) return 'transport';
53
+ if (error.code === 'NATIVE_IMAGE_UPLOAD_RESET' && e.phase === 'upload' &&
54
+ e.upstreamHttpStatus === null && e.grpcStatus === null) return 'transport';
53
55
  const completed = e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 && e.wireEnded === true &&
54
56
  e.modelCompleted === true && modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
57
+ const earlyStoppedToolError = e.phase === 'validate' && e.toolErrorEarlyStop === true &&
58
+ (e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) &&
59
+ (e.grpcStatus === null || e.grpcStatus === 0) &&
60
+ modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
55
61
  if (completed && error.code === 'NATIVE_SOFT_ERROR_RESPONSE' && e.outputFailureReason === 'generic_error_offer' &&
56
62
  e.outputFailureSource === 'exact_text_signature' && e.outputToolCalls === 0 && e.nativeStructuredOutputPresent === false) return 'provider_soft_error';
57
- if (completed && TOOL_ERRORS.has(error.code)) return 'tool_protocol';
63
+ if ((completed || earlyStoppedToolError) && TOOL_ERRORS.has(error.code)) return 'tool_protocol';
58
64
  if (completed && STRUCTURED_OUTPUT_ERRORS.has(error.code)) return 'structured_output';
59
65
  // A clean but incomplete turn may be regenerated; never treat it as success.
60
66
  if (error.code === 'INCOMPLETE_NATIVE_RESPONSE' && e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 &&
@@ -5,6 +5,7 @@ import { isIP } from 'node:net';
5
5
  import { parseRemoteImageUrl, isPublicImageAddress } from '../image-url.mjs';
6
6
  import { decodeImageBytes, MAX_IMAGES, MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES } from '../image-input.mjs';
7
7
  import { protocolError, ProtocolError } from '../tool-protocol.mjs';
8
+ import { GATEWAY_USER_AGENT } from '../../native-wire/robin-current.mjs';
8
9
 
9
10
  const fail = (code, status = 400) => { throw protocolError(code, status); };
10
11
  const REDIRECTS = new Set([301, 302, 303, 307, 308]);
@@ -54,7 +55,7 @@ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 }
54
55
  if (limit <= 0) fail('IMAGES_TOO_LARGE', 413);
55
56
  req = request(url, {
56
57
  method: 'GET', agent: false, maxHeaderSize: 16384,
57
- headers: { accept: 'image/png, image/jpeg, image/webp', 'accept-encoding': 'identity', 'user-agent': 'gemini-app2api/1.0' },
58
+ headers: { accept: 'image/png, image/jpeg, image/webp', 'accept-encoding': 'identity', 'user-agent': GATEWAY_USER_AGENT },
58
59
  // Pin after validation; preserve original Host, SNI and certificate verification.
59
60
  lookup: (_host, options, callback) => callback(null, ...(options?.all ? [[pinned]] : [pinned.address, pinned.family])),
60
61
  }, incoming => {
@@ -2,9 +2,11 @@ import crypto from 'node:crypto';
2
2
  import { protocolError } from '../tool-protocol.mjs';
3
3
  import { MAX_IMAGES, MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES } from '../image-input.mjs';
4
4
  import { connectHttp2 } from './outbound-proxy.mjs';
5
+ import { GATEWAY_USER_AGENT } from '../../native-wire/robin-current.mjs';
5
6
 
6
7
  const ORIGIN = 'https://push.clients6.google.com';
7
8
  export const DEFAULT_UPLOAD_CONCURRENCY = 8;
9
+ export const DEFAULT_MAX_IN_FLIGHT_BYTES = 4 * 1024 * 1024;
8
10
  export const MAX_UPLOAD_TIMEOUT_MS = 600_000;
9
11
  const fail = (suffix, status = 502) => { throw protocolError(`NATIVE_IMAGE_UPLOAD_${suffix}`, status); };
10
12
  const mimeTypes = new Set(['image/png', 'image/jpeg', 'image/webp']);
@@ -81,7 +83,7 @@ function boundedLocation(value) {
81
83
  export async function uploadNativeImages(
82
84
  token,
83
85
  images,
84
- { signal, timeoutMs = 60000, concurrency = DEFAULT_UPLOAD_CONCURRENCY } = {},
86
+ { signal, timeoutMs = 60000, concurrency = DEFAULT_UPLOAD_CONCURRENCY, maxInFlightBytes = DEFAULT_MAX_IN_FLIGHT_BYTES, onUploaded } = {},
85
87
  { connect = connectHttp2 } = {},
86
88
  ) {
87
89
  validateImages(images);
@@ -97,15 +99,45 @@ export async function uploadNativeImages(
97
99
  !Number.isSafeInteger(concurrency) ||
98
100
  concurrency < 1 ||
99
101
  concurrency > 32 ||
102
+ !Number.isSafeInteger(maxInFlightBytes) ||
103
+ maxInFlightBytes < 1 ||
104
+ (onUploaded !== undefined && typeof onUploaded !== 'function') ||
100
105
  (signal !== undefined && (!signal || typeof signal.addEventListener !== 'function')) ||
101
106
  typeof connect !== 'function'
102
107
  ) fail('INVALID_RESPONSE');
103
108
  if (signal?.aborted) fail('CANCELLED', 499);
104
109
  const deadline = Date.now() + timeoutMs;
105
110
  let session, timeout, sessionFailed = false, batchError = null;
111
+ let inFlightBytes = 0, activeUploads = 0;
106
112
  const activeStops = new Set();
113
+ const budgetWaiters = [];
114
+ const wakeBudgetWaiters = () => {
115
+ while (budgetWaiters.length) {
116
+ const next = budgetWaiters[0];
117
+ if (activeUploads === 0 || inFlightBytes + next.bytes <= maxInFlightBytes || batchError || sessionFailed || signal?.aborted) {
118
+ budgetWaiters.shift();
119
+ next.resolve();
120
+ } else {
121
+ break;
122
+ }
123
+ }
124
+ };
125
+ const acquireByteBudget = async (bytes) => {
126
+ while (activeUploads > 0 && inFlightBytes + bytes > maxInFlightBytes && !batchError && !sessionFailed && !signal?.aborted) {
127
+ await new Promise(resolve => budgetWaiters.push({ bytes, resolve }));
128
+ }
129
+ ensureAlive();
130
+ activeUploads++;
131
+ inFlightBytes += bytes;
132
+ };
133
+ const releaseByteBudget = (bytes) => {
134
+ activeUploads = Math.max(0, activeUploads - 1);
135
+ inFlightBytes = Math.max(0, inFlightBytes - bytes);
136
+ wakeBudgetWaiters();
137
+ };
107
138
  const stopAll = (err) => {
108
139
  if (!batchError) batchError = err;
140
+ wakeBudgetWaiters();
109
141
  for (const stop of [...activeStops]) stop(err);
110
142
  };
111
143
  const abortCode = () => signal?.aborted ? ['CANCELLED', 499] : Date.now() >= deadline ? ['TIMEOUT', 504] : null;
@@ -167,22 +199,30 @@ export async function uploadNativeImages(
167
199
  });
168
200
  const onSessionError = () => { sessionFailed = true; stopAll(protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); };
169
201
  const uploadOne = async (image) => {
170
- ensureAlive();
171
- const initial = await request({ ':method': 'POST', ':path': '/upload/', authorization: `Bearer ${token}`, 'content-length': '0', 'push-id': 'feeds/mcudyrk2a4khkz', 'x-tenant-id': 'bard-storage', 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'start', 'x-goog-upload-content-type': image.mimeType, 'x-goog-upload-content-length': String(image.data.length), 'user-agent': 'gemini-app2api/1.0' }, null, 8192);
172
- if (String(initial.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'active') fail('INVALID_RESPONSE');
173
- const location = boundedLocation(initial.headers['x-goog-upload-url']);
174
- ensureAlive();
175
- const final = await request({ ':method': 'PUT', ':path': location.pathname + location.search, 'content-length': String(image.data.length), 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'upload, finalize', 'x-goog-upload-offset': '0', 'user-agent': 'gemini-app2api/1.0' }, image.data, 4096);
176
- if (String(final.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'final') fail('INVALID_RESPONSE');
177
- let blobId;
178
- try { blobId = new TextDecoder('utf-8', { fatal: true }).decode(final.body); } catch { fail('INVALID_RESPONSE'); }
179
- if (!blobId || Buffer.byteLength(blobId) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(blobId)) fail('INVALID_RESPONSE');
180
- ensureAlive();
181
- return { blobId, mimeType: image.mimeType };
202
+ await acquireByteBudget(image.data.length);
203
+ try {
204
+ ensureAlive();
205
+ const initial = await request({ ':method': 'POST', ':path': '/upload/', authorization: `Bearer ${token}`, 'content-length': '0', 'push-id': 'feeds/mcudyrk2a4khkz', 'x-tenant-id': 'bard-storage', 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'start', 'x-goog-upload-content-type': image.mimeType, 'x-goog-upload-content-length': String(image.data.length), 'user-agent': GATEWAY_USER_AGENT }, null, 8192);
206
+ if (String(initial.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'active') fail('INVALID_RESPONSE');
207
+ const location = boundedLocation(initial.headers['x-goog-upload-url']);
208
+ ensureAlive();
209
+ const final = await request({ ':method': 'PUT', ':path': location.pathname + location.search, 'content-length': String(image.data.length), 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'upload, finalize', 'x-goog-upload-offset': '0', 'user-agent': GATEWAY_USER_AGENT }, image.data, 4096);
210
+ if (String(final.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'final') fail('INVALID_RESPONSE');
211
+ let blobId;
212
+ try { blobId = new TextDecoder('utf-8', { fatal: true }).decode(final.body); } catch { fail('INVALID_RESPONSE'); }
213
+ if (!blobId || Buffer.byteLength(blobId) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(blobId)) fail('INVALID_RESPONSE');
214
+ ensureAlive();
215
+ return { blobId, mimeType: image.mimeType };
216
+ } finally {
217
+ releaseByteBudget(image.data.length);
218
+ }
182
219
  };
220
+ const onSignalAbort = () => wakeBudgetWaiters();
221
+ signal?.addEventListener('abort', onSignalAbort, { once: true });
183
222
  try {
184
223
  try { session = connect(ORIGIN, { settings: { enablePush: false, maxHeaderListSize: 8192 } }); } catch { fail('RESET'); }
185
224
  if (!session || typeof session.request !== 'function') fail('RESET');
225
+ try { session.socket?.setKeepAlive?.(true, 15_000); } catch {}
186
226
  session.on?.('error', onSessionError);
187
227
  session.on?.('close', onSessionError);
188
228
  timeout = setTimeout(() => { stopAll(protocolError('NATIVE_IMAGE_UPLOAD_TIMEOUT', 504)); try { session.destroy(); } catch {} }, Math.max(1, deadline - Date.now()));
@@ -194,7 +234,9 @@ export async function uploadNativeImages(
194
234
  const index = nextIndex++;
195
235
  if (index >= images.length) return;
196
236
  try {
197
- results[index] = await uploadOne(images[index]);
237
+ const uploaded = await uploadOne(images[index]);
238
+ results[index] = uploaded;
239
+ try { onUploaded?.(index, uploaded); } catch {}
198
240
  } catch (err) {
199
241
  stopAll(err);
200
242
  throw err;
@@ -212,6 +254,8 @@ export async function uploadNativeImages(
212
254
  fail('RESET');
213
255
  } finally {
214
256
  clearTimeout(timeout);
257
+ signal?.removeEventListener('abort', onSignalAbort);
258
+ wakeBudgetWaiters();
215
259
  try { session?.on?.('error', drainError); session?.removeListener?.('error', onSessionError); session?.removeListener?.('close', onSessionError); } catch {}
216
260
  try { session?.destroy(); } catch {}
217
261
  }
@@ -15,10 +15,11 @@ export const NATIVE_DIAGNOSTIC_LIMITS = Object.freeze({
15
15
  });
16
16
  const L = NATIVE_DIAGNOSTIC_LIMITS;
17
17
  const eventNames = new Set(['provider_stop', 'provider_cleanup', 'provider_success', 'provider_failure',
18
- 'early_stop_post_tool_hallucination', 'post_complete_idle_finish', 'post_complete_idle_timeout',
18
+ 'early_stop_post_tool_hallucination', 'early_stop_post_tool_error',
19
+ 'post_complete_idle_finish', 'post_complete_idle_timeout', 'post_tool_error_idle_finish',
19
20
  'post_tool_idle_timeout', 'post_output_idle_timeout',
20
21
  'transport_open', 'local_stream_close', 'local_session_destroy', 'local_signal_abort', 'local_cancel',
21
- 'transport_failure', 'transport_deadline', 'peer_headers', 'peer_trailers', 'peer_reset',
22
+ 'transport_failure', 'transport_deadline', 'transport_ping_timeout', 'peer_headers', 'peer_trailers', 'peer_reset',
22
23
  'peer_goaway', 'stream_error', 'stream_close', 'stream_end', 'peer_data', 'local_half_close',
23
24
  'peer_connection_end', 'peer_connection_close']);
24
25
  const numberKeys = new Set(['httpStatus', 'grpcStatus', 'rstCode', 'requestedCode', 'goawayCode',
@@ -91,6 +91,7 @@ export function safeNativeEvidence(value) {
91
91
  ...(bounded(value.outputToolCalls, 0, 32) !== null ? { outputToolCalls: value.outputToolCalls } : {}),
92
92
  ...(nativeCompletenessState !== null ? { nativeCompletenessState } : {}),
93
93
  ...(toolProtocolReason ? { toolProtocolReason } : {}),
94
+ ...(value.toolErrorEarlyStop === true ? { toolErrorEarlyStop: true } : {}),
94
95
  ...(emptyResponseReason ? { emptyResponseReason } : {}),
95
96
  ...(nativeTextBytes !== null ? { nativeTextBytes } : {}),
96
97
  ...(nativeShareableTextBytes !== null ? { nativeShareableTextBytes } : {}),
@@ -13,6 +13,8 @@ import {
13
13
  import {
14
14
  GrpcMessageReader,
15
15
  frameGrpcMessage,
16
+ NATIVE_VERSION,
17
+ GATEWAY_USER_AGENT,
16
18
  } from "../../native-wire/robin-current.mjs";
17
19
  import { fault } from "./oauth-client-defaults.mjs";
18
20
  import { PROMPT_MAX_BYTES } from "../openai-contract.mjs";
@@ -20,6 +22,7 @@ import { NATIVE_RESPONSE_LIMITS as RESPONSE_LIMITS } from './native-response-lim
20
22
  import { observeNative } from './native-diagnostic.mjs';
21
23
  import { connectHttp2 } from './outbound-proxy.mjs';
22
24
  export const DEFAULT_HTTP2_PING_INTERVAL_MS = 15_000;
25
+ export const DEFAULT_HTTP2_PING_TIMEOUT_MS = 30_000;
23
26
  export const MIN_CONNECT_ATTEMPT_TIMEOUT_MS = 5000;
24
27
  // Node v22 defaults Happy Eyeballs per-family attempt timeout to 250ms, which aborts
25
28
  // IPv4 connects over high-RTT VPN tunnels when IPv6 returns immediate EHOSTUNREACH.
@@ -36,9 +39,9 @@ ensureConnectAttemptTimeout();
36
39
  export const NATIVE_ORIGIN = "https://robinfrontend-pa.googleapis.com";
37
40
  export const NATIVE_RPC =
38
41
  "/assistant.mobile.robin.RobinService/ProcessQuery";
39
- // ProcessQuery compatibility snapshot checked against native 1.135.1.1291.
42
+ // ProcessQuery compatibility snapshot shared with native-wire/robin-current.mjs.
40
43
  // A protocol constant, not a runtime App dependency or copied device identity.
41
- export const NATIVE_COMPATIBILITY_VERSION = "1.135.1.1291";
44
+ export const NATIVE_COMPATIBILITY_VERSION = NATIVE_VERSION;
42
45
  export function openDirectTurn(
43
46
  token,
44
47
  {
@@ -51,6 +54,7 @@ export function openDirectTurn(
51
54
  continuation,
52
55
  timeoutMs = 180000,
53
56
  pingIntervalMs = DEFAULT_HTTP2_PING_INTERVAL_MS,
57
+ pingTimeoutMs = DEFAULT_HTTP2_PING_TIMEOUT_MS,
54
58
  signal,
55
59
  allowNativeTools = false,
56
60
  emitHeaders = false,
@@ -114,7 +118,9 @@ export function openDirectTurn(
114
118
  request,
115
119
  timer,
116
120
  pingTimer = null,
121
+ pingAckTimer = null,
117
122
  pingInFlight = false,
123
+ lastInboundAt = Date.now(),
118
124
  closed = false,
119
125
  ended = false,
120
126
  error = null,
@@ -150,6 +156,10 @@ export function openDirectTurn(
150
156
  clearInterval(pingTimer);
151
157
  pingTimer = null;
152
158
  }
159
+ if (pingAckTimer) {
160
+ clearTimeout(pingAckTimer);
161
+ pingAckTimer = null;
162
+ }
153
163
  pingInFlight = false;
154
164
  };
155
165
  const stop = () => {
@@ -286,13 +296,60 @@ export function openDirectTurn(
286
296
  client.on("error", () => fail("NATIVE_CONNECTION_FAILED"));
287
297
  if (diagnostic) client.on('goaway', code => note('peer_goaway', { goawayCode: code }));
288
298
  if (Number.isInteger(pingIntervalMs) && pingIntervalMs > 0 && typeof client.ping === "function") {
299
+ let pingSeq = 0, activePingSeq = 0;
289
300
  pingTimer = setInterval(() => {
290
- if (closed || ended || client.closed || client.destroyed || pingInFlight) return;
301
+ if (closed || ended || client.closed || client.destroyed || client.connecting || pingInFlight) return;
302
+ const seq = ++pingSeq;
303
+ activePingSeq = seq;
304
+ const pingStartedAt = Date.now();
291
305
  pingInFlight = true;
306
+ let pingQueued = true;
307
+ let sent = false;
292
308
  try {
293
- client.ping(() => { pingInFlight = false; });
309
+ sent = client.ping((err) => {
310
+ if (!pingQueued || seq !== activePingSeq) return;
311
+ if (pingAckTimer) {
312
+ clearTimeout(pingAckTimer);
313
+ pingAckTimer = null;
314
+ }
315
+ pingInFlight = false;
316
+ if (closed || ended) return;
317
+ if (err) {
318
+ if (err.code === 'ERR_HTTP2_PING_CANCEL') return;
319
+ note('transport_ping_timeout');
320
+ fail('NATIVE_CONNECTION_FAILED');
321
+ return;
322
+ }
323
+ lastInboundAt = Date.now();
324
+ });
294
325
  } catch {
326
+ pingQueued = false;
327
+ if (activePingSeq === seq) activePingSeq = 0;
328
+ pingInFlight = false;
329
+ return;
330
+ }
331
+ if (sent === false) {
332
+ pingQueued = false;
333
+ if (activePingSeq === seq) activePingSeq = 0;
295
334
  pingInFlight = false;
335
+ return;
336
+ }
337
+ if (Number.isInteger(pingTimeoutMs) && pingTimeoutMs > 0 && !closed && !ended && pingInFlight && activePingSeq === seq) {
338
+ const armAckWatchdog = (delayMs) => {
339
+ pingAckTimer = setTimeout(() => {
340
+ pingAckTimer = null;
341
+ if (closed || ended || !pingInFlight || activePingSeq !== seq) return;
342
+ const idleSinceInbound = Date.now() - lastInboundAt;
343
+ if (lastInboundAt >= pingStartedAt && idleSinceInbound < pingTimeoutMs) {
344
+ armAckWatchdog(Math.max(1, pingTimeoutMs - idleSinceInbound));
345
+ return;
346
+ }
347
+ note('transport_ping_timeout');
348
+ fail('NATIVE_CONNECTION_FAILED');
349
+ }, delayMs);
350
+ pingAckTimer.unref();
351
+ };
352
+ armAckWatchdog(pingTimeoutMs);
296
353
  }
297
354
  }, pingIntervalMs);
298
355
  pingTimer.unref();
@@ -304,14 +361,15 @@ export function openDirectTurn(
304
361
  "content-type": "application/grpc",
305
362
  "grpc-timeout": `${timeoutMs}m`,
306
363
  te: "trailers",
307
- "user-agent": "gemini-app2api/1.0",
364
+ "user-agent": GATEWAY_USER_AGENT,
308
365
  });
309
366
  request.on("response", headers => {
367
+ lastInboundAt = Date.now();
310
368
  note('peer_headers', { httpStatus: Number(headers[':status']), grpcStatus: Number(headers['grpc-status']) });
311
369
  status(headers);
312
370
  if (emitHeaders && !closed && httpStatus === 200) push({ type: 'headers', httpStatus });
313
371
  });
314
- request.on("trailers", headers => { note('peer_trailers', { grpcStatus: Number(headers['grpc-status']) }); status(headers); });
372
+ request.on("trailers", headers => { lastInboundAt = Date.now(); note('peer_trailers', { grpcStatus: Number(headers['grpc-status']) }); status(headers); });
315
373
  request.on("error", () => {
316
374
  note('stream_error', { rstCode: request?.rstCode });
317
375
  if (!rejectPeerReset()) fail("NATIVE_STREAM_FAILED");
@@ -323,6 +381,7 @@ export function openDirectTurn(
323
381
  });
324
382
  request.on("data", (chunk) => {
325
383
  if (closed) return;
384
+ lastInboundAt = Date.now();
326
385
  note('peer_data', { bytes: chunk.length });
327
386
  try {
328
387
  received += chunk.length;
@@ -336,6 +395,7 @@ export function openDirectTurn(
336
395
  }
337
396
  });
338
397
  request.on("end", () => {
398
+ lastInboundAt = Date.now();
339
399
  note('stream_end', { rstCode: request?.rstCode });
340
400
  if (closed) return;
341
401
  // Node may emit readable 'end' for RST_STREAM(CANCEL). That is not a successful end.
@@ -1,5 +1,5 @@
1
1
  // Read-only Google quota RPC; no generation, quota reset, retry, redirects or model switching.
2
- import {GrpcMessageReader,frameGrpcMessage} from "../../native-wire/robin-current.mjs";
2
+ import {GrpcMessageReader,frameGrpcMessage,GATEWAY_USER_AGENT} from "../../native-wire/robin-current.mjs";
3
3
  import {connectHttp2} from "./outbound-proxy.mjs";
4
4
  export const QUOTA_ORIGIN = "https://robinfrontend-pa.googleapis.com";
5
5
  export const QUOTA_RPC = "/assistant.mobile.robin.RobinService/GetUsageInfo";
@@ -25,7 +25,7 @@ export async function fetchGoogleUsageInfo(accessToken,{signal,timeoutMs=10000,c
25
25
  signal?.addEventListener("abort",abort,{once:true});timer=setTimeout(()=>finish(failure("QUOTA_TIMEOUT",504)),timeoutMs);
26
26
  try{
27
27
  client=connect(QUOTA_ORIGIN);client.on("error",()=>finish(failure("QUOTA_CONNECTION_FAILED")));
28
- request=client.request({":method":"POST",":path":QUOTA_RPC,authorization:"Bearer "+accessToken,"content-type":"application/grpc",te:"trailers","grpc-timeout":timeoutMs+"m","user-agent":"gemini-app2api/1.0"});
28
+ request=client.request({":method":"POST",":path":QUOTA_RPC,authorization:"Bearer "+accessToken,"content-type":"application/grpc",te:"trailers","grpc-timeout":timeoutMs+"m","user-agent":GATEWAY_USER_AGENT});
29
29
  request.on("response",status);request.on("trailers",status);
30
30
  request.on("data",chunk=>{if(settled)return;received+=chunk.length;if(received>1024*1024)return finish(failure("QUOTA_RESPONSE_TOO_LARGE"));try{payloads.push(...reader.push(chunk));if(payloads.length>1)finish(failure("QUOTA_INVALID_RESPONSE"));}catch{finish(failure("QUOTA_INVALID_RESPONSE"));}});
31
31
  request.on("error",()=>{if(!settled&&!reset())finish(failure("QUOTA_STREAM_FAILED"));});
@@ -1,7 +1,7 @@
1
1
  // Native Gemini main-service terms only. Triggered by a user-initiated OAuth login.
2
2
  import crypto from "node:crypto";
3
3
  import { parse, lengthDelimited as message, varintField as integer } from "../../native-wire/protobuf.mjs";
4
- import { GrpcMessageReader, frameGrpcMessage, buildRequestMetadata } from "../../native-wire/robin-current.mjs";
4
+ import { GrpcMessageReader, frameGrpcMessage, buildRequestMetadata, GATEWAY_USER_AGENT } from "../../native-wire/robin-current.mjs";
5
5
  import { decodeGrpcMessage, sanitizeUpstreamMessage } from "./native-evidence.mjs";
6
6
  import { connectHttp2 } from "./outbound-proxy.mjs";
7
7
  export const TERMS_VERSION_RPC = "/assistant.mobile.robin.RobinService/GetTermsOfServiceVersion";
@@ -45,7 +45,7 @@ export async function termsRpc(accessToken, rpc, payload, { signal, timeoutMs =
45
45
  signal?.addEventListener("abort", abort, { once: true }); timer = setTimeout(() => finish(fail("TOS_TIMEOUT", 504)), timeoutMs);
46
46
  try {
47
47
  client = connect(origin); client.on("error", () => finish(fail("TOS_CONNECTION_FAILED")));
48
- request = client.request({ ":method": "POST", ":path": rpc, authorization: "Bearer " + accessToken, "content-type": "application/grpc", te: "trailers", "grpc-timeout": timeoutMs + "m", "user-agent": "gemini-app2api/1.0" });
48
+ request = client.request({ ":method": "POST", ":path": rpc, authorization: "Bearer " + accessToken, "content-type": "application/grpc", te: "trailers", "grpc-timeout": timeoutMs + "m", "user-agent": GATEWAY_USER_AGENT });
49
49
  request.on("response", status); request.on("trailers", status);
50
50
  request.on("data", chunk => {
51
51
  if (settled) return; received += chunk.length;
@@ -104,7 +104,7 @@ export async function acceptGoogleMainTerms(accessToken, { signal, rpc = termsRp
104
104
  // The native main-terms builder uses the numeric oneof setter (wire 6),
105
105
  // not the old standalone enum (wire 1). Locale is already in metadata.
106
106
  const body = Buffer.concat([
107
- message(4, Buffer.from("gemini-app2api/1.0")), integer(5, 21),
107
+ message(4, Buffer.from(GATEWAY_USER_AGENT)), integer(5, 21),
108
108
  integer(6, versionNo), message(7, termsMetadata(language)),
109
109
  message(10, Buffer.concat([integer(1, seconds), ...(nanos ? [integer(2, nanos)] : [])])),
110
110
  ]);
@@ -103,12 +103,19 @@ export function decodeImageBytes(data, mimeType) {
103
103
  if (!width || !height || width > 32768 || height > 32768 || width * height > MAX_PIXELS) fail('IMAGE_DIMENSIONS_TOO_LARGE', 413);
104
104
  return { mimeType, data, width, height };
105
105
  }
106
- export function normalizeImageUrl(url, detail) {
106
+ export function normalizeImageUrl(url, detail, decodedCache) {
107
107
  if (detail !== undefined && detail !== 'auto') fail('UNSUPPORTED_IMAGE_DETAIL');
108
108
  if (typeof url === 'string' && /^https?:/i.test(url)) return parseRemoteImageUrl(url).href;
109
- return decodeImageDataUrl(url).url;
109
+ const cached = decodedCache?.get(url);
110
+ if (cached) return cached.url;
111
+ const decoded = decodeImageDataUrl(url);
112
+ if (decodedCache) {
113
+ decodedCache.set(url, decoded);
114
+ decodedCache.set(decoded.url, decoded);
115
+ }
116
+ return decoded.url;
110
117
  }
111
- export function collectImageInputs(messages, resolvedImages) {
118
+ export function collectImageInputs(messages, resolvedImages, decodedCache) {
112
119
  let total = 0;
113
120
  const images = [], transcript = messages.map(message => {
114
121
  if (!Array.isArray(message.content)) return message;
@@ -117,7 +124,7 @@ export function collectImageInputs(messages, resolvedImages) {
117
124
  if (message.role !== 'user' || part.type !== 'image_url') fail('UNSUPPORTED_IMAGE_ROLE');
118
125
  if (images.length >= MAX_IMAGES) fail('IMAGE_COUNT_EXCEEDED', 413);
119
126
  const url = part.image_url?.url;
120
- const decoded = resolvedImages ? resolvedImages[images.length] : /^https?:/i.test(url) ? { url: parseRemoteImageUrl(url).href } : decodeImageDataUrl(url);
127
+ const decoded = resolvedImages ? resolvedImages[images.length] : /^https?:/i.test(url) ? { url: parseRemoteImageUrl(url).href } : (decodedCache?.get(url) ?? decodeImageDataUrl(url));
121
128
  const { data, mimeType, width, height } = decoded;
122
129
  if ((total += (data?.length ?? 0)) > MAX_TOTAL_IMAGE_BYTES) fail('IMAGES_TOO_LARGE', 413);
123
130
  images.push(data ? { data, mimeType, width, height } : decoded);