Skip to content

Commit d1453c9

Browse files
committed
docs: add architecture and structure guides
1 parent f5bc836 commit d1453c9

2 files changed

Lines changed: 201 additions & 0 deletions

File tree

ARCHITECTURE.md

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
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.

STRUCTURE.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Codebase Structure
2+
3+
## Directory Layout
4+
5+
```
6+
antigravity-auth/
7+
├── packages/
8+
│ ├── core/ # Harness-agnostic core logic
9+
│ ├── opencode/ # OpenCode integration plugin wrapper
10+
│ └── pi/ # Pi coding agent extension wrapper
11+
├── scripts/ # Build and release utility scripts
12+
└── package.json # Root monorepo configuration
13+
```
14+
15+
## Directory Purposes
16+
17+
**`packages/core`:**
18+
- Purpose: Provides harness-agnostic utilities for Google Antigravity integrations.
19+
- Contains: Direct TCP/TLS socket transport, Google OAuth PKCE auth flow, Google Cloud project bootstrapping, Claude and Gemini request/response transforms, device fingerprint generators, and centralized model registries.
20+
- Key files: `packages/core/src/agy-transport.ts` (TCP/TLS socket), `packages/core/src/project.ts` (project resolution), `packages/core/src/transform/model-resolver.ts` (model mapping).
21+
22+
**`packages/opencode`:**
23+
- Purpose: Integrates the Antigravity authentication and request transformation logic into the OpenCode host environment.
24+
- Contains: Fetch interceptors, account managers, interactive CLI authorization menus, signature caching, and session error recovery hooks.
25+
- Key files: `packages/opencode/src/plugin.ts` (main orchestrator), `packages/opencode/src/plugin/accounts.ts` (AccountManager), `packages/opencode/src/plugin/config/schema.ts` (Zod schema).
26+
27+
**`packages/pi`:**
28+
- Purpose: Bridges the Antigravity core library into the Pi coding agent environment as a custom provider extension.
29+
- Contains: Pi-compatible authorization flow handlers and streaming translators.
30+
- Key files: `packages/pi/src/index.ts` (provider setup), `packages/pi/src/stream.ts` (stream mapping).
31+
32+
## Key File Locations
33+
34+
**Entry Points:**
35+
- `packages/core/src/index.ts`: Harness-agnostic library exports.
36+
- `packages/opencode/index.ts`: OpenCode plugin package entry.
37+
- `packages/pi/src/index.ts`: Pi extension provider entry.
38+
39+
**Configuration:**
40+
- `packages/opencode/src/plugin/config/schema.ts`: OpenCode Zod runtime configuration schema.
41+
42+
**Core Logic:**
43+
- `packages/core/src/agy-transport.ts`: Custom TCP/TLS transport socket implementation.
44+
- `packages/core/src/project.ts`: Project resolution, context loading, and GCP project provisioning.
45+
- `packages/core/src/transform/cross-model-sanitizer.ts`: Payload cleanup when switching model families.
46+
- `packages/opencode/src/plugin/accounts.ts`: Multi-account selection, rotation, metrics, and health scores.
47+
48+
**Tests:**
49+
- `packages/core/src/**/*.test.ts`: Unit tests for core transport, models, and transforms.
50+
- `packages/opencode/src/**/*.test.ts`: OpenCode account manager, UI elements, and config validations.
51+
- `packages/pi/src/**/*.test.ts`: Pi converters and cache helpers.
52+
53+
## Naming Conventions
54+
55+
**Files:** `kebab-case.ts` — e.g., `model-resolver.ts`
56+
**Directories:** `kebab-case/` — e.g., `auto-update-checker/`
57+
**Types/Interfaces:** `PascalCase` — e.g., `AccountManager`, `AntigravityConfig`
58+
**Functions:** `camelCase` — e.g., `resolveModelWithTier`
59+
**Constants:** `UPPER_SNAKE_CASE` — e.g., `ANTIGRAVITY_ENDPOINT`
60+
61+
## Where to Add New Code
62+
63+
**New shared core logic / transport rule:** `packages/core/src/` — create helper module or edit existing transport/auth managers.
64+
**New model transform / payload filter:** `packages/core/src/transform/` — add custom Claude or Gemini schema conversion rules.
65+
**New OpenCode lifecycle hook:** `packages/opencode/src/hooks/[hook-name]/` — register in `packages/opencode/src/plugin.ts`.
66+
**New OpenCode plugin configuration field:** `packages/opencode/src/plugin/config/schema.ts` — extend `AntigravityConfigSchema`.
67+
**New Pi stream handler / message converter:** `packages/pi/src/` — adjust converters in `convert.ts` or mapping logic in `stream.ts`.
68+
**Tests:** Co-locate unit and regression tests alongside code using `*.test.ts`.

0 commit comments

Comments
 (0)