pi-gemini-app 0.0.0-stage → 0.1.0

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.
Files changed (39) hide show
  1. package/DISCLAIMER.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +86 -2
  4. package/extensions/pi/auth.js +182 -0
  5. package/extensions/pi/index.js +18 -0
  6. package/extensions/pi/provider.js +156 -0
  7. package/extensions/pi/stream.js +402 -0
  8. package/extensions/pi/transcript.js +473 -0
  9. package/native-wire/consumer-tool-codec.mjs +236 -0
  10. package/native-wire/oauth-loopback.mjs +174 -0
  11. package/native-wire/protobuf.mjs +133 -0
  12. package/native-wire/robin-current.mjs +169 -0
  13. package/package.json +80 -4
  14. package/src/gateway/automatic-recovery.mjs +59 -0
  15. package/src/gateway/image-download.mjs +109 -0
  16. package/src/gateway/image-upload.mjs +109 -0
  17. package/src/gateway/native-diagnostic.mjs +187 -0
  18. package/src/gateway/native-evidence.mjs +113 -0
  19. package/src/gateway/native-response-limits.mjs +8 -0
  20. package/src/gateway/native-search-citations.mjs +196 -0
  21. package/src/gateway/native-search-diagnostic.mjs +282 -0
  22. package/src/gateway/native-search-metadata.mjs +749 -0
  23. package/src/gateway/native-transport.mjs +344 -0
  24. package/src/gateway/oauth-client-defaults.mjs +12 -0
  25. package/src/gateway/output-recovery.mjs +43 -0
  26. package/src/gateway/quota-failover.mjs +14 -0
  27. package/src/gateway/quota-transport.mjs +37 -0
  28. package/src/gateway/quota.mjs +181 -0
  29. package/src/gateway/soft-error.mjs +25 -0
  30. package/src/gateway/structured-output.mjs +157 -0
  31. package/src/gateway/terms.mjs +126 -0
  32. package/src/image-input.mjs +129 -0
  33. package/src/image-url.mjs +21 -0
  34. package/src/native-provider.mjs +492 -0
  35. package/src/openai-contract.mjs +509 -0
  36. package/src/openai-usage.mjs +29 -0
  37. package/src/prompt-tool-schema.mjs +356 -0
  38. package/src/responses-tool-namespaces.mjs +82 -0
  39. package/src/tool-protocol.mjs +287 -0
package/DISCLAIMER.md ADDED
@@ -0,0 +1,17 @@
1
+ # Disclaimer & Terms of Use / 免責聲明與使用條款
2
+
3
+ ## English
4
+
5
+ 1. **Independent Interoperability Research Project:** Gemini App2API is an independent software engineering and protocol-interoperability project. It is **not** affiliated with, endorsed by, sponsored by, or supported by Google LLC.
6
+ 2. **Interoperability Configuration; No User Credentials, Accounts, or Quota Supplied:** The default fallback OAuth 2.0 loopback configuration incorporates standard desktop client identifiers strictly for protocol-interoperability research so users can authenticate locally with Google's OAuth endpoints. This repository does **not** distribute Google application binaries, user credentials, refresh/access tokens, accounts, or model quota. Users must authenticate personally with their own authorized Google accounts.
7
+ 3. **Terms of Service (ToS) & Account Risk:** Using third-party clients, automated coding harnesses, or multi-account routing with Google accounts may conflict with or violate Google's Terms of Service or plan-specific policies. Upstream enforcement by Google may result in rate limiting, feature restrictions, or temporary/permanent account suspension or termination. You are solely responsible for reviewing and complying with all applicable terms governing your accounts.
8
+ 4. **No Warranty & Limitation of Liability:** This software is provided **"AS IS"**, without warranty of any kind, express or implied (see [LICENSE](LICENSE)). In no event shall the authors, maintainers, or contributors be liable for any account suspension, quota loss, service interruption, data loss, or any direct, indirect, incidental, or consequential damages arising out of or in connection with the use of this software. **Your accounts, your deployment, your risk.**
9
+
10
+ ---
11
+
12
+ ## 繁體中文
13
+
14
+ 1. **獨立互通性研究專案:** Gemini App2API 為獨立之軟體工程與通訊協定互通性(Protocol Interoperability)研究專案,**與 Google LLC 無任何隸屬、合作、授權或背書關係**。
15
+ 2. **互通性設定聲明;不提供任何使用者憑證、帳戶或額度:** 預設之本機 OAuth 2.0 loopback 備援設定包含標準桌面端 client 識別參數,僅供通訊協定互通性(Protocol Interoperability)研究與本機標準 OAuth 驗證流程使用。本儲存庫**絕不分發**任何 Google 應用程式二進位檔、使用者登入憑證、Refresh/Access Token、帳戶或模型額度;使用者必須親自以本人合法授權之 Google 帳戶完成驗證。
16
+ 3. **服務條款(ToS)與帳戶風控風險:** 將 Google 帳戶連接至非官方客戶端、自動化編碼 Agent 工具鏈或使用多帳戶路由功能,可能違反 Google 服務條款(Terms of Service)或個別訂閱方案之使用規範,並可能導致上游限流、功能受限,或帳戶遭到暫時/永久停權與封禁。使用者須自行查閱並遵守其帳戶所適用之相關條款。
17
+ 4. **無擔保與零法律責任:** 本軟體係依「現狀(AS IS)」提供,不附帶任何明示或默示之保證(詳見 [LICENSE](LICENSE))。作者、維護者與貢獻者亦不鼓勵或誘導任何違反第三方合約之行為,且對因使用本軟體而引致之任何帳戶封禁、額度損失、服務中斷、資料遺失或任何直接/間接損害**概不承擔任何法律責任**。**你的帳戶、你的部署,一切風險由你自行承擔。**
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shawtim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # `pi-gemini-app` — Google Gemini App Provider for Pi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
4
+
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
+
7
+ ## Installation
8
+
9
+ ### Option 1: Install from npm / Pi Marketplace (Recommended)
10
+
11
+ ```bash
12
+ pi install npm:pi-gemini-app
13
+ ```
14
+
15
+ ### Option 2: Install directly from Git
16
+
17
+ ```bash
18
+ pi install git:github.com/ShawTim/gemini-app2api
19
+ ```
20
+
21
+ ### Option 3: Load from a local clone
22
+
23
+ ```bash
24
+ git clone https://github.com/ShawTim/gemini-app2api.git
25
+ cd gemini-app2api
26
+ pi -e ./extensions/pi
27
+ ```
28
+
29
+ Or add the extension path to your Pi settings (`~/.pi/agent/settings.json`):
30
+
31
+ ```json
32
+ {
33
+ "extensions": ["/path/to/gemini-app2api/extensions/pi"]
34
+ }
35
+ ```
36
+
37
+ ## Architecture & When to Choose `pi-gemini-app` vs `gemini-app2api`
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.
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
+
42
+ ## Authentication (`/login gemini-app`)
43
+
44
+ Credentials are stored and refreshed exclusively through Pi's built-in `CredentialStore` (`auth.json` with file locking).
45
+
46
+ Run inside Pi:
47
+
48
+ ```text
49
+ /login gemini-app
50
+ ```
51
+
52
+ > **Terms of Service Notice**: Completing `/login gemini-app` exchanges a scoped Gemini credential and **automatically submits acceptance of the Google Gemini Terms of Service** on behalf of the signed-in Google account so native HTTP/2 turns work immediately without an extra prompt (transient `TOS_*` check errors are deferred non-fatally). Sign in only with an eligible account whose Terms of Service you intend to accept.
53
+
54
+ The login flow supports both local desktop and headless SSH environments simultaneously:
55
+
56
+ 1. **Desktop / Local Browser**: Opens (or prints) the Google OAuth consent URL and listens on a random ephemeral loopback port (`127.0.0.1:0`). Completing sign-in in the browser finishes automatically.
57
+ 2. **Headless / SSH**: Open the printed authorization URL in a browser on another machine. After approving sign-in, copy the final `http://localhost:...` redirect URL from your browser's address bar and paste it into Pi's prompt.
58
+
59
+ Optional environment overrides if using your own OAuth desktop client:
60
+
61
+ - `GEMINI_OAUTH_CLIENT_ID`
62
+ - `GEMINI_OAUTH_CLIENT_SECRET`
63
+
64
+ ## Models
65
+
66
+ | Model ID | Display Name | Context Window | Max Output | Capabilities |
67
+ | :--- | :--- | ---: | ---: | :--- |
68
+ | `gemini-argon` | Gemini Argon | 128,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
69
+ | `gemini-hydrogen` | Gemini Hydrogen | 512,000 | 16,384 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
70
+ | `gemini-flash-lite` | Gemini Flash Lite | 128,000 | 8,192 | Text, static images (PNG/JPEG/WebP), tools, thinking (`minimal`–`xhigh`) |
71
+
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
+ >
74
+ > **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
+ >
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`).
77
+
78
+ ## Commands
79
+
80
+ - `/gemini-quota` — Fetches and displays your signed-in account's rolling usage percentages and reset timestamps.
81
+
82
+ ## Security & Privacy
83
+
84
+ - **Zero runtime dependencies**: Ships only pure ESM modules using built-in Node.js APIs; `@earendil-works/pi-ai` and `@earendil-works/pi-coding-agent` are provided by the Pi host via `peerDependencies`.
85
+ - **No shell or daemon spawning**: Contains zero `child_process` invocations and never starts background services.
86
+ - **Host-managed credentials**: OAuth refresh and scoped access tokens live exclusively in Pi's `CredentialStore` (`auth.json`).
87
+ - **Automatic Terms of Service submission**: Completing `/login gemini-app` automatically submits Google Gemini Terms of Service acceptance for that signed-in account.
@@ -0,0 +1,182 @@
1
+ import { startLoopbackLogin as defaultStartLoopbackLogin, refreshNativeCredential as defaultRefreshNativeCredential } from '../../native-wire/oauth-loopback.mjs';
2
+ import { acceptGoogleMainTerms as defaultAcceptGoogleMainTerms } from '../../src/gateway/terms.mjs';
3
+ import { DEFAULT_OAUTH_PROFILE } from '../../src/gateway/oauth-client-defaults.mjs';
4
+
5
+ const FLEXIBLE_API_SCOPE = 'https://www.googleapis.com/auth/flexible-api';
6
+ const FALLBACK_REFRESH_SCOPES = [
7
+ 'https://www.googleapis.com/auth/assistant',
8
+ 'https://www.googleapis.com/auth/gemini',
9
+ ];
10
+
11
+ export function resolveOAuthConfig({ defaultProfile = DEFAULT_OAUTH_PROFILE, env = process.env } = {}) {
12
+ const envClientId = typeof env?.GEMINI_OAUTH_CLIENT_ID === 'string' ? env.GEMINI_OAUTH_CLIENT_ID.trim() : '';
13
+ const hasEnvClientId = envClientId.length > 0;
14
+ const clientId = hasEnvClientId
15
+ ? envClientId
16
+ : (typeof defaultProfile?.clientId === 'string' ? defaultProfile.clientId.trim() : '');
17
+ if (!clientId) {
18
+ throw new Error('OAuth client ID is not configured; set GEMINI_OAUTH_CLIENT_ID.');
19
+ }
20
+ const envClientSecret = typeof env?.GEMINI_OAUTH_CLIENT_SECRET === 'string' ? env.GEMINI_OAUTH_CLIENT_SECRET.trim() : '';
21
+ const clientSecret = hasEnvClientId
22
+ ? envClientSecret
23
+ : (envClientSecret || (typeof defaultProfile?.clientSecret === 'string' ? defaultProfile.clientSecret.trim() : ''));
24
+ const refreshScopes = Array.isArray(defaultProfile?.scopes) && defaultProfile.scopes.length > 0
25
+ ? [...defaultProfile.scopes]
26
+ : [...FALLBACK_REFRESH_SCOPES];
27
+ return {
28
+ clientId,
29
+ ...(clientSecret ? { clientSecret } : {}),
30
+ scopes: [FLEXIBLE_API_SCOPE],
31
+ refreshScopes,
32
+ port: 0,
33
+ listenHost: '127.0.0.1',
34
+ redirectHost: 'localhost',
35
+ nativeLoopback: true,
36
+ forceConsent: true,
37
+ };
38
+ }
39
+
40
+ function computeExpiresAtMs(expiresInSeconds) {
41
+ const ttlSeconds = Number.isFinite(expiresInSeconds) && expiresInSeconds > 0 ? expiresInSeconds : 3600;
42
+ return Date.now() + Math.max(60, ttlSeconds - 300) * 1000;
43
+ }
44
+
45
+ export function createGeminiOAuthAuth({
46
+ startLoopbackLogin = defaultStartLoopbackLogin,
47
+ refreshNativeCredential = defaultRefreshNativeCredential,
48
+ acceptGoogleMainTerms = defaultAcceptGoogleMainTerms,
49
+ defaultProfile = DEFAULT_OAUTH_PROFILE,
50
+ env = process.env,
51
+ } = {}) {
52
+ async function login(interaction) {
53
+ const config = resolveOAuthConfig({ defaultProfile, env });
54
+ const outerSignal = interaction?.signal;
55
+ if (outerSignal?.aborted) {
56
+ throw Object.assign(new Error('Login cancelled'), { code: 'LOGIN_CLOSED' });
57
+ }
58
+ const session = await startLoopbackLogin(config, { signal: outerSignal });
59
+ const manualAbort = new AbortController();
60
+ const onOuterAbort = () => manualAbort.abort(outerSignal.reason);
61
+ let tokens;
62
+ try {
63
+ outerSignal?.addEventListener('abort', onOuterAbort, { once: true });
64
+ if (outerSignal?.aborted) onOuterAbort();
65
+
66
+ const runManualPrompt = async () => {
67
+ if (typeof interaction?.prompt !== 'function') {
68
+ return new Promise(() => {});
69
+ }
70
+ while (!manualAbort.signal.aborted) {
71
+ let rawInput;
72
+ try {
73
+ rawInput = await interaction.prompt({
74
+ type: 'manual_code',
75
+ message: 'Paste the localhost redirect URL if your browser cannot reach this machine:',
76
+ placeholder: 'http://localhost:...',
77
+ signal: manualAbort.signal,
78
+ });
79
+ } catch (error) {
80
+ if (manualAbort.signal.aborted) return null;
81
+ session.close('LOGIN_CLOSED');
82
+ throw error;
83
+ }
84
+ if (manualAbort.signal.aborted) return null;
85
+ if (typeof rawInput !== 'string' || !rawInput.trim()) {
86
+ continue;
87
+ }
88
+ try {
89
+ return await session.completeCallbackUrl(rawInput);
90
+ } catch (error) {
91
+ if (error?.code === 'INVALID_CALLBACK_URL' || error?.code === 'INVALID_LOGIN_STATE') {
92
+ interaction?.notify?.({
93
+ type: 'progress',
94
+ message: 'Invalid callback URL or state; please paste the complete redirect URL.',
95
+ });
96
+ continue;
97
+ }
98
+ throw error;
99
+ }
100
+ }
101
+ return null;
102
+ };
103
+
104
+ interaction?.notify?.({
105
+ type: 'auth_url',
106
+ url: session.authorizationUrl,
107
+ instructions: 'Open the Google sign-in URL in a browser. If running over SSH/headless, paste the final localhost redirect URL below.',
108
+ });
109
+ const manualPromise = runManualPrompt();
110
+ manualPromise.catch(() => {});
111
+ tokens = await Promise.race([session.done, manualPromise]);
112
+ if (!tokens) {
113
+ tokens = await session.done;
114
+ }
115
+ } finally {
116
+ outerSignal?.removeEventListener('abort', onOuterAbort);
117
+ manualAbort.abort();
118
+ if (!tokens) {
119
+ try { session.close(); } catch {}
120
+ }
121
+ }
122
+
123
+ if (!tokens || typeof tokens.refreshToken !== 'string' || !tokens.refreshToken) {
124
+ throw new Error('Google OAuth login did not return a refresh token.');
125
+ }
126
+
127
+ interaction?.notify?.({
128
+ type: 'progress',
129
+ message: 'Exchanging scoped Gemini access token...',
130
+ });
131
+ const scoped = await refreshNativeCredential(config, tokens.refreshToken, { signal: outerSignal });
132
+
133
+ interaction?.notify?.({
134
+ type: 'progress',
135
+ message: 'Verifying Gemini Terms of Service...',
136
+ });
137
+ try {
138
+ await acceptGoogleMainTerms(scoped.accessToken, { signal: outerSignal });
139
+ } catch (error) {
140
+ if (outerSignal?.aborted) throw error;
141
+ const code = typeof error?.code === 'string' ? error.code : '';
142
+ if (!code.startsWith('TOS_')) throw error;
143
+ interaction?.notify?.({
144
+ type: 'progress',
145
+ message: `Gemini Terms of Service check deferred (${code}); sign-in succeeded.`,
146
+ });
147
+ }
148
+
149
+ return {
150
+ type: 'oauth',
151
+ refresh: scoped.refreshToken || tokens.refreshToken,
152
+ access: scoped.accessToken,
153
+ expires: computeExpiresAtMs(scoped.expiresInSeconds ?? tokens.expiresInSeconds),
154
+ };
155
+ }
156
+
157
+ async function refresh(credential, signal) {
158
+ if (!credential || typeof credential.refresh !== 'string' || !credential.refresh) {
159
+ throw new Error('Missing OAuth refresh token.');
160
+ }
161
+ const config = resolveOAuthConfig({ defaultProfile, env });
162
+ const refreshed = await refreshNativeCredential(config, credential.refresh, { signal });
163
+ return {
164
+ ...credential,
165
+ type: 'oauth',
166
+ refresh: refreshed.refreshToken || credential.refresh,
167
+ access: refreshed.accessToken,
168
+ expires: computeExpiresAtMs(refreshed.expiresInSeconds),
169
+ };
170
+ }
171
+
172
+ async function toAuth(credential) {
173
+ return { apiKey: credential.access };
174
+ }
175
+
176
+ return {
177
+ name: 'Google Gemini App',
178
+ login,
179
+ refresh,
180
+ toAuth,
181
+ };
182
+ }
@@ -0,0 +1,18 @@
1
+ import {
2
+ createProvider,
3
+ createAssistantMessageEventStream,
4
+ getCurrentSystemPrompt,
5
+ getCurrentTools,
6
+ toToolDeclaration,
7
+ } from '@earendil-works/pi-ai';
8
+ import { registerGeminiAppExtension } from './provider.js';
9
+
10
+ export default function (pi) {
11
+ registerGeminiAppExtension(pi, {
12
+ createProvider,
13
+ createAssistantMessageEventStream,
14
+ getCurrentSystemPrompt,
15
+ getCurrentTools,
16
+ toToolDeclaration,
17
+ });
18
+ }
@@ -0,0 +1,156 @@
1
+ import { createGeminiOAuthAuth } from './auth.js';
2
+ import { createGeminiStreamHandler } from './stream.js';
3
+ import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
4
+ import { decodeUsageInfo as defaultDecodeUsageInfo } from '../../src/gateway/quota.mjs';
5
+
6
+ const BASE_URL = 'https://robinfrontend-pa.googleapis.com';
7
+ const PROVIDER_ID = 'gemini-app';
8
+ const API_ID = 'gemini-app-api';
9
+
10
+ export const MODELS = Object.freeze([
11
+ {
12
+ id: 'gemini-argon',
13
+ name: 'Gemini Argon',
14
+ api: API_ID,
15
+ provider: PROVIDER_ID,
16
+ baseUrl: BASE_URL,
17
+ type: 'chat',
18
+ contextWindow: 128000,
19
+ maxTokens: 16384,
20
+ input: ['text', 'image'],
21
+ reasoning: true,
22
+ thinkingLevelMap: {
23
+ minimal: 'minimal',
24
+ low: 'low',
25
+ medium: 'medium',
26
+ high: 'high',
27
+ xhigh: 'xhigh',
28
+ },
29
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
30
+ },
31
+ {
32
+ id: 'gemini-hydrogen',
33
+ name: 'Gemini Hydrogen',
34
+ api: API_ID,
35
+ provider: PROVIDER_ID,
36
+ baseUrl: BASE_URL,
37
+ type: 'chat',
38
+ contextWindow: 512000,
39
+ maxTokens: 16384,
40
+ input: ['text', 'image'],
41
+ reasoning: true,
42
+ thinkingLevelMap: {
43
+ minimal: 'minimal',
44
+ low: 'low',
45
+ medium: 'medium',
46
+ high: 'high',
47
+ xhigh: 'xhigh',
48
+ },
49
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
50
+ },
51
+ {
52
+ id: 'gemini-flash-lite',
53
+ name: 'Gemini Flash Lite',
54
+ api: API_ID,
55
+ provider: PROVIDER_ID,
56
+ baseUrl: BASE_URL,
57
+ type: 'chat',
58
+ contextWindow: 128000,
59
+ maxTokens: 8192,
60
+ input: ['text', 'image'],
61
+ reasoning: true,
62
+ thinkingLevelMap: {
63
+ minimal: 'minimal',
64
+ low: 'low',
65
+ medium: 'medium',
66
+ high: 'high',
67
+ xhigh: 'xhigh',
68
+ },
69
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
70
+ },
71
+ ]);
72
+
73
+ export function formatQuotaDisplay(usageInfo) {
74
+ if (!usageInfo?.usageRows?.length) {
75
+ return 'No active quota limits reported for this account.';
76
+ }
77
+ const lines = usageInfo.usageRows.map((row) => {
78
+ if (row.providerPercent === null || !Number.isFinite(row.providerPercent)) {
79
+ const reset = row.providerTimestamp ? ` (resets: ${row.providerTimestamp})` : '';
80
+ return `• ${row.label || 'Usage'}: N/A${reset}`;
81
+ }
82
+ const used = Math.round(row.providerPercent);
83
+ const remaining = Math.max(0, Math.min(100, 100 - used));
84
+ const reset = row.providerTimestamp ? ` (resets: ${row.providerTimestamp})` : '';
85
+ return `• ${row.label || 'Usage'}: ${remaining}% remaining (${used}% used)${reset}`;
86
+ });
87
+ return `Gemini Quota:\n${lines.join('\n')}`;
88
+ }
89
+
90
+ export function createGeminiAppProvider({
91
+ createProvider,
92
+ createAssistantMessageEventStream,
93
+ getCurrentSystemPrompt,
94
+ getCurrentTools,
95
+ toToolDeclaration,
96
+ auth = createGeminiOAuthAuth(),
97
+ ...streamDependencies
98
+ }) {
99
+ if (typeof createProvider !== 'function') {
100
+ throw new TypeError('createProvider factory is required');
101
+ }
102
+
103
+ const streamHandler = createGeminiStreamHandler({
104
+ createAssistantMessageEventStream,
105
+ getCurrentSystemPrompt,
106
+ getCurrentTools,
107
+ toToolDeclaration,
108
+ ...streamDependencies,
109
+ });
110
+
111
+ return createProvider({
112
+ id: PROVIDER_ID,
113
+ name: 'Google Gemini App',
114
+ baseUrl: BASE_URL,
115
+ auth: { oauth: auth },
116
+ models: MODELS,
117
+ api: {
118
+ stream: streamHandler.stream,
119
+ streamSimple: streamHandler.streamSimple,
120
+ },
121
+ });
122
+ }
123
+
124
+ export function registerGeminiAppExtension(pi, dependencies) {
125
+ const provider = createGeminiAppProvider(dependencies);
126
+ pi.registerProvider(provider);
127
+
128
+ const fetchUsage = dependencies?.fetchGoogleUsageInfo || defaultFetchGoogleUsageInfo;
129
+ const decodeUsage = dependencies?.decodeUsageInfo || defaultDecodeUsageInfo;
130
+
131
+ pi.registerCommand('gemini-quota', {
132
+ description: 'Check Gemini account quota and rolling reset windows',
133
+ handler: async (_args, ctx) => {
134
+ let token;
135
+ try {
136
+ token = await ctx.modelRegistry?.getApiKeyForProvider?.('gemini-app');
137
+ } catch (err) {
138
+ ctx.ui?.notify?.(`Failed to retrieve credentials: ${err.message}`, 'error');
139
+ return;
140
+ }
141
+ if (!token) {
142
+ ctx.ui?.notify?.('No active Gemini App token. Run /login gemini-app to sign in.', 'warning');
143
+ return;
144
+ }
145
+ try {
146
+ ctx.ui?.notify?.('Fetching Gemini quota information...', 'info');
147
+ const { payload } = await fetchUsage(token, ctx?.signal ? { signal: ctx.signal } : undefined);
148
+ const decoded = decodeUsage(payload);
149
+ const formatted = formatQuotaDisplay(decoded);
150
+ ctx.ui?.notify?.(formatted, 'info');
151
+ } catch (err) {
152
+ ctx.ui?.notify?.(`Failed to fetch Gemini quota: ${err.message}`, 'error');
153
+ }
154
+ },
155
+ });
156
+ }