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.
- package/DISCLAIMER.md +17 -0
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/extensions/opencode/auth.js +324 -0
- package/extensions/opencode/fetch.js +494 -0
- package/extensions/opencode/index.js +27 -0
- package/extensions/opencode/models.js +84 -0
- package/extensions/pi/auth.js +215 -0
- package/native-wire/consumer-tool-codec.mjs +239 -0
- package/native-wire/oauth-loopback.mjs +175 -0
- package/native-wire/protobuf.mjs +133 -0
- package/native-wire/robin-current.mjs +172 -0
- package/package.json +75 -4
- package/src/gateway/automatic-recovery.mjs +70 -0
- package/src/gateway/image-download.mjs +110 -0
- package/src/gateway/image-upload.mjs +262 -0
- package/src/gateway/native-diagnostic.mjs +190 -0
- package/src/gateway/native-evidence.mjs +114 -0
- package/src/gateway/native-response-limits.mjs +8 -0
- package/src/gateway/native-search-citations.mjs +196 -0
- package/src/gateway/native-search-diagnostic.mjs +282 -0
- package/src/gateway/native-search-metadata.mjs +749 -0
- package/src/gateway/native-transport.mjs +433 -0
- package/src/gateway/oauth-client-defaults.mjs +12 -0
- package/src/gateway/oauth-identity.mjs +67 -0
- package/src/gateway/outbound-proxy.mjs +320 -0
- package/src/gateway/output-recovery.mjs +48 -0
- package/src/gateway/quota-failover.mjs +14 -0
- package/src/gateway/quota-transport.mjs +37 -0
- package/src/gateway/quota.mjs +181 -0
- package/src/gateway/soft-error.mjs +25 -0
- package/src/gateway/structured-output.mjs +157 -0
- package/src/gateway/subscription.mjs +51 -0
- package/src/gateway/terms.mjs +126 -0
- package/src/image-input.mjs +137 -0
- package/src/image-url.mjs +21 -0
- package/src/native-provider.mjs +806 -0
- package/src/openai-contract.mjs +576 -0
- package/src/openai-usage.mjs +66 -0
- package/src/prompt-tool-schema.mjs +391 -0
- package/src/responses-tool-namespaces.mjs +84 -0
- package/src/tool-protocol.mjs +366 -0
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { protocolError } from '../tool-protocol.mjs';
|
|
3
|
+
import { MAX_IMAGES, MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES } from '../image-input.mjs';
|
|
4
|
+
import { connectHttp2 } from './outbound-proxy.mjs';
|
|
5
|
+
import { GATEWAY_USER_AGENT } from '../../native-wire/robin-current.mjs';
|
|
6
|
+
|
|
7
|
+
const ORIGIN = 'https://push.clients6.google.com';
|
|
8
|
+
export const DEFAULT_UPLOAD_CONCURRENCY = 8;
|
|
9
|
+
export const DEFAULT_MAX_IN_FLIGHT_BYTES = 4 * 1024 * 1024;
|
|
10
|
+
export const MAX_UPLOAD_TIMEOUT_MS = 600_000;
|
|
11
|
+
const fail = (suffix, status = 502) => { throw protocolError(`NATIVE_IMAGE_UPLOAD_${suffix}`, status); };
|
|
12
|
+
const mimeTypes = new Set(['image/png', 'image/jpeg', 'image/webp']);
|
|
13
|
+
const drainError = () => {};
|
|
14
|
+
|
|
15
|
+
/** Ephemeral in-memory per-account hash -> blobId LRU cache. Never stores image bytes or persists to disk. */
|
|
16
|
+
export function createImageBlobCache({ maxEntries = 2048, ttlMs = 15 * 60 * 1000, now = Date.now } = {}) {
|
|
17
|
+
const entries = new Map();
|
|
18
|
+
const limit = Number.isSafeInteger(maxEntries) && maxEntries > 0 ? maxEntries : 2048;
|
|
19
|
+
const ttl = Number.isSafeInteger(ttlMs) && ttlMs > 0 ? ttlMs : 15 * 60 * 1000;
|
|
20
|
+
function keyOf(accountId, mimeType, data) {
|
|
21
|
+
const digest = crypto.createHash('sha256').update(data).digest('hex');
|
|
22
|
+
return `${accountId}\0${mimeType}\0${digest}`;
|
|
23
|
+
}
|
|
24
|
+
function get(key) {
|
|
25
|
+
const entry = entries.get(key);
|
|
26
|
+
if (!entry) return null;
|
|
27
|
+
if (entry.expiresAt <= now()) {
|
|
28
|
+
entries.delete(key);
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
// Refresh LRU recency.
|
|
32
|
+
entries.delete(key);
|
|
33
|
+
entries.set(key, entry);
|
|
34
|
+
return { blobId: entry.blobId, mimeType: entry.mimeType };
|
|
35
|
+
}
|
|
36
|
+
function set(key, { blobId, mimeType }) {
|
|
37
|
+
if (typeof key !== 'string' || !key || typeof blobId !== 'string' || !blobId || !mimeTypes.has(mimeType)) return;
|
|
38
|
+
entries.delete(key);
|
|
39
|
+
while (entries.size >= limit) {
|
|
40
|
+
const oldest = entries.keys().next().value;
|
|
41
|
+
if (oldest === undefined) break;
|
|
42
|
+
entries.delete(oldest);
|
|
43
|
+
}
|
|
44
|
+
entries.set(key, { blobId, mimeType, expiresAt: now() + ttl });
|
|
45
|
+
}
|
|
46
|
+
function del(key) { entries.delete(key); }
|
|
47
|
+
function deleteAccount(accountId) {
|
|
48
|
+
const prefix = `${accountId}\0`;
|
|
49
|
+
for (const key of entries.keys()) if (key.startsWith(prefix)) entries.delete(key);
|
|
50
|
+
}
|
|
51
|
+
function clear() { entries.clear(); }
|
|
52
|
+
return {
|
|
53
|
+
keyOf,
|
|
54
|
+
get,
|
|
55
|
+
set,
|
|
56
|
+
delete: del,
|
|
57
|
+
deleteAccount,
|
|
58
|
+
clear,
|
|
59
|
+
get size() { return entries.size; },
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function validateImages(images) {
|
|
64
|
+
if (!Array.isArray(images) || images.length > MAX_IMAGES) fail('INVALID_RESPONSE');
|
|
65
|
+
let total = 0;
|
|
66
|
+
for (const image of images) {
|
|
67
|
+
if (!image || !Buffer.isBuffer(image.data) || !image.data.length || !mimeTypes.has(image.mimeType)) fail('INVALID_RESPONSE');
|
|
68
|
+
if (image.data.length > MAX_IMAGE_BYTES) fail('INVALID_RESPONSE');
|
|
69
|
+
total += image.data.length;
|
|
70
|
+
if (total > MAX_TOTAL_IMAGE_BYTES) fail('INVALID_RESPONSE');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function boundedLocation(value) {
|
|
75
|
+
if (Array.isArray(value)) value = value.length === 1 ? value[0] : null;
|
|
76
|
+
if (typeof value !== 'string' || Buffer.byteLength(value) > 8192 || /[\x00-\x20\x7f\\]/.test(value)) fail('LOCATION_REJECTED');
|
|
77
|
+
let parsed;
|
|
78
|
+
try { parsed = new URL(value); } catch { fail('LOCATION_REJECTED'); }
|
|
79
|
+
if (parsed.protocol !== 'https:' || parsed.hostname !== 'push.clients6.google.com' || parsed.port !== '' || parsed.username || parsed.password || parsed.hash || !parsed.pathname.startsWith('/upload/')) fail('LOCATION_REJECTED');
|
|
80
|
+
return parsed;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function uploadNativeImages(
|
|
84
|
+
token,
|
|
85
|
+
images,
|
|
86
|
+
{ signal, timeoutMs = 60000, concurrency = DEFAULT_UPLOAD_CONCURRENCY, maxInFlightBytes = DEFAULT_MAX_IN_FLIGHT_BYTES, onUploaded } = {},
|
|
87
|
+
{ connect = connectHttp2 } = {},
|
|
88
|
+
) {
|
|
89
|
+
validateImages(images);
|
|
90
|
+
if (!images.length) return [];
|
|
91
|
+
if (
|
|
92
|
+
typeof token !== 'string' ||
|
|
93
|
+
!token ||
|
|
94
|
+
token.length > 65536 ||
|
|
95
|
+
/\s|[\x00-\x1f\x7f]/u.test(token) ||
|
|
96
|
+
!Number.isSafeInteger(timeoutMs) ||
|
|
97
|
+
timeoutMs < 1 ||
|
|
98
|
+
timeoutMs > MAX_UPLOAD_TIMEOUT_MS ||
|
|
99
|
+
!Number.isSafeInteger(concurrency) ||
|
|
100
|
+
concurrency < 1 ||
|
|
101
|
+
concurrency > 32 ||
|
|
102
|
+
!Number.isSafeInteger(maxInFlightBytes) ||
|
|
103
|
+
maxInFlightBytes < 1 ||
|
|
104
|
+
(onUploaded !== undefined && typeof onUploaded !== 'function') ||
|
|
105
|
+
(signal !== undefined && (!signal || typeof signal.addEventListener !== 'function')) ||
|
|
106
|
+
typeof connect !== 'function'
|
|
107
|
+
) fail('INVALID_RESPONSE');
|
|
108
|
+
if (signal?.aborted) fail('CANCELLED', 499);
|
|
109
|
+
const deadline = Date.now() + timeoutMs;
|
|
110
|
+
let session, timeout, sessionFailed = false, batchError = null;
|
|
111
|
+
let inFlightBytes = 0, activeUploads = 0;
|
|
112
|
+
const activeStops = new Set();
|
|
113
|
+
const budgetWaiters = [];
|
|
114
|
+
const wakeBudgetWaiters = () => {
|
|
115
|
+
while (budgetWaiters.length) {
|
|
116
|
+
const next = budgetWaiters[0];
|
|
117
|
+
if (activeUploads === 0 || inFlightBytes + next.bytes <= maxInFlightBytes || batchError || sessionFailed || signal?.aborted) {
|
|
118
|
+
budgetWaiters.shift();
|
|
119
|
+
next.resolve();
|
|
120
|
+
} else {
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const acquireByteBudget = async (bytes) => {
|
|
126
|
+
while (activeUploads > 0 && inFlightBytes + bytes > maxInFlightBytes && !batchError && !sessionFailed && !signal?.aborted) {
|
|
127
|
+
await new Promise(resolve => budgetWaiters.push({ bytes, resolve }));
|
|
128
|
+
}
|
|
129
|
+
ensureAlive();
|
|
130
|
+
activeUploads++;
|
|
131
|
+
inFlightBytes += bytes;
|
|
132
|
+
};
|
|
133
|
+
const releaseByteBudget = (bytes) => {
|
|
134
|
+
activeUploads = Math.max(0, activeUploads - 1);
|
|
135
|
+
inFlightBytes = Math.max(0, inFlightBytes - bytes);
|
|
136
|
+
wakeBudgetWaiters();
|
|
137
|
+
};
|
|
138
|
+
const stopAll = (err) => {
|
|
139
|
+
if (!batchError) batchError = err;
|
|
140
|
+
wakeBudgetWaiters();
|
|
141
|
+
for (const stop of [...activeStops]) stop(err);
|
|
142
|
+
};
|
|
143
|
+
const abortCode = () => signal?.aborted ? ['CANCELLED', 499] : Date.now() >= deadline ? ['TIMEOUT', 504] : null;
|
|
144
|
+
const ensureAlive = () => {
|
|
145
|
+
if (batchError) throw batchError;
|
|
146
|
+
const stopped = abortCode(); if (stopped) fail(...stopped);
|
|
147
|
+
if (sessionFailed || session?.destroyed || session?.closed) fail('RESET');
|
|
148
|
+
};
|
|
149
|
+
const request = (headers, body, maxBody) => new Promise((resolve, reject) => {
|
|
150
|
+
let stream, responseHeaders, chunks = [], size = 0, settled = false, ended = false;
|
|
151
|
+
const cleanup = () => {
|
|
152
|
+
activeStops.delete(onForcedStop);
|
|
153
|
+
signal?.removeEventListener('abort', onAbort);
|
|
154
|
+
stream?.removeListener('response', onResponse);
|
|
155
|
+
stream?.removeListener('data', onData);
|
|
156
|
+
stream?.removeListener('end', onEnd);
|
|
157
|
+
stream?.removeListener('error', onError);
|
|
158
|
+
stream?.removeListener('aborted', onAborted);
|
|
159
|
+
stream?.removeListener('close', onClose);
|
|
160
|
+
stream?.on('error', drainError);
|
|
161
|
+
};
|
|
162
|
+
const finish = (error, result) => { if (settled) return; settled = true; cleanup(); error ? reject(error) : resolve(result); };
|
|
163
|
+
const onForcedStop = error => { finish(error); try { stream?.close(); } catch {} };
|
|
164
|
+
const onAbort = () => { const c = abortCode() || ['CANCELLED', 499]; onForcedStop(protocolError(`NATIVE_IMAGE_UPLOAD_${c[0]}`, c[1])); };
|
|
165
|
+
const onResponse = h => {
|
|
166
|
+
responseHeaders = h;
|
|
167
|
+
let headerBytes = 0;
|
|
168
|
+
for (const [key, value] of Object.entries(h)) {
|
|
169
|
+
headerBytes += Buffer.byteLength(key) + Buffer.byteLength(Array.isArray(value) ? value.join('') : String(value ?? ''));
|
|
170
|
+
if (headerBytes > 8192) { finish(protocolError('NATIVE_IMAGE_UPLOAD_INVALID_RESPONSE', 502)); return; }
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
const onData = chunk => { size += chunk.length; if (size > maxBody) { finish(protocolError('NATIVE_IMAGE_UPLOAD_INVALID_RESPONSE', 502)); try { stream.close(); } catch {} return; } chunks.push(Buffer.from(chunk)); };
|
|
174
|
+
const onError = () => { const c = abortCode(); finish(c ? protocolError(`NATIVE_IMAGE_UPLOAD_${c[0]}`, c[1]) : protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); };
|
|
175
|
+
const onAborted = () => onError();
|
|
176
|
+
const onEnd = () => { ended = true; };
|
|
177
|
+
const onClose = () => {
|
|
178
|
+
if (!ended || stream.rstCode) { onError(); return; }
|
|
179
|
+
const c = abortCode(); if (c) { finish(protocolError(`NATIVE_IMAGE_UPLOAD_${c[0]}`, c[1])); return; }
|
|
180
|
+
if (session?.destroyed || session?.closed || stream.rstCode) { finish(protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); return; }
|
|
181
|
+
if (!responseHeaders) { finish(protocolError('NATIVE_IMAGE_UPLOAD_INVALID_RESPONSE', 502)); return; }
|
|
182
|
+
const status = Number(responseHeaders[':status']);
|
|
183
|
+
if (status !== 200) { finish(protocolError('NATIVE_IMAGE_UPLOAD_INVALID_RESPONSE', status === 401 || status === 403 ? 403 : status === 429 ? 429 : 502)); return; }
|
|
184
|
+
finish(null, { headers: responseHeaders, body: Buffer.concat(chunks) });
|
|
185
|
+
};
|
|
186
|
+
activeStops.add(onForcedStop);
|
|
187
|
+
try {
|
|
188
|
+
ensureAlive();
|
|
189
|
+
stream = session.request(headers);
|
|
190
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
191
|
+
stream.on('response', onResponse); stream.on('data', onData); stream.on('end', onEnd); stream.on('error', onError); stream.on('aborted', onAborted); stream.on('close', onClose);
|
|
192
|
+
if (signal?.aborted) onAbort();
|
|
193
|
+
else if (body) stream.end(body); else stream.end();
|
|
194
|
+
} catch (err) {
|
|
195
|
+
if (typeof err?.code === 'string' && err.code.startsWith('NATIVE_IMAGE_UPLOAD_')) { finish(err); return; }
|
|
196
|
+
const c = abortCode();
|
|
197
|
+
finish(c ? protocolError(`NATIVE_IMAGE_UPLOAD_${c[0]}`, c[1]) : protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502));
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
const onSessionError = () => { sessionFailed = true; stopAll(protocolError('NATIVE_IMAGE_UPLOAD_RESET', 502)); };
|
|
201
|
+
const uploadOne = async (image) => {
|
|
202
|
+
await acquireByteBudget(image.data.length);
|
|
203
|
+
try {
|
|
204
|
+
ensureAlive();
|
|
205
|
+
const initial = await request({ ':method': 'POST', ':path': '/upload/', authorization: `Bearer ${token}`, 'content-length': '0', 'push-id': 'feeds/mcudyrk2a4khkz', 'x-tenant-id': 'bard-storage', 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'start', 'x-goog-upload-content-type': image.mimeType, 'x-goog-upload-content-length': String(image.data.length), 'user-agent': GATEWAY_USER_AGENT }, null, 8192);
|
|
206
|
+
if (String(initial.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'active') fail('INVALID_RESPONSE');
|
|
207
|
+
const location = boundedLocation(initial.headers['x-goog-upload-url']);
|
|
208
|
+
ensureAlive();
|
|
209
|
+
const final = await request({ ':method': 'PUT', ':path': location.pathname + location.search, 'content-length': String(image.data.length), 'x-goog-upload-protocol': 'resumable', 'x-goog-upload-command': 'upload, finalize', 'x-goog-upload-offset': '0', 'user-agent': GATEWAY_USER_AGENT }, image.data, 4096);
|
|
210
|
+
if (String(final.headers['x-goog-upload-status'] ?? '').toLowerCase() !== 'final') fail('INVALID_RESPONSE');
|
|
211
|
+
let blobId;
|
|
212
|
+
try { blobId = new TextDecoder('utf-8', { fatal: true }).decode(final.body); } catch { fail('INVALID_RESPONSE'); }
|
|
213
|
+
if (!blobId || Buffer.byteLength(blobId) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(blobId)) fail('INVALID_RESPONSE');
|
|
214
|
+
ensureAlive();
|
|
215
|
+
return { blobId, mimeType: image.mimeType };
|
|
216
|
+
} finally {
|
|
217
|
+
releaseByteBudget(image.data.length);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
const onSignalAbort = () => wakeBudgetWaiters();
|
|
221
|
+
signal?.addEventListener('abort', onSignalAbort, { once: true });
|
|
222
|
+
try {
|
|
223
|
+
try { session = connect(ORIGIN, { settings: { enablePush: false, maxHeaderListSize: 8192 } }); } catch { fail('RESET'); }
|
|
224
|
+
if (!session || typeof session.request !== 'function') fail('RESET');
|
|
225
|
+
try { session.socket?.setKeepAlive?.(true, 15_000); } catch {}
|
|
226
|
+
session.on?.('error', onSessionError);
|
|
227
|
+
session.on?.('close', onSessionError);
|
|
228
|
+
timeout = setTimeout(() => { stopAll(protocolError('NATIVE_IMAGE_UPLOAD_TIMEOUT', 504)); try { session.destroy(); } catch {} }, Math.max(1, deadline - Date.now()));
|
|
229
|
+
const results = new Array(images.length);
|
|
230
|
+
const workerCount = Math.min(concurrency, images.length);
|
|
231
|
+
let nextIndex = 0;
|
|
232
|
+
const worker = async () => {
|
|
233
|
+
while (!batchError) {
|
|
234
|
+
const index = nextIndex++;
|
|
235
|
+
if (index >= images.length) return;
|
|
236
|
+
try {
|
|
237
|
+
const uploaded = await uploadOne(images[index]);
|
|
238
|
+
results[index] = uploaded;
|
|
239
|
+
try { onUploaded?.(index, uploaded); } catch {}
|
|
240
|
+
} catch (err) {
|
|
241
|
+
stopAll(err);
|
|
242
|
+
throw err;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
const outcomes = await Promise.allSettled(Array.from({ length: workerCount }, () => worker()));
|
|
247
|
+
const failed = outcomes.find(o => o.status === 'rejected');
|
|
248
|
+
if (failed) throw failed.reason;
|
|
249
|
+
if (batchError) throw batchError;
|
|
250
|
+
return results;
|
|
251
|
+
} catch (error) {
|
|
252
|
+
if (typeof error?.code === 'string' && error.code.startsWith('NATIVE_IMAGE_UPLOAD_')) throw error;
|
|
253
|
+
const c = abortCode(); if (c) fail(...c);
|
|
254
|
+
fail('RESET');
|
|
255
|
+
} finally {
|
|
256
|
+
clearTimeout(timeout);
|
|
257
|
+
signal?.removeEventListener('abort', onSignalAbort);
|
|
258
|
+
wakeBudgetWaiters();
|
|
259
|
+
try { session?.on?.('error', drainError); session?.removeListener?.('error', onSessionError); session?.removeListener?.('close', onSessionError); } catch {}
|
|
260
|
+
try { session?.destroy(); } catch {}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// Host-consented, default-off, one logical request. Never retain wire bytes or strings.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { performance } from 'node:perf_hooks';
|
|
6
|
+
|
|
7
|
+
export const NATIVE_DIAGNOSTIC_FILES = Object.freeze({
|
|
8
|
+
arm: 'native-diagnostic.arm.private.json',
|
|
9
|
+
claimed: 'native-diagnostic.claimed.private.json',
|
|
10
|
+
result: 'native-diagnostic.result.private.json',
|
|
11
|
+
});
|
|
12
|
+
export const NATIVE_DIAGNOSTIC_LIMITS = Object.freeze({
|
|
13
|
+
expiryMs: 24 * 60 * 60 * 1000, attempts: 16, events: 64,
|
|
14
|
+
firstFrames: 8, lastFrames: 8, fieldsPerLayer: 8, scanFieldsPerLayer: 64, reportBytes: 512 * 1024,
|
|
15
|
+
});
|
|
16
|
+
const L = NATIVE_DIAGNOSTIC_LIMITS;
|
|
17
|
+
const eventNames = new Set(['provider_stop', 'provider_cleanup', 'provider_success', 'provider_failure',
|
|
18
|
+
'early_stop_post_tool_hallucination', 'early_stop_post_tool_error',
|
|
19
|
+
'post_complete_idle_finish', 'post_complete_idle_timeout', 'post_tool_error_idle_finish',
|
|
20
|
+
'post_tool_idle_timeout', 'post_output_idle_timeout',
|
|
21
|
+
'transport_open', 'local_stream_close', 'local_session_destroy', 'local_signal_abort', 'local_cancel',
|
|
22
|
+
'transport_failure', 'transport_deadline', 'transport_ping_timeout', 'peer_headers', 'peer_trailers', 'peer_reset',
|
|
23
|
+
'peer_goaway', 'stream_error', 'stream_close', 'stream_end', 'peer_data', 'local_half_close',
|
|
24
|
+
'peer_connection_end', 'peer_connection_close']);
|
|
25
|
+
const numberKeys = new Set(['httpStatus', 'grpcStatus', 'rstCode', 'requestedCode', 'goawayCode',
|
|
26
|
+
'bytes', 'mode', 'thinking', 'timeoutMs']);
|
|
27
|
+
const failureCodes = new Set(['NATIVE_STREAM_RESET', 'NATIVE_CONNECTION_FAILED', 'NATIVE_STREAM_FAILED',
|
|
28
|
+
'NATIVE_STREAM_CLOSED_EARLY', 'NATIVE_HTTP_REJECTED', 'NATIVE_INVALID_STATUS', 'NATIVE_RECEIVE_LIMIT',
|
|
29
|
+
'NATIVE_FRAME_REJECTED', 'NATIVE_TRANSPORT_TIMEOUT', 'REQUEST_CANCELLED', 'NATIVE_TURN_ABORTED',
|
|
30
|
+
'NATIVE_TURN_TIMEOUT', 'NATIVE_QUOTA_EXHAUSTED', 'NATIVE_QUOTA_INSUFFICIENT', 'NATIVE_RATE_LIMITED',
|
|
31
|
+
'NATIVE_PERMISSION_OR_AUTH', 'MODEL_DOWNGRADE_REJECTED', 'INCOMPLETE_NATIVE_RESPONSE',
|
|
32
|
+
'INVALID_NATIVE_RESPONSE', 'EMPTY_NATIVE_RESPONSE', 'NATIVE_SOFT_ERROR_RESPONSE',
|
|
33
|
+
'NATIVE_AUTH_REJECTED', 'NATIVE_PERMISSION_REJECTED', 'NATIVE_PRECONDITION_REQUIRED',
|
|
34
|
+
'NATIVE_TURN_FAILED', 'NATIVE_UPSTREAM_UNAVAILABLE', 'NATIVE_RESPONSE_LIMIT', 'INVALID_NATIVE_EVENT', 'NATIVE_AUTH_FAILED',
|
|
35
|
+
'NATIVE_READER_BUSY', 'ACCOUNT_LOGIN_REQUIRED', 'OAUTH_REFRESH_FAILED',
|
|
36
|
+
'NATIVE_RESPONSE_REFUSED', 'NATIVE_OUTPUT_NOT_TEXT', 'NATIVE_ASYNC_RESPONSE_UNSUPPORTED',
|
|
37
|
+
'MISSING_NATIVE_MODE_EVIDENCE', 'UNSUPPORTED_NATIVE_TOOL_EVENT', 'INVALID_NATIVE_THINKING_LEVEL',
|
|
38
|
+
'INVALID_NATIVE_IMAGE_UPLOAD', 'NON_MONOTONIC_NATIVE_RESPONSE', 'PARALLEL_TOOL_CALLS_DISABLED',
|
|
39
|
+
'MALFORMED_TOOL_CALL', 'ACCOUNT_COOLDOWN', 'SESSION_ACCOUNT_UNAVAILABLE', 'NO_AVAILABLE_ACCOUNTS']);
|
|
40
|
+
const safeCode = code => code == null ? null : failureCodes.has(code) ? code : 'OTHER_ERROR';
|
|
41
|
+
const uint = value => Number.isSafeInteger(value) && value >= 0 && value <= 0xffffffff;
|
|
42
|
+
export function observeNative(observer, method, ...args) {
|
|
43
|
+
try { observer?.[method]?.(...args); } catch { /* Observability is never control flow. */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Scan only fixed envelope/model layers. Skip all values, including strings and IDs.
|
|
47
|
+
// Scan at most64 fields per layer, retain8; no generic recursion or text conversion.
|
|
48
|
+
export function nativeFrameMetadata(bytes) {
|
|
49
|
+
if (!Buffer.isBuffer(bytes) || bytes.length > 1024 * 1024) return { invalid: true };
|
|
50
|
+
const result = { bytes: bytes.length, fields: [], scalars: {} };
|
|
51
|
+
const descended = new Set();
|
|
52
|
+
const varint = (buffer, position) => {
|
|
53
|
+
let value = 0n;
|
|
54
|
+
for (let i = 0; i < 10; i++) {
|
|
55
|
+
const b = buffer[position++];
|
|
56
|
+
if (b === undefined || (i === 9 && b > 1)) throw Error();
|
|
57
|
+
value |= BigInt(b & 127) << BigInt(i * 7);
|
|
58
|
+
if (!(b & 128)) return [value, position];
|
|
59
|
+
}
|
|
60
|
+
throw Error();
|
|
61
|
+
};
|
|
62
|
+
const scan = (buffer, layer, descendNumber) => {
|
|
63
|
+
let position = 0, count = 0;
|
|
64
|
+
while (position < buffer.length && count++ < L.scanFieldsPerLayer) {
|
|
65
|
+
let key; [key, position] = varint(buffer, position);
|
|
66
|
+
const number = Number(key >> 3n), wire = Number(key & 7n);
|
|
67
|
+
if (number < 1 || number > 0x1fffffff) throw Error();
|
|
68
|
+
let start = position, end, scalar;
|
|
69
|
+
if (wire === 0) [scalar, end] = varint(buffer, position);
|
|
70
|
+
else if (wire === 1 || wire === 5) end = position + (wire === 1 ? 8 : 4);
|
|
71
|
+
else if (wire === 2) {
|
|
72
|
+
let length; [length, start] = varint(buffer, position);
|
|
73
|
+
if (length > BigInt(buffer.length)) throw Error();
|
|
74
|
+
end = start + Number(length);
|
|
75
|
+
} else throw Error();
|
|
76
|
+
if (end > buffer.length) throw Error();
|
|
77
|
+
if (count <= L.fieldsPerLayer) result.fields.push({ layer, number, wire, bytes: end - start });
|
|
78
|
+
else result.truncated = true;
|
|
79
|
+
if (layer === 2 && number === 7) result.nativeToolsPresent = true;
|
|
80
|
+
if (layer === 2 && [13, 17].includes(number)) result.refusalPresent = true;
|
|
81
|
+
if ((layer === 2 && [9, 11, 31, 41, 42].includes(number)) || (layer === 3 && number === 19)) {
|
|
82
|
+
if (wire === 0 && scalar <= 0x7fffffffn) result.scalars[`${layer}:${number}`] = Number(scalar);
|
|
83
|
+
}
|
|
84
|
+
if (wire === 2 && number === descendNumber && layer < 3 && !descended.has(layer)) {
|
|
85
|
+
descended.add(layer);
|
|
86
|
+
scan(buffer.subarray(start, end), layer + 1, 1);
|
|
87
|
+
}
|
|
88
|
+
position = end;
|
|
89
|
+
}
|
|
90
|
+
if (position < buffer.length) result.truncated = true;
|
|
91
|
+
};
|
|
92
|
+
try { scan(bytes, 0, 1003); } catch { result.invalid = true; }
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function privateRegular(stat) {
|
|
97
|
+
return stat.isFile() && (stat.mode & 0o777) === 0o600 &&
|
|
98
|
+
(typeof process.getuid !== 'function' || stat.uid === process.getuid());
|
|
99
|
+
}
|
|
100
|
+
export class NativeDiagnostic {
|
|
101
|
+
constructor(directory, { now = Date.now, monotonic = () => performance.now() } = {}) {
|
|
102
|
+
this.directory = typeof directory === 'string' && directory ? directory : null;
|
|
103
|
+
this.now = now; this.monotonic = monotonic;
|
|
104
|
+
}
|
|
105
|
+
claim(requestId) {
|
|
106
|
+
let fd;
|
|
107
|
+
try {
|
|
108
|
+
if (!this.directory || !/^req_[a-f0-9-]{36}$/.test(requestId)) return null;
|
|
109
|
+
const directory = fs.lstatSync(this.directory);
|
|
110
|
+
if (!directory.isDirectory() || (directory.mode & 0o077) !== 0) return null;
|
|
111
|
+
const files = Object.fromEntries(Object.entries(NATIVE_DIAGNOSTIC_FILES).map(([key, name]) => [key, path.join(this.directory, name)]));
|
|
112
|
+
if (fs.existsSync(files.claimed) || fs.existsSync(files.result)) return null;
|
|
113
|
+
if (!privateRegular(fs.lstatSync(files.arm))) return null;
|
|
114
|
+
fd = fs.openSync(files.arm, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
115
|
+
const stat = fs.fstatSync(fd);
|
|
116
|
+
if (!privateRegular(stat) || stat.size > 256 || stat.size < 1) return null;
|
|
117
|
+
const buffer = Buffer.alloc(257);
|
|
118
|
+
const length = fs.readSync(fd, buffer, 0, buffer.length, 0);
|
|
119
|
+
if (length > 256) return null;
|
|
120
|
+
const arm = JSON.parse(buffer.subarray(0, length).toString('utf8'));
|
|
121
|
+
const now = this.now();
|
|
122
|
+
if (Object.keys(arm).sort().join(',') !== 'expiresAt,version' || arm.version !== 1 ||
|
|
123
|
+
!Number.isSafeInteger(arm.expiresAt) || arm.expiresAt <= now || arm.expiresAt > now + L.expiryMs) return null;
|
|
124
|
+
// link is atomic and unlike rename cannot overwrite another process's claim.
|
|
125
|
+
fs.linkSync(files.arm, files.claimed);
|
|
126
|
+
const claimed = fs.lstatSync(files.claimed);
|
|
127
|
+
if (!privateRegular(claimed) || claimed.ino !== stat.ino || claimed.dev !== stat.dev) return null;
|
|
128
|
+
fs.unlinkSync(files.arm);
|
|
129
|
+
return this.trace(requestId, files.result);
|
|
130
|
+
} catch { return null; }
|
|
131
|
+
finally { if (fd !== undefined) try { fs.closeSync(fd); } catch {} }
|
|
132
|
+
}
|
|
133
|
+
trace(requestId, destination) {
|
|
134
|
+
const started = this.monotonic(), elapsed = () => Math.max(0, Math.round(this.monotonic() - started));
|
|
135
|
+
const report = { version: 1, requestId, startedAt: this.now(), attempts: [], omittedAttempts: 0 };
|
|
136
|
+
let finished = false;
|
|
137
|
+
return {
|
|
138
|
+
attempt: () => {
|
|
139
|
+
if (finished) return null;
|
|
140
|
+
if (report.attempts.length >= L.attempts) { report.omittedAttempts++; return null; }
|
|
141
|
+
const attempt = { number: report.attempts.length + 1, atMs: elapsed(), events: [], tailEvents: [],
|
|
142
|
+
eventCount: 0, frameCount: 0, firstFrames: [], lastFrames: [] };
|
|
143
|
+
report.attempts.push(attempt);
|
|
144
|
+
return {
|
|
145
|
+
event: (name, values = {}) => {
|
|
146
|
+
if (!eventNames.has(name)) return;
|
|
147
|
+
const entry = { name, atMs: elapsed() };
|
|
148
|
+
for (const key of numberKeys) if (uint(values[key])) entry[key] = values[key];
|
|
149
|
+
if (values.code !== undefined) entry.code = safeCode(values.code);
|
|
150
|
+
attempt.eventCount++;
|
|
151
|
+
if (attempt.events.length < 48) attempt.events.push(entry);
|
|
152
|
+
else { attempt.tailEvents.push(entry); if (attempt.tailEvents.length > 16) attempt.tailEvents.shift(); }
|
|
153
|
+
},
|
|
154
|
+
frame: bytes => {
|
|
155
|
+
const frame = { number: ++attempt.frameCount, atMs: elapsed(), ...nativeFrameMetadata(bytes) };
|
|
156
|
+
if (attempt.firstFrames.length < L.firstFrames) attempt.firstFrames.push(frame);
|
|
157
|
+
else { attempt.lastFrames.push(frame); if (attempt.lastFrames.length > L.lastFrames) attempt.lastFrames.shift(); }
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
},
|
|
161
|
+
finish: ({ status, errorCode, providerAttempts } = {}) => {
|
|
162
|
+
if (finished) return;
|
|
163
|
+
finished = true;
|
|
164
|
+
report.durationMs = elapsed();
|
|
165
|
+
report.status = uint(status) ? status : null;
|
|
166
|
+
report.errorCode = safeCode(errorCode);
|
|
167
|
+
report.providerAttempts = uint(providerAttempts) ? providerAttempts : null;
|
|
168
|
+
// Observe async stream close after existing cleanup without delaying a response.
|
|
169
|
+
setTimeout(() => {
|
|
170
|
+
let temporary;
|
|
171
|
+
try {
|
|
172
|
+
report.cleanupWindowMs = elapsed() - report.durationMs;
|
|
173
|
+
let json = JSON.stringify(report);
|
|
174
|
+
if (Buffer.byteLength(json) > L.reportBytes) {
|
|
175
|
+
report.truncated = true;
|
|
176
|
+
for (const attempt of report.attempts) { attempt.firstFrames = []; attempt.lastFrames = []; }
|
|
177
|
+
json = JSON.stringify(report);
|
|
178
|
+
}
|
|
179
|
+
if (Buffer.byteLength(json) > L.reportBytes) return;
|
|
180
|
+
temporary = destination + '.' + crypto.randomBytes(8).toString('hex') + '.tmp';
|
|
181
|
+
fs.writeFileSync(temporary, json, { flag: 'wx', mode: 0o600 });
|
|
182
|
+
fs.linkSync(temporary, destination); // Never overwrite a prior result.
|
|
183
|
+
} catch { /* A failed trace must not change request completion. */ }
|
|
184
|
+
finally { if (temporary) try { fs.unlinkSync(temporary); } catch {} }
|
|
185
|
+
}, 300);
|
|
186
|
+
// Keep this single bounded timer referenced so graceful exit writes the result.
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Bounded admin diagnostics. Upstream error headers are text, never executable HTML.
|
|
2
|
+
import { NATIVE_RESPONSE_LIMITS } from './native-response-limits.mjs';
|
|
3
|
+
import { NATIVE_MODELS } from '../openai-contract.mjs';
|
|
4
|
+
const bounded = (value, min, max) =>
|
|
5
|
+
Number.isSafeInteger(value) && value >= min && value <= max ? value : null;
|
|
6
|
+
const phases = new Set([
|
|
7
|
+
"auth",
|
|
8
|
+
"upload",
|
|
9
|
+
"open",
|
|
10
|
+
"read",
|
|
11
|
+
"decode",
|
|
12
|
+
"end",
|
|
13
|
+
"validate",
|
|
14
|
+
"output",
|
|
15
|
+
]);
|
|
16
|
+
export function sanitizeUpstreamMessage(value) {
|
|
17
|
+
if (typeof value !== "string" || !value) return null;
|
|
18
|
+
const text = value
|
|
19
|
+
.slice(0, 16384)
|
|
20
|
+
.replace(/https?:\/\/[^\s<>"']+/gi, "[URL redacted]")
|
|
21
|
+
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, "[email redacted]")
|
|
22
|
+
.replace(
|
|
23
|
+
/\b(?:ya29\.[A-Za-z0-9._-]+|GOCSPX-[A-Za-z0-9_-]+|Bearer\s+\S+)|1\/\/[A-Za-z0-9._-]+/gi,
|
|
24
|
+
"[credential redacted]",
|
|
25
|
+
)
|
|
26
|
+
.replace(
|
|
27
|
+
/\b(?:sk-|gsk_|gw_|gk_|gapi_)[A-Za-z0-9_-]{16,}|\b[0-9]{7,}\b|\b[A-Za-z0-9_-]{64,}\b/g,
|
|
28
|
+
"[identifier redacted]",
|
|
29
|
+
)
|
|
30
|
+
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, "");
|
|
31
|
+
return text.length > 2048 ? text.slice(0, 2036) + "\n[truncated]" : text;
|
|
32
|
+
}
|
|
33
|
+
export function decodeGrpcMessage(value) {
|
|
34
|
+
if (typeof value !== "string" || value.length > 32768) return null;
|
|
35
|
+
let text = value;
|
|
36
|
+
try {
|
|
37
|
+
text = decodeURIComponent(value);
|
|
38
|
+
} catch {}
|
|
39
|
+
return sanitizeUpstreamMessage(text);
|
|
40
|
+
}
|
|
41
|
+
export function safeAccountError(value) {
|
|
42
|
+
if (
|
|
43
|
+
!value ||
|
|
44
|
+
!bounded(value.at, 1, 8640000000000000) ||
|
|
45
|
+
!bounded(value.status, 400, 599)
|
|
46
|
+
)
|
|
47
|
+
return null;
|
|
48
|
+
const nativeEvidence = safeNativeEvidence(value.nativeEvidence);
|
|
49
|
+
if (!nativeEvidence) return null;
|
|
50
|
+
return {
|
|
51
|
+
at: value.at,
|
|
52
|
+
status: value.status,
|
|
53
|
+
code:
|
|
54
|
+
typeof value.code === "string" && /^[A-Z0-9_]{1,80}$/.test(value.code)
|
|
55
|
+
? value.code
|
|
56
|
+
: "NATIVE_TURN_FAILED",
|
|
57
|
+
...(NATIVE_MODELS.includes(value.model) || value.model === "gemini-argon" || value.model === "gemini-flash"
|
|
58
|
+
? { model: value.model }
|
|
59
|
+
: {}),
|
|
60
|
+
nativeEvidence,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export function safeNativeEvidence(value) {
|
|
64
|
+
if (!value || typeof value !== "object") return null;
|
|
65
|
+
const upstreamMessage = sanitizeUpstreamMessage(value.upstreamMessage);
|
|
66
|
+
const http2ResetCode = bounded(value.http2ResetCode, 1, 0xffffffff);
|
|
67
|
+
const streamCloseCode = bounded(value.streamCloseCode, 1, 0xffffffff);
|
|
68
|
+
const fallback = bounded(value.fallback, 0, 1);
|
|
69
|
+
const downgradeReason = bounded(value.downgradeReason, 0, 0x7fffffff);
|
|
70
|
+
const toolProtocolReason = ['opening_fence', 'closing_fence'].includes(value.toolProtocolReason) ? value.toolProtocolReason : null;
|
|
71
|
+
const emptyResponseReason = ['no_text', 'whitespace_only', 'thoughts_only', 'post_parse_empty'].includes(value.emptyResponseReason) ? value.emptyResponseReason : null;
|
|
72
|
+
const nativeTextBytes = bounded(value.nativeTextBytes, 0, 8 * 1024 * 1024);
|
|
73
|
+
const nativeShareableTextBytes = bounded(value.nativeShareableTextBytes, 0, 8 * 1024 * 1024);
|
|
74
|
+
const nativeResponseRevisions = bounded(value.nativeResponseRevisions, 0, 4096);
|
|
75
|
+
const nativeCompletenessState = bounded(value.nativeCompletenessState, 0, 0x7fffffff);
|
|
76
|
+
return {
|
|
77
|
+
phase: phases.has(value.phase) ? value.phase : null,
|
|
78
|
+
upstreamHttpStatus: bounded(value.upstreamHttpStatus, 100, 599),
|
|
79
|
+
grpcStatus: bounded(value.grpcStatus, 0, 16),
|
|
80
|
+
wireEnded: value.wireEnded === true,
|
|
81
|
+
modelCompleted: value.modelCompleted === true,
|
|
82
|
+
frameCount: bounded(value.frameCount, 0, 4097),
|
|
83
|
+
receivedBytes: bounded(value.receivedBytes, 0, NATIVE_RESPONSE_LIMITS.wireBytes + NATIVE_RESPONSE_LIMITS.queuedBytes),
|
|
84
|
+
observedMode: bounded(value.observedMode, 0, 64),
|
|
85
|
+
observedThinking: bounded(value.observedThinking, 0, 4),
|
|
86
|
+
...(fallback !== null ? { fallback } : {}),
|
|
87
|
+
...(downgradeReason !== null ? { downgradeReason } : {}),
|
|
88
|
+
...(['frame_count', 'wire_bytes'].includes(value.nativeResponseLimitReason) ? { nativeResponseLimitReason: value.nativeResponseLimitReason } : {}),
|
|
89
|
+
...(value.outputFailureReason === 'generic_error_offer' ? { outputFailureReason: value.outputFailureReason } : {}),
|
|
90
|
+
...(value.outputFailureSource === 'exact_text_signature' ? { outputFailureSource: value.outputFailureSource } : {}),
|
|
91
|
+
...(bounded(value.outputToolCalls, 0, 32) !== null ? { outputToolCalls: value.outputToolCalls } : {}),
|
|
92
|
+
...(nativeCompletenessState !== null ? { nativeCompletenessState } : {}),
|
|
93
|
+
...(toolProtocolReason ? { toolProtocolReason } : {}),
|
|
94
|
+
...(value.toolErrorEarlyStop === true ? { toolErrorEarlyStop: true } : {}),
|
|
95
|
+
...(emptyResponseReason ? { emptyResponseReason } : {}),
|
|
96
|
+
...(nativeTextBytes !== null ? { nativeTextBytes } : {}),
|
|
97
|
+
...(nativeShareableTextBytes !== null ? { nativeShareableTextBytes } : {}),
|
|
98
|
+
...(nativeResponseRevisions !== null ? { nativeResponseRevisions } : {}),
|
|
99
|
+
...(typeof value.nativeResponseIdentityVerified === 'boolean' ? { nativeResponseIdentityVerified: value.nativeResponseIdentityVerified } : {}),
|
|
100
|
+
...(['provider_publish', 'snapshot_stream', 'snapshot_identity', 'delivery_reset', 'delivery_final'].includes(value.nonMonotonicSite) ? { nonMonotonicSite: value.nonMonotonicSite } : {}),
|
|
101
|
+
...(typeof value.sameResponseIdentity === 'boolean' ? { sameResponseIdentity: value.sameResponseIdentity } : {}),
|
|
102
|
+
...(bounded(value.snapshotPriorBytes, 0, 8 * 1024 * 1024) !== null ? { snapshotPriorBytes: value.snapshotPriorBytes } : {}),
|
|
103
|
+
...(bounded(value.snapshotNextBytes, 0, 8 * 1024 * 1024) !== null ? { snapshotNextBytes: value.snapshotNextBytes } : {}),
|
|
104
|
+
...(bounded(value.snapshotCommonPrefixBytes, 0, 8 * 1024 * 1024) !== null ? { snapshotCommonPrefixBytes: value.snapshotCommonPrefixBytes } : {}),
|
|
105
|
+
...(bounded(value.publishedBytes, 0, 8 * 1024 * 1024) !== null ? { publishedBytes: value.publishedBytes } : {}),
|
|
106
|
+
...(bounded(value.toolCallCount, 0, 32) !== null ? { toolCallCount: value.toolCallCount } : {}),
|
|
107
|
+
...Object.fromEntries(['nativeThoughtsPresent', 'nativeStructuredOutputPresent', 'nativeRefusalPresent']
|
|
108
|
+
.filter(key => typeof value[key] === 'boolean').map(key => [key, value[key]])),
|
|
109
|
+
...(upstreamMessage ? { upstreamMessage } : {}),
|
|
110
|
+
...(http2ResetCode !== null ? { http2ResetCode } : {}),
|
|
111
|
+
...(typeof value.connectionEndObserved === 'boolean' ? { connectionEndObserved: value.connectionEndObserved } : {}),
|
|
112
|
+
...(streamCloseCode !== null ? { streamCloseCode } : {}),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Whole-text snapshots repeat prior output. Bound transient buffering separately
|
|
2
|
+
// from lifetime traffic; never retain the complete wire history in memory.
|
|
3
|
+
export const NATIVE_RESPONSE_LIMITS = Object.freeze({
|
|
4
|
+
frames: 4096,
|
|
5
|
+
frameBytes: 1024 * 1024,
|
|
6
|
+
queuedBytes: 8 * 1024 * 1024,
|
|
7
|
+
wireBytes: 256 * 1024 * 1024,
|
|
8
|
+
});
|