pi-gemini-app 0.1.4 → 0.1.7

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,7 @@
1
1
  # `pi-gemini-app` — Google Gemini App Provider for Pi
2
2
 
3
+ ![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
+
3
5
  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.
4
6
 
5
7
  > **Disclaimer**: Unofficial interoperability software. Not affiliated with, endorsed by, or sponsored by Google. You must authenticate personally with your own eligible Google account.
@@ -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
  });
@@ -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.4",
3
+ "version": "0.1.7",
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": [
@@ -33,6 +33,7 @@
33
33
  "node": ">=22.0.0"
34
34
  },
35
35
  "pi": {
36
+ "image": "https://raw.githubusercontent.com/ShawTim/gemini-app2api/main/docs/assets/pi-extension.jpg",
36
37
  "extensions": [
37
38
  "./extensions/pi/index.js"
38
39
  ]
@@ -65,6 +66,7 @@
65
66
  "src/gateway/native-search-metadata.mjs",
66
67
  "src/gateway/native-transport.mjs",
67
68
  "src/gateway/oauth-client-defaults.mjs",
69
+ "src/gateway/outbound-proxy.mjs",
68
70
  "src/gateway/output-recovery.mjs",
69
71
  "src/gateway/quota-failover.mjs",
70
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
  }