pi-gemini-app 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # `pi-gemini-app` — Google Gemini App Provider for Pi
2
2
 
3
- Native in-process provider extension for `@earendil-works/pi-coding-agent` (`pi`). Connects directly to Gemini's native HTTP/2 endpoint (`ProcessQuery`) inside the Pi process—no separate HTTP gateway server, Docker container, or extra npm runtime dependencies required.
3
+ Native in-process provider extension for `@earendil-works/pi-coding-agent` (`pi`) and GooeyPi. Connects directly to Gemini's native HTTP/2 endpoint (`ProcessQuery`) inside the Pi process—no separate HTTP gateway server, Docker container, or extra npm runtime dependencies required.
4
4
 
5
5
  > **Disclaimer**: Unofficial interoperability software. Not affiliated with, endorsed by, or sponsored by Google. You must authenticate personally with your own eligible Google account.
6
6
 
@@ -36,7 +36,7 @@ Or add the extension path to your Pi settings (`~/.pi/agent/settings.json`):
36
36
 
37
37
  ## Architecture & When to Choose `pi-gemini-app` vs `gemini-app2api`
38
38
 
39
- - **In-Process Direct HTTP/2 (`pi-gemini-app`)**: Runs completely inside Pi using Node.js built-ins (`node:http2`, `node:crypto`). Ideal for single-user Pi terminal sessions with zero background daemons or Docker containers.
39
+ - **In-Process Direct HTTP/2 (`pi-gemini-app`)**: Runs completely inside Pi / GooeyPi using Node.js built-ins (`node:http2`, `node:crypto`). Ideal for single-user Pi / GooeyPi terminal sessions with zero background daemons or Docker containers.
40
40
  - **Full Standalone Gateway (`gemini-app2api`)**: Use the [main repository](https://github.com/ShawTim/gemini-app2api) if you need multi-account quota pooling/failover, OpenAI-compatible `/v1/chat/completions` & `/v1/responses` endpoints for Cursor/Cline/Codex CLI, or the `/admin` web operations console.
41
41
 
42
42
  ## Authentication (`/login gemini-app`)
@@ -65,19 +65,22 @@ Optional environment overrides if using your own OAuth desktop client:
65
65
 
66
66
  | Model ID | Display Name | Context Window | Max Output | Capabilities |
67
67
  | :--- | :--- | ---: | ---: | :--- |
68
- | `gemini-argon` | Gemini Argon | 128,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
68
+ | `gemini-neon` | Gemini Neon | 128,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`); `gemini-argon` temporarily aliases here |
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
 
72
- > **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
+ > **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
+ >
75
+ > **Quota Tip**: `gemini-hydrogen` consumes significantly less rolling window quota than flagship Pro-tier modes (`gemini-neon`) and responds faster, making it ideal for multi-step coding and tool-calling loops. Reserve `gemini-neon` 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 Neon/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,15 +2,33 @@ 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
- id: 'gemini-argon',
13
- name: 'Gemini Argon',
30
+ id: 'gemini-neon',
31
+ name: 'Gemini Neon',
14
32
  api: API_ID,
15
33
  provider: PROVIDER_ID,
16
34
  baseUrl: BASE_URL,
@@ -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,15 +1,17 @@
1
1
  {
2
2
  "name": "pi-gemini-app",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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": [
7
7
  "pi-package",
8
8
  "pi-extension",
9
9
  "pi-coding-agent",
10
+ "gooeypi",
10
11
  "gemini",
11
- "gemini-argon",
12
+ "gemini-neon",
12
13
  "gemini-hydrogen",
14
+ "gemini-auto",
13
15
  "provider",
14
16
  "oauth"
15
17
  ],
@@ -69,6 +71,7 @@
69
71
  "src/gateway/quota.mjs",
70
72
  "src/gateway/soft-error.mjs",
71
73
  "src/gateway/structured-output.mjs",
74
+ "src/gateway/subscription.mjs",
72
75
  "src/gateway/terms.mjs",
73
76
  "src/image-input.mjs",
74
77
  "src/image-url.mjs",
@@ -1,5 +1,5 @@
1
1
  // Request-scoped bounded recovery; never repair/execute an invalid tool call.
2
- import { MODEL_MODES } from '../openai-contract.mjs';
2
+ import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
3
3
  import { isVerifiedEmptyResponse } from './output-recovery.mjs';
4
4
  import { isExplicitQuotaFailure } from './quota-failover.mjs';
5
5
  const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON', 'TRUNCATED_TOOL_CALL', 'INVALID_TOOL_CALL',
@@ -18,11 +18,16 @@ 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
+ const resolvedModel = canonicalModel(model);
22
23
  if (isExplicitQuotaFailure(error)) return 'quota';
23
- if (isVerifiedEmptyResponse(error, model)) return 'empty_response';
24
- const expected = MODEL_MODES[model];
25
- if (expected === undefined) return null;
24
+ if (isVerifiedEmptyResponse(error, resolvedModel, { allowAutoModel })) return 'empty_response';
25
+ const isAuto = allowAutoModel === true && resolvedModel === 'gemini-auto';
26
+ const expected = MODEL_MODES[resolvedModel];
27
+ if (!isAuto && expected === undefined) return null;
28
+ const modeOk = mode => isAuto
29
+ ? (mode === null || mode === undefined || (Number.isSafeInteger(mode) && mode >= 0 && mode <= 64))
30
+ : mode === expected;
26
31
  const e = error?.nativeEvidence;
27
32
  if (error?.code === 'OAUTH_REFRESH_FAILED' && error?.status === 502) {
28
33
  if (!e) return 'transport';
@@ -34,8 +39,8 @@ export function automaticRecoveryKind(error, model) {
34
39
  return null;
35
40
  }
36
41
  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;
42
+ (!isAuto && ((e.fallback !== undefined && e.fallback !== 0) || (e.downgradeReason !== undefined && e.downgradeReason !== 0)))) return null;
43
+ if (!isAuto && e.observedMode !== null && e.observedMode !== undefined && e.observedMode !== 0 && e.observedMode !== expected) return null;
39
44
  if (error.code === 'NATIVE_UPSTREAM_UNAVAILABLE' && error.status === 503 &&
40
45
  ['open', 'read', 'decode', 'end'].includes(e.phase) &&
41
46
  ((e.upstreamHttpStatus === 503 && (e.grpcStatus === null || e.grpcStatus === 0 || e.grpcStatus === 14)) ||
@@ -46,14 +51,14 @@ export function automaticRecoveryKind(error, model) {
46
51
  if (TRANSPORT_ERRORS.has(error.code) && ['open', 'read', 'decode', 'end'].includes(e.phase) &&
47
52
  (e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) && (e.grpcStatus === null || e.grpcStatus === 0)) return 'transport';
48
53
  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;
54
+ e.modelCompleted === true && modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
50
55
  if (completed && error.code === 'NATIVE_SOFT_ERROR_RESPONSE' && e.outputFailureReason === 'generic_error_offer' &&
51
56
  e.outputFailureSource === 'exact_text_signature' && e.outputToolCalls === 0 && e.nativeStructuredOutputPresent === false) return 'provider_soft_error';
52
57
  if (completed && TOOL_ERRORS.has(error.code)) return 'tool_protocol';
53
58
  if (completed && STRUCTURED_OUTPUT_ERRORS.has(error.code)) return 'structured_output';
54
59
  // A clean but incomplete turn may be regenerated; never treat it as success.
55
60
  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 &&
61
+ e.wireEnded === true && modeOk(e.observedMode) && e.nativeRefusalPresent === false &&
57
62
  e.nativeStructuredOutputPresent === false && e.nativeShareableTextBytes === 0 && e.http2ResetCode === undefined) return 'incomplete_response';
58
63
  return null;
59
64
  }
@@ -54,7 +54,7 @@ export function safeAccountError(value) {
54
54
  typeof value.code === "string" && /^[A-Z0-9_]{1,80}$/.test(value.code)
55
55
  ? value.code
56
56
  : "NATIVE_TURN_FAILED",
57
- ...(NATIVE_MODELS.includes(value.model) || value.model === "gemini-flash"
57
+ ...(NATIVE_MODELS.includes(value.model) || value.model === "gemini-argon" || value.model === "gemini-flash"
58
58
  ? { model: value.model }
59
59
  : {}),
60
60
  nativeEvidence,
@@ -220,20 +220,20 @@ export async function runNativeSearchDiagnostic({
220
220
  const result = await provider.runTurn(
221
221
  "diagnostic",
222
222
  {
223
- model: "gemini-argon",
223
+ model: "gemini-neon",
224
224
  messages: [{ role: "user", content: query }],
225
225
  thinking_level: 2,
226
226
  },
227
227
  () => {},
228
228
  { signal },
229
229
  );
230
- if (result.resolvedModeCategory !== 8 || result.thinkingLevel !== 2)
230
+ if (result.resolvedModeCategory !== 3 || result.thinkingLevel !== 2)
231
231
  return fail("NATIVE_THINKING_MISMATCH");
232
232
  return {
233
233
  ok: true,
234
234
  answer: result.content,
235
235
  query,
236
- requestedModel: "gemini-argon",
236
+ requestedModel: "gemini-neon",
237
237
  revisionCount: result.revisionCount,
238
238
  resolvedModeCategory: result.resolvedModeCategory,
239
239
  requestedThinkingLevel: 2,
@@ -42,8 +42,9 @@ export function openDirectTurn(
42
42
  {
43
43
  messages,
44
44
  images = [],
45
- modeCategory = 8,
45
+ modeCategory = 3,
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,
@@ -1,6 +1,6 @@
1
1
  // Only a fully completed, verified empty ordinary turn is recoverable automatically.
2
2
  // Never promote thoughts/shareable/structured output to an assistant answer.
3
- import { MODEL_MODES } from '../openai-contract.mjs';
3
+ 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']);
@@ -28,16 +28,21 @@ 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
+ const resolvedModel = canonicalModel(model);
32
33
  const e = error?.nativeEvidence;
34
+ const isAuto = allowAutoModel === true && resolvedModel === 'gemini-auto';
35
+ const modeOk = isAuto
36
+ ? (e?.observedMode === null || e?.observedMode === undefined || (Number.isSafeInteger(e.observedMode) && e.observedMode >= 0 && e.observedMode <= 64))
37
+ : (MODEL_MODES[resolvedModel] !== undefined && e?.observedMode === MODEL_MODES[resolvedModel]);
33
38
  return error?.status === 502 && error.code === 'EMPTY_NATIVE_RESPONSE' &&
34
39
  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 &&
40
+ e.wireEnded === true && e.modelCompleted === true && modeOk &&
36
41
  ['no_text', 'whitespace_only', 'thoughts_only'].includes(e.emptyResponseReason) &&
37
42
  Number.isSafeInteger(e.nativeTextBytes) && e.nativeTextBytes >= 0 && e.nativeTextBytes <= 8 * 1024 * 1024 &&
38
43
  (e.emptyResponseReason === 'whitespace_only' ? e.nativeTextBytes > 0 : e.nativeTextBytes === 0) &&
39
44
  typeof e.nativeThoughtsPresent === 'boolean' && (e.emptyResponseReason !== 'thoughts_only' || e.nativeThoughtsPresent === true) &&
40
45
  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);
46
+ e.http2ResetCode === undefined &&
47
+ (isAuto || ((e.fallback === undefined || e.fallback === 0) && (e.downgradeReason === undefined || e.downgradeReason === 0)));
43
48
  }
@@ -162,7 +162,7 @@ export function safeQuota(value) {
162
162
  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
163
  })) : [];
164
164
  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-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 } : {}) };
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 } : {}) };
166
166
  }
167
167
  export function quotaFailureCode(error) { return SAFE_ERRORS.has(error?.code) ? error.code : "QUOTA_REFRESH_FAILED"; }
168
168
 
@@ -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
+ }
@@ -7,7 +7,7 @@ import crypto from 'node:crypto';
7
7
  import { parse } from '../native-wire/protobuf.mjs';
8
8
  import { decodeClientGenerateResponse } from '../native-wire/robin-current.mjs';
9
9
  import { ProtocolError, protocolError, compileToolPolicy, createToolCallSplitter, validateToolCompletion } from './tool-protocol.mjs';
10
- import { MODEL_MODES, NATIVE_MODELS, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
10
+ import { MODEL_ALIASES, MODEL_MODES, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
11
11
  import { RESPONSE_TOOL_IDENTITIES } from './responses-tool-namespaces.mjs';
12
12
  import { safeNativeEvidence } from './gateway/native-evidence.mjs';
13
13
  import { decodePassiveQuota, mergeQuotaObservation } from './gateway/quota.mjs';
@@ -20,7 +20,7 @@ import { validateStructuredOutputText } from './gateway/structured-output.mjs';
20
20
  import { mapNativeSearchAnnotations, extractNativeSearchSources } from './gateway/native-search-citations.mjs';
21
21
  import { softErrorReason } from './gateway/soft-error.mjs';
22
22
  import { observeNative } from './gateway/native-diagnostic.mjs';
23
- export { NATIVE_MODELS, normalizeChatRequest, normalizeResponsesRequest, writeChatResponse, writeResponsesResponse };
23
+ export { MODEL_ALIASES, NATIVE_MODELS, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, writeChatResponse, writeResponsesResponse };
24
24
 
25
25
  import { NATIVE_RESPONSE_LIMITS as RESPONSE_LIMITS } from './gateway/native-response-limits.mjs';
26
26
  const fail = (code, status = 502) => { throw protocolError(code, status); };
@@ -37,6 +37,7 @@ const failWithEvidence = (code, evidence) => {
37
37
  };
38
38
  const utf8 = new TextDecoder('utf-8', { fatal: true });
39
39
  const HYDROGEN_ATTRIBUTION = /\bhydrogen\b/i;
40
+ const NEON_ATTRIBUTION = /\bneon\b/i;
40
41
  function one(fields, number) {
41
42
  const found = fields.filter(field => field.number === number);
42
43
  if (found.length > 1) fail('INVALID_NATIVE_RESPONSE');
@@ -100,22 +101,26 @@ function safeFailure(error) {
100
101
 
101
102
 
102
103
  export class NativeDirectProvider {
103
- constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, timeoutMs = 600_000, modelAlias = 'gemini-argon', continuation = false, allowTextSnapshotReplacement = false } = {}) {
104
+ constructor(authManager, { openTurn, uploadImages = uploadNativeImages, downloadImages = downloadRemoteImages, timeoutMs = 600_000, modelAlias = 'gemini-neon', continuation = false, allowTextSnapshotReplacement = false, allowAutoModel = false } = {}) {
104
105
  if (!authManager || typeof authManager.getValidAccessToken !== 'function') throw new TypeError('authManager.getValidAccessToken required');
105
106
  if (typeof openTurn !== 'function') throw new TypeError('openTurn required');
106
107
  if (typeof uploadImages !== 'function') throw new TypeError('uploadImages required');
107
108
  if (typeof downloadImages !== 'function') throw new TypeError('downloadImages required');
108
109
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600_000) throw new TypeError('invalid timeout');
109
110
  if (continuation !== false) throw protocolError('UNSUPPORTED_CONTINUATION', 400);
110
- if (!NATIVE_MODELS.includes(modelAlias)) throw protocolError('UNSUPPORTED_MODEL', 400);
111
+ if (typeof allowAutoModel !== 'boolean') throw new TypeError('invalid auto model policy');
112
+ const resolvedAlias = canonicalModel(modelAlias);
113
+ const allowedModels = allowAutoModel ? [...NATIVE_MODELS, 'gemini-auto'] : NATIVE_MODELS;
114
+ if (!allowedModels.includes(resolvedAlias)) throw protocolError('UNSUPPORTED_MODEL', 400);
111
115
  this.authManager = authManager; this.openTurn = openTurn; this.uploadImages = uploadImages; this.timeoutMs = timeoutMs;
112
116
  this.downloadImages = downloadImages;
113
117
  if (typeof allowTextSnapshotReplacement !== 'boolean') throw new TypeError('invalid snapshot policy');
114
118
  this.allowTextSnapshotReplacement = allowTextSnapshotReplacement;
115
- this.modelAlias = modelAlias; this.continuationEnabled = false;
119
+ this.allowAutoModel = allowAutoModel;
120
+ this.modelAlias = resolvedAlias; this.continuationEnabled = false;
116
121
  }
117
122
 
118
- buildTurn(body) { return buildCanonicalPrompt(normalizeChatRequest(body)); }
123
+ buildTurn(body) { return buildCanonicalPrompt(normalizeChatRequest(body, { allowAutoModel: this.allowAutoModel })); }
119
124
 
120
125
  async runNativeSearch(accountId, body, onDelta, context) {
121
126
  const timeoutMs = context.timeoutMs ?? this.timeoutMs;
@@ -173,14 +178,18 @@ export class NativeDirectProvider {
173
178
  async runTurn(accountId, canonicalChatBody, onDelta = () => {}, context = {}) {
174
179
  const timeoutMs = context.timeoutMs ?? this.timeoutMs;
175
180
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 600000) fail('INVALID_TIMEOUT', 400);
176
- const body = normalizeChatRequest(canonicalChatBody);
181
+ const body = normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
177
182
  if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
178
183
  const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode);
179
184
  if (recoveryInstruction) body.messages = [...body.messages, { role: 'system', content: recoveryInstruction }];
180
185
  if (this.allowTextSnapshotReplacement && body.tools.length) fail('NATIVE_TEXT_SNAPSHOT_TOOLS_FORBIDDEN', 400);
181
186
  const policy = compileToolPolicy(body.tools, body.tool_choice);
182
187
  let { messages, images } = buildCanonicalPrompt(body);
183
- const modeCategory = MODEL_MODES[body.model];
188
+ const isAutoModel = this.allowAutoModel && body.model === 'gemini-auto';
189
+ const modeCategory = isAutoModel ? null : MODEL_MODES[body.model];
190
+ const modeMatches = mode => isAutoModel
191
+ ? (mode === null || (Number.isSafeInteger(mode) && mode >= 0 && mode <= 64))
192
+ : mode === modeCategory;
184
193
  if (context.signal?.aborted) fail('NATIVE_TURN_ABORTED', 499);
185
194
  const controller = new AbortController();
186
195
  const note = (name, values) => observeNative(context.nativeDiagnostic, 'event', name, values);
@@ -198,10 +207,12 @@ export class NativeDirectProvider {
198
207
  timer = setTimeout(() => stop(protocolError('NATIVE_TURN_TIMEOUT', 504)), timeoutMs);
199
208
  const bounded = promise => Promise.race([promise, deadline]);
200
209
  const requiresHydrogen = body.model === 'gemini-hydrogen';
210
+ const requiresNeon = body.model === 'gemini-neon';
201
211
  let rawText = '', frames = 0, received = 0, observedMode = null, observedThinking = null;
202
212
  let modelComplete = false, ended = false, grpc = null, httpStatus = null, downgrade = false, phase = 'auth';
203
213
  let observedFallback = null, downgradeReason = null, observedAttribution = null;
204
- const attributionVerified = () => !requiresHydrogen || HYDROGEN_ATTRIBUTION.test(observedAttribution ?? '');
214
+ const attributionMatches = value => (!requiresHydrogen || HYDROGEN_ATTRIBUTION.test(value ?? '')) && (!requiresNeon || NEON_ATTRIBUTION.test(value ?? ''));
215
+ const attributionVerified = () => attributionMatches(observedAttribution);
205
216
  let snapshotId = null, revisionCount = 0, quotaObservation = null, quotaFrames = 0;
206
217
  let emptyResponseReason = null, outputObserved = false, responseLimitReason = null, outputFailureReason = null;
207
218
  const outputShape = { nativeShareableTextBytes: 0, nativeThoughtsPresent: false, nativeStructuredOutputPresent: false, nativeRefusalPresent: false };
@@ -267,7 +278,11 @@ export class NativeDirectProvider {
267
278
  if (controller.signal.aborted) await deadline;
268
279
  // The product injects its independent transport; historical research ledgers are untouched.
269
280
  phase = 'open';
270
- turn = this.openTurn(token, { messages, images: attachments, temporaryChat: true, modeCategory, thinkingLevel: body.thinking_level, timeoutMs, signal: controller.signal,
281
+ turn = this.openTurn(token, { messages, images: attachments, temporaryChat: true,
282
+ modeCategory: isAutoModel ? null : modeCategory,
283
+ thinkingLevel: isAutoModel ? null : body.thinking_level,
284
+ ...(isAutoModel ? { smartModelSelection: true } : {}),
285
+ timeoutMs, signal: controller.signal,
271
286
  emitHeaders: incremental,
272
287
  ...(context.nativeDiagnostic ? { diagnostic: context.nativeDiagnostic } : {}) });
273
288
  iterator = turn.events[Symbol.asyncIterator]();
@@ -303,12 +318,14 @@ export class NativeDirectProvider {
303
318
  }
304
319
  if (frameResolved && info.attribution !== null && info.attribution.length > 0) {
305
320
  observedAttribution = info.attribution;
306
- if (requiresHydrogen && !HYDROGEN_ATTRIBUTION.test(info.attribution)) downgrade = true;
321
+ if (!attributionMatches(info.attribution)) downgrade = true;
322
+ }
323
+ // Final generate evidence must name the requested mode unless auto selection is enabled.
324
+ // Prior proven rejection is sticky; an unresolved zero is not a proven downgrade.
325
+ if (!isAutoModel) {
326
+ if (observedMode !== null && observedMode !== 0 && observedMode !== modeCategory) downgrade = true;
327
+ if (info.fallback === 1 || (info.downgradeReason !== null && info.downgradeReason !== undefined && info.downgradeReason !== 0)) downgrade = true;
307
328
  }
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;
312
329
  if (info.thinkingLevel !== null && info.thinkingLevel !== undefined) {
313
330
  if (!Number.isSafeInteger(info.thinkingLevel) || info.thinkingLevel < 0 || info.thinkingLevel > 4) fail('INVALID_NATIVE_THINKING_LEVEL');
314
331
  observedThinking = info.thinkingLevel;
@@ -350,7 +367,7 @@ export class NativeDirectProvider {
350
367
  } else if (snapshotId !== null && info.responseId && info.responseId !== snapshotId) {
351
368
  fail('INVALID_NATIVE_RESPONSE');
352
369
  }
353
- if (incremental && observedMode === modeCategory && attributionVerified() && liveSyncedLength < rawText.length) {
370
+ if (incremental && modeMatches(observedMode) && attributionVerified() && liveSyncedLength < rawText.length) {
354
371
  const delta = rawText.slice(liveSyncedLength);
355
372
  liveSyncedLength = rawText.length;
356
373
  await publish(liveSplitter.push(delta));
@@ -378,7 +395,7 @@ export class NativeDirectProvider {
378
395
  // must be non-retryable or PI will repeatedly submit fresh generations.
379
396
  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
397
  if (!modelComplete) fail('INCOMPLETE_NATIVE_RESPONSE');
381
- if (observedMode !== modeCategory) fail('MISSING_NATIVE_MODE_EVIDENCE');
398
+ if (!modeMatches(observedMode)) fail('MISSING_NATIVE_MODE_EVIDENCE');
382
399
  if (!attributionVerified()) fail('MODEL_DOWNGRADE_REJECTED');
383
400
  if (outputShape.nativeRefusalPresent) fail('NATIVE_RESPONSE_REFUSED', 422);
384
401
  if (!rawText.trim()) {
@@ -431,7 +448,7 @@ export class NativeDirectProvider {
431
448
  note('provider_success');
432
449
  return result;
433
450
  } catch (error) {
434
- const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && observedMode === modeCategory && attributionVerified();
451
+ const modeVerified = !downgrade && !outputShape.nativeRefusalPresent && modeMatches(observedMode) && attributionVerified();
435
452
  if (incremental && modeVerified && !sinkFailed) {
436
453
  try { await publish(liveSplitter.flush()); }
437
454
  catch { /* Retain already-published text; never release an invalid/incomplete tool body. */ }
@@ -14,9 +14,16 @@ import { RESPONSE_TOOL_IDENTITIES, normalizeResponsesTools, responsesCallFields
14
14
  import { toResponsesUsage } from './openai-usage.mjs';
15
15
 
16
16
  const fail = (code, status = 400, param = null) => { throw protocolError(code, status, param); };
17
- export const NATIVE_MODELS = Object.freeze(['gemini-argon', 'gemini-hydrogen', 'gemini-flash-lite']);
18
- // Native ModeCategory wire values: ULTRA=8, FAST=1 (Gemini 4 Hydrogen), FLASH_LITE=6. Never auto/Plus.
19
- export const MODEL_MODES = Object.freeze({ 'gemini-argon': 8, 'gemini-hydrogen': 1, 'gemini-flash-lite': 6 });
17
+ export const NATIVE_MODELS = Object.freeze(['gemini-neon', 'gemini-hydrogen', 'gemini-flash-lite']);
18
+ // Temporary compatibility alias while clients migrate from retired gemini-argon (mode 8) to gemini-neon (mode 3).
19
+ export const MODEL_ALIASES = Object.freeze({ 'gemini-argon': 'gemini-neon' });
20
+ // Native ModeCategory wire values: PRO=3 (Gemini 4 Neon), FAST=1 (Gemini 4 Hydrogen), FLASH_LITE=6. Never auto/Plus.
21
+ export const MODEL_MODES = Object.freeze({ 'gemini-neon': 3, 'gemini-hydrogen': 1, 'gemini-flash-lite': 6 });
22
+ export function canonicalModel(model) {
23
+ if (typeof model !== 'string') return model;
24
+ const stripped = model.startsWith('models/') ? model.slice(7) : model;
25
+ return Object.hasOwn(MODEL_ALIASES, stripped) ? MODEL_ALIASES[stripped] : stripped;
26
+ }
20
27
  // Ordinary effort hints must never opt into native asynchronous Deep Think (3).
21
28
  // Extended thinking (2) is the existing normal-turn default, not an ordered scale.
22
29
  export const REASONING_EFFORT_LEVELS = Object.freeze({ none: 0, minimal: 0, low: 1, medium: 2, high: 2, xhigh: 2 });
@@ -166,11 +173,12 @@ function content(value, { assistant = false, responses = false, user = false, pr
166
173
  });
167
174
  return parts.some(part => part.type === 'image_url') ? parts : parts.map(part => part.text).join('');
168
175
  }
169
- function settings(body) {
170
- const model = body.model === undefined ? 'gemini-argon' : body.model;
176
+ function settings(body, { allowAutoModel = false } = {}) {
177
+ const model = body.model === undefined ? 'gemini-neon' : body.model;
171
178
  if (typeof model !== 'string') fail('UNSUPPORTED_MODEL', 400, 'model');
172
- const alias = model.startsWith('models/') ? model.slice(7) : model;
173
- if (!NATIVE_MODELS.includes(alias)) fail('UNSUPPORTED_MODEL', 400, 'model');
179
+ const alias = canonicalModel(model);
180
+ const allowedModels = allowAutoModel ? [...NATIVE_MODELS, 'gemini-auto'] : NATIVE_MODELS;
181
+ if (!allowedModels.includes(alias)) fail('UNSUPPORTED_MODEL', 400, 'model');
174
182
  const thinking = thinkingSettings(body);
175
183
  if (body.stream !== undefined && typeof body.stream !== 'boolean') fail('INVALID_STREAM', 400, 'stream');
176
184
  if (body.native_search !== undefined && typeof body.native_search !== 'boolean') fail('INVALID_NATIVE_SEARCH', 400, 'native_search');
@@ -244,7 +252,7 @@ export function buildCanonicalPrompt(body, resolvedImages) {
244
252
  const tailReminder = activeToolNames
245
253
  ? '\n\n[Tool Protocol Reminder]\nUpstream native/internal function-calling channels are disabled (`INVALID_ARGUMENT: function does not exist`). Never invoke tools through native/internal tool channels; to call `' +
246
254
  activeToolNames +
247
- '`, write a literal plain-text Markdown ```tool_call fenced JSON block in your visible assistant response.'
255
+ '`, write a literal plain-text Markdown ```tool_call fenced JSON block in your visible assistant response. Stop immediately after your tool_call block(s) and never emit [Caller tool result] yourself.'
248
256
  : '';
249
257
  const prompt = '[System Instructions]\n' + preamble + '\n\n' + userText + tailReminder;
250
258
  if (prompt.length > MAX_CHARS || Buffer.byteLength(prompt) > PROMPT_MAX_BYTES) fail('PROMPT_TOO_LARGE', 413);
@@ -308,15 +316,15 @@ function validateInertOpenAIFields(payload, { responses = false } = {}) {
308
316
  }
309
317
  }
310
318
 
311
- export function normalizeChatRequest(payload) {
319
+ export function normalizeChatRequest(payload, { allowAutoModel = false } = {}) {
312
320
  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
321
  requestBudget(payload);
314
322
  validateInertOpenAIFields(payload);
315
323
  const compat = compatibility(payload);
316
- const resolved = settings(payload);
324
+ const resolved = settings(payload, { allowAutoModel });
317
325
  const response_format = normalizeChatResponseFormat(payload.response_format);
318
326
  if (resolved.native_search) {
319
- if (resolved.model !== 'gemini-argon' || resolved.thinking_level !== 2) fail('UNSUPPORTED_NATIVE_SEARCH_MODE');
327
+ if (resolved.model !== 'gemini-neon' || resolved.thinking_level !== 2) fail('UNSUPPORTED_NATIVE_SEARCH_MODE');
320
328
  if (response_format) fail('NATIVE_SEARCH_RESPONSE_FORMAT_CONFLICT');
321
329
  if ((payload.tools !== undefined && (!Array.isArray(payload.tools) || payload.tools.length)) || (payload.tool_choice !== undefined && payload.tool_choice !== 'auto') || payload.parallel_tool_calls !== undefined) fail('NATIVE_SEARCH_TOOL_CONFLICT');
322
330
  if (Array.isArray(payload.messages) && payload.messages.some(message => message?.role === 'tool' || message?.tool_calls !== undefined || message?.tool_call_id !== undefined)) fail('NATIVE_SEARCH_TOOL_HISTORY_UNSUPPORTED');
@@ -381,12 +389,12 @@ export function normalizeChatRequest(payload) {
381
389
  return body;
382
390
  }
383
391
 
384
- export function normalizeResponsesRequest(payload) {
392
+ export function normalizeResponsesRequest(payload, { allowAutoModel = false } = {}) {
385
393
  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
394
  requestBudget(payload);
387
395
  validateInertOpenAIFields(payload, { responses: true });
388
396
  const compat = compatibility(payload, true);
389
- const resolved = settings(payload);
397
+ const resolved = settings(payload, { allowAutoModel });
390
398
  const response_format = normalizeResponsesText(payload.text);
391
399
  const messages = [];
392
400
  if (payload.instructions !== undefined && payload.instructions !== null) messages.push({ role: 'system', content: text(payload.instructions) });
@@ -421,7 +429,7 @@ export function normalizeResponsesRequest(payload) {
421
429
  }
422
430
  }
423
431
  const { include: _include, ...inertCompat } = compat;
424
- const body = normalizeChatRequest({ ...resolved, ...inertCompat, ...(response_format ? { response_format } : {}), messages, tools, tool_choice: choice, [RESPONSE_TOOL_IDENTITIES]: identities });
432
+ const body = normalizeChatRequest({ ...resolved, ...inertCompat, ...(response_format ? { response_format } : {}), messages, tools, tool_choice: choice, [RESPONSE_TOOL_IDENTITIES]: identities }, { allowAutoModel });
425
433
  const projected = collectImageInputs(body.messages).messages;
426
434
  return {
427
435
  body,
@@ -120,7 +120,7 @@ export function validateToolCompletion(calls, policy) {
120
120
 
121
121
  export function buildToolInstruction(tools = [], choice = 'auto') {
122
122
  const policy = compileToolPolicy(tools, choice);
123
- if (!policy.enabled) return 'Answer the latest user request now as the assistant. If caller tool results are present, use them to complete your answer; do not wait for another user message. Never invent tool outputs. Tool calls are prohibited for this turn. Do not emit a tool_call fence. For literal examples use a json fence.';
123
+ if (!policy.enabled) return 'Answer the latest user request now as the assistant. If caller tool results are present, use them to complete your answer; do not wait for another user message. Never invent tool outputs. Never emit transcript role markers such as [Caller tool result], [User], or [Assistant]. Tool calls are prohibited for this turn. Do not emit a tool_call fence. For literal examples use a json fence.';
124
124
  return [
125
125
  '# Available Local Tools (caller-owned prompt protocol, NOT native function calling)',
126
126
  JSON.stringify(tools),
@@ -132,6 +132,7 @@ export function buildToolInstruction(tools = [], choice = 'auto') {
132
132
  '```',
133
133
  'Arguments must be a JSON object matching the declared schema. Never invent tools or results.',
134
134
  'Only the caller executes tools. Wait for linked caller tool results before using results.',
135
+ 'After emitting your tool_call block(s), STOP your response immediately. Never emit, simulate, or echo [Caller tool result], [User], [Assistant], or any transcript role markers.',
135
136
  'A standalone top-level tool_call fence is reserved for actual requests; use json fences for literal examples. Inline references are text.',
136
137
  policy.forced ? `You MUST request only ${policy.forced}.` : choice === 'required' ? 'You MUST request at least one declared tool.' : 'Request tools only when needed.',
137
138
  ].join('\n');
@@ -161,10 +162,28 @@ export function flattenMessages(messages = [], { maxChars = 3_500_000 } = {}) {
161
162
  return { systemText, userText };
162
163
  }
163
164
 
165
+ const CALLER_RESULT_MARKER = '[Caller tool result]';
166
+
167
+ // Returns the safe prefix length before a full or trailing partial CALLER_RESULT_MARKER.
168
+ // Because CALLER_RESULT_MARKER contains '[' only at index 0, any partial prefix at the end
169
+ // of `str` must start at the last '[' within the trailing slice.
170
+ function callerResultPreviewCut(str) {
171
+ const full = str.indexOf(CALLER_RESULT_MARKER);
172
+ if (full >= 0) return full;
173
+ const lastBracket = str.lastIndexOf('[');
174
+ if (lastBracket >= 0 && CALLER_RESULT_MARKER.startsWith(str.slice(lastBracket))) {
175
+ return lastBracket;
176
+ }
177
+ return -1;
178
+ }
179
+
164
180
  /** Bounded tool-fence splitter. Only complete JSON/name/schema-checked calls
165
- * become call events; preview exposes ordinary pending text, never a tool body. */
181
+ * become call events; preview exposes ordinary pending text, never a tool body.
182
+ * Once at least one real tool_call has been emitted, any unquoted hallucinated
183
+ * `[Caller tool result]` continuation and everything after it is suppressed so
184
+ * the caller receives only the real tool calls. */
166
185
  export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBytes(12).toString('hex'), policy = compileToolPolicy([]) } = {}) {
167
- let pending = '', scanned = 0, seen = 0, closed = false, bytes = 0;
186
+ let pending = '', scanned = 0, seen = 0, closed = false, suppressed = false, bytes = 0;
168
187
  let mode = 'text', marker = '`', fenceLength = 3, toolBody = '', toolBytes = 0, headerBytes = 0, inlineTicks = 0;
169
188
  const ids = new Set();
170
189
  const malformed = reason => {
@@ -184,10 +203,25 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
184
203
  };
185
204
  const inlineText = (text, raw, eol, events) => {
186
205
  if (/^(?: {4}|\t| {0,3}(?:>|[-+*][ \t]|\d+[.)][ \t]))/.test(text)) {
187
- inlineTicks = 0; events.push({ type: 'content', text: raw }); return;
206
+ inlineTicks = 0;
207
+ if (seen > 0) {
208
+ const idx = text.indexOf(CALLER_RESULT_MARKER);
209
+ if (idx >= 0) {
210
+ if (idx > 0) events.push({ type: 'content', text: text.slice(0, idx) });
211
+ suppressed = true;
212
+ return;
213
+ }
214
+ }
215
+ events.push({ type: 'content', text: raw });
216
+ return;
188
217
  }
189
218
  if (!text.trim()) inlineTicks = 0;
190
219
  for (let i = 0; i < text.length;) {
220
+ if (seen > 0 && !inlineTicks && text.startsWith(CALLER_RESULT_MARKER, i)) {
221
+ if (i) events.push({ type: 'content', text: text.slice(0, i) });
222
+ suppressed = true;
223
+ return;
224
+ }
191
225
  if (text[i] === '\\' && !inlineTicks) {
192
226
  i += 2;
193
227
  while (text[i] === '`' && text[i - 1] === '`') i++;
@@ -210,6 +244,7 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
210
244
  events.push({ type: 'content', text: raw });
211
245
  };
212
246
  const line = (raw, final, events) => {
247
+ if (suppressed) return;
213
248
  const eol = /\r?\n$/.exec(raw)?.[0] ?? '';
214
249
  const text = eol ? raw.slice(0, -eol.length) : raw;
215
250
  // Prefix-only matching avoids backtracking across long untrusted lines.
@@ -220,8 +255,15 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
220
255
  // JSON/name/schema validation, not incidental Markdown suffix layout,
221
256
  // authorizes the call. Never scan the suffix again as another request.
222
257
  emitCall(events); mode = 'text'; toolBody = ''; toolBytes = 0; inlineTicks = 0;
223
- if (info.trim()) events.push({ type: 'content', text: info + eol });
224
- else if (eol) events.push({ type: 'content', text: eol });
258
+ if (info.trim()) {
259
+ const markerIdx = info.indexOf(CALLER_RESULT_MARKER);
260
+ if (markerIdx >= 0) {
261
+ if (markerIdx > 0) events.push({ type: 'content', text: info.slice(0, markerIdx) });
262
+ suppressed = true;
263
+ return;
264
+ }
265
+ events.push({ type: 'content', text: info + eol });
266
+ } else if (eol) events.push({ type: 'content', text: eol });
225
267
  return;
226
268
  }
227
269
  if (run?.[0] === '`' && info.trim()) malformed('closing_fence');
@@ -255,10 +297,15 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
255
297
  if (end < 0) break;
256
298
  line(pending.slice(consumed, end + 1), false, events);
257
299
  consumed = end + 1; from = consumed;
300
+ if (suppressed) { pending = ''; scanned = 0; return events; }
258
301
  }
259
302
  if (consumed) pending = pending.slice(consumed);
260
303
  scanned = pending.length;
261
- if (final && pending) { line(pending, true, events); pending = ''; scanned = 0; }
304
+ if (final && pending) {
305
+ line(pending, true, events);
306
+ pending = ''; scanned = 0;
307
+ if (suppressed) return events;
308
+ }
262
309
  if (mode === 'tool') {
263
310
  if (headerBytes + toolBytes + Buffer.byteLength(pending) > TOOL_LIMITS.bytes) fail('TOOL_SIZE_LIMIT', 502);
264
311
  if (final) fail('TRUNCATED_TOOL_CALL', 502);
@@ -269,18 +316,31 @@ export function createToolCallSplitter({ newId = () => 'call_' + crypto.randomBy
269
316
  push(text) {
270
317
  if (closed) fail('SPLITTER_CLOSED', 502);
271
318
  if (typeof text !== 'string' || (bytes += Buffer.byteLength(text)) > 8 * 1024 * 1024) fail('RESPONSE_TOO_LARGE', 502);
319
+ if (suppressed) return [];
272
320
  pending += text;
273
321
  return drain(false);
274
322
  },
275
- flush() { if (closed) fail('SPLITTER_CLOSED', 502); closed = true; return drain(true); },
323
+ flush() {
324
+ if (closed) fail('SPLITTER_CLOSED', 502);
325
+ closed = true;
326
+ if (suppressed) return [];
327
+ return drain(true);
328
+ },
276
329
  preview() {
277
- if (mode === 'tool') return '';
330
+ if (suppressed || mode === 'tool') return '';
278
331
  if (mode === 'ordinary') return pending;
279
332
  if (!pending.trim() && pending.length <= 3) return '';
280
- const tick = pending.indexOf('`');
281
- if (tick < 0) return pending;
282
- if (tick <= 3 && /^ *$/.test(pending.slice(0, tick))) return '';
283
- return pending.slice(0, tick);
333
+ let safe = pending;
334
+ const tick = safe.indexOf('`');
335
+ if (tick >= 0) {
336
+ if (tick <= 3 && /^ *$/.test(safe.slice(0, tick))) return '';
337
+ safe = safe.slice(0, tick);
338
+ }
339
+ if (seen > 0) {
340
+ const cut = callerResultPreviewCut(safe);
341
+ if (cut >= 0) safe = safe.slice(0, cut);
342
+ }
343
+ return safe;
284
344
  },
285
345
  get toolCallCount() { return seen; },
286
346
  };