pi-gemini-app 0.1.1 → 0.1.2

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
@@ -68,16 +68,19 @@ Optional environment overrides if using your own OAuth desktop client:
68
68
  | `gemini-argon` | Gemini Argon | 128,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
69
69
  | `gemini-hydrogen` | Gemini Hydrogen | 512,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
70
70
  | `gemini-flash-lite` | Gemini Flash Lite | 128,000 | 8,192 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
71
+ | `gemini-auto` | Gemini Auto | 128,000 | 8,192 | Smart Model Selection for Free & paid Google accounts (text, static images, tools) |
71
72
 
73
+ > **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.
74
+ >
72
75
  > **Quota Tip**: `gemini-hydrogen` consumes significantly less rolling window quota than `gemini-argon` and responds faster, making it ideal for multi-step coding and tool-calling loops. Reserve `gemini-argon` for complex architecture or deep reasoning tasks.
73
76
  >
74
77
  > **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.
75
78
  >
76
- > **Auto-Compaction**: The configured `contextWindow` (`128,000` for Argon/Flash Lite; `512,000` for Hydrogen) works automatically with Pi's proactive compaction (`contextWindow - reserveTokens`) and `413` context-overflow recovery compaction (or manual `/compact`).
79
+ > **Auto-Compaction**: The configured `contextWindow` (`128,000` for Argon/Flash Lite/Auto; `512,000` for Hydrogen) works automatically with Pi's proactive compaction (`contextWindow - reserveTokens`) and `413` context-overflow recovery compaction (or manual `/compact`).
77
80
 
78
81
  ## Commands
79
82
 
80
- - `/gemini-quota` — Fetches and displays your signed-in account's rolling usage percentages and reset timestamps.
83
+ - `/gemini-quota` — Fetches and displays your signed-in account's detected subscription tier, rolling usage percentages, and reset timestamps.
81
84
 
82
85
  ## Security & Privacy
83
86
 
@@ -1,5 +1,7 @@
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';
4
+ import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
3
5
  import { DEFAULT_OAUTH_PROFILE } from '../../src/gateway/oauth-client-defaults.mjs';
4
6
 
5
7
  const FLEXIBLE_API_SCOPE = 'https://www.googleapis.com/auth/flexible-api';
@@ -46,9 +48,21 @@ export function createGeminiOAuthAuth({
46
48
  startLoopbackLogin = defaultStartLoopbackLogin,
47
49
  refreshNativeCredential = defaultRefreshNativeCredential,
48
50
  acceptGoogleMainTerms = defaultAcceptGoogleMainTerms,
51
+ fetchGoogleUsageInfo = defaultFetchGoogleUsageInfo,
52
+ decodeSubscription = defaultDecodeSubscription,
49
53
  defaultProfile = DEFAULT_OAUTH_PROFILE,
50
54
  env = process.env,
51
55
  } = {}) {
56
+ async function detectSubscriptionTier(accessToken, { signal } = {}) {
57
+ try {
58
+ const { payload } = await fetchGoogleUsageInfo(accessToken, { signal, timeoutMs: 8000 });
59
+ const sub = decodeSubscription(payload);
60
+ return typeof sub?.tier === 'string' && sub.tier ? sub.tier : 'unknown';
61
+ } catch (error) {
62
+ if (signal?.aborted) throw error;
63
+ return 'unknown';
64
+ }
65
+ }
52
66
  async function login(interaction) {
53
67
  const config = resolveOAuthConfig({ defaultProfile, env });
54
68
  const outerSignal = interaction?.signal;
@@ -146,11 +160,27 @@ export function createGeminiOAuthAuth({
146
160
  });
147
161
  }
148
162
 
163
+ interaction?.notify?.({
164
+ type: 'progress',
165
+ message: 'Checking Gemini subscription tier...',
166
+ });
167
+ const subscriptionTier = await detectSubscriptionTier(scoped.accessToken, { signal: outerSignal });
168
+ if (subscriptionTier !== 'unknown') {
169
+ interaction?.notify?.({
170
+ type: 'progress',
171
+ message:
172
+ subscriptionTier === 'free'
173
+ ? 'Detected Gemini Free account (gemini-auto enabled).'
174
+ : `Detected Gemini subscription tier: ${subscriptionTier}.`,
175
+ });
176
+ }
177
+
149
178
  return {
150
179
  type: 'oauth',
151
180
  refresh: scoped.refreshToken || tokens.refreshToken,
152
181
  access: scoped.accessToken,
153
182
  expires: computeExpiresAtMs(scoped.expiresInSeconds ?? tokens.expiresInSeconds),
183
+ ...(subscriptionTier !== 'unknown' ? { subscriptionTier } : {}),
154
184
  };
155
185
  }
156
186
 
@@ -160,12 +190,15 @@ export function createGeminiOAuthAuth({
160
190
  }
161
191
  const config = resolveOAuthConfig({ defaultProfile, env });
162
192
  const refreshed = await refreshNativeCredential(config, credential.refresh, { signal });
193
+ const detectedTier = await detectSubscriptionTier(refreshed.accessToken, { signal });
194
+ const subscriptionTier = detectedTier !== 'unknown' ? detectedTier : credential.subscriptionTier;
163
195
  return {
164
196
  ...credential,
165
197
  type: 'oauth',
166
198
  refresh: refreshed.refreshToken || credential.refresh,
167
199
  access: refreshed.accessToken,
168
200
  expires: computeExpiresAtMs(refreshed.expiresInSeconds),
201
+ ...(subscriptionTier ? { subscriptionTier } : {}),
169
202
  };
170
203
  }
171
204
 
@@ -2,11 +2,29 @@ import { createGeminiOAuthAuth } from './auth.js';
2
2
  import { createGeminiStreamHandler } from './stream.js';
3
3
  import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
4
4
  import { decodeUsageInfo as defaultDecodeUsageInfo } from '../../src/gateway/quota.mjs';
5
+ import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
5
6
 
6
7
  const BASE_URL = 'https://robinfrontend-pa.googleapis.com';
7
8
  const PROVIDER_ID = 'gemini-app';
8
9
  const API_ID = 'gemini-app-api';
9
10
 
11
+ export const SUBSCRIPTION_LABELS = Object.freeze({
12
+ free: 'Free',
13
+ plus: 'AI Plus',
14
+ pro: 'AI Pro',
15
+ ultra: 'AI Ultra',
16
+ ultra_neon: 'Ultra/Neon',
17
+ });
18
+
19
+ export function filterGeminiModels(models, credential) {
20
+ if (!Array.isArray(models)) return [];
21
+ const tier = credential?.type === 'oauth' ? credential.subscriptionTier : undefined;
22
+ if (tier === 'free') {
23
+ return models.filter((m) => m.provider !== PROVIDER_ID || m.id === 'gemini-auto');
24
+ }
25
+ return models;
26
+ }
27
+
10
28
  export const MODELS = Object.freeze([
11
29
  {
12
30
  id: 'gemini-argon',
@@ -68,11 +86,32 @@ export const MODELS = Object.freeze([
68
86
  },
69
87
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
70
88
  },
89
+ {
90
+ id: 'gemini-auto',
91
+ name: 'Gemini Auto',
92
+ api: API_ID,
93
+ provider: PROVIDER_ID,
94
+ baseUrl: BASE_URL,
95
+ type: 'chat',
96
+ contextWindow: 128000,
97
+ maxTokens: 8192,
98
+ input: ['text', 'image'],
99
+ reasoning: false,
100
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
101
+ },
71
102
  ]);
72
103
 
73
- export function formatQuotaDisplay(usageInfo) {
104
+ export function formatQuotaDisplay(usageInfo, subscriptionInfo) {
105
+ const tier = subscriptionInfo?.tier;
106
+ const label = tier && tier !== 'unknown' ? SUBSCRIPTION_LABELS[tier] || tier : null;
107
+ const header = label
108
+ ? tier === 'free'
109
+ ? `Gemini Subscription: ${label} (available model: gemini-auto)`
110
+ : `Gemini Subscription: ${label}`
111
+ : null;
74
112
  if (!usageInfo?.usageRows?.length) {
75
- return 'No active quota limits reported for this account.';
113
+ const emptyMsg = 'No active quota limits reported for this account.';
114
+ return header ? `${header}\n${emptyMsg}` : emptyMsg;
76
115
  }
77
116
  const lines = usageInfo.usageRows.map((row) => {
78
117
  if (row.providerPercent === null || !Number.isFinite(row.providerPercent)) {
@@ -84,7 +123,8 @@ export function formatQuotaDisplay(usageInfo) {
84
123
  const reset = row.providerTimestamp ? ` (resets: ${row.providerTimestamp})` : '';
85
124
  return `• ${row.label || 'Usage'}: ${remaining}% remaining (${used}% used)${reset}`;
86
125
  });
87
- return `Gemini Quota:\n${lines.join('\n')}`;
126
+ const body = `Gemini Quota:\n${lines.join('\n')}`;
127
+ return header ? `${header}\n${body}` : body;
88
128
  }
89
129
 
90
130
  export function createGeminiAppProvider({
@@ -93,13 +133,22 @@ export function createGeminiAppProvider({
93
133
  getCurrentSystemPrompt,
94
134
  getCurrentTools,
95
135
  toToolDeclaration,
96
- auth = createGeminiOAuthAuth(),
136
+ auth,
137
+ fetchGoogleUsageInfo,
138
+ decodeSubscription,
97
139
  ...streamDependencies
98
140
  }) {
99
141
  if (typeof createProvider !== 'function') {
100
142
  throw new TypeError('createProvider factory is required');
101
143
  }
102
144
 
145
+ const resolvedAuth =
146
+ auth ||
147
+ createGeminiOAuthAuth({
148
+ ...(fetchGoogleUsageInfo ? { fetchGoogleUsageInfo } : {}),
149
+ ...(decodeSubscription ? { decodeSubscription } : {}),
150
+ });
151
+
103
152
  const streamHandler = createGeminiStreamHandler({
104
153
  createAssistantMessageEventStream,
105
154
  getCurrentSystemPrompt,
@@ -112,8 +161,9 @@ export function createGeminiAppProvider({
112
161
  id: PROVIDER_ID,
113
162
  name: 'Google Gemini App',
114
163
  baseUrl: BASE_URL,
115
- auth: { oauth: auth },
164
+ auth: { oauth: resolvedAuth },
116
165
  models: MODELS,
166
+ filterModels: filterGeminiModels,
117
167
  api: {
118
168
  stream: streamHandler.stream,
119
169
  streamSimple: streamHandler.streamSimple,
@@ -122,14 +172,25 @@ export function createGeminiAppProvider({
122
172
  }
123
173
 
124
174
  export function registerGeminiAppExtension(pi, dependencies = {}) {
175
+ const fetchUsage = dependencies?.fetchGoogleUsageInfo || defaultFetchGoogleUsageInfo;
176
+ const decodeUsage = dependencies?.decodeUsageInfo || defaultDecodeUsageInfo;
177
+ const decodeSub = dependencies?.decodeSubscription || defaultDecodeSubscription;
178
+
125
179
  if (dependencies?.createProvider === undefined) {
126
180
  const {
127
181
  createProvider: _ignoredCreateProvider,
128
- auth = createGeminiOAuthAuth(),
182
+ auth,
129
183
  fetchGoogleUsageInfo: _ignoredFetchUsage,
130
184
  decodeUsageInfo: _ignoredDecodeUsage,
185
+ decodeSubscription: _ignoredDecodeSub,
131
186
  ...streamDependencies
132
187
  } = dependencies;
188
+ const resolvedAuth =
189
+ auth ||
190
+ createGeminiOAuthAuth({
191
+ ...(dependencies?.fetchGoogleUsageInfo ? { fetchGoogleUsageInfo: dependencies.fetchGoogleUsageInfo } : {}),
192
+ ...(dependencies?.decodeSubscription ? { decodeSubscription: dependencies.decodeSubscription } : {}),
193
+ });
133
194
  const streamHandler = createGeminiStreamHandler(streamDependencies);
134
195
  pi.registerProvider(PROVIDER_ID, {
135
196
  name: 'Google Gemini App',
@@ -138,9 +199,9 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
138
199
  models: MODELS,
139
200
  streamSimple: streamHandler.streamSimple,
140
201
  oauth: {
141
- name: auth.name,
202
+ name: resolvedAuth.name,
142
203
  login: (callbacks) =>
143
- auth.login({
204
+ resolvedAuth.login({
144
205
  signal: callbacks?.signal,
145
206
  notify: (ev) => {
146
207
  if (ev.type === 'auth_url') {
@@ -154,8 +215,9 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
154
215
  ? callbacks.onManualCodeInput()
155
216
  : callbacks?.onPrompt?.({ message: p.message, placeholder: p.placeholder }),
156
217
  }),
157
- refreshToken: (cred, signal) => auth.refresh(cred, signal),
218
+ refreshToken: (cred, signal) => resolvedAuth.refresh(cred, signal),
158
219
  getApiKey: (cred) => cred.access,
220
+ modifyModels: filterGeminiModels,
159
221
  },
160
222
  });
161
223
  } else {
@@ -163,9 +225,6 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
163
225
  pi.registerProvider(provider);
164
226
  }
165
227
 
166
- const fetchUsage = dependencies?.fetchGoogleUsageInfo || defaultFetchGoogleUsageInfo;
167
- const decodeUsage = dependencies?.decodeUsageInfo || defaultDecodeUsageInfo;
168
-
169
228
  pi.registerCommand('gemini-quota', {
170
229
  description: 'Check Gemini account quota and rolling reset windows',
171
230
  handler: async (_args, ctx) => {
@@ -184,7 +243,11 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
184
243
  ctx.ui?.notify?.('Fetching Gemini quota information...', 'info');
185
244
  const { payload } = await fetchUsage(token, ctx?.signal ? { signal: ctx.signal } : undefined);
186
245
  const decoded = decodeUsage(payload);
187
- const formatted = formatQuotaDisplay(decoded);
246
+ let subscription = null;
247
+ try {
248
+ subscription = decodeSub(payload);
249
+ } catch {}
250
+ const formatted = formatQuotaDisplay(decoded, subscription);
188
251
  ctx.ui?.notify?.(formatted, 'info');
189
252
  } catch (err) {
190
253
  ctx.ui?.notify?.(`Failed to fetch Gemini quota: ${err.message}`, 'error');
@@ -19,7 +19,7 @@ const GENERIC_PROTOCOL_MESSAGES = new Set([
19
19
  'Unsupported or invalid request',
20
20
  ]);
21
21
 
22
- function formatFriendlyError(error, isAborted) {
22
+ function formatFriendlyError(error, isAborted, modelId) {
23
23
  if (isAborted) return 'Request was aborted';
24
24
  if (
25
25
  error?.status === 429 ||
@@ -47,16 +47,33 @@ function formatFriendlyError(error, isAborted) {
47
47
  ) {
48
48
  return `Google Gemini authentication expired or permission denied${error?.code ? ` (${error.code})` : ''}. Please run /login gemini-app to sign in again.`;
49
49
  }
50
+ const upstreamMessage =
51
+ typeof error?.nativeEvidence?.upstreamMessage === 'string' &&
52
+ error.nativeEvidence.upstreamMessage.length > 0
53
+ ? error.nativeEvidence.upstreamMessage
54
+ : '';
50
55
  const code = typeof error?.code === 'string' && error.code.length > 0 ? error.code : '';
56
+ if (code === 'NATIVE_PRECONDITION_REQUIRED') {
57
+ if (/terms of service|tos_not_accepted/i.test(upstreamMessage)) {
58
+ return `Google Gemini Terms of Service not accepted [NATIVE_PRECONDITION_REQUIRED]: ${upstreamMessage} — Accept Terms of Service at https://gemini.google.com or run /login gemini-app again.`;
59
+ }
60
+ if (/requires_advanced|mismatched_bard_mode|invalid_bard_mode/i.test(upstreamMessage)) {
61
+ return `Selected model (${modelId || 'requested mode'}) requires a paid Google AI subscription [NATIVE_PRECONDITION_REQUIRED]: ${upstreamMessage} — Switch to gemini-auto (or run /login gemini-app to refresh available models).`;
62
+ }
63
+ return `Native response failed verification: [NATIVE_PRECONDITION_REQUIRED]${upstreamMessage ? ` — ${upstreamMessage}` : ''}. Free Gemini accounts only support gemini-auto (switch to gemini-auto or run /login gemini-app; if new to Gemini, ensure Terms of Service are accepted at https://gemini.google.com).`;
64
+ }
65
+ if (code === 'MODEL_DOWNGRADE_REJECTED') {
66
+ return `Requested model (${modelId || 'selected model'}) was downgraded or is unavailable for this account [MODEL_DOWNGRADE_REJECTED]. Try gemini-hydrogen, or switch to gemini-auto on Free accounts.`;
67
+ }
51
68
  const param = typeof error?.param === 'string' && error.param.length > 0 ? ` (param: ${error.param})` : '';
52
69
  const message = typeof error?.message === 'string' && error.message.length > 0 ? error.message : '';
53
70
  if (code && (!message || GENERIC_PROTOCOL_MESSAGES.has(message))) {
54
- return `${message ? `${message}: ` : ''}[${code}]${param}`;
71
+ return `${message ? `${message}: ` : ''}[${code}]${param}${upstreamMessage ? ` — ${upstreamMessage}` : ''}`;
55
72
  }
56
73
  if (code && !message.includes(code)) {
57
- return `[${code}] ${message}${param}`;
74
+ return `[${code}] ${message}${param}${upstreamMessage ? ` — ${upstreamMessage}` : ''}`;
58
75
  }
59
- return message ? `${message}${param}` : code || 'Unknown error';
76
+ return message ? `${message}${param}${upstreamMessage ? ` — ${upstreamMessage}` : ''}` : code || 'Unknown error';
60
77
  }
61
78
 
62
79
  function hasTrailingHighSurrogate(str) {
@@ -323,6 +340,7 @@ export function createGeminiStreamHandler({
323
340
  const provider = new NativeDirectProvider(authManager, {
324
341
  openTurn,
325
342
  modelAlias: model.id,
343
+ allowAutoModel: true,
326
344
  });
327
345
 
328
346
  let attempts = 0;
@@ -418,7 +436,7 @@ export function createGeminiStreamHandler({
418
436
  turnError?.code !== 'NATIVE_TURN_ABORTED' &&
419
437
  turnError?.code !== 'REQUEST_CANCELLED'
420
438
  ) {
421
- const kind = automaticRecoveryKind(turnError, model.id);
439
+ const kind = automaticRecoveryKind(turnError, model.id, { allowAutoModel: true });
422
440
  if (ALLOWED_RECOVERY_KINDS.has(kind)) {
423
441
  attempts++;
424
442
  recoveryCode = turnError.code;
@@ -470,7 +488,7 @@ export function createGeminiStreamHandler({
470
488
  };
471
489
  }
472
490
  partial.stopReason = stopReason;
473
- partial.errorMessage = formatFriendlyError(error, isAborted);
491
+ partial.errorMessage = formatFriendlyError(error, isAborted, model?.id);
474
492
  stream.push({ type: 'error', reason: stopReason, error: partial });
475
493
  stream.end();
476
494
  }
@@ -212,9 +212,10 @@ export function encodeClientFunctionCallResult(calls,contents){
212
212
  }));
213
213
  }
214
214
  export const encodeConsumerResultsEnd = turnSequence => cat(sequence(turnSequence), m(1011, m(2, Buffer.alloc(0))));
215
- export function buildConsumerToolInitial({ userText, images = [], systemText, tools = [], toolChoice = 'auto', turnSequence = 1, clientMetadata, identifiers, continuation, agentChat = false, clientToolsFeature = false, operationFeature = true, halfCloseFeature = false, localSession = false, clientToolsCapability = false, clientFunctionCapabilities = false, ownedDeviceId, modeCategory, thinkingLevel = ARGON_THINKING_LEVEL, temporaryChat = true, allowNativeTools = false } = {}, { maxInputBytes = TOOL_LIMITS.bytes } = {}) {
215
+ export function buildConsumerToolInitial({ userText, images = [], systemText, tools = [], toolChoice = 'auto', turnSequence = 1, clientMetadata, identifiers, continuation, agentChat = false, clientToolsFeature = false, operationFeature = true, halfCloseFeature = false, localSession = false, clientToolsCapability = false, clientFunctionCapabilities = false, ownedDeviceId, modeCategory, thinkingLevel = ARGON_THINKING_LEVEL, temporaryChat = true, allowNativeTools = false, smartModelSelection = false } = {}, { maxInputBytes = TOOL_LIMITS.bytes } = {}) {
216
216
  if (!Number.isSafeInteger(maxInputBytes) || maxInputBytes < 1 || maxInputBytes > MAX_MESSAGE_BYTES) rejectTool('INVALID_NATIVE_INPUT_LIMIT');
217
217
  string(userText, maxInputBytes); if (systemText !== undefined) string(systemText); if (typeof allowNativeTools !== 'boolean') rejectTool('INVALID_NATIVE_TOOLS_PERMISSION'); if (allowNativeTools && tools.length) rejectTool('NATIVE_TOOLS_WITH_DECLARATIONS'); if (typeof agentChat !== 'boolean') rejectTool('INVALID_AGENT_CONTEXT'); if (typeof clientToolsFeature !== 'boolean') rejectTool('INVALID_CLIENT_TOOLS_FEATURE'); if (typeof operationFeature !== 'boolean') rejectTool('INVALID_OPERATION_FEATURE'); if (typeof halfCloseFeature !== 'boolean') rejectTool('INVALID_HALF_CLOSE_FEATURE'); if (typeof localSession !== 'boolean') rejectTool('INVALID_LOCAL_SESSION'); if (typeof clientToolsCapability !== 'boolean') rejectTool('INVALID_CLIENT_TOOLS_CAPABILITY'); if (typeof clientFunctionCapabilities !== 'boolean') rejectTool('INVALID_CLIENT_FUNCTION_CAPABILITIES');
218
+ if (typeof smartModelSelection !== 'boolean') rejectTool('INVALID_SMART_MODEL_SELECTION');
218
219
  if (allowNativeTools && (!Array.isArray(images) || images.length)) rejectTool('NATIVE_SEARCH_IMAGES_UNSUPPORTED');
219
220
  if(ownedDeviceId!==undefined&&(typeof ownedDeviceId!=='string'||!/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/.test(ownedDeviceId)))rejectTool('INVALID_OWNED_DEVICE_ID');if(ownedDeviceId!==undefined&&!localSession)rejectTool('OWNED_DEVICE_REQUIRES_LOCAL_SESSION');
220
221
  const registry = compileConsumerTools(tools, toolChoice);if(localSession&&!registry.size)rejectTool('LOCAL_TOOLS_REQUIRED');if((clientToolsCapability||clientFunctionCapabilities)&&!registry.size)rejectTool('TOOL_CAPABILITY_REQUIRES_DECLARATIONS');
@@ -222,13 +223,15 @@ export function buildConsumerToolInitial({ userText, images = [], systemText, to
222
223
  if (!operationFeature && (!registry.size || !clientToolsFeature)) rejectTool('OPERATION_OMISSION_REQUIRES_CLIENT_TOOLS');
223
224
  if (halfCloseFeature && !operationFeature) rejectTool('HALF_CLOSE_REQUIRES_OPERATION_FEATURE');
224
225
  const metadata = { ...(clientMetadata ?? { clientType: 21, languageCode: 'en', interfaceLanguageCode: 'en', clientVersion: NATIVE_VERSION, clientInstanceId: crypto.randomUUID(), triggerType: 1, uiSource: 1 }), clientFunctionCapabilities };
225
- if (!Number.isSafeInteger(thinkingLevel) || thinkingLevel < 0 || thinkingLevel > 4) rejectTool('INVALID_THINKING_LEVEL');
226
+ const omitThinking = smartModelSelection && thinkingLevel === null;
227
+ if (!omitThinking && (!Number.isSafeInteger(thinkingLevel) || thinkingLevel < 0 || thinkingLevel > 4)) rejectTool('INVALID_THINKING_LEVEL');
226
228
  if (typeof temporaryChat !== 'boolean') rejectTool('INVALID_TEMPORARY_CHAT');
227
- const base = buildClientGenerate({ userText, images, systemText, identifiers, clientMetadata: metadata, temporaryChat });
229
+ const base = buildClientGenerate({ userText, images, systemText, identifiers, clientMetadata: metadata, temporaryChat, smartModelSelection });
228
230
  const desktopInfo = cat(...[...registry.values()].map(tool => m(2, tool.declaration)), ...(ownedDeviceId===undefined?[]:[s(6,ownedDeviceId)]), ...(clientToolsCapability ? [m(7, unsignedVarint(CLIENT_TOOLS_CAPABILITY))] : []));
229
- const requestedMode = modeCategory === undefined ? ARGON_MODE_CATEGORY : modeCategory;
230
- if (!Number.isSafeInteger(requestedMode) || requestedMode < 0 || requestedMode > 255) rejectTool('INVALID_MODE_CATEGORY');
231
- const template = cat(...parse(base).map(field => field.number === 15 ? v(15, registry.size || allowNativeTools ? 0 : 1) : field.raw), v(47, requestedMode), v(48, thinkingLevel), ...(agentChat ? [v(49, 1)] : []), ...(registry.size ? [m(51, cat(...(ownedDeviceId===undefined?[]:[s(1,ownedDeviceId)]),m(3, desktopInfo), ...(localSession ? [v(5, 1)] : [])))] : []));
231
+ const omitMode = smartModelSelection && (modeCategory === undefined || modeCategory === null);
232
+ const requestedMode = omitMode ? null : (modeCategory === undefined ? ARGON_MODE_CATEGORY : modeCategory);
233
+ 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)] : [])))] : []));
232
235
  if (continuation !== undefined && !Buffer.isBuffer(continuation)) rejectTool('INVALID_OWN_CONTINUATION');
233
236
  // Proven empty InitialRequest.ext1013 marker; NOT an outer update carrier or declaration list.
234
237
  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))] : []));
@@ -70,7 +70,8 @@ function imageAttachments(images) {
70
70
  * Model IDs and mode numbers are passed explicitly by caller policy.
71
71
  * Built-in tools, overage credits and smart model selection default off.
72
72
  */
73
- export function buildClientGenerate({ userText, images = [], systemText, modelId, identifiers, clientMetadata, includePolicyFlags = true, temporaryChat = false } = {}) {
73
+ export function buildClientGenerate({ userText, images = [], systemText, modelId, identifiers, clientMetadata, includePolicyFlags = true, temporaryChat = false, smartModelSelection = false } = {}) {
74
+ if (typeof smartModelSelection !== 'boolean') throw new TypeError('Invalid smart model selection');
74
75
  const fields = [message(1, Buffer.concat([string(1, userText), ...imageAttachments(images)]))];
75
76
  if (modelId !== undefined) fields.push(message(3, string(2, modelId)));
76
77
  if (identifiers !== undefined) {
@@ -86,7 +87,7 @@ export function buildClientGenerate({ userText, images = [], systemText, modelId
86
87
  if (systemText !== undefined) fields.push(message(29, string(4, systemText)));
87
88
  // Temporary chat keeps the turn out of the account's saved conversation history.
88
89
  if (temporaryChat) fields.push(varintField(31, 1));
89
- if (includePolicyFlags) fields.push(varintField(55, 0), varintField(56, 0));
90
+ if (includePolicyFlags) fields.push(varintField(55, 0), varintField(56, smartModelSelection ? 1 : 0));
90
91
  const output = Buffer.concat(fields);
91
92
  if (output.length > MAX_MESSAGE_BYTES) throw new RangeError('Message exceeds budget');
92
93
  return output;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
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": [
@@ -69,6 +69,7 @@
69
69
  "src/gateway/quota.mjs",
70
70
  "src/gateway/soft-error.mjs",
71
71
  "src/gateway/structured-output.mjs",
72
+ "src/gateway/subscription.mjs",
72
73
  "src/gateway/terms.mjs",
73
74
  "src/image-input.mjs",
74
75
  "src/image-url.mjs",
@@ -18,11 +18,15 @@ export function toolRecoveryInstruction(code) {
18
18
  }
19
19
  return null;
20
20
  }
21
- export function automaticRecoveryKind(error, model) {
21
+ export function automaticRecoveryKind(error, model, { allowAutoModel = false } = {}) {
22
22
  if (isExplicitQuotaFailure(error)) return 'quota';
23
- if (isVerifiedEmptyResponse(error, model)) return 'empty_response';
23
+ if (isVerifiedEmptyResponse(error, model, { allowAutoModel })) return 'empty_response';
24
+ const isAuto = allowAutoModel === true && model === 'gemini-auto';
24
25
  const expected = MODEL_MODES[model];
25
- if (expected === undefined) return null;
26
+ if (!isAuto && expected === undefined) return null;
27
+ const modeOk = mode => isAuto
28
+ ? (mode === null || mode === undefined || (Number.isSafeInteger(mode) && mode >= 0 && mode <= 64))
29
+ : mode === expected;
26
30
  const e = error?.nativeEvidence;
27
31
  if (error?.code === 'OAUTH_REFRESH_FAILED' && error?.status === 502) {
28
32
  if (!e) return 'transport';
@@ -34,8 +38,8 @@ export function automaticRecoveryKind(error, model) {
34
38
  return null;
35
39
  }
36
40
  if (!e || ![502, 503].includes(error?.status) || e.nativeRefusalPresent === true ||
37
- (e.fallback !== undefined && e.fallback !== 0) || (e.downgradeReason !== undefined && e.downgradeReason !== 0)) return null;
38
- if (e.observedMode !== null && e.observedMode !== undefined && e.observedMode !== 0 && e.observedMode !== expected) return null;
41
+ (!isAuto && ((e.fallback !== undefined && e.fallback !== 0) || (e.downgradeReason !== undefined && e.downgradeReason !== 0)))) return null;
42
+ if (!isAuto && e.observedMode !== null && e.observedMode !== undefined && e.observedMode !== 0 && e.observedMode !== expected) return null;
39
43
  if (error.code === 'NATIVE_UPSTREAM_UNAVAILABLE' && error.status === 503 &&
40
44
  ['open', 'read', 'decode', 'end'].includes(e.phase) &&
41
45
  ((e.upstreamHttpStatus === 503 && (e.grpcStatus === null || e.grpcStatus === 0 || e.grpcStatus === 14)) ||
@@ -46,14 +50,14 @@ export function automaticRecoveryKind(error, model) {
46
50
  if (TRANSPORT_ERRORS.has(error.code) && ['open', 'read', 'decode', 'end'].includes(e.phase) &&
47
51
  (e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) && (e.grpcStatus === null || e.grpcStatus === 0)) return 'transport';
48
52
  const completed = e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 && e.wireEnded === true &&
49
- e.modelCompleted === true && e.observedMode === expected && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
53
+ e.modelCompleted === true && modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
50
54
  if (completed && error.code === 'NATIVE_SOFT_ERROR_RESPONSE' && e.outputFailureReason === 'generic_error_offer' &&
51
55
  e.outputFailureSource === 'exact_text_signature' && e.outputToolCalls === 0 && e.nativeStructuredOutputPresent === false) return 'provider_soft_error';
52
56
  if (completed && TOOL_ERRORS.has(error.code)) return 'tool_protocol';
53
57
  if (completed && STRUCTURED_OUTPUT_ERRORS.has(error.code)) return 'structured_output';
54
58
  // A clean but incomplete turn may be regenerated; never treat it as success.
55
59
  if (error.code === 'INCOMPLETE_NATIVE_RESPONSE' && e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 &&
56
- e.wireEnded === true && e.observedMode === expected && e.nativeRefusalPresent === false &&
60
+ e.wireEnded === true && modeOk(e.observedMode) && e.nativeRefusalPresent === false &&
57
61
  e.nativeStructuredOutputPresent === false && e.nativeShareableTextBytes === 0 && e.http2ResetCode === undefined) return 'incomplete_response';
58
62
  return null;
59
63
  }
@@ -44,6 +44,7 @@ export function openDirectTurn(
44
44
  images = [],
45
45
  modeCategory = 8,
46
46
  thinkingLevel = 2,
47
+ smartModelSelection = false,
47
48
  temporaryChat = true,
48
49
  continuation,
49
50
  timeoutMs = 180000,
@@ -79,6 +80,7 @@ export function openDirectTurn(
79
80
  images,
80
81
  modeCategory,
81
82
  thinkingLevel,
83
+ smartModelSelection,
82
84
  temporaryChat,
83
85
  continuation,
84
86
  allowNativeTools,
@@ -28,16 +28,20 @@ export function inspectNativeOutput(fields) {
28
28
  nativeStructuredOutputPresent: structured, nativeRefusalPresent: refusal,
29
29
  ...(Number.isSafeInteger(completenessState) && completenessState >= 0 && completenessState <= 0x7fffffff ? { nativeCompletenessState: completenessState } : {}) };
30
30
  }
31
- export function isVerifiedEmptyResponse(error, model) {
31
+ export function isVerifiedEmptyResponse(error, model, { allowAutoModel = false } = {}) {
32
32
  const e = error?.nativeEvidence;
33
+ const isAuto = allowAutoModel === true && model === 'gemini-auto';
34
+ const modeOk = isAuto
35
+ ? (e?.observedMode === null || e?.observedMode === undefined || (Number.isSafeInteger(e.observedMode) && e.observedMode >= 0 && e.observedMode <= 64))
36
+ : (MODEL_MODES[model] !== undefined && e?.observedMode === MODEL_MODES[model]);
33
37
  return error?.status === 502 && error.code === 'EMPTY_NATIVE_RESPONSE' &&
34
38
  e?.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 &&
35
- e.wireEnded === true && e.modelCompleted === true && e.observedMode === MODEL_MODES[model] && MODEL_MODES[model] !== undefined &&
39
+ e.wireEnded === true && e.modelCompleted === true && modeOk &&
36
40
  ['no_text', 'whitespace_only', 'thoughts_only'].includes(e.emptyResponseReason) &&
37
41
  Number.isSafeInteger(e.nativeTextBytes) && e.nativeTextBytes >= 0 && e.nativeTextBytes <= 8 * 1024 * 1024 &&
38
42
  (e.emptyResponseReason === 'whitespace_only' ? e.nativeTextBytes > 0 : e.nativeTextBytes === 0) &&
39
43
  typeof e.nativeThoughtsPresent === 'boolean' && (e.emptyResponseReason !== 'thoughts_only' || e.nativeThoughtsPresent === true) &&
40
44
  e.nativeShareableTextBytes === 0 && e.nativeStructuredOutputPresent === false && e.nativeRefusalPresent === false &&
41
- e.http2ResetCode === undefined && (e.fallback === undefined || e.fallback === 0) &&
42
- (e.downgradeReason === undefined || e.downgradeReason === 0);
45
+ e.http2ResetCode === undefined &&
46
+ (isAuto || ((e.fallback === undefined || e.fallback === 0) && (e.downgradeReason === undefined || e.downgradeReason === 0)));
43
47
  }
@@ -0,0 +1,51 @@
1
+ // GetUsageInfo.user_tier=2 uses the native UserSubscriptionTier enum.
2
+ // Verified from SwiftProtobuf name-map/type metadata and an existing upstream payload.
3
+ import { parse } from '../../native-wire/protobuf.mjs';
4
+ import { fault } from './oauth-client-defaults.mjs';
5
+ export const SUBSCRIPTION_FIELDS = Object.freeze({ nativeTier: 2 });
6
+ const TIERS = Object.freeze({ 1: 'free', 2: 'pro', 3: 'ultra', 4: 'plus', 5: 'ultra_neon' });
7
+ const NAMES = Object.freeze({ 0: 'TIER_UNSPECIFIED', 1: 'BASIC_USER', 2: 'TIER1', 3: 'TIER2', 4: 'LITE_USER', 5: 'TIER_NEON' });
8
+ const CODES = new Set(['SUBSCRIPTION_CREDENTIAL_REQUIRED', 'INVALID_SUBSCRIPTION_TIMEOUT', 'INVALID_SUBSCRIPTION_METADATA',
9
+ 'SUBSCRIPTION_CANCELLED', 'SUBSCRIPTION_TIMEOUT', 'SUBSCRIPTION_STREAM_RESET', 'SUBSCRIPTION_RATE_LIMITED',
10
+ 'SUBSCRIPTION_AUTH_REJECTED', 'SUBSCRIPTION_HTTP_REJECTED', 'SUBSCRIPTION_INVALID_STATUS', 'SUBSCRIPTION_PRECONDITION_REQUIRED',
11
+ 'SUBSCRIPTION_UPSTREAM_REJECTED', 'SUBSCRIPTION_CONNECTION_FAILED', 'SUBSCRIPTION_RESPONSE_TOO_LARGE',
12
+ 'SUBSCRIPTION_INVALID_RESPONSE', 'SUBSCRIPTION_STREAM_FAILED', 'SUBSCRIPTION_STREAM_CLOSED_EARLY',
13
+ 'SUBSCRIPTION_INCOMPLETE_RESPONSE', 'SUBSCRIPTION_FETCH_FAILED', 'OAUTH_REFRESH_FAILED', 'NATIVE_PERMISSION_OR_AUTH',
14
+ 'ACCOUNT_LOGIN_REQUIRED']);
15
+ const integer = value => Number.isSafeInteger(value) && value >= 0 && value <= 0x7fffffff ? value : null;
16
+ const timestamp = value => {
17
+ if (typeof value !== 'string' || value.length > 40) return null;
18
+ const ms = Date.parse(value); return Number.isFinite(ms) && ms >= 0 ? new Date(ms).toISOString() : null;
19
+ };
20
+ export const subscriptionFailureCode = error => CODES.has(error?.code) ? error.code : 'SUBSCRIPTION_FETCH_FAILED';
21
+ // Established read-only unary GetUsageInfo request is empty. No client-supplied tier.
22
+ export const buildSubscriptionRequest = () => Buffer.alloc(0);
23
+ export function safeSubscription(input) {
24
+ const value = input && typeof input === 'object' && !Array.isArray(input) ? input : {};
25
+ const official = value.source === 'official' && value.provider === 'google-robin' && value.rpc === 'GetUsageInfo';
26
+ const nativeTier = official ? integer(value.nativeTier) : null, tier = TIERS[nativeTier] ?? 'unknown';
27
+ let status = ['unqueried', 'ok', 'missing', 'error'].includes(value.status) ? value.status : 'unqueried';
28
+ if (status === 'ok' && (!official || tier === 'unknown')) status = 'missing';
29
+ return { source: official ? 'official' : 'unknown', provider: official ? 'google-robin' : null, rpc: official ? 'GetUsageInfo' : null, status,
30
+ tier, nativeTier, nativeTierName: nativeTier === null ? null : NAMES[nativeTier] ?? 'UNRECOGNIZED',
31
+ // This RPC reports a tier, not billing/cancellation/forced-tier details.
32
+ nativeState: null, membershipStatus: 'unknown', isForced: null,
33
+ updatedAt: timestamp(value.updatedAt), lastAttemptAt: timestamp(value.lastAttemptAt),
34
+ errorCode: status === 'error' ? subscriptionFailureCode({ code: value.errorCode }) : null };
35
+ }
36
+ export function decodeSubscription(payload) {
37
+ try {
38
+ if (!Buffer.isBuffer(payload) || payload.length > 512 * 1024) throw Error();
39
+ const fields = parse(payload); if (fields.length > 10000) throw Error();
40
+ const found = fields.filter(field => field.number === 2);
41
+ if (found.length > 1 || (found.length && found[0].wire !== 0)) throw Error();
42
+ let nativeTier = null;
43
+ if (found.length) {
44
+ let value = 0n, shift = 0n;
45
+ for (const byte of found[0].payload) { value |= BigInt(byte & 127) << shift; shift += 7n; }
46
+ if (value > 0x7fffffffn) throw Error();
47
+ nativeTier = Number(value);
48
+ }
49
+ return safeSubscription({ source: 'official', provider: 'google-robin', rpc: 'GetUsageInfo', status: TIERS[nativeTier] ? 'ok' : 'missing', nativeTier });
50
+ } catch { throw fault('INVALID_SUBSCRIPTION_METADATA', 502); }
51
+ }
@@ -100,22 +100,25 @@ function safeFailure(error) {
100
100
 
101
101
 
102
102
  export class NativeDirectProvider {
103
- constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, timeoutMs = 600_000, modelAlias = 'gemini-argon', continuation = false, allowTextSnapshotReplacement = false } = {}) {
103
+ constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, timeoutMs = 600_000, modelAlias = 'gemini-argon', continuation = false, allowTextSnapshotReplacement = false, allowAutoModel = false } = {}) {
104
104
  if (!authManager || typeof authManager.getValidAccessToken !== 'function') throw new TypeError('authManager.getValidAccessToken required');
105
105
  if (typeof openTurn !== 'function') throw new TypeError('openTurn required');
106
106
  if (typeof uploadImages !== 'function') throw new TypeError('uploadImages required');
107
107
  if (typeof downloadImages !== 'function') throw new TypeError('downloadImages required');
108
108
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600_000) throw new TypeError('invalid timeout');
109
109
  if (continuation !== false) throw protocolError('UNSUPPORTED_CONTINUATION', 400);
110
- if (!NATIVE_MODELS.includes(modelAlias)) throw protocolError('UNSUPPORTED_MODEL', 400);
110
+ if (typeof allowAutoModel !== 'boolean') throw new TypeError('invalid auto model policy');
111
+ const allowedModels = allowAutoModel ? [...NATIVE_MODELS, 'gemini-auto'] : NATIVE_MODELS;
112
+ if (!allowedModels.includes(modelAlias)) throw protocolError('UNSUPPORTED_MODEL', 400);
111
113
  this.authManager = authManager; this.openTurn = openTurn; this.uploadImages = uploadImages; this.timeoutMs = timeoutMs;
112
114
  this.downloadImages = downloadImages;
113
115
  if (typeof allowTextSnapshotReplacement !== 'boolean') throw new TypeError('invalid snapshot policy');
114
116
  this.allowTextSnapshotReplacement = allowTextSnapshotReplacement;
117
+ this.allowAutoModel = allowAutoModel;
115
118
  this.modelAlias = modelAlias; this.continuationEnabled = false;
116
119
  }
117
120
 
118
- buildTurn(body) { return buildCanonicalPrompt(normalizeChatRequest(body)); }
121
+ buildTurn(body) { return buildCanonicalPrompt(normalizeChatRequest(body, { allowAutoModel: this.allowAutoModel })); }
119
122
 
120
123
  async runNativeSearch(accountId, body, onDelta, context) {
121
124
  const timeoutMs = context.timeoutMs ?? this.timeoutMs;
@@ -173,14 +176,18 @@ export class NativeDirectProvider {
173
176
  async runTurn(accountId, canonicalChatBody, onDelta = () => {}, context = {}) {
174
177
  const timeoutMs = context.timeoutMs ?? this.timeoutMs;
175
178
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600000) fail('INVALID_TIMEOUT', 400);
176
- const body = normalizeChatRequest(canonicalChatBody);
179
+ const body = normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
177
180
  if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
178
181
  const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode);
179
182
  if (recoveryInstruction) body.messages = [...body.messages, { role: 'system', content: recoveryInstruction }];
180
183
  if (this.allowTextSnapshotReplacement && body.tools.length) fail('NATIVE_TEXT_SNAPSHOT_TOOLS_FORBIDDEN', 400);
181
184
  const policy = compileToolPolicy(body.tools, body.tool_choice);
182
185
  let { messages, images } = buildCanonicalPrompt(body);
183
- const modeCategory = MODEL_MODES[body.model];
186
+ const isAutoModel = this.allowAutoModel && body.model === 'gemini-auto';
187
+ const modeCategory = isAutoModel ? null : MODEL_MODES[body.model];
188
+ const modeMatches = mode => isAutoModel
189
+ ? (mode === null || (Number.isSafeInteger(mode) && mode >= 0 && mode <= 64))
190
+ : mode === modeCategory;
184
191
  if (context.signal?.aborted) fail('NATIVE_TURN_ABORTED', 499);
185
192
  const controller = new AbortController();
186
193
  const note = (name, values) => observeNative(context.nativeDiagnostic, 'event', name, values);
@@ -267,7 +274,11 @@ export class NativeDirectProvider {
267
274
  if (controller.signal.aborted) await deadline;
268
275
  // The product injects its independent transport; historical research ledgers are untouched.
269
276
  phase = 'open';
270
- turn = this.openTurn(token, { messages, images: attachments, temporaryChat: true, modeCategory, thinkingLevel: body.thinking_level, timeoutMs, signal: controller.signal,
277
+ turn = this.openTurn(token, { messages, images: attachments, temporaryChat: true,
278
+ modeCategory: isAutoModel ? null : modeCategory,
279
+ thinkingLevel: isAutoModel ? null : body.thinking_level,
280
+ ...(isAutoModel ? { smartModelSelection: true } : {}),
281
+ timeoutMs, signal: controller.signal,
271
282
  emitHeaders: incremental,
272
283
  ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
273
284
  iterator = turn.events[Symbol.asyncIterator]();
@@ -305,10 +316,12 @@ export class NativeDirectProvider {
305
316
  observedAttribution = info.attribution;
306
317
  if (requiresHydrogen && !HYDROGEN_ATTRIBUTION.test(info.attribution)) downgrade = true;
307
318
  }
308
- // Final generate evidence must name the requested mode. Prior proven
309
- // rejection is sticky; an unresolved zero is not a proven downgrade.
310
- if (observedMode !== null && observedMode !== 0 && observedMode !== modeCategory) downgrade = true;
311
- if (info.fallback === 1 || (info.downgradeReason !== null && info.downgradeReason !== undefined && info.downgradeReason !== 0)) downgrade = true;
319
+ // Final generate evidence must name the requested mode unless auto selection is enabled.
320
+ // Prior proven rejection is sticky; an unresolved zero is not a proven downgrade.
321
+ if (!isAutoModel) {
322
+ if (observedMode !== null && observedMode !== 0 && observedMode !== modeCategory) downgrade = true;
323
+ if (info.fallback === 1 || (info.downgradeReason !== null && info.downgradeReason !== undefined && info.downgradeReason !== 0)) downgrade = true;
324
+ }
312
325
  if (info.thinkingLevel !== null && info.thinkingLevel !== undefined) {
313
326
  if (!Number.isSafeInteger(info.thinkingLevel) || info.thinkingLevel < 0 || info.thinkingLevel > 4) fail('INVALID_NATIVE_THINKING_LEVEL');
314
327
  observedThinking = info.thinkingLevel;
@@ -350,7 +363,7 @@ export class NativeDirectProvider {
350
363
  } else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
351
364
  fail('INVALID_NATIVE_RESPONSE');
352
365
  }
353
- if (incremental && observedMode === modeCategory && attributionVerified() && liveSyncedLength < rawText.length) {
366
+ if (incremental && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
354
367
  const delta = rawText.slice(liveSyncedLength);
355
368
  liveSyncedLength = rawText.length;
356
369
  await publish(liveSplitter.push(delta));
@@ -378,7 +391,7 @@ export class NativeDirectProvider {
378
391
  // must be non-retryable or PI will repeatedly submit fresh generations.
379
392
  if (/^\s*I'm on it\.\s*Responses with Deep Think can take some time, so check back in a bit\.\s*https?:\/\/googleusercontent\.com\/agentic_processing_chip\/\d+\s*$/i.test(rawText)) fail('NATIVE_ASYNC_RESPONSE_UNSUPPORTED', 422);
380
393
  if (!modelComplete) fail('INCOMPLETE_NATIVE_RESPONSE');
381
- if (observedMode !== modeCategory) fail('MISSING_NATIVE_MODE_EVIDENCE');
394
+ if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
382
395
  if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
383
396
  if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
384
397
  if (!rawText.trim()) {
@@ -431,7 +444,7 @@ export class NativeDirectProvider {
431
444
  note('provider_success');
432
445
  return result;
433
446
  } catch (error) {
434
- const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && observedMode === modeCategory && attributionVerified();
447
+ const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
435
448
  if (incremental && modeVerified && !sinkFailed) {
436
449
  try { await publish(liveSplitter.flush()); }
437
450
  catch { /* Retain already-published text; never release an invalid/incomplete tool body. */ }
@@ -166,11 +166,12 @@ function content(value, { assistant = false, responses = false, user = false, pr
166
166
  });
167
167
  return parts.some(part => part.type === 'image_url') ? parts : parts.map(part => part.text).join('');
168
168
  }
169
- function settings(body) {
169
+ function settings(body, { allowAutoModel = false } = {}) {
170
170
  const model = body.model === undefined ? 'gemini-argon' : body.model;
171
171
  if (typeof model !== 'string') fail('UNSUPPORTED_MODEL', 400, 'model');
172
172
  const alias = model.startsWith('models/') ? model.slice(7) : model;
173
- if (!NATIVE_MODELS.includes(alias)) fail('UNSUPPORTED_MODEL', 400, 'model');
173
+ const allowedModels = allowAutoModel ? [...NATIVE_MODELS, 'gemini-auto'] : NATIVE_MODELS;
174
+ if (!allowedModels.includes(alias)) fail('UNSUPPORTED_MODEL', 400, 'model');
174
175
  const thinking = thinkingSettings(body);
175
176
  if (body.stream !== undefined && typeof body.stream !== 'boolean') fail('INVALID_STREAM', 400, 'stream');
176
177
  if (body.native_search !== undefined && typeof body.native_search !== 'boolean') fail('INVALID_NATIVE_SEARCH', 400, 'native_search');
@@ -308,12 +309,12 @@ function validateInertOpenAIFields(payload, { responses = false } = {}) {
308
309
  }
309
310
  }
310
311
 
311
- export function normalizeChatRequest(payload) {
312
+ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
312
313
  keys(payload, ['model', 'messages', 'tools', 'tool_choice', 'thinking_level', 'reasoning_effort', 'stream', 'stream_options', 'store', 'parallel_tool_calls', 'reasoning', 'include', 'prompt_cache_key', 'client_metadata', 'native_search', 'max_tokens', 'max_completion_tokens', 'temperature', 'top_p', 'presence_penalty', 'frequency_penalty', 'seed', 'logprobs', 'top_logprobs', 'response_format', 'user', 'metadata', 'stop', 'n', 'service_tier', 'logit_bias', 'verbosity', 'modalities']);
313
314
  requestBudget(payload);
314
315
  validateInertOpenAIFields(payload);
315
316
  const compat = compatibility(payload);
316
- const resolved = settings(payload);
317
+ const resolved = settings(payload, { allowAutoModel });
317
318
  const response_format = normalizeChatResponseFormat(payload.response_format);
318
319
  if (resolved.native_search) {
319
320
  if (resolved.model !== 'gemini-argon' || resolved.thinking_level !== 2) fail('UNSUPPORTED_NATIVE_SEARCH_MODE');
@@ -381,12 +382,12 @@ export function normalizeChatRequest(payload) {
381
382
  return body;
382
383
  }
383
384
 
384
- export function normalizeResponsesRequest(payload) {
385
+ export function normalizeResponsesRequest(payload, { allowAutoModel = false } = {}) {
385
386
  keys(payload, ['model', 'input', 'instructions', 'tools', 'tool_choice', 'thinking_level', 'reasoning_effort', 'stream', 'store', 'parallel_tool_calls', 'reasoning', 'include', 'prompt_cache_key', 'client_metadata', 'native_search', 'temperature', 'top_p', 'max_output_tokens', 'text', 'user', 'metadata', 'service_tier', 'truncation']);
386
387
  requestBudget(payload);
387
388
  validateInertOpenAIFields(payload, { responses: true });
388
389
  const compat = compatibility(payload, true);
389
- const resolved = settings(payload);
390
+ const resolved = settings(payload, { allowAutoModel });
390
391
  const response_format = normalizeResponsesText(payload.text);
391
392
  const messages = [];
392
393
  if (payload.instructions !== undefined && payload.instructions !== null) messages.push({ role: 'system', content: text(payload.instructions) });
@@ -421,7 +422,7 @@ export function normalizeResponsesRequest(payload) {
421
422
  }
422
423
  }
423
424
  const { include: _include, ...inertCompat } = compat;
424
- const body = normalizeChatRequest({ ...resolved, ...inertCompat, ...(response_format ? { response_format } : {}), messages, tools, tool_choice: choice, [RESPONSE_TOOL_IDENTITIES]: identities });
425
+ const body = normalizeChatRequest({ ...resolved, ...inertCompat, ...(response_format ? { response_format } : {}), messages, tools, tool_choice: choice, [RESPONSE_TOOL_IDENTITIES]: identities }, { allowAutoModel });
425
426
  const projected = collectImageInputs(body.messages).messages;
426
427
  return {
427
428
  body,