pi-gemini-app 0.1.15 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import zlib from 'node:zlib';
1
2
  import { parseRemoteImageUrl } from './image-url.mjs';
2
3
  import { protocolError } from './tool-protocol.mjs';
3
4
 
@@ -9,15 +10,45 @@ export const MAX_TOTAL_IMAGE_URL_BYTES = Math.ceil(MAX_TOTAL_IMAGE_BYTES / 3) *
9
10
  const MAX_PIXELS = 40_000_000;
10
11
  const fail = (code, status = 400) => { throw protocolError(code, status); };
11
12
  const pngMagic = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
12
- const crcTable = Uint32Array.from({ length: 256 }, (_, value) => {
13
- for (let i = 0; i < 8; i++) value = value & 1 ? (value >>> 1) ^ 0xedb88320 : value >>> 1;
14
- return value >>> 0;
15
- });
16
- function crc32(bytes) {
13
+ let crcTable = null;
14
+ export function jsCrc32(bytes) {
15
+ if (!crcTable) {
16
+ crcTable = Uint32Array.from({ length: 256 }, (_, value) => {
17
+ for (let i = 0; i < 8; i++) value = value & 1 ? (value >>> 1) ^ 0xedb88320 : value >>> 1;
18
+ return value >>> 0;
19
+ });
20
+ }
17
21
  let value = 0xffffffff;
18
22
  for (const byte of bytes) value = crcTable[(value ^ byte) & 255] ^ (value >>> 8);
19
23
  return (value ^ 0xffffffff) >>> 0;
20
24
  }
25
+ // Node 22 added zlib.crc32() in 22.2.0 while package.json supports >=22.0.0;
26
+ // feature-detect once and keep the standard JS implementation as fallback.
27
+ export function createCrc32(zlibModule = zlib) {
28
+ return typeof zlibModule?.crc32 === 'function'
29
+ ? bytes => zlibModule.crc32(bytes) >>> 0
30
+ : jsCrc32;
31
+ }
32
+ const crc32 = createCrc32();
33
+ function base64Sextet(code) {
34
+ if (code >= 65 && code <= 90) return code - 65; // A-Z
35
+ if (code >= 97 && code <= 122) return code - 71; // a-z
36
+ if (code >= 48 && code <= 57) return code + 4; // 0-9
37
+ if (code === 43) return 62; // +
38
+ if (code === 47) return 63; // /
39
+ return -1;
40
+ }
41
+ export function hasCanonicalBase64Tail(b64) {
42
+ const len = b64.length;
43
+ if (!len || (len & 3)) return false;
44
+ if (b64.charCodeAt(len - 1) !== 61) return true;
45
+ if (b64.charCodeAt(len - 2) === 61) {
46
+ const sextet = base64Sextet(b64.charCodeAt(len - 3));
47
+ return sextet >= 0 && (sextet & 0x0f) === 0;
48
+ }
49
+ const sextet = base64Sextet(b64.charCodeAt(len - 2));
50
+ return sextet >= 0 && (sextet & 0x03) === 0;
51
+ }
21
52
  // Structural checks only: the gateway never decompresses or renders caller images.
22
53
  function dimensions(bytes, mimeType) {
23
54
  if (mimeType === 'image/png') {
@@ -85,16 +116,88 @@ function dimensions(bytes, mimeType) {
85
116
  }
86
117
  fail('UNSUPPORTED_IMAGE_FORMAT');
87
118
  }
119
+ const validatedImageCaches = new WeakMap();
120
+
121
+ function lookupValidatedCache(cacheHandle, url) {
122
+ if (typeof url !== 'string' || !url.startsWith('data:')) return null;
123
+ const store = cacheHandle && typeof cacheHandle === 'object' ? validatedImageCaches.get(cacheHandle) : undefined;
124
+ if (!store) return null;
125
+ const rec = store.get(url);
126
+ if (!rec) return null;
127
+ if (rec.url === url) return { mimeType: rec.mimeType, data: rec.data, width: rec.width, height: rec.height, url: rec.url };
128
+ const comma = rec.url.indexOf(',');
129
+ if (
130
+ comma > 0 &&
131
+ url.length === rec.url.length &&
132
+ url.indexOf(',') === comma &&
133
+ url.slice(0, comma).toLowerCase() === rec.url.slice(0, comma) &&
134
+ url.slice(comma) === rec.url.slice(comma)
135
+ ) {
136
+ return { mimeType: rec.mimeType, data: rec.data, width: rec.width, height: rec.height, url: rec.url };
137
+ }
138
+ return null;
139
+ }
140
+
141
+ /**
142
+ * Unforgeable, request-scoped in-process cache of validated image bytes.
143
+ * Validated Buffers stay private inside this module so callers cannot mutate
144
+ * bytes or metadata after validation. Never cross an HTTP trust boundary.
145
+ */
146
+ export function createValidatedImageCache() {
147
+ const store = new Map();
148
+ const handle = Object.freeze({
149
+ get size() { return store.size; },
150
+ decodeDataUrl(url) {
151
+ const existing = lookupValidatedCache(handle, url);
152
+ if (existing) {
153
+ return { mimeType: existing.mimeType, width: existing.width, height: existing.height, url: existing.url };
154
+ }
155
+ const decoded = decodeImageDataUrl(url);
156
+ const record = Object.freeze({
157
+ mimeType: decoded.mimeType,
158
+ data: decoded.data,
159
+ width: decoded.width,
160
+ height: decoded.height,
161
+ url: decoded.url,
162
+ });
163
+ store.set(url, record);
164
+ store.set(record.url, record);
165
+ return { mimeType: record.mimeType, width: record.width, height: record.height, url: record.url };
166
+ },
167
+ encodeBytes(data, mimeType) {
168
+ if (!Buffer.isBuffer(data) || !data.length) fail('INVALID_IMAGE_BYTES');
169
+ // Copy caller Buffer before validating so later caller mutations cannot alter stored bytes.
170
+ const ownBytes = Buffer.from(data);
171
+ const decoded = decodeImageBytes(ownBytes, mimeType);
172
+ const url = `data:${decoded.mimeType};base64,${ownBytes.toString('base64')}`;
173
+ if (Buffer.byteLength(url) > MAX_IMAGE_URL_BYTES) fail('IMAGE_TOO_LARGE', 413);
174
+ const record = Object.freeze({
175
+ mimeType: decoded.mimeType,
176
+ data: ownBytes,
177
+ width: decoded.width,
178
+ height: decoded.height,
179
+ url,
180
+ });
181
+ store.set(url, record);
182
+ return { mimeType: record.mimeType, width: record.width, height: record.height, url };
183
+ },
184
+ });
185
+ validatedImageCaches.set(handle, store);
186
+ return handle;
187
+ }
188
+
88
189
  /** Inline decoder only; remote downloads separately reuse decodeImageBytes. */
89
190
  export function decodeImageDataUrl(url) {
90
191
  if (typeof url !== 'string') fail('INVALID_IMAGE_URL');
91
192
  if (!url.startsWith('data:')) fail('UNSUPPORTED_IMAGE_URL');
92
193
  if (Buffer.byteLength(url) > MAX_IMAGE_URL_BYTES) fail('IMAGE_TOO_LARGE', 413);
93
194
  const match = /^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/]*={0,2})$/i.exec(url);
94
- if (!match || !match[2].length || match[2].length % 4) fail('INVALID_IMAGE_DATA_URL');
95
- const mimeType = match[1].toLowerCase(), data = Buffer.from(match[2], 'base64');
96
- if (!data.length || data.toString('base64') !== match[2]) fail('INVALID_IMAGE_DATA_URL');
97
- return { ...decodeImageBytes(data, mimeType), url: `data:${mimeType};base64,${match[2]}` };
195
+ if (!match || !hasCanonicalBase64Tail(match[2])) fail('INVALID_IMAGE_DATA_URL');
196
+ const b64 = match[2];
197
+ const pad = b64.charCodeAt(b64.length - 1) === 61 ? (b64.charCodeAt(b64.length - 2) === 61 ? 2 : 1) : 0;
198
+ const mimeType = match[1].toLowerCase(), data = Buffer.from(b64, 'base64');
199
+ if (!data.length || data.length !== (b64.length / 4) * 3 - pad) fail('INVALID_IMAGE_DATA_URL');
200
+ return { ...decodeImageBytes(data, mimeType), url: `data:${mimeType};base64,${b64}` };
98
201
  }
99
202
  export function decodeImageBytes(data, mimeType) {
100
203
  if (!Buffer.isBuffer(data) || !data.length) fail('INVALID_IMAGE_BYTES');
@@ -106,25 +209,41 @@ export function decodeImageBytes(data, mimeType) {
106
209
  export function normalizeImageUrl(url, detail, decodedCache) {
107
210
  if (detail !== undefined && detail !== 'auto') fail('UNSUPPORTED_IMAGE_DETAIL');
108
211
  if (typeof url === 'string' && /^https?:/i.test(url)) return parseRemoteImageUrl(url).href;
109
- const cached = decodedCache?.get(url);
212
+ const cached = lookupValidatedCache(decodedCache, url);
110
213
  if (cached) return cached.url;
214
+ const store = decodedCache && typeof decodedCache === 'object' ? validatedImageCaches.get(decodedCache) : undefined;
111
215
  const decoded = decodeImageDataUrl(url);
112
- if (decodedCache) {
113
- decodedCache.set(url, decoded);
114
- decodedCache.set(decoded.url, decoded);
216
+ if (store) {
217
+ const record = Object.freeze({
218
+ mimeType: decoded.mimeType,
219
+ data: decoded.data,
220
+ width: decoded.width,
221
+ height: decoded.height,
222
+ url: decoded.url,
223
+ });
224
+ store.set(url, record);
225
+ store.set(record.url, record);
115
226
  }
116
227
  return decoded.url;
117
228
  }
118
- export function collectImageInputs(messages, resolvedImages, decodedCache) {
229
+ export function resolveMaxImages(maxImages) {
230
+ if (maxImages === undefined || maxImages === null || maxImages === 0) return MAX_IMAGES;
231
+ if (!Number.isSafeInteger(maxImages) || maxImages < 1 || maxImages > MAX_IMAGES) {
232
+ throw new RangeError(`Invalid maxImages: expected integer 0..${MAX_IMAGES}`);
233
+ }
234
+ return maxImages;
235
+ }
236
+ export function collectImageInputs(messages, resolvedImages, decodedCache, maxImages = MAX_IMAGES) {
237
+ const limit = resolveMaxImages(maxImages);
119
238
  let total = 0;
120
239
  const images = [], transcript = messages.map(message => {
121
240
  if (!Array.isArray(message.content)) return message;
122
241
  const content = message.content.map(part => {
123
242
  if (part.type === 'text') return part.text;
124
243
  if (message.role !== 'user' || part.type !== 'image_url') fail('UNSUPPORTED_IMAGE_ROLE');
125
- if (images.length >= MAX_IMAGES) fail('IMAGE_COUNT_EXCEEDED', 413);
244
+ if (images.length >= limit) fail('IMAGE_COUNT_EXCEEDED', 413);
126
245
  const url = part.image_url?.url;
127
- const decoded = resolvedImages ? resolvedImages[images.length] : /^https?:/i.test(url) ? { url: parseRemoteImageUrl(url).href } : (decodedCache?.get(url) ?? decodeImageDataUrl(url));
246
+ const decoded = resolvedImages ? resolvedImages[images.length] : /^https?:/i.test(url) ? { url: parseRemoteImageUrl(url).href } : (lookupValidatedCache(decodedCache, url) ?? decodeImageDataUrl(url));
128
247
  const { data, mimeType, width, height } = decoded;
129
248
  if ((total += (data?.length ?? 0)) > MAX_TOTAL_IMAGE_BYTES) fail('IMAGES_TOO_LARGE', 413);
130
249
  images.push(data ? { data, mimeType, width, height } : decoded);
@@ -4,9 +4,10 @@
4
4
  * This does not change the legacy provider, shared codecs or research transport.
5
5
  */
6
6
  import crypto from 'node:crypto';
7
+ import { performance } from 'node:perf_hooks';
7
8
  import { parse } from '../native-wire/protobuf.mjs';
8
- import { decodeClientGenerateResponse } from '../native-wire/robin-current.mjs';
9
- import { ProtocolError, protocolError, compileToolPolicy, createToolCallSplitter, validateToolCompletion } from './tool-protocol.mjs';
9
+ import { decodeClientGenerateResponseFields } from '../native-wire/robin-current.mjs';
10
+ import { ProtocolError, protocolError, compileToolPolicy, isCompiledToolPolicy, createToolCallSplitter, validateToolCompletion } from './tool-protocol.mjs';
10
11
  import { MODEL_ALIASES, MODEL_MODES, MODEL_SPECS, NATIVE_MODELS, PROMPT_MAX_BYTES, CANONICAL_BUILT, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
11
12
  import { RESPONSE_TOOL_IDENTITIES } from './responses-tool-namespaces.mjs';
12
13
  import { safeNativeEvidence } from './gateway/native-evidence.mjs';
@@ -38,6 +39,7 @@ const failWithEvidence = (code, evidence) => {
38
39
  const utf8 = new TextDecoder('utf-8', { fatal: true });
39
40
  const HYDROGEN_ATTRIBUTION = /\bhydrogen\b/i;
40
41
  const NEON_ATTRIBUTION = /\bneon\b/i;
42
+ const CARBON_ATTRIBUTION = /\bcarbon\b/i;
41
43
  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
44
  const CLOSING_FENCE_LINE_RE = /^ {0,3}`{3,}/;
43
45
  const PENDING_TOOL_OPEN_RE = /^ {0,3}`{3,}[ \t]*t(?:o(?:o(?:l(?:_(?:c(?:a(?:l(?:l)?)?)?)?)?)?)?)?[ \t]*$/;
@@ -113,7 +115,7 @@ function frameInfo(bytes) {
113
115
  if (attribution.wire !== 2 || attribution.payload.length > 4096) fail('INVALID_NATIVE_RESPONSE');
114
116
  try { utf8.decode(attribution.payload); } catch { fail('INVALID_NATIVE_RESPONSE'); }
115
117
  }
116
- const info = decodeClientGenerateResponse(client.payload);
118
+ const info = decodeClientGenerateResponseFields(fields, { includeModels: false });
117
119
  if (info.hasToolOperations) fail('UNSUPPORTED_NATIVE_TOOL_EVENT');
118
120
  for (const n of [9, 11]) {
119
121
  const flag = one(fields, n);
@@ -122,8 +124,10 @@ function frameInfo(bytes) {
122
124
  info.text = null;
123
125
  info.responseId = null;
124
126
  const model = one(fields, 1);
127
+ let modelFields = null;
125
128
  if (model) {
126
- const modelFields = parse(model.payload);
129
+ if (model.wire !== 2) fail('INVALID_NATIVE_RESPONSE');
130
+ modelFields = parse(model.payload);
127
131
  const responseId = one(modelFields, 1);
128
132
  if (responseId) {
129
133
  if (responseId.wire !== 2 || responseId.payload.length > 4096) fail('INVALID_NATIVE_RESPONSE');
@@ -131,12 +135,17 @@ function frameInfo(bytes) {
131
135
  }
132
136
  const display = one(modelFields, 2);
133
137
  if (display) {
138
+ if (display.wire !== 2) fail('INVALID_NATIVE_RESPONSE');
134
139
  const text = one(parse(display.payload), 1);
135
- if (text) info.text = utf8.decode(text.payload);
140
+ if (text) {
141
+ if (text.wire !== 2) fail('INVALID_NATIVE_RESPONSE');
142
+ info.text = utf8.decode(text.payload);
143
+ }
136
144
  }
145
+ info.models = [{ responseId: info.responseId, text: info.text }];
137
146
  }
138
- info.outputShape = inspectNativeOutput(fields);
139
- info.quotaObservation = decodePassiveQuota(client.payload);
147
+ info.outputShape = inspectNativeOutput(fields, modelFields);
148
+ info.quotaObservation = decodePassiveQuota(client.payload, undefined, fields);
140
149
  return info;
141
150
  }
142
151
  const TRANSPORT_ERRORS = new Set(['NATIVE_CONNECTION_FAILED', 'NATIVE_STREAM_FAILED', 'NATIVE_STREAM_RESET', 'NATIVE_STREAM_CLOSED_EARLY', 'NATIVE_HTTP_REJECTED', 'NATIVE_INVALID_STATUS', 'NATIVE_RECEIVE_LIMIT', 'NATIVE_FRAME_REJECTED', 'NATIVE_READER_BUSY']);
@@ -289,6 +298,7 @@ export class NativeDirectProvider {
289
298
  getAccessToken: () => this.authManager.getValidAccessToken(accountId),
290
299
  openTurn: this.openTurn, query: messages[0].content,
291
300
  allowNativeTools: true, timeoutMs: Math.min(timeoutMs, 180000), signal: context.signal,
301
+ ...(context.timing ? { timing: context.timing } : {}),
292
302
  });
293
303
  if (!report.ok) {
294
304
  const status = ['NATIVE_RATE_LIMITED','NATIVE_QUOTA_EXHAUSTED'].includes(report.errorCode) ? 429
@@ -359,7 +369,10 @@ export class NativeDirectProvider {
359
369
  context.preNormalized === true &&
360
370
  canonicalChatBody?.[CANONICAL_BUILT]?.allowAutoModel === this.allowAutoModel
361
371
  ? canonicalChatBody
362
- : normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
372
+ : normalizeChatRequest(canonicalChatBody, {
373
+ allowAutoModel: this.allowAutoModel,
374
+ ...(context.imageCache ? { _imageCache: context.imageCache } : {}),
375
+ });
363
376
  if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
364
377
  const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode, context.recoveryReason);
365
378
  const appendRecovery = promptMessages => {
@@ -373,8 +386,9 @@ export class NativeDirectProvider {
373
386
  return next;
374
387
  };
375
388
  if (this.allowTextSnapshotReplacement && body.tools.length) fail('NATIVE_TEXT_SNAPSHOT_TOOLS_FORBIDDEN', 400);
376
- const policy = compileToolPolicy(body.tools, body.tool_choice);
377
- let { messages, images } = body[CANONICAL_BUILT] ?? buildCanonicalPrompt(body);
389
+ const built = body[CANONICAL_BUILT];
390
+ const policy = isCompiledToolPolicy(built?.policy) ? built.policy : compileToolPolicy(body.tools, body.tool_choice);
391
+ let { messages, images } = built ?? buildCanonicalPrompt(body, undefined, undefined, policy);
378
392
  messages = appendRecovery(messages);
379
393
  const isAutoModel = this.allowAutoModel && body.model === 'gemini-auto';
380
394
  const modeCategory = isAutoModel ? null : MODEL_MODES[body.model];
@@ -399,21 +413,23 @@ export class NativeDirectProvider {
399
413
  const bounded = promise => Promise.race([promise, deadline]);
400
414
  const requiresHydrogen = body.model === 'gemini-hydrogen';
401
415
  const requiresNeon = body.model === 'gemini-neon';
416
+ const requiresCarbon = body.model === 'gemini-carbon';
402
417
  let rawText = '', frames = 0, received = 0, observedMode = null, observedThinking = null;
403
418
  let modelComplete = false, modelCompleteAt = null, lastTextProgressAt = null, lastGenerationProgressAt = null, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
404
419
  let thoughtHighWaterBytes = 0, allowThoughtRebase = false;
405
420
  let observedFallback = null, downgradeReason = null, observedAttribution = null;
406
- const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? ''));
421
+ const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? '')) && (!requiresCarbon || CARBON_ATTRIBUTION.test(value ?? ''));
407
422
  const attributionVerified = () => attributionMatches(observedAttribution);
408
423
  let snapshotId = null, revisionCount = 0, quotaObservation = null, quotaFrames = 0;
409
424
  let emptyResponseReason = null, outputObserved = false, responseLimitReason = null, outputFailureReason = null;
425
+ let firstVerifiedTextMarked = false;
410
426
  const outputShape = { nativeShareableTextBytes: 0, nativeThoughtsPresent: false, nativeThoughtBytes: 0, nativeStructuredOutputPresent: false, nativeRefusalPresent: false };
411
427
  const incremental = context.incrementalOutput === true && !body.response_format;
412
428
  const identity = { id: 'chatcmpl-' + crypto.randomBytes(16).toString('hex'), created: Math.floor(Date.now() / 1000), model: body.model,
413
429
  [RESPONSE_TOOL_IDENTITIES]: body[RESPONSE_TOOL_IDENTITIES],
414
430
  requestedThinkingLevel: body.thinking_level, ignoredTokenParameters: ['max_tokens', 'max_completion_tokens'].filter(key => body[key] !== undefined),
415
431
  ...((body.reasoning_effort ?? body.reasoning?.effort) === undefined ? {} : { requestedReasoningEffort: body.reasoning_effort ?? body.reasoning?.effort }) };
416
- let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, liveToolError = null, liveToolErrorTailStart = 0, liveToolErrorDeadline = null, validatedIdleOutput = null, readExit = 'none', sinkFailed = false;
432
+ let liveSplitter = incremental ? createToolCallSplitter({ policy }) : null, liveItems = [], liveContent = '', livePreCallContent = '', liveCalls = [], publishedContent = '', publishedCalls = 0, liveSyncedLength = 0, liveToolError = null, liveToolErrorTailStart = 0, liveToolErrorDeadline = null, validatedIdleOutput = null, readExit = 'none', sinkFailed = false;
417
433
  const deliver = async event => {
418
434
  try { await onDelta(event); }
419
435
  catch (error) { sinkFailed = true; throw error; }
@@ -443,14 +459,10 @@ export class NativeDirectProvider {
443
459
  // bodies. With deferToolCalls, calls (and any text after the first call) are held
444
460
  // until the turn is final so callers never receive draft calls that upstream rewrites.
445
461
  const deferCalls = incremental && context.deferToolCalls === true;
446
- const visibleText = (items, content, splitter, final) => {
462
+ const visibleText = (hasCalls, preCallContent, content, splitter, final) => {
447
463
  if (!deferCalls || final) return content + splitter.preview();
448
- let text = '';
449
- for (const item of items) {
450
- if (item.type === 'call') return text;
451
- text += item.text;
452
- }
453
- return text + splitter.preview();
464
+ if (hasCalls) return preCallContent;
465
+ return preCallContent + splitter.preview();
454
466
  };
455
467
  // Same-id revision after output was committed: accept it only if replaying the new
456
468
  // snapshot reproduces everything already delivered (visible text prefix + identical calls).
@@ -482,16 +494,19 @@ export class NativeDirectProvider {
482
494
  splitter = replay;
483
495
  }
484
496
  let content = '';
497
+ let preCallContent = '';
485
498
  const calls = [];
486
499
  for (const item of items) {
487
- if (item.type === 'content') content += item.text;
488
- else calls.push(item.call);
500
+ if (item.type === 'content') {
501
+ content += item.text;
502
+ if (calls.length === 0) preCallContent += item.text;
503
+ } else calls.push(item.call);
489
504
  }
490
505
  if (calls.length < publishedCalls) return false;
491
506
  for (let i = 0; i < publishedCalls; i++) {
492
507
  if (calls[i].function.name !== liveCalls[i].function.name || calls[i].function.arguments !== liveCalls[i].function.arguments) return false;
493
508
  }
494
- if (!visibleText(items, content, splitter, false).startsWith(publishedContent)) return false;
509
+ if (!visibleText(calls.length > 0, preCallContent, content, splitter, false).startsWith(publishedContent)) return false;
495
510
  // Preserve IDs of calls that were already delivered.
496
511
  let callIndex = 0;
497
512
  for (const item of items) {
@@ -504,6 +519,7 @@ export class NativeDirectProvider {
504
519
  liveSplitter = splitter;
505
520
  liveItems = items;
506
521
  liveContent = content;
522
+ livePreCallContent = preCallContent;
507
523
  liveCalls = calls;
508
524
  liveSyncedLength = nextText.length;
509
525
  if (rebaseToolError) {
@@ -518,8 +534,16 @@ export class NativeDirectProvider {
518
534
  return true;
519
535
  };
520
536
  const publish = async (items, { final = false } = {}) => {
521
- for (const item of items) { liveItems.push(item); if (item.type === 'content') liveContent += item.text; else liveCalls.push(item.call); }
522
- const text = visibleText(liveItems, liveContent, liveSplitter, final);
537
+ for (const item of items) {
538
+ liveItems.push(item);
539
+ if (item.type === 'content') {
540
+ liveContent += item.text;
541
+ if (liveCalls.length === 0) livePreCallContent += item.text;
542
+ } else {
543
+ liveCalls.push(item.call);
544
+ }
545
+ }
546
+ const text = visibleText(liveCalls.length > 0, livePreCallContent, liveContent, liveSplitter, final);
523
547
  if (!text.startsWith(publishedContent)) {
524
548
  const committed = committedOutput();
525
549
  if (snapshotId === null || committed.publishedBytes || committed.toolCallCount) failWithEvidence('NON_MONOTONIC_NATIVE_RESPONSE', {
@@ -544,8 +568,13 @@ export class NativeDirectProvider {
544
568
  try {
545
569
  if (images.some(image => image.url)) {
546
570
  phase = 'upload';
547
- images = await bounded(this.downloadImages(images, { signal: controller.signal, timeoutMs: Math.min(timeoutMs, 30000) }));
548
- ({ messages, images } = buildCanonicalPrompt(body, images));
571
+ const downloadStart = performance.now();
572
+ try {
573
+ images = await bounded(this.downloadImages(images, { signal: controller.signal, timeoutMs: Math.min(timeoutMs, 30000) }));
574
+ } finally {
575
+ observeNative(context.timing, 'imageDownload', performance.now() - downloadStart);
576
+ }
577
+ ({ messages, images } = buildCanonicalPrompt(body, images, undefined, policy));
549
578
  messages = appendRecovery(messages);
550
579
  }
551
580
  phase = 'auth';
@@ -554,18 +583,29 @@ export class NativeDirectProvider {
554
583
  catch (error) { if (error instanceof ProtocolError || ['NATIVE_PERMISSION_OR_AUTH','NATIVE_CREDENTIAL_REQUIRED','OAUTH_REFRESH_FAILED','ACCOUNT_LOGIN_REQUIRED'].includes(error?.code)) throw safeFailure(error); fail('NATIVE_AUTH_FAILED', 503); }
555
584
  if (controller.signal.aborted) await deadline;
556
585
  phase = 'upload';
557
- let { attachments, usedCachedKeys } = await bounded(this.#resolveImageAttachments(accountId, token, images, { signal: controller.signal, timeoutMs }));
586
+ let attachments = [], usedCachedKeys = [];
587
+ if (images.length) {
588
+ const uploadStart = performance.now();
589
+ try {
590
+ ({ attachments, usedCachedKeys } = await bounded(this.#resolveImageAttachments(accountId, token, images, { signal: controller.signal, timeoutMs })));
591
+ } finally {
592
+ observeNative(context.timing, 'imageUpload', performance.now() - uploadStart);
593
+ }
594
+ }
558
595
  if (controller.signal.aborted) await deadline;
559
596
  // The product injects its independent transport; historical research ledgers are untouched.
560
597
  const STALE_BLOB_CODES = new Set(['NATIVE_HTTP_REJECTED', 'NATIVE_INVALID_STATUS', 'NATIVE_PRECONDITION_REQUIRED', 'NATIVE_TURN_FAILED']);
561
598
  for (let blobAttempt = 0; ; blobAttempt++) {
562
599
  phase = 'open';
600
+ let markOpenHeaders = null;
601
+ try { markOpenHeaders = context.timing?.openStart?.() ?? null; } catch {}
563
602
  turn = this.openTurn(token, { messages, images: attachments, temporaryChat: true,
564
603
  modeCategory: isAutoModel ? null : modeCategory,
565
604
  thinkingLevel: isAutoModel ? null : body.thinking_level,
566
605
  ...(isAutoModel ? { smartModelSelection: true } : {}),
567
606
  timeoutMs, signal: controller.signal,
568
607
  emitHeaders: incremental,
608
+ ...(typeof markOpenHeaders === 'function' ? { onHeaders: () => { try { markOpenHeaders(); } catch {} } } : {}),
569
609
  ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
570
610
  iterator = turn.events[Symbol.asyncIterator]();
571
611
  try {
@@ -707,7 +747,11 @@ export class NativeDirectProvider {
707
747
  }
708
748
  if (item.done) break;
709
749
  const event = item.value;
710
- if (incremental && event.type === 'headers') { await deliver({ start: true, response: identity }); continue; }
750
+ if (incremental && event.type === 'headers') {
751
+ observeNative(context.timing, 'headers');
752
+ await deliver({ start: true, response: identity });
753
+ continue;
754
+ }
711
755
  if (event.type === 'frame') {
712
756
  frames++;
713
757
  received += event.bytes?.length ?? RESPONSE_LIMITS.wireBytes + 1;
@@ -778,7 +822,7 @@ export class NativeDirectProvider {
778
822
  rebased = true;
779
823
  } else if (incremental) {
780
824
  if (liveSyncedLength > 0) await deliver({ reset: true, sameResponseIdentity: true, response: identity });
781
- liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0; liveToolError = null; liveToolErrorTailStart = 0; liveToolErrorDeadline = null;
825
+ liveSplitter = createToolCallSplitter({ policy }); liveItems = []; liveContent = ''; livePreCallContent = ''; liveCalls = []; publishedContent = ''; publishedCalls = 0; liveSyncedLength = 0; liveToolError = null; liveToolErrorTailStart = 0; liveToolErrorDeadline = null;
782
826
  }
783
827
  }
784
828
  if (id) snapshotId = id;
@@ -827,6 +871,10 @@ export class NativeDirectProvider {
827
871
  allowThoughtRebase = false;
828
872
  }
829
873
  }
874
+ if (!firstVerifiedTextMarked && !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified() && rawText.trim().length > 0) {
875
+ firstVerifiedTextMarked = true;
876
+ observeNative(context.timing, 'firstVerifiedText');
877
+ }
830
878
  if (incremental && !liveToolError && modeMatches(observedMode) && attributionVerified() && (rebased || liveSyncedLength < rawText.length)) {
831
879
  if (rebased) {
832
880
  await publish([]);
@@ -924,7 +972,13 @@ export class NativeDirectProvider {
924
972
  try { turn?.cancel(); } catch {}
925
973
  turn = null; iterator = null; ended = false; grpc = null; httpStatus = null;
926
974
  phase = 'upload';
927
- ({ attachments, usedCachedKeys } = await bounded(this.#resolveImageAttachments(accountId, token, images, { signal: controller.signal, timeoutMs, bypassCache: true })));
975
+ observeNative(context.timing, 'blobRetry');
976
+ const retryUploadStart = performance.now();
977
+ try {
978
+ ({ attachments, usedCachedKeys } = await bounded(this.#resolveImageAttachments(accountId, token, images, { signal: controller.signal, timeoutMs, bypassCache: true })));
979
+ } finally {
980
+ observeNative(context.timing, 'imageUpload', performance.now() - retryUploadStart);
981
+ }
928
982
  if (controller.signal.aborted) await deadline;
929
983
  }
930
984
  }