shortcutxl 0.2.12 → 0.2.13

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.
Files changed (110) hide show
  1. package/README.md +26 -26
  2. package/agent-docs/README.md +397 -397
  3. package/agent-docs/docs/compaction.md +390 -390
  4. package/agent-docs/docs/custom-provider.md +580 -580
  5. package/agent-docs/docs/extensions.md +1971 -1971
  6. package/agent-docs/docs/packages.md +209 -209
  7. package/agent-docs/docs/rpc.md +1317 -1317
  8. package/agent-docs/docs/sdk.md +962 -962
  9. package/agent-docs/docs/session.md +412 -412
  10. package/agent-docs/docs/termux.md +127 -127
  11. package/agent-docs/docs/tui.md +887 -887
  12. package/agent-docs/examples/README.md +25 -25
  13. package/agent-docs/examples/extensions/README.md +205 -205
  14. package/agent-docs/examples/extensions/antigravity-image-gen.ts +447 -447
  15. package/agent-docs/examples/extensions/auto-commit-on-exit.ts +49 -49
  16. package/agent-docs/examples/extensions/bash-spawn-hook.ts +30 -30
  17. package/agent-docs/examples/extensions/bookmark.ts +50 -50
  18. package/agent-docs/examples/extensions/built-in-tool-renderer.ts +256 -256
  19. package/agent-docs/examples/extensions/claude-rules.ts +86 -86
  20. package/agent-docs/examples/extensions/commands.ts +75 -75
  21. package/agent-docs/examples/extensions/confirm-destructive.ts +59 -59
  22. package/agent-docs/examples/extensions/custom-compaction.ts +126 -126
  23. package/agent-docs/examples/extensions/custom-footer.ts +63 -63
  24. package/agent-docs/examples/extensions/custom-header.ts +73 -73
  25. package/agent-docs/examples/extensions/custom-provider-anthropic/index.ts +660 -660
  26. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/index.ts +362 -362
  27. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/test.ts +88 -88
  28. package/agent-docs/examples/extensions/custom-provider-qwen-cli/index.ts +349 -349
  29. package/agent-docs/examples/extensions/dirty-repo-guard.ts +56 -56
  30. package/agent-docs/examples/extensions/doom-overlay/doom-component.ts +133 -133
  31. package/agent-docs/examples/extensions/doom-overlay/doom-keys.ts +108 -108
  32. package/agent-docs/examples/extensions/doom-overlay/index.ts +74 -74
  33. package/agent-docs/examples/extensions/dynamic-resources/index.ts +15 -15
  34. package/agent-docs/examples/extensions/dynamic-tools.ts +77 -77
  35. package/agent-docs/examples/extensions/event-bus.ts +43 -43
  36. package/agent-docs/examples/extensions/file-trigger.ts +41 -41
  37. package/agent-docs/examples/extensions/git-checkpoint.ts +53 -53
  38. package/agent-docs/examples/extensions/handoff.ts +155 -155
  39. package/agent-docs/examples/extensions/hello.ts +25 -25
  40. package/agent-docs/examples/extensions/inline-bash.ts +94 -94
  41. package/agent-docs/examples/extensions/input-transform.ts +43 -43
  42. package/agent-docs/examples/extensions/interactive-shell.ts +209 -209
  43. package/agent-docs/examples/extensions/mac-system-theme.ts +47 -47
  44. package/agent-docs/examples/extensions/message-renderer.ts +59 -59
  45. package/agent-docs/examples/extensions/minimal-mode.ts +430 -430
  46. package/agent-docs/examples/extensions/modal-editor.ts +90 -90
  47. package/agent-docs/examples/extensions/model-status.ts +31 -31
  48. package/agent-docs/examples/extensions/notify.ts +55 -55
  49. package/agent-docs/examples/extensions/overlay-qa-tests.ts +936 -936
  50. package/agent-docs/examples/extensions/overlay-test.ts +159 -159
  51. package/agent-docs/examples/extensions/permission-gate.ts +37 -37
  52. package/agent-docs/examples/extensions/pirate.ts +47 -47
  53. package/agent-docs/examples/extensions/plan-mode/index.ts +363 -363
  54. package/agent-docs/examples/extensions/preset.ts +418 -418
  55. package/agent-docs/examples/extensions/protected-paths.ts +30 -30
  56. package/agent-docs/examples/extensions/qna.ts +122 -122
  57. package/agent-docs/examples/extensions/question.ts +278 -278
  58. package/agent-docs/examples/extensions/questionnaire.ts +440 -440
  59. package/agent-docs/examples/extensions/rainbow-editor.ts +90 -90
  60. package/agent-docs/examples/extensions/reload-runtime.ts +37 -37
  61. package/agent-docs/examples/extensions/rpc-demo.ts +124 -124
  62. package/agent-docs/examples/extensions/sandbox/index.ts +324 -324
  63. package/agent-docs/examples/extensions/send-user-message.ts +97 -97
  64. package/agent-docs/examples/extensions/session-name.ts +27 -27
  65. package/agent-docs/examples/extensions/shutdown-command.ts +69 -69
  66. package/agent-docs/examples/extensions/snake.ts +343 -343
  67. package/agent-docs/examples/extensions/space-invaders.ts +566 -566
  68. package/agent-docs/examples/extensions/ssh.ts +233 -233
  69. package/agent-docs/examples/extensions/status-line.ts +40 -40
  70. package/agent-docs/examples/extensions/subagent/agents.ts +130 -130
  71. package/agent-docs/examples/extensions/subagent/index.ts +1068 -1068
  72. package/agent-docs/examples/extensions/summarize.ts +206 -206
  73. package/agent-docs/examples/extensions/system-prompt-header.ts +17 -17
  74. package/agent-docs/examples/extensions/timed-confirm.ts +72 -72
  75. package/agent-docs/examples/extensions/titlebar-spinner.ts +58 -58
  76. package/agent-docs/examples/extensions/todo.ts +314 -314
  77. package/agent-docs/examples/extensions/tool-override.ts +146 -146
  78. package/agent-docs/examples/extensions/tools.ts +145 -145
  79. package/agent-docs/examples/extensions/trigger-compact.ts +40 -40
  80. package/agent-docs/examples/extensions/truncated-tool.ts +194 -194
  81. package/agent-docs/examples/extensions/widget-placement.ts +17 -17
  82. package/agent-docs/examples/extensions/with-deps/index.ts +37 -37
  83. package/agent-docs/examples/rpc-extension-ui.ts +654 -654
  84. package/agent-docs/examples/sdk/01-minimal.ts +22 -22
  85. package/agent-docs/examples/sdk/02-custom-model.ts +48 -48
  86. package/agent-docs/examples/sdk/03-custom-prompt.ts +55 -55
  87. package/agent-docs/examples/sdk/04-skills.ts +53 -53
  88. package/agent-docs/examples/sdk/05-tools.ts +56 -56
  89. package/agent-docs/examples/sdk/06-extensions.ts +88 -88
  90. package/agent-docs/examples/sdk/07-context-files.ts +40 -40
  91. package/agent-docs/examples/sdk/08-prompt-templates.ts +47 -47
  92. package/agent-docs/examples/sdk/09-api-keys-and-oauth.ts +48 -48
  93. package/agent-docs/examples/sdk/10-settings.ts +54 -54
  94. package/agent-docs/examples/sdk/11-sessions.ts +48 -48
  95. package/agent-docs/examples/sdk/12-full-control.ts +82 -82
  96. package/agent-docs/examples/sdk/README.md +144 -144
  97. package/agent-docs/xll-spec.md +110 -110
  98. package/dist/core/auth-storage.js +21 -2
  99. package/package.json +1 -1
  100. package/xll/ShortcutXL.xll +0 -0
  101. package/xll/modules/debug_render.py +272 -272
  102. package/xll/modules/gameboy.py +241 -241
  103. package/xll/modules/pong.py +188 -188
  104. package/xll/modules/shortcut_xl/_diff_highlight.py +176 -0
  105. package/xll/modules/shortcut_xl/_log.py +12 -12
  106. package/xll/modules/shortcut_xl/_registry.py +44 -44
  107. package/xll/modules/stocks.py +100 -100
  108. /package/skills/{com-advanced-api → COM-advanced-api}/SKILL.md +0 -0
  109. /package/skills/{com-advanced-api → COM-advanced-api}/excel-type-library.py +0 -0
  110. /package/skills/{com-advanced-api → COM-advanced-api}/office-type-library.py +0 -0
@@ -1,349 +1,349 @@
1
- /**
2
- * Qwen CLI Provider Extension
3
- *
4
- * Provides access to Qwen models via OAuth authentication with chat.qwen.ai.
5
- * Uses device code flow with PKCE for secure browser-based authentication.
6
- *
7
- * Usage:
8
- * shortcut -e ./packages/coding-agent/examples/extensions/custom-provider-qwen-cli
9
- * # Then /login qwen-cli, or set QWEN_CLI_API_KEY=...
10
- */
11
-
12
- import type { ExtensionAPI, OAuthCredentials, OAuthLoginCallbacks } from 'shortcutxl';
13
-
14
- // =============================================================================
15
- // Constants
16
- // =============================================================================
17
-
18
- const QWEN_DEVICE_CODE_ENDPOINT = 'https://chat.qwen.ai/api/v1/oauth2/device/code';
19
- const QWEN_TOKEN_ENDPOINT = 'https://chat.qwen.ai/api/v1/oauth2/token';
20
- const QWEN_CLIENT_ID = 'f0304373b74a44d2b584a3fb70ca9e56';
21
- const QWEN_SCOPE = 'openid profile email model.completion';
22
- const QWEN_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
23
- const QWEN_DEFAULT_BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
24
- const QWEN_POLL_INTERVAL_MS = 2000;
25
-
26
- // =============================================================================
27
- // PKCE Helpers
28
- // =============================================================================
29
-
30
- async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {
31
- const array = new Uint8Array(32);
32
- crypto.getRandomValues(array);
33
- const verifier = btoa(String.fromCharCode(...array))
34
- .replace(/\+/g, '-')
35
- .replace(/\//g, '_')
36
- .replace(/=+$/, '');
37
-
38
- const encoder = new TextEncoder();
39
- const data = encoder.encode(verifier);
40
- const hash = await crypto.subtle.digest('SHA-256', data);
41
- const challenge = btoa(String.fromCharCode(...new Uint8Array(hash)))
42
- .replace(/\+/g, '-')
43
- .replace(/\//g, '_')
44
- .replace(/=+$/, '');
45
-
46
- return { verifier, challenge };
47
- }
48
-
49
- // =============================================================================
50
- // OAuth Implementation
51
- // =============================================================================
52
-
53
- interface DeviceCodeResponse {
54
- device_code: string;
55
- user_code: string;
56
- verification_uri: string;
57
- verification_uri_complete?: string;
58
- expires_in: number;
59
- interval?: number;
60
- }
61
-
62
- interface TokenResponse {
63
- access_token: string;
64
- refresh_token?: string;
65
- token_type: string;
66
- expires_in: number;
67
- resource_url?: string;
68
- }
69
-
70
- function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
71
- return new Promise((resolve, reject) => {
72
- if (signal?.aborted) {
73
- reject(new Error('Login cancelled'));
74
- return;
75
- }
76
- const timeout = setTimeout(resolve, ms);
77
- signal?.addEventListener(
78
- 'abort',
79
- () => {
80
- clearTimeout(timeout);
81
- reject(new Error('Login cancelled'));
82
- },
83
- { once: true }
84
- );
85
- });
86
- }
87
-
88
- async function startDeviceFlow(): Promise<{ deviceCode: DeviceCodeResponse; verifier: string }> {
89
- const { verifier, challenge } = await generatePKCE();
90
-
91
- const body = new URLSearchParams({
92
- client_id: QWEN_CLIENT_ID,
93
- scope: QWEN_SCOPE,
94
- code_challenge: challenge,
95
- code_challenge_method: 'S256'
96
- });
97
-
98
- const headers: Record<string, string> = {
99
- 'Content-Type': 'application/x-www-form-urlencoded',
100
- Accept: 'application/json'
101
- };
102
- const requestId = globalThis.crypto?.randomUUID?.();
103
- if (requestId) headers['x-request-id'] = requestId;
104
-
105
- const response = await fetch(QWEN_DEVICE_CODE_ENDPOINT, {
106
- method: 'POST',
107
- headers,
108
- body: body.toString()
109
- });
110
-
111
- if (!response.ok) {
112
- const text = await response.text();
113
- throw new Error(`Device code request failed: ${response.status} ${text}`);
114
- }
115
-
116
- const data = (await response.json()) as DeviceCodeResponse;
117
-
118
- if (!data.device_code || !data.user_code || !data.verification_uri) {
119
- throw new Error('Invalid device code response: missing required fields');
120
- }
121
-
122
- return { deviceCode: data, verifier };
123
- }
124
-
125
- async function pollForToken(
126
- deviceCode: string,
127
- verifier: string,
128
- intervalSeconds: number | undefined,
129
- expiresIn: number,
130
- signal?: AbortSignal
131
- ): Promise<TokenResponse> {
132
- const deadline = Date.now() + expiresIn * 1000;
133
- const resolvedIntervalSeconds =
134
- typeof intervalSeconds === 'number' && Number.isFinite(intervalSeconds) && intervalSeconds > 0
135
- ? intervalSeconds
136
- : QWEN_POLL_INTERVAL_MS / 1000;
137
- let intervalMs = Math.max(1000, Math.floor(resolvedIntervalSeconds * 1000));
138
-
139
- const handleTokenError = async (error: string, description?: string): Promise<boolean> => {
140
- switch (error) {
141
- case 'authorization_pending':
142
- await abortableSleep(intervalMs, signal);
143
- return true;
144
- case 'slow_down':
145
- intervalMs = Math.min(intervalMs + 5000, 10000);
146
- await abortableSleep(intervalMs, signal);
147
- return true;
148
- case 'expired_token':
149
- throw new Error('Device code expired. Please restart authentication.');
150
- case 'access_denied':
151
- throw new Error('Authorization denied by user.');
152
- default:
153
- throw new Error(`Token request failed: ${error} - ${description || ''}`);
154
- }
155
- };
156
-
157
- while (Date.now() < deadline) {
158
- if (signal?.aborted) {
159
- throw new Error('Login cancelled');
160
- }
161
-
162
- const body = new URLSearchParams({
163
- grant_type: QWEN_GRANT_TYPE,
164
- client_id: QWEN_CLIENT_ID,
165
- device_code: deviceCode,
166
- code_verifier: verifier
167
- });
168
-
169
- const response = await fetch(QWEN_TOKEN_ENDPOINT, {
170
- method: 'POST',
171
- headers: {
172
- 'Content-Type': 'application/x-www-form-urlencoded',
173
- Accept: 'application/json'
174
- },
175
- body: body.toString()
176
- });
177
-
178
- const responseText = await response.text();
179
- let data: (TokenResponse & { error?: string; error_description?: string }) | null = null;
180
- if (responseText) {
181
- try {
182
- data = JSON.parse(responseText) as TokenResponse & {
183
- error?: string;
184
- error_description?: string;
185
- };
186
- } catch {
187
- data = null;
188
- }
189
- }
190
-
191
- const error = data?.error;
192
- const errorDescription = data?.error_description;
193
-
194
- if (!response.ok) {
195
- if (error && (await handleTokenError(error, errorDescription))) {
196
- continue;
197
- }
198
- throw new Error(
199
- `Token request failed: ${response.status} ${response.statusText}. Response: ${responseText}`
200
- );
201
- }
202
-
203
- if (data?.access_token) {
204
- return data;
205
- }
206
-
207
- if (error && (await handleTokenError(error, errorDescription))) {
208
- continue;
209
- }
210
-
211
- throw new Error('Token request failed: missing access token in response');
212
- }
213
-
214
- throw new Error('Authentication timed out. Please try again.');
215
- }
216
-
217
- async function loginQwen(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
218
- const { deviceCode, verifier } = await startDeviceFlow();
219
-
220
- // Show verification URL and user code to user
221
- const authUrl = deviceCode.verification_uri_complete || deviceCode.verification_uri;
222
- const instructions = deviceCode.verification_uri_complete
223
- ? undefined // Code is already embedded in the URL
224
- : `Enter code: ${deviceCode.user_code}`;
225
- callbacks.onAuth({ url: authUrl, instructions });
226
-
227
- // Poll for token
228
- const tokenResponse = await pollForToken(
229
- deviceCode.device_code,
230
- verifier,
231
- deviceCode.interval,
232
- deviceCode.expires_in,
233
- callbacks.signal
234
- );
235
-
236
- // Calculate expiry with 5-minute buffer
237
- const expiresAt = Date.now() + tokenResponse.expires_in * 1000 - 5 * 60 * 1000;
238
-
239
- return {
240
- refresh: tokenResponse.refresh_token || '',
241
- access: tokenResponse.access_token,
242
- expires: expiresAt,
243
- // Store resource_url for API base URL if provided
244
- enterpriseUrl: tokenResponse.resource_url
245
- };
246
- }
247
-
248
- async function refreshQwenToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
249
- const body = new URLSearchParams({
250
- grant_type: 'refresh_token',
251
- refresh_token: credentials.refresh,
252
- client_id: QWEN_CLIENT_ID
253
- });
254
-
255
- const response = await fetch(QWEN_TOKEN_ENDPOINT, {
256
- method: 'POST',
257
- headers: {
258
- 'Content-Type': 'application/x-www-form-urlencoded',
259
- Accept: 'application/json'
260
- },
261
- body: body.toString()
262
- });
263
-
264
- if (!response.ok) {
265
- const text = await response.text();
266
- throw new Error(`Token refresh failed: ${response.status} ${text}`);
267
- }
268
-
269
- const data = (await response.json()) as TokenResponse;
270
-
271
- if (!data.access_token) {
272
- throw new Error('Token refresh failed: no access token in response');
273
- }
274
-
275
- const expiresAt = Date.now() + data.expires_in * 1000 - 5 * 60 * 1000;
276
-
277
- return {
278
- refresh: data.refresh_token || credentials.refresh,
279
- access: data.access_token,
280
- expires: expiresAt,
281
- enterpriseUrl: data.resource_url ?? credentials.enterpriseUrl
282
- };
283
- }
284
-
285
- function getQwenBaseUrl(resourceUrl?: string): string {
286
- if (!resourceUrl) {
287
- return QWEN_DEFAULT_BASE_URL;
288
- }
289
-
290
- let url = resourceUrl.startsWith('http') ? resourceUrl : `https://${resourceUrl}`;
291
- if (!url.endsWith('/v1')) {
292
- url = `${url}/v1`;
293
- }
294
- return url;
295
- }
296
-
297
- // =============================================================================
298
- // Extension Entry Point
299
- // =============================================================================
300
-
301
- export default function (shortcut: ExtensionAPI) {
302
- shortcut.registerProvider('qwen-cli', {
303
- baseUrl: QWEN_DEFAULT_BASE_URL,
304
- apiKey: 'QWEN_CLI_API_KEY',
305
- api: 'openai-completions',
306
-
307
- models: [
308
- {
309
- id: 'qwen3-coder-plus',
310
- name: 'Qwen3 Coder Plus',
311
- reasoning: false,
312
- input: ['text'],
313
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
314
- contextWindow: 1000000,
315
- maxTokens: 65536
316
- },
317
- {
318
- id: 'qwen3-coder-flash',
319
- name: 'Qwen3 Coder Flash',
320
- reasoning: false,
321
- input: ['text'],
322
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
323
- contextWindow: 1000000,
324
- maxTokens: 65536
325
- },
326
- {
327
- id: 'vision-model',
328
- name: 'Qwen3 VL Plus',
329
- reasoning: true,
330
- input: ['text', 'image'],
331
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
332
- contextWindow: 262144,
333
- maxTokens: 32768,
334
- compat: { supportsDeveloperRole: false, thinkingFormat: 'qwen' }
335
- }
336
- ],
337
-
338
- oauth: {
339
- name: 'Qwen CLI',
340
- login: loginQwen,
341
- refreshToken: refreshQwenToken,
342
- getApiKey: (cred) => cred.access,
343
- modifyModels: (models, cred) => {
344
- const baseUrl = getQwenBaseUrl(cred.enterpriseUrl as string | undefined);
345
- return models.map((m) => (m.provider === 'qwen-cli' ? { ...m, baseUrl } : m));
346
- }
347
- }
348
- });
349
- }
1
+ /**
2
+ * Qwen CLI Provider Extension
3
+ *
4
+ * Provides access to Qwen models via OAuth authentication with chat.qwen.ai.
5
+ * Uses device code flow with PKCE for secure browser-based authentication.
6
+ *
7
+ * Usage:
8
+ * shortcut -e ./packages/coding-agent/examples/extensions/custom-provider-qwen-cli
9
+ * # Then /login qwen-cli, or set QWEN_CLI_API_KEY=...
10
+ */
11
+
12
+ import type { ExtensionAPI, OAuthCredentials, OAuthLoginCallbacks } from 'shortcutxl';
13
+
14
+ // =============================================================================
15
+ // Constants
16
+ // =============================================================================
17
+
18
+ const QWEN_DEVICE_CODE_ENDPOINT = 'https://chat.qwen.ai/api/v1/oauth2/device/code';
19
+ const QWEN_TOKEN_ENDPOINT = 'https://chat.qwen.ai/api/v1/oauth2/token';
20
+ const QWEN_CLIENT_ID = 'f0304373b74a44d2b584a3fb70ca9e56';
21
+ const QWEN_SCOPE = 'openid profile email model.completion';
22
+ const QWEN_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
23
+ const QWEN_DEFAULT_BASE_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
24
+ const QWEN_POLL_INTERVAL_MS = 2000;
25
+
26
+ // =============================================================================
27
+ // PKCE Helpers
28
+ // =============================================================================
29
+
30
+ async function generatePKCE(): Promise<{ verifier: string; challenge: string }> {
31
+ const array = new Uint8Array(32);
32
+ crypto.getRandomValues(array);
33
+ const verifier = btoa(String.fromCharCode(...array))
34
+ .replace(/\+/g, '-')
35
+ .replace(/\//g, '_')
36
+ .replace(/=+$/, '');
37
+
38
+ const encoder = new TextEncoder();
39
+ const data = encoder.encode(verifier);
40
+ const hash = await crypto.subtle.digest('SHA-256', data);
41
+ const challenge = btoa(String.fromCharCode(...new Uint8Array(hash)))
42
+ .replace(/\+/g, '-')
43
+ .replace(/\//g, '_')
44
+ .replace(/=+$/, '');
45
+
46
+ return { verifier, challenge };
47
+ }
48
+
49
+ // =============================================================================
50
+ // OAuth Implementation
51
+ // =============================================================================
52
+
53
+ interface DeviceCodeResponse {
54
+ device_code: string;
55
+ user_code: string;
56
+ verification_uri: string;
57
+ verification_uri_complete?: string;
58
+ expires_in: number;
59
+ interval?: number;
60
+ }
61
+
62
+ interface TokenResponse {
63
+ access_token: string;
64
+ refresh_token?: string;
65
+ token_type: string;
66
+ expires_in: number;
67
+ resource_url?: string;
68
+ }
69
+
70
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
71
+ return new Promise((resolve, reject) => {
72
+ if (signal?.aborted) {
73
+ reject(new Error('Login cancelled'));
74
+ return;
75
+ }
76
+ const timeout = setTimeout(resolve, ms);
77
+ signal?.addEventListener(
78
+ 'abort',
79
+ () => {
80
+ clearTimeout(timeout);
81
+ reject(new Error('Login cancelled'));
82
+ },
83
+ { once: true }
84
+ );
85
+ });
86
+ }
87
+
88
+ async function startDeviceFlow(): Promise<{ deviceCode: DeviceCodeResponse; verifier: string }> {
89
+ const { verifier, challenge } = await generatePKCE();
90
+
91
+ const body = new URLSearchParams({
92
+ client_id: QWEN_CLIENT_ID,
93
+ scope: QWEN_SCOPE,
94
+ code_challenge: challenge,
95
+ code_challenge_method: 'S256'
96
+ });
97
+
98
+ const headers: Record<string, string> = {
99
+ 'Content-Type': 'application/x-www-form-urlencoded',
100
+ Accept: 'application/json'
101
+ };
102
+ const requestId = globalThis.crypto?.randomUUID?.();
103
+ if (requestId) headers['x-request-id'] = requestId;
104
+
105
+ const response = await fetch(QWEN_DEVICE_CODE_ENDPOINT, {
106
+ method: 'POST',
107
+ headers,
108
+ body: body.toString()
109
+ });
110
+
111
+ if (!response.ok) {
112
+ const text = await response.text();
113
+ throw new Error(`Device code request failed: ${response.status} ${text}`);
114
+ }
115
+
116
+ const data = (await response.json()) as DeviceCodeResponse;
117
+
118
+ if (!data.device_code || !data.user_code || !data.verification_uri) {
119
+ throw new Error('Invalid device code response: missing required fields');
120
+ }
121
+
122
+ return { deviceCode: data, verifier };
123
+ }
124
+
125
+ async function pollForToken(
126
+ deviceCode: string,
127
+ verifier: string,
128
+ intervalSeconds: number | undefined,
129
+ expiresIn: number,
130
+ signal?: AbortSignal
131
+ ): Promise<TokenResponse> {
132
+ const deadline = Date.now() + expiresIn * 1000;
133
+ const resolvedIntervalSeconds =
134
+ typeof intervalSeconds === 'number' && Number.isFinite(intervalSeconds) && intervalSeconds > 0
135
+ ? intervalSeconds
136
+ : QWEN_POLL_INTERVAL_MS / 1000;
137
+ let intervalMs = Math.max(1000, Math.floor(resolvedIntervalSeconds * 1000));
138
+
139
+ const handleTokenError = async (error: string, description?: string): Promise<boolean> => {
140
+ switch (error) {
141
+ case 'authorization_pending':
142
+ await abortableSleep(intervalMs, signal);
143
+ return true;
144
+ case 'slow_down':
145
+ intervalMs = Math.min(intervalMs + 5000, 10000);
146
+ await abortableSleep(intervalMs, signal);
147
+ return true;
148
+ case 'expired_token':
149
+ throw new Error('Device code expired. Please restart authentication.');
150
+ case 'access_denied':
151
+ throw new Error('Authorization denied by user.');
152
+ default:
153
+ throw new Error(`Token request failed: ${error} - ${description || ''}`);
154
+ }
155
+ };
156
+
157
+ while (Date.now() < deadline) {
158
+ if (signal?.aborted) {
159
+ throw new Error('Login cancelled');
160
+ }
161
+
162
+ const body = new URLSearchParams({
163
+ grant_type: QWEN_GRANT_TYPE,
164
+ client_id: QWEN_CLIENT_ID,
165
+ device_code: deviceCode,
166
+ code_verifier: verifier
167
+ });
168
+
169
+ const response = await fetch(QWEN_TOKEN_ENDPOINT, {
170
+ method: 'POST',
171
+ headers: {
172
+ 'Content-Type': 'application/x-www-form-urlencoded',
173
+ Accept: 'application/json'
174
+ },
175
+ body: body.toString()
176
+ });
177
+
178
+ const responseText = await response.text();
179
+ let data: (TokenResponse & { error?: string; error_description?: string }) | null = null;
180
+ if (responseText) {
181
+ try {
182
+ data = JSON.parse(responseText) as TokenResponse & {
183
+ error?: string;
184
+ error_description?: string;
185
+ };
186
+ } catch {
187
+ data = null;
188
+ }
189
+ }
190
+
191
+ const error = data?.error;
192
+ const errorDescription = data?.error_description;
193
+
194
+ if (!response.ok) {
195
+ if (error && (await handleTokenError(error, errorDescription))) {
196
+ continue;
197
+ }
198
+ throw new Error(
199
+ `Token request failed: ${response.status} ${response.statusText}. Response: ${responseText}`
200
+ );
201
+ }
202
+
203
+ if (data?.access_token) {
204
+ return data;
205
+ }
206
+
207
+ if (error && (await handleTokenError(error, errorDescription))) {
208
+ continue;
209
+ }
210
+
211
+ throw new Error('Token request failed: missing access token in response');
212
+ }
213
+
214
+ throw new Error('Authentication timed out. Please try again.');
215
+ }
216
+
217
+ async function loginQwen(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
218
+ const { deviceCode, verifier } = await startDeviceFlow();
219
+
220
+ // Show verification URL and user code to user
221
+ const authUrl = deviceCode.verification_uri_complete || deviceCode.verification_uri;
222
+ const instructions = deviceCode.verification_uri_complete
223
+ ? undefined // Code is already embedded in the URL
224
+ : `Enter code: ${deviceCode.user_code}`;
225
+ callbacks.onAuth({ url: authUrl, instructions });
226
+
227
+ // Poll for token
228
+ const tokenResponse = await pollForToken(
229
+ deviceCode.device_code,
230
+ verifier,
231
+ deviceCode.interval,
232
+ deviceCode.expires_in,
233
+ callbacks.signal
234
+ );
235
+
236
+ // Calculate expiry with 5-minute buffer
237
+ const expiresAt = Date.now() + tokenResponse.expires_in * 1000 - 5 * 60 * 1000;
238
+
239
+ return {
240
+ refresh: tokenResponse.refresh_token || '',
241
+ access: tokenResponse.access_token,
242
+ expires: expiresAt,
243
+ // Store resource_url for API base URL if provided
244
+ enterpriseUrl: tokenResponse.resource_url
245
+ };
246
+ }
247
+
248
+ async function refreshQwenToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
249
+ const body = new URLSearchParams({
250
+ grant_type: 'refresh_token',
251
+ refresh_token: credentials.refresh,
252
+ client_id: QWEN_CLIENT_ID
253
+ });
254
+
255
+ const response = await fetch(QWEN_TOKEN_ENDPOINT, {
256
+ method: 'POST',
257
+ headers: {
258
+ 'Content-Type': 'application/x-www-form-urlencoded',
259
+ Accept: 'application/json'
260
+ },
261
+ body: body.toString()
262
+ });
263
+
264
+ if (!response.ok) {
265
+ const text = await response.text();
266
+ throw new Error(`Token refresh failed: ${response.status} ${text}`);
267
+ }
268
+
269
+ const data = (await response.json()) as TokenResponse;
270
+
271
+ if (!data.access_token) {
272
+ throw new Error('Token refresh failed: no access token in response');
273
+ }
274
+
275
+ const expiresAt = Date.now() + data.expires_in * 1000 - 5 * 60 * 1000;
276
+
277
+ return {
278
+ refresh: data.refresh_token || credentials.refresh,
279
+ access: data.access_token,
280
+ expires: expiresAt,
281
+ enterpriseUrl: data.resource_url ?? credentials.enterpriseUrl
282
+ };
283
+ }
284
+
285
+ function getQwenBaseUrl(resourceUrl?: string): string {
286
+ if (!resourceUrl) {
287
+ return QWEN_DEFAULT_BASE_URL;
288
+ }
289
+
290
+ let url = resourceUrl.startsWith('http') ? resourceUrl : `https://${resourceUrl}`;
291
+ if (!url.endsWith('/v1')) {
292
+ url = `${url}/v1`;
293
+ }
294
+ return url;
295
+ }
296
+
297
+ // =============================================================================
298
+ // Extension Entry Point
299
+ // =============================================================================
300
+
301
+ export default function (shortcut: ExtensionAPI) {
302
+ shortcut.registerProvider('qwen-cli', {
303
+ baseUrl: QWEN_DEFAULT_BASE_URL,
304
+ apiKey: 'QWEN_CLI_API_KEY',
305
+ api: 'openai-completions',
306
+
307
+ models: [
308
+ {
309
+ id: 'qwen3-coder-plus',
310
+ name: 'Qwen3 Coder Plus',
311
+ reasoning: false,
312
+ input: ['text'],
313
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
314
+ contextWindow: 1000000,
315
+ maxTokens: 65536
316
+ },
317
+ {
318
+ id: 'qwen3-coder-flash',
319
+ name: 'Qwen3 Coder Flash',
320
+ reasoning: false,
321
+ input: ['text'],
322
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
323
+ contextWindow: 1000000,
324
+ maxTokens: 65536
325
+ },
326
+ {
327
+ id: 'vision-model',
328
+ name: 'Qwen3 VL Plus',
329
+ reasoning: true,
330
+ input: ['text', 'image'],
331
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
332
+ contextWindow: 262144,
333
+ maxTokens: 32768,
334
+ compat: { supportsDeveloperRole: false, thinkingFormat: 'qwen' }
335
+ }
336
+ ],
337
+
338
+ oauth: {
339
+ name: 'Qwen CLI',
340
+ login: loginQwen,
341
+ refreshToken: refreshQwenToken,
342
+ getApiKey: (cred) => cred.access,
343
+ modifyModels: (models, cred) => {
344
+ const baseUrl = getQwenBaseUrl(cred.enterpriseUrl as string | undefined);
345
+ return models.map((m) => (m.provider === 'qwen-cli' ? { ...m, baseUrl } : m));
346
+ }
347
+ }
348
+ });
349
+ }