Skip to content

Feature: ACP Rest API #557

Closed
Closed

Description

@EmilienM

🚀 Feature Description

Is your feature request related to a problem?
Currently, the only way to interact with the Ambient Platform is by the UI or by directly manipulating Kubernetes Custom Resources (CRDs) via kubectl. This requires users to have direct cluster access, manage kubeconfig files, and understand the internal operator architecture. We lack a standard, agnostic interface for external tools (Frontends, SDKs, MCP Servers) to manage agentic sessions.

Describe the solution you'd like
I want to implement a standalone Public API Service (REST) that acts as a gateway. It should abstract the underlying Kubernetes implementation and expose "Basic Operations" for managing sessions via standard HTTP requests.

💡 Proposed Solution

Detailed Description:
We will build a lightweight Go service (likely using Gin or standard library) that sits at the edge of the cluster.

  • It authenticates users (initially via a simple Token/API Key).
  • It translates HTTP requests into Kubernetes client operations (client-go).
  • It returns standard JSON responses, hiding the K8s metadata and spec complexities.

User Experience:
A user (or frontend) can simply run a curl command to start an agent:

curl -X POST https://api.ambient.dev/v1/sessions \
  -H "Authorization: Bearer <token>" \
  -d '{"task": "Refactor login.py", "model": "gpt-4"}'

API Changes (The Interface):
We will implement the standard CRUD operations for the Session resource:

  1. List: GET /v1/sessions - Returns a list of active/recent sessions.
  2. Create: POST /v1/sessions - Creates a K8s CRD based on the payload.
  3. Read: GET /v1/sessions/{id} - Returns status (Running, Completed, Failed) and high-level results.
  4. Delete: DELETE /v1/sessions/{id} - Deletes the underlying CRD.

🎯 Use Cases

Primary Use Case:
Building a Web UI or CLI that does not require Kubernetes permissions.

User Stories:

  • As a Frontend Developer, I want to list all running agent sessions so I can display them in a dashboard table.
  • As a CI Integration, I want to POST a new session request to trigger a code review agent without installing kubectl.

🔧 Technical Considerations

Component: [Infrastructure / New Service]

Implementation Approach:

  • Language: Go.
  • K8s Integration: Use k8s.io/client-go with a ServiceAccount that has RBAC permissions to get, list, create, delete the specific CRDs (e.g., AgentSession).
  • Mapping: The service must map the complex CRD Status fields into a simplified JSON struct (e.g., status: "running" instead of deep K8s conditions).

Dependencies:

  • Docker image for the new API Gateway.
  • Helm chart updates to deploy this service alongside the operator.

Breaking Changes:
None (Additive).

📊 Success Metrics

  • API service is deployable via existing Helm charts.
  • Can successfully create a K8s CRD via a curl command to the endpoint.
  • Latency for API requests is under 200ms (excluding K8s propagation time).

🔄 Alternatives Considered

Alternative 1: Direct K8s Proxy
rejected because we want to sanitize the data and hide implementation details (like valid/invalid spec configurations) from the consumer.

Alternative 2: gRPC
Rejected for now. REST is more universally accessible for the initial set of basic operations and easier to debug.

📋 Additional Context

Reference:
Inspired by the resource model in [ambient-code/mcp/issues/4](ambient-code/mcp#4) — aiming for that level of simplicity in the resource definitions.

✅ Acceptance Criteria

  • POST /sessions: Accepts JSON, validates input, creates CRD.
  • GET /sessions/{id}: Returns JSON with ID, Status, and Result.
  • GET /sessions: Returns array of sessions.
  • DELETE /sessions/{id}: Deletes the CRD.
  • Basic API Key Authentication middleware is in place.
  • Dockerfile created for the API service.

🏷️ Labels

  • Priority: high
  • Effort: L
  • Component: frontend-api
  • Type: new-feature

Activity

  1. added
    enhancement
    on Jan 29, 2026
  2. EmilienM commented on Jan 29, 2026

    @EmilienM
    ContributorAuthor

    Proposal: ACP Public REST API

    Issue: #557 - Feature: ACP Rest API
    Date: 2026-01-29
    Status: Draft


    Executive Summary

    After analyzing the codebase, most of the infrastructure already exists. The key question is whether to extend the existing backend or create a new standalone service.


    Current State (What Already Exists)

    Component Status Details
    Backend API Complete Full CRUD for sessions at /api/projects/:projectName/agentic-sessions
    Backend Route Deployed backend-route.yaml already exposes backend directly in production
    Access Keys Complete ServiceAccount-based API keys (/api/projects/:projectName/keys)
    Token Auth Complete Backend accepts Authorization: Bearer <token>
    Sessions CRUD Complete List, Create, Get, Update, Delete, Start, Stop sessions

    Access Key System

    The access key system (components/backend/handlers/permissions.go:339-444) already provides long-lived API tokens:

    # Create an access key (returns a JWT token)
    curl -X POST https://backend.ambient-code.example.com/api/projects/my-project/keys \
      -H "Authorization: Bearer <ocp-token>" \
      -d '{"name": "my-cli-key", "role": "edit"}'
    
    # Response: {"id": "ambient-key-...", "key": "<jwt-token>", "role": "edit"}

    This token can then be used for all subsequent API calls without needing an OpenShift session.


    What's Missing (Per Issue #557)

    1. Versioned API prefix (/v1/) - Currently uses /api/projects/...
    2. Simplified JSON responses - Currently returns raw K8s CRD structure
    3. Abstracted resource model - Hide K8s metadata from consumers
    4. OpenAPI documentation - No spec file exists
    5. Clear separation - Public vs internal APIs mixed together

    Proposed Options

    Option A: Extend Existing Backend (Recommended)

    Add a /v1/ route group with simplified DTOs that wrap existing handlers:

    GET    /v1/sessions           → Lists sessions (simplified JSON)
    GET    /v1/sessions/{id}      → Get session status
    POST   /v1/sessions           → Create session
    DELETE /v1/sessions/{id}      → Delete session
    

    Pros:

    • Minimal new code (~200-300 lines)
    • Reuses existing auth, K8s clients, middleware
    • Single deployment, single route
    • Access keys already work

    Cons:

    • Mixes internal and public API in one binary
    • Harder to apply different rate limits

    Effort: Small (1-2 days)


    Option B: Standalone API Gateway Service

    Create a new components/api-gateway/ service that calls the backend or K8s directly:

    ┌─────────────┐     ┌─────────────┐     ┌─────────────┐
    │  Client     │────▶│ API Gateway │────▶│ Backend API │
    │  (SDK/CLI)  │     │ (/v1/...)   │     │ or K8s API  │
    └─────────────┘     └─────────────┘     └─────────────┘
    

    Pros:

    • Clean separation of concerns
    • Independent scaling
    • Can add rate limiting, caching layer

    Cons:

    • New image, deployment, route to maintain
    • Additional network hop (latency)
    • Duplicates some backend logic

    Effort: Medium (3-5 days)


    Recommendation: Option A (Extended Backend)

    Given that:

    1. The backend already has all the handler logic
    2. Access keys already provide long-lived tokens
    3. The backend route already exists in production
    4. The issue prioritizes simplicity ("lightweight")

    Option A is recommended with the following implementation plan:

    Phase 1: Versioned Public API Endpoints

    Add /v1/ routes with simplified DTOs:

    // routes.go - add v1 group
    v1 := r.Group("/v1")
    {
        v1.GET("/sessions", handlers.ListSessionsV1)
        v1.POST("/sessions", handlers.CreateSessionV1)
        v1.GET("/sessions/:id", handlers.GetSessionV1)
        v1.DELETE("/sessions/:id", handlers.DeleteSessionV1)
    }

    Phase 2: Simplified Response DTOs

    // Simplified session response (not raw K8s CR)
    type SessionV1 struct {
        ID          string `json:"id"`
        Status      string `json:"status"`  // "pending", "running", "completed", "failed"
        Task        string `json:"task"`
        Model       string `json:"model"`
        CreatedAt   string `json:"createdAt"`
        CompletedAt string `json:"completedAt,omitempty"`
        Result      string `json:"result,omitempty"`
    }

    Phase 3: Project-Scoped Access Keys

    Access keys are already project-scoped. For the /v1/ API, we can either:

    • Option A1: Require project in header (X-Ambient-Project: my-project)
    • Option A2: Infer project from ServiceAccount namespace in the token

    Recommendation: Option A2 since the access key token already encodes system:serviceaccount:<namespace>:<sa-name>.


    Authentication Strategy

    The current access key mechanism solves the "token expiration" problem:

    Auth Method Lifetime Use Case
    OpenShift OAuth token Hours (configurable) UI users
    Access Key (SA token) Cluster-defined (default: 1 year) SDK/CLI/CI

    Token Creation Flow

    # 1. User creates access key via UI or API (requires OCP auth initially)
    # 2. Key is returned once (must be saved)
    # 3. Key can be used for all future API calls
    
    curl -H "Authorization: Bearer $ACCESS_KEY" \
      https://api.ambient-code.example.com/v1/sessions

    Open Questions

    1. Project scoping: Should /v1/sessions require a project header, or should the token implicitly determine the project?

    2. Access key UI: Is there already UI for managing access keys, or should we add that?

    3. Rate limiting: Do we need rate limiting on the public API?

    4. OpenAPI spec: Should we generate an OpenAPI spec and Swagger UI?


    Success Criteria (from Issue #557)

    • API service is deployable via existing Helm charts
    • Can successfully create a K8s CRD via a curl command to the endpoint
    • Latency for API requests is under 200ms (excluding K8s propagation time)

    Acceptance Criteria (from Issue #557)

    • POST /sessions: Accepts JSON, validates input, creates CRD
    • GET /sessions/{id}: Returns JSON with ID, Status, and Result
    • GET /sessions: Returns array of sessions
    • DELETE /sessions/{id}: Deletes the CRD
    • Basic API Key Authentication middleware is in place
    • Dockerfile created for the API service (N/A if using Option A)

    References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions