pi-gemini-app 0.1.14 → 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
 
@@ -1,6 +1,6 @@
1
1
  import { startLoopbackLogin as defaultStartLoopbackLogin, refreshNativeCredential as defaultRefreshNativeCredential } from '../../native-wire/oauth-loopback.mjs';
2
2
  import { acceptGoogleMainTerms as defaultAcceptGoogleMainTerms } from '../../src/gateway/terms.mjs';
3
- import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
3
+ import { fetchGoogleSubscription as defaultFetchGoogleSubscription } from '../../src/gateway/subscription-transport.mjs';
4
4
  import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
5
5
  import { DEFAULT_OAUTH_PROFILE } from '../../src/gateway/oauth-client-defaults.mjs';
6
6
 
@@ -48,14 +48,16 @@ export function createGeminiOAuthAuth({
48
48
  startLoopbackLogin = defaultStartLoopbackLogin,
49
49
  refreshNativeCredential = defaultRefreshNativeCredential,
50
50
  acceptGoogleMainTerms = defaultAcceptGoogleMainTerms,
51
- fetchGoogleUsageInfo = defaultFetchGoogleUsageInfo,
51
+ fetchGoogleSubscription,
52
+ fetchGoogleUsageInfo,
52
53
  decodeSubscription = defaultDecodeSubscription,
53
54
  defaultProfile = DEFAULT_OAUTH_PROFILE,
54
55
  env = process.env,
55
56
  } = {}) {
57
+ const subscriptionFetch = fetchGoogleSubscription || fetchGoogleUsageInfo || defaultFetchGoogleSubscription;
56
58
  async function detectSubscriptionTier(accessToken, { signal } = {}) {
57
59
  try {
58
- const { payload } = await fetchGoogleUsageInfo(accessToken, { signal, timeoutMs: 8000 });
60
+ const { payload } = await subscriptionFetch(accessToken, { signal, timeoutMs: 8000 });
59
61
  const sub = decodeSubscription(payload);
60
62
  return typeof sub?.tier === 'string' && sub.tier ? sub.tier : 'unknown';
61
63
  } catch (error) {
@@ -180,7 +182,7 @@ export function createGeminiOAuthAuth({
180
182
  refresh: scoped.refreshToken || tokens.refreshToken,
181
183
  access: scoped.accessToken,
182
184
  expires: computeExpiresAtMs(scoped.expiresInSeconds ?? tokens.expiresInSeconds),
183
- ...(subscriptionTier !== 'unknown' ? { subscriptionTier } : {}),
185
+ ...(subscriptionTier !== 'unknown' ? { subscriptionTier, subscriptionRpc: 'GetUserStatus' } : {}),
184
186
  };
185
187
  }
186
188
 
@@ -191,14 +193,16 @@ export function createGeminiOAuthAuth({
191
193
  const config = resolveOAuthConfig({ defaultProfile, env });
192
194
  const refreshed = await refreshNativeCredential(config, credential.refresh, { signal });
193
195
  const detectedTier = await detectSubscriptionTier(refreshed.accessToken, { signal });
194
- const subscriptionTier = detectedTier !== 'unknown' ? detectedTier : credential.subscriptionTier;
196
+ const verifiedPrior = credential.subscriptionRpc === 'GetUserStatus' ? credential.subscriptionTier : undefined;
197
+ const subscriptionTier = detectedTier !== 'unknown' ? detectedTier : verifiedPrior;
198
+ const { subscriptionTier: _oldTier, subscriptionRpc: _oldRpc, ...rest } = credential;
195
199
  return {
196
- ...credential,
200
+ ...rest,
197
201
  type: 'oauth',
198
202
  refresh: refreshed.refreshToken || credential.refresh,
199
203
  access: refreshed.accessToken,
200
204
  expires: computeExpiresAtMs(refreshed.expiresInSeconds),
201
- ...(subscriptionTier ? { subscriptionTier } : {}),
205
+ ...(subscriptionTier ? { subscriptionTier, subscriptionRpc: 'GetUserStatus' } : {}),
202
206
  };
203
207
  }
204
208
 
@@ -2,8 +2,9 @@ import { createGeminiOAuthAuth } from './auth.js';
2
2
  import { createGeminiStreamHandler } from './stream.js';
3
3
  import { MODEL_SPECS } from '../../src/openai-contract.mjs';
4
4
  import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
5
+ import { fetchGoogleSubscription as defaultFetchGoogleSubscription } from '../../src/gateway/subscription-transport.mjs';
5
6
  import { decodeUsageInfo as defaultDecodeUsageInfo } from '../../src/gateway/quota.mjs';
6
- import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
7
+ import { decodeSubscription as defaultDecodeSubscription, isCarbonExcludedTier } from '../../src/gateway/subscription.mjs';
7
8
 
8
9
  const BASE_URL = 'https://robinfrontend-pa.googleapis.com';
9
10
  const PROVIDER_ID = 'gemini-app';
@@ -23,6 +24,9 @@ export function filterGeminiModels(models, credential) {
23
24
  if (tier === 'free') {
24
25
  return models.filter((m) => m.provider !== PROVIDER_ID || m.id === 'gemini-auto');
25
26
  }
27
+ if (isCarbonExcludedTier(tier)) {
28
+ return models.filter((m) => m.provider !== PROVIDER_ID || m.id !== 'gemini-carbon');
29
+ }
26
30
  return models;
27
31
  }
28
32
 
@@ -84,6 +88,7 @@ export function createGeminiAppProvider({
84
88
  getCurrentTools,
85
89
  toToolDeclaration,
86
90
  auth,
91
+ fetchGoogleSubscription,
87
92
  fetchGoogleUsageInfo,
88
93
  decodeSubscription,
89
94
  ...streamDependencies
@@ -95,6 +100,7 @@ export function createGeminiAppProvider({
95
100
  const resolvedAuth =
96
101
  auth ||
97
102
  createGeminiOAuthAuth({
103
+ ...(fetchGoogleSubscription ? { fetchGoogleSubscription } : {}),
98
104
  ...(fetchGoogleUsageInfo ? { fetchGoogleUsageInfo } : {}),
99
105
  ...(decodeSubscription ? { decodeSubscription } : {}),
100
106
  });
@@ -123,6 +129,7 @@ export function createGeminiAppProvider({
123
129
 
124
130
  export function registerGeminiAppExtension(pi, dependencies = {}) {
125
131
  const fetchUsage = dependencies?.fetchGoogleUsageInfo || defaultFetchGoogleUsageInfo;
132
+ const fetchSub = dependencies?.fetchGoogleSubscription || (dependencies?.fetchGoogleUsageInfo ? null : defaultFetchGoogleSubscription);
126
133
  const decodeUsage = dependencies?.decodeUsageInfo || defaultDecodeUsageInfo;
127
134
  const decodeSub = dependencies?.decodeSubscription || defaultDecodeSubscription;
128
135
 
@@ -130,6 +137,7 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
130
137
  const {
131
138
  createProvider: _ignoredCreateProvider,
132
139
  auth,
140
+ fetchGoogleSubscription: _ignoredFetchSub,
133
141
  fetchGoogleUsageInfo: _ignoredFetchUsage,
134
142
  decodeUsageInfo: _ignoredDecodeUsage,
135
143
  decodeSubscription: _ignoredDecodeSub,
@@ -138,6 +146,7 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
138
146
  const resolvedAuth =
139
147
  auth ||
140
148
  createGeminiOAuthAuth({
149
+ ...(dependencies?.fetchGoogleSubscription ? { fetchGoogleSubscription: dependencies.fetchGoogleSubscription } : {}),
141
150
  ...(dependencies?.fetchGoogleUsageInfo ? { fetchGoogleUsageInfo: dependencies.fetchGoogleUsageInfo } : {}),
142
151
  ...(dependencies?.decodeSubscription ? { decodeSubscription: dependencies.decodeSubscription } : {}),
143
152
  });
@@ -191,12 +200,18 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
191
200
  }
192
201
  try {
193
202
  ctx.ui?.notify?.('Fetching Gemini quota information...', 'info');
194
- const { payload } = await fetchUsage(token, ctx?.signal ? { signal: ctx.signal } : undefined);
195
- const decoded = decodeUsage(payload);
203
+ const opts = ctx?.signal ? { signal: ctx.signal } : undefined;
204
+ const [usageRes, subRes] = await Promise.all([
205
+ fetchUsage(token, opts),
206
+ fetchSub ? fetchSub(token, opts).catch(() => null) : Promise.resolve(null),
207
+ ]);
208
+ const decoded = decodeUsage(usageRes.payload);
196
209
  let subscription = null;
197
- try {
198
- subscription = decodeSub(payload);
199
- } catch {}
210
+ if (fetchSub && subRes?.payload) {
211
+ try {
212
+ subscription = decodeSub(subRes.payload);
213
+ } catch {}
214
+ }
200
215
  const formatted = formatQuotaDisplay(decoded, subscription);
201
216
  ctx.ui?.notify?.(formatted, 'info');
202
217
  } catch (err) {
@@ -2,6 +2,7 @@ import { openDirectTurn as defaultOpenDirectTurn } from '../../src/gateway/nativ
2
2
  import { createImageBlobCache } from '../../src/gateway/image-upload.mjs';
3
3
  import { NativeDirectProvider as DefaultNativeDirectProvider } from '../../src/native-provider.mjs';
4
4
  import { TOOL_ERRORS, automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
5
+ import { canCompleteInterruptedOutput } from '../../src/gateway/output-recovery.mjs';
5
6
  import { buildChatPayload as defaultBuildChatPayload } from './transcript.js';
6
7
  import { estimateUsage as defaultEstimateUsage, measurePromptImagePayload } from '../../src/openai-usage.mjs';
7
8
 
@@ -327,7 +328,8 @@ export function createGeminiStreamHandler({
327
328
 
328
329
  let body;
329
330
  let codec;
330
- ({ payload: body, codec } = await buildChatPayload(model, context, options, {
331
+ let imageCache;
332
+ ({ payload: body, codec, imageCache } = await buildChatPayload(model, context, options, {
331
333
  getCurrentSystemPrompt,
332
334
  getCurrentTools,
333
335
  toToolDeclaration,
@@ -443,6 +445,7 @@ export function createGeminiStreamHandler({
443
445
  recoveryCode,
444
446
  recoveryReason,
445
447
  getOutputCommitState,
448
+ ...(imageCache?.size ? { imageCache } : {}),
446
449
  });
447
450
  if (turnResult?.thinkingLevel !== undefined && turnResult.thinkingLevel !== null) {
448
451
  observedThinking = turnResult.thinkingLevel;
@@ -452,11 +455,18 @@ export function createGeminiStreamHandler({
452
455
  }
453
456
  break;
454
457
  } catch (turnError) {
455
- const usableTimeout =
456
- turnError?.code === 'NATIVE_TURN_TIMEOUT' &&
457
- (hasToolCalls || turnError?.postOutputIdleStall === true || publishedBytes >= PREFIX_BYTES);
458
- const salvageValidatedCalls = hasToolCalls && TOOL_ERRORS.has(turnError?.code);
459
- if (!options?.signal?.aborted && turnError?.unverifiedOutput !== true && (usableTimeout || salvageValidatedCalls)) {
458
+ if (
459
+ canCompleteInterruptedOutput({
460
+ error: turnError,
461
+ publishedBytes,
462
+ callCount: toolCallCount,
463
+ hasVisibleText: publishedBytes > 0 || textBuffer.trim().length > 0,
464
+ aborted: options?.signal?.aborted === true,
465
+ allowPrefixPartialOnTransport: false,
466
+ salvageToolErrors: true,
467
+ toolErrors: TOOL_ERRORS,
468
+ })
469
+ ) {
460
470
  break;
461
471
  }
462
472
  if (
@@ -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))] : []));
@@ -38,9 +38,10 @@ const stringValue = (fields, number) => {
38
38
  return value === undefined ? null : utf8.decode(value);
39
39
  };
40
40
  /** Native ROBINRequestMetadata subset. No device IDs or hardware attestation. */
41
- export function buildRequestMetadata({ clientType, languageCode, interfaceLanguageCode, clientVersion, clientInstanceId, triggerType, uiSource, clientFunctionCapabilities = false } = {}) {
41
+ export function buildRequestMetadata({ clientType, languageCode, interfaceLanguageCode, clientVersion, clientInstanceId, triggerType, uiSource, clientFunctionCapabilities = false, subscriptionTierCapability = false } = {}) {
42
42
  if (!Number.isSafeInteger(clientType) || clientType < 0 || clientType > 255) throw new Error('Explicit client type required');
43
43
  if (typeof clientFunctionCapabilities !== 'boolean') throw new TypeError('Invalid client-function capabilities');
44
+ if (typeof subscriptionTierCapability !== 'boolean') throw new TypeError('Invalid subscription-tier capability');
44
45
  const fields = [];
45
46
  if (triggerType !== undefined) {if (!Number.isSafeInteger(triggerType)||triggerType<0)throw new Error('Invalid trigger');fields.push(message(1,varintField(1,triggerType)));}
46
47
  if (interfaceLanguageCode !== undefined) fields.push(message(2, string(1, interfaceLanguageCode)));
@@ -48,8 +49,12 @@ export function buildRequestMetadata({ clientType, languageCode, interfaceLangua
48
49
  fields.push(varintField(4, clientType));
49
50
  if (languageCode !== undefined) fields.push(string(7, languageCode));
50
51
  if (uiSource !== undefined) {if (!Number.isSafeInteger(uiSource)||uiSource<0)throw new Error('Invalid UI source');fields.push(varintField(5,uiSource));}
51
- // Metadata CapabilityType values, distinct from DesktopInfo capability enum 379.
52
- if (clientFunctionCapabilities) fields.push(message(6, message(2, Buffer.concat([varint(668), varint(669)]))));
52
+ // Metadata CapabilityType values (field 6.2), distinct from DesktopInfo capability enum 379.
53
+ // 529 = ENABLE_USER_SUBSCRIPTION_TIER; 668/669 = CLIENT_TOOLS / ROBIN_OP_CLIENT_FUNCTION_CALL.
54
+ const capabilities = [];
55
+ if (subscriptionTierCapability) capabilities.push(529);
56
+ if (clientFunctionCapabilities) capabilities.push(668, 669);
57
+ if (capabilities.length) fields.push(message(6, message(2, Buffer.concat(capabilities.map(varint)))));
53
58
  if (clientInstanceId !== undefined) fields.push(string(23, clientInstanceId));
54
59
  return Buffer.concat(fields);
55
60
  }
@@ -62,7 +67,7 @@ function imageAttachments(images) {
62
67
  return images.map((image, index) => {
63
68
  const extension = image?.mimeType === 'image/png' ? 'png' : image?.mimeType === 'image/jpeg' ? 'jpg' : image?.mimeType === 'image/webp' ? 'webp' : null;
64
69
  const id = image?.blobId;
65
- 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');
66
71
  const blob = Buffer.concat([string(1, id), varintField(2, 1), string(3, image.mimeType), varintField(4, 1)]);
67
72
  return message(3, Buffer.concat([message(1, blob), string(2, `image-${index + 1}.${extension}`)]));
68
73
  });
@@ -72,8 +77,9 @@ function imageAttachments(images) {
72
77
  * Model IDs and mode numbers are passed explicitly by caller policy.
73
78
  * Built-in tools, overage credits and smart model selection default off.
74
79
  */
75
- 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 } = {}) {
76
81
  if (typeof smartModelSelection !== 'boolean') throw new TypeError('Invalid smart model selection');
82
+ if (typeof disableNativeTools !== 'boolean') throw new TypeError('Invalid native tools flag');
77
83
  const fields = [message(1, Buffer.concat([string(1, userText), ...imageAttachments(images)]))];
78
84
  if (modelId !== undefined) fields.push(message(3, string(2, modelId)));
79
85
  if (identifiers !== undefined) {
@@ -85,7 +91,7 @@ export function buildClientGenerate({ userText, images = [], systemText, modelId
85
91
  }
86
92
  fields.push(varintField(5, 1));
87
93
  if (clientMetadata !== undefined) fields.push(message(13, buildRequestMetadata(clientMetadata)));
88
- fields.push(varintField(15, 1));
94
+ fields.push(varintField(15, disableNativeTools ? 1 : 0));
89
95
  if (systemText !== undefined) fields.push(message(29, string(4, systemText)));
90
96
  // Temporary chat keeps the turn out of the account's saved conversation history.
91
97
  if (temporaryChat) fields.push(varintField(31, 1));
@@ -95,16 +101,16 @@ export function buildClientGenerate({ userText, images = [], systemText, modelId
95
101
  return output;
96
102
  }
97
103
 
98
- /** Decode inner ClientGenerateResponse. Thought contents are not exported.
99
- * Model identity fields are recorded as evidence and verified by caller policy.
100
- */
101
- export function decodeClientGenerateResponse(bytes) {
102
- 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);
103
107
  const models = [];
104
- for (const model of fields.filter(value => value.number === 1)) {
105
- if (model.wire !== 2) throw new Error('Invalid model response');
106
- const item = parse(model.payload), display = field(item, 2);
107
- 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
+ }
108
114
  }
109
115
  const responseIds = ids === undefined ? [] : parse(ids);
110
116
  return {
@@ -119,6 +125,13 @@ export function decodeClientGenerateResponse(bytes) {
119
125
  };
120
126
  }
121
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
+
122
135
  /** Extension 1014 wrapper field 1 -> streaming ContinuationIdentifiers
123
136
  * consumed by InitialRequest field 6. Treat opaque token bytes as private session state.
124
137
  */
@@ -142,31 +155,63 @@ export function frameGrpcMessage(bytes) {
142
155
  export class GrpcMessageReader {
143
156
  constructor({ maxBytes = MAX_MESSAGE_BYTES } = {}) {
144
157
  if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_MESSAGE_BYTES) throw new RangeError('Invalid frame budget');
145
- this.maxBytes = maxBytes; this.pending = Buffer.alloc(0); this.closed = false;
158
+ this.maxBytes = maxBytes;
159
+ this.header = Buffer.allocUnsafe(5);
160
+ this.headerBytes = 0;
161
+ this.expectedLength = null;
162
+ this.payloadChunks = [];
163
+ this.payloadBytes = 0;
164
+ this.closed = false;
146
165
  }
147
166
  push(bytes) {
148
167
  if (this.closed) throw new Error('Reader already closed');
149
168
  if (!Buffer.isBuffer(bytes)) throw new TypeError('Expected Buffer');
150
169
  const frames = [];
151
- // Accept concatenated chunks without allowing an unbounded pending allocation.
152
170
  let offset = 0;
153
171
  while (offset < bytes.length) {
154
- const needed = this.pending.length < 5 ? 5 - this.pending.length : 5 + this.pending.readUInt32BE(1) - this.pending.length;
172
+ if (this.expectedLength === null) {
173
+ const take = Math.min(5 - this.headerBytes, bytes.length - offset);
174
+ bytes.copy(this.header, this.headerBytes, offset, offset + take);
175
+ this.headerBytes += take;
176
+ offset += take;
177
+ if (this.headerBytes < 5) continue;
178
+ if (this.header[0] !== 0) throw new Error('Compressed gRPC messages not supported');
179
+ const length = this.header.readUInt32BE(1);
180
+ if (length > this.maxBytes) throw new RangeError('gRPC frame exceeds budget');
181
+ if (length === 0) {
182
+ frames.push(Buffer.alloc(0));
183
+ this.headerBytes = 0;
184
+ continue;
185
+ }
186
+ this.expectedLength = length;
187
+ continue;
188
+ }
189
+ const needed = this.expectedLength - this.payloadBytes;
155
190
  const take = Math.min(needed, bytes.length - offset);
156
- this.pending = Buffer.concat([this.pending, bytes.subarray(offset, offset + take)]);
191
+ const slice = bytes.subarray(offset, offset + take);
157
192
  offset += take;
158
- if (this.pending.length < 5) continue;
159
- if (this.pending[0] !== 0) throw new Error('Compressed gRPC messages not supported');
160
- const length = this.pending.readUInt32BE(1);
161
- if (length > this.maxBytes) throw new RangeError('gRPC frame exceeds budget');
162
- if (this.pending.length === length + 5) {
163
- frames.push(this.pending.subarray(5)); this.pending = Buffer.alloc(0);
193
+ this.payloadBytes += take;
194
+ const owned = Buffer.from(slice);
195
+ if (this.payloadChunks.length === 0 && this.payloadBytes === this.expectedLength) {
196
+ frames.push(owned);
197
+ this.headerBytes = 0;
198
+ this.expectedLength = null;
199
+ this.payloadBytes = 0;
200
+ continue;
201
+ }
202
+ this.payloadChunks.push(owned);
203
+ if (this.payloadBytes === this.expectedLength) {
204
+ frames.push(Buffer.concat(this.payloadChunks, this.expectedLength));
205
+ this.headerBytes = 0;
206
+ this.expectedLength = null;
207
+ this.payloadChunks = [];
208
+ this.payloadBytes = 0;
164
209
  }
165
210
  }
166
211
  return frames;
167
212
  }
168
213
  finish() {
169
214
  this.closed = true;
170
- if (this.pending.length) throw new Error('Truncated gRPC stream');
215
+ if (this.headerBytes > 0 || this.expectedLength !== null) throw new Error('Truncated gRPC stream');
171
216
  }
172
217
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.14",
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",
@@ -73,6 +74,7 @@
73
74
  "src/gateway/quota.mjs",
74
75
  "src/gateway/soft-error.mjs",
75
76
  "src/gateway/structured-output.mjs",
77
+ "src/gateway/subscription-transport.mjs",
76
78
  "src/gateway/subscription.mjs",
77
79
  "src/gateway/terms.mjs",
78
80
  "src/image-input.mjs",
@@ -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;