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,494 @@
1
+ import crypto from 'node:crypto';
2
+ import { NativeDirectProvider } from '../../src/native-provider.mjs';
3
+ import { openDirectTurn as defaultOpenDirectTurn } from '../../src/gateway/native-transport.mjs';
4
+ import { createImageBlobCache } from '../../src/gateway/image-upload.mjs';
5
+ import { automaticRecoveryKind as defaultAutomaticRecoveryKind } from '../../src/gateway/automatic-recovery.mjs';
6
+ import { measurePromptImagePayload, estimateUsage } from '../../src/openai-usage.mjs';
7
+ import { toChatAnnotations } from '../../src/openai-contract.mjs';
8
+ import { normalizeOpenCodeModelId } from './models.js';
9
+
10
+ const KEEPALIVE_INTERVAL_MS = 15_000;
11
+ const DEFAULT_TIMEOUT_MS = 300_000;
12
+
13
+ function jsonErrorResponse(error) {
14
+ const status = Number.isInteger(error?.status) && error.status >= 400 && error.status < 600
15
+ ? error.status
16
+ : error?.code === 'NATIVE_PERMISSION_OR_AUTH' ||
17
+ error?.code === 'OAUTH_REFRESH_FAILED' ||
18
+ error?.code === 'OAUTH_LOGGED_OUT' ||
19
+ error?.code === 'OAUTH_ACCOUNT_CHANGED'
20
+ ? 401
21
+ : error?.code === 'NATIVE_QUOTA_EXHAUSTED'
22
+ ? 429
23
+ : 502;
24
+ const code = typeof error?.code === 'string' && error.code ? error.code : 'UPSTREAM_ERROR';
25
+ const type = status === 429
26
+ ? 'rate_limit_error'
27
+ : status === 401 || status === 403
28
+ ? 'authentication_error'
29
+ : status >= 500
30
+ ? 'server_error'
31
+ : 'invalid_request_error';
32
+ const message = error?.upstreamMessage
33
+ ? `${code}: ${error.upstreamMessage}`
34
+ : error?.message || code;
35
+ return new Response(
36
+ JSON.stringify({
37
+ error: {
38
+ message,
39
+ type,
40
+ code,
41
+ param: error?.param ?? null,
42
+ },
43
+ }),
44
+ {
45
+ status,
46
+ headers: { 'content-type': 'application/json' },
47
+ },
48
+ );
49
+ }
50
+
51
+ function measurePromptChars(payload) {
52
+ if (!Array.isArray(payload?.messages)) return 0;
53
+ let total = 0;
54
+ for (const m of payload.messages) {
55
+ if (typeof m?.content === 'string') total += m.content.length;
56
+ else if (Array.isArray(m?.content)) {
57
+ for (const p of m.content) {
58
+ if (typeof p?.text === 'string') total += p.text.length;
59
+ }
60
+ }
61
+ if (Array.isArray(m?.tool_calls)) {
62
+ total += JSON.stringify(m.tool_calls).length;
63
+ }
64
+ }
65
+ if (Array.isArray(payload?.tools) && payload.tools.length) {
66
+ total += JSON.stringify(payload.tools).length;
67
+ }
68
+ return total;
69
+ }
70
+
71
+ async function readRequestJson(input, init) {
72
+ if (typeof init?.body === 'string') return JSON.parse(init.body);
73
+ if (init?.body instanceof Uint8Array) return JSON.parse(Buffer.from(init.body).toString('utf8'));
74
+ if (init?.body instanceof ArrayBuffer) return JSON.parse(Buffer.from(init.body).toString('utf8'));
75
+ if (input instanceof Request) return await input.clone().json();
76
+ throw Object.assign(new Error('Expected JSON request body'), { code: 'INVALID_JSON', status: 400 });
77
+ }
78
+
79
+ function getRequestUrl(input) {
80
+ if (typeof input === 'string') return input;
81
+ if (input instanceof URL) return input.href;
82
+ if (input && typeof input.url === 'string') return input.url;
83
+ return '';
84
+ }
85
+
86
+ function getRequestSignal(input, init) {
87
+ return init?.signal ?? (input instanceof Request ? input.signal : undefined);
88
+ }
89
+
90
+ export function createOpenCodeFetch({
91
+ resolveAccessToken,
92
+ getSubscriptionTier = () => 'unknown',
93
+ openTurn = defaultOpenDirectTurn,
94
+ uploadImages,
95
+ automaticRecoveryKind = defaultAutomaticRecoveryKind,
96
+ fallbackFetch = globalThis.fetch,
97
+ timeoutMs = DEFAULT_TIMEOUT_MS,
98
+ keepaliveMs = KEEPALIVE_INTERVAL_MS,
99
+ } = {}) {
100
+ if (typeof resolveAccessToken !== 'function') {
101
+ throw new TypeError('resolveAccessToken is required');
102
+ }
103
+ const blobCache = createImageBlobCache();
104
+
105
+ async function runWithRetry({ rawBody, requestedModel, signal, onDelta, getOutputCommitState, onModelResolved }) {
106
+ let attempts = 0;
107
+ let recoveryCode;
108
+ let authRefreshed = false;
109
+ let pinnedAccountEpoch;
110
+
111
+ while (true) {
112
+ let currentToken;
113
+ let currentTier;
114
+ let currentEpoch;
115
+ try {
116
+ const resolved = await resolveAccessToken({ signal, forceRefresh: authRefreshed });
117
+ if (typeof resolved === 'string') {
118
+ currentToken = resolved;
119
+ currentTier = getSubscriptionTier();
120
+ } else {
121
+ currentToken = resolved?.accessToken;
122
+ currentTier = resolved?.subscriptionTier ?? getSubscriptionTier();
123
+ currentEpoch = resolved?.accountEpoch;
124
+ }
125
+ if (typeof currentToken !== 'string' || !currentToken) {
126
+ throw Object.assign(new Error('OAuth did not return a valid access token'), {
127
+ code: 'OAUTH_REFRESH_FAILED',
128
+ status: 401,
129
+ });
130
+ }
131
+ // Pin retries strictly to the original request's account epoch so switching accounts
132
+ // between attempt 1 and automatic recovery/auth retry never replays Account A's prompt to Account B.
133
+ if (pinnedAccountEpoch === undefined) {
134
+ pinnedAccountEpoch = currentEpoch;
135
+ } else if (currentEpoch !== undefined && currentEpoch !== pinnedAccountEpoch) {
136
+ throw Object.assign(new Error('Google Gemini account changed before retry; aborting to prevent cross-account replay.'), {
137
+ code: 'OAUTH_ACCOUNT_CHANGED',
138
+ status: 401,
139
+ });
140
+ }
141
+ } catch (err) {
142
+ throw Object.assign(err instanceof Error ? err : new Error(String(err)), {
143
+ code: err?.code || 'OAUTH_REFRESH_FAILED',
144
+ status: 401,
145
+ });
146
+ }
147
+
148
+ // Compute effective model & gemini-auto AFTER resolving the active account's token and tier.
149
+ const effectiveModel = currentTier === 'free' ? 'gemini-auto' : requestedModel;
150
+ const isAuto = effectiveModel === 'gemini-auto';
151
+ const payload = { ...rawBody, model: effectiveModel };
152
+ if (isAuto) {
153
+ delete payload.thinking_level;
154
+ delete payload.reasoning_effort;
155
+ delete payload.reasoning;
156
+ }
157
+ onModelResolved?.(effectiveModel);
158
+
159
+ const provider = new NativeDirectProvider(
160
+ { getValidAccessToken: async () => currentToken },
161
+ {
162
+ openTurn,
163
+ ...(uploadImages ? { uploadImages } : {}),
164
+ blobCache,
165
+ modelAlias: payload.model,
166
+ allowAutoModel: isAuto,
167
+ timeoutMs,
168
+ },
169
+ );
170
+
171
+ try {
172
+ return await provider.runTurn('opencode-session', payload, onDelta, {
173
+ incrementalOutput: Boolean(payload.stream),
174
+ signal,
175
+ recoveryCode,
176
+ getOutputCommitState,
177
+ timeoutMs,
178
+ });
179
+ } catch (err) {
180
+ const commitState = getOutputCommitState();
181
+ const committed = commitState.publishedBytes > 0 || commitState.toolCallCount > 0;
182
+ if (!committed && !signal?.aborted) {
183
+ if ((err?.code === 'NATIVE_PERMISSION_OR_AUTH' || err?.code === 'NATIVE_AUTH_REJECTED') && !authRefreshed) {
184
+ authRefreshed = true;
185
+ continue;
186
+ }
187
+ const kind = automaticRecoveryKind(err, payload.model, { allowAutoModel: isAuto });
188
+ if (kind && kind !== 'quota' && attempts < 1) {
189
+ attempts++;
190
+ recoveryCode = err.code;
191
+ continue;
192
+ }
193
+ }
194
+ throw err;
195
+ }
196
+ }
197
+ }
198
+
199
+ return async function openCodeGeminiFetch(input, init = {}) {
200
+ const rawUrl = getRequestUrl(input);
201
+ let pathname = '';
202
+ try {
203
+ pathname = new URL(rawUrl).pathname;
204
+ } catch {
205
+ return fallbackFetch(input, init);
206
+ }
207
+
208
+ if (!pathname.endsWith('/chat/completions')) {
209
+ return fallbackFetch(input, init);
210
+ }
211
+
212
+ const callerSignal = getRequestSignal(input, init);
213
+ let rawBody;
214
+ try {
215
+ rawBody = await readRequestJson(input, init);
216
+ } catch (err) {
217
+ return jsonErrorResponse(Object.assign(err, { code: 'INVALID_JSON', status: 400 }));
218
+ }
219
+
220
+ const requestedModel = normalizeOpenCodeModelId(rawBody?.model);
221
+ let effectiveModel = requestedModel;
222
+
223
+ const stream = Boolean(rawBody?.stream);
224
+ const includeUsage = Boolean(rawBody?.stream_options?.include_usage);
225
+ const promptChars = measurePromptChars(rawBody || {});
226
+ const { imageCount } = measurePromptImagePayload(rawBody || {});
227
+ const created = Math.floor(Date.now() / 1000);
228
+ const completionId = `chatcmpl-${crypto.randomBytes(12).toString('hex')}`;
229
+
230
+ if (!stream) {
231
+ try {
232
+ const result = await runWithRetry({
233
+ rawBody,
234
+ requestedModel,
235
+ signal: callerSignal,
236
+ onDelta: () => {},
237
+ getOutputCommitState: () => ({ publishedBytes: 0, toolCallCount: 0 }),
238
+ onModelResolved: (m) => { effectiveModel = m; },
239
+ });
240
+ const outputBytes = Buffer.byteLength(
241
+ (result.content || '') + (result.calls?.length ? JSON.stringify(result.calls) : ''),
242
+ 'utf8',
243
+ );
244
+ const usage = estimateUsage({ promptChars, imageCount, outputBytes });
245
+ const finishReason = result.incomplete ? null : result.calls?.length ? 'tool_calls' : 'stop';
246
+ const message = {
247
+ role: 'assistant',
248
+ content: result.calls?.length && !result.content ? null : (result.content || ''),
249
+ ...(result.calls?.length ? { tool_calls: result.calls } : {}),
250
+ ...(result.annotations?.length ? { annotations: toChatAnnotations(result.annotations) } : {}),
251
+ };
252
+ return new Response(
253
+ JSON.stringify({
254
+ id: result.id || completionId,
255
+ object: 'chat.completion',
256
+ created,
257
+ model: result.model || effectiveModel,
258
+ ...(result.incomplete ? { status: 'incomplete', incomplete_details: result.incompleteDetails ?? { reason: 'interrupted' } } : {}),
259
+ choices: [{ index: 0, message, finish_reason: finishReason }],
260
+ usage,
261
+ }),
262
+ { status: 200, headers: { 'content-type': 'application/json' } },
263
+ );
264
+ } catch (err) {
265
+ return jsonErrorResponse(err);
266
+ }
267
+ }
268
+
269
+ // Streaming SSE response: defer HTTP 200 headers until first verified output (or completion)
270
+ // so pre-output validation / auth / upstream errors return genuine 4xx/5xx JSON responses,
271
+ // and link ReadableStream.cancel() to abort the underlying Google HTTP/2 turn.
272
+ const encoder = new TextEncoder();
273
+ const streamAbort = new AbortController();
274
+ const onCallerAbort = () => streamAbort.abort(callerSignal?.reason || new Error('Aborted'));
275
+ if (callerSignal) {
276
+ if (callerSignal.aborted) streamAbort.abort(callerSignal.reason);
277
+ else callerSignal.addEventListener('abort', onCallerAbort, { once: true });
278
+ }
279
+
280
+ let resolveStart;
281
+ let rejectStart;
282
+ let startSettled = false;
283
+ const startGate = new Promise((resolve, reject) => {
284
+ resolveStart = () => {
285
+ if (!startSettled) {
286
+ startSettled = true;
287
+ resolve();
288
+ }
289
+ };
290
+ rejectStart = (err) => {
291
+ if (!startSettled) {
292
+ startSettled = true;
293
+ reject(err);
294
+ }
295
+ };
296
+ });
297
+
298
+ const pendingChunks = [];
299
+ let streamController = null;
300
+ let streamEnded = false;
301
+ let streamClosed = false;
302
+ let publishedBytes = 0;
303
+ let toolCallCount = 0;
304
+ let sentRole = false;
305
+ let emittedAny = false;
306
+ let keepaliveTimer = null;
307
+
308
+ const cleanup = () => {
309
+ if (keepaliveTimer) {
310
+ clearInterval(keepaliveTimer);
311
+ keepaliveTimer = null;
312
+ }
313
+ if (callerSignal) callerSignal.removeEventListener('abort', onCallerAbort);
314
+ };
315
+
316
+ const pushSse = (text) => {
317
+ if (streamClosed) return;
318
+ const bytes = encoder.encode(text);
319
+ if (streamController) {
320
+ try {
321
+ streamController.enqueue(bytes);
322
+ } catch {
323
+ streamClosed = true;
324
+ streamAbort.abort(new Error('Stream consumer closed'));
325
+ }
326
+ } else {
327
+ pendingChunks.push(bytes);
328
+ }
329
+ };
330
+
331
+ const finishSse = () => {
332
+ cleanup();
333
+ streamEnded = true;
334
+ if (streamController && !streamClosed) {
335
+ streamClosed = true;
336
+ try {
337
+ streamController.close();
338
+ } catch {}
339
+ }
340
+ };
341
+
342
+ const sendDeltaChunk = (delta, finishReason = null, extra = {}) => {
343
+ const chunk = {
344
+ id: completionId,
345
+ object: 'chat.completion.chunk',
346
+ created,
347
+ model: effectiveModel,
348
+ choices: [{ index: 0, delta, finish_reason: finishReason }],
349
+ ...extra,
350
+ };
351
+ pushSse(`data: ${JSON.stringify(chunk)}\n\n`);
352
+ };
353
+
354
+ const sendUsageChunk = (usage) => {
355
+ const chunk = {
356
+ id: completionId,
357
+ object: 'chat.completion.chunk',
358
+ created,
359
+ model: effectiveModel,
360
+ choices: [],
361
+ usage,
362
+ };
363
+ pushSse(`data: ${JSON.stringify(chunk)}\n\n`);
364
+ };
365
+
366
+ const ensureRoleSent = () => {
367
+ if (!sentRole) {
368
+ sentRole = true;
369
+ sendDeltaChunk({ role: 'assistant' }, null);
370
+ resolveStart();
371
+ if (keepaliveMs > 0 && !keepaliveTimer) {
372
+ keepaliveTimer = setInterval(() => {
373
+ pushSse(': keepalive\n\n');
374
+ }, keepaliveMs);
375
+ keepaliveTimer.unref?.();
376
+ }
377
+ }
378
+ };
379
+
380
+ (async () => {
381
+ try {
382
+ const result = await runWithRetry({
383
+ rawBody,
384
+ requestedModel,
385
+ signal: streamAbort.signal,
386
+ getOutputCommitState: () => ({ publishedBytes, toolCallCount }),
387
+ onModelResolved: (m) => { effectiveModel = m; },
388
+ onDelta: async (ev) => {
389
+ if (!ev || typeof ev !== 'object') return;
390
+ if (ev.reset && !emittedAny) return;
391
+ if (typeof ev.content === 'string' && ev.content.length > 0) {
392
+ ensureRoleSent();
393
+ emittedAny = true;
394
+ publishedBytes += Buffer.byteLength(ev.content, 'utf8');
395
+ sendDeltaChunk({ content: ev.content }, null);
396
+ }
397
+ if (ev.call) {
398
+ ensureRoleSent();
399
+ emittedAny = true;
400
+ const index = toolCallCount++;
401
+ publishedBytes += Buffer.byteLength(JSON.stringify(ev.call), 'utf8');
402
+ sendDeltaChunk({ tool_calls: [{ index, ...ev.call }] }, null);
403
+ }
404
+ },
405
+ });
406
+
407
+ ensureRoleSent();
408
+ const finishReason = toolCallCount > 0 || result.calls?.length ? 'tool_calls' : 'stop';
409
+ const annotations = result.annotations?.length ? toChatAnnotations(result.annotations) : null;
410
+ sendDeltaChunk(annotations ? { annotations } : {}, finishReason);
411
+ if (includeUsage) {
412
+ const usage = estimateUsage({ promptChars, imageCount, outputBytes: publishedBytes });
413
+ sendUsageChunk(usage);
414
+ }
415
+ pushSse('data: [DONE]\n\n');
416
+ } catch (err) {
417
+ if (!sentRole) {
418
+ rejectStart(err);
419
+ cleanup();
420
+ streamEnded = true;
421
+ streamClosed = true;
422
+ return;
423
+ }
424
+ if (
425
+ !streamAbort.signal.aborted &&
426
+ err?.code === 'NATIVE_TURN_TIMEOUT' &&
427
+ err?.unverifiedOutput !== true &&
428
+ err?.postOutputIdleStall === true &&
429
+ (publishedBytes > 0 || toolCallCount > 0)
430
+ ) {
431
+ sendDeltaChunk({}, toolCallCount > 0 ? 'tool_calls' : 'stop', { incomplete: true });
432
+ if (includeUsage) {
433
+ const usage = estimateUsage({ promptChars, imageCount, outputBytes: publishedBytes });
434
+ sendUsageChunk(usage);
435
+ }
436
+ pushSse('data: [DONE]\n\n');
437
+ } else {
438
+ pushSse(
439
+ `data: ${JSON.stringify({
440
+ error: {
441
+ code: err?.code || 'UPSTREAM_ERROR',
442
+ message: err?.upstreamMessage || err?.message || 'Generation failed',
443
+ },
444
+ incomplete: true,
445
+ })}\n\n`,
446
+ );
447
+ pushSse('data: [DONE]\n\n');
448
+ }
449
+ } finally {
450
+ finishSse();
451
+ }
452
+ })();
453
+
454
+ try {
455
+ await startGate;
456
+ } catch (err) {
457
+ return jsonErrorResponse(err);
458
+ }
459
+
460
+ const sseStream = new ReadableStream({
461
+ start(controller) {
462
+ streamController = controller;
463
+ while (pendingChunks.length > 0 && !streamClosed) {
464
+ try {
465
+ controller.enqueue(pendingChunks.shift());
466
+ } catch {
467
+ streamClosed = true;
468
+ streamAbort.abort(new Error('Stream consumer closed'));
469
+ break;
470
+ }
471
+ }
472
+ if (streamEnded && !streamClosed) {
473
+ streamClosed = true;
474
+ try {
475
+ controller.close();
476
+ } catch {}
477
+ }
478
+ },
479
+ cancel(reason) {
480
+ streamClosed = true;
481
+ cleanup();
482
+ streamAbort.abort(reason instanceof Error ? reason : new Error('Stream cancelled by consumer'));
483
+ },
484
+ });
485
+
486
+ return new Response(sseStream, {
487
+ status: 200,
488
+ headers: {
489
+ 'content-type': 'text/event-stream',
490
+ 'cache-control': 'no-cache',
491
+ },
492
+ });
493
+ };
494
+ }
@@ -0,0 +1,27 @@
1
+ import { PROVIDER_ID, mergeOpenCodeConfig, filterOpenCodeModels } from './models.js';
2
+ import { createOpenCodeAuthHook } from './auth.js';
3
+
4
+ export function createGeminiAppOpenCodePlugin(deps = {}) {
5
+ return async function GeminiAppOpenCodePlugin(input = {}) {
6
+ const { auth, getSubscriptionTier } = createOpenCodeAuthHook({
7
+ client: input?.client,
8
+ ...deps,
9
+ });
10
+
11
+ return {
12
+ async config(cfg) {
13
+ mergeOpenCodeConfig(cfg);
14
+ },
15
+ auth,
16
+ provider: {
17
+ id: PROVIDER_ID,
18
+ async models(provider) {
19
+ return filterOpenCodeModels(provider?.models, getSubscriptionTier());
20
+ },
21
+ },
22
+ };
23
+ };
24
+ }
25
+
26
+ export const GeminiAppOpenCodePlugin = createGeminiAppOpenCodePlugin();
27
+ export default GeminiAppOpenCodePlugin;
@@ -0,0 +1,84 @@
1
+ import { MODEL_SPECS, canonicalModel } from '../../src/openai-contract.mjs';
2
+
3
+ export const PROVIDER_ID = 'gemini-app';
4
+ export const PROVIDER_NAME = 'Gemini App (Direct HTTP/2)';
5
+ export const VIRTUAL_BASE_URL = 'https://gemini-app.local/v1';
6
+
7
+ export const OPENCODE_MODELS = Object.freeze(
8
+ Object.fromEntries(
9
+ Object.entries(MODEL_SPECS).map(([id, spec]) => [
10
+ id,
11
+ Object.freeze({
12
+ id,
13
+ name: spec.name,
14
+ attachment: true,
15
+ reasoning: spec.reasoning,
16
+ tool_call: true,
17
+ temperature: false,
18
+ modalities: Object.freeze({
19
+ input: Object.freeze(['text', 'image']),
20
+ output: Object.freeze(['text']),
21
+ }),
22
+ cost: Object.freeze({
23
+ input: 0,
24
+ output: 0,
25
+ cache_read: 0,
26
+ cache_write: 0,
27
+ }),
28
+ limit: Object.freeze({
29
+ context: spec.contextWindow,
30
+ output: spec.maxTokens,
31
+ }),
32
+ }),
33
+ ]),
34
+ ),
35
+ );
36
+
37
+ export function buildOpenCodeProviderConfig() {
38
+ return {
39
+ npm: '@ai-sdk/openai-compatible',
40
+ name: PROVIDER_NAME,
41
+ options: {
42
+ baseURL: VIRTUAL_BASE_URL,
43
+ },
44
+ models: JSON.parse(JSON.stringify(OPENCODE_MODELS)),
45
+ };
46
+ }
47
+
48
+ export function mergeOpenCodeConfig(cfg) {
49
+ if (!cfg || typeof cfg !== 'object') return cfg;
50
+ cfg.provider = cfg.provider && typeof cfg.provider === 'object' ? cfg.provider : {};
51
+ const existing = cfg.provider[PROVIDER_ID] && typeof cfg.provider[PROVIDER_ID] === 'object'
52
+ ? cfg.provider[PROVIDER_ID]
53
+ : {};
54
+ const defaults = buildOpenCodeProviderConfig();
55
+ cfg.provider[PROVIDER_ID] = {
56
+ ...defaults,
57
+ ...existing,
58
+ options: {
59
+ ...defaults.options,
60
+ ...(existing.options && typeof existing.options === 'object' ? existing.options : {}),
61
+ },
62
+ models: {
63
+ ...defaults.models,
64
+ ...(existing.models && typeof existing.models === 'object' ? existing.models : {}),
65
+ },
66
+ };
67
+ return cfg;
68
+ }
69
+
70
+ export function normalizeOpenCodeModelId(raw) {
71
+ if (typeof raw !== 'string') return 'gemini-neon';
72
+ let trimmed = raw.trim();
73
+ if (trimmed.startsWith(`${PROVIDER_ID}/`)) trimmed = trimmed.slice(PROVIDER_ID.length + 1);
74
+ return canonicalModel(trimmed);
75
+ }
76
+
77
+ export function filterOpenCodeModels(models, subscriptionTier) {
78
+ if (!models || typeof models !== 'object') return {};
79
+ if (subscriptionTier === 'free') {
80
+ const auto = models['gemini-auto'];
81
+ return auto ? { 'gemini-auto': auto } : {};
82
+ }
83
+ return { ...models };
84
+ }