feat(ai): capability loader, gates and refusal envelope

loadAiCapabilityInputs reads the switches, module access, provider
presence and active consent kinds for one record in parallel, memoised
per request, and fails closed to check_failed. requireAiCapability,
getAiCapability and aiCapabilityForJob resolve for the request's
record, masked to the active grant like moduleAccess, or for a job's
record under the worker's authority.

apiHandler renders AiUnavailableError as one envelope with errorCode,
capability, reason and module. Existing codes stay: the operator
family keeps assistant.disabled.<switch>, modules keep module.disabled,
consent keeps consent.ai.required. New codes are ai.record.notPermitted,
ai.provider.none and ai.unavailable.
This commit is contained in:
Marc-André Bombeck committed 2026-09-24 07:46:12 +02:00
1 parent 1be2392c81
commit 7c757520f1
8 files changed
+873 -28

No files matched your search

+13 -1
View File
@@ -27,6 +27,7 @@ import {
type ActingCarrier,
} from "./auth/acting-carrier";
import { AssistantDisabledError } from "./feature-flags";
import { AiUnavailableError } from "./ai/capabilities/refusal";
import { ConsentRequiredError } from "./ai/consent-guard";
import { SCOPE_HEALTH_READ, SCOPE_HEALTH_WRITE } from "./mcp/oauth/config";
import {
@@ -234,7 +235,18 @@ export function apiHandler<T extends (...args: any[]) => Promise<Response>>(
try {
response = await handler(...args);
} catch (error) {
if (error instanceof AssistantDisabledError) {
if (error instanceof AiUnavailableError) {
// An AI capability is unavailable for this record. One envelope
// for every reason, keeping every code a shipped client already
// branches on: `meta.errorCode` plus the `capability` and the
// outermost `reason`, and `module` where the reason is about one.
// See `src/lib/ai/capabilities/gate.ts` for the table.
evt.setError(error);
response = NextResponse.json(
{ data: null, error: error.message, meta: error.meta },
{ status: error.status },
);
} else if (error instanceof AssistantDisabledError) {
// v1.4.31 — operator has disabled the assistant surface.
// The 403 + `errorCode: "assistant.disabled.<surface>"`
// envelope is locked per