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.
@@ -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 = 8_000, postToolIdleMs = 15_000, postOutputIdleMs = 45_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,68 @@ 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 nextEventWithIdle = async () => {
364
+ const verified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
365
+ const committed = committedOutput();
366
+ const idleKind = modelComplete ? 'post_complete'
367
+ : (verified && liveCalls.length > 0 ? 'post_tool'
368
+ : (verified && committed.publishedBytes > 0 ? 'post_output' : null));
369
+ const idleMs = idleKind === 'post_complete' ? postCompleteGraceMs
370
+ : idleKind === 'post_tool' ? postToolIdleMs
371
+ : idleKind === 'post_output' ? postOutputIdleMs
372
+ : null;
373
+ const nextPromise = iterator.next();
374
+ if (idleMs === null) return bounded(nextPromise);
375
+ nextPromise.catch(() => {});
376
+ let idleTimer = null;
377
+ try {
378
+ return await Promise.race([
379
+ bounded(nextPromise),
380
+ new Promise(resolve => {
381
+ idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified }), idleMs);
382
+ idleTimer.unref?.();
383
+ }),
384
+ ]);
385
+ } finally {
386
+ if (idleTimer !== null) clearTimeout(idleTimer);
387
+ }
388
+ };
289
389
  for (;;) {
290
390
  phase = 'read';
291
- const item = await bounded(iterator.next());
391
+ const item = await nextEventWithIdle();
392
+ if (item && item[IDLE_TIMEOUT_SENTINEL]) {
393
+ const idleKind = item[IDLE_TIMEOUT_SENTINEL];
394
+ if (idleKind === 'post_complete' && item.verified && rawText.trim().length > 0) {
395
+ note('post_complete_idle_finish', { frames, textBytes: Buffer.byteLength(rawText) });
396
+ try { turn?.cancel(); } catch {}
397
+ ended = true;
398
+ httpStatus = httpStatus ?? 200;
399
+ grpc = grpc ?? 0;
400
+ break;
401
+ }
402
+ note(`${idleKind}_idle_timeout`, {
403
+ frames,
404
+ calls: liveCalls.length,
405
+ textBytes: Buffer.byteLength(rawText),
406
+ });
407
+ try { turn?.cancel(); } catch {}
408
+ throw protocolError('NATIVE_TURN_TIMEOUT', 504);
409
+ }
292
410
  if (item.done) break;
293
411
  const event = item.value;
294
412
  if (incremental && event.type === 'headers') { await deliver({ start: true, response: identity }); continue; }
@@ -371,6 +489,18 @@ export class NativeDirectProvider {
371
489
  const delta = rawText.slice(liveSyncedLength);
372
490
  liveSyncedLength = rawText.length;
373
491
  await publish(liveSplitter.push(delta));
492
+ // Once valid tool_call(s) have been parsed and the model begins hallucinating
493
+ // a fake [Caller tool result], stop upstream immediately instead of waiting
494
+ // minutes for the model to finish generating discarded text.
495
+ if (liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
496
+ note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
497
+ try { turn?.cancel(); } catch {}
498
+ ended = true;
499
+ modelComplete = true;
500
+ httpStatus = httpStatus ?? 200;
501
+ grpc = grpc ?? 0;
502
+ break;
503
+ }
374
504
  }
375
505
  if (info.quotaObservation) {
376
506
  quotaFrames++;
@@ -387,6 +517,25 @@ export class NativeDirectProvider {
387
517
  if (event.httpStatus !== 200 || (grpc !== null && grpc !== undefined && grpc !== 0)) fail('NATIVE_TURN_FAILED');
388
518
  break;
389
519
  } else fail('INVALID_NATIVE_EVENT');
520
+ }
521
+ break;
522
+ } catch (turnErr) {
523
+ const safeErr = safeFailure(turnErr);
524
+ const canRetryFreshBlobs =
525
+ blobAttempt === 0 &&
526
+ usedCachedKeys.length > 0 &&
527
+ frames === 0 &&
528
+ !outputObserved &&
529
+ !controller.signal.aborted &&
530
+ STALE_BLOB_CODES.has(safeErr.code);
531
+ if (!canRetryFreshBlobs) throw turnErr;
532
+ for (const key of usedCachedKeys) this.blobCache?.delete(key);
533
+ try { turn?.cancel(); } catch {}
534
+ turn = null; iterator = null; ended = false; grpc = null; httpStatus = null;
535
+ phase = 'upload';
536
+ ({ attachments, usedCachedKeys } = await bounded(this.#resolveImageAttachments(accountId, token, images, { signal: controller.signal, timeoutMs, bypassCache: true })));
537
+ if (controller.signal.aborted) await deadline;
538
+ }
390
539
  }
391
540
  phase = 'validate';
392
541
  if (downgrade) fail('MODEL_DOWNGRADE_REJECTED');