pi-gemini-app 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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';
@@ -15,12 +15,12 @@ import { uploadNativeImages, createImageBlobCache } from './gateway/image-upload
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';
18
- import { toolRecoveryInstruction } from './gateway/automatic-recovery.mjs';
18
+ import { TOOL_ERRORS, toolRecoveryInstruction } from './gateway/automatic-recovery.mjs';
19
19
  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); };
@@ -163,21 +163,51 @@ export class NativeDirectProvider {
163
163
  }
164
164
  }
165
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];
166
+ const deadline = Date.now() + uploadTimeoutMs;
167
+ const completed = new Array(missImages.length);
168
+ const recordSlot = (slot, item) => {
169
+ if (!item || item.mimeType !== missImages[slot].mimeType || typeof item.blobId !== 'string' || !item.blobId.length) return false;
170
+ completed[slot] = item;
176
171
  for (const targetIndex of missSlotIndices[slot]) {
177
172
  attachments[targetIndex] = item;
178
173
  const key = keys[targetIndex];
179
174
  if (this.blobCache && key) this.blobCache.set(key, item);
180
175
  }
176
+ return true;
177
+ };
178
+ for (let attempt = 0; attempt < 3; attempt++) {
179
+ const pendingSlots = [];
180
+ for (let slot = 0; slot < missImages.length; slot++) {
181
+ if (!completed[slot]) pendingSlots.push(slot);
182
+ }
183
+ if (!pendingSlots.length) break;
184
+ const remainingMs = Math.max(1, deadline - Date.now());
185
+ const batch = pendingSlots.map(slot => missImages[slot]);
186
+ try {
187
+ const uploaded = await this.uploadImages(token, batch, {
188
+ signal,
189
+ timeoutMs: remainingMs,
190
+ ...(attempt > 0 ? { concurrency: 1 } : {}),
191
+ onUploaded: (batchIndex, item) => {
192
+ const slot = pendingSlots[batchIndex];
193
+ if (slot !== undefined) recordSlot(slot, item);
194
+ },
195
+ });
196
+ if (!Array.isArray(uploaded) || uploaded.length !== batch.length) fail('INVALID_NATIVE_IMAGE_UPLOAD');
197
+ for (let batchIndex = 0; batchIndex < uploaded.length; batchIndex++) {
198
+ if (!recordSlot(pendingSlots[batchIndex], uploaded[batchIndex])) fail('INVALID_NATIVE_IMAGE_UPLOAD');
199
+ }
200
+ break;
201
+ } catch (err) {
202
+ const retryableReset = err?.code === 'NATIVE_IMAGE_UPLOAD_RESET' && !signal?.aborted && attempt < 2 && Date.now() + 250 < deadline;
203
+ if (!retryableReset) throw err;
204
+ await new Promise((resolve, reject) => {
205
+ const onAbort = () => { clearTimeout(t); reject(protocolError('NATIVE_IMAGE_UPLOAD_CANCELLED', 499)); };
206
+ const t = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, 200);
207
+ t.unref?.();
208
+ signal?.addEventListener('abort', onAbort, { once: true });
209
+ });
210
+ }
181
211
  }
182
212
  }
183
213
  return { attachments, usedCachedKeys };
@@ -281,7 +311,7 @@ export class NativeDirectProvider {
281
311
  const requiresHydrogen = body.model === 'gemini-hydrogen';
282
312
  const requiresNeon = body.model === 'gemini-neon';
283
313
  let rawText = '', frames = 0, received = 0, observedMode = null, observedThinking = null;
284
- let modelComplete = false, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
314
+ let modelComplete = false, modelCompleteAt = null, lastTextProgressAt = null, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
285
315
  let observedFallback = null, downgradeReason = null, observedAttribution = null;
286
316
  const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? ''));
287
317
  const attributionVerified = () => attributionMatches(observedAttribution);
@@ -293,7 +323,7 @@ export class NativeDirectProvider {
293
323
  [RESPONSE_TOOL_IDENTITIES]: body[RESPONSE_TOOL_IDENTITIES],
294
324
  requestedThinkingLevel: body.thinking_level, ignoredTokenParameters: ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined),
295
325
  ...((body.reasoning_effort ?? body.reasoning?.effort) === undefined ? {} : { requestedReasoningEffort: body.reasoning_effort ?? body.reasoning?.effort }) };
296
- let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, sinkFailed = false;
326
+ let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, liveToolError = null, liveToolErrorTailStart = 0, liveToolErrorDeadline = null, toolErrorEarlyStop = false, postCompleteIdleFinished = false, sinkFailed = false;
297
327
  const deliver = async event => {
298
328
  try { await onDelta(event); }
299
329
  catch (error) { sinkFailed = true; throw error; }
@@ -360,35 +390,85 @@ export class NativeDirectProvider {
360
390
  ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
361
391
  iterator = turn.events[Symbol.asyncIterator]();
362
392
  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;
393
+ let cachedProbeText = null, cachedProbeRevision = -1, cachedProbeLiveCalls = -1, cachedProbeStructured = false, cachedProbeResult = { kind: 'none' };
394
+ const probeIdleState = () => {
395
+ if (cachedProbeText === rawText && cachedProbeRevision === revisionCount && cachedProbeLiveCalls === liveCalls.length && cachedProbeStructured === outputShape.nativeStructuredOutputPresent) {
396
+ return cachedProbeResult;
397
+ }
398
+ cachedProbeText = rawText;
399
+ cachedProbeRevision = revisionCount;
400
+ cachedProbeLiveCalls = liveCalls.length;
401
+ cachedProbeStructured = outputShape.nativeStructuredOutputPresent;
402
+ if (!rawText.trim()) return (cachedProbeResult = { kind: 'none' });
403
+ 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)) {
404
+ return (cachedProbeResult = { kind: 'none' });
405
+ }
406
+ let probeItems;
366
407
  try {
367
408
  const probe = createToolCallSplitter({ policy });
368
- const probeItems = [...probe.push(rawText), ...probe.flush()];
409
+ probeItems = [...probe.push(rawText), ...probe.flush()];
410
+ } catch (probeError) {
411
+ // Only a closed tool block (or malformed fence/call) failing parse/schema validation
412
+ // is a closed_tool_error. TRUNCATED_TOOL_CALL means a tool block is still streaming,
413
+ // and TOOL_CHOICE_NOT_SATISFIED is checked separately below so a valid preamble before
414
+ // a required tool_choice call is never misclassified as a closed tool error.
415
+ if (probeError?.code === 'TRUNCATED_TOOL_CALL') {
416
+ return (cachedProbeResult = { kind: 'streaming_tool' });
417
+ }
418
+ if (TOOL_ERRORS.has(probeError?.code)) {
419
+ return (cachedProbeResult = { kind: 'closed_tool_error', error: probeError });
420
+ }
421
+ return (cachedProbeResult = { kind: 'none' });
422
+ }
423
+ if (liveCalls.length > 0) return (cachedProbeResult = { kind: 'none' });
424
+ try {
369
425
  const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
370
426
  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;
427
+ if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return (cachedProbeResult = { kind: 'none' });
428
+ if (body.parallel_tool_calls === false && probeCalls.length > 1) return (cachedProbeResult = { kind: 'none' });
373
429
  validateToolCompletion(probeCalls, policy);
374
- if (!probeCalls.length && !probeContent.trim()) return false;
430
+ if (!probeCalls.length && !probeContent.trim()) return (cachedProbeResult = { kind: 'none' });
375
431
  if (body.response_format && !probeCalls.length) validateStructuredOutputText(probeContent, body.response_format);
376
- return true;
432
+ return (cachedProbeResult = { kind: 'clean_output' });
377
433
  } catch {
378
- return false;
434
+ return (cachedProbeResult = { kind: 'none' });
379
435
  }
380
436
  };
437
+ const isCleanPostOutputIdleStall = () => probeIdleState().kind === 'clean_output';
381
438
  const nextEventWithIdle = async () => {
382
439
  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
440
+ const probeState = (verified && !liveToolError) ? probeIdleState() : { kind: 'none' };
441
+ // Never arm an idle timer unless we already have verified, complete, deliverable output
442
+ // or a closed invalid tool block; never kill a slow still-streaming tool call (TRUNCATED_TOOL_CALL)
443
+ // or a valid preamble preceding a required tool_choice call.
444
+ const now = Date.now();
445
+ const toolErrorRemaining = liveToolError
446
+ ? (postToolIdleMs === null ? null : Math.max(0, (liveToolErrorDeadline ?? now) - now))
447
+ : (postToolIdleMs === null ? null : Math.max(0, postToolIdleMs - (lastTextProgressAt !== null ? now - lastTextProgressAt : 0)));
448
+ const completeRemaining = (modelComplete && postCompleteGraceMs !== null)
449
+ ? Math.max(0, postCompleteGraceMs - (modelCompleteAt !== null ? now - modelCompleteAt : 0))
391
450
  : null;
451
+ let idleKind = null;
452
+ let idleMs = null;
453
+ if (verified && (liveToolError || probeState.kind === 'closed_tool_error')) {
454
+ // Take the shortest enabled deadline across post_tool_error and (when modelComplete) post_complete.
455
+ if (toolErrorRemaining !== null && (completeRemaining === null || toolErrorRemaining <= completeRemaining)) {
456
+ idleKind = 'post_tool_error';
457
+ idleMs = toolErrorRemaining;
458
+ } else if (completeRemaining !== null) {
459
+ idleKind = 'post_tool_error';
460
+ idleMs = completeRemaining;
461
+ }
462
+ } else if (modelComplete && verified && rawText.trim().length > 0) {
463
+ idleKind = 'post_complete';
464
+ idleMs = completeRemaining;
465
+ } else if (verified && liveCalls.length > 0 && probeState.kind !== 'streaming_tool') {
466
+ idleKind = 'post_tool';
467
+ idleMs = postToolIdleMs === null ? null : Math.max(0, postToolIdleMs - (lastTextProgressAt !== null ? now - lastTextProgressAt : 0));
468
+ } else if (probeState.kind === 'clean_output') {
469
+ idleKind = 'post_output';
470
+ idleMs = postOutputIdleMs === null ? null : Math.max(0, postOutputIdleMs - (lastTextProgressAt !== null ? now - lastTextProgressAt : 0));
471
+ }
392
472
  const nextPromise = iterator.next();
393
473
  if (idleMs === null) return bounded(nextPromise);
394
474
  nextPromise.catch(() => {});
@@ -397,7 +477,7 @@ export class NativeDirectProvider {
397
477
  return await Promise.race([
398
478
  bounded(nextPromise),
399
479
  new Promise(resolve => {
400
- idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified }), idleMs);
480
+ idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified, probeError: probeState.error ?? null }), idleMs);
401
481
  idleTimer.unref?.();
402
482
  }),
403
483
  ]);
@@ -411,13 +491,21 @@ export class NativeDirectProvider {
411
491
  if (item && item[IDLE_TIMEOUT_SENTINEL]) {
412
492
  const idleKind = item[IDLE_TIMEOUT_SENTINEL];
413
493
  if (idleKind === 'post_complete' && item.verified && rawText.trim().length > 0) {
414
- note('post_complete_idle_finish', { frames, textBytes: Buffer.byteLength(rawText) });
494
+ note('post_complete_idle_finish', { bytes: Buffer.byteLength(rawText) });
415
495
  try { turn?.cancel(); } catch {}
496
+ postCompleteIdleFinished = true;
416
497
  ended = true;
417
498
  httpStatus = httpStatus ?? 200;
418
499
  grpc = grpc ?? 0;
419
500
  break;
420
501
  }
502
+ if (idleKind === 'post_tool_error' && item.verified && (liveToolError || item.probeError)) {
503
+ if (!liveToolError) liveToolError = item.probeError;
504
+ note('post_tool_error_idle_finish', { code: liveToolError.code, bytes: Buffer.byteLength(rawText) });
505
+ try { turn?.cancel(); } catch {}
506
+ toolErrorEarlyStop = true;
507
+ break;
508
+ }
421
509
  note(`${idleKind}_idle_timeout`, {
422
510
  frames,
423
511
  calls: liveCalls.length,
@@ -471,7 +559,9 @@ export class NativeDirectProvider {
471
559
  if (!Number.isSafeInteger(info.thinkingLevel) || info.thinkingLevel < 0 || info.thinkingLevel > 4) fail('INVALID_NATIVE_THINKING_LEVEL');
472
560
  observedThinking = info.thinkingLevel;
473
561
  }
562
+ const wasComplete = modelComplete;
474
563
  modelComplete ||= info.completed;
564
+ if (!wasComplete && modelComplete) modelCompleteAt = Date.now();
475
565
  // Stop as soon as a wrong model is proven; do not pay for a full
476
566
  // downgraded answer that this gateway can never return as success.
477
567
  if (downgrade) {
@@ -498,24 +588,41 @@ export class NativeDirectProvider {
498
588
  snapshotPriorBytes: Buffer.byteLength(rawText), snapshotNextBytes: Buffer.byteLength(info.text),
499
589
  snapshotCommonPrefixBytes: commonPrefixBytes(rawText, info.text), ...committed });
500
590
  if (liveSyncedLength > 0) await deliver({ reset: true, sameResponseIdentity: true, response: identity });
501
- liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0;
591
+ liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0; liveToolError = null; liveToolErrorTailStart = 0; liveToolErrorDeadline = null;
502
592
  }
503
593
  }
504
594
  if (id) snapshotId = id;
505
595
  if (!extendsPrior) revisionCount++;
506
- if (info.text !== rawText) modelComplete = info.completed;
596
+ if (info.text !== rawText) {
597
+ modelComplete = info.completed;
598
+ modelCompleteAt = modelComplete ? Date.now() : null;
599
+ lastTextProgressAt = Date.now();
600
+ }
507
601
  rawText = info.text;
508
602
  } else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
509
603
  fail('INVALID_NATIVE_RESPONSE');
510
604
  }
511
- if (incremental && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
605
+ if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
512
606
  const delta = rawText.slice(liveSyncedLength);
513
607
  liveSyncedLength = rawText.length;
514
- await publish(liveSplitter.push(delta));
608
+ try {
609
+ await publish(liveSplitter.push(delta));
610
+ } catch (splitError) {
611
+ // Defer recoverable tool-protocol errors briefly until stream completion so
612
+ // upstream completion/downgrade/refusal evidence is fully verified and
613
+ // automatic tool_protocol recovery (or same-ID revision) can run cleanly.
614
+ if (!sinkFailed && TOOL_ERRORS.has(splitError?.code)) {
615
+ liveToolError = splitError;
616
+ liveToolErrorTailStart = Number.isInteger(splitError.postFenceOffset) ? splitError.postFenceOffset : rawText.length;
617
+ liveToolErrorDeadline = postToolIdleMs === null ? null : Date.now() + postToolIdleMs;
618
+ } else {
619
+ throw splitError;
620
+ }
621
+ }
515
622
  // Once valid tool_call(s) have been parsed and the model begins hallucinating
516
623
  // a fake [Caller tool result], stop upstream immediately instead of waiting
517
624
  // minutes for the model to finish generating discarded text.
518
- if (liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
625
+ if (!liveToolError && liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
519
626
  note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
520
627
  try { turn?.cancel(); } catch {}
521
628
  ended = true;
@@ -525,6 +632,17 @@ export class NativeDirectProvider {
525
632
  break;
526
633
  }
527
634
  }
635
+ if (incremental && liveToolError && !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified()) {
636
+ const postErrorTail = rawText.slice(liveToolErrorTailStart);
637
+ const postErrorTailBytes = Buffer.byteLength(postErrorTail);
638
+ const graceExpired = liveToolErrorDeadline !== null && Date.now() >= liveToolErrorDeadline;
639
+ if (postErrorTail.includes('[Caller tool result]') || postErrorTailBytes > 4096 || graceExpired) {
640
+ note('early_stop_post_tool_error', { code: liveToolError.code, bytes: postErrorTailBytes });
641
+ try { turn?.cancel(); } catch {}
642
+ toolErrorEarlyStop = true;
643
+ break;
644
+ }
645
+ }
528
646
  if (info.quotaObservation) {
529
647
  quotaFrames++;
530
648
  if (quotaFrames > 16) quotaObservation = null;
@@ -562,6 +680,12 @@ export class NativeDirectProvider {
562
680
  }
563
681
  phase = 'validate';
564
682
  if (downgrade) fail('MODEL_DOWNGRADE_REJECTED');
683
+ if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
684
+ if (toolErrorEarlyStop && liveToolError) {
685
+ if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
686
+ if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
687
+ throw liveToolError;
688
+ }
565
689
  if (!ended) fail('INCOMPLETE_NATIVE_RESPONSE');
566
690
  // An ordinary RPC close is not model completion. Async UI placeholders
567
691
  // must be non-retryable or PI will repeatedly submit fresh generations.
@@ -569,7 +693,6 @@ export class NativeDirectProvider {
569
693
  if (!modelComplete) fail('INCOMPLETE_NATIVE_RESPONSE');
570
694
  if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
571
695
  if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
572
- if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
573
696
  if (!rawText.trim()) {
574
697
  if (outputShape.nativeShareableTextBytes || outputShape.nativeStructuredOutputPresent) fail('NATIVE_OUTPUT_NOT_TEXT', 422);
575
698
  emptyResponseReason = rawText.length ? 'whitespace_only' : outputShape.nativeThoughtsPresent ? 'thoughts_only' : 'no_text';
@@ -577,6 +700,7 @@ export class NativeDirectProvider {
577
700
  }
578
701
  let items;
579
702
  if (incremental) {
703
+ if (liveToolError) throw liveToolError;
580
704
  if (liveSyncedLength < rawText.length) {
581
705
  const delta = rawText.slice(liveSyncedLength);
582
706
  liveSyncedLength = rawText.length;
@@ -621,7 +745,7 @@ export class NativeDirectProvider {
621
745
  return result;
622
746
  } catch (error) {
623
747
  const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
624
- if (incremental && modeVerified && !sinkFailed) {
748
+ if (incremental && !liveToolError && modeVerified && !sinkFailed) {
625
749
  try { await publish(liveSplitter.flush()); }
626
750
  catch { /* Retain already-published text; never release an invalid/incomplete tool body. */ }
627
751
  }
@@ -644,6 +768,7 @@ export class NativeDirectProvider {
644
768
  observedMode, observedThinking,
645
769
  fallback: observedFallback, downgradeReason,
646
770
  toolProtocolReason: safe.toolProtocolReason,
771
+ ...((toolErrorEarlyStop || (postCompleteIdleFinished && phase === 'validate' && TOOL_ERRORS.has(safe.code))) ? { toolErrorEarlyStop: true } : {}),
647
772
  ...(outputObserved ? { nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
648
773
  nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null } : {}),
649
774
  ...(responseLimitReason ? { nativeResponseLimitReason: responseLimitReason } : {}),
@@ -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 = '') {
@@ -78,10 +86,11 @@ function requestBudget(root) {
78
86
  for (const item of Array.isArray(root.input) ? root.input.slice(0, MAX_MESSAGES) : []) {
79
87
  if (item?.type === 'input_image') mark(item, true);
80
88
  if (item?.role === 'user' && Array.isArray(item.content) && item.content.length <= 1024) for (const part of item.content) mark(part, true);
89
+ if (item?.type === 'function_call_output' && Array.isArray(item.output) && item.output.length <= 1024) for (const part of item.output) mark(part, true);
81
90
  }
82
91
  const ancestors = new Set();
83
92
  const visit = (value, depth, image = false) => {
84
- if (++nodes > 32768 || depth > 32) fail('REQUEST_TOO_LARGE', 413);
93
+ if (++nodes > REQUEST_MAX_NODES || depth > 32) fail('REQUEST_TOO_LARGE', 413);
85
94
  if (typeof value === 'string') {
86
95
  if (image) {
87
96
  const len = Buffer.byteLength(value);
@@ -151,7 +160,7 @@ function validateReplayAnnotations(annotations, { chat = false } = {}) {
151
160
  }
152
161
  }
153
162
  }
154
- function content(value, { assistant = false, responses = false, user = false, prefix = 'messages.content' } = {}) {
163
+ function content(value, { assistant = false, responses = false, user = false, toolOutput = false, prefix = 'messages.content', imageCache } = {}) {
155
164
  if (value === null && assistant) return null;
156
165
  if (typeof value === 'string') return text(value);
157
166
  if (!Array.isArray(value) || !value.length || value.length > 1024) fail('INVALID_MESSAGE_CONTENT');
@@ -162,7 +171,12 @@ function content(value, { assistant = false, responses = false, user = false, pr
162
171
  if (!responses) keys(part.image_url, ['url', 'detail'], `${prefix}.image_url`);
163
172
  const url = responses ? part.image_url : part.image_url.url;
164
173
  const detail = responses ? part.detail : part.image_url.detail;
165
- return { type: 'image_url', image_url: { url: normalizeImageUrl(url, detail), detail: 'auto' } };
174
+ return { type: 'image_url', image_url: { url: normalizeImageUrl(url, detail, imageCache), detail: 'auto' } };
175
+ }
176
+ if (toolOutput) {
177
+ keys(part, ['type', 'text'], prefix);
178
+ if (part.type !== 'input_text') fail('UNSUPPORTED_CONTENT_TYPE');
179
+ return { type: 'text', text: text(part.text) };
166
180
  }
167
181
  keys(part, responses ? ['type', 'text', 'annotations', 'logprobs', 'parsed'] : ['type', 'text'], prefix);
168
182
  if (part.parsed !== undefined && (part.parsed !== null || !assistant)) fail('UNSUPPORTED_PARAMETER', 400, `${prefix}.parsed`);
@@ -238,8 +252,8 @@ function stripToolAnnotations(tools) {
238
252
  }
239
253
 
240
254
  /** Also used by the provider; computes the EXACT budgeted wire prompt. */
241
- export function buildCanonicalPrompt(body, resolvedImages) {
242
- const { messages: transcript, images } = collectImageInputs(body.messages, resolvedImages);
255
+ export function buildCanonicalPrompt(body, resolvedImages, decodedImageCache) {
256
+ const { messages: transcript, images } = collectImageInputs(body.messages, resolvedImages, decodedImageCache);
243
257
  if (body.native_search && images.length) fail('NATIVE_SEARCH_IMAGES_UNSUPPORTED');
244
258
  const { systemText, userText } = flattenMessages(transcript, { maxChars: MAX_CHARS });
245
259
  const instruction = body.native_search
@@ -319,7 +333,8 @@ function validateInertOpenAIFields(payload, { responses = false } = {}) {
319
333
  }
320
334
  }
321
335
 
322
- export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
336
+ export function normalizeChatRequest(payload, { allowAutoModel = false, _imageCache } = {}) {
337
+ const imageCache = _imageCache ?? new Map();
323
338
  keys(payload, ['model', 'messages', 'tools', 'tool_choice', 'thinking_level', 'reasoning_effort', 'stream', 'stream_options', 'store', 'parallel_tool_calls', 'reasoning', 'include', 'prompt_cache_key', 'client_metadata', 'native_search', 'max_tokens', 'max_completion_tokens', 'temperature', 'top_p', 'presence_penalty', 'frequency_penalty', 'seed', 'logprobs', 'top_logprobs', 'response_format', 'user', 'metadata', 'stop', 'n', 'service_tier', 'logit_bias', 'verbosity', 'modalities']);
324
339
  requestBudget(payload);
325
340
  validateInertOpenAIFields(payload);
@@ -335,7 +350,8 @@ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
335
350
  const tools = stripToolAnnotations(payload.tools === undefined ? [] : payload.tools);
336
351
  const choice = payload.tool_choice === undefined ? 'auto' : payload.tool_choice;
337
352
  const policy = compileToolPolicy(tools, choice);
338
- if (!Array.isArray(payload.messages) || !payload.messages.length || payload.messages.length > MAX_MESSAGES) fail('MESSAGES_REQUIRED');
353
+ if (!Array.isArray(payload.messages) || !payload.messages.length) fail('MESSAGES_REQUIRED');
354
+ if (payload.messages.length > MAX_MESSAGES) fail('REQUEST_TOO_LARGE', 413, 'messages');
339
355
  const pending = new Set(), seen = new Set();
340
356
  const messages = payload.messages.map(message => {
341
357
  keys(message, ['role', 'content', 'name', 'tool_calls', 'tool_call_id', 'refusal', 'parsed', 'annotations', 'reasoning_content', 'reasoning'], 'messages');
@@ -368,7 +384,7 @@ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
368
384
  if (role !== 'assistant' && message.tool_calls !== undefined) fail('INVALID_TOOL_CALL');
369
385
  if (role !== 'tool' && message.tool_call_id !== undefined) fail('INVALID_TOOL_RESULT');
370
386
  const messageContent = role === 'assistant' && message.content === undefined && message.tool_calls !== undefined ? null : message.content;
371
- const normalized = { role, content: content(messageContent, { assistant: role === 'assistant', user: role === 'user' }) };
387
+ const normalized = { role, content: content(messageContent, { assistant: role === 'assistant', user: role === 'user', imageCache }) };
372
388
  if (role === 'assistant' && message.tool_calls !== undefined) {
373
389
  if (!Array.isArray(message.tool_calls) || !message.tool_calls.length || message.tool_calls.length > 32) fail('INVALID_TOOL_CALL');
374
390
  normalized.tool_calls = message.tool_calls.map(call => {
@@ -399,11 +415,12 @@ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
399
415
  body.stream_options = { include_usage: payload.stream_options.include_usage };
400
416
  }
401
417
  }
402
- buildCanonicalPrompt(body); // Validate budgets BEFORE any account reservation.
418
+ buildCanonicalPrompt(body, undefined, imageCache); // Validate budgets BEFORE any account reservation.
403
419
  return body;
404
420
  }
405
421
 
406
422
  export function normalizeResponsesRequest(payload, { allowAutoModel = false } = {}) {
423
+ const imageCache = new Map();
407
424
  keys(payload, ['model', 'input', 'instructions', 'tools', 'tool_choice', 'thinking_level', 'reasoning_effort', 'stream', 'store', 'parallel_tool_calls', 'reasoning', 'include', 'prompt_cache_key', 'client_metadata', 'native_search', 'temperature', 'top_p', 'max_output_tokens', 'text', 'user', 'metadata', 'service_tier', 'truncation']);
408
425
  requestBudget(payload);
409
426
  validateInertOpenAIFields(payload, { responses: true });
@@ -413,10 +430,17 @@ export function normalizeResponsesRequest(payload, { allowAutoModel = false } =
413
430
  const messages = [];
414
431
  if (payload.instructions !== undefined && payload.instructions !== null) messages.push({ role: 'system', content: text(payload.instructions) });
415
432
  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');
433
+ if (!Array.isArray(input) || !input.length) fail('INPUT_REQUIRED');
434
+ if (input.length > MAX_MESSAGES) fail('REQUEST_TOO_LARGE', 413, 'input');
417
435
  const { tools, choice, callName, identities } = normalizeResponsesTools(payload);
436
+ const deferredToolImages = [];
437
+ let toolImageSeq = 0;
438
+ const flushToolImages = () => {
439
+ if (deferredToolImages.length) messages.push({ role: 'user', content: deferredToolImages.splice(0) });
440
+ };
418
441
  for (const item of input) {
419
442
  if (!plainObject(item)) fail('INVALID_INPUT_ITEM');
443
+ if (item.type !== 'function_call_output') flushToolImages();
420
444
  if (item.type === 'function_call') {
421
445
  keys(item, ['type', 'id', 'status', 'call_id', 'namespace', 'name', 'arguments', 'parsed_arguments'], 'input');
422
446
  if (item.parsed_arguments !== undefined && item.parsed_arguments !== null) fail('UNSUPPORTED_PARAMETER', 400, 'input.parsed_arguments');
@@ -429,22 +453,43 @@ export function normalizeResponsesRequest(payload, { allowAutoModel = false } =
429
453
  } else if (item.type === 'function_call_output') {
430
454
  keys(item, ['type', 'id', 'call_id', 'output'], 'input');
431
455
  if (item.id !== undefined) id(item.id);
432
- messages.push({ role: 'tool', tool_call_id: id(item.call_id), content: text(item.output) });
456
+ const callId = id(item.call_id);
457
+ if (Array.isArray(item.output)) {
458
+ const normalized = content(item.output, { user: true, responses: true, toolOutput: true, prefix: 'input.output', imageCache });
459
+ if (Array.isArray(normalized)) {
460
+ const toolTextParts = [];
461
+ for (const part of normalized) {
462
+ if (part.type === 'text') {
463
+ toolTextParts.push(part.text);
464
+ } else {
465
+ const label = `[Tool image ${++toolImageSeq} for ${callId}]`;
466
+ toolTextParts.push(toolTextParts.length ? `\n${label}\n` : label);
467
+ deferredToolImages.push({ type: 'text', text: `${label}:` }, part);
468
+ }
469
+ }
470
+ messages.push({ role: 'tool', tool_call_id: callId, content: toolTextParts.join('') });
471
+ } else {
472
+ messages.push({ role: 'tool', tool_call_id: callId, content: normalized });
473
+ }
474
+ } else {
475
+ messages.push({ role: 'tool', tool_call_id: callId, content: text(item.output) });
476
+ }
433
477
  } else if (item.type === 'input_text') {
434
478
  keys(item, ['type', 'text'], 'input'); messages.push({ role: 'user', content: text(item.text) });
435
479
  } else if (item.type === 'input_image') {
436
- messages.push({ role: 'user', content: content([item], { user: true, responses: true, prefix: 'input' }) });
480
+ messages.push({ role: 'user', content: content([item], { user: true, responses: true, prefix: 'input', imageCache }) });
437
481
  } else {
438
482
  keys(item, ['type', 'id', 'status', 'role', 'content'], 'input');
439
483
  if (item.type !== undefined && item.type !== 'message') fail('UNSUPPORTED_INPUT_TYPE');
440
484
  if (item.id !== undefined) id(item.id);
441
485
  if (item.status !== undefined && (item.role !== 'assistant' || item.status !== 'completed')) fail('INVALID_INPUT_STATUS');
442
- messages.push({ role: item.role, content: content(item.content, { assistant: item.role === 'assistant', user: item.role === 'user', responses: true, prefix: 'input.content' }) });
486
+ messages.push({ role: item.role, content: content(item.content, { assistant: item.role === 'assistant', user: item.role === 'user', responses: true, prefix: 'input.content', imageCache }) });
443
487
  }
444
488
  }
489
+ flushToolImages();
445
490
  const { include: _include, ...inertCompat } = compat;
446
- const body = normalizeChatRequest({ ...resolved, ...inertCompat, ...(response_format ? { response_format } : {}), messages, tools, tool_choice: choice, [RESPONSE_TOOL_IDENTITIES]: identities }, { allowAutoModel });
447
- const projected = collectImageInputs(body.messages).messages;
491
+ const body = normalizeChatRequest({ ...resolved, ...inertCompat, ...(response_format ? { response_format } : {}), messages, tools, tool_choice: choice, [RESPONSE_TOOL_IDENTITIES]: identities }, { allowAutoModel, _imageCache: imageCache });
492
+ const projected = collectImageInputs(body.messages, undefined, imageCache).messages;
448
493
  return {
449
494
  body,
450
495
  systemPrompt: projected.filter(m => ['system', 'developer'].includes(m.role)).map(m => m.content).join('\n'),
@@ -2,11 +2,48 @@
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
+ scanParts(item?.output);
36
+ }
37
+ }
38
+ }
39
+ return { imageCount, imageUrlChars };
40
+ }
41
+
42
+ export function estimateUsage({ promptChars = 0, imageCount = 0, outputBytes = 0 } = {}) {
7
43
  const safePrompt = Number.isFinite(promptChars) && promptChars > 0 ? promptChars : 0;
44
+ const safeImages = Number.isInteger(imageCount) && imageCount > 0 ? imageCount : 0;
8
45
  const safeOutput = Number.isFinite(outputBytes) && outputBytes > 0 ? outputBytes : 0;
9
- const prompt = Math.ceil(safePrompt / CHARS_PER_TOKEN);
46
+ const prompt = Math.ceil(safePrompt / CHARS_PER_TOKEN) + safeImages * TOKENS_PER_IMAGE;
10
47
  const completion = Math.ceil(safeOutput / CHARS_PER_TOKEN);
11
48
  return {
12
49
  prompt_tokens: prompt,