pi-gemini-app 0.1.14 → 0.1.16

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.
@@ -14,7 +14,7 @@ function sliceCodeUnitsSafe(text, maxChars = CITATION_LIMITS.MAX_TITLE_CHARS) {
14
14
  }
15
15
 
16
16
  function cleanPlainTitle(value, { stripHtml = false } = {}) {
17
- if (typeof value !== 'string' || Buffer.from(value, 'utf8').toString('utf8') !== value) return '';
17
+ if (typeof value !== 'string' || !value.isWellFormed()) return '';
18
18
  let text = stripHtml ? value.replace(/<[^>]*>/g, '') : value;
19
19
  text = text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').replace(/\s+/g, ' ').trim();
20
20
  return sliceCodeUnitsSafe(text, CITATION_LIMITS.MAX_TITLE_CHARS);
@@ -58,6 +58,7 @@ export async function runNativeSearchDiagnostic({
58
58
  signal,
59
59
  timeoutMs = 180000,
60
60
  allowNativeTools = false,
61
+ timing,
61
62
  } = {}) {
62
63
  if (
63
64
  typeof getAccessToken !== "function" ||
@@ -225,7 +226,7 @@ export async function runNativeSearchDiagnostic({
225
226
  thinking_level: 2,
226
227
  },
227
228
  () => {},
228
- { signal },
229
+ { signal, ...(timing ? { timing } : {}) },
229
230
  );
230
231
  if (result.resolvedModeCategory !== 3 || result.thinkingLevel !== 2)
231
232
  return fail("NATIVE_THINKING_MISMATCH");
@@ -59,6 +59,7 @@ export function openDirectTurn(
59
59
  allowNativeTools = false,
60
60
  emitHeaders = false,
61
61
  diagnostic,
62
+ onHeaders,
62
63
  } = {},
63
64
  { connect = connectHttp2 } = {},
64
65
  ) {
@@ -366,6 +367,7 @@ export function openDirectTurn(
366
367
  request.on("response", headers => {
367
368
  lastInboundAt = Date.now();
368
369
  note('peer_headers', { httpStatus: Number(headers[':status']), grpcStatus: Number(headers['grpc-status']) });
370
+ if (typeof onHeaders === 'function') try { onHeaders(); } catch {}
369
371
  status(headers);
370
372
  if (emitHeaders && !closed && httpStatus === 200) push({ type: 'headers', httpStatus });
371
373
  });
@@ -4,14 +4,15 @@ import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
4
4
  import { parse } from '../../native-wire/protobuf.mjs';
5
5
  import { protocolError } from '../tool-protocol.mjs';
6
6
  export const EMPTY_RESPONSE_REASONS = Object.freeze(['no_text', 'whitespace_only', 'thoughts_only', 'post_parse_empty']);
7
- export function inspectNativeOutput(fields) {
7
+ export function inspectNativeOutput(fields, preParsedModelFields = null) {
8
8
  const singular = (list, number, wire = 2) => {
9
9
  const found = list.filter(field => field.number === number);
10
10
  if (found.length > 1 || found.some(field => field.wire !== wire)) throw protocolError('INVALID_NATIVE_RESPONSE', 502);
11
11
  return found[0];
12
12
  };
13
13
  const refusal = [13, 17].some(number => singular(fields, number) !== undefined);
14
- const model = singular(fields, 1), mf = model ? parse(model.payload) : [];
14
+ const model = singular(fields, 1);
15
+ const mf = model ? (Array.isArray(preParsedModelFields) ? preParsedModelFields : parse(model.payload)) : [];
15
16
  const shareable = singular(mf, 7), thoughts = singular(mf, 12);
16
17
  const tf = thoughts ? parse(thoughts.payload) : [];
17
18
  const thoughtText = singular(tf, 1);
@@ -57,3 +58,36 @@ export function isVerifiedEmptyResponse(error, model, { allowAutoModel = false }
57
58
  e.http2ResetCode === undefined &&
58
59
  (isAuto || ((e.fallback === undefined || e.fallback === 0) && (e.downgradeReason === undefined || e.downgradeReason === 0)));
59
60
  }
61
+
62
+ /**
63
+ * Shared terminal-outcome gate for interrupted turns across HTTP Gateway, Pi,
64
+ * OpenClaw, and OpenCode. Unverified output (refusal/downgrade/missing mode)
65
+ * and caller aborts NEVER qualify for partial-success completion.
66
+ */
67
+ export function canCompleteInterruptedOutput({
68
+ error,
69
+ publishedBytes = 0,
70
+ callCount = 0,
71
+ hasVisibleText = false,
72
+ prefixBytes = 2048,
73
+ aborted = false,
74
+ allowPrefixPartialOnTransport = false,
75
+ salvageToolErrors = false,
76
+ toolErrors = null,
77
+ } = {}) {
78
+ if (aborted || error?.unverifiedOutput === true) return false;
79
+ if (allowPrefixPartialOnTransport) {
80
+ return (
81
+ publishedBytes >= prefixBytes ||
82
+ callCount > 0 ||
83
+ (error?.postOutputIdleStall === true && hasVisibleText)
84
+ );
85
+ }
86
+ const usableTimeout =
87
+ error?.code === 'NATIVE_TURN_TIMEOUT' &&
88
+ (callCount > 0 || (error?.postOutputIdleStall === true && hasVisibleText));
89
+ const salvageValidatedCalls = Boolean(
90
+ salvageToolErrors && callCount > 0 && toolErrors?.has?.(error?.code),
91
+ );
92
+ return usableTimeout || salvageValidatedCalls;
93
+ }
@@ -94,9 +94,12 @@ export function decodeUsageInfo(payload) {
94
94
  }
95
95
 
96
96
  /** Optional in-generation metadata. Invalid quota metadata is isolated from the turn. */
97
- export function decodePassiveQuota(clientBytes, observedModel) {
97
+ export function decodePassiveQuota(clientBytes, observedModel, preParsedFields = null) {
98
98
  try {
99
- const fs = fields(clientBytes), budgets = [], refills = [];
99
+ if (!Buffer.isBuffer(clientBytes) || clientBytes.length > MAX) fail();
100
+ const fs = Array.isArray(preParsedFields) ? preParsedFields : fields(clientBytes);
101
+ if (!fs.some((x) => x.number === 20 || x.number === 29 || x.number === 33)) return null;
102
+ const budgets = [], refills = [];
100
103
  for (const n of [20, 29, 33]) one(fs, n, 2);
101
104
  for (const f of fs.filter((x) => x.number === 20)) {
102
105
  if (f.wire !== 2) fail();
@@ -162,7 +165,7 @@ export function safeQuota(value) {
162
165
  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
166
  })) : [];
164
167
  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 } : {}) };
168
+ 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-carbon", "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
169
  }
167
170
  export function quotaFailureCode(error) { return SAFE_ERRORS.has(error?.code) ? error.code : "QUOTA_REFRESH_FAILED"; }
168
171
 
@@ -16,7 +16,7 @@ function assertOnlyKeys(obj, allowed, code = 'INVALID_RESPONSE_FORMAT') {
16
16
  }
17
17
 
18
18
  function validUtf8String(value) {
19
- return typeof value === 'string' && Buffer.from(value).toString('utf8') === value;
19
+ return typeof value === 'string' && value.isWellFormed();
20
20
  }
21
21
 
22
22
  function parseJsonSchemaSpec(spec) {
@@ -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,9 +1,16 @@
1
- // GetUsageInfo.user_tier=2 uses the native UserSubscriptionTier enum.
2
- // Verified from SwiftProtobuf name-map/type metadata and an existing upstream payload.
3
- import { parse } from '../../native-wire/protobuf.mjs';
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: 2 });
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' });
10
+ // The Gemini app offers Carbon only on Google AI Ultra; confirmed Free, Plus and Pro accounts never list it.
11
+ export const CARBON_EXCLUDED_TIERS = Object.freeze(['free', 'plus', 'pro']);
12
+ const CARBON_EXCLUDED_TIER_SET = new Set(CARBON_EXCLUDED_TIERS);
13
+ export const isCarbonExcludedTier = (tier) => typeof tier === 'string' && CARBON_EXCLUDED_TIER_SET.has(tier);
7
14
  const NAMES = Object.freeze({ 0: 'TIER_UNSPECIFIED', 1: 'BASIC_USER', 2: 'TIER1', 3: 'TIER2', 4: 'LITE_USER', 5: 'TIER_NEON' });
8
15
  const CODES = new Set(['SUBSCRIPTION_CREDENTIAL_REQUIRED', 'INVALID_SUBSCRIPTION_TIMEOUT', 'INVALID_SUBSCRIPTION_METADATA',
9
16
  'SUBSCRIPTION_CANCELLED', 'SUBSCRIPTION_TIMEOUT', 'SUBSCRIPTION_STREAM_RESET', 'SUBSCRIPTION_RATE_LIMITED',
@@ -18,34 +25,48 @@ const timestamp = value => {
18
25
  const ms = Date.parse(value); return Number.isFinite(ms) && ms >= 0 ? new Date(ms).toISOString() : null;
19
26
  };
20
27
  export const subscriptionFailureCode = error => CODES.has(error?.code) ? error.code : 'SUBSCRIPTION_FETCH_FAILED';
21
- // Established read-only unary GetUsageInfo request is empty. No client-supplied tier.
22
- export const buildSubscriptionRequest = () => Buffer.alloc(0);
28
+ // Read-only GetUserStatus request with RequestMetadata (field 1) advertising ENABLE_USER_SUBSCRIPTION_TIER (529).
29
+ export const buildSubscriptionRequest = () => lengthDelimited(
30
+ 1,
31
+ buildRequestMetadata({
32
+ clientType: 21,
33
+ uiSource: 1,
34
+ languageCode: 'en',
35
+ interfaceLanguageCode: 'en',
36
+ subscriptionTierCapability: true,
37
+ }),
38
+ );
23
39
  export function safeSubscription(input) {
24
40
  const value = input && typeof input === 'object' && !Array.isArray(input) ? input : {};
25
- const official = value.source === 'official' && value.provider === 'google-robin' && value.rpc === 'GetUsageInfo';
41
+ const official = value.source === 'official' && value.provider === 'google-robin' && value.rpc === 'GetUserStatus';
26
42
  const nativeTier = official ? integer(value.nativeTier) : null, tier = TIERS[nativeTier] ?? 'unknown';
43
+ const isForced = official && typeof value.isForced === 'boolean' ? value.isForced : null;
27
44
  let status = ['unqueried', 'ok', 'missing', 'error'].includes(value.status) ? value.status : 'unqueried';
28
45
  if (status === 'ok' && (!official || tier === 'unknown')) status = 'missing';
29
- return { source: official ? 'official' : 'unknown', provider: official ? 'google-robin' : null, rpc: official ? 'GetUsageInfo' : null, status,
46
+ return { source: official ? 'official' : 'unknown', provider: official ? 'google-robin' : null, rpc: official ? 'GetUserStatus' : null, status,
30
47
  tier, nativeTier, nativeTierName: nativeTier === null ? null : NAMES[nativeTier] ?? 'UNRECOGNIZED',
31
- // This RPC reports a tier, not billing/cancellation/forced-tier details.
32
- nativeState: null, membershipStatus: 'unknown', isForced: null,
48
+ // GetUserStatus does not establish billing/cancellation ownership details.
49
+ nativeState: null, membershipStatus: 'unknown', isForced,
33
50
  updatedAt: timestamp(value.updatedAt), lastAttemptAt: timestamp(value.lastAttemptAt),
34
51
  errorCode: status === 'error' ? subscriptionFailureCode({ code: value.errorCode }) : null };
35
52
  }
53
+ function decodeBoundedVarint(payload, max = 0x7fffffffn) {
54
+ if (!payload.length || payload.length > 10 || (payload.at(-1) & 128)) throw Error();
55
+ let value = 0n, shift = 0n;
56
+ for (const byte of payload) { value |= BigInt(byte & 127) << shift; shift += 7n; }
57
+ if (value > max) throw Error();
58
+ return Number(value);
59
+ }
36
60
  export function decodeSubscription(payload) {
37
61
  try {
38
62
  if (!Buffer.isBuffer(payload) || payload.length > 512 * 1024) throw Error();
39
63
  const fields = parse(payload); if (fields.length > 10000) throw Error();
40
- const found = fields.filter(field => field.number === 2);
64
+ const found = fields.filter(field => field.number === SUBSCRIPTION_FIELDS.nativeTier);
41
65
  if (found.length > 1 || (found.length && found[0].wire !== 0)) throw Error();
42
- let nativeTier = null;
43
- if (found.length) {
44
- let value = 0n, shift = 0n;
45
- for (const byte of found[0].payload) { value |= BigInt(byte & 127) << shift; shift += 7n; }
46
- if (value > 0x7fffffffn) throw Error();
47
- nativeTier = Number(value);
48
- }
49
- return safeSubscription({ source: 'official', provider: 'google-robin', rpc: 'GetUsageInfo', status: TIERS[nativeTier] ? 'ok' : 'missing', nativeTier });
66
+ const forced = fields.filter(field => field.number === SUBSCRIPTION_FIELDS.isForced);
67
+ if (forced.length > 1 || (forced.length && forced[0].wire !== 0)) throw Error();
68
+ const nativeTier = found.length ? decodeBoundedVarint(found[0].payload) : null;
69
+ const isForced = forced.length ? decodeBoundedVarint(forced[0].payload, 1n) === 1 : null;
70
+ return safeSubscription({ source: 'official', provider: 'google-robin', rpc: 'GetUserStatus', status: TIERS[nativeTier] ? 'ok' : 'missing', nativeTier, isForced });
50
71
  } catch { throw fault('INVALID_SUBSCRIPTION_METADATA', 502); }
51
72
  }
@@ -1,3 +1,4 @@
1
+ import zlib from 'node:zlib';
1
2
  import { parseRemoteImageUrl } from './image-url.mjs';
2
3
  import { protocolError } from './tool-protocol.mjs';
3
4
 
@@ -9,15 +10,45 @@ export const MAX_TOTAL_IMAGE_URL_BYTES = Math.ceil(MAX_TOTAL_IMAGE_BYTES / 3) *
9
10
  const MAX_PIXELS = 40_000_000;
10
11
  const fail = (code, status = 400) => { throw protocolError(code, status); };
11
12
  const pngMagic = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
12
- const crcTable = Uint32Array.from({ length: 256 }, (_, value) => {
13
- for (let i = 0; i < 8; i++) value = value & 1 ? (value >>> 1) ^ 0xedb88320 : value >>> 1;
14
- return value >>> 0;
15
- });
16
- function crc32(bytes) {
13
+ let crcTable = null;
14
+ export function jsCrc32(bytes) {
15
+ if (!crcTable) {
16
+ crcTable = Uint32Array.from({ length: 256 }, (_, value) => {
17
+ for (let i = 0; i < 8; i++) value = value & 1 ? (value >>> 1) ^ 0xedb88320 : value >>> 1;
18
+ return value >>> 0;
19
+ });
20
+ }
17
21
  let value = 0xffffffff;
18
22
  for (const byte of bytes) value = crcTable[(value ^ byte) & 255] ^ (value >>> 8);
19
23
  return (value ^ 0xffffffff) >>> 0;
20
24
  }
25
+ // Node 22 added zlib.crc32() in 22.2.0 while package.json supports >=22.0.0;
26
+ // feature-detect once and keep the standard JS implementation as fallback.
27
+ export function createCrc32(zlibModule = zlib) {
28
+ return typeof zlibModule?.crc32 === 'function'
29
+ ? bytes => zlibModule.crc32(bytes) >>> 0
30
+ : jsCrc32;
31
+ }
32
+ const crc32 = createCrc32();
33
+ function base64Sextet(code) {
34
+ if (code >= 65 && code <= 90) return code - 65; // A-Z
35
+ if (code >= 97 && code <= 122) return code - 71; // a-z
36
+ if (code >= 48 && code <= 57) return code + 4; // 0-9
37
+ if (code === 43) return 62; // +
38
+ if (code === 47) return 63; // /
39
+ return -1;
40
+ }
41
+ export function hasCanonicalBase64Tail(b64) {
42
+ const len = b64.length;
43
+ if (!len || (len & 3)) return false;
44
+ if (b64.charCodeAt(len - 1) !== 61) return true;
45
+ if (b64.charCodeAt(len - 2) === 61) {
46
+ const sextet = base64Sextet(b64.charCodeAt(len - 3));
47
+ return sextet >= 0 && (sextet & 0x0f) === 0;
48
+ }
49
+ const sextet = base64Sextet(b64.charCodeAt(len - 2));
50
+ return sextet >= 0 && (sextet & 0x03) === 0;
51
+ }
21
52
  // Structural checks only: the gateway never decompresses or renders caller images.
22
53
  function dimensions(bytes, mimeType) {
23
54
  if (mimeType === 'image/png') {
@@ -85,16 +116,88 @@ function dimensions(bytes, mimeType) {
85
116
  }
86
117
  fail('UNSUPPORTED_IMAGE_FORMAT');
87
118
  }
119
+ const validatedImageCaches = new WeakMap();
120
+
121
+ function lookupValidatedCache(cacheHandle, url) {
122
+ if (typeof url !== 'string' || !url.startsWith('data:')) return null;
123
+ const store = cacheHandle && typeof cacheHandle === 'object' ? validatedImageCaches.get(cacheHandle) : undefined;
124
+ if (!store) return null;
125
+ const rec = store.get(url);
126
+ if (!rec) return null;
127
+ if (rec.url === url) return { mimeType: rec.mimeType, data: rec.data, width: rec.width, height: rec.height, url: rec.url };
128
+ const comma = rec.url.indexOf(',');
129
+ if (
130
+ comma > 0 &&
131
+ url.length === rec.url.length &&
132
+ url.indexOf(',') === comma &&
133
+ url.slice(0, comma).toLowerCase() === rec.url.slice(0, comma) &&
134
+ url.slice(comma) === rec.url.slice(comma)
135
+ ) {
136
+ return { mimeType: rec.mimeType, data: rec.data, width: rec.width, height: rec.height, url: rec.url };
137
+ }
138
+ return null;
139
+ }
140
+
141
+ /**
142
+ * Unforgeable, request-scoped in-process cache of validated image bytes.
143
+ * Validated Buffers stay private inside this module so callers cannot mutate
144
+ * bytes or metadata after validation. Never cross an HTTP trust boundary.
145
+ */
146
+ export function createValidatedImageCache() {
147
+ const store = new Map();
148
+ const handle = Object.freeze({
149
+ get size() { return store.size; },
150
+ decodeDataUrl(url) {
151
+ const existing = lookupValidatedCache(handle, url);
152
+ if (existing) {
153
+ return { mimeType: existing.mimeType, width: existing.width, height: existing.height, url: existing.url };
154
+ }
155
+ const decoded = decodeImageDataUrl(url);
156
+ const record = Object.freeze({
157
+ mimeType: decoded.mimeType,
158
+ data: decoded.data,
159
+ width: decoded.width,
160
+ height: decoded.height,
161
+ url: decoded.url,
162
+ });
163
+ store.set(url, record);
164
+ store.set(record.url, record);
165
+ return { mimeType: record.mimeType, width: record.width, height: record.height, url: record.url };
166
+ },
167
+ encodeBytes(data, mimeType) {
168
+ if (!Buffer.isBuffer(data) || !data.length) fail('INVALID_IMAGE_BYTES');
169
+ // Copy caller Buffer before validating so later caller mutations cannot alter stored bytes.
170
+ const ownBytes = Buffer.from(data);
171
+ const decoded = decodeImageBytes(ownBytes, mimeType);
172
+ const url = `data:${decoded.mimeType};base64,${ownBytes.toString('base64')}`;
173
+ if (Buffer.byteLength(url) > MAX_IMAGE_URL_BYTES) fail('IMAGE_TOO_LARGE', 413);
174
+ const record = Object.freeze({
175
+ mimeType: decoded.mimeType,
176
+ data: ownBytes,
177
+ width: decoded.width,
178
+ height: decoded.height,
179
+ url,
180
+ });
181
+ store.set(url, record);
182
+ return { mimeType: record.mimeType, width: record.width, height: record.height, url };
183
+ },
184
+ });
185
+ validatedImageCaches.set(handle, store);
186
+ return handle;
187
+ }
188
+
88
189
  /** Inline decoder only; remote downloads separately reuse decodeImageBytes. */
89
190
  export function decodeImageDataUrl(url) {
90
191
  if (typeof url !== 'string') fail('INVALID_IMAGE_URL');
91
192
  if (!url.startsWith('data:')) fail('UNSUPPORTED_IMAGE_URL');
92
193
  if (Buffer.byteLength(url) > MAX_IMAGE_URL_BYTES) fail('IMAGE_TOO_LARGE', 413);
93
194
  const match = /^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/]*={0,2})$/i.exec(url);
94
- if (!match || !match[2].length || match[2].length % 4) fail('INVALID_IMAGE_DATA_URL');
95
- const mimeType = match[1].toLowerCase(), data = Buffer.from(match[2], 'base64');
96
- if (!data.length || data.toString('base64') !== match[2]) fail('INVALID_IMAGE_DATA_URL');
97
- return { ...decodeImageBytes(data, mimeType), url: `data:${mimeType};base64,${match[2]}` };
195
+ if (!match || !hasCanonicalBase64Tail(match[2])) fail('INVALID_IMAGE_DATA_URL');
196
+ const b64 = match[2];
197
+ const pad = b64.charCodeAt(b64.length - 1) === 61 ? (b64.charCodeAt(b64.length - 2) === 61 ? 2 : 1) : 0;
198
+ const mimeType = match[1].toLowerCase(), data = Buffer.from(b64, 'base64');
199
+ if (!data.length || data.length !== (b64.length / 4) * 3 - pad) fail('INVALID_IMAGE_DATA_URL');
200
+ return { ...decodeImageBytes(data, mimeType), url: `data:${mimeType};base64,${b64}` };
98
201
  }
99
202
  export function decodeImageBytes(data, mimeType) {
100
203
  if (!Buffer.isBuffer(data) || !data.length) fail('INVALID_IMAGE_BYTES');
@@ -106,25 +209,41 @@ export function decodeImageBytes(data, mimeType) {
106
209
  export function normalizeImageUrl(url, detail, decodedCache) {
107
210
  if (detail !== undefined && detail !== 'auto') fail('UNSUPPORTED_IMAGE_DETAIL');
108
211
  if (typeof url === 'string' && /^https?:/i.test(url)) return parseRemoteImageUrl(url).href;
109
- const cached = decodedCache?.get(url);
212
+ const cached = lookupValidatedCache(decodedCache, url);
110
213
  if (cached) return cached.url;
214
+ const store = decodedCache && typeof decodedCache === 'object' ? validatedImageCaches.get(decodedCache) : undefined;
111
215
  const decoded = decodeImageDataUrl(url);
112
- if (decodedCache) {
113
- decodedCache.set(url, decoded);
114
- decodedCache.set(decoded.url, decoded);
216
+ if (store) {
217
+ const record = Object.freeze({
218
+ mimeType: decoded.mimeType,
219
+ data: decoded.data,
220
+ width: decoded.width,
221
+ height: decoded.height,
222
+ url: decoded.url,
223
+ });
224
+ store.set(url, record);
225
+ store.set(record.url, record);
115
226
  }
116
227
  return decoded.url;
117
228
  }
118
- export function collectImageInputs(messages, resolvedImages, decodedCache) {
229
+ export function resolveMaxImages(maxImages) {
230
+ if (maxImages === undefined || maxImages === null || maxImages === 0) return MAX_IMAGES;
231
+ if (!Number.isSafeInteger(maxImages) || maxImages < 1 || maxImages > MAX_IMAGES) {
232
+ throw new RangeError(`Invalid maxImages: expected integer 0..${MAX_IMAGES}`);
233
+ }
234
+ return maxImages;
235
+ }
236
+ export function collectImageInputs(messages, resolvedImages, decodedCache, maxImages = MAX_IMAGES) {
237
+ const limit = resolveMaxImages(maxImages);
119
238
  let total = 0;
120
239
  const images = [], transcript = messages.map(message => {
121
240
  if (!Array.isArray(message.content)) return message;
122
241
  const content = message.content.map(part => {
123
242
  if (part.type === 'text') return part.text;
124
243
  if (message.role !== 'user' || part.type !== 'image_url') fail('UNSUPPORTED_IMAGE_ROLE');
125
- if (images.length >= MAX_IMAGES) fail('IMAGE_COUNT_EXCEEDED', 413);
244
+ if (images.length >= limit) fail('IMAGE_COUNT_EXCEEDED', 413);
126
245
  const url = part.image_url?.url;
127
- const decoded = resolvedImages ? resolvedImages[images.length] : /^https?:/i.test(url) ? { url: parseRemoteImageUrl(url).href } : (decodedCache?.get(url) ?? decodeImageDataUrl(url));
246
+ const decoded = resolvedImages ? resolvedImages[images.length] : /^https?:/i.test(url) ? { url: parseRemoteImageUrl(url).href } : (lookupValidatedCache(decodedCache, url) ?? decodeImageDataUrl(url));
128
247
  const { data, mimeType, width, height } = decoded;
129
248
  if ((total += (data?.length ?? 0)) > MAX_TOTAL_IMAGE_BYTES) fail('IMAGES_TOO_LARGE', 413);
130
249
  images.push(data ? { data, mimeType, width, height } : decoded);