agy-gateway
v4.0.16
Published
OpenAI and Anthropic compatible HTTP gateway for agy ACP
Downloads
326
Maintainers
Readme
agy-gateway
Stateless HTTP/SSE gateway exposing the local Antigravity ACP server (agy acp) through OpenAI Chat Completions and Anthropic Messages compatible APIs. Built on Pattern C (stateless API surface + ephemeral warm cache + stateless cold fallback).
Architecture
Bridges stateless HTTP clients with the stateful agy acp stdio JSON-RPC 2.0 protocol (@agentclientprotocol/sdk/unstable), reproducing the verified Zed → agy client fingerprint (clientInfo + clientCapabilities). Four routes, tried in this order:
| # | Route | Mechanism |
| :-: | :--- | :--- |
| 1 | tool_resume | Resumes a suspended session in-process via a loopback Reverse-MCP Tool Bridge (127.0.0.1:0) when trailing role: "tool" / tool_result messages match pending tool_call_ids. |
| 2 | warm_hit | Reuses an IDLE Tier-2 worker indexed by deterministic SHA-256 parentHash — zero handshake. |
| 3 | session_resume | On warm-hash miss, if a committed session's history is a strict per-message prefix of the request, resumes it (session/resume) and sends only the trailing messages. |
| 4 | cold_fallback | Claims a pre-initialized Tier-1 standby and replays history via a deterministic XML <conversation_transcript> flattener. |
session_resume is what makes coding agents cheap: a prefix-proven resume re-sends only the new turns instead of re-buying the whole transcript. Measured against agy 1.5.21 on a 59.7k-char / 6-turn history — cold replay 42,246 full-price input tokens, resume ~2.3k full + ~42–44k provider-cached, with correct recall. Set SESSION_REUSE_ENABLED=false to disable route 3 and reproduce the original three-route behaviour byte-identically.
Correctness guards for route 3 (each verified by a unit test): strict prefix match per message hash, single-owner lease (a claimed session id is destroyed from every other index so two processes can never drive it), tool-scope match (useMcp must equal the session's binding), and a minimum-delta floor. Resume is only attempted when the agent advertises sessionCapabilities.resume; otherwise the route is skipped entirely.
Worker lifecycle is bounded by STANDBY_POOL_SIZE / MAX_TOTAL_WORKERS, idle TTL eviction, and per-turn timeouts. Teardown is SIGTERM → SIGKILL over the whole process group, plus a process.on("exit") hook that SIGKILLs every tracked group — so a hard crash leaves no orphaned agy process.
Endpoints
| Method & Path | Description | Auth |
| :--- | :--- | :--- |
| POST /v1/chat/completions | OpenAI Chat Completions (SSE stream & JSON) | Optional |
| POST /v1/messages | Anthropic Messages (SSE stream & JSON) | Optional |
| GET /v1/models | Live models from agy configOptions (OpenAI shape; Anthropic shape when anthropic-version is present) | Optional |
| GET /v1/models/:model | Single model descriptor (same shape switching) | Optional |
| GET /healthz | Pool diagnostics & readiness | Public |
| GET /metrics | Route mix, resume success/failure, full vs cached prompt tokens, session-index gauge (404 when EXPOSE_METRICS_ENDPOINT=false) | Public |
Auth is an optional Authorization: Bearer or x-api-key check against GATEWAY_API_KEY; empty disables it. /healthz, /metrics, and unknown routes are the only non-/v1 paths.
/v1/models returns a single object per model with all verified metadata flattened to the top level — no x_agy wrapper. The OpenAI shape overlays id/object/created/owned_by onto the models.dev record (so family, reasoning_options, limit, cost, modalities, … are read directly); the Anthropic shape adds type/display_name/created_at/capabilities/max_input_tokens. Models without a models.dev match fall back to a minimal object built from what ACP advertises.
Effort variants published by ACP (e.g. gemini-4-hydrogen-low) are collapsed onto one base model whose reasoning_options lists every supported level. A request for a suffixed id is split into the base id plus thought_level; an explicit reasoning_effort wins over the suffix.
Request Feature Support
| API | Supported |
| :--- | :--- |
| OpenAI | messages (system/developer/user/assistant/tool), tools, tool_choice (none/auto/required/function), parallel_tool_calls, reasoning_effort, stop (max 4), max_tokens / max_completion_tokens, response_format (text, json_object, json_schema), multimodal image_url, stream, stream_options.include_usage |
| Anthropic | Required max_tokens, messages + optional system, content blocks (text, image base64/url, tool_use, tool_result, thinking), tools + tool_choice (auto/any/tool/none, disable_parallel_tool_use), stop_sequences (max 4), thinking.budget_tokens, metadata.user_id, stream |
Usage mapping: prompt_tokens = ACP input + cached-read tokens, completion_tokens = output tokens, completion_tokens_details.reasoning_tokens = thought tokens. Anthropic stop_reason (end_turn, max_tokens, tool_use, stop_sequence) derives from the OpenAI finish_reason. Unknown models return 404 model_not_found.
Any anthropic-version header must match YYYY-MM-DD; it is accepted as-is and only selects the Anthropic shape on /v1/models. Without it, the OpenAI shape is returned.
Installation
1. Prerequisites
- Node.js
>= 22.0.0 - pnpm
>= 10.x - Antigravity CLI (
agy) installed and authenticated onPATH(override withAGY_BIN_PATH)
node -v && pnpm -v && agy --version2. Install
From npm
npm install -g agy-gateway
agy-gatewayOr run directly without installing:
npx agy-gatewayFrom source
pnpm install3. Configuration
All runtime parameters are Zod-validated at startup (src/config.ts); an invalid value fails fast.
cp .env.example .envThe gateway reads process.env only — it does not auto-load .env. Load it explicitly:
# Development
pnpm exec tsx --env-file=.env watch src/index.ts
# Production build
pnpm run build
node --env-file=.env dist/index.js| Variable | Default | Description |
| :--- | :--- | :--- |
| HOST | 127.0.0.1 | HTTP bind address |
| PORT | 8787 | HTTP bind port |
| GATEWAY_API_KEY | "" (disabled) | Optional ingress key (Authorization: Bearer or x-api-key) |
| AGY_BIN_PATH | agy | agy binary name or absolute path (resolved via PATH) |
| AGY_BIN_ARGS | acp | Space-separated args passed to agy (the profile flags are appended automatically) |
| AGY_PROFILE_DIR | ~/.agy-gateway/profile | Isolated agy profile home, bootstrapped at startup; ~ expands, empty disables |
| AGY_PROFILE_AGENT | zed | Agent id written to <AGY_PROFILE_DIR>/agents/<id>.md and passed via agy --agent |
| AGY_HTTP_PROXY | "" (disabled) | Route only the agy subprocess through this HTTP proxy (http(s) URL). The gateway's own calls are never proxied |
| AGY_NO_PROXY | 127.0.0.1,localhost | Proxy bypass list for agy; loopback must stay direct or the MCP bridge breaks |
| ACP_CLIENT_NAME | zed | ACP clientInfo.name fingerprint |
| ACP_CLIENT_TITLE | Zed | ACP clientInfo.title fingerprint |
| ACP_CLIENT_VERSION | 1.30.2+stable.398.610ea4b8de1c6e887f03563f067278002f41256e | ACP clientInfo.version fingerprint |
| SANDBOX_CWD | /tmp/agy-gateway-sandbox | Sandbox cwd for agy sessions (created read-only) |
| STANDBY_POOL_SIZE | 2 | Pre-initialized Tier-1 standby workers (≤ MAX_TOTAL_WORKERS) |
| MAX_TOTAL_WORKERS | 12 | Hard cap on concurrent agy processes |
| WARM_SESSION_TTL_MS | 900000 | Idle TTL in ms for Tier-2 workers (15m) |
| SESSION_CLOSE_TIMEOUT_MS | 1000 | Graceful ACP session/close timeout during teardown |
| WORKER_SIGKILL_GRACE_MS | 2000 | Grace period between SIGTERM and SIGKILL |
| SUSPENDED_TOOL_TIMEOUT_MS | 300000 | Max wait for a SUSPENDED_ON_TOOL worker (5m) |
| TOOL_BATCH_WINDOW_MS | 25 | Micro-batch window for parallel MCP tool calls |
| PROMPT_TIMEOUT_MS | 600000 | Hard timeout per session/prompt turn (10m) |
| COMPACT_TIMEOUT_MS | 60000 | Timeout for background /compact |
| COMPACTION_THRESHOLD | 0.85 | Context ratio (used/size) triggering /compact |
| MAX_REQUEST_BODY_BYTES | 52428800 | Max HTTP JSON body size (50 MiB) |
| MAX_IMAGE_BYTES | 10485760 | Max decoded image payload (10 MiB) |
| IMAGE_FETCH_TIMEOUT_MS | 10000 | Remote image fetch timeout |
| ALLOW_PRIVATE_IMAGE_URLS | false | Allow private/loopback image URLs (SSRF guard toggle) |
| EXPOSE_DEBUG_HEADERS | true | Emit X-Agy-Route / X-Agy-Worker-Id (X-Agy-Ignored-Params is always emitted when applicable) |
| DEFAULT_THOUGHT_LEVEL | medium | Default reasoning level when omitted (low/medium/high/xhigh) |
| MODEL_PREFIX_TO_STRIP | antigravity/ | Optional provider prefix stripped from model IDs |
| MODELS_DEV_CATALOG_ENABLED | true | Enable models.dev metadata enrichment |
| MODELS_DEV_CATALOG_URL | https://models.dev/api.json?type=all | models.dev catalog JSON URL |
| MODELS_DEV_CATALOG_TIMEOUT_MS | 5000 | Catalog fetch timeout |
| MODELS_DEV_CATALOG_TTL_MS | 3600000 | Catalog cache TTL (1h) |
| ANTHROPIC_MODEL_ALIASES | {} | JSON map of Anthropic model aliases → AGY model IDs |
| LOG_LEVEL | info | Pino log level |
| SESSION_REUSE_ENABLED | true | Enable prefix-proven session/resume; false restores the cold-replay baseline |
| SESSION_RESUME_TIMEOUT_MS | 5000 | Hard timeout for one session/resume round-trip |
| SESSION_INDEX_MAX_ENTRIES | 64 | Max resumable sessions in the bounded index |
| SESSION_INDEX_MAX_BYTES | 8388608 | Max fingerprint bytes in the resume index (8 MiB) |
| SESSION_RESUME_MIN_DELTA_MESSAGES | 1 | Minimum new trailing messages before resuming |
| EXPOSE_METRICS_ENDPOINT | true | Expose GET /metrics JSON counters |
4. Run
pnpm run dev # watch mode (env must be loaded, see above)
pnpm run build && pnpm run start # compile + run dist/Production daemon (PM2 + Bun)
Build dist/ first, then start with bun as the PM2 interpreter. Environment must already be exported or loaded:
pnpm run build && pm2 start dist/index.js --interpreter bun --name agy-gateway5. Smoke Test
Model ids are live — read them from GET /v1/models rather than hardcoding.
curl -s http://127.0.0.1:8787/healthz
curl -s http://127.0.0.1:8787/v1/models
curl -s http://127.0.0.1:8787/metrics
curl -s http://127.0.0.1:8787/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"<id-from-/v1/models>","messages":[{"role":"user","content":"Say hi"}]}'
curl -s http://127.0.0.1:8787/v1/messages \
-H "Content-Type: application/json" \
-H "anthropic-version: 2023-06-01" \
-d '{"model":"<id-from-/v1/models>","max_tokens":64,"messages":[{"role":"user","content":"Say hi"}]}'If GATEWAY_API_KEY is set, add -H "Authorization: Bearer $GATEWAY_API_KEY" (or -H "x-api-key: $GATEWAY_API_KEY").
6. Verification
pnpm run typecheck # TypeScript strict check
pnpm run lint # Biome lint & format
pnpm run test # Unit + integration (fake ACP agent, zero model tokens)
pnpm run test:e2e # All live E2E suites
pnpm run test:e2e:openai # Live OpenAI suite
pnpm run test:e2e:anthropic # Live Anthropic suitepnpm run test:e2e* requires an authenticated agy. Each file launches pnpm run dev on an ephemeral port, pulls .env, forces debug headers on for route assertions, and tears down the process group. Seven mirrored scenarios per API (e2e/openai/, e2e/anthropic/): A model listing, B non-stream, C stream + system prompt, D parallel tools, E multi-turn recall, F Hono CRUD scaffold, G compaction & warm reuse.
7. CI/CD
- CI (
.github/workflows/ci.yml):pull_requestandpushtomainonshukoilab/agy-gateway, Node.js 24,pnpm --frozen-lockfile; runstypecheck,lint,test. E2E is excluded from CI to avoid live quota use. - Release (
.github/workflows/release.yml): onpushtomainandworkflow_dispatch, after the same checks pass: bumps the patch version, commits asgithub-actions[bot], tagsvX.Y.Z, creates a GitHub Release.chore(release):commits are skipped to prevent loops.
Project Structure
src/
config.ts Zod-validated env configuration
index.ts Startup, graceful shutdown, exit hook wiring
acp/ Worker lifecycle & pool, model registry, models.dev catalog, permission gate
canonical/ Normalization, hashing/fingerprints, transcript flattening, resumable-session index
http/ Server, routes, SSE writers, stream guard, metrics
mcp/ Loopback Reverse-MCP bridge and server
types/ OpenAI, Anthropic, and canonical schemas
utils/ Logger (redaction), SSRF guard, crypto
tests/ Unit + integration (fake ACP agent)
e2e/
helper.ts Dev-server launcher, env loading, process-group cleanup
openai/ Live OpenAI scenarios (A–G)
anthropic/ Live Anthropic scenarios (A–G)
docs/ Design baseline (prd.md) and ACP wire reference (zed_agy_acp.md)docs/prd.md records the original Pattern C design baseline; this README is the authoritative description of current behaviour.
Security & Governance
- Security Policy: SECURITY.md
- Contributing: CONTRIBUTING.md
- Code of Conduct: CODE_OF_CONDUCT.md
- Changelog: CHANGELOG.md
- License: LICENSE
Disclaimer
Independent, experimental research effort. Not affiliated with, endorsed by, sponsored by, or otherwise connected to Google, Antigravity, Zed Industries, OpenAI, Anthropic, or any other company, product, or service mentioned in this repository. All names and trademarks belong to their respective owners.
Provided "as is", without warranty of any kind, express or implied. By using it you accept full responsibility for your own use, configuration, and deployment, and for complying with any applicable terms of service, licenses, and laws in your jurisdiction. The maintainers assume no liability for any damage, loss, misuse, or legal consequence arising from use of this project.
Intended for research, experimentation, and interoperability testing only.
