chore(openspec): archive phase-5-scale-ecosystem — 68/68 tasks complete

WS1 (Rust SDK), WS2 (A2A Authorization), WS5 (Developer Experience)
all delivered, QA gates passed, committed to main.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
SentryAgent.ai Developer
2026-04-03 02:54:45 +00:00
parent eaabaebf52
commit 8fd6823581
7 changed files with 0 additions and 58 deletions

View File

@@ -0,0 +1,254 @@
## WS2: Agent-to-Agent (A2A) Authorization
### Purpose
Enable AI agents to delegate authority to other AI agents via verifiable, auditable, revocable delegation chains. This is a first-class authorization primitive aligned with the AGNTCY multi-agent orchestration model: an orchestrator agent issues sub-tasks to worker agents and must grant those workers scoped authority to act on its behalf.
A delegation chain is: Agent A (delegator) issues a delegation token granting Agent B (delegatee) a subset of A's own scopes for a bounded time period. Agent B presents this token to verify its delegated authority. The chain is stored in PostgreSQL, signed cryptographically, and audited in the existing audit log.
### New Endpoints
#### `POST /oauth2/token/delegate`
**Summary:** Delegate authority from one agent to another.
**Authentication:** Bearer token (the delegating agent's access token).
**Request Body** (`application/json`):
```json
{
"delegateeAgentId": "string",
"scopes": ["string"],
"ttlSeconds": 3600
}
```
| Field | Type | Required | Constraints |
|---|---|---|---|
| `delegateeAgentId` | string | yes | Must be an existing, active agent in the same tenant |
| `scopes` | string[] | yes | Min 1 item. Each scope must be a subset of the delegator's own scopes |
| `ttlSeconds` | integer | yes | Min: 60, Max: 86400 (24 hours) |
**Response 201** (`application/json`):
```json
{
"delegationToken": "string",
"chainId": "string (UUID)",
"delegatorAgentId": "string",
"delegateeAgentId": "string",
"scopes": ["string"],
"expiresAt": "string (ISO 8601)"
}
```
**Error Responses:**
| Status | Code | Description |
|---|---|---|
| 400 | `INVALID_SCOPES` | Requested scopes exceed delegator's own scopes |
| 400 | `INVALID_TTL` | `ttlSeconds` outside allowed range [60, 86400] |
| 401 | `UNAUTHORIZED` | Missing or invalid Bearer token |
| 404 | `AGENT_NOT_FOUND` | `delegateeAgentId` does not exist or is in a different tenant |
| 422 | `SELF_DELEGATION` | Delegator and delegatee are the same agent |
| 429 | `RATE_LIMITED` | Rate limit exceeded |
**Business Rules:**
- Delegated scopes MUST be a strict subset of the delegator's own scopes (no privilege escalation)
- The delegatee must be an active agent in the same tenant as the delegator
- An agent may not delegate to itself
- A delegation entry is written to `delegation_chains` and an audit log entry is created with `event_type: "delegation.created"`
---
#### `POST /oauth2/token/verify-delegation`
**Summary:** Verify a delegation token and return the delegation chain details.
**Authentication:** Bearer token (any authenticated agent in the same tenant, or unauthenticated if `A2A_PUBLIC_VERIFY=true`).
**Request Body** (`application/json`):
```json
{
"delegationToken": "string"
}
```
| Field | Type | Required | Constraints |
|---|---|---|---|
| `delegationToken` | string | yes | The `delegationToken` value returned by `POST /oauth2/token/delegate` |
**Response 200** (`application/json`):
```json
{
"valid": true,
"chainId": "string (UUID)",
"delegatorAgentId": "string",
"delegateeAgentId": "string",
"scopes": ["string"],
"issuedAt": "string (ISO 8601)",
"expiresAt": "string (ISO 8601)",
"revokedAt": null
}
```
**Response when delegation is expired or revoked** (HTTP 200, not 4xx — the token exists but is not valid):
```json
{
"valid": false,
"chainId": "string (UUID)",
"delegatorAgentId": "string",
"delegateeAgentId": "string",
"scopes": ["string"],
"issuedAt": "string (ISO 8601)",
"expiresAt": "string (ISO 8601)",
"revokedAt": "string (ISO 8601) | null"
}
```
**Error Responses:**
| Status | Code | Description |
|---|---|---|
| 400 | `MALFORMED_TOKEN` | Token is not a valid delegation token format |
| 401 | `UNAUTHORIZED` | Missing Bearer token (when `A2A_PUBLIC_VERIFY=false`) |
| 404 | `CHAIN_NOT_FOUND` | No delegation chain found for the given token |
| 429 | `RATE_LIMITED` | Rate limit exceeded |
**Business Rules:**
- Expired delegations return `valid: false` — not an error response
- Revoked delegations return `valid: false` with `revokedAt` populated
- Verification is non-destructive (does not consume or modify the delegation)
- An audit log entry is created with `event_type: "delegation.verified"` on every call
---
#### `DELETE /oauth2/token/delegate/:chainId`
**Summary:** Revoke a delegation chain. Only the delegator agent can revoke.
**Authentication:** Bearer token (must be the delegator agent's token).
**Path Parameter:**
| Parameter | Type | Description |
|---|---|---|
| `chainId` | string (UUID) | The chain ID returned at delegation creation |
**Response 204:** No body.
**Error Responses:**
| Status | Code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | Missing or invalid Bearer token |
| 403 | `FORBIDDEN` | Authenticated agent is not the delegator of this chain |
| 404 | `CHAIN_NOT_FOUND` | No delegation chain with this ID |
| 409 | `ALREADY_REVOKED` | Delegation chain has already been revoked |
**Business Rules:**
- Sets `revoked_at` timestamp on the `delegation_chains` row
- Audit log entry created with `event_type: "delegation.revoked"`
- Revoking a parent chain does NOT cascade-revoke child chains — each link must be revoked explicitly
---
### Database Schema Changes
#### Migration: `008_add_delegation_chains.sql`
```sql
CREATE TABLE delegation_chains (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
delegator_agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
delegatee_agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
scopes TEXT[] NOT NULL,
delegation_token TEXT NOT NULL UNIQUE,
signature TEXT NOT NULL, -- HMAC-SHA256 of delegation payload, keyed by delegator secret
ttl_seconds INTEGER NOT NULL CHECK (ttl_seconds BETWEEN 60 AND 86400),
issued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL,
revoked_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Index for token lookup (verify-delegation hot path)
CREATE UNIQUE INDEX idx_delegation_chains_token ON delegation_chains(delegation_token);
-- Index for listing delegations by agent
CREATE INDEX idx_delegation_chains_delegator ON delegation_chains(delegator_agent_id, tenant_id);
CREATE INDEX idx_delegation_chains_delegatee ON delegation_chains(delegatee_agent_id, tenant_id);
-- Index for cleanup of expired chains
CREATE INDEX idx_delegation_chains_expires_at ON delegation_chains(expires_at);
```
### New Source Files
| File | Description |
|---|---|
| `src/services/DelegationService.ts` | Business logic: create delegation, verify chain, revoke chain |
| `src/controllers/DelegationController.ts` | HTTP handlers for delegation endpoints |
| `src/routes/delegation.ts` | Express router: `POST /oauth2/token/delegate`, `POST /oauth2/token/verify-delegation`, `DELETE /oauth2/token/delegate/:chainId` |
| `src/types/delegation.ts` | TypeScript interfaces: `DelegationChain`, `CreateDelegationRequest`, `VerifyDelegationRequest`, `DelegationTokenPayload` |
| `src/utils/delegationCrypto.ts` | HMAC-SHA256 signing and verification for delegation payloads — extracted utility, no duplication |
### Modified Source Files
| File | Change |
|---|---|
| `src/routes/index.ts` | Register `delegation` router |
| `src/infrastructure/migrations/` | Add `008_add_delegation_chains.sql` |
| `docs/openapi.yaml` | Add delegation endpoints |
### `DelegationService` Interface
```typescript
interface IDelegationService {
/**
* Create a delegation chain from delegator to delegatee.
* Validates scope subset, signs payload, inserts DB row, writes audit log.
*/
createDelegation(
tenantId: string,
delegatorAgentId: string,
request: CreateDelegationRequest
): Promise<DelegationChain>;
/**
* Verify a delegation token. Returns chain details with valid flag.
* Does not throw on expired/revoked — returns valid: false.
*/
verifyDelegation(delegationToken: string): Promise<DelegationVerificationResult>;
/**
* Revoke a delegation chain. Only the delegator may revoke.
*/
revokeDelegation(chainId: string, requestingAgentId: string): Promise<void>;
}
```
### Prometheus Metrics
| Metric | Type | Labels | Description |
|---|---|---|---|
| `agentidp_delegations_created_total` | Counter | `tenant_id` | Total delegation chains created |
| `agentidp_delegations_verified_total` | Counter | `tenant_id`, `result` (valid/invalid/expired/revoked) | Delegation verification outcomes |
| `agentidp_delegations_revoked_total` | Counter | `tenant_id` | Total delegations revoked |
| `agentidp_delegation_chain_depth` | Histogram | `tenant_id` | Distribution of delegation chain nesting depth |
### Feature Flag
`A2A_ENABLED` environment variable (default: `true`). When `false`, all `/oauth2/token/delegate*` routes return HTTP 404.
### Acceptance Criteria
- `POST /oauth2/token/delegate` creates a delegation chain and returns a delegation token
- Scope subset validation rejects any scope not held by the delegating agent
- `POST /oauth2/token/verify-delegation` returns `valid: true` for active chains
- `POST /oauth2/token/verify-delegation` returns `valid: false` (not 4xx) for expired or revoked chains
- `DELETE /oauth2/token/delegate/:chainId` sets `revoked_at` and subsequent verification returns `valid: false`
- A 403 is returned when a non-delegator agent attempts to revoke a chain
- All delegation events are written to the audit log with correct `event_type`
- Delegation crypto signature uses HMAC-SHA256 — verified at `verify-delegation` time
- Unit test coverage >= 80% on `DelegationService` and `delegationCrypto`
- Integration tests cover: create, verify (valid), verify (expired), verify (revoked), revoke, unauthorized revoke

View File

@@ -0,0 +1,228 @@
## WS5: Developer Experience (DX) Improvements
### Purpose
Reduce time-to-first-successful-agent-call to under 5 minutes for a new developer. Three concrete improvements: (1) upgrade the developer portal's API explorer from Swagger UI v4 to Stoplight Elements — a modern, component-based API documentation experience with better navigation, code samples, and mock server support; (2) add a scaffold generator endpoint that returns a language-specific starter project pre-wired with the developer's agent credentials as a downloadable ZIP; (3) add a `sentryagent scaffold` CLI command that calls the scaffold endpoint and extracts the ZIP into the current directory.
### New Endpoint
#### `GET /sdk/scaffold/:agentId`
**Summary:** Generate and return a language-specific scaffold ZIP for the specified agent.
**Authentication:** Bearer token (tenant-scoped). The authenticated tenant must own the specified agent.
**Path Parameter:**
| Parameter | Type | Description |
|---|---|---|
| `agentId` | string (UUID) | The agent for which to generate the scaffold |
**Query Parameters:**
| Parameter | Type | Required | Default | Constraints |
|---|---|---|---|---|
| `language` | string | no | `typescript` | Enum: `typescript`, `python`, `go`, `java`, `rust` |
**Response 200:**
- Content-Type: `application/zip`
- Content-Disposition: `attachment; filename="sentryagent-scaffold-{agentName}-{language}.zip"`
- Body: Binary ZIP archive stream
**ZIP Archive Contents (TypeScript example):**
```
sentryagent-scaffold-my-agent-typescript/
├── package.json (name: my-agent, version: 0.1.0, deps: sentryagent-idp-sdk)
├── tsconfig.json (strict mode, ES2022 target)
├── .env.example (AGENTIDP_API_URL, AGENTIDP_CLIENT_ID=<pre-filled>, AGENTIDP_CLIENT_SECRET=<placeholder>)
├── .gitignore (.env on first line)
├── src/
│ └── index.ts (imports SDK, creates client from env, issues token, logs success)
└── README.md (step-by-step: cp .env.example .env, fill secret, npm install, npm start)
```
**ZIP Archive Contents (Python example):**
```
sentryagent-scaffold-my-agent-python/
├── requirements.txt (sentryagent-idp)
├── .env.example (AGENTIDP_API_URL, AGENTIDP_CLIENT_ID=<pre-filled>, AGENTIDP_CLIENT_SECRET=<placeholder>)
├── .gitignore (.env on first line)
├── main.py (imports SDK, creates client from env, issues token, prints success)
└── README.md (step-by-step: cp .env.example .env, fill secret, pip install -r requirements.txt, python main.py)
```
**ZIP Archive Contents (Go example):**
```
sentryagent-scaffold-my-agent-go/
├── go.mod (module: my-agent, dep: github.com/sentryagent/sentryagent-idp-go)
├── .env.example (AGENTIDP_API_URL, AGENTIDP_CLIENT_ID=<pre-filled>, AGENTIDP_CLIENT_SECRET=<placeholder>)
├── .gitignore (.env on first line)
├── main.go (imports SDK, creates client from env, issues token, logs success)
└── README.md (step-by-step instructions)
```
**Error Responses:**
| Status | Code | Description |
|---|---|---|
| 400 | `INVALID_LANGUAGE` | `language` query param is not one of the supported values |
| 401 | `UNAUTHORIZED` | Missing or invalid Bearer token |
| 403 | `FORBIDDEN` | Authenticated tenant does not own this agent |
| 404 | `AGENT_NOT_FOUND` | No agent with `agentId` found |
| 429 | `RATE_LIMITED` | Rate limit exceeded |
**Business Rules:**
- `clientId` is pre-filled in `.env.example` — taken from the agent's credentials in the database
- `clientSecret` is always a `<your-client-secret>` placeholder — never returned in scaffold (credentials security policy)
- The ZIP is generated in memory using `archiver` — no disk writes on the server
- Scaffold generation is rate-limited to 10 requests per minute per tenant (separate from the main tier rate limit)
- An audit log entry is created with `event_type: "scaffold.generated"`, `metadata.language`
---
### Developer Portal: Elements API Explorer Upgrade
**File to modify:** `portal/app/api-explorer/page.tsx`
**Current state (Phase 4):** Embeds `swagger-ui-react` (Swagger UI v4) loaded from `NEXT_PUBLIC_API_URL/openapi.json`.
**New state (Phase 5):** Replaces `swagger-ui-react` with `@stoplight/elements` (`<API>` component). Stoplight Elements provides: three-panel layout (navigation, docs, try-it), built-in code samples in multiple languages, mock server support, and better mobile responsiveness.
**Implementation:**
```tsx
// portal/app/api-explorer/page.tsx (complete replacement)
'use client';
import { API } from '@stoplight/elements';
import '@stoplight/elements/styles.min.css';
export default function ApiExplorerPage() {
return (
<main className="h-screen w-full">
<API
apiDescriptionUrl={`${process.env.NEXT_PUBLIC_API_URL}/openapi.json`}
router="hash"
layout="sidebar"
hideSchemas={false}
tryItCredentialsPolicy="same-origin"
/>
</main>
);
}
```
**Files modified:**
- `portal/app/api-explorer/page.tsx` — replace Swagger UI component with Elements `<API>` component
- `portal/package.json` — replace `swagger-ui-react` with `@stoplight/elements`
---
### CLI: `sentryagent scaffold` Command
**File to create:** `cli/src/commands/scaffold.ts`
**Command syntax:**
```
sentryagent scaffold --agent-id <id> [--language typescript|python|go|java|rust] [--out <directory>]
```
**Options:**
| Option | Alias | Default | Description |
|---|---|---|---|
| `--agent-id <id>` | `-a` | (required) | Agent ID to scaffold for |
| `--language <lang>` | `-l` | `typescript` | Target language for scaffold |
| `--out <dir>` | `-o` | `.` (current dir) | Directory to extract scaffold ZIP into |
**Behavior:**
1. Load config from `~/.sentryagent/config.json` — fail with helpful message if not configured
2. Issue an API call: `GET /sdk/scaffold/{agentId}?language={language}` with Bearer token from `POST /oauth2/token`
3. Receive ZIP stream, pipe through `unzipper` to extract into `--out` directory
4. Print success message: `Scaffold generated at ./{agentName}-{language}/`
5. Print next steps:
```
Next steps:
1. cd {agentName}-{language}
2. cp .env.example .env
3. Add your AGENTIDP_CLIENT_SECRET to .env
4. npm install (or equivalent for your language)
5. npm start
```
**Error handling:**
- Agent not found: print `Agent {agentId} not found.`
- Forbidden: print `You do not own agent {agentId}.`
- Invalid language: print `Unsupported language '{lang}'. Choose: typescript, python, go, java, rust`
- Output directory does not exist: create it (with user prompt for confirmation if non-empty)
**New CLI dependencies** (add to `cli/package.json`):
- `unzipper` — streaming ZIP extraction (pure JS, no native deps)
### New Source Files
| File | Description |
|---|---|
| `src/services/ScaffoldService.ts` | Business logic: build ZIP archive in memory using `archiver` |
| `src/controllers/ScaffoldController.ts` | HTTP handler: stream ZIP response |
| `src/routes/scaffold.ts` | Express router: `GET /sdk/scaffold/:agentId` |
| `src/types/scaffold.ts` | TypeScript interfaces: `ScaffoldLanguage`, `ScaffoldOptions`, `ScaffoldTemplate` |
| `src/templates/scaffold/typescript/` | Template files for TypeScript scaffold (package.json, tsconfig.json, index.ts, .env.example, .gitignore, README.md) |
| `src/templates/scaffold/python/` | Template files for Python scaffold (requirements.txt, main.py, .env.example, .gitignore, README.md) |
| `src/templates/scaffold/go/` | Template files for Go scaffold (go.mod, main.go, .env.example, .gitignore, README.md) |
| `src/templates/scaffold/java/` | Template files for Java scaffold (pom.xml, Main.java, .env.example, .gitignore, README.md) |
| `src/templates/scaffold/rust/` | Template files for Rust scaffold (Cargo.toml, src/main.rs, .env.example, .gitignore, README.md) |
| `cli/src/commands/scaffold.ts` | CLI scaffold command implementation |
### Modified Source Files
| File | Change |
|---|---|
| `src/routes/index.ts` | Register `scaffold` router |
| `src/app.ts` | No change needed (routes registered via index) |
| `package.json` (API) | Add `archiver` and `@types/archiver` |
| `portal/app/api-explorer/page.tsx` | Replace Swagger UI with Elements |
| `portal/package.json` | Replace `swagger-ui-react` with `@stoplight/elements` |
| `cli/src/index.ts` | Register `scaffold` command with Commander |
| `cli/package.json` | Add `unzipper` and `@types/unzipper` |
| `docs/openapi.yaml` | Add `GET /sdk/scaffold/:agentId` endpoint |
### `ScaffoldService` Interface
```typescript
interface IScaffoldService {
/**
* Generate an in-memory ZIP archive for the given agent and language.
* Returns a Node.js Readable stream of the ZIP binary.
* Template variables injected: {{AGENT_ID}}, {{AGENT_NAME}}, {{CLIENT_ID}}, {{API_URL}}
*/
generateScaffold(
agentId: string,
language: ScaffoldLanguage,
apiUrl: string
): Promise<{ stream: NodeJS.ReadableStream; filename: string }>;
}
```
### Prometheus Metrics
| Metric | Type | Labels | Description |
|---|---|---|---|
| `agentidp_scaffold_generated_total` | Counter | `language` | Scaffold ZIPs generated by language |
| `agentidp_scaffold_generation_duration_ms` | Histogram | `language` | Time to generate scaffold ZIP |
### Acceptance Criteria
- `GET /sdk/scaffold/:agentId?language=typescript` returns a valid ZIP with all 6 template files
- ZIP contains `.env.example` with `AGENTIDP_CLIENT_ID` pre-filled and `AGENTIDP_CLIENT_SECRET=<your-client-secret>` as placeholder
- ZIP never contains the actual client secret
- `GET /sdk/scaffold/:agentId?language=python` returns Python-specific template files
- All 5 languages (typescript, python, go, java, rust) return valid ZIPs
- HTTP 400 on unknown `language` query param
- HTTP 403 when authenticated tenant does not own the agent
- `sentryagent scaffold --agent-id abc123 --language go` extracts scaffold to current directory
- `sentryagent scaffold --agent-id abc123 --language python --out /tmp/myagent` extracts to `/tmp/myagent`
- Developer portal `/api-explorer` renders Elements v5 with sidebar layout — TypeScript build passes
- Unit tests cover: scaffold generation (each language), forbidden access, invalid language
- Integration tests cover: scaffold endpoint response type, content-disposition header, ZIP validity

View File

@@ -0,0 +1,289 @@
## WS1: Rust SDK
### Purpose
Deliver a production-grade, idiomatic Rust SDK for SentryAgent.ai AgentIdP. The SDK covers all 14 API endpoints, provides a thread-safe `TokenManager` with automatic token refresh, uses `async/await` throughout via `tokio`, and models all errors as a typed `AgentIdPError` enum. Rust developers building high-performance or safety-critical AI agents can integrate with SentryAgent.ai without writing HTTP boilerplate.
The SDK is published to crates.io as `sentryagent-idp`. It mirrors the API surface of the Go SDK (the most recently authored and cleanest SDK) to reduce cognitive load for polyglot teams.
### New Files to Create
| File | Description |
|---|---|
| `sdk-rust/Cargo.toml` | Crate manifest — name: `sentryagent-idp`, edition: 2021 |
| `sdk-rust/src/lib.rs` | Crate root — re-exports `AgentIdPClient`, `TokenManager`, `AgentIdPError`, all model types |
| `sdk-rust/src/client.rs` | `AgentIdPClient` struct — wraps `reqwest::Client`, holds base URL + credentials |
| `sdk-rust/src/token_manager.rs` | `TokenManager` struct — `Arc<Mutex<TokenCache>>`, auto-refresh logic |
| `sdk-rust/src/error.rs` | `AgentIdPError` enum — all typed error variants, implements `std::error::Error` |
| `sdk-rust/src/models.rs` | All request/response model structs — serde Serialize/Deserialize |
| `sdk-rust/src/agents.rs` | Agent CRUD methods on `AgentIdPClient` |
| `sdk-rust/src/oauth2.rs` | Token issuance and refresh methods |
| `sdk-rust/src/credentials.rs` | Credential management methods |
| `sdk-rust/src/audit.rs` | Audit log query methods |
| `sdk-rust/src/marketplace.rs` | Marketplace listing and detail methods |
| `sdk-rust/src/delegation.rs` | A2A delegation methods (WS2 integration) |
| `sdk-rust/examples/quickstart.rs` | Working quickstart example — register agent, issue token, make authenticated call |
| `sdk-rust/README.md` | Installation, configuration, quickstart, all methods with examples |
| `sdk-rust/tests/integration_test.rs` | Integration tests against a real API instance (reads `AGENTIDP_API_URL` env var) |
### Cargo.toml Dependencies
```toml
[dependencies]
tokio = { version = "1.35", features = ["full"] }
reqwest = { version = "0.11", features = ["json", "rustls-tls"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
uuid = { version = "1.6", features = ["v4"] }
thiserror = "1.0"
async-trait = "0.1"
[dev-dependencies]
tokio-test = "0.4"
mockito = "1.2"
```
### Public API Surface
#### `AgentIdPClient`
```rust
pub struct AgentIdPClient {
base_url: String,
client_id: String,
client_secret: String,
http: reqwest::Client,
token_manager: Arc<Mutex<TokenManager>>,
}
impl AgentIdPClient {
/// Create a new client. Does not make any network calls at construction time.
pub fn new(base_url: &str, client_id: &str, client_secret: &str) -> Self;
/// Create a client from environment variables:
/// AGENTIDP_API_URL, AGENTIDP_CLIENT_ID, AGENTIDP_CLIENT_SECRET
pub fn from_env() -> Result<Self, AgentIdPError>;
// Agent methods
pub async fn register_agent(&self, req: RegisterAgentRequest) -> Result<Agent, AgentIdPError>;
pub async fn get_agent(&self, agent_id: &str) -> Result<Agent, AgentIdPError>;
pub async fn list_agents(&self, page: u32, per_page: u32) -> Result<AgentList, AgentIdPError>;
pub async fn update_agent(&self, agent_id: &str, req: UpdateAgentRequest) -> Result<Agent, AgentIdPError>;
pub async fn delete_agent(&self, agent_id: &str) -> Result<(), AgentIdPError>;
// OAuth2 token methods
pub async fn issue_token(&self, agent_id: &str, scopes: &[&str]) -> Result<TokenResponse, AgentIdPError>;
// Credential methods
pub async fn generate_credentials(&self, agent_id: &str) -> Result<Credentials, AgentIdPError>;
pub async fn rotate_credentials(&self, agent_id: &str) -> Result<Credentials, AgentIdPError>;
pub async fn revoke_credentials(&self, agent_id: &str) -> Result<(), AgentIdPError>;
// Audit log methods
pub async fn list_audit_logs(&self, filters: AuditLogFilters) -> Result<AuditLogList, AgentIdPError>;
// Marketplace methods
pub async fn list_public_agents(&self, filters: MarketplaceFilters) -> Result<MarketplaceAgentList, AgentIdPError>;
pub async fn get_public_agent(&self, agent_id: &str) -> Result<MarketplaceAgent, AgentIdPError>;
// Delegation methods (WS2)
pub async fn delegate(&self, req: DelegateRequest) -> Result<DelegationToken, AgentIdPError>;
pub async fn verify_delegation(&self, token: &str) -> Result<DelegationVerification, AgentIdPError>;
}
```
#### `TokenManager`
```rust
/// Thread-safe token cache with automatic refresh.
/// Holds the current access token and its expiry.
/// Re-issues a token when it is within 60 seconds of expiry.
pub struct TokenManager {
client_id: String,
client_secret: String,
api_url: String,
cache: Arc<Mutex<TokenCache>>,
}
struct TokenCache {
access_token: Option<String>,
expires_at: Option<std::time::Instant>,
}
impl TokenManager {
pub fn new(api_url: &str, client_id: &str, client_secret: &str) -> Self;
/// Returns a valid access token. Refreshes automatically if expired or within 60s of expiry.
pub async fn get_token(&self) -> Result<String, AgentIdPError>;
}
```
#### `AgentIdPError`
```rust
#[derive(Debug, thiserror::Error)]
pub enum AgentIdPError {
#[error("HTTP request failed: {0}")]
HttpError(#[from] reqwest::Error),
#[error("API error {status}: {message}")]
ApiError { status: u16, message: String, code: Option<String> },
#[error("Authentication failed: {0}")]
AuthError(String),
#[error("Agent not found: {0}")]
NotFound(String),
#[error("Rate limit exceeded. Retry after {retry_after_secs}s")]
RateLimited { retry_after_secs: u64 },
#[error("Invalid configuration: {0}")]
ConfigError(String),
#[error("Serialization error: {0}")]
SerdeError(#[from] serde_json::Error),
#[error("Delegation chain invalid: {0}")]
DelegationError(String),
}
```
### Model Structs (complete — no placeholders)
```rust
// Request types
pub struct RegisterAgentRequest {
pub name: String,
pub description: Option<String>,
pub capabilities: Vec<String>,
pub metadata: Option<serde_json::Value>,
}
pub struct UpdateAgentRequest {
pub name: Option<String>,
pub description: Option<String>,
pub capabilities: Option<Vec<String>>,
pub is_public: Option<bool>,
pub metadata: Option<serde_json::Value>,
}
pub struct AuditLogFilters {
pub agent_id: Option<String>,
pub event_type: Option<String>,
pub from: Option<String>, // ISO 8601
pub to: Option<String>, // ISO 8601
pub page: u32,
pub per_page: u32,
}
pub struct MarketplaceFilters {
pub q: Option<String>,
pub capability: Option<String>,
pub publisher: Option<String>,
pub page: u32,
pub per_page: u32,
}
pub struct DelegateRequest {
pub delegatee_agent_id: String,
pub scopes: Vec<String>,
pub ttl_seconds: u64,
}
// Response types
pub struct Agent {
pub id: String,
pub name: String,
pub description: Option<String>,
pub capabilities: Vec<String>,
pub did: String,
pub is_public: bool,
pub created_at: String,
pub updated_at: String,
}
pub struct AgentList {
pub agents: Vec<Agent>,
pub total: u64,
pub page: u32,
pub per_page: u32,
}
pub struct TokenResponse {
pub access_token: String,
pub token_type: String,
pub expires_in: u64,
pub scope: String,
}
pub struct Credentials {
pub client_id: String,
pub client_secret: String, // Only present on generate/rotate — never on read
pub created_at: String,
}
pub struct AuditLogEntry {
pub id: String,
pub agent_id: String,
pub event_type: String,
pub actor: String,
pub metadata: serde_json::Value,
pub timestamp: String,
}
pub struct AuditLogList {
pub entries: Vec<AuditLogEntry>,
pub total: u64,
pub page: u32,
pub per_page: u32,
}
pub struct MarketplaceAgent {
pub id: String,
pub name: String,
pub description: Option<String>,
pub capabilities: Vec<String>,
pub did_document: serde_json::Value,
pub publisher: String,
pub created_at: String,
}
pub struct MarketplaceAgentList {
pub agents: Vec<MarketplaceAgent>,
pub total: u64,
pub page: u32,
pub per_page: u32,
}
pub struct DelegationToken {
pub delegation_token: String,
pub chain_id: String,
pub expires_at: String,
}
pub struct DelegationVerification {
pub valid: bool,
pub chain_id: String,
pub delegator_agent_id: String,
pub delegatee_agent_id: String,
pub scopes: Vec<String>,
pub expires_at: String,
}
```
### Database Schema Changes
None. The Rust SDK is a client library — it makes HTTP calls to the existing API. No database changes are required for WS1.
### Acceptance Criteria
- `cargo build` passes with zero warnings (deny warnings enforced via `#![deny(warnings)]` in `lib.rs`)
- `cargo clippy` passes with zero warnings
- `cargo test` runs all unit tests — all pass
- Integration tests pass against a live API instance when `AGENTIDP_API_URL`, `AGENTIDP_CLIENT_ID`, `AGENTIDP_CLIENT_SECRET` are set
- `TokenManager::get_token()` is thread-safe: concurrent calls from multiple `tokio` tasks do not produce race conditions (verified by a concurrent-call test with 50 parallel futures)
- Zero `unwrap()` calls in `src/` (only in `examples/` and `tests/` where panicking is acceptable)
- All public items have `///` doc comments
- `cargo doc --no-deps` generates docs without errors
- Published to crates.io as `sentryagent-idp` version `1.0.0`