opencode-gemini-app 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/DISCLAIMER.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +44 -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 +64 -0
  15. package/src/gateway/image-download.mjs +110 -0
  16. package/src/gateway/image-upload.mjs +219 -0
  17. package/src/gateway/native-diagnostic.mjs +189 -0
  18. package/src/gateway/native-evidence.mjs +113 -0
  19. package/src/gateway/native-response-limits.mjs +8 -0
  20. package/src/gateway/native-search-citations.mjs +196 -0
  21. package/src/gateway/native-search-diagnostic.mjs +282 -0
  22. package/src/gateway/native-search-metadata.mjs +749 -0
  23. package/src/gateway/native-transport.mjs +375 -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 +681 -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 +348 -0
@@ -0,0 +1,157 @@
1
+ import { plainObject, protocolError, parseBoundedJson } from '../tool-protocol.mjs';
2
+ import { compileOutputSchema, stripSchemaAnnotations, validateOutputValue } from '../prompt-tool-schema.mjs';
3
+
4
+ const NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
5
+ const DESCRIPTION_MAX_BYTES = 4096;
6
+ const VERBOSITY_VALUES = new Set(['low', 'medium', 'high']);
7
+
8
+ function failFormat(code = 'INVALID_RESPONSE_FORMAT', status = 400) {
9
+ throw protocolError(code, status);
10
+ }
11
+
12
+ function assertOnlyKeys(obj, allowed, code = 'INVALID_RESPONSE_FORMAT') {
13
+ for (const key of Object.keys(obj)) {
14
+ if (!allowed.includes(key)) failFormat(code, 400);
15
+ }
16
+ }
17
+
18
+ function validUtf8String(value) {
19
+ return typeof value === 'string' && Buffer.from(value).toString('utf8') === value;
20
+ }
21
+
22
+ function parseJsonSchemaSpec(spec) {
23
+ if (typeof spec.name !== 'string' || !NAME_RE.test(spec.name)) failFormat();
24
+ if (spec.description !== undefined) {
25
+ if (!validUtf8String(spec.description) || Buffer.byteLength(spec.description, 'utf8') > DESCRIPTION_MAX_BYTES) {
26
+ failFormat();
27
+ }
28
+ }
29
+ if (spec.strict !== undefined && typeof spec.strict !== 'boolean') failFormat();
30
+ if (!plainObject(spec.schema)) failFormat();
31
+ let compiled;
32
+ try {
33
+ compiled = compileOutputSchema(stripSchemaAnnotations(spec.schema));
34
+ } catch (error) {
35
+ throw protocolError(error?.code || 'INVALID_RESPONSE_FORMAT', error?.status ?? 400);
36
+ }
37
+ return {
38
+ type: 'json_schema',
39
+ json_schema: {
40
+ name: spec.name,
41
+ ...(spec.description !== undefined ? { description: spec.description } : {}),
42
+ schema: compiled,
43
+ ...(spec.strict !== undefined ? { strict: spec.strict } : {}),
44
+ },
45
+ };
46
+ }
47
+
48
+ /** Validate and canonicalize Chat Completions `response_format`. */
49
+ export function normalizeChatResponseFormat(responseFormat) {
50
+ if (responseFormat === undefined) return undefined;
51
+ if (!plainObject(responseFormat)) failFormat();
52
+ if (responseFormat.type === 'text') {
53
+ assertOnlyKeys(responseFormat, ['type']);
54
+ return undefined;
55
+ }
56
+ if (responseFormat.type === 'json_object') {
57
+ assertOnlyKeys(responseFormat, ['type']);
58
+ return { type: 'json_object' };
59
+ }
60
+ if (responseFormat.type === 'json_schema') {
61
+ assertOnlyKeys(responseFormat, ['type', 'json_schema']);
62
+ if (!plainObject(responseFormat.json_schema)) failFormat();
63
+ assertOnlyKeys(responseFormat.json_schema, ['name', 'description', 'schema', 'strict']);
64
+ return parseJsonSchemaSpec(responseFormat.json_schema);
65
+ }
66
+ failFormat();
67
+ }
68
+
69
+ /** Validate and canonicalize Responses `text` option (`format` + inert `verbosity`). */
70
+ export function normalizeResponsesText(text) {
71
+ if (text === undefined) return undefined;
72
+ if (!plainObject(text)) failFormat();
73
+ assertOnlyKeys(text, ['format', 'verbosity'], 'UNSUPPORTED_PARAMETER');
74
+ if (text.verbosity !== undefined && (typeof text.verbosity !== 'string' || !VERBOSITY_VALUES.has(text.verbosity))) {
75
+ failFormat();
76
+ }
77
+ const format = text.format;
78
+ if (format === undefined) return undefined;
79
+ if (!plainObject(format)) failFormat();
80
+ if (format.type === 'text') {
81
+ assertOnlyKeys(format, ['type']);
82
+ return undefined;
83
+ }
84
+ if (format.type === 'json_object') {
85
+ assertOnlyKeys(format, ['type']);
86
+ return { type: 'json_object' };
87
+ }
88
+ if (format.type === 'json_schema') {
89
+ assertOnlyKeys(format, ['type', 'name', 'description', 'schema', 'strict']);
90
+ return parseJsonSchemaSpec(format);
91
+ }
92
+ failFormat();
93
+ }
94
+
95
+ /** Build canonical prompt instructions enforcing structured JSON outputs. */
96
+ export function buildStructuredOutputInstruction(responseFormat) {
97
+ if (!responseFormat) return '';
98
+ if (responseFormat.type === 'json_object') {
99
+ return [
100
+ '# Output Format Constraint (response_format: json_object)',
101
+ 'When providing your final assistant answer (not emitting a tool_call fence), output ONLY a single valid UTF-8 JSON object.',
102
+ 'Do not include surrounding prose, explanations, or markdown code fences.',
103
+ ].join('\n');
104
+ }
105
+ if (responseFormat.type === 'json_schema') {
106
+ const spec = responseFormat.json_schema;
107
+ return [
108
+ '# Output Format Constraint (response_format: json_schema)',
109
+ `Schema name: ${spec.name}`,
110
+ ...(spec.description ? [`Description: ${spec.description}`] : []),
111
+ ...(spec.strict !== undefined ? [`Strict: ${String(spec.strict)}`] : []),
112
+ 'When providing your final assistant answer (not emitting a tool_call fence), output ONLY a single valid UTF-8 JSON value strictly conforming to this JSON Schema.',
113
+ 'Do not include surrounding prose, explanations, or markdown code fences:',
114
+ JSON.stringify(spec.schema),
115
+ ].join('\n');
116
+ }
117
+ return '';
118
+ }
119
+
120
+ function stripSoleTopLevelJsonFence(text) {
121
+ const trimmed = text.trim();
122
+ if (!trimmed.startsWith('```') || !trimmed.endsWith('```')) return trimmed;
123
+ const firstNl = trimmed.indexOf('\n');
124
+ if (firstNl === -1) return trimmed;
125
+ const header = trimmed.slice(3, firstNl).replace(/\r$/, '');
126
+ if (header !== '' && header !== 'json') return trimmed;
127
+ const beforeClosing = trimmed.slice(firstNl + 1, -3);
128
+ if (!beforeClosing.endsWith('\n')) return trimmed;
129
+ const inner = beforeClosing.endsWith('\r\n') ? beforeClosing.slice(0, -2) : beforeClosing.slice(0, -1);
130
+ return inner.trim();
131
+ }
132
+
133
+ /** Validate final assistant text against normalized `responseFormat`, returning fence-free JSON. */
134
+ export function validateStructuredOutputText(content, responseFormat) {
135
+ if (!responseFormat) return content;
136
+ if (typeof content !== 'string') throw protocolError('INVALID_STRUCTURED_OUTPUT_JSON', 502);
137
+ const candidate = stripSoleTopLevelJsonFence(content);
138
+ let parsed;
139
+ try {
140
+ parsed = parseBoundedJson(candidate, { status: 502 });
141
+ } catch {
142
+ throw protocolError('INVALID_STRUCTURED_OUTPUT_JSON', 502);
143
+ }
144
+ if (responseFormat.type === 'json_object') {
145
+ if (!plainObject(parsed)) throw protocolError('STRUCTURED_OUTPUT_SCHEMA_MISMATCH', 502);
146
+ return candidate;
147
+ }
148
+ if (responseFormat.type === 'json_schema') {
149
+ try {
150
+ validateOutputValue(parsed, responseFormat.json_schema.schema);
151
+ } catch (error) {
152
+ throw protocolError(error?.code || 'STRUCTURED_OUTPUT_SCHEMA_MISMATCH', 502);
153
+ }
154
+ return candidate;
155
+ }
156
+ return candidate;
157
+ }
@@ -0,0 +1,51 @@
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';
4
+ import { fault } from './oauth-client-defaults.mjs';
5
+ export const SUBSCRIPTION_FIELDS = Object.freeze({ nativeTier: 2 });
6
+ const TIERS = Object.freeze({ 1: 'free', 2: 'pro', 3: 'ultra', 4: 'plus', 5: 'ultra_neon' });
7
+ const NAMES = Object.freeze({ 0: 'TIER_UNSPECIFIED', 1: 'BASIC_USER', 2: 'TIER1', 3: 'TIER2', 4: 'LITE_USER', 5: 'TIER_NEON' });
8
+ const CODES = new Set(['SUBSCRIPTION_CREDENTIAL_REQUIRED', 'INVALID_SUBSCRIPTION_TIMEOUT', 'INVALID_SUBSCRIPTION_METADATA',
9
+ 'SUBSCRIPTION_CANCELLED', 'SUBSCRIPTION_TIMEOUT', 'SUBSCRIPTION_STREAM_RESET', 'SUBSCRIPTION_RATE_LIMITED',
10
+ 'SUBSCRIPTION_AUTH_REJECTED', 'SUBSCRIPTION_HTTP_REJECTED', 'SUBSCRIPTION_INVALID_STATUS', 'SUBSCRIPTION_PRECONDITION_REQUIRED',
11
+ 'SUBSCRIPTION_UPSTREAM_REJECTED', 'SUBSCRIPTION_CONNECTION_FAILED', 'SUBSCRIPTION_RESPONSE_TOO_LARGE',
12
+ 'SUBSCRIPTION_INVALID_RESPONSE', 'SUBSCRIPTION_STREAM_FAILED', 'SUBSCRIPTION_STREAM_CLOSED_EARLY',
13
+ 'SUBSCRIPTION_INCOMPLETE_RESPONSE', 'SUBSCRIPTION_FETCH_FAILED', 'OAUTH_REFRESH_FAILED', 'NATIVE_PERMISSION_OR_AUTH',
14
+ 'ACCOUNT_LOGIN_REQUIRED']);
15
+ const integer = value => Number.isSafeInteger(value) && value >= 0 && value <= 0x7fffffff ? value : null;
16
+ const timestamp = value => {
17
+ if (typeof value !== 'string' || value.length > 40) return null;
18
+ const ms = Date.parse(value); return Number.isFinite(ms) && ms >= 0 ? new Date(ms).toISOString() : null;
19
+ };
20
+ 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);
23
+ export function safeSubscription(input) {
24
+ const value = input && typeof input === 'object' && !Array.isArray(input) ? input : {};
25
+ const official = value.source === 'official' && value.provider === 'google-robin' && value.rpc === 'GetUsageInfo';
26
+ const nativeTier = official ? integer(value.nativeTier) : null, tier = TIERS[nativeTier] ?? 'unknown';
27
+ let status = ['unqueried', 'ok', 'missing', 'error'].includes(value.status) ? value.status : 'unqueried';
28
+ if (status === 'ok' && (!official || tier === 'unknown')) status = 'missing';
29
+ return { source: official ? 'official' : 'unknown', provider: official ? 'google-robin' : null, rpc: official ? 'GetUsageInfo' : null, status,
30
+ 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,
33
+ updatedAt: timestamp(value.updatedAt), lastAttemptAt: timestamp(value.lastAttemptAt),
34
+ errorCode: status === 'error' ? subscriptionFailureCode({ code: value.errorCode }) : null };
35
+ }
36
+ export function decodeSubscription(payload) {
37
+ try {
38
+ if (!Buffer.isBuffer(payload) || payload.length > 512 * 1024) throw Error();
39
+ const fields = parse(payload); if (fields.length > 10000) throw Error();
40
+ const found = fields.filter(field => field.number === 2);
41
+ 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 });
50
+ } catch { throw fault('INVALID_SUBSCRIPTION_METADATA', 502); }
51
+ }
@@ -0,0 +1,126 @@
1
+ // Native Gemini main-service terms only. Triggered by a user-initiated OAuth login.
2
+ import crypto from "node:crypto";
3
+ import { parse, lengthDelimited as message, varintField as integer } from "../../native-wire/protobuf.mjs";
4
+ import { GrpcMessageReader, frameGrpcMessage, buildRequestMetadata, GATEWAY_USER_AGENT } from "../../native-wire/robin-current.mjs";
5
+ import { decodeGrpcMessage, sanitizeUpstreamMessage } from "./native-evidence.mjs";
6
+ import { connectHttp2 } from "./outbound-proxy.mjs";
7
+ export const TERMS_VERSION_RPC = "/assistant.mobile.robin.RobinService/GetTermsOfServiceVersion";
8
+ export const TERMS_ACCEPT_RPC = "/assistant.mobile.robin.RobinService/AcceptTermsOfService";
9
+ const origin = "https://robinfrontend-pa.googleapis.com";
10
+ const fail = (code, status = 502) => Object.assign(new Error(code), { code, status });
11
+ const SAFE = new Set(["TOS_CREDENTIAL_REQUIRED", "TOS_CANCELLED", "TOS_TIMEOUT", "TOS_RATE_LIMITED", "TOS_AUTH_REJECTED", "TOS_HTTP_REJECTED", "TOS_INVALID_STATUS", "TOS_PRECONDITION_REQUIRED", "TOS_UPSTREAM_REJECTED", "TOS_CONNECTION_FAILED", "TOS_STREAM_RESET", "TOS_STREAM_FAILED", "TOS_STREAM_CLOSED_EARLY", "TOS_RESPONSE_TOO_LARGE", "TOS_INVALID_RESPONSE", "TOS_INCOMPLETE_RESPONSE", "TOS_VERSION_MISSING", "TOS_COMPLETION_FAILED"]);
12
+ export const termsFailureCode = error => SAFE.has(error?.code) ? error.code : "TOS_COMPLETION_FAILED";
13
+ export async function termsRpc(accessToken, rpc, payload, { signal, timeoutMs = 10000, connect = connectHttp2 } = {}) {
14
+ if (![TERMS_VERSION_RPC, TERMS_ACCEPT_RPC].includes(rpc) || !Buffer.isBuffer(payload) || payload.length > 4096) throw fail("TOS_INVALID_RESPONSE");
15
+ if (typeof accessToken !== "string" || !accessToken || accessToken.length > 65536 || /\s/.test(accessToken)) throw fail("TOS_CREDENTIAL_REQUIRED", 401);
16
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 15000) throw fail("TOS_INVALID_RESPONSE", 400);
17
+ if (signal?.aborted) throw fail("TOS_CANCELLED", 499);
18
+ return new Promise((resolve, reject) => {
19
+ let client, request, timer, settled = false, httpStatus = null, grpcStatus = null, upstreamMessage = null, received = 0;
20
+ const payloads = [], reader = new GrpcMessageReader({ maxBytes: 512 * 1024 });
21
+ const finish = (error, result) => {
22
+ if (settled) return; settled = true; clearTimeout(timer); signal?.removeEventListener("abort", abort);
23
+ try { request?.close(); } catch {} try { client?.destroy(); } catch {}
24
+ if (error) { error.termsEvidence = safeTermsEvidence({ operation: rpc === TERMS_VERSION_RPC ? "version" : "accept", upstreamHttpStatus: httpStatus, grpcStatus, upstreamMessage }); reject(error); } else resolve(result);
25
+ };
26
+ const abort = () => finish(fail("TOS_CANCELLED", 499));
27
+ const reset = () => { if (Number.isInteger(request?.rstCode) && request.rstCode > 0) { finish(fail("TOS_STREAM_RESET")); return true; } return false; };
28
+ const status = headers => {
29
+ if (headers["grpc-message"] !== undefined) upstreamMessage = decodeGrpcMessage(headers["grpc-message"]);
30
+ if (headers[":status"] !== undefined) {
31
+ httpStatus = Number(headers[":status"]);
32
+ if (httpStatus === 429) return finish(fail("TOS_RATE_LIMITED", 429));
33
+ if ([401, 403].includes(httpStatus)) return finish(fail("TOS_AUTH_REJECTED", httpStatus));
34
+ if (httpStatus !== 200) return finish(fail("TOS_HTTP_REJECTED"));
35
+ }
36
+ if (headers["grpc-status"] !== undefined) {
37
+ const raw = String(headers["grpc-status"]);
38
+ if (!/^\d{1,2}$/.test(raw) || Number(raw) > 16) return finish(fail("TOS_INVALID_STATUS"));
39
+ grpcStatus = Number(raw);
40
+ if (grpcStatus === 8) return finish(fail("TOS_RATE_LIMITED", 429));
41
+ if ([7, 16].includes(grpcStatus)) return finish(fail("TOS_AUTH_REJECTED", 403));
42
+ if (grpcStatus !== 0) return finish(fail(grpcStatus === 9 ? "TOS_PRECONDITION_REQUIRED" : "TOS_UPSTREAM_REJECTED"));
43
+ }
44
+ };
45
+ signal?.addEventListener("abort", abort, { once: true }); timer = setTimeout(() => finish(fail("TOS_TIMEOUT", 504)), timeoutMs);
46
+ try {
47
+ client = connect(origin); client.on("error", () => finish(fail("TOS_CONNECTION_FAILED")));
48
+ request = client.request({ ":method": "POST", ":path": rpc, authorization: "Bearer " + accessToken, "content-type": "application/grpc", te: "trailers", "grpc-timeout": timeoutMs + "m", "user-agent": GATEWAY_USER_AGENT });
49
+ request.on("response", status); request.on("trailers", status);
50
+ request.on("data", chunk => {
51
+ if (settled) return; received += chunk.length;
52
+ if (received > 1024 * 1024) return finish(fail("TOS_RESPONSE_TOO_LARGE"));
53
+ try { payloads.push(...reader.push(chunk)); if (payloads.length > 1) finish(fail("TOS_INVALID_RESPONSE")); } catch { finish(fail("TOS_INVALID_RESPONSE")); }
54
+ });
55
+ request.on("error", () => { if (!settled && !reset()) finish(fail("TOS_STREAM_FAILED")); });
56
+ request.on("close", () => { if (!settled && !reset()) finish(fail("TOS_STREAM_CLOSED_EARLY")); });
57
+ request.on("end", () => {
58
+ if (settled || reset()) return;
59
+ try { reader.finish(); if (httpStatus !== 200 || grpcStatus !== 0 || payloads.length !== 1) return finish(fail("TOS_INCOMPLETE_RESPONSE")); finish(null, payloads[0]); } catch { finish(fail("TOS_INVALID_RESPONSE")); }
60
+ });
61
+ request.end(frameGrpcMessage(payload));
62
+ } catch { finish(fail("TOS_CONNECTION_FAILED")); }
63
+ });
64
+ }
65
+ function fields(payload) {
66
+ if (!Buffer.isBuffer(payload) || payload.length > 512 * 1024) throw fail("TOS_INVALID_RESPONSE");
67
+ try { return parse(payload); } catch { throw fail("TOS_INVALID_RESPONSE"); }
68
+ }
69
+ function one(list, number, wire) {
70
+ const found = list.filter(f => f.number === number);
71
+ if (found.length > 1 || found.some(f => f.wire !== wire)) throw fail("TOS_INVALID_RESPONSE");
72
+ return found[0];
73
+ }
74
+ function versionValue(field) {
75
+ if (!field) return null;
76
+ let value = 0n;
77
+ if (!field.payload.length || field.payload.length > 5 || field.payload.at(-1) & 128) throw fail("TOS_INVALID_RESPONSE");
78
+ for (let i = 0; i < field.payload.length; i++) value |= BigInt(field.payload[i] & 127) << BigInt(i * 7);
79
+ if (value > 0x7fffffffn) throw fail("TOS_INVALID_RESPONSE");
80
+ return value > 0n ? Number(value) : null;
81
+ }
82
+ function termsMetadata(language) {
83
+ // Same implemented client/surface as the gateway's native generation codec.
84
+ // Do not borrow a device ID, App version, audit token or consent flag.
85
+ return buildRequestMetadata({ clientType: 21, uiSource: 1, languageCode: language, interfaceLanguageCode: language });
86
+ }
87
+ export async function fetchGoogleTermsVersion(accessToken, { signal, rpc = termsRpc, language = "en" } = {}) {
88
+ if (!/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(language) || language.length > 35) throw fail("TOS_INVALID_RESPONSE");
89
+ if (signal?.aborted) throw fail("TOS_CANCELLED", 499);
90
+ const response = await rpc(accessToken, TERMS_VERSION_RPC, Buffer.concat([message(1, Buffer.from(language)), message(2, termsMetadata(language))]), { signal });
91
+ const fs = fields(response), version = versionValue(one(fs, 1, 0)), legacyVersion = versionValue(one(fs, 2, 0));
92
+ for (const n of [3, 4, 5]) one(fs, n, 2);
93
+ if (version === null && legacyVersion === null) throw fail("TOS_VERSION_MISSING");
94
+ return { version, legacyVersion, versionResponseSha256: crypto.createHash("sha256").update(response).digest("hex") };
95
+ }
96
+ export async function acceptGoogleMainTerms(accessToken, { signal, rpc = termsRpc, beforeAccept = () => {}, now = Date.now, language = "en" } = {}) {
97
+ const current = await fetchGoogleTermsVersion(accessToken, { signal, rpc, language });
98
+ const versionNo = current.legacyVersion;
99
+ if (versionNo === null) throw fail("TOS_VERSION_MISSING");
100
+ if (signal?.aborted) throw fail("TOS_CANCELLED", 499);
101
+ beforeAccept();
102
+ const at = now(), seconds = Math.floor(at / 1000), nanos = (at % 1000) * 1000000;
103
+ if (!Number.isSafeInteger(at) || at < 0) throw fail("TOS_INVALID_RESPONSE");
104
+ // The native main-terms builder uses the numeric oneof setter (wire 6),
105
+ // not the old standalone enum (wire 1). Locale is already in metadata.
106
+ const body = Buffer.concat([
107
+ message(4, Buffer.from(GATEWAY_USER_AGENT)), integer(5, 21),
108
+ integer(6, versionNo), message(7, termsMetadata(language)),
109
+ message(10, Buffer.concat([integer(1, seconds), ...(nanos ? [integer(2, nanos)] : [])])),
110
+ ]);
111
+ const accepted = fields(await rpc(accessToken, TERMS_ACCEPT_RPC, body, { signal }));
112
+ one(accepted, 1, 2);
113
+ return { status: "accepted", version: versionNo, legacyVersion: versionNo, versionResponseSha256: current.versionResponseSha256, acceptedAt: new Date(at).toISOString() };
114
+ }
115
+
116
+ export function safeTerms(value) {
117
+ const version = v => Number.isSafeInteger(v) && v > 0 && v <= 0x7fffffff ? v : null;
118
+ const time = v => typeof v === "string" && Number.isFinite(Date.parse(v)) && new Date(v).toISOString() === v ? v : null;
119
+ return { status: ["accepted", "error"].includes(value?.status) ? value.status : "unknown", version: version(value?.version), legacyVersion: version(value?.legacyVersion), acceptedAt: time(value?.acceptedAt), errorCode: SAFE.has(value?.errorCode) ? value.errorCode : null, evidence: safeTermsEvidence(value?.evidence) };
120
+ }
121
+
122
+ export function safeTermsEvidence(value) {
123
+ if (!value || !["version", "accept"].includes(value.operation)) return null;
124
+ const bounded = (v, min, max) => Number.isSafeInteger(v) && v >= min && v <= max ? v : null;
125
+ return { operation: value.operation, upstreamHttpStatus: bounded(value.upstreamHttpStatus, 100, 599), grpcStatus: bounded(value.grpcStatus, 0, 16), upstreamMessage: sanitizeUpstreamMessage(value.upstreamMessage) };
126
+ }
@@ -0,0 +1,137 @@
1
+ import { parseRemoteImageUrl } from './image-url.mjs';
2
+ import { protocolError } from './tool-protocol.mjs';
3
+
4
+ export const MAX_IMAGES = 256;
5
+ export const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
6
+ export const MAX_TOTAL_IMAGE_BYTES = 256 * 1024 * 1024;
7
+ export const MAX_IMAGE_URL_BYTES = Math.ceil(MAX_IMAGE_BYTES / 3) * 4 + 1024;
8
+ export const MAX_TOTAL_IMAGE_URL_BYTES = Math.ceil(MAX_TOTAL_IMAGE_BYTES / 3) * 4 + MAX_IMAGES * 1024;
9
+ const MAX_PIXELS = 40_000_000;
10
+ const fail = (code, status = 400) => { throw protocolError(code, status); };
11
+ 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) {
17
+ let value = 0xffffffff;
18
+ for (const byte of bytes) value = crcTable[(value ^ byte) & 255] ^ (value >>> 8);
19
+ return (value ^ 0xffffffff) >>> 0;
20
+ }
21
+ // Structural checks only: the gateway never decompresses or renders caller images.
22
+ function dimensions(bytes, mimeType) {
23
+ if (mimeType === 'image/png') {
24
+ if (bytes.length < 57 || !bytes.subarray(0, 8).equals(pngMagic) || bytes.readUInt32BE(8) !== 13 || bytes.toString('latin1', 12, 16) !== 'IHDR') fail('INVALID_IMAGE_BYTES');
25
+ let offset = 8, ended = false, chunks = 0, hasData = false;
26
+ while (offset + 12 <= bytes.length) {
27
+ if (++chunks > 2048) fail('INVALID_IMAGE_BYTES');
28
+ const length = bytes.readUInt32BE(offset), type = bytes.toString('latin1', offset + 4, offset + 8);
29
+ if (!/^[A-Za-z]{4}$/.test(type) || length > bytes.length - offset - 12) fail('INVALID_IMAGE_BYTES');
30
+ if (['acTL', 'fcTL', 'fdAT'].includes(type)) fail('UNSUPPORTED_ANIMATED_IMAGE');
31
+ if ((type === 'IHDR' && offset !== 8) || bytes.readUInt32BE(offset + 8 + length) !== crc32(bytes.subarray(offset + 4, offset + 8 + length))) fail('INVALID_IMAGE_BYTES');
32
+ if (type === 'IDAT' && length) hasData = true;
33
+ offset += length + 12;
34
+ if (type === 'IEND') { if (length || offset !== bytes.length || !hasData) fail('INVALID_IMAGE_BYTES'); ended = true; break; }
35
+ }
36
+ if (!ended) fail('INVALID_IMAGE_BYTES');
37
+ return [bytes.readUInt32BE(16), bytes.readUInt32BE(20)];
38
+ }
39
+ if (mimeType === 'image/jpeg') {
40
+ if (bytes.length < 12 || bytes[0] !== 255 || bytes[1] !== 216 || bytes.at(-2) !== 255 || bytes.at(-1) !== 217) fail('INVALID_IMAGE_BYTES');
41
+ let offset = 2, result;
42
+ while (offset + 4 <= bytes.length) {
43
+ if (bytes[offset++] !== 255) fail('INVALID_IMAGE_BYTES');
44
+ while (offset < bytes.length && bytes[offset] === 255) offset++;
45
+ const marker = bytes[offset++];
46
+ if (marker === 217) break;
47
+ if (marker === 1 || (marker >= 208 && marker <= 215)) continue;
48
+ if (offset + 2 > bytes.length) fail('INVALID_IMAGE_BYTES');
49
+ const length = bytes.readUInt16BE(offset);
50
+ if (length < 2 || length > bytes.length - offset) fail('INVALID_IMAGE_BYTES');
51
+ if (marker === 218) {
52
+ if (!result || length < 6 || offset + length >= bytes.length - 2) fail('INVALID_IMAGE_BYTES');
53
+ return result;
54
+ }
55
+ if ([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker)) {
56
+ if (result || length < 8 || !bytes[offset + 7] || length !== 8 + 3 * bytes[offset + 7]) fail('INVALID_IMAGE_BYTES');
57
+ result = [bytes.readUInt16BE(offset + 5), bytes.readUInt16BE(offset + 3)];
58
+ }
59
+ offset += length;
60
+ }
61
+ fail('INVALID_IMAGE_BYTES');
62
+ }
63
+ if (mimeType === 'image/webp') {
64
+ if (bytes.length < 26 || bytes.toString('latin1', 0, 4) !== 'RIFF' || bytes.toString('latin1', 8, 12) !== 'WEBP' || bytes.readUInt32LE(4) + 8 !== bytes.length) fail('INVALID_IMAGE_BYTES');
65
+ let offset = 12, chunks = 0, canvas, pixels;
66
+ while (offset + 8 <= bytes.length) {
67
+ if (++chunks > 2048) fail('INVALID_IMAGE_BYTES');
68
+ const kind = bytes.toString('latin1', offset, offset + 4), size = bytes.readUInt32LE(offset + 4), start = offset + 8;
69
+ if (size > bytes.length - start || start + size + (size & 1) > bytes.length) fail('INVALID_IMAGE_BYTES');
70
+ if (kind === 'ANIM' || kind === 'ANMF') fail('UNSUPPORTED_ANIMATED_IMAGE');
71
+ if (kind === 'VP8X') {
72
+ if (offset !== 12 || size !== 10) fail('INVALID_IMAGE_BYTES');
73
+ if (bytes[start] & 2) fail('UNSUPPORTED_ANIMATED_IMAGE');
74
+ canvas = [bytes.readUIntLE(start + 4, 3) + 1, bytes.readUIntLE(start + 7, 3) + 1];
75
+ } else if (kind === 'VP8 ' || kind === 'VP8L') {
76
+ if (pixels || (!canvas && offset !== 12)) fail('INVALID_IMAGE_BYTES');
77
+ if (kind === 'VP8 ' && size >= 10 && !(bytes[start] & 1) && bytes[start + 3] === 157 && bytes[start + 4] === 1 && bytes[start + 5] === 42) pixels = [bytes.readUInt16LE(start + 6) & 16383, bytes.readUInt16LE(start + 8) & 16383];
78
+ else if (kind === 'VP8L' && size >= 5 && bytes[start] === 47) pixels = [1 + bytes[start + 1] + ((bytes[start + 2] & 63) << 8), 1 + (bytes[start + 2] >> 6) + (bytes[start + 3] << 2) + ((bytes[start + 4] & 15) << 10)];
79
+ else fail('INVALID_IMAGE_BYTES');
80
+ }
81
+ offset = start + size + (size & 1);
82
+ }
83
+ if (offset !== bytes.length || !pixels || (canvas && (canvas[0] !== pixels[0] || canvas[1] !== pixels[1]))) fail('INVALID_IMAGE_BYTES');
84
+ return pixels;
85
+ }
86
+ fail('UNSUPPORTED_IMAGE_FORMAT');
87
+ }
88
+ /** Inline decoder only; remote downloads separately reuse decodeImageBytes. */
89
+ export function decodeImageDataUrl(url) {
90
+ if (typeof url !== 'string') fail('INVALID_IMAGE_URL');
91
+ if (!url.startsWith('data:')) fail('UNSUPPORTED_IMAGE_URL');
92
+ if (Buffer.byteLength(url) > MAX_IMAGE_URL_BYTES) fail('IMAGE_TOO_LARGE', 413);
93
+ 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]}` };
98
+ }
99
+ export function decodeImageBytes(data, mimeType) {
100
+ if (!Buffer.isBuffer(data) || !data.length) fail('INVALID_IMAGE_BYTES');
101
+ if (data.length > MAX_IMAGE_BYTES) fail('IMAGE_TOO_LARGE', 413);
102
+ const [width, height] = dimensions(data, mimeType);
103
+ if (!width || !height || width > 32768 || height > 32768 || width * height > MAX_PIXELS) fail('IMAGE_DIMENSIONS_TOO_LARGE', 413);
104
+ return { mimeType, data, width, height };
105
+ }
106
+ export function normalizeImageUrl(url, detail, decodedCache) {
107
+ if (detail !== undefined && detail !== 'auto') fail('UNSUPPORTED_IMAGE_DETAIL');
108
+ if (typeof url === 'string' && /^https?:/i.test(url)) return parseRemoteImageUrl(url).href;
109
+ const cached = decodedCache?.get(url);
110
+ if (cached) return cached.url;
111
+ const decoded = decodeImageDataUrl(url);
112
+ if (decodedCache) {
113
+ decodedCache.set(url, decoded);
114
+ decodedCache.set(decoded.url, decoded);
115
+ }
116
+ return decoded.url;
117
+ }
118
+ export function collectImageInputs(messages, resolvedImages, decodedCache) {
119
+ let total = 0;
120
+ const images = [], transcript = messages.map(message => {
121
+ if (!Array.isArray(message.content)) return message;
122
+ const content = message.content.map(part => {
123
+ if (part.type === 'text') return part.text;
124
+ if (message.role !== 'user' || part.type !== 'image_url') fail('UNSUPPORTED_IMAGE_ROLE');
125
+ if (images.length >= MAX_IMAGES) fail('IMAGE_COUNT_EXCEEDED', 413);
126
+ 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));
128
+ const { data, mimeType, width, height } = decoded;
129
+ if ((total += (data?.length ?? 0)) > MAX_TOTAL_IMAGE_BYTES) fail('IMAGES_TOO_LARGE', 413);
130
+ images.push(data ? { data, mimeType, width, height } : decoded);
131
+ const extension = mimeType === 'image/jpeg' ? 'jpg' : mimeType?.slice(6) ?? 'image';
132
+ return `\n[Attached user image ${images.length}: image-${images.length}.${extension}]\n`;
133
+ }).join('');
134
+ return { ...message, content };
135
+ });
136
+ return { messages: transcript, images };
137
+ }
@@ -0,0 +1,21 @@
1
+ import { BlockList, isIP } from 'node:net';
2
+ import { protocolError } from './tool-protocol.mjs';
3
+
4
+ export const MAX_REMOTE_IMAGE_URL_BYTES = 8192;
5
+ const blocked = new BlockList();
6
+ for (const [address, prefix] of [['0.0.0.0',8],['10.0.0.0',8],['100.64.0.0',10],['127.0.0.0',8],['169.254.0.0',16],['172.16.0.0',12],['192.0.0.0',24],['192.0.2.0',24],['192.88.99.0',24],['192.168.0.0',16],['198.18.0.0',15],['198.51.100.0',24],['203.0.113.0',24],['224.0.0.0',3]]) blocked.addSubnet(address, prefix, 'ipv4');
7
+ const globalV6 = new BlockList(); globalV6.addSubnet('2000::', 3, 'ipv6');
8
+ for (const [address, prefix] of [['2001::',23],['2001:db8::',32],['2002::',16],['3fff::',20]]) blocked.addSubnet(address, prefix, 'ipv6');
9
+ export function isPublicImageAddress(address) {
10
+ const family = isIP(address);
11
+ return family === 4 ? !blocked.check(address, 'ipv4') : family === 6 && globalV6.check(address, 'ipv6') && !blocked.check(address, 'ipv6');
12
+ }
13
+ export function parseRemoteImageUrl(value) {
14
+ const fail = () => { throw protocolError('UNSAFE_IMAGE_URL', 400); };
15
+ if (typeof value !== 'string' || !value.length || Buffer.byteLength(value) > MAX_REMOTE_IMAGE_URL_BYTES || value.includes('#') || /[\s\\\x00-\x1f\x7f]/.test(value)) fail();
16
+ let url; try { url = new URL(value); } catch { fail(); }
17
+ if (!['http:', 'https:'].includes(url.protocol) || !/^https?:\/\//i.test(value) || url.username || url.password || url.hash || url.port || !url.hostname) fail();
18
+ const host = url.hostname.replace(/^\[|\]$/g, '');
19
+ if ((isIP(host) && !isPublicImageAddress(host)) || host.endsWith('.') || (!host.includes('.') && !isIP(host)) || /(?:^|\.)(?:localhost|local|internal|home|lan|invalid|test|onion)$/.test(host)) fail();
20
+ return url;
21
+ }