pi-gemini-app 0.1.7 → 0.1.9

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,5 +1,6 @@
1
1
  import { createGeminiOAuthAuth } from './auth.js';
2
2
  import { createGeminiStreamHandler } from './stream.js';
3
+ import { MODEL_SPECS } from '../../src/openai-contract.mjs';
3
4
  import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
4
5
  import { decodeUsageInfo as defaultDecodeUsageInfo } from '../../src/gateway/quota.mjs';
5
6
  import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
@@ -25,81 +26,30 @@ export function filterGeminiModels(models, credential) {
25
26
  return models;
26
27
  }
27
28
 
28
- export const MODELS = Object.freeze([
29
- {
30
- id: 'gemini-neon',
31
- name: 'Gemini Neon',
32
- api: API_ID,
33
- provider: PROVIDER_ID,
34
- baseUrl: BASE_URL,
35
- type: 'chat',
36
- contextWindow: 512000,
37
- maxTokens: 16384,
38
- input: ['text', 'image'],
39
- reasoning: true,
40
- thinkingLevelMap: {
41
- minimal: 'minimal',
42
- low: 'low',
43
- medium: 'medium',
44
- high: 'high',
45
- xhigh: 'xhigh',
46
- },
47
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
48
- },
49
- {
50
- id: 'gemini-hydrogen',
51
- name: 'Gemini Hydrogen',
52
- api: API_ID,
53
- provider: PROVIDER_ID,
54
- baseUrl: BASE_URL,
55
- type: 'chat',
56
- contextWindow: 512000,
57
- maxTokens: 16384,
58
- input: ['text', 'image'],
59
- reasoning: true,
60
- thinkingLevelMap: {
61
- minimal: 'minimal',
62
- low: 'low',
63
- medium: 'medium',
64
- high: 'high',
65
- xhigh: 'xhigh',
66
- },
67
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
68
- },
69
- {
70
- id: 'gemini-flash-lite',
71
- name: 'Gemini Flash Lite',
72
- api: API_ID,
73
- provider: PROVIDER_ID,
74
- baseUrl: BASE_URL,
75
- type: 'chat',
76
- contextWindow: 128000,
77
- maxTokens: 8192,
78
- input: ['text', 'image'],
79
- reasoning: true,
80
- thinkingLevelMap: {
81
- minimal: 'minimal',
82
- low: 'low',
83
- medium: 'medium',
84
- high: 'high',
85
- xhigh: 'xhigh',
86
- },
87
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
88
- },
89
- {
90
- id: 'gemini-auto',
91
- name: 'Gemini Auto',
29
+ const PI_THINKING_LEVEL_MAP = Object.freeze({
30
+ minimal: 'minimal',
31
+ low: 'low',
32
+ medium: 'medium',
33
+ high: 'high',
34
+ xhigh: 'xhigh',
35
+ });
36
+
37
+ export const MODELS = Object.freeze(
38
+ Object.entries(MODEL_SPECS).map(([id, spec]) => ({
39
+ id,
40
+ name: spec.name,
92
41
  api: API_ID,
93
42
  provider: PROVIDER_ID,
94
43
  baseUrl: BASE_URL,
95
44
  type: 'chat',
96
- contextWindow: 128000,
97
- maxTokens: 8192,
45
+ contextWindow: spec.contextWindow,
46
+ maxTokens: spec.maxTokens,
98
47
  input: ['text', 'image'],
99
- reasoning: false,
48
+ reasoning: spec.reasoning,
49
+ ...(spec.reasoning ? { thinkingLevelMap: { ...PI_THINKING_LEVEL_MAP } } : {}),
100
50
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
101
- },
102
- ]);
51
+ })),
52
+ );
103
53
 
104
54
  export function formatQuotaDisplay(usageInfo, subscriptionInfo) {
105
55
  const tier = subscriptionInfo?.tier;
@@ -3,7 +3,7 @@ import { createImageBlobCache } from '../../src/gateway/image-upload.mjs';
3
3
  import { NativeDirectProvider as DefaultNativeDirectProvider } from '../../src/native-provider.mjs';
4
4
  import { automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
5
5
  import { buildChatPayload as defaultBuildChatPayload } from './transcript.js';
6
- import { estimateUsage as defaultEstimateUsage } from '../../src/openai-usage.mjs';
6
+ import { estimateUsage as defaultEstimateUsage, measurePromptImagePayload } from '../../src/openai-usage.mjs';
7
7
 
8
8
  const PREFIX_BYTES = 2048;
9
9
 
@@ -239,6 +239,7 @@ export function createGeminiStreamHandler({
239
239
  let hasToolCalls = false;
240
240
 
241
241
  let promptChars = 0;
242
+ let imageCount = 0;
242
243
 
243
244
  function ensureTextBlock() {
244
245
  if (!textBlock) {
@@ -335,6 +336,7 @@ export function createGeminiStreamHandler({
335
336
  promptChars = Array.isArray(body?.messages)
336
337
  ? body.messages.reduce((n, m) => n + contentChars(m?.content), 0)
337
338
  : 0;
339
+ ({ imageCount } = measurePromptImagePayload(body));
338
340
 
339
341
  const authManager = {
340
342
  getValidAccessToken: async () => {
@@ -447,6 +449,14 @@ export function createGeminiStreamHandler({
447
449
  }
448
450
  break;
449
451
  } catch (turnError) {
452
+ if (
453
+ !options?.signal?.aborted &&
454
+ turnError?.code === 'NATIVE_TURN_TIMEOUT' &&
455
+ turnError?.unverifiedOutput !== true &&
456
+ (hasToolCalls || turnError?.postOutputIdleStall === true || publishedBytes >= PREFIX_BYTES)
457
+ ) {
458
+ break;
459
+ }
450
460
  if (
451
461
  !started &&
452
462
  attempts === 0 &&
@@ -472,7 +482,7 @@ export function createGeminiStreamHandler({
472
482
  await startOutput({ flushAll: true });
473
483
  endTextBlock();
474
484
 
475
- const est = estimateUsage({ promptChars, outputBytes: publishedBytes });
485
+ const est = estimateUsage({ promptChars, imageCount, outputBytes: publishedBytes });
476
486
  partial.usage = {
477
487
  input: est.prompt_tokens,
478
488
  output: est.completion_tokens,
@@ -494,8 +504,8 @@ export function createGeminiStreamHandler({
494
504
  error?.code === 'NATIVE_TURN_ABORTED' ||
495
505
  error?.code === 'REQUEST_CANCELLED';
496
506
  const stopReason = isAborted ? 'aborted' : 'error';
497
- if (publishedBytes > 0 || promptChars > 0) {
498
- const est = estimateUsage({ promptChars, outputBytes: publishedBytes });
507
+ if (publishedBytes > 0 || promptChars > 0 || imageCount > 0) {
508
+ const est = estimateUsage({ promptChars, imageCount, outputBytes: publishedBytes });
499
509
  partial.usage = {
500
510
  input: est.prompt_tokens,
501
511
  output: est.completion_tokens,
@@ -4,7 +4,8 @@
4
4
  import { lengthDelimited as message, varintField, varint, parse, MAX_MESSAGE_BYTES } from './protobuf.mjs';
5
5
  import { TextDecoder } from 'node:util';
6
6
 
7
- export const NATIVE_VERSION = '1.131.4.1198';
7
+ export const NATIVE_VERSION = '1.135.1.1291';
8
+ export const GATEWAY_USER_AGENT = 'gemini-app2api/1.0';
8
9
  const utf8 = new TextDecoder('utf-8', { fatal: true });
9
10
  function text(value) {
10
11
  if (typeof value !== 'string') throw new TypeError('Expected string');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
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": [
@@ -5,6 +5,7 @@ import { isIP } from 'node:net';
5
5
  import { parseRemoteImageUrl, isPublicImageAddress } from '../image-url.mjs';
6
6
  import { decodeImageBytes, MAX_IMAGES, MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES } from '../image-input.mjs';
7
7
  import { protocolError, ProtocolError } from '../tool-protocol.mjs';
8
+ import { GATEWAY_USER_AGENT } from '../../native-wire/robin-current.mjs';
8
9
 
9
10
  const fail = (code, status = 400) => { throw protocolError(code, status); };
10
11
  const REDIRECTS = new Set([301, 302, 303, 307, 308]);
@@ -54,7 +55,7 @@ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 }
54
55
  if (limit <= 0) fail('IMAGES_TOO_LARGE', 413);
55
56
  req = request(url, {
56
57
  method: 'GET', agent: false, maxHeaderSize: 16384,
57
- headers: { accept: 'image/png, image/jpeg, image/webp', 'accept-encoding': 'identity', 'user-agent': 'gemini-app2api/1.0' },
58
+ headers: { accept: 'image/png, image/jpeg, image/webp', 'accept-encoding': 'identity', 'user-agent': GATEWAY_USER_AGENT },
58
59
  // Pin after validation; preserve original Host, SNI and certificate verification.
59
60
  lookup: (_host, options, callback) => callback(null, ...(options?.all ? [[pinned]] : [pinned.address, pinned.family])),
60
61
  }, incoming => {
@@ -2,6 +2,7 @@ import crypto from 'node:crypto';
2
2
  import { protocolError } from '../tool-protocol.mjs';
3
3
  import { MAX_IMAGES, MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES } from '../image-input.mjs';
4
4
  import { connectHttp2 } from './outbound-proxy.mjs';
5
+ import { GATEWAY_USER_AGENT } from '../../native-wire/robin-current.mjs';
5
6
 
6
7
  const ORIGIN = 'https://push.clients6.google.com';
7
8
  export const DEFAULT_UPLOAD_CONCURRENCY = 8;
@@ -168,11 +169,11 @@ export async function uploadNativeImages(
168
169
  const onSessionError = () => { sessionFailed = true; stopAll(protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); };
169
170
  const uploadOne = async (image) => {
170
171
  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
+ const initial = await request({ ':method': 'POST', ':path': '/upload/', authorization: `Bearer ${token}`, 'content-length': '0', 'push-id': 'feeds/mcudyrk2a4khkz', 'x-tenant-id': 'bard-storage', 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'start', 'x-goog-upload-content-type': image.mimeType, 'x-goog-upload-content-length': String(image.data.length), 'user-agent': GATEWAY_USER_AGENT }, null, 8192);
172
173
  if (String(initial.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'active') fail('INVALID_RESPONSE');
173
174
  const location = boundedLocation(initial.headers['x-goog-upload-url']);
174
175
  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
+ const final = await request({ ':method': 'PUT', ':path': location.pathname + location.search, 'content-length': String(image.data.length), 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'upload, finalize', 'x-goog-upload-offset': '0', 'user-agent': GATEWAY_USER_AGENT }, image.data, 4096);
176
177
  if (String(final.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'final') fail('INVALID_RESPONSE');
177
178
  let blobId;
178
179
  try { blobId = new TextDecoder('utf-8', { fatal: true }).decode(final.body); } catch { fail('INVALID_RESPONSE'); }
@@ -13,6 +13,8 @@ import {
13
13
  import {
14
14
  GrpcMessageReader,
15
15
  frameGrpcMessage,
16
+ NATIVE_VERSION,
17
+ GATEWAY_USER_AGENT,
16
18
  } from "../../native-wire/robin-current.mjs";
17
19
  import { fault } from "./oauth-client-defaults.mjs";
18
20
  import { PROMPT_MAX_BYTES } from "../openai-contract.mjs";
@@ -36,9 +38,9 @@ ensureConnectAttemptTimeout();
36
38
  export const NATIVE_ORIGIN = "https://robinfrontend-pa.googleapis.com";
37
39
  export const NATIVE_RPC =
38
40
  "/assistant.mobile.robin.RobinService/ProcessQuery";
39
- // ProcessQuery compatibility snapshot checked against native 1.135.1.1291.
41
+ // ProcessQuery compatibility snapshot shared with native-wire/robin-current.mjs.
40
42
  // A protocol constant, not a runtime App dependency or copied device identity.
41
- export const NATIVE_COMPATIBILITY_VERSION = "1.135.1.1291";
43
+ export const NATIVE_COMPATIBILITY_VERSION = NATIVE_VERSION;
42
44
  export function openDirectTurn(
43
45
  token,
44
46
  {
@@ -304,7 +306,7 @@ export function openDirectTurn(
304
306
  "content-type": "application/grpc",
305
307
  "grpc-timeout": `${timeoutMs}m`,
306
308
  te: "trailers",
307
- "user-agent": "gemini-app2api/1.0",
309
+ "user-agent": GATEWAY_USER_AGENT,
308
310
  });
309
311
  request.on("response", headers => {
310
312
  note('peer_headers', { httpStatus: Number(headers[':status']), grpcStatus: Number(headers['grpc-status']) });
@@ -1,5 +1,5 @@
1
1
  // Read-only Google quota RPC; no generation, quota reset, retry, redirects or model switching.
2
- import {GrpcMessageReader,frameGrpcMessage} from "../../native-wire/robin-current.mjs";
2
+ import {GrpcMessageReader,frameGrpcMessage,GATEWAY_USER_AGENT} from "../../native-wire/robin-current.mjs";
3
3
  import {connectHttp2} from "./outbound-proxy.mjs";
4
4
  export const QUOTA_ORIGIN = "https://robinfrontend-pa.googleapis.com";
5
5
  export const QUOTA_RPC = "/assistant.mobile.robin.RobinService/GetUsageInfo";
@@ -25,7 +25,7 @@ export async function fetchGoogleUsageInfo(accessToken,{signal,timeoutMs=10000,c
25
25
  signal?.addEventListener("abort",abort,{once:true});timer=setTimeout(()=>finish(failure("QUOTA_TIMEOUT",504)),timeoutMs);
26
26
  try{
27
27
  client=connect(QUOTA_ORIGIN);client.on("error",()=>finish(failure("QUOTA_CONNECTION_FAILED")));
28
- request=client.request({":method":"POST",":path":QUOTA_RPC,authorization:"Bearer "+accessToken,"content-type":"application/grpc",te:"trailers","grpc-timeout":timeoutMs+"m","user-agent":"gemini-app2api/1.0"});
28
+ request=client.request({":method":"POST",":path":QUOTA_RPC,authorization:"Bearer "+accessToken,"content-type":"application/grpc",te:"trailers","grpc-timeout":timeoutMs+"m","user-agent":GATEWAY_USER_AGENT});
29
29
  request.on("response",status);request.on("trailers",status);
30
30
  request.on("data",chunk=>{if(settled)return;received+=chunk.length;if(received>1024*1024)return finish(failure("QUOTA_RESPONSE_TOO_LARGE"));try{payloads.push(...reader.push(chunk));if(payloads.length>1)finish(failure("QUOTA_INVALID_RESPONSE"));}catch{finish(failure("QUOTA_INVALID_RESPONSE"));}});
31
31
  request.on("error",()=>{if(!settled&&!reset())finish(failure("QUOTA_STREAM_FAILED"));});
@@ -1,7 +1,7 @@
1
1
  // Native Gemini main-service terms only. Triggered by a user-initiated OAuth login.
2
2
  import crypto from "node:crypto";
3
3
  import { parse, lengthDelimited as message, varintField as integer } from "../../native-wire/protobuf.mjs";
4
- import { GrpcMessageReader, frameGrpcMessage, buildRequestMetadata } from "../../native-wire/robin-current.mjs";
4
+ import { GrpcMessageReader, frameGrpcMessage, buildRequestMetadata, GATEWAY_USER_AGENT } from "../../native-wire/robin-current.mjs";
5
5
  import { decodeGrpcMessage, sanitizeUpstreamMessage } from "./native-evidence.mjs";
6
6
  import { connectHttp2 } from "./outbound-proxy.mjs";
7
7
  export const TERMS_VERSION_RPC = "/assistant.mobile.robin.RobinService/GetTermsOfServiceVersion";
@@ -45,7 +45,7 @@ export async function termsRpc(accessToken, rpc, payload, { signal, timeoutMs =
45
45
  signal?.addEventListener("abort", abort, { once: true }); timer = setTimeout(() => finish(fail("TOS_TIMEOUT", 504)), timeoutMs);
46
46
  try {
47
47
  client = connect(origin); client.on("error", () => finish(fail("TOS_CONNECTION_FAILED")));
48
- request = client.request({ ":method": "POST", ":path": rpc, authorization: "Bearer " + accessToken, "content-type": "application/grpc", te: "trailers", "grpc-timeout": timeoutMs + "m", "user-agent": "gemini-app2api/1.0" });
48
+ request = client.request({ ":method": "POST", ":path": rpc, authorization: "Bearer " + accessToken, "content-type": "application/grpc", te: "trailers", "grpc-timeout": timeoutMs + "m", "user-agent": GATEWAY_USER_AGENT });
49
49
  request.on("response", status); request.on("trailers", status);
50
50
  request.on("data", chunk => {
51
51
  if (settled) return; received += chunk.length;
@@ -104,7 +104,7 @@ export async function acceptGoogleMainTerms(accessToken, { signal, rpc = termsRp
104
104
  // The native main-terms builder uses the numeric oneof setter (wire 6),
105
105
  // not the old standalone enum (wire 1). Locale is already in metadata.
106
106
  const body = Buffer.concat([
107
- message(4, Buffer.from("gemini-app2api/1.0")), integer(5, 21),
107
+ message(4, Buffer.from(GATEWAY_USER_AGENT)), integer(5, 21),
108
108
  integer(6, versionNo), message(7, termsMetadata(language)),
109
109
  message(10, Buffer.concat([integer(1, seconds), ...(nanos ? [integer(2, nanos)] : [])])),
110
110
  ]);
@@ -7,7 +7,7 @@ import crypto from 'node:crypto';
7
7
  import { parse } from '../native-wire/protobuf.mjs';
8
8
  import { decodeClientGenerateResponse } from '../native-wire/robin-current.mjs';
9
9
  import { ProtocolError, protocolError, compileToolPolicy, createToolCallSplitter, validateToolCompletion } from './tool-protocol.mjs';
10
- import { MODEL_ALIASES, MODEL_MODES, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
10
+ import { MODEL_ALIASES, MODEL_MODES, MODEL_SPECS, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
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';
@@ -20,7 +20,7 @@ import { validateStructuredOutputText } from './gateway/structured-output.mjs';
20
20
  import { mapNativeSearchAnnotations, extractNativeSearchSources } from './gateway/native-search-citations.mjs';
21
21
  import { softErrorReason } from './gateway/soft-error.mjs';
22
22
  import { observeNative } from './gateway/native-diagnostic.mjs';
23
- export { MODEL_ALIASES, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, writeChatResponse, writeResponsesResponse };
23
+ export { MODEL_ALIASES, MODEL_SPECS, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, writeChatResponse, writeResponsesResponse };
24
24
 
25
25
  import { NATIVE_RESPONSE_LIMITS as RESPONSE_LIMITS } from './gateway/native-response-limits.mjs';
26
26
  const fail = (code, status = 502) => { throw protocolError(code, status); };
@@ -108,7 +108,7 @@ const validateIdleMs = (value, name) => {
108
108
  const IDLE_TIMEOUT_SENTINEL = Symbol('IDLE_TIMEOUT_SENTINEL');
109
109
 
110
110
  export class NativeDirectProvider {
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 } = {}) {
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 } = {}) {
112
112
  if (!authManager || typeof authManager.getValidAccessToken !== 'function') throw new TypeError('authManager.getValidAccessToken required');
113
113
  if (typeof openTurn !== 'function') throw new TypeError('openTurn required');
114
114
  if (typeof uploadImages !== 'function') throw new TypeError('uploadImages required');
@@ -360,12 +360,31 @@ export class NativeDirectProvider {
360
360
  ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
361
361
  iterator = turn.events[Symbol.asyncIterator]();
362
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
+ };
363
381
  const nextEventWithIdle = async () => {
364
382
  const verified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
365
- const committed = committedOutput();
366
- const idleKind = modelComplete ? 'post_complete'
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'
367
386
  : (verified && liveCalls.length > 0 ? 'post_tool'
368
- : (verified && committed.publishedBytes > 0 ? 'post_output' : null));
387
+ : (verified && liveCalls.length === 0 && isCleanPostOutputIdleStall() ? 'post_output' : null));
369
388
  const idleMs = idleKind === 'post_complete' ? postCompleteGraceMs
370
389
  : idleKind === 'post_tool' ? postToolIdleMs
371
390
  : idleKind === 'post_output' ? postOutputIdleMs
@@ -405,7 +424,11 @@ export class NativeDirectProvider {
405
424
  textBytes: Buffer.byteLength(rawText),
406
425
  });
407
426
  try { turn?.cancel(); } catch {}
408
- throw protocolError('NATIVE_TURN_TIMEOUT', 504);
427
+ const idleError = protocolError('NATIVE_TURN_TIMEOUT', 504);
428
+ if (idleKind === 'post_output' && item.verified && isCleanPostOutputIdleStall()) {
429
+ idleError.postOutputIdleStall = true;
430
+ }
431
+ throw idleError;
409
432
  }
410
433
  if (item.done) break;
411
434
  const event = item.value;
@@ -19,6 +19,13 @@ export const NATIVE_MODELS = Object.freeze(['gemini-neon', 'gemini-hydrogen', 'g
19
19
  export const MODEL_ALIASES = Object.freeze({ 'gemini-argon': 'gemini-neon' });
20
20
  // Native ModeCategory wire values: PRO=3 (Gemini 4 Neon), FAST=1 (Gemini 4 Hydrogen), FLASH_LITE=6. Never auto/Plus.
21
21
  export const MODEL_MODES = Object.freeze({ 'gemini-neon': 3, 'gemini-hydrogen': 1, 'gemini-flash-lite': 6 });
22
+ // Shared model metadata source of truth across Gateway (/v1/models), Pi, and OpenClaw.
23
+ export const MODEL_SPECS = Object.freeze({
24
+ 'gemini-neon': Object.freeze({ name: 'Gemini Neon', contextWindow: 512000, maxTokens: 16384, reasoning: true, advertiseContextWindow: true }),
25
+ 'gemini-hydrogen': Object.freeze({ name: 'Gemini Hydrogen', contextWindow: 512000, maxTokens: 16384, reasoning: true, advertiseContextWindow: true }),
26
+ 'gemini-flash-lite': Object.freeze({ name: 'Gemini Flash Lite', contextWindow: 128000, maxTokens: 8192, reasoning: true, advertiseContextWindow: false }),
27
+ 'gemini-auto': Object.freeze({ name: 'Gemini Auto', contextWindow: 128000, maxTokens: 8192, reasoning: false, advertiseContextWindow: false }),
28
+ });
22
29
  export function canonicalModel(model) {
23
30
  if (typeof model !== 'string') return model;
24
31
  const stripped = model.startsWith('models/') ? model.slice(7) : model;
@@ -45,7 +52,8 @@ function thinkingSettings(body) {
45
52
  }
46
53
  export const PROMPT_MAX_BYTES = 4 * 1024 * 1024;
47
54
  export const REQUEST_MAX_NON_IMAGE_BYTES = PROMPT_MAX_BYTES;
48
- const MAX_MESSAGES = 1024;
55
+ export const MAX_MESSAGES = 8192;
56
+ const REQUEST_MAX_NODES = 131072;
49
57
  const configured = Number(process.env.GEMINI_PROMPT_MAX_CHARS);
50
58
  const MAX_CHARS = Number.isSafeInteger(configured) && configured > 0 ? Math.min(configured, PROMPT_MAX_BYTES) : PROMPT_MAX_BYTES;
51
59
  function keys(value, allowed, prefix = '') {
@@ -81,7 +89,7 @@ function requestBudget(root) {
81
89
  }
82
90
  const ancestors = new Set();
83
91
  const visit = (value, depth, image = false) => {
84
- if (++nodes > 32768 || depth > 32) fail('REQUEST_TOO_LARGE', 413);
92
+ if (++nodes > REQUEST_MAX_NODES || depth > 32) fail('REQUEST_TOO_LARGE', 413);
85
93
  if (typeof value === 'string') {
86
94
  if (image) {
87
95
  const len = Buffer.byteLength(value);
@@ -335,7 +343,8 @@ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
335
343
  const tools = stripToolAnnotations(payload.tools === undefined ? [] : payload.tools);
336
344
  const choice = payload.tool_choice === undefined ? 'auto' : payload.tool_choice;
337
345
  const policy = compileToolPolicy(tools, choice);
338
- if (!Array.isArray(payload.messages) || !payload.messages.length || payload.messages.length > MAX_MESSAGES) fail('MESSAGES_REQUIRED');
346
+ if (!Array.isArray(payload.messages) || !payload.messages.length) fail('MESSAGES_REQUIRED');
347
+ if (payload.messages.length > MAX_MESSAGES) fail('REQUEST_TOO_LARGE', 413, 'messages');
339
348
  const pending = new Set(), seen = new Set();
340
349
  const messages = payload.messages.map(message => {
341
350
  keys(message, ['role', 'content', 'name', 'tool_calls', 'tool_call_id', 'refusal', 'parsed', 'annotations', 'reasoning_content', 'reasoning'], 'messages');
@@ -413,7 +422,8 @@ export function normalizeResponsesRequest(payload, { allowAutoModel = false } =
413
422
  const messages = [];
414
423
  if (payload.instructions !== undefined && payload.instructions !== null) messages.push({ role: 'system', content: text(payload.instructions) });
415
424
  const input = typeof payload.input === 'string' ? [{ role: 'user', content: payload.input }] : payload.input;
416
- if (!Array.isArray(input) || !input.length || input.length > MAX_MESSAGES) fail('INPUT_REQUIRED');
425
+ if (!Array.isArray(input) || !input.length) fail('INPUT_REQUIRED');
426
+ if (input.length > MAX_MESSAGES) fail('REQUEST_TOO_LARGE', 413, 'input');
417
427
  const { tools, choice, callName, identities } = normalizeResponsesTools(payload);
418
428
  for (const item of input) {
419
429
  if (!plainObject(item)) fail('INVALID_INPUT_ITEM');
@@ -2,11 +2,47 @@
2
2
  // required counter names. Preserve the estimate label; do not invent unmeasured
3
3
  // cache/reasoning breakdowns or expose Chat-only counter names on Responses.
4
4
  export const CHARS_PER_TOKEN = 3.5;
5
+ // Standard Gemini vision tile estimate so base64 image payloads never inflate
6
+ // prompt_tokens by hundreds of thousands of bogus text tokens.
7
+ export const TOKENS_PER_IMAGE = 258;
5
8
 
6
- export function estimateUsage({ promptChars = 0, outputBytes = 0 } = {}) {
9
+ export function measurePromptImagePayload(body) {
10
+ let imageCount = 0;
11
+ let imageUrlChars = 0;
12
+ const scanParts = (parts) => {
13
+ if (!Array.isArray(parts)) return;
14
+ for (const part of parts) {
15
+ if (!part || typeof part !== 'object') continue;
16
+ if (part.type === 'image_url' && typeof part.image_url?.url === 'string') {
17
+ imageCount++;
18
+ imageUrlChars += part.image_url.url.length;
19
+ } else if (part.type === 'input_image' && typeof part.image_url === 'string') {
20
+ imageCount++;
21
+ imageUrlChars += part.image_url.length;
22
+ }
23
+ }
24
+ };
25
+ if (Array.isArray(body?.messages)) {
26
+ for (const message of body.messages) scanParts(message?.content);
27
+ }
28
+ if (Array.isArray(body?.input)) {
29
+ for (const item of body.input) {
30
+ if (item?.type === 'input_image' && typeof item.image_url === 'string') {
31
+ imageCount++;
32
+ imageUrlChars += item.image_url.length;
33
+ } else {
34
+ scanParts(item?.content);
35
+ }
36
+ }
37
+ }
38
+ return { imageCount, imageUrlChars };
39
+ }
40
+
41
+ export function estimateUsage({ promptChars = 0, imageCount = 0, outputBytes = 0 } = {}) {
7
42
  const safePrompt = Number.isFinite(promptChars) && promptChars > 0 ? promptChars : 0;
43
+ const safeImages = Number.isInteger(imageCount) && imageCount > 0 ? imageCount : 0;
8
44
  const safeOutput = Number.isFinite(outputBytes) && outputBytes > 0 ? outputBytes : 0;
9
- const prompt = Math.ceil(safePrompt / CHARS_PER_TOKEN);
45
+ const prompt = Math.ceil(safePrompt / CHARS_PER_TOKEN) + safeImages * TOKENS_PER_IMAGE;
10
46
  const completion = Math.ceil(safeOutput / CHARS_PER_TOKEN);
11
47
  return {
12
48
  prompt_tokens: prompt,