-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
1632 lines (1378 loc) · 49.9 KB
/
plugin.js
File metadata and controls
1632 lines (1378 loc) · 49.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* OpenQwenCode plugin
*
* - uses the qwen.ai OAuth device flow
* - persists and refreshes tokens in qwen-code compatible format
* - keeps local credentials as the single source of truth
* - syncs safely across processes with a lockfile + atomic writes
* - exposes only the single upstream-supported free model: coder-model
*/
import { spawn } from 'node:child_process';
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { homedir, hostname } from 'node:os';
import { join } from 'node:path';
const require = createRequire(import.meta.url);
const { version: PACKAGE_VERSION } = require('./package.json');
const PROVIDER_ID = 'openqwencode';
const PROVIDER_NAME = 'OpenQwenCode';
const MODEL_ID = 'coder-model';
const OFFICIAL_BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
const CONFIGURED_BASE_URL = normalizeBaseURL(process.env.OPENQWENCODE_BASE_URL);
const DEFAULT_BASE_URL = CONFIGURED_BASE_URL ?? OFFICIAL_BASE_URL;
const LEGACY_PROVIDER_IDS = ['qwen', 'qwen-code'];
const CREDS_DIR_MODE = 0o700;
const CREDS_FILE_MODE = 0o600;
const REFRESH_BUFFER_MS = 60_000;
const CACHE_RELOAD_INTERVAL_MS = 5_000;
const LOCK_STALE_MS = 30_000;
const LOCK_TIMEOUT_MS = 15_000;
const LOCK_RETRY_INTERVAL_MS = 100;
const LOCK_MAX_RETRY_INTERVAL_MS = 1_000;
const DEVICE_POLL_MARGIN_MS = 3_000;
const DEVICE_POLL_MAX_INTERVAL_MS = 15_000;
const REFRESH_MAX_ATTEMPTS = 3;
const REQUEST_MAX_ATTEMPTS = 3;
const REQUEST_THROTTLE_MIN_SPACING_MS = 300;
const REQUEST_THROTTLE_JITTER_MS = 150;
const BACKOFF_JITTER_RATIO = 0.2;
const RATE_LIMIT_CATEGORY = Object.freeze({
BURST: 'burst',
QUOTA: 'quota',
TRANSIENT: 'transient',
});
const RATE_LIMIT_BACKOFF_PRESETS = {
[RATE_LIMIT_CATEGORY.BURST]: { baseMs: 2_000, maxMs: 15_000 },
[RATE_LIMIT_CATEGORY.QUOTA]: { baseMs: 10_000, maxMs: 60_000 },
[RATE_LIMIT_CATEGORY.TRANSIENT]: { baseMs: 3_000, maxMs: 30_000 },
};
const DEBUG_ENABLED = /^(1|true|yes)$/i.test(process.env.OPENQWENCODE_DEBUG ?? '');
const SYSTEM_MESSAGE =
'You are Qwen Code, an interactive CLI agent developed by Alibaba Group, specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.';
const DEFAULT_REQUEST_CHANNEL = 'opencode';
const DEFAULT_REQUEST_SESSION_ID = randomUUID();
const UPSTREAM_USER_AGENT_PRODUCT = 'QwenCode';
const QWEN_OAUTH_CONFIG = {
baseUrl: 'https://chat.qwen.ai',
deviceCodeEndpoint: 'https://chat.qwen.ai/api/v1/oauth2/device/code',
tokenEndpoint: 'https://chat.qwen.ai/api/v1/oauth2/token',
clientId: 'f0304373b74a44d2b584a3fb70ca9e56',
scope: 'openid profile email model.completion',
grantType: 'urn:ietf:params:oauth:grant-type:device_code',
};
const QWEN_MODELS = {
[MODEL_ID]: {
id: MODEL_ID,
name: 'Qwen Coder',
contextWindow: 1048576,
maxOutput: 65536,
description:
'Official free Qwen Code OAuth model. Supports coding and image input through the same coder-model alias.',
reasoning: false,
cost: { input: 0, output: 0 },
},
};
let credentialCache = null;
let credentialCacheMtimeMs = 0;
let credentialCacheCheckedAt = 0;
let telemetryCredentialCache = null;
let telemetryCredentialCacheMtimeMs = 0;
let telemetryCredentialCacheCheckedAt = 0;
let authBootstrapConsumed = false;
function getCredsDir() {
return join(homedir(), '.qwen');
}
function getCredsPath() {
return join(getCredsDir(), 'oauth_creds.json');
}
function getTelemetryCredsPath() {
return join(getCredsDir(), 'telemetry_creds.json');
}
function getLockPath() {
return join(getCredsDir(), 'oauth_creds.lock');
}
let activeAuthSession = null;
let inFlightRefreshPromise = null;
let nextAllowedRequestAt = 0;
let requestThrottleChain = Promise.resolve();
export const qwenAuthEvents = new EventEmitter();
class SlowDownError extends Error {
constructor(retryAfterMs = null) {
super('slow_down');
this.name = 'SlowDownError';
this.retryAfterMs = retryAfterMs;
}
}
class RetryableHttpError extends Error {
constructor(message, status, retryAfterMs = null) {
super(message);
this.name = 'RetryableHttpError';
this.status = status;
this.retryAfterMs = retryAfterMs;
}
}
function debugLog(message, error) {
if (!DEBUG_ENABLED) return;
const detail = error instanceof Error ? error.message : error ? String(error) : '';
console.debug(`[openqwencode] ${message}${detail ? `: ${detail}` : ''}`);
}
function createAbortError(message = 'Operation aborted') {
const error = new Error(message);
error.name = 'AbortError';
return error;
}
function isAbortError(error) {
return error instanceof Error && error.name === 'AbortError';
}
function throwIfAborted(signal) {
if (!signal?.aborted) return;
throw signal.reason instanceof Error
? signal.reason
: createAbortError(typeof signal.reason === 'string' ? signal.reason : 'Operation aborted');
}
async function sleep(ms, signal) {
if (!ms || ms <= 0) return;
throwIfAborted(signal);
await new Promise((resolve, reject) => {
const timer = setTimeout(() => {
cleanup();
resolve();
}, ms);
const onAbort = () => {
cleanup();
reject(
signal.reason instanceof Error
? signal.reason
: createAbortError(typeof signal.reason === 'string' ? signal.reason : 'Operation aborted'),
);
};
const cleanup = () => {
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
};
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function waitForPromiseWithSignal(promise, signal) {
throwIfAborted(signal);
if (!signal) return promise;
return Promise.race([
promise,
new Promise((_, reject) => {
const onAbort = () => {
cleanup();
reject(
signal.reason instanceof Error
? signal.reason
: createAbortError(typeof signal.reason === 'string' ? signal.reason : 'Operation aborted'),
);
};
const cleanup = () => {
signal.removeEventListener('abort', onAbort);
};
signal.addEventListener('abort', onAbort, { once: true });
promise.finally(cleanup);
}),
]);
}
function didCredentialsChange(previous, next) {
if (!previous || !next) return false;
return (
previous.accessToken !== next.accessToken ||
previous.refreshToken !== next.refreshToken ||
previous.expiryDate !== next.expiryDate ||
previous.resourceUrl !== next.resourceUrl
);
}
function parseJson(text) {
try {
return text ? JSON.parse(text) : {};
} catch (error) {
debugLog('Failed to parse JSON payload', error);
return {};
}
}
function parseRetryAfterMs(headers) {
const retryAfterMsHeader = headers?.get?.('retry-after-ms');
const retryAfterMs = Number(retryAfterMsHeader);
if (Number.isFinite(retryAfterMs) && retryAfterMs > 0) return retryAfterMs;
const retryAfterHeader = headers?.get?.('retry-after');
if (!retryAfterHeader) return null;
const retryAfterSeconds = Number(retryAfterHeader);
if (Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0) {
return retryAfterSeconds * 1000;
}
const retryAfterDate = Date.parse(retryAfterHeader);
if (Number.isNaN(retryAfterDate)) return null;
return Math.max(retryAfterDate - Date.now(), 0);
}
function normalizeHttpUrl(candidate) {
if (typeof candidate !== 'string' || !candidate.trim()) return null;
try {
const parsed = new URL(candidate.trim());
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return parsed.toString();
} catch {
// ignore invalid configured urls
}
return null;
}
function normalizeServiceBaseUrl(candidate) {
const normalized = normalizeHttpUrl(candidate);
return normalized ? normalized.replace(/\/+$/, '') : null;
}
function resolveTelemetryLinkBaseUrl(telemetryEndpoint) {
const normalized = normalizeHttpUrl(telemetryEndpoint);
if (!normalized) return null;
try {
const parsed = new URL(normalized);
const trimmedPath = parsed.pathname.replace(/\/+$/, '');
parsed.pathname = trimmedPath.toLowerCase().endsWith('/telemetry')
? trimmedPath.slice(0, -'/telemetry'.length) || '/'
: '/';
parsed.search = '';
parsed.hash = '';
return parsed.pathname === '/' ? parsed.origin : `${parsed.origin}${parsed.pathname}`;
} catch {
return null;
}
}
function getTelemetryEndpoint() {
return normalizeHttpUrl(process.env.OPENQWENCODE_TELEMETRY_ENDPOINT);
}
function getTelemetryLinkBaseUrl() {
return (
normalizeServiceBaseUrl(process.env.OPENQWENCODE_TELEMETRY_LINK_URL) ??
resolveTelemetryLinkBaseUrl(getTelemetryEndpoint())
);
}
function normalizeBaseURL(candidate) {
const normalized = normalizeHttpUrl(candidate);
if (!normalized) return null;
return normalized.endsWith('/v1') ? normalized : `${normalized.replace(/\/+$/, '')}/v1`;
}
function getBackoffMs({ attempt = 0, retryAfterMs = null, baseMs = 1000, maxMs = 30_000 } = {}) {
if (Number.isFinite(retryAfterMs) && retryAfterMs > 0) return retryAfterMs;
const baseDelayMs = Math.min(baseMs * 2 ** attempt, maxMs);
const jitterWindowMs = Math.floor(baseDelayMs * BACKOFF_JITTER_RATIO);
if (jitterWindowMs <= 0) return baseDelayMs;
return Math.min(baseDelayMs + Math.floor(Math.random() * (jitterWindowMs + 1)), maxMs);
}
function classifyRateLimitCategory(headers, status) {
if (status >= 500) return RATE_LIMIT_CATEGORY.TRANSIENT;
if (status !== 429) return RATE_LIMIT_CATEGORY.BURST;
const errorCode = (headers?.get?.('x-error-code') ?? '').toLowerCase();
if (/quota|exhausted|insufficient/.test(errorCode)) return RATE_LIMIT_CATEGORY.QUOTA;
if (/internal|timeout|service_unavailable|gateway/.test(errorCode)) return RATE_LIMIT_CATEGORY.TRANSIENT;
return RATE_LIMIT_CATEGORY.BURST;
}
function getRateLimitBackoffMs({ attempt = 0, retryAfterMs = null, category = RATE_LIMIT_CATEGORY.BURST } = {}) {
const preset = RATE_LIMIT_BACKOFF_PRESETS[category] ?? RATE_LIMIT_BACKOFF_PRESETS[RATE_LIMIT_CATEGORY.BURST];
return getBackoffMs({ attempt, retryAfterMs, baseMs: preset.baseMs, maxMs: preset.maxMs });
}
function pickErrorMessage(...candidates) {
for (const candidate of candidates) {
if (typeof candidate === 'string' && candidate.trim()) return candidate.trim();
}
return null;
}
async function createOpenAICompatibleErrorResponse(
response,
{ defaultMessage, defaultType, defaultCode },
) {
let responseText = '';
try {
responseText = await response.text();
} catch {
// ignore body read failures and fall back to a synthetic error payload
}
const parsed = parseJson(responseText);
const upstreamError = parsed?.error && typeof parsed.error === 'object' ? parsed.error : null;
const message = pickErrorMessage(
upstreamError?.message,
parsed?.message,
response.statusText,
defaultMessage,
) ?? defaultMessage;
const headers = new Headers(response.headers);
headers.set('content-type', 'application/json; charset=utf-8');
headers.delete('content-length');
headers.delete('content-encoding');
return new Response(
JSON.stringify({
error: {
message,
type: typeof upstreamError?.type === 'string' && upstreamError.type ? upstreamError.type : defaultType,
param: upstreamError?.param ?? null,
code:
upstreamError?.code != null && upstreamError.code !== ''
? upstreamError.code
: defaultCode,
},
}),
{
status: response.status,
statusText: response.statusText,
headers,
},
);
}
async function normalizeBackoffResponse(response) {
const category = classifyRateLimitCategory(response.headers, response.status);
if (response.status === 429) {
if (category === RATE_LIMIT_CATEGORY.QUOTA) {
return createOpenAICompatibleErrorResponse(response, {
defaultMessage: 'Upstream quota exhausted. Please wait before retrying.',
defaultType: 'rate_limit_error',
defaultCode: 'quota_exceeded',
});
}
return createOpenAICompatibleErrorResponse(response, {
defaultMessage: 'Rate limited by upstream. Please retry shortly.',
defaultType: 'rate_limit_error',
defaultCode: 'rate_limit_exceeded',
});
}
return createOpenAICompatibleErrorResponse(response, {
defaultMessage: 'Upstream service temporarily failed. Please retry shortly.',
defaultType: 'server_error',
defaultCode: `upstream_${response.status}`,
});
}
async function waitForRequestThrottle(signal) {
let release;
const previous = requestThrottleChain;
requestThrottleChain = new Promise(resolve => {
release = resolve;
});
await previous;
let waitMs = 0;
try {
const now = Date.now();
const jitterMs = Math.floor(Math.random() * (REQUEST_THROTTLE_JITTER_MS + 1));
const scheduledAt = Math.max(now, nextAllowedRequestAt) + jitterMs;
nextAllowedRequestAt = scheduledAt + REQUEST_THROTTLE_MIN_SPACING_MS;
waitMs = Math.max(scheduledAt - now, 0);
} finally {
release();
}
if (waitMs > 0) {
await sleep(waitMs, signal);
}
}
function base64urlEncode(buffer) {
return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
function generatePKCE() {
const verifier = base64urlEncode(randomBytes(32));
const challenge = base64urlEncode(createHash('sha256').update(verifier).digest());
return { verifier, challenge };
}
function resolveBaseURL(resourceUrl) {
if (CONFIGURED_BASE_URL) return CONFIGURED_BASE_URL;
if (!resourceUrl || typeof resourceUrl !== 'string') return DEFAULT_BASE_URL;
const normalized = resourceUrl.startsWith('http') ? resourceUrl : `https://${resourceUrl}`;
return normalized.endsWith('/v1') ? normalized : `${normalized.replace(/\/+$/, '')}/v1`;
}
function getDeviceCode() {
const seed = `${hostname()}:${process.platform}:${process.arch}`;
return createHash('sha256').update(seed).digest('hex').slice(0, 12);
}
function buildTelemetryEvent({ input, status, attempts, startedAt }) {
const url = (() => {
try {
return new URL(input instanceof Request ? input.url : String(input));
} catch {
return null;
}
})();
return {
ts: new Date().toISOString(),
deviceCode: getDeviceCode(),
requestCount: 1,
attempts,
status,
durationMs: Math.max(Date.now() - startedAt, 0),
path: url?.pathname ?? null,
};
}
async function sendTelemetryEvent(event) {
const telemetryEndpoint = getTelemetryEndpoint();
if (!telemetryEndpoint) return;
try {
const telemetryCreds = await loadTelemetryCredentialsFromDisk();
const headers = { 'content-type': 'application/json' };
if (telemetryCreds?.linkToken) {
headers.Authorization = `Bearer ${telemetryCreds.linkToken}`;
}
await globalThis.fetch(telemetryEndpoint, {
method: 'POST',
headers,
body: JSON.stringify(event),
signal: AbortSignal.timeout?.(2000),
});
} catch (error) {
debugLog('Telemetry delivery failed', error);
}
}
async function requestTelemetryLink(deviceCode, signal) {
const telemetryLinkBaseUrl = getTelemetryLinkBaseUrl();
if (!telemetryLinkBaseUrl) {
throw new Error('Set OPENQWENCODE_TELEMETRY_ENDPOINT or OPENQWENCODE_TELEMETRY_LINK_URL first');
}
const response = await globalThis.fetch(`${telemetryLinkBaseUrl}/device-link/request`, {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({
deviceId: deviceCode,
deviceName: hostname(),
pluginVersion: PACKAGE_VERSION,
}),
signal,
});
const text = await response.text();
const data = parseJson(text);
if (!response.ok) {
throw new Error(`Device link request failed: ${data.error ?? response.status}`);
}
if (!data?.pollToken || !data?.linkCode) {
throw new Error('Device link request returned an invalid payload');
}
return {
pollToken: data.pollToken,
linkCode: data.linkCode,
expiresIn: typeof data.expiresIn === 'number' ? data.expiresIn : 900,
pollIntervalMs: typeof data.pollIntervalMs === 'number' ? data.pollIntervalMs : 5000,
verificationUrl: normalizeVerificationUrl(data.verificationUrl ?? `${telemetryLinkBaseUrl}/link`),
};
}
async function pollTelemetryLink(pollToken, signal) {
const telemetryLinkBaseUrl = getTelemetryLinkBaseUrl();
if (!telemetryLinkBaseUrl) {
throw new Error('Telemetry link base URL is not configured');
}
const response = await globalThis.fetch(`${telemetryLinkBaseUrl}/device-link/poll`, {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ pollToken }),
signal,
});
const text = await response.text();
const data = parseJson(text);
if (!response.ok) {
throw new Error(`Device link polling failed: ${data.error ?? response.status}`);
}
return data;
}
export async function linkDevice({ signal, log = console.log, autoOpen = true } = {}) {
const deviceCode = getDeviceCode();
const deviceLink = await requestTelemetryLink(deviceCode, signal);
if (autoOpen) {
openBrowser(deviceLink.verificationUrl);
}
if (typeof log === 'function') {
log(`Visit ${deviceLink.verificationUrl}`);
log(`Enter code: ${deviceLink.linkCode}`);
}
const timeoutAt = Date.now() + deviceLink.expiresIn * 1000;
const pollIntervalMs = Math.max(deviceLink.pollIntervalMs, 1000);
while (Date.now() < timeoutAt) {
throwIfAborted(signal);
const status = await pollTelemetryLink(deviceLink.pollToken, signal);
if (status?.status === 'approved' && typeof status.linkToken === 'string' && status.linkToken) {
await saveTelemetryCredentials({
linkToken: status.linkToken,
linkedAt: Date.now(),
deviceCode,
verificationUrl: deviceLink.verificationUrl,
});
if (typeof log === 'function') {
log('Device linked successfully.');
}
return {
status: 'approved',
linkCode: deviceLink.linkCode,
linkToken: status.linkToken,
deviceCode,
verificationUrl: deviceLink.verificationUrl,
};
}
if (status?.status === 'expired') {
throw new Error('Device link expired before it was approved');
}
await sleep(pollIntervalMs, signal);
}
throw new Error('Device link timed out before it was approved');
}
function normalizeVerificationUrl(candidate) {
if (typeof candidate === 'string' && candidate.trim()) {
try {
const parsed = new URL(candidate);
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return parsed.toString();
} catch {
// fall through
}
}
return QWEN_OAUTH_CONFIG.baseUrl;
}
function openBrowser(url) {
try {
const command =
process.platform === 'darwin'
? 'open'
: process.platform === 'win32'
? 'rundll32'
: 'xdg-open';
const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];
const child = spawn(command, args, { stdio: 'ignore', detached: true });
child.unref?.();
} catch {
// ignore browser open failures
}
}
function toFormBody(payload) {
const entries = Object.entries(payload)
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => [key, String(value)]);
return new URLSearchParams(entries).toString();
}
function normalizeCredentials(raw) {
if (!raw || typeof raw !== 'object') return null;
const accessToken = raw.access_token ?? raw.accessToken;
const refreshToken = raw.refresh_token ?? raw.refreshToken;
const resourceUrl = raw.resource_url ?? raw.resourceUrl;
const tokenType = raw.token_type ?? raw.tokenType ?? 'Bearer';
const expiryDateRaw = raw.expiry_date ?? raw.expiryDate;
const expiryDate =
typeof expiryDateRaw === 'number' ? expiryDateRaw : expiryDateRaw ? Number(expiryDateRaw) : undefined;
if (
(!accessToken || typeof accessToken !== 'string') &&
(!refreshToken || typeof refreshToken !== 'string')
) {
return null;
}
return {
accessToken: typeof accessToken === 'string' && accessToken ? accessToken : undefined,
tokenType: typeof tokenType === 'string' && tokenType ? tokenType : 'Bearer',
refreshToken: typeof refreshToken === 'string' && refreshToken ? refreshToken : undefined,
resourceUrl: typeof resourceUrl === 'string' && resourceUrl ? resourceUrl : undefined,
expiryDate: Number.isFinite(expiryDate) ? expiryDate : undefined,
scope: typeof raw.scope === 'string' && raw.scope ? raw.scope : undefined,
};
}
function serializeCredentials(creds) {
return JSON.stringify(
{
access_token: creds.accessToken,
token_type: creds.tokenType ?? 'Bearer',
refresh_token: creds.refreshToken,
resource_url: creds.resourceUrl,
expiry_date: creds.expiryDate,
scope: creds.scope,
},
null,
2,
);
}
function normalizeTelemetryCredentials(raw) {
if (!raw || typeof raw !== 'object') return null;
const linkToken = raw.link_token ?? raw.linkToken;
const linkedAtRaw = raw.linked_at ?? raw.linkedAt;
const linkedAt = typeof linkedAtRaw === 'number' ? linkedAtRaw : Number(linkedAtRaw);
const deviceCode = raw.device_code ?? raw.deviceCode;
const verificationUrl = raw.verification_url ?? raw.verificationUrl;
if (typeof linkToken !== 'string' || !linkToken) return null;
return {
linkToken,
linkedAt: Number.isFinite(linkedAt) ? linkedAt : Date.now(),
deviceCode: typeof deviceCode === 'string' && deviceCode ? deviceCode : getDeviceCode(),
verificationUrl: typeof verificationUrl === 'string' && verificationUrl ? verificationUrl : undefined,
};
}
function serializeTelemetryCredentials(creds) {
return JSON.stringify(
{
link_token: creds.linkToken,
linked_at: creds.linkedAt,
device_code: creds.deviceCode,
verification_url: creds.verificationUrl,
},
null,
2,
);
}
function updateCredentialCache(creds, mtimeMs = Date.now()) {
credentialCache = creds ? { ...creds } : null;
credentialCacheMtimeMs = creds ? mtimeMs : 0;
credentialCacheCheckedAt = Date.now();
}
function updateTelemetryCredentialCache(creds, mtimeMs = Date.now()) {
telemetryCredentialCache = creds ? { ...creds } : null;
telemetryCredentialCacheMtimeMs = creds ? mtimeMs : 0;
telemetryCredentialCacheCheckedAt = Date.now();
}
function isCredentialFresh(creds) {
return Boolean(creds?.accessToken) &&
(typeof creds.expiryDate !== 'number' || Date.now() <= creds.expiryDate - REFRESH_BUFFER_MS);
}
async function ensureCredentialsDir() {
await mkdir(getCredsDir(), { recursive: true, mode: CREDS_DIR_MODE });
}
async function maybeClearStaleLock() {
try {
const info = await stat(getLockPath());
if (Date.now() - info.mtimeMs <= LOCK_STALE_MS) return;
await rm(getLockPath(), { force: true });
debugLog('Removed stale credential lock');
} catch {
// ignore lock cleanup failures
}
}
async function acquireCredentialLock(signal) {
await ensureCredentialsDir();
const startedAt = Date.now();
let attempt = 0;
while (Date.now() - startedAt < LOCK_TIMEOUT_MS) {
throwIfAborted(signal);
try {
const handle = await open(getLockPath(), 'wx', CREDS_FILE_MODE);
try {
await handle.writeFile(JSON.stringify({ pid: process.pid, createdAt: Date.now() }));
} finally {
try {
await handle.close();
} catch {
// ignore close failures
}
}
return async () => {
try {
await rm(getLockPath(), { force: true });
} catch {
// ignore lock cleanup failures
}
};
} catch (error) {
if (error?.code !== 'EEXIST') throw error;
await maybeClearStaleLock();
await sleep(
getBackoffMs({
attempt,
baseMs: LOCK_RETRY_INTERVAL_MS,
maxMs: LOCK_MAX_RETRY_INTERVAL_MS,
}),
signal,
);
attempt += 1;
}
}
throw new Error('Timed out acquiring credential lock');
}
async function withCredentialLock(fn, signal) {
const release = await acquireCredentialLock(signal);
try {
return await fn();
} finally {
await release();
}
}
async function loadCredentialsFromDisk({ force = false } = {}) {
const now = Date.now();
if (credentialCache && !force && now - credentialCacheCheckedAt < CACHE_RELOAD_INTERVAL_MS) {
return credentialCache;
}
try {
const info = await stat(getCredsPath());
if (credentialCache && !force && credentialCacheMtimeMs === info.mtimeMs) {
credentialCacheCheckedAt = now;
return credentialCache;
}
const raw = parseJson(await readFile(getCredsPath(), 'utf-8'));
const creds = normalizeCredentials(raw);
updateCredentialCache(creds, info.mtimeMs);
return creds;
} catch (error) {
if (error?.code !== 'ENOENT') {
debugLog('Failed to read credential file', error);
}
updateCredentialCache(null);
return null;
}
}
async function loadTelemetryCredentialsFromDisk({ force = false } = {}) {
const now = Date.now();
if (telemetryCredentialCache && !force && now - telemetryCredentialCacheCheckedAt < CACHE_RELOAD_INTERVAL_MS) {
return telemetryCredentialCache;
}
try {
const info = await stat(getTelemetryCredsPath());
if (telemetryCredentialCache && !force && telemetryCredentialCacheMtimeMs === info.mtimeMs) {
telemetryCredentialCacheCheckedAt = now;
return telemetryCredentialCache;
}
const raw = parseJson(await readFile(getTelemetryCredsPath(), 'utf-8'));
const creds = normalizeTelemetryCredentials(raw);
updateTelemetryCredentialCache(creds, info.mtimeMs);
return creds;
} catch (error) {
if (error?.code !== 'ENOENT') {
debugLog('Failed to read telemetry credential file', error);
}
updateTelemetryCredentialCache(null);
return null;
}
}
async function persistCredentialsUnlocked(creds) {
const normalized = normalizeCredentials(creds);
if (!normalized?.accessToken && !normalized?.refreshToken) {
throw new Error('Cannot persist empty credentials');
}
await ensureCredentialsDir();
const credsPath = getCredsPath();
const tempPath = `${credsPath}.tmp.${randomUUID()}`;
const payload = serializeCredentials(normalized);
try {
await writeFile(tempPath, payload, { encoding: 'utf-8', mode: CREDS_FILE_MODE });
await rename(tempPath, credsPath);
const info = await stat(credsPath).catch(() => null);
updateCredentialCache(normalized, info?.mtimeMs ?? Date.now());
return normalized;
} finally {
await rm(tempPath, { force: true }).catch(() => {});
}
}
async function persistTelemetryCredentialsUnlocked(creds) {
const normalized = normalizeTelemetryCredentials(creds);
if (!normalized?.linkToken) {
throw new Error('Cannot persist empty telemetry credentials');
}
await ensureCredentialsDir();
const telemetryCredsPath = getTelemetryCredsPath();
const tempPath = `${telemetryCredsPath}.tmp.${randomUUID()}`;
const payload = serializeTelemetryCredentials(normalized);
try {
await writeFile(tempPath, payload, { encoding: 'utf-8', mode: CREDS_FILE_MODE });
await rename(tempPath, telemetryCredsPath);
const info = await stat(telemetryCredsPath).catch(() => null);
updateTelemetryCredentialCache(normalized, info?.mtimeMs ?? Date.now());
return normalized;
} finally {
await rm(tempPath, { force: true }).catch(() => {});
}
}
async function saveCredentials(creds) {
return withCredentialLock(() => persistCredentialsUnlocked(creds));
}
async function saveTelemetryCredentials(creds) {
return withCredentialLock(() => persistTelemetryCredentialsUnlocked(creds));
}
async function getStoredAuth(getAuth) {
if (authBootstrapConsumed) return null;
try {
return await getAuth();
} catch (error) {
debugLog('Failed to read OpenCode auth bootstrap state', error);
return null;
}
}
async function bootstrapCredentialsFromAuth(getAuth, signal) {
if (authBootstrapConsumed) return null;
const auth = await getStoredAuth(getAuth);
authBootstrapConsumed = true;
if (!auth || auth.type !== 'oauth') return null;
const bootstrapped = normalizeCredentials({
accessToken: auth.access,
refreshToken: auth.refresh,
expiryDate: auth.expires,
resourceUrl: auth.accountId,
});
if (!bootstrapped) return null;
return withCredentialLock(async () => {
const latest = await loadCredentialsFromDisk({ force: true });
if (latest) return latest;
if (isCredentialFresh(bootstrapped)) {
return persistCredentialsUnlocked(bootstrapped);
}
if (!bootstrapped.refreshToken) {
return bootstrapped.accessToken ? persistCredentialsUnlocked(bootstrapped) : null;
}
try {
const refreshed = await refreshAccessTokenWithRetry(
bootstrapped.refreshToken,
bootstrapped.resourceUrl,
signal,
);
return persistCredentialsUnlocked(refreshed);
} catch (error) {
debugLog('Failed to bootstrap credentials from OpenCode auth', error);
if (bootstrapped.accessToken) {
return persistCredentialsUnlocked(bootstrapped);
}
return null;
}
}, signal);
}
async function requestDeviceAuthorization(challenge, signal) {
throwIfAborted(signal);
const response = await fetch(QWEN_OAUTH_CONFIG.deviceCodeEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
'x-request-id': randomUUID(),
},
body: toFormBody({
client_id: QWEN_OAUTH_CONFIG.clientId,
scope: QWEN_OAUTH_CONFIG.scope,
code_challenge: challenge,
code_challenge_method: 'S256',
}),
signal,
});
const text = await response.text();
const retryAfterMs = parseRetryAfterMs(response.headers);
if (!response.ok) {
if (response.status === 429 || response.status >= 500) {
throw new RetryableHttpError(
`Device authorization failed with status ${response.status}`,
response.status,
retryAfterMs,
);
}