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.
package/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # `pi-gemini-app` — Google Gemini App Provider for Pi
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/pi-gemini-app?logo=npm&label=pi-gemini-app)](https://www.npmjs.com/package/pi-gemini-app)
4
+ [![Pi Packages](https://img.shields.io/badge/Pi%20Packages-pi--gemini--app-6366F1)](https://pi.dev/packages/pi-gemini-app?name=pi-gemini-app)
5
+
3
6
  ![pi-gemini-app — Native Pi Extension for Gemini Neon over Direct HTTP/2](https://raw.githubusercontent.com/ShawTim/gemini-app2api/main/docs/assets/pi-extension.jpg)
4
7
 
5
8
  Native in-process provider extension for `@earendil-works/pi-coding-agent` (`pi`) and GooeyPi. Connects directly to Gemini's native HTTP/2 endpoint (`ProcessQuery`) inside the Pi process—no separate HTTP gateway server, Docker container, or extra npm runtime dependencies required.
@@ -1,7 +1,7 @@
1
1
  import { openDirectTurn as defaultOpenDirectTurn } from '../../src/gateway/native-transport.mjs';
2
2
  import { createImageBlobCache } from '../../src/gateway/image-upload.mjs';
3
3
  import { NativeDirectProvider as DefaultNativeDirectProvider } from '../../src/native-provider.mjs';
4
- import { automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
4
+ import { TOOL_ERRORS, automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
5
5
  import { buildChatPayload as defaultBuildChatPayload } from './transcript.js';
6
6
  import { estimateUsage as defaultEstimateUsage, measurePromptImagePayload } from '../../src/openai-usage.mjs';
7
7
 
@@ -365,6 +365,7 @@ export function createGeminiStreamHandler({
365
365
 
366
366
  let attempts = 0;
367
367
  let recoveryCode;
368
+ let recoveryReason;
368
369
 
369
370
  while (true) {
370
371
  try {
@@ -439,6 +440,7 @@ export function createGeminiStreamHandler({
439
440
  incrementalOutput: true,
440
441
  signal: options?.signal,
441
442
  recoveryCode,
443
+ recoveryReason,
442
444
  getOutputCommitState,
443
445
  });
444
446
  if (turnResult?.thinkingLevel !== undefined && turnResult.thinkingLevel !== null) {
@@ -449,25 +451,25 @@ export function createGeminiStreamHandler({
449
451
  }
450
452
  break;
451
453
  } catch (turnError) {
452
- if (
453
- !options?.signal?.aborted &&
454
+ const usableTimeout =
454
455
  turnError?.code === 'NATIVE_TURN_TIMEOUT' &&
455
- turnError?.unverifiedOutput !== true &&
456
- (hasToolCalls || turnError?.postOutputIdleStall === true || publishedBytes >= PREFIX_BYTES)
457
- ) {
456
+ (hasToolCalls || turnError?.postOutputIdleStall === true || publishedBytes >= PREFIX_BYTES);
457
+ const salvageValidatedCalls = hasToolCalls && TOOL_ERRORS.has(turnError?.code);
458
+ if (!options?.signal?.aborted && turnError?.unverifiedOutput !== true && (usableTimeout || salvageValidatedCalls)) {
458
459
  break;
459
460
  }
460
461
  if (
461
462
  !started &&
462
- attempts === 0 &&
463
463
  !options?.signal?.aborted &&
464
464
  turnError?.code !== 'NATIVE_TURN_ABORTED' &&
465
465
  turnError?.code !== 'REQUEST_CANCELLED'
466
466
  ) {
467
467
  const kind = automaticRecoveryKind(turnError, model.id, { allowAutoModel: true });
468
- if (ALLOWED_RECOVERY_KINDS.has(kind)) {
468
+ const maxRetries = kind === 'tool_protocol' || kind === 'structured_output' ? 2 : 1;
469
+ if (ALLOWED_RECOVERY_KINDS.has(kind) && attempts < maxRetries) {
469
470
  attempts++;
470
471
  recoveryCode = turnError.code;
472
+ recoveryReason = turnError.toolProtocolReason ?? turnError.nativeEvidence?.toolProtocolReason ?? null;
471
473
  textBuffer = '';
472
474
  pendingSurrogate = '';
473
475
  observedThinking = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
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": [
@@ -2,15 +2,31 @@
2
2
  import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
3
3
  import { isVerifiedEmptyResponse } from './output-recovery.mjs';
4
4
  import { isExplicitQuotaFailure } from './quota-failover.mjs';
5
- const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON', 'TRUNCATED_TOOL_CALL', 'INVALID_TOOL_CALL',
5
+ export const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON', 'TRUNCATED_TOOL_CALL', 'INVALID_TOOL_CALL',
6
6
  'INVALID_TOOL_ARGUMENTS', 'UNDECLARED_TOOL', 'TOOL_ARGUMENT_SCHEMA_MISMATCH', 'TOOL_CHOICE_NOT_SATISFIED',
7
7
  'TOOL_CHOICE_MISMATCH', 'TOOL_CALL_NOT_ALLOWED', 'PARALLEL_TOOL_CALLS_DISABLED']);
8
8
  const STRUCTURED_OUTPUT_ERRORS = new Set(['INVALID_STRUCTURED_OUTPUT_JSON', 'STRUCTURED_OUTPUT_SCHEMA_MISMATCH']);
9
9
  const TRANSPORT_ERRORS = new Set(['NATIVE_STREAM_RESET', 'NATIVE_CONNECTION_FAILED', 'NATIVE_STREAM_FAILED', 'NATIVE_STREAM_CLOSED_EARLY']);
10
- export function toolRecoveryInstruction(code) {
10
+ const JSON_REASON_HINTS = Object.freeze({
11
+ multiple_root_values: ' The previous tool_call block failed JSON parsing (multiple_root_values): never put multiple JSON objects inside one tool_call fence; open a separate ```tool_call block for each call.',
12
+ raw_newline_in_string: ' The previous tool_call block failed JSON parsing (raw_newline_in_string): encode all newlines inside JSON string values as \\n, never raw line breaks.',
13
+ control_char_in_string: ' The previous tool_call block failed JSON parsing (control_char_in_string): escape control characters (such as \\t and \\n) inside JSON strings.',
14
+ invalid_escape: ' The previous tool_call block failed JSON parsing (invalid_escape): double-escape backslashes (\\\\) in regexes, paths, and shell commands.',
15
+ unexpected_token_after_string: ' The previous tool_call block failed JSON parsing (unexpected_token_after_string): escape all inner double quotes as \\" inside shell/code strings.',
16
+ trailing_comma: ' The previous tool_call block failed JSON parsing (trailing_comma): remove trailing commas before } or ].',
17
+ unterminated_json: ' The previous tool_call block was truncated or missing a closing quote/brace (unterminated_json): emit the complete JSON object before closing the ``` fence.',
18
+ duplicate_key: ' The previous tool_call block contained duplicate JSON object keys (duplicate_key): emit each key only once.',
19
+ limit_exceeded: ' The previous tool_call block exceeded JSON size/depth limits (limit_exceeded): split large edits into smaller calls.',
20
+ });
21
+ export function toolRecoveryInstruction(code, reason = null) {
11
22
  if (TOOL_ERRORS.has(code)) {
23
+ const jsonHint = code === 'INVALID_TOOL_JSON'
24
+ ? (JSON_REASON_HINTS[reason] ?? ' The previous tool_call block failed strict JSON parsing: double-escape all backslashes (\\\\) and quotes (\\") inside shell/code strings, use \\n instead of raw newlines inside strings, avoid trailing commas, and never put multiple JSON objects inside one tool_call fence (use a separate ```tool_call block per call).')
25
+ : '';
12
26
  return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered and no caller tool was executed.]\n' +
13
- 'Answer the latest user request using the complete history. If a tool is needed and permitted, emit a complete tool_call block with exactly the keys "name" and "arguments" as valid JSON. Use only declared names and actual JSON-object arguments matching the original schema. Respect the selected tool choice and parallel-call restriction. Put both fences on separate lines. Do not invent tool results, duplicate already completed work, or discuss this recovery instruction. If tools are prohibited, answer normally without tool_call blocks.';
27
+ 'Answer the latest user request using the complete history. If a tool is needed and permitted, emit a complete tool_call block with exactly the keys "name" and "arguments" as valid JSON. Emit one strict JSON object per tool_call block with properly escaped strings (no raw newlines, invalid escapes, or trailing commas).' +
28
+ jsonHint +
29
+ ' Use only declared names and actual JSON-object arguments matching the original schema. Respect the selected tool choice and parallel-call restriction. Put both fences on separate lines. Do not invent tool results, duplicate already completed work, or discuss this recovery instruction. If tools are prohibited, answer normally without tool_call blocks.';
14
30
  }
15
31
  if (STRUCTURED_OUTPUT_ERRORS.has(code)) {
16
32
  return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered because it did not satisfy the required JSON output format.]\n' +
@@ -50,11 +66,17 @@ export function automaticRecoveryKind(error, model, { allowAutoModel = false } =
50
66
  if (error.status !== 502) return null;
51
67
  if (TRANSPORT_ERRORS.has(error.code) && ['open', 'read', 'decode', 'end'].includes(e.phase) &&
52
68
  (e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) && (e.grpcStatus === null || e.grpcStatus === 0)) return 'transport';
69
+ if (error.code === 'NATIVE_IMAGE_UPLOAD_RESET' && e.phase === 'upload' &&
70
+ e.upstreamHttpStatus === null && e.grpcStatus === null) return 'transport';
53
71
  const completed = e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 && e.wireEnded === true &&
54
72
  e.modelCompleted === true && modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
73
+ const earlyStoppedToolError = e.phase === 'validate' && e.toolErrorEarlyStop === true &&
74
+ (e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) &&
75
+ (e.grpcStatus === null || e.grpcStatus === 0) &&
76
+ modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
55
77
  if (completed && error.code === 'NATIVE_SOFT_ERROR_RESPONSE' && e.outputFailureReason === 'generic_error_offer' &&
56
78
  e.outputFailureSource === 'exact_text_signature' && e.outputToolCalls === 0 && e.nativeStructuredOutputPresent === false) return 'provider_soft_error';
57
- if (completed && TOOL_ERRORS.has(error.code)) return 'tool_protocol';
79
+ if ((completed || earlyStoppedToolError) && TOOL_ERRORS.has(error.code)) return 'tool_protocol';
58
80
  if (completed && STRUCTURED_OUTPUT_ERRORS.has(error.code)) return 'structured_output';
59
81
  // A clean but incomplete turn may be regenerated; never treat it as success.
60
82
  if (error.code === 'INCOMPLETE_NATIVE_RESPONSE' && e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 &&
@@ -6,6 +6,7 @@ import { GATEWAY_USER_AGENT } from '../../native-wire/robin-current.mjs';
6
6
 
7
7
  const ORIGIN = 'https://push.clients6.google.com';
8
8
  export const DEFAULT_UPLOAD_CONCURRENCY = 8;
9
+ export const DEFAULT_MAX_IN_FLIGHT_BYTES = 4 * 1024 * 1024;
9
10
  export const MAX_UPLOAD_TIMEOUT_MS = 600_000;
10
11
  const fail = (suffix, status = 502) => { throw protocolError(`NATIVE_IMAGE_UPLOAD_${suffix}`, status); };
11
12
  const mimeTypes = new Set(['image/png', 'image/jpeg', 'image/webp']);
@@ -82,7 +83,7 @@ function boundedLocation(value) {
82
83
  export async function uploadNativeImages(
83
84
  token,
84
85
  images,
85
- { signal, timeoutMs = 60000, concurrency = DEFAULT_UPLOAD_CONCURRENCY } = {},
86
+ { signal, timeoutMs = 60000, concurrency = DEFAULT_UPLOAD_CONCURRENCY, maxInFlightBytes = DEFAULT_MAX_IN_FLIGHT_BYTES, onUploaded } = {},
86
87
  { connect = connectHttp2 } = {},
87
88
  ) {
88
89
  validateImages(images);
@@ -98,15 +99,45 @@ export async function uploadNativeImages(
98
99
  !Number.isSafeInteger(concurrency) ||
99
100
  concurrency < 1 ||
100
101
  concurrency > 32 ||
102
+ !Number.isSafeInteger(maxInFlightBytes) ||
103
+ maxInFlightBytes < 1 ||
104
+ (onUploaded !== undefined && typeof onUploaded !== 'function') ||
101
105
  (signal !== undefined && (!signal || typeof signal.addEventListener !== 'function')) ||
102
106
  typeof connect !== 'function'
103
107
  ) fail('INVALID_RESPONSE');
104
108
  if (signal?.aborted) fail('CANCELLED', 499);
105
109
  const deadline = Date.now() + timeoutMs;
106
110
  let session, timeout, sessionFailed = false, batchError = null;
111
+ let inFlightBytes = 0, activeUploads = 0;
107
112
  const activeStops = new Set();
113
+ const budgetWaiters = [];
114
+ const wakeBudgetWaiters = () => {
115
+ while (budgetWaiters.length) {
116
+ const next = budgetWaiters[0];
117
+ if (activeUploads === 0 || inFlightBytes + next.bytes <= maxInFlightBytes || batchError || sessionFailed || signal?.aborted) {
118
+ budgetWaiters.shift();
119
+ next.resolve();
120
+ } else {
121
+ break;
122
+ }
123
+ }
124
+ };
125
+ const acquireByteBudget = async (bytes) => {
126
+ while (activeUploads > 0 && inFlightBytes + bytes > maxInFlightBytes && !batchError && !sessionFailed && !signal?.aborted) {
127
+ await new Promise(resolve => budgetWaiters.push({ bytes, resolve }));
128
+ }
129
+ ensureAlive();
130
+ activeUploads++;
131
+ inFlightBytes += bytes;
132
+ };
133
+ const releaseByteBudget = (bytes) => {
134
+ activeUploads = Math.max(0, activeUploads - 1);
135
+ inFlightBytes = Math.max(0, inFlightBytes - bytes);
136
+ wakeBudgetWaiters();
137
+ };
108
138
  const stopAll = (err) => {
109
139
  if (!batchError) batchError = err;
140
+ wakeBudgetWaiters();
110
141
  for (const stop of [...activeStops]) stop(err);
111
142
  };
112
143
  const abortCode = () => signal?.aborted ? ['CANCELLED', 499] : Date.now() >= deadline ? ['TIMEOUT', 504] : null;
@@ -168,22 +199,30 @@ export async function uploadNativeImages(
168
199
  });
169
200
  const onSessionError = () => { sessionFailed = true; stopAll(protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); };
170
201
  const uploadOne = async (image) => {
171
- ensureAlive();
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);
173
- if (String(initial.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'active') fail('INVALID_RESPONSE');
174
- const location = boundedLocation(initial.headers['x-goog-upload-url']);
175
- ensureAlive();
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);
177
- if (String(final.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'final') fail('INVALID_RESPONSE');
178
- let blobId;
179
- try { blobId = new TextDecoder('utf-8', { fatal: true }).decode(final.body); } catch { fail('INVALID_RESPONSE'); }
180
- if (!blobId || Buffer.byteLength(blobId) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(blobId)) fail('INVALID_RESPONSE');
181
- ensureAlive();
182
- return { blobId, mimeType: image.mimeType };
202
+ await acquireByteBudget(image.data.length);
203
+ try {
204
+ ensureAlive();
205
+ 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);
206
+ if (String(initial.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'active') fail('INVALID_RESPONSE');
207
+ const location = boundedLocation(initial.headers['x-goog-upload-url']);
208
+ ensureAlive();
209
+ 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);
210
+ if (String(final.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'final') fail('INVALID_RESPONSE');
211
+ let blobId;
212
+ try { blobId = new TextDecoder('utf-8', { fatal: true }).decode(final.body); } catch { fail('INVALID_RESPONSE'); }
213
+ if (!blobId || Buffer.byteLength(blobId) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(blobId)) fail('INVALID_RESPONSE');
214
+ ensureAlive();
215
+ return { blobId, mimeType: image.mimeType };
216
+ } finally {
217
+ releaseByteBudget(image.data.length);
218
+ }
183
219
  };
220
+ const onSignalAbort = () => wakeBudgetWaiters();
221
+ signal?.addEventListener('abort', onSignalAbort, { once: true });
184
222
  try {
185
223
  try { session = connect(ORIGIN, { settings: { enablePush: false, maxHeaderListSize: 8192 } }); } catch { fail('RESET'); }
186
224
  if (!session || typeof session.request !== 'function') fail('RESET');
225
+ try { session.socket?.setKeepAlive?.(true, 15_000); } catch {}
187
226
  session.on?.('error', onSessionError);
188
227
  session.on?.('close', onSessionError);
189
228
  timeout = setTimeout(() => { stopAll(protocolError('NATIVE_IMAGE_UPLOAD_TIMEOUT', 504)); try { session.destroy(); } catch {} }, Math.max(1, deadline - Date.now()));
@@ -195,7 +234,9 @@ export async function uploadNativeImages(
195
234
  const index = nextIndex++;
196
235
  if (index >= images.length) return;
197
236
  try {
198
- results[index] = await uploadOne(images[index]);
237
+ const uploaded = await uploadOne(images[index]);
238
+ results[index] = uploaded;
239
+ try { onUploaded?.(index, uploaded); } catch {}
199
240
  } catch (err) {
200
241
  stopAll(err);
201
242
  throw err;
@@ -213,6 +254,8 @@ export async function uploadNativeImages(
213
254
  fail('RESET');
214
255
  } finally {
215
256
  clearTimeout(timeout);
257
+ signal?.removeEventListener('abort', onSignalAbort);
258
+ wakeBudgetWaiters();
216
259
  try { session?.on?.('error', drainError); session?.removeListener?.('error', onSessionError); session?.removeListener?.('close', onSessionError); } catch {}
217
260
  try { session?.destroy(); } catch {}
218
261
  }
@@ -15,10 +15,11 @@ export const NATIVE_DIAGNOSTIC_LIMITS = Object.freeze({
15
15
  });
16
16
  const L = NATIVE_DIAGNOSTIC_LIMITS;
17
17
  const eventNames = new Set(['provider_stop', 'provider_cleanup', 'provider_success', 'provider_failure',
18
- 'early_stop_post_tool_hallucination', 'post_complete_idle_finish', 'post_complete_idle_timeout',
18
+ 'early_stop_post_tool_hallucination', 'early_stop_post_tool_error',
19
+ 'post_complete_idle_finish', 'post_complete_idle_timeout', 'post_tool_error_idle_finish',
19
20
  'post_tool_idle_timeout', 'post_output_idle_timeout',
20
21
  'transport_open', 'local_stream_close', 'local_session_destroy', 'local_signal_abort', 'local_cancel',
21
- 'transport_failure', 'transport_deadline', 'peer_headers', 'peer_trailers', 'peer_reset',
22
+ 'transport_failure', 'transport_deadline', 'transport_ping_timeout', 'peer_headers', 'peer_trailers', 'peer_reset',
22
23
  'peer_goaway', 'stream_error', 'stream_close', 'stream_end', 'peer_data', 'local_half_close',
23
24
  'peer_connection_end', 'peer_connection_close']);
24
25
  const numberKeys = new Set(['httpStatus', 'grpcStatus', 'rstCode', 'requestedCode', 'goawayCode',
@@ -102,6 +103,7 @@ export class NativeDiagnostic {
102
103
  this.now = now; this.monotonic = monotonic;
103
104
  }
104
105
  claim(requestId) {
106
+ if (process.platform === 'win32') return null;
105
107
  let fd;
106
108
  try {
107
109
  if (!this.directory || !/^req_[a-f0-9-]{36}$/.test(requestId)) return null;
@@ -3,6 +3,22 @@ import { NATIVE_RESPONSE_LIMITS } from './native-response-limits.mjs';
3
3
  import { NATIVE_MODELS } from '../openai-contract.mjs';
4
4
  const bounded = (value, min, max) =>
5
5
  Number.isSafeInteger(value) && value >= min && value <= max ? value : null;
6
+ const TOOL_PROTOCOL_REASONS = new Set([
7
+ 'opening_fence',
8
+ 'closing_fence',
9
+ 'multiple_root_values',
10
+ 'raw_newline_in_string',
11
+ 'control_char_in_string',
12
+ 'invalid_escape',
13
+ 'unexpected_token_after_string',
14
+ 'trailing_comma',
15
+ 'unterminated_json',
16
+ 'duplicate_key',
17
+ 'nonfinite_number',
18
+ 'invalid_surrogate',
19
+ 'limit_exceeded',
20
+ 'invalid_syntax',
21
+ ]);
6
22
  const phases = new Set([
7
23
  "auth",
8
24
  "upload",
@@ -67,7 +83,7 @@ export function safeNativeEvidence(value) {
67
83
  const streamCloseCode = bounded(value.streamCloseCode, 1, 0xffffffff);
68
84
  const fallback = bounded(value.fallback, 0, 1);
69
85
  const downgradeReason = bounded(value.downgradeReason, 0, 0x7fffffff);
70
- const toolProtocolReason = ['opening_fence', 'closing_fence'].includes(value.toolProtocolReason) ? value.toolProtocolReason : null;
86
+ const toolProtocolReason = TOOL_PROTOCOL_REASONS.has(value.toolProtocolReason) ? value.toolProtocolReason : null;
71
87
  const emptyResponseReason = ['no_text', 'whitespace_only', 'thoughts_only', 'post_parse_empty'].includes(value.emptyResponseReason) ? value.emptyResponseReason : null;
72
88
  const nativeTextBytes = bounded(value.nativeTextBytes, 0, 8 * 1024 * 1024);
73
89
  const nativeShareableTextBytes = bounded(value.nativeShareableTextBytes, 0, 8 * 1024 * 1024);
@@ -91,6 +107,7 @@ export function safeNativeEvidence(value) {
91
107
  ...(bounded(value.outputToolCalls, 0, 32) !== null ? { outputToolCalls: value.outputToolCalls } : {}),
92
108
  ...(nativeCompletenessState !== null ? { nativeCompletenessState } : {}),
93
109
  ...(toolProtocolReason ? { toolProtocolReason } : {}),
110
+ ...(value.toolErrorEarlyStop === true ? { toolErrorEarlyStop: true } : {}),
94
111
  ...(emptyResponseReason ? { emptyResponseReason } : {}),
95
112
  ...(nativeTextBytes !== null ? { nativeTextBytes } : {}),
96
113
  ...(nativeShareableTextBytes !== null ? { nativeShareableTextBytes } : {}),
@@ -22,6 +22,7 @@ import { NATIVE_RESPONSE_LIMITS as RESPONSE_LIMITS } from './native-response-lim
22
22
  import { observeNative } from './native-diagnostic.mjs';
23
23
  import { connectHttp2 } from './outbound-proxy.mjs';
24
24
  export const DEFAULT_HTTP2_PING_INTERVAL_MS = 15_000;
25
+ export const DEFAULT_HTTP2_PING_TIMEOUT_MS = 30_000;
25
26
  export const MIN_CONNECT_ATTEMPT_TIMEOUT_MS = 5000;
26
27
  // Node v22 defaults Happy Eyeballs per-family attempt timeout to 250ms, which aborts
27
28
  // IPv4 connects over high-RTT VPN tunnels when IPv6 returns immediate EHOSTUNREACH.
@@ -53,6 +54,7 @@ export function openDirectTurn(
53
54
  continuation,
54
55
  timeoutMs = 180000,
55
56
  pingIntervalMs = DEFAULT_HTTP2_PING_INTERVAL_MS,
57
+ pingTimeoutMs = DEFAULT_HTTP2_PING_TIMEOUT_MS,
56
58
  signal,
57
59
  allowNativeTools = false,
58
60
  emitHeaders = false,
@@ -116,7 +118,9 @@ export function openDirectTurn(
116
118
  request,
117
119
  timer,
118
120
  pingTimer = null,
121
+ pingAckTimer = null,
119
122
  pingInFlight = false,
123
+ lastInboundAt = Date.now(),
120
124
  closed = false,
121
125
  ended = false,
122
126
  error = null,
@@ -152,6 +156,10 @@ export function openDirectTurn(
152
156
  clearInterval(pingTimer);
153
157
  pingTimer = null;
154
158
  }
159
+ if (pingAckTimer) {
160
+ clearTimeout(pingAckTimer);
161
+ pingAckTimer = null;
162
+ }
155
163
  pingInFlight = false;
156
164
  };
157
165
  const stop = () => {
@@ -288,13 +296,60 @@ export function openDirectTurn(
288
296
  client.on("error", () => fail("NATIVE_CONNECTION_FAILED"));
289
297
  if (diagnostic) client.on('goaway', code => note('peer_goaway', { goawayCode: code }));
290
298
  if (Number.isInteger(pingIntervalMs) && pingIntervalMs > 0 && typeof client.ping === "function") {
299
+ let pingSeq = 0, activePingSeq = 0;
291
300
  pingTimer = setInterval(() => {
292
- if (closed || ended || client.closed || client.destroyed || pingInFlight) return;
301
+ if (closed || ended || client.closed || client.destroyed || client.connecting || pingInFlight) return;
302
+ const seq = ++pingSeq;
303
+ activePingSeq = seq;
304
+ const pingStartedAt = Date.now();
293
305
  pingInFlight = true;
306
+ let pingQueued = true;
307
+ let sent = false;
294
308
  try {
295
- client.ping(() => { pingInFlight = false; });
309
+ sent = client.ping((err) => {
310
+ if (!pingQueued || seq !== activePingSeq) return;
311
+ if (pingAckTimer) {
312
+ clearTimeout(pingAckTimer);
313
+ pingAckTimer = null;
314
+ }
315
+ pingInFlight = false;
316
+ if (closed || ended) return;
317
+ if (err) {
318
+ if (err.code === 'ERR_HTTP2_PING_CANCEL') return;
319
+ note('transport_ping_timeout');
320
+ fail('NATIVE_CONNECTION_FAILED');
321
+ return;
322
+ }
323
+ lastInboundAt = Date.now();
324
+ });
296
325
  } catch {
326
+ pingQueued = false;
327
+ if (activePingSeq === seq) activePingSeq = 0;
328
+ pingInFlight = false;
329
+ return;
330
+ }
331
+ if (sent === false) {
332
+ pingQueued = false;
333
+ if (activePingSeq === seq) activePingSeq = 0;
297
334
  pingInFlight = false;
335
+ return;
336
+ }
337
+ if (Number.isInteger(pingTimeoutMs) && pingTimeoutMs > 0 && !closed && !ended && pingInFlight && activePingSeq === seq) {
338
+ const armAckWatchdog = (delayMs) => {
339
+ pingAckTimer = setTimeout(() => {
340
+ pingAckTimer = null;
341
+ if (closed || ended || !pingInFlight || activePingSeq !== seq) return;
342
+ const idleSinceInbound = Date.now() - lastInboundAt;
343
+ if (lastInboundAt >= pingStartedAt && idleSinceInbound < pingTimeoutMs) {
344
+ armAckWatchdog(Math.max(1, pingTimeoutMs - idleSinceInbound));
345
+ return;
346
+ }
347
+ note('transport_ping_timeout');
348
+ fail('NATIVE_CONNECTION_FAILED');
349
+ }, delayMs);
350
+ pingAckTimer.unref();
351
+ };
352
+ armAckWatchdog(pingTimeoutMs);
298
353
  }
299
354
  }, pingIntervalMs);
300
355
  pingTimer.unref();
@@ -309,11 +364,12 @@ export function openDirectTurn(
309
364
  "user-agent": GATEWAY_USER_AGENT,
310
365
  });
311
366
  request.on("response", headers => {
367
+ lastInboundAt = Date.now();
312
368
  note('peer_headers', { httpStatus: Number(headers[':status']), grpcStatus: Number(headers['grpc-status']) });
313
369
  status(headers);
314
370
  if (emitHeaders && !closed && httpStatus === 200) push({ type: 'headers', httpStatus });
315
371
  });
316
- request.on("trailers", headers => { note('peer_trailers', { grpcStatus: Number(headers['grpc-status']) }); status(headers); });
372
+ request.on("trailers", headers => { lastInboundAt = Date.now(); note('peer_trailers', { grpcStatus: Number(headers['grpc-status']) }); status(headers); });
317
373
  request.on("error", () => {
318
374
  note('stream_error', { rstCode: request?.rstCode });
319
375
  if (!rejectPeerReset()) fail("NATIVE_STREAM_FAILED");
@@ -325,6 +381,7 @@ export function openDirectTurn(
325
381
  });
326
382
  request.on("data", (chunk) => {
327
383
  if (closed) return;
384
+ lastInboundAt = Date.now();
328
385
  note('peer_data', { bytes: chunk.length });
329
386
  try {
330
387
  received += chunk.length;
@@ -338,6 +395,7 @@ export function openDirectTurn(
338
395
  }
339
396
  });
340
397
  request.on("end", () => {
398
+ lastInboundAt = Date.now();
341
399
  note('stream_end', { rstCode: request?.rstCode });
342
400
  if (closed) return;
343
401
  // Node may emit readable 'end' for RST_STREAM(CANCEL). That is not a successful end.
@@ -103,12 +103,19 @@ export function decodeImageBytes(data, mimeType) {
103
103
  if (!width || !height || width > 32768 || height > 32768 || width * height > MAX_PIXELS) fail('IMAGE_DIMENSIONS_TOO_LARGE', 413);
104
104
  return { mimeType, data, width, height };
105
105
  }
106
- export function normalizeImageUrl(url, detail) {
106
+ export function normalizeImageUrl(url, detail, decodedCache) {
107
107
  if (detail !== undefined && detail !== 'auto') fail('UNSUPPORTED_IMAGE_DETAIL');
108
108
  if (typeof url === 'string' && /^https?:/i.test(url)) return parseRemoteImageUrl(url).href;
109
- return decodeImageDataUrl(url).url;
109
+ const cached = decodedCache?.get(url);
110
+ if (cached) return cached.url;
111
+ const decoded = decodeImageDataUrl(url);
112
+ if (decodedCache) {
113
+ decodedCache.set(url, decoded);
114
+ decodedCache.set(decoded.url, decoded);
115
+ }
116
+ return decoded.url;
110
117
  }
111
- export function collectImageInputs(messages, resolvedImages) {
118
+ export function collectImageInputs(messages, resolvedImages, decodedCache) {
112
119
  let total = 0;
113
120
  const images = [], transcript = messages.map(message => {
114
121
  if (!Array.isArray(message.content)) return message;
@@ -117,7 +124,7 @@ export function collectImageInputs(messages, resolvedImages) {
117
124
  if (message.role !== 'user' || part.type !== 'image_url') fail('UNSUPPORTED_IMAGE_ROLE');
118
125
  if (images.length >= MAX_IMAGES) fail('IMAGE_COUNT_EXCEEDED', 413);
119
126
  const url = part.image_url?.url;
120
- const decoded = resolvedImages ? resolvedImages[images.length] : /^https?:/i.test(url) ? { url: parseRemoteImageUrl(url).href } : decodeImageDataUrl(url);
127
+ const decoded = resolvedImages ? resolvedImages[images.length] : /^https?:/i.test(url) ? { url: parseRemoteImageUrl(url).href } : (decodedCache?.get(url) ?? decodeImageDataUrl(url));
121
128
  const { data, mimeType, width, height } = decoded;
122
129
  if ((total += (data?.length ?? 0)) > MAX_TOTAL_IMAGE_BYTES) fail('IMAGES_TOO_LARGE', 413);
123
130
  images.push(data ? { data, mimeType, width, height } : decoded);