mirror of
https://github.com/OpenSquawk/OpenSquawk
synced 2026-08-13 21:25:42 +08:00
Phase 0 of the OpenSquawk repo separation. Everything happens inside the
monorepo so that the split itself becomes a mechanical path filter — filtering
first and repairing afterwards would leave two broken repos at once.
AUTH_MODE (0.1)
New server/utils/authMode.ts, session.ts and jwt.ts (the latter extracted
from auth.ts). requireUserSession now resolves in three steps: the app's own
session cookie, an app-minted bearer token, then the website access token.
Only the last one is transitional; it is marked PHASE 1 and disappears with
the User collection. The app's session is its own JWT in a host-only cookie
plus a short-lived bearer, so the existing Authorization call sites are
unchanged.
AUTH_MODE defaults to 'sso', not 'open' as the plan proposed: while the admin
and editor surface still lives here, an unset variable would otherwise serve
it to everyone as a local admin. requireAdmin additionally refuses in open
mode. Both are one-line removals in Phase 1 and marked as such.
SSO handoff (0.2)
Issuer: /api/service/auth/sso/{authorize,exchange}. Codes are stored as
SHA-256 hashes with a TTL index and claimed by a single atomic update, so
concurrent redemption cannot succeed twice. redirect_uri is matched against
SSO_REDIRECT_ORIGINS by exact origin — a prefix check would accept
app.opensquawk.de.evil.tld. There is no default and no wildcard: an empty
allowlist disables the handoff rather than opening a redirector.
Consumer: /api/auth/sso/callback plus app/pages/auth/callback.vue. The
browser only ever carries the code; it is redeemed server-to-server.
Hardcoded values and leaks (0.3)
Hotjar ID, the dome-light webhook URL and the bug-report recipient were
compiled in. All three are env-gated and off by default now, so a foreign
instance cannot ship analytics, cockpit telemetry or its users' bug reports
to us. Setting HOTJAR_ID, DOME_LIGHT_WEBHOOK_URL and BUG_REPORT_NOTIFY_EMAIL
restores the current behaviour on opensquawk.de.
Two databases, no shared Mongo (0.6)
AppUser mirrors an identity locally. Its _id is deliberately the SSO subject,
i.e. the website's User._id, so every existing LearnProfile, PilotProfile and
BridgeToken reference keeps resolving without a migration.
telemetry.ts mirrors records to the hosted service only when TELEMETRY_URL
and SERVICE_SECRET are both set — the self-host default is that nothing ever
leaves the instance. It writes locally first, buffers with a bound, drops on
overflow and never blocks the request path.
/api/service/user-deleted purges the app's half on account deletion. Unlike
telemetry this is deliberately loud: the admin delete aborts with the user
intact if the purge fails, because their id is the only handle for retrying.
?force=true overrides it and says so in the response.
Also here
/api/service/analytics/product-session was an unauthenticated public write
endpoint; it moves to /api/analytics/product-session behind the auth guard.
The bridge no longer populates against User but resolves through the mirror,
backfilling missing rows so live bridges never have to re-pair.
.claude/worktrees was tracked and would have reached the public repo.
scripts/split-paths.txt carries the filter list, verified by
scripts/verify-split-paths.mjs: every path exists, nothing website-only is
kept, and no kept file imports a dropped one. That check found real gaps —
tests/ cannot be taken wholesale, and two shared modules were missing. Ten
remaining edges are allowlisted, each annotated PHASE 1 in the code.
Open item, flagged and not resolved: flightlabTelemetryStore is an in-process
singleton written by the bridge (app) and read by FlightLab (website). Two
repos means two processes, so that read breaks regardless of which side it
lands on. FlightLab needs an HTTP path in Phase 2/3.
Verified: 609 tests pass, vue-tsc clean. Ran against two throwaway local
MongoDBs: open mode reaches /classroom and /live-atc with no login and
persists progress; the full SSO loop works and the mirror _id matches the
website User._id; lookalike origins, code reuse, forged codes and wrong
service secrets are all rejected; ingest is idempotent on bug-report code;
deletion purges all five collections; and with the app unreachable the admin
delete fails 502 with the user still present.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
181 lines
6.4 KiB
TypeScript
181 lines
6.4 KiB
TypeScript
// server/api/decision/route.post.ts
|
|
//
|
|
// Internal endpoint the Python decision backend calls when regex routing fails
|
|
// to match a pilot transmission. It asks the LLM to pick the best candidate
|
|
// transition for the (often STT-garbled) transcript, records the cost in the
|
|
// central usage ledger, and persists a routing-review record — including
|
|
// timeouts — so the time budget can be tuned against real latency.
|
|
|
|
import { createError, readBody } from 'h3'
|
|
import { getOpenAIClient } from '../../utils/openai'
|
|
import { requireServiceSecret } from '../../utils/serviceAuth'
|
|
import { recordUsage, estimateCostUsd } from '../../utils/usage'
|
|
import {
|
|
LlmRoutingDecision,
|
|
type LlmRoutingCandidate,
|
|
type LlmRoutingStatus,
|
|
} from '../../models/LlmRoutingDecision'
|
|
import { emit as emitTelemetry } from '../../utils/telemetry'
|
|
|
|
interface RouteRequestBody {
|
|
sessionId: string
|
|
flowSlug?: string
|
|
stateId: string
|
|
transcript: string
|
|
expectedPhrase?: string
|
|
candidates: LlmRoutingCandidate[]
|
|
timeoutMs?: number
|
|
}
|
|
|
|
const ROUTER_MODEL = (process.env.ROUTER_LLM_MODEL || 'gpt-5-mini').trim()
|
|
const DEFAULT_TIMEOUT_MS = 10_000
|
|
|
|
const SYSTEM_PROMPT = [
|
|
'You are a routing classifier for an ATC radio-communication trainer.',
|
|
'A pilot transmission was transcribed by speech-to-text and a deterministic regex layer could NOT match it to a next state.',
|
|
'The transcript is frequently garbled by STT errors (split words, wrong numbers, homophones).',
|
|
'Compare the transcript against the expected pilot phrase and choose the single candidate transition whose intent best matches what the pilot most likely said.',
|
|
'Candidates are marked kind="ok" (a correct/expected radio call) or kind="bad" (an incorrect or incomplete call).',
|
|
'Only choose a candidate id from the provided list. If none plausibly matches, choose "none".',
|
|
'Respond with strict JSON only: {"chosen": "<candidate id or none>", "reason": "<one short sentence>"}.',
|
|
].join(' ')
|
|
|
|
function buildUserPrompt(body: RouteRequestBody): string {
|
|
const lines: string[] = []
|
|
lines.push(`Current state: ${body.stateId}${body.flowSlug ? ` (flow ${body.flowSlug})` : ''}`)
|
|
if (body.expectedPhrase) {
|
|
lines.push(`Expected pilot phrase: "${body.expectedPhrase}"`)
|
|
}
|
|
lines.push(`Transcript (from STT): "${body.transcript}"`)
|
|
lines.push('Candidates:')
|
|
for (const c of body.candidates) {
|
|
lines.push(`- id="${c.id}" kind=${c.kind}${c.label ? ` label="${c.label}"` : ''}`)
|
|
}
|
|
return lines.join('\n')
|
|
}
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
requireServiceSecret(event)
|
|
|
|
const body = await readBody<RouteRequestBody>(event)
|
|
if (!body?.transcript || !body?.stateId || !Array.isArray(body?.candidates) || body.candidates.length === 0) {
|
|
throw createError({ statusCode: 400, statusMessage: 'transcript, stateId and candidates[] are required.' })
|
|
}
|
|
|
|
const timeoutMs = Number.isFinite(body.timeoutMs) && (body.timeoutMs as number) > 0
|
|
? (body.timeoutMs as number)
|
|
: DEFAULT_TIMEOUT_MS
|
|
|
|
const candidateIds = new Set(body.candidates.map((c) => c.id))
|
|
const client = getOpenAIClient()
|
|
|
|
let status: LlmRoutingStatus = 'error'
|
|
let chosen: string | null = null
|
|
let reason: string | undefined
|
|
let inputTokens: number | undefined
|
|
let outputTokens: number | undefined
|
|
let costUsd: number | undefined
|
|
|
|
const started = Date.now()
|
|
try {
|
|
const response = await client.chat.completions.create(
|
|
{
|
|
model: ROUTER_MODEL,
|
|
n: 1,
|
|
response_format: { type: 'json_object' },
|
|
messages: [
|
|
{ role: 'system', content: SYSTEM_PROMPT },
|
|
{ role: 'user', content: buildUserPrompt(body) },
|
|
],
|
|
},
|
|
// Per-request budget; no retries so a slow call fails fast within budget.
|
|
{ timeout: timeoutMs, maxRetries: 0 },
|
|
)
|
|
|
|
inputTokens = response.usage?.prompt_tokens
|
|
outputTokens = response.usage?.completion_tokens
|
|
|
|
const raw = response.choices?.[0]?.message?.content?.trim() || ''
|
|
let parsedChosen: string | null = null
|
|
try {
|
|
const parsed = JSON.parse(raw) as { chosen?: string; reason?: string }
|
|
parsedChosen = typeof parsed.chosen === 'string' ? parsed.chosen.trim() : null
|
|
reason = typeof parsed.reason === 'string' ? parsed.reason.trim() : undefined
|
|
} catch {
|
|
reason = `Unparseable model output: ${raw.slice(0, 200)}`
|
|
}
|
|
|
|
if (parsedChosen && candidateIds.has(parsedChosen)) {
|
|
chosen = parsedChosen
|
|
status = 'decided'
|
|
} else if (parsedChosen && parsedChosen.toLowerCase() === 'none') {
|
|
status = 'abstain'
|
|
} else if (parsedChosen) {
|
|
// Model named a state outside the allowed set — never trust it.
|
|
status = 'invalid'
|
|
reason = reason || `Model returned out-of-set candidate "${parsedChosen}"`
|
|
} else {
|
|
status = 'error'
|
|
}
|
|
} catch (err: any) {
|
|
const name = String(err?.name || '')
|
|
const isTimeout = name.includes('Timeout') || err?.code === 'ETIMEDOUT' || name === 'APIConnectionTimeoutError'
|
|
status = isTimeout ? 'timeout' : 'error'
|
|
reason = `${name || 'LLM call failed'}: ${String(err?.message || err).slice(0, 200)}`
|
|
}
|
|
|
|
const latencyMs = Date.now() - started
|
|
|
|
// Cost only when the call actually returned token usage (not on timeout/error).
|
|
if (inputTokens != null || outputTokens != null) {
|
|
costUsd = estimateCostUsd({
|
|
kind: 'llm',
|
|
provider: 'openai',
|
|
model: ROUTER_MODEL,
|
|
endpoint: '/api/decision/route',
|
|
inputTokens,
|
|
outputTokens,
|
|
})
|
|
// Fire-and-forget into the central usage ledger (attributed by sessionId;
|
|
// backend has no user id on the runtime session yet).
|
|
await recordUsage({
|
|
sessionId: body.sessionId,
|
|
kind: 'llm',
|
|
provider: 'openai',
|
|
model: ROUTER_MODEL,
|
|
endpoint: '/api/decision/route',
|
|
inputTokens,
|
|
outputTokens,
|
|
})
|
|
}
|
|
|
|
const decision = {
|
|
sessionId: body.sessionId,
|
|
flowSlug: body.flowSlug,
|
|
stateId: body.stateId,
|
|
transcript: body.transcript,
|
|
expectedPhrase: body.expectedPhrase,
|
|
candidates: body.candidates,
|
|
chosen,
|
|
reason,
|
|
status,
|
|
model: ROUTER_MODEL,
|
|
timeoutMs,
|
|
latencyMs,
|
|
inputTokens,
|
|
outputTokens,
|
|
costUsd,
|
|
}
|
|
|
|
// Always persist the routing-review record locally, including timeouts/errors.
|
|
try {
|
|
await LlmRoutingDecision.create(decision)
|
|
} catch (e) {
|
|
console.warn('[decision/route] persisting routing decision failed', e)
|
|
}
|
|
|
|
emitTelemetry('llm-routing-decision', decision)
|
|
|
|
return { chosen, reason, status, latencyMs, timeoutMs, model: ROUTER_MODEL }
|
|
})
|