antigravity-auth 1.6.0 → 1.7.1

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 (258) hide show
  1. package/README.md +79 -41
  2. package/dist/cli.js +17854 -0
  3. package/dist/handler.js +25147 -0
  4. package/dist/index.js +25138 -5
  5. package/package.json +66 -54
  6. package/dist/antigravity/oauth.d.ts +0 -30
  7. package/dist/antigravity/oauth.js +0 -170
  8. package/dist/claude/login.d.ts +0 -7
  9. package/dist/claude/login.js +0 -480
  10. package/dist/claude/menu-helpers.d.ts +0 -22
  11. package/dist/claude/menu-helpers.js +0 -281
  12. package/dist/claude/proxy-manager.d.ts +0 -11
  13. package/dist/claude/proxy-manager.js +0 -129
  14. package/dist/claude/proxy.d.ts +0 -1
  15. package/dist/claude/proxy.js +0 -733
  16. package/dist/constants.d.ts +0 -138
  17. package/dist/constants.js +0 -216
  18. package/dist/hooks/auto-update-checker/cache.d.ts +0 -2
  19. package/dist/hooks/auto-update-checker/cache.js +0 -70
  20. package/dist/hooks/auto-update-checker/checker.d.ts +0 -15
  21. package/dist/hooks/auto-update-checker/checker.js +0 -233
  22. package/dist/hooks/auto-update-checker/constants.d.ts +0 -8
  23. package/dist/hooks/auto-update-checker/constants.js +0 -22
  24. package/dist/hooks/auto-update-checker/index.d.ts +0 -33
  25. package/dist/hooks/auto-update-checker/index.js +0 -121
  26. package/dist/hooks/auto-update-checker/logging.d.ts +0 -2
  27. package/dist/hooks/auto-update-checker/logging.js +0 -8
  28. package/dist/hooks/auto-update-checker/types.d.ts +0 -24
  29. package/dist/hooks/auto-update-checker/types.js +0 -1
  30. package/dist/index.d.ts +0 -6
  31. package/dist/opencode/hooks/auto-update-checker/cache.d.ts +0 -2
  32. package/dist/opencode/hooks/auto-update-checker/cache.js +0 -70
  33. package/dist/opencode/hooks/auto-update-checker/checker.d.ts +0 -15
  34. package/dist/opencode/hooks/auto-update-checker/checker.js +0 -233
  35. package/dist/opencode/hooks/auto-update-checker/constants.d.ts +0 -8
  36. package/dist/opencode/hooks/auto-update-checker/constants.js +0 -22
  37. package/dist/opencode/hooks/auto-update-checker/index.d.ts +0 -33
  38. package/dist/opencode/hooks/auto-update-checker/index.js +0 -121
  39. package/dist/opencode/hooks/auto-update-checker/logging.d.ts +0 -2
  40. package/dist/opencode/hooks/auto-update-checker/logging.js +0 -8
  41. package/dist/opencode/hooks/auto-update-checker/types.d.ts +0 -24
  42. package/dist/opencode/hooks/auto-update-checker/types.js +0 -1
  43. package/dist/opencode/plugin.d.ts +0 -29
  44. package/dist/opencode/plugin.js +0 -2954
  45. package/dist/plugin/accounts.d.ts +0 -173
  46. package/dist/plugin/accounts.js +0 -966
  47. package/dist/plugin/auth.d.ts +0 -20
  48. package/dist/plugin/auth.js +0 -44
  49. package/dist/plugin/cache/index.d.ts +0 -4
  50. package/dist/plugin/cache/index.js +0 -4
  51. package/dist/plugin/cache/signature-cache.d.ts +0 -110
  52. package/dist/plugin/cache/signature-cache.js +0 -347
  53. package/dist/plugin/cache.d.ts +0 -43
  54. package/dist/plugin/cache.js +0 -180
  55. package/dist/plugin/cli.d.ts +0 -26
  56. package/dist/plugin/cli.js +0 -126
  57. package/dist/plugin/config/index.d.ts +0 -15
  58. package/dist/plugin/config/index.js +0 -15
  59. package/dist/plugin/config/loader.d.ts +0 -38
  60. package/dist/plugin/config/loader.js +0 -150
  61. package/dist/plugin/config/models.d.ts +0 -26
  62. package/dist/plugin/config/models.js +0 -95
  63. package/dist/plugin/config/schema.d.ts +0 -144
  64. package/dist/plugin/config/schema.js +0 -458
  65. package/dist/plugin/config/updater.d.ts +0 -76
  66. package/dist/plugin/config/updater.js +0 -205
  67. package/dist/plugin/core/streaming/index.d.ts +0 -2
  68. package/dist/plugin/core/streaming/index.js +0 -2
  69. package/dist/plugin/core/streaming/transformer.d.ts +0 -9
  70. package/dist/plugin/core/streaming/transformer.js +0 -301
  71. package/dist/plugin/core/streaming/types.d.ts +0 -28
  72. package/dist/plugin/core/streaming/types.js +0 -1
  73. package/dist/plugin/debug.d.ts +0 -93
  74. package/dist/plugin/debug.js +0 -375
  75. package/dist/plugin/errors.d.ts +0 -27
  76. package/dist/plugin/errors.js +0 -41
  77. package/dist/plugin/fingerprint.d.ts +0 -69
  78. package/dist/plugin/fingerprint.js +0 -137
  79. package/dist/plugin/image-saver.d.ts +0 -24
  80. package/dist/plugin/image-saver.js +0 -78
  81. package/dist/plugin/logger.d.ts +0 -35
  82. package/dist/plugin/logger.js +0 -67
  83. package/dist/plugin/logging-utils.d.ts +0 -22
  84. package/dist/plugin/logging-utils.js +0 -91
  85. package/dist/plugin/project.d.ts +0 -32
  86. package/dist/plugin/project.js +0 -229
  87. package/dist/plugin/quota.d.ts +0 -34
  88. package/dist/plugin/quota.js +0 -261
  89. package/dist/plugin/recovery/constants.d.ts +0 -21
  90. package/dist/plugin/recovery/constants.js +0 -42
  91. package/dist/plugin/recovery/index.d.ts +0 -11
  92. package/dist/plugin/recovery/index.js +0 -11
  93. package/dist/plugin/recovery/storage.d.ts +0 -23
  94. package/dist/plugin/recovery/storage.js +0 -340
  95. package/dist/plugin/recovery/types.d.ts +0 -115
  96. package/dist/plugin/recovery/types.js +0 -6
  97. package/dist/plugin/recovery.d.ts +0 -60
  98. package/dist/plugin/recovery.js +0 -360
  99. package/dist/plugin/refresh-queue.d.ts +0 -99
  100. package/dist/plugin/refresh-queue.js +0 -235
  101. package/dist/plugin/request-helpers.d.ts +0 -281
  102. package/dist/plugin/request-helpers.js +0 -2200
  103. package/dist/plugin/request.d.ts +0 -110
  104. package/dist/plugin/request.js +0 -1489
  105. package/dist/plugin/rotation.d.ts +0 -182
  106. package/dist/plugin/rotation.js +0 -364
  107. package/dist/plugin/search.d.ts +0 -31
  108. package/dist/plugin/search.js +0 -185
  109. package/dist/plugin/server.d.ts +0 -22
  110. package/dist/plugin/server.js +0 -306
  111. package/dist/plugin/storage.d.ts +0 -136
  112. package/dist/plugin/storage.js +0 -599
  113. package/dist/plugin/stores/signature-store.d.ts +0 -4
  114. package/dist/plugin/stores/signature-store.js +0 -24
  115. package/dist/plugin/thinking-recovery.d.ts +0 -89
  116. package/dist/plugin/thinking-recovery.js +0 -289
  117. package/dist/plugin/token.d.ts +0 -18
  118. package/dist/plugin/token.js +0 -127
  119. package/dist/plugin/transform/claude.d.ts +0 -79
  120. package/dist/plugin/transform/claude.js +0 -256
  121. package/dist/plugin/transform/cross-model-sanitizer.d.ts +0 -34
  122. package/dist/plugin/transform/cross-model-sanitizer.js +0 -224
  123. package/dist/plugin/transform/gemini.d.ts +0 -132
  124. package/dist/plugin/transform/gemini.js +0 -659
  125. package/dist/plugin/transform/index.d.ts +0 -14
  126. package/dist/plugin/transform/index.js +0 -9
  127. package/dist/plugin/transform/model-resolver.d.ts +0 -98
  128. package/dist/plugin/transform/model-resolver.js +0 -320
  129. package/dist/plugin/transform/types.d.ts +0 -110
  130. package/dist/plugin/transform/types.js +0 -1
  131. package/dist/plugin/types.d.ts +0 -95
  132. package/dist/plugin/types.js +0 -1
  133. package/dist/plugin/ui/ansi.d.ts +0 -31
  134. package/dist/plugin/ui/ansi.js +0 -45
  135. package/dist/plugin/ui/auth-menu.d.ts +0 -47
  136. package/dist/plugin/ui/auth-menu.js +0 -199
  137. package/dist/plugin/ui/confirm.d.ts +0 -1
  138. package/dist/plugin/ui/confirm.js +0 -14
  139. package/dist/plugin/ui/select.d.ts +0 -22
  140. package/dist/plugin/ui/select.js +0 -243
  141. package/dist/plugin/version.d.ts +0 -18
  142. package/dist/plugin/version.js +0 -79
  143. package/dist/src/antigravity/oauth.d.ts +0 -30
  144. package/dist/src/antigravity/oauth.js +0 -170
  145. package/dist/src/constants.d.ts +0 -138
  146. package/dist/src/constants.js +0 -216
  147. package/dist/src/hooks/auto-update-checker/cache.d.ts +0 -2
  148. package/dist/src/hooks/auto-update-checker/cache.js +0 -70
  149. package/dist/src/hooks/auto-update-checker/checker.d.ts +0 -15
  150. package/dist/src/hooks/auto-update-checker/checker.js +0 -233
  151. package/dist/src/hooks/auto-update-checker/constants.d.ts +0 -8
  152. package/dist/src/hooks/auto-update-checker/constants.js +0 -22
  153. package/dist/src/hooks/auto-update-checker/index.d.ts +0 -33
  154. package/dist/src/hooks/auto-update-checker/index.js +0 -121
  155. package/dist/src/hooks/auto-update-checker/logging.d.ts +0 -2
  156. package/dist/src/hooks/auto-update-checker/logging.js +0 -8
  157. package/dist/src/hooks/auto-update-checker/types.d.ts +0 -24
  158. package/dist/src/hooks/auto-update-checker/types.js +0 -1
  159. package/dist/src/index.d.ts +0 -6
  160. package/dist/src/index.js +0 -5
  161. package/dist/src/plugin/accounts.d.ts +0 -173
  162. package/dist/src/plugin/accounts.js +0 -966
  163. package/dist/src/plugin/auth.d.ts +0 -20
  164. package/dist/src/plugin/auth.js +0 -44
  165. package/dist/src/plugin/cache/index.d.ts +0 -4
  166. package/dist/src/plugin/cache/index.js +0 -4
  167. package/dist/src/plugin/cache/signature-cache.d.ts +0 -110
  168. package/dist/src/plugin/cache/signature-cache.js +0 -347
  169. package/dist/src/plugin/cache.d.ts +0 -43
  170. package/dist/src/plugin/cache.js +0 -180
  171. package/dist/src/plugin/cli.d.ts +0 -26
  172. package/dist/src/plugin/cli.js +0 -126
  173. package/dist/src/plugin/config/index.d.ts +0 -15
  174. package/dist/src/plugin/config/index.js +0 -15
  175. package/dist/src/plugin/config/loader.d.ts +0 -38
  176. package/dist/src/plugin/config/loader.js +0 -150
  177. package/dist/src/plugin/config/models.d.ts +0 -26
  178. package/dist/src/plugin/config/models.js +0 -95
  179. package/dist/src/plugin/config/schema.d.ts +0 -144
  180. package/dist/src/plugin/config/schema.js +0 -458
  181. package/dist/src/plugin/config/updater.d.ts +0 -76
  182. package/dist/src/plugin/config/updater.js +0 -205
  183. package/dist/src/plugin/core/streaming/index.d.ts +0 -2
  184. package/dist/src/plugin/core/streaming/index.js +0 -2
  185. package/dist/src/plugin/core/streaming/transformer.d.ts +0 -9
  186. package/dist/src/plugin/core/streaming/transformer.js +0 -301
  187. package/dist/src/plugin/core/streaming/types.d.ts +0 -28
  188. package/dist/src/plugin/core/streaming/types.js +0 -1
  189. package/dist/src/plugin/debug.d.ts +0 -93
  190. package/dist/src/plugin/debug.js +0 -375
  191. package/dist/src/plugin/errors.d.ts +0 -27
  192. package/dist/src/plugin/errors.js +0 -41
  193. package/dist/src/plugin/fingerprint.d.ts +0 -69
  194. package/dist/src/plugin/fingerprint.js +0 -137
  195. package/dist/src/plugin/image-saver.d.ts +0 -24
  196. package/dist/src/plugin/image-saver.js +0 -78
  197. package/dist/src/plugin/logger.d.ts +0 -35
  198. package/dist/src/plugin/logger.js +0 -67
  199. package/dist/src/plugin/logging-utils.d.ts +0 -22
  200. package/dist/src/plugin/logging-utils.js +0 -91
  201. package/dist/src/plugin/project.d.ts +0 -32
  202. package/dist/src/plugin/project.js +0 -229
  203. package/dist/src/plugin/quota.d.ts +0 -34
  204. package/dist/src/plugin/quota.js +0 -261
  205. package/dist/src/plugin/recovery/constants.d.ts +0 -21
  206. package/dist/src/plugin/recovery/constants.js +0 -42
  207. package/dist/src/plugin/recovery/index.d.ts +0 -11
  208. package/dist/src/plugin/recovery/index.js +0 -11
  209. package/dist/src/plugin/recovery/storage.d.ts +0 -23
  210. package/dist/src/plugin/recovery/storage.js +0 -340
  211. package/dist/src/plugin/recovery/types.d.ts +0 -115
  212. package/dist/src/plugin/recovery/types.js +0 -6
  213. package/dist/src/plugin/recovery.d.ts +0 -60
  214. package/dist/src/plugin/recovery.js +0 -360
  215. package/dist/src/plugin/refresh-queue.d.ts +0 -99
  216. package/dist/src/plugin/refresh-queue.js +0 -235
  217. package/dist/src/plugin/request-helpers.d.ts +0 -281
  218. package/dist/src/plugin/request-helpers.js +0 -2200
  219. package/dist/src/plugin/request.d.ts +0 -110
  220. package/dist/src/plugin/request.js +0 -1489
  221. package/dist/src/plugin/rotation.d.ts +0 -182
  222. package/dist/src/plugin/rotation.js +0 -364
  223. package/dist/src/plugin/search.d.ts +0 -31
  224. package/dist/src/plugin/search.js +0 -185
  225. package/dist/src/plugin/server.d.ts +0 -22
  226. package/dist/src/plugin/server.js +0 -306
  227. package/dist/src/plugin/storage.d.ts +0 -136
  228. package/dist/src/plugin/storage.js +0 -599
  229. package/dist/src/plugin/stores/signature-store.d.ts +0 -4
  230. package/dist/src/plugin/stores/signature-store.js +0 -24
  231. package/dist/src/plugin/thinking-recovery.d.ts +0 -89
  232. package/dist/src/plugin/thinking-recovery.js +0 -289
  233. package/dist/src/plugin/token.d.ts +0 -18
  234. package/dist/src/plugin/token.js +0 -127
  235. package/dist/src/plugin/transform/claude.d.ts +0 -79
  236. package/dist/src/plugin/transform/claude.js +0 -256
  237. package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +0 -34
  238. package/dist/src/plugin/transform/cross-model-sanitizer.js +0 -224
  239. package/dist/src/plugin/transform/gemini.d.ts +0 -132
  240. package/dist/src/plugin/transform/gemini.js +0 -659
  241. package/dist/src/plugin/transform/index.d.ts +0 -14
  242. package/dist/src/plugin/transform/index.js +0 -9
  243. package/dist/src/plugin/transform/model-resolver.d.ts +0 -98
  244. package/dist/src/plugin/transform/model-resolver.js +0 -320
  245. package/dist/src/plugin/transform/types.d.ts +0 -110
  246. package/dist/src/plugin/transform/types.js +0 -1
  247. package/dist/src/plugin/types.d.ts +0 -95
  248. package/dist/src/plugin/types.js +0 -1
  249. package/dist/src/plugin/ui/ansi.d.ts +0 -31
  250. package/dist/src/plugin/ui/ansi.js +0 -45
  251. package/dist/src/plugin/ui/auth-menu.d.ts +0 -47
  252. package/dist/src/plugin/ui/auth-menu.js +0 -199
  253. package/dist/src/plugin/ui/confirm.d.ts +0 -1
  254. package/dist/src/plugin/ui/confirm.js +0 -14
  255. package/dist/src/plugin/ui/select.d.ts +0 -22
  256. package/dist/src/plugin/ui/select.js +0 -243
  257. package/dist/src/plugin/version.d.ts +0 -18
  258. package/dist/src/plugin/version.js +0 -79
@@ -1,375 +0,0 @@
1
- import { createWriteStream, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { env } from "node:process";
4
- import { homedir } from "node:os";
5
- import { deriveDebugPolicy, formatAccountContextLabel, formatAccountLabel, formatBodyPreviewForLog, formatErrorForLog, isTruthyFlag, truncateTextForLog, } from "./logging-utils";
6
- import { ensureGitignoreSync } from "./storage";
7
- const MAX_BODY_PREVIEW_CHARS = 12000;
8
- const MAX_BODY_LOG_CHARS = 50000;
9
- export const DEBUG_MESSAGE_PREFIX = "[opencode-antigravity-auth debug]";
10
- let debugState = null;
11
- /**
12
- * Get the OS-specific config directory.
13
- */
14
- function getConfigDir() {
15
- const platform = process.platform;
16
- if (platform === "win32") {
17
- return join(env.APPDATA || join(homedir(), "AppData", "Roaming"), "opencode");
18
- }
19
- const xdgConfig = env.XDG_CONFIG_HOME || join(homedir(), ".config");
20
- return join(xdgConfig, "opencode");
21
- }
22
- /**
23
- * Returns the logs directory, creating it if needed.
24
- */
25
- function getLogsDir(customLogDir) {
26
- const logsDir = customLogDir || join(getConfigDir(), "antigravity-logs");
27
- try {
28
- mkdirSync(logsDir, { recursive: true });
29
- }
30
- catch {
31
- }
32
- return logsDir;
33
- }
34
- /**
35
- * Builds a timestamped log file path.
36
- */
37
- function createLogFilePath(customLogDir) {
38
- const logsDir = getLogsDir(customLogDir);
39
- cleanupOldLogs(logsDir, 25);
40
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
41
- return join(logsDir, `antigravity-debug-${timestamp}.log`);
42
- }
43
- /**
44
- * Cleans up old log files, keeping only the most recent maxFiles.
45
- */
46
- function cleanupOldLogs(logsDir, maxFiles) {
47
- try {
48
- const files = readdirSync(logsDir)
49
- .filter((file) => file.startsWith("antigravity-debug-") && file.endsWith(".log"))
50
- .map((file) => join(logsDir, file));
51
- if (files.length <= maxFiles) {
52
- return;
53
- }
54
- const sortedFiles = files
55
- .map((file) => ({
56
- file,
57
- mtime: statSync(file).mtimeMs,
58
- }))
59
- .sort((a, b) => b.mtime - a.mtime);
60
- for (let i = maxFiles; i < sortedFiles.length; i++) {
61
- try {
62
- unlinkSync(sortedFiles[i].file);
63
- }
64
- catch {
65
- }
66
- }
67
- }
68
- catch {
69
- }
70
- }
71
- /**
72
- * Creates a log writer function that writes to a file.
73
- */
74
- function createLogWriter(filePath) {
75
- if (!filePath) {
76
- return () => { };
77
- }
78
- try {
79
- const stream = createWriteStream(filePath, { flags: "a" });
80
- stream.on("error", () => { });
81
- return (line) => {
82
- const timestamp = new Date().toISOString();
83
- const formatted = `[${timestamp}] ${line}`;
84
- stream.write(`${formatted}\n`);
85
- };
86
- }
87
- catch {
88
- return () => { };
89
- }
90
- }
91
- /**
92
- * Initialize or reinitialize debug state with the given config.
93
- * Call this once at plugin startup after loading config.
94
- */
95
- export function initializeDebug(config) {
96
- const envDebugFlag = env.OPENCODE_ANTIGRAVITY_DEBUG ?? "";
97
- const { debugEnabled } = deriveDebugPolicy({
98
- configDebug: config.debug,
99
- configDebugTui: config.debug_tui,
100
- envDebugFlag,
101
- envDebugTuiFlag: env.OPENCODE_ANTIGRAVITY_DEBUG_TUI,
102
- });
103
- const debugTuiEnabled = config.debug_tui || isTruthyFlag(env.OPENCODE_ANTIGRAVITY_DEBUG_TUI);
104
- const logFilePath = debugEnabled ? createLogFilePath(config.log_dir) : undefined;
105
- const logWriter = createLogWriter(logFilePath);
106
- if (debugEnabled) {
107
- ensureGitignoreSync(getConfigDir());
108
- }
109
- debugState = {
110
- debugEnabled,
111
- debugTuiEnabled,
112
- logFilePath,
113
- logWriter,
114
- };
115
- }
116
- /**
117
- * Get the current debug state, initializing with defaults if needed.
118
- * This allows the module to work even before initializeDebug is called.
119
- */
120
- function getDebugState() {
121
- if (!debugState) {
122
- const { debugEnabled } = deriveDebugPolicy({
123
- configDebug: false,
124
- configDebugTui: false,
125
- envDebugFlag: env.OPENCODE_ANTIGRAVITY_DEBUG,
126
- envDebugTuiFlag: env.OPENCODE_ANTIGRAVITY_DEBUG_TUI,
127
- });
128
- const debugTuiEnabled = isTruthyFlag(env.OPENCODE_ANTIGRAVITY_DEBUG_TUI);
129
- const logFilePath = debugEnabled ? createLogFilePath() : undefined;
130
- const logWriter = createLogWriter(logFilePath);
131
- debugState = {
132
- debugEnabled,
133
- debugTuiEnabled,
134
- logFilePath,
135
- logWriter,
136
- };
137
- }
138
- return debugState;
139
- }
140
- // =============================================================================
141
- // =============================================================================
142
- export function isDebugEnabled() {
143
- return getDebugState().debugEnabled;
144
- }
145
- export function isDebugTuiEnabled() {
146
- return getDebugState().debugTuiEnabled;
147
- }
148
- export function getLogFilePath() {
149
- return getDebugState().logFilePath;
150
- }
151
- let requestCounter = 0;
152
- /**
153
- * Begins a debug trace for an Antigravity request.
154
- */
155
- export function startAntigravityDebugRequest(meta) {
156
- const state = getDebugState();
157
- if (!state.debugEnabled) {
158
- return null;
159
- }
160
- const id = `ANTIGRAVITY-${++requestCounter}`;
161
- const method = meta.method ?? "GET";
162
- logDebug(`[Antigravity Debug ${id}] pid=${process.pid} ${method} ${meta.resolvedUrl}`);
163
- if (meta.originalUrl && meta.originalUrl !== meta.resolvedUrl) {
164
- logDebug(`[Antigravity Debug ${id}] Original URL: ${meta.originalUrl}`);
165
- }
166
- if (meta.projectId) {
167
- logDebug(`[Antigravity Debug ${id}] Project: ${meta.projectId}`);
168
- }
169
- logDebug(`[Antigravity Debug ${id}] Streaming: ${meta.streaming ? "yes" : "no"}`);
170
- logDebug(`[Antigravity Debug ${id}] Headers: ${JSON.stringify(maskHeaders(meta.headers))}`);
171
- const bodyPreview = formatBodyPreviewForLog(meta.body, MAX_BODY_PREVIEW_CHARS);
172
- if (bodyPreview) {
173
- logDebug(`[Antigravity Debug ${id}] Body Preview: ${bodyPreview}`);
174
- }
175
- return { id, streaming: meta.streaming, startedAt: Date.now() };
176
- }
177
- /**
178
- * Logs response details for a previously started debug trace.
179
- */
180
- export function logAntigravityDebugResponse(context, response, meta = {}) {
181
- const state = getDebugState();
182
- if (!state.debugEnabled || !context) {
183
- return;
184
- }
185
- const durationMs = Date.now() - context.startedAt;
186
- logDebug(`[Antigravity Debug ${context.id}] Response ${response.status} ${response.statusText} (${durationMs}ms)`);
187
- logDebug(`[Antigravity Debug ${context.id}] Response Headers: ${JSON.stringify(maskHeaders(meta.headersOverride ?? response.headers))}`);
188
- if (meta.note) {
189
- logDebug(`[Antigravity Debug ${context.id}] Note: ${meta.note}`);
190
- }
191
- if (meta.error) {
192
- logDebug(`[Antigravity Debug ${context.id}] Error: ${formatErrorForLog(meta.error)}`);
193
- }
194
- if (meta.body) {
195
- logDebug(`[Antigravity Debug ${context.id}] Response Body Preview: ${truncateTextForLog(meta.body, MAX_BODY_PREVIEW_CHARS)}`);
196
- }
197
- }
198
- /**
199
- * Obscures sensitive headers and returns a plain object for logging.
200
- */
201
- function maskHeaders(headers) {
202
- if (!headers) {
203
- return {};
204
- }
205
- const result = {};
206
- const parsed = headers instanceof Headers ? headers : new Headers(headers);
207
- parsed.forEach((value, key) => {
208
- if (key.toLowerCase() === "authorization") {
209
- result[key] = "[redacted]";
210
- }
211
- else {
212
- result[key] = value;
213
- }
214
- });
215
- return result;
216
- }
217
- /**
218
- * Writes a single debug line using the configured writer.
219
- */
220
- function logDebug(line) {
221
- getDebugState().logWriter(line);
222
- }
223
- function runWithDebugEnabled(action) {
224
- if (!getDebugState().debugEnabled)
225
- return;
226
- action();
227
- }
228
- export function logAccountContext(label, info) {
229
- runWithDebugEnabled(() => {
230
- const accountLabel = formatAccountContextLabel(info.email, info.index);
231
- const indexLabel = info.index >= 0 ? `${info.index + 1}/${info.totalAccounts}` : `-/${info.totalAccounts}`;
232
- let rateLimitInfo = "";
233
- if (info.rateLimitState && Object.keys(info.rateLimitState).length > 0) {
234
- const now = Date.now();
235
- const activeRateLimits = {};
236
- for (const [key, resetTime] of Object.entries(info.rateLimitState)) {
237
- if (typeof resetTime === "number" && resetTime > now) {
238
- const remainingSec = Math.ceil((resetTime - now) / 1000);
239
- activeRateLimits[key] = `${remainingSec}s`;
240
- }
241
- }
242
- if (Object.keys(activeRateLimits).length > 0) {
243
- rateLimitInfo = ` rateLimits=${JSON.stringify(activeRateLimits)}`;
244
- }
245
- }
246
- logDebug(`[Account] ${label}: ${accountLabel} (${indexLabel}) family=${info.family}${rateLimitInfo}`);
247
- });
248
- }
249
- export function logRateLimitEvent(accountIndex, email, family, status, retryAfterMs, bodyInfo) {
250
- runWithDebugEnabled(() => {
251
- const accountLabel = formatAccountLabel(email, accountIndex);
252
- logDebug(`[RateLimit] ${status} on ${accountLabel} family=${family} retryAfterMs=${retryAfterMs}`);
253
- if (bodyInfo.message) {
254
- logDebug(`[RateLimit] message: ${bodyInfo.message}`);
255
- }
256
- if (bodyInfo.quotaResetTime) {
257
- logDebug(`[RateLimit] quotaResetTime: ${bodyInfo.quotaResetTime}`);
258
- }
259
- if (bodyInfo.retryDelayMs !== undefined && bodyInfo.retryDelayMs !== null) {
260
- logDebug(`[RateLimit] body retryDelayMs: ${bodyInfo.retryDelayMs}`);
261
- }
262
- if (bodyInfo.reason) {
263
- logDebug(`[RateLimit] reason: ${bodyInfo.reason}`);
264
- }
265
- });
266
- }
267
- export function logRateLimitSnapshot(family, accounts) {
268
- runWithDebugEnabled(() => {
269
- const now = Date.now();
270
- const entries = accounts.map((account) => {
271
- const label = formatAccountLabel(account.email, account.index);
272
- const reset = account.rateLimitResetTimes?.[family];
273
- if (typeof reset !== "number") {
274
- return `${label}=ready`;
275
- }
276
- const remaining = Math.max(0, reset - now);
277
- const seconds = Math.ceil(remaining / 1000);
278
- return `${label}=wait ${seconds}s`;
279
- });
280
- logDebug(`[RateLimit] snapshot family=${family} ${entries.join(" | ")}`);
281
- });
282
- }
283
- export async function logResponseBody(context, response, status) {
284
- const state = getDebugState();
285
- if (!state.debugEnabled || !context)
286
- return undefined;
287
- try {
288
- const text = await response.clone().text();
289
- const preview = truncateTextForLog(text, MAX_BODY_LOG_CHARS);
290
- logDebug(`[Antigravity Debug ${context.id}] Response Body (${status}): ${preview}`);
291
- return text;
292
- }
293
- catch (e) {
294
- logDebug(`[Antigravity Debug ${context.id}] Failed to read response body: ${formatErrorForLog(e)}`);
295
- return undefined;
296
- }
297
- }
298
- export function logModelFamily(url, extractedModel, family) {
299
- runWithDebugEnabled(() => {
300
- logDebug(`[ModelFamily] url=${url} model=${extractedModel ?? "unknown"} family=${family}`);
301
- });
302
- }
303
- export function debugLogToFile(message) {
304
- runWithDebugEnabled(() => {
305
- logDebug(message);
306
- });
307
- }
308
- /**
309
- * Logs a toast message to the debug file.
310
- * This helps correlate what the user saw with debug events.
311
- */
312
- export function logToast(message, variant) {
313
- runWithDebugEnabled(() => {
314
- const variantLabel = variant.toUpperCase();
315
- logDebug(`[Toast/${variantLabel}] ${message}`);
316
- });
317
- }
318
- /**
319
- * Logs retry attempt information.
320
- * @param maxAttempts - Use -1 for unlimited retries
321
- */
322
- export function logRetryAttempt(attempt, maxAttempts, reason, delayMs) {
323
- runWithDebugEnabled(() => {
324
- const delayInfo = delayMs !== undefined ? ` delay=${delayMs}ms` : "";
325
- const maxInfo = maxAttempts < 0 ? "∞" : maxAttempts.toString();
326
- logDebug(`[Retry] Attempt ${attempt}/${maxInfo} reason=${reason}${delayInfo}`);
327
- });
328
- }
329
- /**
330
- * Logs cache hit/miss information from response usage metadata.
331
- */
332
- export function logCacheStats(model, cacheReadTokens, cacheWriteTokens, totalInputTokens) {
333
- runWithDebugEnabled(() => {
334
- const cacheHitRate = totalInputTokens > 0
335
- ? Math.round((cacheReadTokens / totalInputTokens) * 100)
336
- : 0;
337
- const status = cacheReadTokens > 0 ? "HIT" : (cacheWriteTokens > 0 ? "WRITE" : "MISS");
338
- logDebug(`[Cache] ${status} model=${model} read=${cacheReadTokens} write=${cacheWriteTokens} total=${totalInputTokens} hitRate=${cacheHitRate}%`);
339
- });
340
- }
341
- /**
342
- * Logs quota status for an account.
343
- */
344
- export function logQuotaStatus(accountEmail, accountIndex, quotaPercent, family) {
345
- runWithDebugEnabled(() => {
346
- const accountLabel = formatAccountLabel(accountEmail, accountIndex);
347
- const familyInfo = family ? ` family=${family}` : "";
348
- const status = quotaPercent <= 0 ? "EXHAUSTED" : quotaPercent < 20 ? "LOW" : "OK";
349
- logDebug(`[Quota] ${accountLabel} remaining=${quotaPercent.toFixed(1)}% status=${status}${familyInfo}`);
350
- });
351
- }
352
- /**
353
- * Logs background quota fetch events.
354
- */
355
- export function logQuotaFetch(event, accountCount, details) {
356
- runWithDebugEnabled(() => {
357
- const countInfo = accountCount !== undefined ? ` accounts=${accountCount}` : "";
358
- const detailsInfo = details ? ` ${details}` : "";
359
- logDebug(`[QuotaFetch] ${event.toUpperCase()}${countInfo}${detailsInfo}`);
360
- });
361
- }
362
- /**
363
- * Logs which model is being used for a request.
364
- */
365
- export function logModelUsed(requestedModel, actualModel, accountEmail) {
366
- runWithDebugEnabled(() => {
367
- const accountInfo = accountEmail ? ` account=${accountEmail}` : "";
368
- if (requestedModel !== actualModel) {
369
- logDebug(`[Model] requested=${requestedModel} actual=${actualModel}${accountInfo}`);
370
- }
371
- else {
372
- logDebug(`[Model] ${actualModel}${accountInfo}`);
373
- }
374
- });
375
- }
@@ -1,27 +0,0 @@
1
- /**
2
- * Custom error types for opencode-antigravity-auth plugin.
3
- *
4
- * Ported from LLM-API-Key-Proxy for robust error handling.
5
- */
6
- /**
7
- * Error thrown when Antigravity returns an empty response after retry attempts.
8
- *
9
- * Empty responses can occur when:
10
- * - The model has no candidates/choices
11
- * - The response body is empty or malformed
12
- * - A temporary service issue prevents generation
13
- */
14
- export declare class EmptyResponseError extends Error {
15
- readonly provider: string;
16
- readonly model: string;
17
- readonly attempts: number;
18
- constructor(provider: string, model: string, attempts: number, message?: string);
19
- }
20
- /**
21
- * Error thrown when tool ID matching fails and cannot be recovered.
22
- */
23
- export declare class ToolIdMismatchError extends Error {
24
- readonly expectedIds: string[];
25
- readonly foundIds: string[];
26
- constructor(expectedIds: string[], foundIds: string[], message?: string);
27
- }
@@ -1,41 +0,0 @@
1
- /**
2
- * Custom error types for opencode-antigravity-auth plugin.
3
- *
4
- * Ported from LLM-API-Key-Proxy for robust error handling.
5
- */
6
- /**
7
- * Error thrown when Antigravity returns an empty response after retry attempts.
8
- *
9
- * Empty responses can occur when:
10
- * - The model has no candidates/choices
11
- * - The response body is empty or malformed
12
- * - A temporary service issue prevents generation
13
- */
14
- export class EmptyResponseError extends Error {
15
- provider;
16
- model;
17
- attempts;
18
- constructor(provider, model, attempts, message) {
19
- super(message ??
20
- `The model returned an empty response after ${attempts} attempts. ` +
21
- `This may indicate a temporary service issue. Please try again.`);
22
- this.name = "EmptyResponseError";
23
- this.provider = provider;
24
- this.model = model;
25
- this.attempts = attempts;
26
- }
27
- }
28
- /**
29
- * Error thrown when tool ID matching fails and cannot be recovered.
30
- */
31
- export class ToolIdMismatchError extends Error {
32
- expectedIds;
33
- foundIds;
34
- constructor(expectedIds, foundIds, message) {
35
- super(message ??
36
- `Tool ID mismatch: expected [${expectedIds.join(", ")}] but found [${foundIds.join(", ")}]`);
37
- this.name = "ToolIdMismatchError";
38
- this.expectedIds = expectedIds;
39
- this.foundIds = foundIds;
40
- }
41
- }
@@ -1,69 +0,0 @@
1
- /**
2
- * Device Fingerprint Generator for Rate Limit Mitigation
3
- *
4
- * Ported from antigravity-claude-proxy PR #170
5
- * https://github.com/badrisnarayanan/antigravity-claude-proxy/pull/170
6
- *
7
- * Generates randomized device fingerprints to help distribute API usage
8
- * across different apparent device identities.
9
- */
10
- export interface ClientMetadata {
11
- ideType: string;
12
- platform: string;
13
- pluginType: string;
14
- }
15
- export interface Fingerprint {
16
- deviceId: string;
17
- sessionToken: string;
18
- userAgent: string;
19
- apiClient: string;
20
- clientMetadata: ClientMetadata;
21
- createdAt: number;
22
- /** @deprecated Kept for backward compat with stored fingerprints */
23
- quotaUser?: string;
24
- }
25
- /**
26
- * Fingerprint version for history tracking.
27
- * Stores a snapshot of a fingerprint with metadata about when/why it was saved.
28
- */
29
- export interface FingerprintVersion {
30
- fingerprint: Fingerprint;
31
- timestamp: number;
32
- reason: 'initial' | 'regenerated' | 'restored';
33
- }
34
- /** Maximum number of fingerprint versions to keep per account */
35
- export declare const MAX_FINGERPRINT_HISTORY = 5;
36
- export interface FingerprintHeaders {
37
- "User-Agent": string;
38
- }
39
- /**
40
- * Generate a randomized device fingerprint.
41
- * Each fingerprint represents a unique "device" identity.
42
- */
43
- export declare function generateFingerprint(): Fingerprint;
44
- /**
45
- * Collect fingerprint based on actual current system.
46
- * Uses real OS info instead of randomized values.
47
- */
48
- export declare function collectCurrentFingerprint(): Fingerprint;
49
- /**
50
- * Update the version in a fingerprint's userAgent to match the current runtime version.
51
- * Called after version fetcher resolves so saved fingerprints always carry the latest version.
52
- * Returns true if the userAgent was changed.
53
- */
54
- export declare function updateFingerprintVersion(fingerprint: Fingerprint): boolean;
55
- /**
56
- * Build HTTP headers from a fingerprint object.
57
- * These headers are used to identify the "device" making API requests.
58
- */
59
- export declare function buildFingerprintHeaders(fingerprint: Fingerprint | null): Partial<FingerprintHeaders>;
60
- /**
61
- * Get or create the session fingerprint.
62
- * Returns the same fingerprint for all calls within a session.
63
- */
64
- export declare function getSessionFingerprint(): Fingerprint;
65
- /**
66
- * Regenerate the session fingerprint.
67
- * Call this to get a fresh identity (e.g., after rate limiting).
68
- */
69
- export declare function regenerateSessionFingerprint(): Fingerprint;
@@ -1,137 +0,0 @@
1
- /**
2
- * Device Fingerprint Generator for Rate Limit Mitigation
3
- *
4
- * Ported from antigravity-claude-proxy PR #170
5
- * https://github.com/badrisnarayanan/antigravity-claude-proxy/pull/170
6
- *
7
- * Generates randomized device fingerprints to help distribute API usage
8
- * across different apparent device identities.
9
- */
10
- import * as crypto from "node:crypto";
11
- import * as os from "node:os";
12
- import { getAntigravityVersion } from "../constants";
13
- const OS_VERSIONS = {
14
- darwin: ["10.15.7", "11.6.8", "12.6.3", "13.5.2", "14.2.1", "14.5"],
15
- win32: ["10.0.19041", "10.0.19042", "10.0.19043", "10.0.22000", "10.0.22621", "10.0.22631"],
16
- linux: ["5.15.0", "5.19.0", "6.1.0", "6.2.0", "6.5.0", "6.6.0"],
17
- };
18
- const ARCHITECTURES = ["x64", "arm64"];
19
- const IDE_TYPES = [
20
- "ANTIGRAVITY",
21
- ];
22
- const PLATFORMS = [
23
- "WINDOWS",
24
- "MACOS",
25
- ];
26
- const SDK_CLIENTS = [
27
- "google-cloud-sdk vscode_cloudshelleditor/0.1",
28
- "google-cloud-sdk vscode/1.86.0",
29
- "google-cloud-sdk vscode/1.87.0",
30
- "google-cloud-sdk vscode/1.96.0",
31
- ];
32
- /** Maximum number of fingerprint versions to keep per account */
33
- export const MAX_FINGERPRINT_HISTORY = 5;
34
- const PLATFORM_CHOICES = ["darwin", "win32"];
35
- function randomFrom(arr) {
36
- return arr[Math.floor(Math.random() * arr.length)];
37
- }
38
- function platformToDisplayName(platform) {
39
- return platform === "win32" ? "WINDOWS" : "MACOS";
40
- }
41
- function generateDeviceId() {
42
- return crypto.randomUUID();
43
- }
44
- function generateSessionToken() {
45
- return crypto.randomBytes(16).toString("hex");
46
- }
47
- /**
48
- * Generate a randomized device fingerprint.
49
- * Each fingerprint represents a unique "device" identity.
50
- */
51
- export function generateFingerprint() {
52
- const platform = randomFrom(PLATFORM_CHOICES);
53
- const arch = randomFrom(ARCHITECTURES);
54
- const osVersion = randomFrom(OS_VERSIONS[platform] ?? OS_VERSIONS.darwin);
55
- return {
56
- deviceId: generateDeviceId(),
57
- sessionToken: generateSessionToken(),
58
- userAgent: `antigravity/${getAntigravityVersion()} ${platform}/${arch}`,
59
- apiClient: randomFrom(SDK_CLIENTS),
60
- clientMetadata: {
61
- ideType: randomFrom(IDE_TYPES),
62
- platform: platformToDisplayName(platform),
63
- pluginType: "GEMINI",
64
- },
65
- createdAt: Date.now(),
66
- };
67
- }
68
- /**
69
- * Collect fingerprint based on actual current system.
70
- * Uses real OS info instead of randomized values.
71
- */
72
- export function collectCurrentFingerprint() {
73
- const platform = os.platform();
74
- const arch = os.arch();
75
- return {
76
- deviceId: generateDeviceId(),
77
- sessionToken: generateSessionToken(),
78
- userAgent: `antigravity/${getAntigravityVersion()} ${platform}/${arch}`,
79
- apiClient: "google-cloud-sdk vscode_cloudshelleditor/0.1",
80
- clientMetadata: {
81
- ideType: "ANTIGRAVITY",
82
- platform: platformToDisplayName(platform),
83
- pluginType: "GEMINI",
84
- },
85
- createdAt: Date.now(),
86
- };
87
- }
88
- /**
89
- * Update the version in a fingerprint's userAgent to match the current runtime version.
90
- * Called after version fetcher resolves so saved fingerprints always carry the latest version.
91
- * Returns true if the userAgent was changed.
92
- */
93
- export function updateFingerprintVersion(fingerprint) {
94
- const currentVersion = getAntigravityVersion();
95
- const versionPattern = /^(antigravity\/)([\d.]+)/;
96
- const match = fingerprint.userAgent.match(versionPattern);
97
- if (!match || match[2] === currentVersion) {
98
- return false;
99
- }
100
- fingerprint.userAgent = fingerprint.userAgent.replace(versionPattern, `$1${currentVersion}`);
101
- return true;
102
- }
103
- /**
104
- * Build HTTP headers from a fingerprint object.
105
- * These headers are used to identify the "device" making API requests.
106
- */
107
- export function buildFingerprintHeaders(fingerprint) {
108
- if (!fingerprint) {
109
- return {};
110
- }
111
- return {
112
- "User-Agent": fingerprint.userAgent,
113
- };
114
- }
115
- /**
116
- * Session-level fingerprint instance.
117
- * Generated once at module load, persists for the lifetime of the process.
118
- */
119
- let sessionFingerprint = null;
120
- /**
121
- * Get or create the session fingerprint.
122
- * Returns the same fingerprint for all calls within a session.
123
- */
124
- export function getSessionFingerprint() {
125
- if (!sessionFingerprint) {
126
- sessionFingerprint = generateFingerprint();
127
- }
128
- return sessionFingerprint;
129
- }
130
- /**
131
- * Regenerate the session fingerprint.
132
- * Call this to get a fresh identity (e.g., after rate limiting).
133
- */
134
- export function regenerateSessionFingerprint() {
135
- sessionFingerprint = generateFingerprint();
136
- return sessionFingerprint;
137
- }
@@ -1,24 +0,0 @@
1
- /**
2
- * Image Saving Utility
3
- *
4
- * Handles saving generated images to disk and returning file paths.
5
- */
6
- /**
7
- * Save base64 image data to disk and return the file path.
8
- *
9
- * @param base64Data - The base64-encoded image data
10
- * @param mimeType - The MIME type of the image (e.g., "image/jpeg")
11
- * @returns The absolute path to the saved image file
12
- */
13
- export declare function saveImageToDisk(base64Data: string, mimeType: string): string;
14
- /**
15
- * Process inlineData and return either a file path or base64 data URL.
16
- * Attempts to save to disk first, falls back to base64 if saving fails.
17
- *
18
- * @param inlineData - Object containing mimeType and base64 data
19
- * @returns Markdown image string with either file path or data URL
20
- */
21
- export declare function processImageData(inlineData: {
22
- mimeType?: string;
23
- data?: string;
24
- }): string | null;