Runtime boundary
Codapult keeps provider calls behind one server-side gateway. Product features call the gateway or the full pipeline; they do not create provider clients in route handlers or components.
Client UI / server action
│
▼
API route: auth → rate limit → Zod request validation → organization quota
│
▼
AI pipeline: budget → RAG context → input guardrails → tools → gateway
│
▼
Model catalogue → provider adapter → Vercel AI SDK
│
├── response / stream
├── output guardrails
└── usage, cost, latency, and request log
The route owns access control and request shape. The pipeline owns product policy. The gateway owns model selection, retries, fallback, AI SDK calls, usage normalization, and cost calculation.
Agents and batch jobs use the same pipeline as chat. Agents resolve their versioned prompt and organization-scoped tools before entering it; batch resolves its prompt version once and runs each item through the pipeline. API entry points apply the user rate limit and organization AI quota before work is scheduled.
Chat, agents, and batch share provider, policy, and metering controls while keeping distinct interaction models: chat can stream, agents can run multi-step tools, and batch processes asynchronously. The detailed request flow and extension sequence are in the .
Runtime guarantees and boundaries
- Prompt versioning: prompts are stored with versions and the selected prompt ID can be attached to a gateway request and its usage log. Agent execution resolves the current configured version before calling the gateway.
- Tool permissions: tools are resolved only when enabled and available to the organization. Sensitive tools still need authorization inside their handler; registering a tool is not a substitute for domain permission checks.
- Tenant isolation: RAG retrieval, guardrail loading, tool lookup, request logs, quotas, and agent lookup accept the active organization scope. Do not derive that scope from arbitrary browser input.
- Fallback semantics: retries happen within a model attempt; the configured fallback chain is considered after a classified error, rate limit, or timeout, and every fallback model must pass the configured allow-list.
- Evaluation and testing: deterministic evals cover request validation, model allow-lists, guardrail behavior, and cost accounting. Provider-backed quality evals remain application-specific and should be versioned with their datasets.
- PII redaction: non-streaming responses can be blocked or redacted before they are returned. Streaming output is evaluated after completion because already-delivered tokens cannot be retracted. The gateway accepts
requireCompleteResponse: trueto force the complete-response path even if a caller also requests streaming; configure output guardrails on that route when pre-delivery redaction is required. - Streaming and cancellation: streaming is implemented through the AI SDK and the chat route now propagates the request
AbortSignalto the provider call. Batch cancellation still changes the persisted job state; it is not the same as cancelling every already-started batch item. - Audit trail: request logs include a compact summary of agent tool calls. The current
aiRequestLogis still an operational log, not a complete immutable audit trail of every tool side effect; add domain audit events around sensitive handlers when that evidence is required.
Capability coverage
This table is the contract boundary for the current AI foundation. “Application-specific” means the extension point is present, but the integrating application must provide the product policy or domain implementation.
| Capability | Current coverage | Boundary to account for |
|---|---|---|
| Unified gateway for chat, agents, batch, and RAG | Implemented through the shared gateway pipeline. | The user experience differs by surface: chat streams, agents run tool steps, and batch runs asynchronously. |
| Shared guardrails and metering | Implemented for the full pipeline used by chat, agents, and batch. | Direct low-level provider calls or gatewayGenerate() calls bypass pipeline policy and should remain internal. |
| Tool permissions | Organization-scoped enabled tools are resolved before execution. | Tool handlers must enforce record-level and business authorization; registry access is not RBAC. |
| Tenant isolation | Organization scope is carried through RAG, guardrails, tools, agents, quotas, and logs. | Never accept the active organization from arbitrary browser input; validate membership at the route boundary. |
| Prompt versioning | Agents and batch resolve a prompt version and record its ID with the request. Gateway requests can attach promptId. | The built-in chat request does not currently expose prompt selection; product-critical chat prompts should be wired explicitly by the integrating route. |
| Fallback semantics | Classified provider errors, rate limits, and timeouts can move through the configured fallback chain. | Fallbacks still need compatible capabilities and valid credentials; they do not guarantee semantic equivalence between models. |
| Retries | Bounded retries are applied within a model attempt. | Retry limits and backoff are configuration; non-idempotent tool side effects need their own idempotency protection. |
| Model allow-list | Unknown models and configured disallowed models are rejected before generation. | Adding a provider requires a catalogue entry, adapter configuration, and pricing/capability data. |
| Cost calculation | Usage is normalized and provider cost is recorded on the gateway path. | Pricing metadata must be kept current when models or providers are added. |
| Quotas | Chat, gateway, and batch entry points apply the organization aiChat request quota; the pipeline also checks optional spend budgets. | Internal direct calls are not an independent quota boundary. Request quotas, token cost, and spend budgets are separate controls. |
| Evaluation and testing | Deterministic evals cover schema validation, model policy, guardrails, and cost accounting. | Provider-backed quality evals require application-owned datasets, acceptance criteria, and model-cost decisions. |
| Audit trail | Request logs and compact tool activity events capture operational evidence. | This is not an immutable business audit ledger. Sensitive handlers must emit domain audit events for reconstructable side effects. |
| Streaming and cancellation | Chat streaming propagates AbortSignal; complete responses support pre-delivery output checks. | Batch cancellation changes job state but does not guarantee cancellation of every provider call already in progress. |
| PII redaction | Input policies run before generation; complete responses can block or redact before delivery. | Streaming output is evaluated after tokens are delivered. Use requireCompleteResponse: true plus a configured output rule for strict pre-delivery handling. |
Extension boundaries
The AI foundation is organized around stable responsibilities rather than a single provider implementation. Extend the capability at its boundary, then keep provider selection, tenant scope, validation, and metering inside the shared runtime.
| Capability | Extension responsibility |
|---|---|
| Models and providers | Add a catalogue entry, provider credentials, capability metadata, and pricing data. |
| Tools and agents | Register a typed, organization-scoped tool and enforce domain authorization in its handler. |
| RAG and embeddings | Choose the embedding/vector providers and define the product's retrieval policy. |
| Prompts and evaluations | Version product-critical prompts and keep application quality datasets separate from deterministic runtime checks. |
| Chat and other surfaces | Call the shared pipeline rather than creating provider clients in a route or UI component. |
Extension rules
- Add a model to the model catalogue before using it in configuration, UI, or pricing.
- Add provider credentials to the server environment schema; never send them to the client.
- Add domain tools through the tool registry with a Zod-compatible parameter schema and an explicit organization scope.
- Keep tenant context in
PipelineContext; do not resolve organization ownership from browser-provided data alone. - Keep prompts versioned when the response is product-critical, and record the prompt ID with usage logs.
- Bound
maxSteps,maxTokens, request size, RAG chunks, retries, and budgets. - Treat model output and tool arguments as untrusted input. Apply validation, authorization, and guardrails before side effects.
Runtime evals
The built-in evals are deterministic contract checks around the provider boundary. They do not call an external model or spend tokens. They cover:
- request schema rejection;
- model catalogue and allow-list behavior;
- input blocking and output PII redaction;
- additive token-cost accounting.
Run them independently from the full suite:
pnpm test:ai-evals
Provider-backed quality evals belong to the product that owns the prompts and acceptance criteria. Keep those datasets versioned, redact user data, pin the model and temperature, and record latency, token usage, cost, and pass/fail reasons. Do not make external model calls part of the default unit-test suite.