@brunobracaioli/aibrain 0.4.0-beta.3 → 0.4.0-beta.30

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 (70) hide show
  1. package/README.md +199 -13
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +939 -13
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +34 -5
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +1084 -44
  11. package/dist/codex-compatibility.mjs +67 -5
  12. package/dist/codex-hooks.mjs +411 -0
  13. package/dist/codex-permissions.mjs +242 -51
  14. package/dist/codex-protocol-fingerprint.json +12 -13
  15. package/dist/device-login.mjs +511 -0
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +191 -14
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/engineering.mjs +43 -5
  23. package/dist/extensions-catalog.mjs +390 -0
  24. package/dist/extensions-cli.mjs +524 -0
  25. package/dist/extensions-preferences.mjs +151 -0
  26. package/dist/guardrails/continuity.mjs +239 -0
  27. package/dist/guardrails/format.mjs +111 -0
  28. package/dist/guardrails/guards.mjs +1560 -0
  29. package/dist/guardrails/patch.mjs +33 -0
  30. package/dist/guardrails/run.mjs +286 -0
  31. package/dist/guardrails/shell-words.mjs +206 -0
  32. package/dist/guardrails-plugin.mjs +216 -0
  33. package/dist/launch-banner-art.json +40 -0
  34. package/dist/launch-banner.mjs +533 -0
  35. package/dist/launch-feedback.mjs +286 -0
  36. package/dist/launch.mjs +744 -64
  37. package/dist/managed-host.mjs +1276 -0
  38. package/dist/manager/adapter.mjs +304 -0
  39. package/dist/manager/bus.mjs +2222 -0
  40. package/dist/manager/claude-bus-worker.mjs +1355 -0
  41. package/dist/manager/delegation.mjs +354 -0
  42. package/dist/manager/hooks.mjs +918 -0
  43. package/dist/manager/launch-role.mjs +733 -0
  44. package/dist/manager/mcp-stdio.mjs +463 -0
  45. package/dist/manager/messages.mjs +861 -0
  46. package/dist/manager/native-worker.mjs +338 -0
  47. package/dist/manager/reserve.mjs +2170 -0
  48. package/dist/manager/room.mjs +106 -0
  49. package/dist/manager/send-grant.mjs +147 -0
  50. package/dist/manager/server.mjs +2010 -0
  51. package/dist/manager/status.mjs +119 -0
  52. package/dist/manager/wake-state.mjs +93 -0
  53. package/dist/manager/watch.mjs +87 -0
  54. package/dist/manager/worker.mjs +2977 -0
  55. package/dist/manager/workers-cli.mjs +1880 -0
  56. package/dist/mcp-servers.mjs +192 -0
  57. package/dist/mcp.mjs +10 -2
  58. package/dist/monitor.mjs +179 -2
  59. package/dist/package.json +1 -1
  60. package/dist/platform.mjs +78 -29
  61. package/dist/release-manifest-public-keys.json +10 -0
  62. package/dist/release-manifest.json +334 -0
  63. package/dist/release-manifest.mjs +817 -0
  64. package/dist/release-settings.mjs +335 -0
  65. package/dist/self-update.mjs +1047 -0
  66. package/dist/setup-login-state.mjs +19 -0
  67. package/dist/state.mjs +25 -1
  68. package/dist/token-guide.mjs +201 -0
  69. package/dist/update-actions.mjs +442 -0
  70. package/package.json +2 -2
@@ -0,0 +1,511 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { deviceLoginInstructions } from './token-guide.mjs';
5
+
6
+ const REQUEST_TIMEOUT_MS = 10_000;
7
+ const MAX_RESPONSE_BYTES = 8 * 1024;
8
+ const MAX_DEVICE_LIFETIME_SECONDS = 600;
9
+ const MAX_POLL_INTERVAL_SECONDS = 600;
10
+ const USER_CODE = /^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/u;
11
+ const DEVICE_CODE = /^braindc_[A-Za-z0-9_-]{43}$/u;
12
+ const ACCESS_TOKEN = /^brain_[A-Za-z0-9_-]{32,256}$/u;
13
+ const ACCOUNT_HINT = /^[^\p{Cc}\p{Cf}\s@*]\*\*\*@[\p{L}\p{M}\p{N}.-]+$/u;
14
+
15
+ /** @typedef {'pt-BR' | 'en'} DeviceLoginLocale */
16
+
17
+ /**
18
+ * @param {string} code
19
+ * @param {number} [exitCode]
20
+ */
21
+ function loginError(code, exitCode) {
22
+ const error = new Error(code);
23
+ if (exitCode !== undefined) Object.defineProperty(error, 'exitCode', { value: exitCode });
24
+ return error;
25
+ }
26
+
27
+ /**
28
+ * A failure before any code was shown: the server has the flow off, is rate
29
+ * limiting, or cannot be reached. No grant exists yet, so the caller may offer
30
+ * the manual token instead.
31
+ * @param {string} code
32
+ */
33
+ function notStartedError(code) {
34
+ const error = loginError(code);
35
+ Object.defineProperty(error, 'loginNotStarted', { value: true });
36
+ return error;
37
+ }
38
+
39
+ /** @param {unknown} error */
40
+ export function isLoginNotStarted(error) {
41
+ return error instanceof Error && 'loginNotStarted' in error && error.loginNotStarted === true;
42
+ }
43
+
44
+ /** @param {AbortSignal | undefined} signal */
45
+ function assertNotAborted(signal) {
46
+ if (signal?.aborted) throw loginError('login_cancelled', 130);
47
+ }
48
+
49
+ /** @param {AbortSignal | undefined} signal */
50
+ function requestSignal(signal) {
51
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
52
+ return signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
53
+ }
54
+
55
+ /** @param {number} milliseconds @param {AbortSignal | undefined} signal */
56
+ function wait(milliseconds, signal) {
57
+ assertNotAborted(signal);
58
+ /** @type {Promise<void>} */
59
+ const pending = new Promise((resolve, reject) => {
60
+ const timer = setTimeout(
61
+ () => {
62
+ signal?.removeEventListener('abort', onAbort);
63
+ resolve();
64
+ },
65
+ Math.max(0, milliseconds),
66
+ );
67
+ const onAbort = () => {
68
+ clearTimeout(timer);
69
+ reject(loginError('login_cancelled', 130));
70
+ };
71
+ signal?.addEventListener('abort', onAbort, { once: true });
72
+ });
73
+ return pending;
74
+ }
75
+
76
+ /** @param {string} endpoint */
77
+ function endpointOrigin(endpoint) {
78
+ let url;
79
+ try {
80
+ url = new URL(endpoint);
81
+ } catch {
82
+ throw loginError('login_endpoint_invalid');
83
+ }
84
+ const localHttp =
85
+ url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);
86
+ if (
87
+ (url.protocol !== 'https:' && !localHttp) ||
88
+ url.username !== '' ||
89
+ url.password !== '' ||
90
+ url.search !== '' ||
91
+ url.hash !== ''
92
+ )
93
+ throw loginError('login_endpoint_invalid');
94
+ return url.origin;
95
+ }
96
+
97
+ /** @param {AbortSignal | undefined} requestSignal @param {AbortSignal | undefined} cancelSignal */
98
+ function throwIfAborted(requestSignal, cancelSignal) {
99
+ if (cancelSignal?.aborted) throw loginError('login_cancelled', 130);
100
+ if (requestSignal?.aborted) throw loginError('login_response_unavailable');
101
+ }
102
+
103
+ /** @param {ReadableStreamDefaultReader<Uint8Array>} reader @param {AbortSignal | undefined} requestSignal @param {AbortSignal | undefined} cancelSignal */
104
+ function readWithSignals(reader, requestSignal, cancelSignal) {
105
+ throwIfAborted(requestSignal, cancelSignal);
106
+ if (requestSignal === undefined && cancelSignal === undefined) return reader.read();
107
+ return new Promise((resolve, reject) => {
108
+ let settled = false;
109
+ const cleanup = () => {
110
+ requestSignal?.removeEventListener('abort', onAbort);
111
+ cancelSignal?.removeEventListener('abort', onAbort);
112
+ };
113
+ const onAbort = () => {
114
+ if (settled) return;
115
+ settled = true;
116
+ cleanup();
117
+ void reader.cancel().catch(() => undefined);
118
+ reject(
119
+ cancelSignal?.aborted
120
+ ? loginError('login_cancelled', 130)
121
+ : loginError('login_response_unavailable'),
122
+ );
123
+ };
124
+ requestSignal?.addEventListener('abort', onAbort, { once: true });
125
+ cancelSignal?.addEventListener('abort', onAbort, { once: true });
126
+ reader.read().then(
127
+ (result) => {
128
+ if (settled) return;
129
+ settled = true;
130
+ cleanup();
131
+ resolve(result);
132
+ },
133
+ (error) => {
134
+ if (settled) return;
135
+ settled = true;
136
+ cleanup();
137
+ reject(error);
138
+ },
139
+ );
140
+ });
141
+ }
142
+
143
+ /** @param {Response} response @param {AbortSignal | undefined} requestSignal @param {AbortSignal | undefined} cancelSignal */
144
+ async function readJson(response, requestSignal, cancelSignal) {
145
+ const declaredLength = Number(response.headers.get('content-length'));
146
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
147
+ await response.body?.cancel().catch(() => undefined);
148
+ throw loginError('login_response_invalid');
149
+ }
150
+ if (response.body === null) throw loginError('login_response_invalid');
151
+ const reader = response.body.getReader();
152
+ /** @type {Uint8Array[]} */
153
+ const chunks = [];
154
+ let totalBytes = 0;
155
+ try {
156
+ while (true) {
157
+ throwIfAborted(requestSignal, cancelSignal);
158
+ const { done, value } = await readWithSignals(reader, requestSignal, cancelSignal);
159
+ if (done) break;
160
+ totalBytes += value.byteLength;
161
+ if (totalBytes > MAX_RESPONSE_BYTES) {
162
+ await reader.cancel().catch(() => undefined);
163
+ throw loginError('login_response_invalid');
164
+ }
165
+ chunks.push(value);
166
+ }
167
+ } catch (error) {
168
+ await reader.cancel().catch(() => undefined);
169
+ if (cancelSignal?.aborted) throw loginError('login_cancelled', 130);
170
+ if (requestSignal?.aborted) throw loginError('login_response_unavailable');
171
+ if (error instanceof Error && error.message === 'login_response_invalid') throw error;
172
+ throw loginError('login_response_unavailable');
173
+ }
174
+ const bytes = new Uint8Array(totalBytes);
175
+ let offset = 0;
176
+ for (const chunk of chunks) {
177
+ bytes.set(chunk, offset);
178
+ offset += chunk.byteLength;
179
+ }
180
+ let value;
181
+ try {
182
+ value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
183
+ } catch {
184
+ throw loginError('login_response_invalid');
185
+ }
186
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
187
+ throw loginError('login_response_invalid');
188
+ return /** @type {Record<string, unknown>} */ (value);
189
+ }
190
+
191
+ /** @param {string | null} value @param {number} fallbackSeconds */
192
+ function retryAfterSeconds(value, fallbackSeconds) {
193
+ if (value === null) return fallbackSeconds;
194
+ const seconds = Number(value);
195
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds, MAX_POLL_INTERVAL_SECONDS);
196
+ const date = Date.parse(value);
197
+ if (Number.isFinite(date))
198
+ return Math.min(Math.max(0, (date - Date.now()) / 1000), MAX_POLL_INTERVAL_SECONDS);
199
+ return fallbackSeconds;
200
+ }
201
+
202
+ /** @param {Response} response */
203
+ async function discardResponse(response) {
204
+ await response.body?.cancel().catch(() => undefined);
205
+ }
206
+
207
+ /**
208
+ * Run an opener without a shell. Its output and failures are deliberately ignored.
209
+ * @param {string} file
210
+ * @param {string[]} args
211
+ * @param {AbortSignal | undefined} signal
212
+ * @returns {Promise<boolean>} Whether the opener command completed successfully.
213
+ */
214
+ async function runOpener(file, args, signal) {
215
+ assertNotAborted(signal);
216
+ /** @type {import('node:child_process').ChildProcess | undefined} */
217
+ let child;
218
+ try {
219
+ await new Promise((resolve, reject) => {
220
+ child = execFile(
221
+ file,
222
+ args,
223
+ { timeout: 4_000, windowsHide: true, encoding: 'utf8' },
224
+ (error) => (error ? reject(error) : resolve(undefined)),
225
+ );
226
+ const onAbort = () => {
227
+ child?.kill();
228
+ reject(loginError('login_cancelled', 130));
229
+ };
230
+ signal?.addEventListener('abort', onAbort, { once: true });
231
+ child.once('close', () => signal?.removeEventListener('abort', onAbort));
232
+ });
233
+ return true;
234
+ } catch {
235
+ if (signal?.aborted) throw loginError('login_cancelled', 130);
236
+ // Browser opening is best-effort; the terminal always displays the address.
237
+ return false;
238
+ }
239
+ }
240
+
241
+ /** @param {NodeJS.ProcessEnv} env */
242
+ async function isWsl(env) {
243
+ if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true;
244
+ try {
245
+ return /microsoft|wsl/iu.test(await readFile('/proc/version', 'utf8'));
246
+ } catch {
247
+ return false;
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Open the verification page with fixed arguments and no shell. This function never
253
+ * prints opener errors; the user can use the address shown in the terminal.
254
+ * @param {string} url
255
+ * @param {{ platform?: NodeJS.Platform | undefined, env?: NodeJS.ProcessEnv | undefined, signal?: AbortSignal | undefined, runCommand?: typeof runOpener | undefined }} [options]
256
+ */
257
+ export async function openVerificationPage(url, options = {}) {
258
+ const platform = options.platform ?? process.platform;
259
+ const env = options.env ?? process.env;
260
+ const signal = options.signal;
261
+ const runCommand = options.runCommand ?? runOpener;
262
+ if (platform === 'darwin') return runCommand('open', [url], signal);
263
+ if (platform !== 'linux') return;
264
+ if (await isWsl(env)) {
265
+ if (await runCommand('wslview', [url], signal)) return;
266
+ if (!safeWindowsOpenUrl(url)) return;
267
+ return runCommand('cmd.exe', ['/c', 'start', '', url], signal);
268
+ }
269
+ return runCommand('xdg-open', [url], signal);
270
+ }
271
+
272
+ /**
273
+ * `cmd.exe /c start` parses a command string even though Node invokes cmd.exe via
274
+ * `execFile`. Permit only the locally constructed verification URL grammar.
275
+ * @param {string} value
276
+ */
277
+ function safeWindowsOpenUrl(value) {
278
+ try {
279
+ const url = new URL(value);
280
+ const hostname = url.hostname;
281
+ const dnsName = hostname
282
+ .split('.')
283
+ .every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(label));
284
+ const ipv4 = /^(?:\d{1,3}\.){3}\d{1,3}$/u.test(hostname);
285
+ const ipv6Loopback = hostname === '[::1]';
286
+ const loopback = hostname === 'localhost' || hostname === '127.0.0.1' || ipv6Loopback;
287
+ const portValid =
288
+ url.port === '' || (/^\d{1,5}$/u.test(url.port) && Number(url.port) <= 65_535);
289
+ return (
290
+ (url.protocol === 'https:' || (url.protocol === 'http:' && loopback)) &&
291
+ url.username === '' &&
292
+ url.password === '' &&
293
+ url.pathname === '/device' &&
294
+ url.search === '' &&
295
+ url.hash === '' &&
296
+ portValid &&
297
+ (dnsName || ipv4 || ipv6Loopback) &&
298
+ value === url.href
299
+ );
300
+ } catch {
301
+ return false;
302
+ }
303
+ }
304
+
305
+ /**
306
+ * @param {{
307
+ * endpoint: string,
308
+ * clientVersion: string,
309
+ * agent: 'claude' | 'codex' | 'both',
310
+ * locale: DeviceLoginLocale,
311
+ * fetchImpl?: typeof fetch,
312
+ * openBrowser?: (url: string, signal?: AbortSignal) => Promise<void>,
313
+ * writeLine?: (line: string) => void,
314
+ * sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>,
315
+ * now?: () => number,
316
+ * signal?: AbortSignal
317
+ * }} options
318
+ * @returns {Promise<{ token: string, accountHint: string }>} The token is returned only to the caller.
319
+ */
320
+ export async function deviceLogin(options) {
321
+ const origin = endpointOrigin(options.endpoint);
322
+ const codeUrl = new URL('/device/code', origin).href;
323
+ const tokenUrl = new URL('/device/token', origin).href;
324
+ const verificationUrl = new URL('/device', origin).href;
325
+ const fetchImpl = options.fetchImpl ?? fetch;
326
+ const openBrowser =
327
+ options.openBrowser ??
328
+ (async (url, signal) => {
329
+ await openVerificationPage(url, signal === undefined ? {} : { signal });
330
+ });
331
+ const writeLine = options.writeLine ?? ((line) => process.stdout.write(`${line}\n`));
332
+ const sleep = options.sleep ?? wait;
333
+ const now = options.now ?? (() => performance.now());
334
+ const startForm = new URLSearchParams({
335
+ client_id: 'aisac-cli',
336
+ client_version: options.clientVersion,
337
+ agent: options.agent,
338
+ });
339
+ assertNotAborted(options.signal);
340
+
341
+ let startResponse;
342
+ const startSignal = requestSignal(options.signal);
343
+ try {
344
+ startResponse = await fetchImpl(codeUrl, {
345
+ method: 'POST',
346
+ redirect: 'error',
347
+ cache: 'no-store',
348
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
349
+ body: startForm,
350
+ signal: startSignal,
351
+ });
352
+ } catch {
353
+ assertNotAborted(options.signal);
354
+ throw notStartedError('login_unavailable');
355
+ }
356
+ if (startResponse.status !== 200) {
357
+ await discardResponse(startResponse);
358
+ if (startResponse.status === 429) throw notStartedError('login_rate_limited');
359
+ if (startResponse.status >= 500) throw notStartedError('login_unavailable');
360
+ throw notStartedError('login_request_rejected');
361
+ }
362
+ let start;
363
+ try {
364
+ start = await readJson(startResponse, startSignal, options.signal);
365
+ } catch (error) {
366
+ if (options.signal?.aborted) throw loginError('login_cancelled', 130);
367
+ if (error instanceof Error && error.message === 'login_response_unavailable')
368
+ throw notStartedError('login_unavailable');
369
+ throw error;
370
+ }
371
+ const deviceCode = start.device_code;
372
+ const userCode = start.user_code;
373
+ const expiresIn = start.expires_in;
374
+ const interval = start.interval;
375
+ if (
376
+ typeof deviceCode !== 'string' ||
377
+ !DEVICE_CODE.test(deviceCode) ||
378
+ typeof userCode !== 'string' ||
379
+ !USER_CODE.test(userCode) ||
380
+ typeof expiresIn !== 'number' ||
381
+ !Number.isSafeInteger(expiresIn) ||
382
+ expiresIn < 1 ||
383
+ expiresIn > MAX_DEVICE_LIFETIME_SECONDS ||
384
+ typeof interval !== 'number' ||
385
+ !Number.isSafeInteger(interval) ||
386
+ interval < 1 ||
387
+ interval > MAX_POLL_INTERVAL_SECONDS ||
388
+ typeof start.verification_uri !== 'string'
389
+ )
390
+ throw loginError('login_response_invalid');
391
+
392
+ let returnedVerification;
393
+ try {
394
+ returnedVerification = new URL(start.verification_uri);
395
+ } catch {
396
+ throw loginError('login_response_invalid');
397
+ }
398
+ if (returnedVerification.origin !== origin) throw loginError('login_origin_mismatch');
399
+
400
+ const deadline = now() + expiresIn * 1000;
401
+ writeLine(deviceLoginInstructions(options.locale, verificationUrl, userCode));
402
+ assertNotAborted(options.signal);
403
+ try {
404
+ await openBrowser(verificationUrl, options.signal);
405
+ } catch {
406
+ assertNotAborted(options.signal);
407
+ // The displayed address is the fallback when no browser can be opened.
408
+ }
409
+
410
+ let pollIntervalSeconds = interval;
411
+ const pollForm = () =>
412
+ new URLSearchParams({
413
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
414
+ device_code: deviceCode,
415
+ client_id: 'aisac-cli',
416
+ });
417
+
418
+ while (now() < deadline) {
419
+ assertNotAborted(options.signal);
420
+ const remaining = deadline - now();
421
+ await sleep(Math.min(pollIntervalSeconds * 1000, remaining), options.signal);
422
+ assertNotAborted(options.signal);
423
+ if (now() >= deadline) break;
424
+ let response;
425
+ const pollSignal = requestSignal(options.signal);
426
+ try {
427
+ response = await fetchImpl(tokenUrl, {
428
+ method: 'POST',
429
+ redirect: 'error',
430
+ cache: 'no-store',
431
+ headers: {
432
+ 'Content-Type': 'application/x-www-form-urlencoded',
433
+ Accept: 'application/json',
434
+ },
435
+ body: pollForm(),
436
+ signal: pollSignal,
437
+ });
438
+ } catch {
439
+ assertNotAborted(options.signal);
440
+ continue;
441
+ }
442
+ if (response.status >= 500) {
443
+ await discardResponse(response);
444
+ continue;
445
+ }
446
+ if (response.status === 429) {
447
+ await discardResponse(response);
448
+ pollIntervalSeconds = Math.max(
449
+ pollIntervalSeconds,
450
+ retryAfterSeconds(response.headers.get('retry-after'), pollIntervalSeconds),
451
+ );
452
+ continue;
453
+ }
454
+ if (response.status === 200) {
455
+ let result;
456
+ try {
457
+ result = await readJson(response, pollSignal, options.signal);
458
+ } catch (error) {
459
+ if (options.signal?.aborted) throw loginError('login_cancelled', 130);
460
+ if (error instanceof Error && error.message === 'login_response_unavailable') continue;
461
+ throw error;
462
+ }
463
+ if (
464
+ result.token_type !== 'Bearer' ||
465
+ typeof result.access_token !== 'string' ||
466
+ !ACCESS_TOKEN.test(result.access_token) ||
467
+ typeof result.account_hint !== 'string' ||
468
+ result.account_hint.length > 258 ||
469
+ !ACCOUNT_HINT.test(result.account_hint)
470
+ )
471
+ throw loginError('login_response_invalid');
472
+ return { token: result.access_token, accountHint: result.account_hint };
473
+ }
474
+ if (response.status !== 400) {
475
+ await discardResponse(response);
476
+ throw loginError('login_response_invalid');
477
+ }
478
+
479
+ let result;
480
+ try {
481
+ result = await readJson(response, pollSignal, options.signal);
482
+ } catch (error) {
483
+ if (options.signal?.aborted) throw loginError('login_cancelled', 130);
484
+ if (error instanceof Error && error.message === 'login_response_unavailable') continue;
485
+ throw error;
486
+ }
487
+ if (typeof result.error !== 'string') throw loginError('login_response_invalid');
488
+ if (result.error === 'authorization_pending') {
489
+ pollIntervalSeconds = Math.max(
490
+ pollIntervalSeconds,
491
+ retryAfterSeconds(response.headers.get('retry-after'), pollIntervalSeconds),
492
+ );
493
+ continue;
494
+ }
495
+ if (result.error === 'slow_down') {
496
+ pollIntervalSeconds = Math.min(
497
+ MAX_POLL_INTERVAL_SECONDS,
498
+ Math.max(
499
+ pollIntervalSeconds + 5,
500
+ retryAfterSeconds(response.headers.get('retry-after'), pollIntervalSeconds + 5),
501
+ ),
502
+ );
503
+ continue;
504
+ }
505
+ if (result.error === 'access_denied') throw loginError('login_denied');
506
+ if (result.error === 'expired_token') throw loginError('login_expired');
507
+ if (result.error === 'invalid_grant') throw loginError('login_invalid_grant');
508
+ throw loginError('login_response_invalid');
509
+ }
510
+ throw loginError('login_expired');
511
+ }