opencode-next 0.0.0-stage → 1.0.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.
@@ -0,0 +1,161 @@
1
+ export const PROVIDER = "opencode-next";
2
+ export const PROVIDER_NAME = "OpenCode (OAuth)";
3
+
4
+ export const GO_PROVIDER = "opencode-go-subscription";
5
+ export const GO_PROVIDER_NAME = "OpenCode Go (Subscription)";
6
+ export const GO_CREDENTIAL_ENV_VAR = "OPENCODE_GO_API_KEY";
7
+ export const OPENCODE_GO_ORIGIN = "https://opencode.ai";
8
+ export const OPENCODE_GO_USAGE_URL = "https://opencode.ai/inference/go/v1/usage";
9
+ export const OPENCODE_GO_MODELS_URL = "https://opencode.ai/inference/go/v1/models";
10
+ export const OPENCODE_GO_CHAT_URL = "https://opencode.ai/inference/go/openai/v1/chat/completions";
11
+ export const GO_REQUEST_TIMEOUT_MS = 15000;
12
+
13
+ export const OPENCODE_INFERENCE_URL = "https://opencode.ai/inference/openai/v1";
14
+ export const OPENCODE_MODELS_URL = "https://models.opencode.ai/api.json";
15
+
16
+ export const OAUTH_CLIENT_ID = "opencode-cli";
17
+ export const OAUTH_DEVICE_CODE_URL = "https://opencode.ai/console/auth/device/code";
18
+ export const OAUTH_DEVICE_TOKEN_URL = "https://opencode.ai/console/auth/device/token";
19
+
20
+ export const DEFAULT_STREAM_IDLE_MS = 60000;
21
+ export const DEFAULT_FIRST_EVENT_MS = 30000;
22
+
23
+ /**
24
+ * 送出請求時的圖片投影預算。
25
+ *
26
+ * OpenAI 相容端點把圖片內嵌成 base64 放在 body 裡,整包都會計入請求大小,而
27
+ * 長 session 累積多張截圖時很容易把 body 撐爆。640000 px(約 1050x610)是
28
+ * 保守值:足以讓 UI 截圖裡的小字仍然可讀,同時把單圖壓到數十 KB。
29
+ *
30
+ * 這兩個值必須固定且確定,因為 attachment service 會用「附件 + 目標」算出的
31
+ * variant id 做快取;預算一旦浮動,圖片位元組就會每次都重新編碼。
32
+ */
33
+ export const DEFAULT_IMAGE_PIXEL_BUDGET = 640000;
34
+ export const DEFAULT_IMAGE_MAX_BYTES = 2 * 1024 * 1024;
35
+
36
+ /** Live availability probing of the free lane. */
37
+ export const PROBE_CONCURRENCY = 4;
38
+ export const PROBE_MAX_TOKENS = 16;
39
+ export const PROBE_TIMEOUT_MS = 20000;
40
+ /** Full re-verification interval; retires models that stopped serving. */
41
+ export const DEFAULT_PROBE_INTERVAL_MS = 6 * 60 * 60 * 1000;
42
+ /** How often to re-fetch the catalog looking for newly published free models. */
43
+ export const DEFAULT_CATALOG_POLL_MS = 15 * 60 * 1000;
44
+ /** Persisted probe results older than this are treated as stale on startup. */
45
+ export const PROBE_CACHE_TTL_MS = 12 * 60 * 60 * 1000;
46
+
47
+ /**
48
+ * Offline fallback, used only when the public catalog cannot be fetched.
49
+ * Effort values mirror what the live catalog publishes (and what upstream
50
+ * accepted in probes), so a fallback list behaves like a fetched one.
51
+ */
52
+ export const STATIC_FREE_MODELS = [
53
+ {
54
+ id: "deepseek-v4.1-flash-free",
55
+ name: "DeepSeek V4.1 Flash Free",
56
+ contextWindow: 200000,
57
+ defaultMaxTokens: 65536,
58
+ inputModalities: ["text", "image"],
59
+ efforts: ["off", "low", "high", "max"],
60
+ defaultEffort: "high"
61
+ },
62
+ {
63
+ id: "big-pickle",
64
+ name: "Big Pickle",
65
+ contextWindow: 200000,
66
+ defaultMaxTokens: 65536,
67
+ inputModalities: ["text"],
68
+ efforts: ["off", "low", "medium", "high"],
69
+ defaultEffort: "medium"
70
+ },
71
+ {
72
+ id: "glm-5.3-flash-free",
73
+ name: "GLM-5.3-Flash Free",
74
+ contextWindow: 200000,
75
+ defaultMaxTokens: 65536,
76
+ inputModalities: ["text"],
77
+ efforts: ["off", "low", "high", "max"],
78
+ defaultEffort: "high"
79
+ },
80
+ {
81
+ id: "mimo-v2.6-flash-free",
82
+ name: "MiMo-V2.6-Flash Free",
83
+ contextWindow: 200000,
84
+ defaultMaxTokens: 65536,
85
+ inputModalities: ["text"],
86
+ efforts: ["off", "low", "medium", "high"],
87
+ defaultEffort: "medium"
88
+ },
89
+ {
90
+ id: "longcat-2.5-preview-free",
91
+ name: "LongCat 2.5 Preview Free",
92
+ contextWindow: 1000000,
93
+ defaultMaxTokens: 65536,
94
+ inputModalities: ["text"],
95
+ efforts: ["off", "low", "medium", "high"],
96
+ defaultEffort: "medium"
97
+ },
98
+ {
99
+ id: "nemotron-3-ultra-free",
100
+ name: "Nemotron 3 Ultra Free",
101
+ contextWindow: 1000000,
102
+ defaultMaxTokens: 65536,
103
+ inputModalities: ["text"],
104
+ efforts: ["off", "low", "medium", "high"],
105
+ defaultEffort: "medium"
106
+ },
107
+ {
108
+ id: "nemotron-3.5-lightning-free",
109
+ name: "Nemotron 3.5 Lightning Free",
110
+ contextWindow: 1000000,
111
+ defaultMaxTokens: 65536,
112
+ inputModalities: ["text"],
113
+ efforts: ["off", "low", "medium", "high"],
114
+ defaultEffort: "medium"
115
+ },
116
+ {
117
+ id: "nemotron-3.5-super-vl-free",
118
+ name: "Nemotron 3.5 Super VL Free",
119
+ contextWindow: 1048576,
120
+ defaultMaxTokens: 65536,
121
+ inputModalities: ["text", "image"],
122
+ efforts: ["off", "minimal", "low", "medium", "high", "xhigh"],
123
+ defaultEffort: "medium"
124
+ },
125
+ {
126
+ id: "beam-free",
127
+ name: "Beam Free",
128
+ contextWindow: 1048576,
129
+ defaultMaxTokens: 65536,
130
+ inputModalities: ["text"],
131
+ efforts: ["low", "medium", "high", "xhigh", "max"],
132
+ defaultEffort: "medium"
133
+ },
134
+ {
135
+ id: "space-bunny-free",
136
+ name: "Space Bunny Free",
137
+ contextWindow: 1048576,
138
+ defaultMaxTokens: 65536,
139
+ inputModalities: ["text"],
140
+ efforts: ["low", "medium", "high", "xhigh", "max"],
141
+ defaultEffort: "medium"
142
+ },
143
+ {
144
+ id: "exo-free",
145
+ name: "Exo Free",
146
+ contextWindow: 1048576,
147
+ defaultMaxTokens: 65536,
148
+ inputModalities: ["text"],
149
+ efforts: ["high"],
150
+ defaultEffort: "high"
151
+ },
152
+ {
153
+ id: "cat-jam-free",
154
+ name: "Cat Jam Free",
155
+ contextWindow: 1048576,
156
+ defaultMaxTokens: 65536,
157
+ inputModalities: ["text"],
158
+ efforts: ["low", "medium", "high", "xhigh", "max"],
159
+ defaultEffort: "medium"
160
+ }
161
+ ];
@@ -0,0 +1,117 @@
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readFileSync,
5
+ renameSync,
6
+ unlinkSync,
7
+ writeFileSync
8
+ } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { homedir } from 'node:os';
11
+ import { randomBytes } from 'node:crypto';
12
+
13
+ /** 避免無效或極端值破壞宿主的 token 預算計算。 */
14
+ export const MIN_CONTEXT_WINDOW = 1024;
15
+ export const MAX_CONTEXT_WINDOW = 100_000_000;
16
+
17
+ export function defaultContextWindowPath() {
18
+ return join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'opencode-next.context.json');
19
+ }
20
+
21
+ function isValidContextWindow(value) {
22
+ return Number.isSafeInteger(value)
23
+ && value >= MIN_CONTEXT_WINDOW
24
+ && value <= MAX_CONTEXT_WINDOW;
25
+ }
26
+
27
+ function normalizeOverrides(input) {
28
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return {};
29
+ const result = Object.create(null);
30
+ for (const [modelId, value] of Object.entries(input)) {
31
+ const id = modelId.trim();
32
+ if (id && id.length <= 200 && isValidContextWindow(value)) result[id] = value;
33
+ }
34
+ return result;
35
+ }
36
+
37
+ /**
38
+ * 每個模型的手動上下文覆寫。
39
+ * 只儲存 model id 與整數容量,不碰憑證或對話內容。
40
+ */
41
+ export class ContextWindowStore {
42
+ #path;
43
+ #overrides = Object.create(null);
44
+ #loaded = false;
45
+
46
+ constructor({ path } = {}) {
47
+ this.#path = path || defaultContextWindowPath();
48
+ }
49
+
50
+ #load() {
51
+ if (this.#loaded) return;
52
+ this.#loaded = true;
53
+ try {
54
+ if (!existsSync(this.#path)) return;
55
+ const parsed = JSON.parse(readFileSync(this.#path, 'utf8').replace(/^\uFEFF/, ''));
56
+ if (parsed?.version !== 1) return;
57
+ this.#overrides = normalizeOverrides(parsed.overrides);
58
+ } catch {
59
+ // 設定檔損毀時退回跟隨目錄值;不覆寫原檔,保留供使用者檢查。
60
+ this.#overrides = Object.create(null);
61
+ }
62
+ }
63
+
64
+ #persist(next) {
65
+ mkdirSync(dirname(this.#path), { recursive: true });
66
+ const temporary = `${this.#path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
67
+ try {
68
+ writeFileSync(temporary, JSON.stringify({ version: 1, overrides: next }, null, 2), {
69
+ encoding: 'utf8',
70
+ mode: 0o600
71
+ });
72
+ renameSync(temporary, this.#path);
73
+ } finally {
74
+ try {
75
+ if (existsSync(temporary)) unlinkSync(temporary);
76
+ } catch {}
77
+ }
78
+ }
79
+
80
+ /** 取得單一模型的覆寫值;沒有覆寫時回傳 null。 */
81
+ getOverride(modelId) {
82
+ this.#load();
83
+ return Object.hasOwn(this.#overrides, modelId) ? this.#overrides[modelId] : null;
84
+ }
85
+
86
+ /** 取得副本,避免呼叫端修改內部設定。 */
87
+ get() {
88
+ this.#load();
89
+ return { ...this.#overrides };
90
+ }
91
+
92
+ /** 設定手動值;成功寫入後才更新記憶體狀態。 */
93
+ set(modelId, contextWindow) {
94
+ this.#load();
95
+ const id = typeof modelId === 'string' ? modelId.trim() : '';
96
+ if (!id || id.length > 200) throw new TypeError('modelId must be a non-empty string of at most 200 characters.');
97
+ if (!isValidContextWindow(contextWindow)) {
98
+ throw new RangeError(`contextWindow must be an integer from ${MIN_CONTEXT_WINDOW} to ${MAX_CONTEXT_WINDOW}.`);
99
+ }
100
+ const next = { ...this.#overrides, [id]: contextWindow };
101
+ this.#persist(next);
102
+ this.#overrides = next;
103
+ return contextWindow;
104
+ }
105
+
106
+ /** 清除單一模型覆寫,讓它回到目錄/外掛備援值。 */
107
+ reset(modelId) {
108
+ this.#load();
109
+ const id = typeof modelId === 'string' ? modelId.trim() : '';
110
+ if (!id || !Object.hasOwn(this.#overrides, id)) return false;
111
+ const next = { ...this.#overrides };
112
+ delete next[id];
113
+ this.#persist(next);
114
+ this.#overrides = next;
115
+ return true;
116
+ }
117
+ }
@@ -0,0 +1,263 @@
1
+ import {
2
+ OAUTH_CLIENT_ID,
3
+ OAUTH_DEVICE_CODE_URL,
4
+ OAUTH_DEVICE_TOKEN_URL
5
+ } from './constants.js';
6
+
7
+ /** 單次 OAuth HTTP 請求的逾時。輪詢總期限另計,不受這 15 秒限制。 */
8
+ export const DEFAULT_HTTP_TIMEOUT_MS = 15_000;
9
+
10
+ function resolveTimeoutMs(options) {
11
+ const value = options?.timeoutMs;
12
+ return Number.isFinite(value) && value >= 0 ? value : DEFAULT_HTTP_TIMEOUT_MS;
13
+ }
14
+
15
+ function combineAbortSignals(outer, timeout) {
16
+ if (!outer) return timeout;
17
+ if (outer.aborted) return outer;
18
+ if (typeof AbortSignal.any === 'function') return AbortSignal.any([outer, timeout]);
19
+ const controller = new AbortController();
20
+ const forward = (signal) => {
21
+ if (signal.aborted) {
22
+ controller.abort(signal.reason);
23
+ return;
24
+ }
25
+ signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
26
+ };
27
+ forward(outer);
28
+ forward(timeout);
29
+ return controller.signal;
30
+ }
31
+
32
+ function timeoutError(timeoutMs, cause) {
33
+ const seconds = Math.max(1, Math.round(timeoutMs / 1000));
34
+ const error = new Error(`OpenCode request timed out after ${seconds} seconds`);
35
+ error.name = 'TimeoutError';
36
+ if (cause) error.cause = cause;
37
+ return error;
38
+ }
39
+
40
+ /**
41
+ * 給單次 fetch 加上逾時,且不讓逾時把呼叫端的取消訊號一併作廢。
42
+ * 呼叫端已取消時原樣拋出,方便上層分辨「使用者取消」與「網路逾時」。
43
+ */
44
+ async function fetchWithTimeout(url, init, { signal, timeoutMs } = {}) {
45
+ const timeout = AbortSignal.timeout(timeoutMs);
46
+ const combined = combineAbortSignals(signal, timeout);
47
+ try {
48
+ return await fetch(url, { ...init, signal: combined });
49
+ } catch (err) {
50
+ if (signal?.aborted) throw err;
51
+ if (timeout.aborted || err?.name === 'TimeoutError') throw timeoutError(timeoutMs, err);
52
+ throw err;
53
+ }
54
+ }
55
+
56
+ /** 登入失敗要給設定頁看的訊息。取消不是失敗;權杖一律遮掉。 */
57
+ export function classifyDeviceLoginError(error) {
58
+ if (!error) return null;
59
+ const raw = String(error.message ?? error);
60
+ if (error.name === 'AbortError' || /polling aborted/i.test(raw)) return null;
61
+ let code = 'failed';
62
+ if (error.name === 'TimeoutError' || /OpenCode request timed out/i.test(raw)) code = 'network';
63
+ else if (/Device login timed out/i.test(raw)) code = 'timeout';
64
+ else if (/access_denied|access denied/i.test(raw)) code = 'denied';
65
+ else if (/expired_token|code expired|device code expired/i.test(raw)) code = 'expired';
66
+ else if (/failed to request device code|fetch failed|ECONN|ENOTFOUND|EAI_AGAIN|network/i.test(raw)) {
67
+ code = 'network';
68
+ }
69
+ return { code, message: sanitizeLoginDetail(raw) };
70
+ }
71
+
72
+ function sanitizeLoginDetail(text) {
73
+ return String(text)
74
+ .replace(/st_[A-Za-z0-9._-]+/g, '[redacted]')
75
+ .replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
76
+ .replace(/\s+/g, ' ')
77
+ .trim()
78
+ .slice(0, 240);
79
+ }
80
+
81
+ /**
82
+ * Step 1: Request a device code from OpenCode Console.
83
+ * Returns { device_code, user_code, verification_url, expires_in, interval }
84
+ */
85
+ export async function requestDeviceCode(signal, options = {}) {
86
+ const res = await fetchWithTimeout(OAUTH_DEVICE_CODE_URL, {
87
+ method: 'POST',
88
+ headers: { 'content-type': 'application/json' },
89
+ body: JSON.stringify({
90
+ client_id: OAUTH_CLIENT_ID,
91
+ supports_org_scope: true
92
+ })
93
+ }, { signal, timeoutMs: resolveTimeoutMs(options) });
94
+
95
+ if (!res.ok) {
96
+ const text = await res.text();
97
+ throw new Error(`Failed to request device code (HTTP ${res.status}): ${text}`);
98
+ }
99
+
100
+ const data = await res.json();
101
+ const rawUrl = data?.verification_uri_complete || data?.verification_uri;
102
+ if (!data?.device_code || !data?.user_code || typeof rawUrl !== 'string' || !rawUrl.trim()) {
103
+ throw new Error('Device authorization response missing required fields');
104
+ }
105
+
106
+ let parsedUrl;
107
+ try {
108
+ parsedUrl = new URL(rawUrl, 'https://opencode.ai/');
109
+ } catch {
110
+ throw new Error(`Invalid verification URL format: ${rawUrl}`);
111
+ }
112
+
113
+ if (
114
+ parsedUrl.protocol !== 'https:' ||
115
+ !(parsedUrl.hostname === 'opencode.ai' || parsedUrl.hostname.endsWith('.opencode.ai'))
116
+ ) {
117
+ throw new Error(`Insecure or untrusted verification URL: ${parsedUrl.href}`);
118
+ }
119
+
120
+ return {
121
+ device_code: data.device_code,
122
+ user_code: data.user_code,
123
+ verification_url: parsedUrl.href,
124
+ expires_in: data.expires_in || 600,
125
+ interval: data.interval || 5
126
+ };
127
+ }
128
+
129
+ function abortableSleep(ms, signal) {
130
+ if (signal?.aborted) return Promise.reject(new Error('Device login polling aborted'));
131
+ return new Promise((resolve, reject) => {
132
+ const timer = setTimeout(() => {
133
+ cleanup();
134
+ resolve();
135
+ }, ms);
136
+ const onAbort = () => {
137
+ cleanup();
138
+ reject(new Error('Device login polling aborted'));
139
+ };
140
+ function cleanup() {
141
+ clearTimeout(timer);
142
+ signal?.removeEventListener('abort', onAbort);
143
+ }
144
+ signal?.addEventListener('abort', onAbort);
145
+ });
146
+ }
147
+
148
+ /**
149
+ * Step 2: Poll OpenCode Console until user approves device code or timeout occurs.
150
+ */
151
+ export async function pollDeviceToken(deviceCode, intervalSec = 5, timeoutSec = 600, signal, options = {}) {
152
+ const deadline = Date.now() + timeoutSec * 1000;
153
+ let intervalMs = Math.max(2, intervalSec) * 1000;
154
+ const timeoutMs = resolveTimeoutMs(options);
155
+
156
+ while (Date.now() < deadline) {
157
+ if (signal?.aborted) {
158
+ throw new Error('Device login polling aborted');
159
+ }
160
+
161
+ let res;
162
+ try {
163
+ res = await fetchWithTimeout(OAUTH_DEVICE_TOKEN_URL, {
164
+ method: 'POST',
165
+ headers: { 'content-type': 'application/json' },
166
+ body: JSON.stringify({
167
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
168
+ client_id: OAUTH_CLIENT_ID,
169
+ device_code: deviceCode
170
+ })
171
+ }, { signal, timeoutMs });
172
+ } catch (err) {
173
+ if (signal?.aborted) throw err;
174
+ // 單次 HTTP 逾時或短暫斷線:保留輪詢,不把整段授權作廢。
175
+ await abortableSleep(intervalMs, signal);
176
+ continue;
177
+ }
178
+
179
+ if (res.ok) {
180
+ const tokenData = await res.json();
181
+ const access = tokenData.access_token || tokenData.access;
182
+ const refresh = tokenData.refresh_token || tokenData.refresh;
183
+ if (!access || !refresh) {
184
+ throw new Error('Device token response did not contain access and refresh tokens');
185
+ }
186
+ return {
187
+ access_token: access,
188
+ refresh_token: refresh,
189
+ expires_in: tokenData.expires_in || 3600,
190
+ org_id: tokenData.org_id
191
+ };
192
+ }
193
+
194
+ const body = await res.text().catch(() => '');
195
+ let errorCode = '';
196
+ try {
197
+ errorCode = JSON.parse(body)?.error ?? '';
198
+ } catch {
199
+ // 非 JSON 的回應仍可用文字判斷 authorization_pending。
200
+ }
201
+
202
+ // RFC 8628: 收到 slow_down 時,輪詢間隔必須至少延長 5 秒
203
+ const isSlowDown = errorCode === 'slow_down' || body.includes('slow_down');
204
+ if (isSlowDown) {
205
+ intervalMs += 5000;
206
+ }
207
+
208
+ const waiting =
209
+ errorCode === 'authorization_pending' ||
210
+ isSlowDown ||
211
+ body.includes('authorization_pending');
212
+ if (waiting) {
213
+ await abortableSleep(intervalMs, signal);
214
+ continue;
215
+ }
216
+
217
+ // 服務端暫時錯誤仍可重試;參數或授權錯誤要立刻回報,不能假裝在等待。
218
+ if (res.status >= 500 || res.status === 429) {
219
+ await abortableSleep(intervalMs, signal);
220
+ continue;
221
+ }
222
+
223
+ throw new Error(`Device token polling failed with HTTP ${res.status}: ${body}`);
224
+ }
225
+
226
+ throw new Error(`Device login timed out after ${timeoutSec} seconds`);
227
+ }
228
+
229
+ /**
230
+ * Refresh an expired access token using refresh_token.
231
+ */
232
+ export async function refreshAccessToken(refreshToken, options = {}) {
233
+ if (!refreshToken) {
234
+ throw new Error('No refresh token provided');
235
+ }
236
+
237
+ const res = await fetchWithTimeout(OAUTH_DEVICE_TOKEN_URL, {
238
+ method: 'POST',
239
+ headers: { 'content-type': 'application/json' },
240
+ body: JSON.stringify({
241
+ grant_type: 'refresh_token',
242
+ refresh_token: refreshToken,
243
+ client_id: OAUTH_CLIENT_ID
244
+ })
245
+ }, { timeoutMs: resolveTimeoutMs(options) });
246
+
247
+ if (!res.ok) {
248
+ const text = await res.text();
249
+ throw new Error(`Token refresh failed (HTTP ${res.status}): ${text}`);
250
+ }
251
+
252
+ const data = await res.json();
253
+ const access = data.access_token || data.access;
254
+ if (!access) {
255
+ throw new Error('Token refresh response did not contain an access token');
256
+ }
257
+ return {
258
+ access_token: access,
259
+ refresh_token: data.refresh_token || data.refresh || refreshToken,
260
+ expires_in: data.expires_in || 3600,
261
+ org_id: data.org_id
262
+ };
263
+ }