pi-gemini-app 0.1.9 → 0.1.11

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, MODEL_SPECS, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
10
+ import { MODEL_ALIASES, MODEL_MODES, MODEL_SPECS, NATIVE_MODELS, PROMPT_MAX_BYTES, 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,7 +15,7 @@ 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';
@@ -38,6 +38,48 @@ const failWithEvidence = (code, evidence) => {
38
38
  const utf8 = new TextDecoder('utf-8', { fatal: true });
39
39
  const HYDROGEN_ATTRIBUTION = /\bhydrogen\b/i;
40
40
  const NEON_ATTRIBUTION = /\bneon\b/i;
41
+ const ASYNC_DEEP_THINK_PLACEHOLDER_RE = /^\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;
42
+ const CLOSING_FENCE_LINE_RE = /^ {0,3}`{3,}/;
43
+ const PENDING_TOOL_OPEN_RE = /^ {0,3}`{3,}[ \t]*t(?:o(?:o(?:l(?:_(?:c(?:a(?:l(?:l)?)?)?)?)?)?)?)?[ \t]*$/;
44
+
45
+ /** Pure idle deadline selector for NativeDirectProvider.runTurn().
46
+ * Preserves strict priority: an enabled lower-priority timer never runs while
47
+ * a higher-priority condition matches with its own deadline disabled (null). */
48
+ export function selectIdleDeadline(facts, now = Date.now()) {
49
+ if (!facts?.verified) return { kind: null, ms: null };
50
+ const elapsed = anchor => (anchor !== null && anchor !== undefined ? Math.max(0, now - anchor) : 0);
51
+ const completeRemaining = (facts.modelComplete && facts.postCompleteGraceMs !== null)
52
+ ? Math.max(0, facts.postCompleteGraceMs - elapsed(facts.modelCompleteAt))
53
+ : null;
54
+ if (facts.hasLiveToolError || facts.hasClosedToolError) {
55
+ const toolErrorRemaining = facts.hasLiveToolError
56
+ ? (facts.postToolIdleMs === null ? null : Math.max(0, (facts.liveToolErrorDeadline ?? now) - now))
57
+ : (facts.postToolIdleMs === null ? null : Math.max(0, facts.postToolIdleMs - elapsed(facts.lastTextProgressAt)));
58
+ if (toolErrorRemaining !== null && (completeRemaining === null || toolErrorRemaining <= completeRemaining)) {
59
+ return { kind: 'post_tool_error', ms: toolErrorRemaining };
60
+ }
61
+ if (completeRemaining !== null) {
62
+ return { kind: 'post_tool_error', ms: completeRemaining };
63
+ }
64
+ return { kind: null, ms: null };
65
+ }
66
+ if (facts.modelComplete && facts.hasText) {
67
+ return { kind: 'post_complete', ms: completeRemaining };
68
+ }
69
+ if (facts.hasLiveCalls && !facts.streamingTool) {
70
+ return {
71
+ kind: 'post_tool',
72
+ ms: facts.postToolIdleMs === null ? null : Math.max(0, facts.postToolIdleMs - elapsed(facts.lastTextProgressAt)),
73
+ };
74
+ }
75
+ if (facts.cleanOutput) {
76
+ return {
77
+ kind: 'post_output',
78
+ ms: facts.postOutputIdleMs === null ? null : Math.max(0, facts.postOutputIdleMs - elapsed(facts.lastTextProgressAt)),
79
+ };
80
+ }
81
+ return { kind: null, ms: null };
82
+ }
41
83
  function one(fields, number) {
42
84
  const found = fields.filter(field => field.number === number);
43
85
  if (found.length > 1) fail('INVALID_NATIVE_RESPONSE');
@@ -163,21 +205,51 @@ export class NativeDirectProvider {
163
205
  }
164
206
  }
165
207
  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];
208
+ const deadline = Date.now() + uploadTimeoutMs;
209
+ const completed = new Array(missImages.length);
210
+ const recordSlot = (slot, item) => {
211
+ if (!item || item.mimeType !== missImages[slot].mimeType || typeof item.blobId !== 'string' || !item.blobId.length) return false;
212
+ completed[slot] = item;
176
213
  for (const targetIndex of missSlotIndices[slot]) {
177
214
  attachments[targetIndex] = item;
178
215
  const key = keys[targetIndex];
179
216
  if (this.blobCache && key) this.blobCache.set(key, item);
180
217
  }
218
+ return true;
219
+ };
220
+ for (let attempt = 0; attempt < 3; attempt++) {
221
+ const pendingSlots = [];
222
+ for (let slot = 0; slot < missImages.length; slot++) {
223
+ if (!completed[slot]) pendingSlots.push(slot);
224
+ }
225
+ if (!pendingSlots.length) break;
226
+ const remainingMs = Math.max(1, deadline - Date.now());
227
+ const batch = pendingSlots.map(slot => missImages[slot]);
228
+ try {
229
+ const uploaded = await this.uploadImages(token, batch, {
230
+ signal,
231
+ timeoutMs: remainingMs,
232
+ ...(attempt > 0 ? { concurrency: 1 } : {}),
233
+ onUploaded: (batchIndex, item) => {
234
+ const slot = pendingSlots[batchIndex];
235
+ if (slot !== undefined) recordSlot(slot, item);
236
+ },
237
+ });
238
+ if (!Array.isArray(uploaded) || uploaded.length !== batch.length) fail('INVALID_NATIVE_IMAGE_UPLOAD');
239
+ for (let batchIndex = 0; batchIndex < uploaded.length; batchIndex++) {
240
+ if (!recordSlot(pendingSlots[batchIndex], uploaded[batchIndex])) fail('INVALID_NATIVE_IMAGE_UPLOAD');
241
+ }
242
+ break;
243
+ } catch (err) {
244
+ const retryableReset = err?.code === 'NATIVE_IMAGE_UPLOAD_RESET' && !signal?.aborted && attempt < 2 && Date.now() + 250 < deadline;
245
+ if (!retryableReset) throw err;
246
+ await new Promise((resolve, reject) => {
247
+ const onAbort = () => { clearTimeout(t); reject(protocolError('NATIVE_IMAGE_UPLOAD_CANCELLED', 499)); };
248
+ const t = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, 200);
249
+ t.unref?.();
250
+ signal?.addEventListener('abort', onAbort, { once: true });
251
+ });
252
+ }
181
253
  }
182
254
  }
183
255
  return { attachments, usedCachedKeys };
@@ -252,11 +324,21 @@ export class NativeDirectProvider {
252
324
  : validateIdleMs(context.postOutputIdleMs, 'postOutputIdleMs');
253
325
  const body = normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
254
326
  if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
255
- const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode);
256
- if (recoveryInstruction) body.messages = [...body.messages, { role: 'system', content: recoveryInstruction }];
327
+ const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode, context.recoveryReason);
328
+ const appendRecovery = promptMessages => {
329
+ if (!recoveryInstruction || !promptMessages?.length) return promptMessages;
330
+ const next = promptMessages.map(msg => ({ ...msg }));
331
+ const last = next[next.length - 1];
332
+ const suffix = `\n\n${recoveryInstruction}`;
333
+ if (typeof last?.content === 'string' && Buffer.byteLength(last.content + suffix) <= PROMPT_MAX_BYTES) {
334
+ last.content += suffix;
335
+ }
336
+ return next;
337
+ };
257
338
  if (this.allowTextSnapshotReplacement && body.tools.length) fail('NATIVE_TEXT_SNAPSHOT_TOOLS_FORBIDDEN', 400);
258
339
  const policy = compileToolPolicy(body.tools, body.tool_choice);
259
340
  let { messages, images } = buildCanonicalPrompt(body);
341
+ messages = appendRecovery(messages);
260
342
  const isAutoModel = this.allowAutoModel && body.model === 'gemini-auto';
261
343
  const modeCategory = isAutoModel ? null : MODEL_MODES[body.model];
262
344
  const modeMatches = mode => isAutoModel
@@ -281,7 +363,7 @@ export class NativeDirectProvider {
281
363
  const requiresHydrogen = body.model === 'gemini-hydrogen';
282
364
  const requiresNeon = body.model === 'gemini-neon';
283
365
  let rawText = '', frames = 0, received = 0, observedMode = null, observedThinking = null;
284
- let modelComplete = false, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
366
+ let modelComplete = false, modelCompleteAt = null, lastTextProgressAt = null, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
285
367
  let observedFallback = null, downgradeReason = null, observedAttribution = null;
286
368
  const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? ''));
287
369
  const attributionVerified = () => attributionMatches(observedAttribution);
@@ -293,7 +375,7 @@ export class NativeDirectProvider {
293
375
  [RESPONSE_TOOL_IDENTITIES]: body[RESPONSE_TOOL_IDENTITIES],
294
376
  requestedThinkingLevel: body.thinking_level, ignoredTokenParameters: ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined),
295
377
  ...((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;
378
+ let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, liveToolError = null, liveToolErrorTailStart = 0, liveToolErrorDeadline = null, readExit = 'none', sinkFailed = false;
297
379
  const deliver = async event => {
298
380
  try { await onDelta(event); }
299
381
  catch (error) { sinkFailed = true; throw error; }
@@ -338,6 +420,7 @@ export class NativeDirectProvider {
338
420
  phase = 'upload';
339
421
  images = await bounded(this.downloadImages(images, { signal: controller.signal, timeoutMs: Math.min(timeoutMs, 30000) }));
340
422
  ({ messages, images } = buildCanonicalPrompt(body, images));
423
+ messages = appendRecovery(messages);
341
424
  }
342
425
  phase = 'auth';
343
426
  let token;
@@ -360,35 +443,78 @@ export class NativeDirectProvider {
360
443
  ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
361
444
  iterator = turn.events[Symbol.asyncIterator]();
362
445
  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;
446
+ let cachedFallbackText = null, cachedFallbackRevision = -1, cachedFallbackResult = { kind: 'none' };
447
+ const probeFullRawText = () => {
448
+ if (cachedFallbackText === rawText && cachedFallbackRevision === revisionCount) return cachedFallbackResult;
449
+ cachedFallbackText = rawText;
450
+ cachedFallbackRevision = revisionCount;
451
+ if (!rawText.trim() || ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) {
452
+ return (cachedFallbackResult = { kind: 'none' });
453
+ }
454
+ let probeItems;
366
455
  try {
367
456
  const probe = createToolCallSplitter({ policy });
368
- const probeItems = [...probe.push(rawText), ...probe.flush()];
457
+ probeItems = [...probe.push(rawText), ...probe.flush()];
458
+ } catch (probeError) {
459
+ if (probeError?.code === 'TRUNCATED_TOOL_CALL') return (cachedFallbackResult = { kind: 'streaming_tool' });
460
+ if (TOOL_ERRORS.has(probeError?.code)) return (cachedFallbackResult = { kind: 'closed_tool_error', error: probeError });
461
+ return (cachedFallbackResult = { kind: 'none' });
462
+ }
463
+ if (liveCalls.length > 0) return (cachedFallbackResult = { kind: 'none' });
464
+ try {
369
465
  const probeCalls = probeItems.filter(it => it.type === 'call').map(it => it.call);
370
466
  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;
467
+ if (!outputShape.nativeStructuredOutputPresent && softErrorReason(probeContent, body, probeCalls.length)) return (cachedFallbackResult = { kind: 'none' });
468
+ if (body.parallel_tool_calls === false && probeCalls.length > 1) return (cachedFallbackResult = { kind: 'none' });
373
469
  validateToolCompletion(probeCalls, policy);
374
- if (!probeCalls.length && !probeContent.trim()) return false;
470
+ if (!probeCalls.length && !probeContent.trim()) return (cachedFallbackResult = { kind: 'none' });
375
471
  if (body.response_format && !probeCalls.length) validateStructuredOutputText(probeContent, body.response_format);
376
- return true;
472
+ return (cachedFallbackResult = { kind: 'clean_output' });
377
473
  } catch {
378
- return false;
474
+ return (cachedFallbackResult = { kind: 'none' });
475
+ }
476
+ };
477
+ // O(1) incremental idle classification for streaming turns via liveSplitter.state;
478
+ // only falls back to full probe when a pending closing fence lacks trailing LF or !incremental.
479
+ const classifyIdleSnapshot = () => {
480
+ if (!rawText.trim() || ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) return { kind: 'none' };
481
+ if (!liveSplitter) return probeFullRawText();
482
+ const state = liveSplitter.state;
483
+ const lastLf = rawText.lastIndexOf('\n');
484
+ const trailingLine = lastLf < 0 ? rawText : rawText.slice(lastLf + 1);
485
+ if (state === 'tool_fence') {
486
+ if (trailingLine && CLOSING_FENCE_LINE_RE.test(trailingLine)) return probeFullRawText();
487
+ return { kind: 'streaming_tool' };
379
488
  }
489
+ if (state === 'text' && trailingLine && PENDING_TOOL_OPEN_RE.test(trailingLine)) {
490
+ return { kind: 'streaming_tool' };
491
+ }
492
+ if (liveCalls.length > 0) return { kind: 'none' };
493
+ if (policy.choice === 'required' || policy.forced) return { kind: 'none' };
494
+ const candidateText = liveContent + liveSplitter.preview();
495
+ if (!candidateText.trim()) return { kind: 'none' };
496
+ if (!outputShape.nativeStructuredOutputPresent && softErrorReason(candidateText, body, 0)) return { kind: 'none' };
497
+ return { kind: 'clean_output' };
380
498
  };
381
499
  const nextEventWithIdle = async () => {
382
500
  const verified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
383
- // Never arm an idle timer unless we already have verified, complete, deliverable output;
384
- // otherwise a slow mid-tool-call or mid-JSON pause would be falsely killed with 504 -> 422.
385
- const idleKind = (modelComplete && verified && rawText.trim().length > 0) ? 'post_complete'
386
- : (verified && liveCalls.length > 0 ? 'post_tool'
387
- : (verified && liveCalls.length === 0 && isCleanPostOutputIdleStall() ? 'post_output' : null));
388
- const idleMs = idleKind === 'post_complete' ? postCompleteGraceMs
389
- : idleKind === 'post_tool' ? postToolIdleMs
390
- : idleKind === 'post_output' ? postOutputIdleMs
391
- : null;
501
+ const snap = (verified && !liveToolError) ? classifyIdleSnapshot() : { kind: 'none' };
502
+ const { kind: idleKind, ms: idleMs } = selectIdleDeadline({
503
+ verified,
504
+ hasText: rawText.trim().length > 0,
505
+ hasLiveToolError: Boolean(liveToolError),
506
+ hasClosedToolError: snap.kind === 'closed_tool_error',
507
+ modelComplete,
508
+ hasLiveCalls: liveCalls.length > 0,
509
+ streamingTool: snap.kind === 'streaming_tool',
510
+ cleanOutput: snap.kind === 'clean_output',
511
+ liveToolErrorDeadline,
512
+ lastTextProgressAt,
513
+ modelCompleteAt,
514
+ postCompleteGraceMs,
515
+ postToolIdleMs,
516
+ postOutputIdleMs,
517
+ });
392
518
  const nextPromise = iterator.next();
393
519
  if (idleMs === null) return bounded(nextPromise);
394
520
  nextPromise.catch(() => {});
@@ -397,7 +523,7 @@ export class NativeDirectProvider {
397
523
  return await Promise.race([
398
524
  bounded(nextPromise),
399
525
  new Promise(resolve => {
400
- idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified }), idleMs);
526
+ idleTimer = setTimeout(() => resolve({ [IDLE_TIMEOUT_SENTINEL]: idleKind, verified, probeError: snap.error ?? null }), idleMs);
401
527
  idleTimer.unref?.();
402
528
  }),
403
529
  ]);
@@ -411,13 +537,21 @@ export class NativeDirectProvider {
411
537
  if (item && item[IDLE_TIMEOUT_SENTINEL]) {
412
538
  const idleKind = item[IDLE_TIMEOUT_SENTINEL];
413
539
  if (idleKind === 'post_complete' && item.verified && rawText.trim().length > 0) {
414
- note('post_complete_idle_finish', { frames, textBytes: Buffer.byteLength(rawText) });
540
+ note('post_complete_idle_finish', { bytes: Buffer.byteLength(rawText) });
415
541
  try { turn?.cancel(); } catch {}
542
+ readExit = 'complete_grace';
416
543
  ended = true;
417
544
  httpStatus = httpStatus ?? 200;
418
545
  grpc = grpc ?? 0;
419
546
  break;
420
547
  }
548
+ if (idleKind === 'post_tool_error' && item.verified && (liveToolError || item.probeError)) {
549
+ if (!liveToolError) liveToolError = item.probeError;
550
+ note('post_tool_error_idle_finish', { code: liveToolError.code, bytes: Buffer.byteLength(rawText) });
551
+ try { turn?.cancel(); } catch {}
552
+ readExit = 'deferred_tool_error';
553
+ break;
554
+ }
421
555
  note(`${idleKind}_idle_timeout`, {
422
556
  frames,
423
557
  calls: liveCalls.length,
@@ -425,7 +559,10 @@ export class NativeDirectProvider {
425
559
  });
426
560
  try { turn?.cancel(); } catch {}
427
561
  const idleError = protocolError('NATIVE_TURN_TIMEOUT', 504);
428
- if (idleKind === 'post_output' && item.verified && isCleanPostOutputIdleStall()) {
562
+ if (idleKind === 'post_tool' && item.verified && liveCalls.length > 0) {
563
+ idleError.postToolIdleStall = true;
564
+ }
565
+ if (idleKind === 'post_output' && item.verified && classifyIdleSnapshot().kind === 'clean_output') {
429
566
  idleError.postOutputIdleStall = true;
430
567
  }
431
568
  throw idleError;
@@ -471,7 +608,9 @@ export class NativeDirectProvider {
471
608
  if (!Number.isSafeInteger(info.thinkingLevel) || info.thinkingLevel < 0 || info.thinkingLevel > 4) fail('INVALID_NATIVE_THINKING_LEVEL');
472
609
  observedThinking = info.thinkingLevel;
473
610
  }
611
+ const wasComplete = modelComplete;
474
612
  modelComplete ||= info.completed;
613
+ if (!wasComplete && modelComplete) modelCompleteAt = Date.now();
475
614
  // Stop as soon as a wrong model is proven; do not pay for a full
476
615
  // downgraded answer that this gateway can never return as success.
477
616
  if (downgrade) {
@@ -498,26 +637,44 @@ export class NativeDirectProvider {
498
637
  snapshotPriorBytes: Buffer.byteLength(rawText), snapshotNextBytes: Buffer.byteLength(info.text),
499
638
  snapshotCommonPrefixBytes: commonPrefixBytes(rawText, info.text), ...committed });
500
639
  if (liveSyncedLength > 0) await deliver({ reset: true, sameResponseIdentity: true, response: identity });
501
- liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0;
640
+ liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0; liveToolError = null; liveToolErrorTailStart = 0; liveToolErrorDeadline = null;
502
641
  }
503
642
  }
504
643
  if (id) snapshotId = id;
505
644
  if (!extendsPrior) revisionCount++;
506
- if (info.text !== rawText) modelComplete = info.completed;
645
+ if (info.text !== rawText) {
646
+ modelComplete = info.completed;
647
+ modelCompleteAt = modelComplete ? Date.now() : null;
648
+ lastTextProgressAt = Date.now();
649
+ }
507
650
  rawText = info.text;
508
651
  } else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
509
652
  fail('INVALID_NATIVE_RESPONSE');
510
653
  }
511
- if (incremental && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
654
+ if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
512
655
  const delta = rawText.slice(liveSyncedLength);
513
656
  liveSyncedLength = rawText.length;
514
- await publish(liveSplitter.push(delta));
657
+ try {
658
+ await publish(liveSplitter.push(delta));
659
+ } catch (splitError) {
660
+ // Defer recoverable tool-protocol errors briefly until stream completion so
661
+ // upstream completion/downgrade/refusal evidence is fully verified and
662
+ // automatic tool_protocol recovery (or same-ID revision) can run cleanly.
663
+ if (!sinkFailed && TOOL_ERRORS.has(splitError?.code)) {
664
+ liveToolError = splitError;
665
+ liveToolErrorTailStart = Number.isInteger(splitError.postFenceOffset) ? splitError.postFenceOffset : rawText.length;
666
+ liveToolErrorDeadline = postToolIdleMs === null ? null : Date.now() + postToolIdleMs;
667
+ } else {
668
+ throw splitError;
669
+ }
670
+ }
515
671
  // Once valid tool_call(s) have been parsed and the model begins hallucinating
516
672
  // a fake [Caller tool result], stop upstream immediately instead of waiting
517
673
  // minutes for the model to finish generating discarded text.
518
- if (liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
674
+ if (!liveToolError && liveSplitter.suppressed && liveCalls.length > 0 && !downgrade && !outputShape.nativeRefusalPresent) {
519
675
  note('early_stop_post_tool_hallucination', { calls: liveCalls.length });
520
676
  try { turn?.cancel(); } catch {}
677
+ readExit = 'suppressed_after_valid_call';
521
678
  ended = true;
522
679
  modelComplete = true;
523
680
  httpStatus = httpStatus ?? 200;
@@ -525,13 +682,24 @@ export class NativeDirectProvider {
525
682
  break;
526
683
  }
527
684
  }
685
+ if (incremental && liveToolError && !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified()) {
686
+ const postErrorTail = rawText.slice(liveToolErrorTailStart);
687
+ const postErrorTailBytes = Buffer.byteLength(postErrorTail);
688
+ const graceExpired = liveToolErrorDeadline !== null && Date.now() >= liveToolErrorDeadline;
689
+ if (postErrorTail.includes('[Caller tool result]') || postErrorTailBytes > 4096 || graceExpired) {
690
+ note('early_stop_post_tool_error', { code: liveToolError.code, bytes: postErrorTailBytes });
691
+ try { turn?.cancel(); } catch {}
692
+ readExit = 'deferred_tool_error';
693
+ break;
694
+ }
695
+ }
528
696
  if (info.quotaObservation) {
529
697
  quotaFrames++;
530
698
  if (quotaFrames > 16) quotaObservation = null;
531
699
  else if (info.quotaObservation.source === 'official') quotaObservation = mergeQuotaObservation(quotaObservation, info.quotaObservation);
532
700
  }
533
701
  } else if (event.type === 'end') {
534
- phase = 'end'; ended = true; grpc = event.grpcStatus; httpStatus = event.httpStatus;
702
+ phase = 'end'; readExit = 'wire_end'; ended = true; grpc = event.grpcStatus; httpStatus = event.httpStatus;
535
703
  if (event.httpStatus === 429 || grpc === 8) fail('NATIVE_RATE_LIMITED', 429);
536
704
  if (event.httpStatus === 401 || grpc === 16) fail('NATIVE_AUTH_REJECTED');
537
705
  if (event.httpStatus === 403 || grpc === 7) fail('NATIVE_PERMISSION_REJECTED');
@@ -562,14 +730,19 @@ export class NativeDirectProvider {
562
730
  }
563
731
  phase = 'validate';
564
732
  if (downgrade) fail('MODEL_DOWNGRADE_REJECTED');
733
+ if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
734
+ if (readExit === 'deferred_tool_error' && liveToolError) {
735
+ if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
736
+ if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
737
+ throw liveToolError;
738
+ }
565
739
  if (!ended) fail('INCOMPLETE_NATIVE_RESPONSE');
566
740
  // An ordinary RPC close is not model completion. Async UI placeholders
567
741
  // must be non-retryable or PI will repeatedly submit fresh generations.
568
- 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)) fail('NATIVE_ASYNC_RESPONSE_UNSUPPORTED', 422);
742
+ if (ASYNC_DEEP_THINK_PLACEHOLDER_RE.test(rawText)) fail('NATIVE_ASYNC_RESPONSE_UNSUPPORTED', 422);
569
743
  if (!modelComplete) fail('INCOMPLETE_NATIVE_RESPONSE');
570
744
  if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
571
745
  if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
572
- if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
573
746
  if (!rawText.trim()) {
574
747
  if (outputShape.nativeShareableTextBytes || outputShape.nativeStructuredOutputPresent) fail('NATIVE_OUTPUT_NOT_TEXT', 422);
575
748
  emptyResponseReason = rawText.length ? 'whitespace_only' : outputShape.nativeThoughtsPresent ? 'thoughts_only' : 'no_text';
@@ -577,6 +750,7 @@ export class NativeDirectProvider {
577
750
  }
578
751
  let items;
579
752
  if (incremental) {
753
+ if (liveToolError) throw liveToolError;
580
754
  if (liveSyncedLength < rawText.length) {
581
755
  const delta = rawText.slice(liveSyncedLength);
582
756
  liveSyncedLength = rawText.length;
@@ -621,7 +795,7 @@ export class NativeDirectProvider {
621
795
  return result;
622
796
  } catch (error) {
623
797
  const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
624
- if (incremental && modeVerified && !sinkFailed) {
798
+ if (incremental && !liveToolError && modeVerified && !sinkFailed) {
625
799
  try { await publish(liveSplitter.flush()); }
626
800
  catch { /* Retain already-published text; never release an invalid/incomplete tool body. */ }
627
801
  }
@@ -630,8 +804,10 @@ export class NativeDirectProvider {
630
804
  note('provider_failure', { code: safe.code });
631
805
  let transport = {};
632
806
  try { transport = turn?.getSafeStatus?.() ?? {}; } catch {}
807
+ const committedOnFailure = committedOutput();
633
808
  safe.nativeEvidence = safeNativeEvidence({
634
809
  // Keep guard-site diagnostics raised deeper in this turn; they are byte counts only.
810
+ ...((committedOnFailure.publishedBytes > 0 || committedOnFailure.toolCallCount > 0 || TOOL_ERRORS.has(safe.code)) ? committedOnFailure : {}),
635
811
  ...(error.nativeEvidence ?? {}),
636
812
  phase, upstreamHttpStatus: transport.httpStatus ?? httpStatus,
637
813
  grpcStatus: transport.grpcStatus ?? grpc,
@@ -644,6 +820,7 @@ export class NativeDirectProvider {
644
820
  observedMode, observedThinking,
645
821
  fallback: observedFallback, downgradeReason,
646
822
  toolProtocolReason: safe.toolProtocolReason,
823
+ ...((readExit === 'deferred_tool_error' || (readExit === 'complete_grace' && phase === 'validate' && TOOL_ERRORS.has(safe.code))) ? { toolErrorEarlyStop: true } : {}),
647
824
  ...(outputObserved ? { nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
648
825
  nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null } : {}),
649
826
  ...(responseLimitReason ? { nativeResponseLimitReason: responseLimitReason } : {}),
@@ -86,6 +86,7 @@ function requestBudget(root) {
86
86
  for (const item of Array.isArray(root.input) ? root.input.slice(0, MAX_MESSAGES) : []) {
87
87
  if (item?.type === 'input_image') mark(item, true);
88
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);
89
90
  }
90
91
  const ancestors = new Set();
91
92
  const visit = (value, depth, image = false) => {
@@ -159,7 +160,7 @@ function validateReplayAnnotations(annotations, { chat = false } = {}) {
159
160
  }
160
161
  }
161
162
  }
162
- 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 } = {}) {
163
164
  if (value === null && assistant) return null;
164
165
  if (typeof value === 'string') return text(value);
165
166
  if (!Array.isArray(value) || !value.length || value.length > 1024) fail('INVALID_MESSAGE_CONTENT');
@@ -170,7 +171,12 @@ function content(value, { assistant = false, responses = false, user = false, pr
170
171
  if (!responses) keys(part.image_url, ['url', 'detail'], `${prefix}.image_url`);
171
172
  const url = responses ? part.image_url : part.image_url.url;
172
173
  const detail = responses ? part.detail : part.image_url.detail;
173
- 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) };
174
180
  }
175
181
  keys(part, responses ? ['type', 'text', 'annotations', 'logprobs', 'parsed'] : ['type', 'text'], prefix);
176
182
  if (part.parsed !== undefined && (part.parsed !== null || !assistant)) fail('UNSUPPORTED_PARAMETER', 400, `${prefix}.parsed`);
@@ -246,8 +252,8 @@ function stripToolAnnotations(tools) {
246
252
  }
247
253
 
248
254
  /** Also used by the provider; computes the EXACT budgeted wire prompt. */
249
- export function buildCanonicalPrompt(body, resolvedImages) {
250
- 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);
251
257
  if (body.native_search && images.length) fail('NATIVE_SEARCH_IMAGES_UNSUPPORTED');
252
258
  const { systemText, userText } = flattenMessages(transcript, { maxChars: MAX_CHARS });
253
259
  const instruction = body.native_search
@@ -327,7 +333,8 @@ function validateInertOpenAIFields(payload, { responses = false } = {}) {
327
333
  }
328
334
  }
329
335
 
330
- export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
336
+ export function normalizeChatRequest(payload, { allowAutoModel = false, _imageCache } = {}) {
337
+ const imageCache = _imageCache ?? new Map();
331
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']);
332
339
  requestBudget(payload);
333
340
  validateInertOpenAIFields(payload);
@@ -377,7 +384,7 @@ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
377
384
  if (role !== 'assistant' && message.tool_calls !== undefined) fail('INVALID_TOOL_CALL');
378
385
  if (role !== 'tool' && message.tool_call_id !== undefined) fail('INVALID_TOOL_RESULT');
379
386
  const messageContent = role === 'assistant' && message.content === undefined && message.tool_calls !== undefined ? null : message.content;
380
- 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 }) };
381
388
  if (role === 'assistant' && message.tool_calls !== undefined) {
382
389
  if (!Array.isArray(message.tool_calls) || !message.tool_calls.length || message.tool_calls.length > 32) fail('INVALID_TOOL_CALL');
383
390
  normalized.tool_calls = message.tool_calls.map(call => {
@@ -408,11 +415,12 @@ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
408
415
  body.stream_options = { include_usage: payload.stream_options.include_usage };
409
416
  }
410
417
  }
411
- buildCanonicalPrompt(body); // Validate budgets BEFORE any account reservation.
418
+ buildCanonicalPrompt(body, undefined, imageCache); // Validate budgets BEFORE any account reservation.
412
419
  return body;
413
420
  }
414
421
 
415
422
  export function normalizeResponsesRequest(payload, { allowAutoModel = false } = {}) {
423
+ const imageCache = new Map();
416
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']);
417
425
  requestBudget(payload);
418
426
  validateInertOpenAIFields(payload, { responses: true });
@@ -425,8 +433,14 @@ export function normalizeResponsesRequest(payload, { allowAutoModel = false } =
425
433
  if (!Array.isArray(input) || !input.length) fail('INPUT_REQUIRED');
426
434
  if (input.length > MAX_MESSAGES) fail('REQUEST_TOO_LARGE', 413, 'input');
427
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
+ };
428
441
  for (const item of input) {
429
442
  if (!plainObject(item)) fail('INVALID_INPUT_ITEM');
443
+ if (item.type !== 'function_call_output') flushToolImages();
430
444
  if (item.type === 'function_call') {
431
445
  keys(item, ['type', 'id', 'status', 'call_id', 'namespace', 'name', 'arguments', 'parsed_arguments'], 'input');
432
446
  if (item.parsed_arguments !== undefined && item.parsed_arguments !== null) fail('UNSUPPORTED_PARAMETER', 400, 'input.parsed_arguments');
@@ -439,22 +453,43 @@ export function normalizeResponsesRequest(payload, { allowAutoModel = false } =
439
453
  } else if (item.type === 'function_call_output') {
440
454
  keys(item, ['type', 'id', 'call_id', 'output'], 'input');
441
455
  if (item.id !== undefined) id(item.id);
442
- 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
+ }
443
477
  } else if (item.type === 'input_text') {
444
478
  keys(item, ['type', 'text'], 'input'); messages.push({ role: 'user', content: text(item.text) });
445
479
  } else if (item.type === 'input_image') {
446
- 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 }) });
447
481
  } else {
448
482
  keys(item, ['type', 'id', 'status', 'role', 'content'], 'input');
449
483
  if (item.type !== undefined && item.type !== 'message') fail('UNSUPPORTED_INPUT_TYPE');
450
484
  if (item.id !== undefined) id(item.id);
451
485
  if (item.status !== undefined && (item.role !== 'assistant' || item.status !== 'completed')) fail('INVALID_INPUT_STATUS');
452
- 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 }) });
453
487
  }
454
488
  }
489
+ flushToolImages();
455
490
  const { include: _include, ...inertCompat } = compat;
456
- const body = normalizeChatRequest({ ...resolved, ...inertCompat, ...(response_format ? { response_format } : {}), messages, tools, tool_choice: choice, [RESPONSE_TOOL_IDENTITIES]: identities }, { allowAutoModel });
457
- 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;
458
493
  return {
459
494
  body,
460
495
  systemPrompt: projected.filter(m => ['system', 'developer'].includes(m.role)).map(m => m.content).join('\n'),
@@ -32,6 +32,7 @@ export function measurePromptImagePayload(body) {
32
32
  imageUrlChars += item.image_url.length;
33
33
  } else {
34
34
  scanParts(item?.content);
35
+ scanParts(item?.output);
35
36
  }
36
37
  }
37
38
  }