opencode-gemini-app 0.0.0-stage → 0.1.1

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 (42) hide show
  1. package/DISCLAIMER.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +46 -2
  4. package/extensions/opencode/auth.js +324 -0
  5. package/extensions/opencode/fetch.js +494 -0
  6. package/extensions/opencode/index.js +27 -0
  7. package/extensions/opencode/models.js +84 -0
  8. package/extensions/pi/auth.js +215 -0
  9. package/native-wire/consumer-tool-codec.mjs +239 -0
  10. package/native-wire/oauth-loopback.mjs +175 -0
  11. package/native-wire/protobuf.mjs +133 -0
  12. package/native-wire/robin-current.mjs +172 -0
  13. package/package.json +75 -4
  14. package/src/gateway/automatic-recovery.mjs +70 -0
  15. package/src/gateway/image-download.mjs +110 -0
  16. package/src/gateway/image-upload.mjs +262 -0
  17. package/src/gateway/native-diagnostic.mjs +190 -0
  18. package/src/gateway/native-evidence.mjs +114 -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 +433 -0
  24. package/src/gateway/oauth-client-defaults.mjs +12 -0
  25. package/src/gateway/oauth-identity.mjs +67 -0
  26. package/src/gateway/outbound-proxy.mjs +320 -0
  27. package/src/gateway/output-recovery.mjs +48 -0
  28. package/src/gateway/quota-failover.mjs +14 -0
  29. package/src/gateway/quota-transport.mjs +37 -0
  30. package/src/gateway/quota.mjs +181 -0
  31. package/src/gateway/soft-error.mjs +25 -0
  32. package/src/gateway/structured-output.mjs +157 -0
  33. package/src/gateway/subscription.mjs +51 -0
  34. package/src/gateway/terms.mjs +126 -0
  35. package/src/image-input.mjs +137 -0
  36. package/src/image-url.mjs +21 -0
  37. package/src/native-provider.mjs +806 -0
  38. package/src/openai-contract.mjs +576 -0
  39. package/src/openai-usage.mjs +66 -0
  40. package/src/prompt-tool-schema.mjs +391 -0
  41. package/src/responses-tool-namespaces.mjs +84 -0
  42. package/src/tool-protocol.mjs +366 -0
@@ -0,0 +1,320 @@
1
+ /** Zero-dependency outbound HTTP(S) proxy helper for Node HTTP/2 and HTTPS fetch.
2
+ * Respects HTTPS_PROXY / HTTP_PROXY / ALL_PROXY and NO_PROXY without logging proxy credentials.
3
+ */
4
+ import http from 'node:http';
5
+ import https from 'node:https';
6
+ import http2 from 'node:http2';
7
+ import net from 'node:net';
8
+ import tls from 'node:tls';
9
+ import { Duplex, Readable } from 'node:stream';
10
+
11
+ const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
12
+
13
+ function stripBrackets(host) {
14
+ return host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
15
+ }
16
+
17
+ function defaultPort(protocol) {
18
+ return protocol === 'https:' ? '443' : '80';
19
+ }
20
+
21
+ function isBypassed(target, noProxyRaw) {
22
+ if (typeof noProxyRaw !== 'string' || !noProxyRaw.trim()) return false;
23
+ const host = stripBrackets(target.hostname).toLowerCase();
24
+ const port = target.port || defaultPort(target.protocol);
25
+ for (const rawEntry of noProxyRaw.split(',')) {
26
+ const entry = rawEntry.trim().toLowerCase();
27
+ if (!entry) continue;
28
+ if (entry === '*') return true;
29
+ let entryHost = entry;
30
+ let entryPort = null;
31
+ if (entry.startsWith('[')) {
32
+ const end = entry.indexOf(']');
33
+ if (end < 0) continue;
34
+ entryHost = entry.slice(1, end);
35
+ if (entry[end + 1] === ':') entryPort = entry.slice(end + 2);
36
+ } else {
37
+ const colon = entry.lastIndexOf(':');
38
+ if (colon > 0 && /^\d+$/.test(entry.slice(colon + 1))) {
39
+ entryHost = entry.slice(0, colon);
40
+ entryPort = entry.slice(colon + 1);
41
+ }
42
+ }
43
+ if (entryPort && entryPort !== port) continue;
44
+ const normalized = entryHost.startsWith('.') ? entryHost.slice(1) : entryHost;
45
+ if (!normalized) continue;
46
+ if (host === normalized || host.endsWith('.' + normalized)) return true;
47
+ }
48
+ return false;
49
+ }
50
+
51
+ export function resolveOutboundProxy(targetUrl, env = process.env) {
52
+ if (!env || typeof env !== 'object') return null;
53
+ let target;
54
+ try { target = targetUrl instanceof URL ? targetUrl : new URL(targetUrl); } catch { return null; }
55
+ if (target.protocol !== 'https:' && target.protocol !== 'http:') return null;
56
+ if (isBypassed(target, env.NO_PROXY ?? env.no_proxy ?? '')) return null;
57
+ const raw = target.protocol === 'https:'
58
+ ? (env.HTTPS_PROXY || env.https_proxy || env.ALL_PROXY || env.all_proxy || '')
59
+ : (env.HTTP_PROXY || env.http_proxy || env.ALL_PROXY || env.all_proxy || '');
60
+ const trimmed = typeof raw === 'string' ? raw.trim() : '';
61
+ if (!trimmed || /[\r\n\0]/.test(trimmed)) return null;
62
+ let proxy;
63
+ try { proxy = new URL(trimmed); } catch { return null; }
64
+ if ((proxy.protocol !== 'http:' && proxy.protocol !== 'https:') || !proxy.hostname) return null;
65
+ return proxy;
66
+ }
67
+
68
+ function formatAuthority(host, port) {
69
+ const bare = stripBrackets(host);
70
+ return bare.includes(':') ? `[${bare}]:${port}` : `${bare}:${port}`;
71
+ }
72
+
73
+ export function createConnectTunnel(
74
+ proxyUrl,
75
+ targetHost,
76
+ targetPort,
77
+ { timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS, signal, rejectUnauthorized = true, ca } = {},
78
+ ) {
79
+ const authority = formatAuthority(targetHost, targetPort);
80
+ const headers = { Host: authority };
81
+ if (proxyUrl.username || proxyUrl.password) {
82
+ const user = decodeURIComponent(proxyUrl.username || '');
83
+ const pass = decodeURIComponent(proxyUrl.password || '');
84
+ headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(`${user}:${pass}`, 'utf8').toString('base64');
85
+ }
86
+ let rawSocket = null;
87
+ let connected = false;
88
+ let finished = false;
89
+ let finalCallback = null;
90
+ const pendingWrites = [];
91
+
92
+ const failPending = (err) => {
93
+ while (pendingWrites.length) {
94
+ const item = pendingWrites.shift();
95
+ try { item.callback(err); } catch {}
96
+ }
97
+ if (finalCallback) {
98
+ const cb = finalCallback;
99
+ finalCallback = null;
100
+ try { cb(err); } catch {}
101
+ }
102
+ };
103
+
104
+ const tunnel = new Duplex({
105
+ read() {
106
+ rawSocket?.resume();
107
+ },
108
+ write(chunk, encoding, callback) {
109
+ if (connected && rawSocket) {
110
+ if (rawSocket.destroyed) { callback(new Error('PROXY_TUNNEL_CLOSED')); return; }
111
+ rawSocket.write(chunk, encoding, callback);
112
+ return;
113
+ }
114
+ pendingWrites.push({ chunk, encoding, callback });
115
+ },
116
+ final(callback) {
117
+ finished = true;
118
+ if (connected && rawSocket) {
119
+ rawSocket.end(callback);
120
+ return;
121
+ }
122
+ finalCallback = callback;
123
+ },
124
+ destroy(err, callback) {
125
+ signal?.removeEventListener('abort', onAbort);
126
+ try { req.destroy(); } catch {}
127
+ try { rawSocket?.destroy(); } catch {}
128
+ failPending(err || new Error('PROXY_TUNNEL_DESTROYED'));
129
+ callback(err);
130
+ },
131
+ });
132
+
133
+ const onAbort = () => tunnel.destroy(new Error('PROXY_CONNECT_ABORTED'));
134
+ signal?.addEventListener('abort', onAbort, { once: true });
135
+
136
+ const transport = proxyUrl.protocol === 'https:' ? https : http;
137
+ const req = transport.request({
138
+ host: stripBrackets(proxyUrl.hostname),
139
+ port: Number(proxyUrl.port) || Number(defaultPort(proxyUrl.protocol)),
140
+ method: 'CONNECT',
141
+ path: authority,
142
+ headers,
143
+ timeout: timeoutMs,
144
+ ...(proxyUrl.protocol === 'https:' ? { rejectUnauthorized, ...(ca ? { ca } : {}) } : {}),
145
+ });
146
+
147
+ req.on('connect', (res, socket, head) => {
148
+ signal?.removeEventListener('abort', onAbort);
149
+ if (tunnel.destroyed) {
150
+ try { socket.destroy(); } catch {}
151
+ return;
152
+ }
153
+ if (res.statusCode !== 200) {
154
+ try { socket.destroy(); } catch {}
155
+ tunnel.destroy(new Error(`PROXY_CONNECT_REJECTED_${res.statusCode || 0}`));
156
+ return;
157
+ }
158
+ rawSocket = socket;
159
+ connected = true;
160
+ try { socket.setKeepAlive?.(true, 15_000); } catch {}
161
+ try { socket.setNoDelay?.(true); } catch {}
162
+ socket.on('data', (chunk) => {
163
+ if (!tunnel.destroyed && !tunnel.push(chunk)) socket.pause();
164
+ });
165
+ socket.on('end', () => {
166
+ if (!tunnel.destroyed) tunnel.push(null);
167
+ });
168
+ socket.on('error', (err) => {
169
+ if (!tunnel.destroyed) tunnel.destroy(err);
170
+ });
171
+ socket.on('close', () => {
172
+ if (!tunnel.destroyed) tunnel.destroy();
173
+ });
174
+ if (head && head.length > 0 && !tunnel.push(head)) socket.pause();
175
+ while (pendingWrites.length) {
176
+ const item = pendingWrites.shift();
177
+ socket.write(item.chunk, item.encoding, item.callback);
178
+ }
179
+ if (finished) {
180
+ const cb = finalCallback;
181
+ finalCallback = null;
182
+ socket.end(cb || undefined);
183
+ }
184
+ });
185
+
186
+ req.on('response', (res) => {
187
+ res.resume();
188
+ if (!tunnel.destroyed) tunnel.destroy(new Error(`PROXY_CONNECT_REJECTED_${res.statusCode || 0}`));
189
+ });
190
+ req.on('timeout', () => {
191
+ req.destroy();
192
+ if (!tunnel.destroyed) tunnel.destroy(new Error('PROXY_CONNECT_TIMEOUT'));
193
+ });
194
+ req.on('error', (err) => {
195
+ if (!tunnel.destroyed) tunnel.destroy(err);
196
+ });
197
+ req.end();
198
+
199
+ return tunnel;
200
+ }
201
+
202
+ export function connectHttp2(origin, options = {}, { env = process.env } = {}) {
203
+ const proxyUrl = resolveOutboundProxy(origin, env);
204
+ if (!proxyUrl) return http2.connect(origin, options);
205
+ const target = origin instanceof URL ? origin : new URL(origin);
206
+ if (target.protocol !== 'https:') return http2.connect(origin, options);
207
+ const targetHost = stripBrackets(target.hostname);
208
+ const targetPort = Number(target.port) || 443;
209
+ return http2.connect(origin, {
210
+ ...options,
211
+ createConnection: () => {
212
+ const tunnel = createConnectTunnel(proxyUrl, targetHost, targetPort, {
213
+ rejectUnauthorized: options?.proxyRejectUnauthorized ?? true,
214
+ ...(options?.proxyCa ? { ca: options.proxyCa } : {}),
215
+ });
216
+ return tls.connect({
217
+ socket: tunnel,
218
+ servername: net.isIP(targetHost) ? undefined : targetHost,
219
+ ALPNProtocols: ['h2'],
220
+ rejectUnauthorized: options?.rejectUnauthorized ?? true,
221
+ ...(options?.ca ? { ca: options.ca } : {}),
222
+ });
223
+ },
224
+ });
225
+ }
226
+
227
+ function normalizeRequestBody(body) {
228
+ if (body === undefined || body === null) return null;
229
+ if (Buffer.isBuffer(body)) return body;
230
+ if (body instanceof Uint8Array) return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
231
+ if (body instanceof URLSearchParams) return Buffer.from(body.toString(), 'utf8');
232
+ return Buffer.from(String(body), 'utf8');
233
+ }
234
+
235
+ function normalizeHeaders(headers) {
236
+ const out = {};
237
+ if (!headers) return out;
238
+ if (typeof headers.forEach === 'function') {
239
+ headers.forEach((value, key) => { out[key] = value; });
240
+ return out;
241
+ }
242
+ for (const [key, value] of Object.entries(headers)) {
243
+ if (value !== undefined) out[key] = value;
244
+ }
245
+ return out;
246
+ }
247
+
248
+ export async function fetchWithProxy(url, init = {}, { env = process.env, fetchImpl = fetch, tlsOptions = {} } = {}) {
249
+ const proxyUrl = fetchImpl === fetch ? resolveOutboundProxy(url, env) : null;
250
+ if (!proxyUrl) return fetchImpl(url, init);
251
+ const target = url instanceof URL ? url : new URL(url);
252
+ if (target.protocol !== 'https:') return fetchImpl(url, init);
253
+ const targetHost = stripBrackets(target.hostname);
254
+ const targetPort = Number(target.port) || 443;
255
+ const body = normalizeRequestBody(init.body);
256
+ const headers = normalizeHeaders(init.headers);
257
+ if (body && headers['content-length'] === undefined && headers['Content-Length'] === undefined) {
258
+ headers['Content-Length'] = String(body.length);
259
+ }
260
+ if (init.signal?.aborted) throw init.signal.reason || new DOMException('Aborted', 'AbortError');
261
+ return new Promise((resolve, reject) => {
262
+ let settled = false;
263
+ const done = (err, value) => {
264
+ if (settled) return;
265
+ settled = true;
266
+ init.signal?.removeEventListener('abort', onAbort);
267
+ if (err) reject(err); else resolve(value);
268
+ };
269
+ const tunnel = createConnectTunnel(proxyUrl, targetHost, targetPort, {
270
+ signal: init.signal,
271
+ rejectUnauthorized: tlsOptions.proxyRejectUnauthorized ?? true,
272
+ ...(tlsOptions.proxyCa ? { ca: tlsOptions.proxyCa } : {}),
273
+ });
274
+ const socket = tls.connect({
275
+ socket: tunnel,
276
+ servername: net.isIP(targetHost) ? undefined : targetHost,
277
+ ALPNProtocols: ['http/1.1'],
278
+ rejectUnauthorized: tlsOptions.rejectUnauthorized ?? true,
279
+ ...(tlsOptions.ca ? { ca: tlsOptions.ca } : {}),
280
+ });
281
+ const req = https.request({
282
+ host: targetHost,
283
+ port: targetPort,
284
+ path: target.pathname + target.search,
285
+ method: init.method || 'GET',
286
+ headers,
287
+ agent: false,
288
+ createConnection: () => socket,
289
+ }, (res) => {
290
+ const status = res.statusCode || 502;
291
+ if (init.redirect === 'error' && status >= 300 && status < 400 && res.headers.location) {
292
+ res.destroy();
293
+ done(new TypeError('Unexpected redirect'));
294
+ return;
295
+ }
296
+ const responseHeaders = new Headers();
297
+ for (const [k, v] of Object.entries(res.headers)) {
298
+ if (v === undefined) continue;
299
+ if (Array.isArray(v)) for (const item of v) responseHeaders.append(k, item);
300
+ else responseHeaders.set(k, String(v));
301
+ }
302
+ const webBody = status === 204 || status === 304 || init.method === 'HEAD' ? null : Readable.toWeb(res);
303
+ done(null, new Response(webBody, { status, headers: responseHeaders }));
304
+ });
305
+ const onAbort = () => {
306
+ req.destroy();
307
+ socket.destroy();
308
+ tunnel.destroy();
309
+ done(init.signal?.reason || new DOMException('Aborted', 'AbortError'));
310
+ };
311
+ init.signal?.addEventListener('abort', onAbort, { once: true });
312
+ req.on('error', (err) => {
313
+ socket.destroy();
314
+ tunnel.destroy();
315
+ done(err);
316
+ });
317
+ if (body) req.write(body);
318
+ req.end();
319
+ });
320
+ }
@@ -0,0 +1,48 @@
1
+ // Only a fully completed, verified empty ordinary turn is recoverable automatically.
2
+ // Never promote thoughts/shareable/structured output to an assistant answer.
3
+ import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
4
+ import { parse } from '../../native-wire/protobuf.mjs';
5
+ import { protocolError } from '../tool-protocol.mjs';
6
+ export const EMPTY_RESPONSE_REASONS = Object.freeze(['no_text', 'whitespace_only', 'thoughts_only', 'post_parse_empty']);
7
+ export function inspectNativeOutput(fields) {
8
+ const singular = (list, number, wire = 2) => {
9
+ const found = list.filter(field => field.number === number);
10
+ if (found.length > 1 || found.some(field => field.wire !== wire)) throw protocolError('INVALID_NATIVE_RESPONSE', 502);
11
+ return found[0];
12
+ };
13
+ const refusal = [13, 17].some(number => singular(fields, number) !== undefined);
14
+ const model = singular(fields, 1), mf = model ? parse(model.payload) : [];
15
+ const shareable = singular(mf, 7), thoughts = singular(mf, 12);
16
+ const tf = thoughts ? parse(thoughts.payload) : [];
17
+ const thoughtText = singular(tf, 1);
18
+ const thoughtsPresent = !!thoughtText?.payload.length || tf.some(field => field.number === 3 && field.wire === 2 && field.payload.length > 0);
19
+ // Descriptor model field19 is completenessState. Retain only the bounded raw
20
+ // enum for diagnostics; its values are not established as acceptance rules.
21
+ const completeness = mf.filter(field => field.number === 19);
22
+ const cf = completeness.length === 1 && completeness[0].wire === 0 ? completeness[0] : null;
23
+ const completenessState = cf && cf.payload.length <= 5
24
+ ? cf.payload.reduce((value, byte, i) => value + (byte & 127) * 2 ** (7 * i), 0) : null;
25
+ // Native media/tree/artifact/goal channels are not caller-owned prompt tools.
26
+ const structured = [4, 5, 13, 21, 23, 24, 25].some(number => mf.some(field => field.number === number && field.payload.length > 0));
27
+ return { nativeShareableTextBytes: shareable?.payload.length ?? 0, nativeThoughtsPresent: thoughtsPresent,
28
+ nativeStructuredOutputPresent: structured, nativeRefusalPresent: refusal,
29
+ ...(Number.isSafeInteger(completenessState) && completenessState >= 0 && completenessState <= 0x7fffffff ? { nativeCompletenessState: completenessState } : {}) };
30
+ }
31
+ export function isVerifiedEmptyResponse(error, model, { allowAutoModel = false } = {}) {
32
+ const resolvedModel = canonicalModel(model);
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]);
38
+ return error?.status === 502 && error.code === 'EMPTY_NATIVE_RESPONSE' &&
39
+ e?.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 &&
40
+ e.wireEnded === true && e.modelCompleted === true && modeOk &&
41
+ ['no_text', 'whitespace_only', 'thoughts_only'].includes(e.emptyResponseReason) &&
42
+ Number.isSafeInteger(e.nativeTextBytes) && e.nativeTextBytes >= 0 && e.nativeTextBytes <= 8 * 1024 * 1024 &&
43
+ (e.emptyResponseReason === 'whitespace_only' ? e.nativeTextBytes > 0 : e.nativeTextBytes === 0) &&
44
+ typeof e.nativeThoughtsPresent === 'boolean' && (e.emptyResponseReason !== 'thoughts_only' || e.nativeThoughtsPresent === true) &&
45
+ e.nativeShareableTextBytes === 0 && e.nativeStructuredOutputPresent === false && e.nativeRefusalPresent === false &&
46
+ e.http2ResetCode === undefined &&
47
+ (isAuto || ((e.fallback === undefined || e.fallback === 0) && (e.downgradeReason === undefined || e.downgradeReason === 0)));
48
+ }
@@ -0,0 +1,14 @@
1
+ // Verified native BardModeDowngradeReason values, not inferred from model identity.
2
+ export const QUOTA_DOWNGRADE_REASONS = Object.freeze({
3
+ 2: 'QUOTA_EXHAUSTED',
4
+ 3: 'FAST_FLASH_QUOTA_EXHAUSTED',
5
+ 6: 'GXU_QUOTA_EXHAUSTED',
6
+ 8: 'GXU_BUDGET_LOW',
7
+ });
8
+ export function quotaDowngradeCode(reason) {
9
+ if (!Number.isSafeInteger(reason) || !Object.hasOwn(QUOTA_DOWNGRADE_REASONS, reason)) return null;
10
+ return reason === 8 ? 'NATIVE_QUOTA_INSUFFICIENT' : 'NATIVE_QUOTA_EXHAUSTED';
11
+ }
12
+ export function isExplicitQuotaFailure(error) {
13
+ return error?.status === 429 && ['NATIVE_QUOTA_EXHAUSTED', 'NATIVE_QUOTA_INSUFFICIENT'].includes(error.code);
14
+ }
@@ -0,0 +1,37 @@
1
+ // Read-only Google quota RPC; no generation, quota reset, retry, redirects or model switching.
2
+ import {GrpcMessageReader,frameGrpcMessage,GATEWAY_USER_AGENT} from "../../native-wire/robin-current.mjs";
3
+ import {connectHttp2} from "./outbound-proxy.mjs";
4
+ export const QUOTA_ORIGIN = "https://robinfrontend-pa.googleapis.com";
5
+ export const QUOTA_RPC = "/assistant.mobile.robin.RobinService/GetUsageInfo";
6
+ const failure=(code,status=502)=>Object.assign(new Error(code),{code,status});
7
+ export async function fetchGoogleUsageInfo(accessToken,{signal,timeoutMs=10000,connect=connectHttp2}={}) {
8
+ if(typeof accessToken!=="string"||!accessToken||accessToken.length>65536||/\s/.test(accessToken))throw failure("QUOTA_CREDENTIAL_REQUIRED",401);
9
+ if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>15000)throw failure("INVALID_QUOTA_TIMEOUT",400);
10
+ if(signal?.aborted)throw failure("QUOTA_CANCELLED",499);
11
+ return new Promise((resolve,reject)=>{
12
+ let client,request,timer,settled=false,httpStatus=null,grpcStatus=null,received=0;
13
+ const payloads=[],reader=new GrpcMessageReader({maxBytes:512*1024});
14
+ const finish=(error,result)=>{
15
+ if(settled)return;settled=true;clearTimeout(timer);signal?.removeEventListener("abort",abort);
16
+ try{request?.close();}catch{}try{client?.destroy();}catch{}
17
+ if(error){error.quotaEvidence={httpStatus,grpcStatus};reject(error);}else resolve(result);
18
+ };
19
+ const abort=()=>finish(failure("QUOTA_CANCELLED",499));
20
+ const reset=()=>{if(Number.isInteger(request?.rstCode)&&request.rstCode>0){finish(failure("QUOTA_STREAM_RESET"));return true;}return false;};
21
+ const status=headers=>{
22
+ if(headers[":status"]!==undefined){httpStatus=Number(headers[":status"]);if(httpStatus===429)return finish(failure("QUOTA_RATE_LIMITED",429));if(httpStatus===401||httpStatus===403)return finish(failure("QUOTA_AUTH_REJECTED",httpStatus));if(httpStatus!==200)return finish(failure("QUOTA_HTTP_REJECTED"));}
23
+ if(headers["grpc-status"]!==undefined){const raw=String(headers["grpc-status"]);if(!/^\d{1,2}$/.test(raw)||Number(raw)>16)return finish(failure("QUOTA_INVALID_STATUS"));grpcStatus=Number(raw);if(grpcStatus===8)return finish(failure("QUOTA_RATE_LIMITED",429));if([7,16].includes(grpcStatus))return finish(failure("QUOTA_AUTH_REJECTED",403));if(grpcStatus!==0)return finish(failure(grpcStatus===9?"QUOTA_PRECONDITION_REQUIRED":"QUOTA_UPSTREAM_REJECTED"));}
24
+ };
25
+ signal?.addEventListener("abort",abort,{once:true});timer=setTimeout(()=>finish(failure("QUOTA_TIMEOUT",504)),timeoutMs);
26
+ try{
27
+ client=connect(QUOTA_ORIGIN);client.on("error",()=>finish(failure("QUOTA_CONNECTION_FAILED")));
28
+ request=client.request({":method":"POST",":path":QUOTA_RPC,authorization:"Bearer "+accessToken,"content-type":"application/grpc",te:"trailers","grpc-timeout":timeoutMs+"m","user-agent":GATEWAY_USER_AGENT});
29
+ request.on("response",status);request.on("trailers",status);
30
+ request.on("data",chunk=>{if(settled)return;received+=chunk.length;if(received>1024*1024)return finish(failure("QUOTA_RESPONSE_TOO_LARGE"));try{payloads.push(...reader.push(chunk));if(payloads.length>1)finish(failure("QUOTA_INVALID_RESPONSE"));}catch{finish(failure("QUOTA_INVALID_RESPONSE"));}});
31
+ request.on("error",()=>{if(!settled&&!reset())finish(failure("QUOTA_STREAM_FAILED"));});
32
+ request.on("close",()=>{if(!settled&&!reset())finish(failure("QUOTA_STREAM_CLOSED_EARLY"));});
33
+ request.on("end",()=>{if(settled||reset())return;try{reader.finish();if(httpStatus!==200||grpcStatus!==0||payloads.length!==1)return finish(failure("QUOTA_INCOMPLETE_RESPONSE"));finish(null,{payload:payloads[0],observedAt:new Date().toISOString(),httpStatus,grpcStatus});}catch{finish(failure("QUOTA_INVALID_RESPONSE"));}});
34
+ request.end(frameGrpcMessage(Buffer.alloc(0)));
35
+ }catch{finish(failure("QUOTA_CONNECTION_FAILED"));}
36
+ });
37
+ }
@@ -0,0 +1,181 @@
1
+ import { parse } from "../../native-wire/protobuf.mjs";
2
+
3
+ const MAX = 1024 * 1024;
4
+ const text = new TextDecoder("utf-8", { fatal: true });
5
+ const fail = () => { throw Object.assign(new Error("INVALID_QUOTA_METADATA"), { code: "INVALID_QUOTA_METADATA" }); };
6
+ function fields(bytes, limit = MAX) {
7
+ if (!Buffer.isBuffer(bytes) || bytes.length > limit) fail();
8
+ try { return parse(bytes); } catch { fail(); }
9
+ }
10
+ function one(list, n, wire) {
11
+ const found = list.filter((f) => f.number === n);
12
+ if (found.length > 1 || found.some((f) => f.wire !== wire)) fail();
13
+ return found[0] ?? null;
14
+ }
15
+ function integer(f, max = Number.MAX_SAFE_INTEGER) {
16
+ if (!f) return null;
17
+ let n = 0n;
18
+ for (let i = 0; i < f.payload.length; i++) n |= BigInt(f.payload[i] & 127) << BigInt(i * 7);
19
+ if (!f.payload.length || f.payload.length > 10 || f.payload.at(-1) & 128 || n > BigInt(max)) fail();
20
+ return Number(n);
21
+ }
22
+ function timestamp(bytes) {
23
+ const fs = fields(bytes, 128), s = integer(one(fs, 1, 0)), nanos = integer(one(fs, 2, 0), 999999999);
24
+ if ((s !== null && s > 253402300799) || (nanos !== null && nanos > 999999999)) fail();
25
+ if (s === null) return null;
26
+ const ms = s * 1000 + Math.floor((nanos ?? 0) / 1e6);
27
+ const date = new Date(ms);
28
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
29
+ }
30
+ function ratio(available, max) {
31
+ return available !== null && max !== null && max > 0 && available >= 0 && available <= max
32
+ ? Math.round((available / max) * 10000) / 100 : null;
33
+ }
34
+ function budget(bytes, sourcePath) {
35
+ const fs = fields(bytes, 4096);
36
+ one(fs, 1, 2); // opaque quota context; its identity and scope are unknown
37
+ const unit = integer(one(fs, 2, 0), 0x7fffffff);
38
+ const providerPercent = integer(one(fs, 4, 0), 100);
39
+ const refillField = one(fs, 5, 2);
40
+ const availableField = one(fs, 7, 5), maxField = one(fs, 8, 5);
41
+ const float = (f) => {
42
+ if (!f) return null;
43
+ const n = f.payload.readFloatLE(0);
44
+ if (!Number.isFinite(n) || n < 0) fail();
45
+ return n;
46
+ };
47
+ const available = float(availableField), max = float(maxField);
48
+ return { sourcePath, available, max, remainingPercent: ratio(available, max), providerPercent, unit, refillAt: refillField ? timestamp(refillField.payload) : null, scope: "unknown" };
49
+ }
50
+ function refill(bytes, sourcePath, extra = {}) {
51
+ const fs = fields(bytes, 2048), tf = one(fs, 1, 2);
52
+ const out = { sourcePath, refillAt: tf ? timestamp(tf.payload) : null, ...extra };
53
+ return out.refillAt ? out : null;
54
+ }
55
+ function boundedArray(list, max) { if (list.length > max) fail(); return list; }
56
+
57
+ function labelText(field, maxBytes = 2048) {
58
+ if (!field) return "";
59
+ if (field.payload.length > maxBytes) fail();
60
+ return text.decode(field.payload);
61
+ }
62
+
63
+ /** GetUsageInfo has repeated root.3 groups and repeated GxuPool row.2.
64
+ * GxuPool wire 1 = windowRefreshesAt; wire 2 = pctUsed (fraction).
65
+ * See docs/ACCOUNT_LIFECYCLE.md. A window refresh is not a full-refill guarantee. */
66
+ export function decodeUsageInfo(payload) {
67
+ try {
68
+ const root = fields(payload), groups = boundedArray(root.filter(f => f.number === 3), 16), usageRows = [];
69
+ groups.forEach((group, groupIndex) => {
70
+ if (group.wire !== 2) fail();
71
+ const gf = fields(group.payload, 64 * 1024), groupType = integer(one(gf, 1, 0), 0x7fffffff);
72
+ const rows = boundedArray(gf.filter(f => f.number === 2), 32);
73
+ rows.forEach((row, rowIndex) => {
74
+ if (row.wire !== 2) fail();
75
+ const rf = fields(row.payload, 16 * 1024), percent = one(rf, 2, 5), label = one(rf, 3, 2), time = one(rf, 1, 2), help = one(rf, 4, 2);
76
+ const value = percent?.payload.readFloatLE(0);
77
+ if (percent && (!Number.isFinite(value) || value < 0 || value > 1)) fail();
78
+ const hf = help ? fields(help.payload, 8192) : [];
79
+ const helpItems = boundedArray(hf.filter(f => f.number === 2), 16).map(item => {
80
+ if (item.wire !== 2) fail();
81
+ const itemFields = fields(item.payload, 4096);
82
+ return { label: labelText(one(itemFields, 1, 2), 512), description: labelText(one(itemFields, 2, 2)) };
83
+ });
84
+ const entry = { label: labelText(label, 512), providerPercent: percent ? value * 100 : null,
85
+ percentMeaning: "used", providerTimestamp: time ? timestamp(time.payload) : null, timestampMeaning: "window_refresh",
86
+ groupType, sourcePath: `getUsageInfo.3[${groupIndex}].2[${rowIndex}]`,
87
+ helpTitle: labelText(one(hf, 1, 2), 512), helpItems };
88
+ if (entry.label || entry.providerPercent !== null) usageRows.push(entry);
89
+ });
90
+ });
91
+ boundedArray(usageRows, 32);
92
+ return { usageRows };
93
+ } catch { fail(); }
94
+ }
95
+
96
+ /** Optional in-generation metadata. Invalid quota metadata is isolated from the turn. */
97
+ export function decodePassiveQuota(clientBytes, observedModel) {
98
+ try {
99
+ const fs = fields(clientBytes), budgets = [], refills = [];
100
+ for (const n of [20, 29, 33]) one(fs, n, 2);
101
+ for (const f of fs.filter((x) => x.number === 20)) {
102
+ if (f.wire !== 2) fail();
103
+ const root = fields(f.payload, 64 * 1024), rows = boundedArray(root.filter((x) => x.number === 1), 32);
104
+ rows.forEach((r, i) => { if (r.wire !== 2) fail(); budgets.push(budget(r.payload, `clientGenerateResponse.20.1[${i}]`)); });
105
+ }
106
+ for (const f of fs.filter((x) => x.number === 29)) {
107
+ if (f.wire !== 2) fail();
108
+ const root = fields(f.payload, 64 * 1024), rows = boundedArray(root.filter((x) => x.number === 2), 32);
109
+ rows.forEach((r, i) => {
110
+ if (r.wire !== 2) fail();
111
+ const rf = fields(r.payload, 2048), time = one(rf, 1, 2), action = integer(one(rf, 2, 0), 0x7fffffff);
112
+ if (time) { const entry = refill(r.payload, `clientGenerateResponse.29.2[${i}]`, action === null ? {} : { action }); if (entry) refills.push(entry); }
113
+ });
114
+ }
115
+ for (const f of fs.filter((x) => x.number === 33)) {
116
+ if (f.wire !== 2) fail();
117
+ const root = fields(f.payload, 64 * 1024), time = one(root, 6, 2);
118
+ if (time) { const at = timestamp(time.payload); if (at) refills.push({ sourcePath: "clientGenerateResponse.33.6", refillAt: at }); }
119
+ for (const dis of root.filter((x) => x.number === 4)) {
120
+ if (dis.wire !== 2) fail();
121
+ const df = fields(dis.payload, 2048), mode = integer(one(df, 1, 0), 0x7fffffff), tf = one(df, 2, 2);
122
+ if (tf) { const at = timestamp(tf.payload); if (at) refills.push({ sourcePath: "clientGenerateResponse.33.4.2", refillAt: at, ...(mode === null ? {} : { featureMode: mode }) }); }
123
+ }
124
+ }
125
+ boundedArray(budgets, 32); boundedArray(refills, 32);
126
+ if (!budgets.length && !refills.length) return null;
127
+ const observedAt = new Date().toISOString();
128
+ return { source: "official", status: "ok", updatedAt: observedAt, budgetsUpdatedAt: budgets.length ? observedAt : null, refillsUpdatedAt: refills.length ? observedAt : null, usageUpdatedAt: null, lastAttemptAt: null, errorCode: null, budgets, refills, usageRows: [], provider: "google-robin", ...(observedModel ? { observedModel } : {}) };
129
+ } catch { return { source: "unknown", status: "error", updatedAt: null, lastAttemptAt: null, errorCode: "INVALID_QUOTA_METADATA", budgets: [], refills: [], usageRows: [], provider: "google-robin" }; }
130
+ }
131
+
132
+ const SAFE_ERRORS = new Set(["INVALID_QUOTA_METADATA", "QUOTA_REFRESH_FAILED", "QUOTA_REFRESH_THROTTLED", "QUOTA_AUTH_REJECTED", "QUOTA_RATE_LIMITED", "QUOTA_TIMEOUT", "QUOTA_CANCELLED", "QUOTA_CONNECTION_FAILED", "QUOTA_STREAM_FAILED", "QUOTA_STREAM_RESET", "QUOTA_STREAM_CLOSED_EARLY", "QUOTA_HTTP_REJECTED", "QUOTA_UPSTREAM_REJECTED", "QUOTA_PRECONDITION_REQUIRED", "QUOTA_INVALID_RESPONSE", "QUOTA_INVALID_STATUS", "QUOTA_RESPONSE_TOO_LARGE", "QUOTA_INCOMPLETE_RESPONSE", "QUOTA_CREDENTIAL_REQUIRED", "ACCOUNT_DISABLED", "ACCOUNT_LOGIN_REQUIRED", "NATIVE_PERMISSION_OR_AUTH", "OAUTH_REFRESH_FAILED"]);
133
+ export function safeQuota(value) {
134
+ const empty = { source: "unknown", status: "unqueried", updatedAt: null, budgetsUpdatedAt: null, refillsUpdatedAt: null, usageUpdatedAt: null, lastAttemptAt: null, errorCode: null, budgets: [], refills: [], usageRows: [], provider: "google-robin", remainingPercent: null };
135
+ if (!value || typeof value !== "object") return empty;
136
+ const safeTime = (v) => {
137
+ if (typeof v !== "string") return null;
138
+ const ms = Date.parse(v);
139
+ return Number.isFinite(ms) && new Date(ms).toISOString() === v ? v : null;
140
+ };
141
+ const safePath = (v) => typeof v === "string" && /^clientGenerateResponse\.(?:20\.1|29\.2|33\.6|33\.4\.2)(?:\[\d{1,2}\])?$/.test(v) ? v : null;
142
+ const budgets = Array.isArray(value.budgets) ? value.budgets.slice(0, 32).map((b) => {
143
+ if (!b || !safePath(b.sourcePath)) return null;
144
+ const available = Number.isFinite(b.available) && b.available >= 0 ? b.available : null;
145
+ const max = Number.isFinite(b.max) && b.max >= 0 ? b.max : null;
146
+ const remainingPercent = ratio(available, max);
147
+ return { sourcePath: b.sourcePath, available, max, remainingPercent, providerPercent: Number.isSafeInteger(b.providerPercent) && b.providerPercent >= 0 && b.providerPercent <= 100 ? b.providerPercent : null, unit: Number.isSafeInteger(b.unit) && b.unit >= 0 ? b.unit : null, refillAt: safeTime(b.refillAt), scope: "unknown" };
148
+ }).filter(Boolean) : [];
149
+ const refills = Array.isArray(value.refills) ? value.refills.slice(0, 32).map((r) => {
150
+ if (!r || !safePath(r.sourcePath) || !safeTime(r.refillAt)) return null;
151
+ return { sourcePath: r.sourcePath, refillAt: r.refillAt, ...(Number.isSafeInteger(r.action) && r.action >= 0 ? { action: r.action } : {}), ...(Number.isSafeInteger(r.featureMode) && r.featureMode >= 0 ? { featureMode: r.featureMode } : {}) };
152
+ }).filter(Boolean) : [];
153
+ // Upgrade legacy cache semantics only with verified message-specific provenance.
154
+ const officialUsage = value.source === "official" && value.provider === "google-robin";
155
+ const usagePath = v => typeof v === "string" && /^getUsageInfo\.3\[(?:[0-9]|1[0-5])\]\.2\[(?:[0-9]|[12][0-9]|3[01])\]$/.test(v) ? v : null;
156
+ const usageRows = Array.isArray(value.usageRows) ? value.usageRows.slice(0, 32).filter(r => r && typeof r.label === "string").map(r => ({
157
+ label: r.label.slice(0, 512), providerPercent: Number.isFinite(r.providerPercent) && r.providerPercent >= 0 && r.providerPercent <= 100 ? r.providerPercent : null,
158
+ percentMeaning: officialUsage && usagePath(r.sourcePath) ? "used" : "unspecified",
159
+ providerTimestamp: safeTime(r.providerTimestamp), timestampMeaning: officialUsage && usagePath(r.sourcePath) ? "window_refresh" : "unspecified", groupType: Number.isSafeInteger(r.groupType) && r.groupType >= 0 ? r.groupType : null,
160
+ sourcePath: officialUsage ? usagePath(r.sourcePath) : null,
161
+ helpTitle: typeof r.helpTitle === "string" ? r.helpTitle.slice(0, 512) : "",
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
+ })) : [];
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-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
+ }
167
+ export function quotaFailureCode(error) { return SAFE_ERRORS.has(error?.code) ? error.code : "QUOTA_REFRESH_FAILED"; }
168
+
169
+ export function mergeQuotaObservation(previous, observation) {
170
+ const prior = safeQuota(previous), next = safeQuota(observation);
171
+ if (next.source !== "official" || next.status !== "ok") return prior;
172
+ return safeQuota({ ...prior, ...next,
173
+ budgets: next.budgets.length ? next.budgets : prior.budgets,
174
+ budgetsUpdatedAt: next.budgets.length ? next.budgetsUpdatedAt : prior.budgetsUpdatedAt,
175
+ refills: next.refills.length ? next.refills : prior.refills,
176
+ refillsUpdatedAt: next.refills.length ? next.refillsUpdatedAt : prior.refillsUpdatedAt,
177
+ usageRows: next.usageRows.length ? next.usageRows : prior.usageRows,
178
+ usageUpdatedAt: next.usageRows.length ? next.usageUpdatedAt : prior.usageUpdatedAt,
179
+ lastAttemptAt: prior.lastAttemptAt,
180
+ });
181
+ }
@@ -0,0 +1,25 @@
1
+ // Gateway policy for observed whole-answer boilerplates, NOT a native error
2
+ // status decoder or a general evaluator of answer quality. Never scan snippets
3
+ // or tool arguments for error words and never turn quoted data into failures.
4
+ const GENERIC_ERROR_OFFERS = new Set([
5
+ 'I seem to be encountering an error. Can I try something else for you?',
6
+ "I'm having a hard time fulfilling your request. Can I help you with something else instead?",
7
+ 'I encountered an error doing what you asked. Could you try again?',
8
+ ]);
9
+ const folded = text => text.replace(/\s+/gu, ' ').trim();
10
+ const contentText = content => typeof content === 'string' ? content : Array.isArray(content)
11
+ ? content.filter(part => part?.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n') : '';
12
+ export function softErrorReason(text, body, callCount = 0) {
13
+ if (callCount !== 0 || typeof text !== 'string' || text.length > 1024) return null;
14
+ const signature = folded(text);
15
+ if (!GENERIC_ERROR_OFFERS.has(signature)) return null;
16
+ const messages = body?.messages ?? [];
17
+ const latestUser = messages.findLast(message => message.role === 'user');
18
+ const last = messages.at(-1);
19
+ // Conservative literal-data exemption. This is deliberately not an attempt
20
+ // to infer whether arbitrary instructions are quoting or denying a phrase.
21
+ const literalSources = [latestUser, ...messages.filter(message => ['system', 'developer'].includes(message.role)),
22
+ ...(last?.role === 'tool' ? [last] : [])];
23
+ if (literalSources.some(message => folded(contentText(message?.content)).includes(signature))) return null;
24
+ return 'generic_error_offer';
25
+ }