Sentin8:AI - Detailed Design Document
1. Scope & Context
Sentin8:AI owns the platform's AI plane: prompt assets (versioned, immutable), provider routing (openai / anthropic / ollama / vllm adapters with normalised tool-call support), synchronous inference (buffered + streamed), multi-turn agent conversations with a bounded tool-calling loop, vector + keyword retrieval, async AI jobs (embeddings, summaries, classifications, document pipelines), budgets, evaluations, output filters, traces/costs, and its dead-letter queue.
- Owns (schema
ai, databasesentin8):prompts,providers,embeddings,traces,embedding_registry,dlq,budgets,evaluations,filters, and the agent plane -agents,tools,conversations,messages,runs,tool_calls,approvals,agent_policies- plusoutbox(DBX) andaudit_journal(DBX); the stream familyai; the three direct-consumer groups on it. - Does NOT own: model credentials (secret references resolved via Sentin8:Secrets / env backend), long-running side effects of agent tools (Sentin8:Flow workflows, Sentin8:Func modules), scheduling (Sentin8:Cron), document blobs (Sentin8:Storage), spend analytics (Sentin8:Stat), identity issuance (Sentin8:Auth - AI only requests agent tokens).
- Agent plane boundary: the model loop (context assembly, provider
iteration, tool dispatch, guards) is AI's. The work a tool performs
belongs to the owning service and is reached through the tool gateway
(
sys.service_actions, Flow, Func) - AI never reads another service's tables and never executes domain logic itself.
2. Runtime Architecture
Request lifecycle - buffered inference (POST /v1/chat):
Error branches: terminal provider error (4xx/auth/schema) → 422; retries exhausted → 502; moderation failure → 422 with filter name.
Request lifecycle - one agent turn (POST /v1/conversations/{id}/turns):
A turn is the unit of multi-turn behaviour: it appends the user message,
runs the bounded loop, persists every tool exchange, and returns the final
assistant message. Everything the loop decided is recorded, so a turn is
reproducible from ai.runs.context_plan.
Loop guards are mandatory and each one is recorded on the run:
max_turns (agent policy), token + cost budget (decremented before each
provider call), and a wall-clock deadline for the whole turn. Stop reasons
are a closed set: completed, max_turns, budget, cancelled,
awaiting_approval, error.
3. Data Model
- RLS: every table
ENABLE+FORCE, per-op policies keyed onsentin8_current_env_id() = env_id; outbox/journal policies additionally requiresentin8_context_initialized(). - Holder-scoped RLS on conversations (§4.3c):
ai.conversationsselect/update admit theowner_subrow only (plus env/org admins through the context-stamped flags).ai.messages,ai.runs,ai.tool_callsandai.approvalsinherit the scope through their parent conversation - a policy that joins the parent is the only permitted shape; there is no org-wide visibility tier on agents. ai.toolsandai.agentsare tenant-authorable (origin-less: every row is tenant-owned; the platform seeds none).ai.agent_policiesis the per-env bounds document (models, turn caps, tool classes, retention) - an agent's effective policy is its referenced policy or the env default.ai.tracesgainsrun_idso an inference is attributable to the turn that caused it; the conversation key never lives on the trace (the trace stays a metrics row).- Secrets:
providers.credential_refholds a secret reference - material never lands in application tables (resolved via Secrets or the env backendSENTIN8_AI_PROVIDER_KEY_*). - Indexes: HNSW cosine on
ai.embeddings.embedding(pgvector-guarded), GIN onto_tsvector('simple', chunk_text), partial unrelayed indexes onoutbox/audit_journal; helperai.ai_monthly_tokens(env, feature);UNIQUE (conversation_id, seq)onai.messages(turn ordering and idempotent append),UNIQUE (env_id, name)onai.toolsandai.agents, partialai.approvals_pending_idxon(run_id) WHERE state='pending'.
Prompt lifecycle:
Agent plane lifecycles:
- Run records are append-only apart from the terminal
stop_reasonand usage counters. A resumed approval never rewrites history: it opens the next iteration of the same run so the transcript stays linear.
3.9 Capability tables (AI-first programme)
The tables below extend the model for the capabilities described in §4.7-§4.13
and §5. They follow the same rules as every other ai table: env_id is the
sole tenant key, RLS is forced, and a holder-scoped table stamps owner_sub.
| Table | Tier | Notes |
|---|---|---|
ai.mcp_servers | env-scoped | Credential is a reference; streamable_http is the only accepted transport; the URL is scheme-checked at registration, never at dispatch |
ai.mcp_tools | env-scoped | exposed_name is UNIQUE (env_id, exposed_name) so two servers cannot both own search |
ai.memories | holder-scoped | owner_sub + sentin8_current_subject_id(); region records where the content originated |
ai.cost_ledger | env-scoped | Append-only; settled flips when bill8 acknowledges, never on push attempt |
ai.eval_baselines | env-scoped | One row per (prompt, version, metric); the gate compares against the previous version's row |
Two capabilities deliberately add no table:
- Residency is a column on
ai.providers(region) plus a list onai.agent_policies(allowed_regions). A separate rates table would be a second place the truth could live, and the Shield context builder needs both values as attributes, not as a join. - A2A is a projection: an external task is an
ai.runsrow, and its state is the run'sstop_reason. Materialising a parallela2a_taskstable would give the platform two owners of one lifecycle.
Why the MCP tool row is materialised, not discovered at dispatch. The
residency rule (§5) forbids a handler from making a cross-service call to
answer a request, and the same reasoning governs tools: the model's tool list
is assembled from local state. Discovery writes ai.mcp_tools on registration
and on a TTL refresh; a dispatch reads the cached row and calls the server with
the row's timeout. A server that dies therefore fails one dispatch, not every
listing.
Why memory carries region. A memory extracted from an EU conversation
must not be retrieved into a call routed to a US provider (§5). Storing the
origin region on the row makes that a predicate in the retrieval query rather
than an inference from source_run_id, whose run may itself have been deleted
by retention.
4. API Surface
4.1 Endpoint groups
Groups (every route: bearer verify → Shield require_policy, target env
required for data surfaces, no in-handler scope checks):
| Group | Endpoints | Gate action | Events |
|---|---|---|---|
| prompts | POST/GET /v1/prompts, DELETE /v1/prompts/{name}/{version} | ai:prompt:write / ai:prompt:read | sentin8:ai:prompt:updated |
| inference | POST /v1/chat, /v1/completions, /v1/chat/stream (ndjson) | ai:chat:write / ai:completion:write | trace rows + Stat |
| vectors | POST /v1/embeddings, POST /v1/retrieval, /v1/documents/ingest, GET/PUT /v1/registry | ai:embedding:write / ai:retrieval:read | sentin8:ai:document:ready |
| ops | /v1/budgets/{feature}, /v1/dlq[/replay], /v1/evaluations/run, /v1/costs, /v1/traces | prompt scopes | sentin8:ai:{job_type}:job (replay) |
| conversations | POST/GET /v1/conversations, GET /v1/conversations/{id}, PUT /v1/conversations/{id}, GET /v1/conversations/{id}/messages?after_seq= | ai:conversation:read / ai:conversation:write | sentin8:ai:conversation:created, :archived |
| turns | POST /v1/conversations/{id}/turns, GET /v1/runs/{id}, POST /v1/runs/{id}/cancel | ai:agent:run | sentin8:ai:run:completed, sentin8:ai:turn:delta (SSE) |
| tools | POST/GET /v1/tools, GET /v1/tools/{name}, PUT/DELETE /v1/tools/{name} | ai:tool:read / ai:tool:write | sentin8:ai:tool:updated |
| agents | POST/GET /v1/agents, PUT/DELETE /v1/agents/{name}, POST/GET /v1/agent-policies | ai:agent:write / ai:agent:read | sentin8:ai:agent:updated |
| approvals | GET /v1/approvals?state=pending, POST /v1/approvals/{id}/decide | ai:agent:approve | sentin8:ai:approval:decided |
| internal | /v1/internal/traces/archive (Cron proxy-back), /v1/internal/schedules/run (stale re-embed scan) | ai:embedding:write | archive events |
| admin/SDUI | /v1/admin/ui/{page}, /v1/admin/{resource}, shared policy admin | Shield | - |
| health | GET /v1/health | none | - |
Event flow (outbox → Bus → trigger):
Registration-declared triggers: *:document:uploaded → document-pipeline;
sentin8:ai:trace:archive (cron ai-trace-archive);
sentin8:ai:embedding:stale (cron ai-reembed-stale);
sentin8:ai:agent:turn_requested → {"kind": "agent", "agent_name": ...}
(an inbound event opens a turn instead of a job).
4.2 Tool gateway contract
A tool is a tenant-authored row, not a code path. Dispatch is uniform, so adding a capability never edits AI:
http_actionresolves throughsys.service_actions- the same registry the BFF's/bff/action/{action}uses. No URL is ever stored on a tool row; the tool names an action, enroll published the mapping. This also gives discovery for free: the candidate tool set for an env is the actions its scopes admit.side_effectis the confirmation axis:readandwriteexecute inline;irreversiblealways pauses forPOST /v1/approvals/{id}/decidebefore dispatch. The class is on the tool row, so a tenant can declare their own tool irreversible.rate_limit_per_minis enforced at the gateway: a fixed one-minuteINCR/EXPIREwindow keyed(env, tool)in Valkey (airate_limit.rs), with a process-local minute window as the degraded mode - a Valkey outage tightens to the local bound, it never fails open and never blocks a tool outright. A refused call is a model-visibledeniedwith the reason.- Tool results are sanitized before they re-enter the transcript: capped
to the row's
max_response_bytes, then deny-list PII keys are removed RECURSIVELY (a tool result nests; the shared top-levelstrip_piiused by traces is not enough for this path). The sanitizer issanitize_tool_resultinagent_gateway.rs, pinned by an integration test. - Approval EXECUTES the tool: an approved decision reopens the run, re-validates the arguments and the APPROVER's scope (approval never bypasses the gates), dispatches under the approver's authorization, appends the sanitized result to the transcript, and re-closes the run. A denial fails it. The decision commits first, so an approval is never re-decidable.
- Arguments never reach a target unvalidated. The schema check happens
in the gateway, not in the target, and
arguments_hashlands in audit so a mutation is provable after the fact. - Results are bounded and filtered before they re-enter the transcript:
max_response_bytestruncation plus the env PII deny-list, so a large or sensitive tool payload cannot bloat context or leak into a message row. - Tool execution authority is the caller's, never AI's: the agent token
carries the conversation owner plus the
actchain (see §5), and Shield evaluates it. A tool cannot escalate beyond what the requesting user could do directly.
4.3 Provider tool-call normalisation
The adapters convert each provider's native shape into one ToolCall
({id, name, arguments}) plus a normalized FinishReason
(stop | tool_calls | length | content_filter):
| Provider | Request | Response |
|---|---|---|
| OpenAI / vLLM / Ollama | tools[] + tool_choice | choices[].message.tool_calls[], finish_reason |
| Anthropic | tools[] (added - the body previously had none) + tool_choice | content[] blocks of type: "tool_use" (id, name, input), stop_reason |
| Assistant echo | role: tool + tool_call_id replayed as the provider expects (tool role on OpenAI family, tool_result block on Anthropic) | - |
The JSON-intent contract ({action, params, requires_confirmation}) is
retained as an explicit JSON-output mode for deterministic
classification prompts - a prompt may declare it, and parse_intent
remains the fail-closed parser for that mode. It is no longer the only
path: the default agent path is native tool calling.
4.4 Edge-function inference (ai_infer)
Sentin8:Func modules reach inference through a host builtin that AI serves on its normal inference surface - no per-service passthrough endpoint exists anywhere in the platform.
- Identity is the module's workload certificate, not the caller's
bearer: the Func runtime holds a
sentin8:ai:infer:writegrant (narrower thanchat:write- inference only, no prompt or tool administration). - Multi-turn inside a stateless sandbox: the request may carry
conversation_id; AI loads history, runs the turn, and persists it. The module stays fuel-bounded and state-free, which is the only shape the sandbox permits. - The module cannot outspend its env: AI's budget gate applies unchanged, and the model choice comes from the env's provider routes (§4.4), not from anything the module sends.
- Bounded: the same 1 MiB response cap as every proxy-back, and a provider timeout that aborts the host call rather than the module (the module sees an error and decides).
4.5 Provider routes are tenant-scoped and live
Routes resolve per request from the caller's env, not from a boot-time
snapshot of sys/ops:
- A tenant registering
ai.providerstakes effect on the next request.put_provider/delete_providerwrite an outbox row (sentin8:ai:provider:updated) in the same transaction and invalidate the local entry, so the change is immediate on the writing instance and propagates to the fleet through the Bus relay; the(env, provider)cache entry also expires on its 5-minute TTL as the backstop for a missed event. - The route load runs inside a tenant transaction.
ai.providersisFORCE ROW LEVEL SECURITY, so a pool-levelSELECTcarries nosentin8_current_env_id()and is filtered to zero rows - the route would never resolve and the caller would see "provider not configured" for an env that configured it.ProviderRouteCache::loadtherefore sets the context for the env it is resolving on the same connection before reading (§3, and the platform rule that the context is transaction-local). - Credential resolution stays secret-reference-only; the cache holds the resolved adapter and a short-lived credential, never plaintext at rest.
- An env with no provider row falls back to the platform (
sys/ops) route only for platform-origin prompts; a tenant prompt with no tenant route is a 422 naming the env, never a silent platform charge.
4.6 Provider credentials resolve through Sentin8:Secrets
ai.providers.credential_ref is a reference, never material. Resolution
is delegated per environment to the fleet's secret store:
Four backend forms are accepted by credential_from_ref:
credential_ref | Backend | Posture |
|---|---|---|
secrets://ai/<name> | Sentin8:Secrets over the AI workload certificate | Production - the only supported path |
service://ai/<name> | alias of the above | Production |
env://<name> | SENTIN8_AI_PROVIDER_KEY_<NAME> in the AI process env | Dev bootstrap only |
file://<path> | a local file | Dev bootstrap only |
The secrets path is the only one that satisfies the platform's
secret-reference rule (principles "secret references only"), because the
value lives encrypted in the secret store and is decrypted per use under the
service's own identity. It depends on exactly one grant: the ai workload
holds sentin8:secrets:secret:read, declared in this service's m2m_grants
and provisioned by vertical enroll (DCR is dynamic - no static row is seeded
anywhere). Without that grant the resolution returns None, the provider is
reported as unconfigured, and the caller gets a 422 naming the env - it never
silently falls back to another backend.
The workload name in that grant is the one whose certificate is presented.
This service authenticates as ai (the certificate its Bus consumer and its
Secrets resolve both load), so a grant on any other slug - including the fuller
sentin8:ai identity - is inert for this edge: the certificate IS the
identity, and the scopes that authorize the call are read from the workload
map row for the presented certificate's subject. A running instance reads the
map at boot, so changing the grant requires a restart (or the map's TTL) before
the new scopes apply.
The env:// and file:// forms exist so a developer can smoke-test without
a secret store; both keep material outside the database but inside a
process's reachable surface, so neither is a production posture.
4.7 MCP egress - external tool servers as tools
The tool registry accepts a fifth kind: mcp_server. An env registers an
external Model Context Protocol server once, and its tools become available to
every agent bound to them, with the same validation, rate-limit, PII-stripping,
and audit treatment as a native tool.
Decisions and their reasons.
- Namespacing is mandatory. An MCP server's tool names are local to that
server; two servers both exposing
searchis the normal case. The exposed name is{server}__{tool}. Collisions are rejected at registration byUNIQUE (env_id, exposed_name), not resolved by last-write-wins. - Discovery is cached, never on the request path.
tools/listruns on registration and on a TTL; the rows are what dispatch reads. This is the AGENTS.md rule-3 pattern applied to a tool catalogue: the handler serves from local state. - The credential is a reference.
auth_refissecrets://..., resolved through the same path as a provider key (§4.6) and never persisted. - A tool-level error is not a platform error. Per the MCP contract, a
server that ran and failed returns content the model should see; a transport
failure is
DispatchOutcome::Error. Collapsing the two would either hide recoverable information from the model or feed transport noise into the transcript. - Sanitisation is unchanged.
cap_resultthenstrip_pii_deep, exactly as for native tools: an MCP server is a third-party data source and the least trustworthy hop in the loop. stdiotransport is not offered to tenants. A tenant-authored MCP server would be arbitrary process execution inside a platform service. Onlystreamable_httpis accepted;stdioexists solely for platform-internal modules, which are not tenant-registerable. This is a security boundary, not a missing feature.
Schema dialect. MCP inputSchema is JSON Schema 2020-12; tools:: validate_arguments already implements the subset the platform honours
(type, required, properties, additionalProperties, array items). A
schema using a construct outside that subset is rejected at registration with a
message naming the construct, rather than silently under-validating at
dispatch.
Endpoint group.
| Endpoint | Gate | Notes |
|---|---|---|
PUT /v1/mcp/servers/{name} | ai:tool:write | Registers server + triggers discovery |
GET /v1/mcp/servers | ai:tool:read | Metadata only, never credentials |
DELETE /v1/mcp/servers/{name} | ai:tool:write | Disables server and its tools |
POST /v1/mcp/servers/{name}/refresh | ai:tool:write | Synchronous re-discovery (explicit operator action) |
Registration emits sentin8:ai:mcp:server:updated on the outbox so every
instance drops its tool cache.
4.8 Structured output on the agent path
/v1/chat validates the response against the prompt's output_schema; the
agent loop does not. That asymmetry is a defect, and it is worse than an absent
feature because the tenant configured a contract that is silently ignored.
The fix is not a bare validate_schema call on free text - a model answering a
schema-constrained prompt still returns prose or a fenced code block, so naive
validation fails most of the time. The sequence is:
Decisions and their reasons.
response_formatfirst. Asking the provider for JSON is strictly better than asking for prose and then complaining: it removes most failures instead of handling them.- One repair attempt, then fail. Unbounded repair loops are how a
schema-constrained agent becomes an infinite loop. One retry with the exact
validation error appended to the transcript is the maximum that earns its
cost; failure is an explicit
StopReason::Error, not a silent pass-through. - Reuse
tools::validate_arguments. There is exactly one JSON Schema validator in this service, and it is the subset engine the tool gateway uses. A second validator would drift from it. - Validation happens on the final iteration only. Intermediate iterations produce tool calls, not the deliverable; validating them would fail correctly formed tool-calling responses.
- The parsed object is what the transcript stores when the schema is present, so a downstream consumer reads structured data rather than a string to re-parse.
4.9 Data residency per provider
A provider row declares where inference physically happens; a request declares what it is allowed to accept. The decision is Shield's, not a handler's.
| Column | Table | Meaning |
|---|---|---|
region | ai.providers | Physical region the provider endpoint serves (eu, us, uk, ca) |
in_region_only | ai.residency_rates | The provider will not serve a request whose data must stay in its region |
allowed_regions | ai.agent_policies | Regions this agent's prompts may be routed to; empty = no constraint |
Decisions and their reasons.
- Residency is a policy attribute, not an
ifinturn.rs. The platform law is that authorization is Shield's and roles/scopes are resolved live (principles §5.2). A residency check written inline in the service would be unauditable, untunable by a tenant, and invisible to the policy admin surface. - The fallback chain obeys the same gate.
route_for_envresolves a fallback provider; a fallback that crosses a border is a silent violation of the primary's constraint, and it is the most likely place for this rule to be broken. The gate runs per resolved route, not once per request. - Fail closed. A provider with no
regionis treated as unable to satisfy a constrained policy. Missing data must not widen an obligation. - Memory inherits the constraint (§4.11): retrieval filters on the row's origin region, so a residency-scoped agent cannot be handed content that originated outside its permitted set.
Endpoint. PUT /v1/providers/{provider} gains region; the value is
validated against a closed set so a typo cannot silently create a new
jurisdiction.
4.10 Evaluation as a practice, not a demo
ai.evaluations scores cases by exact match or substring containment. That is
sufficient to prove a prompt runs and insufficient to decide whether a prompt
change is safe to ship.
Two additions, both reusing the inference plane:
(a) Judge metrics. A metric is a rubric prompt evaluated by a model:
ai.eval_metrics(env_id, name, kind, rubric, model, threshold)
kind = 'judge' | 'exact' | 'contains' | 'regex' | 'trajectory'
A judge metric runs run_inference with the rubric and the case, and returns
{score, reason}. Because it is an ordinary inference call it inherits
budgets, traces, moderation, and the residency gate - none of which a
Python-side evaluator would honour.
trajectory metrics score the path, not the answer: the ordered list of
ai.tool_calls for the run. This is what makes an agent change reviewable -
"it still answers correctly" is weaker than "it still calls the same tools in a
sane order".
(b) Regression baseline and promotion gate.
ai.eval_baselinesstores one row per (prompt, version, metric).POST /v1/prompts/{name}/{version}/promotecompares the candidate's score against the baseline and refuses when the delta is worse than the policy'seval_regression_tolerance.- A prompt version with no baseline cannot be promoted; it must be evaluated first.
Decisions and their reasons.
- The judge lives in the service, not in an external harness. An external evaluator
that calls the provider directly would bypass budgets, residency, and
moderation - the three things that make AI spend and data handling
governable.
run_inferenceis the only sanctioned path to a model. - promptfoo and DeepEval are used as CI drivers, not as runtime. Both can
target an HTTP endpoint. Pointing promptfoo at
/v1/chatwith atests:file gives red-teaming and model comparison without embedding an external evaluation stack inside the service. The system of record staysai.evaluations. - Exact match is retained for deterministic prompts (classification, extraction). Judge scoring is not a replacement for a case that has one correct answer.
4.11 Long-term memory
A conversation summariser exists (jobs::spawn_summary_consumer); recall
across conversations does not. Memory is the difference between an assistant
that remembers you and one that meets you again every session.
Implementation. jobs::spawn_memory_consumer subscribes to the ai
stream family as the sentin8-ai-memory consumer group; the trigger is
declared in the registration (event_triggers), so enroll provisions it.
memory_consumer::extract_for_run does the work: it reads the agent policy
(memory_enabled, memory_retention_days), loads the run's user turns
(extracting from our own assistant text would confirm a hallucination into
memory), calls the same ProviderRouter a turn uses so extraction inherits
budgets, moderation, and the residency gate, then admits candidates through
memory_consumer::admit and inserts them under
ON CONFLICT (env_id, owner_sub, agent_id, kind, content) DO NOTHING so a
replayed event is a no-op. expires_at is stamped from
memory_retention_days; the extraction rubric (EXTRACTION_RUBRIC) is fixed
wording and states that the transcript is data, not instructions.
Decisions and their reasons.
- Write is event-driven, read is synchronous and local. Extraction runs on
run:completedthrough the Bus (AGENTS.md rule 3: an event can carry this work). Retrieval is a local query in the existing context-assembly transaction - a handler may not call out to answer. - Memory is holder-scoped, not env-scoped. A memory belongs to a subject,
under the same
owner_subrule as conversations. An env admin may read for support (context-stamped flag); a peer may not. - Provenance is recorded.
source_run_idmakes a memory explicable ("this is why the agent believed that") and removable when a run is purged. - Residency is a retrieval predicate. The row carries
region; retrieval filters on it. Memory is exactly the capability that would otherwise smuggle data across a border that §4.9 just closed. - Extraction must not be a second injection vector. The extractor's input is a summary that has already been moderated; its output is text, not instructions, and it enters the transcript as a labelled memory block, never as a system instruction.
- Bounded by policy.
ai.agent_policiesgainsmemory_enabledandmemory_retention_days; a disabled agent neither writes nor reads memory.
4.12 Multi-agent composition
An agent delegating to another agent is the expected enterprise shape. The platform expresses it in two places, deliberately distinct:
(a) Internal composition uses sentin8:flow. A sub-agent invocation is a
flow step kind agent_turn:
{ "kind": "agent_turn", "agent_name": "researcher", "input": "$.task",
"output": "$.research", "budget_ref": "$.budget" }
The step calls POST /v1/conversations/{id}/turns on this service. Consequences
that make this the right shape:
- One transcript owner per conversation; no nested-loop ambiguity.
- The parent's budget tree includes the child's spend because the child is an ordinary turn against the same budget.
- Flow already owns retries, step state, and the proxy-back contract.
(b) A2A is the external facade. Another organisation's agent is an opaque peer, not a flow step. That is a protocol boundary, and the platform's A2A surface is specified separately (§4.13).
What is explicitly rejected: a bespoke multi-agent DSL with its own planner. The platform already has a durable step engine with retries, and a second orchestration model would fork the failure semantics that Flow, Cron, and Func share.
4.13 Agent interop (A2A)
An A2A facade lets an external agent discover this platform's agents, send them tasks, and stream results. It is a projection of the run model, not a second engine:
| A2A concept | Existing primitive |
|---|---|
AgentCard (skills, capabilities, security) | ai.agents + policy + provider capabilities |
Task | ai.runs |
TaskState | StopReason |
Message.parts[] | ai.messages |
Artifact | tool results / Storage objects |
contextId | conversation_id |
TASK_STATE_INPUT_REQUIRED | AwaitingApproval |
TASK_STATE_AUTH_REQUIRED | approval pending |
securitySchemes.mtls | the platform workload certificate |
Scope of the facade. The HTTP+JSON binding only: POST /message:send,
POST /message:stream, GET /tasks/{id}, POST /tasks/{id}:cancel,
GET /.well-known/agent-card.json. gRPC is deliberately not offered: it
duplicates the surface for no capability this platform needs.
Decisions and their reasons.
- The Agent Card is generated, never hand-written. It is derived from the agent row, its bound tools, and the provider's declared capabilities, so it cannot drift from what the agent actually does. A card that advertises a skill the agent cannot perform is worse than no card.
- Signing uses
sentin8:sign. A2A allows JWS over a canonicalised card (RFC 8785). The platform already owns a signing service with ML-DSA-65; a hand-rolled signature would be the one place the platform's post-quantum posture lapsed. TASK_STATE_AUTH_REQUIREDmaps to the existing approval gate. This is the strongest mapping in the table: human oversight is enforced at runtime, so an external peer sees a real pause with a real approver, not a status string.- A2A traffic is a first-class authorized principal. An external agent
presents a workload certificate; it is authorized by Shield like any other
caller, and its tool calls land in
ai.tool_callswith its identity. This is the platform's differentiator expressed on a standard wire protocol.
5. Cross-Cutting Concerns
- Auth: every route
verify_bearer_token→ Shieldrequire_policy(live roles/scopes from auth); step 5 is the only gate - no handler scope checks. - Tenant resolution:
target_env_idquery REQUIRED on admin/data endpoints (no fallback to token env - rejects with 400). - RLS context: transaction-local
sentin8_set_tenant_contexton the caller's env inside each write transaction; trace insert shares the request's transaction. Every tenant read runs in a tenant transaction too:ai.*tables areFORCE ROW LEVEL SECURITY, so a pool-levelSELECThas nosentin8_current_env_id()and returns zero rows - the list endpoints would answer[]for an env holding data, and route resolution would find no provider. The regression testtenant_reads_require_the_rls_contextpins both halves (context-less read sees nothing, context-scoped read sees the row). - Idempotency:
ai:idem:{env}:{key}(24h TTL) replays full response for retried inference calls; job consumers dedupe onjob_id. A turn is idempotent on the caller-suppliedturn_id(a partial unique index on(conversation_id, turn_id) WHERE role='user'): a retried turn returns the stored assistant message instead of appending a second one. - Turn serialisation is structural:
ai.runscarriesUNIQUE (conversation_id, turn), so a concurrent duplicate turn is rejected by the index (409) rather than by a lock some path forgets to release. There is no advisory lock in the turn path. The number itself is allocated fromMAX(ai.runs.turn) + 1- the authoritative allocator - not fromconversations.turn_count: the counter is a roll-up, and a run that closes early (provider failure, moderation block) must not be able to wedge the conversation on the same number forever. Every exit path rolls the conversation up (ai.ai_conversation_touch) so the counter and the run table stay consistent. That function declaresp_cost numeric, so callers bind a numeric-coercible value (a float bind isdouble precision, which PostgreSQL does not implicitly cast). - The loop runs in SHORT transactions: setup, each provider iteration, each tool dispatch, and the close each commit separately - a crash loses at most the in-flight provider call, never a partial transcript.
- Moderation: input stage before provider call; buffered output stage after; streaming moderation on an accumulated buffer per delta (mid-stream violation aborts with an error frame). Agent turns moderate both directions of every hop: the user message on entry, each assistant message on arrival, and each tool result before it re-enters the transcript - a tool returning injected text is the primary prompt-injection channel in an agent loop.
- Budgets: env-wide
'*'fallback + per-feature caps;reject→ 429,degrade/queue→ cost-labelled traces ({feature}:cost-{mode}). A turn chargesfeature = agent:{agent_name}and the env'*'budget; the check runs before each provider call inside the loop, so a long tool chain cannot overspend a cap it already crossed. - Agent identity: the run executes under the caller's token - the
run records that token's
jti(runs.agent_token_jti) and the audit chain carries the caller's claims (sub,jti,email,env_id). No new token is minted for the agent, so there is nothing extra to leak, expire, or revoke: revoking the caller's token revokes the run's authority on the next request, and one run remains traceable end to end by itsjti. - The model reaches the provider in WIRE form:
ai.prompts.model_primarycarries the registry'sprovider/modelvalue, but the provider is selected from the route registry separately, so the request body must send only the part after the slash - forwardingollama/<model>asks the provider for a model literally named that and fails with 404. This is the same rule/v1/chatfollows. - Audit journaling: agent runs, tool calls, approvals, DLQ writes, and
every inference land in
ai.audit_journal(pushed to the shared audit ingest). A tool call row carriesrun_id,tool_name,arguments_hash,status,approval_by,duration_ms- enough to reconstruct what the agent did without replaying the model. The inference row carries cache provenance -cache: "hit"|"miss"plus the prompt-hash key - so a replay is distinguishable from a fresh generation. - Context assembly is recorded, not implicit:
runs.context_planstores the window boundary, the summary message id (when history was summarised), and the retrieval chunk ids that were injected. Two runs of the same turn over the same history produce the same plan, which is what makes an agent turn reproducible and auditable. - Retention:
ai.agent_policies.retention_daysbounds conversation history; the sweep archives messages beyond the window into Storage and keeps the conversation skeleton (the same archive pattern as traces). - Graceful drain: shell-owned graceful shutdown; relay fail-open. An
in-flight turn finishes or fails with
stop_reason=error; it never leaves a half-written transcript because messages and the run update commit together. - Turn streaming to the client: each iteration emits
sentin8:ai:turn:deltathrough the outbox. The payload is iteration-level (the provider adapter is non-streaming), and it carries the conversation OWNER inuser_idplusrun_id,conversation_id,iteration, akind(delta|tool_call), the content, and the token counts. Delivery is the BFF'sGET /subscribeSSE hop (§4 subscription table in the BFF design). The publisher stampsuser_idbecause the BFF's per-session filter keys on it and its fallback for a missing claim is tenant-wide fan-out: the BFF holds no grant on theaischema, so it cannot resolve the owner itself (owner-first, principles §6.6a), and a frame without the claim is dropped rather than broadcast. Token-level deltas require a streaming adapter method and are a separate change (§10 Open Questions). - Observability: spans mirror the data model rather than inventing a
second one -
ai.conversation.turn(run_id, conversation_id, turn) withai.provider.call(model, tokens, latency) andai.tool.call(tool, side effect, duration) children. Every attribute is already a column inai.runs,ai.traces, andai.tool_calls. Attributes follow the OpenTelemetry GenAI conventions (gen_ai.*) where a name exists and thesentin8.*namespace otherwise. Export is off unlessSENTIN8_OTEL_ENDPOINTis set. - Cost attribution: a run's charge lands in
ai.cost_ledgerin the same transaction that closes the run, priced fromai.price_book. Settlement is a Bus consumer onsentin8:ai:run:completedposting to Bank8:Bill's public API - never a call from a handler, andsettledflips only on acknowledgement so a billing outage does not lose a charge. - Injection defence is layered, and the structural layer is the load-bearing
one: tool results are capped, PII-stripped recursively, and re-enter as
role: "tool"data inside a labelled envelope; a tool result may never grant the run a new tool; the input deny-list is a coarse first filter, not the defence. Red-team suites run in CI against the public endpoint rather than relying on the phrase list. - Regulatory evidence is queryable, not authored.
GET /v1/compliance/ai-act/{env}assembles the Annex-IV view from live rows: intended purpose (agent + prompt), model identity and region (provider), data governance (filters, PII rules), human oversight (policy + approval log), accuracy (evaluations + baselines), logging (audit references). A model card per agent is stored asai.agents.model_cardand is the only hand-authored part.
6. Failure Modes & Recovery
- Valkey down: idempotency + cache degrade to direct execution (best-effort paths never fail the request). The tool rate-limit bucket degrades to process-local counting - a Valkey outage weakens rate limiting, it never blocks tool execution.
- Bus down: outbox relay persists rows in
ai.outbox(5s safety poll); consumer loops retry their connections. - Stat/Flow/Cron/Storage outages: log-only degradations (trace row
still carries spend; a
flow_workflowtool returnserrorwhile the turn continues; cron registration skipped; archive retains hot rows). - Credential loss: secret ref unresolvable → provider disabled at
routing time (422 to caller or
stop_reason=errorinside a turn, no crash loop).
Agent-loop failure paths:
- A failing tool does not fail the turn. The error becomes a tool message so the model can recover, change approach, or explain. The turn fails only when the model cannot continue (provider terminal, guards).
- A denied tool is a model-visible fact, not a silent drop: the model
sees
denied: <reason>and the audit row carries the same reason. A silent drop makes an agent loop look like it succeeded when it did not. - Crash mid-turn: the run row holds
stop_reasonunset and the last committed message seq; the next request resumes context from the last committed seq. Committing messages and the run update in one transaction bounds the loss to the in-flight provider call. - Approval expiry: a pending approval past its deadline transitions to
expiredand the run toerror- an agent never parks forever.
7. Concurrency & Performance Model
- Turns are not background tasks. A turn runs inside its request (bounded by the wall-clock guard), so no unbounded tokio task is spawned per conversation and a crashed instance loses at most one in-flight call.
- One turn per conversation at a time: an advisory lock keyed
(env_id, conversation_id)serialises concurrent turn requests, which is what makesseqassignment andturn_countcorrect under retries. - Tool dispatch is sequential within a turn. Parallel tool execution is deliberately not done: the transcript ordering must stay deterministic and an irreversible tool must not race a read.
- Pool capped (
sentin8_config::pg_pool::connect, max 3 default) - inference trace writes, job upserts and turn commits share the cap; the budget check runs once per provider call inside the loop. - Retrieval
top_kclamped 1-100; archives bounded (LIMIT 10000); trace lists 1-500; DLQ listing 200; message pages 1-200 (default 50). - Hot paths cached: exact-match response cache (1h TTL; the key covers env, model, messages, temperature, max_tokens, and the tool set - hashed to a bounded sha256 prompt-hash, so a near-hit can never replay a response generated under different sampling params) - bypassed for conversation turns, because a dialog key never repeats and a hit would replay a stale answer; embeddings via HNSW; keyword via GIN tsvector.
8. Invariants, Insecure-Defaults Rejected, Unsafe Rationale
- Prompt versions immutable - an update creates a new version; 409 on
duplicate
(env_id, name, version);origin platformrows are enroll-owned,tenantrows never touched by enroll. target_env_idREQUIRED on data endpoints - no silent fallback to the token env (cross-tenant read guard).- Credential references only - provider keys never stored in
ai.providers; resolution order: Secrets ref → env backend. - Filters run both directions (input + output) with a persistent PII deny-list; output moderation cannot be skipped by model_override.
- Budget checks precede provider spend - a rejected request never reaches a provider.
- DLQ replay is manual - failed jobs never auto-retry past the consumer redelivery; malformed payloads are acked (poison-pill guard).
- Traces insert in the same transaction as the response decision - a trace row exists for every completed or failed inference.
- No
unsafeblocks in the service. - The model never executes. It emits tool calls; the gateway validates the arguments, checks the scope, applies the confirmation class, and only then dispatches. There is no code path from model output to execution that skips the gateway.
- Conversation history lives only in AI. No Func module, Flow workflow, or client holds authoritative transcript state; each addresses a conversation by id. History is therefore bounded, auditable, and tenant-deletable in one place.
- Every loop is bounded and the bound is recorded -
max_turns, token + cost budget, wall-clock deadline. A turn always terminates with a stop reason from the closed set. - No tool executes on an unvalidated argument set, and every executed
call carries
arguments_hashin audit. - Tool authority is the caller's, never AI's: the per-run agent token carries the owner and the act chain, and Shield evaluates it. AI holds no scope that a tool target honours on its own behalf.
- A tool result is re-moderated before it enters the transcript - tool output is untrusted model input and is the primary injection channel.
- Turns bypass the exact-match cache; prompt-only inference keeps it.
- Provider credentials are references, never material. The production
form is
secrets://ai/<name>, decrypted per use over the AI workload certificate. A missingsentin8:secrets:secret:readgrant is a hard unconfigured state (422 naming the env), never a silent fallback to an env var or a file.
9. Testing Strategy
tests/integration.rs: adapters (openai/anthropic/ollama/vllm mock round-trips including tool-call responses), error taxonomy (429 transient, 401 terminal), retry + fallback routing, DB RLS isolation, version immutability, filter load per env, chunk persistence, credential-ref resolution, registration identity/scopes, policy boot.- Agent suite (same file, DB-gated): a multi-iteration turn against a
scripted mock provider (model calls a tool, receives the result, answers);
each guard tripping to its expected stop reason; schema-invalid arguments
denied without dispatch; out-of-scope tool denied;
irreversibletool pausing then resuming on approval;turn_idreplay returning the stored message; conversation visibility isolation between two users in one env. tests/live_provider.rs(opt-in, real provider): the only layer that answers "does an agent work on this fleet". It spans four layers that are each tested separately and were never tested together - theai.providersrow, thecredential_refresolution, the adapter's wire shape, and the request the turn loop builds. Gated onSENTIN8_AI_LIVE_PROVIDER=1and bounded to 16max_tokens, so a plaincargo teststays green and offline. The credential is resolved through the service's own resolver, never by reading the file in the test: re-implementing thefile:///env:///secrets://chain would let a ref-format regression pass the test and fail in production.- Deliberately not unit-tested: provider HTTP correctness (mocked), Stat emission, cron registration (e2e/platform layer), real model quality (that is the evaluations surface).
9.1 Providing a real model (operator path)
Three pieces make a live agent work; each fails with a different, misleading symptom when missing.
-
The credential. Store the provider key in a file outside any tracked tree, mode
0600:mkdir -p <tree>/.run/secrets/aiprintf '%s' '<key>' > <tree>/.run/secrets/ai/ollama-cloud.keychmod 600 <tree>/.run/secrets/ai/ollama-cloud.keyA trailing newline is the most common mistake: the resolver returns the bytes verbatim, so the adapter sends
Authorization: Bearer <key>\nand the provider answers 401 with no useful message. The live test asserts this directly rather than leaving it to a support ticket. -
The provider row.
base_urlis the OpenAI-compatible endpoint (Ollama Cloud:https://ollama.com), andcredential_refisfile://<abs path>for a single-host deployment orsecrets://<name>in production:INSERT INTO ai.providers (provider, base_url, credential_ref, models, status, env_id)VALUES ('ollama', 'https://ollama.com','file:///<tree>/.run/secrets/ai/ollama-cloud.key','["deepseek-v4.1-flash"]', 'active','00000000-0000-0000-0000-000000000002')ON CONFLICT (env_id, provider) DO UPDATESET base_url = EXCLUDED.base_url,credential_ref = EXCLUDED.credential_ref,models = EXCLUDED.models,status = 'active';Routes resolve per request with a cache (
provider_routes::resolve), and the platform env (sys/ops) is the fallback for every tenant, so this one row serves the whole fleet until a tenant registers its own. -
The agent's three rows. A prompt pins the model in registry form (
provider/wire-model), a policy must ALLOW that same string, and an agent binds the two. A mismatch is the "agent exists but every turn 422s" class: the policy check and the route lookup fail differently, and neither message names the disagreement. The live test's assembly check reads all three rows through one join so the disagreement surfaces before a turn is attempted.
file:// is deliberately preferred over an environment variable for a
single-host deployment: provider env vars pass through captain's allowlist
(catalog.rs), which is a security boundary that should not be widened for a
credential. secrets:// remains the production path (cert-bound
sentin8:secrets:secret:read on the ai workload).
10. Open Questions
- SSE transport for
POST /v1/chat/streamis already aligned: the transport rule (principles §4.7a) governs, not a per-endpoint choice. - Token-accurate streaming accounting adopts the approximation the normalization already performs (estimate from the terminal frame).
- Embedding model versioning is live (AI-2):
ai.embeddings.model_versionstamps every write with the registry-active version (ai_version_for); the Cronmodel_migrationsweep (POST /v1/internal/schedules/run) re-enqueues jobs for rows trailing the registry - the dual-read discriminator. Per-model DIMENSIONS remain a pgvector-typmod concern: changing the pinned dimension is a greenfield re-init (the registry row- version sweep govern which rows are current).
- Context compression strategy is deliberately coarse: a conversation
beyond the model window is summarised once at a recorded boundary rather
than continuously re-summarised. Token-exact budgeting per model family
is deferred; the guard uses provider-reported usage where available and
the existing char/4 estimate otherwise (
usage_estimatedflags it). - Parallel tool execution is not implemented. If a concrete workload needs it, it must arrive with a deterministic transcript ordering rule (a batch id per assistant message) rather than ad-hoc concurrency.
- Multi-agent orchestration (an agent delegating to another agent) is
out of scope here: it composes as a tool of kind
flow_workflowwhose logic callsPOST /v1/conversations/{id}/turns, which keeps one transcript owner per conversation and avoids nested-loop guard ambiguity. If that proves insufficient, the design change is an explicitsub_agenttool kind with a shared budget tree - not a new execution engine. The flow step kindagent_turn(§4.12) is the concrete form; the A2A facade (§4.13) is the cross-organisation boundary. Neither adds an execution engine. - Model routing per turn (cheap model for tool selection, strong model
for synthesis) is expressible today as a per-prompt
model_primaryon different prompts; a first-class per-iteration routing policy is deferred until a tenant asks for it. - Token-level streaming on the agent path. The turn event is
iteration-level because
CompletionProvider::completeis buffered. Real token deltas needcomplete_stream()returning a chunk stream, wired for the final iteration only (tool-calling iterations still need the complete response to parsetool_calls). Deferred until the BFF SSE hop ships and a client needs the latency improvement; the iteration-level event is sufficient for progress and approvals. - MCP
stdiotransport for tenant servers is deliberately unsupported (§4.7): it is arbitrary process execution inside a platform service. If a tenant needs a local server, the shape is a platform-internal module, not a tenant registration. - A2A gRPC binding is not offered (§4.13). HTTP+JSON covers the capability; a second binding doubles the conformance surface without adding behaviour.
- Memory consolidation across kinds (merging a preference into a fact, or superseding a contradicted memory) is deferred. The first version inserts and retrieves with similarity dedupe; a contradiction-resolution policy needs a real corpus to tune against.
Architecture & Design: sentin8:ai and its underlying concepts were designed by Hamid Jahanzad.