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.
package/lib/store.js ADDED
@@ -0,0 +1,434 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { createRequire } from 'node:module';
6
+
7
+ const require = createRequire(import.meta.url);
8
+
9
+ function getHomeDir() {
10
+ return os.homedir();
11
+ }
12
+
13
+ /**
14
+ * Path of the credential file this plugin writes itself.
15
+ *
16
+ * Exposed so the web API can report and remove exactly the file this plugin
17
+ * owns, without re-deriving `~/.dsh/...` from a URL (which would break the
18
+ * moment `lib/` is bundled to another depth).
19
+ */
20
+ export function defaultDshTokenPath() {
21
+ return path.join(getHomeDir(), '.dsh', 'opencode-next.token.json');
22
+ }
23
+
24
+ export function defaultAccountsPath() {
25
+ return path.join(getHomeDir(), '.dsh', 'opencode-next.accounts.json');
26
+ }
27
+
28
+ /** 自動切換帳號的設定檔(只有一個布林值,不含任何憑證)。 */
29
+ export function defaultAutoSwitchPath() {
30
+ return path.join(getHomeDir(), '.dsh', 'opencode-next.autoswitch.json');
31
+ }
32
+
33
+ /**
34
+ * 自動切換的持久化開關。
35
+ *
36
+ * 刻意只存 `enabled`:免費方案沒有可信的流量額度訊號,任何「帳號健康度」
37
+ * 持久化都只會變成下一次誤判的依據。真正的觸發條件由 adapter 每次請求
38
+ * 重新證實(同一帳號 refresh 後仍 401),不從檔案推論。
39
+ */
40
+ export class AutoSwitchStore {
41
+ #path;
42
+ #defaultEnabled;
43
+ #state;
44
+ #loaded = false;
45
+
46
+ constructor({ path: customPath, defaultEnabled = false } = {}) {
47
+ this.#path = customPath || defaultAutoSwitchPath();
48
+ this.#defaultEnabled = defaultEnabled === true;
49
+ this.#state = { enabled: this.#defaultEnabled };
50
+ }
51
+
52
+ #load() {
53
+ if (this.#loaded) return;
54
+ this.#loaded = true;
55
+ try {
56
+ if (!fs.existsSync(this.#path)) return;
57
+ const parsed = JSON.parse(fs.readFileSync(this.#path, 'utf8'));
58
+ if (!parsed || typeof parsed !== 'object') return;
59
+ this.#state = { enabled: parsed.enabled === true };
60
+ } catch {
61
+ // 壞掉的設定檔等同沒設定過;自動切換寧可關著,也不要因讀檔失敗而開啟。
62
+ this.#state = { enabled: this.#defaultEnabled };
63
+ }
64
+ }
65
+
66
+ get() {
67
+ this.#load();
68
+ return { enabled: this.#state.enabled };
69
+ }
70
+
71
+ set(patch = {}) {
72
+ this.#load();
73
+ const enabled =
74
+ patch && patch.enabled !== undefined ? patch.enabled === true : this.#state.enabled;
75
+ this.#state = { enabled };
76
+ try {
77
+ const dir = path.dirname(this.#path);
78
+ fs.mkdirSync(dir, { recursive: true });
79
+ const temporary = `${this.#path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
80
+ try {
81
+ fs.writeFileSync(temporary, JSON.stringify({ version: 1, enabled }, null, 2), {
82
+ encoding: 'utf8',
83
+ mode: 0o600
84
+ });
85
+ fs.renameSync(temporary, this.#path);
86
+ } finally {
87
+ try {
88
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
89
+ } catch {}
90
+ }
91
+ } catch {
92
+ // 寫不進去時仍套用記憶體狀態,讓同一個 process 內的行為一致;
93
+ // 下次啟動會回到預設值。
94
+ }
95
+ return this.get();
96
+ }
97
+ }
98
+
99
+ export function loadAccounts(customPath) {
100
+ const file = customPath || defaultAccountsPath();
101
+ try {
102
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
103
+ if (data?.version !== 1 || !Array.isArray(data.accounts) || data.accounts.length === 0) return null;
104
+ if (data.accounts.some((account) => !account || typeof account.id !== 'string' || typeof account.access !== 'string')) return null;
105
+ return data;
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * 把一組 OAuth 憑證追加進帳號清單,並設為目前帳號。
113
+ *
114
+ * CLI 登入原本只寫舊版單一憑證檔。帳號清單存在時,解析順序會先讀它,
115
+ * 那次登入就等於沒發生。這裡在清單已存在時追加;清單不存在就建立。
116
+ * 相同 access token 不重複新增,只更新續期資料並切過去。
117
+ * 檔案存在但讀不出可用清單時拒絕覆寫,避免把壞掉的檔蓋成只剩新帳號。
118
+ */
119
+ export function appendAccountCredential(cred, { accountsPath, label } = {}) {
120
+ if (!isOAuthAccessToken(cred?.access)) {
121
+ throw new Error('An OpenCode OAuth token is required');
122
+ }
123
+ const target = accountsPath || defaultAccountsPath();
124
+ let existing = null;
125
+ if (fs.existsSync(target)) {
126
+ existing = loadAccounts(target);
127
+ if (!existing) {
128
+ throw new Error('accounts file exists but is not a usable account list; refusing to overwrite it');
129
+ }
130
+ }
131
+ const data = existing || { version: 1, activeId: null, accounts: [] };
132
+ const orgId = typeof cred.orgId === 'string' ? cred.orgId.trim() : '';
133
+ const match = data.accounts.find((account) => account.access === cred.access);
134
+ if (match) {
135
+ if (cred.refresh) match.refresh = cred.refresh;
136
+ if (cred.expires) match.expires = cred.expires;
137
+ if (orgId) match.orgId = orgId;
138
+ match.lastUsedAt = Date.now();
139
+ data.activeId = match.id;
140
+ saveAccounts(data, target);
141
+ return { path: target, accountId: match.id, created: false, alreadyPresent: true };
142
+ }
143
+
144
+ let id;
145
+ do {
146
+ id = `acc-${randomBytes(4).toString('hex')}`;
147
+ } while (data.accounts.some((account) => account.id === id));
148
+ const account = {
149
+ id,
150
+ label: String(label || `帳號 ${data.accounts.length + 1}`).trim() || `帳號 ${data.accounts.length + 1}`,
151
+ access: cred.access,
152
+ refresh: cred.refresh,
153
+ expires: cred.expires || 0,
154
+ addedAt: Date.now(),
155
+ lastUsedAt: Date.now(),
156
+ ...(orgId ? { orgId } : {})
157
+ };
158
+ data.accounts.push(account);
159
+ data.activeId = id;
160
+ saveAccounts(data, target);
161
+ return { path: target, accountId: id, created: !existing, alreadyPresent: false };
162
+ }
163
+
164
+ export function saveAccounts(data, customPath) {
165
+ if (!data || data.version !== 1 || !Array.isArray(data.accounts)) throw new TypeError('Invalid accounts data');
166
+ const target = customPath || defaultAccountsPath();
167
+ const dir = path.dirname(target);
168
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
169
+ const temporary = `${target}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
170
+ try {
171
+ fs.writeFileSync(temporary, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 });
172
+ fs.renameSync(temporary, target);
173
+ } finally {
174
+ try { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); } catch {}
175
+ }
176
+ return target;
177
+ }
178
+
179
+ function credentialFor(account) {
180
+ if (!account || !isOAuthAccessToken(account.access)) return null;
181
+ return {
182
+ access: account.access,
183
+ refresh: account.refresh,
184
+ expires: account.expires || 0,
185
+ source: 'accounts',
186
+ accountId: account.id,
187
+ label: account.label,
188
+ ...(account.orgId ? { orgId: account.orgId } : {})
189
+ };
190
+ }
191
+
192
+ export function resolveFromAccounts(customPath) {
193
+ const data = loadAccounts(customPath);
194
+ return data ? credentialFor(data.accounts.find((a) => a.id === data.activeId)) : null;
195
+ }
196
+
197
+ export function resolveAccountById(id, customPath) {
198
+ const data = loadAccounts(customPath);
199
+ return data ? credentialFor(data.accounts.find((a) => a.id === id)) : null;
200
+ }
201
+
202
+ /**
203
+ * Lightweight resolver for local OpenCode organization ID matching a specific token if provided.
204
+ */
205
+ export function resolveLocalOrgId(accessToken) {
206
+ const home = getHomeDir();
207
+ const dbPath = path.join(home, '.local', 'share', 'opencode', 'opencode.db');
208
+ if (!fs.existsSync(dbPath)) return null;
209
+
210
+ try {
211
+ const { DatabaseSync } = require('node:sqlite');
212
+ const db = new DatabaseSync(dbPath, { readOnly: true });
213
+ let row = null;
214
+ if (typeof accessToken === 'string' && accessToken.startsWith('st_')) {
215
+ row = db.prepare(
216
+ "SELECT value FROM credential WHERE (integration_id = 'opencode' OR connector_id = 'opencode') AND value LIKE ? LIMIT 1"
217
+ ).get(`%"${accessToken}"%`);
218
+ }
219
+ if (!row) {
220
+ row = db.prepare(
221
+ "SELECT value FROM credential WHERE integration_id = 'opencode' OR connector_id = 'opencode' ORDER BY active DESC, time_updated DESC LIMIT 1"
222
+ ).get();
223
+ }
224
+ db.close();
225
+ if (!row?.value) return null;
226
+ const v = JSON.parse(row.value);
227
+ return v.metadata?.orgID || v.metadata?.orgId || null;
228
+ } catch {
229
+ return null;
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Resolve OpenCode OAuth credentials from local OpenCode Desktop database.
235
+ * Returns { access, refresh, expires, source: 'local-db' } or null.
236
+ */
237
+ export function resolveFromLocalOpenCodeDb() {
238
+ const home = getHomeDir();
239
+ const dbPath = path.join(home, '.local', 'share', 'opencode', 'opencode.db');
240
+
241
+ if (!fs.existsSync(dbPath)) return null;
242
+
243
+ try {
244
+ // Try native node:sqlite DatabaseSync first
245
+ const { DatabaseSync } = require('node:sqlite');
246
+ const db = new DatabaseSync(dbPath, { readOnly: true });
247
+
248
+ // OpenCode keeps several opencode credentials side by side: an OAuth
249
+ // "Personal" login plus API-key entries. Its `active` flag can point at an
250
+ // API key (which the free lane always rejects), so `active` is only a
251
+ // tie-breaker here — an OAuth token always wins.
252
+ const rows = db.prepare(
253
+ "SELECT value, active, time_updated FROM credential WHERE integration_id = 'opencode' OR connector_id = 'opencode' ORDER BY time_updated DESC"
254
+ ).all();
255
+
256
+ db.close();
257
+
258
+ const parsed = [];
259
+ for (const row of rows) {
260
+ if (!row?.value) continue;
261
+ try {
262
+ const v = JSON.parse(row.value);
263
+ const access = v.access || v.access_token;
264
+ if (!access) continue;
265
+ const orgId = v.metadata?.orgID || v.metadata?.orgId || null;
266
+ parsed.push({
267
+ access,
268
+ refresh: v.refresh || v.refresh_token,
269
+ expires: v.expires || v.expires_at || 0,
270
+ orgId,
271
+ active: row.active === 1,
272
+ oauth: isOAuthAccessToken(access),
273
+ updated: row.time_updated ?? 0
274
+ });
275
+ } catch {
276
+ // Skip malformed rows.
277
+ }
278
+ }
279
+
280
+ // 1) active OAuth, 2) any OAuth, 3) active key, 4) newest key.
281
+ const chosen =
282
+ parsed.find((c) => c.oauth && c.active) ??
283
+ parsed.find((c) => c.oauth) ??
284
+ parsed.find((c) => c.active) ??
285
+ parsed[0];
286
+
287
+ if (chosen) {
288
+ return {
289
+ access: chosen.access,
290
+ refresh: chosen.refresh,
291
+ expires: chosen.expires,
292
+ orgId: chosen.orgId || null,
293
+ source: 'local-db'
294
+ };
295
+ }
296
+ } catch (err) {
297
+ // If node:sqlite is unavailable or fails, try fallback
298
+ }
299
+
300
+ return null;
301
+ }
302
+
303
+ /**
304
+ * Resolve OpenCode credentials from local auth.json.
305
+ */
306
+ export function resolveFromLocalAuthJson() {
307
+ const home = getHomeDir();
308
+ const authPath = path.join(home, '.local', 'share', 'opencode', 'auth.json');
309
+ if (!fs.existsSync(authPath)) return null;
310
+
311
+ try {
312
+ const raw = fs.readFileSync(authPath, 'utf8');
313
+ const data = JSON.parse(raw);
314
+ const opencode = data.opencode;
315
+ if (!opencode) return null;
316
+
317
+ if (typeof opencode === 'string') {
318
+ return { access: opencode, source: 'local-auth-json' };
319
+ }
320
+ if (opencode.key) {
321
+ return { access: opencode.key, source: 'local-auth-json' };
322
+ }
323
+ if (opencode.access || opencode.access_token) {
324
+ return {
325
+ access: opencode.access || opencode.access_token,
326
+ refresh: opencode.refresh || opencode.refresh_token,
327
+ source: 'local-auth-json'
328
+ };
329
+ }
330
+ } catch {}
331
+
332
+ return null;
333
+ }
334
+
335
+ /**
336
+ * Resolve credentials saved by DSH OAuth flow (~/.dsh/opencode-next.token.json).
337
+ */
338
+ export function resolveFromDshTokenFile(customPath) {
339
+ const tokenPath = customPath || defaultDshTokenPath();
340
+ if (!fs.existsSync(tokenPath)) return null;
341
+
342
+ try {
343
+ const raw = fs.readFileSync(tokenPath, 'utf8');
344
+ const data = JSON.parse(raw);
345
+ if (data.access || data.access_token) {
346
+ return {
347
+ access: data.access || data.access_token,
348
+ refresh: data.refresh || data.refresh_token,
349
+ expires: data.expires || data.expires_in || 0,
350
+ source: 'dsh-token-file',
351
+ ...(typeof data.orgId === 'string' && data.orgId.trim() ? { orgId: data.orgId.trim() } : {})
352
+ };
353
+ }
354
+ } catch {}
355
+
356
+ return null;
357
+ }
358
+
359
+ /**
360
+ * Save credentials obtained via DSH Device OAuth flow.
361
+ */
362
+ export function saveDshTokenFile(tokenData, customPath) {
363
+ const targetPath = customPath || path.join(getHomeDir(), '.dsh', 'opencode-next.token.json');
364
+ const dir = path.dirname(targetPath);
365
+ if (!fs.existsSync(dir)) {
366
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
367
+ }
368
+
369
+ const orgId = typeof tokenData.orgId === 'string' ? tokenData.orgId.trim() : '';
370
+ const payload = {
371
+ access: tokenData.access || tokenData.access_token,
372
+ refresh: tokenData.refresh || tokenData.refresh_token,
373
+ expires: tokenData.expires || tokenData.expires_in || 0,
374
+ updatedAt: Date.now(),
375
+ ...(orgId ? { orgId } : {})
376
+ };
377
+
378
+ const temporary = `${targetPath}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
379
+ try {
380
+ fs.writeFileSync(temporary, JSON.stringify(payload, null, 2), { encoding: 'utf8', mode: 0o600 });
381
+ fs.renameSync(temporary, targetPath);
382
+ } finally {
383
+ try { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); } catch {}
384
+ }
385
+ return targetPath;
386
+ }
387
+
388
+ /**
389
+ * Master credential resolver prioritizing:
390
+ * 1. Explicit DSH token file (~/.dsh/opencode-next.token.json)
391
+ * 2. Local OpenCode Desktop DB (~/.local/share/opencode/opencode.db)
392
+ * 3. Local OpenCode auth.json (~/.local/share/opencode/auth.json)
393
+ *
394
+ * Only OAuth access tokens (`st_` prefix) are accepted. An `sk_` API key is
395
+ * rejected here on purpose: OpenCode's free lane answers `403 FreeTierError`
396
+ * for API-key bearer auth, so falling back to one produces a misleading error
397
+ * that looks like a plugin defect instead of a missing login.
398
+ */
399
+ export function resolveCredential(customPath, customAccountsPath) {
400
+ const candidates = [
401
+ resolveFromAccounts(customAccountsPath),
402
+ resolveFromDshTokenFile(customPath),
403
+ resolveFromLocalOpenCodeDb(),
404
+ resolveFromLocalAuthJson()
405
+ ];
406
+ for (const candidate of candidates) {
407
+ if (candidate?.access && isOAuthAccessToken(candidate.access)) return candidate;
408
+ }
409
+ // No OAuth token anywhere. Keep a non-OAuth candidate only for diagnostics.
410
+ return null;
411
+ }
412
+
413
+ /** An OpenCode OAuth access token; API keys use the `sk-` prefix. */
414
+ export function isOAuthAccessToken(token) {
415
+ return typeof token === 'string' && token.startsWith('st_');
416
+ }
417
+
418
+ /**
419
+ * Explain why no usable credential was found, for the adapter error message.
420
+ */
421
+ export function describeMissingCredential() {
422
+ const authJson = resolveFromLocalAuthJson();
423
+ if (authJson?.access && !isOAuthAccessToken(authJson.access)) {
424
+ return (
425
+ 'OpenCode Console is signed out: the only stored credential is an API key ' +
426
+ `(${authJson.access.slice(0, 8)}...), and the free lane rejects API keys. ` +
427
+ 'Sign in again in OpenCode Desktop, or run `opencode-next-login` for a browser login.'
428
+ );
429
+ }
430
+ return (
431
+ 'No OpenCode OAuth credential found. Sign in with OpenCode Desktop, ' +
432
+ 'or run `opencode-next-login` to authorize in a browser.'
433
+ );
434
+ }
package/lib/stream.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Maps OpenAI finish_reason to a DSH FinishReason object.
3
+ *
4
+ * DSH's `StreamChunk` finish variant carries `reason: FinishReason`, a
5
+ * discriminated object (`{ kind: 'stop' | 'tool-calls' | 'max-tokens' | ... }`),
6
+ * not a bare string. Returning a string leaves `finish.kind` undefined, so the
7
+ * agent loop cannot recognize truncation or error terminals.
8
+ */
9
+ export function mapFinishReason(reason) {
10
+ switch (reason) {
11
+ case 'tool_calls':
12
+ case 'function_call':
13
+ return { kind: 'tool-calls' };
14
+ case 'length':
15
+ return { kind: 'max-tokens' };
16
+ case 'content_filter':
17
+ return { kind: 'stop' };
18
+ case 'stop':
19
+ default:
20
+ return { kind: 'stop' };
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Transforms an OpenAI Server-Sent Events (SSE) readable stream into DSH StreamChunks.
26
+ *
27
+ * Handles `reasoning_content`, `content`, `tool_calls`, `usage`, and block
28
+ * boundaries. Upstream `tool_calls[].index` is mapped onto DSH block indexes
29
+ * once, so a tool-call block opened at block index N keeps receiving deltas
30
+ * even when reasoning/text blocks were streamed before it.
31
+ */
32
+ export async function* parseOpenAiSseStream(responseBody, _options = {}) {
33
+ const reader = responseBody.getReader();
34
+ const decoder = new TextDecoder('utf8');
35
+
36
+ let buffer = '';
37
+
38
+ /** Completed blocks, indexed by DSH block index (kept dense). */
39
+ const blocks = [];
40
+
41
+ /** Next DSH block index to hand out. */
42
+ let nextBlockIndex = 0;
43
+
44
+ /** The open text/reasoning block, if any. */
45
+ let openTextBlock = null; // { index, type: 'text' | 'reasoning', text }
46
+
47
+ /** Open tool-call blocks keyed by DSH block index. */
48
+ const openToolBlocks = new Map(); // blockIndex -> { blockIndex, id, name, arguments, provisionalId }
49
+
50
+ /** Upstream tool_calls[].index -> open tool-call block accumulator. */
51
+ const toolBlocksByUpstreamIndex = new Map();
52
+
53
+ let finishReason = null;
54
+ let usage = null;
55
+
56
+ /** Close the open text/reasoning block; returns the block-end event or null. */
57
+ function closeTextBlock() {
58
+ if (openTextBlock === null) return null;
59
+ const { index, type, text } = openTextBlock;
60
+ openTextBlock = null;
61
+ const block = type === 'reasoning' ? { type: 'reasoning', text } : { type: 'text', text };
62
+ blocks[index] = block;
63
+ return { type: 'block-end', index, block };
64
+ }
65
+
66
+ /** Close every open tool-call block, in block order. */
67
+ function closeToolBlocks() {
68
+ const events = [];
69
+ const accumulators = [...openToolBlocks.values()].sort((a, b) => a.blockIndex - b.blockIndex);
70
+ openToolBlocks.clear();
71
+ toolBlocksByUpstreamIndex.clear();
72
+ for (const acc of accumulators) {
73
+ const block = {
74
+ type: 'tool-call',
75
+ id: acc.id,
76
+ name: acc.name,
77
+ arguments: acc.arguments
78
+ };
79
+ blocks[acc.blockIndex] = block;
80
+ events.push({ type: 'block-end', index: acc.blockIndex, block });
81
+ }
82
+ return events;
83
+ }
84
+
85
+ /** Close everything still open (used at stream end). */
86
+ function closeAllBlocks() {
87
+ const events = [];
88
+ const textEvent = closeTextBlock();
89
+ if (textEvent !== null) events.push(textEvent);
90
+ events.push(...closeToolBlocks());
91
+ return events;
92
+ }
93
+
94
+ /**
95
+ * Switch to a text/reasoning block. Every open tool-call block is closed
96
+ * first: text following a tool call means that call is finished, and a later
97
+ * tool_calls delta reusing the same upstream index then opens a new block
98
+ * instead of appending to the closed one.
99
+ */
100
+ function openTextStream(type) {
101
+ const events = [];
102
+ if (openTextBlock !== null && openTextBlock.type === type) return events;
103
+ const textEvent = closeTextBlock();
104
+ if (textEvent !== null) events.push(textEvent);
105
+ events.push(...closeToolBlocks());
106
+ const index = nextBlockIndex++;
107
+ openTextBlock = { index, type, text: '' };
108
+ events.push({ type: 'block-start', index, blockType: type });
109
+ return events;
110
+ }
111
+
112
+ try {
113
+ while (true) {
114
+ const { done, value } = await reader.read();
115
+ if (done) break;
116
+
117
+ buffer += decoder.decode(value, { stream: true });
118
+ const lines = buffer.split('\n');
119
+ buffer = lines.pop() || ''; // Keep the incomplete trailing line
120
+
121
+ for (const rawLine of lines) {
122
+ const line = rawLine.trim();
123
+ if (!line || line.startsWith(':')) continue; // SSE comments / keep-alive pings
124
+ if (line === 'data: [DONE]') continue;
125
+ if (!line.startsWith('data: ')) continue;
126
+
127
+ const jsonStr = line.slice(6);
128
+ let chunk;
129
+ try {
130
+ chunk = JSON.parse(jsonStr);
131
+ } catch {
132
+ continue;
133
+ }
134
+
135
+ if (chunk.usage) {
136
+ const inputTokens = chunk.usage.prompt_tokens || 0;
137
+ const outputTokens = chunk.usage.completion_tokens || 0;
138
+ const totalTokens = chunk.usage.total_tokens || inputTokens + outputTokens;
139
+ const reasoningTokens = chunk.usage.completion_tokens_details?.reasoning_tokens;
140
+ if (_options.includeGoBilling === true) {
141
+ const cost = typeof chunk.usage.cost === 'number' && Number.isFinite(chunk.usage.cost)
142
+ ? chunk.usage.cost
143
+ : null;
144
+ const rawSource = chunk.usage.opencode?.billing_source;
145
+ const billingSource = typeof rawSource === 'string' && rawSource.trim()
146
+ ? rawSource.trim()
147
+ : null;
148
+ const rawAllowance = chunk.usage.opencode?.allowance;
149
+ const allowance = typeof rawAllowance === 'number' && Number.isFinite(rawAllowance)
150
+ ? rawAllowance
151
+ : null;
152
+ usage = {
153
+ inputTokens,
154
+ outputTokens,
155
+ totalTokens,
156
+ ...(typeof reasoningTokens === 'number' && reasoningTokens > 0 ? { reasoningTokens } : {}),
157
+ cost,
158
+ opencode: {
159
+ billing_source: billingSource,
160
+ allowance
161
+ }
162
+ };
163
+ } else {
164
+ usage = {
165
+ inputTokens,
166
+ outputTokens,
167
+ totalTokens,
168
+ ...(typeof reasoningTokens === 'number' && reasoningTokens > 0 ? { reasoningTokens } : {})
169
+ };
170
+ }
171
+ }
172
+
173
+ const choice = chunk.choices?.[0];
174
+ if (!choice) continue;
175
+
176
+ if (choice.finish_reason) finishReason = choice.finish_reason;
177
+
178
+ const delta = choice.delta;
179
+ if (!delta) continue;
180
+
181
+ // 1. Reasoning content (thinking)
182
+ const reasoningDelta = delta.reasoning_content || delta.reasoning || delta.thought;
183
+ if (typeof reasoningDelta === 'string' && reasoningDelta.length > 0) {
184
+ for (const event of openTextStream('reasoning')) yield event;
185
+ openTextBlock.text += reasoningDelta;
186
+ yield { type: 'reasoning-delta', index: openTextBlock.index, text: reasoningDelta };
187
+ }
188
+
189
+ // 2. Standard text content
190
+ const contentDelta = delta.content;
191
+ if (typeof contentDelta === 'string' && contentDelta.length > 0) {
192
+ for (const event of openTextStream('text')) yield event;
193
+ openTextBlock.text += contentDelta;
194
+ yield { type: 'text-delta', index: openTextBlock.index, text: contentDelta };
195
+ }
196
+
197
+ // 3. Tool calls
198
+ if (Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0) {
199
+ for (const tc of delta.tool_calls) {
200
+ const upstreamIndex = typeof tc?.index === 'number' ? tc.index : 0;
201
+ let acc = toolBlocksByUpstreamIndex.get(upstreamIndex);
202
+
203
+ if (acc === undefined) {
204
+ // A tool call ends any open text/reasoning block, but never another
205
+ // tool-call block: parallel tool calls stay open until the stream ends.
206
+ const textEvent = closeTextBlock();
207
+ if (textEvent !== null) yield textEvent;
208
+
209
+ const blockIndex = nextBlockIndex++;
210
+ const upstreamId = typeof tc?.id === 'string' && tc.id.length > 0 ? tc.id : '';
211
+ acc = {
212
+ blockIndex,
213
+ id: upstreamId || `call_${blockIndex}`,
214
+ provisionalId: upstreamId === '',
215
+ name: '',
216
+ arguments: ''
217
+ };
218
+ toolBlocksByUpstreamIndex.set(upstreamIndex, acc);
219
+ openToolBlocks.set(blockIndex, acc);
220
+
221
+ yield { type: 'block-start', index: blockIndex, blockType: 'tool-call' };
222
+ }
223
+
224
+ if (typeof tc.id === 'string' && tc.id.length > 0 && acc.provisionalId) {
225
+ acc.id = tc.id;
226
+ acc.provisionalId = false;
227
+ }
228
+ if (typeof tc.function?.name === 'string' && tc.function.name.length > 0 && acc.name === '') {
229
+ const rawName = tc.function.name;
230
+ acc.name = typeof _options.resolveToolName === 'function'
231
+ ? _options.resolveToolName(rawName)
232
+ : rawName;
233
+ }
234
+
235
+ const argDelta = typeof tc.function?.arguments === 'string' ? tc.function.arguments : '';
236
+ if (argDelta.length > 0) acc.arguments += argDelta;
237
+
238
+ yield {
239
+ type: 'tool-call-delta',
240
+ index: acc.blockIndex,
241
+ id: acc.id,
242
+ ...(acc.name !== '' ? { name: acc.name } : {}),
243
+ argumentsDelta: argDelta
244
+ };
245
+ }
246
+ }
247
+ }
248
+ }
249
+ } finally {
250
+ try {
251
+ reader.releaseLock();
252
+ } catch {
253
+ /* the body may already be errored or closed */
254
+ }
255
+ }
256
+
257
+ // Only a normally completed stream emits the terminal records; an aborted or
258
+ // errored stream must surface its error instead of a synthetic finish.
259
+ for (const event of closeAllBlocks()) yield event;
260
+
261
+ if (usage !== null) yield { type: 'usage', usage };
262
+
263
+ const hasToolCalls = blocks.some((block) => block?.type === 'tool-call');
264
+ const terminalReason = finishReason !== null ? finishReason : hasToolCalls ? 'tool_calls' : 'stop';
265
+
266
+ yield {
267
+ type: 'finish',
268
+ reason: mapFinishReason(terminalReason),
269
+ replayState: { blocks }
270
+ };
271
+ }