@zhafron/opencode-kiro-auth 1.0.0 → 1.1.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.
Files changed (81) hide show
  1. package/README.md +1 -1
  2. package/dist/constants.js +7 -1
  3. package/dist/kiro/oauth-idc.js +4 -1
  4. package/dist/plugin/accounts.js +11 -2
  5. package/dist/plugin/auth-page.js +6 -1
  6. package/dist/plugin/config/loader.js +3 -1
  7. package/dist/plugin/logger.js +3 -5
  8. package/dist/plugin/request.js +148 -28
  9. package/dist/plugin/response.js +9 -2
  10. package/dist/plugin/server.js +16 -3
  11. package/dist/plugin/streaming.js +9 -2
  12. package/dist/plugin/types.d.ts +1 -1
  13. package/dist/plugin/usage.js +11 -2
  14. package/dist/plugin.js +30 -6
  15. package/package.json +2 -2
  16. package/dist/kiro/oauth-social.d.ts +0 -17
  17. package/dist/kiro/oauth-social.js +0 -51
  18. package/dist/plugin/cli.d.ts +0 -6
  19. package/dist/plugin/cli.js +0 -98
  20. package/dist/plugin/debug.d.ts +0 -2
  21. package/dist/plugin/debug.js +0 -9
  22. package/dist/plugin/oauth-parser.d.ts +0 -5
  23. package/dist/plugin/oauth-parser.js +0 -23
  24. package/dist/plugin/quota.d.ts +0 -15
  25. package/dist/plugin/quota.js +0 -68
  26. package/dist/plugin/recovery.d.ts +0 -19
  27. package/dist/plugin/recovery.js +0 -302
  28. package/dist/plugin/refresh-queue.d.ts +0 -14
  29. package/dist/plugin/refresh-queue.js +0 -69
  30. package/dist/src/constants.d.ts +0 -22
  31. package/dist/src/constants.js +0 -35
  32. package/dist/src/kiro/auth.d.ts +0 -5
  33. package/dist/src/kiro/auth.js +0 -69
  34. package/dist/src/kiro/oauth-idc.d.ts +0 -22
  35. package/dist/src/kiro/oauth-idc.js +0 -99
  36. package/dist/src/kiro/oauth-social.d.ts +0 -17
  37. package/dist/src/kiro/oauth-social.js +0 -69
  38. package/dist/src/plugin/accounts.d.ts +0 -23
  39. package/dist/src/plugin/accounts.js +0 -265
  40. package/dist/src/plugin/cli.d.ts +0 -6
  41. package/dist/src/plugin/cli.js +0 -98
  42. package/dist/src/plugin/config/index.d.ts +0 -3
  43. package/dist/src/plugin/config/index.js +0 -2
  44. package/dist/src/plugin/config/loader.d.ts +0 -7
  45. package/dist/src/plugin/config/loader.js +0 -143
  46. package/dist/src/plugin/config/schema.d.ts +0 -68
  47. package/dist/src/plugin/config/schema.js +0 -44
  48. package/dist/src/plugin/debug.d.ts +0 -2
  49. package/dist/src/plugin/debug.js +0 -9
  50. package/dist/src/plugin/errors.d.ts +0 -17
  51. package/dist/src/plugin/errors.js +0 -34
  52. package/dist/src/plugin/logger.d.ts +0 -4
  53. package/dist/src/plugin/logger.js +0 -17
  54. package/dist/src/plugin/models.d.ts +0 -3
  55. package/dist/src/plugin/models.js +0 -14
  56. package/dist/src/plugin/oauth-parser.d.ts +0 -5
  57. package/dist/src/plugin/oauth-parser.js +0 -23
  58. package/dist/src/plugin/quota.d.ts +0 -25
  59. package/dist/src/plugin/quota.js +0 -175
  60. package/dist/src/plugin/recovery.d.ts +0 -19
  61. package/dist/src/plugin/recovery.js +0 -302
  62. package/dist/src/plugin/refresh-queue.d.ts +0 -14
  63. package/dist/src/plugin/refresh-queue.js +0 -69
  64. package/dist/src/plugin/request.d.ts +0 -35
  65. package/dist/src/plugin/request.js +0 -411
  66. package/dist/src/plugin/response.d.ts +0 -6
  67. package/dist/src/plugin/response.js +0 -246
  68. package/dist/src/plugin/server.d.ts +0 -10
  69. package/dist/src/plugin/server.js +0 -203
  70. package/dist/src/plugin/storage.d.ts +0 -5
  71. package/dist/src/plugin/storage.js +0 -106
  72. package/dist/src/plugin/streaming.d.ts +0 -12
  73. package/dist/src/plugin/streaming.js +0 -444
  74. package/dist/src/plugin/token.d.ts +0 -8
  75. package/dist/src/plugin/token.js +0 -130
  76. package/dist/src/plugin/types.d.ts +0 -144
  77. package/dist/src/plugin/types.js +0 -0
  78. package/dist/src/plugin/usage.d.ts +0 -28
  79. package/dist/src/plugin/usage.js +0 -159
  80. package/dist/src/plugin.d.ts +0 -2
  81. package/dist/src/plugin.js +0 -341
@@ -1,6 +0,0 @@
1
- import type { KiroAuthMethod, KiroRegion } from './types';
2
- export declare function promptAuthMethod(): Promise<KiroAuthMethod>;
3
- export declare function promptRegion(): Promise<KiroRegion>;
4
- export declare function promptConfirmation(message: string): Promise<boolean>;
5
- export declare function displayAuthUrl(url: string): void;
6
- export declare function cleanup(): void;
@@ -1,98 +0,0 @@
1
- import { createInterface } from 'node:readline';
2
- import * as logger from './logger';
3
- let rl = null;
4
- function getReadline() {
5
- if (!rl) {
6
- rl = createInterface({
7
- input: process.stdin,
8
- output: process.stdout,
9
- });
10
- rl.on('SIGINT', () => {
11
- logger.log('Received SIGINT, closing readline');
12
- closeReadline();
13
- process.exit(130);
14
- });
15
- }
16
- return rl;
17
- }
18
- function closeReadline() {
19
- if (rl) {
20
- rl.close();
21
- rl = null;
22
- }
23
- }
24
- function question(prompt) {
25
- return new Promise((resolve) => {
26
- const readline = getReadline();
27
- readline.question(prompt, (answer) => {
28
- resolve(answer.trim());
29
- });
30
- });
31
- }
32
- function clearLine() {
33
- if (process.stdout.isTTY) {
34
- process.stdout.clearLine(0);
35
- process.stdout.cursorTo(0);
36
- }
37
- }
38
- export async function promptAuthMethod() {
39
- console.log('\nSelect authentication method:');
40
- console.log(' 1. Social (GitHub, Google, etc.)');
41
- console.log(' 2. IDC (Identity Center)');
42
- while (true) {
43
- const answer = await question('\nEnter your choice (1 or 2): ');
44
- if (answer === '1' || answer.toLowerCase() === 'social') {
45
- clearLine();
46
- return 'social';
47
- }
48
- if (answer === '2' || answer.toLowerCase() === 'idc') {
49
- clearLine();
50
- return 'idc';
51
- }
52
- console.log('Invalid choice. Please enter 1 or 2.');
53
- }
54
- }
55
- export async function promptRegion() {
56
- console.log('\nSelect AWS region:');
57
- console.log(' 1. us-east-1 (default)');
58
- console.log(' 2. us-west-2');
59
- while (true) {
60
- const answer = await question('\nEnter your choice (1 or 2, default: 1): ');
61
- if (!answer || answer === '1' || answer.toLowerCase() === 'us-east-1') {
62
- clearLine();
63
- return 'us-east-1';
64
- }
65
- if (answer === '2' || answer.toLowerCase() === 'us-west-2') {
66
- clearLine();
67
- return 'us-west-2';
68
- }
69
- console.log('Invalid choice. Please enter 1 or 2.');
70
- }
71
- }
72
- export async function promptConfirmation(message) {
73
- while (true) {
74
- const answer = await question(`${message} (y/n): `);
75
- const lower = answer.toLowerCase();
76
- if (lower === 'y' || lower === 'yes') {
77
- clearLine();
78
- return true;
79
- }
80
- if (lower === 'n' || lower === 'no') {
81
- clearLine();
82
- return false;
83
- }
84
- console.log('Invalid input. Please enter y or n.');
85
- }
86
- }
87
- export function displayAuthUrl(url) {
88
- console.log('\n' + '='.repeat(70));
89
- console.log('Authentication Required');
90
- console.log('='.repeat(70));
91
- console.log('\nPlease open the following URL in your browser to authenticate:\n');
92
- console.log(` ${url}\n`);
93
- console.log('Waiting for authentication to complete...');
94
- console.log('='.repeat(70) + '\n');
95
- }
96
- export function cleanup() {
97
- closeReadline();
98
- }
@@ -1,2 +0,0 @@
1
- export declare function isDebugEnabled(): boolean;
2
- export declare function debugLog(context: string, message: string, data?: unknown): void;
@@ -1,9 +0,0 @@
1
- export function isDebugEnabled() {
2
- return !!process.env.DEBUG;
3
- }
4
- export function debugLog(context, message, data) {
5
- if (isDebugEnabled()) {
6
- const formattedData = data !== undefined ? ` ${JSON.stringify(data)}` : '';
7
- console.debug(`[${context}] ${message}${formattedData}`);
8
- }
9
- }
@@ -1,5 +0,0 @@
1
- export interface ParsedOAuthCallback {
2
- code: string;
3
- state: string;
4
- }
5
- export declare function parseOAuthCallbackInput(input: string): ParsedOAuthCallback;
@@ -1,23 +0,0 @@
1
- export function parseOAuthCallbackInput(input) {
2
- const trimmed = input.trim();
3
- try {
4
- const url = new URL(trimmed);
5
- const code = url.searchParams.get('code');
6
- const state = url.searchParams.get('state');
7
- if (!code || !state) {
8
- throw new Error('Missing code or state in URL');
9
- }
10
- return { code, state };
11
- }
12
- catch {
13
- const codeMatch = trimmed.match(/code=([^&\s]+)/);
14
- const stateMatch = trimmed.match(/state=([^&\s]+)/);
15
- if (codeMatch?.[1] && stateMatch?.[1]) {
16
- return {
17
- code: decodeURIComponent(codeMatch[1]),
18
- state: decodeURIComponent(stateMatch[1]),
19
- };
20
- }
21
- throw new Error('Invalid OAuth callback format. Expected full URL or query string with code and state parameters.');
22
- }
23
- }
@@ -1,15 +0,0 @@
1
- import { ManagedAccount } from './types';
2
- export type QuotaStatus = 'healthy' | 'warning' | 'exhausted';
3
- export interface QuotaInfo {
4
- status: QuotaStatus;
5
- used: number;
6
- limit: number;
7
- remaining: number;
8
- percentage: number;
9
- recoveryTime?: number;
10
- }
11
- export declare function checkQuotaStatus(account: ManagedAccount): QuotaStatus;
12
- export declare function updateAccountQuota(account: ManagedAccount, usage: any, accountManager?: any): void;
13
- export declare function sortAccountsByQuota(accounts: ManagedAccount[]): ManagedAccount[];
14
- export declare function filterHealthyAccounts(accounts: ManagedAccount[]): ManagedAccount[];
15
- export declare function getAccountWithMostQuota(accounts: ManagedAccount[]): ManagedAccount | null;
@@ -1,68 +0,0 @@
1
- import { calculateUsagePercentage, isQuotaExhausted, getRemainingCount } from './usage';
2
- const WARNING_THRESHOLD_PERCENT = 80;
3
- export function checkQuotaStatus(account) {
4
- if (!account.usedCount || !account.limitCount) {
5
- return 'healthy';
6
- }
7
- const usage = {
8
- usedCount: account.usedCount,
9
- limitCount: account.limitCount,
10
- };
11
- if (isQuotaExhausted(usage)) {
12
- return 'exhausted';
13
- }
14
- const percentage = calculateUsagePercentage(usage);
15
- if (percentage >= WARNING_THRESHOLD_PERCENT) {
16
- return 'warning';
17
- }
18
- return 'healthy';
19
- }
20
- export function updateAccountQuota(account, usage, accountManager) {
21
- const metadata = {
22
- usedCount: typeof usage.usedCount === 'number' ? usage.usedCount : 0,
23
- limitCount: typeof usage.limitCount === 'number' ? usage.limitCount : 0,
24
- realEmail: usage.email
25
- };
26
- account.usedCount = metadata.usedCount;
27
- account.limitCount = metadata.limitCount;
28
- if (metadata.realEmail) {
29
- account.realEmail = metadata.realEmail;
30
- }
31
- if (accountManager) {
32
- accountManager.updateUsage(account.id, metadata);
33
- }
34
- }
35
- export function sortAccountsByQuota(accounts) {
36
- return [...accounts].sort((a, b) => {
37
- const aRemaining = getRemainingQuota(a);
38
- const bRemaining = getRemainingQuota(b);
39
- return bRemaining - aRemaining;
40
- });
41
- }
42
- function getRemainingQuota(account) {
43
- if (!account.usedCount || !account.limitCount) {
44
- return Infinity;
45
- }
46
- const usage = {
47
- usedCount: account.usedCount,
48
- limitCount: account.limitCount,
49
- };
50
- return getRemainingCount(usage);
51
- }
52
- export function filterHealthyAccounts(accounts) {
53
- return accounts.filter(account => {
54
- if (!account.isHealthy) {
55
- return false;
56
- }
57
- const status = checkQuotaStatus(account);
58
- return status !== 'exhausted';
59
- });
60
- }
61
- export function getAccountWithMostQuota(accounts) {
62
- const healthyAccounts = filterHealthyAccounts(accounts);
63
- if (healthyAccounts.length === 0) {
64
- return null;
65
- }
66
- const sorted = sortAccountsByQuota(healthyAccounts);
67
- return sorted[0] || null;
68
- }
@@ -1,19 +0,0 @@
1
- export interface RecoveryState {
2
- sessionId: string;
3
- conversationId: string;
4
- model: string;
5
- lastMessageIndex: number;
6
- errorCount: number;
7
- lastError?: string;
8
- timestamp: number;
9
- }
10
- export interface RecoveryStorage {
11
- version: 1;
12
- sessions: Record<string, RecoveryState>;
13
- }
14
- export interface SessionRecoveryHook {
15
- handleSessionError(error: any, sessionId: string): Promise<boolean>;
16
- isRecoverableError(error: any): boolean;
17
- clearSession(sessionId: string): Promise<void>;
18
- }
19
- export declare function createSessionRecoveryHook(enabled: boolean, autoResume: boolean): SessionRecoveryHook;
@@ -1,302 +0,0 @@
1
- import { promises as fs } from 'node:fs';
2
- import { dirname } from 'node:path';
3
- import { randomBytes } from 'node:crypto';
4
- import lockfile from 'proper-lockfile';
5
- import { xdgConfig } from 'xdg-basedir';
6
- import * as logger from './logger';
7
- import { KiroTokenRefreshError, KiroQuotaExhaustedError, KiroRateLimitError, KiroAuthError } from './errors';
8
- const LOCK_OPTIONS = {
9
- stale: 10000,
10
- retries: {
11
- retries: 5,
12
- minTimeout: 100,
13
- maxTimeout: 1000,
14
- factor: 2,
15
- },
16
- };
17
- const MAX_ERROR_COUNT = 3;
18
- function getRecoveryPath() {
19
- const configDir = xdgConfig || `${process.env.HOME}/.config`;
20
- return `${configDir}/opencode/kiro-recovery.json`;
21
- }
22
- async function ensureFileExists(path) {
23
- try {
24
- await fs.access(path);
25
- }
26
- catch {
27
- await fs.mkdir(dirname(path), { recursive: true });
28
- const defaultStorage = {
29
- version: 1,
30
- sessions: {},
31
- };
32
- await fs.writeFile(path, JSON.stringify(defaultStorage, null, 2), 'utf-8');
33
- }
34
- }
35
- async function withFileLock(path, fn) {
36
- await ensureFileExists(path);
37
- let release = null;
38
- try {
39
- release = await lockfile.lock(path, LOCK_OPTIONS);
40
- return await fn();
41
- }
42
- catch (error) {
43
- logger.error('Recovery file lock operation failed', error);
44
- throw error;
45
- }
46
- finally {
47
- if (release) {
48
- try {
49
- await release();
50
- }
51
- catch (unlockError) {
52
- logger.warn('Failed to release recovery lock', unlockError);
53
- }
54
- }
55
- }
56
- }
57
- async function loadRecoveryState() {
58
- const path = getRecoveryPath();
59
- try {
60
- await ensureFileExists(path);
61
- const content = await fs.readFile(path, 'utf-8');
62
- const data = JSON.parse(content);
63
- if (data.version !== 1) {
64
- logger.warn('Unknown recovery storage version, returning default');
65
- return {
66
- version: 1,
67
- sessions: {},
68
- };
69
- }
70
- if (typeof data.sessions !== 'object' || data.sessions === null) {
71
- logger.warn('Invalid sessions object, returning default');
72
- return {
73
- version: 1,
74
- sessions: {},
75
- };
76
- }
77
- return data;
78
- }
79
- catch (error) {
80
- const code = error.code;
81
- if (code === 'ENOENT') {
82
- return {
83
- version: 1,
84
- sessions: {},
85
- };
86
- }
87
- logger.error('Failed to load recovery state', error);
88
- return {
89
- version: 1,
90
- sessions: {},
91
- };
92
- }
93
- }
94
- async function saveRecoveryState(state) {
95
- const path = getRecoveryPath();
96
- await withFileLock(path, async () => {
97
- const tempPath = `${path}.${randomBytes(6).toString('hex')}.tmp`;
98
- const content = JSON.stringify(state, null, 2);
99
- await fs.mkdir(dirname(path), { recursive: true });
100
- await fs.writeFile(tempPath, content, 'utf-8');
101
- await fs.rename(tempPath, path);
102
- });
103
- }
104
- function isNetworkError(error) {
105
- if (!error)
106
- return false;
107
- const errorCode = error.code || error.errno;
108
- if (typeof errorCode === 'string') {
109
- const networkCodes = [
110
- 'ECONNRESET',
111
- 'ECONNREFUSED',
112
- 'ETIMEDOUT',
113
- 'ENOTFOUND',
114
- 'ENETUNREACH',
115
- 'EHOSTUNREACH',
116
- 'EPIPE',
117
- 'EAI_AGAIN',
118
- ];
119
- if (networkCodes.includes(errorCode)) {
120
- return true;
121
- }
122
- }
123
- const message = error.message || error.toString?.() || '';
124
- const lowerMessage = message.toLowerCase();
125
- const networkPatterns = [
126
- 'network',
127
- 'connection',
128
- 'timeout',
129
- 'econnreset',
130
- 'econnrefused',
131
- 'socket hang up',
132
- 'fetch failed',
133
- ];
134
- return networkPatterns.some(pattern => lowerMessage.includes(pattern));
135
- }
136
- function getStatusCode(error) {
137
- if (!error)
138
- return null;
139
- if (typeof error.statusCode === 'number') {
140
- return error.statusCode;
141
- }
142
- if (typeof error.status === 'number') {
143
- return error.status;
144
- }
145
- if (error.response && typeof error.response.status === 'number') {
146
- return error.response.status;
147
- }
148
- return null;
149
- }
150
- function isRecoverableStatusCode(statusCode) {
151
- const recoverableCodes = [
152
- 429,
153
- 502,
154
- 503,
155
- 504,
156
- ];
157
- return recoverableCodes.includes(statusCode);
158
- }
159
- function isUnrecoverableStatusCode(statusCode) {
160
- const unrecoverableCodes = [
161
- 400,
162
- 402,
163
- 403,
164
- 404,
165
- ];
166
- return unrecoverableCodes.includes(statusCode);
167
- }
168
- function isRecoverableErrorImpl(error) {
169
- if (!error)
170
- return false;
171
- if (error instanceof KiroTokenRefreshError) {
172
- return false;
173
- }
174
- if (error instanceof KiroQuotaExhaustedError) {
175
- return false;
176
- }
177
- if (error instanceof KiroRateLimitError) {
178
- return true;
179
- }
180
- if (error instanceof KiroAuthError) {
181
- const statusCode = error.statusCode;
182
- if (statusCode === 401) {
183
- return true;
184
- }
185
- if (statusCode && isUnrecoverableStatusCode(statusCode)) {
186
- return false;
187
- }
188
- return true;
189
- }
190
- if (isNetworkError(error)) {
191
- return true;
192
- }
193
- const statusCode = getStatusCode(error);
194
- if (statusCode !== null) {
195
- if (isUnrecoverableStatusCode(statusCode)) {
196
- return false;
197
- }
198
- if (isRecoverableStatusCode(statusCode)) {
199
- return true;
200
- }
201
- }
202
- return false;
203
- }
204
- function getErrorMessage(error) {
205
- if (!error)
206
- return 'Unknown error';
207
- if (typeof error === 'string') {
208
- return error;
209
- }
210
- if (error.message && typeof error.message === 'string') {
211
- return error.message;
212
- }
213
- if (error.toString && typeof error.toString === 'function') {
214
- return error.toString();
215
- }
216
- try {
217
- return JSON.stringify(error);
218
- }
219
- catch {
220
- return 'Unknown error';
221
- }
222
- }
223
- export function createSessionRecoveryHook(enabled, autoResume) {
224
- const handleSessionError = async (error, sessionId) => {
225
- if (!enabled) {
226
- return false;
227
- }
228
- if (!sessionId) {
229
- logger.warn('No session ID provided for recovery');
230
- return false;
231
- }
232
- if (!isRecoverableErrorImpl(error)) {
233
- logger.debug('Error is not recoverable', { sessionId, error: getErrorMessage(error) });
234
- return false;
235
- }
236
- try {
237
- const storage = await loadRecoveryState();
238
- let sessionState = storage.sessions[sessionId];
239
- if (!sessionState) {
240
- sessionState = {
241
- sessionId,
242
- conversationId: '',
243
- model: '',
244
- lastMessageIndex: 0,
245
- errorCount: 1,
246
- lastError: getErrorMessage(error),
247
- timestamp: Date.now(),
248
- };
249
- }
250
- else {
251
- sessionState.errorCount += 1;
252
- sessionState.lastError = getErrorMessage(error);
253
- sessionState.timestamp = Date.now();
254
- }
255
- if (sessionState.errorCount > MAX_ERROR_COUNT) {
256
- logger.warn('Session error count exceeded maximum', {
257
- sessionId,
258
- errorCount: sessionState.errorCount
259
- });
260
- delete storage.sessions[sessionId];
261
- await saveRecoveryState(storage);
262
- return false;
263
- }
264
- storage.sessions[sessionId] = sessionState;
265
- await saveRecoveryState(storage);
266
- logger.log('Session error recorded for recovery', {
267
- sessionId,
268
- errorCount: sessionState.errorCount,
269
- shouldRetry: true
270
- });
271
- return true;
272
- }
273
- catch (storageError) {
274
- logger.error('Failed to handle session error', storageError);
275
- return false;
276
- }
277
- };
278
- const isRecoverableError = (error) => {
279
- return isRecoverableErrorImpl(error);
280
- };
281
- const clearSession = async (sessionId) => {
282
- if (!sessionId) {
283
- return;
284
- }
285
- try {
286
- const storage = await loadRecoveryState();
287
- if (storage.sessions[sessionId]) {
288
- delete storage.sessions[sessionId];
289
- await saveRecoveryState(storage);
290
- logger.debug('Session cleared from recovery state', { sessionId });
291
- }
292
- }
293
- catch (error) {
294
- logger.error('Failed to clear session', error);
295
- }
296
- };
297
- return {
298
- handleSessionError,
299
- isRecoverableError,
300
- clearSession,
301
- };
302
- }
@@ -1,14 +0,0 @@
1
- import type { KiroAuthDetails } from './types';
2
- import type { AccountManager } from './accounts';
3
- export interface ProactiveRefreshQueue {
4
- start(): void;
5
- stop(): void;
6
- setAccountManager(manager: AccountManager): void;
7
- }
8
- export interface RefreshQueueConfig {
9
- enabled: boolean;
10
- checkIntervalSeconds: number;
11
- bufferSeconds: number;
12
- }
13
- export declare function isTokenExpiringSoon(auth: KiroAuthDetails, bufferMs: number): boolean;
14
- export declare function createProactiveRefreshQueue(config: RefreshQueueConfig): ProactiveRefreshQueue;
@@ -1,69 +0,0 @@
1
- import { refreshAccessToken } from './token';
2
- import * as logger from './logger';
3
- export function isTokenExpiringSoon(auth, bufferMs) {
4
- const now = Date.now();
5
- const expiresAt = auth.expires;
6
- const timeUntilExpiry = expiresAt - now;
7
- return timeUntilExpiry <= bufferMs && timeUntilExpiry > 0;
8
- }
9
- export function createProactiveRefreshQueue(config) {
10
- let intervalId = null;
11
- let accountManager = null;
12
- let isRunning = false;
13
- async function checkAndRefresh() {
14
- if (!accountManager) {
15
- return;
16
- }
17
- try {
18
- const accounts = accountManager.getAccounts();
19
- const bufferMs = config.bufferSeconds * 1000;
20
- for (const account of accounts) {
21
- try {
22
- const auth = accountManager.toAuthDetails(account);
23
- if (isTokenExpiringSoon(auth, bufferMs)) {
24
- logger.log(`[RefreshQueue] Token expiring soon for account ${account.email}, refreshing...`);
25
- const refreshedAuth = await refreshAccessToken(auth);
26
- accountManager.updateFromAuth(account, refreshedAuth);
27
- await accountManager.saveToDisk();
28
- logger.log(`[RefreshQueue] Successfully refreshed token for account ${account.email}`);
29
- }
30
- }
31
- catch (error) {
32
- logger.error(`[RefreshQueue] Failed to refresh token for account ${account.email}: ${error instanceof Error ? error.message : String(error)}`);
33
- }
34
- }
35
- }
36
- catch (error) {
37
- logger.error(`[RefreshQueue] Error during refresh check: ${error instanceof Error ? error.message : String(error)}`);
38
- }
39
- }
40
- function start() {
41
- if (!config.enabled || isRunning) {
42
- return;
43
- }
44
- const intervalMs = config.checkIntervalSeconds * 1000;
45
- intervalId = setInterval(() => {
46
- checkAndRefresh().catch((error) => {
47
- logger.error(`[RefreshQueue] Unhandled error in refresh check: ${error instanceof Error ? error.message : String(error)}`);
48
- });
49
- }, intervalMs);
50
- isRunning = true;
51
- logger.log(`[RefreshQueue] Started proactive refresh queue (interval: ${config.checkIntervalSeconds}s, buffer: ${config.bufferSeconds}s)`);
52
- }
53
- function stop() {
54
- if (intervalId) {
55
- clearInterval(intervalId);
56
- intervalId = null;
57
- }
58
- isRunning = false;
59
- logger.log('[RefreshQueue] Stopped proactive refresh queue');
60
- }
61
- function setAccountManager(manager) {
62
- accountManager = manager;
63
- }
64
- return {
65
- start,
66
- stop,
67
- setAccountManager,
68
- };
69
- }
@@ -1,22 +0,0 @@
1
- import type { KiroRegion } from './plugin/types';
2
- export declare const KIRO_CONSTANTS: {
3
- REFRESH_URL: string;
4
- REFRESH_IDC_URL: string;
5
- BASE_URL: string;
6
- USAGE_LIMITS_URL: string;
7
- DEFAULT_REGION: KiroRegion;
8
- ACCESS_TOKEN_EXPIRY_BUFFER_MS: number;
9
- AXIOS_TIMEOUT: number;
10
- USER_AGENT: string;
11
- KIRO_VERSION: string;
12
- CHAT_TRIGGER_TYPE_MANUAL: string;
13
- ORIGIN_AI_EDITOR: string;
14
- };
15
- export declare const MODEL_MAPPING: Record<string, string>;
16
- export declare const SUPPORTED_MODELS: string[];
17
- export declare const KIRO_AUTH_SERVICE: {
18
- ENDPOINT: string;
19
- SSO_OIDC_ENDPOINT: string;
20
- BUILDER_ID_START_URL: string;
21
- SCOPES: string[];
22
- };