Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(model): let users choose where the model runs (#1123)
Beenu Arora21fe39f543a3
diff --git a/.env.example b/.env.exampleindex 517444a19..bdc718ad7 100644--- a/.env.example+++ b/.env.example@@ -464,3 +464,23 @@ AISOC_INTERNAL_TOKEN=# starts the consumer; each tenant must still opt in from its own settings# (PUT /api/v1/retro-hunts/settings), so this switch alone sweeps nobody.RETRO_HUNT_ENABLED=false++# ── Where the model runs ────────────────────────────────────────────────────+#+# `make up` runs the bundled model on CPU and needs none of these. They exist+# for the other three options; see apps/docs/docs/operations/where-the-model-runs.md+#+# make up-gpu bundled model on an NVIDIA GPU (Linux / Windows+WSL2)+# make up-host-llm an Ollama you already run (the only GPU path on a Mac)+# a hosted provider configured per tenant in the console (no variable here)++# How many NVIDIA devices `make up-gpu` exposes. `all` for every device.+AISOC_GPU_COUNT=1++# Where the gateway looks for a model. `make up-host-llm` sets this to the+# host's Ollama; set it yourself to point at another machine or an existing+# vLLM. Left empty here so the bundled service address applies.+AISOC_LLM_API_BASE=++# Where the API's runtime probe asks "GPU or CPU?". Follows the above.+AISOC_OLLAMA_URL=diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex cf6c138c3..22f2535fd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -514,6 +514,20 @@ jobs:# something leaks. The script existed and passed; nothing ran it.- name: Verify vendored redactor is in syncrun: python scripts/sync_vendored_redactor.py --check+ # The SSRF guard, vendored so the API can test a tenant's LLM credential+ # without depending on `services/agents` being in its build context.+ # Drift here is a security failure in a specific direction: the API's own+ # `destinations.py::_guard_url` refuses every private address, which+ # would break the `local-*` providers this endpoint exists to serve, so+ # the copy that permits private *while still blocking link-local* has to+ # stay the one that is actually used.+ - name: Verify vendored SSRF guard is in sync+ run: python scripts/sync_vendored_ssrf_guard.py --check+ # The GPU preflight's own self-test. The real verdict depends on the+ # host, so CI can only assert that the refusals fire and say something+ # actionable -- which is the part that rots, since the advice is prose.+ - name: GPU preflight — self-test+ run: python3 scripts/check_gpu_runtime.py --self-test# Gap-closure Phase 2.2. The sixth mirror, and the one where drift is a# safety failure rather than an inconsistency. These rules decide what a# tenant's track record has to show before the agent may act unattended:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da0c01f24..480a2f0d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,78 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Three ways to run the model, and a wizard step that says which is in+ effect.** `make up` is unchanged: the bundled model on CPU, no account and no+ GPU. Alongside it, `make up-gpu` layers an NVIDIA device reservation onto the+ bundled Ollama, and `make up-host-llm` uses an Ollama already running on the+ host -- which is the **only** way to reach a GPU on Apple Silicon, since+ Docker Desktop cannot pass Metal into a Linux container. Hosted providers+ were already supported and are now reachable from the first-run wizard rather+ than only from Settings.++ The reservation is an overlay and not a line in the base file, deliberately.+ A host without an NVIDIA GPU and the container toolkit cannot start a service+ that reserves one -- the daemon answers `could not select device driver+ "nvidia"` -- so putting it in `docker-compose.yml` would take out `make up`+ for every Mac, every CPU-only Linux box and every CI runner. A test asserts+ the base file reserves no devices, and reintroducing the reservation fails it.++- **`GET /api/v1/llm/runtime` reports where the model actually is.** A+ reservation is a *request*: a model can still land on the CPU for want of+ VRAM or a usable driver, so reading the compose file back would report the+ intent and call it the outcome. This asks Ollama, which publishes `size_vram`+ on `/api/ps`. Five states including **not loaded right now** -- Ollama unloads+ when idle, and answering "CPU" for an idle instance would be a guess about+ the exact thing an operator is deciding on. Verified against the pinned+ `ollama/ollama:0.6.7` image, which reports `size_vram: 0` in a container on+ Apple Silicon, and against a native Ollama on the same host, which reports+ `size_vram == size` because it reaches Metal.++- **`POST /api/v1/llm/credentials/test` places one real call.** The existing+ credential routes validate *shape* and never talk to the provider, so a+ revoked key surfaced as triage quietly falling back to the deterministic path+ -- a failure that is hard to attribute precisely because it is silent. Four+ outcomes, and `unverified` is deliberately not an error: an air-gapped+ deployment refusing the egress is the policy working.++ The call goes through `safe_chat_completions_request`, not a raw POST. The+ prompt is a constant with no untrusted input, so the contract has nothing+ to reject -- but the rule is that *every* call to a completions endpoint+ goes through it, and a call site that argues its way out is how the next+ one, with a real prompt, gets written the same way.+ `test_llm_contract_no_bypass.py` caught the first version.++ It does **not** use `destinations.py::_guard_url`, which refuses every+ private address and would therefore refuse `local-ollama`, `local-vllm` and+ `local-litellm` -- three of the seven providers migration 038 allows, and the+ ones this feature most exists to serve. It uses the agents service's+ `validate_outbound_url(..., allow_private=True)`, vendored and held+ byte-identical by a new sync gate, which permits a private host while still+ rejecting loopback and link-local so cloud metadata stays unreachable.++- **`scripts/check_gpu_runtime.py`**, which `make up-gpu` runs first so the+ failure names a cause. It distinguishes a missing card, driver, toolkit and+ daemon configuration, and on Apple Silicon says plainly that no amount of+ installing will help and points at `make up-host-llm` instead.++### Fixed++- **`make doctor` told operators to stop their own Ollama.** `11434` is in the+ managed port inventory, so a host already running Ollama got a hard failure+ reading *"aisoc ollama needs it"* with the advice to stop it. On a Mac that+ Ollama is the only one with a GPU, so the advice was to switch off the fast+ model in favour of a slow one. It is now a warning that points at+ `make up-host-llm`.++- **An air-gap check could silently stop applying.** The credential probe read+ `settings.AISOC_AIRGAPPED` through a module-level reference, which goes stale+ the moment anything reloads `app.core.config` -- the probe's own test passed+ alone and failed in the full suite for exactly that reason. It now calls+ `enforce_airgap_for_url`, the same function every other outbound call uses,+ which reads the flag at call time.+### Security- **A revoked session kept the graph WebSocket open** ([GHSA-25fh-rxp8-67j8]).diff --git a/Makefile b/Makefileindex 817184414..c34a5007e 100644--- a/Makefile+++ b/Makefile@@ -77,7 +77,7 @@ CONSOLE_URL = $(shell sed -n 's/^AISOC_CONSOLE_URL=//p' .env 2>/dev/null | tailCONSOLE_PORT = $(shell grep -m1 'web: 3000 was in use, published on' docker-compose.ports.yml 2>/dev/null | tr -cd '0-9 ' | tr ' ' '\n' | grep -v '^$$' | tail -n1)console_url = $(if $(strip $(CONSOLE_URL)),$(strip $(CONSOLE_URL)),http://localhost:$(if $(strip $(CONSOLE_PORT)),$(strip $(CONSOLE_PORT)),3000))-.PHONY: help install env up up-dev up-full pull down restart status doctor smoke _anonymous_write_is_refused demo logs clean \+.PHONY: help install env up up-dev up-full up-gpu up-host-llm _gpu_preflight pull down restart status doctor smoke _anonymous_write_is_refused demo logs clean \bootstrap ingest-token api-token test test-unit test-integration test-e2e stats papers \papers-install demo-script@@ -208,6 +208,55 @@ up-full: env _ports _refresh@echo "Prove the pipeline works: make smoke"@$(MAKE) --no-print-directory bootstrap+# ── Where the model runs ─────────────────────────────────────────────────────+#+# Three options, and the default is unchanged: `make up` runs the bundled+# Ollama on CPU, which works everywhere and needs nothing.+#+# make up-gpu bundled Ollama, on an NVIDIA GPU (Linux, Windows+WSL2)+# make up-host-llm an Ollama you already run yourself (the only option that+# uses Apple Silicon's GPU, since Docker Desktop cannot+# pass Metal into a Linux container)+#+# A hosted provider is the fourth option and needs no target at all: configure+# it per tenant from the console, Settings -> Deployment & AI, or from the+# first-run wizard.++# `_gpu_preflight` first, deliberately. Without it the failure on a host with+# no NVIDIA container toolkit is the daemon's own+# `could not select device driver "nvidia"`, which names neither a cause nor a+# next command.+up-gpu: env _gpu_preflight _ports _refresh+ $(COMPOSE) -f docker-compose.yml -f infra/compose/docker-compose.gpu.yml up -d+ @$(MAKE) --no-print-directory _wait+ @echo ""+ @echo " Console: $(console_url)"+ @echo " API: http://localhost:8000"+ @echo ""+ @echo " Ollama is running with an NVIDIA device reserved. Confirm the model"+ @echo " actually loaded onto it: docker compose exec ollama ollama ps"+ @echo " (a SIZE with 100% GPU is what you want; 100% CPU means it did not)"+ @echo ""+ @$(MAKE) --no-print-directory bootstrap++_gpu_preflight:+ @python3 scripts/check_gpu_runtime.py++# Uses an Ollama already listening on the host. The bundled one is not started+# at all, so there is no second copy and no port conflict to resolve.+up-host-llm: env _ports _refresh+ $(COMPOSE) -f docker-compose.yml -f infra/compose/docker-compose.host-llm.yml up -d+ @$(MAKE) --no-print-directory _wait+ @echo ""+ @echo " Console: $(console_url)"+ @echo " API: http://localhost:8000"+ @echo ""+ @echo " Using your host's Ollama. The bundled one was not started."+ @echo " If triage reports no model, check it is listening on all interfaces:"+ @echo " OLLAMA_HOST=0.0.0.0 ollama serve"+ @echo ""+ @$(MAKE) --no-print-directory bootstrap+# Refreshes the images when the tag they name can move.## `pull_policy: missing` is correct for a pinned tag — `v12.0.0` is immutable,diff --git a/README.md b/README.mdindex fbe843e2f..0e4878c43 100644--- a/README.md+++ b/README.md@@ -155,9 +155,10 @@ credentials to do either.**sized for CPU-only inference, so `make up` produces real triage verdicts with real token counts inthe Investigation Ledger — not a stub. It is not a frontier model: over 50 alerts it gave triageusable output 44 times before the reply was constrained to JSON and 50 after-([method](scripts/measure_triage_reliability.py)), and the rail labels which path answered. Upgrade-by setting `OPENAI_API_KEY` and the model pins. **No hosted provider has ever been exercised here**-— there is no funded key, so per-model rows read *not measured* rather than zero.+([method](scripts/measure_triage_reliability.py)), and the rail labels which path answered. Run it+faster with `make up-gpu`, `make up-host-llm`, or your own provider from the console+([all four](apps/docs/docs/operations/where-the-model-runs.md)). **No hosted provider has ever been+exercised here** — there is no funded key, so per-model rows read *not measured* rather than zero.([ADR-0006](docs/decisions/0006-llm-gateway-in-core.md))**One real external feed ships too.** `services/threatintel` polls the CISA Known Exploiteddiff --git a/apps/docs/docs/operations/where-the-model-runs.md b/apps/docs/docs/operations/where-the-model-runs.mdnew file mode 100644index 000000000..df17347a2--- /dev/null+++ b/apps/docs/docs/operations/where-the-model-runs.md@@ -0,0 +1,149 @@+---+id: where-the-model-runs+title: Where the model runs+sidebar_label: Where the model runs+---++# Where the model runs++AiSOC ships a model and runs it. `make up` needs no account, no key and no GPU,+and triage produces a real verdict from a real model with real token counts.++It is also the slowest of the four options. This page is the other three.++## The four options++| Option | Command | Works on |+|---|---|---|+| Bundled model, CPU | `make up` | everything |+| Bundled model, NVIDIA GPU | `make up-gpu` | Linux, Windows + WSL2 |+| An Ollama you already run | `make up-host-llm` | everything, and the **only** GPU option on a Mac |+| A hosted provider | no command — configure it in the console | everything |++`make doctor` tells you which fits the host you are on, and the setup wizard+tells you which one is in effect right now.++## Why the GPU option is not in the console++Switching the bundled model onto a GPU means restarting that container with+different device reservations. A web service that could do that would need the+Docker socket, which is a container-escape path rather than a feature. So the+console *reports* where the model is running and shows you the command; it does+not run it.++The hosted-provider option is different — that is a database row, so the wizard+configures it outright.++## NVIDIA++```bash+make up-gpu+```++This layers `infra/compose/docker-compose.gpu.yml`, which reserves one NVIDIA+device for Ollama and changes nothing else.++It runs `scripts/check_gpu_runtime.py` first, and that check is the point.+Without it, a host missing the container toolkit gets the daemon's own answer:++```+Error response from daemon: could not select device driver "nvidia" with capabilities: [[gpu]]+```++which names neither a cause nor a next command. The preflight says which of the+four things is missing — card, driver, toolkit, daemon configuration — and what+installs it.++Expose more than one device with `AISOC_GPU_COUNT=all`. The pinned model needs+roughly 3 GB of VRAM; if your card is smaller, Ollama splits the model and the+wizard reports it as *partly on a GPU* rather than pretending otherwise.++## Apple Silicon++`make up-gpu` does nothing useful here, and the preflight will say so rather+than letting you find out slowly. **Docker Desktop cannot pass the Metal GPU+into a Linux container.** No toolkit, driver or setting changes that: a+container on a Mac is CPU-only.++A natively-installed Ollama *does* use Metal:++```bash+brew install ollama+OLLAMA_HOST=0.0.0.0 ollama serve # in its own terminal+ollama pull llama3.2:3b-instruct-q4_K_M+make up-host-llm+```++`OLLAMA_HOST=0.0.0.0` matters: Ollama binds loopback by default, which a+container cannot reach.++## An Ollama you already run++```bash+make up-host-llm+```++This layers `infra/compose/docker-compose.host-llm.yml`, which moves the+bundled `ollama` and `ollama-pull` into a `bundled` profile so neither starts,+clears the gateway's dependency on the puller, and points+`AISOC_LLM_API_BASE` at `host.docker.internal:11434`.++It is worth doing even without a GPU. `11434` is in the port inventory, so on a+host already running Ollama, `make up` sees the conflict and republishes the+*bundled* one on a free port — leaving you with two Ollamas, the stack talking+to the new one, and yours idle.++Point somewhere else entirely by setting `AISOC_LLM_API_BASE` in `.env`: another+machine on the LAN, or an existing vLLM.++Bring the bundled one back without editing anything:++```bash+docker compose --profile bundled up -d ollama+```++## A hosted provider++Console → **Settings → Deployment & AI**, or the **Choose where the AI runs**+step in the setup wizard. Seven providers: `openai`, `anthropic`,+`azure-openai`, `local-ollama`, `local-vllm`, `local-litellm`, `custom`. The key+is encrypted at rest with the credential vault and never returned by the API —+reads report only `has_api_key`.++**Test it before you rely on it.** The *Test* button places one real+one-token completion and reports what happened:++| Outcome | Means |+|---|---|+| `ok` | the provider answered |+| `refused` | reached it and it said no — usually the key, sometimes the model name |+| `unreachable` | nothing answered at that address |+| `unverified` | air-gapped, so the call was not attempted — the policy working, not a bad key |++Before this existed, the routes validated only *shape*, so a revoked key+surfaced as triage quietly falling back to the deterministic path — a failure+that is hard to attribute to a credential precisely because it is silent.++## Checking what is actually running++A GPU reservation is a *request*. A model can still land on the CPU for want of+VRAM or a usable driver, so reading the compose file back would report the+intent and call it the outcome. Ask instead:++```bash+curl -s localhost:8000/api/v1/llm/runtime -H "Authorization: Bearer $TOKEN"+docker compose exec ollama ollama ps # SIZE and the GPU/CPU split+```++The wizard shows the same thing. Five answers, and **not loaded right now** is+one of them: Ollama unloads after a few minutes idle, so an empty answer means+nobody has asked it anything yet — which is not the same as CPU, and reporting+CPU there would be a guess about the exact thing you are deciding on.++## Air-gapped deployments++All four options work air-gapped except a hosted provider on a public address.+`AISOC_AIRGAPPED=true` refuses egress to anything outside+`AISOC_AIRGAP_ALLOWLIST`, while still permitting private hosts — so a+`local-ollama` or `local-vllm` on your own network is allowed by design. See+[air-gapped](./air-gapped.md).diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex dc9f10975..de7948003 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -191,6 +191,7 @@ const sidebars: SidebarsConfig = {"compliance/evidence-pack","compliance/fips-posture","operations/credentials",+ "operations/where-the-model-runs","operations/secrets","operations/scim","operations/case-orchestration",diff --git a/apps/web/src/components/onboarding/ModelPlacement.tsx b/apps/web/src/components/onboarding/ModelPlacement.tsxnew file mode 100644index 000000000..d4feac18d--- /dev/null+++ b/apps/web/src/components/onboarding/ModelPlacement.tsx@@ -0,0 +1,93 @@+'use client';++/**+ * Where AI triage is running, and the ways to change it.+ *+ * Shown inside the setup checklist's "Choose where the AI runs" step. It+ * reports rather than configures, for the two local options, because it has to:+ * switching the bundled Ollama onto a GPU means restarting that container with+ * different compose arguments, and a web service that could do that would need+ * the Docker socket -- which is a container-escape path, not a feature.+ *+ * The hosted-provider option *is* configurable from here, because that is a+ * database row rather than a container restart. It links to the existing BYOK+ * form rather than duplicating it.+ */++import Link from 'next/link';+import useSWR from 'swr';++import { llmApi, type LlmRuntime } from '@/lib/api';++/** How each placement reads to someone deciding what to do about it. */+const TONE: Record<string, { label: string; className: string }> = {+ gpu: { label: 'On a GPU', className: 'border-emerald-700/60 bg-emerald-950/30 text-emerald-200' },+ partial: { label: 'Partly on a GPU', className: 'border-amber-700/60 bg-amber-950/30 text-amber-200' },+ cpu: { label: 'On the CPU', className: 'border-slate-600 bg-slate-800/40 text-slate-200' },+ unknown: { label: 'Not loaded right now', className: 'border-slate-600 bg-slate-800/40 text-slate-300' },+ unreachable: { label: 'No local model', className: 'border-slate-600 bg-slate-800/40 text-slate-300' },+};++export function ModelPlacement() {+ const { data, error, isLoading } = useSWR<LlmRuntime>(+ 'onboarding:llm-runtime',+ () => llmApi.runtime(),+ // No `fallbackData`: supplying one disables revalidation, so a placeholder+ // would be what this panel *shows* rather than a first paint. There is no+ // invented placement better than saying the probe failed.+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );++ if (isLoading) {+ return <p className="mt-2 text-sm text-slate-500">Asking the model where it is running…</p>;+ }++ if (error || !data) {+ return (+ <p className="mt-2 text-sm text-slate-400">+ Could not determine where the model is running. Triage is unaffected; this panel is+ informational.{' '}+ <Link href="/settings" className="underline hover:text-slate-200">+ Configure a provider+ </Link>+ </p>+ );+ }++ const tone = TONE[data.placement] ?? TONE.unknown;++ return (+ <div className="mt-2 space-y-2">+ <div className={`inline-flex items-center gap-2 rounded-md border px-2.5 py-1 text-xs ${tone.className}`}>+ <span className="font-medium">{tone.label}</span>+ {typeof data.vram_bytes === 'number' && data.vram_bytes > 0 && (+ <span className="opacity-80">{(data.vram_bytes / 1024 ** 3).toFixed(1)} GB in VRAM</span>+ )}+ </div>++ <p className="text-sm text-slate-400">{data.detail}</p>++ {data.options.length > 0 && (+ <ul className="space-y-1 text-sm text-slate-400">+ {data.options.map((option) => (+ <li key={option} className="flex gap-2">+ <span aria-hidden className="text-slate-600">+ ·+ </span>+ <span>{option}</span>+ </li>+ ))}+ </ul>+ )}++ <Link+ href="/settings?tab=deployment"+ className="mt-1 inline-block rounded-md border border-slate-600 px-3 py-1.5 text-sm text-slate-200 transition hover:border-slate-400 hover:bg-slate-800"+ >+ Use my own provider+ </Link>+ </div>+ );+}++export default ModelPlacement;diff --git a/apps/web/src/components/onboarding/SetupChecklist.tsx b/apps/web/src/components/onboarding/SetupChecklist.tsxindex e95c02688..cda3a6c65 100644--- a/apps/web/src/components/onboarding/SetupChecklist.tsx+++ b/apps/web/src/components/onboarding/SetupChecklist.tsx@@ -6,6 +6,7 @@ import useSWR from 'swr';import toast from 'react-hot-toast';import { onboardingApi, type OnboardingStatus, type SampleDataResult } from '@/lib/api';+import { ModelPlacement } from './ModelPlacement';import { clsx } from 'clsx';/**@@ -86,7 +87,13 @@ export function SetupChecklist({ compact = false }: { compact?: boolean }) {return <div className="h-32 animate-pulse rounded-lg bg-slate-800/40" />;}- const remaining = data.steps.filter((s) => !s.done && s.key !== 'try').length;+ // `try` and `model` are both optional: sample data is an alternative to a real+ // connector, and the model step is informational because a local model ships+ // and works. Counting either would show a tenant that is genuinely finished as+ // having work left.+ const remaining = data.steps.filter(+ (s) => !s.done && s.key !== 'try' && s.key !== 'model',+ ).length;return (<section@@ -136,6 +143,8 @@ export function SetupChecklist({ compact = false }: { compact?: boolean }) {</div>{!compact && <p className="mt-1 text-sm text-slate-400">{step.why}</p>}+ {step.key === 'model' && <ModelPlacement />}+{step.key === 'try' && !step.done && (<buttontype="button"diff --git a/apps/web/src/components/settings/SettingsView.tsx b/apps/web/src/components/settings/SettingsView.tsxindex d61e175ac..386db486b 100644--- a/apps/web/src/components/settings/SettingsView.tsx+++ b/apps/web/src/components/settings/SettingsView.tsx@@ -1823,6 +1823,7 @@ function BYOKCard({}) {const [editing, setEditing] = useState(false);const [confirmingDelete, setConfirmingDelete] = useState(false);+ const [testing, setTesting] = useState(false);const [submitting, setSubmitting] = useState(false);const [provider, setProvider] = useState<LlmWritableProvider>('openai');@@ -1907,6 +1908,29 @@ function BYOKCard({setEditing(false);};+ // One real call with the saved credential. Reports four outcomes, and+ // `unverified` is deliberately not an error: an air-gapped deployment+ // refusing the egress is the posture working, and a red toast there would+ // send an operator to rotate a key that is fine.+ const onTestClick = async () => {+ setTesting(true);+ try {+ const result = await deploymentApi.testLlmCredential();+ const where = result.model ? ` (${result.model})` : '';+ if (result.outcome === 'ok') {+ toast.success(`${result.detail}${where}`);+ } else if (result.outcome === 'unverified') {+ toast(result.detail);+ } else {+ toast.error(result.detail);+ }+ } catch (err) {+ toast.error(extractApiDetail(err, 'Could not test the credential.'));+ } finally {+ setTesting(false);+ }+ };+const onDeleteClick = async () => {if (!confirmingDelete) {setConfirmingDelete(true);@@ -1969,6 +1993,14 @@ function BYOKCard({</p></div><div className="flex shrink-0 gap-2">+ <button+ type="button"+ onClick={onTestClick}+ disabled={testing || submitting}+ className="rounded-md border border-gray-700 bg-gray-900 px-3 py-1.5 text-xs font-medium text-gray-200 hover:bg-gray-800 disabled:opacity-50"+ >+ {testing ? 'Testing…' : 'Test'}+ </button><buttontype="button"onClick={() => setEditing(true)}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex ece49c559..ac2ff6c6c 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -5752,6 +5752,38 @@ export interface LlmCredentialView {last_rotated_at: string | null;}+/**+ * Where the local model is actually running, as Ollama reports it.+ *+ * Distinct from `LlmStatus`, which describes *configuration*. A GPU+ * reservation is a request: a model can still land on the CPU for want of+ * VRAM or a usable driver, so this is the outcome rather than the intent.+ */+export interface LlmRuntime {+ placement: 'gpu' | 'partial' | 'cpu' | 'unknown' | 'unreachable' | 'not_local';+ detail: string;+ base_url: string;+ /** What an operator can do about the answer. Never empty for a CPU verdict. */+ options: string[];+ /** Absent, not zero, when nothing is loaded — "not measured" is not "zero". */+ model?: string;+ vram_bytes?: number;+ total_bytes?: number;+}++export const llmApi = {+ /** Ask the model where it is running. Reports, never changes. */+ runtime: () => request<LlmRuntime>('/api/v1/llm/runtime'),+};++export interface LlmCredentialTestResult {+ outcome: 'ok' | 'refused' | 'unreachable' | 'unverified';+ detail: string;+ provider: string;+ model?: string;+ latency_ms?: number;+}+export const deploymentApi = {/** Live air-gap policy snapshot for this pod. Safe to poll. */getAirgapStatus: () => request<AirgapStatus>('/api/v1/airgap/status'),@@ -5776,6 +5808,19 @@ export const deploymentApi = {/** Hard-delete the credential. Returns 204 on success. */deleteLlmCredential: () =>request<void>('/api/v1/llm/credentials', { method: 'DELETE' }),++ /**+ * Make one real call with the saved credential and report what happened.+ *+ * The routes above validate shape and never talk to the provider, so a+ * revoked key used to surface as triage quietly falling back. `unverified`+ * is a success-adjacent outcome: an air-gapped deployment refuses the+ * egress rather than attempting it, which is the policy working.+ */+ testLlmCredential: () =>+ request<LlmCredentialTestResult>('/api/v1/llm/credentials/test', {+ method: 'POST',+ }),};// ─── Reports / Executive digest (WS-G2) ─────────────────────────────────────diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex ad0ce8b06..4c0a3766c 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -15621,15 +15621,16 @@ paths:tags:- llmsummary: Current LLM provider configuration- description: "Return the env-only LLM provider snapshot for this pod.\n\nIntentionally\- \ **unauthenticated** and **env-only**, mirroring\n``GET /api/v1/airgap/status``:\- \ the response carries no secrets\n(only ``key_set: bool``) and is safe for\- \ operator dashboards,\nauditors, and k8s liveness probes.\n\nTenant-aware\- \ callers (the web UI's \"Deployment & AI\" Settings\npanel, the agents service's\- \ explain path) layer per-tenant BYOK\noverrides on top of this baseline by\- \ either:\n\n* calling :func:`tenant_llm_status` with their own DB session,\- \ or\n* pairing this response with ``GET /api/v1/llm/credentials`` to\n perform\- \ the merge client-side."+ description: "Return the env-only LLM provider snapshot for this pod.\n\n**Authenticated**\+ \ -- the signature binds ``AuthUser`` and has for as long\nas this route has\+ \ existed. The docstring used to say \"intentionally\nunauthenticated\", which\+ \ was prose disagreeing with the code beneath it.\n\n**Env-only**: the response\+ \ carries no secrets (only ``key_set: bool``).\n\nTenant-aware callers (the\+ \ web UI's \"Deployment & AI\" Settings\npanel, the agents service's explain\+ \ path) layer per-tenant BYOK\noverrides on top of this baseline by either:\n\+ \n* calling :func:`tenant_llm_status` with their own DB session, or\n* pairing\+ \ this response with ``GET /api/v1/llm/credentials`` to\n perform the merge\+ \ client-side."operationId: get_llm_status_api_v1_llm_status_getresponses:'200':@@ -15642,6 +15643,44 @@ paths:title: Response Get Llm Status Api V1 Llm Status Getsecurity:- HTTPBearer: []+ /api/v1/llm/runtime:+ get:+ tags:+ - llm+ summary: Where the local model is actually running+ description: 'Ask Ollama whether the model is on a GPU or a CPU, and say so.+++ Separate from ``/status`` deliberately. That route reports *configuration*++ -- which provider and model this pod is pointed at. This one reports++ *outcome*, which can differ: a GPU reservation is a request, and a model++ can still land on the CPU for want of VRAM or a usable driver. Reading the++ compose file back would report the intent and call it the result.+++ Carries the commands that would change the answer, because the console++ cannot change it: switching the bundled Ollama onto a GPU means restarting++ that container with different compose arguments, which a web service must++ not be able to do.'+ operationId: get_llm_runtime_api_v1_llm_runtime_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ additionalProperties: true+ type: object+ title: Response Get Llm Runtime Api V1 Llm Runtime Get+ security:+ - HTTPBearer: []/api/v1/llm/credentials:get:tags:@@ -15716,6 +15755,40 @@ paths:description: Successful Responsesecurity:- HTTPBearer: []+ /api/v1/llm/credentials/test:+ post:+ tags:+ - llm+ summary: Make one real call with this tenant's credential+ description: 'Place one minimal completion and report what happened.+++ There was no way to find out whether a saved key worked. The three routes++ above validate *shape* -- that the URL parses, that the provider/key/base++ combination is internally consistent -- and none of them talks to the++ provider, so an operator who pasted a revoked key learned about it when++ triage silently fell back to the deterministic path. That failure is quiet++ by design, which is exactly what makes it hard to attribute.+++ `settings:write` rather than `settings:read`: this spends the tenant''s++ money and touches an external service, which is not a read.'+ operationId: test_llm_credential_api_v1_llm_credentials_test_post+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/LlmCredentialTestResult'+ security:+ - HTTPBearer: []/api/v1/threatintel/stix/indicators:get:tags:@@ -26179,6 +26252,46 @@ components:- rules- totaltitle: ListResponse+ LlmCredentialTestResult:+ properties:+ outcome:+ type: string+ enum:+ - ok+ - refused+ - unreachable+ - unverified+ title: Outcome+ detail:+ type: string+ title: Detail+ provider:+ type: string+ title: Provider+ model:+ anyOf:+ - type: string+ - type: 'null'+ title: Model+ latency_ms:+ anyOf:+ - type: integer+ - type: 'null'+ title: Latency Ms+ type: object+ required:+ - outcome+ - detail+ - provider+ title: LlmCredentialTestResult+ description: 'What a real call to the configured provider did.+++ Four outcomes, and `unverified` is one of them on purpose: an air-gapped++ deployment refuses the egress rather than attempting it, and reporting that++ as a failure would send an operator to debug a credential that is fine.'LlmCredentialUpsert:properties:provider:diff --git a/infra/compose/docker-compose.gpu.yml b/infra/compose/docker-compose.gpu.ymlnew file mode 100644index 000000000..6721a86ec--- /dev/null+++ b/infra/compose/docker-compose.gpu.yml@@ -0,0 +1,57 @@+# AiSOC — NVIDIA GPU overlay for the bundled Ollama+#+# Usage:+# make up-gpu+#+# or by hand:+# docker compose -f docker-compose.yml -f infra/compose/docker-compose.gpu.yml up -d+#+# What this changes+# -----------------+# One thing: it reserves an NVIDIA device for the `ollama` service. Nothing+# else moves. The model, the gateway, the aliases and every other service are+# whatever the base file says.+#+# Why it is an overlay and not a line in the base file+# ----------------------------------------------------+# A `deploy.resources.reservations.devices` block naming the nvidia driver is+# not advisory. On a host without an NVIDIA GPU *and* the container toolkit,+# the daemon refuses to start the service at all:+#+# Error response from daemon: could not select device driver "nvidia" with+# capabilities: [[gpu]]+#+# `make up` is the documented first-run path and CORE ships+# `llama3.2:3b-instruct-q4_K_M` to run CPU-only in 8 GB, so putting this in the+# base file takes out first run for every Mac, every CPU-only Linux box and+# every CI runner. It has to be opt-in, and `make up-gpu` runs+# `scripts/check_gpu_runtime.py` first so the failure names a cause and a next+# command rather than handing over the daemon's error.+#+# Apple Silicon+# -------------+# This overlay does nothing for you. Docker Desktop cannot pass the Metal GPU+# into a Linux container, so a bundled Ollama is CPU-only on a Mac no matter+# what is reserved here. Run Ollama natively instead -- it uses Metal -- and+# point the stack at it with `make up-host-llm`.+#+# Sizing+# ------+# The pinned model needs roughly 3 GB of VRAM. `count: 1` takes the first+# visible device; set `AISOC_GPU_COUNT=all` to expose every device, or pin+# specific ones with `device_ids` instead of `count` if you share the host.++services:+ ollama:+ environment:+ # Ollama decides layer placement itself and logs what it did. Left+ # unset rather than forced, because a hardcoded layer count is wrong+ # on every card except the one it was measured on.+ OLLAMA_NUM_PARALLEL: "${OLLAMA_NUM_PARALLEL:-1}"+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: ${AISOC_GPU_COUNT:-1}+ capabilities: [gpu]diff --git a/infra/compose/docker-compose.host-llm.yml b/infra/compose/docker-compose.host-llm.ymlnew file mode 100644index 000000000..b4ac3397c--- /dev/null+++ b/infra/compose/docker-compose.host-llm.yml@@ -0,0 +1,82 @@+# AiSOC — use an Ollama you already run on the host+#+# Usage:+# make up-host-llm+#+# or by hand:+# docker compose -f docker-compose.yml -f infra/compose/docker-compose.host-llm.yml up -d+#+# Who this is for+# ---------------+# Two audiences, and the second is the larger one.+#+# **Apple Silicon.** Docker Desktop cannot pass the Metal GPU into a Linux+# container, so the bundled Ollama is CPU-only on a Mac whatever is reserved+# for it. An Ollama installed natively *does* use Metal. This overlay is the+# only way a Mac gets GPU-accelerated triage.+#+# **Anyone already running Ollama.** Today the bundled one is started anyway:+# 11434 is in `scripts/doctor.sh`'s managed port table, so+# `scripts/resolve_port_conflicts.py` sees the conflict and republishes the+# bundled Ollama on a free port. The result is two Ollamas, the stack talking+# to the new CPU-only one, and the host's — very possibly GPU-accelerated —+# sitting idle. This points the stack at the one that already exists.+#+# What this changes+# -----------------+# 1. `ollama` and `ollama-pull` move into a `bundled` profile. A service with a+# profile is not started unless that profile is named, so neither runs. They+# are not deleted: `docker compose --profile bundled up -d ollama` still+# brings the bundled one back without editing anything.+#+# 2. `litellm` loses its dependency on `ollama-pull`. In the base file it waits+# for `service_completed_successfully` so the gateway cannot answer before+# the weights exist; with the bundled pair not running that condition can+# never be met and the gateway would wait forever. `!reset` rather than an+# empty mapping because a plain override *merges* — it can add a dependency+# but not remove one.+#+# 3. The gateway's model base URL points at the host.+#+# `extra_hosts` is required and not decorative: Docker Desktop resolves+# `host.docker.internal` for you and Linux does not, so without it this works+# on a Mac and fails on a server.+#+# Your Ollama has to be reachable from a container+# ------------------------------------------------+# By default `ollama serve` binds 127.0.0.1, which a container cannot reach+# through the gateway address. If triage reports no model:+#+# OLLAMA_HOST=0.0.0.0 ollama serve+#+# and confirm the model this stack asks for is pulled:+#+# ollama pull llama3.2:3b-instruct-q4_K_M+#+# Point at something else entirely by setting AISOC_LLM_API_BASE in `.env` —+# another machine on the LAN, or an existing vLLM. This overlay only supplies+# the default.++services:+ ollama:+ profiles: ["bundled"]++ ollama-pull:+ profiles: ["bundled"]++ litellm:+ depends_on: !reset null+ extra_hosts:+ - "host.docker.internal:host-gateway"+ environment:+ AISOC_LLM_API_BASE: "${AISOC_LLM_API_BASE:-http://host.docker.internal:11434}"++ # The API reads Ollama directly for the runtime probe behind+ # `GET /api/v1/llm/runtime` — "is the model on a GPU or a CPU" is answered by+ # asking Ollama, not by guessing — so it needs the same address and the same+ # host mapping.+ api:+ extra_hosts:+ - "host.docker.internal:host-gateway"+ environment:+ AISOC_OLLAMA_URL: "${AISOC_OLLAMA_URL:-http://host.docker.internal:11434}"diff --git a/install.ps1 b/install.ps1index 5b12fa270..83418722c 100644--- a/install.ps1+++ b/install.ps1@@ -1055,6 +1055,43 @@ function Invoke-SmokeTest {# ─── Final banner ─────────────────────────────────────────────────────────+function Write-ModelPlacement {+ # Where the model runs, reported once at the end.+ #+ # Printed, never prompted: this installer asks the user nothing and should+ # keep it that way (tests/test_installer_parity_gate.py holds it in step+ # with the Makefile). Switching Ollama onto a GPU means restarting that+ # container with different compose arguments, so the only honest thing an+ # installer can do is say which option fits the host it just ran on.+ $advice = $null++ if (Get-Command nvidia-smi -ErrorAction SilentlyContinue) {+ # Windows reaches an NVIDIA GPU through WSL2, which Docker Desktop+ # already requires, so the toolkit question is the daemon's not the+ # host's. check_gpu_runtime.py answers it properly.+ $advice = @(+ 'This host has an NVIDIA GPU. To run the bundled model on it:'+ ' docker compose -f docker-compose.yml -f infra\compose\docker-compose.gpu.yml up -d'+ ' Check it will work first:'+ ' python scripts\check_gpu_runtime.py'+ )+ }+ elseif (Get-Command ollama -ErrorAction SilentlyContinue) {+ $advice = @(+ 'You already run Ollama natively. To use it instead of the bundled one:'+ ' docker compose -f docker-compose.yml -f infra\compose\docker-compose.host-llm.yml up -d'+ )+ }++ if (-not $advice) { return }++ Write-Host ''+ Write-Host 'Where the model runs:' -ForegroundColor White+ foreach ($line in $advice) { Write-Host " $line" }+ Write-Host ' Or use a hosted provider: console -> Settings -> Deployment & AI.' -ForegroundColor DarkGray+ Write-Host ''+}+function Write-SuccessBanner {if ($NoLaunch) {Write-Host ''@@ -1203,6 +1240,7 @@ function Invoke-Main {New-AdminAccountInvoke-SmokeTestWrite-SuccessBanner+ Write-ModelPlacement}Invoke-Maindiff --git a/install.sh b/install.shindex 886c2653a..e2724852e 100755--- a/install.sh+++ b/install.sh@@ -870,6 +870,43 @@ run_smoke_test() {exit 5}+# Where the model runs, reported once at the end.+#+# Printed, never prompted: this installer asks the user nothing and should keep+# it that way. Switching Ollama onto a GPU means restarting that container with+# different compose arguments, so the only honest thing an installer can do is+# say which option fits the host it just ran on.+print_model_placement() {+ _advice=""+ case "$(uname -s)" in+ Darwin)+ if [ "$(uname -m)" = "arm64" ]; then+ if have ollama; then+ _advice="You already run Ollama natively, and on Apple Silicon that is the only one+ with a GPU — Docker cannot pass Metal into a container. To use it:+ make up-host-llm"+ else+ _advice="AI triage is running on CPU. On Apple Silicon a container gets no GPU at+ all, so for a faster model install Ollama natively and point the stack at it:+ brew install ollama && OLLAMA_HOST=0.0.0.0 ollama serve+ make up-host-llm"+ fi+ fi+ ;;+ Linux)+ if have nvidia-smi && nvidia-smi -L >/dev/null 2>&1; then+ _advice="This host has an NVIDIA GPU. To run the bundled model on it:+ make up-gpu+ (\`python3 scripts/check_gpu_runtime.py\` says whether the container toolkit+ is installed, and what to do if not.)"+ fi+ ;;+ esac+ [ -z "$_advice" ] && return 0+ printf '\n%sWhere the model runs:%s\n %s\n' "$C_BOLD" "$C_RESET" "$_advice"+ printf ' %sOr use a hosted provider: console → Settings → Deployment & AI.%s\n' "$C_DIM" "$C_RESET"+}+print_success() {cat <<EOF@@ -948,6 +985,7 @@ main() {run_pnpm_installrun_demorun_smoke_test+ print_model_placementprint_success}diff --git a/scripts/check_gpu_runtime.py b/scripts/check_gpu_runtime.pynew file mode 100644index 000000000..c42eb9eb4--- /dev/null+++ b/scripts/check_gpu_runtime.py@@ -0,0 +1,279 @@+#!/usr/bin/env python3+"""Refuse `make up-gpu` with a cause, rather than letting Docker refuse it without one.++What this exists to prevent+---------------------------+`infra/compose/docker-compose.gpu.yml` reserves an NVIDIA device for the+bundled Ollama. On a host that cannot provide one, the daemon's answer is:++ Error response from daemon: could not select device driver "nvidia" with+ capabilities: [[gpu]]++That names no cause and no next command. It does not say whether the card, the+driver, the container toolkit or the daemon configuration is the missing piece,+and on a Mac it does not say that no amount of installing will help because+Docker Desktop cannot pass Metal into a Linux container at all.++So this runs first and answers the question the daemon does not: which of the+four things is missing, what installs it, and what to do instead when nothing+will.++Why it probes rather than reads configuration+---------------------------------------------+`docker info` listing `nvidia` under Runtimes is necessary and not sufficient:+the runtime can be registered while the driver is too old for the toolkit, or+while no device is visible to the daemon. The only answer that means anything+is whether a container can actually acquire a GPU, so the last check runs one.+It is a 4 MB image and a few seconds, which is cheaper than a failed stack+start.++Usage::++ python3 scripts/check_gpu_runtime.py # verdict+ python3 scripts/check_gpu_runtime.py --self-test+"""++from __future__ import annotations++import argparse+import json+import platform+import shutil+import subprocess+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import self_test_if_requested # noqa: E402++#: Small and already common on a developer machine. `busybox` would be smaller+#: but carries no CUDA stack, so it cannot answer the question that matters.+_PROBE_IMAGE = "nvidia/cuda:12.4.1-base-ubuntu22.04"++_APPLE_SILICON_ADVICE = """+This is an Apple Silicon Mac, and `make up-gpu` cannot help here.++Docker Desktop does not pass the Metal GPU into a Linux container. There is no+setting, driver or toolkit that changes this -- a container on this machine is+CPU-only whatever the compose file reserves.++What does work is running Ollama natively, where it uses Metal, and pointing+the stack at it:++ brew install ollama+ OLLAMA_HOST=0.0.0.0 ollama serve # in its own terminal+ ollama pull llama3.2:3b-instruct-q4_K_M+ make up-host-llm++`make up` also remains correct: the bundled model runs on CPU and triage works,+just more slowly.+""".strip()++_NO_TOOLKIT_ADVICE = """+Install the NVIDIA Container Toolkit, which is what lets the daemon hand a GPU+to a container:++ https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html++On Debian/Ubuntu that is roughly:++ sudo apt-get install -y nvidia-container-toolkit+ sudo nvidia-ctk runtime configure --runtime=docker+ sudo systemctl restart docker++Then run `make up-gpu` again.++If you would rather not install it, `make up` runs the same model on CPU, and+`make up-host-llm` uses an Ollama you run outside Docker.+""".strip()+++class Result:+ """One check's outcome, with the advice that belongs to it."""++ def __init__(self, ok: bool, detail: str, advice: str = "") -> None:+ self.ok = ok+ self.detail = detail+ self.advice = advice+++def check_platform() -> Result:+ """Apple Silicon is a refusal, not a missing dependency."""+ if platform.system() == "Darwin":+ if platform.machine() in {"arm64", "aarch64"}:+ return Result(False, "Apple Silicon: Docker cannot pass Metal to a container", _APPLE_SILICON_ADVICE)+ return Result(+ False,+ "macOS on Intel: Docker Desktop exposes no GPU to Linux containers",+ _APPLE_SILICON_ADVICE,+ )+ return Result(True, f"{platform.system()} {platform.machine()}")+++def _docker_info() -> dict:+ if not shutil.which("docker"):+ return {}+ try:+ done = subprocess.run(+ ["docker", "info", "--format", "{{json .}}"],+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )+ except (OSError, subprocess.SubprocessError):+ return {}+ if done.returncode != 0:+ return {}+ try:+ return json.loads(done.stdout or "{}")+ except json.JSONDecodeError:+ return {}+++def check_daemon_runtime() -> Result:+ """Is `nvidia` registered as a runtime with the daemon?++ Necessary, not sufficient -- see the module docstring. A registered runtime+ with a too-old driver still fails at container start.+ """+ info = _docker_info()+ if not info:+ return Result(+ False,+ "could not read `docker info`",+ "Docker is not running, or this user cannot reach its socket. Start Docker and retry.",+ )+ runtimes = info.get("Runtimes") or {}+ if "nvidia" not in runtimes:+ return Result(+ False,+ f"the Docker daemon has no `nvidia` runtime (it has: {', '.join(sorted(runtimes)) or 'none'})",+ _NO_TOOLKIT_ADVICE,+ )+ return Result(True, "the daemon has an `nvidia` runtime registered")+++def check_container_can_acquire(skip: bool = False) -> Result:+ """The only check whose answer means anything: run one.++ `docker info` can list the runtime while the driver is too old, or while+ the daemon sees no device. This asks the question the stack will ask.+ """+ if skip:+ return Result(True, "skipped (--no-probe)")+ try:+ done = subprocess.run(+ ["docker", "run", "--rm", "--gpus", "all", _PROBE_IMAGE, "nvidia-smi", "-L"],+ capture_output=True,+ text=True,+ timeout=180,+ check=False,+ )+ except subprocess.TimeoutExpired:+ return Result(+ False,+ "the probe container did not finish within 180s",+ "The image may still be downloading. Re-run, or pass --no-probe to skip this check.",+ )+ except (OSError, subprocess.SubprocessError) as exc:+ return Result(False, f"could not run the probe container ({type(exc).__name__}: {exc})", _NO_TOOLKIT_ADVICE)++ if done.returncode != 0:+ tail = (done.stderr or done.stdout or "").strip().splitlines()+ reason = tail[-1][:300] if tail else "no output"+ return Result(+ False,+ f"a container could not acquire a GPU: {reason}",+ _NO_TOOLKIT_ADVICE,+ )++ devices = [ln for ln in (done.stdout or "").splitlines() if ln.strip().startswith("GPU ")]+ if not devices:+ return Result(+ False,+ "the probe ran but reported no devices",+ "The toolkit is installed and the daemon sees no GPU. Check `nvidia-smi` on the host.",+ )+ return Result(True, f"{len(devices)} device(s): {devices[0].strip()[:80]}")+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--self-test", action="store_true")+ parser.add_argument(+ "--no-probe",+ action="store_true",+ help="Skip the container probe. Faster, and answers a weaker question.",+ )+ args = parser.parse_args(argv)++ if args.self_test:+ return _self_test()++ checks = [+ ("host platform", check_platform()),+ ]+ if checks[-1][1].ok:+ checks.append(("docker daemon runtime", check_daemon_runtime()))+ if checks[-1][1].ok:+ checks.append(("a container can acquire a GPU", check_container_can_acquire(skip=args.no_probe)))++ print("check_gpu_runtime: can this host give a container an NVIDIA GPU?")+ for label, result in checks:+ print(f" {'PASS' if result.ok else 'FAIL'} {label}: {result.detail}")++ failed = next((r for _, r in checks if not r.ok), None)+ if failed is None:+ print("\nOK — `make up-gpu` will work on this host.")+ return 0++ print("\n" + failed.advice)+ return 1+++def _self_test() -> int:+ """Prove the refusals fire and say something actionable.++ The platform check is the one that can be exercised deterministically here;+ the daemon and probe checks depend on the host, so they are asserted to+ carry advice rather than to reach a particular verdict.+ """+ checks: list[tuple[str, bool]] = []++ mac = check_platform+ import platform as _p++ real_system, real_machine = _p.system, _p.machine+ try:+ _p.system = lambda: "Darwin" # type: ignore[assignment]+ _p.machine = lambda: "arm64" # type: ignore[assignment]+ r = mac()+ checks.append(("apple silicon is refused", not r.ok))+ checks.append(("and the refusal names make up-host-llm", "make up-host-llm" in r.advice))+ checks.append(("and it says metal cannot be passed through", "Metal" in r.advice))++ _p.system = lambda: "Linux" # type: ignore[assignment]+ _p.machine = lambda: "x86_64" # type: ignore[assignment]+ checks.append(("linux passes the platform check", mac().ok))+ finally:+ _p.system, _p.machine = real_system, real_machine++ toolkit_advice = _NO_TOOLKIT_ADVICE+ checks.append(("the no-toolkit advice names the install guide", "nvidia-container-toolkit" in toolkit_advice))+ checks.append(("and offers both fallbacks", "make up" in toolkit_advice and "make up-host-llm" in toolkit_advice))++ for label, ok in checks:+ print(f" {'[ok]' if ok else '[FAIL]'} {label}")+ failed = [label for label, ok in checks if not ok]+ if failed:+ print(f"\ncheck_gpu_runtime.py: self-test FAILED ({len(failed)})")+ return 1+ print("\ncheck_gpu_runtime.py: self-test OK")+ return 0+++if __name__ == "__main__":+ self_test_if_requested("check_gpu_runtime.py")+ sys.exit(main())diff --git a/scripts/doctor.sh b/scripts/doctor.shindex 484e05502..fa6f44cd4 100755--- a/scripts/doctor.sh+++ b/scripts/doctor.sh@@ -137,6 +137,40 @@ if [ "$PORTS_ONLY" = "0" ] && docker info >/dev/null 2>&1; thenfifi+ # Where the model can run. Reported, never changed: switching Ollama onto a+ # GPU means restarting that container with different compose arguments, so+ # the honest thing here is to say which option fits this host and let the+ # operator choose. `make up` stays correct on every one of them.+ gpu_advice=""+ case "$(uname -s)" in+ Darwin)+ if [ "$(uname -m)" = "arm64" ]; then+ # Docker Desktop cannot pass Metal into a Linux container. No toolkit+ # changes that, so pointing a Mac at `make up-gpu` would waste an+ # afternoon.+ if command -v ollama >/dev/null 2>&1; then+ gpu_advice="Apple Silicon: a native Ollama is installed and uses Metal — \`make up-host-llm\` to use it"+ else+ gpu_advice="Apple Silicon: containers get no GPU here. \`brew install ollama\` then \`make up-host-llm\` for Metal, or stay on CPU"+ fi+ fi+ ;;+ Linux)+ if command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi -L >/dev/null 2>&1; then+ if docker info --format '{{json .Runtimes}}' 2>/dev/null | grep -q nvidia; then+ gpu_advice="NVIDIA GPU and container toolkit both present — \`make up-gpu\` will use it"+ else+ gpu_advice="NVIDIA GPU present but the container toolkit is not installed — see \`python3 scripts/check_gpu_runtime.py\`"+ fi+ fi+ ;;+ esac+ if [ -n "$gpu_advice" ]; then+ # , not : CPU is a supported configuration and the default, so+ # a host with no GPU is not a problem to be fixed.+ pass "$gpu_advice"+ fi+# ── 2. Ports ────────────────────────────────────────────────────────────────head2 "Ports"port_busy() {@@ -236,6 +270,17 @@ for spec in "5432 postgres 5432" "6379 redis 6379" "9092 kafka 9092" \# Already remapped. The canonical port being busy is then irrelevant, and# failing on it would send the operator to fix something that is working.pass "aisoc $owner is published on $ours (not the default $port)"+ elif [ "$owner" = "ollama" ] && port_busy "$port"; then+ # An Ollama already on 11434 is an asset, not a conflict, and this used to+ # tell the operator to stop it. On a Mac that Ollama is the *only* one with+ # a GPU -- Docker cannot pass Metal into a container -- so the advice was to+ # switch off the fast model in favour of a slow one.+ #+ # `make up` still works either way: resolve_port_conflicts.py republishes+ # the bundled Ollama somewhere free. It is just rarely what this operator+ # wants, so this is a warning with a better option rather than a failure.+ warn "port $port is held by $(port_holder "$port") — you already run Ollama" \+ "use it instead of starting a second one: 'make up-host-llm'. Or keep both: 'make up' publishes the bundled one on a free port."elif port_busy "$port"; thenfail "port $port is held by $(port_holder "$port") — aisoc $owner needs it" \"stop it, or change the host port in docker-compose.yml. A docker-compose.override.yml must use 'ports: !override' — a plain override appends and leaves $port published."diff --git a/scripts/mypy_baseline.json b/scripts/mypy_baseline.jsonindex db764970c..a141b6f4b 100644--- a/scripts/mypy_baseline.json+++ b/scripts/mypy_baseline.json@@ -322,6 +322,10 @@}},"services/api": {+ "app/_vendor/ssrf_guard.py": {+ "attr-defined": 6,+ "union-attr": 1+ },"app/api/v1/endpoints/identity_timeline.py": {"assignment": 1},diff --git a/scripts/sync_vendored_ssrf_guard.py b/scripts/sync_vendored_ssrf_guard.pynew file mode 100644index 000000000..87ad19f1d--- /dev/null+++ b/scripts/sync_vendored_ssrf_guard.py@@ -0,0 +1,91 @@+"""Keep `services/api/app/_vendor/ssrf_guard.py` byte-identical to the agents copy.++Why the API needs this one and not `destinations.py::_guard_url`+----------------------------------------------------------------+`POST /api/v1/llm/credentials/test` makes an outbound call to a base URL the+tenant supplied, so it needs an SSRF guard. The API already has one, and it is+the wrong shape for this: `_guard_url` in `app/services/destinations.py`+rejects every private and loopback address outright, which is correct for a+webhook and would refuse the `local-ollama`, `local-vllm` and `local-litellm`+providers that `migrations/038_tenant_llm_credentials.sql`'s own CHECK allows.+Those are the configurations this endpoint exists to serve.++`validate_outbound_url(url, allow_private=True)` is the shape that fits: it+permits a private host while still rejecting loopback and link-local, so the+cloud-metadata endpoint stays blocked even when private addresses are allowed.++Run modes+---------+* ``python scripts/sync_vendored_ssrf_guard.py`` — copy source → vendored.+* ``python scripts/sync_vendored_ssrf_guard.py --check`` — fail (exit 1) if the+ vendored file is missing or differs from the source. CI uses this mode.++AiSOC — open-source AI Security Operations Center (MIT License)+Author: Beenu Arora <[email protected]>+"""++from __future__ import annotations++import argparse+import filecmp+import shutil+import sys+from pathlib import Path++# `scripts/` is on sys.path when this file is run as a program, but not when a+# test loads it by path with importlib. gate_toolkit sits beside it either way.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()+SOURCE_FILE = REPO_ROOT / "services" / "agents" / "app" / "playbook" / "ssrf_guard.py"+VENDORED_FILE = REPO_ROOT / "services" / "api" / "app" / "_vendor" / "ssrf_guard.py"+++def _check() -> int:+ if not SOURCE_FILE.is_file():+ print(f"FAIL: source file missing: {SOURCE_FILE}", file=sys.stderr)+ return 1+ if not VENDORED_FILE.is_file():+ print(f"FAIL: vendored file missing: {VENDORED_FILE}", file=sys.stderr)+ return 1+ if not filecmp.cmp(SOURCE_FILE, VENDORED_FILE, shallow=False):+ print(+ "FAIL: vendored ssrf_guard.py is out of sync with source.\n"+ f" Source: {SOURCE_FILE.relative_to(REPO_ROOT)}\n"+ f" Vendored: {VENDORED_FILE.relative_to(REPO_ROOT)}\n\n"+ "Re-run: python scripts/sync_vendored_ssrf_guard.py",+ file=sys.stderr,+ )+ return 1+ print("OK: vendored ssrf_guard.py matches source.")+ return 0+++def _sync() -> int:+ if not SOURCE_FILE.is_file():+ print(f"FAIL: source file missing: {SOURCE_FILE}", file=sys.stderr)+ return 1+ VENDORED_FILE.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(SOURCE_FILE, VENDORED_FILE)+ print(f"copied {SOURCE_FILE.relative_to(REPO_ROOT)} → {VENDORED_FILE.relative_to(REPO_ROOT)}")+ print("\nDone. Don't forget to commit services/api/app/_vendor/ssrf_guard.py.")+ return 0+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--check",+ action="store_true",+ help="Fail with a non-zero exit code if the vendored file is out of sync.",+ )+ args = parser.parse_args()+ return _check() if args.check else _sync()+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/api/app/_vendor/ssrf_guard.py b/services/api/app/_vendor/ssrf_guard.pynew file mode 100644index 000000000..e22b82d46--- /dev/null+++ b/services/api/app/_vendor/ssrf_guard.py@@ -0,0 +1,243 @@+"""+SSRF guard for playbook outbound HTTP steps.++Playbooks let analysts configure ``http`` and ``notify`` steps that make+outbound HTTP requests to arbitrary URLs. Without validation, a playbook+author can target cloud instance metadata services (e.g. AWS+``169.254.169.254``, GCP ``metadata.google.internal``), loopback / private+RFC1918 addresses, or non-HTTP schemes like ``file://`` — a classic+Server-Side Request Forgery (SSRF) class of bug.++This module provides :func:`validate_outbound_url`, called by playbook step+handlers before they hand a URL to ``httpx``. It rejects:++* Schemes other than ``http`` / ``https`` (overridable via+ ``AISOC_SSRF_ALLOWED_SCHEMES``).+* URLs with userinfo (``http://user:pw@host/...``) — these are a common+ credential-smuggling and host-spoofing vector.+* Hostnames or IP literals that resolve to loopback, link-local, private,+ reserved, unspecified, or multicast ranges.+* A blocklist of well-known cloud metadata endpoints (AWS, GCP, Azure,+ Alibaba, Oracle) even if their hostnames happen to resolve to a public IP.+* Hostnames where *any* of the returned addresses is unsafe (defence in+ depth against DNS records that mix one public and one private answer).++Operators can:++* Set ``AISOC_SSRF_ALLOW_PRIVATE=1`` to relax the **private-range** check+ for on-prem deployments where playbooks must reach internal services.+ It does not relax loopback, and this header used to say it did —+ directly contradicting :func:`_is_disallowed_address`'s own docstring+ two hundred lines below, which has always said loopback is rejected+ either way. The code is the correct half: a playbook that can reach+ ``127.0.0.1`` can reach every unauthenticated service on the host+ running the engine, which is a larger hole than the one the flag+ exists to open. Link-local, multicast, reserved, unspecified and+ cloud-metadata literals are likewise always rejected.+* Set ``AISOC_SSRF_EXTRA_BLOCKED_HOSTS=foo.internal,bar.svc`` to extend+ the metadata host blocklist.++Failures raise :class:`SSRFError`, which propagates up to the engine and+marks the step as failed via the normal exception path.+"""++from __future__ import annotations++import ipaddress+import os+import socket+from urllib.parse import urlsplit+++class SSRFError(ValueError):+ """Raised when an outbound URL is blocked by the SSRF guard."""+++# ---------------------------------------------------------------------------+# Static blocklists+# ---------------------------------------------------------------------------++# Hostnames that must never be reached regardless of DNS resolution, e.g.+# operators sometimes wire ``metadata.google.internal`` to a public proxy.+# Comparison is case-insensitive against the URL's hostname (no port).+_DEFAULT_BLOCKED_HOSTS: frozenset[str] = frozenset(+ {+ # AWS / Alibaba IMDS literal+ "169.254.169.254",+ # GCP IMDS+ "metadata.google.internal",+ "metadata",+ # Azure IMDS — its IP literal is the same as AWS; hostname forms vary.+ "metadata.azure.com",+ # Alibaba Cloud+ "100.100.100.200",+ # Oracle Cloud Infrastructure+ "169.254.169.254.nip.io",+ }+)++_DEFAULT_ALLOWED_SCHEMES: frozenset[str] = frozenset({"http", "https"})+++def _env_set(name: str) -> frozenset[str]:+ """Read a comma-separated env var into a lowercase frozenset."""+ raw = os.getenv(name, "") or ""+ return frozenset(part.strip().lower() for part in raw.split(",") if part.strip())+++def _allowed_schemes() -> frozenset[str]:+ extra = _env_set("AISOC_SSRF_ALLOWED_SCHEMES")+ return extra or _DEFAULT_ALLOWED_SCHEMES+++def _blocked_hosts() -> frozenset[str]:+ return _DEFAULT_BLOCKED_HOSTS | _env_set("AISOC_SSRF_EXTRA_BLOCKED_HOSTS")+++def _allow_private_by_default() -> bool:+ return os.getenv("AISOC_SSRF_ALLOW_PRIVATE", "").strip().lower() in {"1", "true", "yes"}+++# ---------------------------------------------------------------------------+# IP classification+# ---------------------------------------------------------------------------+++def _is_disallowed_address(ip: ipaddress._BaseAddress, *, allow_private: bool) -> tuple[bool, str]:+ """Return ``(blocked, reason)`` for an IP address.++ When ``allow_private`` is True we still reject loopback, link-local,+ unspecified, multicast, and reserved addresses — only the+ private/RFC1918 + ULA bands are loosened.+ """+ if ip.is_loopback:+ return True, "loopback address"+ if ip.is_link_local:+ return True, "link-local address (cloud metadata range)"+ if ip.is_unspecified:+ return True, "unspecified address"+ if ip.is_multicast:+ return True, "multicast address"+ if ip.is_reserved:+ return True, "reserved address"+ # Block IPv4-mapped/IPv4-compatible IPv6 against private v4 ranges.+ if isinstance(ip, ipaddress.IPv6Address):+ mapped = getattr(ip, "ipv4_mapped", None)+ if mapped is not None:+ return _is_disallowed_address(mapped, allow_private=allow_private)+ if not allow_private and ip.is_private:+ return True, "private/RFC1918 address"+ return False, ""+++def _coerce_ip(value: str) -> ipaddress._BaseAddress | None:+ """Try to parse ``value`` as an IP address (v4 or v6), return None if not."""+ try:+ return ipaddress.ip_address(value)+ except ValueError:+ return None+++def _resolve_host_addresses(host: str) -> list[ipaddress._BaseAddress]:+ """Resolve ``host`` via ``getaddrinfo`` and return all unique IP objects.++ Raises :class:`SSRFError` if the host cannot be resolved.+ """+ try:+ infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)+ except OSError as exc:+ raise SSRFError(f"could not resolve hostname {host!r}: {exc}") from exc++ addrs: list[ipaddress._BaseAddress] = []+ seen: set[str] = set()+ for info in infos:+ sockaddr = info[4]+ addr_str = sockaddr[0] if sockaddr else ""+ # IPv6 sockaddrs can include zone IDs ("fe80::1%eth0"); strip them.+ addr_str = addr_str.split("%", 1)[0]+ if not addr_str or addr_str in seen:+ continue+ seen.add(addr_str)+ ip = _coerce_ip(addr_str)+ if ip is not None:+ addrs.append(ip)+ if not addrs:+ raise SSRFError(f"hostname {host!r} resolved to no usable addresses")+ return addrs+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++def validate_outbound_url(url: str, *, allow_private: bool | None = None) -> str:+ """Validate ``url`` for outbound HTTP calls from playbook steps.++ Parameters+ ----------+ url:+ The candidate URL string.+ allow_private:+ Override the env-driven default. ``True`` permits private/RFC1918+ addresses (still blocks loopback, link-local, metadata literals,+ and explicit blocklist entries). ``None`` falls back to+ ``AISOC_SSRF_ALLOW_PRIVATE``.++ Returns+ -------+ str+ The original URL on success.++ Raises+ ------+ SSRFError+ If the URL is blocked for any reason.+ """+ if not isinstance(url, str) or not url.strip():+ raise SSRFError("URL is empty")++ try:+ parts = urlsplit(url.strip())+ except ValueError as exc:+ raise SSRFError(f"could not parse URL: {exc}") from exc++ scheme = (parts.scheme or "").lower()+ if scheme not in _allowed_schemes():+ raise SSRFError(f"scheme {scheme!r} is not allowed (must be one of {sorted(_allowed_schemes())})")++ # Reject userinfo to avoid credential smuggling and host-confusion attacks.+ if parts.username or parts.password:+ raise SSRFError("URL must not include userinfo (user:password@host)")++ host = (parts.hostname or "").strip().lower()+ if not host:+ raise SSRFError("URL has no hostname")++ # Explicit blocklist takes precedence over IP / DNS checks.+ blocked = _blocked_hosts()+ if host in blocked:+ raise SSRFError(f"hostname {host!r} is on the SSRF blocklist (cloud metadata or operator-blocked)")++ if allow_private is None:+ allow_private = _allow_private_by_default()++ # If host is an IP literal, validate it directly.+ literal_ip = _coerce_ip(host)+ if literal_ip is not None:+ blocked_flag, reason = _is_disallowed_address(literal_ip, allow_private=allow_private)+ if blocked_flag:+ raise SSRFError(f"host {host!r} is blocked: {reason}")+ return url++ # Otherwise, resolve the hostname and validate every returned address.+ addresses = _resolve_host_addresses(host)+ for ip in addresses:+ blocked_flag, reason = _is_disallowed_address(ip, allow_private=allow_private)+ if blocked_flag:+ raise SSRFError(f"hostname {host!r} resolves to a blocked address {ip} ({reason})")++ return url+++__all__ = ["SSRFError", "validate_outbound_url"]diff --git a/services/api/app/api/v1/endpoints/llm_credentials.py b/services/api/app/api/v1/endpoints/llm_credentials.pyindex ac4837f1e..36f6143c7 100644--- a/services/api/app/api/v1/endpoints/llm_credentials.py+++ b/services/api/app/api/v1/endpoints/llm_credentials.py@@ -61,6 +61,7 @@ from app.api.v1.deps import AuthUser, DBSession, require_permissionfrom app.models.llm_credential import TenantLlmCredentialfrom app.security.credential_vault import CredentialVaultError, get_vaultfrom app.services.audit import emit_audit+from app.services.llm_credential_probe import ProbeResult, probe_credentiallogger = logging.getLogger(__name__)@@ -433,3 +434,90 @@ async def delete_llm_credential("provider": existing.provider,},)+++# --------------------------------------------------------- test connection+++class LlmCredentialTestResult(BaseModel):+ """What a real call to the configured provider did.++ Four outcomes, and `unverified` is one of them on purpose: an air-gapped+ deployment refuses the egress rather than attempting it, and reporting that+ as a failure would send an operator to debug a credential that is fine.+ """++ outcome: Literal["ok", "refused", "unreachable", "unverified"]+ detail: str+ provider: str+ model: str | None = None+ latency_ms: int | None = None+++ # The router already carries `prefix="/llm/credentials"`, so this is the+ # bare suffix. It read "/credentials/test" and published+ # `/api/v1/llm/credentials/credentials/test` -- an endpoint reachable at+ # no URL anything calls. Thirteen tests passed throughout, because every+ # one of them called the probe function rather than the route.+ "/test",+ response_model=LlmCredentialTestResult,+ summary="Make one real call with this tenant's credential",+)+async def test_llm_credential(+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],+ db: DBSession,+) -> LlmCredentialTestResult:+ """Place one minimal completion and report what happened.++ There was no way to find out whether a saved key worked. The three routes+ above validate *shape* -- that the URL parses, that the provider/key/base+ combination is internally consistent -- and none of them talks to the+ provider, so an operator who pasted a revoked key learned about it when+ triage silently fell back to the deterministic path. That failure is quiet+ by design, which is exactly what makes it hard to attribute.++ `settings:write` rather than `settings:read`: this spends the tenant's+ money and touches an external service, which is not a read.+ """+ res = await db.execute(select(TenantLlmCredential).where(TenantLlmCredential.tenant_id == current_user.tenant_id))+ existing: TenantLlmCredential | None = res.scalar_one_or_none()++ if existing is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=(+ "No credential is configured for this tenant, so there is nothing to test. The platform is using its environment defaults."+ ),+ )++ api_key: str | None = None+ if existing.api_key_vault:+ try:+ api_key = get_vault().decrypt(existing.api_key_vault)+ except CredentialVaultError:+ # A key that cannot be decrypted is a real finding and not an+ # outage: it means the vault key rotated without this row being+ # re-encrypted, and triage is already falling back.+ return LlmCredentialTestResult(+ outcome="refused",+ detail=(+ "The stored key could not be decrypted. It was encrypted with a vault key "+ "this deployment no longer has; re-enter it to fix."+ ),+ provider=existing.provider,+ )++ result: ProbeResult = await probe_credential(+ provider=existing.provider,+ base_url=existing.base_url,+ model=existing.model,+ api_key=api_key,+ )+ return LlmCredentialTestResult(+ outcome=result.outcome,+ detail=result.detail,+ provider=existing.provider,+ model=result.model,+ latency_ms=result.latency_ms,+ )diff --git a/services/api/app/api/v1/endpoints/llm_status.py b/services/api/app/api/v1/endpoints/llm_status.pyindex a758b90e0..2968a17a8 100644--- a/services/api/app/api/v1/endpoints/llm_status.py+++ b/services/api/app/api/v1/endpoints/llm_status.py@@ -66,6 +66,7 @@ from app.core.airgap import is_host_allowed_for_airgapfrom app.core.config import settingsfrom app.models.llm_credential import TenantLlmCredentialfrom app.security.credential_vault import CredentialVaultError, get_vault+from app.services.llm_runtime import probe as probe_runtimefrom app.services.model_aliases import gateway_url, is_gateway_alias, resolve_api_keyrouter = APIRouter(prefix="/llm", tags=["llm"])@@ -394,10 +395,11 @@ async def tenant_llm_status(async def get_llm_status(user: AuthUser) -> dict[str, object]:"""Return the env-only LLM provider snapshot for this pod.- Intentionally **unauthenticated** and **env-only**, mirroring- ``GET /api/v1/airgap/status``: the response carries no secrets- (only ``key_set: bool``) and is safe for operator dashboards,- auditors, and k8s liveness probes.+ **Authenticated** -- the signature binds ``AuthUser`` and has for as long+ as this route has existed. The docstring used to say "intentionally+ unauthenticated", which was prose disagreeing with the code beneath it.++ **Env-only**: the response carries no secrets (only ``key_set: bool``).Tenant-aware callers (the web UI's "Deployment & AI" Settingspanel, the agents service's explain path) layer per-tenant BYOK@@ -408,3 +410,49 @@ async def get_llm_status(user: AuthUser) -> dict[str, object]:perform the merge client-side."""return llm_status()++[email protected]("/runtime", summary="Where the local model is actually running")+async def get_llm_runtime(user: AuthUser) -> dict[str, object]:+ """Ask Ollama whether the model is on a GPU or a CPU, and say so.++ Separate from ``/status`` deliberately. That route reports *configuration*+ -- which provider and model this pod is pointed at. This one reports+ *outcome*, which can differ: a GPU reservation is a request, and a model+ can still land on the CPU for want of VRAM or a usable driver. Reading the+ compose file back would report the intent and call it the result.++ Carries the commands that would change the answer, because the console+ cannot change it: switching the bundled Ollama onto a GPU means restarting+ that container with different compose arguments, which a web service must+ not be able to do.+ """+ report = await probe_runtime()+ report.options = _placement_options(report.placement)+ return report.as_dict()+++def _placement_options(placement: str) -> list[str]:+ """What an operator can do about the answer.++ Deliberately not host-specific: this runs inside a container and cannot see+ whether the *host* has an NVIDIA card. `make doctor` runs on the host and+ does know, so it gives the targeted recommendation; this lists what exists+ and lets the reader pick.+ """+ hosted = "Use a hosted provider instead: Settings -> Deployment & AI, or the setup wizard."+ if placement in {"cpu", "partial", "unknown"}:+ return [+ "NVIDIA GPU: `make up-gpu` (run `make doctor` to see whether this host has one).",+ "Apple Silicon: containers get no GPU; run Ollama natively and use `make up-host-llm`.",+ hosted,+ ]+ if placement == "unreachable":+ return [+ "If you use a hosted provider, this is expected and nothing is wrong.",+ "Otherwise check the model container: `docker compose ps ollama`.",+ hosted,+ ]+ if placement == "gpu":+ return [hosted]+ return [hosted]diff --git a/services/api/app/api/v1/endpoints/onboarding.py b/services/api/app/api/v1/endpoints/onboarding.pyindex 0c9c6afec..7175a4701 100644--- a/services/api/app/api/v1/endpoints/onboarding.py+++ b/services/api/app/api/v1/endpoints/onboarding.py@@ -121,6 +121,18 @@ async def onboarding_status("SELECT COUNT(*) FROM users WHERE tenant_id = CAST(:t AS uuid)",t=tenant_id,)+ # Derived from the tenant's own row like everything else here, so this step+ # cannot drift either. A disabled credential does not count: it is+ # configuration that is deliberately not in effect.+ byok = await _count(+ db,+ """+ SELECT COUNT(*) FROM tenant_llm_credentials+ WHERE tenant_id = CAST(:t AS uuid)+ AND enabled IS TRUE+ """,+ t=tenant_id,+ )# A connector that is only *configured* is not a connector that is# working, so "data arriving" is a separate step. Conflating them is@@ -156,6 +168,23 @@ async def onboarding_status(href="/alerts",detail=(f"{real_alerts} from your own sources" if real_alerts else "No alerts from a connected source yet"),),+ SetupStep(+ key="model",+ label="Choose where the AI runs",+ # A local model ships and runs, so this is never blocking -- which+ # is why it is `done` out of the box and the step is informational.+ # It exists because a first-run operator otherwise has no way to+ # learn that the bundled model is on CPU, that their GPU could be+ # used, or that their own provider is three fields away.+ done=True,+ why=(+ "A model ships with AiSOC and runs on CPU, so triage works out of the box. "+ "It is also the slowest option: a GPU or your own provider is usually "+ "faster, and both take one step."+ ),+ href=None,+ detail=("Using your own provider" if byok else "Using the bundled local model"),+ ),SetupStep(key="try",label="Or try it with sample data",diff --git a/services/api/app/services/llm_credential_probe.py b/services/api/app/services/llm_credential_probe.pynew file mode 100644index 000000000..81f7c0ea3--- /dev/null+++ b/services/api/app/services/llm_credential_probe.py@@ -0,0 +1,237 @@+"""Place one real call with a tenant's BYOK credential, and report what happened.++Why this exists+---------------+`GET`/`PUT`/`DELETE /api/v1/llm/credentials` validate *shape*: that the URL+parses, that the provider/key/base-URL combination is internally consistent.+None of them talks to the provider. So an operator who pasted a revoked key,+or pointed at a host that is not running, found out when triage silently fell+back to the deterministic path -- a failure that is quiet by design, which is+precisely what makes it hard to attribute to the key.++The guard, and why it is not the webhook one+--------------------------------------------+This makes an outbound request to a URL the tenant supplied, so it needs an+SSRF guard. The API already has one and it is the wrong shape:+`destinations.py::_guard_url` rejects every private and loopback address+outright. That is correct for a webhook and would refuse `local-ollama`,+`local-vllm` and `local-litellm` -- three of the seven providers migration 038+explicitly allows, and the ones most likely to be on a private address.++`validate_outbound_url(url, allow_private=True)` is the shape that fits: a+private host is permitted while loopback and link-local are still rejected, so+the cloud-metadata endpoint at 169.254.169.254 stays blocked *even though*+private addresses are allowed. Vendored from the agents service and held+byte-identical by `scripts/sync_vendored_ssrf_guard.py`.++Air-gap+-------+Checked before anything is dialled, and reported as `unverified` rather than+as a failure: an air-gapped deployment refusing egress is the posture working,+not a broken credential.+"""++from __future__ import annotations++import time+from dataclasses import dataclass+from typing import Literal++import httpx+import structlog++from app._vendor.ssrf_guard import SSRFError, validate_outbound_url+from app.core.airgap import AirgapViolation, enforce_airgap_for_url+from app.services.llm_safety import safe_chat_completions_request++logger = structlog.get_logger(__name__)++Outcome = Literal["ok", "refused", "unreachable", "unverified"]++#: Short. A human is waiting on this in a settings panel, and a provider that+#: takes longer than this to answer a one-token completion is not one triage+#: should be pointed at either.+PROBE_TIMEOUT_SECONDS = 15.0++#: Where each provider's chat-completions endpoint lives when the tenant did+#: not give a base URL. Only the hosted ones have a default; the local and+#: custom providers are required to supply one (migration 038's CHECK and+#: `_enforce_provider_invariants` both say so).+_DEFAULT_BASE: dict[str, str] = {+ "openai": "https://api.openai.com/v1",+ "anthropic": "https://api.anthropic.com/v1",+}++#: A model has to be named to complete anything. These are the cheapest+#: generally-available model per provider, used only when the tenant left the+#: field blank -- the probe says which one it used so the result is readable.+_FALLBACK_MODEL: dict[str, str] = {+ "openai": "gpt-4o-mini",+ "anthropic": "claude-3-5-haiku-20241022",+ "azure-openai": "gpt-4o-mini",+ "local-ollama": "llama3.2:3b-instruct-q4_K_M",+ "local-vllm": "default",+ "local-litellm": "aisoc-triage",+ "custom": "default",+}+++@dataclass+class ProbeResult:+ outcome: Outcome+ detail: str+ model: str | None = None+ latency_ms: int | None = None+++def _base_url_for(provider: str, base_url: str | None) -> str | None:+ return (base_url or _DEFAULT_BASE.get(provider) or "").rstrip("/") or None+++def _from_status(response: httpx.Response, model: str, latency_ms: int) -> ProbeResult:+ """Turn the provider's refusal into something an operator can act on."""+ code = response.status_code++ if code in (401, 403):+ return ProbeResult(+ outcome="refused",+ detail=f"The provider rejected the credential (HTTP {code}). Check the key.",+ model=model,+ latency_ms=latency_ms,+ )+ if code == 404:+ return ProbeResult(+ outcome="refused",+ detail=(+ f"The provider answered 404 for model '{model}'. The key may be fine and the "+ "model name wrong, or not available to this account."+ ),+ model=model,+ latency_ms=latency_ms,+ )+ if code == 429:+ # Reached it, and authenticated enough to be counted against a quota,+ # which answers the question being asked.+ return ProbeResult(+ outcome="ok",+ detail="Reached the provider and was rate-limited, so the credential works.",+ model=model,+ latency_ms=latency_ms,+ )+ body = (response.text or "")[:200].replace("\n", " ")+ return ProbeResult(+ outcome="refused",+ detail=f"The provider answered HTTP {code}: {body}",+ model=model,+ latency_ms=latency_ms,+ )+++async def probe_credential(+ *,+ provider: str,+ base_url: str | None,+ model: str | None,+ api_key: str | None,+) -> ProbeResult:+ """One minimal completion. Never raises; every failure is a reported state."""+ resolved_base = _base_url_for(provider, base_url)+ if not resolved_base:+ return ProbeResult(+ outcome="refused",+ detail=f"provider '{provider}' has no base URL configured and no default for it.",+ )++ resolved_model = model or _FALLBACK_MODEL.get(provider) or "default"++ # Air-gap first, before anything is dialled, and through the same function+ # every other outbound call uses -- so this cannot drift from what the+ # deployment would actually permit, and it is a no-op when the flag is off.+ #+ # Called rather than reading `settings.AISOC_AIRGAPPED` here: a module-level+ # reference to the settings object goes stale the moment anything reloads+ # `app.core.config`, and a security check that silently stops applying is+ # the worst kind. `enforce_airgap_for_url` reads the flag at call time.+ try:+ enforce_airgap_for_url(resolved_base)+ except AirgapViolation as exc:+ return ProbeResult(+ outcome="unverified",+ detail=(+ f"This deployment is air-gapped, so the call was not attempted: {exc} That is the policy working, not a bad credential."+ ),+ model=resolved_model,+ )++ try:+ # `allow_private=True` on purpose: see the module docstring. Loopback+ # and link-local are still rejected, so metadata stays unreachable.+ validate_outbound_url(resolved_base, allow_private=True)+ except SSRFError as exc:+ return ProbeResult(+ outcome="refused",+ detail=f"The base URL was refused: {exc}",+ model=resolved_model,+ )++ # Anthropic authenticates with `x-api-key` rather than a bearer token and+ # wants its API version pinned. The helper always sets `Authorization`,+ # which Anthropic ignores.+ extra_headers: dict[str, str] = {}+ if provider == "anthropic":+ extra_headers = {"x-api-key": api_key or "", "anthropic-version": "2023-06-01"}++ url = f"{resolved_base}/messages" if provider == "anthropic" else f"{resolved_base}/chat/completions"++ started = time.monotonic()+ try:+ # Through `safe_chat_completions_request`, not a raw `client.post`.+ #+ # The prompt here is a constant carrying no untrusted input, so the+ # contract has nothing to reject -- but the rule is that *every* call+ # to a completions endpoint goes through it, and a call site that+ # argues its way out is how the next one, with a real prompt, gets+ # written the same way. `services/agents/tests/test_llm_contract_no_bypass.py`+ # enforces this and caught the first version of this function.+ #+ # One token: a reachability and authorisation check, not a capability+ # evaluation, and a longer generation bills the tenant for output+ # nobody reads.+ await safe_chat_completions_request(+ api_key=api_key or "",+ model=resolved_model,+ messages=[{"role": "user", "content": "ping"}],+ url=url,+ timeout=PROBE_TIMEOUT_SECONDS,+ extra_headers=extra_headers or None,+ max_tokens=1,+ )+ except httpx.HTTPStatusError as exc:+ # The helper calls `raise_for_status`, and the status code is exactly+ # what separates "the key is wrong" from "the model name is wrong"+ # from "you were rate-limited, so it works".+ return _from_status(exc.response, resolved_model, int((time.monotonic() - started) * 1000))+ except httpx.TimeoutException:+ return ProbeResult(+ outcome="unreachable",+ detail=f"{resolved_base} did not answer within {PROBE_TIMEOUT_SECONDS:.0f}s.",+ model=resolved_model,+ )+ except Exception as exc: # noqa: BLE001 - every failure is a state+ logger.info("llm_probe.unreachable", provider=provider, error=type(exc).__name__)+ return ProbeResult(+ outcome="unreachable",+ detail=f"Could not reach {resolved_base} ({type(exc).__name__}).",+ model=resolved_model,+ )++ latency_ms = int((time.monotonic() - started) * 1000)+ return ProbeResult(+ outcome="ok",+ detail=f"Completed a one-token request against '{resolved_model}' in {latency_ms} ms.",+ model=resolved_model,+ latency_ms=latency_ms,+ )+++__all__ = ["Outcome", "ProbeResult", "probe_credential"]diff --git a/services/api/app/services/llm_runtime.py b/services/api/app/services/llm_runtime.pynew file mode 100644index 000000000..3f0393234--- /dev/null+++ b/services/api/app/services/llm_runtime.py@@ -0,0 +1,209 @@+"""What the local model is *actually* running on, asked rather than assumed.++Why this asks Ollama instead of reading configuration+-----------------------------------------------------+`infra/compose/docker-compose.gpu.yml` reserves an NVIDIA device, but a+reservation is a request. The model can still land on the CPU -- too little+VRAM for the layer count, a driver the runtime cannot use, another process+holding the card. Reading the compose file back would report the intent and+call it the outcome.++Ollama already knows, and publishes it. `GET /api/ps` lists each loaded model+with `size` and `size_vram`, and the ratio between them is the answer.+Verified against the pinned `ollama/ollama:0.6.7` image: a model loaded in a+container on an Apple Silicon host reports `size_vram: 0` against+`size: 820601088`, correctly CPU, while the same host's *native* Ollama+reports `size_vram == size` because it reaches Metal. Those are the two+configurations this feature exists to tell apart, and the field distinguishes+them.++The four states, and why "unknown" is one of them+-------------------------------------------------+`/api/ps` lists models that are loaded **right now**. Ollama unloads after a+few minutes idle, so an empty list is the ordinary state of a stack nobody has+asked anything of yet. It means *we have not been told*, which is not the same+as CPU -- and answering CPU there would be a fabricated verdict about the thing+an operator is deciding on.++A missing `size_vram` key is treated the same way, so a future Ollama that+renames or drops it degrades to "unknown" rather than silently reporting every+deployment as CPU.+"""++from __future__ import annotations++import os+from dataclasses import dataclass, field+from typing import Any, Literal++import httpx+import structlog++logger = structlog.get_logger(__name__)++Placement = Literal["gpu", "partial", "cpu", "unknown", "unreachable", "not_local"]++#: Where the bundled Ollama lives on the compose network. `make up-host-llm`+#: overrides this to the host's own Ollama, which is the configuration where+#: the answer is most likely to be "gpu" on a Mac.+DEFAULT_OLLAMA_URL = "http://ollama:11434"++#: Short. This runs behind a wizard step a human is waiting on, and a slow+#: probe would make the page feel broken. A timeout is reported as+#: `unreachable`, which is honest and actionable.+PROBE_TIMEOUT_SECONDS = 4.0+++def ollama_url() -> str:+ """Where to ask. `AISOC_OLLAMA_URL` is set by the host-llm overlay."""+ return (os.getenv("AISOC_OLLAMA_URL") or DEFAULT_OLLAMA_URL).rstrip("/")+++@dataclass+class RuntimeReport:+ """What is running, where, and how sure we are."""++ placement: Placement+ detail: str+ base_url: str+ model: str | None = None+ vram_bytes: int | None = None+ total_bytes: int | None = None+ #: The commands that would change the answer, for the surface that shows it.+ #: Populated by the endpoint, which knows the host; this module only knows+ #: what Ollama said.+ options: list[str] = field(default_factory=list)++ def as_dict(self) -> dict[str, Any]:+ out: dict[str, Any] = {+ "placement": self.placement,+ "detail": self.detail,+ "base_url": self.base_url,+ "options": self.options,+ }+ # Absent rather than null, matching the convention the performance+ # results follow: an unmeasured quantity carries no value key, so no+ # renderer downstream can turn an absence into `0`.+ if self.model is not None:+ out["model"] = self.model+ if self.vram_bytes is not None:+ out["vram_bytes"] = self.vram_bytes+ if self.total_bytes is not None:+ out["total_bytes"] = self.total_bytes+ return out+++def classify(models: list[dict[str, Any]]) -> RuntimeReport:+ """Turn Ollama's `/api/ps` payload into a verdict.++ Pure, so the states can be tested without a container.+ """+ base = ollama_url()++ if not models:+ return RuntimeReport(+ placement="unknown",+ detail=(+ "No model is loaded right now, so Ollama cannot say where one would run. "+ "Ollama unloads after a few minutes idle; run a triage and check again."+ ),+ base_url=base,+ )++ # The largest resident model is the one that matters: it is what a triage+ # will use and what a GPU would have to hold.+ model = max(models, key=lambda m: int(m.get("size") or 0))+ name = str(model.get("name") or model.get("model") or "unknown")+ total = int(model.get("size") or 0)++ if "size_vram" not in model:+ return RuntimeReport(+ placement="unknown",+ detail=(+ f"Ollama is serving {name} but did not report VRAM usage, so where it runs cannot be determined from this version's API."+ ),+ base_url=base,+ model=name,+ total_bytes=total or None,+ )++ vram = int(model.get("size_vram") or 0)++ if vram <= 0:+ return RuntimeReport(+ placement="cpu",+ detail=f"{name} is running entirely on the CPU.",+ base_url=base,+ model=name,+ vram_bytes=0,+ total_bytes=total or None,+ )++ if total and vram < total:+ pct = round(100.0 * vram / total)+ return RuntimeReport(+ placement="partial",+ detail=(+ f"{name} is split: {pct}% of it is in VRAM and the rest is on the CPU. "+ "A card with more memory, or a smaller model, would hold all of it."+ ),+ base_url=base,+ model=name,+ vram_bytes=vram,+ total_bytes=total,+ )++ return RuntimeReport(+ placement="gpu",+ detail=f"{name} is running on the GPU ({_gib(vram)} in VRAM).",+ base_url=base,+ model=name,+ vram_bytes=vram,+ total_bytes=total or None,+ )+++def _gib(n: int) -> str:+ return f"{n / (1024**3):.1f} GB"+++async def probe() -> RuntimeReport:+ """Ask the local Ollama what it is doing.++ Never raises. Every failure becomes a reported state, because this is+ rendered on a setup page and an exception there is a blank panel with no+ explanation.+ """+ base = ollama_url()+ try:+ async with httpx.AsyncClient(timeout=PROBE_TIMEOUT_SECONDS) as client:+ resp = await client.get(f"{base}/api/ps")+ except Exception as exc: # noqa: BLE001 - every failure is a state, not a crash+ logger.info("llm_runtime.unreachable", base_url=base, error=type(exc).__name__)+ return RuntimeReport(+ placement="unreachable",+ detail=(f"No Ollama answered at {base}. If this deployment uses a hosted provider that is expected and nothing is wrong."),+ base_url=base,+ )++ if resp.status_code != 200:+ return RuntimeReport(+ placement="unreachable",+ detail=f"Ollama at {base} answered HTTP {resp.status_code}.",+ base_url=base,+ )++ try:+ payload = resp.json()+ except ValueError:+ return RuntimeReport(+ placement="unknown",+ detail=f"Ollama at {base} returned a response that is not JSON.",+ base_url=base,+ )++ models = payload.get("models")+ return classify(models if isinstance(models, list) else [])+++__all__ = ["Placement", "RuntimeReport", "classify", "ollama_url", "probe"]diff --git a/services/api/tests/test_llm_credential_probe.py b/services/api/tests/test_llm_credential_probe.pynew file mode 100644index 000000000..99aeef997--- /dev/null+++ b/services/api/tests/test_llm_credential_probe.py@@ -0,0 +1,246 @@+"""A saved LLM credential can be tested, and the test cannot be used to reach inward.++What this closes+----------------+The three credential routes validate *shape* -- that the URL parses, that the+provider/key/base combination is internally consistent -- and none of them+talks to the provider. So an operator who pasted a revoked key found out when+triage silently fell back to the deterministic path, which is quiet by design+and therefore hard to attribute to the key.++The guard, and why the obvious one is wrong+-------------------------------------------+This endpoint dials a URL the tenant supplied. The API's existing+`destinations.py::_guard_url` rejects every private and loopback address, which+is right for a webhook and would refuse `local-ollama`, `local-vllm` and+`local-litellm` -- three of the seven providers migration 038 allows, and the+ones most likely to sit on a private address. Using it here would break the+feature for exactly the deployments it is for.++So the vendored `validate_outbound_url(..., allow_private=True)` is used+instead, and the tests below pin both halves of what that buys: a private host+is reachable, and the cloud-metadata address is still refused *even though*+private addresses are allowed. The second is the one that matters -- a guard+that allowed private and stopped there would read as working.+"""++from __future__ import annotations++import pytest+++class TestTheGuardAllowsLocalProvidersAndStillBlocksMetadata:+ @pytest.mark.asyncio+ async def test_a_private_host_is_permitted(self) -> None:+ """`local-ollama` on a LAN address is the configuration this exists+ for. A probe that refused it would be refusing the common case."""+ from app._vendor.ssrf_guard import validate_outbound_url++ # Does not raise.+ validate_outbound_url("http://192.168.1.50:11434/v1", allow_private=True)++ @pytest.mark.parametrize(+ "url",+ [+ "http://169.254.169.254/latest/meta-data/",+ "http://169.254.169.254/v1",+ ],+ )+ @pytest.mark.asyncio+ async def test_cloud_metadata_is_refused_even_with_private_allowed(self, url: str) -> None:+ """The half that makes `allow_private=True` safe. Link-local stays+ rejected, so the metadata endpoint is unreachable through this route."""+ from app._vendor.ssrf_guard import SSRFError, validate_outbound_url++ with pytest.raises(SSRFError):+ validate_outbound_url(url, allow_private=True)++ @pytest.mark.asyncio+ async def test_loopback_is_refused(self) -> None:+ """From inside the API container, loopback is the container itself."""+ from app._vendor.ssrf_guard import SSRFError, validate_outbound_url++ with pytest.raises(SSRFError):+ validate_outbound_url("http://127.0.0.1:11434/v1", allow_private=True)++ @pytest.mark.asyncio+ async def test_the_probe_reports_a_refusal_rather_than_raising(self) -> None:+ """A guard rejection must become a reported outcome. An exception here+ would surface as a 500 on a settings page, which tells the operator+ nothing about their own URL."""+ from app.services.llm_credential_probe import probe_credential++ result = await probe_credential(+ provider="custom",+ base_url="http://169.254.169.254/v1",+ model="m",+ api_key="k",+ )++ assert result.outcome == "refused"+ assert "refused" in result.detail.lower()+++class TestAirGapIsNotAFailure:+ @pytest.mark.asyncio+ async def test_a_blocked_host_reports_unverified(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """An air-gapped deployment refusing egress is the posture working.+ Reporting it as `refused` would send an operator to debug a credential+ that is fine."""+ # Patched where it is read, at call time: a module-level settings+ # reference goes stale if anything reloads app.core.config, which is+ # how this test passed alone and failed in the suite.+ from app.core import airgap as airgap_mod+ from app.services.llm_credential_probe import probe_credential++ monkeypatch.setattr(airgap_mod.settings, "AISOC_AIRGAPPED", True, raising=False)++ result = await probe_credential(+ provider="openai",+ base_url=None,+ model="gpt-4o-mini",+ api_key="sk-test",+ )++ assert result.outcome == "unverified"+ assert "air-gapped" in result.detail.lower()+ assert "not attempted" in result.detail.lower()++ @pytest.mark.asyncio+ async def test_a_local_host_still_runs_under_airgap(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """The negative control. Air-gap permits a private model host -- that+ is the whole point of running one -- so the probe must not refuse+ every call just because the flag is set."""+ # Patched where it is read, at call time: a module-level settings+ # reference goes stale if anything reloads app.core.config, which is+ # how this test passed alone and failed in the suite.+ from app.core import airgap as airgap_mod+ from app.services.llm_credential_probe import probe_credential++ monkeypatch.setattr(airgap_mod.settings, "AISOC_AIRGAPPED", True, raising=False)++ # A bare hostname with no dots is a compose/k8s service name, which+ # `_is_private_address` treats as internal by definition -- and that is+ # exactly what `local-ollama` looks like on a real air-gapped stack.+ result = await probe_credential(+ provider="local-ollama",+ base_url="http://ollama:11434/v1",+ model="llama3.2:3b",+ api_key=None,+ )++ # It will not reach that host from a test runner, but it must have+ # *tried* -- an `unverified` here would mean air-gap blocked a local+ # provider, which would make air-gapped BYOK impossible.+ assert result.outcome != "unverified", result.detail+++class TestItNamesWhatWentWrong:+ @pytest.mark.parametrize(+ ("status_code", "expected"),+ [(401, "refused"), (403, "refused"), (404, "refused"), (429, "ok"), (500, "refused")],+ )+ @pytest.mark.asyncio+ async def test_each_provider_answer_maps_to_an_outcome(self, status_code: int, expected: str, monkeypatch: pytest.MonkeyPatch) -> None:+ """429 is `ok` deliberately: being rate-limited means the request+ reached the provider and was authenticated enough to be counted, which+ is the question being asked."""+ import httpx+ from app.services import llm_credential_probe as probe_mod++ class _Client:+ def __init__(self, *_: object, **__: object) -> None:+ """No setup; the stub exists to intercept the POST below."""++ async def __aenter__(self) -> _Client:+ return self++ async def __aexit__(self, *_: object) -> bool:+ return False++ async def post(self, *_: object, **__: object) -> httpx.Response:+ return httpx.Response(status_code, text="detail", request=httpx.Request("POST", "http://x"))++ monkeypatch.setattr(probe_mod.httpx, "AsyncClient", _Client)++ result = await probe_mod.probe_credential(+ provider="custom",+ base_url="http://192.168.1.50:11434/v1",+ model="m",+ api_key="k",+ )++ assert result.outcome == expected, result.detail++ @pytest.mark.asyncio+ async def test_a_404_says_the_model_might_be_the_problem(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """A key can be perfect and the model name wrong. Saying only+ "rejected" sends the operator to rotate a working key."""+ import httpx+ from app.services import llm_credential_probe as probe_mod++ class _Client:+ def __init__(self, *_: object, **__: object) -> None:+ """No setup; the stub exists to intercept the POST below."""++ async def __aenter__(self) -> _Client:+ return self++ async def __aexit__(self, *_: object) -> bool:+ return False++ async def post(self, *_: object, **__: object) -> httpx.Response:+ return httpx.Response(404, text="no such model", request=httpx.Request("POST", "http://x"))++ monkeypatch.setattr(probe_mod.httpx, "AsyncClient", _Client)++ result = await probe_mod.probe_credential(+ provider="custom",+ base_url="http://192.168.1.50:11434/v1",+ model="typo-model",+ api_key="k",+ )++ assert "typo-model" in result.detail+ assert "model name" in result.detail.lower()+++class TestTheRouteIsReachableAtTheUrlTheConsoleCalls:+ """Ask the app what it published, not what the decorator says.++ Every test above calls `probe_credential` directly, and all thirteen+ passed while the route was mounted at+ `/api/v1/llm/credentials/credentials/test` -- a doubled segment, because+ the decorator repeated a prefix the router already carried. The endpoint+ was reachable at no URL anything calls, and only+ `check_console_route_contract` noticed, by comparing the console's fetches+ against the real OpenAPI document.++ Read from `app.openapi()` rather than `app.routes`: on FastAPI 0.141.x+ `include_router` leaves an opaque object there and the `APIRoute` count is+ zero, so an enumeration silently compares nothing.+ """++ def test_it_is_published_where_the_client_asks_for_it(self) -> None:+ from app.main import app++ assert "/api/v1/llm/credentials/test" in app.openapi()["paths"]++ def test_no_segment_is_doubled(self) -> None:+ from app.main import app++ doubled = [p for p in app.openapi()["paths"] if "credentials/credentials" in p]++ assert not doubled, f"a router prefix is repeated in the decorator: {doubled}"++ def test_the_console_and_the_api_agree_on_the_url(self) -> None:+ """The two halves of the contract, compared directly. A client string+ and a server path that drift apart produce a 404 nobody owns."""+ from pathlib import Path++ from app.main import app++ client = (Path(__file__).resolve().parents[3] / "apps" / "web" / "src" / "lib" / "api.ts").read_text(encoding="utf-8")++ assert "/api/v1/llm/credentials/test" in client+ assert "/api/v1/llm/credentials/test" in app.openapi()["paths"]diff --git a/services/api/tests/test_llm_runtime_placement.py b/services/api/tests/test_llm_runtime_placement.pynew file mode 100644index 000000000..a1176a64a--- /dev/null+++ b/services/api/tests/test_llm_runtime_placement.py@@ -0,0 +1,159 @@+"""Where the model runs is asked, and an absent answer stays absent.++The states, and the one that matters most+-----------------------------------------+`GET /api/v1/llm/runtime` exists because a GPU reservation is a *request*: a+model can still land on the CPU for want of VRAM or a usable driver, so+reading the compose file back would report the intent and call it the outcome.+Ollama knows and publishes it on `/api/ps`.++The payloads below are not invented. They were captured from real Ollama+instances while building this:++* **CPU** -- the pinned `ollama/ollama:0.6.7` image running in a container on+ an Apple Silicon host, which reports `size_vram: 0` against a real `size`.+ That is the configuration `make up` produces on a Mac.+* **GPU** -- the same host's *native* Ollama 0.30.7, which reaches Metal and+ reports `size_vram == size`. That is what `make up-host-llm` produces.++Those two are the configurations this whole feature exists to tell apart, so+the fixtures are the two it was measured on.++**`unknown` is a state, not a fallback.** `/api/ps` lists models loaded *right+now*, and Ollama unloads after a few minutes idle, so an empty list is the+ordinary condition of a stack nobody has asked anything of. Answering "CPU"+there would be a fabricated verdict about the exact thing an operator is+deciding on.+"""++from __future__ import annotations++import pytest++# Captured from `ollama/ollama:0.6.7` in a container on Apple Silicon.+CPU_PAYLOAD = [+ {+ "name": "qwen2.5:0.5b",+ "model": "qwen2.5:0.5b",+ "size": 820601088,+ "size_vram": 0,+ "digest": "a8b0c515",+ "details": {"family": "qwen2", "quantization_level": "Q4_K_M"},+ }+]++# Captured from a native Ollama 0.30.7 on the same host, using Metal.+GPU_PAYLOAD = [+ {+ "name": "qwen2.5:0.5b",+ "model": "qwen2.5:0.5b",+ "size": 928755219,+ "size_vram": 928755219,+ "digest": "a8b0c515",+ "details": {"family": "qwen2", "quantization_level": "Q4_K_M"},+ }+]+++class TestTheFourStates:+ def test_nothing_loaded_is_unknown_not_cpu(self) -> None:+ """The state that must never be guessed."""+ from app.services.llm_runtime import classify++ report = classify([])++ assert report.placement == "unknown"+ assert "unloads" in report.detail or "not loaded" in report.detail.lower()+ # No fabricated measurement travels with a non-answer.+ assert report.vram_bytes is None+ assert "vram_bytes" not in report.as_dict()++ def test_a_containerised_model_on_a_mac_is_cpu(self) -> None:+ from app.services.llm_runtime import classify++ report = classify(CPU_PAYLOAD)++ assert report.placement == "cpu"+ assert report.vram_bytes == 0+ assert report.total_bytes == 820601088+ assert "CPU" in report.detail++ def test_a_native_metal_model_is_gpu(self) -> None:+ from app.services.llm_runtime import classify++ report = classify(GPU_PAYLOAD)++ assert report.placement == "gpu"+ assert report.vram_bytes == 928755219+ assert "GPU" in report.detail++ def test_a_split_model_is_partial_and_says_how_much(self) -> None:+ """A card too small for the layer count is the common half-measure, and+ reporting it as `gpu` would explain neither the latency nor the fix."""+ from app.services.llm_runtime import classify++ report = classify([{"name": "m", "size": 1000, "size_vram": 400}])++ assert report.placement == "partial"+ assert "40%" in report.detail+++class TestItDegradesHonestly:+ def test_a_missing_size_vram_is_unknown_not_cpu(self) -> None:+ """Guards against a future Ollama renaming or dropping the field.++ Defaulting a missing key to `0` would silently report every deployment+ as CPU, which is the shape of wrongness that is hardest to notice: it+ looks like a measurement.+ """+ from app.services.llm_runtime import classify++ report = classify([{"name": "m", "size": 1000}])++ assert report.placement == "unknown"+ assert report.vram_bytes is None++ def test_the_largest_resident_model_is_the_one_reported(self) -> None:+ """Two models can be resident. The big one is what a triage will use+ and what a GPU would have to hold."""+ from app.services.llm_runtime import classify++ report = classify(+ [+ {"name": "small", "size": 100, "size_vram": 100},+ {"name": "big", "size": 9000, "size_vram": 0},+ ]+ )++ assert report.model == "big"+ assert report.placement == "cpu"+++class TestTheEndpointOffersSomethingToDo:+ @pytest.mark.parametrize("placement", ["cpu", "partial", "unknown"])+ def test_a_cpu_answer_names_all_three_alternatives(self, placement: str) -> None:+ from app.api.v1.endpoints.llm_status import _placement_options++ options = _placement_options(placement)+ joined = " ".join(options)++ assert "make up-gpu" in joined+ assert "make up-host-llm" in joined+ assert "hosted provider" in joined++ def test_unreachable_does_not_read_as_a_fault_when_it_is_not(self) -> None:+ """A deployment on a hosted provider has no Ollama, and telling that+ operator something is broken sends them to debug a service they+ deliberately do not run."""+ from app.api.v1.endpoints.llm_status import _placement_options++ joined = " ".join(_placement_options("unreachable"))++ assert "expected" in joined++ def test_a_gpu_answer_does_not_nag(self) -> None:+ from app.api.v1.endpoints.llm_status import _placement_options++ options = _placement_options("gpu")++ assert not any("make up-gpu" in o for o in options)diff --git a/services/api/tests/test_onboarding_wizard.py b/services/api/tests/test_onboarding_wizard.pyindex 298306bbd..8ce7b6ab9 100644--- a/services/api/tests/test_onboarding_wizard.py+++ b/services/api/tests/test_onboarding_wizard.py@@ -193,3 +193,44 @@ class TestTheIngestProfileExists:assert "Sample data" in block, ("the profile does not name the sample vendor, so a reader cannot tell sample alerts from real ones in the source column")+++class TestTheModelStep:+ """The wizard tells a first-run operator where AI triage is running.++ Added because nothing did. A tenant could finish setup without ever+ learning that the bundled model is on CPU, that their GPU could be used,+ or that their own provider is three fields away -- and the first two are+ not reachable from the console at all, since switching the bundled Ollama+ onto a GPU means restarting that container with different compose+ arguments.+ """++ def test_the_step_exists(self) -> None:+ source = ENDPOINT.read_text()+ assert 'key="model"' in source++ def test_it_is_not_blocking(self) -> None:+ """`done=True` out of the box, deliberately: a local model ships and+ runs, so a tenant on CPU is configured, not unfinished. A step that+ showed red until somebody bought a GPU would be a chore invented by+ the checklist."""+ source = ENDPOINT.read_text()+ block = source[source.index('key="model"') :]+ block = block[: block.index("SetupStep(", 10)] if "SetupStep(" in block[10:] else block+ assert "done=True" in block++ def test_it_is_derived_from_the_tenants_own_row(self) -> None:+ """Same discipline as every other step: no stored flag to drift. A+ credential that exists but is disabled must not read as configured."""+ source = ENDPOINT.read_text()+ assert "tenant_llm_credentials" in source+ assert "enabled IS TRUE" in source++ def test_it_explains_why_like_the_others(self) -> None:+ """The existing gate counts `why=` occurrences; this asserts the new+ step carries one rather than relying on the count rising."""+ source = ENDPOINT.read_text()+ block = source[source.index('key="model"') :]+ block = block[: block.index('key="try"')]+ assert "why=(" in block or 'why="' in blockdiff --git a/tests/test_env_placeholder_gate.py b/tests/test_env_placeholder_gate.pyindex c9ad26543..bbde0c821 100644--- a/tests/test_env_placeholder_gate.py+++ b/tests/test_env_placeholder_gate.py@@ -68,6 +68,10 @@ DELIBERATE_DEFAULTS: dict[str, str] = {"AISOC_AGENTS_URL": "the compose hostname the console proxies agent calls to","AISOC_REALTIME_URL": "the compose hostname the console proxies WS/SSE to","AISOC_DEMO_MODE": "a boolean; false is the correct value for every deployment that is not the public demo",+ "AISOC_GPU_COUNT": (+ "a device count, not a secret. 1 is the right value for every host with one "+ "GPU, and it is only read by `make up-gpu` — the default `make up` ignores it"+ ),"RETRO_HUNT_ENABLED": ("a boolean, and off is the correct value for every deployment: a sweep reads back ""over a tenant's history, which is a cost and a privacy decision, so it waits for "diff --git a/tests/test_model_runtime_overlays.py b/tests/test_model_runtime_overlays.pynew file mode 100644index 000000000..57c2d826d--- /dev/null+++ b/tests/test_model_runtime_overlays.py@@ -0,0 +1,167 @@+"""The GPU reservation is opt-in, and `make up` stays runnable everywhere.++The regression this exists to prevent+-------------------------------------+A contributed change once put an unconditional NVIDIA device reservation on+the `ollama` service in the **base** compose file. On a host without an NVIDIA+GPU and the container toolkit the daemon refuses to start the service at all:++ Error response from daemon: could not select device driver "nvidia" with+ capabilities: [[gpu]]++`make up` is the documented first-run path and CORE ships a model that runs+CPU-only in 8 GB, so that one line takes out first run for every Mac, every+CPU-only Linux box and every CI runner. The first test below is the guard, and+the second is its negative control: an assertion that only ever checked the+base file would also pass against a tree where the overlay had been deleted.++These parse the compose files rather than shelling out to `docker compose`, so+they run on a machine with no Docker at all -- which is where a CI lint job+usually is.+"""++from __future__ import annotations++from pathlib import Path++import pytest+import yaml++ROOT = Path(__file__).resolve().parents[1]+BASE = ROOT / "docker-compose.yml"+GPU_OVERLAY = ROOT / "infra" / "compose" / "docker-compose.gpu.yml"+HOST_LLM_OVERLAY = ROOT / "infra" / "compose" / "docker-compose.host-llm.yml"+++class _ComposeLoader(yaml.SafeLoader):+ """PyYAML plus Compose's merge tags.++ Compose 2.24+ understands `!reset` and `!override` on a value, and+ `yaml.safe_load` refuses them with `could not determine a constructor for+ the tag '!reset'`. They are merge *directives* rather than data, so the+ loader keeps the value and drops the tag -- which is the right shape for a+ test asserting on the resulting structure. Tests that care whether the tag+ is present read the raw text instead, because this loader deliberately+ throws that away.+ """+++def _drop_tag(loader: yaml.Loader, node: yaml.Node) -> object:+ if isinstance(node, yaml.ScalarNode):+ return loader.construct_scalar(node)+ if isinstance(node, yaml.SequenceNode):+ return loader.construct_sequence(node)+ return loader.construct_mapping(node)+++for _tag in ("!reset", "!override"):+ _ComposeLoader.add_constructor(_tag, _drop_tag)+++def _load(path: Path) -> dict:+ assert path.is_file(), f"{path.relative_to(ROOT)} is missing"+ return yaml.load(path.read_text(encoding="utf-8"), Loader=_ComposeLoader) or {}+++def _device_reservations(service: dict) -> list:+ return (((service.get("deploy") or {}).get("resources") or {}).get("reservations") or {}).get("devices") or []+++class TestTheBaseFileStaysRunnableWithoutAGpu:+ def test_no_service_reserves_a_device(self) -> None:+ """The guard. Any device reservation here is a host requirement that+ `make up` does not otherwise have."""+ services = _load(BASE).get("services") or {}++ reserving = [name for name, svc in services.items() if _device_reservations(svc or {})]++ assert not reserving, (+ f"{reserving} reserve a device in the base compose file. That makes `make up` fail on "+ "any host without the matching driver, which is most of them. Put it in "+ "infra/compose/docker-compose.gpu.yml instead."+ )++ def test_no_service_pins_an_nvidia_runtime(self) -> None:+ """The other spelling of the same mistake."""+ services = _load(BASE).get("services") or {}++ pinned = [n for n, s in services.items() if (s or {}).get("runtime") == "nvidia"]++ assert not pinned, f"{pinned} pin runtime: nvidia in the base file"+++class TestTheGpuOverlayDoesTheOppositeThing:+ """The negative control. Without this, deleting the overlay would leave the+ guard above passing and the feature gone."""++ def test_it_reserves_an_nvidia_device_for_ollama(self) -> None:+ services = _load(GPU_OVERLAY).get("services") or {}++ devices = _device_reservations(services.get("ollama") or {})++ assert devices, "the GPU overlay reserves nothing"+ assert any(d.get("driver") == "nvidia" for d in devices)+ assert any("gpu" in (d.get("capabilities") or []) for d in devices)++ def test_it_touches_only_ollama(self) -> None:+ """An overlay that quietly changed other services would be a second+ deployment shape nobody reviewed."""+ services = _load(GPU_OVERLAY).get("services") or {}++ assert set(services) == {"ollama"}, f"the GPU overlay also changes {sorted(set(services) - {'ollama'})}"+++class TestTheHostLlmOverlayStopsTheBundledOne:+ def test_ollama_and_its_puller_move_into_a_profile(self) -> None:+ """A service with a profile is not started unless the profile is named,+ which is how the bundled pair is skipped without deleting it."""+ services = _load(HOST_LLM_OVERLAY).get("services") or {}++ for name in ("ollama", "ollama-pull"):+ assert (services.get(name) or {}).get("profiles"), f"{name} is still started by default"++ def test_litellm_stops_waiting_for_a_puller_that_will_not_run(self) -> None:+ """`!reset` and not an empty mapping: a plain override *merges*, so it+ can add a dependency and cannot remove one. Without this the gateway+ waits forever on a one-shot that never starts.++ Read from the raw text because PyYAML does not keep the compose tag.+ """+ text = HOST_LLM_OVERLAY.read_text(encoding="utf-8")++ assert "depends_on: !reset" in text, "litellm still depends on the bundled ollama-pull, which this overlay does not start"++ def test_the_gateway_is_pointed_at_the_host(self) -> None:+ services = _load(HOST_LLM_OVERLAY).get("services") or {}+ env = (services.get("litellm") or {}).get("environment") or {}++ assert "host.docker.internal" in str(env.get("AISOC_LLM_API_BASE", ""))++ @pytest.mark.parametrize("service", ["litellm", "api"])+ def test_linux_can_resolve_the_host_address(self, service: str) -> None:+ """Docker Desktop provides `host.docker.internal` and Linux does not,+ so without `extra_hosts` this works on a Mac and fails on a server --+ which is the worst place for it to fail, because the Mac is where it+ would have been tested."""+ services = _load(HOST_LLM_OVERLAY).get("services") or {}+ hosts = (services.get(service) or {}).get("extra_hosts") or []++ assert any("host.docker.internal" in str(h) and "host-gateway" in str(h) for h in hosts), f"{service} has no host-gateway mapping"+++class TestTheMakefileWiresThemUp:+ def test_up_gpu_runs_the_preflight_before_compose(self) -> None:+ """The whole point of the preflight is to replace the daemon's+ `could not select device driver` with something actionable. Running it+ after compose would be decoration."""+ text = (ROOT / "Makefile").read_text(encoding="utf-8")++ line = next((ln for ln in text.splitlines() if ln.startswith("up-gpu:")), "")+ assert "_gpu_preflight" in line, "up-gpu does not depend on the preflight"+ assert "_gpu_preflight" in text.split("up-gpu:")[1].split("\n")[0]++ def test_both_targets_use_their_overlay(self) -> None:+ text = (ROOT / "Makefile").read_text(encoding="utf-8")++ assert "infra/compose/docker-compose.gpu.yml" in text+ assert "infra/compose/docker-compose.host-llm.yml" in text