@cortexkit/opencode-antigravity-auth 1.1.0 → 2.0.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 +225 -569
- package/dist/cli.js +3790 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +18767 -13829
- package/dist/index.js.map +4 -4
- package/dist/src/antigravity/oauth.d.ts +1 -1
- package/dist/src/antigravity/oauth.js +1 -1
- package/dist/src/cli.d.ts +21 -0
- package/dist/src/cli.d.ts.map +1 -0
- package/dist/src/cli.js +237 -0
- package/dist/src/cli.js.map +1 -0
- package/dist/src/constants.d.ts +1 -1
- package/dist/src/constants.js +1 -1
- package/dist/src/hooks/auto-update-checker/cache.d.ts.map +1 -1
- package/dist/src/hooks/auto-update-checker/cache.js +13 -13
- package/dist/src/hooks/auto-update-checker/cache.js.map +1 -1
- package/dist/src/hooks/auto-update-checker/checker.d.ts +1 -1
- package/dist/src/hooks/auto-update-checker/checker.d.ts.map +1 -1
- package/dist/src/hooks/auto-update-checker/checker.js +75 -51
- package/dist/src/hooks/auto-update-checker/checker.js.map +1 -1
- package/dist/src/hooks/auto-update-checker/constants.d.ts.map +1 -1
- package/dist/src/hooks/auto-update-checker/constants.js +12 -12
- package/dist/src/hooks/auto-update-checker/constants.js.map +1 -1
- package/dist/src/hooks/auto-update-checker/index.d.ts +6 -6
- package/dist/src/hooks/auto-update-checker/index.d.ts.map +1 -1
- package/dist/src/hooks/auto-update-checker/index.js +17 -17
- package/dist/src/hooks/auto-update-checker/index.js.map +1 -1
- package/dist/src/hooks/auto-update-checker/logging.js +2 -2
- package/dist/src/hooks/auto-update-checker/logging.js.map +1 -1
- package/dist/src/hooks/auto-update-checker/types.d.ts.map +1 -1
- package/dist/src/plugin/account-access.d.ts +99 -0
- package/dist/src/plugin/account-access.d.ts.map +1 -0
- package/dist/src/plugin/account-access.js +480 -0
- package/dist/src/plugin/account-access.js.map +1 -0
- package/dist/src/plugin/accounts.d.ts +7 -256
- package/dist/src/plugin/accounts.d.ts.map +1 -1
- package/dist/src/plugin/accounts.js +31 -1367
- package/dist/src/plugin/accounts.js.map +1 -1
- package/dist/src/plugin/agy-request-metadata.d.ts +1 -1
- package/dist/src/plugin/agy-request-metadata.js +1 -1
- package/dist/src/plugin/agy-transport.d.ts +1 -1
- package/dist/src/plugin/agy-transport.js +1 -1
- package/dist/src/plugin/auth-doctor.d.ts +6 -6
- package/dist/src/plugin/auth-doctor.d.ts.map +1 -1
- package/dist/src/plugin/auth-doctor.js +74 -66
- package/dist/src/plugin/auth-doctor.js.map +1 -1
- package/dist/src/plugin/auth-drift.d.ts +4 -4
- package/dist/src/plugin/auth-drift.d.ts.map +1 -1
- package/dist/src/plugin/auth-drift.js +15 -15
- package/dist/src/plugin/auth-drift.js.map +1 -1
- package/dist/src/plugin/auth-loader.d.ts +35 -0
- package/dist/src/plugin/auth-loader.d.ts.map +1 -0
- package/dist/src/plugin/auth-loader.js +144 -0
- package/dist/src/plugin/auth-loader.js.map +1 -0
- package/dist/src/plugin/auth.d.ts +1 -1
- package/dist/src/plugin/auth.js +1 -1
- package/dist/src/plugin/cache/index.d.ts +1 -1
- package/dist/src/plugin/cache/index.d.ts.map +1 -1
- package/dist/src/plugin/cache/index.js +1 -1
- package/dist/src/plugin/cache/index.js.map +1 -1
- package/dist/src/plugin/cache/signature-cache.d.ts +1 -1
- package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -1
- package/dist/src/plugin/cache/signature-cache.js +23 -24
- package/dist/src/plugin/cache/signature-cache.js.map +1 -1
- package/dist/src/plugin/cache.d.ts +6 -5
- package/dist/src/plugin/cache.d.ts.map +1 -1
- package/dist/src/plugin/cache.js +21 -7
- package/dist/src/plugin/cache.js.map +1 -1
- package/dist/src/plugin/catalog.d.ts +23 -0
- package/dist/src/plugin/catalog.d.ts.map +1 -0
- package/dist/src/plugin/catalog.js +60 -0
- package/dist/src/plugin/catalog.js.map +1 -0
- package/dist/src/plugin/cli.d.ts +7 -7
- package/dist/src/plugin/cli.d.ts.map +1 -1
- package/dist/src/plugin/cli.js +62 -55
- package/dist/src/plugin/cli.js.map +1 -1
- package/dist/src/plugin/command-data.d.ts +276 -0
- package/dist/src/plugin/command-data.d.ts.map +1 -0
- package/dist/src/plugin/command-data.js +325 -0
- package/dist/src/plugin/command-data.js.map +1 -0
- package/dist/src/plugin/commands.d.ts +151 -0
- package/dist/src/plugin/commands.d.ts.map +1 -0
- package/dist/src/plugin/commands.js +639 -0
- package/dist/src/plugin/commands.js.map +1 -0
- package/dist/src/plugin/config/index.d.ts +2 -2
- package/dist/src/plugin/config/index.d.ts.map +1 -1
- package/dist/src/plugin/config/index.js +2 -2
- package/dist/src/plugin/config/index.js.map +1 -1
- package/dist/src/plugin/config/loader.d.ts +1 -1
- package/dist/src/plugin/config/loader.d.ts.map +1 -1
- package/dist/src/plugin/config/loader.js +18 -16
- package/dist/src/plugin/config/loader.js.map +1 -1
- package/dist/src/plugin/config/models.d.ts +2 -2
- package/dist/src/plugin/config/models.d.ts.map +1 -1
- package/dist/src/plugin/config/models.js +1 -1
- package/dist/src/plugin/config/models.js.map +1 -1
- package/dist/src/plugin/config/operator-settings-schema.d.ts +29 -0
- package/dist/src/plugin/config/operator-settings-schema.d.ts.map +1 -0
- package/dist/src/plugin/config/operator-settings-schema.js +28 -0
- package/dist/src/plugin/config/operator-settings-schema.js.map +1 -0
- package/dist/src/plugin/config/schema.d.ts +21 -2
- package/dist/src/plugin/config/schema.d.ts.map +1 -1
- package/dist/src/plugin/config/schema.js +85 -25
- package/dist/src/plugin/config/schema.js.map +1 -1
- package/dist/src/plugin/config/updater.d.ts.map +1 -1
- package/dist/src/plugin/config/updater.js +15 -15
- package/dist/src/plugin/config/updater.js.map +1 -1
- package/dist/src/plugin/config/writer.d.ts +34 -0
- package/dist/src/plugin/config/writer.d.ts.map +1 -0
- package/dist/src/plugin/config/writer.js +81 -0
- package/dist/src/plugin/config/writer.js.map +1 -0
- package/dist/src/plugin/core/streaming/index.d.ts +1 -1
- package/dist/src/plugin/core/streaming/index.d.ts.map +1 -1
- package/dist/src/plugin/core/streaming/index.js +1 -1
- package/dist/src/plugin/core/streaming/index.js.map +1 -1
- package/dist/src/plugin/core/streaming/transformer.d.ts.map +1 -1
- package/dist/src/plugin/core/streaming/transformer.js +85 -44
- package/dist/src/plugin/core/streaming/transformer.js.map +1 -1
- package/dist/src/plugin/core/streaming/types.d.ts.map +1 -1
- package/dist/src/plugin/debug.d.ts +3 -3
- package/dist/src/plugin/debug.d.ts.map +1 -1
- package/dist/src/plugin/debug.js +85 -47
- package/dist/src/plugin/debug.js.map +1 -1
- package/dist/src/plugin/dependencies.d.ts +129 -0
- package/dist/src/plugin/dependencies.d.ts.map +1 -0
- package/dist/src/plugin/dependencies.js +107 -0
- package/dist/src/plugin/dependencies.js.map +1 -0
- package/dist/src/plugin/errors.d.ts +27 -0
- package/dist/src/plugin/errors.d.ts.map +1 -1
- package/dist/src/plugin/errors.js +29 -3
- package/dist/src/plugin/errors.js.map +1 -1
- package/dist/src/plugin/event-handler.d.ts +53 -0
- package/dist/src/plugin/event-handler.d.ts.map +1 -0
- package/dist/src/plugin/event-handler.js +101 -0
- package/dist/src/plugin/event-handler.js.map +1 -0
- package/dist/src/plugin/fetch/retry-state.d.ts +61 -0
- package/dist/src/plugin/fetch/retry-state.d.ts.map +1 -0
- package/dist/src/plugin/fetch/retry-state.js +248 -0
- package/dist/src/plugin/fetch/retry-state.js.map +1 -0
- package/dist/src/plugin/fetch/warmup.d.ts +30 -0
- package/dist/src/plugin/fetch/warmup.d.ts.map +1 -0
- package/dist/src/plugin/fetch/warmup.js +76 -0
- package/dist/src/plugin/fetch/warmup.js.map +1 -0
- package/dist/src/plugin/fetch-interceptor.d.ts +59 -0
- package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -0
- package/dist/src/plugin/fetch-interceptor.js +1387 -0
- package/dist/src/plugin/fetch-interceptor.js.map +1 -0
- package/dist/src/plugin/fetch-routing.d.ts +26 -0
- package/dist/src/plugin/fetch-routing.d.ts.map +1 -0
- package/dist/src/plugin/fetch-routing.js +99 -0
- package/dist/src/plugin/fetch-routing.js.map +1 -0
- package/dist/src/plugin/fingerprint.d.ts +1 -1
- package/dist/src/plugin/fingerprint.js +1 -1
- package/dist/src/plugin/gemini-dump.d.ts +5 -5
- package/dist/src/plugin/gemini-dump.d.ts.map +1 -1
- package/dist/src/plugin/gemini-dump.js +109 -55
- package/dist/src/plugin/gemini-dump.js.map +1 -1
- package/dist/src/plugin/google-search-tool.d.ts +9 -0
- package/dist/src/plugin/google-search-tool.d.ts.map +1 -0
- package/dist/src/plugin/google-search-tool.js +56 -0
- package/dist/src/plugin/google-search-tool.js.map +1 -0
- package/dist/src/plugin/image-saver.d.ts.map +1 -1
- package/dist/src/plugin/image-saver.js +16 -16
- package/dist/src/plugin/image-saver.js.map +1 -1
- package/dist/src/plugin/index.d.ts +23 -0
- package/dist/src/plugin/index.d.ts.map +1 -0
- package/dist/src/plugin/index.js +308 -0
- package/dist/src/plugin/index.js.map +1 -0
- package/dist/src/plugin/killswitch.d.ts +94 -0
- package/dist/src/plugin/killswitch.d.ts.map +1 -0
- package/dist/src/plugin/killswitch.js +194 -0
- package/dist/src/plugin/killswitch.js.map +1 -0
- package/dist/src/plugin/lifecycle.d.ts +40 -0
- package/dist/src/plugin/lifecycle.d.ts.map +1 -0
- package/dist/src/plugin/lifecycle.js +73 -0
- package/dist/src/plugin/lifecycle.js.map +1 -0
- package/dist/src/plugin/logger.d.ts +10 -1
- package/dist/src/plugin/logger.d.ts.map +1 -1
- package/dist/src/plugin/logger.js +38 -12
- package/dist/src/plugin/logger.js.map +1 -1
- package/dist/src/plugin/logging-utils.d.ts +35 -1
- package/dist/src/plugin/logging-utils.d.ts.map +1 -1
- package/dist/src/plugin/logging-utils.js +98 -15
- package/dist/src/plugin/logging-utils.js.map +1 -1
- package/dist/src/plugin/model-registry.d.ts +1 -1
- package/dist/src/plugin/model-registry.js +1 -1
- package/dist/src/plugin/oauth-login.d.ts +22 -0
- package/dist/src/plugin/oauth-login.d.ts.map +1 -0
- package/dist/src/plugin/oauth-login.js +37 -0
- package/dist/src/plugin/oauth-login.js.map +1 -0
- package/dist/src/plugin/oauth-methods.d.ts +42 -0
- package/dist/src/plugin/oauth-methods.d.ts.map +1 -0
- package/dist/src/plugin/oauth-methods.js +1284 -0
- package/dist/src/plugin/oauth-methods.js.map +1 -0
- package/dist/src/plugin/operator-settings.d.ts +40 -0
- package/dist/src/plugin/operator-settings.d.ts.map +1 -0
- package/dist/src/plugin/operator-settings.js +148 -0
- package/dist/src/plugin/operator-settings.js.map +1 -0
- package/dist/src/plugin/persist-account-pool.d.ts +37 -0
- package/dist/src/plugin/persist-account-pool.d.ts.map +1 -0
- package/dist/src/plugin/persist-account-pool.js +142 -0
- package/dist/src/plugin/persist-account-pool.js.map +1 -0
- package/dist/src/plugin/project.d.ts +1 -1
- package/dist/src/plugin/project.js +1 -1
- package/dist/src/plugin/prompt-context.d.ts.map +1 -1
- package/dist/src/plugin/prompt-context.js +11 -11
- package/dist/src/plugin/prompt-context.js.map +1 -1
- package/dist/src/plugin/quota.d.ts +97 -41
- package/dist/src/plugin/quota.d.ts.map +1 -1
- package/dist/src/plugin/quota.js +273 -285
- package/dist/src/plugin/quota.js.map +1 -1
- package/dist/src/plugin/recovery/constants.d.ts.map +1 -1
- package/dist/src/plugin/recovery/constants.js +24 -15
- package/dist/src/plugin/recovery/constants.js.map +1 -1
- package/dist/src/plugin/recovery/index.d.ts +3 -3
- package/dist/src/plugin/recovery/index.d.ts.map +1 -1
- package/dist/src/plugin/recovery/index.js +3 -3
- package/dist/src/plugin/recovery/index.js.map +1 -1
- package/dist/src/plugin/recovery/storage.d.ts +1 -1
- package/dist/src/plugin/recovery/storage.d.ts.map +1 -1
- package/dist/src/plugin/recovery/storage.js +31 -39
- package/dist/src/plugin/recovery/storage.js.map +1 -1
- package/dist/src/plugin/recovery/types.d.ts +12 -12
- package/dist/src/plugin/recovery/types.d.ts.map +1 -1
- package/dist/src/plugin/recovery.d.ts +3 -3
- package/dist/src/plugin/recovery.d.ts.map +1 -1
- package/dist/src/plugin/recovery.js +62 -58
- package/dist/src/plugin/recovery.js.map +1 -1
- package/dist/src/plugin/refresh-queue.d.ts +5 -2
- package/dist/src/plugin/refresh-queue.d.ts.map +1 -1
- package/dist/src/plugin/refresh-queue.js +37 -15
- package/dist/src/plugin/refresh-queue.js.map +1 -1
- package/dist/src/plugin/request-helpers.d.ts +1 -1
- package/dist/src/plugin/request-helpers.d.ts.map +1 -1
- package/dist/src/plugin/request-helpers.js +451 -352
- package/dist/src/plugin/request-helpers.js.map +1 -1
- package/dist/src/plugin/request.d.ts +7 -7
- package/dist/src/plugin/request.d.ts.map +1 -1
- package/dist/src/plugin/request.js +622 -384
- package/dist/src/plugin/request.js.map +1 -1
- package/dist/src/plugin/rotation.d.ts +1 -168
- package/dist/src/plugin/rotation.d.ts.map +1 -1
- package/dist/src/plugin/rotation.js +1 -327
- package/dist/src/plugin/rotation.js.map +1 -1
- package/dist/src/plugin/search.d.ts.map +1 -1
- package/dist/src/plugin/search.js +39 -35
- package/dist/src/plugin/search.js.map +1 -1
- package/dist/src/plugin/server.d.ts +1 -1
- package/dist/src/plugin/server.d.ts.map +1 -1
- package/dist/src/plugin/server.js +42 -37
- package/dist/src/plugin/server.js.map +1 -1
- package/dist/src/plugin/session-context.d.ts +2 -1
- package/dist/src/plugin/session-context.d.ts.map +1 -1
- package/dist/src/plugin/session-context.js +11 -7
- package/dist/src/plugin/session-context.js.map +1 -1
- package/dist/src/plugin/storage.d.ts +59 -120
- package/dist/src/plugin/storage.d.ts.map +1 -1
- package/dist/src/plugin/storage.js +140 -485
- package/dist/src/plugin/storage.js.map +1 -1
- package/dist/src/plugin/stores/signature-store.d.ts.map +1 -1
- package/dist/src/plugin/stores/signature-store.js.map +1 -1
- package/dist/src/plugin/thinking-recovery.d.ts.map +1 -1
- package/dist/src/plugin/thinking-recovery.js +35 -33
- package/dist/src/plugin/thinking-recovery.js.map +1 -1
- package/dist/src/plugin/token.d.ts +2 -2
- package/dist/src/plugin/token.d.ts.map +1 -1
- package/dist/src/plugin/token.js +30 -21
- package/dist/src/plugin/token.js.map +1 -1
- package/dist/src/plugin/transform/cross-model-sanitizer.d.ts +1 -1
- package/dist/src/plugin/transform/cross-model-sanitizer.js +1 -1
- package/dist/src/plugin/transform/index.d.ts +1 -1
- package/dist/src/plugin/transform/index.js +1 -1
- package/dist/src/plugin/transform/model-resolver.d.ts +1 -1
- package/dist/src/plugin/transform/model-resolver.js +1 -1
- package/dist/src/plugin/transform/types.d.ts +1 -1
- package/dist/src/plugin/transform/types.js +1 -1
- package/dist/src/plugin/types.d.ts +25 -69
- package/dist/src/plugin/types.d.ts.map +1 -1
- package/dist/src/plugin/ui/ansi.d.ts.map +1 -1
- package/dist/src/plugin/ui/ansi.js.map +1 -1
- package/dist/src/plugin/ui/auth-menu.d.ts +1 -1
- package/dist/src/plugin/ui/auth-menu.d.ts.map +1 -1
- package/dist/src/plugin/ui/auth-menu.js +82 -31
- package/dist/src/plugin/ui/auth-menu.js.map +1 -1
- package/dist/src/plugin/ui/confirm.d.ts.map +1 -1
- package/dist/src/plugin/ui/confirm.js.map +1 -1
- package/dist/src/plugin/ui/model-status.d.ts +3 -3
- package/dist/src/plugin/ui/model-status.d.ts.map +1 -1
- package/dist/src/plugin/ui/model-status.js +3 -3
- package/dist/src/plugin/ui/model-status.js.map +1 -1
- package/dist/src/plugin/ui/quota-status.d.ts +4 -4
- package/dist/src/plugin/ui/quota-status.d.ts.map +1 -1
- package/dist/src/plugin/ui/quota-status.js +51 -49
- package/dist/src/plugin/ui/quota-status.js.map +1 -1
- package/dist/src/plugin/ui/select.d.ts.map +1 -1
- package/dist/src/plugin/ui/select.js +22 -12
- package/dist/src/plugin/ui/select.js.map +1 -1
- package/dist/src/plugin/version.d.ts +1 -1
- package/dist/src/plugin/version.js +1 -1
- package/dist/src/rpc/notifications.d.ts +6 -0
- package/dist/src/rpc/notifications.d.ts.map +1 -0
- package/dist/src/rpc/notifications.js +46 -0
- package/dist/src/rpc/notifications.js.map +1 -0
- package/dist/src/rpc/port-file.d.ts +13 -0
- package/dist/src/rpc/port-file.d.ts.map +1 -0
- package/dist/src/rpc/port-file.js +109 -0
- package/dist/src/rpc/port-file.js.map +1 -0
- package/dist/src/rpc/protocol.d.ts +22 -0
- package/dist/src/rpc/protocol.d.ts.map +1 -0
- package/dist/src/rpc/protocol.js +1 -0
- package/dist/src/rpc/protocol.js.map +1 -0
- package/dist/src/rpc/rpc-client.d.ts +10 -0
- package/dist/src/rpc/rpc-client.d.ts.map +1 -0
- package/dist/src/rpc/rpc-client.js +58 -0
- package/dist/src/rpc/rpc-client.js.map +1 -0
- package/dist/src/rpc/rpc-dir.d.ts +4 -0
- package/dist/src/rpc/rpc-dir.d.ts.map +1 -0
- package/dist/src/rpc/rpc-dir.js +19 -0
- package/dist/src/rpc/rpc-dir.js.map +1 -0
- package/dist/src/rpc/rpc-server.d.ts +13 -0
- package/dist/src/rpc/rpc-server.d.ts.map +1 -0
- package/dist/src/rpc/rpc-server.js +231 -0
- package/dist/src/rpc/rpc-server.js.map +1 -0
- package/dist/src/sidebar-state.d.ts +240 -0
- package/dist/src/sidebar-state.d.ts.map +1 -0
- package/dist/src/sidebar-state.js +520 -0
- package/dist/src/sidebar-state.js.map +1 -0
- package/dist/src/tui/command-dialogs.d.ts +61 -0
- package/dist/src/tui/command-dialogs.d.ts.map +1 -0
- package/dist/src/tui/command-dialogs.js +497 -0
- package/dist/src/tui/command-dialogs.js.map +1 -0
- package/dist/src/tui/file-logger.d.ts +41 -0
- package/dist/src/tui/file-logger.d.ts.map +1 -0
- package/dist/src/tui/file-logger.js +114 -0
- package/dist/src/tui/file-logger.js.map +1 -0
- package/dist/src/tui-preferences.d.ts +40 -0
- package/dist/src/tui-preferences.d.ts.map +1 -0
- package/dist/src/tui-preferences.js +328 -0
- package/dist/src/tui-preferences.js.map +1 -0
- package/dist/src/tui.d.ts +68 -0
- package/dist/src/tui.d.ts.map +1 -0
- package/dist/src/tui.js +662 -0
- package/dist/src/tui.js.map +1 -0
- package/package.json +46 -22
- package/src/plugin/command-data.ts +651 -0
- package/src/rpc/port-file.ts +143 -0
- package/src/rpc/protocol.ts +31 -0
- package/src/rpc/rpc-client.ts +102 -0
- package/src/rpc/rpc-dir.ts +24 -0
- package/src/sidebar-state.ts +717 -0
- package/src/tui/command-dialogs.tsx +699 -0
- package/src/tui/entry.mjs +74 -0
- package/src/tui/file-logger.ts +145 -0
- package/src/tui-compiled/plugin/command-data.ts +651 -0
- package/src/tui-compiled/rpc/port-file.ts +143 -0
- package/src/tui-compiled/rpc/protocol.ts +31 -0
- package/src/tui-compiled/rpc/rpc-client.ts +102 -0
- package/src/tui-compiled/rpc/rpc-dir.ts +24 -0
- package/src/tui-compiled/sidebar-state.ts +717 -0
- package/src/tui-compiled/tui/command-dialogs.tsx +659 -0
- package/src/tui-compiled/tui/file-logger.ts +145 -0
- package/src/tui-compiled/tui-preferences.ts +416 -0
- package/src/tui-compiled/tui.tsx +1150 -0
- package/src/tui-preferences.ts +416 -0
- package/src/tui.tsx +1117 -0
- package/dist/src/plugin.d.ts +0 -48
- package/dist/src/plugin.d.ts.map +0 -1
- package/dist/src/plugin.js +0 -3311
- package/dist/src/plugin.js.map +0 -1
|
@@ -0,0 +1,1387 @@
|
|
|
1
|
+
import { fetchWithAgyCliTransport } from '@cortexkit/antigravity-auth-core';
|
|
2
|
+
import { ANTIGRAVITY_ENDPOINT_FALLBACKS } from '../constants';
|
|
3
|
+
import { upsertSidebarActiveRouting, } from '../sidebar-state';
|
|
4
|
+
import { extractAccountAccessErrorDetails } from './account-access';
|
|
5
|
+
import { calculateBackoffMs, computeSoftQuotaCacheTtlMs, parseRateLimitReason, resolveQuotaGroup, } from './accounts';
|
|
6
|
+
import { accessTokenExpired, isOAuthAuth } from './auth';
|
|
7
|
+
import { isDebugEnabled, logAccountContext, logAntigravityDebugResponse, logRateLimitEvent, logRateLimitSnapshot, logResponseBody, startAntigravityDebugRequest, } from './debug';
|
|
8
|
+
import { AntigravityKillswitchError } from './errors';
|
|
9
|
+
import { createRetryState, } from './fetch/retry-state';
|
|
10
|
+
import { createWarmupState } from './fetch/warmup';
|
|
11
|
+
import { extractModelFromUrl, getModelFamilyFromUrl, isCapacityRetryBudgetExhausted, MAX_TOTAL_CAPACITY_RETRIES, resolveHeaderRoutingDecision, resolveQuotaFallbackHeaderStyle, toUrlString, toWarmupStreamUrl, } from './fetch-routing';
|
|
12
|
+
import { dumpGeminiRequest, noteGeminiDumpResponse } from './gemini-dump';
|
|
13
|
+
import { evaluateKillswitchForAccount, throwIfAllKilled } from './killswitch';
|
|
14
|
+
import { createLogger } from './logger';
|
|
15
|
+
import { ensureProjectContext } from './project';
|
|
16
|
+
import { buildThinkingWarmupBody, getImageModelLocalTitle, getLastCacheStats, isGenerativeLanguageRequest, prepareAntigravityRequest, transformAntigravityResponse, } from './request';
|
|
17
|
+
import { createSyntheticErrorResponse, createSyntheticTextResponse, isEmptyResponseBody, } from './request-helpers';
|
|
18
|
+
import { getHealthTracker, getTokenTracker } from './rotation';
|
|
19
|
+
import { extractOpenCodeSessionIdentity, } from './session-context';
|
|
20
|
+
import { AntigravityTokenRefreshError, refreshAccessToken } from './token';
|
|
21
|
+
const log = createLogger('fetch-interceptor');
|
|
22
|
+
/**
|
|
23
|
+
* Per-call delay applied before the first 429 retry on the same account.
|
|
24
|
+
* Matches the legacy plugin so callers that compare timing logs see parity.
|
|
25
|
+
*/
|
|
26
|
+
const FIRST_RETRY_DELAY_MS = 1000;
|
|
27
|
+
/** Production transport — used when the interceptor context omits one. */
|
|
28
|
+
const defaultAgyTransport = (url, init, options) => fetchWithAgyCliTransport(url, init, options);
|
|
29
|
+
/** Default `fetchImpl` used when the interceptor context omits one. */
|
|
30
|
+
const defaultFetchImpl = (input, init) => globalThis.fetch(input, init);
|
|
31
|
+
/**
|
|
32
|
+
* Builds a Google-style 401 envelope describing a missing-account failure.
|
|
33
|
+
*
|
|
34
|
+
* The legacy plugin returned `createSyntheticErrorResponse(...)`, which yields
|
|
35
|
+
* a 200 SSE body pretending to be a Gemini stream. That hid the underlying
|
|
36
|
+
* misconfiguration from any caller that inspected `response.status`. Callers
|
|
37
|
+
* (notably OpenCode's HTTP layer) treat 200 as success and silently swallow
|
|
38
|
+
* the payload, so the user sees nothing. Surfacing a real 401 with the
|
|
39
|
+
* standard Google error envelope makes the failure actionable.
|
|
40
|
+
*/
|
|
41
|
+
function createNoAccountResponse(message, model) {
|
|
42
|
+
const body = {
|
|
43
|
+
error: {
|
|
44
|
+
code: 401,
|
|
45
|
+
message,
|
|
46
|
+
status: 'UNAUTHENTICATED',
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
return new Response(JSON.stringify(body), {
|
|
50
|
+
status: 401,
|
|
51
|
+
headers: {
|
|
52
|
+
'Content-Type': 'application/json',
|
|
53
|
+
'X-Antigravity-Error-Type': 'no_accounts',
|
|
54
|
+
'X-Antigravity-Requested-Model': model,
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/** Reads `retry-after-ms` / `retry-after` headers, in that order. */
|
|
59
|
+
function retryAfterMsFromResponse(response, defaultRetryMs = 60_000) {
|
|
60
|
+
const retryAfterMsHeader = response.headers.get('retry-after-ms');
|
|
61
|
+
if (retryAfterMsHeader) {
|
|
62
|
+
const parsed = Number.parseInt(retryAfterMsHeader, 10);
|
|
63
|
+
if (!Number.isNaN(parsed) && parsed > 0) {
|
|
64
|
+
return parsed;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const retryAfterHeader = response.headers.get('retry-after');
|
|
68
|
+
if (retryAfterHeader) {
|
|
69
|
+
const parsed = Number.parseInt(retryAfterHeader, 10);
|
|
70
|
+
if (!Number.isNaN(parsed) && parsed > 0) {
|
|
71
|
+
return parsed * 1000;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return defaultRetryMs;
|
|
75
|
+
}
|
|
76
|
+
/** Formats a millisecond duration the way the legacy toast pipeline did. */
|
|
77
|
+
function formatWaitTime(ms) {
|
|
78
|
+
if (ms < 1000)
|
|
79
|
+
return `${ms}ms`;
|
|
80
|
+
const seconds = Math.ceil(ms / 1000);
|
|
81
|
+
if (seconds < 60)
|
|
82
|
+
return `${seconds}s`;
|
|
83
|
+
const minutes = Math.floor(seconds / 60);
|
|
84
|
+
const remainingSeconds = seconds % 60;
|
|
85
|
+
if (minutes < 60) {
|
|
86
|
+
return remainingSeconds > 0
|
|
87
|
+
? `${minutes}m ${remainingSeconds}s`
|
|
88
|
+
: `${minutes}m`;
|
|
89
|
+
}
|
|
90
|
+
const hours = Math.floor(minutes / 60);
|
|
91
|
+
const remainingMinutes = minutes % 60;
|
|
92
|
+
return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Sleep for `ms` milliseconds, rejecting with the abort reason when the
|
|
96
|
+
* supplied signal fires before the timer elapses.
|
|
97
|
+
*/
|
|
98
|
+
function sleep(ms, signal) {
|
|
99
|
+
return new Promise((resolve, reject) => {
|
|
100
|
+
if (signal?.aborted) {
|
|
101
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error('Aborted'));
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const timeout = setTimeout(() => {
|
|
105
|
+
cleanup();
|
|
106
|
+
resolve();
|
|
107
|
+
}, ms);
|
|
108
|
+
const onAbort = () => {
|
|
109
|
+
cleanup();
|
|
110
|
+
reject(signal?.reason instanceof Error ? signal.reason : new Error('Aborted'));
|
|
111
|
+
};
|
|
112
|
+
const cleanup = () => {
|
|
113
|
+
clearTimeout(timeout);
|
|
114
|
+
signal?.removeEventListener('abort', onAbort);
|
|
115
|
+
};
|
|
116
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Wraps the upstream fetch with the full account-rotation, rate-limit, and
|
|
121
|
+
* quota-fallback pipeline. Each interceptor owns its retry/warmup bookkeeping
|
|
122
|
+
* so disposing the plugin releases every counter.
|
|
123
|
+
*/
|
|
124
|
+
export function createFetchInterceptor(context) {
|
|
125
|
+
const { client, providerId, config, accountManager, quotaManager, getAuth, agySessionRegistry, operatorSettings, agyTransport = defaultAgyTransport, fetchImpl = defaultFetchImpl,
|
|
126
|
+
// directory is part of the contract but not consumed by this interceptor;
|
|
127
|
+
// callers use it when constructing sibling services (e.g. project context).
|
|
128
|
+
} = context;
|
|
129
|
+
void context.directory;
|
|
130
|
+
const retryState = createRetryState();
|
|
131
|
+
const warmupState = createWarmupState();
|
|
132
|
+
let disposed = false;
|
|
133
|
+
// Capture the host fetch at factory time so the interceptor never shadows
|
|
134
|
+
// it with its own (recursive) fetch binding. Production wires this up via
|
|
135
|
+
// the OpenCode plugin runtime; tests inject a mock by stubbing globalThis
|
|
136
|
+
// OR — preferred for e2e — pass `fetchImpl` through the context so the
|
|
137
|
+
// stub survives a process-wide fetch replacement.
|
|
138
|
+
const upstreamFetch = fetchImpl;
|
|
139
|
+
// Cache the bound transport so the three call sites (warmup, probe,
|
|
140
|
+
// dispatch) reuse the same closure. The binding happens once per
|
|
141
|
+
// interceptor to mirror the historical `fetchWithAgyCliTransport`
|
|
142
|
+
// import behavior — call sites used the function reference, not a
|
|
143
|
+
// re-bind per request.
|
|
144
|
+
const transport = agyTransport;
|
|
145
|
+
async function triggerAsyncQuotaRefreshForAccount(accountIndex, intervalMinutes) {
|
|
146
|
+
if (intervalMinutes <= 0)
|
|
147
|
+
return;
|
|
148
|
+
const accounts = accountManager.getAccounts();
|
|
149
|
+
const account = accounts[accountIndex];
|
|
150
|
+
if (!account || account.enabled === false)
|
|
151
|
+
return;
|
|
152
|
+
const intervalMs = intervalMinutes * 60 * 1000;
|
|
153
|
+
const age = account.cachedQuotaUpdatedAt != null
|
|
154
|
+
? Date.now() - account.cachedQuotaUpdatedAt
|
|
155
|
+
: Infinity;
|
|
156
|
+
if (age < intervalMs)
|
|
157
|
+
return;
|
|
158
|
+
let singleAccount;
|
|
159
|
+
try {
|
|
160
|
+
const accountsForCheck = accountManager.getAccountsForQuotaCheck();
|
|
161
|
+
singleAccount = accountsForCheck[accountIndex];
|
|
162
|
+
if (!singleAccount)
|
|
163
|
+
return;
|
|
164
|
+
const result = await quotaManager.refreshAccount(singleAccount, {
|
|
165
|
+
index: accountIndex,
|
|
166
|
+
});
|
|
167
|
+
if (result.status === 'ok' && result.quota?.groups) {
|
|
168
|
+
accountManager.updateQuotaCache(accountIndex, result.quota.groups);
|
|
169
|
+
accountManager.requestSaveToDisk();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
log.debug(`quota-refresh-failed ${singleAccount ? quotaManager.hashedLogLabel('account', singleAccount) : `idx-${accountIndex}`}`, { error: String(err) });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async function fetch(input, init) {
|
|
177
|
+
if (disposed) {
|
|
178
|
+
// After dispose we deliberately stop intercepting so an in-flight call
|
|
179
|
+
// can still resolve without throwing. The plugin tear-down order may
|
|
180
|
+
// race with a final inflight fetch.
|
|
181
|
+
return upstreamFetch(input, init);
|
|
182
|
+
}
|
|
183
|
+
if (!isGenerativeLanguageRequest(input)) {
|
|
184
|
+
return upstreamFetch(input, init);
|
|
185
|
+
}
|
|
186
|
+
const latestAuth = await getAuth();
|
|
187
|
+
if (!isOAuthAuth(latestAuth)) {
|
|
188
|
+
return upstreamFetch(input, init);
|
|
189
|
+
}
|
|
190
|
+
// Normalize Request/URL inputs to (urlString, init) so the string-based
|
|
191
|
+
// transform pipeline sees the real method/headers/body. Without this,
|
|
192
|
+
// fetch(new Request(...)) would carry its payload on the Request object
|
|
193
|
+
// where our string path can't read it.
|
|
194
|
+
if (typeof input !== 'string') {
|
|
195
|
+
if (input instanceof Request) {
|
|
196
|
+
const req = input;
|
|
197
|
+
const headers = new Headers(req.headers);
|
|
198
|
+
if (init?.headers) {
|
|
199
|
+
new Headers(init.headers).forEach((v, k) => {
|
|
200
|
+
headers.set(k, v);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
const bodyBuffer = req.body
|
|
204
|
+
? await req.clone().arrayBuffer()
|
|
205
|
+
: undefined;
|
|
206
|
+
init = {
|
|
207
|
+
method: init?.method ?? req.method,
|
|
208
|
+
headers,
|
|
209
|
+
body: init?.body ?? (bodyBuffer ? Buffer.from(bodyBuffer) : undefined),
|
|
210
|
+
signal: init?.signal ?? req.signal,
|
|
211
|
+
};
|
|
212
|
+
input = req.url;
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
input = String(input.href ?? input);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const localImageTitle = getImageModelLocalTitle(input, init);
|
|
219
|
+
if (localImageTitle !== undefined) {
|
|
220
|
+
return createSyntheticTextResponse(localImageTitle, {
|
|
221
|
+
'X-Antigravity-Response-Type': 'local_title',
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
const requestSessionIdentity = extractOpenCodeSessionIdentity(init?.headers);
|
|
225
|
+
const agyRequestScope = agySessionRegistry.beginRequest(requestSessionIdentity);
|
|
226
|
+
const agyRequestSession = agyRequestScope.session;
|
|
227
|
+
const accountSessionIdentity = requestSessionIdentity.sessionId
|
|
228
|
+
? {
|
|
229
|
+
id: requestSessionIdentity.sessionId,
|
|
230
|
+
parentId: requestSessionIdentity.parentSessionId,
|
|
231
|
+
}
|
|
232
|
+
: undefined;
|
|
233
|
+
const isChildRequest = requestSessionIdentity.parentSessionId !== null;
|
|
234
|
+
if (accountManager.getAccountCount() === 0) {
|
|
235
|
+
// Surface a real 401 with the Google error envelope instead of a
|
|
236
|
+
// 200 SSE body — OpenCode's HTTP layer treats 200 as success and
|
|
237
|
+
// would otherwise swallow the misconfiguration silently.
|
|
238
|
+
const urlString = typeof input === 'string' ? input : toUrlString(input);
|
|
239
|
+
const modelFromUrl = extractModelFromUrl(urlString) ?? 'unknown';
|
|
240
|
+
return createNoAccountResponse('No Antigravity accounts configured. Run `opencode auth login`.', modelFromUrl);
|
|
241
|
+
}
|
|
242
|
+
const urlString = toUrlString(input);
|
|
243
|
+
const family = getModelFamilyFromUrl(urlString);
|
|
244
|
+
const model = extractModelFromUrl(urlString);
|
|
245
|
+
const debugLines = [];
|
|
246
|
+
const pushDebug = (line) => {
|
|
247
|
+
if (!isDebugEnabled())
|
|
248
|
+
return;
|
|
249
|
+
debugLines.push(line);
|
|
250
|
+
};
|
|
251
|
+
pushDebug(`request=${urlString}`);
|
|
252
|
+
if (requestSessionIdentity.sessionId) {
|
|
253
|
+
pushDebug(`[Session] id=${requestSessionIdentity.sessionId}` +
|
|
254
|
+
` parent=${requestSessionIdentity.parentSessionId ?? 'none'}` +
|
|
255
|
+
` child=${isChildRequest}`);
|
|
256
|
+
}
|
|
257
|
+
const cachedStats = getLastCacheStats();
|
|
258
|
+
if (cachedStats) {
|
|
259
|
+
const label = cachedStats.hitRate > 0 ? 'HIT' : 'MISS';
|
|
260
|
+
pushDebug(`[Cache] ${label} model=${cachedStats.model} read=${cachedStats.read} total=${cachedStats.total} hitRate=${cachedStats.hitRate}%`);
|
|
261
|
+
}
|
|
262
|
+
let lastFailure = null;
|
|
263
|
+
let lastError = null;
|
|
264
|
+
const abortSignal = init?.signal ?? undefined;
|
|
265
|
+
const checkAborted = () => {
|
|
266
|
+
if (abortSignal?.aborted) {
|
|
267
|
+
throw abortSignal.reason instanceof Error
|
|
268
|
+
? abortSignal.reason
|
|
269
|
+
: new Error('Aborted');
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
const quietMode = config.quiet_mode;
|
|
273
|
+
const toastScope = config.toast_scope;
|
|
274
|
+
// Apply operator-controlled routing overrides live. The slash
|
|
275
|
+
// commands mutate these values through `applyCommand`; reading
|
|
276
|
+
// them per-request means a runtime flip takes effect on the next
|
|
277
|
+
// dispatched call without restarting the plugin.
|
|
278
|
+
const operatorRouting = operatorSettings?.get().routing;
|
|
279
|
+
const effectiveConfig = {
|
|
280
|
+
...config,
|
|
281
|
+
cli_first: operatorRouting?.cli_first ?? config.cli_first,
|
|
282
|
+
quota_style_fallback: operatorRouting?.quota_style_fallback ?? config.quota_style_fallback,
|
|
283
|
+
};
|
|
284
|
+
const showToast = async (message, variant) => {
|
|
285
|
+
log.debug('toast', {
|
|
286
|
+
message,
|
|
287
|
+
variant,
|
|
288
|
+
isChildSession: isChildRequest,
|
|
289
|
+
toastScope,
|
|
290
|
+
});
|
|
291
|
+
if (quietMode)
|
|
292
|
+
return;
|
|
293
|
+
if (abortSignal?.aborted)
|
|
294
|
+
return;
|
|
295
|
+
if (toastScope === 'root_only' && isChildRequest) {
|
|
296
|
+
log.debug('toast-suppressed-child-session', {
|
|
297
|
+
message,
|
|
298
|
+
variant,
|
|
299
|
+
parentID: requestSessionIdentity.parentSessionId,
|
|
300
|
+
});
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
if (variant === 'warning' && message.toLowerCase().includes('rate')) {
|
|
304
|
+
if (!retryState.shouldShowRateLimitToast(message)) {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
try {
|
|
309
|
+
await client.tui.showToast({ body: { message, variant } });
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
// TUI may not be available
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
const hasOtherAccountWithAntigravity = (currentAccount) => {
|
|
316
|
+
if (family !== 'gemini')
|
|
317
|
+
return false;
|
|
318
|
+
return accountManager.hasOtherAccountWithAntigravityAvailable(currentAccount.index, family, model);
|
|
319
|
+
};
|
|
320
|
+
let accountSwitchCount = 0;
|
|
321
|
+
const maxAccountSwitches = config.max_account_switches ?? 2;
|
|
322
|
+
let previousAccountIndex = -1;
|
|
323
|
+
let needsCacheWarmup = false;
|
|
324
|
+
while (true) {
|
|
325
|
+
checkAborted();
|
|
326
|
+
const accountCount = accountManager.getAccountCount();
|
|
327
|
+
const routingDecision = resolveHeaderRoutingDecision(urlString, family, effectiveConfig);
|
|
328
|
+
const { preferredHeaderStyle, explicitQuota, allowQuotaFallback } = routingDecision;
|
|
329
|
+
if (accountCount === 0) {
|
|
330
|
+
// Mirror the no-account short-circuit inside the retry loop so callers
|
|
331
|
+
// that race with account removal still get a proper 401 instead of a
|
|
332
|
+
// hang or a synthetic 200.
|
|
333
|
+
return createNoAccountResponse('No Antigravity accounts available. Run `opencode auth login`.', model ?? 'unknown');
|
|
334
|
+
}
|
|
335
|
+
const softQuotaCacheTtlMs = computeSoftQuotaCacheTtlMs(config.soft_quota_cache_ttl_minutes, config.quota_refresh_interval_minutes);
|
|
336
|
+
// Operator killswitch — drop candidates whose freshest cached
|
|
337
|
+
// quota remaining-percent is below the configured floor. Fail
|
|
338
|
+
// open on missing/stale quota so a cold start cannot deadlock
|
|
339
|
+
// the pipeline. The evaluation is model-aware: a `gemini-pro`
|
|
340
|
+
// request checks ONLY the `gemini-pro` quota group, not the max
|
|
341
|
+
// of pro+flash.
|
|
342
|
+
const operatorKillswitch = operatorSettings?.get().killswitch;
|
|
343
|
+
const eligibleIndexes = operatorKillswitch?.enabled
|
|
344
|
+
? new Set(accountManager
|
|
345
|
+
.getAccounts()
|
|
346
|
+
.filter((entry) => {
|
|
347
|
+
const decision = evaluateKillswitchForAccount(entry, family, {
|
|
348
|
+
routing: effectiveConfig.cli_first !== undefined
|
|
349
|
+
? {
|
|
350
|
+
cli_first: effectiveConfig.cli_first,
|
|
351
|
+
quota_style_fallback: !!effectiveConfig.quota_style_fallback,
|
|
352
|
+
}
|
|
353
|
+
: { cli_first: false, quota_style_fallback: false },
|
|
354
|
+
killswitch: operatorKillswitch,
|
|
355
|
+
log_level: 'info',
|
|
356
|
+
}, { now: Date.now(), model });
|
|
357
|
+
return decision.allowed;
|
|
358
|
+
})
|
|
359
|
+
.map((entry) => entry.index))
|
|
360
|
+
: null;
|
|
361
|
+
if (eligibleIndexes !== null &&
|
|
362
|
+
eligibleIndexes.size === 0 &&
|
|
363
|
+
accountCount > 0) {
|
|
364
|
+
try {
|
|
365
|
+
throwIfAllKilled({
|
|
366
|
+
family,
|
|
367
|
+
model: model ?? 'unknown',
|
|
368
|
+
accounts: accountManager.getAccounts(),
|
|
369
|
+
settings: {
|
|
370
|
+
routing: { cli_first: false, quota_style_fallback: false },
|
|
371
|
+
killswitch: operatorKillswitch ?? {
|
|
372
|
+
enabled: false,
|
|
373
|
+
minimum_remaining_percent: 0,
|
|
374
|
+
},
|
|
375
|
+
log_level: 'info',
|
|
376
|
+
},
|
|
377
|
+
quotaModel: model,
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
if (error instanceof AntigravityKillswitchError) {
|
|
382
|
+
log.warn('killswitch-all-excluded', {
|
|
383
|
+
family,
|
|
384
|
+
model,
|
|
385
|
+
threshold: error.thresholdPercent,
|
|
386
|
+
summaries: error.summaries,
|
|
387
|
+
});
|
|
388
|
+
return createSyntheticErrorResponse(error.message, model ?? 'unknown');
|
|
389
|
+
}
|
|
390
|
+
throw error;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
// Feed the killswitch verdict INTO selection: every index the
|
|
394
|
+
// precomputed eligible set rules out is excluded at the source,
|
|
395
|
+
// so a killed current account falls through to the next eligible
|
|
396
|
+
// account instead of collapsing the request into the rate-limit
|
|
397
|
+
// wait path below. The precomputed set is the source of truth —
|
|
398
|
+
// selection never re-evaluates quota, so a long-running request
|
|
399
|
+
// cannot see a different answer than the pre-filter above.
|
|
400
|
+
const killedIndexes = eligibleIndexes === null
|
|
401
|
+
? undefined
|
|
402
|
+
: new Set(accountManager
|
|
403
|
+
.getAccounts()
|
|
404
|
+
.map((entry) => entry.index)
|
|
405
|
+
.filter((index) => !eligibleIndexes.has(index)));
|
|
406
|
+
let account = accountManager.getCurrentOrNextForFamily(family, model, config.account_selection_strategy, preferredHeaderStyle, config.pid_offset_enabled, config.soft_quota_threshold_percent, softQuotaCacheTtlMs, accountSessionIdentity, killedIndexes);
|
|
407
|
+
// Belt-and-suspenders re-check on the chosen candidate against
|
|
408
|
+
// the precomputed eligible set (selection already excluded the
|
|
409
|
+
// killed indexes; this guards the fallback paths below).
|
|
410
|
+
if (account &&
|
|
411
|
+
eligibleIndexes !== null &&
|
|
412
|
+
!eligibleIndexes.has(account.index)) {
|
|
413
|
+
pushDebug(`killswitch-excluded idx=${account.index} (precomputed eligible set)`);
|
|
414
|
+
account = null;
|
|
415
|
+
}
|
|
416
|
+
if (!account && allowQuotaFallback) {
|
|
417
|
+
const alternateHeaderStyle = preferredHeaderStyle === 'antigravity' ? 'gemini-cli' : 'antigravity';
|
|
418
|
+
account = accountManager.getCurrentOrNextForFamily(family, model, config.account_selection_strategy, alternateHeaderStyle, config.pid_offset_enabled, config.soft_quota_threshold_percent, softQuotaCacheTtlMs, accountSessionIdentity, killedIndexes);
|
|
419
|
+
if (account) {
|
|
420
|
+
pushDebug(`selected-by-fallback idx=${account.index} preferred=${preferredHeaderStyle} alternate=${alternateHeaderStyle}`);
|
|
421
|
+
}
|
|
422
|
+
// The fallback path also has to clear the killswitch — a
|
|
423
|
+
// previous pre-filter scoped to the preferred-header accounts
|
|
424
|
+
// may have allowed an account only on the fallback header.
|
|
425
|
+
if (account &&
|
|
426
|
+
eligibleIndexes !== null &&
|
|
427
|
+
!eligibleIndexes.has(account.index)) {
|
|
428
|
+
pushDebug(`killswitch-excluded idx=${account.index} after fallback (precomputed eligible set)`);
|
|
429
|
+
account = null;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
if (!account) {
|
|
433
|
+
if (accountManager.areAllAccountsOverSoftQuota(family, config.soft_quota_threshold_percent, softQuotaCacheTtlMs, model)) {
|
|
434
|
+
const threshold = config.soft_quota_threshold_percent;
|
|
435
|
+
const softQuotaWaitMs = accountManager.getMinWaitTimeForSoftQuota(family, threshold, softQuotaCacheTtlMs, model);
|
|
436
|
+
const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1000;
|
|
437
|
+
if (softQuotaWaitMs === null ||
|
|
438
|
+
(maxWaitMs > 0 && softQuotaWaitMs > maxWaitMs)) {
|
|
439
|
+
const waitTimeFormatted = softQuotaWaitMs
|
|
440
|
+
? formatWaitTime(softQuotaWaitMs)
|
|
441
|
+
: 'unknown';
|
|
442
|
+
await showToast(`All accounts over ${threshold}% quota threshold. Resets in ${waitTimeFormatted}.`, 'error');
|
|
443
|
+
return createSyntheticErrorResponse(`Quota protection: All ${accountCount} account(s) are over ${threshold}% usage for ${family}. ` +
|
|
444
|
+
`Quota resets in ${waitTimeFormatted}. ` +
|
|
445
|
+
`Add more accounts, wait for quota reset, or set soft_quota_threshold_percent: 100 to disable.`, model ?? 'unknown');
|
|
446
|
+
}
|
|
447
|
+
pushDebug(`all-over-soft-quota family=${family} accounts=${accountCount} waitMs=${softQuotaWaitMs}`);
|
|
448
|
+
if (!retryState.softQuotaToastShown()) {
|
|
449
|
+
await showToast(`All ${accountCount} account(s) over ${threshold}% quota. Waiting ${formatWaitTime(softQuotaWaitMs)}...`, 'warning');
|
|
450
|
+
retryState.markSoftQuotaToastShown();
|
|
451
|
+
}
|
|
452
|
+
await sleep(softQuotaWaitMs, abortSignal);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
const strictWait = !allowQuotaFallback;
|
|
456
|
+
const waitMs = accountManager.getMinWaitTimeForFamily(family, model, preferredHeaderStyle, strictWait) || 60_000;
|
|
457
|
+
pushDebug(`all-rate-limited family=${family} accounts=${accountCount} waitMs=${waitMs}`);
|
|
458
|
+
if (isDebugEnabled()) {
|
|
459
|
+
logAccountContext('All accounts rate-limited', {
|
|
460
|
+
index: -1,
|
|
461
|
+
family,
|
|
462
|
+
totalAccounts: accountCount,
|
|
463
|
+
});
|
|
464
|
+
logRateLimitSnapshot(family, accountManager.getAccountsSnapshot());
|
|
465
|
+
}
|
|
466
|
+
const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1000;
|
|
467
|
+
if (maxWaitMs > 0 && waitMs > maxWaitMs) {
|
|
468
|
+
const waitTimeFormatted = formatWaitTime(waitMs);
|
|
469
|
+
await showToast(`Rate limited for ${waitTimeFormatted}. Try again later or add another account.`, 'error');
|
|
470
|
+
return createSyntheticErrorResponse(`All ${accountCount} account(s) rate-limited for ${family}. ` +
|
|
471
|
+
`Quota resets in ${waitTimeFormatted}. ` +
|
|
472
|
+
`Add more accounts with \`opencode auth login\` or wait and retry.`, model ?? 'unknown');
|
|
473
|
+
}
|
|
474
|
+
if (!retryState.rateLimitToastShown()) {
|
|
475
|
+
const waitSecValue = Math.max(1, Math.ceil(waitMs / 1000));
|
|
476
|
+
await showToast(`All ${accountCount} account(s) rate-limited for ${family}. Waiting ${waitSecValue}s...`, 'warning');
|
|
477
|
+
retryState.markRateLimitToastShown();
|
|
478
|
+
}
|
|
479
|
+
await sleep(waitMs, abortSignal);
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
// Account is available - reset the toast flag
|
|
483
|
+
retryState.resetAllAccountsBlockedToasts();
|
|
484
|
+
pushDebug(`selected idx=${account.index} email=${account.email ?? ''} family=${family} accounts=${accountCount} strategy=${config.account_selection_strategy}`);
|
|
485
|
+
if (previousAccountIndex >= 0 && previousAccountIndex !== account.index) {
|
|
486
|
+
needsCacheWarmup = config.cache_warmup_on_switch;
|
|
487
|
+
pushDebug(`account-switch: ${previousAccountIndex} → ${account.index}, warmup=${needsCacheWarmup}`);
|
|
488
|
+
}
|
|
489
|
+
previousAccountIndex = account.index;
|
|
490
|
+
accountManager.recordSessionUsage(account.index, accountSessionIdentity);
|
|
491
|
+
if (isDebugEnabled()) {
|
|
492
|
+
logAccountContext('Selected', {
|
|
493
|
+
index: account.index,
|
|
494
|
+
email: account.email,
|
|
495
|
+
family,
|
|
496
|
+
totalAccounts: accountCount,
|
|
497
|
+
rateLimitState: account.rateLimitResetTimes,
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
if (accountCount > 1 &&
|
|
501
|
+
accountManager.shouldShowAccountToast(account.index)) {
|
|
502
|
+
const accountLabel = account.email || `Account ${account.index + 1}`;
|
|
503
|
+
const enabledAccounts = accountManager.getEnabledAccounts();
|
|
504
|
+
const enabledPosition = enabledAccounts.findIndex((a) => a.index === account.index) + 1;
|
|
505
|
+
await showToast(`Using ${accountLabel} (${enabledPosition}/${accountCount})`, 'info');
|
|
506
|
+
accountManager.markToastShown(account.index);
|
|
507
|
+
}
|
|
508
|
+
accountManager.requestSaveToDisk();
|
|
509
|
+
let authRecord = accountManager.toAuthDetails(account);
|
|
510
|
+
if (accessTokenExpired(authRecord)) {
|
|
511
|
+
try {
|
|
512
|
+
const refreshed = await refreshAccessToken(authRecord, client, providerId);
|
|
513
|
+
if (!refreshed) {
|
|
514
|
+
const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
|
|
515
|
+
getHealthTracker().recordFailure(account.index);
|
|
516
|
+
lastError = new Error('Antigravity token refresh failed');
|
|
517
|
+
if (shouldCooldown) {
|
|
518
|
+
accountManager.markAccountCoolingDown(account, cooldownMs, 'auth-failure');
|
|
519
|
+
accountManager.markRateLimited(account, cooldownMs, family, 'antigravity', model);
|
|
520
|
+
pushDebug(`token-refresh-failed: cooldown ${cooldownMs}ms after ${failures} failures`);
|
|
521
|
+
}
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
retryState.resetAccountFailureState(account.index);
|
|
525
|
+
accountManager.updateFromAuth(account, refreshed);
|
|
526
|
+
authRecord = refreshed;
|
|
527
|
+
try {
|
|
528
|
+
await accountManager.saveToDisk();
|
|
529
|
+
}
|
|
530
|
+
catch (error) {
|
|
531
|
+
log.error('Failed to persist refreshed auth', {
|
|
532
|
+
error: String(error),
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
catch (error) {
|
|
537
|
+
if (error instanceof AntigravityTokenRefreshError &&
|
|
538
|
+
error.code === 'invalid_grant') {
|
|
539
|
+
const removed = accountManager.removeAccount(account);
|
|
540
|
+
if (removed) {
|
|
541
|
+
log.warn('Removed revoked account from pool - reauthenticate via `opencode auth login`');
|
|
542
|
+
try {
|
|
543
|
+
await accountManager.saveToDiskReplace();
|
|
544
|
+
}
|
|
545
|
+
catch (persistError) {
|
|
546
|
+
log.error('Failed to persist revoked account removal', {
|
|
547
|
+
error: String(persistError),
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
if (accountManager.getAccountCount() === 0) {
|
|
552
|
+
try {
|
|
553
|
+
await client.auth.set({
|
|
554
|
+
path: { id: providerId },
|
|
555
|
+
body: { type: 'oauth', refresh: '', access: '', expires: 0 },
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
catch (storeError) {
|
|
559
|
+
log.error('Failed to clear stored Antigravity OAuth credentials', {
|
|
560
|
+
error: String(storeError),
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
return createNoAccountResponse('All Antigravity accounts have invalid refresh tokens. Run `opencode auth login` and reauthenticate.', model ?? 'unknown');
|
|
564
|
+
}
|
|
565
|
+
lastError = error;
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
|
|
569
|
+
getHealthTracker().recordFailure(account.index);
|
|
570
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
571
|
+
if (shouldCooldown) {
|
|
572
|
+
accountManager.markAccountCoolingDown(account, cooldownMs, 'auth-failure');
|
|
573
|
+
accountManager.markRateLimited(account, cooldownMs, family, 'antigravity', model);
|
|
574
|
+
pushDebug(`token-refresh-error: cooldown ${cooldownMs}ms after ${failures} failures`);
|
|
575
|
+
}
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
const accessToken = authRecord.access;
|
|
580
|
+
if (!accessToken) {
|
|
581
|
+
lastError = new Error('Missing access token');
|
|
582
|
+
if (accountCount <= 1) {
|
|
583
|
+
return createSyntheticErrorResponse('Missing access token. Run `opencode auth login` to reauthenticate.', model ?? 'unknown');
|
|
584
|
+
}
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
let projectContext;
|
|
588
|
+
try {
|
|
589
|
+
projectContext = await ensureProjectContext(authRecord);
|
|
590
|
+
retryState.resetAccountFailureState(account.index);
|
|
591
|
+
}
|
|
592
|
+
catch (error) {
|
|
593
|
+
const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
|
|
594
|
+
getHealthTracker().recordFailure(account.index);
|
|
595
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
596
|
+
if (shouldCooldown) {
|
|
597
|
+
accountManager.markAccountCoolingDown(account, cooldownMs, 'project-error');
|
|
598
|
+
accountManager.markRateLimited(account, cooldownMs, family, 'antigravity', model);
|
|
599
|
+
pushDebug(`project-context-error: cooldown ${cooldownMs}ms after ${failures} failures`);
|
|
600
|
+
}
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
if (projectContext.auth.refresh !== authRecord.refresh ||
|
|
604
|
+
projectContext.auth.access !== authRecord.access) {
|
|
605
|
+
accountManager.updateFromAuth(account, projectContext.auth);
|
|
606
|
+
authRecord = projectContext.auth;
|
|
607
|
+
try {
|
|
608
|
+
await accountManager.saveToDisk();
|
|
609
|
+
}
|
|
610
|
+
catch (error) {
|
|
611
|
+
log.error('Failed to persist project context', {
|
|
612
|
+
error: String(error),
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
const runThinkingWarmup = async (prepared, projectId) => {
|
|
617
|
+
if (!config.thinking_warmup)
|
|
618
|
+
return;
|
|
619
|
+
if (!prepared.needsSignedThinkingWarmup || !prepared.sessionId)
|
|
620
|
+
return;
|
|
621
|
+
if (!warmupState.trackAttempt(prepared.sessionId))
|
|
622
|
+
return;
|
|
623
|
+
const warmupBody = buildThinkingWarmupBody(typeof prepared.init.body === 'string'
|
|
624
|
+
? prepared.init.body
|
|
625
|
+
: undefined, Boolean(prepared.effectiveModel?.toLowerCase().includes('claude') &&
|
|
626
|
+
prepared.effectiveModel?.toLowerCase().includes('thinking')));
|
|
627
|
+
if (!warmupBody)
|
|
628
|
+
return;
|
|
629
|
+
const warmupUrl = toWarmupStreamUrl(prepared.request);
|
|
630
|
+
const warmupHeaders = new Headers(prepared.init.headers ?? {});
|
|
631
|
+
warmupHeaders.set('accept', 'text/event-stream');
|
|
632
|
+
const warmupInit = {
|
|
633
|
+
...prepared.init,
|
|
634
|
+
method: prepared.init.method ?? 'POST',
|
|
635
|
+
headers: warmupHeaders,
|
|
636
|
+
body: warmupBody,
|
|
637
|
+
};
|
|
638
|
+
const warmupDebugContext = startAntigravityDebugRequest({
|
|
639
|
+
originalUrl: warmupUrl,
|
|
640
|
+
resolvedUrl: warmupUrl,
|
|
641
|
+
method: warmupInit.method,
|
|
642
|
+
headers: warmupHeaders,
|
|
643
|
+
body: warmupBody,
|
|
644
|
+
streaming: true,
|
|
645
|
+
projectId,
|
|
646
|
+
});
|
|
647
|
+
try {
|
|
648
|
+
pushDebug('thinking-warmup: start');
|
|
649
|
+
const warmupResponse = prepared.headerStyle === 'antigravity'
|
|
650
|
+
? await transport(warmupUrl, warmupInit, {
|
|
651
|
+
signal: abortSignal,
|
|
652
|
+
onDebug: pushDebug,
|
|
653
|
+
})
|
|
654
|
+
: await upstreamFetch(warmupUrl, warmupInit);
|
|
655
|
+
const transformed = await transformAntigravityResponse(warmupResponse, true, warmupDebugContext, prepared.requestedModel, projectId, warmupUrl, prepared.effectiveModel, prepared.sessionId);
|
|
656
|
+
await transformed.text();
|
|
657
|
+
warmupState.markSuccess(prepared.sessionId);
|
|
658
|
+
pushDebug('thinking-warmup: done');
|
|
659
|
+
}
|
|
660
|
+
catch (error) {
|
|
661
|
+
warmupState.clearWarmupAttempt(prepared.sessionId);
|
|
662
|
+
pushDebug(`thinking-warmup: failed ${error instanceof Error ? error.message : String(error)}`);
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
const runCacheWarmupProbe = async (prepared) => {
|
|
666
|
+
if (!needsCacheWarmup)
|
|
667
|
+
return;
|
|
668
|
+
needsCacheWarmup = false;
|
|
669
|
+
const bodyStr = typeof prepared.init.body === 'string'
|
|
670
|
+
? prepared.init.body
|
|
671
|
+
: undefined;
|
|
672
|
+
if (!bodyStr)
|
|
673
|
+
return;
|
|
674
|
+
try {
|
|
675
|
+
pushDebug('cache-warmup-probe: start');
|
|
676
|
+
const probeInit = {
|
|
677
|
+
...prepared.init,
|
|
678
|
+
method: 'POST',
|
|
679
|
+
body: bodyStr,
|
|
680
|
+
};
|
|
681
|
+
const probeResponse = prepared.headerStyle === 'antigravity'
|
|
682
|
+
? await transport(toUrlString(prepared.request), probeInit, {
|
|
683
|
+
signal: abortSignal,
|
|
684
|
+
onDebug: pushDebug,
|
|
685
|
+
})
|
|
686
|
+
: await upstreamFetch(toUrlString(prepared.request), probeInit);
|
|
687
|
+
if (probeResponse.body) {
|
|
688
|
+
const reader = probeResponse.body.getReader();
|
|
689
|
+
await reader.read();
|
|
690
|
+
await reader.cancel();
|
|
691
|
+
}
|
|
692
|
+
const status = probeResponse.status;
|
|
693
|
+
if (status >= 400) {
|
|
694
|
+
let errorSnippet = '';
|
|
695
|
+
try {
|
|
696
|
+
const errText = await probeResponse.text().catch(() => '');
|
|
697
|
+
errorSnippet = errText.slice(0, 200);
|
|
698
|
+
}
|
|
699
|
+
catch {
|
|
700
|
+
/* ignore */
|
|
701
|
+
}
|
|
702
|
+
pushDebug(`cache-warmup-probe: done status=${status}${errorSnippet ? ` error=${errorSnippet}` : ''}`);
|
|
703
|
+
}
|
|
704
|
+
else {
|
|
705
|
+
pushDebug(`cache-warmup-probe: done status=${status} (aborted after first chunk)`);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
catch (error) {
|
|
709
|
+
pushDebug(`cache-warmup-probe: failed ${error instanceof Error ? error.message : String(error)}`);
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
let apiRequestCount = 0;
|
|
713
|
+
let shouldSwitchAccount = false;
|
|
714
|
+
let headerStyle = preferredHeaderStyle;
|
|
715
|
+
pushDebug(`headerStyle=${headerStyle} explicit=${explicitQuota}`);
|
|
716
|
+
if (account.fingerprint) {
|
|
717
|
+
pushDebug(`fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`);
|
|
718
|
+
}
|
|
719
|
+
if (accountManager.isRateLimitedForHeaderStyle(account, family, headerStyle, model)) {
|
|
720
|
+
if (allowQuotaFallback &&
|
|
721
|
+
family === 'gemini' &&
|
|
722
|
+
headerStyle === 'antigravity') {
|
|
723
|
+
if (accountManager.hasOtherAccountWithAntigravityAvailable(account.index, family, model)) {
|
|
724
|
+
pushDebug(`antigravity rate-limited on account ${account.index}, but available on other accounts. Switching.`);
|
|
725
|
+
shouldSwitchAccount = true;
|
|
726
|
+
}
|
|
727
|
+
else {
|
|
728
|
+
const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
|
|
729
|
+
const fallbackStyle = resolveQuotaFallbackHeaderStyle({
|
|
730
|
+
family,
|
|
731
|
+
headerStyle,
|
|
732
|
+
alternateStyle,
|
|
733
|
+
});
|
|
734
|
+
if (fallbackStyle) {
|
|
735
|
+
await showToast(`Antigravity quota exhausted on all accounts. Using Gemini CLI quota.`, 'warning');
|
|
736
|
+
headerStyle = fallbackStyle;
|
|
737
|
+
pushDebug(`all-accounts antigravity exhausted, quota fallback: ${headerStyle}`);
|
|
738
|
+
}
|
|
739
|
+
else {
|
|
740
|
+
shouldSwitchAccount = true;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
else if (allowQuotaFallback && family === 'gemini') {
|
|
745
|
+
const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
|
|
746
|
+
const fallbackStyle = resolveQuotaFallbackHeaderStyle({
|
|
747
|
+
family,
|
|
748
|
+
headerStyle,
|
|
749
|
+
alternateStyle,
|
|
750
|
+
});
|
|
751
|
+
if (fallbackStyle) {
|
|
752
|
+
const quotaName = headerStyle === 'gemini-cli' ? 'Gemini CLI' : 'Antigravity';
|
|
753
|
+
const altQuotaName = fallbackStyle === 'gemini-cli' ? 'Gemini CLI' : 'Antigravity';
|
|
754
|
+
await showToast(`${quotaName} quota exhausted, using ${altQuotaName} quota`, 'warning');
|
|
755
|
+
headerStyle = fallbackStyle;
|
|
756
|
+
pushDebug(`quota fallback: ${headerStyle}`);
|
|
757
|
+
}
|
|
758
|
+
else {
|
|
759
|
+
shouldSwitchAccount = true;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
else {
|
|
763
|
+
shouldSwitchAccount = true;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
let totalCapacityRetries = 0;
|
|
767
|
+
while (!shouldSwitchAccount) {
|
|
768
|
+
let forceThinkingRecovery = false;
|
|
769
|
+
let tokenConsumed = false;
|
|
770
|
+
let capacityRetryCount = 0;
|
|
771
|
+
let lastEndpointIndex = -1;
|
|
772
|
+
for (let i = 0; i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length; i++) {
|
|
773
|
+
if (i !== lastEndpointIndex) {
|
|
774
|
+
capacityRetryCount = 0;
|
|
775
|
+
lastEndpointIndex = i;
|
|
776
|
+
}
|
|
777
|
+
const currentEndpoint = ANTIGRAVITY_ENDPOINT_FALLBACKS[i];
|
|
778
|
+
if (headerStyle === 'gemini-cli' &&
|
|
779
|
+
currentEndpoint !== 'https://cloudcode-pa.googleapis.com') {
|
|
780
|
+
pushDebug(`Skipping sandbox endpoint ${currentEndpoint} for gemini-cli headerStyle`);
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
try {
|
|
784
|
+
const prepared = prepareAntigravityRequest(input, init, accessToken, projectContext.effectiveProjectId, currentEndpoint, headerStyle, forceThinkingRecovery, {
|
|
785
|
+
claudeToolHardening: config.claude_tool_hardening,
|
|
786
|
+
claudePromptAutoCaching: config.claude_prompt_auto_caching,
|
|
787
|
+
fingerprint: account.fingerprint,
|
|
788
|
+
agySession: agyRequestSession,
|
|
789
|
+
agyRequestTimestamp: agyRequestScope.timestamp,
|
|
790
|
+
});
|
|
791
|
+
const originalUrl = toUrlString(input);
|
|
792
|
+
const resolvedUrl = toUrlString(prepared.request);
|
|
793
|
+
pushDebug(`endpoint=${currentEndpoint}`);
|
|
794
|
+
pushDebug(`resolved=${resolvedUrl}`);
|
|
795
|
+
const debugContext = startAntigravityDebugRequest({
|
|
796
|
+
originalUrl,
|
|
797
|
+
resolvedUrl,
|
|
798
|
+
method: prepared.init.method,
|
|
799
|
+
headers: prepared.init.headers,
|
|
800
|
+
body: prepared.init.body,
|
|
801
|
+
streaming: prepared.streaming,
|
|
802
|
+
projectId: projectContext.effectiveProjectId,
|
|
803
|
+
});
|
|
804
|
+
const dumpContext = dumpGeminiRequest({
|
|
805
|
+
originalUrl,
|
|
806
|
+
resolvedUrl,
|
|
807
|
+
method: prepared.init.method,
|
|
808
|
+
headers: prepared.init.headers,
|
|
809
|
+
body: prepared.init.body,
|
|
810
|
+
streaming: prepared.streaming,
|
|
811
|
+
requestedModel: prepared.requestedModel,
|
|
812
|
+
effectiveModel: prepared.effectiveModel,
|
|
813
|
+
sessionId: prepared.sessionId,
|
|
814
|
+
projectId: projectContext.effectiveProjectId,
|
|
815
|
+
});
|
|
816
|
+
const createFailureContext = (failureResponse) => ({
|
|
817
|
+
response: failureResponse,
|
|
818
|
+
streaming: prepared.streaming,
|
|
819
|
+
debugContext,
|
|
820
|
+
requestedModel: prepared.requestedModel,
|
|
821
|
+
projectId: prepared.projectId,
|
|
822
|
+
endpoint: prepared.endpoint,
|
|
823
|
+
effectiveModel: prepared.effectiveModel,
|
|
824
|
+
sessionId: prepared.sessionId,
|
|
825
|
+
toolDebugMissing: prepared.toolDebugMissing,
|
|
826
|
+
toolDebugSummary: prepared.toolDebugSummary,
|
|
827
|
+
toolDebugPayload: prepared.toolDebugPayload,
|
|
828
|
+
dumpContext,
|
|
829
|
+
});
|
|
830
|
+
await runThinkingWarmup(prepared, projectContext.effectiveProjectId);
|
|
831
|
+
await runCacheWarmupProbe(prepared);
|
|
832
|
+
if (config.request_jitter_max_ms > 0) {
|
|
833
|
+
const jitterMs = Math.floor(Math.random() * config.request_jitter_max_ms);
|
|
834
|
+
if (jitterMs > 0) {
|
|
835
|
+
await sleep(jitterMs, abortSignal);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
if (config.account_selection_strategy === 'hybrid') {
|
|
839
|
+
tokenConsumed = getTokenTracker().consume(account.index);
|
|
840
|
+
}
|
|
841
|
+
pushDebug(`dispatching request via ${prepared.headerStyle} transport`);
|
|
842
|
+
const response = prepared.headerStyle === 'antigravity'
|
|
843
|
+
? await transport(toUrlString(prepared.request), prepared.init, { signal: abortSignal, onDebug: pushDebug })
|
|
844
|
+
: await upstreamFetch(prepared.request, prepared.init);
|
|
845
|
+
apiRequestCount++;
|
|
846
|
+
accountManager.recordRequest(account.index, family);
|
|
847
|
+
const requestCounts = accountManager.getDailyRequestCounts(account.index);
|
|
848
|
+
if (requestCounts) {
|
|
849
|
+
pushDebug(`[Quota] account=${account.index} ${family}_today=${requestCounts[family]} total_${family}_today=${accountManager.getTotalDailyRequests(family)}`);
|
|
850
|
+
}
|
|
851
|
+
pushDebug(`status=${response.status} ${response.statusText} (api_request #${apiRequestCount})`);
|
|
852
|
+
noteGeminiDumpResponse(dumpContext, response);
|
|
853
|
+
// Record the final route selection so the sidebar renders the
|
|
854
|
+
// actual account/header-style used by this request. Fire-and-
|
|
855
|
+
// forget — the dispatch path must not wait on a state write.
|
|
856
|
+
const sessionKey = requestSessionIdentity.sessionId;
|
|
857
|
+
if (sessionKey) {
|
|
858
|
+
const routingEntry = {
|
|
859
|
+
accountId: `acct-${account.index}`,
|
|
860
|
+
modelFamily: family,
|
|
861
|
+
headerStyle: prepared.headerStyle,
|
|
862
|
+
strategy: config.account_selection_strategy,
|
|
863
|
+
updatedAt: Date.now(),
|
|
864
|
+
};
|
|
865
|
+
void upsertSidebarActiveRouting(sessionKey, routingEntry, {
|
|
866
|
+
authoritative: true,
|
|
867
|
+
}).catch((error) => {
|
|
868
|
+
log.debug('sidebar-routing-upsert-failed', {
|
|
869
|
+
sessionId: sessionKey,
|
|
870
|
+
error: String(error),
|
|
871
|
+
});
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
if (response.status === 429 ||
|
|
875
|
+
response.status === 503 ||
|
|
876
|
+
response.status === 529) {
|
|
877
|
+
if (tokenConsumed) {
|
|
878
|
+
getTokenTracker().refund(account.index);
|
|
879
|
+
tokenConsumed = false;
|
|
880
|
+
}
|
|
881
|
+
const defaultRetryMs = (config.default_retry_after_seconds ?? 60) * 1000;
|
|
882
|
+
const _maxBackoffMs = (config.max_backoff_seconds ?? 60) * 1000;
|
|
883
|
+
const headerRetryMs = retryAfterMsFromResponse(response, defaultRetryMs);
|
|
884
|
+
const bodyInfo = await (async () => {
|
|
885
|
+
try {
|
|
886
|
+
const text = await response.clone().text();
|
|
887
|
+
try {
|
|
888
|
+
return JSON.parse(text);
|
|
889
|
+
}
|
|
890
|
+
catch {
|
|
891
|
+
return null;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
catch {
|
|
895
|
+
return null;
|
|
896
|
+
}
|
|
897
|
+
})();
|
|
898
|
+
const reasonInfo = bodyInfo
|
|
899
|
+
? extractRateLimitBodyInfo(bodyInfo)
|
|
900
|
+
: { retryDelayMs: null };
|
|
901
|
+
const serverRetryMs = reasonInfo.retryDelayMs ?? headerRetryMs;
|
|
902
|
+
const rateLimitReason = parseRateLimitReason(reasonInfo.reason, reasonInfo.message, response.status);
|
|
903
|
+
if (rateLimitReason === 'MODEL_CAPACITY_EXHAUSTED' ||
|
|
904
|
+
rateLimitReason === 'SERVER_ERROR') {
|
|
905
|
+
totalCapacityRetries++;
|
|
906
|
+
if (isCapacityRetryBudgetExhausted(totalCapacityRetries)) {
|
|
907
|
+
pushDebug(`Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`);
|
|
908
|
+
lastFailure = createFailureContext(response);
|
|
909
|
+
shouldSwitchAccount = true;
|
|
910
|
+
break;
|
|
911
|
+
}
|
|
912
|
+
const baseDelayMs = 1000;
|
|
913
|
+
const maxDelayMs = 8000;
|
|
914
|
+
const exponentialDelay = Math.min(baseDelayMs * 2 ** capacityRetryCount, maxDelayMs);
|
|
915
|
+
const jitter = exponentialDelay * (0.9 + Math.random() * 0.2);
|
|
916
|
+
const waitMs = Math.round(jitter);
|
|
917
|
+
const waitSec = Math.round(waitMs / 1000);
|
|
918
|
+
pushDebug(`Server busy (${rateLimitReason}) on account ${account.index}, exponential backoff ${waitMs}ms (attempt ${capacityRetryCount + 1}, total ${totalCapacityRetries}/${MAX_TOTAL_CAPACITY_RETRIES})`);
|
|
919
|
+
await showToast(`⏳ Server busy (${response.status}). Retrying in ${waitSec}s...`, 'warning');
|
|
920
|
+
await sleep(waitMs, abortSignal);
|
|
921
|
+
if (capacityRetryCount < 1) {
|
|
922
|
+
capacityRetryCount++;
|
|
923
|
+
i -= 1;
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
926
|
+
else {
|
|
927
|
+
pushDebug(`Max capacity retries (1) exhausted for endpoint ${currentEndpoint}, regenerating fingerprint...`);
|
|
928
|
+
const newFingerprint = accountManager.regenerateAccountFingerprint(account.index);
|
|
929
|
+
if (newFingerprint) {
|
|
930
|
+
pushDebug(`Fingerprint regenerated for account ${account.index}`);
|
|
931
|
+
}
|
|
932
|
+
continue;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
const quotaKey = retryState.headerStyleToQuotaKey(headerStyle, family);
|
|
936
|
+
const backoff = retryState.getRateLimitBackoff(account.index, quotaKey, serverRetryMs);
|
|
937
|
+
const smartBackoffMs = calculateBackoffMs(rateLimitReason, account.consecutiveFailures ?? 0, serverRetryMs);
|
|
938
|
+
const effectiveDelayMs = Math.max(backoff.delayMs, smartBackoffMs);
|
|
939
|
+
pushDebug(`429 idx=${account.index} email=${account.email ?? ''} family=${family} delayMs=${effectiveDelayMs} attempt=${backoff.attempt} reason=${rateLimitReason}`);
|
|
940
|
+
if (reasonInfo.message)
|
|
941
|
+
pushDebug(`429 message=${reasonInfo.message}`);
|
|
942
|
+
if (reasonInfo.quotaResetTime)
|
|
943
|
+
pushDebug(`429 quotaResetTime=${reasonInfo.quotaResetTime}`);
|
|
944
|
+
if (reasonInfo.reason)
|
|
945
|
+
pushDebug(`429 reason=${reasonInfo.reason}`);
|
|
946
|
+
logRateLimitEvent(account.index, account.email, family, response.status, effectiveDelayMs, reasonInfo);
|
|
947
|
+
await logResponseBody(debugContext, response, 429);
|
|
948
|
+
getHealthTracker().recordRateLimit(account.index);
|
|
949
|
+
const _accountLabel = account.email || `Account ${account.index + 1}`;
|
|
950
|
+
if (backoff.attempt === 1 &&
|
|
951
|
+
rateLimitReason !== 'QUOTA_EXHAUSTED') {
|
|
952
|
+
await showToast(`Rate limited. Quick retry in 1s...`, 'warning');
|
|
953
|
+
await sleep(FIRST_RETRY_DELAY_MS, abortSignal);
|
|
954
|
+
if (config.scheduling_mode === 'cache_first') {
|
|
955
|
+
const maxCacheFirstWaitMs = config.max_cache_first_wait_seconds * 1000;
|
|
956
|
+
if (effectiveDelayMs <= maxCacheFirstWaitMs) {
|
|
957
|
+
pushDebug(`cache_first: waiting ${effectiveDelayMs}ms for same account to recover`);
|
|
958
|
+
await showToast(`⏳ Waiting ${Math.ceil(effectiveDelayMs / 1000)}s for same account (prompt cache preserved)...`, 'info');
|
|
959
|
+
accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs);
|
|
960
|
+
await sleep(effectiveDelayMs, abortSignal);
|
|
961
|
+
i -= 1;
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
pushDebug(`cache_first: wait ${effectiveDelayMs}ms exceeds max ${maxCacheFirstWaitMs}ms, switching account`);
|
|
965
|
+
}
|
|
966
|
+
if (config.switch_on_first_rate_limit && accountCount > 1) {
|
|
967
|
+
accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs, config.failure_ttl_seconds * 1000);
|
|
968
|
+
shouldSwitchAccount = true;
|
|
969
|
+
break;
|
|
970
|
+
}
|
|
971
|
+
i -= 1;
|
|
972
|
+
continue;
|
|
973
|
+
}
|
|
974
|
+
accountManager.markRateLimitedWithReason(account, family, headerStyle, model, rateLimitReason, serverRetryMs, config.failure_ttl_seconds * 1000);
|
|
975
|
+
accountManager.requestSaveToDisk();
|
|
976
|
+
const switchAccountDelayMs = config.switch_account_delay_ms ?? 500;
|
|
977
|
+
if (family === 'gemini') {
|
|
978
|
+
if (headerStyle === 'antigravity') {
|
|
979
|
+
if (hasOtherAccountWithAntigravity(account)) {
|
|
980
|
+
pushDebug(`antigravity exhausted on account ${account.index}, but available on others. Switching account.`);
|
|
981
|
+
await showToast(`Rate limited again. Switching account in ${formatWaitTime(switchAccountDelayMs)}...`, 'warning');
|
|
982
|
+
await sleep(switchAccountDelayMs, abortSignal);
|
|
983
|
+
shouldSwitchAccount = true;
|
|
984
|
+
break;
|
|
985
|
+
}
|
|
986
|
+
if (allowQuotaFallback) {
|
|
987
|
+
const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
|
|
988
|
+
const fallbackStyle = resolveQuotaFallbackHeaderStyle({
|
|
989
|
+
family,
|
|
990
|
+
headerStyle,
|
|
991
|
+
alternateStyle,
|
|
992
|
+
});
|
|
993
|
+
if (fallbackStyle) {
|
|
994
|
+
const safeModelName = model || 'this model';
|
|
995
|
+
await showToast(`Antigravity quota exhausted for ${safeModelName}. Switching to Gemini CLI quota...`, 'warning');
|
|
996
|
+
headerStyle = fallbackStyle;
|
|
997
|
+
pushDebug(`quota fallback: ${headerStyle}`);
|
|
998
|
+
continue;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
else if (headerStyle === 'gemini-cli') {
|
|
1003
|
+
if (allowQuotaFallback) {
|
|
1004
|
+
const alternateStyle = accountManager.getAvailableHeaderStyle(account, family, model);
|
|
1005
|
+
const fallbackStyle = resolveQuotaFallbackHeaderStyle({
|
|
1006
|
+
family,
|
|
1007
|
+
headerStyle,
|
|
1008
|
+
alternateStyle,
|
|
1009
|
+
});
|
|
1010
|
+
if (fallbackStyle) {
|
|
1011
|
+
const safeModelName = model || 'this model';
|
|
1012
|
+
await showToast(`Gemini CLI quota exhausted for ${safeModelName}. Switching to Antigravity quota...`, 'warning');
|
|
1013
|
+
headerStyle = fallbackStyle;
|
|
1014
|
+
pushDebug(`quota fallback: ${headerStyle}`);
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
if (accountCount > 1) {
|
|
1021
|
+
const quotaMsg = reasonInfo.quotaResetTime
|
|
1022
|
+
? ` (quota resets ${reasonInfo.quotaResetTime})`
|
|
1023
|
+
: ``;
|
|
1024
|
+
await showToast(`Rate limited again. Switching account in ${formatWaitTime(switchAccountDelayMs)}...${quotaMsg}`, 'warning');
|
|
1025
|
+
await sleep(switchAccountDelayMs, abortSignal);
|
|
1026
|
+
}
|
|
1027
|
+
else {
|
|
1028
|
+
const expBackoffMs = Math.min(FIRST_RETRY_DELAY_MS * 2 ** (backoff.attempt - 1), 60000);
|
|
1029
|
+
const expBackoffFormatted = expBackoffMs >= 1000
|
|
1030
|
+
? `${Math.round(expBackoffMs / 1000)}s`
|
|
1031
|
+
: `${expBackoffMs}ms`;
|
|
1032
|
+
await showToast(`Rate limited. Retrying in ${expBackoffFormatted} (attempt ${backoff.attempt})...`, 'warning');
|
|
1033
|
+
await sleep(expBackoffMs, abortSignal);
|
|
1034
|
+
}
|
|
1035
|
+
lastFailure = createFailureContext(response);
|
|
1036
|
+
shouldSwitchAccount = true;
|
|
1037
|
+
break;
|
|
1038
|
+
}
|
|
1039
|
+
const quotaKey = retryState.headerStyleToQuotaKey(headerStyle, family);
|
|
1040
|
+
retryState.resetRateLimitState(account.index, quotaKey);
|
|
1041
|
+
retryState.resetAccountFailureState(account.index);
|
|
1042
|
+
if (response.status === 403) {
|
|
1043
|
+
const errorBodyText = await response
|
|
1044
|
+
.clone()
|
|
1045
|
+
.text()
|
|
1046
|
+
.catch(() => '');
|
|
1047
|
+
const extracted = extractAccountAccessErrorDetails(errorBodyText);
|
|
1048
|
+
if (extracted.accountIneligible) {
|
|
1049
|
+
const ineligibleReason = extracted.message ??
|
|
1050
|
+
'Google marked this account as ineligible for Antigravity.';
|
|
1051
|
+
accountManager.markAccountIneligible(account.index, ineligibleReason);
|
|
1052
|
+
const label = account.email || `Account ${account.index + 1}`;
|
|
1053
|
+
if (accountManager.shouldShowAccountToast(account.index, 60000)) {
|
|
1054
|
+
await showToast(`${label} is not eligible for Antigravity and has been disabled. ` +
|
|
1055
|
+
'Recheck it from opencode auth login > Verify accounts.', 'warning');
|
|
1056
|
+
accountManager.markToastShown(account.index);
|
|
1057
|
+
}
|
|
1058
|
+
pushDebug(`account-ineligible: disabled account ${account.index}`);
|
|
1059
|
+
getHealthTracker().recordFailure(account.index);
|
|
1060
|
+
lastFailure = createFailureContext(response);
|
|
1061
|
+
shouldSwitchAccount = true;
|
|
1062
|
+
break;
|
|
1063
|
+
}
|
|
1064
|
+
if (extracted.validationRequired) {
|
|
1065
|
+
const verificationReason = extracted.message ?? 'Google requires account verification.';
|
|
1066
|
+
const cooldownMs = 10 * 60 * 1000;
|
|
1067
|
+
accountManager.markAccountVerificationRequired(account.index, verificationReason, extracted.verifyUrl);
|
|
1068
|
+
accountManager.markAccountCoolingDown(account, cooldownMs, 'validation-required');
|
|
1069
|
+
accountManager.markRateLimited(account, cooldownMs, family, headerStyle, model);
|
|
1070
|
+
const label = account.email || `Account ${account.index + 1}`;
|
|
1071
|
+
if (accountManager.shouldShowAccountToast(account.index, 60000)) {
|
|
1072
|
+
await showToast(`⚠ ${label} needs verification. Run 'opencode auth login' and use Verify accounts.`, 'warning');
|
|
1073
|
+
accountManager.markToastShown(account.index);
|
|
1074
|
+
}
|
|
1075
|
+
pushDebug(`verification-required: disabled account ${account.index}`);
|
|
1076
|
+
getHealthTracker().recordFailure(account.index);
|
|
1077
|
+
lastFailure = createFailureContext(response);
|
|
1078
|
+
shouldSwitchAccount = true;
|
|
1079
|
+
break;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
const shouldRetryEndpoint = response.status === 403 ||
|
|
1083
|
+
response.status === 404 ||
|
|
1084
|
+
response.status >= 500;
|
|
1085
|
+
if (shouldRetryEndpoint &&
|
|
1086
|
+
i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
|
|
1087
|
+
await logResponseBody(debugContext, response, response.status);
|
|
1088
|
+
lastFailure = createFailureContext(response);
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
if (response.ok) {
|
|
1092
|
+
account.consecutiveFailures = 0;
|
|
1093
|
+
getHealthTracker().recordSuccess(account.index);
|
|
1094
|
+
accountManager.markAccountUsed(account.index);
|
|
1095
|
+
void triggerAsyncQuotaRefreshForAccount(account.index, config.quota_refresh_interval_minutes);
|
|
1096
|
+
const proactiveThreshold = config.proactive_rotation_threshold_percent ?? 20;
|
|
1097
|
+
if (proactiveThreshold > 0 &&
|
|
1098
|
+
accountManager.shouldProactivelyRotate(family, model, proactiveThreshold, softQuotaCacheTtlMs, accountSessionIdentity)) {
|
|
1099
|
+
const rotated = accountManager.proactivelyRotateForFamily(family, model, headerStyle, config.soft_quota_threshold_percent, softQuotaCacheTtlMs, accountSessionIdentity);
|
|
1100
|
+
if (rotated) {
|
|
1101
|
+
const remaining = account.cachedQuota?.[resolveQuotaGroup(family, model)]
|
|
1102
|
+
?.remainingFraction;
|
|
1103
|
+
const remainingPct = remaining != null ? `${(remaining * 100).toFixed(1)}%` : '?';
|
|
1104
|
+
pushDebug(`[ProactiveRotation] account ${account.index} quota ${remainingPct} < ${proactiveThreshold}%, pre-switched to account ${rotated.index} for next request`);
|
|
1105
|
+
pushDebug(`[ProactiveRotation] ${account.index} → ${rotated.index}` +
|
|
1106
|
+
` (warm=${accountManager.wasUsedInSession(rotated.index, accountSessionIdentity)})`);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
logAntigravityDebugResponse(debugContext, response, {
|
|
1111
|
+
note: response.ok ? 'Success' : `Error ${response.status}`,
|
|
1112
|
+
});
|
|
1113
|
+
if (response.ok && !prepared.streaming) {
|
|
1114
|
+
await logResponseBody(debugContext, response, response.status);
|
|
1115
|
+
}
|
|
1116
|
+
if (!response.ok) {
|
|
1117
|
+
await logResponseBody(debugContext, response, response.status);
|
|
1118
|
+
if (response.status === 400) {
|
|
1119
|
+
const cloned = response.clone();
|
|
1120
|
+
const bodyText = await cloned.text();
|
|
1121
|
+
if (bodyText.includes('Prompt is too long') ||
|
|
1122
|
+
bodyText.includes('prompt_too_long')) {
|
|
1123
|
+
await showToast('Context too long - use /compact to reduce size', 'warning');
|
|
1124
|
+
const errorMessage = `[Antigravity Error] Context is too long for this model.\n\nPlease use /compact to reduce context size, then retry your request.\n\nAlternatively, you can:\n- Use /clear to start fresh\n- Use /undo to remove recent messages\n- Switch to a model with larger context window`;
|
|
1125
|
+
return createSyntheticErrorResponse(errorMessage, prepared.requestedModel);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
if (response.ok && !prepared.streaming) {
|
|
1130
|
+
const maxAttempts = config.empty_response_max_attempts ?? 4;
|
|
1131
|
+
const retryDelayMs = config.empty_response_retry_delay_ms ?? 2000;
|
|
1132
|
+
const clonedForCheck = response.clone();
|
|
1133
|
+
const bodyText = await clonedForCheck.text();
|
|
1134
|
+
if (isEmptyResponseBody(bodyText)) {
|
|
1135
|
+
const emptyAttemptKey = `${prepared.sessionId ?? 'none'}:${prepared.effectiveModel ?? 'unknown'}`;
|
|
1136
|
+
const currentAttempts = retryState.recordEmptyResponseAttempt(emptyAttemptKey);
|
|
1137
|
+
pushDebug(`empty-response: attempt ${currentAttempts}/${maxAttempts}`);
|
|
1138
|
+
if (currentAttempts < maxAttempts) {
|
|
1139
|
+
await showToast(`Empty response received. Retrying (${currentAttempts}/${maxAttempts})...`, 'warning');
|
|
1140
|
+
await sleep(retryDelayMs, abortSignal);
|
|
1141
|
+
continue;
|
|
1142
|
+
}
|
|
1143
|
+
retryState.clearEmptyResponseAttempts();
|
|
1144
|
+
return createSyntheticErrorResponse(`Empty response after ${currentAttempts} attempts for model ${prepared.effectiveModel ?? 'unknown'}.`, prepared.effectiveModel ?? 'unknown');
|
|
1145
|
+
}
|
|
1146
|
+
const _emptyAttemptKeyClean = `${prepared.sessionId ?? 'none'}:${prepared.effectiveModel ?? 'unknown'}`;
|
|
1147
|
+
retryState.clearEmptyResponseAttempts();
|
|
1148
|
+
}
|
|
1149
|
+
const transformedResponse = await transformAntigravityResponse(response, prepared.streaming, debugContext, prepared.requestedModel, prepared.projectId, prepared.endpoint, prepared.effectiveModel, prepared.sessionId, prepared.toolDebugMissing, prepared.toolDebugSummary, prepared.toolDebugPayload, debugLines, dumpContext);
|
|
1150
|
+
const contextError = transformedResponse.headers.get('x-antigravity-context-error');
|
|
1151
|
+
if (contextError) {
|
|
1152
|
+
if (contextError === 'prompt_too_long') {
|
|
1153
|
+
await showToast('Context too long - use /compact to reduce size, or trim your request', 'warning');
|
|
1154
|
+
}
|
|
1155
|
+
else if (contextError === 'tool_pairing') {
|
|
1156
|
+
await showToast('Tool call/result mismatch - use /compact to fix, or /undo last message', 'warning');
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
if (apiRequestCount > 1) {
|
|
1160
|
+
pushDebug(`[Quota] Total API requests for this user message: ${apiRequestCount} (${apiRequestCount - 1} retries)`);
|
|
1161
|
+
}
|
|
1162
|
+
const dailyCounts = accountManager.getDailyRequestCounts(account.index);
|
|
1163
|
+
if (dailyCounts) {
|
|
1164
|
+
pushDebug(`[Quota] Account ${account.index} (${account.email ?? 'unknown'}) today: claude=${dailyCounts.claude} gemini=${dailyCounts.gemini}`);
|
|
1165
|
+
}
|
|
1166
|
+
const totalToday = accountManager.getTotalDailyRequests(family);
|
|
1167
|
+
pushDebug(`[Quota] Total ${family} requests today (all accounts): ${totalToday}`);
|
|
1168
|
+
const cachedQuota = account.cachedQuota;
|
|
1169
|
+
if (cachedQuota) {
|
|
1170
|
+
const quotaFamily = resolveQuotaGroup(family, model);
|
|
1171
|
+
const groupQuota = cachedQuota[quotaFamily];
|
|
1172
|
+
if (groupQuota?.remainingFraction != null) {
|
|
1173
|
+
const pct = Math.round(groupQuota.remainingFraction * 100);
|
|
1174
|
+
pushDebug(`[Quota] Account ${account.index} cached ${quotaFamily} remaining: ${pct}%${groupQuota.resetTime ? ` (resets ${groupQuota.resetTime})` : ''}`);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
const sessionSummary = accountManager.getSessionSummary();
|
|
1178
|
+
if (sessionSummary.durationMinutes >= 1) {
|
|
1179
|
+
const familyTotal = family === 'claude'
|
|
1180
|
+
? sessionSummary.totalClaude
|
|
1181
|
+
: sessionSummary.totalGemini;
|
|
1182
|
+
if (familyTotal > 0) {
|
|
1183
|
+
const ratePerHour = sessionSummary.requestsPerHour;
|
|
1184
|
+
pushDebug(`[Quota] Session: ${sessionSummary.durationMinutes}min, ${familyTotal} ${family} reqs, ~${ratePerHour} reqs/hr, ${sessionSummary.accountsUsed} accounts used`);
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
return transformedResponse;
|
|
1188
|
+
}
|
|
1189
|
+
catch (error) {
|
|
1190
|
+
if (tokenConsumed) {
|
|
1191
|
+
getTokenTracker().refund(account.index);
|
|
1192
|
+
tokenConsumed = false;
|
|
1193
|
+
}
|
|
1194
|
+
if (error instanceof Error &&
|
|
1195
|
+
error.message === 'THINKING_RECOVERY_NEEDED') {
|
|
1196
|
+
if (!forceThinkingRecovery) {
|
|
1197
|
+
pushDebug('thinking-recovery: API error detected, retrying with forced recovery');
|
|
1198
|
+
forceThinkingRecovery = true;
|
|
1199
|
+
i = -1;
|
|
1200
|
+
continue;
|
|
1201
|
+
}
|
|
1202
|
+
const recoveryError = error;
|
|
1203
|
+
const originalError = recoveryError.originalError || {
|
|
1204
|
+
error: { message: 'Thinking recovery triggered' },
|
|
1205
|
+
};
|
|
1206
|
+
const recoveryMessage = `${originalError.error?.message || 'Session recovery failed'}\n\n[RECOVERY] Thinking block corruption could not be resolved. Try starting a new session.`;
|
|
1207
|
+
return new Response(JSON.stringify({
|
|
1208
|
+
type: 'error',
|
|
1209
|
+
error: {
|
|
1210
|
+
type: 'unrecoverable_error',
|
|
1211
|
+
message: recoveryMessage,
|
|
1212
|
+
},
|
|
1213
|
+
}), {
|
|
1214
|
+
status: 400,
|
|
1215
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
if (i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
|
|
1219
|
+
lastError =
|
|
1220
|
+
error instanceof Error ? error : new Error(String(error));
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
const { failures, shouldCooldown, cooldownMs } = retryState.trackAccountFailure(account.index);
|
|
1224
|
+
lastError =
|
|
1225
|
+
error instanceof Error ? error : new Error(String(error));
|
|
1226
|
+
if (shouldCooldown) {
|
|
1227
|
+
accountManager.markAccountCoolingDown(account, cooldownMs, 'network-error');
|
|
1228
|
+
accountManager.markRateLimited(account, cooldownMs, family, headerStyle, model);
|
|
1229
|
+
pushDebug(`endpoint-error: cooldown ${cooldownMs}ms after ${failures} failures`);
|
|
1230
|
+
}
|
|
1231
|
+
shouldSwitchAccount = true;
|
|
1232
|
+
break;
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
if (shouldSwitchAccount) {
|
|
1237
|
+
accountSwitchCount++;
|
|
1238
|
+
if (accountSwitchCount > maxAccountSwitches) {
|
|
1239
|
+
pushDebug(`account-switch-cap: exceeded max_account_switches=${maxAccountSwitches}, giving up`);
|
|
1240
|
+
if (lastFailure) {
|
|
1241
|
+
return transformAntigravityResponse(lastFailure.response, lastFailure.streaming, lastFailure.debugContext, lastFailure.requestedModel, lastFailure.projectId, lastFailure.endpoint, lastFailure.effectiveModel, lastFailure.sessionId, lastFailure.toolDebugMissing, lastFailure.toolDebugSummary, lastFailure.toolDebugPayload, debugLines, lastFailure.dumpContext);
|
|
1242
|
+
}
|
|
1243
|
+
return createSyntheticErrorResponse(lastError?.message ||
|
|
1244
|
+
`Exceeded max account switches (${maxAccountSwitches}). All accounts rate-limited.`, model ?? 'unknown');
|
|
1245
|
+
}
|
|
1246
|
+
if (accountCount <= 1) {
|
|
1247
|
+
if (lastFailure) {
|
|
1248
|
+
return transformAntigravityResponse(lastFailure.response, lastFailure.streaming, lastFailure.debugContext, lastFailure.requestedModel, lastFailure.projectId, lastFailure.endpoint, lastFailure.effectiveModel, lastFailure.sessionId, lastFailure.toolDebugMissing, lastFailure.toolDebugSummary, lastFailure.toolDebugPayload, debugLines, lastFailure.dumpContext);
|
|
1249
|
+
}
|
|
1250
|
+
return createSyntheticErrorResponse(lastError?.message || 'All Antigravity endpoints failed', model ?? 'unknown');
|
|
1251
|
+
}
|
|
1252
|
+
continue;
|
|
1253
|
+
}
|
|
1254
|
+
if (lastFailure) {
|
|
1255
|
+
return transformAntigravityResponse(lastFailure.response, lastFailure.streaming, lastFailure.debugContext, lastFailure.requestedModel, lastFailure.projectId, lastFailure.endpoint, lastFailure.effectiveModel, lastFailure.sessionId, lastFailure.toolDebugMissing, lastFailure.toolDebugSummary, lastFailure.toolDebugPayload, debugLines, lastFailure.dumpContext);
|
|
1256
|
+
}
|
|
1257
|
+
return createSyntheticErrorResponse(lastError?.message || 'All Antigravity accounts failed', model ?? 'unknown');
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
function dispose() {
|
|
1261
|
+
if (disposed)
|
|
1262
|
+
return;
|
|
1263
|
+
disposed = true;
|
|
1264
|
+
retryState.dispose();
|
|
1265
|
+
warmupState.dispose();
|
|
1266
|
+
}
|
|
1267
|
+
return { fetch, dispose };
|
|
1268
|
+
}
|
|
1269
|
+
function extractRateLimitBodyInfo(body) {
|
|
1270
|
+
if (!body || typeof body !== 'object')
|
|
1271
|
+
return { retryDelayMs: null };
|
|
1272
|
+
const error = body.error;
|
|
1273
|
+
const message = error && typeof error === 'object'
|
|
1274
|
+
? error.message
|
|
1275
|
+
: undefined;
|
|
1276
|
+
const details = error && typeof error === 'object'
|
|
1277
|
+
? error.details
|
|
1278
|
+
: undefined;
|
|
1279
|
+
let reason;
|
|
1280
|
+
if (Array.isArray(details)) {
|
|
1281
|
+
for (const detail of details) {
|
|
1282
|
+
if (!detail || typeof detail !== 'object')
|
|
1283
|
+
continue;
|
|
1284
|
+
const type = detail['@type'];
|
|
1285
|
+
if (typeof type === 'string' && type.includes('google.rpc.ErrorInfo')) {
|
|
1286
|
+
const detailReason = detail.reason;
|
|
1287
|
+
if (typeof detailReason === 'string') {
|
|
1288
|
+
reason = detailReason;
|
|
1289
|
+
break;
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
for (const detail of details) {
|
|
1294
|
+
if (!detail || typeof detail !== 'object')
|
|
1295
|
+
continue;
|
|
1296
|
+
const type = detail['@type'];
|
|
1297
|
+
if (typeof type === 'string' && type.includes('google.rpc.RetryInfo')) {
|
|
1298
|
+
const retryDelay = detail.retryDelay;
|
|
1299
|
+
if (typeof retryDelay === 'string') {
|
|
1300
|
+
const retryDelayMs = parseDurationToMs(retryDelay);
|
|
1301
|
+
if (retryDelayMs !== null) {
|
|
1302
|
+
return { retryDelayMs, message, reason };
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
for (const detail of details) {
|
|
1308
|
+
if (!detail || typeof detail !== 'object')
|
|
1309
|
+
continue;
|
|
1310
|
+
const metadata = detail
|
|
1311
|
+
.metadata;
|
|
1312
|
+
if (metadata && typeof metadata === 'object') {
|
|
1313
|
+
const quotaResetDelay = metadata.quotaResetDelay;
|
|
1314
|
+
const quotaResetTime = metadata.quotaResetTimeStamp;
|
|
1315
|
+
if (typeof quotaResetDelay === 'string') {
|
|
1316
|
+
const quotaResetDelayMs = parseDurationToMs(quotaResetDelay);
|
|
1317
|
+
if (quotaResetDelayMs !== null) {
|
|
1318
|
+
return {
|
|
1319
|
+
retryDelayMs: quotaResetDelayMs,
|
|
1320
|
+
message,
|
|
1321
|
+
quotaResetTime,
|
|
1322
|
+
reason,
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
if (message) {
|
|
1330
|
+
const afterMatch = message.match(/reset after\s+([0-9hms.]+)/i);
|
|
1331
|
+
const rawDuration = afterMatch?.[1];
|
|
1332
|
+
if (rawDuration) {
|
|
1333
|
+
const parsed = parseDurationToMs(rawDuration);
|
|
1334
|
+
if (parsed !== null) {
|
|
1335
|
+
return { retryDelayMs: parsed, message, reason };
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
return { retryDelayMs: null, message, reason };
|
|
1340
|
+
}
|
|
1341
|
+
function parseDurationToMs(duration) {
|
|
1342
|
+
const simpleMatch = duration.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/i);
|
|
1343
|
+
if (simpleMatch) {
|
|
1344
|
+
const value = parseFloat(simpleMatch[1]);
|
|
1345
|
+
const unit = (simpleMatch[2] || 's').toLowerCase();
|
|
1346
|
+
switch (unit) {
|
|
1347
|
+
case 'h':
|
|
1348
|
+
return value * 3600 * 1000;
|
|
1349
|
+
case 'm':
|
|
1350
|
+
return value * 60 * 1000;
|
|
1351
|
+
case 's':
|
|
1352
|
+
return value * 1000;
|
|
1353
|
+
case 'ms':
|
|
1354
|
+
return value;
|
|
1355
|
+
default:
|
|
1356
|
+
return value * 1000;
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
const compoundRegex = /(\d+(?:\.\d+)?)(h|m(?!s)|s|ms)/gi;
|
|
1360
|
+
let totalMs = 0;
|
|
1361
|
+
let matchFound = false;
|
|
1362
|
+
let match = null;
|
|
1363
|
+
while (true) {
|
|
1364
|
+
match = compoundRegex.exec(duration);
|
|
1365
|
+
if (match === null)
|
|
1366
|
+
break;
|
|
1367
|
+
matchFound = true;
|
|
1368
|
+
const value = parseFloat(match[1]);
|
|
1369
|
+
const unit = match[2]?.toLowerCase();
|
|
1370
|
+
switch (unit) {
|
|
1371
|
+
case 'h':
|
|
1372
|
+
totalMs += value * 3600 * 1000;
|
|
1373
|
+
break;
|
|
1374
|
+
case 'm':
|
|
1375
|
+
totalMs += value * 60 * 1000;
|
|
1376
|
+
break;
|
|
1377
|
+
case 's':
|
|
1378
|
+
totalMs += value * 1000;
|
|
1379
|
+
break;
|
|
1380
|
+
case 'ms':
|
|
1381
|
+
totalMs += value;
|
|
1382
|
+
break;
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
return matchFound ? totalMs : null;
|
|
1386
|
+
}
|
|
1387
|
+
//# sourceMappingURL=fetch-interceptor.js.map
|