@cortexkit/opencode-anthropic-auth 1.1.2 → 1.2.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.
package/dist/index.js CHANGED
@@ -1,1027 +1,5 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { authorize, buildClaudeQuotaSummary, buildFallbackQuotaSummaries, buildRefreshOperationError, CACHE_1H_COMMAND_NAME, CACHE_KEEP_EXTENDED_TTL_BETA, CacheKeepManager, CLAUDE_CACHE_KEEP_COMMAND_NAME, CLAUDE_DUMP_COMMAND_NAME, CLAUDE_FAST_COMMAND_NAME, CLAUDE_QUOTAS_COMMAND_NAME, ClaudeOAuthRefreshError, exchange, executeCache1hCommand, executeCacheKeepCommand, executeDumpCommand, executeFastModeCommand, FallbackAccountManager, fetchOAuthQuotaSnapshot, formatRefreshBackoffMessage, getCache1hMode, getCache1hPersistentMode, getCacheKeepWindow, getQuotaCheckIntervalMs, getQuotaNextRefreshAt, getRelayConfig, hashRefreshToken, isCache1hEnabled, isCache1hPersistentlyEnabled, isCacheKeepHybridActive, isCacheKeepPersistentlyEnabled, isDumpPersistentlyEnabled, isFastModeEnabled, isFastModePersistentlyEnabled, isFastModeSupportedModel, loadAccounts, log, mergeAnthropicBetas, parseCache1hCommandAction, parseCacheKeepCommandAction, parseDumpCommandAction, parseFastModeCommandAction, quotaSnapshotPassesPolicy, refreshBackoffActive, refreshClaudeOAuthToken, resolveClaudeCodeIdentity, saveAccounts, sendViaRelay, setCache1hPersistentEnabled, setCache1hPersistentMode, setCache1hState, setCacheKeepPersistentEnabled, setCacheKeepPersistentWindow, setDumpEnabled, setDumpPersistentEnabled, setFastModeEnabled, setFastModePersistentEnabled, shouldFallbackStatus, } from '@cortexkit/anthropic-auth-core';
3
- import { resolvePromptContext } from "./prompt-context.js";
4
- import { addFastModeBetaHeader, createStrippedStream, isInsecure, mergeHeaders, rewriteRequestBody, rewriteUrl, setOAuthHeaders, } from "./transform.js";
5
- const HANDLED_SENTINEL = '__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__';
6
- const MAIN_AUTH_REFRESH_TICK_MS = 60_000;
7
- const DEFAULT_MAIN_REFRESH_BEFORE_EXPIRY_MINUTES = 30;
8
- let nextPerfRequestId = 1;
9
- let eventLoopLagMonitorStarted = false;
10
- function perfLoggingEnabled() {
11
- return process.env.OPENCODE_ANTHROPIC_AUTH_PERF === '1';
12
- }
13
- function nowMs() {
14
- return performance.now();
15
- }
16
- function roundMs(value) {
17
- return Math.round(value * 10) / 10;
18
- }
19
- function startEventLoopLagMonitor() {
20
- if (eventLoopLagMonitorStarted ||
21
- process.env.NODE_ENV === 'test' ||
22
- !perfLoggingEnabled()) {
23
- return;
24
- }
25
- eventLoopLagMonitorStarted = true;
26
- const intervalMs = 100;
27
- const thresholdMs = 250;
28
- let expected = nowMs() + intervalMs;
29
- setInterval(() => {
30
- const current = nowMs();
31
- const lag = current - expected;
32
- expected = current + intervalMs;
33
- if (lag < thresholdMs)
34
- return;
35
- log('[perf] opencode event_loop_lag', {
36
- lagMs: roundMs(lag),
37
- thresholdMs,
38
- });
39
- }, intervalMs).unref?.();
40
- }
41
- function createPerfTrace(data) {
42
- const start = nowMs();
43
- const trace = {
44
- requestId: String(nextPerfRequestId++),
45
- start,
46
- last: start,
47
- mark(stage, stageData) {
48
- const current = nowMs();
49
- if (perfLoggingEnabled()) {
50
- log('[perf] opencode request stage', {
51
- requestId: trace.requestId,
52
- stage,
53
- deltaMs: roundMs(current - trace.last),
54
- totalMs: roundMs(current - trace.start),
55
- ...stageData,
56
- });
57
- }
58
- trace.last = current;
59
- },
60
- done(stage, stageData) {
61
- const current = nowMs();
62
- if (perfLoggingEnabled()) {
63
- log('[perf] opencode request done', {
64
- requestId: trace.requestId,
65
- stage,
66
- deltaMs: roundMs(current - trace.last),
67
- totalMs: roundMs(current - trace.start),
68
- ...stageData,
69
- });
70
- }
71
- trace.last = current;
72
- },
73
- };
74
- if (perfLoggingEnabled()) {
75
- log('[perf] opencode request start', {
76
- requestId: trace.requestId,
77
- ...data,
78
- });
79
- }
80
- return trace;
81
- }
82
- async function sendIgnoredMessage(ctx, sessionId, text) {
83
- const session = ctx.client.session;
84
- const promptContext = await resolvePromptContext(ctx.client, sessionId);
85
- const request = {
86
- path: { id: sessionId },
87
- body: {
88
- noReply: true,
89
- parts: [{ type: 'text', text, ignored: true }],
90
- },
91
- };
92
- if (promptContext?.agent)
93
- request.body.agent = promptContext.agent;
94
- if (promptContext?.model)
95
- request.body.model = promptContext.model;
96
- if (promptContext?.variant)
97
- request.body.variant = promptContext.variant;
98
- if (typeof session?.promptAsync === 'function') {
99
- await session.promptAsync(request);
100
- return;
101
- }
102
- if (typeof session?.prompt === 'function') {
103
- await Promise.resolve(session.prompt(request));
104
- return;
105
- }
106
- throw new Error('OpenCode session prompt API is unavailable for ignored replies.');
107
- }
108
- function throwHandledSentinel() {
109
- throw new Error(HANDLED_SENTINEL);
110
- }
111
- export const AnthropicAuthPlugin = async (ctx) => {
112
- startEventLoopLagMonitor();
113
- const { client } = ctx;
114
- const fallbackManager = new FallbackAccountManager();
115
- fallbackManager.startBackgroundRefresh();
116
- let latestRefreshMainAccessToken = null;
117
- const cacheKeepManager = new CacheKeepManager({
118
- loadStorage: () => loadAccounts(),
119
- prepareHeaders: async (headers, target) => {
120
- if (!latestGetAuth)
121
- return headers;
122
- const auth = await latestGetAuth();
123
- if (auth.type !== 'oauth')
124
- return headers;
125
- if (!auth.access || (auth.expires && auth.expires < Date.now())) {
126
- if (!latestRefreshMainAccessToken)
127
- return headers;
128
- auth.access = await latestRefreshMainAccessToken();
129
- }
130
- if (!auth.access)
131
- return headers;
132
- try {
133
- const parsedBody = JSON.parse(target.bodyText);
134
- const identity = await resolveClaudeCodeIdentity(auth.access, typeof parsedBody.model === 'string' ? parsedBody.model : undefined);
135
- headers.delete('anthropic-beta');
136
- setOAuthHeaders(headers, auth.access, {
137
- body: parsedBody,
138
- identity,
139
- });
140
- headers.set('anthropic-beta', mergeAnthropicBetas(headers.get('anthropic-beta'), [
141
- CACHE_KEEP_EXTENDED_TTL_BETA,
142
- ]));
143
- if (parsedBody.speed === 'fast')
144
- addFastModeBetaHeader(headers);
145
- }
146
- catch {
147
- setOAuthHeaders(headers, auth.access);
148
- }
149
- return headers;
150
- },
151
- log,
152
- });
153
- const initialCache1hStorage = await loadAccounts();
154
- const relayConfig = getRelayConfig(initialCache1hStorage);
155
- setCache1hState({
156
- enabled: isCache1hPersistentlyEnabled(initialCache1hStorage),
157
- mode: getCache1hPersistentMode(initialCache1hStorage),
158
- });
159
- setDumpEnabled(isDumpPersistentlyEnabled(initialCache1hStorage));
160
- setFastModeEnabled(isFastModePersistentlyEnabled(initialCache1hStorage));
161
- let latestGetAuth = null;
162
- let mainBackgroundRefreshTimer = null;
163
- function mainRefreshBeforeExpiryMs(storage) {
164
- const minutes = storage?.refresh?.refreshBeforeExpiryMinutes ??
165
- DEFAULT_MAIN_REFRESH_BEFORE_EXPIRY_MINUTES;
166
- return Math.max(0, minutes) * 60_000;
167
- }
168
- function mainRefreshEnabled(storage) {
169
- return storage?.refresh?.enabled !== false;
170
- }
171
- async function clearStaleMainRefreshError(refreshToken) {
172
- if (!refreshToken)
173
- return;
174
- const storage = await loadAccounts();
175
- const error = storage?.refresh?.mainLastRefreshError;
176
- if (!storage?.refresh || !error?.tokenHash)
177
- return;
178
- const tokenHash = hashRefreshToken(refreshToken);
179
- if (error.tokenHash === tokenHash)
180
- return;
181
- storage.refresh.mainLastRefreshError = undefined;
182
- await saveAccounts(storage);
183
- log('[refresh] opencode main oauth cleared stale backoff after token rotation', {
184
- previousCheckedAt: error.checkedAt,
185
- previousNextRetryAt: error.nextRetryAt,
186
- previousRetryCount: error.retryCount,
187
- });
188
- }
189
- async function buildQuotaCommandSummary() {
190
- const accounts = [];
191
- if (latestGetAuth) {
192
- try {
193
- const auth = await latestGetAuth();
194
- if (auth.type === 'oauth' && auth.access) {
195
- accounts.push({
196
- name: 'OpenCode anthropic',
197
- role: 'main',
198
- quota: await fetchOAuthQuotaSnapshot({ accessToken: auth.access }),
199
- });
200
- }
201
- else if (auth.type === 'oauth') {
202
- accounts.push({
203
- name: 'OpenCode anthropic',
204
- role: 'main',
205
- error: 'missing access token; send a request first or reconnect auth',
206
- });
207
- }
208
- }
209
- catch (error) {
210
- accounts.push({
211
- name: 'OpenCode anthropic',
212
- role: 'main',
213
- error: error instanceof Error ? error.message : String(error),
214
- });
215
- }
216
- }
217
- const { storage, errors } = await fallbackManager.refreshQuotaForAllAccounts();
218
- accounts.push(...buildFallbackQuotaSummaries(storage, new Map(errors.map((error) => [error.accountId, error.message]))));
219
- if (!latestGetAuth) {
220
- accounts.unshift({
221
- name: 'OpenCode anthropic',
222
- role: 'main',
223
- error: 'auth loader has not run yet; send a request first',
224
- });
225
- }
226
- return buildClaudeQuotaSummary({ accounts, refreshedAt: Date.now() });
227
- }
228
- async function executePersistentCache1hCommand(argumentsText) {
229
- const action = parseCache1hCommandAction(argumentsText);
230
- if (action.type === 'enable' || action.type === 'disable') {
231
- const enabled = action.type === 'enable';
232
- const storage = await setCache1hPersistentEnabled(enabled);
233
- const mode = getCache1hPersistentMode(storage);
234
- setCache1hState({ enabled, mode });
235
- return executeCache1hCommand({ argumentsText, enabled, mode });
236
- }
237
- if (action.type === 'mode') {
238
- const storage = await setCache1hPersistentMode(action.mode);
239
- const enabled = isCache1hPersistentlyEnabled(storage);
240
- setCache1hState({ enabled, mode: action.mode });
241
- return executeCache1hCommand({
242
- argumentsText,
243
- enabled,
244
- mode: action.mode,
245
- });
246
- }
247
- const storage = await loadAccounts();
248
- const enabled = isCache1hPersistentlyEnabled(storage);
249
- const mode = getCache1hPersistentMode(storage);
250
- setCache1hState({ enabled, mode });
251
- return executeCache1hCommand({ argumentsText, enabled, mode });
252
- }
253
- async function executePersistentCacheKeepCommand(argumentsText) {
254
- const action = parseCacheKeepCommandAction(argumentsText);
255
- let storage = await loadAccounts();
256
- if (action.type === 'window') {
257
- storage = await setCacheKeepPersistentWindow(action.startHour, action.endHour);
258
- }
259
- else if (action.type === 'disable') {
260
- storage = await setCacheKeepPersistentEnabled(false);
261
- }
262
- const window = getCacheKeepWindow(storage);
263
- const stats = cacheKeepManager.stats(window);
264
- return executeCacheKeepCommand({
265
- argumentsText,
266
- enabled: isCacheKeepPersistentlyEnabled(storage),
267
- window,
268
- hybridActive: isCacheKeepHybridActive(storage),
269
- trackedSessions: stats.trackedSessions,
270
- nextPrewarmAt: stats.nextPrewarmAt,
271
- });
272
- }
273
- async function executePersistentDumpCommand(argumentsText) {
274
- const action = parseDumpCommandAction(argumentsText);
275
- if (action.type === 'enable' || action.type === 'disable') {
276
- const enabled = action.type === 'enable';
277
- await setDumpPersistentEnabled(enabled);
278
- setDumpEnabled(enabled);
279
- return executeDumpCommand({ argumentsText, enabled });
280
- }
281
- const storage = await loadAccounts();
282
- const enabled = isDumpPersistentlyEnabled(storage);
283
- setDumpEnabled(enabled);
284
- return executeDumpCommand({ argumentsText, enabled });
285
- }
286
- async function executePersistentFastModeCommand(argumentsText) {
287
- const action = parseFastModeCommandAction(argumentsText);
288
- if (action.type === 'enable' || action.type === 'disable') {
289
- const enabled = action.type === 'enable';
290
- await setFastModePersistentEnabled(enabled);
291
- setFastModeEnabled(enabled);
292
- return executeFastModeCommand({ argumentsText, enabled });
293
- }
294
- const storage = await loadAccounts();
295
- const enabled = isFastModePersistentlyEnabled(storage);
296
- setFastModeEnabled(enabled);
297
- return executeFastModeCommand({ argumentsText, enabled });
298
- }
299
- return {
300
- config: async (config) => {
301
- config.command = {
302
- ...(config.command ?? {}),
303
- [CACHE_1H_COMMAND_NAME]: {
304
- template: CACHE_1H_COMMAND_NAME,
305
- description: 'Show or toggle 1-hour Anthropic ephemeral prompt cache TTL.',
306
- },
307
- [CLAUDE_CACHE_KEEP_COMMAND_NAME]: {
308
- template: CLAUDE_CACHE_KEEP_COMMAND_NAME,
309
- description: 'Keep hybrid Claude cache warm for recently used sessions during a local time window.',
310
- },
311
- [CLAUDE_QUOTAS_COMMAND_NAME]: {
312
- template: CLAUDE_QUOTAS_COMMAND_NAME,
313
- description: 'Show current Claude OAuth quota usage for all accounts.',
314
- },
315
- [CLAUDE_DUMP_COMMAND_NAME]: {
316
- template: CLAUDE_DUMP_COMMAND_NAME,
317
- description: 'Show or toggle Anthropic request dump capture for debugging.',
318
- },
319
- [CLAUDE_FAST_COMMAND_NAME]: {
320
- template: CLAUDE_FAST_COMMAND_NAME,
321
- description: 'Show or toggle Anthropic fast mode for supported Opus models.',
322
- },
323
- };
324
- },
325
- 'command.execute.before': async (input) => {
326
- if (input.command === CACHE_1H_COMMAND_NAME) {
327
- await sendIgnoredMessage(ctx, input.sessionID, await executePersistentCache1hCommand(input.arguments));
328
- throwHandledSentinel();
329
- }
330
- if (input.command === CLAUDE_CACHE_KEEP_COMMAND_NAME) {
331
- await sendIgnoredMessage(ctx, input.sessionID, await executePersistentCacheKeepCommand(input.arguments));
332
- throwHandledSentinel();
333
- }
334
- if (input.command === CLAUDE_QUOTAS_COMMAND_NAME) {
335
- await sendIgnoredMessage(ctx, input.sessionID, await buildQuotaCommandSummary());
336
- throwHandledSentinel();
337
- }
338
- if (input.command === CLAUDE_DUMP_COMMAND_NAME) {
339
- await sendIgnoredMessage(ctx, input.sessionID, await executePersistentDumpCommand(input.arguments));
340
- throwHandledSentinel();
341
- }
342
- if (input.command === CLAUDE_FAST_COMMAND_NAME) {
343
- await sendIgnoredMessage(ctx, input.sessionID, await executePersistentFastModeCommand(input.arguments));
344
- throwHandledSentinel();
345
- }
346
- },
347
- auth: {
348
- provider: 'anthropic',
349
- async loader(getAuth, provider) {
350
- latestGetAuth = getAuth;
351
- const auth = await getAuth();
352
- if (auth.type === 'oauth') {
353
- // zero out cost for max plan
354
- for (const model of Object.values(provider.models)) {
355
- model.cost = {
356
- input: 0,
357
- output: 0,
358
- cache: {
359
- read: 0,
360
- write: 0,
361
- },
362
- };
363
- }
364
- // Shared inflight refresh promise — prevents concurrent token refreshes
365
- // from racing against each other (and causing 401 cascades with token rotation)
366
- let refreshPromise = null;
367
- let mainQuotaCache = null;
368
- let mainQuotaRefreshPromise = null;
369
- let mainQuotaRetryAfter = 0;
370
- async function refreshMainAccessToken() {
371
- if (!refreshPromise) {
372
- refreshPromise = (async () => {
373
- const maxRetries = 2;
374
- const baseDelayMs = 500;
375
- let leaseId = null;
376
- let leaseTokenHash = null;
377
- async function updateMainRefreshState(update) {
378
- const storage = (await loadAccounts()) ?? {
379
- version: 1,
380
- main: { type: 'opencode', provider: 'anthropic' },
381
- accounts: [],
382
- };
383
- storage.refresh = storage.refresh ?? {};
384
- update(storage);
385
- await saveAccounts(storage);
386
- }
387
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
388
- let freshAuth = null;
389
- try {
390
- if (attempt > 0) {
391
- const delay = baseDelayMs * 2 ** (attempt - 1);
392
- await new Promise((resolve) => setTimeout(resolve, delay));
393
- }
394
- // Re-read auth to get the latest refresh token.
395
- // The outer `auth` snapshot may be stale if tokens
396
- // were rotated since the fetch() call was made.
397
- freshAuth = await getAuth();
398
- if (!freshAuth.refresh) {
399
- throw new Error('Token refresh failed: missing refresh token');
400
- }
401
- const storage = await loadAccounts();
402
- const refreshTokenHash = hashRefreshToken(freshAuth.refresh);
403
- const mainError = storage?.refresh?.mainLastRefreshError;
404
- log('[refresh] opencode main oauth refresh check', {
405
- attempt,
406
- expiresInMs: freshAuth.expires
407
- ? freshAuth.expires - Date.now()
408
- : undefined,
409
- hasBackoff: Boolean(mainError),
410
- backoffActive: mainError
411
- ? refreshBackoffActive(mainError, freshAuth.refresh, Date.now())
412
- : false,
413
- retryCount: mainError?.retryCount,
414
- nextRetryAt: mainError?.nextRetryAt,
415
- });
416
- if (mainError &&
417
- refreshBackoffActive(mainError, freshAuth.refresh, Date.now())) {
418
- log('[refresh] opencode main oauth refresh skipped backoff', {
419
- nextRetryAt: mainError.nextRetryAt,
420
- retryCount: mainError.retryCount,
421
- });
422
- throw new Error(formatRefreshBackoffMessage(mainError, Date.now()));
423
- }
424
- if (storage?.refresh?.mainRefreshLeaseUntil &&
425
- storage.refresh.mainRefreshLeaseUntil > Date.now() &&
426
- storage.refresh.mainRefreshLeaseTokenHash ===
427
- refreshTokenHash) {
428
- log('[refresh] opencode main oauth refresh skipped lease', {
429
- leaseUntil: storage.refresh.mainRefreshLeaseUntil,
430
- });
431
- throw new Error('Claude OAuth refresh is already in progress');
432
- }
433
- leaseId = randomUUID();
434
- leaseTokenHash = refreshTokenHash;
435
- await updateMainRefreshState((nextStorage) => {
436
- nextStorage.refresh = nextStorage.refresh ?? {};
437
- nextStorage.refresh.mainRefreshLeaseId =
438
- leaseId ?? undefined;
439
- nextStorage.refresh.mainRefreshLeaseUntil =
440
- Date.now() + 2 * 60_000;
441
- nextStorage.refresh.mainRefreshLeaseTokenHash =
442
- refreshTokenHash;
443
- });
444
- const latestLease = await loadAccounts();
445
- log('[refresh] opencode main oauth refresh lease acquired', {
446
- attempt,
447
- leaseUntil: Date.now() + 2 * 60_000,
448
- });
449
- if (latestLease?.refresh?.mainRefreshLeaseId !== leaseId ||
450
- latestLease.refresh.mainRefreshLeaseTokenHash !==
451
- refreshTokenHash) {
452
- throw new Error('Claude OAuth refresh is already in progress');
453
- }
454
- log('[refresh] opencode main oauth refresh request start', {
455
- attempt,
456
- });
457
- const refreshed = await refreshClaudeOAuthToken({
458
- refreshToken: freshAuth.refresh,
459
- });
460
- // biome-ignore lint/suspicious/noExplicitAny: SDK types don't expose auth.set
461
- await client.auth.set({
462
- path: {
463
- id: 'anthropic',
464
- },
465
- body: {
466
- type: 'oauth',
467
- refresh: refreshed.refresh,
468
- access: refreshed.access,
469
- expires: refreshed.expires,
470
- },
471
- });
472
- await updateMainRefreshState((storage) => {
473
- if (!storage?.refresh)
474
- return;
475
- storage.refresh.mainLastRefreshError = undefined;
476
- if (storage.refresh.mainRefreshLeaseId === leaseId) {
477
- storage.refresh.mainRefreshLeaseId = undefined;
478
- storage.refresh.mainRefreshLeaseUntil = undefined;
479
- storage.refresh.mainRefreshLeaseTokenHash = undefined;
480
- }
481
- });
482
- log('[refresh] opencode main oauth refresh succeeded', {
483
- attempt,
484
- expiresInMs: refreshed.expires - Date.now(),
485
- });
486
- return refreshed.access;
487
- }
488
- catch (error) {
489
- const isNetworkError = error instanceof Error &&
490
- (error.message.includes('fetch failed') ||
491
- ('code' in error &&
492
- (error.code === 'ECONNRESET' ||
493
- error.code === 'ECONNREFUSED' ||
494
- error.code === 'ETIMEDOUT' ||
495
- error.code === 'UND_ERR_CONNECT_TIMEOUT')));
496
- if (attempt < maxRetries &&
497
- (isNetworkError ||
498
- (error instanceof ClaudeOAuthRefreshError &&
499
- error.status >= 500))) {
500
- continue;
501
- }
502
- log('[refresh] opencode main oauth refresh attempt failed', {
503
- attempt,
504
- error: error instanceof Error
505
- ? error.message
506
- : String(error),
507
- transient: isNetworkError,
508
- });
509
- const failedRefreshToken = freshAuth?.refresh;
510
- if (failedRefreshToken &&
511
- error instanceof ClaudeOAuthRefreshError) {
512
- await updateMainRefreshState((storage) => {
513
- storage.refresh = storage.refresh ?? {};
514
- storage.refresh.mainLastRefreshError =
515
- buildRefreshOperationError({
516
- error,
517
- now: Date.now(),
518
- refreshToken: failedRefreshToken,
519
- previous: storage.refresh.mainLastRefreshError,
520
- });
521
- });
522
- }
523
- throw error;
524
- }
525
- finally {
526
- if (leaseId) {
527
- await updateMainRefreshState((storage) => {
528
- if (!storage?.refresh)
529
- return;
530
- if (storage.refresh.mainRefreshLeaseId === leaseId &&
531
- storage.refresh.mainRefreshLeaseTokenHash ===
532
- leaseTokenHash) {
533
- storage.refresh.mainRefreshLeaseId = undefined;
534
- storage.refresh.mainRefreshLeaseUntil = undefined;
535
- storage.refresh.mainRefreshLeaseTokenHash = undefined;
536
- }
537
- }).catch(() => { });
538
- }
539
- }
540
- }
541
- // Unreachable — each iteration either returns or throws.
542
- // Kept as a TypeScript exhaustiveness guard.
543
- throw new Error('Token refresh exhausted all retries');
544
- })().finally(() => {
545
- refreshPromise = null;
546
- });
547
- }
548
- return refreshPromise;
549
- }
550
- latestRefreshMainAccessToken = refreshMainAccessToken;
551
- function startMainBackgroundRefresh() {
552
- if (mainBackgroundRefreshTimer) {
553
- clearInterval(mainBackgroundRefreshTimer);
554
- mainBackgroundRefreshTimer = null;
555
- }
556
- const run = async () => {
557
- try {
558
- const storage = await loadAccounts();
559
- if (!mainRefreshEnabled(storage))
560
- return;
561
- const latestAuth = await getAuth();
562
- if (latestAuth.type !== 'oauth')
563
- return;
564
- await clearStaleMainRefreshError(latestAuth.refresh);
565
- if (!latestAuth.expires)
566
- return;
567
- const expiresInMs = latestAuth.expires - Date.now();
568
- const refreshBeforeMs = mainRefreshBeforeExpiryMs(storage);
569
- if (expiresInMs > refreshBeforeMs) {
570
- return;
571
- }
572
- log('[refresh] opencode main oauth background due', {
573
- expiresInMs,
574
- refreshBeforeMs,
575
- });
576
- if (latestAuth.refresh &&
577
- refreshBackoffActive(storage?.refresh?.mainLastRefreshError, latestAuth.refresh, Date.now())) {
578
- log('[refresh] opencode main oauth background skipped backoff', {
579
- nextRetryAt: storage?.refresh?.mainLastRefreshError?.nextRetryAt,
580
- retryCount: storage?.refresh?.mainLastRefreshError?.retryCount,
581
- });
582
- return;
583
- }
584
- if (latestAuth.refresh &&
585
- storage?.refresh?.mainRefreshLeaseUntil &&
586
- storage.refresh.mainRefreshLeaseUntil > Date.now() &&
587
- storage.refresh.mainRefreshLeaseTokenHash ===
588
- hashRefreshToken(latestAuth.refresh)) {
589
- return;
590
- }
591
- await refreshMainAccessToken();
592
- log('[refresh] opencode main oauth refreshed in background', {
593
- expires: latestAuth.expires,
594
- });
595
- }
596
- catch (error) {
597
- log('[refresh] opencode main oauth refresh failed', {
598
- message: error instanceof Error ? error.message : String(error),
599
- });
600
- }
601
- };
602
- mainBackgroundRefreshTimer = setInterval(() => {
603
- void run();
604
- }, MAIN_AUTH_REFRESH_TICK_MS);
605
- if ('unref' in mainBackgroundRefreshTimer) {
606
- mainBackgroundRefreshTimer.unref();
607
- }
608
- }
609
- startMainBackgroundRefresh();
610
- function isReplayableRequest(input, body) {
611
- if (input instanceof Request && input.body)
612
- return false;
613
- return body == null || typeof body === 'string';
614
- }
615
- function isSubagentRequest(headers) {
616
- return headers.has('x-parent-session-id');
617
- }
618
- function isStreamingRateLimitText(text) {
619
- return (text.includes('rate_limit_error') ||
620
- /exceed your account'?s rate limit/i.test(text));
621
- }
622
- function mainQuotaRoutingEnabled(storage) {
623
- return storage?.quota?.enabled === true;
624
- }
625
- async function inspectStreamingRateLimit(response, trace) {
626
- if (!response.body || response.status !== 200) {
627
- trace?.mark('inspect_stream_skip', { status: response.status });
628
- return { response, rateLimited: false };
629
- }
630
- if (response.headers.get('x-cortexkit-relay-optimistic') === 'true') {
631
- trace?.mark('inspect_stream_skip', {
632
- status: response.status,
633
- reason: 'optimistic_relay',
634
- });
635
- return { response, rateLimited: false };
636
- }
637
- const start = nowMs();
638
- const reader = response.body.getReader();
639
- const chunks = [];
640
- const decoder = new TextDecoder();
641
- let text = '';
642
- let bytes = 0;
643
- while (!text.includes('\n\n') && text.length < 65_536) {
644
- const { done, value } = await reader.read();
645
- if (done)
646
- break;
647
- chunks.push(value);
648
- bytes += value.byteLength;
649
- text += decoder.decode(value, { stream: true });
650
- if (isStreamingRateLimitText(text))
651
- break;
652
- }
653
- if (isStreamingRateLimitText(text)) {
654
- await reader.cancel().catch(() => { });
655
- trace?.mark('inspect_stream_first_event', {
656
- ms: roundMs(nowMs() - start),
657
- bytes,
658
- rateLimited: true,
659
- });
660
- return { response, rateLimited: true };
661
- }
662
- const stream = new ReadableStream({
663
- start(controller) {
664
- for (const chunk of chunks)
665
- controller.enqueue(chunk);
666
- },
667
- async pull(controller) {
668
- const { done, value } = await reader.read();
669
- if (done) {
670
- controller.close();
671
- return;
672
- }
673
- controller.enqueue(value);
674
- },
675
- cancel(reason) {
676
- return reader.cancel(reason);
677
- },
678
- });
679
- trace?.mark('inspect_stream_first_event', {
680
- ms: roundMs(nowMs() - start),
681
- bytes,
682
- rateLimited: false,
683
- });
684
- return {
685
- response: new Response(stream, {
686
- status: response.status,
687
- statusText: response.statusText,
688
- headers: response.headers,
689
- }),
690
- rateLimited: false,
691
- };
692
- }
693
- async function sendWithAccessToken(input, init, accessToken, trace, route = 'unknown') {
694
- const start = nowMs();
695
- const requestHeaders = mergeHeaders(input, init);
696
- const relayAffinity = requestHeaders.get('x-session-affinity') ||
697
- requestHeaders.get('x-opencode-session');
698
- const subagentRequest = isSubagentRequest(requestHeaders);
699
- requestHeaders.delete('x-parent-session-id');
700
- requestHeaders.delete('x-session-affinity');
701
- requestHeaders.delete('x-opencode-session');
702
- let body = init?.body;
703
- let modelForIdentity;
704
- if (body && typeof body === 'string') {
705
- try {
706
- const parsedBody = JSON.parse(body);
707
- if (typeof parsedBody.model === 'string') {
708
- modelForIdentity = parsedBody.model;
709
- }
710
- }
711
- catch { }
712
- }
713
- const identity = await resolveClaudeCodeIdentity(accessToken, modelForIdentity);
714
- const originalBytes = typeof body === 'string' ? body.length : undefined;
715
- if (body && typeof body === 'string') {
716
- const rewriteStart = nowMs();
717
- const fastModeRequested = (() => {
718
- if (!isFastModeEnabled())
719
- return false;
720
- try {
721
- return isFastModeSupportedModel(JSON.parse(body).model);
722
- }
723
- catch {
724
- return false;
725
- }
726
- })();
727
- body = await rewriteRequestBody(body, {
728
- cache1hEnabled: !subagentRequest && isCache1hEnabled(),
729
- cache1hMode: getCache1hMode(),
730
- fastModeEnabled: fastModeRequested,
731
- identity,
732
- });
733
- try {
734
- setOAuthHeaders(requestHeaders, accessToken, {
735
- body: JSON.parse(body),
736
- identity,
737
- });
738
- }
739
- catch {
740
- setOAuthHeaders(requestHeaders, accessToken, { identity });
741
- }
742
- if (fastModeRequested)
743
- addFastModeBetaHeader(requestHeaders);
744
- trace?.mark('rewrite_body', {
745
- route,
746
- ms: roundMs(nowMs() - rewriteStart),
747
- originalBytes,
748
- rewrittenBytes: body.length,
749
- cacheEnabled: !subagentRequest && isCache1hEnabled(),
750
- cacheMode: getCache1hMode(),
751
- fastModeEnabled: fastModeRequested,
752
- subagent: subagentRequest,
753
- });
754
- }
755
- const rewritten = rewriteUrl(input);
756
- if (route === 'main' &&
757
- typeof body === 'string' &&
758
- !subagentRequest &&
759
- isCache1hEnabled() &&
760
- getCache1hMode() === 'hybrid') {
761
- const storage = await loadAccounts();
762
- const tracked = await cacheKeepManager.track({
763
- sessionId: relayAffinity,
764
- url: rewritten.url?.toString() ?? rewritten.input.toString(),
765
- headers: requestHeaders,
766
- bodyText: body,
767
- storage,
768
- cacheMode: 'hybrid',
769
- });
770
- if (tracked.tracked) {
771
- trace?.mark('cachekeep_track', { session: relayAffinity });
772
- }
773
- }
774
- const directFetch = () => fetch(rewritten.input, {
775
- ...init,
776
- body,
777
- headers: requestHeaders,
778
- ...(isInsecure() && { tls: { rejectUnauthorized: false } }),
779
- });
780
- const sendStart = nowMs();
781
- const response = await sendViaRelay({
782
- config: relayConfig,
783
- input: rewritten.input,
784
- init,
785
- headers: requestHeaders,
786
- body,
787
- fallback: directFetch,
788
- affinity: relayAffinity,
789
- optimisticResponse: relayConfig?.transport === 'websocket',
790
- });
791
- trace?.mark('send_headers_received', {
792
- route,
793
- ms: roundMs(nowMs() - sendStart),
794
- status: response.status,
795
- relayConfigured: relayConfig != null,
796
- totalSendWithAccessMs: roundMs(nowMs() - start),
797
- });
798
- return response;
799
- }
800
- async function refreshMainQuotaCache(accessToken, storage) {
801
- const now = Date.now();
802
- const quota = await fetchOAuthQuotaSnapshot({ accessToken });
803
- mainQuotaCache = {
804
- accessToken,
805
- refreshAfter: getQuotaNextRefreshAt(quota, storage, now),
806
- quota,
807
- };
808
- return quota;
809
- }
810
- function refreshMainQuotaCacheInBackground(accessToken, storage) {
811
- const now = Date.now();
812
- if (mainQuotaRefreshPromise || now < mainQuotaRetryAfter)
813
- return;
814
- mainQuotaRefreshPromise = refreshMainQuotaCache(accessToken, storage)
815
- .catch((error) => {
816
- mainQuotaRetryAfter = now + getQuotaCheckIntervalMs(storage);
817
- throw error;
818
- })
819
- .finally(() => {
820
- mainQuotaRefreshPromise = null;
821
- });
822
- void mainQuotaRefreshPromise.catch(() => { });
823
- }
824
- async function getMainQuotaForRouting(accessToken, storage) {
825
- const now = Date.now();
826
- if (mainQuotaCache?.accessToken !== accessToken) {
827
- return await refreshMainQuotaCache(accessToken, storage);
828
- }
829
- if (now >= mainQuotaCache.refreshAfter) {
830
- refreshMainQuotaCacheInBackground(accessToken, storage);
831
- }
832
- return mainQuotaCache.quota;
833
- }
834
- async function tryUsableFallbackAccounts(input, init, accounts, storage, currentResponse, trace) {
835
- if (!accounts.length)
836
- return currentResponse ?? null;
837
- await currentResponse?.body?.cancel().catch(() => { });
838
- let lastResponse = currentResponse ?? null;
839
- for (const [index, account] of accounts.entries()) {
840
- const access = account.access;
841
- if (!access)
842
- continue;
843
- let response = await sendWithAccessToken(input, init, access, trace, `fallback_${index}`);
844
- lastResponse = response;
845
- let fallbackAgain = shouldFallbackStatus(response.status, storage);
846
- if (!fallbackAgain) {
847
- const inspected = await inspectStreamingRateLimit(response, trace);
848
- response = inspected.response;
849
- lastResponse = response;
850
- fallbackAgain = inspected.rateLimited;
851
- }
852
- if (!fallbackAgain) {
853
- await fallbackManager.markUsed(account);
854
- return response;
855
- }
856
- if (index < accounts.length - 1) {
857
- await response.body?.cancel().catch(() => { });
858
- }
859
- }
860
- return lastResponse;
861
- }
862
- async function tryFallbackAccounts(input, init, mainResponse, preselectedAccounts, trace) {
863
- if (!isReplayableRequest(input, init?.body))
864
- return mainResponse;
865
- const loadStart = nowMs();
866
- const storage = await loadAccounts();
867
- trace?.mark('fallback_load_storage', {
868
- ms: roundMs(nowMs() - loadStart),
869
- });
870
- let currentResponse = mainResponse;
871
- let shouldFallback = shouldFallbackStatus(currentResponse.status, storage);
872
- if (!shouldFallback) {
873
- const inspected = await inspectStreamingRateLimit(currentResponse, trace);
874
- currentResponse = inspected.response;
875
- shouldFallback = inspected.rateLimited;
876
- }
877
- if (!shouldFallback) {
878
- return currentResponse;
879
- }
880
- let accounts = preselectedAccounts;
881
- if (!accounts) {
882
- const accountsStart = nowMs();
883
- accounts = await fallbackManager.getUsableFallbackAccounts();
884
- trace?.mark('fallback_get_accounts', {
885
- ms: roundMs(nowMs() - accountsStart),
886
- accounts: accounts.length,
887
- });
888
- }
889
- return ((await tryUsableFallbackAccounts(input, init, accounts, storage, currentResponse, trace)) ?? currentResponse);
890
- }
891
- return {
892
- apiKey: '',
893
- async fetch(input, init) {
894
- const initialBody = init?.body;
895
- const trace = createPerfTrace({
896
- bodyBytes: typeof initialBody === 'string'
897
- ? initialBody.length
898
- : undefined,
899
- relayConfigured: relayConfig != null,
900
- });
901
- const authStart = nowMs();
902
- const auth = await getAuth();
903
- trace.mark('get_auth', {
904
- ms: roundMs(nowMs() - authStart),
905
- authType: auth.type,
906
- hasAccess: Boolean(auth.access),
907
- });
908
- if (auth.type !== 'oauth') {
909
- const response = await fetch(input, init);
910
- trace.done('non_oauth_passthrough', { status: response.status });
911
- return response;
912
- }
913
- await clearStaleMainRefreshError(auth.refresh);
914
- if (!auth.access || !auth.expires || auth.expires < Date.now()) {
915
- log('[refresh] opencode main oauth refresh required for request', {
916
- hasAccess: Boolean(auth.access),
917
- expiresInMs: auth.expires
918
- ? auth.expires - Date.now()
919
- : undefined,
920
- });
921
- const refreshStart = nowMs();
922
- auth.access = await refreshMainAccessToken();
923
- trace.mark('refresh_main_access', {
924
- ms: roundMs(nowMs() - refreshStart),
925
- });
926
- }
927
- if (!auth.access) {
928
- trace.done('missing_access_error');
929
- throw new Error('OAuth access token is missing after refresh');
930
- }
931
- const loadStart = nowMs();
932
- const storage = await loadAccounts();
933
- trace.mark('load_storage', { ms: roundMs(nowMs() - loadStart) });
934
- let preselectedFallbackAccounts;
935
- if (isReplayableRequest(input, init?.body) &&
936
- mainQuotaRoutingEnabled(storage)) {
937
- try {
938
- const quotaStart = nowMs();
939
- const mainQuota = await getMainQuotaForRouting(auth.access, storage);
940
- trace.mark('main_quota_for_routing', {
941
- ms: roundMs(nowMs() - quotaStart),
942
- passes: quotaSnapshotPassesPolicy(mainQuota, storage),
943
- });
944
- if (!quotaSnapshotPassesPolicy(mainQuota, storage)) {
945
- const fallbackStart = nowMs();
946
- preselectedFallbackAccounts =
947
- await fallbackManager.getUsableFallbackAccounts();
948
- trace.mark('preselect_fallback_accounts', {
949
- ms: roundMs(nowMs() - fallbackStart),
950
- accounts: preselectedFallbackAccounts.length,
951
- });
952
- const fallbackResponse = await tryUsableFallbackAccounts(input, init, preselectedFallbackAccounts, storage, undefined, trace);
953
- if (fallbackResponse) {
954
- trace.done('return_preselected_fallback', {
955
- status: fallbackResponse.status,
956
- });
957
- return createStrippedStream(fallbackResponse);
958
- }
959
- }
960
- }
961
- catch (error) {
962
- trace.mark('main_quota_for_routing_error', {
963
- error: error instanceof Error ? error.message : String(error),
964
- });
965
- // Main quota checks should optimize routing, not break requests.
966
- }
967
- }
968
- const mainResponse = await sendWithAccessToken(input, init, auth.access, trace, 'main');
969
- const response = await tryFallbackAccounts(input, init, mainResponse, preselectedFallbackAccounts, trace);
970
- trace.done('return_response', { status: response.status });
971
- return createStrippedStream(response);
972
- },
973
- };
974
- }
975
- return {};
976
- },
977
- methods: [
978
- {
979
- label: 'Claude Pro/Max',
980
- type: 'oauth',
981
- authorize: async () => {
982
- const result = await authorize('max');
983
- return {
984
- url: result.url,
985
- instructions: 'Paste the authorization code here:',
986
- method: 'code',
987
- callback: async (code) => {
988
- return exchange(code, result.verifier, result.redirectUri, result.state);
989
- },
990
- };
991
- },
992
- },
993
- {
994
- label: 'Create an API Key',
995
- type: 'oauth',
996
- authorize: async () => {
997
- const result = await authorize('console');
998
- return {
999
- url: result.url,
1000
- instructions: 'Paste the authorization code here:',
1001
- method: 'code',
1002
- callback: async (code) => {
1003
- const credentials = await exchange(code, result.verifier, result.redirectUri, result.state);
1004
- if (credentials.type === 'failed')
1005
- return credentials;
1006
- const apiKey = await fetch(`https://api.anthropic.com/api/oauth/claude_cli/create_api_key`, {
1007
- method: 'POST',
1008
- headers: {
1009
- 'Content-Type': 'application/json',
1010
- authorization: `Bearer ${credentials.access}`,
1011
- },
1012
- }).then((r) => r.json());
1013
- return { type: 'success', key: apiKey.raw_key };
1014
- },
1015
- };
1016
- },
1017
- },
1018
- {
1019
- provider: 'anthropic',
1020
- label: 'Manually enter API Key',
1021
- type: 'api',
1022
- },
1023
- ],
1024
- },
1025
- // biome-ignore lint/suspicious/noExplicitAny: Plugin type doesn't include undocumented auth/hooks
1026
- };
1027
- };
1
+ import{$ as H1,A as Q1,B as L1,C as x0,D as j0,E as v1,F as J0,G as N1,H as _1,I as H0,J as F1,K as q0,L as M1,M as K0,N as Z0,O as $0,P as l,Q as B1,R as G0,S as s0,T as e0,U as S0,V as j1,W as J1,X as K1,Y as D0,Z as U1,_ as x1,a as p0,aa as q1,b as c0,ba as S1,c as a,ca as A1,d as r,da as E1,e as o0,ea as V0,f as u,fa as P0,g as t0,ga as R1,h as a0,ha as A0,i as r0,ia as X0,j as N0,ja as f1,k as W1,ka as W0,l as _0,la as C1,m as F0,ma as E0,n as H,na as Y0,oa as T1,p as S,pa as y1,q as M0,qa as k1,r as Y1,s,sa as g1,t as e,u as w1,v as z1,w as B0,x as I1,y as U0,z as O1}from"./index-sebye7nt.js";import{randomUUID as Pj}from"node:crypto";function m(j){return typeof j==="object"&&j!==null}function a1(j){if(Array.isArray(j))return j;if(m(j)&&Array.isArray(j.data))return j.data;return[]}function r1(j){if(!m(j)||!m(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function m0(j){if(!m(j)||!m(j.info))return null;let J=j.info,K=m(J.model)?J.model:void 0,Z=typeof J.agent==="string"?J.agent:void 0,G=typeof K?.providerID==="string"?K.providerID:typeof J.providerID==="string"?J.providerID:void 0,D=typeof K?.modelID==="string"?K.modelID:typeof J.modelID==="string"?J.modelID:void 0,F=typeof K?.variant==="string"?K.variant:typeof J.variant==="string"?J.variant:void 0;if(!Z&&(!G||!D)&&!F)return null;let A={};if(Z)A.agent=Z;if(G&&D)A.model={providerID:G,modelID:D};if(F)A.variant=F;return A}function b0(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function h0(j){return Boolean(j.agent&&j.model&&j.variant)}async function u0(j,J){if(!j||!J)return null;let K=j;if(typeof K.session?.messages!=="function")return null;let Z=[];try{Z=a1(await Promise.resolve(K.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(Z.length===0)return null;let G={};for(let D=Z.length-1;D>=0;D--){if(r1(Z[D])!=="assistant")continue;let F=m0(Z[D]);if(!F)continue;if(G=b0(G,F),h0(G))return G}for(let D=Z.length-1;D>=0;D--){let F=m0(Z[D]);if(!F)continue;if(G=b0(G,F),h0(G))return G}if(!G.agent&&!G.model&&!G.variant)return null;return G}function d0(j){return`${p0}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function s1(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}function Z1(j,J){let K=new Headers;if(j instanceof Request)j.headers.forEach((G,D)=>{K.set(D,G)});let Z=J?.headers;if(Z){if(Z instanceof Headers)Z.forEach((G,D)=>{K.set(D,G)});else if(Array.isArray(Z))for(let G of Z){let[D,F]=G;if(typeof F<"u")K.set(D,String(F))}else for(let[G,D]of Object.entries(Z))if(typeof D<"u")K.set(G,String(D))}return K}function L0(j){return j.set("anthropic-beta",a(j.get("anthropic-beta"),[c0])),j}function d(j,J,K={}){return J1(j,J,K)}function e1(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?d0(J.name):J.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map((K)=>{if(K.type==="tool_use"&&K.name)return{...K,name:d0(K.name)};return K});return J});return JSON.stringify(K1(j))}function O0(j){return j.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,(J,K)=>`"name": "${s1(K)}"`)}function n0(j,J=!1){if(J)return{ready:O0(j),pending:""};let K=j.length,Z='"name"',G=Math.max(0,j.length-Z.length+1);for(let F=G;F<j.length;F++)if(Z.startsWith(j.slice(F))){K=Math.min(K,F);break}let D=j.lastIndexOf(Z);if(D!==-1){let F=j.slice(D);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(F))K=Math.min(K,D)}if(K<j.length)return{ready:O0(j.slice(0,K)),pending:j.slice(K)};return{ready:O0(j),pending:""}}function $1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function jj(){let j=process.env.ANTHROPIC_BASE_URL?.trim();if(!j)return null;try{let J=new URL(j);if(J.protocol!=="http:"&&J.protocol!=="https:"||J.username||J.password)return null;return J}catch{return null}}function G1(j){let J=null;try{if(typeof j==="string"||j instanceof URL)J=new URL(j.toString());else if(j instanceof Request)J=new URL(j.url)}catch{J=null}if(!J)return{input:j,url:null};let K=J.href,Z=jj();if(Z)J.protocol=Z.protocol,J.host=Z.host;if(J.pathname==="/v1/messages"&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===K)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function c(j){let Z=j.split(/\n\n+/).filter((G)=>{if(G.includes(o0))return!1;for(let D of a0)if(G.includes(D))return!1;return!0}).join(`
2
+
3
+ `);for(let G of r0)Z=Z.replace(G.match,G.replacement);return Z.trim()}function E(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function Jj(j){let J={type:"text",text:u};if(j==null)return[J];if(typeof j==="string"){let Z=c(j);if(Z===u)return[J];return[J,{type:"text",text:Z}]}if(E(j)){let Z=typeof j.type==="string"?j.type:"text",G=typeof j.text==="string"?j.text:"";return[J,{...j,type:Z,text:c(G)}]}if(!Array.isArray(j))return[J];let K=j.map((Z)=>{if(typeof Z==="string")return{type:"text",text:c(Z)};if(E(Z)&&Z.type==="text"&&typeof Z.text==="string")return{...Z,type:"text",text:c(Z.text)};return{type:"text",text:String(Z)}});if(K[0]?.text===u)return K;return[J,...K]}var D1={type:"ephemeral",ttl:"1h"};function Kj(j){if(E(j.cache_control))return j.cache_control;if(E(j.cacheControl))return j.cacheControl;return null}function t(j,J){if(!E(j))return!1;return delete j.cacheControl,j.cache_control=J?{...D1}:{type:"ephemeral"},!0}function i0(j){if(!E(j))return;delete j.cache_control,delete j.cacheControl}function Zj(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function o(j,J){if(!E(j))return;let K=Kj(j);if(!K||K.type!=="ephemeral")return;if(J)K.ttl="1h";else delete K.ttl}function l0(j,J){if(Array.isArray(j.system))for(let K of j.system)o(K,J);else o(j.system,J);if(!Array.isArray(j.messages))return;for(let K of j.messages)if(o(K,J),E(K)&&Array.isArray(K.content))for(let Z of K.content)o(Z,J)}function $j(j,J){if(Array.isArray(j.system))for(let K of j.system)J(K);else J(j.system);if(!Array.isArray(j.messages))return;for(let K of j.messages)if(J(K),E(K)&&Array.isArray(K.content))for(let Z of K.content)J(Z)}function V1(j){i0(j),$j(j,i0)}function Gj(j){V1(j),j.cache_control={...D1}}function Q0(j){if(!E(j))return!1;let J=Zj(j.content);if(!J?.length)return t(j,!0);j.content=J;let K=[...J].reverse().find((Z)=>E(Z)&&Z.type!=="thinking");return t(K??j,!0)}function Dj(j){if(V1(j),Array.isArray(j.system)){let K=j.system.findIndex((D)=>E(D)&&D.text===u),Z=j.system.slice(K>=0?K+1:0).filter(E),G=Z[Z.length-1];t(G,!0)}else t(j.system,!0);if(!Array.isArray(j.messages))return;Q0(j.messages[0]),Q0(j.messages[1]);let J=j.messages.length-2;if(J>1)Q0(j.messages[J])}function Vj(j,J){if(!J.enabled){l0(j,!1),delete j.cache_control,delete j.cacheControl;return}if(J.mode==="automatic"){Gj(j);return}if(J.mode==="hybrid"){Dj(j);return}l0(j,!0),delete j.cacheControl}async function P1(j,J={}){try{let K=JSON.parse(j),Z=Array.isArray(K.messages)&&K.messages.some((G)=>G.role==="user")?e0(K.messages,void 0,t0):null;if(K.system=Jj(K.system),Z&&Array.isArray(K.system))K.system.unshift({type:"text",text:Z});if(Vj(K,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&r(K.model))K.speed="fast";else if(K.speed==="fast")delete K.speed;if(J.identity)j1(K,J.identity);return await s0(e1(K))}catch{return j}}function v0(j){if(!j.body)return j;let J=j.body.getReader(),K=new TextDecoder,Z=new TextEncoder,G="",D=new ReadableStream({async pull(F){let{done:A,value:T}=await J.read();if(A){let h=n0(`${G}${K.decode()}`,!0);if(h.ready)F.enqueue(Z.encode(h.ready));F.close();return}let z0=G+K.decode(T,{stream:!0}),b=n0(z0);if(G=b.pending,b.ready)F.enqueue(Z.encode(b.ready))}});return new Response(D,{status:j.status,statusText:j.statusText,headers:j.headers})}var Xj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",Wj=60000,m1=240,Yj=m1,wj=1,X1=!1;function w0(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function M(){return performance.now()}function q(j){return Math.round(j*10)/10}function zj(){if(X1||!1||!w0())return;X1=!0;let j=100,J=250,K=M()+j;setInterval(()=>{let Z=M(),G=Z-K;if(K=Z+j,G<J)return;H("[perf] opencode event_loop_lag",{lagMs:q(G),thresholdMs:J})},j).unref?.()}function Ij(j){let J=M(),K={requestId:String(wj++),start:J,last:J,mark(Z,G){let D=M();if(w0())H("[perf] opencode request stage",{requestId:K.requestId,stage:Z,deltaMs:q(D-K.last),totalMs:q(D-K.start),...G});K.last=D},done(Z,G){let D=M();if(w0())H("[perf] opencode request done",{requestId:K.requestId,stage:Z,deltaMs:q(D-K.last),totalMs:q(D-K.start),...G});K.last=D}};if(w0())H("[perf] opencode request start",{requestId:K.requestId,...j});return K}async function n(j,J,K){let Z=j.client.session,G=await u0(j.client,J),D={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:K,ignored:!0}]}};if(G?.agent)D.body.agent=G.agent;if(G?.model)D.body.model=G.model;if(G?.variant)D.body.variant=G.variant;if(typeof Z?.promptAsync==="function"){await Z.promptAsync(D);return}if(typeof Z?.prompt==="function"){await Promise.resolve(Z.prompt(D));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function i(){throw Error(Xj)}var Bj=async(j)=>{zj();let{client:J}=j,K=new M1;K.startBackgroundRefresh();let Z=null,G=new E1({loadStorage:()=>S(),prepareHeaders:async($,O)=>{if(!A)return $;let L=await A();if(L.type!=="oauth")return $;if(!L.access||L.expires&&L.expires<Date.now()){if(!Z)return $;L.access=await Z()}if(!L.access)return $;try{let Q=JSON.parse(O.bodyText),U=await S0(L.access,typeof Q.model==="string"?Q.model:void 0);if($.delete("anthropic-beta"),d($,L.access,{body:Q,identity:U}),$.set("anthropic-beta",a($.get("anthropic-beta"),[U1])),Q.speed==="fast")L0($)}catch{d($,L.access)}return $},log:H}),D=await S(),F=k1(D);l({enabled:s(D),mode:e(D)}),P0(B0(D)),W0(U0(D));let A=null,T=null;function z0($){let O=$?.refresh?.refreshBeforeExpiryMinutes??Yj;return Math.max(m1,O)*60000}function b($){return $?.refresh?.enabled!==!1}async function h($){if(!$)return;let O=await S(),L=O?.refresh?.mainLastRefreshError;if(!O?.refresh||!L?.tokenHash)return;let Q=j0($);if(L.tokenHash===Q)return;O.refresh.mainLastRefreshError=void 0,await M0(O),H("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:L.checkedAt,previousNextRetryAt:L.nextRetryAt,previousRetryCount:L.retryCount})}async function b1(){let $=[];if(A)try{let Q=await A();if(Q.type==="oauth"&&Q.access)$.push({name:"OpenCode anthropic",role:"main",quota:await q0({accessToken:Q.access})});else if(Q.type==="oauth")$.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(Q){$.push({name:"OpenCode anthropic",role:"main",error:Q instanceof Error?Q.message:String(Q)})}let{storage:O,errors:L}=await K.refreshQuotaForAllAccounts();if($.push(...T1(O,new Map(L.map((Q)=>[Q.accountId,Q.message])))),!A)$.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return y1({accounts:$,refreshedAt:Date.now()})}async function h1($){let O=B1($);if(O.type==="enable"||O.type==="disable"){let f=O.type==="enable",y=await w1(f),k=e(y);return l({enabled:f,mode:k}),G0({argumentsText:$,enabled:f,mode:k})}if(O.type==="mode"){let f=await z1(O.mode),y=s(f);return l({enabled:y,mode:O.mode}),G0({argumentsText:$,enabled:y,mode:O.mode})}let L=await S(),Q=s(L),U=e(L);return l({enabled:Q,mode:U}),G0({argumentsText:$,enabled:Q,mode:U})}async function u1($){let O=x1($),L=await S();if(O.type==="window")L=await Q1(O.startHour,O.endHour);else if(O.type==="disable")L=await L1(!1);let Q=H1(L),U=G.stats(Q);return A1({argumentsText:$,enabled:q1(L),window:Q,hybridActive:S1(L),trackedSessions:U.trackedSessions,nextPrewarmAt:U.nextPrewarmAt})}async function d1($){let O=R1($);if(O.type==="enable"||O.type==="disable"){let U=O.type==="enable";return await I1(U),P0(U),A0({argumentsText:$,enabled:U})}let L=await S(),Q=B0(L);return P0(Q),A0({argumentsText:$,enabled:Q})}async function n1($){let O=C1($);if(O.type==="enable"||O.type==="disable"){let U=O.type==="enable";return await O1(U),W0(U),E0({argumentsText:$,enabled:U})}let L=await S(),Q=U0(L);return W0(Q),E0({argumentsText:$,enabled:Q})}return{config:async($)=>{$.command={...$.command??{},[K0]:{template:K0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[D0]:{template:D0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[Y0]:{template:Y0,description:"Show current Claude OAuth quota usage for all accounts."},[V0]:{template:V0,description:"Show or toggle Anthropic request dump capture for debugging."},[X0]:{template:X0,description:"Show or toggle Anthropic fast mode for supported Opus models."}}},"command.execute.before":async($)=>{if($.command===K0)await n(j,$.sessionID,await h1($.arguments)),i();if($.command===D0)await n(j,$.sessionID,await u1($.arguments)),i();if($.command===Y0)await n(j,$.sessionID,await b1()),i();if($.command===V0)await n(j,$.sessionID,await d1($.arguments)),i();if($.command===X0)await n(j,$.sessionID,await n1($.arguments)),i()},auth:{provider:"anthropic",async loader($,O){if(A=$,(await $()).type==="oauth"){let i1=function(){if(T)clearInterval(T),T=null;let V=async()=>{try{let X=await S();if(!b(X))return;let Y=await $();if(Y.type!=="oauth")return;if(await h(Y.refresh),!Y.expires)return;let I=Y.expires-Date.now(),B=z0(X);if(I>B)return;if(H("[refresh] opencode main oauth background due",{expiresInMs:I,refreshBeforeMs:B}),Y.refresh&&J0(X?.refresh?.mainLastRefreshError,Y.refresh,Date.now())){H("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:X?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:X?.refresh?.mainLastRefreshError?.retryCount});return}if(Y.refresh&&X?.refresh?.mainRefreshLeaseUntil&&X.refresh.mainRefreshLeaseUntil>Date.now()&&X.refresh.mainRefreshLeaseTokenHash===j0(Y.refresh))return;await k(),H("[refresh] opencode main oauth refreshed in background",{expires:Y.expires})}catch(X){H("[refresh] opencode main oauth refresh failed",{message:X instanceof Error?X.message:String(X)})}};if(T=setInterval(()=>{V()},Wj),"unref"in T)T.unref()},R0=function(V,X){if(V instanceof Request&&V.body)return!1;return X==null||typeof X==="string"},l1=function(V){return V.has("x-parent-session-id")},f0=function(V){return V.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(V)},p1=function(V){return V?.quota?.enabled===!0},c1=function(V,X){let Y=Date.now();if(f||Y<y)return;f=y0(V,X).catch((I)=>{throw y=Y+_1(X),I}).finally(()=>{f=null}),f.catch(()=>{})};for(let V of Object.values(O.models))V.cost={input:0,output:0,cache:{read:0,write:0}};let Q=null,U=null,f=null,y=0;async function k(){if(!Q)Q=(async()=>{let Y=null,I=null,B=null;async function _(z){let v=await S()??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};v.refresh=v.refresh??{},z(v),await M0(v)}for(let z=0;z<=2;z++){let v=null;try{if(z>0){let x=500*2**(z-1);await new Promise((I0)=>setTimeout(I0,x))}if(v=await $(),!v.refresh)throw Error("Token refresh failed: missing refresh token");let P=await S(),W=j0(v.refresh),w=P?.refresh?.mainLastRefreshError;if(H("[refresh] opencode main oauth refresh check",{attempt:z,expiresInMs:v.expires?v.expires-Date.now():void 0,hasBackoff:Boolean(w),backoffActive:w?J0(w,v.refresh,Date.now()):!1,retryCount:w?.retryCount,nextRetryAt:w?.nextRetryAt}),w&&J0(w,v.refresh,Date.now()))throw H("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:w.nextRetryAt,retryCount:w.retryCount}),Error(N1(w,Date.now()));if(P?.refresh?.mainRefreshLeaseUntil&&P.refresh.mainRefreshLeaseUntil>Date.now()&&P.refresh.mainRefreshLeaseTokenHash===W)throw H("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:P.refresh.mainRefreshLeaseUntil}),Error("Claude OAuth refresh is already in progress");let N=await Y1({name:"opencode-main-oauth-refresh",ttlMs:120000});if(!N)throw H("[refresh] opencode main oauth refresh skipped file lock"),Error("Claude OAuth refresh is already in progress");B=N.release,Y=Pj(),I=W,await _((x)=>{x.refresh=x.refresh??{},x.refresh.mainRefreshLeaseId=Y??void 0,x.refresh.mainRefreshLeaseUntil=Date.now()+120000,x.refresh.mainRefreshLeaseTokenHash=W});let C=await S();if(H("[refresh] opencode main oauth refresh lease acquired",{attempt:z,leaseUntil:Date.now()+120000}),C?.refresh?.mainRefreshLeaseId!==Y||C.refresh.mainRefreshLeaseTokenHash!==W)throw Error("Claude OAuth refresh is already in progress");H("[refresh] opencode main oauth refresh request start",{attempt:z});let R=await W1({refreshToken:v.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:R.refresh,access:R.access,expires:R.expires}}),await _((x)=>{if(!x?.refresh)return;if(x.refresh.mainLastRefreshError=void 0,x.refresh.mainRefreshLeaseId===Y)x.refresh.mainRefreshLeaseId=void 0,x.refresh.mainRefreshLeaseUntil=void 0,x.refresh.mainRefreshLeaseTokenHash=void 0}),H("[refresh] opencode main oauth refresh succeeded",{attempt:z,expiresInMs:R.expires-Date.now()}),R.access}catch(P){let W=P instanceof Error&&(P.message.includes("fetch failed")||("code"in P)&&(P.code==="ECONNRESET"||P.code==="ECONNREFUSED"||P.code==="ETIMEDOUT"||P.code==="UND_ERR_CONNECT_TIMEOUT"));if(z<2&&(W||P instanceof N0&&P.status>=500))continue;H("[refresh] opencode main oauth refresh attempt failed",{attempt:z,error:P instanceof Error?P.message:String(P),transient:W});let w=v?.refresh;if(w&&P instanceof N0)await _((N)=>{N.refresh=N.refresh??{},N.refresh.mainLastRefreshError=v1({error:P,now:Date.now(),refreshToken:w,previous:N.refresh.mainLastRefreshError})});throw P}finally{if(Y)await _((P)=>{if(!P?.refresh)return;if(P.refresh.mainRefreshLeaseId===Y&&P.refresh.mainRefreshLeaseTokenHash===I)P.refresh.mainRefreshLeaseId=void 0,P.refresh.mainRefreshLeaseUntil=void 0,P.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await B?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{Q=null});return Q}Z=k,i1();async function C0(V,X){if(!V.body||V.status!==200)return X?.mark("inspect_stream_skip",{status:V.status}),{response:V,rateLimited:!1};if(V.headers.get("x-cortexkit-relay-optimistic")==="true")return X?.mark("inspect_stream_skip",{status:V.status,reason:"optimistic_relay"}),{response:V,rateLimited:!1};let Y=M(),I=V.body.getReader(),B=[],_=new TextDecoder,z="",v=0;while(!z.includes(`
4
+
5
+ `)&&z.length<65536){let{done:W,value:w}=await I.read();if(W)break;if(B.push(w),v+=w.byteLength,z+=_.decode(w,{stream:!0}),f0(z))break}if(f0(z))return await I.cancel().catch(()=>{}),X?.mark("inspect_stream_first_event",{ms:q(M()-Y),bytes:v,rateLimited:!0}),{response:V,rateLimited:!0};let P=new ReadableStream({start(W){for(let w of B)W.enqueue(w)},async pull(W){let{done:w,value:N}=await I.read();if(w){W.close();return}W.enqueue(N)},cancel(W){return I.cancel(W)}});return X?.mark("inspect_stream_first_event",{ms:q(M()-Y),bytes:v,rateLimited:!1}),{response:new Response(P,{status:V.status,statusText:V.statusText,headers:V.headers}),rateLimited:!1}}async function T0(V,X,Y,I,B="unknown"){let _=M(),z=Z1(V,X),v=z.get("x-session-affinity")||z.get("x-opencode-session"),P=l1(z);z.delete("x-parent-session-id"),z.delete("x-session-affinity"),z.delete("x-opencode-session");let W=X?.body,w;if(W&&typeof W==="string")try{let g=JSON.parse(W);if(typeof g.model==="string")w=g.model}catch{}let N=await S0(Y,w),C=typeof W==="string"?W.length:void 0;if(W&&typeof W==="string"){let g=M(),p=(()=>{if(!f1())return!1;try{return r(JSON.parse(W).model)}catch{return!1}})();W=await P1(W,{cache1hEnabled:!P&&Z0(),cache1hMode:$0(),fastModeEnabled:p,identity:N});try{d(z,Y,{body:JSON.parse(W),identity:N})}catch{d(z,Y,{identity:N})}if(p)L0(z);I?.mark("rewrite_body",{route:B,ms:q(M()-g),originalBytes:C,rewrittenBytes:W.length,cacheEnabled:!P&&Z0(),cacheMode:$0(),fastModeEnabled:p,subagent:P})}let R=G1(V);if(B==="main"&&typeof W==="string"&&!P&&Z0()&&$0()==="hybrid"){let g=await S();if((await G.track({sessionId:v,url:R.url?.toString()??R.input.toString(),headers:z,bodyText:W,storage:g,cacheMode:"hybrid"})).tracked)I?.mark("cachekeep_track",{session:v})}let x=()=>fetch(R.input,{...X,body:W,headers:z,...$1()&&{tls:{rejectUnauthorized:!1}}}),I0=M(),g0=await g1({config:F,input:R.input,init:X,headers:z,body:W,fallback:x,affinity:v,optimisticResponse:F?.transport==="websocket"});return I?.mark("send_headers_received",{route:B,ms:q(M()-I0),status:g0.status,relayConfigured:F!=null,totalSendWithAccessMs:q(M()-_)}),g0}async function y0(V,X){let Y=Date.now(),I=await q0({accessToken:V});return U={accessToken:V,refreshAfter:F1(I,X,Y),quota:I},I}async function o1(V,X){let Y=Date.now();if(U?.accessToken!==V)return await y0(V,X);if(Y>=U.refreshAfter)c1(V,X);return U.quota}async function k0(V,X,Y,I,B,_){if(!Y.length)return B??null;await B?.body?.cancel().catch(()=>{});let z=B??null;for(let[v,P]of Y.entries()){let W=P.access;if(!W)continue;let w=await T0(V,X,W,_,`fallback_${v}`);z=w;let N=x0(w.status,I);if(!N){let C=await C0(w,_);w=C.response,z=w,N=C.rateLimited}if(!N)return await K.markUsed(P),w;if(v<Y.length-1)await w.body?.cancel().catch(()=>{})}return z}async function t1(V,X,Y,I,B,_){if(!R0(V,X?.body))return Y;let z=M(),v=_??await S();B?.mark("fallback_load_storage",{ms:q(M()-z),cached:!!_});let P=Y,W=x0(P.status,v);if(!W){let N=await C0(P,B);P=N.response,W=N.rateLimited}if(!W)return P;let w=I;if(!w){let N=M();w=await K.getUsableFallbackAccounts(),B?.mark("fallback_get_accounts",{ms:q(M()-N),accounts:w.length})}return await k0(V,X,w,v,P,B)??P}return{apiKey:"",async fetch(V,X){let Y=X?.body,I=Ij({bodyBytes:typeof Y==="string"?Y.length:void 0,relayConfigured:F!=null}),B=M(),_=await $();if(I.mark("get_auth",{ms:q(M()-B),authType:_.type,hasAccess:Boolean(_.access)}),_.type!=="oauth"){let N=await fetch(V,X);return I.done("non_oauth_passthrough",{status:N.status}),N}if(await h(_.refresh),!_.access||!_.expires||_.expires<Date.now()){H("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(_.access),expiresInMs:_.expires?_.expires-Date.now():void 0});let N=M();_.access=await k(),I.mark("refresh_main_access",{ms:q(M()-N)})}if(!_.access)throw I.done("missing_access_error"),Error("OAuth access token is missing after refresh");let z=M(),v=await S();I.mark("load_storage",{ms:q(M()-z)});let P;if(R0(V,X?.body)&&p1(v))try{let N=M(),C=await o1(_.access,v);if(I.mark("main_quota_for_routing",{ms:q(M()-N),passes:H0(C,v)}),!H0(C,v)){let R=M();P=await K.getUsableFallbackAccounts(),I.mark("preselect_fallback_accounts",{ms:q(M()-R),accounts:P.length});let x=await k0(V,X,P,v,void 0,I);if(x)return I.done("return_preselected_fallback",{status:x.status}),v0(x)}}catch(N){I.mark("main_quota_for_routing_error",{error:N instanceof Error?N.message:String(N)})}let W=await T0(V,X,_.access,I,"main"),w=await t1(V,X,W,P,I,v);return I.done("return_response",{status:w.status}),v0(w)}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let $=await _0("max");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(O)=>{return F0(O,$.verifier,$.redirectUri,$.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let $=await _0("console");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(O)=>{let L=await F0(O,$.verifier,$.redirectUri,$.state);if(L.type==="failed")return L;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${L.access}`}}).then((U)=>U.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{Bj as AnthropicAuthPlugin};