opencode-gemini-app 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/DISCLAIMER.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +46 -2
  4. package/extensions/opencode/auth.js +324 -0
  5. package/extensions/opencode/fetch.js +494 -0
  6. package/extensions/opencode/index.js +27 -0
  7. package/extensions/opencode/models.js +84 -0
  8. package/extensions/pi/auth.js +215 -0
  9. package/native-wire/consumer-tool-codec.mjs +239 -0
  10. package/native-wire/oauth-loopback.mjs +175 -0
  11. package/native-wire/protobuf.mjs +133 -0
  12. package/native-wire/robin-current.mjs +172 -0
  13. package/package.json +75 -4
  14. package/src/gateway/automatic-recovery.mjs +70 -0
  15. package/src/gateway/image-download.mjs +110 -0
  16. package/src/gateway/image-upload.mjs +262 -0
  17. package/src/gateway/native-diagnostic.mjs +190 -0
  18. package/src/gateway/native-evidence.mjs +114 -0
  19. package/src/gateway/native-response-limits.mjs +8 -0
  20. package/src/gateway/native-search-citations.mjs +196 -0
  21. package/src/gateway/native-search-diagnostic.mjs +282 -0
  22. package/src/gateway/native-search-metadata.mjs +749 -0
  23. package/src/gateway/native-transport.mjs +433 -0
  24. package/src/gateway/oauth-client-defaults.mjs +12 -0
  25. package/src/gateway/oauth-identity.mjs +67 -0
  26. package/src/gateway/outbound-proxy.mjs +320 -0
  27. package/src/gateway/output-recovery.mjs +48 -0
  28. package/src/gateway/quota-failover.mjs +14 -0
  29. package/src/gateway/quota-transport.mjs +37 -0
  30. package/src/gateway/quota.mjs +181 -0
  31. package/src/gateway/soft-error.mjs +25 -0
  32. package/src/gateway/structured-output.mjs +157 -0
  33. package/src/gateway/subscription.mjs +51 -0
  34. package/src/gateway/terms.mjs +126 -0
  35. package/src/image-input.mjs +137 -0
  36. package/src/image-url.mjs +21 -0
  37. package/src/native-provider.mjs +806 -0
  38. package/src/openai-contract.mjs +576 -0
  39. package/src/openai-usage.mjs +66 -0
  40. package/src/prompt-tool-schema.mjs +391 -0
  41. package/src/responses-tool-namespaces.mjs +84 -0
  42. package/src/tool-protocol.mjs +366 -0
@@ -0,0 +1,133 @@
1
+ // Wire-only editor: no generated schema, reflection, network, or native loading.
2
+ export const MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
3
+ const MAX_FIELDS = 100000;
4
+ const MAX_DEPTH = 32;
5
+ const MAX_FIELD = 0x1fffffff;
6
+
7
+ function bytes(input) {
8
+ if (!Buffer.isBuffer(input)) throw new TypeError('Expected Buffer');
9
+ if (input.length > MAX_MESSAGE_BYTES) throw new RangeError('Message exceeds 16 MiB');
10
+ return input;
11
+ }
12
+
13
+ export function varint(value) {
14
+ if (typeof value !== 'bigint' && !Number.isSafeInteger(value)) throw new RangeError('Invalid integer');
15
+ let n = BigInt(value);
16
+ if (n < 0n || n > 0xffffffffffffffffn) throw new RangeError('Outside uint64');
17
+ const out = [];
18
+ do {
19
+ out.push(Number(n & 127n) | (n > 127n ? 128 : 0));
20
+ n >>= 7n;
21
+ } while (n);
22
+ return Buffer.from(out);
23
+ }
24
+
25
+ function readVarint(input, start) {
26
+ let n = 0n;
27
+ for (let i = 0; i < 10; i++) {
28
+ if (start + i >= input.length) throw new Error('Truncated varint');
29
+ const b = input[start + i];
30
+ if (i === 9 && b > 1) throw new Error('Varint overflows uint64');
31
+ n |= BigInt(b & 127) << BigInt(i * 7);
32
+ if (!(b & 128)) return { value: n, end: start + i + 1 };
33
+ }
34
+ throw new Error('Invalid varint');
35
+ }
36
+
37
+ export function lengthDelimited(number, value) {
38
+ bytes(value);
39
+ if (!Number.isInteger(number) || number < 1 || number > MAX_FIELD) throw new RangeError('Invalid field number');
40
+ const result = Buffer.concat([varint(BigInt(number) * 8n + 2n), varint(value.length), value]);
41
+ return bytes(result);
42
+ }
43
+
44
+ export function varintField(number, value) {
45
+ if (!Number.isInteger(number) || number < 1 || number > MAX_FIELD) throw new RangeError('Invalid field number');
46
+ return Buffer.concat([varint(BigInt(number) * 8n + 0n), varint(BigInt(value))]);
47
+ }
48
+
49
+ // Unknown fields retain their original key/length/value bytes, even noncanonical
50
+ // (but valid) varints. Legacy groups are opaque and bounded, not dropped.
51
+ export function parse(input) {
52
+ bytes(input);
53
+ let count = 0;
54
+ function sequence(start, group, depth) {
55
+ if (depth > MAX_DEPTH) throw new Error('Group nesting exceeds limit');
56
+ const fields = [];
57
+ let pos = start;
58
+ while (pos < input.length) {
59
+ if (++count > MAX_FIELDS) throw new Error('Too many fields');
60
+ const begin = pos;
61
+ const key = readVarint(input, pos);
62
+ pos = key.end;
63
+ const number = Number(key.value >> 3n), wire = Number(key.value & 7n);
64
+ if (number < 1 || number > MAX_FIELD) throw new Error('Invalid field number');
65
+ if (wire === 4) {
66
+ if (number !== group) throw new Error('Unmatched end group');
67
+ return { fields, end: pos, contentEnd: begin };
68
+ }
69
+ let payloadStart = pos, payloadEnd;
70
+ if (wire === 0) pos = readVarint(input, pos).end;
71
+ else if (wire === 1) pos += 8;
72
+ else if (wire === 5) pos += 4;
73
+ else if (wire === 2) {
74
+ const size = readVarint(input, pos);
75
+ if (size.value > BigInt(MAX_MESSAGE_BYTES)) throw new Error('Oversized length');
76
+ payloadStart = size.end;
77
+ pos = payloadStart + Number(size.value);
78
+ } else if (wire === 3) {
79
+ const nested = sequence(pos, number, depth + 1);
80
+ payloadEnd = nested.contentEnd;
81
+ pos = nested.end;
82
+ } else throw new Error('Unsupported wire type');
83
+ if (pos > input.length) throw new Error('Truncated field');
84
+ payloadEnd ??= pos;
85
+ fields.push({ number, wire, raw: input.subarray(begin, pos),
86
+ payload: input.subarray(payloadStart, payloadEnd) });
87
+ }
88
+ if (group !== null) throw new Error('Unterminated group');
89
+ return { fields, end: pos };
90
+ }
91
+ return sequence(0, null, 0).fields;
92
+ }
93
+
94
+ export function singular(input, number, { required = false } = {}) {
95
+ const found = parse(input).filter(f => f.number === number);
96
+ // Protobuf singular messages may merge duplicates. Reject rather than silently
97
+ // choose a fragment or accidentally alter merge/oneof semantics.
98
+ if (found.length > 1) throw new Error(`Ambiguous duplicate singular field ${number}`);
99
+ if (!found.length) {
100
+ if (required) throw new Error(`Missing required existing field ${number}`);
101
+ return undefined;
102
+ }
103
+ if (found[0].wire !== 2) throw new Error(`Field ${number} must be length-delimited`);
104
+ return found[0].payload;
105
+ }
106
+
107
+ export function replaceFields(input, number, values) {
108
+ if (!Array.isArray(values)) throw new TypeError('Expected replacement array');
109
+ let replacementSize = 0;
110
+ for (const value of values) {
111
+ bytes(value);
112
+ replacementSize += value.length + varint(value.length).length + varint(BigInt(number) * 8n + 2n).length;
113
+ if (replacementSize > MAX_MESSAGE_BYTES) throw new RangeError('Replacements exceed 16 MiB');
114
+ }
115
+ const replacements = values.map(v => lengthDelimited(number, v));
116
+ const fields = parse(input), out = [];
117
+ let inserted = false;
118
+ for (const field of fields) {
119
+ if (field.number === number) {
120
+ if (field.wire !== 2) throw new Error(`Field ${number} has wrong wire type`);
121
+ if (!inserted) out.push(...replacements);
122
+ inserted = true;
123
+ } else out.push(field.raw);
124
+ }
125
+ if (!inserted) out.push(...replacements);
126
+ if (out.reduce((size, part) => size + part.length, 0) > MAX_MESSAGE_BYTES)
127
+ throw new RangeError('Edited message exceeds 16 MiB');
128
+ return bytes(Buffer.concat(out));
129
+ }
130
+
131
+ export function removeFields(input, numbers) {
132
+ return bytes(Buffer.concat(parse(input).filter(f => !numbers.includes(f.number)).map(f => f.raw)));
133
+ }
@@ -0,0 +1,172 @@
1
+ /** Gemini native HTTP/2 protobuf wire codec (ROBINRequestMetadata & ClientGenerate).
2
+ * Pure message framing and field serialization; zero network, credential or IPC I/O.
3
+ */
4
+ import { lengthDelimited as message, varintField, varint, parse, MAX_MESSAGE_BYTES } from './protobuf.mjs';
5
+ import { TextDecoder } from 'node:util';
6
+
7
+ export const NATIVE_VERSION = '1.135.1.1291';
8
+ export const GATEWAY_USER_AGENT = 'gemini-app2api/1.0';
9
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
10
+ function text(value) {
11
+ if (typeof value !== 'string') throw new TypeError('Expected string');
12
+ const bytes = Buffer.from(value);
13
+ if (bytes.length > MAX_MESSAGE_BYTES) throw new RangeError('Text exceeds message budget');
14
+ return bytes;
15
+ }
16
+ const string = (field, value) => message(field, text(value));
17
+ function scalar(fields, number) {
18
+ const found = fields.filter(field => field.number === number);
19
+ if (found.length > 1) throw new Error(`Duplicate scalar ${number}`);
20
+ if (!found.length) return null;
21
+ if (found[0].wire !== 0) throw new Error(`Invalid scalar wire type ${number}`);
22
+ let value = 0n, shift = 0n;
23
+ for (const byte of found[0].payload) {
24
+ value |= BigInt(byte & 127) << shift;
25
+ if (!(byte & 128)) return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : value;
26
+ shift += 7n;
27
+ }
28
+ throw new Error('Truncated scalar');
29
+ }
30
+ function field(fields, number) {
31
+ const found = fields.filter(value => value.number === number);
32
+ if (found.length > 1) throw new Error(`Duplicate message ${number}`);
33
+ if (found[0] && found[0].wire !== 2) throw new Error(`Invalid message wire type ${number}`);
34
+ return found[0]?.payload;
35
+ }
36
+ const stringValue = (fields, number) => {
37
+ const value = field(fields, number);
38
+ return value === undefined ? null : utf8.decode(value);
39
+ };
40
+ /** Native ROBINRequestMetadata subset. No device IDs or hardware attestation. */
41
+ export function buildRequestMetadata({ clientType, languageCode, interfaceLanguageCode, clientVersion, clientInstanceId, triggerType, uiSource, clientFunctionCapabilities = false } = {}) {
42
+ if (!Number.isSafeInteger(clientType) || clientType < 0 || clientType > 255) throw new Error('Explicit client type required');
43
+ if (typeof clientFunctionCapabilities !== 'boolean') throw new TypeError('Invalid client-function capabilities');
44
+ const fields = [];
45
+ if (triggerType !== undefined) {if (!Number.isSafeInteger(triggerType)||triggerType<0)throw new Error('Invalid trigger');fields.push(message(1,varintField(1,triggerType)));}
46
+ if (interfaceLanguageCode !== undefined) fields.push(message(2, string(1, interfaceLanguageCode)));
47
+ if (clientVersion !== undefined) fields.push(message(3, string(1, clientVersion)));
48
+ fields.push(varintField(4, clientType));
49
+ if (languageCode !== undefined) fields.push(string(7, languageCode));
50
+ if (uiSource !== undefined) {if (!Number.isSafeInteger(uiSource)||uiSource<0)throw new Error('Invalid UI source');fields.push(varintField(5,uiSource));}
51
+ // Metadata CapabilityType values, distinct from DesktopInfo capability enum 379.
52
+ if (clientFunctionCapabilities) fields.push(message(6, message(2, Buffer.concat([varint(668), varint(669)]))));
53
+ if (clientInstanceId !== undefined) fields.push(string(23, clientInstanceId));
54
+ return Buffer.concat(fields);
55
+ }
56
+ // Query.attachments (field 3) -> Attachment.blob (field 1), name (field 2).
57
+ // Blob fields: ID (1), type (2 = 1), MIME (3), source (4 = 1).
58
+ // Upload completes beforehand; raw image bytes are never inline-encoded here.
59
+ export const MAX_NATIVE_IMAGE_ATTACHMENTS = 256;
60
+ function imageAttachments(images) {
61
+ if (!Array.isArray(images) || images.length > MAX_NATIVE_IMAGE_ATTACHMENTS) throw new TypeError('Invalid native images');
62
+ return images.map((image, index) => {
63
+ const extension = image?.mimeType === 'image/png' ? 'png' : image?.mimeType === 'image/jpeg' ? 'jpg' : image?.mimeType === 'image/webp' ? 'webp' : null;
64
+ const id = image?.blobId;
65
+ if (!extension || Object.hasOwn(image, 'data') || typeof id !== 'string' || !id.length || Buffer.byteLength(id) > 4096 || /\s|[\x00-\x1f\x7f]/u.test(id) || Buffer.from(id).toString('utf8') !== id) throw new TypeError('Invalid native image');
66
+ const blob = Buffer.concat([string(1, id), varintField(2, 1), string(3, image.mimeType), varintField(4, 1)]);
67
+ return message(3, Buffer.concat([message(1, blob), string(2, `image-${index + 1}.${extension}`)]));
68
+ });
69
+ }
70
+
71
+ /** Construct a fresh inner ClientGenerateRequest payload.
72
+ * Model IDs and mode numbers are passed explicitly by caller policy.
73
+ * Built-in tools, overage credits and smart model selection default off.
74
+ */
75
+ export function buildClientGenerate({ userText, images = [], systemText, modelId, identifiers, clientMetadata, includePolicyFlags = true, temporaryChat = false, smartModelSelection = false } = {}) {
76
+ if (typeof smartModelSelection !== 'boolean') throw new TypeError('Invalid smart model selection');
77
+ const fields = [message(1, Buffer.concat([string(1, userText), ...imageAttachments(images)]))];
78
+ if (modelId !== undefined) fields.push(message(3, string(2, modelId)));
79
+ if (identifiers !== undefined) {
80
+ const ids = [];
81
+ for (const [name, number] of [['conversationId', 1], ['parentRequestId', 2], ['parentResponseId', 3]]) {
82
+ if (identifiers[name] !== undefined) ids.push(string(number, identifiers[name]));
83
+ }
84
+ fields.push(message(4, Buffer.concat(ids)));
85
+ }
86
+ fields.push(varintField(5, 1));
87
+ if (clientMetadata !== undefined) fields.push(message(13, buildRequestMetadata(clientMetadata)));
88
+ fields.push(varintField(15, 1));
89
+ if (systemText !== undefined) fields.push(message(29, string(4, systemText)));
90
+ // Temporary chat keeps the turn out of the account's saved conversation history.
91
+ if (temporaryChat) fields.push(varintField(31, 1));
92
+ if (includePolicyFlags) fields.push(varintField(55, 0), varintField(56, smartModelSelection ? 1 : 0));
93
+ const output = Buffer.concat(fields);
94
+ if (output.length > MAX_MESSAGE_BYTES) throw new RangeError('Message exceeds budget');
95
+ return output;
96
+ }
97
+
98
+ /** Decode inner ClientGenerateResponse. Thought contents are not exported.
99
+ * Model identity fields are recorded as evidence and verified by caller policy.
100
+ */
101
+ export function decodeClientGenerateResponse(bytes) {
102
+ const fields = parse(bytes), ids = field(fields, 2);
103
+ const models = [];
104
+ for (const model of fields.filter(value => value.number === 1)) {
105
+ if (model.wire !== 2) throw new Error('Invalid model response');
106
+ const item = parse(model.payload), display = field(item, 2);
107
+ models.push({ responseId: stringValue(item, 1), text: display === undefined ? null : stringValue(parse(display), 1) });
108
+ }
109
+ const responseIds = ids === undefined ? [] : parse(ids);
110
+ return {
111
+ models, conversationId: stringValue(responseIds, 1), requestId: stringValue(responseIds, 2),
112
+ completed: scalar(fields, 9) === 1,
113
+ fallback: scalar(fields, 11), attribution: stringValue(fields, 30),
114
+ downgradeReason: scalar(fields, 31), resolvedModeCategory: scalar(fields, 41),
115
+ thinkingLevel: scalar(fields, 42), modeVariantId: stringValue(fields, 39),
116
+ routingVariantId: stringValue(fields, 40),
117
+ hasToolOperations: fields.some(value => value.number === 7),
118
+ unknownFieldNumbers: fields.filter(value => ![1, 2, 7, 9, 11, 30, 31, 39, 40, 41, 42].includes(value.number)).map(value => value.number)
119
+ };
120
+ }
121
+
122
+ /** Extension 1014 wrapper field 1 -> streaming ContinuationIdentifiers
123
+ * consumed by InitialRequest field 6. Treat opaque token bytes as private session state.
124
+ */
125
+ export function decodeContinuationResponse(bytes) {
126
+ const wrapper = parse(bytes), raw = field(wrapper, 1);
127
+ if (raw === undefined) return null;
128
+ const ids = parse(raw), conversationId = stringValue(ids, 1), token = field(ids, 2);
129
+ if (!conversationId) return null;
130
+ // Proto fields are optional: a conversation-only continuation is valid.
131
+ return { conversationId, sessionContinuationToken: token === undefined ? null : Buffer.from(token), bytes: Buffer.from(raw) };
132
+ }
133
+
134
+ export function frameGrpcMessage(bytes) {
135
+ if (!Buffer.isBuffer(bytes)) throw new TypeError('Expected Buffer');
136
+ if (bytes.length > MAX_MESSAGE_BYTES) throw new RangeError('Message exceeds budget');
137
+ const header = Buffer.alloc(5); header.writeUInt32BE(bytes.length, 1);
138
+ return Buffer.concat([header, bytes]);
139
+ }
140
+
141
+ /** Portable streaming frame reader. No network, token, App or IPC dependencies. */
142
+ export class GrpcMessageReader {
143
+ constructor({ maxBytes = MAX_MESSAGE_BYTES } = {}) {
144
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_MESSAGE_BYTES) throw new RangeError('Invalid frame budget');
145
+ this.maxBytes = maxBytes; this.pending = Buffer.alloc(0); this.closed = false;
146
+ }
147
+ push(bytes) {
148
+ if (this.closed) throw new Error('Reader already closed');
149
+ if (!Buffer.isBuffer(bytes)) throw new TypeError('Expected Buffer');
150
+ const frames = [];
151
+ // Accept concatenated chunks without allowing an unbounded pending allocation.
152
+ let offset = 0;
153
+ while (offset < bytes.length) {
154
+ const needed = this.pending.length < 5 ? 5 - this.pending.length : 5 + this.pending.readUInt32BE(1) - this.pending.length;
155
+ const take = Math.min(needed, bytes.length - offset);
156
+ this.pending = Buffer.concat([this.pending, bytes.subarray(offset, offset + take)]);
157
+ offset += take;
158
+ if (this.pending.length < 5) continue;
159
+ if (this.pending[0] !== 0) throw new Error('Compressed gRPC messages not supported');
160
+ const length = this.pending.readUInt32BE(1);
161
+ if (length > this.maxBytes) throw new RangeError('gRPC frame exceeds budget');
162
+ if (this.pending.length === length + 5) {
163
+ frames.push(this.pending.subarray(5)); this.pending = Buffer.alloc(0);
164
+ }
165
+ }
166
+ return frames;
167
+ }
168
+ finish() {
169
+ this.closed = true;
170
+ if (this.pending.length) throw new Error('Truncated gRPC stream');
171
+ }
172
+ }
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "opencode-gemini-app",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Zero-dependency native Google Gemini HTTP/2 provider plugin for OpenCode (Gemini Neon, Hydrogen, Flash Lite, Auto) using your Google Gemini subscription via OAuth.",
5
+ "type": "module",
6
+ "main": "./extensions/opencode/index.js",
7
+ "exports": {
8
+ ".": "./extensions/opencode/index.js"
9
+ },
10
+ "license": "MIT",
11
+ "author": "shawtim",
12
+ "homepage": "https://github.com/ShawTim/gemini-app2api/blob/main/extensions/opencode/README.md",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/ShawTim/gemini-app2api.git",
16
+ "directory": "extensions/opencode"
17
+ },
18
+ "bugs": {
19
+ "url": "https://github.com/ShawTim/gemini-app2api/issues"
20
+ },
21
+ "keywords": [
22
+ "opencode",
23
+ "opencode-plugin",
24
+ "gemini",
25
+ "gemini-neon",
26
+ "gemini-hydrogen",
27
+ "oauth",
28
+ "http2"
29
+ ],
30
+ "engines": {
31
+ "node": ">=22.0.0"
32
+ },
33
+ "files": [
34
+ "DISCLAIMER.md",
35
+ "LICENSE",
36
+ "README.md",
37
+ "extensions/opencode/auth.js",
38
+ "extensions/opencode/fetch.js",
39
+ "extensions/opencode/index.js",
40
+ "extensions/opencode/models.js",
41
+ "extensions/pi/auth.js",
42
+ "native-wire/consumer-tool-codec.mjs",
43
+ "native-wire/oauth-loopback.mjs",
44
+ "native-wire/protobuf.mjs",
45
+ "native-wire/robin-current.mjs",
46
+ "src/gateway/automatic-recovery.mjs",
47
+ "src/gateway/image-download.mjs",
48
+ "src/gateway/image-upload.mjs",
49
+ "src/gateway/native-diagnostic.mjs",
50
+ "src/gateway/native-evidence.mjs",
51
+ "src/gateway/native-response-limits.mjs",
52
+ "src/gateway/native-search-citations.mjs",
53
+ "src/gateway/native-search-diagnostic.mjs",
54
+ "src/gateway/native-search-metadata.mjs",
55
+ "src/gateway/native-transport.mjs",
56
+ "src/gateway/oauth-client-defaults.mjs",
57
+ "src/gateway/oauth-identity.mjs",
58
+ "src/gateway/outbound-proxy.mjs",
59
+ "src/gateway/output-recovery.mjs",
60
+ "src/gateway/quota-failover.mjs",
61
+ "src/gateway/quota-transport.mjs",
62
+ "src/gateway/quota.mjs",
63
+ "src/gateway/soft-error.mjs",
64
+ "src/gateway/structured-output.mjs",
65
+ "src/gateway/subscription.mjs",
66
+ "src/gateway/terms.mjs",
67
+ "src/image-input.mjs",
68
+ "src/image-url.mjs",
69
+ "src/native-provider.mjs",
70
+ "src/openai-contract.mjs",
71
+ "src/openai-usage.mjs",
72
+ "src/prompt-tool-schema.mjs",
73
+ "src/responses-tool-namespaces.mjs",
74
+ "src/tool-protocol.mjs"
75
+ ],
76
+ "dependencies": {}
77
+ }
@@ -0,0 +1,70 @@
1
+ // Request-scoped bounded recovery; never repair/execute an invalid tool call.
2
+ import { MODEL_MODES, canonicalModel } from '../openai-contract.mjs';
3
+ import { isVerifiedEmptyResponse } from './output-recovery.mjs';
4
+ import { isExplicitQuotaFailure } from './quota-failover.mjs';
5
+ export const TOOL_ERRORS = new Set(['MALFORMED_TOOL_CALL', 'INVALID_TOOL_JSON', 'TRUNCATED_TOOL_CALL', 'INVALID_TOOL_CALL',
6
+ 'INVALID_TOOL_ARGUMENTS', 'UNDECLARED_TOOL', 'TOOL_ARGUMENT_SCHEMA_MISMATCH', 'TOOL_CHOICE_NOT_SATISFIED',
7
+ 'TOOL_CHOICE_MISMATCH', 'TOOL_CALL_NOT_ALLOWED', 'PARALLEL_TOOL_CALLS_DISABLED']);
8
+ const STRUCTURED_OUTPUT_ERRORS = new Set(['INVALID_STRUCTURED_OUTPUT_JSON', 'STRUCTURED_OUTPUT_SCHEMA_MISMATCH']);
9
+ const TRANSPORT_ERRORS = new Set(['NATIVE_STREAM_RESET', 'NATIVE_CONNECTION_FAILED', 'NATIVE_STREAM_FAILED', 'NATIVE_STREAM_CLOSED_EARLY']);
10
+ export function toolRecoveryInstruction(code) {
11
+ if (TOOL_ERRORS.has(code)) {
12
+ return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered and no caller tool was executed.]\n' +
13
+ 'Answer the latest user request using the complete history. If a tool is needed and permitted, emit a complete tool_call block with exactly the keys "name" and "arguments" as valid JSON. Emit one strict JSON object per tool_call block with properly escaped strings (no raw newlines, invalid escapes, or trailing commas). Use only declared names and actual JSON-object arguments matching the original schema. Respect the selected tool choice and parallel-call restriction. Put both fences on separate lines. Do not invent tool results, duplicate already completed work, or discuss this recovery instruction. If tools are prohibited, answer normally without tool_call blocks.';
14
+ }
15
+ if (STRUCTURED_OUTPUT_ERRORS.has(code)) {
16
+ return '[Gateway automatic recovery: regenerate this turn; the previous response was not delivered because it did not satisfy the required JSON output format.]\n' +
17
+ 'Answer the latest user request with a single valid UTF-8 JSON value matching the requested response_format or JSON Schema, with no surrounding prose, explanations, or markdown code fences (unless emitting an allowed tool_call block). Do not discuss this recovery instruction.';
18
+ }
19
+ return null;
20
+ }
21
+ export function automaticRecoveryKind(error, model, { allowAutoModel = false } = {}) {
22
+ const resolvedModel = canonicalModel(model);
23
+ if (isExplicitQuotaFailure(error)) return 'quota';
24
+ if (isVerifiedEmptyResponse(error, resolvedModel, { allowAutoModel })) return 'empty_response';
25
+ const isAuto = allowAutoModel === true && resolvedModel === 'gemini-auto';
26
+ const expected = MODEL_MODES[resolvedModel];
27
+ if (!isAuto && expected === undefined) return null;
28
+ const modeOk = mode => isAuto
29
+ ? (mode === null || mode === undefined || (Number.isSafeInteger(mode) && mode >= 0 && mode <= 64))
30
+ : mode === expected;
31
+ const e = error?.nativeEvidence;
32
+ if (error?.code === 'OAUTH_REFRESH_FAILED' && error?.status === 502) {
33
+ if (!e) return 'transport';
34
+ if (e.phase === 'auth' && e.upstreamHttpStatus === null && e.grpcStatus === null &&
35
+ e.nativeRefusalPresent !== true && (e.fallback === undefined || e.fallback === 0) &&
36
+ (e.downgradeReason === undefined || e.downgradeReason === 0)) {
37
+ return 'transport';
38
+ }
39
+ return null;
40
+ }
41
+ if (!e || ![502, 503].includes(error?.status) || e.nativeRefusalPresent === true ||
42
+ (!isAuto && ((e.fallback !== undefined && e.fallback !== 0) || (e.downgradeReason !== undefined && e.downgradeReason !== 0)))) return null;
43
+ if (!isAuto && e.observedMode !== null && e.observedMode !== undefined && e.observedMode !== 0 && e.observedMode !== expected) return null;
44
+ if (error.code === 'NATIVE_UPSTREAM_UNAVAILABLE' && error.status === 503 &&
45
+ ['open', 'read', 'decode', 'end'].includes(e.phase) &&
46
+ ((e.upstreamHttpStatus === 503 && (e.grpcStatus === null || e.grpcStatus === 0 || e.grpcStatus === 14)) ||
47
+ ((e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) && e.grpcStatus === 14))) {
48
+ return 'transport';
49
+ }
50
+ if (error.status !== 502) return null;
51
+ if (TRANSPORT_ERRORS.has(error.code) && ['open', 'read', 'decode', 'end'].includes(e.phase) &&
52
+ (e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) && (e.grpcStatus === null || e.grpcStatus === 0)) return 'transport';
53
+ if (error.code === 'NATIVE_IMAGE_UPLOAD_RESET' && e.phase === 'upload' &&
54
+ e.upstreamHttpStatus === null && e.grpcStatus === null) return 'transport';
55
+ const completed = e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 && e.wireEnded === true &&
56
+ e.modelCompleted === true && modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
57
+ const earlyStoppedToolError = e.phase === 'validate' && e.toolErrorEarlyStop === true &&
58
+ (e.upstreamHttpStatus === null || e.upstreamHttpStatus === 200) &&
59
+ (e.grpcStatus === null || e.grpcStatus === 0) &&
60
+ modeOk(e.observedMode) && e.nativeRefusalPresent === false && e.http2ResetCode === undefined;
61
+ if (completed && error.code === 'NATIVE_SOFT_ERROR_RESPONSE' && e.outputFailureReason === 'generic_error_offer' &&
62
+ e.outputFailureSource === 'exact_text_signature' && e.outputToolCalls === 0 && e.nativeStructuredOutputPresent === false) return 'provider_soft_error';
63
+ if ((completed || earlyStoppedToolError) && TOOL_ERRORS.has(error.code)) return 'tool_protocol';
64
+ if (completed && STRUCTURED_OUTPUT_ERRORS.has(error.code)) return 'structured_output';
65
+ // A clean but incomplete turn may be regenerated; never treat it as success.
66
+ if (error.code === 'INCOMPLETE_NATIVE_RESPONSE' && e.phase === 'validate' && e.upstreamHttpStatus === 200 && e.grpcStatus === 0 &&
67
+ e.wireEnded === true && modeOk(e.observedMode) && e.nativeRefusalPresent === false &&
68
+ e.nativeStructuredOutputPresent === false && e.nativeShareableTextBytes === 0 && e.http2ResetCode === undefined) return 'incomplete_response';
69
+ return null;
70
+ }
@@ -0,0 +1,110 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
3
+ import { lookup as dnsLookup } from 'node:dns/promises';
4
+ import { isIP } from 'node:net';
5
+ import { parseRemoteImageUrl, isPublicImageAddress } from '../image-url.mjs';
6
+ import { decodeImageBytes, MAX_IMAGES, MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES } from '../image-input.mjs';
7
+ import { protocolError, ProtocolError } from '../tool-protocol.mjs';
8
+ import { GATEWAY_USER_AGENT } from '../../native-wire/robin-current.mjs';
9
+
10
+ const fail = (code, status = 400) => { throw protocolError(code, status); };
11
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
12
+ const MIME = new Set(['image/png', 'image/jpeg', 'image/webp']);
13
+
14
+ /** No proxy, cookies, caller/Google headers, cache, retries or URL-bearing errors. */
15
+ export async function downloadRemoteImages(images, { signal, timeoutMs = 30000 } = {}, {
16
+ lookup = dnsLookup, request = (url, options, callback) => (url.protocol === 'https:' ? https : http).request(url, options, callback),
17
+ } = {}) {
18
+ if (!Array.isArray(images) || images.length > MAX_IMAGES) fail('IMAGE_COUNT_EXCEEDED', 413);
19
+ if (!images.some(image => image.url)) return images;
20
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 180000) fail('INVALID_IMAGE_DOWNLOAD_TIMEOUT');
21
+ if (signal?.aborted) fail('IMAGE_DOWNLOAD_ABORTED', 499);
22
+ const controller = new AbortController();
23
+ let rejectStop;
24
+ const stopped = new Promise((_, reject) => { rejectStop = reject; });
25
+ // The shared deadline includes DNS, every redirect and every image in this batch.
26
+ const stop = error => { rejectStop(error); controller.abort(); };
27
+ const abort = () => stop(protocolError('IMAGE_DOWNLOAD_ABORTED', 499));
28
+ signal?.addEventListener('abort', abort, { once: true });
29
+ const timer = setTimeout(() => stop(protocolError('IMAGE_DOWNLOAD_TIMEOUT', 504)), timeoutMs);
30
+ const bounded = promise => Promise.race([promise, stopped]);
31
+ let remaining = MAX_TOTAL_IMAGE_BYTES - images.reduce((sum, image) => sum + (image.data?.length ?? 0), 0);
32
+ try {
33
+ if (remaining < 0) fail('IMAGES_TOO_LARGE', 413);
34
+ const result = [];
35
+ for (const image of images) {
36
+ if (!image.url) { result.push(image); continue; }
37
+ let url = parseRemoteImageUrl(image.url);
38
+ for (let redirects = 0;; redirects++) {
39
+ if (controller.signal.aborted) await stopped;
40
+ const host = url.hostname.replace(/^\[|\]$/g, '');
41
+ const addresses = isIP(host) ? [{ address: host, family: isIP(host) }] : await bounded(lookup(host, { all: true, verbatim: true }));
42
+ if (!Array.isArray(addresses) || !addresses.length || addresses.length > 16 || addresses.some(item => !isPublicImageAddress(item.address) || isIP(item.address) !== item.family)) fail('UNSAFE_IMAGE_URL');
43
+ const pinned = addresses[0];
44
+ const response = await bounded(new Promise((resolve, reject) => {
45
+ let req, res, ended = false, settled = false, size = 0;
46
+ const finish = (error, value) => {
47
+ if (settled) return;
48
+ settled = true;
49
+ controller.signal.removeEventListener('abort', cancel);
50
+ if (error) { res?.destroy(); req?.destroy(); reject(error); } else resolve(value);
51
+ };
52
+ const cancel = () => finish(protocolError('IMAGE_DOWNLOAD_ABORTED', 499));
53
+ const limit = Math.min(MAX_IMAGE_BYTES, remaining);
54
+ try {
55
+ if (limit <= 0) fail('IMAGES_TOO_LARGE', 413);
56
+ req = request(url, {
57
+ method: 'GET', agent: false, maxHeaderSize: 16384,
58
+ headers: { accept: 'image/png, image/jpeg, image/webp', 'accept-encoding': 'identity', 'user-agent': GATEWAY_USER_AGENT },
59
+ // Pin after validation; preserve original Host, SNI and certificate verification.
60
+ lookup: (_host, options, callback) => callback(null, ...(options?.all ? [[pinned]] : [pinned.address, pinned.family])),
61
+ }, incoming => {
62
+ res = incoming;
63
+ res.on('error', () => finish(protocolError('IMAGE_DOWNLOAD_FAILED', 502)));
64
+ res.on('aborted', () => finish(protocolError('IMAGE_DOWNLOAD_FAILED', 502)));
65
+ if (REDIRECTS.has(res.statusCode)) {
66
+ const location = res.headers.location;
67
+ if (redirects >= 3 || typeof location !== 'string' || Buffer.byteLength(location) > 8192 || /[\s\\\x00-\x1f\x7f]/.test(location)) { finish(protocolError('INVALID_IMAGE_REDIRECT')); return; }
68
+ let next;
69
+ try { next = parseRemoteImageUrl(new URL(location, url).href); }
70
+ catch { finish(protocolError('UNSAFE_IMAGE_URL')); return; }
71
+ if (url.protocol === 'https:' && next.protocol !== 'https:') { finish(protocolError('UNSAFE_IMAGE_URL')); return; }
72
+ finish(null, { next }); res.destroy(); return;
73
+ }
74
+ const mimeType = String(res.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
75
+ const encoding = res.headers['content-encoding'];
76
+ const length = res.headers['content-length'];
77
+ if (res.statusCode !== 200) { finish(protocolError('IMAGE_DOWNLOAD_HTTP_ERROR', 502)); return; }
78
+ if (!MIME.has(mimeType) || encoding !== undefined && encoding !== 'identity') { finish(protocolError('UNSUPPORTED_IMAGE_FORMAT')); return; }
79
+ if (length !== undefined && (!/^\d+$/.test(length) || Number(length) > limit)) { finish(protocolError('IMAGES_TOO_LARGE', 413)); return; }
80
+ const chunks = [];
81
+ res.on('data', chunk => {
82
+ size += chunk.length;
83
+ if (size > limit) { finish(protocolError('IMAGES_TOO_LARGE', 413)); return; }
84
+ chunks.push(chunk);
85
+ });
86
+ res.on('end', () => { ended = true; });
87
+ res.on('close', () => {
88
+ if (!ended || !res.complete) { finish(protocolError('IMAGE_DOWNLOAD_FAILED', 502)); return; }
89
+ finish(null, { data: Buffer.concat(chunks, size), mimeType });
90
+ });
91
+ });
92
+ req.on('error', () => finish(protocolError('IMAGE_DOWNLOAD_FAILED', 502)));
93
+ controller.signal.addEventListener('abort', cancel, { once: true });
94
+ if (controller.signal.aborted) cancel(); else req.end();
95
+ } catch (error) { finish(error); }
96
+ }));
97
+ if (response.next) { url = response.next; continue; }
98
+ const decoded = decodeImageBytes(response.data, response.mimeType);
99
+ remaining -= decoded.data.length;
100
+ result.push(decoded); break;
101
+ }
102
+ }
103
+ return result;
104
+ } catch (error) {
105
+ if (error instanceof ProtocolError) throw error;
106
+ fail('IMAGE_DOWNLOAD_FAILED', 502);
107
+ } finally {
108
+ clearTimeout(timer); signal?.removeEventListener('abort', abort);
109
+ }
110
+ }