Skip to content

Add AI Gateway SDK and CLI support#1451

Merged
jhaynie merged 8 commits intomainfrom
feat/aigateway-sdk-cli
May 6, 2026
Merged

Add AI Gateway SDK and CLI support#1451
jhaynie merged 8 commits intomainfrom
feat/aigateway-sdk-cli

Conversation

@jhaynie
Copy link
Copy Markdown
Member

@jhaynie jhaynie commented May 6, 2026

Summary

Adds first-pass AI Gateway support across the TypeScript SDK, core service layer, CLI, docs, and examples.

  • Add @agentuity/aigateway standalone package with AIGatewayClient
  • Add core aigateway service for model listing and auto-router completions
  • Add cloud aigateway CLI with models and complete commands
  • Support public model listing without auth/org/region, defaulting gateway region to usc when needed
  • Add model catalog filtering and lookup via --model, --provider, and --name
  • Add stdin/file prompt input, streaming output, JSON/raw/text formats, usage/cost reporting, and save-to-file support
  • Cache AI Gateway model catalog in the CLI SQLite resource.db with --refresh-models
  • Add AI-agent help/capability wiring, docs API reference, README entries, and a TypeScript example

Validation

  • bun run format
  • bun test packages/cli/test/cmd/cloud/aigateway.test.ts packages/core/test/aigateway.test.ts
  • bun run --filter='./packages/core' typecheck
  • bun run --filter='./packages/cli' typecheck
  • bun run --filter='./packages/aigateway' typecheck
  • bun run --filter='./apps/docs' typecheck
  • bun run --filter='./packages/core' build
  • bun run --filter='./packages/cli' build
  • bun run --filter='./packages/aigateway' build

Live Smoke Tests

Validated completions through the AI Gateway auto-router with multiple API shapes:

  • anthropic/claude-haiku-4-5-20251001 (anthropic-messages) -> returned anthropic-ok
  • mistral/mistral-small-latest (mistral-conversations) -> returned mistral-ok
  • groq/llama-3.1-8b-instant (openai-completions) -> returned groq-ok
  • Piped JSON/CSV input into cloud aigateway complete and piped JSON output through jq

Summary by CodeRabbit

  • New Features

    • AI Gateway client and CLI: list models, run completions (streaming & non‑streaming), filtering, caching, TUI discovery, and multiple output modes (text/json/raw)
  • Documentation

    • Full API reference pages, docs nav entry, README guidance, examples, and docs index/routes updated
  • Configuration

    • New env vars and config override support for AI Gateway URL and API key
  • Tests

    • Comprehensive service and CLI test suites
  • Examples

    • New AI Gateway example service and sample agent integration

@agentuity-agent
Copy link
Copy Markdown

agentuity-agent Bot commented May 6, 2026

The latest Agentuity deployment details.

Project Deployment Preview Updated (UTC)
docs 🟢 Ready (deploy_b68ebd9b096a22b93d4b060b548a6709) - 2026-05-06T22:08:49Z

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 6, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a new AI Gateway service: core schemas and service client, a standalone packages/aigateway package and client, CLI commands and utilities (models, complete, caching, URL/config), docs and route/nav entries, example project and agent, server/CLI config and env support, TUI integration, and tests across core, server, and CLI.

Changes

AI Gateway introduction (single DAG)

Layer / File(s) Summary
Data Shape / Schemas
packages/core/src/services/aigateway/service.ts, packages/core/src/services/aigateway/index.ts
Adds Zod schemas and TypeScript types for pricing, model/provider metadata, models responses, chat messages, completion params (including stream), completion responses, response metadata, and streaming frames.
Core Implementation
packages/core/src/services/aigateway/service.ts
Implements AIGatewayService with listModels(), complete(), streamComplete()/streamCompleteWithMetadata(), helpers for parsing numeric headers, extracting/attaching gateway metadata, and error handling.
API Reference (core)
packages/core/src/services/aigateway/api-reference.ts, packages/core/src/services/api-reference.ts
Adds AI Gateway Service API-reference object (endpoints: list-models, create-chat-completion, stream-chat-completion) and adds optional Endpoint.public?: boolean to API reference types.
Core Exports & Env
packages/core/src/services/index.ts, packages/core/src/services/config.ts, packages/core/src/env.d.ts
Re-exports AIGateway symbols; adds aigateway to service URLs schema and ServiceUrls; augments ProcessEnv with AGENTUITY_AIGATEWAY_KEY and AGENTUITY_AIGATEWAY_MODEL.
Public Package & Client
packages/aigateway/src/index.ts, packages/aigateway/package.json, packages/aigateway/tsconfig.json, tsconfig.json
Adds new packages/aigateway package exposing core types and an AIGatewayClient with AIGatewayClientOptionsSchema, option resolution (apiKey, url, org, logger), server fetch adapter wiring, and methods listModels() and complete(); adds package manifest and TS project reference.
Server config & docs
packages/server/src/config.ts, packages/server/README.md
Adds aigateway: string to ServiceUrls, wires it from AGENTUITY_AIGATEWAY_URL or regional URL, and documents usage in server README.
CLI Config & Types
packages/cli/src/types.ts, packages/cli/src/config.ts
Adds overrides.aigateway_url to CLI config schema and reads AGENTUITY_AIGATEWAY_URL into overrides during config loading.
CLI Utilities
packages/cli/src/cmd/cloud/aigateway/util.ts
Adds getAIGatewayUrl, createAIGatewayService (authenticated), createPublicAIGatewayService (unauthenticated), and getCompletionText for URL resolution, service creation, and completion text extraction.
Model Cache
packages/cli/src/cmd/cloud/aigateway/model-cache.ts
Implements a SQLite-backed TTL cache (6 hours) for AIGatewayModels with getCachedAIGatewayModels and setCachedAIGatewayModels.
CLI Commands
packages/cli/src/cmd/cloud/aigateway/models.ts, packages/cli/src/cmd/cloud/aigateway/complete.ts, packages/cli/src/cmd/cloud/aigateway/index.ts, packages/cli/src/cmd/cloud/index.ts
Adds modelsSubcommand (catalog listing, filtering, recommended/simple views, caching) and completeSubcommand (prompt resolution from arg/file/stdin, model lookup, streaming and non-streaming flows, output formats, cost reporting, save-to-file); wires aigatewayCommand into cloud subcommands.
CLI UX / Help / Detection
packages/cli/src/ai-help.ts, packages/cli/src/cmd/ai/capabilities/show.ts, packages/cli/src/cmd/ai/intro.ts, packages/cli/src/agent-detection.ts
Adds AI Gateway references to help/capabilities/intro, inserts capability entry for AI Gateway, adds KNOWN_AGENTS entry ['coder','coder'], and refines process-name matching logic.
CLI Tests & Test integration
packages/cli/test/cmd/cloud/aigateway.test.ts, packages/cli/test/config/profile-creation.test.ts
Adds comprehensive CLI tests for models and complete flows (including streaming, file/stdin prompts, cost reporting) and includes AGENTUITY_AIGATEWAY_URL in test env cleanup.
Core Tests
packages/core/test/aigateway.test.ts
Adds unit tests for AIGatewayService: list models, completions, streaming completions, and metadata extraction using a mock adapter.
Docs: Routes, Nav & Content
apps/docs/src/web/routes/_docs/reference/api/ai-gateway.tsx, apps/docs/src/web/routeTree.gen.ts, apps/docs/src/web/components/docs/nav-data.ts, apps/docs/src/web/content/reference/api/ai-gateway.mdx, apps/docs/src/web/content/reference/api/meta.json, apps/docs/src/web/content/reference/api/index.mdx, apps/docs/scripts/generate-api-reference.ts
Adds docs route and MDX API reference page for AI Gateway, registers ai-gateway in meta and nav, updates API index card (adds Cpu icon), and includes aiGatewayService in docs generation tooling.
Examples & TUI Integration
examples/services-aigateway/*, examples/README.md, packages/coder-tui/src/aigateway.ts, packages/coder-tui/package.json, packages/coder-tui/tsconfig.json
Adds example project demonstrating usage (agent, app, README); integrates server-backed model discovery into coder TUI by using AIGatewayService.listModels(), updates workspace deps and TS config.
Repo build scripts & wiring
package.json, root tsconfig.json
Moves certain app-testing steps into the root build script and trims build:packages; adds packages/aigateway to TypeScript project references.
Docs content tweaks
apps/docs/src/web/content/reference/api/sandboxes.mdx
Adds timeout.paused and executionId fields to Sandboxes API reference payloads.
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 6, 2026

📦 Canary Packages Published

version: 2.0.14-9ad8ade

Packages
Package Version URL
@agentuity/email 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-email-2.0.14-9ad8ade.tgz
@agentuity/cli 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-cli-2.0.14-9ad8ade.tgz
@agentuity/postgres 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-postgres-2.0.14-9ad8ade.tgz
@agentuity/runtime 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-runtime-2.0.14-9ad8ade.tgz
@agentuity/task 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-task-2.0.14-9ad8ade.tgz
@agentuity/db 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-db-2.0.14-9ad8ade.tgz
@agentuity/schema 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-schema-2.0.14-9ad8ade.tgz
@agentuity/auth 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-auth-2.0.14-9ad8ade.tgz
@agentuity/server 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-server-2.0.14-9ad8ade.tgz
@agentuity/migrate 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-migrate-2.0.14-9ad8ade.tgz
@agentuity/frontend 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-frontend-2.0.14-9ad8ade.tgz
@agentuity/schedule 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-schedule-2.0.14-9ad8ade.tgz
@agentuity/workbench 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-workbench-2.0.14-9ad8ade.tgz
@agentuity/coder 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-coder-2.0.14-9ad8ade.tgz
@agentuity/opencode 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-opencode-2.0.14-9ad8ade.tgz
@agentuity/webhook 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-webhook-2.0.14-9ad8ade.tgz
@agentuity/react 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-react-2.0.14-9ad8ade.tgz
@agentuity/keyvalue 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-keyvalue-2.0.14-9ad8ade.tgz
@agentuity/sandbox 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-sandbox-2.0.14-9ad8ade.tgz
@agentuity/vector 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-vector-2.0.14-9ad8ade.tgz
@agentuity/queue 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-queue-2.0.14-9ad8ade.tgz
@agentuity/evals 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-evals-2.0.14-9ad8ade.tgz
@agentuity/coder-tui 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-coder-tui-2.0.14-9ad8ade.tgz
@agentuity/core 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-core-2.0.14-9ad8ade.tgz
@agentuity/drizzle 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-drizzle-2.0.14-9ad8ade.tgz
@agentuity/claude-code 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-claude-code-2.0.14-9ad8ade.tgz
@agentuity/aigateway 2.0.14-9ad8ade https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-aigateway-2.0.14-9ad8ade.tgz
Install

Add to your package.json:

{
  "dependencies": {
    "@agentuity/email": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-email-2.0.14-9ad8ade.tgz",
    "@agentuity/cli": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-cli-2.0.14-9ad8ade.tgz",
    "@agentuity/postgres": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-postgres-2.0.14-9ad8ade.tgz",
    "@agentuity/runtime": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-runtime-2.0.14-9ad8ade.tgz",
    "@agentuity/task": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-task-2.0.14-9ad8ade.tgz",
    "@agentuity/db": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-db-2.0.14-9ad8ade.tgz",
    "@agentuity/schema": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-schema-2.0.14-9ad8ade.tgz",
    "@agentuity/auth": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-auth-2.0.14-9ad8ade.tgz",
    "@agentuity/server": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-server-2.0.14-9ad8ade.tgz",
    "@agentuity/migrate": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-migrate-2.0.14-9ad8ade.tgz",
    "@agentuity/frontend": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-frontend-2.0.14-9ad8ade.tgz",
    "@agentuity/schedule": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-schedule-2.0.14-9ad8ade.tgz",
    "@agentuity/workbench": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-workbench-2.0.14-9ad8ade.tgz",
    "@agentuity/coder": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-coder-2.0.14-9ad8ade.tgz",
    "@agentuity/opencode": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-opencode-2.0.14-9ad8ade.tgz",
    "@agentuity/webhook": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-webhook-2.0.14-9ad8ade.tgz",
    "@agentuity/react": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-react-2.0.14-9ad8ade.tgz",
    "@agentuity/keyvalue": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-keyvalue-2.0.14-9ad8ade.tgz",
    "@agentuity/sandbox": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-sandbox-2.0.14-9ad8ade.tgz",
    "@agentuity/vector": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-vector-2.0.14-9ad8ade.tgz",
    "@agentuity/queue": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-queue-2.0.14-9ad8ade.tgz",
    "@agentuity/evals": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-evals-2.0.14-9ad8ade.tgz",
    "@agentuity/coder-tui": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-coder-tui-2.0.14-9ad8ade.tgz",
    "@agentuity/core": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-core-2.0.14-9ad8ade.tgz",
    "@agentuity/drizzle": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-drizzle-2.0.14-9ad8ade.tgz",
    "@agentuity/claude-code": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-claude-code-2.0.14-9ad8ade.tgz",
    "@agentuity/aigateway": "https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-aigateway-2.0.14-9ad8ade.tgz"
  }
}

Or install directly:

bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-email-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-cli-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-postgres-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-runtime-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-task-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-db-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-schema-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-auth-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-server-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-migrate-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-frontend-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-schedule-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-workbench-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-coder-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-opencode-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-webhook-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-react-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-keyvalue-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-sandbox-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-vector-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-queue-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-evals-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-coder-tui-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-core-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-drizzle-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-claude-code-2.0.14-9ad8ade.tgz
bun add https://agentuity-sdk-objects.t3.storageapi.dev/npm/2.0.14-9ad8ade/agentuity-aigateway-2.0.14-9ad8ade.tgz

@jhaynie jhaynie force-pushed the feat/aigateway-sdk-cli branch from ca72458 to 9cd6eda Compare May 6, 2026 20:48
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (5)
packages/core/src/services/aigateway/index.ts (1)

1-1: ⚡ Quick win

Use named re-exports instead of wildcard in package index.

Please replace the wildcard barrel with explicit named exports to keep the public surface intentional and stable.

As per coding guidelines, "Use named exports from package index.ts files."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/services/aigateway/index.ts` at line 1, Replace the
wildcard re-export in index.ts with explicit named exports: open
packages/core/src/services/aigateway/service.ts, identify the public symbols
(functions, classes, types) it exports, and change export * from './service.ts'
to an explicit list like export { SymbolA, SymbolB, type TypeC } from
'./service.ts' so the package public surface is intentional and stable; ensure
you include all intended public identifiers from service.ts and keep the file
extension consistent with project style.
packages/cli/src/cmd/cloud/aigateway/model-cache.ts (1)

62-62: ⚡ Quick win

Validate cached payload shape before returning it.

The cast hides schema drift/corruption risks in models_json. Safer to parse and validate, then fall back to null on mismatch.

Suggested fix
-import type { AIGatewayModels } from '@agentuity/core';
+import { AIGatewayModelsSchema, type AIGatewayModels } from '@agentuity/core';
@@
-		return JSON.parse(row.models_json) as AIGatewayModels;
+		const parsed = AIGatewayModelsSchema.safeParse(JSON.parse(row.models_json));
+		return parsed.success ? parsed.data : null;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cmd/cloud/aigateway/model-cache.ts` at line 62, The code
currently returns JSON.parse(row.models_json) as AIGatewayModels which hides
schema drift; replace the direct cast with a safe parse+validation: parse
row.models_json, run a runtime validator (e.g., validateAIGatewayModels(parsed))
that checks required fields and types for the AIGatewayModels shape, and only
return the parsed value if the validator passes, otherwise return null (or
fallback). Add or reuse a helper like validateAIGatewayModels and call it where
models_json is parsed so corrupted/mismatched payloads are detected instead of
being force-cast.
packages/cli/src/cmd/cloud/index.ts (1)

17-17: ⚡ Quick win

Use a named import for the new index-module command export.

Line 17 currently uses a default import from an index.ts module; switch it to a named import for consistency with repo conventions.

Proposed change
-import aigatewayCommand from './aigateway';
+import { aigatewayCommand } from './aigateway';

As per coding guidelines **/index.ts: Use named exports from package index.ts files.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cmd/cloud/index.ts` at line 17, Replace the default import
of the cloud subcommand with a named import to match index.ts conventions:
change the import statement "import aigatewayCommand from './aigateway';" to a
named import "import { aigatewayCommand } from './aigateway';" and ensure the
exported symbol in the ./aigateway module is a named export called
aigatewayCommand; update any references if the identifier name differs.
packages/cli/src/cmd/cloud/aigateway/complete.ts (2)

147-169: 💤 Low value

Unused api parameter in buildCompletionRequest.

The api parameter is accepted in the options (line 151) and passed from the caller at line 364, but it's never included in the returned request object. If this field is intended to inform the gateway about the API format, it should be added to the request; otherwise, remove the parameter to avoid confusion.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cmd/cloud/aigateway/complete.ts` around lines 147 - 169, The
buildCompletionRequest function currently accepts opts.api but never uses it;
update the returned object in buildCompletionRequest to include the api field
(e.g., add api: opts.api when present) so the gateway receives the API format,
or if api is not needed remove it from the function signature and all callers
(notably where buildCompletionRequest is invoked). Locate buildCompletionRequest
and the callers that pass api (caller at the noted invocation) and either add
the api property to the returned request object or remove the unused parameter
from both the function and its callers to eliminate confusion.

31-38: ⚡ Quick win

Add file existence check before reading.

When the file doesn't exist, Bun.file(filename).text() throws a non-descriptive error. As per coding guidelines, use Bun.file(f).exists() to provide a user-friendly error message.

Suggested improvement
 async function readPromptFromFile(filename?: string): Promise<string | undefined> {
 	if (!filename) {
 		return undefined;
 	}
+	const file = Bun.file(filename);
+	if (!(await file.exists())) {
+		return undefined;
+	}
-	const text = await Bun.file(filename).text();
+	const text = await file.text();
 	const trimmed = text.trim();
 	return trimmed.length > 0 ? trimmed : undefined;
 }

As per coding guidelines: packages/cli/**/*.ts: Use Bun.file(f).exists() instead of existsSync(f) for file existence checks.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cmd/cloud/aigateway/complete.ts` around lines 31 - 38, The
readPromptFromFile function reads the file without checking existence and thus
surfaces Bun's non-descriptive error; before calling Bun.file(filename).text()
call await Bun.file(filename).exists() and if it returns false, throw or return
a clear user-facing error/message (e.g., "Prompt file not found: <filename>") so
callers get a friendly message; update the function readPromptFromFile to use
Bun.file(filename).exists() and only call Bun.file(filename).text() when
exists() is true.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/docs/src/web/content/reference/api/ai-gateway.mdx`:
- Around line 12-20: Update the generated metadata and docs to mark the GET
/models endpoint as public and remove the requirement for a Bearer token: change
the Authentication section that currently states "All requests require a Bearer
token" to reflect that /models is unauthenticated, and update the `/models`
status/authorization table row to "Public" or "No auth required" (reference the
"GET /models" endpoint and the Authentication header table in this file). Ensure
any automated metadata generation flag that sets auth for endpoints (the source
that produced the "unauthorized" status for GET /models) is adjusted so /models
is emitted without auth/org/region requirements, and regenerate the docs so the
header text and the status table for GET /models and lines corresponding to
24-41 reflect public access.

In `@examples/services-aigateway/src/agent/aigateway/agent.ts`:
- Around line 29-52: getCompletionText currently only inspects
response.choices[0].message.content (and text) and returns '' for
provider-compatible payloads that put text in a top-level response.content
array; update getCompletionText to also detect a top-level (response as {
content?: unknown }).content array, and if present treat it like the existing
content handling: accept string or array entries, concatenate string parts and
objects with a text field (same logic used for choices[0].message.content), and
return the combined string so Anthropic-style/response.content[] payloads are
supported.

In `@packages/cli/src/agent-detection.ts`:
- Line 36: The 'coder' token in the process token list is too broad because the
detection uses basename.includes(processName); update the matching logic in
packages/cli/src/agent-detection.ts (the code that builds processName tokens and
calls basename.includes(processName)) to avoid simple substring matching: either
perform an exact match (basename === processName), or use a word-boundary/regex
match (e.g. match new RegExp(`\\b${escapeRegex(processName)}\\b`)) or split
basename on non-alphanumerics and check membership; alternatively tighten the
token list (replace 'coder' with a more specific token) if appropriate—apply the
same change for the matching branch that currently uses
basename.includes(processName) around lines 349–354.

In `@packages/cli/src/cmd/ai/capabilities/show.ts`:
- Around line 136-137: The capability metadata currently marks the entire
aigateway capability with requiresAuth and requiresProject flags (the properties
requiresAuth and requiresProject on the aigateway capability object), which is
too strict because the "cloud aigateway models" command is publicly accessible;
update the capability metadata so these flags reflect per-command requirements
rather than blanket settings — either remove or set requiresAuth/requiresProject
to false on the aigateway capability and add command-specific requirement
metadata for commands that actually need auth/project (e.g., add
requiresAuth/requiresProject on the specific command entries for ones that
require them, leaving "cloud aigateway models" as public).

In `@packages/cli/src/cmd/cloud/aigateway/models.ts`:
- Around line 25-30: recommendedModels uses provider-prefixed ids but catalog
rows often come as raw ids, so normalize ids before matching: update the
comparison logic that builds the recommended list (the code referencing
recommendedModels and the matching block around the second occurrence on lines
~36-43) to canonicalize both sides by stripping provider prefixes (e.g.,
"provider/model" -> "model") or otherwise normalizing case/format; implement a
small helper (e.g., normalizeModelId) and apply it to both candidate ids and
catalog row ids before computing recommendations so matches succeed in both
places.

In `@packages/core/src/services/aigateway/service.ts`:
- Around line 193-196: The current return merges metadata and trailerMetadata
but replaces the entire cost object with trailerMetadata.cost (cost:
trailerMetadata.cost ?? metadata.cost), which loses header-only fields; change
this to merge cost per-key by combining metadata.cost and trailerMetadata.cost
with trailer values taking precedence. In the function that returns the object
using metadata and trailerMetadata (the return with headers: {
...metadata.headers, ...trailerMetadata.headers }), create a merged cost like:
if neither cost exists keep undefined, otherwise build { ...(metadata.cost ??
{}), ...(trailerMetadata.cost ?? {}) } and use that as the returned cost so
header-only keys are preserved while trailer keys override.
- Around line 238-239: listModels() currently returns payload.data even when the
gateway indicates failure in the 2xx body; after parsing the response with
AIGatewayModelsResponseSchema.parse(response.data) (the variable named payload),
check payload.success and if it is false, throw or return an error instead of
returning payload.data — include gateway-provided error details (e.g.
payload.error or payload.message) in the thrown error so calling code does not
treat a failed gateway response as a valid model list.

---

Nitpick comments:
In `@packages/cli/src/cmd/cloud/aigateway/complete.ts`:
- Around line 147-169: The buildCompletionRequest function currently accepts
opts.api but never uses it; update the returned object in buildCompletionRequest
to include the api field (e.g., add api: opts.api when present) so the gateway
receives the API format, or if api is not needed remove it from the function
signature and all callers (notably where buildCompletionRequest is invoked).
Locate buildCompletionRequest and the callers that pass api (caller at the noted
invocation) and either add the api property to the returned request object or
remove the unused parameter from both the function and its callers to eliminate
confusion.
- Around line 31-38: The readPromptFromFile function reads the file without
checking existence and thus surfaces Bun's non-descriptive error; before calling
Bun.file(filename).text() call await Bun.file(filename).exists() and if it
returns false, throw or return a clear user-facing error/message (e.g., "Prompt
file not found: <filename>") so callers get a friendly message; update the
function readPromptFromFile to use Bun.file(filename).exists() and only call
Bun.file(filename).text() when exists() is true.

In `@packages/cli/src/cmd/cloud/aigateway/model-cache.ts`:
- Line 62: The code currently returns JSON.parse(row.models_json) as
AIGatewayModels which hides schema drift; replace the direct cast with a safe
parse+validation: parse row.models_json, run a runtime validator (e.g.,
validateAIGatewayModels(parsed)) that checks required fields and types for the
AIGatewayModels shape, and only return the parsed value if the validator passes,
otherwise return null (or fallback). Add or reuse a helper like
validateAIGatewayModels and call it where models_json is parsed so
corrupted/mismatched payloads are detected instead of being force-cast.

In `@packages/cli/src/cmd/cloud/index.ts`:
- Line 17: Replace the default import of the cloud subcommand with a named
import to match index.ts conventions: change the import statement "import
aigatewayCommand from './aigateway';" to a named import "import {
aigatewayCommand } from './aigateway';" and ensure the exported symbol in the
./aigateway module is a named export called aigatewayCommand; update any
references if the identifier name differs.

In `@packages/core/src/services/aigateway/index.ts`:
- Line 1: Replace the wildcard re-export in index.ts with explicit named
exports: open packages/core/src/services/aigateway/service.ts, identify the
public symbols (functions, classes, types) it exports, and change export * from
'./service.ts' to an explicit list like export { SymbolA, SymbolB, type TypeC }
from './service.ts' so the package public surface is intentional and stable;
ensure you include all intended public identifiers from service.ts and keep the
file extension consistent with project style.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5bf31b26-0749-4fc7-8695-941dfbbec4dd

📥 Commits

Reviewing files that changed from the base of the PR and between 3f43833 and fb6762b.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (44)
  • README.md
  • apps/docs/scripts/generate-api-reference.ts
  • apps/docs/src/web/components/docs/nav-data.ts
  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
  • apps/docs/src/web/content/reference/api/index.mdx
  • apps/docs/src/web/content/reference/api/meta.json
  • apps/docs/src/web/content/reference/api/sandboxes.mdx
  • apps/docs/src/web/routeTree.gen.ts
  • apps/docs/src/web/routes/_docs/reference/api/ai-gateway.tsx
  • examples/README.md
  • examples/services-aigateway/README.md
  • examples/services-aigateway/app.ts
  • examples/services-aigateway/package.json
  • examples/services-aigateway/src/agent/aigateway/agent.ts
  • package.json
  • packages/aigateway/README.md
  • packages/aigateway/package.json
  • packages/aigateway/src/index.ts
  • packages/aigateway/tsconfig.json
  • packages/cli/src/agent-detection.ts
  • packages/cli/src/ai-help.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • packages/cli/src/cmd/ai/intro.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/cloud/aigateway/util.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/src/config.ts
  • packages/cli/src/types.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/test/config/profile-creation.test.ts
  • packages/core/src/env.d.ts
  • packages/core/src/services/aigateway/api-reference.ts
  • packages/core/src/services/aigateway/index.ts
  • packages/core/src/services/aigateway/service.ts
  • packages/core/src/services/config.ts
  • packages/core/src/services/index.ts
  • packages/core/test/aigateway.test.ts
  • packages/server/README.md
  • packages/server/src/config.ts
  • packages/server/test/config.test.ts
  • tsconfig.json
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
  • GitHub Check: Pack & Upload
  • GitHub Check: Windows WSL CLI Smoke Test
  • GitHub Check: Playwright E2E Smoke Test
  • GitHub Check: Build
  • GitHub Check: SDK Integration Test Suite
  • GitHub Check: Template Integration Tests
  • GitHub Check: Queue CLI Tests
  • GitHub Check: Postgres SSL Integration Test
  • GitHub Check: Framework Integration Tests (TanStack & Next.js)
  • GitHub Check: Standalone Agent Test
  • GitHub Check: Cloud Deployment Tests
  • GitHub Check: Package Installation & Usage Test
  • GitHub Check: Agentuity Deployment
🧰 Additional context used
📓 Path-based instructions (13)
packages/cli/src/cmd/**/index.ts

📄 CodeRabbit inference engine (packages/cli/AGENTS.md)

packages/cli/src/cmd/**/index.ts: Each command must be structured as a directory in src/cmd/ with an index.ts file as the entry point
Always define interfaces or Zod schemas for command options; never use any type for type safety
Use tui.* helpers (header, info, success, warning, error, table, progress) for formatted TUI output instead of raw console methods
Use ctx.logger for logging instead of console methods; use logger.fatal() for fatal errors which logs and exits with code 1
Always check isJSONMode() before outputting data and provide machine-readable output when in JSON mode
Use requireAuth(ctx) for commands that require authentication or optionalAuth(ctx) for commands that support optional authentication

Files:

  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/cli/src/cmd/cloud/index.ts
packages/cli/**/*.ts

📄 CodeRabbit inference engine (packages/cli/AGENTS.md)

Use Bun.file(f).exists() instead of existsSync(f) for file existence checks

Files:

  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/cli/src/config.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/src/agent-detection.ts
  • packages/cli/src/types.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/cmd/cloud/aigateway/util.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/test/config/profile-creation.test.ts
  • packages/cli/src/cmd/ai/intro.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/ai-help.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Biome as code formatter with tabs (width 3), single quotes, semicolons, lineWidth 100, and trailingCommas es5

Files:

  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/cli/src/config.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/src/agent-detection.ts
  • packages/core/src/services/aigateway/index.ts
  • packages/cli/src/types.ts
  • apps/docs/src/web/routes/_docs/reference/api/ai-gateway.tsx
  • apps/docs/src/web/components/docs/nav-data.ts
  • packages/core/src/services/index.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • examples/services-aigateway/app.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/cmd/cloud/aigateway/util.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/server/src/config.ts
  • packages/cli/test/config/profile-creation.test.ts
  • packages/core/test/aigateway.test.ts
  • packages/core/src/services/aigateway/api-reference.ts
  • packages/cli/src/cmd/ai/intro.ts
  • apps/docs/src/web/routeTree.gen.ts
  • packages/core/src/services/config.ts
  • packages/core/src/env.d.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/ai-help.ts
  • packages/server/test/config.test.ts
  • examples/services-aigateway/src/agent/aigateway/agent.ts
  • apps/docs/scripts/generate-api-reference.ts
  • packages/aigateway/src/index.ts
  • packages/core/src/services/aigateway/service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript Strict mode with ESNext target and bundler moduleResolution
Use StructuredError from @agentuity/core for error handling

Files:

  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/cli/src/config.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/src/agent-detection.ts
  • packages/core/src/services/aigateway/index.ts
  • packages/cli/src/types.ts
  • apps/docs/src/web/routes/_docs/reference/api/ai-gateway.tsx
  • apps/docs/src/web/components/docs/nav-data.ts
  • packages/core/src/services/index.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • examples/services-aigateway/app.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/cmd/cloud/aigateway/util.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/server/src/config.ts
  • packages/cli/test/config/profile-creation.test.ts
  • packages/core/test/aigateway.test.ts
  • packages/core/src/services/aigateway/api-reference.ts
  • packages/cli/src/cmd/ai/intro.ts
  • apps/docs/src/web/routeTree.gen.ts
  • packages/core/src/services/config.ts
  • packages/core/src/env.d.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/ai-help.ts
  • packages/server/test/config.test.ts
  • examples/services-aigateway/src/agent/aigateway/agent.ts
  • apps/docs/scripts/generate-api-reference.ts
  • packages/aigateway/src/index.ts
  • packages/core/src/services/aigateway/service.ts
**/index.ts

📄 CodeRabbit inference engine (AGENTS.md)

Use named exports from package index.ts files

Files:

  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/core/src/services/aigateway/index.ts
  • packages/core/src/services/index.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/aigateway/src/index.ts
**/test/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/test/**/*.{ts,tsx}: Place tests in test/ folder, never in src/ or __tests__/ directories
Import from ../src/ in test files
Use @agentuity/test-utils for mocks in tests

Files:

  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/test/config/profile-creation.test.ts
  • packages/core/test/aigateway.test.ts
  • packages/server/test/config.test.ts
packages/core/src/**/*.ts

📄 CodeRabbit inference engine (packages/core/AGENTS.md)

packages/core/src/**/*.ts: Build TypeScript with bun run build command
Run TypeScript type checking with bun run typecheck command
Ensure runtime compatibility with both Browser and Node/Bun environments with no runtime-specific code
Build target must be ESNext with TypeScript declaration files
Prefer interfaces for public APIs
Use generics for reusable type utilities
Ensure no side effects in all exports - all exports must be pure with no global mutations
All relative imports in TypeScript files MUST include the .ts extension
Run bun run build before publishing to compile TypeScript

Files:

  • packages/core/src/services/aigateway/index.ts
  • packages/core/src/services/index.ts
  • packages/core/src/services/aigateway/api-reference.ts
  • packages/core/src/services/config.ts
  • packages/core/src/env.d.ts
  • packages/core/src/services/aigateway/service.ts
apps/docs/src/web/**/*.tsx

📄 CodeRabbit inference engine (apps/docs/src/web/AGENTS.md)

apps/docs/src/web/**/*.tsx: Wrap your app with AgentuityProvider for React hooks (useAgent, useAPI, useAgentWebsocket, useAgentEventStream) to work correctly
Use useAgent hook for one-off agent calls and useAgentWebsocket for bidirectional real-time communication
Use useAgentEventStream for server-to-client streaming operations in React components
Place reusable components in separate files rather than inline
Handle loading and error states in UI when using Agentuity hooks
Use TypeScript for type safety in React components
For static assets referenced from JS/TSX, use import url from './path.svg' instead of string literals like /public/foo.svg

apps/docs/src/web/**/*.tsx: Use the useSandboxRunner hook from src/web/hooks/useSandboxRunner.ts to execute sandbox scripts in React components
Use the TerminalOutput component from src/web/components/TerminalOutput.tsx to display streaming sandbox output
Use Tailwind CSS for styling in React components
Use hot module reloading in dev mode with import.meta.hot for React components

Files:

  • apps/docs/src/web/routes/_docs/reference/api/ai-gateway.tsx
apps/docs/src/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/docs/AGENTS.md)

apps/docs/src/web/**/*.{ts,tsx}: Place React frontend code in the src/web/ directory, with frontend.tsx as the entry point and App.tsx as the main component
Use React 19 for the frontend with support for modern React features and TypeScript

Files:

  • apps/docs/src/web/routes/_docs/reference/api/ai-gateway.tsx
  • apps/docs/src/web/components/docs/nav-data.ts
  • apps/docs/src/web/routeTree.gen.ts
packages/core/src/services/*.ts

📄 CodeRabbit inference engine (packages/core/AGENTS.md)

Storage services must take a FetchAdapter for HTTP abstraction

Files:

  • packages/core/src/services/index.ts
  • packages/core/src/services/config.ts
packages/server/src/**/*.ts

📄 CodeRabbit inference engine (packages/server/AGENTS.md)

packages/server/src/**/*.ts: All code must be written in TypeScript
Use Zod schemas for runtime validation
Always use .ts extensions in relative imports (e.g., from '../api.ts', not from '../api'). This is required for Node.js ESM compatibility — tsc rewrites .ts.js in compiled output, but leaves extensionless imports untouched, which breaks Node.js module resolution. This is enforced by the useImportExtensions Biome lint rule.

Files:

  • packages/server/src/config.ts
packages/core/**/*.test.ts

📄 CodeRabbit inference engine (packages/core/AGENTS.md)

Use Bun's built-in test runner with bun test command

Files:

  • packages/core/test/aigateway.test.ts
apps/docs/src/web/content/**/*.mdx

📄 CodeRabbit inference engine (apps/docs/src/web/content/AGENTS.md)

apps/docs/src/web/content/**/*.mdx: Write 1-2 sentences of motivation before showing code (context-then-code pattern)
Avoid walls of text; use progressive disclosure with basic examples first, advanced patterns later
Standalone code examples must include imports and be runnable; short inline references are fine without imports
Use scannable formatting with headings, callouts, and inline comments that explain 'why' not 'what'
Explain why someone would use a feature; avoid hollow adjectives like 'powerful', 'seamless', or 'enterprise-grade'
Read SDK source code and AGENTS.md files before documenting APIs or CLI flags to ensure accuracy
Use action-oriented page titles (e.g., 'Calling Other Agents' not 'Agent Communication')
Reference images without the '/public/' prefix; Vite copies static assets from src/web/public/ to build root
Use ctx.logger in server and agent code examples, not console.log
Do not include suppression comments like @ts-ignore, eslint-disable, or similar in code examples
Explicitly mark optional parameters in prose; readers should not need to parse type signatures to understand optionality
Verify current model names in code examples before publishing; use both raw provider SDKs and AI SDK providers (openai(), anthropic()) across examples
Use s from @agentuity/schema for schema examples; also show Zod, ArkType, and Valibot across examples to demonstrate schema-agnostic SDK usage
For local-only browser callback values, use .env.local; verify env file precedence before naming an override file
For Drizzle Kit setup, show drizzle.config.ts with defineConfig, then run 'bunx drizzle-kit push' or normal generate/migrate flow; avoid inline --dialect, --schema, --url commands unless documenting those flags
Cross-links must include specific context explaining why the reader would follow the link; use generic 'See also' links
Link to external tools on first mention only; do not re-link the same resource on the same page
Page intro should be 1-2 sentences focu...

Files:

  • apps/docs/src/web/content/reference/api/sandboxes.mdx
  • apps/docs/src/web/content/reference/api/index.mdx
  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
🧠 Learnings (8)
📚 Learning: 2025-12-21T00:31:41.858Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 274
File: packages/cli/src/cmd/build/vite/server-bundler.ts:12-41
Timestamp: 2025-12-21T00:31:41.858Z
Learning: In Bun runtime, BuildMessage and ResolveMessage are global types and are not exported from the bun module. Do not import { BuildMessage } from 'bun' or similar; these types are available globally and should be used without import. This applies to all TypeScript files that target the Bun runtime within the repository.

Applied to files:

  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/cli/src/config.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/src/agent-detection.ts
  • packages/core/src/services/aigateway/index.ts
  • packages/cli/src/types.ts
  • apps/docs/src/web/components/docs/nav-data.ts
  • packages/core/src/services/index.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • examples/services-aigateway/app.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/cmd/cloud/aigateway/util.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/server/src/config.ts
  • packages/cli/test/config/profile-creation.test.ts
  • packages/core/test/aigateway.test.ts
  • packages/core/src/services/aigateway/api-reference.ts
  • packages/cli/src/cmd/ai/intro.ts
  • apps/docs/src/web/routeTree.gen.ts
  • packages/core/src/services/config.ts
  • packages/core/src/env.d.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/ai-help.ts
  • packages/server/test/config.test.ts
  • examples/services-aigateway/src/agent/aigateway/agent.ts
  • apps/docs/scripts/generate-api-reference.ts
  • packages/aigateway/src/index.ts
  • packages/core/src/services/aigateway/service.ts
📚 Learning: 2026-01-13T04:32:02.691Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 565
File: packages/cli/src/cmd/cloud/region-lookup.ts:14-26
Timestamp: 2026-01-13T04:32:02.691Z
Learning: Enforce sandbox identifier prefixes in new code within the CLI cloud region lookup: new sandboxes must use the sbx_ prefix. The snbx_ prefix may appear in legacy code or examples, but do not use snbx_ for new sandboxes. When reviewing changes in packages/cli/src/cmd/cloud/, ensure any created sandbox identifiers use sbx_ and remove or migrate any snbx_ usages in newly added code.

Applied to files:

  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/cmd/cloud/aigateway/util.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
📚 Learning: 2026-02-17T14:23:15.448Z
Learnt from: potofpie
Repo: agentuity/sdk PR: 974
File: packages/cli/src/cmd/git/account/list.ts:39-40
Timestamp: 2026-02-17T14:23:15.448Z
Learning: In the Agentuity CLI framework (packages/cli), when a subcommand declares requires: { auth: true }, the framework will automatically call requireAuth() before invoking the handler. Do not call requireAuth(ctx) manually inside command handlers. This applies to all TypeScript command files under packages/cli/src, including paths like packages/cli/src/cmd/git/account/list.ts.

Applied to files:

  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/cli/src/config.ts
  • packages/cli/src/agent-detection.ts
  • packages/cli/src/types.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/cmd/cloud/aigateway/util.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/src/cmd/ai/intro.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/ai-help.ts
📚 Learning: 2026-02-21T02:05:57.982Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 1010
File: packages/drizzle/test/proxy.test.ts:594-603
Timestamp: 2026-02-21T02:05:57.982Z
Learning: Do not rely on StructuredError from agentuity/core in test files or simple error handling paths. In tests and straightforward error handling, use plain Error objects to represent failures, reserving StructuredError for more complex error scenarios in application logic.

Applied to files:

  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/test/config/profile-creation.test.ts
  • packages/core/test/aigateway.test.ts
  • packages/server/test/config.test.ts
📚 Learning: 2026-01-09T20:33:30.464Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 515
File: apps/testing/nextjs-app/agentuity/tsconfig.json:0-0
Timestamp: 2026-01-09T20:33:30.464Z
Learning: In TypeScript tsconfig.json files used by Agentuity projects, when a generated type file (e.g. .agentuity/.agentuity_types.ts) must be included while its parent directory is excluded, use include with an explicit file path (or a precise glob) instead of files. The files array requires files to exist at parse time and will fail for generated files; include with a suitable pattern allows the file to be picked up once generated without failing if it doesn't exist yet.

Applied to files:

  • packages/aigateway/tsconfig.json
  • tsconfig.json
📚 Learning: 2026-01-09T16:26:51.893Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 523
File: templates/_base/src/web/frontend.tsx:13-35
Timestamp: 2026-01-09T16:26:51.893Z
Learning: In web frontend code, prefer using the built-in Error class for runtime errors. Do not throw or re-export StructuredError from agentuity/core in web app code. Replace instances of StructuredError with new Error or custom error types that extend Error; ensure error handling logic remains intact and that error messages are descriptive. This guideline applies to all web UI TypeScript/TSX files that run in the browser and import StructuredError from agentuity/core.

Applied to files:

  • apps/docs/src/web/routes/_docs/reference/api/ai-gateway.tsx
📚 Learning: 2026-03-27T23:18:58.450Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 1292
File: packages/keyvalue/package.json:3-3
Timestamp: 2026-03-27T23:18:58.450Z
Learning: In the agentuity/sdk monorepo, subpackage `package.json` files under `packages/` (e.g., `packages/keyvalue`) are allowed to depend on other workspace packages (such as `agentuity/server`) and are not limited to only `agentuity/core` and `zod`. Also, if a subpackage uses `bunx tsc --build --force` as its build script, treat it as a valid/intentional build command and do not flag it as a dependency/build-script violation.

Applied to files:

  • packages/aigateway/package.json
📚 Learning: 2025-12-30T00:13:37.849Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 355
File: packages/server/src/api/sandbox/util.ts:2-6
Timestamp: 2025-12-30T00:13:37.849Z
Learning: In the packages/server tree, treat code as runtime-agnostic between Node.js and Bun. Ensure TypeScript files (e.g., util.ts) import and use APIs in a way that works under both runtimes. It is acceptable to rely on Bun’s Node.js compatibility for built-ins accessed via the node: namespace (e.g., node:events, node:stream, node:buffer). During reviews, prefer patterns and imports that remain compatible with Bun's environment, and flag any hard dependencies on runtime-specific globals or non-portable Node APIs.

Applied to files:

  • packages/server/src/config.ts
  • packages/server/test/config.test.ts
🪛 LanguageTool
examples/README.md

[grammar] ~19-~19: Ensure spelling is correct
Context: ...e-safe LLM interactions #### services-aigateway AI Gateway service usage with the standa...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)

🔇 Additional comments (31)
packages/cli/test/config/profile-creation.test.ts (1)

27-27: Good test isolation update.

Adding AGENTUITY_AIGATEWAY_URL to cleanup avoids host env leakage into config tests.

examples/services-aigateway/package.json (1)

1-18: Manifest looks solid for a workspace example.

Scripts and workspace dependency wiring are clean and aligned with the new example’s purpose.

packages/cli/src/cmd/ai/intro.ts (1)

58-58: Nice intro sync with new command surface.

Including cloud aigateway here improves discoverability for agents using the CLI intro flow.

examples/services-aigateway/README.md (1)

1-81: README is clear and actionable.

The usage flow, testing snippets, and environment variable guidance make this example easy to run and validate.

examples/README.md (1)

19-28: Docs index updates look good.

The new example is consistently reflected in the section list, category table, and advanced quick-start path.

Also applies to: 160-160, 176-178

packages/aigateway/README.md (1)

1-50: Strong package README baseline.

Quick start + configuration + env var reference gives a clear first-use path for @agentuity/aigateway.

packages/core/src/env.d.ts (1)

73-77: Env typing addition is clean and consistent.

These new ProcessEnv fields match the AI Gateway configuration surface introduced in this PR.

packages/core/src/services/aigateway/api-reference.ts (1)

1-163: LGTM!

The API reference schema and service definition are well-structured. The Zod schemas correctly use .catchall(z.unknown()) to allow pass-through of additional provider-specific fields, and the endpoint definitions properly document the OpenAI-compatible chat completion interface with both streaming and non-streaming variants.

packages/core/src/services/config.ts (1)

9-9: LGTM!

The aigateway URL configuration follows the established pattern for other service endpoints. The schema field and URL resolution are properly aligned, with environment variable override (AGENTUITY_AIGATEWAY_URL) and regional fallback.

Also applies to: 46-46

package.json (1)

12-13: LGTM!

The aigateway package is correctly positioned in the build chain after its dependencies (core, server) and before packages that might depend on it.

packages/aigateway/package.json (1)

1-42: LGTM!

The package manifest is well-configured with proper workspace dependencies, build scripts, and export configuration. The dependency on both @agentuity/core and @agentuity/server is appropriate for the client wrapper pattern.

packages/server/src/config.ts (1)

5-5: LGTM!

The aigateway URL configuration in the server package mirrors the core implementation correctly, using process.env directly as appropriate for server-side code while maintaining runtime compatibility between Node.js and Bun.

Also applies to: 39-40

packages/server/README.md (1)

28-28: LGTM!

The documentation update correctly demonstrates the new urls.aigateway property with an appropriate URL format example, consistent with the existing documentation style in this README.

apps/docs/src/web/content/reference/api/sandboxes.mdx (1)

175-180: LGTM!

The API documentation updates for timeout.paused and executionId fields are well-structured and follow the established documentation format. These appear to be legitimate additions regenerated alongside the AI Gateway documentation.

Also applies to: 291-296, 762-767

packages/aigateway/src/index.ts (1)

1-79: LGTM!

The AIGatewayClient implementation is well-structured:

  • Proper re-exports from core for type convenience
  • Clean options validation with Zod schema
  • Sensible API key resolution chain with multiple fallback sources
  • Region defaults to 'usc' as documented in PR objectives
  • Proper encapsulation with private #service field and delegating methods
packages/core/src/services/index.ts (1)

2-2: Looks good for service surface wiring.

This cleanly exposes the new AI Gateway module through the core services barrel.

README.md (1)

65-65: Nice addition to package map.

The new packages/aigateway entry improves discoverability of the new surface area.

tsconfig.json (1)

5-5: Project reference update looks correct.

Including ./packages/aigateway in root references aligns with the new package integration.

apps/docs/src/web/content/reference/api/index.mdx (1)

8-18: Docs index integration is clean.

AI Gateway card/link and icon wiring fit the existing API reference layout.

apps/docs/src/web/content/reference/api/meta.json (1)

5-5: Meta registration looks good.

Adding ai-gateway here correctly includes the page in API reference navigation.

apps/docs/src/web/components/docs/nav-data.ts (1)

661-666: Looks good — nav entry is correctly wired.

The new AI Gateway API reference item is well-formed and matches the expected docs URL shape.

packages/aigateway/tsconfig.json (1)

1-11: TS project config setup is solid.

The new package config is correctly structured for composite builds and project references.

apps/docs/src/web/routes/_docs/reference/api/ai-gateway.tsx (1)

4-7: Route registration is correct.

The new file-route, MDX route key, and crumb metadata are aligned.

packages/cli/src/config.ts (1)

229-231: Nice addition — env override wiring is consistent.

Line 229 through Line 231 cleanly adds AI Gateway URL override support in the same pattern as other service URLs.

packages/cli/src/cmd/cloud/index.ts (1)

45-45: Subcommand registration placement looks good.

Line 45 correctly wires aigatewayCommand into the cloud command tree.

packages/cli/src/ai-help.ts (1)

118-118: Help content update is aligned with the new CLI surface.

The AI Gateway additions in both the use-cases section and quick-reference priorities are consistent with the PR scope.

Also applies to: 231-240

examples/services-aigateway/app.ts (1)

1-6: Example bootstrap wiring is correct.

This cleanly registers the AI Gateway agent in the app entrypoint.

packages/cli/src/types.ts (1)

44-44: Schema extension is well-scoped.

Line 44 cleanly adds the AI Gateway override alongside existing URL overrides.

packages/cli/src/cmd/cloud/aigateway/complete.ts (1)

270-432: LGTM!

The completeSubcommand is well-structured with comprehensive schema definitions, clear examples, and proper handling of both streaming and non-streaming completion flows. The retry mechanism for model lookup on cache miss (lines 356-359) is good defensive coding.

packages/cli/src/cmd/cloud/aigateway/util.ts (1)

1-86: LGTM!

The utility functions are well-designed:

  • URL resolution follows a sensible priority order (env → overrides → region-based service URLs).
  • createAIGatewayService enforces orgId with a clear error message.
  • getCompletionText robustly handles various LLM response formats including OpenAI-style choices, direct content fields, and content arrays.
apps/docs/src/web/routeTree.gen.ts (1)

172-172: LGTM!

This is an auto-generated TanStack Router route tree file. The additions correctly wire the new AI Gateway API reference route (/reference/api/ai-gateway) following the established patterns for other API reference routes.

Also applies to: 1014-1018, 1290-1290, 1478-1478, 1670-1670, 2241-2241, 2862-2862, 2050-2050, 3470-3476, 3677-3677, 3704-3704

Comment thread apps/docs/src/web/content/reference/api/ai-gateway.mdx
Comment thread examples/services-aigateway/src/agent/aigateway/agent.ts
Comment thread packages/cli/src/agent-detection.ts
Comment thread packages/cli/src/cmd/ai/capabilities/show.ts Outdated
Comment thread packages/cli/src/cmd/cloud/aigateway/models.ts
Comment thread packages/core/src/services/aigateway/service.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

♻️ Duplicate comments (1)
apps/docs/src/web/content/reference/api/ai-gateway.mdx (1)

12-20: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix /models auth docs to match current public endpoint behavior.

Line 14 and the /models status table currently document auth-required behavior, but this PR exposes GET /models without auth/org/region. Please update the generator source and regenerate this page so /models is explicitly public and does not advertise unauthorized access for missing tokens.

Suggested doc adjustment
 ## Authentication
 
-All requests require a Bearer token. Pass your API or SDK key in the `Authorization` header.
+`GET /models` is public and does not require authentication.
+All completion endpoints require a Bearer token in the `Authorization` header.
@@
 | Status | Description |
 |--------|-------------|
 | 200 | Model catalog returned |
-| 401 | Unauthorized — invalid or missing API key |

As per coding guidelines, "Read SDK source code and AGENTS.md files before documenting APIs or CLI flags to ensure accuracy".

Also applies to: 36-40

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/docs/src/web/content/reference/api/ai-gateway.mdx` around lines 12 - 20,
Update the docs so GET /models is documented as a public endpoint: modify the
ai-gateway.mdx content that currently states "All requests require a Bearer
token" and the `/models` status table entries to explicitly mark `/models` as
public / "no auth required" (remove or override the `Authorization` / `Bearer
YOUR_SDK_KEY` requirement for that endpoint), update the table rows around the
`/models` entry (lines referencing the `Authorization` header and the `/models`
status table) and then regenerate the page from the doc generator source so the
change is produced from the generator rather than only editing the rendered MDX.
🧹 Nitpick comments (1)
packages/cli/src/cmd/cloud/aigateway/complete.ts (1)

338-341: ⚡ Quick win

Prefer StructuredError over tui.fatal for this validation failure.

This new command otherwise returns structured data, but this branch bypasses the standard typed error path. Throwing a StructuredError keeps automation and JSON consumers consistent with the rest of the CLI.

As per coding guidelines, "Use StructuredError from @agentuity/core for error handling".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cmd/cloud/aigateway/complete.ts` around lines 338 - 341,
Replace the non-structured exit in the prompt validation branch by throwing a
StructuredError instead of calling tui.fatal: import StructuredError from
'@agentuity/core' (or add it to existing imports), then in the branch that
currently checks if (!prompt) throw new StructuredError('Prompt is required.
Pass it as an argument, use --prompt, use --file, or pipe it through stdin.') so
the command returns a typed error consistent with other CLI commands (keep the
existing message text and ensure this change is made in the same
function/conditional that currently references the prompt variable).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cli/src/cmd/cloud/aigateway/complete.ts`:
- Around line 224-229: The raw-stream branch returns early before adding delta
text to the accumulated output, so --save and JSON output get an empty string;
update the handler referenced around the raw handling (options.raw/options.json
checks in complete.ts) to append the incoming delta (the variable used for
streamed token data) to the accumulated text buffer before printing raw data and
continuing, or alternatively write streamed deltas directly to the save
buffer/file instead of relying on the final text variable; apply the same fix to
the duplicate raw branch around the later occurrence (the 380-385 area) so both
streaming/raw codepaths preserve tokens for --save and JSON output.
- Around line 117-125: getCompletionModelInfo currently returns the resolved
canonical id and api but the request-building code still uses the original model
string and always builds chat-style messages; update the request builders (the
code paths around getCompletionModelInfo as well as the similar blocks at the
ranges mentioned) to use the returned CompletionModelInfo.id as the
model/callable identifier and CompletionModelInfo.api to select the correct
request shape (e.g., chat-style messages for chat APIs vs
single-input/completion fields for non-chat APIs), and ensure
matchesModel/getCompletionModelInfo are called first and their result is used to
choose payload shape and model id everywhere the old model string was used.
- Around line 378-391: After awaiting streamed.metadata, also handle the --usage
flag: extract usage info from metadata and render it just like cost.
Specifically, after const metadata = await streamed.metadata (and alongside the
existing cost handling and JSON branch), if ctx.opts.usage is set call the
usage-formatting helper (e.g., getUsageText or the existing usage formatter used
elsewhere) with { agentuity: metadata } and print it (stderr like cost). Also
include usage in the JSON output when format === 'json' (e.g., add a usage field
under the response object) so streaming JSON responses contain usage info too.

In `@packages/coder-tui/src/aigateway.ts`:
- Around line 135-143: The fetchModels function currently swallows errors in
four catch blocks (including the one around AIGatewayService.listModels) using
console.warn and returning an empty object; replace each catch handler to throw
a StructuredError from `@agentuity/core` instead. Import StructuredError if
missing, then in each catch (the blocks surrounding AIGatewayService
instantiation/calls in fetchModels) construct and throw new
StructuredError('Failed to fetch models from AI Gateway', { cause: error }) (or
similar structured payload) so the original error is preserved and propagated
instead of logging and returning {}. Ensure all four catch sites in fetchModels
use the same StructuredError pattern for consistency with the project's
TypeScript error handling guideline.
- Around line 151-152: The code trusts external catalog values by casting
m.input_modalities with "as ('text' | 'image')[]"; instead, validate and
sanitize those strings before assignment: read m.input_modalities (from
AIGatewayModel), filter/map to only allowed modalities ('text' and 'image'), and
if the result is empty or undefined fallback to ['text']; replace the unchecked
cast in the mapping where you set input (the expression using
m.input_modalities) with this sanitized value so only valid modalities
propagate.

---

Duplicate comments:
In `@apps/docs/src/web/content/reference/api/ai-gateway.mdx`:
- Around line 12-20: Update the docs so GET /models is documented as a public
endpoint: modify the ai-gateway.mdx content that currently states "All requests
require a Bearer token" and the `/models` status table entries to explicitly
mark `/models` as public / "no auth required" (remove or override the
`Authorization` / `Bearer YOUR_SDK_KEY` requirement for that endpoint), update
the table rows around the `/models` entry (lines referencing the `Authorization`
header and the `/models` status table) and then regenerate the page from the doc
generator source so the change is produced from the generator rather than only
editing the rendered MDX.

---

Nitpick comments:
In `@packages/cli/src/cmd/cloud/aigateway/complete.ts`:
- Around line 338-341: Replace the non-structured exit in the prompt validation
branch by throwing a StructuredError instead of calling tui.fatal: import
StructuredError from '@agentuity/core' (or add it to existing imports), then in
the branch that currently checks if (!prompt) throw new StructuredError('Prompt
is required. Pass it as an argument, use --prompt, use --file, or pipe it
through stdin.') so the command returns a typed error consistent with other CLI
commands (keep the existing message text and ensure this change is made in the
same function/conditional that currently references the prompt variable).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3897b1ee-4654-4286-973b-126750d3247f

📥 Commits

Reviewing files that changed from the base of the PR and between fb6762b and 793adf8.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
  • examples/README.md
  • examples/services-aigateway/README.md
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/cmd/cloud/aigateway/index.ts
  • packages/coder-tui/package.json
  • packages/coder-tui/src/aigateway.ts
  • packages/coder-tui/tsconfig.json
  • packages/core/src/services/aigateway/api-reference.ts
✅ Files skipped from review due to trivial changes (1)
  • examples/services-aigateway/README.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/cli/src/cmd/cloud/aigateway/index.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Biome as code formatter with tabs (width 3), single quotes, semicolons, lineWidth 100, and trailingCommas es5

Files:

  • packages/core/src/services/aigateway/api-reference.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/coder-tui/src/aigateway.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript Strict mode with ESNext target and bundler moduleResolution
Use StructuredError from @agentuity/core for error handling

Files:

  • packages/core/src/services/aigateway/api-reference.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/coder-tui/src/aigateway.ts
packages/core/src/**/*.ts

📄 CodeRabbit inference engine (packages/core/AGENTS.md)

packages/core/src/**/*.ts: Build TypeScript with bun run build command
Run TypeScript type checking with bun run typecheck command
Ensure runtime compatibility with both Browser and Node/Bun environments with no runtime-specific code
Build target must be ESNext with TypeScript declaration files
Prefer interfaces for public APIs
Use generics for reusable type utilities
Ensure no side effects in all exports - all exports must be pure with no global mutations
All relative imports in TypeScript files MUST include the .ts extension
Run bun run build before publishing to compile TypeScript

Files:

  • packages/core/src/services/aigateway/api-reference.ts
packages/cli/**/*.ts

📄 CodeRabbit inference engine (packages/cli/AGENTS.md)

Use Bun.file(f).exists() instead of existsSync(f) for file existence checks

Files:

  • packages/cli/src/cmd/cloud/aigateway/complete.ts
apps/docs/src/web/content/**/*.mdx

📄 CodeRabbit inference engine (apps/docs/src/web/content/AGENTS.md)

apps/docs/src/web/content/**/*.mdx: Write 1-2 sentences of motivation before showing code (context-then-code pattern)
Avoid walls of text; use progressive disclosure with basic examples first, advanced patterns later
Standalone code examples must include imports and be runnable; short inline references are fine without imports
Use scannable formatting with headings, callouts, and inline comments that explain 'why' not 'what'
Explain why someone would use a feature; avoid hollow adjectives like 'powerful', 'seamless', or 'enterprise-grade'
Read SDK source code and AGENTS.md files before documenting APIs or CLI flags to ensure accuracy
Use action-oriented page titles (e.g., 'Calling Other Agents' not 'Agent Communication')
Reference images without the '/public/' prefix; Vite copies static assets from src/web/public/ to build root
Use ctx.logger in server and agent code examples, not console.log
Do not include suppression comments like @ts-ignore, eslint-disable, or similar in code examples
Explicitly mark optional parameters in prose; readers should not need to parse type signatures to understand optionality
Verify current model names in code examples before publishing; use both raw provider SDKs and AI SDK providers (openai(), anthropic()) across examples
Use s from @agentuity/schema for schema examples; also show Zod, ArkType, and Valibot across examples to demonstrate schema-agnostic SDK usage
For local-only browser callback values, use .env.local; verify env file precedence before naming an override file
For Drizzle Kit setup, show drizzle.config.ts with defineConfig, then run 'bunx drizzle-kit push' or normal generate/migrate flow; avoid inline --dialect, --schema, --url commands unless documenting those flags
Cross-links must include specific context explaining why the reader would follow the link; use generic 'See also' links
Link to external tools on first mention only; do not re-link the same resource on the same page
Page intro should be 1-2 sentences focu...

Files:

  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
🧠 Learnings (6)
📚 Learning: 2026-03-27T23:18:58.450Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 1292
File: packages/keyvalue/package.json:3-3
Timestamp: 2026-03-27T23:18:58.450Z
Learning: In the agentuity/sdk monorepo, subpackage `package.json` files under `packages/` (e.g., `packages/keyvalue`) are allowed to depend on other workspace packages (such as `agentuity/server`) and are not limited to only `agentuity/core` and `zod`. Also, if a subpackage uses `bunx tsc --build --force` as its build script, treat it as a valid/intentional build command and do not flag it as a dependency/build-script violation.

Applied to files:

  • packages/coder-tui/package.json
📚 Learning: 2025-12-21T00:31:41.858Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 274
File: packages/cli/src/cmd/build/vite/server-bundler.ts:12-41
Timestamp: 2025-12-21T00:31:41.858Z
Learning: In Bun runtime, BuildMessage and ResolveMessage are global types and are not exported from the bun module. Do not import { BuildMessage } from 'bun' or similar; these types are available globally and should be used without import. This applies to all TypeScript files that target the Bun runtime within the repository.

Applied to files:

  • packages/core/src/services/aigateway/api-reference.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/coder-tui/src/aigateway.ts
📚 Learning: 2026-01-13T04:32:02.691Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 565
File: packages/cli/src/cmd/cloud/region-lookup.ts:14-26
Timestamp: 2026-01-13T04:32:02.691Z
Learning: Enforce sandbox identifier prefixes in new code within the CLI cloud region lookup: new sandboxes must use the sbx_ prefix. The snbx_ prefix may appear in legacy code or examples, but do not use snbx_ for new sandboxes. When reviewing changes in packages/cli/src/cmd/cloud/, ensure any created sandbox identifiers use sbx_ and remove or migrate any snbx_ usages in newly added code.

Applied to files:

  • packages/cli/src/cmd/cloud/aigateway/complete.ts
📚 Learning: 2026-02-17T14:23:15.448Z
Learnt from: potofpie
Repo: agentuity/sdk PR: 974
File: packages/cli/src/cmd/git/account/list.ts:39-40
Timestamp: 2026-02-17T14:23:15.448Z
Learning: In the Agentuity CLI framework (packages/cli), when a subcommand declares requires: { auth: true }, the framework will automatically call requireAuth() before invoking the handler. Do not call requireAuth(ctx) manually inside command handlers. This applies to all TypeScript command files under packages/cli/src, including paths like packages/cli/src/cmd/git/account/list.ts.

Applied to files:

  • packages/cli/src/cmd/cloud/aigateway/complete.ts
📚 Learning: 2026-01-09T20:33:30.464Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 515
File: apps/testing/nextjs-app/agentuity/tsconfig.json:0-0
Timestamp: 2026-01-09T20:33:30.464Z
Learning: In TypeScript tsconfig.json files used by Agentuity projects, when a generated type file (e.g. .agentuity/.agentuity_types.ts) must be included while its parent directory is excluded, use include with an explicit file path (or a precise glob) instead of files. The files array requires files to exist at parse time and will fail for generated files; include with a suitable pattern allows the file to be picked up once generated without failing if it doesn't exist yet.

Applied to files:

  • packages/coder-tui/tsconfig.json
📚 Learning: 2026-05-03T20:54:18.771Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 1443
File: packages/coder-tui/src/startup-logo.ts:111-145
Timestamp: 2026-05-03T20:54:18.771Z
Learning: In `agentuity/sdk`’s `packages/coder-tui`, when using the `mariozechner/pi-coding-agent` (Pi v0.72.1+) UI API, prefer calling `ctx.ui.setHeader(...)` without manually disposing the previously set custom header. The framework’s underlying `setExtensionHeader` implementation (`ctx.ui.setHeader`) disposes the existing `customHeader` before replacing it or clearing it, so extra/manual `dispose()` calls on the prior header instance are unnecessary (and may be redundant or error-prone) for this Pi version.

Applied to files:

  • packages/coder-tui/src/aigateway.ts
🔇 Additional comments (7)
packages/core/src/services/aigateway/api-reference.ts (3)

1-7: LGTM!

Imports are correctly structured with .ts extensions on relative imports, compliant with project coding guidelines.


9-36: LGTM!

Well-structured Zod schema for SSE streaming responses. The use of .catchall(z.unknown()) appropriately allows for provider-specific additional fields while defining the core structure, and the delta object correctly models incremental streaming content.


38-163: LGTM!

The service definition is comprehensive and well-documented:

  • Clear endpoint separation between non-streaming and streaming completions (differentiated by stream: true)
  • Appropriate response headers for billing metadata including HTTP trailers for streaming responses
  • Good example payloads demonstrating both modes

The status codes 401/402 on list-models are consistent with an optionally-authenticated endpoint design.

packages/coder-tui/package.json (1)

28-29: Workspace dependency additions look correct.

These additions are consistent with the new coder-tui integration against core/server AI Gateway surfaces.

packages/coder-tui/tsconfig.json (1)

7-12: TS project wiring looks solid.

The added path aliases and references match the new core/server dependency flow and should support local type-check/build integration cleanly.

Also applies to: 16-16

examples/README.md (1)

19-28: Nice addition and indexing consistency for services-aigateway.

The new example is documented consistently across the section listing, category table, and advanced quick-start flow.

Also applies to: 160-160, 176-178

packages/coder-tui/src/aigateway.ts (1)

13-19: Good service-layer wiring for the TUI provider path.

Nice move to AIGatewayService + server fetch adapter here; this keeps gateway access consistent with the rest of the PR.

Comment thread packages/cli/src/cmd/cloud/aigateway/complete.ts
Comment thread packages/cli/src/cmd/cloud/aigateway/complete.ts
Comment on lines +378 to +391
const metadata = await streamed.metadata;
const cost = metadata.cost;
if (ctx.opts.save) {
await Bun.write(ctx.opts.save, text);
}
if (!ctx.options.json && format === 'json') {
console.log(JSON.stringify({ text, cost, response: { stream: true, model } }, null, 2));
}
if (!ctx.options.json && ctx.opts.cost) {
const costText = getCostText({ agentuity: metadata });
if (costText) {
console.error(costText);
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Handle --usage in the streaming branch too.

After await streamed.metadata, this path only renders cost. cloud aigateway complete --stream --usage is currently a no-op even though the metadata has already been collected.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cmd/cloud/aigateway/complete.ts` around lines 378 - 391,
After awaiting streamed.metadata, also handle the --usage flag: extract usage
info from metadata and render it just like cost. Specifically, after const
metadata = await streamed.metadata (and alongside the existing cost handling and
JSON branch), if ctx.opts.usage is set call the usage-formatting helper (e.g.,
getUsageText or the existing usage formatter used elsewhere) with { agentuity:
metadata } and print it (stderr like cost). Also include usage in the JSON
output when format === 'json' (e.g., add a usage field under the response
object) so streaming JSON responses contain usage info too.

Comment thread packages/coder-tui/src/aigateway.ts Outdated
Comment thread packages/coder-tui/src/aigateway.ts Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
packages/cli/src/cmd/ai/capabilities/show.ts (1)

131-136: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Split AI Gateway capability metadata by auth requirements.

Removing the blanket flags fixes cloud aigateway models, but now capabilities show implies cloud aigateway complete is public too. This surface still needs either per-command requirement metadata or separate capability entries for models vs. completions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cmd/ai/capabilities/show.ts` around lines 131 - 136, The
capability entry with id 'aigateway' currently groups both 'cloud aigateway
models' and 'cloud aigateway complete' under the same metadata which incorrectly
exposes the completion command as public in the capabilities show output; modify
the capability metadata by either (A) splitting this object into two distinct
capability entries (e.g., 'aigateway-models' and 'aigateway-complete') so each
command has its own auth requirement, or (B) extend the existing capability
object to include per-command auth metadata (e.g., add a commands array of
objects with command and requiredAuth fields) and update whatever renderer reads
capabilities to honor per-command auth; update the entry that currently has id
'aigateway' and the commands list containing 'cloud aigateway models' and 'cloud
aigateway complete' accordingly so the show output reflects correct auth
requirements.
packages/cli/src/cmd/cloud/aigateway/complete.ts (1)

389-416: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

--usage flag is not handled in the streaming branch.

The streaming path handles --cost (lines 409-414) but does not print usage information when ctx.opts.usage is set. The non-streaming path handles both at lines 445-456.

Suggested fix
 			if (!ctx.options.json && ctx.opts.cost) {
 				const costText = getCostText({ agentuity: metadata });
 				if (costText) {
 					console.error(costText);
 				}
 			}
+			if (!ctx.options.json && ctx.opts.usage) {
+				// Note: streaming responses don't include usage in metadata by default
+				// Usage would need to be accumulated from stream events if available
+			}
 			return { text, response: { stream: true, model: requestModel }, cost };

Alternatively, if usage data is genuinely unavailable in streaming mode, document this limitation in the --usage option description.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cmd/cloud/aigateway/complete.ts` around lines 389 - 416, The
streaming branch omits handling the --usage flag; update the block after
retrieving metadata in the stream path (following streamed.metadata and cost) to
mirror the non-streaming branch: if ctx.opts.usage call the same helper used
elsewhere (e.g., getUsageText) passing the metadata (or the same shape used by
getCostText/getUsageText), write the returned usage text to stderr if present,
and otherwise no-op; if the metadata shape differs in streaming mode, adapt by
extracting the usage fields from streamed.metadata before calling getUsageText
or, if usage truly isn't available in streaming, add a short comment and ensure
the CLI docs/option description note that limitation.
🧹 Nitpick comments (1)
packages/cli/src/cmd/cloud/aigateway/model-cache.ts (1)

9-38: 💤 Low value

Consider documenting the singleton database lifetime.

The module-level db singleton is never explicitly closed. While acceptable for a CLI tool (process exit handles cleanup), adding a brief comment clarifying this design choice would help future maintainers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cmd/cloud/aigateway/model-cache.ts` around lines 9 - 38, The
module-level Database singleton `db` returned by `getDatabase()` is never
explicitly closed; add a brief comment above the `let db: Database | null =
null;` and/or atop `getDatabase()` documenting the intentional lifetime (CLI
short-lived process, rely on process exit for cleanup) and the reason for not
calling `db.close()` here; also mention that if long-lived use-cases arise we
should export a `closeDatabase()` helper that calls `db.close()` and set `db =
null`.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/services/aigateway/api-reference.ts`:
- Around line 55-57: The response description for the /models endpoint
incorrectly implies the provider map is top-level; update the
responseDescription string where responseFields uses
AIGatewayModelsResponseSchema to state that the JSON response contains the
provider catalog under the "data" field (e.g. "JSON response with provider keys
mapped to arrays of supported model metadata under the 'data' envelope"), so the
description matches the envelope shape used by AIGatewayModelsResponseSchema.

---

Duplicate comments:
In `@packages/cli/src/cmd/ai/capabilities/show.ts`:
- Around line 131-136: The capability entry with id 'aigateway' currently groups
both 'cloud aigateway models' and 'cloud aigateway complete' under the same
metadata which incorrectly exposes the completion command as public in the
capabilities show output; modify the capability metadata by either (A) splitting
this object into two distinct capability entries (e.g., 'aigateway-models' and
'aigateway-complete') so each command has its own auth requirement, or (B)
extend the existing capability object to include per-command auth metadata
(e.g., add a commands array of objects with command and requiredAuth fields) and
update whatever renderer reads capabilities to honor per-command auth; update
the entry that currently has id 'aigateway' and the commands list containing
'cloud aigateway models' and 'cloud aigateway complete' accordingly so the show
output reflects correct auth requirements.

In `@packages/cli/src/cmd/cloud/aigateway/complete.ts`:
- Around line 389-416: The streaming branch omits handling the --usage flag;
update the block after retrieving metadata in the stream path (following
streamed.metadata and cost) to mirror the non-streaming branch: if
ctx.opts.usage call the same helper used elsewhere (e.g., getUsageText) passing
the metadata (or the same shape used by getCostText/getUsageText), write the
returned usage text to stderr if present, and otherwise no-op; if the metadata
shape differs in streaming mode, adapt by extracting the usage fields from
streamed.metadata before calling getUsageText or, if usage truly isn't available
in streaming, add a short comment and ensure the CLI docs/option description
note that limitation.

---

Nitpick comments:
In `@packages/cli/src/cmd/cloud/aigateway/model-cache.ts`:
- Around line 9-38: The module-level Database singleton `db` returned by
`getDatabase()` is never explicitly closed; add a brief comment above the `let
db: Database | null = null;` and/or atop `getDatabase()` documenting the
intentional lifetime (CLI short-lived process, rely on process exit for cleanup)
and the reason for not calling `db.close()` here; also mention that if
long-lived use-cases arise we should export a `closeDatabase()` helper that
calls `db.close()` and set `db = null`.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fbcc87ff-21a4-4478-8b2e-b9ca30f927b2

📥 Commits

Reviewing files that changed from the base of the PR and between 793adf8 and 99aa54c.

📒 Files selected for processing (15)
  • apps/docs/scripts/generate-api-reference.ts
  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
  • examples/services-aigateway/src/agent/aigateway/agent.ts
  • packages/cli/src/agent-detection.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/coder-tui/src/aigateway.ts
  • packages/core/src/services/aigateway/api-reference.ts
  • packages/core/src/services/aigateway/index.ts
  • packages/core/src/services/aigateway/service.ts
  • packages/core/src/services/api-reference.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
  • GitHub Check: Pack & Upload
  • GitHub Check: Postgres SSL Integration Test
  • GitHub Check: Template Integration Tests
  • GitHub Check: Package Installation & Usage Test
  • GitHub Check: Playwright E2E Smoke Test
  • GitHub Check: Queue CLI Tests
  • GitHub Check: Cloud Deployment Tests
  • GitHub Check: Standalone Agent Test
  • GitHub Check: Windows WSL CLI Smoke Test
  • GitHub Check: Framework Integration Tests (TanStack & Next.js)
  • GitHub Check: SDK Integration Test Suite
  • GitHub Check: Build
  • GitHub Check: Agentuity Deployment
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Biome as code formatter with tabs (width 3), single quotes, semicolons, lineWidth 100, and trailingCommas es5

Files:

  • packages/core/src/services/aigateway/api-reference.ts
  • packages/core/src/services/api-reference.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/core/src/services/aigateway/service.ts
  • packages/core/src/services/aigateway/index.ts
  • examples/services-aigateway/src/agent/aigateway/agent.ts
  • packages/cli/src/agent-detection.ts
  • apps/docs/scripts/generate-api-reference.ts
  • packages/coder-tui/src/aigateway.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript Strict mode with ESNext target and bundler moduleResolution
Use StructuredError from @agentuity/core for error handling

Files:

  • packages/core/src/services/aigateway/api-reference.ts
  • packages/core/src/services/api-reference.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/core/src/services/aigateway/service.ts
  • packages/core/src/services/aigateway/index.ts
  • examples/services-aigateway/src/agent/aigateway/agent.ts
  • packages/cli/src/agent-detection.ts
  • apps/docs/scripts/generate-api-reference.ts
  • packages/coder-tui/src/aigateway.ts
packages/core/src/**/*.ts

📄 CodeRabbit inference engine (packages/core/AGENTS.md)

packages/core/src/**/*.ts: Build TypeScript with bun run build command
Run TypeScript type checking with bun run typecheck command
Ensure runtime compatibility with both Browser and Node/Bun environments with no runtime-specific code
Build target must be ESNext with TypeScript declaration files
Prefer interfaces for public APIs
Use generics for reusable type utilities
Ensure no side effects in all exports - all exports must be pure with no global mutations
All relative imports in TypeScript files MUST include the .ts extension
Run bun run build before publishing to compile TypeScript

Files:

  • packages/core/src/services/aigateway/api-reference.ts
  • packages/core/src/services/api-reference.ts
  • packages/core/src/services/aigateway/service.ts
  • packages/core/src/services/aigateway/index.ts
packages/core/src/services/*.ts

📄 CodeRabbit inference engine (packages/core/AGENTS.md)

Storage services must take a FetchAdapter for HTTP abstraction

Files:

  • packages/core/src/services/api-reference.ts
packages/cli/src/cmd/**/index.ts

📄 CodeRabbit inference engine (packages/cli/AGENTS.md)

packages/cli/src/cmd/**/index.ts: Each command must be structured as a directory in src/cmd/ with an index.ts file as the entry point
Always define interfaces or Zod schemas for command options; never use any type for type safety
Use tui.* helpers (header, info, success, warning, error, table, progress) for formatted TUI output instead of raw console methods
Use ctx.logger for logging instead of console methods; use logger.fatal() for fatal errors which logs and exits with code 1
Always check isJSONMode() before outputting data and provide machine-readable output when in JSON mode
Use requireAuth(ctx) for commands that require authentication or optionalAuth(ctx) for commands that support optional authentication

Files:

  • packages/cli/src/cmd/cloud/index.ts
packages/cli/**/*.ts

📄 CodeRabbit inference engine (packages/cli/AGENTS.md)

Use Bun.file(f).exists() instead of existsSync(f) for file existence checks

Files:

  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/agent-detection.ts
**/index.ts

📄 CodeRabbit inference engine (AGENTS.md)

Use named exports from package index.ts files

Files:

  • packages/cli/src/cmd/cloud/index.ts
  • packages/core/src/services/aigateway/index.ts
**/test/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/test/**/*.{ts,tsx}: Place tests in test/ folder, never in src/ or __tests__/ directories
Import from ../src/ in test files
Use @agentuity/test-utils for mocks in tests

Files:

  • packages/cli/test/cmd/cloud/aigateway.test.ts
apps/docs/src/web/content/**/*.mdx

📄 CodeRabbit inference engine (apps/docs/src/web/content/AGENTS.md)

apps/docs/src/web/content/**/*.mdx: Write 1-2 sentences of motivation before showing code (context-then-code pattern)
Avoid walls of text; use progressive disclosure with basic examples first, advanced patterns later
Standalone code examples must include imports and be runnable; short inline references are fine without imports
Use scannable formatting with headings, callouts, and inline comments that explain 'why' not 'what'
Explain why someone would use a feature; avoid hollow adjectives like 'powerful', 'seamless', or 'enterprise-grade'
Read SDK source code and AGENTS.md files before documenting APIs or CLI flags to ensure accuracy
Use action-oriented page titles (e.g., 'Calling Other Agents' not 'Agent Communication')
Reference images without the '/public/' prefix; Vite copies static assets from src/web/public/ to build root
Use ctx.logger in server and agent code examples, not console.log
Do not include suppression comments like @ts-ignore, eslint-disable, or similar in code examples
Explicitly mark optional parameters in prose; readers should not need to parse type signatures to understand optionality
Verify current model names in code examples before publishing; use both raw provider SDKs and AI SDK providers (openai(), anthropic()) across examples
Use s from @agentuity/schema for schema examples; also show Zod, ArkType, and Valibot across examples to demonstrate schema-agnostic SDK usage
For local-only browser callback values, use .env.local; verify env file precedence before naming an override file
For Drizzle Kit setup, show drizzle.config.ts with defineConfig, then run 'bunx drizzle-kit push' or normal generate/migrate flow; avoid inline --dialect, --schema, --url commands unless documenting those flags
Cross-links must include specific context explaining why the reader would follow the link; use generic 'See also' links
Link to external tools on first mention only; do not re-link the same resource on the same page
Page intro should be 1-2 sentences focu...

Files:

  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
🧠 Learnings (5)
📚 Learning: 2025-12-21T00:31:41.858Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 274
File: packages/cli/src/cmd/build/vite/server-bundler.ts:12-41
Timestamp: 2025-12-21T00:31:41.858Z
Learning: In Bun runtime, BuildMessage and ResolveMessage are global types and are not exported from the bun module. Do not import { BuildMessage } from 'bun' or similar; these types are available globally and should be used without import. This applies to all TypeScript files that target the Bun runtime within the repository.

Applied to files:

  • packages/core/src/services/aigateway/api-reference.ts
  • packages/core/src/services/api-reference.ts
  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • packages/cli/test/cmd/cloud/aigateway.test.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/core/src/services/aigateway/service.ts
  • packages/core/src/services/aigateway/index.ts
  • examples/services-aigateway/src/agent/aigateway/agent.ts
  • packages/cli/src/agent-detection.ts
  • apps/docs/scripts/generate-api-reference.ts
  • packages/coder-tui/src/aigateway.ts
📚 Learning: 2026-01-13T04:32:02.691Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 565
File: packages/cli/src/cmd/cloud/region-lookup.ts:14-26
Timestamp: 2026-01-13T04:32:02.691Z
Learning: Enforce sandbox identifier prefixes in new code within the CLI cloud region lookup: new sandboxes must use the sbx_ prefix. The snbx_ prefix may appear in legacy code or examples, but do not use snbx_ for new sandboxes. When reviewing changes in packages/cli/src/cmd/cloud/, ensure any created sandbox identifiers use sbx_ and remove or migrate any snbx_ usages in newly added code.

Applied to files:

  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
📚 Learning: 2026-02-17T14:23:15.448Z
Learnt from: potofpie
Repo: agentuity/sdk PR: 974
File: packages/cli/src/cmd/git/account/list.ts:39-40
Timestamp: 2026-02-17T14:23:15.448Z
Learning: In the Agentuity CLI framework (packages/cli), when a subcommand declares requires: { auth: true }, the framework will automatically call requireAuth() before invoking the handler. Do not call requireAuth(ctx) manually inside command handlers. This applies to all TypeScript command files under packages/cli/src, including paths like packages/cli/src/cmd/git/account/list.ts.

Applied to files:

  • packages/cli/src/cmd/cloud/index.ts
  • packages/cli/src/cmd/ai/capabilities/show.ts
  • packages/cli/src/cmd/cloud/aigateway/complete.ts
  • packages/cli/src/cmd/cloud/aigateway/models.ts
  • packages/cli/src/cmd/cloud/aigateway/model-cache.ts
  • packages/cli/src/agent-detection.ts
📚 Learning: 2026-02-21T02:05:57.982Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 1010
File: packages/drizzle/test/proxy.test.ts:594-603
Timestamp: 2026-02-21T02:05:57.982Z
Learning: Do not rely on StructuredError from agentuity/core in test files or simple error handling paths. In tests and straightforward error handling, use plain Error objects to represent failures, reserving StructuredError for more complex error scenarios in application logic.

Applied to files:

  • packages/cli/test/cmd/cloud/aigateway.test.ts
📚 Learning: 2026-05-03T20:54:18.771Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 1443
File: packages/coder-tui/src/startup-logo.ts:111-145
Timestamp: 2026-05-03T20:54:18.771Z
Learning: In `agentuity/sdk`’s `packages/coder-tui`, when using the `mariozechner/pi-coding-agent` (Pi v0.72.1+) UI API, prefer calling `ctx.ui.setHeader(...)` without manually disposing the previously set custom header. The framework’s underlying `setExtensionHeader` implementation (`ctx.ui.setHeader`) disposes the existing `customHeader` before replacing it or clearing it, so extra/manual `dispose()` calls on the prior header instance are unnecessary (and may be redundant or error-prone) for this Pi version.

Applied to files:

  • packages/coder-tui/src/aigateway.ts
🔇 Additional comments (21)
packages/core/src/services/aigateway/service.ts (4)

1-9: LGTM - Well-structured error handling and imports.

The file properly uses StructuredError from @agentuity/core for error handling and includes the .ts extension in all relative imports as required by the coding guidelines.


11-151: LGTM - Comprehensive Zod schemas for AI Gateway types.

The schema definitions follow zod 4.x patterns correctly, with proper use of .describe() for documentation, .optional() for nullable fields, and .catchall(z.unknown()) for extensibility.


193-212: Previous cost-merging concern has been addressed.

The trailer metadata merging now correctly uses spread operators to combine cost fields from both headers and trailers, ensuring no values are lost when trailers contain partial cost information.


238-261: Previous gateway failure handling concern has been addressed.

The listModels() method now properly checks payload.success and throws AIGatewayModelsResponseError when the gateway indicates failure, preventing invalid catalog state propagation.

packages/core/src/services/aigateway/index.ts (1)

1-22: LGTM - Clean barrel file with proper named exports.

The index file correctly uses named exports and includes the .ts extension in the relative import path, following the coding guidelines.

packages/cli/src/cmd/cloud/aigateway/model-cache.ts (2)

40-67: LGTM - Robust cache read with TTL validation.

The cache read properly validates data using safeParse, handles TTL expiration, and silently fails on errors - appropriate for non-critical caching.


69-89: LGTM - Safe cache write with stale entry cleanup.

The upsert pattern and stale entry purging are well-implemented, and silently swallowing write errors is appropriate for a non-critical cache.

packages/cli/src/cmd/cloud/aigateway/models.ts (2)

36-50: Previous ID normalization concern has been addressed.

The getRecommendations function now uses normalizeModelId on both the catalog row IDs and the candidate IDs, ensuring matches work regardless of whether IDs include provider prefixes.


82-119: LGTM - Well-documented subcommand schema.

The command schema has clear descriptions for all options and good examples demonstrating different use cases.

packages/cli/src/cmd/cloud/aigateway/complete.ts (4)

372-377: Previous model ID resolution concern has been addressed.

The code now correctly uses modelInfo?.id ?? model as the requestModel, ensuring the resolved catalog entry ID is sent in the completion request.


236-249: Previous raw streaming text accumulation concern has been addressed.

The delta text is now extracted and accumulated (lines 237-240) before the raw-mode check, so --save correctly writes the accumulated text even in raw mode.


28-35: LGTM - Stdin reading handles TTY correctly.

The function properly checks process.stdin.isTTY to avoid blocking when stdin is a terminal.


37-51: LGTM - File prompt reading uses Bun.file().exists() as required.

The code correctly uses Bun.file(filename).exists() instead of existsSync, following the coding guidelines.

packages/cli/test/cmd/cloud/aigateway.test.ts (4)

1-18: LGTM - Proper test setup with cleanup.

The test file correctly imports from ../src/, uses afterEach to clean up the mock server and environment variables, preventing test pollution.


41-73: LGTM - Thorough subcommand schema validation.

The tests validate that both models and complete subcommands expose the expected schema shape, tags, and requirements.


287-331: LGTM - Comprehensive completion request and response testing.

The test validates the full request payload including model, messages, temperature, and max_tokens, plus verifies cost extraction from gateway headers.


511-559: LGTM - Streaming completion test with cost verification.

Good coverage of the streaming path including SSE parsing, cost header extraction, and proper response shape validation.

packages/coder-tui/src/aigateway.ts (4)

47-49: Previous error handling concern has been addressed.

The code now uses StructuredError via AIGatewayModelFetchError for actual errors (CLI execution failure and service fetch failure), while informational messages about missing configuration remain as console.warn with early returns - an appropriate distinction.

Also applies to: 116-121, 148-153


156-161: Previous modality sanitization concern has been addressed.

The new sanitizeModalities function properly filters to only 'text' | 'image' values using a type guard, with a safe default to ['text'] when no valid modalities are found.

Also applies to: 167-168


163-181: LGTM - Robust model conversion with safe defaults.

The toPiModel function properly handles optional fields with sensible defaults for reasoning, contextWindow, maxTokens, and pricing fields.


183-227: LGTM - Clean provider registration logic.

The setupAIGateway function properly aggregates models by API type and registers providers with appropriate configuration including headers for org ID.

Comment thread packages/core/src/services/aigateway/api-reference.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/services/aigateway/api-reference.ts`:
- Around line 109-120: The stream endpoint uses
AIGatewayChatCompletionParamsSchema which has stream optional, so make a
stream-specific schema that enforces stream: true and use it only for the stream
endpoint; e.g. define AIGatewayChatCompletionStreamParamsSchema by extending or
refining AIGatewayChatCompletionParamsSchema to include stream: z.literal(true)
(or an equivalent zod refinement), export/import it alongside
AIGatewayChatCompletionParamsSchema, and replace the schema reference in the
stream endpoint entry (the object with id 'stream-chat-completion' /
requestBody.fields.schema) so generated docs show stream as required and
constrained to true.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 02f222a3-5eaa-4b3d-94d1-3e4261f1b1b1

📥 Commits

Reviewing files that changed from the base of the PR and between 99aa54c and 2aa3c8e.

📒 Files selected for processing (2)
  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
  • packages/core/src/services/aigateway/api-reference.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
  • GitHub Check: Windows WSL CLI Smoke Test
  • GitHub Check: Framework Integration Tests (TanStack & Next.js)
  • GitHub Check: Queue CLI Tests
  • GitHub Check: SDK Integration Test Suite
  • GitHub Check: Template Integration Tests
  • GitHub Check: Package Installation & Usage Test
  • GitHub Check: Standalone Agent Test
  • GitHub Check: Postgres SSL Integration Test
  • GitHub Check: Playwright E2E Smoke Test
  • GitHub Check: Cloud Deployment Tests
  • GitHub Check: Pack & Upload
  • GitHub Check: Build
  • GitHub Check: Agentuity Deployment
🧰 Additional context used
📓 Path-based instructions (4)
apps/docs/src/web/content/**/*.mdx

📄 CodeRabbit inference engine (apps/docs/src/web/content/AGENTS.md)

apps/docs/src/web/content/**/*.mdx: Write 1-2 sentences of motivation before showing code (context-then-code pattern)
Avoid walls of text; use progressive disclosure with basic examples first, advanced patterns later
Standalone code examples must include imports and be runnable; short inline references are fine without imports
Use scannable formatting with headings, callouts, and inline comments that explain 'why' not 'what'
Explain why someone would use a feature; avoid hollow adjectives like 'powerful', 'seamless', or 'enterprise-grade'
Read SDK source code and AGENTS.md files before documenting APIs or CLI flags to ensure accuracy
Use action-oriented page titles (e.g., 'Calling Other Agents' not 'Agent Communication')
Reference images without the '/public/' prefix; Vite copies static assets from src/web/public/ to build root
Use ctx.logger in server and agent code examples, not console.log
Do not include suppression comments like @ts-ignore, eslint-disable, or similar in code examples
Explicitly mark optional parameters in prose; readers should not need to parse type signatures to understand optionality
Verify current model names in code examples before publishing; use both raw provider SDKs and AI SDK providers (openai(), anthropic()) across examples
Use s from @agentuity/schema for schema examples; also show Zod, ArkType, and Valibot across examples to demonstrate schema-agnostic SDK usage
For local-only browser callback values, use .env.local; verify env file precedence before naming an override file
For Drizzle Kit setup, show drizzle.config.ts with defineConfig, then run 'bunx drizzle-kit push' or normal generate/migrate flow; avoid inline --dialect, --schema, --url commands unless documenting those flags
Cross-links must include specific context explaining why the reader would follow the link; use generic 'See also' links
Link to external tools on first mention only; do not re-link the same resource on the same page
Page intro should be 1-2 sentences focu...

Files:

  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Biome as code formatter with tabs (width 3), single quotes, semicolons, lineWidth 100, and trailingCommas es5

Files:

  • packages/core/src/services/aigateway/api-reference.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript Strict mode with ESNext target and bundler moduleResolution
Use StructuredError from @agentuity/core for error handling

Files:

  • packages/core/src/services/aigateway/api-reference.ts
packages/core/src/**/*.ts

📄 CodeRabbit inference engine (packages/core/AGENTS.md)

packages/core/src/**/*.ts: Build TypeScript with bun run build command
Run TypeScript type checking with bun run typecheck command
Ensure runtime compatibility with both Browser and Node/Bun environments with no runtime-specific code
Build target must be ESNext with TypeScript declaration files
Prefer interfaces for public APIs
Use generics for reusable type utilities
Ensure no side effects in all exports - all exports must be pure with no global mutations
All relative imports in TypeScript files MUST include the .ts extension
Run bun run build before publishing to compile TypeScript

Files:

  • packages/core/src/services/aigateway/api-reference.ts
🧠 Learnings (1)
📚 Learning: 2025-12-21T00:31:41.858Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 274
File: packages/cli/src/cmd/build/vite/server-bundler.ts:12-41
Timestamp: 2025-12-21T00:31:41.858Z
Learning: In Bun runtime, BuildMessage and ResolveMessage are global types and are not exported from the bun module. Do not import { BuildMessage } from 'bun' or similar; these types are available globally and should be used without import. This applies to all TypeScript files that target the Bun runtime within the repository.

Applied to files:

  • packages/core/src/services/aigateway/api-reference.ts
🔇 Additional comments (1)
apps/docs/src/web/content/reference/api/ai-gateway.mdx (1)

12-31: Public-vs-authenticated behavior is documented clearly.

The auth section and /models endpoint callout now align with the service behavior and are easy to scan.

Comment thread packages/core/src/services/aigateway/api-reference.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
apps/docs/src/web/content/reference/api/ai-gateway.mdx (2)

7-12: ⚡ Quick win

Add a short problem-first intro before the first component.

The page starts with RegionPicker immediately; add 1–2 sentences that explain what problem this reference solves and when to use it.

Suggested diff
 {/* This file is auto-generated from Zod schemas. Do not edit manually. Run scripts/generate-api-reference.ts to regenerate. */}
 
+Use this reference when you need one endpoint to discover available models and run routed completions without provider-specific APIs.
+Start by selecting the gateway region below, then use the request/response sections to pick the right completion mode.
+
 <RegionPicker host="aigateway" />

As per coding guidelines, "Page intro should be 1-2 sentences focused on the problem, not the feature; must add value beyond the frontmatter description."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/docs/src/web/content/reference/api/ai-gateway.mdx` around lines 7 - 12,
Add a 1–2 sentence problem-first intro immediately before the RegionPicker
component in the ai-gateway reference page that explains the problem this API
solves and when to use it (focus on user problem, not feature). Edit the top of
the document so the new text precedes <RegionPicker host="aigateway" /> and keep
it concise, value-driven, and complementary to the frontmatter (e.g., one
sentence describing the pain point for multi-region AI requests and one sentence
about when to consult this reference). Ensure the copy reads like a problem
statement (not implementation details) and is 1–2 sentences only.

85-88: ⚡ Quick win

Explicitly call out optional request parameters in prose for both completion modes.

Right now readers need to infer optionality from the field tables. Add explicit prose listing optional knobs (messages, prompt, temperature, top_p, max_tokens, stop; and for non-streaming, stream optional/false by default).

Suggested diff
-Completion request. Use `messages` for chat-compatible models and `prompt` for legacy OpenAI completions-compatible models. Additional provider-specific fields are passed through.
+Completion request. `messages` (optional) is for chat-compatible models, and `prompt` (optional) is for legacy completions-compatible models. `temperature`, `top_p`, `max_tokens`, and `stop` are optional tuning fields; `stream` is optional here and defaults to `false`.
@@
-Completion request with `stream` set to `true`.
+Completion request with `stream` set to `true` (required). `messages` or `prompt` are optional input shapes, and `temperature`, `top_p`, `max_tokens`, and `stop` remain optional tuning fields.

As per coding guidelines, "Explicitly mark optional parameters in prose; readers should not need to parse type signatures to understand optionality."

Also applies to: 277-280

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/docs/src/web/content/reference/api/ai-gateway.mdx` around lines 85 - 88,
In the "Request Body" section for the AI Gateway completion endpoint, add
explicit prose that lists which request parameters are optional instead of
relying on tables: state that messages (chat models) and prompt (legacy
completion models) are optional, and explicitly list temperature, top_p,
max_tokens, and stop as optional knobs; also call out that stream is optional
and defaults to false for non-streaming requests. Update the same explanatory
prose near the later usage (the other Request Body paragraph referenced) so both
locations mention the same optional parameters and the default for stream.
Ensure you reference the parameter names exactly as: messages, prompt,
temperature, top_p, max_tokens, stop, and stream.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/services/aigateway/service.ts`:
- Around line 258-270: The current code returns payload.data directly from the
listModels flow which exposes raw/catalog IDs (e.g., OpenRouter-style ":free")
that callers later pass to complete() and fail; update the listModels
implementation (where AIGatewayModelsResponseSchema.parse is used and
AIGatewayModelsResponseError is thrown) to normalize each model entry before
returning: map each payload.data item to a provider-callable model id (e.g.,
convert or strip catalog-specific suffixes, or look up the provider id) and
include the original catalog id in a separate field (e.g., catalogId) so callers
can still access it; ensure the normalized id is what listModels returns to
consumers so callers can round-trip into complete() successfully.
- Around line 206-216: The current trailers branch always returns headers: {}
even when no gateway metadata exists—modify the logic in the trailers-handling
block (where trailers is awaited and extractGatewayMetadataFromHeaders is
called) to only include the headers property when either metadata.headers or
trailerMetadata.headers is present (i.e., build mergedHeaders = {
...metadata.headers, ...trailerMetadata.headers } only if at least one of those
objects has keys, otherwise leave headers undefined); keep the existing cost
merge behavior (metadata.cost || trailerMetadata.cost) and ensure the returned
object only spreads a headers field when mergedHeaders is non-empty so
attachGatewayMetadata does not inject an empty agentuity.headers block.
- Around line 86-100: AIGatewayChatCompletionParamsSchema currently allows
requests with only { model } so add a refinement to require at least one
non-empty input: use .superRefine or .refine on
AIGatewayChatCompletionParamsSchema to assert that either prompt is provided and
non-empty (if string: trim().length > 0; if array: length>0 and all items
non-empty) or messages is provided and non-empty (array length>0), and add a
clear validation error message (e.g. "either prompt or messages must be
provided") so invalid payloads are rejected at schema validation time; refer to
AIGatewayChatCompletionParamsSchema, prompt, and messages when implementing.

---

Nitpick comments:
In `@apps/docs/src/web/content/reference/api/ai-gateway.mdx`:
- Around line 7-12: Add a 1–2 sentence problem-first intro immediately before
the RegionPicker component in the ai-gateway reference page that explains the
problem this API solves and when to use it (focus on user problem, not feature).
Edit the top of the document so the new text precedes <RegionPicker
host="aigateway" /> and keep it concise, value-driven, and complementary to the
frontmatter (e.g., one sentence describing the pain point for multi-region AI
requests and one sentence about when to consult this reference). Ensure the copy
reads like a problem statement (not implementation details) and is 1–2 sentences
only.
- Around line 85-88: In the "Request Body" section for the AI Gateway completion
endpoint, add explicit prose that lists which request parameters are optional
instead of relying on tables: state that messages (chat models) and prompt
(legacy completion models) are optional, and explicitly list temperature, top_p,
max_tokens, and stop as optional knobs; also call out that stream is optional
and defaults to false for non-streaming requests. Update the same explanatory
prose near the later usage (the other Request Body paragraph referenced) so both
locations mention the same optional parameters and the default for stream.
Ensure you reference the parameter names exactly as: messages, prompt,
temperature, top_p, max_tokens, stop, and stream.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 66283291-2fba-4b43-9458-658bdb282325

📥 Commits

Reviewing files that changed from the base of the PR and between 2aa3c8e and e1ce458.

📒 Files selected for processing (4)
  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
  • packages/core/src/services/aigateway/api-reference.ts
  • packages/core/src/services/aigateway/index.ts
  • packages/core/src/services/aigateway/service.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/services/aigateway/api-reference.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
  • GitHub Check: Playwright E2E Smoke Test
  • GitHub Check: Cloud Deployment Tests
  • GitHub Check: Queue CLI Tests
  • GitHub Check: Postgres SSL Integration Test
  • GitHub Check: Standalone Agent Test
  • GitHub Check: Framework Integration Tests (TanStack & Next.js)
  • GitHub Check: Template Integration Tests
  • GitHub Check: Package Installation & Usage Test
  • GitHub Check: SDK Integration Test Suite
  • GitHub Check: Windows WSL CLI Smoke Test
  • GitHub Check: Agentuity Deployment
  • GitHub Check: Build
  • GitHub Check: Pack & Upload
🧰 Additional context used
📓 Path-based instructions (5)
apps/docs/src/web/content/**/*.mdx

📄 CodeRabbit inference engine (apps/docs/src/web/content/AGENTS.md)

apps/docs/src/web/content/**/*.mdx: Write 1-2 sentences of motivation before showing code (context-then-code pattern)
Avoid walls of text; use progressive disclosure with basic examples first, advanced patterns later
Standalone code examples must include imports and be runnable; short inline references are fine without imports
Use scannable formatting with headings, callouts, and inline comments that explain 'why' not 'what'
Explain why someone would use a feature; avoid hollow adjectives like 'powerful', 'seamless', or 'enterprise-grade'
Read SDK source code and AGENTS.md files before documenting APIs or CLI flags to ensure accuracy
Use action-oriented page titles (e.g., 'Calling Other Agents' not 'Agent Communication')
Reference images without the '/public/' prefix; Vite copies static assets from src/web/public/ to build root
Use ctx.logger in server and agent code examples, not console.log
Do not include suppression comments like @ts-ignore, eslint-disable, or similar in code examples
Explicitly mark optional parameters in prose; readers should not need to parse type signatures to understand optionality
Verify current model names in code examples before publishing; use both raw provider SDKs and AI SDK providers (openai(), anthropic()) across examples
Use s from @agentuity/schema for schema examples; also show Zod, ArkType, and Valibot across examples to demonstrate schema-agnostic SDK usage
For local-only browser callback values, use .env.local; verify env file precedence before naming an override file
For Drizzle Kit setup, show drizzle.config.ts with defineConfig, then run 'bunx drizzle-kit push' or normal generate/migrate flow; avoid inline --dialect, --schema, --url commands unless documenting those flags
Cross-links must include specific context explaining why the reader would follow the link; use generic 'See also' links
Link to external tools on first mention only; do not re-link the same resource on the same page
Page intro should be 1-2 sentences focu...

Files:

  • apps/docs/src/web/content/reference/api/ai-gateway.mdx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Biome as code formatter with tabs (width 3), single quotes, semicolons, lineWidth 100, and trailingCommas es5

Files:

  • packages/core/src/services/aigateway/index.ts
  • packages/core/src/services/aigateway/service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript Strict mode with ESNext target and bundler moduleResolution
Use StructuredError from @agentuity/core for error handling

Files:

  • packages/core/src/services/aigateway/index.ts
  • packages/core/src/services/aigateway/service.ts
**/index.ts

📄 CodeRabbit inference engine (AGENTS.md)

Use named exports from package index.ts files

Files:

  • packages/core/src/services/aigateway/index.ts
packages/core/src/**/*.ts

📄 CodeRabbit inference engine (packages/core/AGENTS.md)

packages/core/src/**/*.ts: Build TypeScript with bun run build command
Run TypeScript type checking with bun run typecheck command
Ensure runtime compatibility with both Browser and Node/Bun environments with no runtime-specific code
Build target must be ESNext with TypeScript declaration files
Prefer interfaces for public APIs
Use generics for reusable type utilities
Ensure no side effects in all exports - all exports must be pure with no global mutations
All relative imports in TypeScript files MUST include the .ts extension
Run bun run build before publishing to compile TypeScript

Files:

  • packages/core/src/services/aigateway/index.ts
  • packages/core/src/services/aigateway/service.ts
🧠 Learnings (1)
📚 Learning: 2025-12-21T00:31:41.858Z
Learnt from: jhaynie
Repo: agentuity/sdk PR: 274
File: packages/cli/src/cmd/build/vite/server-bundler.ts:12-41
Timestamp: 2025-12-21T00:31:41.858Z
Learning: In Bun runtime, BuildMessage and ResolveMessage are global types and are not exported from the bun module. Do not import { BuildMessage } from 'bun' or similar; these types are available globally and should be used without import. This applies to all TypeScript files that target the Bun runtime within the repository.

Applied to files:

  • packages/core/src/services/aigateway/index.ts
  • packages/core/src/services/aigateway/service.ts

Comment thread packages/core/src/services/aigateway/service.ts Outdated
Comment on lines +206 to +216
if (trailers) {
try {
const trailerMetadata = extractGatewayMetadataFromHeaders(await trailers);
const cost =
metadata.cost || trailerMetadata.cost
? { ...(metadata.cost ?? {}), ...(trailerMetadata.cost ?? {}) }
: undefined;
return {
headers: { ...metadata.headers, ...trailerMetadata.headers },
...(cost ? { cost } : {}),
};
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Keep headers undefined when no gateway metadata was captured.

If response.trailers exists, this branch always returns headers: {} even when neither headers nor trailers contain gateway metadata. attachGatewayMetadata() then injects an empty agentuity.headers block into otherwise unannotated responses.

Suggested fix
 		try {
 			const trailerMetadata = extractGatewayMetadataFromHeaders(await trailers);
+			const headers = {
+				...(metadata.headers ?? {}),
+				...(trailerMetadata.headers ?? {}),
+			};
 			const cost =
 				metadata.cost || trailerMetadata.cost
 					? { ...(metadata.cost ?? {}), ...(trailerMetadata.cost ?? {}) }
 					: undefined;
 			return {
-				headers: { ...metadata.headers, ...trailerMetadata.headers },
+				...(Object.keys(headers).length > 0 ? { headers } : {}),
 				...(cost ? { cost } : {}),
 			};
 		} catch {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/services/aigateway/service.ts` around lines 206 - 216, The
current trailers branch always returns headers: {} even when no gateway metadata
exists—modify the logic in the trailers-handling block (where trailers is
awaited and extractGatewayMetadataFromHeaders is called) to only include the
headers property when either metadata.headers or trailerMetadata.headers is
present (i.e., build mergedHeaders = { ...metadata.headers,
...trailerMetadata.headers } only if at least one of those objects has keys,
otherwise leave headers undefined); keep the existing cost merge behavior
(metadata.cost || trailerMetadata.cost) and ensure the returned object only
spreads a headers field when mergedHeaders is non-empty so attachGatewayMetadata
does not inject an empty agentuity.headers block.

Comment on lines +258 to +270
const payload = AIGatewayModelsResponseSchema.parse(response.data);
if (!payload.success) {
throw new AIGatewayModelsResponseError({
message: payload.error || payload.message || 'AI Gateway failed to list models',
error: payload.error,
});
}
if (!payload.data) {
throw new AIGatewayModelsResponseError({
message: 'AI Gateway model response did not include data',
});
}
return payload.data;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Don’t expose raw catalog IDs as universally callable model IDs.

The PR notes that /models can return OpenRouter-style :free IDs for Poolside/Laguna while completions expect provider-callable IDs. Returning payload.data unchanged makes listModels() advertise entries that some callers cannot round-trip into complete() successfully.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/services/aigateway/service.ts` around lines 258 - 270, The
current code returns payload.data directly from the listModels flow which
exposes raw/catalog IDs (e.g., OpenRouter-style ":free") that callers later pass
to complete() and fail; update the listModels implementation (where
AIGatewayModelsResponseSchema.parse is used and AIGatewayModelsResponseError is
thrown) to normalize each model entry before returning: map each payload.data
item to a provider-callable model id (e.g., convert or strip catalog-specific
suffixes, or look up the provider id) and include the original catalog id in a
separate field (e.g., catalogId) so callers can still access it; ensure the
normalized id is what listModels returns to consumers so callers can round-trip
into complete() successfully.

@jhaynie jhaynie merged commit e3aeddb into main May 6, 2026
16 checks passed
@jhaynie jhaynie deleted the feat/aigateway-sdk-cli branch May 6, 2026 22:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant