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.
package/README.md CHANGED
@@ -71,17 +71,18 @@ Optional environment overrides if using your own OAuth desktop client:
71
71
  | Model ID | Display Name | Context Window | Max Output | Capabilities |
72
72
  | :--- | :--- | ---: | ---: | :--- |
73
73
  | `gemini-neon` | Gemini Neon | 512,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`); `gemini-argon` temporarily aliases here |
74
+ | `gemini-carbon` | Gemini Carbon | 512,000 | 16,384 | Gemini 4 Carbon, Google AI Ultra accounts only; text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`); the 512,000 window is the same advisory value as Neon and was not measured with a needle test for Carbon |
74
75
  | `gemini-hydrogen` | Gemini Hydrogen | 512,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
75
76
  | `gemini-flash-lite` | Gemini Flash Lite | 128,000 | 8,192 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
76
77
  | `gemini-auto` | Gemini Auto | 128,000 | 8,192 | Smart Model Selection for Free & paid Google accounts (text, static images, tools) |
77
78
 
78
- > **Subscription Tier Detection**: `/login gemini-app` automatically detects your account's Google AI subscription tier via `GetUsageInfo`. **Free** accounts automatically filter available models to `gemini-auto` (avoiding paid-mode precondition rejections), while **AI Plus**, **AI Pro**, and **AI Ultra** accounts expose all models. Run `/gemini-quota` at any time to check both your detected tier and rolling usage windows.
79
+ > **Subscription Tier Detection**: `/login gemini-app` automatically detects your account's Google AI subscription tier via `GetUserStatus`. **Free** accounts automatically filter available models to `gemini-auto` (avoiding paid-mode precondition rejections), while **AI Plus** and **AI Pro** accounts expose all models except `gemini-carbon`, and **AI Ultra** accounts expose all models. Run `/gemini-quota` at any time to check both your detected tier and rolling usage windows.
79
80
  >
80
81
  > **Quota Tip**: On `thinking=2` coding and tool-call loops, `gemini-neon` uses only `~1.5x–2x` the rolling-window quota of `gemini-hydrogen` (and `~4x–5x` on `thinking=0` generation), so you can daily-drive `gemini-neon` comfortably or switch to `gemini-hydrogen` when you want `~1.7x–2.6x` faster responses and extra quota headroom.
81
82
  >
82
83
  > **Usage Accounting**: Token counters reported in Pi are local character-based estimates over message text (`~3.5` chars/token, excluding image payloads and tool schemas) rather than official Google token counts.
83
84
  >
84
- > **Auto-Compaction**: The configured `contextWindow` (`512,000` for Neon/Hydrogen; `128,000` for Flash Lite/Auto) works automatically with Pi's proactive compaction (`contextWindow - reserveTokens`) and `413` context-overflow recovery compaction (or manual `/compact`).
85
+ > **Auto-Compaction**: The configured `contextWindow` (`512,000` for Neon/Carbon/Hydrogen; `128,000` for Flash Lite/Auto) works automatically with Pi's proactive compaction (`contextWindow - reserveTokens`) and `413` context-overflow recovery compaction (or manual `/compact`).
85
86
 
86
87
  ## Commands
87
88
 
@@ -4,7 +4,7 @@ import { MODEL_SPECS } from '../../src/openai-contract.mjs';
4
4
  import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
5
5
  import { fetchGoogleSubscription as defaultFetchGoogleSubscription } from '../../src/gateway/subscription-transport.mjs';
6
6
  import { decodeUsageInfo as defaultDecodeUsageInfo } from '../../src/gateway/quota.mjs';
7
- import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
7
+ import { decodeSubscription as defaultDecodeSubscription, isCarbonExcludedTier } from '../../src/gateway/subscription.mjs';
8
8
 
9
9
  const BASE_URL = 'https://robinfrontend-pa.googleapis.com';
10
10
  const PROVIDER_ID = 'gemini-app';
@@ -24,6 +24,9 @@ export function filterGeminiModels(models, credential) {
24
24
  if (tier === 'free') {
25
25
  return models.filter((m) => m.provider !== PROVIDER_ID || m.id === 'gemini-auto');
26
26
  }
27
+ if (isCarbonExcludedTier(tier)) {
28
+ return models.filter((m) => m.provider !== PROVIDER_ID || m.id !== 'gemini-carbon');
29
+ }
27
30
  return models;
28
31
  }
29
32
 
@@ -328,7 +328,8 @@ export function createGeminiStreamHandler({
328
328
 
329
329
  let body;
330
330
  let codec;
331
- ({ payload: body, codec } = await buildChatPayload(model, context, options, {
331
+ let imageCache;
332
+ ({ payload: body, codec, imageCache } = await buildChatPayload(model, context, options, {
332
333
  getCurrentSystemPrompt,
333
334
  getCurrentTools,
334
335
  toToolDeclaration,
@@ -444,6 +445,7 @@ export function createGeminiStreamHandler({
444
445
  recoveryCode,
445
446
  recoveryReason,
446
447
  getOutputCommitState,
448
+ ...(imageCache?.size ? { imageCache } : {}),
447
449
  });
448
450
  if (turnResult?.thinkingLevel !== undefined && turnResult.thinkingLevel !== null) {
449
451
  observedThinking = turnResult.thinkingLevel;
@@ -1,6 +1,6 @@
1
1
  import crypto from 'node:crypto';
2
2
  import {
3
- decodeImageDataUrl,
3
+ createValidatedImageCache,
4
4
  MAX_IMAGES,
5
5
  MAX_IMAGE_BYTES,
6
6
  MAX_TOTAL_IMAGE_BYTES,
@@ -151,6 +151,7 @@ export function resolveThinkingLevel(options = {}, { simple = false } = {}) {
151
151
  function planImageBudget(messages) {
152
152
  const accepted = new Map();
153
153
  const degraded = new Map();
154
+ const decodedImages = createValidatedImageCache();
154
155
  let count = 0;
155
156
  let totalBytes = 0;
156
157
 
@@ -189,19 +190,20 @@ function planImageBudget(messages) {
189
190
  degraded.set(key, `[Image omitted: ${mimeType} exceeded ${Math.round(MAX_TOTAL_IMAGE_BYTES / (1024 * 1024))}MB total image budget]`);
190
191
  continue;
191
192
  }
193
+ let decoded;
192
194
  try {
193
- decodeImageDataUrl(dataUrl);
195
+ decoded = decodedImages.decodeDataUrl(dataUrl);
194
196
  } catch (err) {
195
197
  degraded.set(key, `[Image omitted: invalid ${mimeType} (${err?.code || 'INVALID_IMAGE'})]`);
196
198
  continue;
197
199
  }
198
200
  count++;
199
201
  totalBytes += byteLength;
200
- accepted.set(key, dataUrl);
202
+ accepted.set(key, decoded.url);
201
203
  }
202
204
  }
203
205
 
204
- return { accepted, degraded };
206
+ return { accepted, degraded, decodedImages };
205
207
  }
206
208
 
207
209
  function serializeToolArguments(block) {
@@ -355,7 +357,7 @@ export async function buildChatPayload(
355
357
  };
356
358
  });
357
359
 
358
- const { accepted: acceptedImages, degraded: degradedImages } = planImageBudget(rawMessages);
360
+ const { accepted: acceptedImages, degraded: degradedImages, decodedImages } = planImageBudget(rawMessages);
359
361
  const messages = [];
360
362
 
361
363
  const systemPrompt = sanitizeText(getCurrentSystemPrompt(rawMessages));
@@ -563,5 +565,5 @@ export async function buildChatPayload(
563
565
  }
564
566
  }
565
567
 
566
- return { payload, codec };
568
+ return { payload, codec, imageCache: decodedImages };
567
569
  }
@@ -226,12 +226,13 @@ export function buildConsumerToolInitial({ userText, images = [], systemText, to
226
226
  const omitThinking = smartModelSelection && thinkingLevel === null;
227
227
  if (!omitThinking && (!Number.isSafeInteger(thinkingLevel) || thinkingLevel < 0 || thinkingLevel > 4)) rejectTool('INVALID_THINKING_LEVEL');
228
228
  if (typeof temporaryChat !== 'boolean') rejectTool('INVALID_TEMPORARY_CHAT');
229
- const base = buildClientGenerate({ userText, images, systemText, identifiers, clientMetadata: metadata, temporaryChat, smartModelSelection });
229
+ const disableNativeTools = !(registry.size || allowNativeTools);
230
+ const base = buildClientGenerate({ userText, images, systemText, identifiers, clientMetadata: metadata, temporaryChat, smartModelSelection, disableNativeTools });
230
231
  const desktopInfo = cat(...[...registry.values()].map(tool => m(2, tool.declaration)), ...(ownedDeviceId===undefined?[]:[s(6,ownedDeviceId)]), ...(clientToolsCapability ? [m(7, unsignedVarint(CLIENT_TOOLS_CAPABILITY))] : []));
231
232
  const omitMode = smartModelSelection && (modeCategory === undefined || modeCategory === null);
232
233
  const requestedMode = omitMode ? null : (modeCategory === undefined ? ARGON_MODE_CATEGORY : modeCategory);
233
234
  if (!omitMode && (!Number.isSafeInteger(requestedMode) || requestedMode < 0 || requestedMode > 255)) rejectTool('INVALID_MODE_CATEGORY');
234
- const template = cat(...parse(base).map(field => field.number === 15 ? v(15, registry.size || allowNativeTools ? 0 : 1) : field.raw), ...(omitMode ? [] : [v(47, requestedMode)]), ...(omitThinking ? [] : [v(48, thinkingLevel)]), ...(agentChat ? [v(49, 1)] : []), ...(registry.size ? [m(51, cat(...(ownedDeviceId===undefined?[]:[s(1,ownedDeviceId)]),m(3, desktopInfo), ...(localSession ? [v(5, 1)] : [])))] : []));
235
+ const template = cat(base, ...(omitMode ? [] : [v(47, requestedMode)]), ...(omitThinking ? [] : [v(48, thinkingLevel)]), ...(agentChat ? [v(49, 1)] : []), ...(registry.size ? [m(51, cat(...(ownedDeviceId===undefined?[]:[s(1,ownedDeviceId)]),m(3, desktopInfo), ...(localSession ? [v(5, 1)] : [])))] : []));
235
236
  if (continuation !== undefined && !Buffer.isBuffer(continuation)) rejectTool('INVALID_OWN_CONTINUATION');
236
237
  // Proven empty InitialRequest.ext1013 marker; NOT an outer update carrier or declaration list.
237
238
  const initial = cat(m(1, buildRequestMetadata(metadata)), ...(continuation === undefined ? [] : [m(6, continuation)]), m(1001, m(1, template)), m(1004, Buffer.alloc(0)), ...(registry.size && operationFeature ? [m(1009, Buffer.alloc(0))] : []), ...(halfCloseFeature ? [m(1010, Buffer.alloc(0))] : []), ...(clientToolsFeature ? [m(1013, Buffer.alloc(0))] : []));
@@ -67,7 +67,7 @@ function imageAttachments(images) {
67
67
  return images.map((image, index) => {
68
68
  const extension = image?.mimeType === 'image/png' ? 'png' : image?.mimeType === 'image/jpeg' ? 'jpg' : image?.mimeType === 'image/webp' ? 'webp' : null;
69
69
  const id = image?.blobId;
70
- if (!extension || Object.hasOwn(image, 'data') || typeof id !== 'string' || !id.length || Buffer.byteLength(id) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(id) || Buffer.from(id).toString('utf8') !== id) throw new TypeError('Invalid native image');
70
+ if (!extension || Object.hasOwn(image, 'data') || typeof id !== 'string' || !id.length || Buffer.byteLength(id) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(id) || !id.isWellFormed()) throw new TypeError('Invalid native image');
71
71
  const blob = Buffer.concat([string(1, id), varintField(2, 1), string(3, image.mimeType), varintField(4, 1)]);
72
72
  return message(3, Buffer.concat([message(1, blob), string(2, `image-${index + 1}.${extension}`)]));
73
73
  });
@@ -77,8 +77,9 @@ function imageAttachments(images) {
77
77
  * Model IDs and mode numbers are passed explicitly by caller policy.
78
78
  * Built-in tools, overage credits and smart model selection default off.
79
79
  */
80
- export function buildClientGenerate({ userText, images = [], systemText, modelId, identifiers, clientMetadata, includePolicyFlags = true, temporaryChat = false, smartModelSelection = false } = {}) {
80
+ export function buildClientGenerate({ userText, images = [], systemText, modelId, identifiers, clientMetadata, includePolicyFlags = true, temporaryChat = false, smartModelSelection = false, disableNativeTools = true } = {}) {
81
81
  if (typeof smartModelSelection !== 'boolean') throw new TypeError('Invalid smart model selection');
82
+ if (typeof disableNativeTools !== 'boolean') throw new TypeError('Invalid native tools flag');
82
83
  const fields = [message(1, Buffer.concat([string(1, userText), ...imageAttachments(images)]))];
83
84
  if (modelId !== undefined) fields.push(message(3, string(2, modelId)));
84
85
  if (identifiers !== undefined) {
@@ -90,7 +91,7 @@ export function buildClientGenerate({ userText, images = [], systemText, modelId
90
91
  }
91
92
  fields.push(varintField(5, 1));
92
93
  if (clientMetadata !== undefined) fields.push(message(13, buildRequestMetadata(clientMetadata)));
93
- fields.push(varintField(15, 1));
94
+ fields.push(varintField(15, disableNativeTools ? 1 : 0));
94
95
  if (systemText !== undefined) fields.push(message(29, string(4, systemText)));
95
96
  // Temporary chat keeps the turn out of the account's saved conversation history.
96
97
  if (temporaryChat) fields.push(varintField(31, 1));
@@ -100,16 +101,16 @@ export function buildClientGenerate({ userText, images = [], systemText, modelId
100
101
  return output;
101
102
  }
102
103
 
103
- /** Decode inner ClientGenerateResponse. Thought contents are not exported.
104
- * Model identity fields are recorded as evidence and verified by caller policy.
105
- */
106
- export function decodeClientGenerateResponse(bytes) {
107
- const fields = parse(bytes), ids = field(fields, 2);
104
+ /** Decode already-parsed ClientGenerateResponse fields (single-pass helper). */
105
+ export function decodeClientGenerateResponseFields(fields, { includeModels = true } = {}) {
106
+ const ids = field(fields, 2);
108
107
  const models = [];
109
- for (const model of fields.filter(value => value.number === 1)) {
110
- if (model.wire !== 2) throw new Error('Invalid model response');
111
- const item = parse(model.payload), display = field(item, 2);
112
- models.push({ responseId: stringValue(item, 1), text: display === undefined ? null : stringValue(parse(display), 1) });
108
+ if (includeModels) {
109
+ for (const model of fields.filter(value => value.number === 1)) {
110
+ if (model.wire !== 2) throw new Error('Invalid model response');
111
+ const item = parse(model.payload), display = field(item, 2);
112
+ models.push({ responseId: stringValue(item, 1), text: display === undefined ? null : stringValue(parse(display), 1) });
113
+ }
113
114
  }
114
115
  const responseIds = ids === undefined ? [] : parse(ids);
115
116
  return {
@@ -124,6 +125,13 @@ export function decodeClientGenerateResponse(bytes) {
124
125
  };
125
126
  }
126
127
 
128
+ /** Decode inner ClientGenerateResponse. Thought contents are not exported.
129
+ * Model identity fields are recorded as evidence and verified by caller policy.
130
+ */
131
+ export function decodeClientGenerateResponse(bytes) {
132
+ return decodeClientGenerateResponseFields(parse(bytes));
133
+ }
134
+
127
135
  /** Extension 1014 wrapper field 1 -> streaming ContinuationIdentifiers
128
136
  * consumed by InitialRequest field 6. Treat opaque token bytes as private session state.
129
137
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
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": [
@@ -10,6 +10,7 @@
10
10
  "gooeypi",
11
11
  "gemini",
12
12
  "gemini-neon",
13
+ "gemini-carbon",
13
14
  "gemini-hydrogen",
14
15
  "gemini-auto",
15
16
  "provider",
@@ -11,31 +11,53 @@ const fail = (code, status = 400) => { throw protocolError(code, status); };
11
11
  const REDIRECTS = new Set([301, 302, 303, 307, 308]);
12
12
  const MIME = new Set(['image/png', 'image/jpeg', 'image/webp']);
13
13
 
14
+ const DEFAULT_DOWNLOAD_CONCURRENCY = 4;
15
+ const MAX_DOWNLOAD_CONCURRENCY = 8;
16
+
14
17
  /** No proxy, cookies, caller/Google headers, cache, retries or URL-bearing errors. */
15
- export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 } = {}, {
18
+ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000, concurrency = DEFAULT_DOWNLOAD_CONCURRENCY } = {}, {
16
19
  lookup = dnsLookup, request = (url, options, callback) => (url.protocol === 'https:' ? https : http).request(url, options, callback),
17
20
  } = {}) {
18
21
  if (!Array.isArray(images) || images.length > MAX_IMAGES) fail('IMAGE_COUNT_EXCEEDED', 413);
19
22
  if (!images.some(image => image.url)) return images;
20
23
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 180000) fail('INVALID_IMAGE_DOWNLOAD_TIMEOUT');
24
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > MAX_DOWNLOAD_CONCURRENCY) fail('INVALID_IMAGE_DOWNLOAD_CONCURRENCY');
21
25
  if (signal?.aborted) fail('IMAGE_DOWNLOAD_ABORTED', 499);
22
26
  const controller = new AbortController();
23
27
  let rejectStop;
28
+ let stopError = null;
24
29
  const stopped = new Promise((_, reject) => { rejectStop = reject; });
30
+ stopped.catch(() => {});
25
31
  // The shared deadline includes DNS, every redirect and every image in this batch.
26
- const stop = error => { rejectStop(error); controller.abort(); };
32
+ const stop = error => {
33
+ if (!stopError) {
34
+ stopError = error;
35
+ rejectStop(error);
36
+ }
37
+ controller.abort();
38
+ };
27
39
  const abort = () => stop(protocolError('IMAGE_DOWNLOAD_ABORTED', 499));
28
40
  signal?.addEventListener('abort', abort, { once: true });
29
41
  const timer = setTimeout(() => stop(protocolError('IMAGE_DOWNLOAD_TIMEOUT', 504)), timeoutMs);
30
42
  const bounded = promise => Promise.race([promise, stopped]);
31
- let remaining = MAX_TOTAL_IMAGE_BYTES - images.reduce((sum, image) => sum + (image.data?.length ?? 0), 0);
43
+ let sharedRemaining = MAX_TOTAL_IMAGE_BYTES - images.reduce((sum, image) => sum + (image.data?.length ?? 0), 0);
32
44
  try {
33
- if (remaining < 0) fail('IMAGES_TOO_LARGE', 413);
34
- const result = [];
35
- for (const image of images) {
36
- if (!image.url) { result.push(image); continue; }
37
- let url = parseRemoteImageUrl(image.url);
38
- for (let redirects = 0;; redirects++) {
45
+ if (sharedRemaining < 0) fail('IMAGES_TOO_LARGE', 413);
46
+ const result = new Array(images.length);
47
+ const remoteTasks = [];
48
+ for (let index = 0; index < images.length; index++) {
49
+ const image = images[index];
50
+ if (!image.url) {
51
+ result[index] = image;
52
+ continue;
53
+ }
54
+ // Validate URL syntax upfront in deterministic index order before opening any socket.
55
+ remoteTasks.push({ index, initialUrl: parseRemoteImageUrl(image.url) });
56
+ }
57
+
58
+ const downloadOne = async ({ index, initialUrl }) => {
59
+ let url = initialUrl;
60
+ for (let redirects = 0; ; redirects++) {
39
61
  if (controller.signal.aborted) await stopped;
40
62
  const host = url.hostname.replace(/^\[|\]$/g, '');
41
63
  const addresses = isIP(host) ? [{ address: host, family: isIP(host) }] : await bounded(lookup(host, { all: true, verbatim: true }));
@@ -49,10 +71,9 @@ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 }
49
71
  controller.signal.removeEventListener('abort', cancel);
50
72
  if (error) { res?.destroy(); req?.destroy(); reject(error); } else resolve(value);
51
73
  };
52
- const cancel = () => finish(protocolError('IMAGE_DOWNLOAD_ABORTED', 499));
53
- const limit = Math.min(MAX_IMAGE_BYTES, remaining);
74
+ const cancel = () => finish(stopError ?? protocolError('IMAGE_DOWNLOAD_ABORTED', 499));
54
75
  try {
55
- if (limit <= 0) fail('IMAGES_TOO_LARGE', 413);
76
+ if (sharedRemaining <= 0) fail('IMAGES_TOO_LARGE', 413);
56
77
  req = request(url, {
57
78
  method: 'GET', agent: false, maxHeaderSize: 16384,
58
79
  headers: { accept: 'image/png, image/jpeg, image/webp', 'accept-encoding': 'identity', 'user-agent': GATEWAY_USER_AGENT },
@@ -76,11 +97,19 @@ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 }
76
97
  const length = res.headers['content-length'];
77
98
  if (res.statusCode !== 200) { finish(protocolError('IMAGE_DOWNLOAD_HTTP_ERROR', 502)); return; }
78
99
  if (!MIME.has(mimeType) || encoding !== undefined && encoding !== 'identity') { finish(protocolError('UNSUPPORTED_IMAGE_FORMAT')); return; }
79
- if (length !== undefined && (!/^\d+$/.test(length) || Number(length) > limit)) { finish(protocolError('IMAGES_TOO_LARGE', 413)); return; }
100
+ if (length !== undefined && (!/^\d+$/.test(length) || Number(length) > Math.min(MAX_IMAGE_BYTES, sharedRemaining))) {
101
+ finish(protocolError('IMAGES_TOO_LARGE', 413));
102
+ return;
103
+ }
80
104
  const chunks = [];
81
105
  res.on('data', chunk => {
106
+ if (settled) return;
82
107
  size += chunk.length;
83
- if (size > limit) { finish(protocolError('IMAGES_TOO_LARGE', 413)); return; }
108
+ sharedRemaining -= chunk.length;
109
+ if (size > MAX_IMAGE_BYTES || sharedRemaining < 0) {
110
+ finish(protocolError('IMAGES_TOO_LARGE', 413));
111
+ return;
112
+ }
84
113
  chunks.push(chunk);
85
114
  });
86
115
  res.on('end', () => { ended = true; });
@@ -95,16 +124,34 @@ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 }
95
124
  } catch (error) { finish(error); }
96
125
  }));
97
126
  if (response.next) { url = response.next; continue; }
98
- const decoded = decodeImageBytes(response.data, response.mimeType);
99
- remaining -= decoded.data.length;
100
- result.push(decoded); break;
127
+ result[index] = decodeImageBytes(response.data, response.mimeType);
128
+ return;
101
129
  }
102
- }
130
+ };
131
+
132
+ const workerCount = Math.min(concurrency, remoteTasks.length);
133
+ let cursor = 0;
134
+ const workers = Array.from({ length: workerCount }, async () => {
135
+ while (cursor < remoteTasks.length) {
136
+ if (controller.signal.aborted) break;
137
+ const task = remoteTasks[cursor++];
138
+ try {
139
+ await downloadOne(task);
140
+ } catch (error) {
141
+ stop(error);
142
+ throw error;
143
+ }
144
+ }
145
+ });
146
+ await Promise.all(workers);
147
+ if (stopError) throw stopError;
103
148
  return result;
104
149
  } catch (error) {
105
- if (error instanceof ProtocolError) throw error;
150
+ const reported = stopError ?? error;
151
+ if (reported instanceof ProtocolError) throw reported;
106
152
  fail('IMAGE_DOWNLOAD_FAILED', 502);
107
153
  } finally {
154
+ controller.abort();
108
155
  clearTimeout(timer); signal?.removeEventListener('abort', abort);
109
156
  }
110
157
  }
@@ -107,11 +107,13 @@ export class NativeDiagnostic {
107
107
  let fd;
108
108
  try {
109
109
  if (!this.directory || !/^req_[a-f0-9-]{36}$/.test(requestId)) return null;
110
+ const armPath = path.join(this.directory, NATIVE_DIAGNOSTIC_FILES.arm);
111
+ const armStat = fs.lstatSync(armPath, { throwIfNoEntry: false });
112
+ if (!armStat || !privateRegular(armStat)) return null;
110
113
  const directory = fs.lstatSync(this.directory);
111
114
  if (!directory.isDirectory() || (directory.mode & 0o077) !== 0) return null;
112
115
  const files = Object.fromEntries(Object.entries(NATIVE_DIAGNOSTIC_FILES).map(([key, name]) => [key, path.join(this.directory, name)]));
113
116
  if (fs.existsSync(files.claimed) || fs.existsSync(files.result)) return null;
114
- if (!privateRegular(fs.lstatSync(files.arm))) return null;
115
117
  fd = fs.openSync(files.arm, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
116
118
  const stat = fs.fstatSync(fd);
117
119
  if (!privateRegular(stat) || stat.size > 256 || stat.size < 1) return null;
@@ -14,7 +14,7 @@ function sliceCodeUnitsSafe(text, maxChars = CITATION_LIMITS.MAX_TITLE_CHARS) {
14
14
  }
15
15
 
16
16
  function cleanPlainTitle(value, { stripHtml = false } = {}) {
17
- if (typeof value !== 'string' || Buffer.from(value, 'utf8').toString('utf8') !== value) return '';
17
+ if (typeof value !== 'string' || !value.isWellFormed()) return '';
18
18
  let text = stripHtml ? value.replace(/<[^>]*>/g, '') : value;
19
19
  text = text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').replace(/\s+/g, ' ').trim();
20
20
  return sliceCodeUnitsSafe(text, CITATION_LIMITS.MAX_TITLE_CHARS);
@@ -58,6 +58,7 @@ export async function runNativeSearchDiagnostic({
58
58
  signal,
59
59
  timeoutMs = 180000,
60
60
  allowNativeTools = false,
61
+ timing,
61
62
  } = {}) {
62
63
  if (
63
64
  typeof getAccessToken !== "function" ||
@@ -225,7 +226,7 @@ export async function runNativeSearchDiagnostic({
225
226
  thinking_level: 2,
226
227
  },
227
228
  () => {},
228
- { signal },
229
+ { signal, ...(timing ? { timing } : {}) },
229
230
  );
230
231
  if (result.resolvedModeCategory !== 3 || result.thinkingLevel !== 2)
231
232
  return fail("NATIVE_THINKING_MISMATCH");
@@ -59,6 +59,7 @@ export function openDirectTurn(
59
59
  allowNativeTools = false,
60
60
  emitHeaders = false,
61
61
  diagnostic,
62
+ onHeaders,
62
63
  } = {},
63
64
  { connect = connectHttp2 } = {},
64
65
  ) {
@@ -366,6 +367,7 @@ export function openDirectTurn(
366
367
  request.on("response", headers => {
367
368
  lastInboundAt = Date.now();
368
369
  note('peer_headers', { httpStatus: Number(headers[':status']), grpcStatus: Number(headers['grpc-status']) });
370
+ if (typeof onHeaders === 'function') try { onHeaders(); } catch {}
369
371
  status(headers);
370
372
  if (emitHeaders && !closed && httpStatus === 200) push({ type: 'headers', httpStatus });
371
373
  });
@@ -4,14 +4,15 @@ import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
4
4
  import { parse } from '../../native-wire/protobuf.mjs';
5
5
  import { protocolError } from '../tool-protocol.mjs';
6
6
  export const EMPTY_RESPONSE_REASONS = Object.freeze(['no_text', 'whitespace_only', 'thoughts_only', 'post_parse_empty']);
7
- export function inspectNativeOutput(fields) {
7
+ export function inspectNativeOutput(fields, preParsedModelFields = null) {
8
8
  const singular = (list, number, wire = 2) => {
9
9
  const found = list.filter(field => field.number === number);
10
10
  if (found.length > 1 || found.some(field => field.wire !== wire)) throw protocolError('INVALID_NATIVE_RESPONSE', 502);
11
11
  return found[0];
12
12
  };
13
13
  const refusal = [13, 17].some(number => singular(fields, number) !== undefined);
14
- const model = singular(fields, 1), mf = model ? parse(model.payload) : [];
14
+ const model = singular(fields, 1);
15
+ const mf = model ? (Array.isArray(preParsedModelFields) ? preParsedModelFields : parse(model.payload)) : [];
15
16
  const shareable = singular(mf, 7), thoughts = singular(mf, 12);
16
17
  const tf = thoughts ? parse(thoughts.payload) : [];
17
18
  const thoughtText = singular(tf, 1);
@@ -94,9 +94,12 @@ export function decodeUsageInfo(payload) {
94
94
  }
95
95
 
96
96
  /** Optional in-generation metadata. Invalid quota metadata is isolated from the turn. */
97
- export function decodePassiveQuota(clientBytes, observedModel) {
97
+ export function decodePassiveQuota(clientBytes, observedModel, preParsedFields = null) {
98
98
  try {
99
- const fs = fields(clientBytes), budgets = [], refills = [];
99
+ if (!Buffer.isBuffer(clientBytes) || clientBytes.length > MAX) fail();
100
+ const fs = Array.isArray(preParsedFields) ? preParsedFields : fields(clientBytes);
101
+ if (!fs.some((x) => x.number === 20 || x.number === 29 || x.number === 33)) return null;
102
+ const budgets = [], refills = [];
100
103
  for (const n of [20, 29, 33]) one(fs, n, 2);
101
104
  for (const f of fs.filter((x) => x.number === 20)) {
102
105
  if (f.wire !== 2) fail();
@@ -162,7 +165,7 @@ export function safeQuota(value) {
162
165
  helpItems: Array.isArray(r.helpItems) ? r.helpItems.slice(0, 16).filter(h => h && typeof h.label === "string" && typeof h.description === "string").map(h => ({ label: h.label.slice(0, 512), description: h.description.slice(0, 2048) })) : [],
163
166
  })) : [];
164
167
  const times = { budgetsUpdatedAt: safeTime(value.budgetsUpdatedAt) || (budgets.length ? safeTime(value.updatedAt) : null), refillsUpdatedAt: safeTime(value.refillsUpdatedAt) || (refills.length ? safeTime(value.updatedAt) : null), usageUpdatedAt: safeTime(value.usageUpdatedAt) || (usageRows.length ? safeTime(value.updatedAt) : null) };
165
- return { source: value.source === "official" && value.provider === "google-robin" ? "official" : "unknown", status: ["ok", "missing", "error", "unqueried"].includes(value.status) ? value.status : "unknown", updatedAt: safeTime(value.updatedAt), ...times, lastAttemptAt: safeTime(value.lastAttemptAt), errorCode: SAFE_ERRORS.has(value.errorCode) || value.errorCode === "INVALID_QUOTA_METADATA" ? value.errorCode : null, budgets, refills, usageRows, provider: "google-robin", remainingPercent: budgets.length === 1 ? budgets[0].remainingPercent : null, ...(typeof value.observedModel === "string" && ["gemini-neon", "gemini-argon", "gemini-argon-thinking", "gemini-hydrogen", "gemini-flash", "gemini-flash-lite", "gemini-3.1-pro-preview", "gemini-3.1-flash-preview"].includes(value.observedModel) ? { observedModel: value.observedModel } : {}) };
168
+ return { source: value.source === "official" && value.provider === "google-robin" ? "official" : "unknown", status: ["ok", "missing", "error", "unqueried"].includes(value.status) ? value.status : "unknown", updatedAt: safeTime(value.updatedAt), ...times, lastAttemptAt: safeTime(value.lastAttemptAt), errorCode: SAFE_ERRORS.has(value.errorCode) || value.errorCode === "INVALID_QUOTA_METADATA" ? value.errorCode : null, budgets, refills, usageRows, provider: "google-robin", remainingPercent: budgets.length === 1 ? budgets[0].remainingPercent : null, ...(typeof value.observedModel === "string" && ["gemini-neon", "gemini-carbon", "gemini-argon", "gemini-argon-thinking", "gemini-hydrogen", "gemini-flash", "gemini-flash-lite", "gemini-3.1-pro-preview", "gemini-3.1-flash-preview"].includes(value.observedModel) ? { observedModel: value.observedModel } : {}) };
166
169
  }
167
170
  export function quotaFailureCode(error) { return SAFE_ERRORS.has(error?.code) ? error.code : "QUOTA_REFRESH_FAILED"; }
168
171
 
@@ -16,7 +16,7 @@ function assertOnlyKeys(obj, allowed, code = 'INVALID_RESPONSE_FORMAT') {
16
16
  }
17
17
 
18
18
  function validUtf8String(value) {
19
- return typeof value === 'string' && Buffer.from(value).toString('utf8') === value;
19
+ return typeof value === 'string' && value.isWellFormed();
20
20
  }
21
21
 
22
22
  function parseJsonSchemaSpec(spec) {
@@ -7,6 +7,10 @@ import { fault } from './oauth-client-defaults.mjs';
7
7
  export const SUBSCRIPTION_FIELDS = Object.freeze({ nativeTier: 21, isForced: 29 });
8
8
  export const SUBSCRIPTION_CAPABILITY_USER_TIER = 529;
9
9
  const TIERS = Object.freeze({ 1: 'free', 2: 'pro', 3: 'ultra', 4: 'plus', 5: 'ultra_neon' });
10
+ // The Gemini app offers Carbon only on Google AI Ultra; confirmed Free, Plus and Pro accounts never list it.
11
+ export const CARBON_EXCLUDED_TIERS = Object.freeze(['free', 'plus', 'pro']);
12
+ const CARBON_EXCLUDED_TIER_SET = new Set(CARBON_EXCLUDED_TIERS);
13
+ export const isCarbonExcludedTier = (tier) => typeof tier === 'string' && CARBON_EXCLUDED_TIER_SET.has(tier);
10
14
  const NAMES = Object.freeze({ 0: 'TIER_UNSPECIFIED', 1: 'BASIC_USER', 2: 'TIER1', 3: 'TIER2', 4: 'LITE_USER', 5: 'TIER_NEON' });
11
15
  const CODES = new Set(['SUBSCRIPTION_CREDENTIAL_REQUIRED', 'INVALID_SUBSCRIPTION_TIMEOUT', 'INVALID_SUBSCRIPTION_METADATA',
12
16
  'SUBSCRIPTION_CANCELLED', 'SUBSCRIPTION_TIMEOUT', 'SUBSCRIPTION_STREAM_RESET', 'SUBSCRIPTION_RATE_LIMITED',