forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug.ts
More file actions
524 lines (466 loc) · 15.4 KB
/
Copy pathdebug.ts
File metadata and controls
524 lines (466 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import { createWriteStream, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
import { join } from "node:path";
import { env } from "node:process";
import { homedir } from "node:os";
import type { AntigravityConfig } from "./config";
import {
deriveDebugPolicy,
formatAccountContextLabel,
formatAccountLabel,
formatBodyPreviewForLog,
formatErrorForLog,
isTruthyFlag,
truncateTextForLog,
} from "./logging-utils";
import { ensureGitignoreSync } from "./storage";
const MAX_BODY_PREVIEW_CHARS = 12000;
const MAX_BODY_LOG_CHARS = 50000;
export const DEBUG_MESSAGE_PREFIX = "[opencode-antigravity-auth debug]";
// =============================================================================
// Debug State (lazily initialized with config)
// =============================================================================
interface DebugState {
debugEnabled: boolean;
debugTuiEnabled: boolean;
logFilePath: string | undefined;
logWriter: (line: string) => void;
}
let debugState: DebugState | null = null;
/**
* Get the OS-specific config directory.
*/
function getConfigDir(): string {
const platform = process.platform;
if (platform === "win32") {
return join(env.APPDATA || join(homedir(), "AppData", "Roaming"), "opencode");
}
const xdgConfig = env.XDG_CONFIG_HOME || join(homedir(), ".config");
return join(xdgConfig, "opencode");
}
/**
* Returns the logs directory, creating it if needed.
*/
function getLogsDir(customLogDir?: string): string {
const logsDir = customLogDir || join(getConfigDir(), "antigravity-logs");
try {
mkdirSync(logsDir, { recursive: true });
} catch {
// Directory may already exist or we don't have permission
}
return logsDir;
}
/**
* Builds a timestamped log file path.
*/
function createLogFilePath(customLogDir?: string): string {
const logsDir = getLogsDir(customLogDir);
cleanupOldLogs(logsDir, 25);
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
return join(logsDir, `antigravity-debug-${timestamp}.log`);
}
/**
* Cleans up old log files, keeping only the most recent maxFiles.
*/
function cleanupOldLogs(logsDir: string, maxFiles: number): void {
try {
const files = readdirSync(logsDir)
.filter((file) => file.startsWith("antigravity-debug-") && file.endsWith(".log"))
.map((file) => join(logsDir, file));
if (files.length <= maxFiles) {
return;
}
const sortedFiles = files
.map((file) => ({
file,
mtime: statSync(file).mtimeMs,
}))
.sort((a, b) => b.mtime - a.mtime);
for (let i = maxFiles; i < sortedFiles.length; i++) {
try {
unlinkSync(sortedFiles[i]!.file);
} catch {
// Ignore deletion errors
}
}
} catch {
// Ignore directory read errors
}
}
/**
* Creates a log writer function that writes to a file.
*/
function createLogWriter(filePath?: string): (line: string) => void {
if (!filePath) {
return () => {};
}
try {
const stream = createWriteStream(filePath, { flags: "a" });
stream.on("error", () => {});
return (line: string) => {
const timestamp = new Date().toISOString();
const formatted = `[${timestamp}] ${line}`;
stream.write(`${formatted}\n`);
};
} catch {
return () => {};
}
}
/**
* Initialize or reinitialize debug state with the given config.
* Call this once at plugin startup after loading config.
*/
export function initializeDebug(config: AntigravityConfig): void {
// Config takes precedence, but env var can force enable for debugging
const envDebugFlag = env.OPENCODE_ANTIGRAVITY_DEBUG ?? "";
const { debugEnabled } = deriveDebugPolicy({
configDebug: config.debug,
configDebugTui: config.debug_tui,
envDebugFlag,
envDebugTuiFlag: env.OPENCODE_ANTIGRAVITY_DEBUG_TUI,
});
const debugTuiEnabled = config.debug_tui || isTruthyFlag(env.OPENCODE_ANTIGRAVITY_DEBUG_TUI);
const logFilePath = debugEnabled ? createLogFilePath(config.log_dir) : undefined;
const logWriter = createLogWriter(logFilePath);
if (debugEnabled) {
ensureGitignoreSync(getConfigDir());
}
debugState = {
debugEnabled,
debugTuiEnabled,
logFilePath,
logWriter,
};
}
/**
* Get the current debug state, initializing with defaults if needed.
* This allows the module to work even before initializeDebug is called.
*/
function getDebugState(): DebugState {
if (!debugState) {
// Fallback to env-based initialization for backward compatibility
const { debugEnabled } = deriveDebugPolicy({
configDebug: false,
configDebugTui: false,
envDebugFlag: env.OPENCODE_ANTIGRAVITY_DEBUG,
envDebugTuiFlag: env.OPENCODE_ANTIGRAVITY_DEBUG_TUI,
});
const debugTuiEnabled = isTruthyFlag(env.OPENCODE_ANTIGRAVITY_DEBUG_TUI);
const logFilePath = debugEnabled ? createLogFilePath() : undefined;
const logWriter = createLogWriter(logFilePath);
debugState = {
debugEnabled,
debugTuiEnabled,
logFilePath,
logWriter,
};
}
return debugState;
}
// =============================================================================
// Public API
// =============================================================================
export function isDebugEnabled(): boolean {
return getDebugState().debugEnabled;
}
export function isDebugTuiEnabled(): boolean {
return getDebugState().debugTuiEnabled;
}
export function getLogFilePath(): string | undefined {
return getDebugState().logFilePath;
}
export interface AntigravityDebugContext {
id: string;
streaming: boolean;
startedAt: number;
}
interface AntigravityDebugRequestMeta {
originalUrl: string;
resolvedUrl: string;
method?: string;
headers?: HeadersInit;
body?: BodyInit | null;
streaming: boolean;
projectId?: string;
}
interface AntigravityDebugResponseMeta {
body?: string;
note?: string;
error?: unknown;
headersOverride?: HeadersInit;
}
let requestCounter = 0;
/**
* Begins a debug trace for an Antigravity request.
*/
export function startAntigravityDebugRequest(meta: AntigravityDebugRequestMeta): AntigravityDebugContext | null {
const state = getDebugState();
if (!state.debugEnabled) {
return null;
}
const id = `ANTIGRAVITY-${++requestCounter}`;
const method = meta.method ?? "GET";
logDebug(`[Antigravity Debug ${id}] pid=${process.pid} ${method} ${meta.resolvedUrl}`);
if (meta.originalUrl && meta.originalUrl !== meta.resolvedUrl) {
logDebug(`[Antigravity Debug ${id}] Original URL: ${meta.originalUrl}`);
}
if (meta.projectId) {
logDebug(`[Antigravity Debug ${id}] Project: ${meta.projectId}`);
}
logDebug(`[Antigravity Debug ${id}] Streaming: ${meta.streaming ? "yes" : "no"}`);
logDebug(`[Antigravity Debug ${id}] Headers: ${JSON.stringify(maskHeaders(meta.headers))}`);
const bodyPreview = formatBodyPreviewForLog(meta.body, MAX_BODY_PREVIEW_CHARS);
if (bodyPreview) {
logDebug(`[Antigravity Debug ${id}] Body Preview: ${bodyPreview}`);
}
return { id, streaming: meta.streaming, startedAt: Date.now() };
}
/**
* Logs response details for a previously started debug trace.
*/
export function logAntigravityDebugResponse(
context: AntigravityDebugContext | null | undefined,
response: Response,
meta: AntigravityDebugResponseMeta = {},
): void {
const state = getDebugState();
if (!state.debugEnabled || !context) {
return;
}
const durationMs = Date.now() - context.startedAt;
logDebug(
`[Antigravity Debug ${context.id}] Response ${response.status} ${response.statusText} (${durationMs}ms)`,
);
logDebug(
`[Antigravity Debug ${context.id}] Response Headers: ${JSON.stringify(
maskHeaders(meta.headersOverride ?? response.headers),
)}`,
);
if (meta.note) {
logDebug(`[Antigravity Debug ${context.id}] Note: ${meta.note}`);
}
if (meta.error) {
logDebug(`[Antigravity Debug ${context.id}] Error: ${formatErrorForLog(meta.error)}`);
}
if (meta.body) {
logDebug(
`[Antigravity Debug ${context.id}] Response Body Preview: ${truncateTextForLog(meta.body, MAX_BODY_PREVIEW_CHARS)}`,
);
}
}
/**
* Obscures sensitive headers and returns a plain object for logging.
*/
function maskHeaders(headers?: HeadersInit | Headers): Record<string, string> {
if (!headers) {
return {};
}
const result: Record<string, string> = {};
const parsed = headers instanceof Headers ? headers : new Headers(headers);
parsed.forEach((value, key) => {
if (key.toLowerCase() === "authorization") {
result[key] = "[redacted]";
} else {
result[key] = value;
}
});
return result;
}
/**
* Writes a single debug line using the configured writer.
*/
function logDebug(line: string): void {
getDebugState().logWriter(line);
}
function runWithDebugEnabled(action: () => void): void {
if (!getDebugState().debugEnabled) return;
action();
}
export interface AccountDebugInfo {
index: number;
email?: string;
family: string;
totalAccounts: number;
rateLimitState?: { claude?: number; gemini?: number };
}
export function logAccountContext(label: string, info: AccountDebugInfo): void {
runWithDebugEnabled(() => {
const accountLabel = formatAccountContextLabel(info.email, info.index);
const indexLabel = info.index >= 0 ? `${info.index + 1}/${info.totalAccounts}` : `-/${info.totalAccounts}`;
let rateLimitInfo = "";
if (info.rateLimitState && Object.keys(info.rateLimitState).length > 0) {
const now = Date.now();
const activeRateLimits: Record<string, string> = {};
for (const [key, resetTime] of Object.entries(info.rateLimitState)) {
if (typeof resetTime === "number" && resetTime > now) {
const remainingSec = Math.ceil((resetTime - now) / 1000);
activeRateLimits[key] = `${remainingSec}s`;
}
}
if (Object.keys(activeRateLimits).length > 0) {
rateLimitInfo = ` rateLimits=${JSON.stringify(activeRateLimits)}`;
}
}
logDebug(`[Account] ${label}: ${accountLabel} (${indexLabel}) family=${info.family}${rateLimitInfo}`);
});
}
export function logRateLimitEvent(
accountIndex: number,
email: string | undefined,
family: string,
status: number,
retryAfterMs: number,
bodyInfo: { message?: string; quotaResetTime?: string; retryDelayMs?: number | null; reason?: string },
): void {
runWithDebugEnabled(() => {
const accountLabel = formatAccountLabel(email, accountIndex);
logDebug(`[RateLimit] ${status} on ${accountLabel} family=${family} retryAfterMs=${retryAfterMs}`);
if (bodyInfo.message) {
logDebug(`[RateLimit] message: ${bodyInfo.message}`);
}
if (bodyInfo.quotaResetTime) {
logDebug(`[RateLimit] quotaResetTime: ${bodyInfo.quotaResetTime}`);
}
if (bodyInfo.retryDelayMs !== undefined && bodyInfo.retryDelayMs !== null) {
logDebug(`[RateLimit] body retryDelayMs: ${bodyInfo.retryDelayMs}`);
}
if (bodyInfo.reason) {
logDebug(`[RateLimit] reason: ${bodyInfo.reason}`);
}
});
}
export function logRateLimitSnapshot(
family: string,
accounts: Array<{ index: number; email?: string; rateLimitResetTimes?: { claude?: number; gemini?: number } }>,
): void {
runWithDebugEnabled(() => {
const now = Date.now();
const entries = accounts.map((account) => {
const label = formatAccountLabel(account.email, account.index);
const reset = account.rateLimitResetTimes?.[family as "claude" | "gemini"];
if (typeof reset !== "number") {
return `${label}=ready`;
}
const remaining = Math.max(0, reset - now);
const seconds = Math.ceil(remaining / 1000);
return `${label}=wait ${seconds}s`;
});
logDebug(`[RateLimit] snapshot family=${family} ${entries.join(" | ")}`);
});
}
export async function logResponseBody(
context: AntigravityDebugContext | null | undefined,
response: Response,
status: number,
): Promise<string | undefined> {
const state = getDebugState();
if (!state.debugEnabled || !context) return undefined;
try {
const text = await response.clone().text();
const preview = truncateTextForLog(text, MAX_BODY_LOG_CHARS);
logDebug(`[Antigravity Debug ${context.id}] Response Body (${status}): ${preview}`);
return text;
} catch (e) {
logDebug(`[Antigravity Debug ${context.id}] Failed to read response body: ${formatErrorForLog(e)}`);
return undefined;
}
}
export function logModelFamily(url: string, extractedModel: string | null, family: string): void {
runWithDebugEnabled(() => {
logDebug(`[ModelFamily] url=${url} model=${extractedModel ?? "unknown"} family=${family}`);
});
}
export function debugLogToFile(message: string): void {
runWithDebugEnabled(() => {
logDebug(message);
});
}
/**
* Logs a toast message to the debug file.
* This helps correlate what the user saw with debug events.
*/
export function logToast(message: string, variant: "info" | "warning" | "success" | "error"): void {
runWithDebugEnabled(() => {
const variantLabel = variant.toUpperCase();
logDebug(`[Toast/${variantLabel}] ${message}`);
});
}
/**
* Logs retry attempt information.
* @param maxAttempts - Use -1 for unlimited retries
*/
export function logRetryAttempt(
attempt: number,
maxAttempts: number,
reason: string,
delayMs?: number,
): void {
runWithDebugEnabled(() => {
const delayInfo = delayMs !== undefined ? ` delay=${delayMs}ms` : "";
const maxInfo = maxAttempts < 0 ? "∞" : maxAttempts.toString();
logDebug(`[Retry] Attempt ${attempt}/${maxInfo} reason=${reason}${delayInfo}`);
});
}
/**
* Logs cache hit/miss information from response usage metadata.
*/
export function logCacheStats(
model: string,
cacheReadTokens: number,
cacheWriteTokens: number,
totalInputTokens: number,
): void {
runWithDebugEnabled(() => {
const cacheHitRate = totalInputTokens > 0
? Math.round((cacheReadTokens / totalInputTokens) * 100)
: 0;
const status = cacheReadTokens > 0 ? "HIT" : (cacheWriteTokens > 0 ? "WRITE" : "MISS");
logDebug(`[Cache] ${status} model=${model} read=${cacheReadTokens} write=${cacheWriteTokens} total=${totalInputTokens} hitRate=${cacheHitRate}%`);
});
}
/**
* Logs quota status for an account.
*/
export function logQuotaStatus(
accountEmail: string | undefined,
accountIndex: number,
quotaPercent: number,
family?: string,
): void {
runWithDebugEnabled(() => {
const accountLabel = formatAccountLabel(accountEmail, accountIndex);
const familyInfo = family ? ` family=${family}` : "";
const status = quotaPercent <= 0 ? "EXHAUSTED" : quotaPercent < 20 ? "LOW" : "OK";
logDebug(`[Quota] ${accountLabel} remaining=${quotaPercent.toFixed(1)}% status=${status}${familyInfo}`);
});
}
/**
* Logs background quota fetch events.
*/
export function logQuotaFetch(
event: "start" | "complete" | "error",
accountCount?: number,
details?: string,
): void {
runWithDebugEnabled(() => {
const countInfo = accountCount !== undefined ? ` accounts=${accountCount}` : "";
const detailsInfo = details ? ` ${details}` : "";
logDebug(`[QuotaFetch] ${event.toUpperCase()}${countInfo}${detailsInfo}`);
});
}
/**
* Logs which model is being used for a request.
*/
export function logModelUsed(
requestedModel: string,
actualModel: string,
accountEmail?: string,
): void {
runWithDebugEnabled(() => {
const accountInfo = accountEmail ? ` account=${accountEmail}` : "";
if (requestedModel !== actualModel) {
logDebug(`[Model] requested=${requestedModel} actual=${actualModel}${accountInfo}`);
} else {
logDebug(`[Model] ${actualModel}${accountInfo}`);
}
});
}