Three things, all from running the real thing rather than trusting a status code.
1. OpenCode as a 4th AI class (lib/ai/opencode.ts + app/api/ai/opencode/*).
A locally-running `opencode serve` — the same runtime Paperclip drives as
an adapter. Its appeal over a BYOK profile is precisely what was broken
before: opencode owns provider auth itself, so there is NO api key for
this app to hold, and it reports a REAL model list (25 on this machine)
instead of asking the user to type an exact provider-specific model id
from memory. Typing "Sonnet 5" into a free-text box and getting a bare
"Provider returned 401" is the failure this removes.
IMPORTANT trap, documented in the module header and pinned by a test:
opencode is NOT OpenAI-compatible. `/v1/models` and `/v1/chat/completions`
both answer 200 — because a web-UI catch-all serves index.html for ANY
unknown path. I built the first version against that assumed compatibility
on the strength of two 200s and had to throw it away once I read a body.
Every probe now validates the parsed shape and content-type, never the
status alone. The real API is GET /api/model + POST /session +
POST /session/{id}/message, and the reply's `reasoning` parts are stripped
so a model's private chain of thought can never surface as the answer.
Proxied through our own backend (like the `server` class) because the
desktop renderer's origin is a random port that changes every launch;
same-origin sidesteps opencode's CORS allowlist entirely. Loopback-only by
construction: a non-loopback OPENCODE_BASE_URL is refused, since "local,
no keys, nothing leaves the device" is the whole point of this class.
2. Retrieval read the WRONG ACCOUNT'S index. The indexer writes under the
active account's cookie slot (catchUpIndex passes it) but fetchLocalLeg
omitted `?slot=`, so search resolved to whichever account the multi-slot
resolver found first. Single-account installs never noticed; a real
multi-account/shared-mailbox setup reads an empty store every time. Both
call sites now pass the active slot.
3. "No local mail index available in this session" was shown even when the
index existed and simply matched nothing — actively misleading, and it
masked the missing-SESSION_SECRET bug for hours. AskResult now carries
retrievalState ('augmented' | 'no-match' | 'no-index') and the two cases
get different words: build the index, versus rephrase (with the honest
caveat that keyword search answers content questions better than recency
ones like "the last mail").
Verified live against real opencode 1.18.14: discovery found 25 models and a
real prompt round-tripped the exact expected answer through the real helper
code, not curl. Gate: tsc clean, eslint clean, 2512/2512 unit tests (10 new,
incl. one that fails if the HTML catch-all is ever accepted as an API), build clean.
56 lines
2.8 KiB
TypeScript
56 lines
2.8 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { configManager } from '@/lib/admin/config-manager';
|
|
import { logger } from '@/lib/logger';
|
|
import { DEFAULT_AI_ENTITLEMENT, type AiPolicy } from '@/lib/ai/types';
|
|
|
|
/**
|
|
* GET /api/ai/policy - AI Assistant policy (NOT admin-protected - users read this)
|
|
*
|
|
* `enabled` mirrors the admin FeatureGates toggle. `entitlement.classes`
|
|
* reflects real configuration, not a hardcoded guess: `server` only appears
|
|
* when AI_SERVER_BASE_URL is actually set (app/api/ai/server/* would 503
|
|
* otherwise) - this is enforcement point 1 (docs §10), cosmetic-only, the
|
|
* client hiding what it can't use; the real gate is checkAndAssignSeat() on
|
|
* every /api/ai/server/chat call, not this list.
|
|
*/
|
|
export async function GET() {
|
|
try {
|
|
await configManager.ensureLoaded();
|
|
const policy = configManager.getPolicy();
|
|
const consoleConfig = configManager.getAiConsoleConfig();
|
|
|
|
// A class must be BOTH infra-available AND not explicitly disabled by
|
|
// the admin console (docs/ADMIN-AI-POLICY-CONSOLE-SPEC.md §6) to reach
|
|
// users. Missing classesEnabled entries default to allowed, so this
|
|
// changes nothing until an admin actually touches the console.
|
|
const classAllowed = (cls: (typeof DEFAULT_AI_ENTITLEMENT.classes)[number]) => consoleConfig.classesEnabled[cls] !== false;
|
|
const classes: typeof DEFAULT_AI_ENTITLEMENT.classes = [];
|
|
if (classAllowed('local')) classes.push('local');
|
|
if (classAllowed('public')) classes.push('public');
|
|
if (process.env.AI_SERVER_BASE_URL && classAllowed('server')) classes.push('server');
|
|
// `opencode` is offered whenever the admin hasn't disabled it — unlike
|
|
// `server` there is no env var to gate on, because availability is "is a
|
|
// local `opencode serve` listening right now", which changes minute to
|
|
// minute and is answered by /api/ai/opencode/models (503 when absent).
|
|
// Advertising the class and letting that probe report the truth beats
|
|
// hiding it based on a stale check at policy-fetch time.
|
|
if (classAllowed('opencode')) classes.push('opencode');
|
|
|
|
const aiPolicy: AiPolicy = {
|
|
enabled: policy.features.aiAssistantEnabled,
|
|
entitlement: { ...DEFAULT_AI_ENTITLEMENT, classes },
|
|
publicConsentVersion: consoleConfig.consent?.version ?? null,
|
|
retrievalEnabled: consoleConfig.retrievalEnabled,
|
|
consent: consoleConfig.consent,
|
|
publicProviderAllowlist: consoleConfig.publicProviderAllowlist,
|
|
};
|
|
|
|
return NextResponse.json(aiPolicy, {
|
|
headers: { 'Cache-Control': 'no-store' },
|
|
});
|
|
} catch (error) {
|
|
logger.error('AI policy read error', { error: error instanceof Error ? error.message : 'Unknown error' });
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|