|
| 1 | +# Architecture |
| 2 | + |
| 3 | +## Pattern Overview |
| 4 | + |
| 5 | +**Overall:** Monorepo architecture with a harness-agnostic core & host-specific integration plugins. |
| 6 | + |
| 7 | +**Key Characteristics:** |
| 8 | +- **Shared Agnostic Core:** Consolidates all wire formats, OAuth code exchanges, model configurations, project context resolutions, and Claude/Gemini-specific transformations into the `@cortexkit/antigravity-auth-core` package. |
| 9 | +- **Interception & Extraction:** Translates host-specific formats (e.g. Gemini, Claude) into Google Cloud Code Assist (Antigravity) API envelopes, intercepts network transport levels, and parses downstream SSE response streams to strip metadata and recover signatures. |
| 10 | +- **TCP/TLS Raw Socket Transport:** Outbounds all Antigravity API requests via custom raw TLS sockets (`packages/core/src/agy-transport.ts`) supporting SSL connection racing and corporate HTTP proxy tunneling, bypassing default fetch agents. |
| 11 | +- **Multi-Account State & Cooldowns:** Manages account rotation, rate-limit backoffs (with jitter), token refresh queues, session-scoped account pinning, and secure POSIX permissions within the OpenCode wrapper. |
| 12 | + |
| 13 | +## Layers |
| 14 | + |
| 15 | +**Host Integration Layer (Wrappers):** |
| 16 | +- Purpose: Registers integration points and config/event bindings into target execution environments. |
| 17 | +- Location: `packages/opencode/` and `packages/pi/` |
| 18 | +- Contains: Main plugin interfaces, lifecycle hook listeners, interactive UI menus, and Pi-specific streaming adapters. |
| 19 | +- Depends on: `@cortexkit/antigravity-auth-core` and target client environments (`@opencode-ai/plugin`, `@earendil-works/pi-ai`, `@earendil-works/pi-coding-agent`). |
| 20 | +- Used by: OpenCode editor host and Pi agent runner. |
| 21 | + |
| 22 | +**Multi-Account Management:** |
| 23 | +- Purpose: Rotates OAuth accounts, tracks cooldowns, caches remaining quotas, builds device fingerprints, and monitors storage health. |
| 24 | +- Location: `packages/opencode/src/plugin/accounts.ts`, `packages/opencode/src/plugin/rotation.ts`, `packages/opencode/src/plugin/session-context.ts`, `packages/opencode/src/plugin/fingerprint.ts`, `packages/opencode/src/plugin/auth-doctor.ts` |
| 25 | +- Contains: `AccountManager`, `HealthScoreTracker`, `TokenBucketTracker`, fingerprint generation algorithms, self-healing diagnostic tasks, and daily request tracking counters. |
| 26 | +- Depends on: `@cortexkit/antigravity-auth-core` (for fingerprints, request metadata, auth types, and models). |
| 27 | +- Used by: OpenCode plugin orchestrator (`packages/opencode/src/plugin.ts`). |
| 28 | + |
| 29 | +**Core Authentication & Project Context:** |
| 30 | +- Purpose: Handles Google OAuth flow redirection, PKCE code exchanges, token refreshes, and dynamic GCP project context lookup or provisioning. |
| 31 | +- Location: `packages/core/src/antigravity/oauth.ts`, `packages/core/src/auth.ts`, `packages/core/src/project.ts` |
| 32 | +- Contains: `authorizeAntigravity`, `exchangeAntigravity`, `refreshAntigravityToken`, `ensureProjectContext`, `loadManagedProject`. |
| 33 | +- Depends on: `@openauthjs/openauth` |
| 34 | +- Used by: Account manager modules and Pi authentication hooks. |
| 35 | + |
| 36 | +**Payload Transformation:** |
| 37 | +- Purpose: Resolves client-supplied model names into logical Antigravity identifiers, injects tool description hardening rules, strips Claude thinking blocks, and sanitizes payload fields during model family swaps. |
| 38 | +- Location: `packages/core/src/transform/` and `packages/core/src/model-registry.ts` |
| 39 | +- Contains: `resolveModelWithTier`, `applyClaudeTransforms`, `applyGeminiTransforms`, `sanitizeCrossModelPayload`. |
| 40 | +- Depends on: `packages/core/src/constants.ts` |
| 41 | +- Used by: Host request interceptors and streaming parsers. |
| 42 | + |
| 43 | +**Low-Level Socket Transport:** |
| 44 | +- Purpose: Custom TCP/TLS socket transport for sending serialized HTTP requests directly to Google endpoints, bypassing proxy restrictions or system agents. |
| 45 | +- Location: `packages/core/src/agy-transport.ts` |
| 46 | +- Contains: `fetchWithAgyCliTransport`, SSL racing sockets, chunked decoding streams, and idle-timeout logic. |
| 47 | +- Depends on: Node `net` and `tls` built-ins. |
| 48 | +- Used by: Request pipelines, quota fetches, and project discovery. |
| 49 | + |
| 50 | +## Data Flow |
| 51 | + |
| 52 | +**OpenCode Interception and Request Transformation Pipeline:** |
| 53 | + |
| 54 | +1. Host triggers `loader()` function with client request — `packages/opencode/src/plugin.ts` |
| 55 | +2. `isGenerativeLanguageRequest()` checks if target URL corresponds to googleapis — `packages/opencode/src/plugin/request.ts` |
| 56 | +3. `AccountManager.getCurrentOrNextForFamily()` selects and pins an eligible Google account using model quota, rate limits, and host session identity — `packages/opencode/src/plugin/accounts.ts` |
| 57 | +4. `resolveModelWithTier()` converts user-facing model tag into Antigravity wire model ID — `packages/core/src/transform/model-resolver.ts` |
| 58 | +5. `prepareAntigravityRequest()` sanitizes properties, strips Claude thinking, and appends Claude tool instructions in a strict prefix-stabilized order to optimize prompt caching — `packages/opencode/src/plugin/request.ts` |
| 59 | +6. `buildFingerprintHeaders()` constructs the live-captured AGY CLI identity header — `packages/core/src/fingerprint.ts` |
| 60 | +7. `fetchWithAgyCliTransport()` sends the raw bytes over direct/proxied TLS socket connection — `packages/core/src/agy-transport.ts` |
| 61 | +8. `AccountManager.recordRequest()` registers request metrics and updates daily file counters — `packages/opencode/src/plugin/accounts.ts` |
| 62 | +9. `transformAntigravityResponse()` translates the resulting stream back to the expected Gemini client format — `packages/opencode/src/plugin/request.ts` |
| 63 | +10. Streaming transformer captures SSE tokens, caches signatures, and logs cache-hit rates via `onUsageMetadata` callback — `packages/opencode/src/plugin/core/streaming/transformer.ts` |
| 64 | + |
| 65 | +**Pi Extension Stream Mapping:** |
| 66 | + |
| 67 | +1. Extension triggers the `streamSimple` callback for model generation — `packages/pi/src/stream.ts` |
| 68 | +2. Model parameters are mapped, and cached authorization details are fetched — `packages/pi/src/stream.ts` |
| 69 | +3. `ensureProjectContext()` retrieves or provisions a Code Assist project ID — `packages/core/src/project.ts` |
| 70 | +4. Payload details map to a standard Gemini request structure — `packages/pi/src/convert.ts` |
| 71 | +5. SSE connection is initiated to the Antigravity daily endpoint via custom socket transport — `packages/core/src/agy-transport.ts` |
| 72 | +6. Incoming chunks are unwrapped and parsed into Pi-compatible text and tool-call events — `packages/pi/src/stream.ts` |
| 73 | + |
| 74 | +## Key Abstractions |
| 75 | + |
| 76 | +**`AccountManager`:** |
| 77 | +- Purpose: Stateful manager orchestrating Google accounts, token refreshes, health values, rate limit backoffs, and fingerprint history. |
| 78 | +- Location: `packages/opencode/src/plugin/accounts.ts` |
| 79 | +- Pattern: Selection state machine delegating to `HealthScoreTracker` and `TokenBucketTracker`. |
| 80 | + |
| 81 | +**`AgyRequestSessionStore`:** |
| 82 | +- Purpose: Keeps conversation and trajectory IDs stable per host session while deriving request step metadata from payload parts. |
| 83 | +- Location: `packages/core/src/agy-request-metadata.ts` |
| 84 | +- Pattern: Bounded session-context store shared by OpenCode and Pi; OpenCode hashes the workspace URI for its numeric session ID. |
| 85 | + |
| 86 | +**`fetchWithAgyCliTransport`:** |
| 87 | +- Purpose: Direct TCP/TLS streaming connection agent that replicates the official Google Cloud SDK/agy CLI networking behavior. |
| 88 | +- Location: `packages/core/src/agy-transport.ts` |
| 89 | +- Pattern: Raw socket read-write buffer stream with custom chunked-transfer decoding. |
| 90 | + |
| 91 | +**`ModelResolver` (`resolveModelWithTier`):** |
| 92 | +- Purpose: Maps external AI model tags (e.g. `claude-3-7-sonnet`) into internal Google Antigravity identifiers, specifying thinking budgets and custom header styles. |
| 93 | +- Location: `packages/core/src/transform/model-resolver.ts` |
| 94 | +- Pattern: Regular expression and alias lookup maps. |
| 95 | + |
| 96 | +**`ensureProjectContext`:** |
| 97 | +- Purpose: Automatically initializes, caches, and maintains valid Google Cloud project mappings for standard or enterprise accounts. |
| 98 | +- Location: `packages/core/src/project.ts` |
| 99 | +- Pattern: Async caching proxy with TTL checks and onboard fallback triggers. |
| 100 | + |
| 101 | +**`Cross-Model Sanitizer`:** |
| 102 | +- Purpose: Strips or converts metadata fields that would violate schema expectations when switching between Claude and Gemini model backends. |
| 103 | +- Location: `packages/core/src/transform/cross-model-sanitizer.ts` |
| 104 | +- Pattern: Recursive JSON tree pruning. |
| 105 | + |
| 106 | +## Entry Points |
| 107 | + |
| 108 | +**OpenCode Plugin Entry:** |
| 109 | +- Location: `packages/opencode/index.ts` |
| 110 | +- Triggers: OpenCode loading the package at host startup. |
| 111 | +- Responsibilities: Exposes `createAntigravityPlugin` to initialize interceptors, UI CLI systems, and event channels. |
| 112 | + |
| 113 | +**Pi Extension Entry:** |
| 114 | +- Location: `packages/pi/src/index.ts` |
| 115 | +- Triggers: Pi agent runtime loading extensions. |
| 116 | +- Responsibilities: Registers the "Google Antigravity (CortexKit OAuth)" provider, login menus, credentials refresh hooks, and stream processors. |
| 117 | + |
| 118 | +**Agnostic Core Entry:** |
| 119 | +- Location: `packages/core/src/index.ts` |
| 120 | +- Triggers: Sub-packages importing core libraries. |
| 121 | +- Responsibilities: Exports all shared constants, transforms, transport mechanisms, and OAuth helper functions. |
| 122 | + |
| 123 | +## Error Handling |
| 124 | + |
| 125 | +**Strategy:** Fail closed with active fallback and self-healing. Intercepted request errors (like 429/503) trigger account cooldown penalties and rotate execution to a different account rather than throwing to the client. Storage corruption or auth drift is checked during boot via `AuthDoctor` and self-healed. Invalid or mismatched thinking signatures utilize the `SKIP_THOUGHT_SIGNATURE` sentinel to prevent server-side verification failures. Capacity limits automatically regenerate the device fingerprint history. |
| 126 | + |
| 127 | +## Cross-Cutting Concerns |
| 128 | + |
| 129 | +**Logging:** A unified `createLogger` wrapper maps log records to the OpenCode TUI interface or a file sink (`packages/core/src/logger.ts`). At stream end, request rates, cache hit rates (HIT, MISS, WRITE), and remaining account quota are logged. |
| 130 | + |
| 131 | +**Caching:** Accounts and project identifiers are cached in memory (with TTL) and serialized to disk. Claude thinking block signatures are stored in memory and flushed to a signature cache on disk to persist across sessions (`packages/opencode/src/plugin/cache/signature-cache.ts`). |
| 132 | + |
| 133 | +**Storage:** Account pools are persisted to `antigravity-accounts.json` under the OpenCode/XDG configuration directory using `proper-lockfile` to prevent parallel write conflicts. Sensitive files use mode 0600 and their directories use mode 0700. |
0 commit comments