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,647 @@
1
+ /**
2
+ * OpenCode Go 官方唯讀端點用戶端(Stage 1)。
3
+ *
4
+ * 僅存取兩個官方唯讀端點:
5
+ * - GET https://opencode.ai/inference/go/v1/usage
6
+ * - GET https://opencode.ai/inference/go/v1/models
7
+ *
8
+ * 安全不變式:
9
+ * - 固定官方目的地(`https://opencode.ai`),絕不跟隨 HTTP 重新導向。
10
+ * - 使用 Bearer Personal API Key 與本外掛自己的 User-Agent;不帶 `org_id` 或 OAuth 標頭。
11
+ * - 錯誤訊息必經脫敏處理,絕不外洩 API key。
12
+ */
13
+
14
+ import {
15
+ GO_REQUEST_TIMEOUT_MS,
16
+ OPENCODE_GO_CHAT_URL,
17
+ OPENCODE_GO_MODELS_URL,
18
+ OPENCODE_GO_ORIGIN,
19
+ OPENCODE_GO_USAGE_URL
20
+ } from '../constants.js';
21
+ import { redactSecret } from './credentials.js';
22
+ import { normalizeGoModelsPayload } from './catalog.js';
23
+
24
+ export class GoClientError extends Error {
25
+ constructor(message, {
26
+ category = 'transient',
27
+ subCategory = null,
28
+ status = null,
29
+ retryable = false,
30
+ retryAfterMs = null,
31
+ errorType = null
32
+ } = {}) {
33
+ super(message);
34
+ this.name = 'GoClientError';
35
+ this.category = category;
36
+ this.subCategory = subCategory;
37
+ this.status = status;
38
+ this.retryable = retryable;
39
+ this.retryAfterMs = retryAfterMs;
40
+ this.errorType = errorType;
41
+ }
42
+ }
43
+
44
+ const ALLOWED_GO_PATHS = new Set([
45
+ '/inference/go/v1/usage',
46
+ '/inference/go/v1/models',
47
+ '/inference/go/openai/v1/chat/completions'
48
+ ]);
49
+
50
+ /**
51
+ * 嚴格驗證目的地必須為官方 `https://opencode.ai` Go 端點。
52
+ */
53
+ export function assertOfficialGoUrl(rawUrl, expectedPath = null) {
54
+ let parsed;
55
+ try {
56
+ parsed = new URL(rawUrl);
57
+ } catch {
58
+ throw new GoClientError('Invalid OpenCode Go endpoint URL.', {
59
+ category: 'invalid-destination',
60
+ retryable: false
61
+ });
62
+ }
63
+
64
+ if (
65
+ parsed.protocol !== 'https:'
66
+ || parsed.origin !== OPENCODE_GO_ORIGIN
67
+ || parsed.username !== ''
68
+ || parsed.password !== ''
69
+ || parsed.search !== ''
70
+ || parsed.hash !== ''
71
+ || !ALLOWED_GO_PATHS.has(parsed.pathname)
72
+ || (expectedPath && parsed.pathname !== expectedPath)
73
+ ) {
74
+ throw new GoClientError('Blocked non-official OpenCode Go destination URL.', {
75
+ category: 'invalid-destination',
76
+ retryable: false
77
+ });
78
+ }
79
+
80
+ return parsed.toString();
81
+ }
82
+
83
+ function getHeaderValue(headers, name) {
84
+ if (!headers) return null;
85
+ if (typeof headers.get === 'function') return headers.get(name);
86
+ const target = name.toLowerCase();
87
+ for (const [k, v] of Object.entries(headers)) {
88
+ if (String(k).toLowerCase() === target) return v;
89
+ }
90
+ return null;
91
+ }
92
+
93
+ export function parseRetryAfterMs(headers, now = Date.now()) {
94
+ const raw = getHeaderValue(headers, 'retry-after');
95
+ if (typeof raw !== 'string') return null;
96
+ const trimmed = raw.trim();
97
+ if (!trimmed) return null;
98
+ if (/^\d+$/.test(trimmed)) {
99
+ const secs = Number(trimmed);
100
+ return Number.isFinite(secs) && secs >= 0 ? secs * 1000 : null;
101
+ }
102
+ const dateMs = Date.parse(trimmed);
103
+ if (Number.isFinite(dateMs)) {
104
+ return Math.max(0, dateMs - now);
105
+ }
106
+ return null;
107
+ }
108
+
109
+ function extractErrorMeta(rawText) {
110
+ if (typeof rawText !== 'string' || !rawText.trim()) {
111
+ return { type: null, code: null, message: '' };
112
+ }
113
+ try {
114
+ const parsed = JSON.parse(rawText);
115
+ const err = parsed?.error && typeof parsed.error === 'object' ? parsed.error : parsed;
116
+ const type = typeof err?.type === 'string' ? err.type : (typeof parsed?.type === 'string' ? parsed.type : null);
117
+ const code = typeof err?.code === 'string' ? err.code : (typeof parsed?.code === 'string' ? parsed.code : null);
118
+ const message = typeof err?.message === 'string'
119
+ ? err.message
120
+ : (typeof parsed?.message === 'string' ? parsed.message : rawText);
121
+ return { type, code, message };
122
+ } catch {
123
+ return { type: null, code: null, message: rawText };
124
+ }
125
+ }
126
+
127
+ const INVALID_KEY_TYPE_RE = /(?:authentication|invalid[_-]?api[_-]?key|unauthorized|auth[_-]?error|token[_-]?invalid)/i;
128
+ const INVALID_KEY_MSG_RE = /(?:invalid\s+api\s*key|invalid\s+key|api\s*key\s+(?:is\s+)?invalid|expired\s+api\s*key|revoked\s+api\s*key|unauthorized|authentication\s+failed|missing\s+bearer)/i;
129
+
130
+ const ENTITLEMENT_TYPE_RE = /(?:entitlement|subscription|no[_-]?go[_-]?plan|plan[_-]?required)/i;
131
+ const ENTITLEMENT_MSG_RE = /(?:entitlement|not\s+subscribed|no\s+active\s+subscription|subscription\s+required|subscribe\s+to\s+opencode\s+go|opencode\s+go\s+subscription|upgrade\s+to\s+(?:opencode\s+)?go|no\s+go\s+access|go\s+plan\s+required)/i;
132
+
133
+ /**
134
+ * 區分無效 key、無 Go 權益、其他權限/政策錯誤與暫時故障。
135
+ */
136
+ export function classifyGoHttpFailure(status, rawText = '', headers = null, activeKey = '') {
137
+ const { type, code, message } = extractErrorMeta(rawText);
138
+ const safeMessage = redactSecret(String(message || '').trim(), activeKey).slice(0, 300);
139
+ const combinedTag = `${type || ''} ${code || ''}`.trim();
140
+
141
+ if (status >= 300 && status < 400) {
142
+ return new GoClientError('OpenCode Go blocked an unexpected HTTP redirect.', {
143
+ category: 'redirect-blocked',
144
+ subCategory: 'http-redirect',
145
+ status,
146
+ retryable: false,
147
+ errorType: type
148
+ });
149
+ }
150
+
151
+ if (
152
+ status === 401
153
+ || ((status === 400 || status === 403) && (INVALID_KEY_TYPE_RE.test(combinedTag) || INVALID_KEY_MSG_RE.test(safeMessage)))
154
+ ) {
155
+ return new GoClientError(
156
+ safeMessage || 'OpenCode Go API key is invalid or revoked.',
157
+ {
158
+ category: 'invalid-key',
159
+ subCategory: 'unauthorized',
160
+ status,
161
+ retryable: false,
162
+ errorType: type
163
+ }
164
+ );
165
+ }
166
+
167
+ if (
168
+ (status === 403 || status === 402)
169
+ && (ENTITLEMENT_TYPE_RE.test(combinedTag) || ENTITLEMENT_MSG_RE.test(safeMessage))
170
+ ) {
171
+ return new GoClientError(
172
+ safeMessage || 'This workspace does not have an active OpenCode Go subscription.',
173
+ {
174
+ category: 'no-entitlement',
175
+ subCategory: 'entitlement-required',
176
+ status,
177
+ retryable: false,
178
+ errorType: type
179
+ }
180
+ );
181
+ }
182
+
183
+ if (status === 403) {
184
+ const lower = `${combinedTag} ${safeMessage}`.toLowerCase();
185
+ let subCategory = 'policy-denied';
186
+ if (lower.includes('region') || lower.includes('country') || lower.includes('geo')) {
187
+ subCategory = 'region-restricted';
188
+ } else if (lower.includes('privacy') || lower.includes('data policy') || lower.includes('zero data retention')) {
189
+ subCategory = 'privacy-policy';
190
+ } else if (lower.includes('network') || lower.includes('abusive') || lower.includes('ip address')) {
191
+ subCategory = 'network-policy';
192
+ } else if (lower.includes('scope') || lower.includes('permission') || lower.includes('models')) {
193
+ subCategory = 'scope-denied';
194
+ }
195
+
196
+ return new GoClientError(
197
+ safeMessage || 'OpenCode Go rejected this request due to workspace permissions or policy.',
198
+ {
199
+ category: 'permission-policy',
200
+ subCategory,
201
+ status,
202
+ retryable: false,
203
+ errorType: type
204
+ }
205
+ );
206
+ }
207
+
208
+ if (status === 429) {
209
+ const lower = `${combinedTag} ${safeMessage}`.toLowerCase();
210
+ const isQuota = /(?:quota|allowance|usage\s*limit|rolling|weekly|monthly|exhausted)/i.test(lower);
211
+ const retryAfterMs = parseRetryAfterMs(headers);
212
+ return new GoClientError(
213
+ safeMessage || (isQuota
214
+ ? 'OpenCode Go subscription quota reached.'
215
+ : 'OpenCode Go rate limit reached; try again later.'),
216
+ {
217
+ category: 'transient',
218
+ subCategory: isQuota ? 'quota-exceeded' : 'rate-limited',
219
+ status,
220
+ retryable: true,
221
+ retryAfterMs,
222
+ errorType: type
223
+ }
224
+ );
225
+ }
226
+
227
+ if (status === 400) {
228
+ const lower = safeMessage.toLowerCase();
229
+ let subCategory = 'bad-request';
230
+ if (
231
+ lower.includes('maximum context length')
232
+ || lower.includes('context length')
233
+ || lower.includes('too many tokens')
234
+ || lower.includes('prompt is too long')
235
+ ) {
236
+ subCategory = 'context-overflow';
237
+ } else if (
238
+ lower.includes('model is unavailable')
239
+ || lower.includes('model unavailable')
240
+ || lower.includes('no such model')
241
+ || lower.includes('unknown model')
242
+ ) {
243
+ subCategory = 'unavailable';
244
+ }
245
+ return new GoClientError(
246
+ safeMessage || 'OpenCode Go rejected this request (HTTP 400).',
247
+ {
248
+ category: 'invalid-request',
249
+ subCategory,
250
+ status,
251
+ retryable: false,
252
+ errorType: type
253
+ }
254
+ );
255
+ }
256
+
257
+ if (status === 408 || (status >= 500 && status <= 599)) {
258
+ return new GoClientError(
259
+ safeMessage || `OpenCode Go temporary upstream failure (HTTP ${status}).`,
260
+ {
261
+ category: 'transient',
262
+ subCategory: status === 408 ? 'timeout' : 'upstream-error',
263
+ status,
264
+ retryable: true,
265
+ errorType: type
266
+ }
267
+ );
268
+ }
269
+
270
+ return new GoClientError(
271
+ safeMessage || `OpenCode Go request failed (HTTP ${status}).`,
272
+ {
273
+ category: 'invalid-response',
274
+ subCategory: status === 404 ? 'endpoint-not-found' : 'http-error',
275
+ status,
276
+ retryable: false,
277
+ errorType: type
278
+ }
279
+ );
280
+ }
281
+
282
+ function normalizeWindow(rawWindow) {
283
+ if (!rawWindow || typeof rawWindow !== 'object' || Array.isArray(rawWindow)) {
284
+ return null;
285
+ }
286
+ const status = typeof rawWindow.status === 'string' && rawWindow.status.trim()
287
+ ? rawWindow.status.trim()
288
+ : null;
289
+ if (!status) return null;
290
+
291
+ const percent = typeof rawWindow.percent === 'number' && Number.isFinite(rawWindow.percent) && rawWindow.percent >= 0
292
+ ? rawWindow.percent
293
+ : null;
294
+ if (percent === null) return null;
295
+
296
+ let resetsAt;
297
+ if (rawWindow.resetsAt === null) {
298
+ resetsAt = null;
299
+ } else if (typeof rawWindow.resetsAt === 'string' && rawWindow.resetsAt.trim()) {
300
+ const trimmed = rawWindow.resetsAt.trim();
301
+ if (!Number.isFinite(Date.parse(trimmed))) return null;
302
+ resetsAt = trimmed;
303
+ } else if (typeof rawWindow.resetsAt === 'number' && Number.isFinite(rawWindow.resetsAt)) {
304
+ resetsAt = rawWindow.resetsAt;
305
+ } else {
306
+ return null;
307
+ }
308
+
309
+ return { status, percent, resetsAt };
310
+ }
311
+
312
+ /**
313
+ * 正規化官方 `/inference/go/v1/usage` 回應(`usage.rolling`/`weekly`/`monthly`)。
314
+ *
315
+ * 合約要求:
316
+ * - 若明確指出未訂閱/無資格,回傳 `no-entitlement` 錯誤。
317
+ * - 空回應或缺少 `usage.{rolling, weekly, monthly}` 合約欄位者,回傳 `invalid-response`,
318
+ * 不可標記已連線,也不可繼續查 `/models`。
319
+ * - 不從未公開欄位推定方案或 Extra Usage 已關閉。
320
+ */
321
+ export function normalizeUsagePayload(data) {
322
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
323
+ throw new GoClientError('Invalid OpenCode Go usage response.', {
324
+ category: 'invalid-response',
325
+ status: 200,
326
+ retryable: false
327
+ });
328
+ }
329
+
330
+ if (
331
+ data.entitled === false
332
+ || data.subscribed === false
333
+ || data.active === false
334
+ || data.hasSubscription === false
335
+ ) {
336
+ throw new GoClientError('This workspace does not have an active OpenCode Go subscription.', {
337
+ category: 'no-entitlement',
338
+ subCategory: 'entitlement-required',
339
+ status: 200,
340
+ retryable: false
341
+ });
342
+ }
343
+
344
+ const usageObj = data.usage;
345
+ if (!usageObj || typeof usageObj !== 'object' || Array.isArray(usageObj)) {
346
+ throw new GoClientError('OpenCode Go /usage response does not match official usage contract.', {
347
+ category: 'invalid-response',
348
+ status: 200,
349
+ retryable: false
350
+ });
351
+ }
352
+
353
+ const rolling = normalizeWindow(usageObj.rolling);
354
+ const weekly = normalizeWindow(usageObj.weekly);
355
+ const monthly = normalizeWindow(usageObj.monthly);
356
+
357
+ if (!rolling || !weekly || !monthly) {
358
+ throw new GoClientError('OpenCode Go /usage response is missing required rolling, weekly, or monthly windows.', {
359
+ category: 'invalid-response',
360
+ status: 200,
361
+ retryable: false
362
+ });
363
+ }
364
+
365
+ return {
366
+ entitled: true,
367
+ windows: {
368
+ rolling,
369
+ weekly,
370
+ monthly
371
+ }
372
+ };
373
+ }
374
+
375
+ function buildCombinedSignal(callerSignal, timeoutMs) {
376
+ const limit = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : GO_REQUEST_TIMEOUT_MS;
377
+ const timeoutSignal = AbortSignal.timeout(limit);
378
+ if (!callerSignal) {
379
+ return { signal: timeoutSignal, dispose: () => {} };
380
+ }
381
+ if (typeof AbortSignal.any === 'function') {
382
+ return { signal: AbortSignal.any([callerSignal, timeoutSignal]), dispose: () => {} };
383
+ }
384
+ const controller = new AbortController();
385
+ const onAbort = () => controller.abort(callerSignal.reason);
386
+ const onTimeout = () => controller.abort(timeoutSignal.reason);
387
+ if (callerSignal.aborted) controller.abort(callerSignal.reason);
388
+ else callerSignal.addEventListener('abort', onAbort, { once: true });
389
+ timeoutSignal.addEventListener('abort', onTimeout, { once: true });
390
+ return {
391
+ signal: controller.signal,
392
+ dispose: () => {
393
+ callerSignal.removeEventListener?.('abort', onAbort);
394
+ timeoutSignal.removeEventListener?.('abort', onTimeout);
395
+ }
396
+ };
397
+ }
398
+
399
+ async function performGoGet({
400
+ url,
401
+ expectedPath,
402
+ key,
403
+ fetchFn = globalThis.fetch,
404
+ signal = undefined,
405
+ timeoutMs = GO_REQUEST_TIMEOUT_MS,
406
+ userAgent = 'opencode-next-go/1'
407
+ }) {
408
+ if (typeof key !== 'string' || !key.trim()) {
409
+ throw new GoClientError('Missing OpenCode Go API key.', {
410
+ category: 'invalid-key',
411
+ retryable: false
412
+ });
413
+ }
414
+ if (typeof fetchFn !== 'function') {
415
+ throw new GoClientError('No fetch implementation available.', {
416
+ category: 'transient',
417
+ subCategory: 'network',
418
+ retryable: true
419
+ });
420
+ }
421
+
422
+ const targetUrl = assertOfficialGoUrl(url, expectedPath);
423
+ const combined = buildCombinedSignal(signal, timeoutMs);
424
+
425
+ let res;
426
+ try {
427
+ res = await fetchFn(targetUrl, {
428
+ method: 'GET',
429
+ redirect: 'manual',
430
+ headers: {
431
+ Authorization: `Bearer ${key}`,
432
+ Accept: 'application/json',
433
+ 'User-Agent': userAgent
434
+ },
435
+ signal: combined.signal
436
+ });
437
+ } catch (err) {
438
+ if (signal?.aborted) {
439
+ throw new GoClientError('OpenCode Go request aborted.', {
440
+ category: 'aborted',
441
+ retryable: false
442
+ });
443
+ }
444
+ const isTimeout = err?.name === 'TimeoutError' || err?.name === 'AbortError';
445
+ const safeMsg = redactSecret(err?.message || 'OpenCode Go network request failed.', key);
446
+ throw new GoClientError(safeMsg, {
447
+ category: 'transient',
448
+ subCategory: isTimeout ? 'timeout' : 'network',
449
+ retryable: true
450
+ });
451
+ } finally {
452
+ combined.dispose();
453
+ }
454
+
455
+ if (res?.type === 'opaqueredirect' || res?.redirected === true || (res?.status >= 300 && res?.status < 400)) {
456
+ throw new GoClientError('OpenCode Go blocked an unexpected HTTP redirect.', {
457
+ category: 'redirect-blocked',
458
+ subCategory: 'http-redirect',
459
+ status: res?.status ?? 302,
460
+ retryable: false
461
+ });
462
+ }
463
+
464
+ if (!res?.ok) {
465
+ let rawText = '';
466
+ try {
467
+ rawText = typeof res?.text === 'function' ? await res.text() : '';
468
+ } catch {}
469
+ throw classifyGoHttpFailure(res?.status ?? 500, rawText, res?.headers, key);
470
+ }
471
+
472
+ try {
473
+ if (typeof res.json === 'function') {
474
+ return await res.json();
475
+ }
476
+ const text = typeof res.text === 'function' ? await res.text() : '';
477
+ return JSON.parse(text);
478
+ } catch (err) {
479
+ throw new GoClientError(
480
+ `Invalid JSON from OpenCode Go endpoint: ${redactSecret(err?.message || 'parse error', key)}`,
481
+ {
482
+ category: 'invalid-response',
483
+ status: res?.status ?? 200,
484
+ retryable: false
485
+ }
486
+ );
487
+ }
488
+ }
489
+
490
+ export async function fetchGoUsage({
491
+ key,
492
+ fetchFn = globalThis.fetch,
493
+ signal = undefined,
494
+ timeoutMs = GO_REQUEST_TIMEOUT_MS,
495
+ userAgent = 'opencode-next-go/1',
496
+ url = OPENCODE_GO_USAGE_URL
497
+ } = {}) {
498
+ const payload = await performGoGet({
499
+ url,
500
+ expectedPath: '/inference/go/v1/usage',
501
+ key,
502
+ fetchFn,
503
+ signal,
504
+ timeoutMs,
505
+ userAgent
506
+ });
507
+ return normalizeUsagePayload(payload);
508
+ }
509
+
510
+ export async function fetchGoModels({
511
+ key,
512
+ fetchFn = globalThis.fetch,
513
+ signal = undefined,
514
+ timeoutMs = GO_REQUEST_TIMEOUT_MS,
515
+ userAgent = 'opencode-next-go/1',
516
+ url = OPENCODE_GO_MODELS_URL
517
+ } = {}) {
518
+ const payload = await performGoGet({
519
+ url,
520
+ expectedPath: '/inference/go/v1/models',
521
+ key,
522
+ fetchFn,
523
+ signal,
524
+ timeoutMs,
525
+ userAgent
526
+ });
527
+ try {
528
+ return normalizeGoModelsPayload(payload);
529
+ } catch (err) {
530
+ throw new GoClientError(
531
+ redactSecret(err?.message || 'Invalid OpenCode Go models payload.', key),
532
+ {
533
+ category: 'invalid-response',
534
+ status: 200,
535
+ retryable: false
536
+ }
537
+ );
538
+ }
539
+ }
540
+
541
+ /**
542
+ * 嚴格驗證 DSH 提供的 `options.sessionId`。
543
+ * 不使用 `session.id`、`conversationId`、首則訊息雜湊或隨機 UUID 代替。
544
+ */
545
+ export function validateGoSessionId(options) {
546
+ const raw = options?.sessionId;
547
+ if (typeof raw !== 'string') {
548
+ throw new GoClientError('OpenCode Go requires a valid DSH sessionId; missing sessionId.', {
549
+ category: 'invalid-request',
550
+ subCategory: 'missing-session-id',
551
+ retryable: false
552
+ });
553
+ }
554
+ const sid = raw.trim();
555
+ if (!sid || sid.length > 256 || /[\x00-\x1f\x7f\s]/.test(sid)) {
556
+ throw new GoClientError('OpenCode Go requires a valid DSH sessionId; invalid sessionId.', {
557
+ category: 'invalid-request',
558
+ subCategory: 'missing-session-id',
559
+ retryable: false
560
+ });
561
+ }
562
+ return sid;
563
+ }
564
+
565
+ /**
566
+ * 發送單次 OpenCode Go Chat Completions SSE 請求(不重送、不跟隨重新導向)。
567
+ */
568
+ export async function postGoChatCompletions({
569
+ key,
570
+ sessionId,
571
+ payload,
572
+ fetchFn = globalThis.fetch,
573
+ signal = undefined,
574
+ userAgent = 'opencode-next-go/1',
575
+ url = OPENCODE_GO_CHAT_URL
576
+ } = {}) {
577
+ if (typeof key !== 'string' || !key.trim()) {
578
+ throw new GoClientError('Missing OpenCode Go API key.', {
579
+ category: 'invalid-key',
580
+ retryable: false
581
+ });
582
+ }
583
+ const validSessionId = validateGoSessionId({ sessionId });
584
+ if (typeof fetchFn !== 'function') {
585
+ throw new GoClientError('No fetch implementation available.', {
586
+ category: 'transient',
587
+ subCategory: 'network',
588
+ retryable: false
589
+ });
590
+ }
591
+
592
+ const targetUrl = assertOfficialGoUrl(url, '/inference/go/openai/v1/chat/completions');
593
+
594
+ let res;
595
+ try {
596
+ res = await fetchFn(targetUrl, {
597
+ method: 'POST',
598
+ redirect: 'manual',
599
+ headers: {
600
+ Authorization: `Bearer ${key}`,
601
+ 'Content-Type': 'application/json',
602
+ Accept: 'text/event-stream',
603
+ 'User-Agent': userAgent,
604
+ 'x-opencode-session': validSessionId
605
+ },
606
+ body: JSON.stringify(payload),
607
+ signal
608
+ });
609
+ } catch (err) {
610
+ if (signal?.aborted) {
611
+ throw err;
612
+ }
613
+ const safeMsg = redactSecret(err?.message || 'OpenCode Go inference transport failed.', key);
614
+ throw new GoClientError(safeMsg, {
615
+ category: 'transient',
616
+ subCategory: 'network',
617
+ retryable: false
618
+ });
619
+ }
620
+
621
+ if (res?.type === 'opaqueredirect' || res?.redirected === true || (res?.status >= 300 && res?.status < 400)) {
622
+ throw new GoClientError('OpenCode Go blocked an unexpected HTTP redirect.', {
623
+ category: 'redirect-blocked',
624
+ subCategory: 'http-redirect',
625
+ status: res?.status ?? 302,
626
+ retryable: false
627
+ });
628
+ }
629
+
630
+ if (!res?.ok) {
631
+ let rawText = '';
632
+ try {
633
+ rawText = typeof res?.text === 'function' ? await res.text() : '';
634
+ } catch {}
635
+ throw classifyGoHttpFailure(res?.status ?? 500, rawText, res?.headers, key);
636
+ }
637
+
638
+ if (!res.body || typeof res.body.getReader !== 'function') {
639
+ throw new GoClientError('OpenCode Go inference response did not provide an SSE body.', {
640
+ category: 'invalid-response',
641
+ status: res?.status ?? 200,
642
+ retryable: false
643
+ });
644
+ }
645
+
646
+ return res;
647
+ }