Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions components/ambient-sdk/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
ts-sdk/dist/
ts-sdk/node_modules/
python-sdk/*.egg-info/
python-sdk/venv/
.claude/settings.local.json
125 changes: 125 additions & 0 deletions components/ambient-sdk/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# CLAUDE.md — Ambient Platform SDK

## Project Intent

The Ambient Platform SDK provides language-idiomatic HTTP client libraries for the Ambient Code Platform's public REST API. It exists so that external developers and internal automation can create and manage AI agentic sessions **without Kubernetes dependencies or cluster access**. The SDK is the public-facing contract for the platform — everything behind it (CRDs, operators, runners) is an implementation detail.

## Role in the Platform

This SDK is one piece of a multi-component system coordinated via `../working.md`:

| Component | Purpose | Relationship to SDK |
|---|---|---|
| **ambient-api-server** | REST API gateway (Go + Gin) | The server this SDK talks to — implements `/v1/sessions` |
| **ambient-control-plane** | Reconciler / controller | Watches API server for session changes; SDK users never interact with it |
| **ambient-sdk** (this) | Client libraries (Go, Python) | Consumes the API server's public endpoints |
| **Frontend** | NextJS web UI | Will eventually share generated types from `openapi.yaml` |
| **Operator** | Kubernetes controller | Internal only — spawns Jobs from CRs |
| **Runner** | Claude Code CLI executor | Internal only — runs inside Job pods |

## Quick Reference

```bash
# Go SDK
cd go-sdk && go test ./...
cd go-sdk/examples && go run main.go

# Python SDK
cd python-sdk && ./test.sh
cd python-sdk && pip install -e ".[dev]" && pytest
cd python-sdk && python examples/main.py
```

### Environment Variables (all SDKs)

| Variable | Required | Description |
|---|---|---|
| `AMBIENT_TOKEN` | Yes | Bearer token (OpenShift `sha256~`, JWT, or GitHub `ghp_`) |
| `AMBIENT_PROJECT` | Yes | Target project / Kubernetes namespace |
| `AMBIENT_API_URL` | No | API base URL (default: `http://localhost:8080`) |

## Directory Structure

```
ambient-sdk/
├── CLAUDE.md # This file
├── README.md # Public-facing overview and roadmap
├── docs/ # Detailed documentation
│ ├── architecture.md # Design decisions, platform integration
│ └── authentication.md # Auth flows, token formats, RBAC requirements
├── go-sdk/ # Go client library
│ ├── client/client.go # HTTP client with structured logging and token sanitization
│ ├── types/types.go # Request/response types, SecureToken, input validation
│ ├── examples/main.go # Complete session lifecycle example
│ ├── go.mod # Module: github.com/ambient-code/platform/components/ambient-sdk/go-sdk
│ └── README.md # Go-specific usage and API reference
└── python-sdk/ # Python client library
├── ambient_platform/ # Package root
│ ├── __init__.py # Public exports, version
│ ├── client.py # AmbientClient with httpx, env-based factory
│ ├── types.py # Dataclasses matching OpenAPI schemas
│ └── exceptions.py # Typed exception hierarchy
├── examples/main.py # Complete session lifecycle example
├── test.sh # Integration test runner with env validation
├── pyproject.toml # Package config (black, isort, mypy, pytest)
└── README.md # Python-specific usage and API reference
```

## Code Conventions

### Go SDK

- **Go 1.21+**, standard library only (no third-party deps)
- `go fmt ./...` and `golangci-lint run` enforced
- Token stored as plain string with URL sanitization via `sanitizeLogURL()`
- All client constructors return `(*Client, error)` — token validation is mandatory
- Input validation in `NewClient()` for token length and placeholder detection

### Python SDK

- **Python 3.8+**, single dependency: `httpx>=0.25.0`
- `black` formatting, `isort` with black profile, `mypy` strict mode
- Dataclasses for all types (no Pydantic — intentionally lightweight)
- `AmbientClient.from_env()` factory for environment-based configuration
- Context manager support (`with AmbientClient(...) as client:`)
- Typed exception hierarchy rooted at `AmbientAPIError`

### Both SDKs

- Never log tokens — use `len(token)` or `SecureToken.LogValue()` / `[REDACTED]`
- All request types have `Validate()` / `validate()` methods called before HTTP calls
- API errors return structured `ErrorResponse` without leaking raw response bodies
- Token format validation: OpenShift `sha256~`, JWT (3 dot-separated base64 parts), GitHub `ghp_/gho_/ghu_/ghs_`

## OpenAPI Specification

The API server owns the canonical OpenAPI spec at `../ambient-api-server/openapi/openapi.yaml`. The SDK does **not** maintain its own copy — it derives types and client behavior from the API server's spec.

- **Spec location**: `../ambient-api-server/openapi/` (split by resource: sessions, agents, tasks, workflows, etc.)
- **Session endpoints**: `GET /api/ambient-api-server/v1/sessions`, `POST ...`, `GET .../sessions/{id}`
- **Auth**: `Authorization: Bearer <token>` header (project scoping via `X-Ambient-Project`)
- **Statuses**: `pending` → `running` → `completed` | `failed`
- Update the API server's spec before changing SDK types or client behavior

## Security Considerations

- Tokens are validated on client construction (format, length, placeholder detection)
- Go SDK uses `slog.LogValuer` + `ReplaceAttr` for dual-layer log redaction
- Bearer tokens, SHA256 tokens, and JWTs are pattern-matched and redacted in logs
- API error responses are sanitized before returning to callers
- URL validation rejects placeholder domains (`example.com`) and dangerous schemes

## Smoke Test

Run `cd go-sdk && go run examples/main.go` until it passes. This is the SDK's end-to-end smoke test against the live API server. It currently returns 404 because the API server has not been migrated to serve `/api/ambient-api-server/v1/sessions` yet. Once the full migration (api-server + control-plane + deployment) is complete, this test will pass. Keep running it — when it stops returning 404, the platform is wired up.

## Loadable Context

| Topic | File |
|---|---|
| Architecture and platform integration | `docs/architecture.md` |
| Authentication, tokens, and RBAC | `docs/authentication.md` |
| Go SDK details | `go-sdk/README.md` |
| Python SDK details | `python-sdk/README.md` |
| API contract (source of truth) | `../ambient-api-server/openapi/openapi.yaml` |
| Cross-session coordination | `../working.md` |
27 changes: 27 additions & 0 deletions components/ambient-sdk/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
SPEC_PATH ?= ../ambient-api-server/openapi/openapi.yaml
GO_OUT = go-sdk
PYTHON_OUT = python-sdk/ambient_platform
TS_OUT = ts-sdk
GENERATOR = generator

.PHONY: generate-sdk verify-sdk build-generator clean

build-generator:
cd $(GENERATOR) && go build -o ../bin/ambient-sdk-generator .

generate-sdk: build-generator
./bin/ambient-sdk-generator \
-spec $(SPEC_PATH) \
-go-out $(GO_OUT) \
-python-out $(PYTHON_OUT) \
-ts-out $(TS_OUT)
cd $(GO_OUT) && go fmt ./...

verify-sdk: generate-sdk
cd $(GO_OUT) && go build ./...
cd python-sdk && python3 -c "from ambient_platform import *"
cd $(TS_OUT) && npm run build
@echo "SDK verification passed"

clean:
rm -f bin/ambient-sdk-generator
99 changes: 99 additions & 0 deletions components/ambient-sdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Ambient Platform SDK

**Language-idiomatic HTTP client libraries for the Ambient Code Platform's public REST API.**

## Overview

The Ambient Platform SDK provides Go, Python, and TypeScript client libraries for interacting with the Ambient Platform API. It exists so that external developers and internal automation can create and manage AI agentic sessions **without Kubernetes dependencies or cluster access**. The SDK is the public-facing contract for the platform.

## Supported Languages

- **Go SDK** - `go-sdk/` - Go 1.21+ with standard library only
- **Python SDK** - `python-sdk/` - Python 3.8+ with minimal dependencies
- **TypeScript SDK** - `ts-sdk/` - Modern TypeScript with proper type safety

## Quick Start

### Go

```bash
# Add to go.mod (local development)
require github.com/ambient-code/platform/components/ambient-sdk/go-sdk v0.0.0

# Usage
import "github.com/ambient-code/platform/components/ambient-sdk/go-sdk/client"
```

### Python

```bash
pip install -e python-sdk/
```

```python
from ambient_platform.client import AmbientClient

client = AmbientClient.from_env()
session = client.sessions.create({
"name": "My Analysis Session",
"prompt": "Analyze this codebase"
})
```

### TypeScript

```bash
cd ts-sdk && npm install
```

```typescript
import { AmbientClient } from './src/client'

const client = new AmbientClient({
baseURL: process.env.AMBIENT_API_URL,
token: process.env.AMBIENT_TOKEN,
project: process.env.AMBIENT_PROJECT
})
```

## Environment Variables

All SDKs support these environment variables:

| Variable | Required | Description |
|---|---|---|
| `AMBIENT_TOKEN` | Yes | Bearer token (OpenShift `sha256~`, JWT, or GitHub `ghp_`) |
| `AMBIENT_PROJECT` | Yes | Target project / Kubernetes namespace |
| `AMBIENT_API_URL` | No | API base URL (default: `http://localhost:8080`) |

## API Resources

The SDK provides access to 4 core resources:

- **Sessions** - Create and manage AI agentic sessions
- **Users** - User management and authentication
- **Projects** - Project configuration and settings
- **ProjectSettings** - Project-specific configuration

## Development

```bash
# Generate all SDKs from OpenAPI spec
make generate-sdk

# Verify all SDKs build correctly
make verify-sdk

# Build generator binary
make build-generator
```

## Architecture

The SDK is generated from the OpenAPI specification at `../ambient-api-server/openapi/openapi.yaml` using a custom Go-based generator. This ensures type safety and consistency across all supported languages.

For detailed documentation, see:
- `docs/architecture.md` - Design decisions and platform integration
- `docs/authentication.md` - Auth flows and token formats
- `go-sdk/README.md` - Go-specific usage
- `python-sdk/README.md` - Python-specific usage
122 changes: 122 additions & 0 deletions components/ambient-sdk/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# SDK Architecture

## Design Philosophy

The Ambient Platform SDK is an **HTTP-first, zero-Kubernetes** client library. It deliberately hides the platform's Kubernetes internals behind simple REST semantics so that consumers never need `kubectl`, `client-go`, or cluster credentials.

### Core Principles

1. **Pure HTTP** — Standard REST calls over HTTPS. No CRD watchers, no informers, no leader election.
2. **Minimal Dependencies** — Go SDK uses only the standard library. Python SDK uses only `httpx`.
3. **Type Safety** — Strongly-typed request/response structures in both languages with compile-time (Go) and runtime (Python) validation.
4. **Secure by Default** — Token validation on construction, automatic log redaction, sanitized error surfaces.
5. **API-First** — The API server's `openapi.yaml` is the single source of truth. SDK types derive from it.

## Platform Integration

```
┌──────────────┐
│ Frontend │
│ (NextJS) │
└──────┬───────┘
┌──────────────┐ ┌──────▼───────┐ ┌───────────────┐ ┌────────────┐
│ ambient-sdk │───►│ API Server │───►│ Control Plane │───►│ Operator │
│ (Go/Python) │ │ (Go + Gin) │ │ (Reconciler) │ │ (K8s Ctrl) │
└──────────────┘ └──────────────┘ └───────────────┘ └─────┬──────┘
┌─────▼──────┐
│ Runner │
│ (Claude CLI)│
└────────────┘
```

### Data Flow

1. **SDK** sends `POST /v1/sessions` with task, model, and repos to the API server.
2. **API Server** creates an `AgenticSession` Custom Resource in the target namespace.
3. **Control Plane** detects the new CR via polling (`GET /api/ambient-api-server/v1/sessions`).
4. **Operator** watches CRs and spawns a Kubernetes Job.
5. **Runner** pod executes Claude Code CLI, writes results back to the CR status.
6. **SDK** polls `GET /v1/sessions/{id}` until status is `completed` or `failed`.

### Contract Boundary

The SDK's contract is defined entirely by the API server's OpenAPI spec (`../ambient-api-server/openapi/`). Everything below the API server is opaque:

| Visible to SDK | Hidden from SDK |
|---|---|
| `/v1/sessions` endpoints | AgenticSession CRD schema |
| Bearer token + project header | Kubernetes RBAC policies |
| Session status lifecycle | Job scheduling, pod creation |
| JSON request/response shapes | CR spec/status fields |

## SDK Structure

### Go SDK (`go-sdk/`)

```
client/client.go — HTTP client, request execution, log sanitization
types/types.go — API types, SecureToken, input validators
examples/main.go — Working lifecycle demo
```

The Go client is a single struct wrapping `*http.Client` with:
- `SecureToken` for type-safe, log-safe token handling
- `slog`-based structured logging with `ReplaceAttr` sanitizer
- Context-aware methods (`CreateSession`, `GetSession`, `ListSessions`, `WaitForCompletion`)

### Python SDK (`python-sdk/`)

```
ambient_platform/client.py — AmbientClient with httpx
ambient_platform/types.py — Dataclasses matching OpenAPI
ambient_platform/exceptions.py — Typed exception hierarchy
examples/main.py — Working lifecycle demo
```

The Python client is a class wrapping `httpx.Client` with:
- Input validation on construction (`_validate_token`, `_validate_project`, `_validate_base_url`)
- `from_env()` factory for environment-based setup
- Context manager support for automatic resource cleanup
- Structured exceptions: `AmbientAPIError` → `AuthenticationError`, `SessionNotFoundError`, `AmbientConnectionError`

## Session Lifecycle

```
POST /v1/sessions
┌─────────┐ ┌─────────┐ ┌───────────┐
│ pending │────►│ running │────►│ completed │
└─────────┘ └────┬────┘ └───────────┘
┌─────────┐
│ failed │
└─────────┘
```

- **pending**: CR created, waiting for operator to schedule a Job
- **running**: Job pod is executing the Claude Code CLI
- **completed**: Task finished successfully; `result` field populated
- **failed**: Task failed; `error` field populated

## Cross-Component Coordination

The file `../working.md` serves as a coordination protocol between Claude sessions working on different components. Key rules:

- Read before writing
- Append, don't overwrite
- Tag entries with `[API]` or `[CP]`
- Contracts section defines the agreed API surface

The SDK depends on the contracts in `working.md` — particularly the session list endpoint and authentication scheme.

## Future Roadmap

| Phase | Status | Description |
|---|---|---|
| Phase 1: HTTP-Only Go + Python | Done | Core session CRUD with polling |
| Phase 2: TypeScript SDK | Planned | Generated types from OpenAPI, React Query integration |
| Phase 3: Advanced Features | Planned | OpenTelemetry instrumentation, SDK-based testing utilities |
Loading
Loading