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,196 @@
1
+ import { canonicalWebUrlKey, isSafeWebUrl } from './native-search-metadata.mjs';
2
+
3
+ export const CITATION_LIMITS = Object.freeze({
4
+ MAX_ANNOTATIONS: 64,
5
+ MAX_TITLE_CHARS: 512,
6
+ });
7
+
8
+ function sliceCodeUnitsSafe(text, maxChars = CITATION_LIMITS.MAX_TITLE_CHARS) {
9
+ if (text.length <= maxChars) return text;
10
+ let cut = text.slice(0, maxChars);
11
+ const lastCode = cut.charCodeAt(cut.length - 1);
12
+ if (lastCode >= 0xd800 && lastCode <= 0xdbff) cut = cut.slice(0, -1);
13
+ return cut;
14
+ }
15
+
16
+ function cleanPlainTitle(value, { stripHtml = false } = {}) {
17
+ if (typeof value !== 'string' || Buffer.from(value, 'utf8').toString('utf8') !== value) return '';
18
+ let text = stripHtml ? value.replace(/<[^>]*>/g, '') : value;
19
+ text = text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ').replace(/\s+/g, ' ').trim();
20
+ return sliceCodeUnitsSafe(text, CITATION_LIMITS.MAX_TITLE_CHARS);
21
+ }
22
+
23
+ function hostnameFallback(url) {
24
+ try {
25
+ return sliceCodeUnitsSafe(new URL(url).hostname, CITATION_LIMITS.MAX_TITLE_CHARS) || 'source';
26
+ } catch {
27
+ return 'source';
28
+ }
29
+ }
30
+
31
+ function filterReportMetadata(report) {
32
+ const minFrame = Number.isInteger(report?.lastTextFrameIndex) ? report.lastTextFrameIndex : 0;
33
+ const frameOk = (item) => (minFrame === 0
34
+ ? (item?.frameIndex === undefined || (Number.isInteger(item.frameIndex) && item.frameIndex >= 0))
35
+ : (Number.isInteger(item?.frameIndex) && item.frameIndex >= minFrame));
36
+
37
+ const rawSources = Array.isArray(report?.webSources) ? report.webSources : [];
38
+ const excludedUrls = new Set();
39
+ const excludedBaseUrls = new Set();
40
+ const addExcludedUrl = (url) => {
41
+ if (typeof url !== 'string' || !url) return;
42
+ excludedUrls.add(canonicalWebUrlKey(url));
43
+ try {
44
+ const parsed = new URL(url.trim());
45
+ if (!parsed.hash) excludedBaseUrls.add(canonicalWebUrlKey(url, { stripHash: true }));
46
+ } catch {}
47
+ };
48
+ for (const src of rawSources) {
49
+ if (typeof src?.url === 'string' && src.forceAccount === true) {
50
+ addExcludedUrl(src.url);
51
+ }
52
+ }
53
+ for (const url of Array.isArray(report?.excludedUrls) ? report.excludedUrls : []) {
54
+ addExcludedUrl(url);
55
+ }
56
+ const isExcludedUrl = (url) => (
57
+ excludedUrls.has(canonicalWebUrlKey(url))
58
+ || excludedBaseUrls.has(canonicalWebUrlKey(url, { stripHash: true }))
59
+ );
60
+
61
+ const webSources = [];
62
+ for (const src of rawSources) {
63
+ if (!frameOk(src) || typeof src?.url !== 'string') continue;
64
+ if (src.forceAccount === true || isExcludedUrl(src.url)) continue;
65
+ if (isSafeWebUrl(src.url)) webSources.push(src);
66
+ }
67
+
68
+ const citations = [];
69
+ for (const cit of Array.isArray(report?.citations) ? report.citations : []) {
70
+ if (!frameOk(cit) || !isSafeWebUrl(cit?.link) || isExcludedUrl(cit.link)) continue;
71
+ citations.push(cit);
72
+ }
73
+
74
+ const sourceTitles = new Map();
75
+ for (const src of webSources) {
76
+ const key = canonicalWebUrlKey(src.url);
77
+ if (sourceTitles.has(key)) continue;
78
+ const title = cleanPlainTitle(src.sourceTitle)
79
+ || cleanPlainTitle(src.title)
80
+ || cleanPlainTitle(src.attributionTitle);
81
+ if (title) sourceTitles.set(key, title);
82
+ }
83
+
84
+ return { citations, webSources, sourceTitles };
85
+ }
86
+
87
+ function resolveTitle(url, { sourceTitles, directTitle, untrustedHtmlTitle } = {}) {
88
+ return cleanPlainTitle(directTitle)
89
+ || sourceTitles?.get(canonicalWebUrlKey(url))
90
+ || cleanPlainTitle(untrustedHtmlTitle, { stripHtml: true })
91
+ || hostnameFallback(url);
92
+ }
93
+
94
+ function resolveSpan(answerText, answerBuf, citation, url) {
95
+ const literalIndex = answerText.indexOf(url);
96
+ const fallback = literalIndex >= 0
97
+ ? [literalIndex, literalIndex + url.length]
98
+ : [answerText.length, answerText.length];
99
+
100
+ const start = citation?.startIndex;
101
+ const end = citation?.endIndex;
102
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
103
+ return fallback;
104
+ }
105
+
106
+ const byteLen = answerBuf.length;
107
+ if (byteLen === answerText.length) {
108
+ return end <= answerText.length ? [start, end] : fallback;
109
+ }
110
+
111
+ if (end > byteLen) return fallback;
112
+ const isUtf8Boundary = (offset) => offset === 0 || offset === byteLen || (answerBuf[offset] & 0xc0) !== 0x80;
113
+ if (!isUtf8Boundary(start) || !isUtf8Boundary(end)) return fallback;
114
+
115
+ const startUtf16 = answerBuf.subarray(0, start).toString('utf8').length;
116
+ const endUtf16 = answerBuf.subarray(0, end).toString('utf8').length;
117
+ if (endUtf16 < startUtf16 || endUtf16 > answerText.length) return fallback;
118
+ return [startUtf16, endUtf16];
119
+ }
120
+
121
+ /** Map safe, final-frame native_search citations and webSources to bounded OpenAI url_citation objects. */
122
+ export function mapNativeSearchAnnotations(answerText, report) {
123
+ const text = typeof answerText === 'string' ? answerText : '';
124
+ const answerBuf = Buffer.from(text, 'utf8');
125
+ const { citations, webSources, sourceTitles } = filterReportMetadata(report);
126
+
127
+ const out = [];
128
+ const seen = new Set();
129
+ const citedUrls = new Set();
130
+
131
+ const pushAnnotation = (url, title, [start_index, end_index]) => {
132
+ if (out.length >= CITATION_LIMITS.MAX_ANNOTATIONS) return;
133
+ const canonicalUrl = canonicalWebUrlKey(url);
134
+ const key = `${canonicalUrl}\0${start_index}\0${end_index}`;
135
+ if (seen.has(key)) return;
136
+ seen.add(key);
137
+ citedUrls.add(canonicalUrl);
138
+ out.push({ type: 'url_citation', url, title, start_index, end_index });
139
+ };
140
+
141
+ for (const citation of citations) {
142
+ if (out.length >= CITATION_LIMITS.MAX_ANNOTATIONS) break;
143
+ const url = citation.link;
144
+ const title = resolveTitle(url, {
145
+ sourceTitles,
146
+ directTitle: citation.title,
147
+ untrustedHtmlTitle: citation.untrustedHtmlTitle,
148
+ });
149
+ pushAnnotation(url, title, resolveSpan(text, answerBuf, citation, url));
150
+ }
151
+
152
+ for (const src of webSources) {
153
+ if (out.length >= CITATION_LIMITS.MAX_ANNOTATIONS) break;
154
+ if (citedUrls.has(canonicalWebUrlKey(src.url))) continue;
155
+ const title = resolveTitle(src.url, {
156
+ sourceTitles,
157
+ directTitle: src.sourceTitle || src.title || src.attributionTitle,
158
+ });
159
+ pushAnnotation(src.url, title, resolveSpan(text, answerBuf, null, src.url));
160
+ }
161
+
162
+ return out;
163
+ }
164
+
165
+ /** Extract sanitized public web sources list (<= 64 unique URLs) from final-frame metadata. */
166
+ export function extractNativeSearchSources(report) {
167
+ const { citations, webSources, sourceTitles } = filterReportMetadata(report);
168
+ const sources = [];
169
+ const seenUrls = new Set();
170
+
171
+ const pushSource = (url, title) => {
172
+ const canonicalUrl = canonicalWebUrlKey(url);
173
+ if (sources.length >= CITATION_LIMITS.MAX_ANNOTATIONS || seenUrls.has(canonicalUrl)) return;
174
+ seenUrls.add(canonicalUrl);
175
+ sources.push({ url, title });
176
+ };
177
+
178
+ for (const citation of citations) {
179
+ if (sources.length >= CITATION_LIMITS.MAX_ANNOTATIONS) break;
180
+ pushSource(citation.link, resolveTitle(citation.link, {
181
+ sourceTitles,
182
+ directTitle: citation.title,
183
+ untrustedHtmlTitle: citation.untrustedHtmlTitle,
184
+ }));
185
+ }
186
+
187
+ for (const src of webSources) {
188
+ if (sources.length >= CITATION_LIMITS.MAX_ANNOTATIONS) break;
189
+ pushSource(src.url, resolveTitle(src.url, {
190
+ sourceTitles,
191
+ directTitle: src.sourceTitle || src.title || src.attributionTitle,
192
+ }));
193
+ }
194
+
195
+ return sources;
196
+ }
@@ -0,0 +1,282 @@
1
+ import { TextDecoder } from "node:util";
2
+ import { parse } from "../../native-wire/protobuf.mjs";
3
+ import { NativeDirectProvider } from "../native-provider.mjs";
4
+ import { decodeNativeSearchMetadata } from "./native-search-metadata.mjs";
5
+
6
+ const MAX_FRAMES = 4096;
7
+ const MAX_WIRE_BYTES = 8 * 1024 * 1024;
8
+ const MAX_FRAME_BYTES = 1024 * 1024;
9
+ const MAX_METADATA_FRAMES = 128;
10
+ const MAX_METADATA_ITEMS = 256;
11
+ const strictUtf8 = new TextDecoder("utf-8", { fatal: true });
12
+ function validUtf8Query(value) {
13
+ try {
14
+ return strictUtf8.decode(Buffer.from(value)) === value;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+ const fail = (code, extra = {}) => ({
20
+ ok: false,
21
+ errorCode: code,
22
+ stopRound: [
23
+ "NATIVE_RATE_LIMITED",
24
+ "NATIVE_AUTH_REJECTED",
25
+ "NATIVE_PERMISSION_REJECTED",
26
+ "NATIVE_PERMISSION_OR_AUTH",
27
+ "NATIVE_QUOTA_EXHAUSTED",
28
+ "NATIVE_AUTH_FAILED",
29
+ "NATIVE_PRECONDITION_REQUIRED",
30
+ "ACCOUNT_LOGIN_REQUIRED",
31
+ "OAUTH_REFRESH_FAILED",
32
+ "NATIVE_TURN_ABORTED",
33
+ "NATIVE_STREAM_RESET",
34
+ "NATIVE_UPSTREAM_UNAVAILABLE",
35
+ ].includes(code),
36
+ citations: [],
37
+ webSources: [],
38
+ citationCount: 0,
39
+ webSourceCount: 0,
40
+ searchExecuted: null,
41
+ ...extra,
42
+ });
43
+ function one(fields, n, wire = 2) {
44
+ const found = fields.filter((field) => field.number === n);
45
+ if (found.length > 1 || found.some((field) => field.wire !== wire))
46
+ throw Object.assign(new Error(), { code: "INVALID_NATIVE_RESPONSE" });
47
+ return found[0];
48
+ }
49
+
50
+ /** Bounded diagnostic over the same validation path as product native turns.
51
+ * Requires explicit model completion and stable response identity for whole-text updates.
52
+ * Metadata is withheld unless NativeDirectProvider validates the whole turn.
53
+ */
54
+ export async function runNativeSearchDiagnostic({
55
+ getAccessToken,
56
+ openTurn,
57
+ query,
58
+ signal,
59
+ timeoutMs = 180000,
60
+ allowNativeTools = false,
61
+ } = {}) {
62
+ if (
63
+ typeof getAccessToken !== "function" ||
64
+ typeof openTurn !== "function" ||
65
+ typeof query !== "string" ||
66
+ !query.trim() ||
67
+ !validUtf8Query(query) ||
68
+ Buffer.byteLength(query, "utf8") > 16 * 1024 ||
69
+ !Number.isInteger(timeoutMs) ||
70
+ timeoutMs < 1 ||
71
+ timeoutMs > 180000 ||
72
+ typeof allowNativeTools !== "boolean"
73
+ )
74
+ return fail("INVALID_DIAGNOSTIC_INPUT");
75
+ if (signal?.aborted) return fail("NATIVE_TURN_ABORTED");
76
+
77
+ const metadataFrames = [];
78
+ const googleEvents = [];
79
+ let toolStatusCount = 0,
80
+ otherToolStatusCount = 0;
81
+ let frameCount = 0;
82
+ let lastTextFrameIndex = 0;
83
+ let totalBytes = 0;
84
+ let citationCount = 0;
85
+ let sourceCount = 0;
86
+ let wrapperFailure = null;
87
+ const authManager = { getValidAccessToken: () => getAccessToken() };
88
+ const diagnosticTransport = (token, options) => {
89
+ const turn = openTurn(token, {
90
+ ...options,
91
+ messages: [{ role: "user", content: query }],
92
+ allowNativeTools,
93
+ });
94
+ const events = (async function* () {
95
+ for await (const event of turn.events) {
96
+ if (event?.type === "frame") {
97
+ frameCount++;
98
+ const bytes = event.bytes;
99
+ if (
100
+ !Buffer.isBuffer(bytes) ||
101
+ bytes.length > MAX_FRAME_BYTES ||
102
+ frameCount > MAX_FRAMES ||
103
+ (totalBytes += bytes.length) > MAX_WIRE_BYTES
104
+ ) {
105
+ wrapperFailure = "NATIVE_RESPONSE_LIMIT";
106
+ throw Object.assign(new Error(), { code: wrapperFailure });
107
+ }
108
+ try {
109
+ const outer = parse(bytes);
110
+ const wrapper = one(outer, 1003);
111
+ if (wrapper) {
112
+ const client = one(parse(wrapper.payload), 1);
113
+ if (client) {
114
+ const fields = parse(client.payload);
115
+ one(fields, 6);
116
+ for (const status of fields.filter(
117
+ (f) => f.number === 6 || f.number === 8,
118
+ )) {
119
+ if (status.wire !== 2 || ++toolStatusCount > 256)
120
+ throw Object.assign(new Error(), {
121
+ code: "NATIVE_TOOL_STATUS_LIMIT",
122
+ });
123
+ const processing = one(parse(status.payload), 2);
124
+ if (!processing) continue;
125
+ const toolFields = parse(processing.payload),
126
+ idField = one(toolFields, 1),
127
+ stateField = one(toolFields, 3, 0);
128
+ if (idField?.payload.length > 128)
129
+ throw Object.assign(new Error(), {
130
+ code: "INVALID_NATIVE_RESPONSE",
131
+ });
132
+ const toolId = idField
133
+ ? strictUtf8.decode(idField.payload)
134
+ : null;
135
+ let stateEnum = null;
136
+ if (stateField) {
137
+ let value = 0n,
138
+ shift = 0n;
139
+ for (const byte of stateField.payload) {
140
+ value |= BigInt(byte & 127) << shift;
141
+ shift += 7n;
142
+ }
143
+ if (value > 2147483647n)
144
+ throw Object.assign(new Error(), {
145
+ code: "INVALID_NATIVE_RESPONSE",
146
+ });
147
+ stateEnum = Number(value);
148
+ }
149
+ if (toolId === "google")
150
+ googleEvents.push({
151
+ frameIndex: frameCount,
152
+ channel:
153
+ status.number === 8
154
+ ? "finalToolInvocations"
155
+ : "statusUpdate",
156
+ stateEnum,
157
+ });
158
+ else if (toolId !== null) otherToolStatusCount++;
159
+ }
160
+ const model = one(fields, 1);
161
+ if (model) {
162
+ const modelFields = parse(model.payload);
163
+ const display = one(modelFields, 2);
164
+ if (display && display.wire === 2) {
165
+ const displayText = one(parse(display.payload), 1);
166
+ if (
167
+ displayText &&
168
+ displayText.wire === 2 &&
169
+ displayText.payload.length > 0
170
+ ) {
171
+ lastTextFrameIndex = frameCount;
172
+ }
173
+ }
174
+ const metadata = decodeNativeSearchMetadata(model.payload);
175
+ const excludedUrls = Array.isArray(metadata.excludedUrls) ? metadata.excludedUrls : [];
176
+ if (metadata.citations.length || metadata.webSources.length || excludedUrls.length) {
177
+ if (metadataFrames.length >= MAX_METADATA_FRAMES)
178
+ throw Object.assign(new Error(), {
179
+ code: "NATIVE_METADATA_LIMIT",
180
+ });
181
+ citationCount += metadata.citations.length;
182
+ sourceCount += metadata.webSources.length + excludedUrls.length;
183
+ if (
184
+ citationCount > MAX_METADATA_ITEMS ||
185
+ sourceCount > MAX_METADATA_ITEMS
186
+ )
187
+ throw Object.assign(new Error(), {
188
+ code: "NATIVE_METADATA_LIMIT",
189
+ });
190
+ metadataFrames.push({
191
+ frameIndex: frameCount,
192
+ citations: metadata.citations,
193
+ webSources: metadata.webSources,
194
+ excludedUrls,
195
+ });
196
+ }
197
+ }
198
+ }
199
+ }
200
+ } catch (error) {
201
+ wrapperFailure =
202
+ error?.code && /^[A-Z0-9_]{1,80}$/.test(error.code)
203
+ ? error.code
204
+ : "INVALID_NATIVE_RESPONSE";
205
+ throw Object.assign(new Error(), { code: wrapperFailure });
206
+ }
207
+ }
208
+ yield event;
209
+ }
210
+ })();
211
+ return { ...turn, events };
212
+ };
213
+
214
+ const provider = new NativeDirectProvider(authManager, {
215
+ openTurn: diagnosticTransport,
216
+ timeoutMs,
217
+ allowTextSnapshotReplacement: true,
218
+ });
219
+ try {
220
+ const result = await provider.runTurn(
221
+ "diagnostic",
222
+ {
223
+ model: "gemini-neon",
224
+ messages: [{ role: "user", content: query }],
225
+ thinking_level: 2,
226
+ },
227
+ () => {},
228
+ { signal },
229
+ );
230
+ if (result.resolvedModeCategory !== 3 || result.thinkingLevel !== 2)
231
+ return fail("NATIVE_THINKING_MISMATCH");
232
+ return {
233
+ ok: true,
234
+ answer: result.content,
235
+ query,
236
+ requestedModel: "gemini-neon",
237
+ revisionCount: result.revisionCount,
238
+ resolvedModeCategory: result.resolvedModeCategory,
239
+ requestedThinkingLevel: 2,
240
+ thinkingLevel: result.thinkingLevel,
241
+ nativeToolsRequested: allowNativeTools,
242
+ searchExecuted: null,
243
+ googleToolReported: googleEvents.some(
244
+ (event) => event.channel === "finalToolInvocations",
245
+ ),
246
+ googleToolStatusCount: googleEvents.length,
247
+ googleFinalInvocationCount: googleEvents.filter(
248
+ (event) => event.channel === "finalToolInvocations",
249
+ ).length,
250
+ googleToolEvents: googleEvents,
251
+ otherToolStatusCount,
252
+ toolEvidenceKind:
253
+ "validated-upstream-tool-report; state-enum-semantics-unmapped",
254
+ lastTextFrameIndex,
255
+ framesWithMetadata: metadataFrames.map(({ frameIndex }) => frameIndex),
256
+ citations: metadataFrames.flatMap(({ frameIndex, citations }) =>
257
+ citations.map((item) => ({ ...item, frameIndex })),
258
+ ),
259
+ webSources: metadataFrames.flatMap(({ frameIndex, webSources }) =>
260
+ webSources.map((item) => ({ ...item, frameIndex })),
261
+ ),
262
+ excludedUrls: metadataFrames.flatMap(({ excludedUrls = [] }) => excludedUrls),
263
+ citationCount: metadataFrames.reduce(
264
+ (n, item) => n + item.citations.length,
265
+ 0,
266
+ ),
267
+ webSourceCount: metadataFrames.reduce(
268
+ (n, item) => n + item.webSources.length,
269
+ 0,
270
+ ),
271
+ quotaObservation: result.quotaObservation,
272
+ };
273
+ } catch (error) {
274
+ const code =
275
+ wrapperFailure ??
276
+ (typeof error?.code === "string" && /^[A-Z0-9_]{1,80}$/.test(error.code)
277
+ ? error.code
278
+ : "NATIVE_TURN_FAILED");
279
+ const evidence = error?.nativeEvidence;
280
+ return fail(code, evidence ? { nativeEvidence: evidence } : {});
281
+ }
282
+ }