@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.
- package/README.md +1 -1
- package/dist/constants.js +7 -1
- package/dist/kiro/oauth-idc.js +4 -1
- package/dist/plugin/accounts.js +11 -2
- package/dist/plugin/auth-page.js +6 -1
- package/dist/plugin/config/loader.js +3 -1
- package/dist/plugin/logger.js +3 -5
- package/dist/plugin/request.js +148 -28
- package/dist/plugin/response.js +9 -2
- package/dist/plugin/server.js +16 -3
- package/dist/plugin/streaming.js +9 -2
- package/dist/plugin/types.d.ts +1 -1
- package/dist/plugin/usage.js +11 -2
- package/dist/plugin.js +30 -6
- package/package.json +2 -2
- package/dist/kiro/oauth-social.d.ts +0 -17
- package/dist/kiro/oauth-social.js +0 -51
- package/dist/plugin/cli.d.ts +0 -6
- package/dist/plugin/cli.js +0 -98
- package/dist/plugin/debug.d.ts +0 -2
- package/dist/plugin/debug.js +0 -9
- package/dist/plugin/oauth-parser.d.ts +0 -5
- package/dist/plugin/oauth-parser.js +0 -23
- package/dist/plugin/quota.d.ts +0 -15
- package/dist/plugin/quota.js +0 -68
- package/dist/plugin/recovery.d.ts +0 -19
- package/dist/plugin/recovery.js +0 -302
- package/dist/plugin/refresh-queue.d.ts +0 -14
- package/dist/plugin/refresh-queue.js +0 -69
- package/dist/src/constants.d.ts +0 -22
- package/dist/src/constants.js +0 -35
- package/dist/src/kiro/auth.d.ts +0 -5
- package/dist/src/kiro/auth.js +0 -69
- package/dist/src/kiro/oauth-idc.d.ts +0 -22
- package/dist/src/kiro/oauth-idc.js +0 -99
- package/dist/src/kiro/oauth-social.d.ts +0 -17
- package/dist/src/kiro/oauth-social.js +0 -69
- package/dist/src/plugin/accounts.d.ts +0 -23
- package/dist/src/plugin/accounts.js +0 -265
- package/dist/src/plugin/cli.d.ts +0 -6
- package/dist/src/plugin/cli.js +0 -98
- package/dist/src/plugin/config/index.d.ts +0 -3
- package/dist/src/plugin/config/index.js +0 -2
- package/dist/src/plugin/config/loader.d.ts +0 -7
- package/dist/src/plugin/config/loader.js +0 -143
- package/dist/src/plugin/config/schema.d.ts +0 -68
- package/dist/src/plugin/config/schema.js +0 -44
- package/dist/src/plugin/debug.d.ts +0 -2
- package/dist/src/plugin/debug.js +0 -9
- package/dist/src/plugin/errors.d.ts +0 -17
- package/dist/src/plugin/errors.js +0 -34
- package/dist/src/plugin/logger.d.ts +0 -4
- package/dist/src/plugin/logger.js +0 -17
- package/dist/src/plugin/models.d.ts +0 -3
- package/dist/src/plugin/models.js +0 -14
- package/dist/src/plugin/oauth-parser.d.ts +0 -5
- package/dist/src/plugin/oauth-parser.js +0 -23
- package/dist/src/plugin/quota.d.ts +0 -25
- package/dist/src/plugin/quota.js +0 -175
- package/dist/src/plugin/recovery.d.ts +0 -19
- package/dist/src/plugin/recovery.js +0 -302
- package/dist/src/plugin/refresh-queue.d.ts +0 -14
- package/dist/src/plugin/refresh-queue.js +0 -69
- package/dist/src/plugin/request.d.ts +0 -35
- package/dist/src/plugin/request.js +0 -411
- package/dist/src/plugin/response.d.ts +0 -6
- package/dist/src/plugin/response.js +0 -246
- package/dist/src/plugin/server.d.ts +0 -10
- package/dist/src/plugin/server.js +0 -203
- package/dist/src/plugin/storage.d.ts +0 -5
- package/dist/src/plugin/storage.js +0 -106
- package/dist/src/plugin/streaming.d.ts +0 -12
- package/dist/src/plugin/streaming.js +0 -444
- package/dist/src/plugin/token.d.ts +0 -8
- package/dist/src/plugin/token.js +0 -130
- package/dist/src/plugin/types.d.ts +0 -144
- package/dist/src/plugin/types.js +0 -0
- package/dist/src/plugin/usage.d.ts +0 -28
- package/dist/src/plugin/usage.js +0 -159
- package/dist/src/plugin.d.ts +0 -2
- package/dist/src/plugin.js +0 -341
package/dist/src/plugin/quota.js
DELETED
|
@@ -1,175 +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) {
|
|
21
|
-
account.usedCount = usage.usedCount;
|
|
22
|
-
account.limitCount = usage.limitCount;
|
|
23
|
-
}
|
|
24
|
-
export function getNextAvailableAccount(accounts) {
|
|
25
|
-
const availableAccounts = accounts.filter(account => {
|
|
26
|
-
if (!account.isHealthy) {
|
|
27
|
-
return false;
|
|
28
|
-
}
|
|
29
|
-
const status = checkQuotaStatus(account);
|
|
30
|
-
return status !== 'exhausted';
|
|
31
|
-
});
|
|
32
|
-
if (availableAccounts.length === 0) {
|
|
33
|
-
return null;
|
|
34
|
-
}
|
|
35
|
-
return availableAccounts[0] || null;
|
|
36
|
-
}
|
|
37
|
-
export function sortAccountsByQuota(accounts) {
|
|
38
|
-
return [...accounts].sort((a, b) => {
|
|
39
|
-
const aRemaining = getRemainingQuota(a);
|
|
40
|
-
const bRemaining = getRemainingQuota(b);
|
|
41
|
-
return bRemaining - aRemaining;
|
|
42
|
-
});
|
|
43
|
-
}
|
|
44
|
-
function getRemainingQuota(account) {
|
|
45
|
-
if (!account.usedCount || !account.limitCount) {
|
|
46
|
-
return Infinity;
|
|
47
|
-
}
|
|
48
|
-
const usage = {
|
|
49
|
-
usedCount: account.usedCount,
|
|
50
|
-
limitCount: account.limitCount,
|
|
51
|
-
};
|
|
52
|
-
return getRemainingCount(usage);
|
|
53
|
-
}
|
|
54
|
-
export function buildQuotaInfo(account) {
|
|
55
|
-
const used = account.usedCount || 0;
|
|
56
|
-
const limit = account.limitCount || 0;
|
|
57
|
-
const remaining = Math.max(0, limit - used);
|
|
58
|
-
const percentage = limit > 0 ? Math.round((used / limit) * 100) : 0;
|
|
59
|
-
const status = checkQuotaStatus(account);
|
|
60
|
-
const info = {
|
|
61
|
-
status,
|
|
62
|
-
used,
|
|
63
|
-
limit,
|
|
64
|
-
remaining,
|
|
65
|
-
percentage,
|
|
66
|
-
};
|
|
67
|
-
if (account.recoveryTime) {
|
|
68
|
-
info.recoveryTime = account.recoveryTime;
|
|
69
|
-
}
|
|
70
|
-
return info;
|
|
71
|
-
}
|
|
72
|
-
export function filterHealthyAccounts(accounts) {
|
|
73
|
-
return accounts.filter(account => {
|
|
74
|
-
if (!account.isHealthy) {
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
const status = checkQuotaStatus(account);
|
|
78
|
-
return status !== 'exhausted';
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
export function filterExhaustedAccounts(accounts) {
|
|
82
|
-
return accounts.filter(account => {
|
|
83
|
-
const status = checkQuotaStatus(account);
|
|
84
|
-
return status === 'exhausted';
|
|
85
|
-
});
|
|
86
|
-
}
|
|
87
|
-
export function filterWarningAccounts(accounts) {
|
|
88
|
-
return accounts.filter(account => {
|
|
89
|
-
const status = checkQuotaStatus(account);
|
|
90
|
-
return status === 'warning';
|
|
91
|
-
});
|
|
92
|
-
}
|
|
93
|
-
export function hasAvailableQuota(account) {
|
|
94
|
-
const status = checkQuotaStatus(account);
|
|
95
|
-
return status !== 'exhausted';
|
|
96
|
-
}
|
|
97
|
-
export function isQuotaNearLimit(account, thresholdPercent = WARNING_THRESHOLD_PERCENT) {
|
|
98
|
-
if (!account.usedCount || !account.limitCount) {
|
|
99
|
-
return false;
|
|
100
|
-
}
|
|
101
|
-
const usage = {
|
|
102
|
-
usedCount: account.usedCount,
|
|
103
|
-
limitCount: account.limitCount,
|
|
104
|
-
};
|
|
105
|
-
const percentage = calculateUsagePercentage(usage);
|
|
106
|
-
return percentage >= thresholdPercent;
|
|
107
|
-
}
|
|
108
|
-
export function getAccountWithMostQuota(accounts) {
|
|
109
|
-
const healthyAccounts = filterHealthyAccounts(accounts);
|
|
110
|
-
if (healthyAccounts.length === 0) {
|
|
111
|
-
return null;
|
|
112
|
-
}
|
|
113
|
-
const sorted = sortAccountsByQuota(healthyAccounts);
|
|
114
|
-
return sorted[0] || null;
|
|
115
|
-
}
|
|
116
|
-
export function getAccountWithLeastQuota(accounts) {
|
|
117
|
-
const healthyAccounts = filterHealthyAccounts(accounts);
|
|
118
|
-
if (healthyAccounts.length === 0) {
|
|
119
|
-
return null;
|
|
120
|
-
}
|
|
121
|
-
const sorted = sortAccountsByQuota(healthyAccounts);
|
|
122
|
-
return sorted[sorted.length - 1] || null;
|
|
123
|
-
}
|
|
124
|
-
export function getTotalQuotaInfo(accounts) {
|
|
125
|
-
let totalUsed = 0;
|
|
126
|
-
let totalLimit = 0;
|
|
127
|
-
for (const account of accounts) {
|
|
128
|
-
if (account.usedCount && account.limitCount) {
|
|
129
|
-
totalUsed += account.usedCount;
|
|
130
|
-
totalLimit += account.limitCount;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
const remaining = Math.max(0, totalLimit - totalUsed);
|
|
134
|
-
const percentage = totalLimit > 0 ? Math.round((totalUsed / totalLimit) * 100) : 0;
|
|
135
|
-
let status = 'healthy';
|
|
136
|
-
if (totalUsed >= totalLimit) {
|
|
137
|
-
status = 'exhausted';
|
|
138
|
-
}
|
|
139
|
-
else if (percentage >= WARNING_THRESHOLD_PERCENT) {
|
|
140
|
-
status = 'warning';
|
|
141
|
-
}
|
|
142
|
-
return {
|
|
143
|
-
status,
|
|
144
|
-
used: totalUsed,
|
|
145
|
-
limit: totalLimit,
|
|
146
|
-
remaining,
|
|
147
|
-
percentage,
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
export function shouldRotateAccount(account, rotationThreshold = 90) {
|
|
151
|
-
if (!account.usedCount || !account.limitCount) {
|
|
152
|
-
return false;
|
|
153
|
-
}
|
|
154
|
-
const usage = {
|
|
155
|
-
usedCount: account.usedCount,
|
|
156
|
-
limitCount: account.limitCount,
|
|
157
|
-
};
|
|
158
|
-
const percentage = calculateUsagePercentage(usage);
|
|
159
|
-
return percentage >= rotationThreshold;
|
|
160
|
-
}
|
|
161
|
-
export function selectAccountForRequest(accounts, strategy = 'most-quota') {
|
|
162
|
-
const healthyAccounts = filterHealthyAccounts(accounts);
|
|
163
|
-
if (healthyAccounts.length === 0) {
|
|
164
|
-
return null;
|
|
165
|
-
}
|
|
166
|
-
if (strategy === 'most-quota') {
|
|
167
|
-
return getAccountWithMostQuota(healthyAccounts);
|
|
168
|
-
}
|
|
169
|
-
const sorted = healthyAccounts.sort((a, b) => {
|
|
170
|
-
const aLastUsed = a.lastUsed || 0;
|
|
171
|
-
const bLastUsed = b.lastUsed || 0;
|
|
172
|
-
return aLastUsed - bLastUsed;
|
|
173
|
-
});
|
|
174
|
-
return sorted[0] || null;
|
|
175
|
-
}
|
|
@@ -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,35 +0,0 @@
|
|
|
1
|
-
import type { KiroAuthDetails, PreparedRequest } from './types';
|
|
2
|
-
interface OpenAIMessage {
|
|
3
|
-
role: 'user' | 'assistant' | 'system';
|
|
4
|
-
content: string | Array<{
|
|
5
|
-
type: string;
|
|
6
|
-
text?: string;
|
|
7
|
-
image_url?: {
|
|
8
|
-
url: string;
|
|
9
|
-
};
|
|
10
|
-
tool_use_id?: string;
|
|
11
|
-
id?: string;
|
|
12
|
-
name?: string;
|
|
13
|
-
input?: unknown;
|
|
14
|
-
thinking?: string;
|
|
15
|
-
source?: {
|
|
16
|
-
media_type: string;
|
|
17
|
-
data: string;
|
|
18
|
-
};
|
|
19
|
-
}>;
|
|
20
|
-
}
|
|
21
|
-
interface OpenAITool {
|
|
22
|
-
name: string;
|
|
23
|
-
description?: string;
|
|
24
|
-
input_schema?: Record<string, unknown>;
|
|
25
|
-
}
|
|
26
|
-
export declare function transformToCodeWhisperer(url: string, body: string, model: string, auth: KiroAuthDetails, thinkingEnabled?: boolean, thinkingBudget?: number): PreparedRequest;
|
|
27
|
-
export declare function mergeAdjacentMessages(messages: OpenAIMessage[]): OpenAIMessage[];
|
|
28
|
-
export declare function convertToolsToCodeWhisperer(tools: OpenAITool[]): any[];
|
|
29
|
-
export declare function extractImagesFromContent(content: any): {
|
|
30
|
-
text: string;
|
|
31
|
-
images: any[];
|
|
32
|
-
};
|
|
33
|
-
export declare function buildUserAgent(machineId: string): string;
|
|
34
|
-
export declare function generateMachineId(auth: KiroAuthDetails): string;
|
|
35
|
-
export {};
|