pi-gemini-app 0.1.5 → 0.1.8

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.
@@ -1,4 +1,5 @@
1
1
  import { openDirectTurn as defaultOpenDirectTurn } from '../../src/gateway/native-transport.mjs';
2
+ import { createImageBlobCache } from '../../src/gateway/image-upload.mjs';
2
3
  import { NativeDirectProvider as DefaultNativeDirectProvider } from '../../src/native-provider.mjs';
3
4
  import { automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
4
5
  import { buildChatPayload as defaultBuildChatPayload } from './transcript.js';
@@ -199,10 +200,12 @@ export function createGeminiStreamHandler({
199
200
  automaticRecoveryKind = defaultAutomaticRecoveryKind,
200
201
  buildChatPayload = defaultBuildChatPayload,
201
202
  estimateUsage = defaultEstimateUsage,
203
+ resolveAccessToken,
202
204
  } = {}) {
203
205
  if (typeof createAssistantMessageEventStream !== 'function') {
204
206
  throw new TypeError('createAssistantMessageEventStream is required');
205
207
  }
208
+ const sharedBlobCache = createImageBlobCache();
206
209
 
207
210
  function executeStream(model, context, options = {}, { simple = false } = {}) {
208
211
  const stream = createAssistantMessageEventStream();
@@ -315,8 +318,7 @@ export function createGeminiStreamHandler({
315
318
  });
316
319
 
317
320
  try {
318
- const apiKey = options?.apiKey;
319
- if (!apiKey) {
321
+ if (typeof resolveAccessToken !== 'function' && !options?.apiKey) {
320
322
  throw new Error(
321
323
  `No access token for provider ${model.provider}. Run /login gemini-app to sign in.`,
322
324
  );
@@ -335,10 +337,26 @@ export function createGeminiStreamHandler({
335
337
  : 0;
336
338
 
337
339
  const authManager = {
338
- getValidAccessToken: async () => apiKey,
340
+ getValidAccessToken: async () => {
341
+ if (typeof resolveAccessToken === 'function') {
342
+ const token = await resolveAccessToken({
343
+ signal: options?.signal,
344
+ apiKey: options?.apiKey,
345
+ model,
346
+ });
347
+ if (!token) {
348
+ throw new Error(
349
+ `No access token for provider ${model.provider}. Sign in with OAuth first.`,
350
+ );
351
+ }
352
+ return token;
353
+ }
354
+ return options.apiKey;
355
+ },
339
356
  };
340
357
  const provider = new NativeDirectProvider(authManager, {
341
358
  openTurn,
359
+ blobCache: sharedBlobCache,
342
360
  modelAlias: model.id,
343
361
  allowAutoModel: true,
344
362
  });
@@ -429,6 +447,14 @@ export function createGeminiStreamHandler({
429
447
  }
430
448
  break;
431
449
  } catch (turnError) {
450
+ if (
451
+ !options?.signal?.aborted &&
452
+ turnError?.code === 'NATIVE_TURN_TIMEOUT' &&
453
+ turnError?.unverifiedOutput !== true &&
454
+ (hasToolCalls || turnError?.postOutputIdleStall === true || publishedBytes >= PREFIX_BYTES)
455
+ ) {
456
+ break;
457
+ }
432
458
  if (
433
459
  !started &&
434
460
  attempts === 0 &&
@@ -1,10 +1,12 @@
1
1
  import crypto from 'node:crypto';
2
- import { decodeImageDataUrl } from '../../src/image-input.mjs';
2
+ import {
3
+ decodeImageDataUrl,
4
+ MAX_IMAGES,
5
+ MAX_IMAGE_BYTES,
6
+ MAX_TOTAL_IMAGE_BYTES,
7
+ MAX_IMAGE_URL_BYTES,
8
+ } from '../../src/image-input.mjs';
3
9
 
4
- const MAX_IMAGES = 4;
5
- const MAX_IMAGE_BYTES = 2 * 1024 * 1024;
6
- const MAX_TOTAL_IMAGE_BYTES = 2 * 1024 * 1024;
7
- const MAX_IMAGE_URL_BYTES = Math.ceil(MAX_TOTAL_IMAGE_BYTES / 3) * 4 + 1024;
8
10
  const ALLOWED_IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/webp']);
9
11
 
10
12
  function sanitizeText(value) {
@@ -176,15 +178,15 @@ function planImageBudget(messages) {
176
178
  const byteLength = Buffer.byteLength(compactBase64, 'base64');
177
179
  const dataUrl = `data:${mimeType};base64,${compactBase64}`;
178
180
  if (byteLength <= 0 || byteLength > MAX_IMAGE_BYTES || Buffer.byteLength(dataUrl) > MAX_IMAGE_URL_BYTES) {
179
- degraded.set(key, `[Image omitted: ${mimeType} exceeded 2MB limit]`);
181
+ degraded.set(key, `[Image omitted: ${mimeType} exceeded ${Math.round(MAX_IMAGE_BYTES / (1024 * 1024))}MB limit]`);
180
182
  continue;
181
183
  }
182
184
  if (count >= MAX_IMAGES) {
183
- degraded.set(key, `[Image omitted: ${mimeType} exceeded 4-image limit]`);
185
+ degraded.set(key, `[Image omitted: ${mimeType} exceeded ${MAX_IMAGES}-image limit]`);
184
186
  continue;
185
187
  }
186
188
  if (totalBytes + byteLength > MAX_TOTAL_IMAGE_BYTES) {
187
- degraded.set(key, `[Image omitted: ${mimeType} exceeded 2MB total image budget]`);
189
+ degraded.set(key, `[Image omitted: ${mimeType} exceeded ${Math.round(MAX_TOTAL_IMAGE_BYTES / (1024 * 1024))}MB total image budget]`);
188
190
  continue;
189
191
  }
190
192
  try {
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import http from 'node:http';
5
5
  import crypto from 'node:crypto';
6
+ import { fetchWithProxy } from '../src/gateway/outbound-proxy.mjs';
6
7
 
7
8
  const AUTH = 'https://accounts.google.com/o/oauth2/auth';
8
9
  const TOKEN = 'https://oauth2.googleapis.com/token';
@@ -19,7 +20,7 @@ function validateConfig({ clientId, scopes, refreshScopes, redirectHost, listenH
19
20
  if (listenHost !== undefined && !['127.0.0.1','0.0.0.0'].includes(listenHost)) throw new Error('Unsupported bind address');
20
21
  if (nativeLoopback !== undefined && typeof nativeLoopback !== 'boolean') throw new Error('Invalid native mode');
21
22
  }
22
- async function tokenRequest(body, config, { fetchImpl = fetch, timeoutMs = 12_000, signal } = {}) {
23
+ async function tokenRequest(body, config, { fetchImpl = fetchWithProxy, timeoutMs = 12_000, signal } = {}) {
23
24
  const boundedSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
24
25
  const response = await fetchImpl(config.nativeLoopback ? NATIVE_TOKEN : TOKEN, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body, redirect: 'error', signal: boundedSignal });
25
26
  let data;
@@ -55,8 +55,9 @@ export function buildRequestMetadata({ clientType, languageCode, interfaceLangua
55
55
  // Query.attachments (field 3) -> Attachment.blob (field 1), name (field 2).
56
56
  // Blob fields: ID (1), type (2 = 1), MIME (3), source (4 = 1).
57
57
  // Upload completes beforehand; raw image bytes are never inline-encoded here.
58
+ export const MAX_NATIVE_IMAGE_ATTACHMENTS = 256;
58
59
  function imageAttachments(images) {
59
- if (!Array.isArray(images) || images.length > 4) throw new TypeError('Invalid native images');
60
+ if (!Array.isArray(images) || images.length > MAX_NATIVE_IMAGE_ATTACHMENTS) throw new TypeError('Invalid native images');
60
61
  return images.map((image, index) => {
61
62
  const extension = image?.mimeType === 'image/png' ? 'png' : image?.mimeType === 'image/jpeg' ? 'jpg' : image?.mimeType === 'image/webp' ? 'webp' : null;
62
63
  const id = image?.blobId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.5",
3
+ "version": "0.1.8",
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": [
@@ -66,6 +66,7 @@
66
66
  "src/gateway/native-search-metadata.mjs",
67
67
  "src/gateway/native-transport.mjs",
68
68
  "src/gateway/oauth-client-defaults.mjs",
69
+ "src/gateway/outbound-proxy.mjs",
69
70
  "src/gateway/output-recovery.mjs",
70
71
  "src/gateway/quota-failover.mjs",
71
72
  "src/gateway/quota-transport.mjs",
@@ -16,7 +16,7 @@ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 }
16
16
  } = {}) {
17
17
  if (!Array.isArray(images) || images.length > MAX_IMAGES) fail('IMAGE_COUNT_EXCEEDED', 413);
18
18
  if (!images.some(image => image.url)) return images;
19
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 30000) fail('INVALID_IMAGE_DOWNLOAD_TIMEOUT');
19
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 180000) fail('INVALID_IMAGE_DOWNLOAD_TIMEOUT');
20
20
  if (signal?.aborted) fail('IMAGE_DOWNLOAD_ABORTED', 499);
21
21
  const controller = new AbortController();
22
22
  let rejectStop;
@@ -1,19 +1,71 @@
1
- import http2 from 'node:http2';
1
+ import crypto from 'node:crypto';
2
2
  import { protocolError } from '../tool-protocol.mjs';
3
+ import { MAX_IMAGES, MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES } from '../image-input.mjs';
4
+ import { connectHttp2 } from './outbound-proxy.mjs';
3
5
 
4
6
  const ORIGIN = 'https://push.clients6.google.com';
5
- const MAX_IMAGES = 4, MAX_BYTES = 2 * 1024 * 1024;
7
+ export const DEFAULT_UPLOAD_CONCURRENCY = 8;
8
+ export const MAX_UPLOAD_TIMEOUT_MS = 600_000;
6
9
  const fail = (suffix, status = 502) => { throw protocolError(`NATIVE_IMAGE_UPLOAD_${suffix}`, status); };
7
10
  const mimeTypes = new Set(['image/png', 'image/jpeg', 'image/webp']);
8
11
  const drainError = () => {};
9
12
 
13
+ /** Ephemeral in-memory per-account hash -> blobId LRU cache. Never stores image bytes or persists to disk. */
14
+ export function createImageBlobCache({ maxEntries = 2048, ttlMs = 15 * 60 * 1000, now = Date.now } = {}) {
15
+ const entries = new Map();
16
+ const limit = Number.isSafeInteger(maxEntries) && maxEntries > 0 ? maxEntries : 2048;
17
+ const ttl = Number.isSafeInteger(ttlMs) && ttlMs > 0 ? ttlMs : 15 * 60 * 1000;
18
+ function keyOf(accountId, mimeType, data) {
19
+ const digest = crypto.createHash('sha256').update(data).digest('hex');
20
+ return `${accountId}\0${mimeType}\0${digest}`;
21
+ }
22
+ function get(key) {
23
+ const entry = entries.get(key);
24
+ if (!entry) return null;
25
+ if (entry.expiresAt <= now()) {
26
+ entries.delete(key);
27
+ return null;
28
+ }
29
+ // Refresh LRU recency.
30
+ entries.delete(key);
31
+ entries.set(key, entry);
32
+ return { blobId: entry.blobId, mimeType: entry.mimeType };
33
+ }
34
+ function set(key, { blobId, mimeType }) {
35
+ if (typeof key !== 'string' || !key || typeof blobId !== 'string' || !blobId || !mimeTypes.has(mimeType)) return;
36
+ entries.delete(key);
37
+ while (entries.size >= limit) {
38
+ const oldest = entries.keys().next().value;
39
+ if (oldest === undefined) break;
40
+ entries.delete(oldest);
41
+ }
42
+ entries.set(key, { blobId, mimeType, expiresAt: now() + ttl });
43
+ }
44
+ function del(key) { entries.delete(key); }
45
+ function deleteAccount(accountId) {
46
+ const prefix = `${accountId}\0`;
47
+ for (const key of entries.keys()) if (key.startsWith(prefix)) entries.delete(key);
48
+ }
49
+ function clear() { entries.clear(); }
50
+ return {
51
+ keyOf,
52
+ get,
53
+ set,
54
+ delete: del,
55
+ deleteAccount,
56
+ clear,
57
+ get size() { return entries.size; },
58
+ };
59
+ }
60
+
10
61
  function validateImages(images) {
11
62
  if (!Array.isArray(images) || images.length > MAX_IMAGES) fail('INVALID_RESPONSE');
12
63
  let total = 0;
13
64
  for (const image of images) {
14
65
  if (!image || !Buffer.isBuffer(image.data) || !image.data.length || !mimeTypes.has(image.mimeType)) fail('INVALID_RESPONSE');
66
+ if (image.data.length > MAX_IMAGE_BYTES) fail('INVALID_RESPONSE');
15
67
  total += image.data.length;
16
- if (total > MAX_BYTES) fail('INVALID_RESPONSE');
68
+ if (total > MAX_TOTAL_IMAGE_BYTES) fail('INVALID_RESPONSE');
17
69
  }
18
70
  }
19
71
 
@@ -26,22 +78,56 @@ function boundedLocation(value) {
26
78
  return parsed;
27
79
  }
28
80
 
29
- export async function uploadNativeImages(token, images, { signal, timeoutMs = 60000 } = {}, { connect = http2.connect } = {}) {
81
+ export async function uploadNativeImages(
82
+ token,
83
+ images,
84
+ { signal, timeoutMs = 60000, concurrency = DEFAULT_UPLOAD_CONCURRENCY } = {},
85
+ { connect = connectHttp2 } = {},
86
+ ) {
30
87
  validateImages(images);
31
88
  if (!images.length) return [];
32
- if (typeof token !== 'string' || !token || token.length > 65536 || /\s|[\x00-\x1f\x7f]/u.test(token) || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60000 || (signal !== undefined && (!signal || typeof signal.addEventListener !== 'function')) || typeof connect !== 'function') fail('INVALID_RESPONSE');
89
+ if (
90
+ typeof token !== 'string' ||
91
+ !token ||
92
+ token.length > 65536 ||
93
+ /\s|[\x00-\x1f\x7f]/u.test(token) ||
94
+ !Number.isSafeInteger(timeoutMs) ||
95
+ timeoutMs < 1 ||
96
+ timeoutMs > MAX_UPLOAD_TIMEOUT_MS ||
97
+ !Number.isSafeInteger(concurrency) ||
98
+ concurrency < 1 ||
99
+ concurrency > 32 ||
100
+ (signal !== undefined && (!signal || typeof signal.addEventListener !== 'function')) ||
101
+ typeof connect !== 'function'
102
+ ) fail('INVALID_RESPONSE');
33
103
  if (signal?.aborted) fail('CANCELLED', 499);
34
104
  const deadline = Date.now() + timeoutMs;
35
- let session, timeout, stopPending, sessionFailed = false;
105
+ let session, timeout, sessionFailed = false, batchError = null;
106
+ const activeStops = new Set();
107
+ const stopAll = (err) => {
108
+ if (!batchError) batchError = err;
109
+ for (const stop of [...activeStops]) stop(err);
110
+ };
36
111
  const abortCode = () => signal?.aborted ? ['CANCELLED', 499] : Date.now() >= deadline ? ['TIMEOUT', 504] : null;
37
112
  const ensureAlive = () => {
113
+ if (batchError) throw batchError;
38
114
  const stopped = abortCode(); if (stopped) fail(...stopped);
39
115
  if (sessionFailed || session?.destroyed || session?.closed) fail('RESET');
40
116
  };
41
117
  const request = (headers, body, maxBody) => new Promise((resolve, reject) => {
42
118
  let stream, responseHeaders, chunks = [], size = 0, settled = false, ended = false;
43
- const cleanup = () => { signal?.removeEventListener('abort', onAbort); stream?.removeListener('response', onResponse); stream?.removeListener('data', onData); stream?.removeListener('end', onEnd); stream?.removeListener('error', onError); stream?.removeListener('aborted', onAborted); stream?.removeListener('close', onClose); stream?.on('error', drainError); };
44
- const finish = (error, result) => { if (settled) return; settled = true; if (stopPending === onForcedStop) stopPending = null; cleanup(); error ? reject(error) : resolve(result); };
119
+ const cleanup = () => {
120
+ activeStops.delete(onForcedStop);
121
+ signal?.removeEventListener('abort', onAbort);
122
+ stream?.removeListener('response', onResponse);
123
+ stream?.removeListener('data', onData);
124
+ stream?.removeListener('end', onEnd);
125
+ stream?.removeListener('error', onError);
126
+ stream?.removeListener('aborted', onAborted);
127
+ stream?.removeListener('close', onClose);
128
+ stream?.on('error', drainError);
129
+ };
130
+ const finish = (error, result) => { if (settled) return; settled = true; cleanup(); error ? reject(error) : resolve(result); };
45
131
  const onForcedStop = error => { finish(error); try { stream?.close(); } catch {} };
46
132
  const onAbort = () => { const c = abortCode() || ['CANCELLED', 499]; onForcedStop(protocolError(`NATIVE_IMAGE_UPLOAD_${c[0]}`, c[1])); };
47
133
  const onResponse = h => {
@@ -65,7 +151,7 @@ export async function uploadNativeImages(token, images, { signal, timeoutMs = 60
65
151
  if (status !== 200) { finish(protocolError('NATIVE_IMAGE_UPLOAD_INVALID_RESPONSE', status === 401 || status === 403 ? 403 : status === 429 ? 429 : 502)); return; }
66
152
  finish(null, { headers: responseHeaders, body: Buffer.concat(chunks) });
67
153
  };
68
- stopPending = onForcedStop;
154
+ activeStops.add(onForcedStop);
69
155
  try {
70
156
  ensureAlive();
71
157
  stream = session.request(headers);
@@ -73,29 +159,52 @@ export async function uploadNativeImages(token, images, { signal, timeoutMs = 60
73
159
  stream.on('response', onResponse); stream.on('data', onData); stream.on('end', onEnd); stream.on('error', onError); stream.on('aborted', onAborted); stream.on('close', onClose);
74
160
  if (signal?.aborted) onAbort();
75
161
  else if (body) stream.end(body); else stream.end();
76
- } catch { const c = abortCode(); finish(c ? protocolError(`NATIVE_IMAGE_UPLOAD_${c[0]}`, c[1]) : protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); }
162
+ } catch (err) {
163
+ if (typeof err?.code === 'string' && err.code.startsWith('NATIVE_IMAGE_UPLOAD_')) { finish(err); return; }
164
+ const c = abortCode();
165
+ finish(c ? protocolError(`NATIVE_IMAGE_UPLOAD_${c[0]}`, c[1]) : protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502));
166
+ }
77
167
  });
78
- const onSessionError = () => { sessionFailed = true; stopPending?.(protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); };
168
+ const onSessionError = () => { sessionFailed = true; stopAll(protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); };
169
+ 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 };
182
+ };
79
183
  try {
80
184
  try { session = connect(ORIGIN, { settings: { enablePush: false, maxHeaderListSize: 8192 } }); } catch { fail('RESET'); }
81
185
  if (!session || typeof session.request !== 'function') fail('RESET');
82
186
  session.on?.('error', onSessionError);
83
187
  session.on?.('close', onSessionError);
84
- timeout = setTimeout(() => { stopPending?.(protocolError('NATIVE_IMAGE_UPLOAD_TIMEOUT', 504)); try { session.destroy(); } catch {} }, Math.max(1, deadline - Date.now()));
85
- const results = [];
86
- for (const image of images) {
87
- ensureAlive();
88
- 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);
89
- if (String(initial.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'active') fail('INVALID_RESPONSE');
90
- const location = boundedLocation(initial.headers['x-goog-upload-url']);
91
- ensureAlive();
92
- 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);
93
- if (String(final.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'final') fail('INVALID_RESPONSE');
94
- let blobId;
95
- try { blobId = new TextDecoder('utf-8', { fatal: true }).decode(final.body); } catch { fail('INVALID_RESPONSE'); }
96
- if (!blobId || Buffer.byteLength(blobId) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(blobId)) fail('INVALID_RESPONSE');
97
- ensureAlive(); results.push({ blobId, mimeType: image.mimeType });
98
- }
188
+ timeout = setTimeout(() => { stopAll(protocolError('NATIVE_IMAGE_UPLOAD_TIMEOUT', 504)); try { session.destroy(); } catch {} }, Math.max(1, deadline - Date.now()));
189
+ const results = new Array(images.length);
190
+ const workerCount = Math.min(concurrency, images.length);
191
+ let nextIndex = 0;
192
+ const worker = async () => {
193
+ while (!batchError) {
194
+ const index = nextIndex++;
195
+ if (index >= images.length) return;
196
+ try {
197
+ results[index] = await uploadOne(images[index]);
198
+ } catch (err) {
199
+ stopAll(err);
200
+ throw err;
201
+ }
202
+ }
203
+ };
204
+ const outcomes = await Promise.allSettled(Array.from({ length: workerCount }, () => worker()));
205
+ const failed = outcomes.find(o => o.status === 'rejected');
206
+ if (failed) throw failed.reason;
207
+ if (batchError) throw batchError;
99
208
  return results;
100
209
  } catch (error) {
101
210
  if (typeof error?.code === 'string' && error.code.startsWith('NATIVE_IMAGE_UPLOAD_')) throw error;
@@ -15,6 +15,8 @@ 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',
19
+ 'post_tool_idle_timeout', 'post_output_idle_timeout',
18
20
  'transport_open', 'local_stream_close', 'local_session_destroy', 'local_signal_abort', 'local_cancel',
19
21
  'transport_failure', 'transport_deadline', 'peer_headers', 'peer_trailers', 'peer_reset',
20
22
  'peer_goaway', 'stream_error', 'stream_close', 'stream_end', 'peer_data', 'local_half_close',
@@ -18,6 +18,8 @@ import { fault } from "./oauth-client-defaults.mjs";
18
18
  import { PROMPT_MAX_BYTES } from "../openai-contract.mjs";
19
19
  import { NATIVE_RESPONSE_LIMITS as RESPONSE_LIMITS } from './native-response-limits.mjs';
20
20
  import { observeNative } from './native-diagnostic.mjs';
21
+ import { connectHttp2 } from './outbound-proxy.mjs';
22
+ export const DEFAULT_HTTP2_PING_INTERVAL_MS = 15_000;
21
23
  export const MIN_CONNECT_ATTEMPT_TIMEOUT_MS = 5000;
22
24
  // Node v22 defaults Happy Eyeballs per-family attempt timeout to 250ms, which aborts
23
25
  // IPv4 connects over high-RTT VPN tunnels when IPv6 returns immediate EHOSTUNREACH.
@@ -48,12 +50,13 @@ export function openDirectTurn(
48
50
  temporaryChat = true,
49
51
  continuation,
50
52
  timeoutMs = 180000,
53
+ pingIntervalMs = DEFAULT_HTTP2_PING_INTERVAL_MS,
51
54
  signal,
52
55
  allowNativeTools = false,
53
56
  emitHeaders = false,
54
57
  diagnostic,
55
58
  } = {},
56
- { connect = http2.connect } = {},
59
+ { connect = connectHttp2 } = {},
57
60
  ) {
58
61
  if (
59
62
  typeof token !== "string" ||
@@ -110,6 +113,8 @@ export function openDirectTurn(
110
113
  streamCloseCode = null,
111
114
  request,
112
115
  timer,
116
+ pingTimer = null,
117
+ pingInFlight = false,
113
118
  closed = false,
114
119
  ended = false,
115
120
  error = null,
@@ -140,8 +145,16 @@ export function openDirectTurn(
140
145
  };
141
146
  const socketEnd = () => connectionEnded('end');
142
147
  const socketClose = () => connectionEnded('close');
148
+ const stopPing = () => {
149
+ if (pingTimer) {
150
+ clearInterval(pingTimer);
151
+ pingTimer = null;
152
+ }
153
+ pingInFlight = false;
154
+ };
143
155
  const stop = () => {
144
156
  clearTimeout(timer);
157
+ stopPing();
145
158
  signal?.removeEventListener("abort", abort);
146
159
  detachSocketListeners();
147
160
  note('local_stream_close', { requestedCode: ended ? 0 : 8, rstCode: request?.rstCode });
@@ -264,6 +277,7 @@ export function openDirectTurn(
264
277
  client = connect(NATIVE_ORIGIN);
265
278
  try {
266
279
  socket = client.socket;
280
+ socket?.setKeepAlive?.(true, 15_000);
267
281
  socket?.prependOnceListener?.('end', socketEnd);
268
282
  socket?.prependOnceListener?.('close', socketClose);
269
283
  } catch {
@@ -271,6 +285,18 @@ export function openDirectTurn(
271
285
  }
272
286
  client.on("error", () => fail("NATIVE_CONNECTION_FAILED"));
273
287
  if (diagnostic) client.on('goaway', code => note('peer_goaway', { goawayCode: code }));
288
+ if (Number.isInteger(pingIntervalMs) && pingIntervalMs > 0 && typeof client.ping === "function") {
289
+ pingTimer = setInterval(() => {
290
+ if (closed || ended || client.closed || client.destroyed || pingInFlight) return;
291
+ pingInFlight = true;
292
+ try {
293
+ client.ping(() => { pingInFlight = false; });
294
+ } catch {
295
+ pingInFlight = false;
296
+ }
297
+ }, pingIntervalMs);
298
+ pingTimer.unref();
299
+ }
274
300
  request = client.request({
275
301
  ":method": "POST",
276
302
  ":path": NATIVE_RPC,
@@ -319,6 +345,7 @@ export function openDirectTurn(
319
345
  push({ type: "end", httpStatus, grpcStatus });
320
346
  ended = true;
321
347
  clearTimeout(timer);
348
+ stopPing();
322
349
  } catch {
323
350
  fail("NATIVE_FRAME_REJECTED");
324
351
  }
@@ -0,0 +1,320 @@
1
+ /** Zero-dependency outbound HTTP(S) proxy helper for Node HTTP/2 and HTTPS fetch.
2
+ * Respects HTTPS_PROXY / HTTP_PROXY / ALL_PROXY and NO_PROXY without logging proxy credentials.
3
+ */
4
+ import http from 'node:http';
5
+ import https from 'node:https';
6
+ import http2 from 'node:http2';
7
+ import net from 'node:net';
8
+ import tls from 'node:tls';
9
+ import { Duplex, Readable } from 'node:stream';
10
+
11
+ const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
12
+
13
+ function stripBrackets(host) {
14
+ return host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
15
+ }
16
+
17
+ function defaultPort(protocol) {
18
+ return protocol === 'https:' ? '443' : '80';
19
+ }
20
+
21
+ function isBypassed(target, noProxyRaw) {
22
+ if (typeof noProxyRaw !== 'string' || !noProxyRaw.trim()) return false;
23
+ const host = stripBrackets(target.hostname).toLowerCase();
24
+ const port = target.port || defaultPort(target.protocol);
25
+ for (const rawEntry of noProxyRaw.split(',')) {
26
+ const entry = rawEntry.trim().toLowerCase();
27
+ if (!entry) continue;
28
+ if (entry === '*') return true;
29
+ let entryHost = entry;
30
+ let entryPort = null;
31
+ if (entry.startsWith('[')) {
32
+ const end = entry.indexOf(']');
33
+ if (end < 0) continue;
34
+ entryHost = entry.slice(1, end);
35
+ if (entry[end + 1] === ':') entryPort = entry.slice(end + 2);
36
+ } else {
37
+ const colon = entry.lastIndexOf(':');
38
+ if (colon > 0 && /^\d+$/.test(entry.slice(colon + 1))) {
39
+ entryHost = entry.slice(0, colon);
40
+ entryPort = entry.slice(colon + 1);
41
+ }
42
+ }
43
+ if (entryPort && entryPort !== port) continue;
44
+ const normalized = entryHost.startsWith('.') ? entryHost.slice(1) : entryHost;
45
+ if (!normalized) continue;
46
+ if (host === normalized || host.endsWith('.' + normalized)) return true;
47
+ }
48
+ return false;
49
+ }
50
+
51
+ export function resolveOutboundProxy(targetUrl, env = process.env) {
52
+ if (!env || typeof env !== 'object') return null;
53
+ let target;
54
+ try { target = targetUrl instanceof URL ? targetUrl : new URL(targetUrl); } catch { return null; }
55
+ if (target.protocol !== 'https:' && target.protocol !== 'http:') return null;
56
+ if (isBypassed(target, env.NO_PROXY ?? env.no_proxy ?? '')) return null;
57
+ const raw = target.protocol === 'https:'
58
+ ? (env.HTTPS_PROXY || env.https_proxy || env.ALL_PROXY || env.all_proxy || '')
59
+ : (env.HTTP_PROXY || env.http_proxy || env.ALL_PROXY || env.all_proxy || '');
60
+ const trimmed = typeof raw === 'string' ? raw.trim() : '';
61
+ if (!trimmed || /[\r\n\0]/.test(trimmed)) return null;
62
+ let proxy;
63
+ try { proxy = new URL(trimmed); } catch { return null; }
64
+ if ((proxy.protocol !== 'http:' && proxy.protocol !== 'https:') || !proxy.hostname) return null;
65
+ return proxy;
66
+ }
67
+
68
+ function formatAuthority(host, port) {
69
+ const bare = stripBrackets(host);
70
+ return bare.includes(':') ? `[${bare}]:${port}` : `${bare}:${port}`;
71
+ }
72
+
73
+ export function createConnectTunnel(
74
+ proxyUrl,
75
+ targetHost,
76
+ targetPort,
77
+ { timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS, signal, rejectUnauthorized = true, ca } = {},
78
+ ) {
79
+ const authority = formatAuthority(targetHost, targetPort);
80
+ const headers = { Host: authority };
81
+ if (proxyUrl.username || proxyUrl.password) {
82
+ const user = decodeURIComponent(proxyUrl.username || '');
83
+ const pass = decodeURIComponent(proxyUrl.password || '');
84
+ headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(`${user}:${pass}`, 'utf8').toString('base64');
85
+ }
86
+ let rawSocket = null;
87
+ let connected = false;
88
+ let finished = false;
89
+ let finalCallback = null;
90
+ const pendingWrites = [];
91
+
92
+ const failPending = (err) => {
93
+ while (pendingWrites.length) {
94
+ const item = pendingWrites.shift();
95
+ try { item.callback(err); } catch {}
96
+ }
97
+ if (finalCallback) {
98
+ const cb = finalCallback;
99
+ finalCallback = null;
100
+ try { cb(err); } catch {}
101
+ }
102
+ };
103
+
104
+ const tunnel = new Duplex({
105
+ read() {
106
+ rawSocket?.resume();
107
+ },
108
+ write(chunk, encoding, callback) {
109
+ if (connected && rawSocket) {
110
+ if (rawSocket.destroyed) { callback(new Error('PROXY_TUNNEL_CLOSED')); return; }
111
+ rawSocket.write(chunk, encoding, callback);
112
+ return;
113
+ }
114
+ pendingWrites.push({ chunk, encoding, callback });
115
+ },
116
+ final(callback) {
117
+ finished = true;
118
+ if (connected && rawSocket) {
119
+ rawSocket.end(callback);
120
+ return;
121
+ }
122
+ finalCallback = callback;
123
+ },
124
+ destroy(err, callback) {
125
+ signal?.removeEventListener('abort', onAbort);
126
+ try { req.destroy(); } catch {}
127
+ try { rawSocket?.destroy(); } catch {}
128
+ failPending(err || new Error('PROXY_TUNNEL_DESTROYED'));
129
+ callback(err);
130
+ },
131
+ });
132
+
133
+ const onAbort = () => tunnel.destroy(new Error('PROXY_CONNECT_ABORTED'));
134
+ signal?.addEventListener('abort', onAbort, { once: true });
135
+
136
+ const transport = proxyUrl.protocol === 'https:' ? https : http;
137
+ const req = transport.request({
138
+ host: stripBrackets(proxyUrl.hostname),
139
+ port: Number(proxyUrl.port) || Number(defaultPort(proxyUrl.protocol)),
140
+ method: 'CONNECT',
141
+ path: authority,
142
+ headers,
143
+ timeout: timeoutMs,
144
+ ...(proxyUrl.protocol === 'https:' ? { rejectUnauthorized, ...(ca ? { ca } : {}) } : {}),
145
+ });
146
+
147
+ req.on('connect', (res, socket, head) => {
148
+ signal?.removeEventListener('abort', onAbort);
149
+ if (tunnel.destroyed) {
150
+ try { socket.destroy(); } catch {}
151
+ return;
152
+ }
153
+ if (res.statusCode !== 200) {
154
+ try { socket.destroy(); } catch {}
155
+ tunnel.destroy(new Error(`PROXY_CONNECT_REJECTED_${res.statusCode || 0}`));
156
+ return;
157
+ }
158
+ rawSocket = socket;
159
+ connected = true;
160
+ try { socket.setKeepAlive?.(true, 15_000); } catch {}
161
+ try { socket.setNoDelay?.(true); } catch {}
162
+ socket.on('data', (chunk) => {
163
+ if (!tunnel.destroyed && !tunnel.push(chunk)) socket.pause();
164
+ });
165
+ socket.on('end', () => {
166
+ if (!tunnel.destroyed) tunnel.push(null);
167
+ });
168
+ socket.on('error', (err) => {
169
+ if (!tunnel.destroyed) tunnel.destroy(err);
170
+ });
171
+ socket.on('close', () => {
172
+ if (!tunnel.destroyed) tunnel.destroy();
173
+ });
174
+ if (head && head.length > 0 && !tunnel.push(head)) socket.pause();
175
+ while (pendingWrites.length) {
176
+ const item = pendingWrites.shift();
177
+ socket.write(item.chunk, item.encoding, item.callback);
178
+ }
179
+ if (finished) {
180
+ const cb = finalCallback;
181
+ finalCallback = null;
182
+ socket.end(cb || undefined);
183
+ }
184
+ });
185
+
186
+ req.on('response', (res) => {
187
+ res.resume();
188
+ if (!tunnel.destroyed) tunnel.destroy(new Error(`PROXY_CONNECT_REJECTED_${res.statusCode || 0}`));
189
+ });
190
+ req.on('timeout', () => {
191
+ req.destroy();
192
+ if (!tunnel.destroyed) tunnel.destroy(new Error('PROXY_CONNECT_TIMEOUT'));
193
+ });
194
+ req.on('error', (err) => {
195
+ if (!tunnel.destroyed) tunnel.destroy(err);
196
+ });
197
+ req.end();
198
+
199
+ return tunnel;
200
+ }
201
+
202
+ export function connectHttp2(origin, options = {}, { env = process.env } = {}) {
203
+ const proxyUrl = resolveOutboundProxy(origin, env);
204
+ if (!proxyUrl) return http2.connect(origin, options);
205
+ const target = origin instanceof URL ? origin : new URL(origin);
206
+ if (target.protocol !== 'https:') return http2.connect(origin, options);
207
+ const targetHost = stripBrackets(target.hostname);
208
+ const targetPort = Number(target.port) || 443;
209
+ return http2.connect(origin, {
210
+ ...options,
211
+ createConnection: () => {
212
+ const tunnel = createConnectTunnel(proxyUrl, targetHost, targetPort, {
213
+ rejectUnauthorized: options?.proxyRejectUnauthorized ?? true,
214
+ ...(options?.proxyCa ? { ca: options.proxyCa } : {}),
215
+ });
216
+ return tls.connect({
217
+ socket: tunnel,
218
+ servername: net.isIP(targetHost) ? undefined : targetHost,
219
+ ALPNProtocols: ['h2'],
220
+ rejectUnauthorized: options?.rejectUnauthorized ?? true,
221
+ ...(options?.ca ? { ca: options.ca } : {}),
222
+ });
223
+ },
224
+ });
225
+ }
226
+
227
+ function normalizeRequestBody(body) {
228
+ if (body === undefined || body === null) return null;
229
+ if (Buffer.isBuffer(body)) return body;
230
+ if (body instanceof Uint8Array) return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
231
+ if (body instanceof URLSearchParams) return Buffer.from(body.toString(), 'utf8');
232
+ return Buffer.from(String(body), 'utf8');
233
+ }
234
+
235
+ function normalizeHeaders(headers) {
236
+ const out = {};
237
+ if (!headers) return out;
238
+ if (typeof headers.forEach === 'function') {
239
+ headers.forEach((value, key) => { out[key] = value; });
240
+ return out;
241
+ }
242
+ for (const [key, value] of Object.entries(headers)) {
243
+ if (value !== undefined) out[key] = value;
244
+ }
245
+ return out;
246
+ }
247
+
248
+ export async function fetchWithProxy(url, init = {}, { env = process.env, fetchImpl = fetch, tlsOptions = {} } = {}) {
249
+ const proxyUrl = fetchImpl === fetch ? resolveOutboundProxy(url, env) : null;
250
+ if (!proxyUrl) return fetchImpl(url, init);
251
+ const target = url instanceof URL ? url : new URL(url);
252
+ if (target.protocol !== 'https:') return fetchImpl(url, init);
253
+ const targetHost = stripBrackets(target.hostname);
254
+ const targetPort = Number(target.port) || 443;
255
+ const body = normalizeRequestBody(init.body);
256
+ const headers = normalizeHeaders(init.headers);
257
+ if (body && headers['content-length'] === undefined && headers['Content-Length'] === undefined) {
258
+ headers['Content-Length'] = String(body.length);
259
+ }
260
+ if (init.signal?.aborted) throw init.signal.reason || new DOMException('Aborted', 'AbortError');
261
+ return new Promise((resolve, reject) => {
262
+ let settled = false;
263
+ const done = (err, value) => {
264
+ if (settled) return;
265
+ settled = true;
266
+ init.signal?.removeEventListener('abort', onAbort);
267
+ if (err) reject(err); else resolve(value);
268
+ };
269
+ const tunnel = createConnectTunnel(proxyUrl, targetHost, targetPort, {
270
+ signal: init.signal,
271
+ rejectUnauthorized: tlsOptions.proxyRejectUnauthorized ?? true,
272
+ ...(tlsOptions.proxyCa ? { ca: tlsOptions.proxyCa } : {}),
273
+ });
274
+ const socket = tls.connect({
275
+ socket: tunnel,
276
+ servername: net.isIP(targetHost) ? undefined : targetHost,
277
+ ALPNProtocols: ['http/1.1'],
278
+ rejectUnauthorized: tlsOptions.rejectUnauthorized ?? true,
279
+ ...(tlsOptions.ca ? { ca: tlsOptions.ca } : {}),
280
+ });
281
+ const req = https.request({
282
+ host: targetHost,
283
+ port: targetPort,
284
+ path: target.pathname + target.search,
285
+ method: init.method || 'GET',
286
+ headers,
287
+ agent: false,
288
+ createConnection: () => socket,
289
+ }, (res) => {
290
+ const status = res.statusCode || 502;
291
+ if (init.redirect === 'error' && status >= 300 && status < 400 && res.headers.location) {
292
+ res.destroy();
293
+ done(new TypeError('Unexpected redirect'));
294
+ return;
295
+ }
296
+ const responseHeaders = new Headers();
297
+ for (const [k, v] of Object.entries(res.headers)) {
298
+ if (v === undefined) continue;
299
+ if (Array.isArray(v)) for (const item of v) responseHeaders.append(k, item);
300
+ else responseHeaders.set(k, String(v));
301
+ }
302
+ const webBody = status === 204 || status === 304 || init.method === 'HEAD' ? null : Readable.toWeb(res);
303
+ done(null, new Response(webBody, { status, headers: responseHeaders }));
304
+ });
305
+ const onAbort = () => {
306
+ req.destroy();
307
+ socket.destroy();
308
+ tunnel.destroy();
309
+ done(init.signal?.reason || new DOMException('Aborted', 'AbortError'));
310
+ };
311
+ init.signal?.addEventListener('abort', onAbort, { once: true });
312
+ req.on('error', (err) => {
313
+ socket.destroy();
314
+ tunnel.destroy();
315
+ done(err);
316
+ });
317
+ if (body) req.write(body);
318
+ req.end();
319
+ });
320
+ }
@@ -1,10 +1,10 @@
1
1
  // Read-only Google quota RPC; no generation, quota reset, retry, redirects or model switching.
2
- import http2 from "node:http2";
3
2
  import {GrpcMessageReader,frameGrpcMessage} from "../../native-wire/robin-current.mjs";
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";
6
6
  const failure=(code,status=502)=>Object.assign(new Error(code),{code,status});
7
- export async function fetchGoogleUsageInfo(accessToken,{signal,timeoutMs=10000,connect=http2.connect}={}) {
7
+ export async function fetchGoogleUsageInfo(accessToken,{signal,timeoutMs=10000,connect=connectHttp2}={}) {
8
8
  if(typeof accessToken!=="string"||!accessToken||accessToken.length>65536||/\s/.test(accessToken))throw failure("QUOTA_CREDENTIAL_REQUIRED",401);
9
9
  if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>15000)throw failure("INVALID_QUOTA_TIMEOUT",400);
10
10
  if(signal?.aborted)throw failure("QUOTA_CANCELLED",499);
@@ -1,16 +1,16 @@
1
1
  // Native Gemini main-service terms only. Triggered by a user-initiated OAuth login.
2
- import http2 from "node:http2";
3
2
  import crypto from "node:crypto";
4
3
  import { parse, lengthDelimited as message, varintField as integer } from "../../native-wire/protobuf.mjs";
5
4
  import { GrpcMessageReader, frameGrpcMessage, buildRequestMetadata } from "../../native-wire/robin-current.mjs";
6
5
  import { decodeGrpcMessage, sanitizeUpstreamMessage } from "./native-evidence.mjs";
6
+ import { connectHttp2 } from "./outbound-proxy.mjs";
7
7
  export const TERMS_VERSION_RPC = "/assistant.mobile.robin.RobinService/GetTermsOfServiceVersion";
8
8
  export const TERMS_ACCEPT_RPC = "/assistant.mobile.robin.RobinService/AcceptTermsOfService";
9
9
  const origin = "https://robinfrontend-pa.googleapis.com";
10
10
  const fail = (code, status = 502) => Object.assign(new Error(code), { code, status });
11
11
  const SAFE = new Set(["TOS_CREDENTIAL_REQUIRED", "TOS_CANCELLED", "TOS_TIMEOUT", "TOS_RATE_LIMITED", "TOS_AUTH_REJECTED", "TOS_HTTP_REJECTED", "TOS_INVALID_STATUS", "TOS_PRECONDITION_REQUIRED", "TOS_UPSTREAM_REJECTED", "TOS_CONNECTION_FAILED", "TOS_STREAM_RESET", "TOS_STREAM_FAILED", "TOS_STREAM_CLOSED_EARLY", "TOS_RESPONSE_TOO_LARGE", "TOS_INVALID_RESPONSE", "TOS_INCOMPLETE_RESPONSE", "TOS_VERSION_MISSING", "TOS_COMPLETION_FAILED"]);
12
12
  export const termsFailureCode = error => SAFE.has(error?.code) ? error.code : "TOS_COMPLETION_FAILED";
13
- export async function termsRpc(accessToken, rpc, payload, { signal, timeoutMs = 10000, connect = http2.connect } = {}) {
13
+ export async function termsRpc(accessToken, rpc, payload, { signal, timeoutMs = 10000, connect = connectHttp2 } = {}) {
14
14
  if (![TERMS_VERSION_RPC, TERMS_ACCEPT_RPC].includes(rpc) || !Buffer.isBuffer(payload) || payload.length > 4096) throw fail("TOS_INVALID_RESPONSE");
15
15
  if (typeof accessToken !== "string" || !accessToken || accessToken.length > 65536 || /\s/.test(accessToken)) throw fail("TOS_CREDENTIAL_REQUIRED", 401);
16
16
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 15000) throw fail("TOS_INVALID_RESPONSE", 400);
@@ -1,10 +1,11 @@
1
1
  import { parseRemoteImageUrl } from './image-url.mjs';
2
2
  import { protocolError } from './tool-protocol.mjs';
3
3
 
4
- export const MAX_IMAGES = 4;
5
- export const MAX_IMAGE_BYTES = 2 * 1024 * 1024;
6
- export const MAX_TOTAL_IMAGE_BYTES = 2 * 1024 * 1024;
7
- export const MAX_IMAGE_URL_BYTES = Math.ceil(MAX_TOTAL_IMAGE_BYTES / 3) * 4 + 1024;
4
+ export const MAX_IMAGES = 256;
5
+ export const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
6
+ export const MAX_TOTAL_IMAGE_BYTES = 256 * 1024 * 1024;
7
+ export const MAX_IMAGE_URL_BYTES = Math.ceil(MAX_IMAGE_BYTES / 3) * 4 + 1024;
8
+ export const MAX_TOTAL_IMAGE_URL_BYTES = Math.ceil(MAX_TOTAL_IMAGE_BYTES / 3) * 4 + MAX_IMAGES * 1024;
8
9
  const MAX_PIXELS = 40_000_000;
9
10
  const fail = (code, status = 400) => { throw protocolError(code, status); };
10
11
  const pngMagic = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
@@ -11,7 +11,7 @@ import { MODEL_ALIASES, MODEL_MODES, NATIVE_MODELS, canonicalModel, normalizeCha
11
11
  import { RESPONSE_TOOL_IDENTITIES } from './responses-tool-namespaces.mjs';
12
12
  import { safeNativeEvidence } from './gateway/native-evidence.mjs';
13
13
  import { decodePassiveQuota, mergeQuotaObservation } from './gateway/quota.mjs';
14
- import { uploadNativeImages } from './gateway/image-upload.mjs';
14
+ import { uploadNativeImages, createImageBlobCache } from './gateway/image-upload.mjs';
15
15
  import { downloadRemoteImages } from './gateway/image-download.mjs';
16
16
  import { quotaDowngradeCode } from './gateway/quota-failover.mjs';
17
17
  import { inspectNativeOutput } from './gateway/output-recovery.mjs';
@@ -100,26 +100,89 @@ function safeFailure(error) {
100
100
  }
101
101
 
102
102
 
103
+ const validateIdleMs = (value, name) => {
104
+ if (value === null || value === undefined) return null;
105
+ if (!Number.isInteger(value) || value < 1 || value > 600_000) throw new TypeError(`invalid ${name}`);
106
+ return value;
107
+ };
108
+ const IDLE_TIMEOUT_SENTINEL = Symbol('IDLE_TIMEOUT_SENTINEL');
109
+
103
110
  export class NativeDirectProvider {
104
- constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, timeoutMs = 600_000, modelAlias = 'gemini-neon', continuation = false, allowTextSnapshotReplacement = false, allowAutoModel = false } = {}) {
111
+ constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, blobCache = createImageBlobCache(), timeoutMs = 600_000, postCompleteGraceMs = 2_000, postToolIdleMs = 6_000, postOutputIdleMs = 15_000, modelAlias = 'gemini-neon', continuation = false, allowTextSnapshotReplacement = false, allowAutoModel = false } = {}) {
105
112
  if (!authManager || typeof authManager.getValidAccessToken !== 'function') throw new TypeError('authManager.getValidAccessToken required');
106
113
  if (typeof openTurn !== 'function') throw new TypeError('openTurn required');
107
114
  if (typeof uploadImages !== 'function') throw new TypeError('uploadImages required');
108
115
  if (typeof downloadImages !== 'function') throw new TypeError('downloadImages required');
109
116
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600_000) throw new TypeError('invalid timeout');
117
+ const resolvedPostCompleteGraceMs = validateIdleMs(postCompleteGraceMs, 'postCompleteGraceMs');
118
+ const resolvedPostToolIdleMs = validateIdleMs(postToolIdleMs, 'postToolIdleMs');
119
+ const resolvedPostOutputIdleMs = validateIdleMs(postOutputIdleMs, 'postOutputIdleMs');
110
120
  if (continuation !== false) throw protocolError('UNSUPPORTED_CONTINUATION', 400);
111
121
  if (typeof allowAutoModel !== 'boolean') throw new TypeError('invalid auto model policy');
112
122
  const resolvedAlias = canonicalModel(modelAlias);
113
123
  const allowedModels = allowAutoModel ? [...NATIVE_MODELS, 'gemini-auto'] : NATIVE_MODELS;
114
124
  if (!allowedModels.includes(resolvedAlias)) throw protocolError('UNSUPPORTED_MODEL', 400);
115
125
  this.authManager = authManager; this.openTurn = openTurn; this.uploadImages = uploadImages; this.timeoutMs = timeoutMs;
126
+ this.postCompleteGraceMs = resolvedPostCompleteGraceMs;
127
+ this.postToolIdleMs = resolvedPostToolIdleMs;
128
+ this.postOutputIdleMs = resolvedPostOutputIdleMs;
116
129
  this.downloadImages = downloadImages;
130
+ this.blobCache = blobCache ?? null;
117
131
  if (typeof allowTextSnapshotReplacement !== 'boolean') throw new TypeError('invalid snapshot policy');
118
132
  this.allowTextSnapshotReplacement = allowTextSnapshotReplacement;
119
133
  this.allowAutoModel = allowAutoModel;
120
134
  this.modelAlias = resolvedAlias; this.continuationEnabled = false;
121
135
  }
122
136
 
137
+ async #resolveImageAttachments(accountId, token, images, { signal, timeoutMs, bypassCache = false } = {}) {
138
+ if (!images.length) return { attachments: [], usedCachedKeys: [] };
139
+ const uploadTimeoutMs = Math.min(timeoutMs, 180000);
140
+ const cache = !bypassCache ? this.blobCache : null;
141
+ const scope = `${accountId}:${crypto.createHash('sha256').update(String(token)).digest('hex').slice(0, 16)}`;
142
+ const keys = images.map(img => (this.blobCache && Buffer.isBuffer(img.data) ? this.blobCache.keyOf(scope, img.mimeType, img.data) : null));
143
+ const attachments = new Array(images.length);
144
+ const usedCachedKeys = [];
145
+ const missImages = [];
146
+ const missKeyToSlot = new Map();
147
+ const missSlotIndices = [];
148
+ for (let i = 0; i < images.length; i++) {
149
+ const key = keys[i];
150
+ const cached = cache && key ? cache.get(key) : null;
151
+ if (cached && cached.mimeType === images[i].mimeType) {
152
+ attachments[i] = cached;
153
+ usedCachedKeys.push(key);
154
+ continue;
155
+ }
156
+ if (key && missKeyToSlot.has(key)) {
157
+ missSlotIndices[missKeyToSlot.get(key)].push(i);
158
+ } else {
159
+ const slot = missImages.length;
160
+ if (key) missKeyToSlot.set(key, slot);
161
+ missImages.push(images[i]);
162
+ missSlotIndices.push([i]);
163
+ }
164
+ }
165
+ if (missImages.length) {
166
+ const uploaded = await this.uploadImages(token, missImages, { signal, timeoutMs: uploadTimeoutMs });
167
+ if (
168
+ !Array.isArray(uploaded) ||
169
+ uploaded.length !== missImages.length ||
170
+ uploaded.some((attachment, index) => attachment?.mimeType !== missImages[index].mimeType || typeof attachment.blobId !== 'string' || !attachment.blobId.length)
171
+ ) {
172
+ fail('INVALID_NATIVE_IMAGE_UPLOAD');
173
+ }
174
+ for (let slot = 0; slot < uploaded.length; slot++) {
175
+ const item = uploaded[slot];
176
+ for (const targetIndex of missSlotIndices[slot]) {
177
+ attachments[targetIndex] = item;
178
+ const key = keys[targetIndex];
179
+ if (this.blobCache && key) this.blobCache.set(key, item);
180
+ }
181
+ }
182
+ }
183
+ return { attachments, usedCachedKeys };
184
+ }
185
+
123
186
  buildTurn(body) { return buildCanonicalPrompt(normalizeChatRequest(body, { allowAutoModel: this.allowAutoModel })); }
124
187
 
125
188
  async runNativeSearch(accountId, body, onDelta, context) {
@@ -178,6 +241,15 @@ export class NativeDirectProvider {
178
241
  async runTurn(accountId, canonicalChatBody, onDelta = () => {}, context = {}) {
179
242
  const timeoutMs = context.timeoutMs ?? this.timeoutMs;
180
243
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600000) fail('INVALID_TIMEOUT', 400);
244
+ const postCompleteGraceMs = context.postCompleteGraceMs === undefined
245
+ ? this.postCompleteGraceMs
246
+ : validateIdleMs(context.postCompleteGraceMs, 'postCompleteGraceMs');
247
+ const postToolIdleMs = context.postToolIdleMs === undefined
248
+ ? this.postToolIdleMs
249
+ : validateIdleMs(context.postToolIdleMs, 'postToolIdleMs');
250
+ const postOutputIdleMs = context.postOutputIdleMs === undefined
251
+ ? this.postOutputIdleMs
252
+ : validateIdleMs(context.postOutputIdleMs, 'postOutputIdleMs');
181
253
  const body = normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
182
254
  if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
183
255
  const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode);
@@ -273,22 +345,91 @@ export class NativeDirectProvider {
273
345
  catch (error) { if (error instanceof ProtocolError || ['NATIVE_PERMISSION_OR_AUTH','NATIVE_CREDENTIAL_REQUIRED','OAUTH_REFRESH_FAILED','ACCOUNT_LOGIN_REQUIRED'].includes(error?.code)) throw safeFailure(error); fail('NATIVE_AUTH_FAILED', 503); }
274
346
  if (controller.signal.aborted) await deadline;
275
347
  phase = 'upload';
276
- const attachments = images.length ? await bounded(this.uploadImages(token, images, { signal: controller.signal, timeoutMs: Math.min(timeoutMs, 60000) })) : [];
277
- if (!Array.isArray(attachments) || attachments.length !== images.length || attachments.some((attachment, index) => attachment?.mimeType !== images[index].mimeType || typeof attachment.blobId !== 'string' || !attachment.blobId.length)) fail('INVALID_NATIVE_IMAGE_UPLOAD');
348
+ let { attachments, usedCachedKeys } = await bounded(this.#resolveImageAttachments(accountId, token, images, { signal: controller.signal, timeoutMs }));
278
349
  if (controller.signal.aborted) await deadline;
279
350
  // The product injects its independent transport; historical research ledgers are untouched.
280
- phase = 'open';
281
- turn = this.openTurn(token, { messages, images: attachments, temporaryChat: true,
282
- modeCategory: isAutoModel ? null : modeCategory,
283
- thinkingLevel: isAutoModel ? null : body.thinking_level,
284
- ...(isAutoModel ? { smartModelSelection: true } : {}),
285
- timeoutMs, signal: controller.signal,
286
- emitHeaders: incremental,
287
- ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
288
- iterator = turn.events[Symbol.asyncIterator]();
351
+ const STALE_BLOB_CODES = new Set(['NATIVE_HTTP_REJECTED', 'NATIVE_INVALID_STATUS', 'NATIVE_PRECONDITION_REQUIRED', 'NATIVE_TURN_FAILED']);
352
+ for (let blobAttempt = 0; ; blobAttempt++) {
353
+ phase = 'open';
354
+ turn = this.openTurn(token, { messages, images: attachments, temporaryChat: true,
355
+ modeCategory: isAutoModel ? null : modeCategory,
356
+ thinkingLevel: isAutoModel ? null : body.thinking_level,
357
+ ...(isAutoModel ? { smartModelSelection: true } : {}),
358
+ timeoutMs, signal: controller.signal,
359
+ emitHeaders: incremental,
360
+ ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
361
+ iterator = turn.events[Symbol.asyncIterator]();
362
+ try {
363
+ const isCleanPostOutputIdleStall = () => {
364
+ if (!rawText.trim()) return false;
365
+ if (/^\s*I'm on it\.\s*Responses with Deep Think can take some time, so check back in a bit\.\s*https?:\/\/googleusercontent\.com\/agentic_processing_chip\/\d+\s*$/i.test(rawText)) return false;
366
+ try {
367
+ const probe = createToolCallSplitter({ policy });
368
+ const probeItems = [...probe.push(rawText), ...probe.flush()];
369
+ const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
370
+ const probeContent = probeItems.filter(it => it.type === 'content').map(it => it.text).join('');
371
+ if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return false;
372
+ if (body.parallel_tool_calls === false && probeCalls.length > 1) return false;
373
+ validateToolCompletion(probeCalls, policy);
374
+ if (!probeCalls.length && !probeContent.trim()) return false;
375
+ if (body.response_format && !probeCalls.length) validateStructuredOutputText(probeContent, body.response_format);
376
+ return true;
377
+ } catch {
378
+ return false;
379
+ }
380
+ };
381
+ const nextEventWithIdle = async () => {
382
+ const verified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
383
+ // Never arm an idle timer unless we already have verified, complete, deliverable output;
384
+ // otherwise a slow mid-tool-call or mid-JSON pause would be falsely killed with 504 -> 422.
385
+ const idleKind = (modelComplete && verified && rawText.trim().length > 0) ? 'post_complete'
386
+ : (verified && liveCalls.length > 0 ? 'post_tool'
387
+ : (verified && liveCalls.length === 0 && isCleanPostOutputIdleStall() ? 'post_output' : null));
388
+ const idleMs = idleKind === 'post_complete' ? postCompleteGraceMs
389
+ : idleKind === 'post_tool' ? postToolIdleMs
390
+ : idleKind === 'post_output' ? postOutputIdleMs
391
+ : null;
392
+ const nextPromise = iterator.next();
393
+ if (idleMs === null) return bounded(nextPromise);
394
+ nextPromise.catch(() => {});
395
+ let idleTimer = null;
396
+ try {
397
+ return await Promise.race([
398
+ bounded(nextPromise),
399
+ new Promise(resolve => {
400
+ idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified }), idleMs);
401
+ idleTimer.unref?.();
402
+ }),
403
+ ]);
404
+ } finally {
405
+ if (idleTimer !== null) clearTimeout(idleTimer);
406
+ }
407
+ };
289
408
  for (;;) {
290
409
  phase = 'read';
291
- const item = await bounded(iterator.next());
410
+ const item = await nextEventWithIdle();
411
+ if (item && item[IDLE_TIMEOUT_SENTINEL]) {
412
+ const idleKind = item[IDLE_TIMEOUT_SENTINEL];
413
+ if (idleKind === 'post_complete' && item.verified && rawText.trim().length > 0) {
414
+ note('post_complete_idle_finish', { frames, textBytes: Buffer.byteLength(rawText) });
415
+ try { turn?.cancel(); } catch {}
416
+ ended = true;
417
+ httpStatus = httpStatus ?? 200;
418
+ grpc = grpc ?? 0;
419
+ break;
420
+ }
421
+ note(`${idleKind}_idle_timeout`, {
422
+ frames,
423
+ calls: liveCalls.length,
424
+ textBytes: Buffer.byteLength(rawText),
425
+ });
426
+ try { turn?.cancel(); } catch {}
427
+ const idleError = protocolError('NATIVE_TURN_TIMEOUT', 504);
428
+ if (idleKind === 'post_output' && item.verified && isCleanPostOutputIdleStall()) {
429
+ idleError.postOutputIdleStall = true;
430
+ }
431
+ throw idleError;
432
+ }
292
433
  if (item.done) break;
293
434
  const event = item.value;
294
435
  if (incremental && event.type === 'headers') { await deliver({ start: true, response: identity }); continue; }
@@ -371,6 +512,18 @@ export class NativeDirectProvider {
371
512
  const delta = rawText.slice(liveSyncedLength);
372
513
  liveSyncedLength = rawText.length;
373
514
  await publish(liveSplitter.push(delta));
515
+ // Once valid tool_call(s) have been parsed and the model begins hallucinating
516
+ // a fake [Caller tool result], stop upstream immediately instead of waiting
517
+ // minutes for the model to finish generating discarded text.
518
+ if (liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
519
+ note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
520
+ try { turn?.cancel(); } catch {}
521
+ ended = true;
522
+ modelComplete = true;
523
+ httpStatus = httpStatus ?? 200;
524
+ grpc = grpc ?? 0;
525
+ break;
526
+ }
374
527
  }
375
528
  if (info.quotaObservation) {
376
529
  quotaFrames++;
@@ -387,6 +540,25 @@ export class NativeDirectProvider {
387
540
  if (event.httpStatus !== 200 || (grpc !== null && grpc !== undefined && grpc !== 0)) fail('NATIVE_TURN_FAILED');
388
541
  break;
389
542
  } else fail('INVALID_NATIVE_EVENT');
543
+ }
544
+ break;
545
+ } catch (turnErr) {
546
+ const safeErr = safeFailure(turnErr);
547
+ const canRetryFreshBlobs =
548
+ blobAttempt === 0 &&
549
+ usedCachedKeys.length > 0 &&
550
+ frames === 0 &&
551
+ !outputObserved &&
552
+ !controller.signal.aborted &&
553
+ STALE_BLOB_CODES.has(safeErr.code);
554
+ if (!canRetryFreshBlobs) throw turnErr;
555
+ for (const key of usedCachedKeys) this.blobCache?.delete(key);
556
+ try { turn?.cancel(); } catch {}
557
+ turn = null; iterator = null; ended = false; grpc = null; httpStatus = null;
558
+ phase = 'upload';
559
+ ({ attachments, usedCachedKeys } = await bounded(this.#resolveImageAttachments(accountId, token, images, { signal: controller.signal, timeoutMs, bypassCache: true })));
560
+ if (controller.signal.aborted) await deadline;
561
+ }
390
562
  }
391
563
  phase = 'validate';
392
564
  if (downgrade) fail('MODEL_DOWNGRADE_REJECTED');
@@ -9,7 +9,7 @@ import { plainObject, protocolError, parseBoundedJson, compileToolPolicy, valida
9
9
  import { stripSchemaAnnotations } from './prompt-tool-schema.mjs';
10
10
  import { normalizeChatResponseFormat, normalizeResponsesText, buildStructuredOutputInstruction } from './gateway/structured-output.mjs';
11
11
  import { isSafeWebUrl } from './gateway/native-search-metadata.mjs';
12
- import { MAX_IMAGES, MAX_IMAGE_URL_BYTES, normalizeImageUrl, collectImageInputs } from './image-input.mjs';
12
+ import { MAX_IMAGES, MAX_IMAGE_URL_BYTES, MAX_TOTAL_IMAGE_URL_BYTES, normalizeImageUrl, collectImageInputs } from './image-input.mjs';
13
13
  import { RESPONSE_TOOL_IDENTITIES, normalizeResponsesTools, responsesCallFields } from './responses-tool-namespaces.mjs';
14
14
  import { toResponsesUsage } from './openai-usage.mjs';
15
15
 
@@ -83,8 +83,11 @@ function requestBudget(root) {
83
83
  const visit = (value, depth, image = false) => {
84
84
  if (++nodes > 32768 || depth > 32) fail('REQUEST_TOO_LARGE', 413);
85
85
  if (typeof value === 'string') {
86
- if (image) imageBytes += Buffer.byteLength(value);
87
- else bytes += Buffer.byteLength(value);
86
+ if (image) {
87
+ const len = Buffer.byteLength(value);
88
+ if (len > MAX_IMAGE_URL_BYTES) fail('IMAGE_TOO_LARGE', 413);
89
+ imageBytes += len;
90
+ } else bytes += Buffer.byteLength(value);
88
91
  }
89
92
  else if (value === null || value === undefined || typeof value === 'boolean') bytes += 4;
90
93
  else if (typeof value === 'number' && Number.isFinite(value)) bytes += 8;
@@ -105,7 +108,7 @@ function requestBudget(root) {
105
108
  }
106
109
  ancestors.delete(value);
107
110
  }
108
- if (bytes > REQUEST_MAX_NON_IMAGE_BYTES || imageBytes > MAX_IMAGE_URL_BYTES) fail('REQUEST_TOO_LARGE', 413);
111
+ if (bytes > REQUEST_MAX_NON_IMAGE_BYTES || imageBytes > MAX_TOTAL_IMAGE_URL_BYTES) fail('REQUEST_TOO_LARGE', 413);
109
112
  };
110
113
  visit(root, 0);
111
114
  }
@@ -335,7 +338,7 @@ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
335
338
  if (!Array.isArray(payload.messages) || !payload.messages.length || payload.messages.length > MAX_MESSAGES) fail('MESSAGES_REQUIRED');
336
339
  const pending = new Set(), seen = new Set();
337
340
  const messages = payload.messages.map(message => {
338
- keys(message, ['role', 'content', 'name', 'tool_calls', 'tool_call_id', 'refusal', 'parsed', 'annotations'], 'messages');
341
+ keys(message, ['role', 'content', 'name', 'tool_calls', 'tool_call_id', 'refusal', 'parsed', 'annotations', 'reasoning_content', 'reasoning'], 'messages');
339
342
  const role = message.role;
340
343
  if (!['system', 'developer', 'user', 'assistant', 'tool'].includes(role)) fail('UNSUPPORTED_ROLE');
341
344
  if (message.name !== undefined && message.name !== null) {
@@ -346,6 +349,17 @@ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
346
349
  // SDK stream accumulators attach null parsing/refusal metadata on replay.
347
350
  // Only inert null is accepted; structured/refusal content is unsupported.
348
351
  for (const key of ['refusal', 'parsed']) if (message[key] !== undefined && (role !== 'assistant' || message[key] !== null)) fail('UNSUPPORTED_PARAMETER', 400, `messages.${key}`);
352
+ // OpenAI-compatible reasoning clients (OpenClaw, DeepSeek/LiteLLM, Pi) replay
353
+ // assistant reasoning_content/reasoning strings or null on historical turns.
354
+ // Validate UTF-8/bounds and strip before canonical prompt construction.
355
+ for (const key of ['reasoning_content', 'reasoning']) {
356
+ if (message[key] !== undefined) {
357
+ if (role !== 'assistant' || (message[key] !== null && typeof message[key] !== 'string')) {
358
+ fail('UNSUPPORTED_PARAMETER', 400, `messages.${key}`);
359
+ }
360
+ if (typeof message[key] === 'string') text(message[key]);
361
+ }
362
+ }
349
363
  if (message.annotations !== undefined) {
350
364
  if (role !== 'assistant') fail('UNSUPPORTED_ANNOTATIONS');
351
365
  validateReplayAnnotations(message.annotations, { chat: true });
@@ -343,5 +343,6 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
343
343
  return safe;
344
344
  },
345
345
  get toolCallCount() { return seen; },
346
+ get suppressed() { return suppressed; },
346
347
  };
347
348
  }