Per-district tenant + cost-cap
Composing educationAgent per-district with hard cost ceilings enforced at the gateway boundary via @pleach/gateway/swarm's CostCeilingMiddleware, plus audit ledger scoping by districtTenantId via @pleach/compliance/audit.
K-12 buyers expect three controls before they sign:
- Tenancy: district A's transcripts and spend never touch district B's, even on a shared runtime.
- A hard per-session spend ceiling, enforced before the model call.
- An audit trail scoped to one district for end-of-year review.
This page shows how to compose them today.
The recipe-layer split
educationAgent.ask() does NOT enforce the cost ceiling. The factory registers a
CostCapPolicy on the runtime via the EDUCATION_RUNTIME_TAG symbol. Your
gateway or accounting layer is the enforcement point, because the gateway sees
per-call USD cost and the recipe doesn't.
Per-district runtime construction
Construct one educationAgent per district. The factory is cheap and keeps no shared global state.
import { educationAgent } from "@pleach/recipes/education";
function buildDistrictAgent(districtTenantId: string) {
return educationAgent({
districtId: districtTenantId,
complianceProfile: "ferpa+coppa",
contentSafety: ["self-harm", "profanity"],
costCapUsdPerSession: 0.25,
perDistrictMonthlyBudgetUsd: 1500,
});
}
// In your request handler:
const bot = buildDistrictAgent(req.tenantId);
const reply = await bot.ask(req.body.message);The districtId is stamped on the runtime tag. Read it for per-district scoping in your audit ledger, gateway aggregator, and billing pipeline.
Cost-cap enforcement at the gateway boundary
@pleach/gateway/swarm ships CostCeilingMiddleware — a
pre-call guard that wraps any routing call and throws
CostCeilingExceededError before transport if the per-root-turn
ceiling is already breached.
import {
createCostCeilingMiddleware,
createRootTurnCostAggregator,
} from "@pleach/gateway/swarm";
const aggregator = createRootTurnCostAggregator();
const middleware = createCostCeilingMiddleware({
aggregator,
maxCostUsdPerRootTurn: 0.25, // matches educationAgent's cap
warnCostUsdPerRootTurn: 0.15,
onBreach: async (event) => {
await auditLedger.recordBreach({
tenantId: event.tenantId,
rootTurnId: event.rootTurnId,
severity: event.severity, // "warn" | "breach"
spentUsd: event.accumulatedUsd,
ceilingUsd: event.ceilingUsd,
});
},
});
// Wrap every routing call:
const result = await middleware.guard({
rootTurnId: req.rootTurnId,
invoke: () => gatewayClient.route(routingInput),
});The middleware enforces the ceiling at the routing-call boundary. The aggregator
sums spend across every sub-agent under one rootTurnId, so a swarm fan-out
can't escape the ceiling by spawning more children.
For the per-root-turn-cap primitive itself (independent of the
gateway middleware), see
createRootTurnCostCapPolicy from @pleach/core/spawn:
import { createRootTurnCostCapPolicy } from "@pleach/core/spawn";
const policy = createRootTurnCostCapPolicy({
ceilingUsd: 25,
onBreach: async ({ rootTurnId, spentUsd }) => {
await notifyOperator({ rootTurnId, spentUsd, action: "swarm-paused" });
},
});
if (!policy.canSpend(rootTurnId, projectedCostUsd)) {
throw new Error("root-turn cost-cap reached");
}
await policy.recordSpend(rootTurnId, actualCostUsd);The gateway middleware composes this primitive. Use it directly when you enforce the cap outside @pleach/gateway.
Per-session vs per-root-turn: which to use
| Scope | Primitive | Source | When to use |
|---|---|---|---|
| Per chat session | createCostCapPolicy | @pleach/compliance/education | One student, one tutoring session, no sub-agent fan-out. |
| Per root user turn | createRootTurnCostCapPolicy | @pleach/core/spawn | Sub-agent swarms; one user turn can fan out into many child calls. |
| Per gateway call | createCostCeilingMiddleware | @pleach/gateway/swarm | Production — the pre-call guard that actually rejects before transport. |
educationAgent registers the per-session policy by default
(costCapUsdPerSession, default $0.50). Layer the per-root-turn
cap on top when one user turn fans out into sub-agents.
Driving the per-session cap from your turn gate
The per-session CostCapPolicy is registered on the runtime
tag — read it via the EDUCATION_RUNTIME_TAG symbol and drive
it from your per-turn gate:
import { EDUCATION_RUNTIME_TAG } from "@pleach/recipes/education";
const bot = educationAgent({
districtId: "district-1234",
costCapUsdPerSession: 0.25,
});
const tag = (bot.runtime as unknown as Record<symbol, any>)[
EDUCATION_RUNTIME_TAG
];
// In your per-turn handler:
const projectedCostUsd = estimateTurnCost(message); // your projector
if (!tag.costCap.canSpend(sessionId, projectedCostUsd)) {
throw new Error("classroom session cost-cap reached");
}
const reply = await bot.ask(message);
// After the model returns, record the actual cost:
await tag.costCap.recordSpend(sessionId, actualCostUsd);The policy is in-memory and single-process, so it's lossy across restarts. For
production, implement the same CostCapPolicy interface (canSpend,
recordSpend, spentFor, reset) against your tenant database.
Per-district monthly budget
perDistrictMonthlyBudgetUsd is recorded only. The substrate
does NOT enforce a monthly kill-switch today. Two workable paths:
- Roll it up in your billing pipeline — query the audit ledger
by
tenantId = districtIdat month-roll and disable the district's API token at your application layer. - Compose a second
CostCeilingMiddlewarewith aRootTurnCostAggregatorscoped to month-bucket keys (rootTurnId: ${districtId}-${yyyymm}). Hackier but stays inside the gateway layer.
A first-class monthly budget primitive isn't available yet.
Audit ledger scoped by districtTenantId
@pleach/compliance/audit exposes a vendor-neutral
queryAudit() projector that pulls a filtered slice of audit
rows from any storage backend that satisfies AuditStoreLike:
import { queryAudit, exportAuditPdf } from "@pleach/compliance/audit";
const result = await queryAudit({
store, // your AuditStoreLike (Postgres / Supabase / SQLite / in-memory)
tenantId: "district-1234", // scope to one district
from: "2026-01-01T00:00:00Z",
to: "2026-02-01T00:00:00Z",
limit: 1000,
});
if (!result.chainValid) {
throw new Error("Audit log tampered with — chain broken.");
}
// Render to a single-file PDF for distribution to district counsel:
const pdfBuffer = await exportAuditPdf({
rows: result.rows,
metadata: {
tenantId: "district-1234",
framework: "FERPA+COPPA (mapped to GDPR bundle)",
title: "District 1234 — January 2026 AI Tutor audit",
from: "2026-01-01T00:00:00Z",
to: "2026-02-01T00:00:00Z",
chainValid: result.chainValid,
notes: "Substitution: requested ferpa+coppa, applied gdpr bundle.",
},
format: "letter",
});The PDF carries the tenant, framework, time range, a chain-validity badge, and a per-row table.
pdfkit is an optional peer. Without it, exportAuditPdf throws MissingOptionalPeerError("pdfkit"). Install it, or fall back to JSON or Markdown via produceAuditReport().
result.chainValid tells a district auditor whether rows in the projection were changed.
Where to import
- The education recipe:
@pleach/recipes/education. createRootTurnCostCapPolicy:@pleach/core/spawn.- The cost-ceiling middleware:
@pleach/gateway/swarm. - Audit query and PDF export:
@pleach/compliance/auditand@pleach/compliance/audit/exportPdf.
See also
- Education — the landing page.
- FERPA / COPPA scope — what the compliance substitution does and doesn't cover.
- Audit ledger — the underlying hash-chained event log.
@pleach/gateway— the routing layer where the cost ceiling lives.- Multi-tenant SaaS agent — the generic multi-tenant shape; districts are one instance of it.
- Subagents — when one user turn fans out into many child calls.
FERPA / COPPA scope
What @pleach/compliance covers for FERPA and COPPA, which profile the educationAgent factory applies when you ask for those strings, and the controls your deployment provides.
Worked example: a district privacy request
The steps a tutoring vendor runs when a district privacy officer asks for one student's agent interactions, evidence of redaction before storage, and proof the records weren't altered, and where the district's and vendor's own duties take over.