pi-gemini-app 0.1.14 → 0.1.15
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/extensions/pi/auth.js +11 -7
- package/extensions/pi/provider.js +17 -5
- package/extensions/pi/stream.js +13 -5
- package/native-wire/robin-current.mjs +51 -14
- package/package.json +2 -1
- package/src/gateway/output-recovery.mjs +33 -0
- package/src/gateway/subscription-transport.mjs +78 -0
- package/src/gateway/subscription.mjs +36 -19
- package/src/native-provider.mjs +8 -4
- package/src/openai-contract.mjs +11 -1
package/extensions/pi/auth.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { startLoopbackLogin as defaultStartLoopbackLogin, refreshNativeCredential as defaultRefreshNativeCredential } from '../../native-wire/oauth-loopback.mjs';
|
|
2
2
|
import { acceptGoogleMainTerms as defaultAcceptGoogleMainTerms } from '../../src/gateway/terms.mjs';
|
|
3
|
-
import {
|
|
3
|
+
import { fetchGoogleSubscription as defaultFetchGoogleSubscription } from '../../src/gateway/subscription-transport.mjs';
|
|
4
4
|
import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
|
|
5
5
|
import { DEFAULT_OAUTH_PROFILE } from '../../src/gateway/oauth-client-defaults.mjs';
|
|
6
6
|
|
|
@@ -48,14 +48,16 @@ export function createGeminiOAuthAuth({
|
|
|
48
48
|
startLoopbackLogin = defaultStartLoopbackLogin,
|
|
49
49
|
refreshNativeCredential = defaultRefreshNativeCredential,
|
|
50
50
|
acceptGoogleMainTerms = defaultAcceptGoogleMainTerms,
|
|
51
|
-
|
|
51
|
+
fetchGoogleSubscription,
|
|
52
|
+
fetchGoogleUsageInfo,
|
|
52
53
|
decodeSubscription = defaultDecodeSubscription,
|
|
53
54
|
defaultProfile = DEFAULT_OAUTH_PROFILE,
|
|
54
55
|
env = process.env,
|
|
55
56
|
} = {}) {
|
|
57
|
+
const subscriptionFetch = fetchGoogleSubscription || fetchGoogleUsageInfo || defaultFetchGoogleSubscription;
|
|
56
58
|
async function detectSubscriptionTier(accessToken, { signal } = {}) {
|
|
57
59
|
try {
|
|
58
|
-
const { payload } = await
|
|
60
|
+
const { payload } = await subscriptionFetch(accessToken, { signal, timeoutMs: 8000 });
|
|
59
61
|
const sub = decodeSubscription(payload);
|
|
60
62
|
return typeof sub?.tier === 'string' && sub.tier ? sub.tier : 'unknown';
|
|
61
63
|
} catch (error) {
|
|
@@ -180,7 +182,7 @@ export function createGeminiOAuthAuth({
|
|
|
180
182
|
refresh: scoped.refreshToken || tokens.refreshToken,
|
|
181
183
|
access: scoped.accessToken,
|
|
182
184
|
expires: computeExpiresAtMs(scoped.expiresInSeconds ?? tokens.expiresInSeconds),
|
|
183
|
-
...(subscriptionTier !== 'unknown' ? { subscriptionTier } : {}),
|
|
185
|
+
...(subscriptionTier !== 'unknown' ? { subscriptionTier, subscriptionRpc: 'GetUserStatus' } : {}),
|
|
184
186
|
};
|
|
185
187
|
}
|
|
186
188
|
|
|
@@ -191,14 +193,16 @@ export function createGeminiOAuthAuth({
|
|
|
191
193
|
const config = resolveOAuthConfig({ defaultProfile, env });
|
|
192
194
|
const refreshed = await refreshNativeCredential(config, credential.refresh, { signal });
|
|
193
195
|
const detectedTier = await detectSubscriptionTier(refreshed.accessToken, { signal });
|
|
194
|
-
const
|
|
196
|
+
const verifiedPrior = credential.subscriptionRpc === 'GetUserStatus' ? credential.subscriptionTier : undefined;
|
|
197
|
+
const subscriptionTier = detectedTier !== 'unknown' ? detectedTier : verifiedPrior;
|
|
198
|
+
const { subscriptionTier: _oldTier, subscriptionRpc: _oldRpc, ...rest } = credential;
|
|
195
199
|
return {
|
|
196
|
-
...
|
|
200
|
+
...rest,
|
|
197
201
|
type: 'oauth',
|
|
198
202
|
refresh: refreshed.refreshToken || credential.refresh,
|
|
199
203
|
access: refreshed.accessToken,
|
|
200
204
|
expires: computeExpiresAtMs(refreshed.expiresInSeconds),
|
|
201
|
-
...(subscriptionTier ? { subscriptionTier } : {}),
|
|
205
|
+
...(subscriptionTier ? { subscriptionTier, subscriptionRpc: 'GetUserStatus' } : {}),
|
|
202
206
|
};
|
|
203
207
|
}
|
|
204
208
|
|
|
@@ -2,6 +2,7 @@ import { createGeminiOAuthAuth } from './auth.js';
|
|
|
2
2
|
import { createGeminiStreamHandler } from './stream.js';
|
|
3
3
|
import { MODEL_SPECS } from '../../src/openai-contract.mjs';
|
|
4
4
|
import { fetchGoogleUsageInfo as defaultFetchGoogleUsageInfo } from '../../src/gateway/quota-transport.mjs';
|
|
5
|
+
import { fetchGoogleSubscription as defaultFetchGoogleSubscription } from '../../src/gateway/subscription-transport.mjs';
|
|
5
6
|
import { decodeUsageInfo as defaultDecodeUsageInfo } from '../../src/gateway/quota.mjs';
|
|
6
7
|
import { decodeSubscription as defaultDecodeSubscription } from '../../src/gateway/subscription.mjs';
|
|
7
8
|
|
|
@@ -84,6 +85,7 @@ export function createGeminiAppProvider({
|
|
|
84
85
|
getCurrentTools,
|
|
85
86
|
toToolDeclaration,
|
|
86
87
|
auth,
|
|
88
|
+
fetchGoogleSubscription,
|
|
87
89
|
fetchGoogleUsageInfo,
|
|
88
90
|
decodeSubscription,
|
|
89
91
|
...streamDependencies
|
|
@@ -95,6 +97,7 @@ export function createGeminiAppProvider({
|
|
|
95
97
|
const resolvedAuth =
|
|
96
98
|
auth ||
|
|
97
99
|
createGeminiOAuthAuth({
|
|
100
|
+
...(fetchGoogleSubscription ? { fetchGoogleSubscription } : {}),
|
|
98
101
|
...(fetchGoogleUsageInfo ? { fetchGoogleUsageInfo } : {}),
|
|
99
102
|
...(decodeSubscription ? { decodeSubscription } : {}),
|
|
100
103
|
});
|
|
@@ -123,6 +126,7 @@ export function createGeminiAppProvider({
|
|
|
123
126
|
|
|
124
127
|
export function registerGeminiAppExtension(pi, dependencies = {}) {
|
|
125
128
|
const fetchUsage = dependencies?.fetchGoogleUsageInfo || defaultFetchGoogleUsageInfo;
|
|
129
|
+
const fetchSub = dependencies?.fetchGoogleSubscription || (dependencies?.fetchGoogleUsageInfo ? null : defaultFetchGoogleSubscription);
|
|
126
130
|
const decodeUsage = dependencies?.decodeUsageInfo || defaultDecodeUsageInfo;
|
|
127
131
|
const decodeSub = dependencies?.decodeSubscription || defaultDecodeSubscription;
|
|
128
132
|
|
|
@@ -130,6 +134,7 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
|
|
|
130
134
|
const {
|
|
131
135
|
createProvider: _ignoredCreateProvider,
|
|
132
136
|
auth,
|
|
137
|
+
fetchGoogleSubscription: _ignoredFetchSub,
|
|
133
138
|
fetchGoogleUsageInfo: _ignoredFetchUsage,
|
|
134
139
|
decodeUsageInfo: _ignoredDecodeUsage,
|
|
135
140
|
decodeSubscription: _ignoredDecodeSub,
|
|
@@ -138,6 +143,7 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
|
|
|
138
143
|
const resolvedAuth =
|
|
139
144
|
auth ||
|
|
140
145
|
createGeminiOAuthAuth({
|
|
146
|
+
...(dependencies?.fetchGoogleSubscription ? { fetchGoogleSubscription: dependencies.fetchGoogleSubscription } : {}),
|
|
141
147
|
...(dependencies?.fetchGoogleUsageInfo ? { fetchGoogleUsageInfo: dependencies.fetchGoogleUsageInfo } : {}),
|
|
142
148
|
...(dependencies?.decodeSubscription ? { decodeSubscription: dependencies.decodeSubscription } : {}),
|
|
143
149
|
});
|
|
@@ -191,12 +197,18 @@ export function registerGeminiAppExtension(pi, dependencies = {}) {
|
|
|
191
197
|
}
|
|
192
198
|
try {
|
|
193
199
|
ctx.ui?.notify?.('Fetching Gemini quota information...', 'info');
|
|
194
|
-
const
|
|
195
|
-
const
|
|
200
|
+
const opts = ctx?.signal ? { signal: ctx.signal } : undefined;
|
|
201
|
+
const [usageRes, subRes] = await Promise.all([
|
|
202
|
+
fetchUsage(token, opts),
|
|
203
|
+
fetchSub ? fetchSub(token, opts).catch(() => null) : Promise.resolve(null),
|
|
204
|
+
]);
|
|
205
|
+
const decoded = decodeUsage(usageRes.payload);
|
|
196
206
|
let subscription = null;
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
207
|
+
if (fetchSub && subRes?.payload) {
|
|
208
|
+
try {
|
|
209
|
+
subscription = decodeSub(subRes.payload);
|
|
210
|
+
} catch {}
|
|
211
|
+
}
|
|
200
212
|
const formatted = formatQuotaDisplay(decoded, subscription);
|
|
201
213
|
ctx.ui?.notify?.(formatted, 'info');
|
|
202
214
|
} catch (err) {
|
package/extensions/pi/stream.js
CHANGED
|
@@ -2,6 +2,7 @@ import { openDirectTurn as defaultOpenDirectTurn } from '../../src/gateway/nativ
|
|
|
2
2
|
import { createImageBlobCache } from '../../src/gateway/image-upload.mjs';
|
|
3
3
|
import { NativeDirectProvider as DefaultNativeDirectProvider } from '../../src/native-provider.mjs';
|
|
4
4
|
import { TOOL_ERRORS, automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
|
|
5
|
+
import { canCompleteInterruptedOutput } from '../../src/gateway/output-recovery.mjs';
|
|
5
6
|
import { buildChatPayload as defaultBuildChatPayload } from './transcript.js';
|
|
6
7
|
import { estimateUsage as defaultEstimateUsage, measurePromptImagePayload } from '../../src/openai-usage.mjs';
|
|
7
8
|
|
|
@@ -452,11 +453,18 @@ export function createGeminiStreamHandler({
|
|
|
452
453
|
}
|
|
453
454
|
break;
|
|
454
455
|
} catch (turnError) {
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
456
|
+
if (
|
|
457
|
+
canCompleteInterruptedOutput({
|
|
458
|
+
error: turnError,
|
|
459
|
+
publishedBytes,
|
|
460
|
+
callCount: toolCallCount,
|
|
461
|
+
hasVisibleText: publishedBytes > 0 || textBuffer.trim().length > 0,
|
|
462
|
+
aborted: options?.signal?.aborted === true,
|
|
463
|
+
allowPrefixPartialOnTransport: false,
|
|
464
|
+
salvageToolErrors: true,
|
|
465
|
+
toolErrors: TOOL_ERRORS,
|
|
466
|
+
})
|
|
467
|
+
) {
|
|
460
468
|
break;
|
|
461
469
|
}
|
|
462
470
|
if (
|
|
@@ -38,9 +38,10 @@ const stringValue = (fields, number) => {
|
|
|
38
38
|
return value === undefined ? null : utf8.decode(value);
|
|
39
39
|
};
|
|
40
40
|
/** Native ROBINRequestMetadata subset. No device IDs or hardware attestation. */
|
|
41
|
-
export function buildRequestMetadata({ clientType, languageCode, interfaceLanguageCode, clientVersion, clientInstanceId, triggerType, uiSource, clientFunctionCapabilities = false } = {}) {
|
|
41
|
+
export function buildRequestMetadata({ clientType, languageCode, interfaceLanguageCode, clientVersion, clientInstanceId, triggerType, uiSource, clientFunctionCapabilities = false, subscriptionTierCapability = false } = {}) {
|
|
42
42
|
if (!Number.isSafeInteger(clientType) || clientType < 0 || clientType > 255) throw new Error('Explicit client type required');
|
|
43
43
|
if (typeof clientFunctionCapabilities !== 'boolean') throw new TypeError('Invalid client-function capabilities');
|
|
44
|
+
if (typeof subscriptionTierCapability !== 'boolean') throw new TypeError('Invalid subscription-tier capability');
|
|
44
45
|
const fields = [];
|
|
45
46
|
if (triggerType !== undefined) {if (!Number.isSafeInteger(triggerType)||triggerType<0)throw new Error('Invalid trigger');fields.push(message(1,varintField(1,triggerType)));}
|
|
46
47
|
if (interfaceLanguageCode !== undefined) fields.push(message(2, string(1, interfaceLanguageCode)));
|
|
@@ -48,8 +49,12 @@ export function buildRequestMetadata({ clientType, languageCode, interfaceLangua
|
|
|
48
49
|
fields.push(varintField(4, clientType));
|
|
49
50
|
if (languageCode !== undefined) fields.push(string(7, languageCode));
|
|
50
51
|
if (uiSource !== undefined) {if (!Number.isSafeInteger(uiSource)||uiSource<0)throw new Error('Invalid UI source');fields.push(varintField(5,uiSource));}
|
|
51
|
-
// Metadata CapabilityType values, distinct from DesktopInfo capability enum 379.
|
|
52
|
-
|
|
52
|
+
// Metadata CapabilityType values (field 6.2), distinct from DesktopInfo capability enum 379.
|
|
53
|
+
// 529 = ENABLE_USER_SUBSCRIPTION_TIER; 668/669 = CLIENT_TOOLS / ROBIN_OP_CLIENT_FUNCTION_CALL.
|
|
54
|
+
const capabilities = [];
|
|
55
|
+
if (subscriptionTierCapability) capabilities.push(529);
|
|
56
|
+
if (clientFunctionCapabilities) capabilities.push(668, 669);
|
|
57
|
+
if (capabilities.length) fields.push(message(6, message(2, Buffer.concat(capabilities.map(varint)))));
|
|
53
58
|
if (clientInstanceId !== undefined) fields.push(string(23, clientInstanceId));
|
|
54
59
|
return Buffer.concat(fields);
|
|
55
60
|
}
|
|
@@ -142,31 +147,63 @@ export function frameGrpcMessage(bytes) {
|
|
|
142
147
|
export class GrpcMessageReader {
|
|
143
148
|
constructor({ maxBytes = MAX_MESSAGE_BYTES } = {}) {
|
|
144
149
|
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_MESSAGE_BYTES) throw new RangeError('Invalid frame budget');
|
|
145
|
-
this.maxBytes = maxBytes;
|
|
150
|
+
this.maxBytes = maxBytes;
|
|
151
|
+
this.header = Buffer.allocUnsafe(5);
|
|
152
|
+
this.headerBytes = 0;
|
|
153
|
+
this.expectedLength = null;
|
|
154
|
+
this.payloadChunks = [];
|
|
155
|
+
this.payloadBytes = 0;
|
|
156
|
+
this.closed = false;
|
|
146
157
|
}
|
|
147
158
|
push(bytes) {
|
|
148
159
|
if (this.closed) throw new Error('Reader already closed');
|
|
149
160
|
if (!Buffer.isBuffer(bytes)) throw new TypeError('Expected Buffer');
|
|
150
161
|
const frames = [];
|
|
151
|
-
// Accept concatenated chunks without allowing an unbounded pending allocation.
|
|
152
162
|
let offset = 0;
|
|
153
163
|
while (offset < bytes.length) {
|
|
154
|
-
|
|
164
|
+
if (this.expectedLength === null) {
|
|
165
|
+
const take = Math.min(5 - this.headerBytes, bytes.length - offset);
|
|
166
|
+
bytes.copy(this.header, this.headerBytes, offset, offset + take);
|
|
167
|
+
this.headerBytes += take;
|
|
168
|
+
offset += take;
|
|
169
|
+
if (this.headerBytes < 5) continue;
|
|
170
|
+
if (this.header[0] !== 0) throw new Error('Compressed gRPC messages not supported');
|
|
171
|
+
const length = this.header.readUInt32BE(1);
|
|
172
|
+
if (length > this.maxBytes) throw new RangeError('gRPC frame exceeds budget');
|
|
173
|
+
if (length === 0) {
|
|
174
|
+
frames.push(Buffer.alloc(0));
|
|
175
|
+
this.headerBytes = 0;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
this.expectedLength = length;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const needed = this.expectedLength - this.payloadBytes;
|
|
155
182
|
const take = Math.min(needed, bytes.length - offset);
|
|
156
|
-
|
|
183
|
+
const slice = bytes.subarray(offset, offset + take);
|
|
157
184
|
offset += take;
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
185
|
+
this.payloadBytes += take;
|
|
186
|
+
const owned = Buffer.from(slice);
|
|
187
|
+
if (this.payloadChunks.length === 0 && this.payloadBytes === this.expectedLength) {
|
|
188
|
+
frames.push(owned);
|
|
189
|
+
this.headerBytes = 0;
|
|
190
|
+
this.expectedLength = null;
|
|
191
|
+
this.payloadBytes = 0;
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
this.payloadChunks.push(owned);
|
|
195
|
+
if (this.payloadBytes === this.expectedLength) {
|
|
196
|
+
frames.push(Buffer.concat(this.payloadChunks, this.expectedLength));
|
|
197
|
+
this.headerBytes = 0;
|
|
198
|
+
this.expectedLength = null;
|
|
199
|
+
this.payloadChunks = [];
|
|
200
|
+
this.payloadBytes = 0;
|
|
164
201
|
}
|
|
165
202
|
}
|
|
166
203
|
return frames;
|
|
167
204
|
}
|
|
168
205
|
finish() {
|
|
169
206
|
this.closed = true;
|
|
170
|
-
if (this.
|
|
207
|
+
if (this.headerBytes > 0 || this.expectedLength !== null) throw new Error('Truncated gRPC stream');
|
|
171
208
|
}
|
|
172
209
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-gemini-app",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.15",
|
|
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": [
|
|
@@ -73,6 +73,7 @@
|
|
|
73
73
|
"src/gateway/quota.mjs",
|
|
74
74
|
"src/gateway/soft-error.mjs",
|
|
75
75
|
"src/gateway/structured-output.mjs",
|
|
76
|
+
"src/gateway/subscription-transport.mjs",
|
|
76
77
|
"src/gateway/subscription.mjs",
|
|
77
78
|
"src/gateway/terms.mjs",
|
|
78
79
|
"src/image-input.mjs",
|
|
@@ -57,3 +57,36 @@ export function isVerifiedEmptyResponse(error, model, { allowAutoModel = false }
|
|
|
57
57
|
e.http2ResetCode === undefined &&
|
|
58
58
|
(isAuto || ((e.fallback === undefined || e.fallback === 0) && (e.downgradeReason === undefined || e.downgradeReason === 0)));
|
|
59
59
|
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Shared terminal-outcome gate for interrupted turns across HTTP Gateway, Pi,
|
|
63
|
+
* OpenClaw, and OpenCode. Unverified output (refusal/downgrade/missing mode)
|
|
64
|
+
* and caller aborts NEVER qualify for partial-success completion.
|
|
65
|
+
*/
|
|
66
|
+
export function canCompleteInterruptedOutput({
|
|
67
|
+
error,
|
|
68
|
+
publishedBytes = 0,
|
|
69
|
+
callCount = 0,
|
|
70
|
+
hasVisibleText = false,
|
|
71
|
+
prefixBytes = 2048,
|
|
72
|
+
aborted = false,
|
|
73
|
+
allowPrefixPartialOnTransport = false,
|
|
74
|
+
salvageToolErrors = false,
|
|
75
|
+
toolErrors = null,
|
|
76
|
+
} = {}) {
|
|
77
|
+
if (aborted || error?.unverifiedOutput === true) return false;
|
|
78
|
+
if (allowPrefixPartialOnTransport) {
|
|
79
|
+
return (
|
|
80
|
+
publishedBytes >= prefixBytes ||
|
|
81
|
+
callCount > 0 ||
|
|
82
|
+
(error?.postOutputIdleStall === true && hasVisibleText)
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
const usableTimeout =
|
|
86
|
+
error?.code === 'NATIVE_TURN_TIMEOUT' &&
|
|
87
|
+
(callCount > 0 || (error?.postOutputIdleStall === true && hasVisibleText));
|
|
88
|
+
const salvageValidatedCalls = Boolean(
|
|
89
|
+
salvageToolErrors && callCount > 0 && toolErrors?.has?.(error?.code),
|
|
90
|
+
);
|
|
91
|
+
return usableTimeout || salvageValidatedCalls;
|
|
92
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Read-only GetUserStatus tier lookup. No generation, quota mutation, terms acceptance or retry.
|
|
2
|
+
import http2 from 'node:http2';
|
|
3
|
+
import { GrpcMessageReader, frameGrpcMessage, GATEWAY_USER_AGENT } from '../../native-wire/robin-current.mjs';
|
|
4
|
+
import { buildSubscriptionRequest } from './subscription.mjs';
|
|
5
|
+
import { connectHttp2 } from './outbound-proxy.mjs';
|
|
6
|
+
export const SUBSCRIPTION_ORIGIN = 'https://robinfrontend-pa.googleapis.com';
|
|
7
|
+
export const SUBSCRIPTION_RPC = '/assistant.mobile.robin.RobinService/GetUserStatus';
|
|
8
|
+
const failure = (code, status = 502) => Object.assign(new Error(code), { code, status });
|
|
9
|
+
export async function fetchGoogleSubscription(accessToken, { signal, timeoutMs = 10000, connect = connectHttp2 } = {}) {
|
|
10
|
+
if (typeof accessToken !== 'string' || !accessToken || accessToken.length > 65536 || /\s/.test(accessToken)) throw failure('SUBSCRIPTION_CREDENTIAL_REQUIRED', 401);
|
|
11
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 15000) throw failure('INVALID_SUBSCRIPTION_TIMEOUT', 400);
|
|
12
|
+
if (signal?.aborted) throw failure('SUBSCRIPTION_CANCELLED', 499);
|
|
13
|
+
const payload = buildSubscriptionRequest();
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
let client, request, timer, settled = false, httpStatus = null, grpcStatus = null, received = 0;
|
|
16
|
+
const messages = [], reader = new GrpcMessageReader({ maxBytes: 512 * 1024 });
|
|
17
|
+
const finish = (error, result) => {
|
|
18
|
+
if (settled) return;
|
|
19
|
+
settled = true; clearTimeout(timer); signal?.removeEventListener('abort', abort);
|
|
20
|
+
try { request?.close(error ? http2.constants.NGHTTP2_CANCEL : http2.constants.NGHTTP2_NO_ERROR); } catch {}
|
|
21
|
+
const session = client;
|
|
22
|
+
if (session) {
|
|
23
|
+
const cleanup = setTimeout(() => { try { session.destroy(); } catch {} }, 250); cleanup.unref();
|
|
24
|
+
session.once?.('close', () => clearTimeout(cleanup));
|
|
25
|
+
try { if (typeof session.close === 'function') session.close(); else { clearTimeout(cleanup); session.destroy(); } }
|
|
26
|
+
catch { clearTimeout(cleanup); try { session.destroy(); } catch {} }
|
|
27
|
+
}
|
|
28
|
+
if (error) reject(error); else resolve(result);
|
|
29
|
+
};
|
|
30
|
+
const abort = () => finish(failure('SUBSCRIPTION_CANCELLED', 499));
|
|
31
|
+
const reset = () => {
|
|
32
|
+
if (Number.isInteger(request?.rstCode) && request.rstCode > 0) { finish(failure('SUBSCRIPTION_STREAM_RESET')); return true; }
|
|
33
|
+
return false;
|
|
34
|
+
};
|
|
35
|
+
const status = headers => {
|
|
36
|
+
if (headers[':status'] !== undefined) {
|
|
37
|
+
httpStatus = Number(headers[':status']);
|
|
38
|
+
if (httpStatus === 429) return finish(failure('SUBSCRIPTION_RATE_LIMITED', 429));
|
|
39
|
+
if ([401, 403].includes(httpStatus)) return finish(failure('SUBSCRIPTION_AUTH_REJECTED', httpStatus));
|
|
40
|
+
if (httpStatus !== 200) return finish(failure('SUBSCRIPTION_HTTP_REJECTED'));
|
|
41
|
+
}
|
|
42
|
+
if (headers['grpc-status'] !== undefined) {
|
|
43
|
+
const raw = String(headers['grpc-status']);
|
|
44
|
+
if (!/^\d{1,2}$/.test(raw) || Number(raw) > 16) return finish(failure('SUBSCRIPTION_INVALID_STATUS'));
|
|
45
|
+
grpcStatus = Number(raw);
|
|
46
|
+
if (grpcStatus === 8) return finish(failure('SUBSCRIPTION_RATE_LIMITED', 429));
|
|
47
|
+
if ([7, 16].includes(grpcStatus)) return finish(failure('SUBSCRIPTION_AUTH_REJECTED', 403));
|
|
48
|
+
if (grpcStatus !== 0) return finish(failure(grpcStatus === 9 ? 'SUBSCRIPTION_PRECONDITION_REQUIRED' : 'SUBSCRIPTION_UPSTREAM_REJECTED'));
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
52
|
+
timer = setTimeout(() => finish(failure('SUBSCRIPTION_TIMEOUT', 504)), timeoutMs);
|
|
53
|
+
try {
|
|
54
|
+
client = connect(SUBSCRIPTION_ORIGIN); client.on('error', () => finish(failure('SUBSCRIPTION_CONNECTION_FAILED')));
|
|
55
|
+
request = client.request({ ':method': 'POST', ':path': SUBSCRIPTION_RPC, authorization: 'Bearer ' + accessToken,
|
|
56
|
+
'content-type': 'application/grpc', te: 'trailers', 'grpc-timeout': timeoutMs + 'm', 'user-agent': GATEWAY_USER_AGENT });
|
|
57
|
+
request.on('response', status); request.on('trailers', status);
|
|
58
|
+
request.on('data', chunk => {
|
|
59
|
+
if (settled) return;
|
|
60
|
+
received += chunk.length;
|
|
61
|
+
if (received > 1024 * 1024) return finish(failure('SUBSCRIPTION_RESPONSE_TOO_LARGE'));
|
|
62
|
+
try { messages.push(...reader.push(chunk)); if (messages.length > 1) finish(failure('SUBSCRIPTION_INVALID_RESPONSE')); }
|
|
63
|
+
catch { finish(failure('SUBSCRIPTION_INVALID_RESPONSE')); }
|
|
64
|
+
});
|
|
65
|
+
request.on('error', () => { if (!settled && !reset()) finish(failure('SUBSCRIPTION_STREAM_FAILED')); });
|
|
66
|
+
request.on('close', () => { if (!settled && !reset()) finish(failure('SUBSCRIPTION_STREAM_CLOSED_EARLY')); });
|
|
67
|
+
request.on('end', () => {
|
|
68
|
+
if (settled || reset()) return;
|
|
69
|
+
try {
|
|
70
|
+
reader.finish();
|
|
71
|
+
if (httpStatus !== 200 || grpcStatus !== 0 || messages.length !== 1) return finish(failure('SUBSCRIPTION_INCOMPLETE_RESPONSE'));
|
|
72
|
+
finish(null, { payload: messages[0], observedAt: new Date().toISOString(), httpStatus, grpcStatus });
|
|
73
|
+
} catch { finish(failure('SUBSCRIPTION_INVALID_RESPONSE')); }
|
|
74
|
+
});
|
|
75
|
+
request.end(frameGrpcMessage(payload));
|
|
76
|
+
} catch { finish(failure('SUBSCRIPTION_CONNECTION_FAILED')); }
|
|
77
|
+
});
|
|
78
|
+
}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
|
|
1
|
+
// GetUserStatusResponse.user_subscription_tier (wire field 21) uses the native UserSubscriptionTier enum.
|
|
2
|
+
// Requires RequestMetadata.clientCapabilities (field 6.2) with CapabilityType.ENABLE_USER_SUBSCRIPTION_TIER (529).
|
|
3
|
+
// GetUsageInfo.user_tier (field 2) is unreliable on upstream (reports TIER1 even for Free accounts).
|
|
4
|
+
import { parse, lengthDelimited } from '../../native-wire/protobuf.mjs';
|
|
5
|
+
import { buildRequestMetadata } from '../../native-wire/robin-current.mjs';
|
|
4
6
|
import { fault } from './oauth-client-defaults.mjs';
|
|
5
|
-
export const SUBSCRIPTION_FIELDS = Object.freeze({ nativeTier:
|
|
7
|
+
export const SUBSCRIPTION_FIELDS = Object.freeze({ nativeTier: 21, isForced: 29 });
|
|
8
|
+
export const SUBSCRIPTION_CAPABILITY_USER_TIER = 529;
|
|
6
9
|
const TIERS = Object.freeze({ 1: 'free', 2: 'pro', 3: 'ultra', 4: 'plus', 5: 'ultra_neon' });
|
|
7
10
|
const NAMES = Object.freeze({ 0: 'TIER_UNSPECIFIED', 1: 'BASIC_USER', 2: 'TIER1', 3: 'TIER2', 4: 'LITE_USER', 5: 'TIER_NEON' });
|
|
8
11
|
const CODES = new Set(['SUBSCRIPTION_CREDENTIAL_REQUIRED', 'INVALID_SUBSCRIPTION_TIMEOUT', 'INVALID_SUBSCRIPTION_METADATA',
|
|
@@ -18,34 +21,48 @@ const timestamp = value => {
|
|
|
18
21
|
const ms = Date.parse(value); return Number.isFinite(ms) && ms >= 0 ? new Date(ms).toISOString() : null;
|
|
19
22
|
};
|
|
20
23
|
export const subscriptionFailureCode = error => CODES.has(error?.code) ? error.code : 'SUBSCRIPTION_FETCH_FAILED';
|
|
21
|
-
//
|
|
22
|
-
export const buildSubscriptionRequest = () =>
|
|
24
|
+
// Read-only GetUserStatus request with RequestMetadata (field 1) advertising ENABLE_USER_SUBSCRIPTION_TIER (529).
|
|
25
|
+
export const buildSubscriptionRequest = () => lengthDelimited(
|
|
26
|
+
1,
|
|
27
|
+
buildRequestMetadata({
|
|
28
|
+
clientType: 21,
|
|
29
|
+
uiSource: 1,
|
|
30
|
+
languageCode: 'en',
|
|
31
|
+
interfaceLanguageCode: 'en',
|
|
32
|
+
subscriptionTierCapability: true,
|
|
33
|
+
}),
|
|
34
|
+
);
|
|
23
35
|
export function safeSubscription(input) {
|
|
24
36
|
const value = input && typeof input === 'object' && !Array.isArray(input) ? input : {};
|
|
25
|
-
const official = value.source === 'official' && value.provider === 'google-robin' && value.rpc === '
|
|
37
|
+
const official = value.source === 'official' && value.provider === 'google-robin' && value.rpc === 'GetUserStatus';
|
|
26
38
|
const nativeTier = official ? integer(value.nativeTier) : null, tier = TIERS[nativeTier] ?? 'unknown';
|
|
39
|
+
const isForced = official && typeof value.isForced === 'boolean' ? value.isForced : null;
|
|
27
40
|
let status = ['unqueried', 'ok', 'missing', 'error'].includes(value.status) ? value.status : 'unqueried';
|
|
28
41
|
if (status === 'ok' && (!official || tier === 'unknown')) status = 'missing';
|
|
29
|
-
return { source: official ? 'official' : 'unknown', provider: official ? 'google-robin' : null, rpc: official ? '
|
|
42
|
+
return { source: official ? 'official' : 'unknown', provider: official ? 'google-robin' : null, rpc: official ? 'GetUserStatus' : null, status,
|
|
30
43
|
tier, nativeTier, nativeTierName: nativeTier === null ? null : NAMES[nativeTier] ?? 'UNRECOGNIZED',
|
|
31
|
-
//
|
|
32
|
-
nativeState: null, membershipStatus: 'unknown', isForced
|
|
44
|
+
// GetUserStatus does not establish billing/cancellation ownership details.
|
|
45
|
+
nativeState: null, membershipStatus: 'unknown', isForced,
|
|
33
46
|
updatedAt: timestamp(value.updatedAt), lastAttemptAt: timestamp(value.lastAttemptAt),
|
|
34
47
|
errorCode: status === 'error' ? subscriptionFailureCode({ code: value.errorCode }) : null };
|
|
35
48
|
}
|
|
49
|
+
function decodeBoundedVarint(payload, max = 0x7fffffffn) {
|
|
50
|
+
if (!payload.length || payload.length > 10 || (payload.at(-1) & 128)) throw Error();
|
|
51
|
+
let value = 0n, shift = 0n;
|
|
52
|
+
for (const byte of payload) { value |= BigInt(byte & 127) << shift; shift += 7n; }
|
|
53
|
+
if (value > max) throw Error();
|
|
54
|
+
return Number(value);
|
|
55
|
+
}
|
|
36
56
|
export function decodeSubscription(payload) {
|
|
37
57
|
try {
|
|
38
58
|
if (!Buffer.isBuffer(payload) || payload.length > 512 * 1024) throw Error();
|
|
39
59
|
const fields = parse(payload); if (fields.length > 10000) throw Error();
|
|
40
|
-
const found = fields.filter(field => field.number ===
|
|
60
|
+
const found = fields.filter(field => field.number === SUBSCRIPTION_FIELDS.nativeTier);
|
|
41
61
|
if (found.length > 1 || (found.length && found[0].wire !== 0)) throw Error();
|
|
42
|
-
|
|
43
|
-
if (
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
nativeTier = Number(value);
|
|
48
|
-
}
|
|
49
|
-
return safeSubscription({ source: 'official', provider: 'google-robin', rpc: 'GetUsageInfo', status: TIERS[nativeTier] ? 'ok' : 'missing', nativeTier });
|
|
62
|
+
const forced = fields.filter(field => field.number === SUBSCRIPTION_FIELDS.isForced);
|
|
63
|
+
if (forced.length > 1 || (forced.length && forced[0].wire !== 0)) throw Error();
|
|
64
|
+
const nativeTier = found.length ? decodeBoundedVarint(found[0].payload) : null;
|
|
65
|
+
const isForced = forced.length ? decodeBoundedVarint(forced[0].payload, 1n) === 1 : null;
|
|
66
|
+
return safeSubscription({ source: 'official', provider: 'google-robin', rpc: 'GetUserStatus', status: TIERS[nativeTier] ? 'ok' : 'missing', nativeTier, isForced });
|
|
50
67
|
} catch { throw fault('INVALID_SUBSCRIPTION_METADATA', 502); }
|
|
51
68
|
}
|
package/src/native-provider.mjs
CHANGED
|
@@ -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_ALIASES, MODEL_MODES, MODEL_SPECS, NATIVE_MODELS, PROMPT_MAX_BYTES, canonicalModel, normalizeChatRequest, normalizeResponsesRequest, buildCanonicalPrompt, writeChatResponse, writeResponsesResponse } from './openai-contract.mjs';
|
|
10
|
+
import { MODEL_ALIASES, MODEL_MODES, MODEL_SPECS, NATIVE_MODELS, PROMPT_MAX_BYTES, CANONICAL_BUILT, 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';
|
|
@@ -355,7 +355,11 @@ export class NativeDirectProvider {
|
|
|
355
355
|
: this.maxPostOutputThoughtHoldMs !== undefined
|
|
356
356
|
? this.maxPostOutputThoughtHoldMs
|
|
357
357
|
: (postOutputToolIdleMs === null ? null : Math.min(600_000, postOutputToolIdleMs * 3));
|
|
358
|
-
const body =
|
|
358
|
+
const body =
|
|
359
|
+
context.preNormalized === true &&
|
|
360
|
+
canonicalChatBody?.[CANONICAL_BUILT]?.allowAutoModel === this.allowAutoModel
|
|
361
|
+
? canonicalChatBody
|
|
362
|
+
: normalizeChatRequest(canonicalChatBody, { allowAutoModel: this.allowAutoModel });
|
|
359
363
|
if (body.native_search) return this.runNativeSearch(accountId, body, onDelta, { ...context, timeoutMs });
|
|
360
364
|
const recoveryInstruction = toolRecoveryInstruction(context.recoveryCode, context.recoveryReason);
|
|
361
365
|
const appendRecovery = promptMessages => {
|
|
@@ -370,7 +374,7 @@ export class NativeDirectProvider {
|
|
|
370
374
|
};
|
|
371
375
|
if (this.allowTextSnapshotReplacement && body.tools.length) fail('NATIVE_TEXT_SNAPSHOT_TOOLS_FORBIDDEN', 400);
|
|
372
376
|
const policy = compileToolPolicy(body.tools, body.tool_choice);
|
|
373
|
-
let { messages, images } = buildCanonicalPrompt(body);
|
|
377
|
+
let { messages, images } = body[CANONICAL_BUILT] ?? buildCanonicalPrompt(body);
|
|
374
378
|
messages = appendRecovery(messages);
|
|
375
379
|
const isAutoModel = this.allowAutoModel && body.model === 'gemini-auto';
|
|
376
380
|
const modeCategory = isAutoModel ? null : MODEL_MODES[body.model];
|
|
@@ -980,7 +984,7 @@ export class NativeDirectProvider {
|
|
|
980
984
|
nativeTextBytes: Buffer.byteLength(rawText), ...outputShape,
|
|
981
985
|
nativeResponseRevisions: revisionCount, nativeResponseIdentityVerified: snapshotId !== null });
|
|
982
986
|
phase = 'output';
|
|
983
|
-
if (!incremental) await deliverNonIncremental(items, content, calls);
|
|
987
|
+
if (!incremental) await deliverNonIncremental(items, content, calls, { includeMeta: context.incrementalOutput === true || calls.length > 0 });
|
|
984
988
|
note('provider_success');
|
|
985
989
|
return result;
|
|
986
990
|
} catch (error) {
|
package/src/openai-contract.mjs
CHANGED
|
@@ -14,6 +14,7 @@ import { MAX_IMAGES, MAX_IMAGE_URL_BYTES, MAX_TOTAL_IMAGE_URL_BYTES, normalizeIm
|
|
|
14
14
|
import { RESPONSE_TOOL_IDENTITIES, normalizeResponsesTools, responsesCallFields } from './responses-tool-namespaces.mjs';
|
|
15
15
|
import { toResponsesUsage } from './openai-usage.mjs';
|
|
16
16
|
|
|
17
|
+
export const CANONICAL_BUILT = Symbol('canonicalBuilt');
|
|
17
18
|
const fail = (code, status = 400, param = null) => { throw protocolError(code, status, param); };
|
|
18
19
|
export const NATIVE_MODELS = Object.freeze(['gemini-neon', 'gemini-hydrogen', 'gemini-flash-lite']);
|
|
19
20
|
// Temporary compatibility alias while clients migrate from retired gemini-argon (mode 8) to gemini-neon (mode 3).
|
|
@@ -438,6 +439,15 @@ export function normalizeChatRequest(payload, { allowAutoModel = false, _imageCa
|
|
|
438
439
|
const built = buildCanonicalPrompt(body, undefined, imageCache); // Validate budgets BEFORE any account reservation.
|
|
439
440
|
body[CANONICAL_PROMPT_CHARS] = built.messages.reduce((sum, m) => sum + (typeof m?.content === 'string' ? m.content.length : 0), 0);
|
|
440
441
|
body[CANONICAL_IMAGE_COUNT] = built.images.length;
|
|
442
|
+
Object.defineProperty(body, CANONICAL_BUILT, {
|
|
443
|
+
value: Object.freeze({
|
|
444
|
+
messages: built.messages,
|
|
445
|
+
images: built.images,
|
|
446
|
+
toolCount: built.toolCount,
|
|
447
|
+
allowAutoModel,
|
|
448
|
+
}),
|
|
449
|
+
enumerable: false,
|
|
450
|
+
});
|
|
441
451
|
return body;
|
|
442
452
|
}
|
|
443
453
|
|
|
@@ -688,7 +698,7 @@ export function writeChatResponse(res, result, { stream = false, includeUsage =
|
|
|
688
698
|
return;
|
|
689
699
|
}
|
|
690
700
|
res.writeHead(200, { ...streamHeaders, ...thinkingHeaders(result) });
|
|
691
|
-
const send = (delta, finish_reason = null) => res.write('data: ' + JSON.stringify({ ...base, ...(finish_reason && result.nativeSearch ? {native_search: result.nativeSearch} : {}), choices: [{ index: 0, delta, finish_reason }], ...(includeUsage ? { usage:
|
|
701
|
+
const send = (delta, finish_reason = null) => res.write('data: ' + JSON.stringify({ ...base, ...(finish_reason && result.nativeSearch ? {native_search: result.nativeSearch} : {}), choices: [{ index: 0, delta, finish_reason }], ...(includeUsage ? { usage: null } : {}) }) + '\n\n');
|
|
692
702
|
send({ role: 'assistant' });
|
|
693
703
|
if (result.content) send({ content: result.content });
|
|
694
704
|
result.calls.forEach((call, index) => send({ tool_calls: [{ index, ...call }] }));
|