瀏覽代碼

feat: close the 0.4.0 follow-ups - runner health, run headers, dispatch cache

Runner reachability travels with the functions listing (runners
{configured, healthy}) and the web UI warns up front, instead of the
first signal being a 503 on a push after the work is done. `configured:
0` is the common first state, because installing the runner package does
not switch functions on. The listing also carries runs_kept, so the runs
tab states this server's actual retention rather than hardcoding 50 and
being wrong wherever it was configured.

The warning renders only once the listing has answered: `runners` is
undefined while loading, and defaulting it to zero would flash "no runner
configured" on every page load - accurate about the local variable,
actively misleading about the server.

Settings gains a Function outbound access section under Access &
security, with the egress blocklist and the allow-private opt-out. The
copy says the list can only ever block MORE, never less, because that is
the property an operator would otherwise have to infer, and the opt-out
carries the warning that it exposes loopback where this API listens.

listProjects() is off the /fn/* hot path - it was a database round trip
on every public function call. Cached with a 5s TTL and a deliberate
asymmetry: a positive is served from cache, a MISS is always re-verified
before answering 404. A stale positive at worst permits a registry read
that finds nothing; a stale negative would 404 the functions of a project
created a moment ago. The cheap direction is the safe one.

A logged run now carries headers, omitted from storage when empty, so a
client can render a stored run and a fresh invoke envelope with one
component.

The runner's runtime ceilings are documented as boot-time only rather
than made hot-reloadable: QuickJS fixes a runtime's memory limit at
creation, so changing one live would mean draining and recreating the
whole pool - real complexity for a host-sizing decision nobody tunes
live. Written down so no one hunts for a reload that does not exist.

Verified on the Debian target: systemd-analyze verify clean on the runner
unit, exposure level 3.2, every hardening directive confirmed in effect
with IPAddressDeny expanded to concrete ranges.

426/426 with BUILD_RUNNER=ON.
fszontagh 1 月之前
父節點
當前提交
1565787347

+ 2 - 1
CLAUDE.md

@@ -55,9 +55,10 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A write is validated on a runner before storage**, so the engine that validates is the engine that executes; with no healthy runner the write is refused **503** rather than stored unchecked.
 - **`RunnerPool` retry is three-way, not two.** Never connected → retry (nothing ran). Answered, whatever the answer → never retry (the runner did its job). **Delivered then unanswered** (read timeout, non-200, unparseable body) → **do not retry**, mark unhealthy: the handler may be running right now, and a retry would run a side-effecting function twice. `validate()` retries everything, because compiling has no side effects. Also: `RunnerPool::Options::readTimeoutSec` **must exceed** the runner's `max_wall_time_ms`, or our read times out before the runner can report its own timeout and the caller gets a misleading 503 instead of a 504.
 - **`ctx.collections(...)` is a direct gateway call, never loopback HTTP**, and `ctx.fetch` pins the connection to the single address the guard approved (`set_hostname_addr_map`) rather than re-resolving — re-resolving IS the rebinding window. One resolution, one classification.
+- **The runner's `runtime` ceilings are boot-time only**, unlike every hot-reloading setting in the server: QuickJS fixes a runtime's memory limit at creation, so changing one live would mean draining and recreating the whole pool. Editing them means restarting the runner - cheap, because vectorapi answers 503 for that moment and stores nothing unvalidated. By contrast `function_egress_blocked_cidrs` / `function_egress_allow_private` DO hot-reload, because they are read per run.
 - **`ctx.env` comes from the runner's environment, scoped per project**: `SVAPI_FN_<project>__<NAME>` in `/etc/smartbotic-vectorapi/runner.env` reaches that project's functions as `ctx.env.<NAME>`. The project is part of the variable name because one runner serves every project; nothing outside the `SVAPI_FN_` prefix is ever exposed, so the runner's own token and database address stay invisible to functions. Matched exactly and case-sensitively; the split is at the **first** `__`, so a project whose name contains `__` cannot carry secrets.
 - **The runner authenticates a shared bearer token and fails closed.** No token plus a non-loopback bind address means it **refuses to start**. `isLoopbackBind()` answers "not loopback" for anything it cannot parse, so an unrecognised address produces the refusal. The comparison is constant-time, `/health` is authenticated too, and both sides prefer `SVAPI_RUNNER_TOKEN` in the `.env` over the conffile.
-- **`ctx.fetch` egress goes through the SSRF guard** (`functions/net_guard.hpp`): fail closed on anything unparseable, and classify **every** address a name resolves to, not the first. A custom blocklist from settings *replaces* the defaults rather than extending them.
+- **`ctx.fetch` egress goes through the SSRF guard** (`functions/net_guard.hpp`): fail closed on anything unparseable, and classify **every** address a name resolves to, not the first. A settings blocklist is **UNIONED** with the built-in defaults by `SsrfPolicy::fromSettings()`, never substituted for them - an operator adding one CIDR must not silently reopen loopback, RFC1918 and the metadata endpoint. `function_egress_allow_private` is the explicit opt-out and relaxes **only** `privateBlockedCidrs()`; 169.254.0.0/16, link-local, multicast, reserved space and the IPv6 spellings of an IPv4 destination (NAT64, 6to4, `::/96`) stay blocked whatever it is set to. Note the opt-out does expose loopback, where our own API listens.
 
 ## Data model & runtime config
 

+ 2 - 2
api/llms.txt

@@ -184,7 +184,7 @@ export default async function (ctx) {
 
 **A code push can never widen access.** `policy` is server state: a `policy` field sent with a `POST`/`PUT` body is ignored (not merged, not consulted as a fallback), and `enabled` is likewise preserved, so re-pushing code does not re-enable a function an operator turned off. A first registration inherits the project's default policy, which currently grants **no collection at all** - the function runs, logs and can call out, but reaches no data until an admin grants it a rule.
 
-- `GET  /api/v1/projects/{project}/functions` - List functions **without their sources**: `{functions:[{function_id, path, content_hash, descriptor, policy, enabled, valid, last_error, created_at, updated_at}]}`.
+- `GET  /api/v1/projects/{project}/functions` - List functions **without their sources**: `{functions:[{function_id, path, content_hash, descriptor, policy, enabled, valid, last_error, created_at, updated_at}], runners:{configured, healthy}, runs_kept}`. The `runners` counts let a client warn that a write will fail with **503** *before* an author writes a script, rather than only after the push: `configured: 0` is the common first state, because installing the runner package does not switch functions on - the server needs a `functions.runners` list. `runs_kept` is this server's configured run-log retention, so a client need not guess the default.
 - `POST /api/v1/projects/{project}/functions` `{source, path?}` - Register a new function; the id comes from the validated `on` block, so there is no `function_id` field to send. An id already in use is **409** `function_exists` (PUT it to update).
 - `GET  /api/v1/projects/{project}/functions/{id}` - Get one function, **including** `source`.
 - `PUT  /api/v1/projects/{project}/functions/{id}` `{source, path?}` - Push code. The id the script declares must equal the id in the URL; a mismatch is **422** `id_mismatch` (with `error.details.declared` and `error.details.url`) rather than a rename, because the URL would otherwise move code onto another function's policy. A PUT to an unused id registers it (**201**).
@@ -192,7 +192,7 @@ export default async function (ctx) {
 - `PUT  /api/v1/projects/{project}/functions/{id}/policy` `{policy:{rules, origins?, rate_limit_per_min?, expires_at?}}` **(admin)** - Replace what the function may touch. Same vocabulary as a key scope (`rules` of `{collection, ops}` over `read`/`list`/`search`/`insert`/`update`/`delete`), with one difference: an **empty** rule set is legal and means the function reaches nothing. This is the only route that changes a policy.
 - `PUT  /api/v1/projects/{project}/functions/{id}/enabled` `{enabled}` - Enable or disable a function.
 - `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method. Returns **200** whenever the run was *performed*, with `{run_id, ok, status, headers, body, console, duration_ms, error, timed_out, out_of_memory}` - the function's own failure is in that envelope, not in the HTTP status, so "the function returned 500" stays distinguishable from "the invoke could not be performed". A disabled or invalid function is **409**; a runner that cannot be reached is **503** `runner_unreachable`, and the failed attempt is still logged.
-- `GET  /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, started_at}]}`. `?limit=` defaults to 50. **The log keeps only the newest N runs per function** (trimmed on every write, since there is no scheduler yet), so a limit above N returns N and an old `run_id` eventually stops resolving.
+- `GET  /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, headers, started_at}]}`. `headers` is omitted when the function set none, and is present so a stored run renders with the same shape as a fresh invoke envelope. `?limit=` defaults to 50. **The log keeps only the newest N runs per function** (trimmed on every write, since there is no scheduler yet), so a limit above N returns N and an old `run_id` eventually stops resolving.
 
 ### Calling a function
 

+ 9 - 1
api/openapi.json

@@ -102,7 +102,15 @@
           }
         ]
       },
-      "FunctionRun": {
+      "RunnerStatus": {
+      "type": "object",
+      "description": "Runner reachability, carried by the functions listing so a client can warn that a write will fail before an author writes a script.",
+      "properties": {
+        "configured": { "type": "integer", "description": "Endpoints in the server's functions.runners list. 0 means functions cannot be stored at all - installing the runner package does not switch them on." },
+        "healthy": { "type": "integer", "description": "How many answered their last health check." }
+      }
+    },
+    "FunctionRun": {
         "type": "object",
         "description": "One recorded run. The log is append-only and trimmed to the newest N runs per function on every write, so an old run_id eventually stops resolving.",
         "properties": {

+ 48 - 0
docs/superpowers/specs/2026-10-06-function-runtime-design.md

@@ -330,3 +330,51 @@ system user, so a sandbox escape inherits none of the server's credentials.
   Same for `functions.runs_kept`, which the UI currently hardcodes as 50.
 - A logged run carries no `headers`, while a fresh invoke envelope does, so a
   client naturally trying to render both with one component cannot.
+
+## Follow-ups closed (2026-10-07)
+
+- **SSRF blocklist: now a UNION.** `SsrfPolicy::fromSettings()` adds an
+  operator's CIDRs to the built-in defaults instead of replacing them, so
+  editing the list can only ever refuse MORE. `function_egress_allow_private`
+  is the explicit opt-out and relaxes only `privateBlockedCidrs()` - the
+  metadata endpoint, link-local, multicast, reserved space and the IPv6
+  spellings of an IPv4 destination stay blocked regardless, because almost
+  nothing legitimate targets those and 169.254.169.254 is the highest-value
+  prize an SSRF has. Note the opt-out does expose loopback, where our own API
+  listens; that is the operator's call. Also WIRED: the settings path existed in
+  the design but nothing called it, so the policy was always the hard-coded
+  defaults. The runner now builds it from the settings document on first
+  `ctx.fetch` and pins it for the rest of the run, reporting an unparseable
+  entry into that run's own log.
+- **Runner health is visible before a push.** `GET .../functions` carries
+  `runners:{configured, healthy}` and `runs_kept`, and the web UI warns up front
+  instead of only explaining the 503 afterwards. `configured: 0` is the common
+  first state, because installing the runner package does not switch functions
+  on.
+- **`listProjects()` is off the dispatch hot path**, cached with a 5s TTL and a
+  deliberate asymmetry: a positive is served from cache, a MISS is always
+  re-verified against the database before answering 404. A stale positive at
+  worst permits a registry read that finds nothing; a stale negative would 404
+  the functions of a project created a moment ago.
+- **A logged run carries `headers`**, omitted from storage when empty, so a
+  client can render a stored run and a fresh invoke envelope with one component.
+- **The runner unit is verified** on Debian 13: `systemd-analyze verify` clean,
+  exposure level 3.2, and every hardening directive confirmed in effect -
+  `IPAddressDeny` expanded to concrete ranges, so cgroup-BPF is working rather
+  than warning.
+- **`JsLimits` stays boot-time, deliberately.** QuickJS fixes a runtime's memory
+  limit at creation, so hot-reloading one would mean draining and recreating the
+  whole pool - real complexity for a host-sizing decision nobody tunes live.
+  Documented in `RunnerConfig` and CLAUDE.md so no one hunts for a reload that
+  does not exist.
+- **Per-project runner processes: not now, by decision.** One shared runner
+  stands, with the unit hardening bounding the blast radius. The risk is
+  unchanged and recorded above: a QuickJS memory-safety bug is a cross-tenant
+  compromise, and after a native escape the Principal/KeyOp mapping that
+  separates tenants is gone. Revisit before hosting functions for parties who
+  must not see each other's data.
+- **The two `/fn/*` protocol limits are documented, not fixed.** Repeated query
+  keys collapse to the last value (the trigger's `query` is an object) and `HEAD`
+  is unroutable (cpp-httplib has no `Server::Head`). Both are stated in llms.txt
+  where an author meets them and in openapi.json; widening either is a protocol
+  change on both sides and not worth doing speculatively.

+ 14 - 0
runner/src/main.cpp

@@ -53,6 +53,20 @@ void onSignal(int) { g_running = false; }
 /// Same posture as the server's config though: minimal, and only what has to be
 /// known BEFORE the database is reachable. Anything that can hot-reload belongs
 /// in the database, not here.
+///
+/// The `runtime` ceilings are deliberately BOOT-TIME ONLY, unlike every
+/// hot-reloading setting in the server. QuickJS fixes a runtime's memory limit
+/// when the runtime is created, so changing it live would mean draining and
+/// recreating every pooled runtime - real complexity for a knob that is a
+/// host-sizing decision, not something an operator tunes while watching a
+/// dashboard. Editing these means `systemctl restart
+/// smartbotic-vectorapi-runner`, which is cheap: vectorapi answers 503 for the
+/// moment the runner is down and nothing is stored unvalidated.
+///
+/// The ONE value that has to stay in step with the server is `max_wall_time_ms`:
+/// RunnerPool's readTimeoutSec must exceed it, or our read times out before the
+/// runner can report its own timeout and a caller gets a misleading 503 instead
+/// of a 504.
 struct RunnerConfig {
     std::string logLevel = "info";
     /// Loopback by default: the single-host deployment, where no token is

+ 15 - 9
src/function_run_log.cpp

@@ -54,21 +54,27 @@ FunctionRunLog FunctionRunLog::fromJson(const nlohmann::json& j) {
         for (const auto& line : lines)
             if (line.is_string()) e.console.push_back(line.get<std::string>());
     }
+    if (j.contains("headers") && j.at("headers").is_object()) e.headers = j.at("headers");
     e.startedAt = j.value("started_at", 0ull);
     return e;
 }
 
 nlohmann::json FunctionRunLog::toJson() const {
     // `run_id`, never `id` - see trimOldest above.
-    return {{"run_id", runId},
-            {"function_id", functionId},
-            {"trigger", trigger},
-            {"ok", ok},
-            {"status", status},
-            {"duration_ms", durationMs},
-            {"error", error},
-            {"console", console},
-            {"started_at", startedAt}};
+    nlohmann::json j = {{"run_id", runId},
+                        {"function_id", functionId},
+                        {"trigger", trigger},
+                        {"ok", ok},
+                        {"status", status},
+                        {"duration_ms", durationMs},
+                        {"error", error},
+                        {"console", console},
+                        {"started_at", startedAt}};
+    // Written only when the function set some. This row lands on every
+    // invocation, so an always-present empty object is thousands of bytes of
+    // nothing.
+    if (headers.is_object() && !headers.empty()) j["headers"] = headers;
+    return j;
 }
 
 FunctionRunLogStore::FunctionRunLogStore(DbGateway& db, uint32_t keepPerFunction)

+ 10 - 0
src/function_run_log.hpp

@@ -17,6 +17,11 @@ struct FunctionRunLog {
     int64_t durationMs = 0;
     std::string error;
     std::vector<std::string> console;
+    /// The response headers the function set. Present so a client can render a
+    /// logged run with the same component as a fresh invoke envelope, which
+    /// carries them too. Omitted from storage when empty, since most runs set
+    /// none and this row is written on every invocation.
+    nlohmann::json headers = nlohmann::json::object();
     uint64_t startedAt = 0;
 
     static FunctionRunLog fromJson(const nlohmann::json& j);
@@ -31,6 +36,11 @@ class FunctionRunLogStore {
 public:
     FunctionRunLogStore(DbGateway& db, uint32_t keepPerFunction);
 
+    /// Newest runs kept per function. Surfaced so a client can say what the
+    /// limit actually is rather than hardcoding the default and being wrong on
+    /// a host that configured something else.
+    uint32_t keepPerFunction() const { return keep_; }
+
     void ensure(const std::string& project);
     void append(const std::string& project, const FunctionRunLog& entry);
     std::vector<FunctionRunLog> list(const std::string& project, const std::string& functionId,

+ 58 - 6
src/handlers/function_dispatch.cpp

@@ -13,7 +13,9 @@
 #include "json_http.hpp"
 #include "server.hpp"
 #include <algorithm>
+#include <chrono>
 #include <ctime>
+#include <mutex>
 #include <spdlog/spdlog.h>
 
 namespace svapi {
@@ -67,6 +69,55 @@ bool safeProjectSegment(const std::string& p) {
 /// A ".." segment can never match a literal pattern segment, but it CAN be
 /// captured by a `:name` parameter and handed to a function that uses it as a
 /// key, so it is refused at the edge instead.
+/// Caches the project list for the dispatch path.
+///
+/// listProjects() on every public function call is a database round trip on the
+/// hot path, purely to confirm the project exists before anything qualifies a
+/// collection with it.
+///
+/// The caching is DELIBERATELY ASYMMETRIC: a positive is served from the cache,
+/// but a miss is always re-verified against the database before answering 404.
+/// A stale positive at worst permits a registry read that finds nothing, while
+/// a stale negative would 404 the functions of a project created a moment ago -
+/// so the cheap direction is the safe one, and the expensive direction is the
+/// one that must never be wrong.
+class ProjectCache {
+public:
+    bool exists(DbGateway& db, const std::string& project) {
+        {
+            std::lock_guard<std::mutex> lock(mu_);
+            if (fresh() && contains(project)) return true;
+        }
+        // Either the cache is stale, or this project is not in it. Both mean a
+        // real lookup, because the answer we are about to give is "no".
+        std::vector<std::string> fromDb = db.listProjects();
+        std::lock_guard<std::mutex> lock(mu_);
+        projects_ = std::move(fromDb);
+        loadedAt_ = std::chrono::steady_clock::now();
+        return contains(project);
+    }
+
+private:
+    static constexpr std::chrono::seconds kTtl{5};
+
+    bool fresh() const {
+        return loadedAt_.time_since_epoch().count() != 0 &&
+               std::chrono::steady_clock::now() - loadedAt_ < kTtl;
+    }
+    bool contains(const std::string& project) const {
+        return std::find(projects_.begin(), projects_.end(), project) != projects_.end();
+    }
+
+    std::mutex mu_;
+    std::vector<std::string> projects_;
+    std::chrono::steady_clock::time_point loadedAt_{};
+};
+
+ProjectCache& projectCache() {
+    static ProjectCache cache;
+    return cache;
+}
+
 bool hasDotDotSegment(const std::string& path) {
     size_t i = 0;
     while (i < path.size()) {
@@ -184,12 +235,10 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
     if (!safeProjectSegment(project) || hasDotDotSegment(path)) { sendNotFound(res); return; }
 
     // The project must exist before anything qualifies a collection with it, so
-    // a crafted segment cannot conjure a registry read in a namespace of its own.
-    const std::vector<std::string> projects = d.db.listProjects();
-    if (std::find(projects.begin(), projects.end(), project) == projects.end()) {
-        sendNotFound(res);
-        return;
-    }
+    // a crafted segment cannot conjure a registry read in a namespace of its
+    // own. Cached, but a miss is re-verified against the database before this
+    // answers 404 - see ProjectCache.
+    if (!projectCache().exists(d.db, project)) { sendNotFound(res); return; }
 
     std::vector<FunctionRecord> rows = d.functions.list(project);
     // matchHttpRoute resolves ties by declaration order, so the order we hand it
@@ -260,6 +309,9 @@ void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res
     entry.ok = r.ok;
     entry.durationMs = r.durationMs;
     entry.console = r.console;
+    // Logged alongside the rest so a client can render a stored run with the
+    // same component as a fresh invoke envelope.
+    if (r.headers.is_object()) entry.headers = r.headers;
     entry.error = r.error;
 
     // The status mapping. Three of these four are OUR fault or OUR limit, so

+ 19 - 1
src/handlers/functions.cpp

@@ -185,7 +185,22 @@ void registerFunctionRoutes(ApiServer& s) {
         // Summaries, never full rows: a listing that shipped every function's
         // source would grow without bound in the one response people poll.
         for (const auto& fn : d->functions.list(project)) arr.push_back(fn.toSummaryJson());
-        sendJson(res, 200, {{"functions", arr}});
+
+        // Runner reachability travels with the listing so a client can warn
+        // BEFORE someone writes a script, instead of only explaining the 503
+        // after a push has already failed. `configured` 0 is the common first
+        // state: installing the runner does not enable functions - the server
+        // needs functions.runners in its config.
+        nlohmann::json runners = {{"configured", 0}, {"healthy", 0}};
+        if (d->runners != nullptr) {
+            const nlohmann::json st = d->runners->statusJson();
+            runners["configured"] = st.value("runners", nlohmann::json::array()).size();
+            runners["healthy"] = st.value("healthy", 0);
+        }
+        sendJson(res, 200,
+                 {{"functions", arr},
+                  {"runners", runners},
+                  {"runs_kept", d->functionRuns.keepPerFunction()}});
     });
 
     svr.Post(R"(/api/v1/projects/([^/]+)/functions)",
@@ -296,6 +311,9 @@ void registerFunctionRoutes(ApiServer& s) {
         entry.durationMs = r.durationMs;
         entry.error      = r.error;
         entry.console    = r.console;
+        // Logged alongside the rest so a client can render a stored run with
+        // the same component as this call's own envelope, which carries them.
+        if (r.headers.is_object()) entry.headers = r.headers;
         entry.startedAt  = startedAt;
         // Logged before the 503 below: an attempt that never reached a runner is
         // exactly the one an operator goes looking for afterwards.

+ 21 - 0
tests/test_function_run_log.cpp

@@ -211,3 +211,24 @@ TEST_F(FunctionRunLogTest, ProjectsDoNotShareARunLog) {
 }
 
 }  // namespace
+
+TEST(FunctionRunLogRecord, CarriesResponseHeadersSoAStoredRunRendersLikeAnEnvelope) {
+    // A fresh invoke envelope carries headers; without them here a client could
+    // not render a logged run with the same component.
+    svapi::FunctionRunLog e;
+    e.runId = "r1";
+    e.functionId = "kb-search";
+    e.headers = {{"Content-Type", "application/json"}, {"X-Cache", "miss"}};
+    const svapi::FunctionRunLog back = svapi::FunctionRunLog::fromJson(e.toJson());
+    EXPECT_EQ(back.headers.at("Content-Type"), "application/json");
+    EXPECT_EQ(back.headers.at("X-Cache"), "miss");
+}
+
+TEST(FunctionRunLogRecord, OmitsHeadersFromStorageWhenTheFunctionSetNone) {
+    // This row is written on every invocation, so an always-present empty
+    // object is thousands of bytes of nothing.
+    const svapi::FunctionRunLog e;
+    EXPECT_FALSE(e.toJson().contains("headers"));
+    // And it still reads back as an object, so a client never has to null-check.
+    EXPECT_TRUE(svapi::FunctionRunLog::fromJson(e.toJson()).headers.is_object());
+}

+ 3 - 2
webui/src/api/client.ts

@@ -4,7 +4,8 @@ import type {
   KeyScope, IndexDef, IndexValue, CreateIndexResult,
   ProjectEmbeddingsView, ProjectEmbeddingsPatch,
   RelationDefinition, DeleteImpact,
-  FunctionSummary, FunctionDetail, FunctionRun, InvokeEnvelope, InvokeRequest,
+  FunctionSummary,
+  FunctionsListResponse, FunctionDetail, FunctionRun, InvokeEnvelope, InvokeRequest,
 } from '@/types'
 import { ApiError } from '@/types'
 import { serverUrl } from '@/api/base'
@@ -134,7 +135,7 @@ export const api = {
   // functions
   // The listing carries no `source`; the single-function GET does.
   listFunctions: (project: string) =>
-    request<{ functions: FunctionSummary[] }>(`${P(project)}/functions`),
+    request<FunctionsListResponse>(`${P(project)}/functions`),
   getFunction: (project: string, id: string) =>
     request<FunctionDetail>(`${P(project)}/functions/${enc(id)}`),
   // No id field on create: the id comes from the script's `on` block, which is

+ 51 - 6
webui/src/pages/Functions.tsx

@@ -912,7 +912,7 @@ function ConsoleView({ lines }: { lines: string[] }) {
 
 // ─── runs tab ─────────────────────────────────────────────────────────────────
 
-function RunsTab({ project, fn }: { project: string; fn: FunctionSummary }) {
+function RunsTab({ project, fn, runsKept }: { project: string; fn: FunctionSummary; runsKept: number }) {
   const [limit, setLimit] = useState(50)
   const [open, setOpen] = useState('')
 
@@ -950,10 +950,10 @@ function RunsTab({ project, fn }: { project: string; fn: FunctionSummary }) {
           the normal state, not a loading glitch, and an old run_id is gone for
           good rather than momentarily missing. */}
       <p className="text-xs text-slate-500">
-        Newest first. Only the newest runs per function are kept (50 by default, set by the
-        server's <span className="font-mono">functions.runs_kept</span>), and the log is trimmed on
-        every write - so asking for more than that returns what is left, and a run_id from an older
-        run stops resolving altogether.
+        Newest first. Only the newest {runsKept} runs per function are kept on this server (
+        <span className="font-mono">functions.runs_kept</span>), and the log is trimmed on every
+        write - so asking for more than that returns what is left, and a run_id from an older run
+        stops resolving altogether.
       </p>
 
       {isError && (
@@ -1059,9 +1059,11 @@ function FunctionDetailPanel({
   onDelete,
   onOpenExisting,
   onSaved,
+  runsKept,
 }: {
   project: string
   summary: FunctionSummary
+  runsKept: number
   detail: FunctionDetail | null
   detailLoading: boolean
   admin: boolean
@@ -1166,7 +1168,7 @@ function FunctionDetailPanel({
         <PolicyTab project={project} fn={summary} admin={admin} onSaved={onRefresh} />
       )}
       {tab === 'invoke' && <InvokeTab project={project} fn={summary} />}
-      {tab === 'runs' && <RunsTab project={project} fn={summary} />}
+      {tab === 'runs' && <RunsTab project={project} fn={summary} runsKept={runsKept} />}
 
       <ConfirmDialog
         open={confirmDelete}
@@ -1217,6 +1219,12 @@ export default function Functions() {
   })
 
   const functions = data?.functions ?? []
+  // From the server, not a guess: a host that configured a different retention
+  // would otherwise be described wrongly in the runs tab.
+  const runsKept = data?.runs_kept ?? 50
+  // Runner reachability, so the page can warn BEFORE someone writes a script.
+  // Undefined while the listing loads - do not warn on a value we do not have.
+  const runners = data?.runners
   const summary = functions.find((f) => f.function_id === selectedId) ?? null
 
   // The selected function belongs to the project being left, so switching
@@ -1322,6 +1330,42 @@ export default function Functions() {
         </ErrorPanel>
       )}
 
+      {/* Warn BEFORE someone writes a script. Without this the first signal is
+          a 503 on the push, after the work is done. Only rendered once the
+          listing has actually answered - `runners` is undefined while loading,
+          and warning on a value we do not have would be worse than silence. */}
+      {runners && runners.configured === 0 && (
+        <ErrorPanel title="No function runner is configured - you can write functions, but not save them.">
+          <p>
+            Installing the runner package does not switch functions on. The server has to be told
+            where the runners are: add a <code className="text-slate-200">functions.runners</code>{' '}
+            list to its <code className="text-slate-200">config.json</code> and restart it.
+          </p>
+          <pre className="rounded-md bg-slate-950 border border-slate-700/60 px-3 py-2 overflow-x-auto text-[11px] text-slate-300">
+{`"functions": {
+  "runners": ["127.0.0.1:8090"],
+  "runs_kept": ${runsKept}
+}`}
+          </pre>
+        </ErrorPanel>
+      )}
+
+      {runners && runners.configured > 0 && runners.healthy === 0 && (
+        <ErrorPanel title="Every function runner is down - saving a function will fail.">
+          <p>
+            {runners.configured} runner{runners.configured === 1 ? ' is' : 's are'} configured and
+            none is answering its health check. A write is compiled on a runner before it is
+            stored, so nothing can be saved until one is back.
+          </p>
+          <p>
+            Check that the runner service is up and that its token matches the server's
+            (<code className="text-slate-200">SVAPI_RUNNER_TOKEN</code> in both{' '}
+            <code className="text-slate-200">runner.env</code> and{' '}
+            <code className="text-slate-200">vectorapi.env</code>).
+          </p>
+        </ErrorPanel>
+      )}
+
       {isLoading && (
         <div className="rounded-xl border border-slate-700/40 bg-slate-800/30 px-6 py-10 text-center animate-pulse">
           <p className="text-slate-400 text-sm">Loading functions...</p>
@@ -1374,6 +1418,7 @@ export default function Functions() {
           onDelete={() => void handleDelete()}
           onOpenExisting={(id) => select(id)}
           onSaved={handleSaved}
+          runsKept={runsKept}
         />
       )}
 

+ 58 - 0
webui/src/pages/settings/AccessTab.tsx

@@ -9,12 +9,16 @@ export default function AccessTab() {
   const [captchaProvider, setCaptchaProvider] = useState('')
   const [captchaSecret, setCaptchaSecret] = useState('')
   const [captchaVerifyUrl, setCaptchaVerifyUrl] = useState('')
+  const [egressCidrs, setEgressCidrs] = useState('')
+  const [allowPrivate, setAllowPrivate] = useState(false)
 
   usePopulate(data, (d) => {
     setCorsOrigins(d.cors_origins.join(', '))
     setSessionTtl(String(d.session_ttl_minutes))
     setCaptchaProvider(d.captcha_provider ?? '')
     setCaptchaVerifyUrl(d.captcha_verify_url ?? '')
+    setEgressCidrs((d.function_egress_blocked_cidrs ?? []).join('\n'))
+    setAllowPrivate(d.function_egress_allow_private ?? false)
   })
 
   async function onSubmit(e: React.FormEvent) {
@@ -26,6 +30,14 @@ export default function AccessTab() {
       session_ttl_minutes: ttl,
       captcha_provider: captchaProvider.trim(),
       captcha_verify_url: captchaVerifyUrl.trim(),
+      // One per line is friendlier for a list of CIDRs than comma separation,
+      // and the server validates each entry rather than accepting a typo and
+      // leaving a hole in the guard.
+      function_egress_blocked_cidrs: egressCidrs
+        .split('\n')
+        .map((s) => s.trim())
+        .filter(Boolean),
+      function_egress_allow_private: allowPrivate,
     }
     if (captchaSecret.trim()) patch.captcha_secret = captchaSecret.trim()
     if (await save(patch)) setCaptchaSecret('')
@@ -44,6 +56,52 @@ export default function AccessTab() {
         <input type="number" value={sessionTtl} onChange={(e) => setSessionTtl(e.target.value)} className={inputCls} />
       </FormRow>
 
+      <h2 className="text-sm font-semibold text-slate-300 border-t border-slate-700 pt-4 mt-1">
+        Function outbound access (ctx.fetch)
+      </h2>
+
+      <p className="text-xs text-slate-500">
+        Loopback, private, link-local and reserved ranges are refused by default. Anything you add
+        here is refused <span className="text-slate-300">in addition</span> - this list can only
+        ever block more, never less, so adding one range cannot accidentally reopen the others.
+      </p>
+
+      <FormRow
+        label="Additional blocked ranges"
+        hint="One CIDR or address per line, IPv4 or IPv6. A bare address is treated as a single host. Each entry is validated on save."
+      >
+        <textarea
+          value={egressCidrs}
+          onChange={(e) => setEgressCidrs(e.target.value)}
+          rows={4}
+          spellCheck={false}
+          placeholder={'198.51.100.0/24\n2001:db8::/32'}
+          className={inputCls + ' font-mono text-xs'}
+        />
+      </FormRow>
+
+      <FormRow
+        label="Allow private and loopback"
+        hint="Off by default. Turn this on only to let a function reach an internal service on purpose."
+      >
+        <label className="flex items-start gap-2 text-sm text-slate-300">
+          <input
+            type="checkbox"
+            checked={allowPrivate}
+            onChange={(e) => setAllowPrivate(e.target.checked)}
+            className="mt-0.5"
+          />
+          <span>
+            Let functions reach private and loopback addresses.
+            <span className="block text-xs text-amber-400/90 mt-1">
+              This includes 127.0.0.1, where this API itself listens - a function would be able to
+              call it. The cloud metadata endpoint (169.254.169.254) and link-local stay blocked
+              either way.
+            </span>
+          </span>
+        </label>
+      </FormRow>
+
       <h2 className="text-sm font-semibold text-slate-300 border-t border-slate-700 pt-4 mt-1">
         Captcha (scope rules with require_human_token)
       </h2>

+ 21 - 0
webui/src/types/index.ts

@@ -50,6 +50,12 @@ export interface SettingsView {
   captcha_provider: string
   captcha_secret_set: boolean
   captcha_verify_url: string
+  /// Extra CIDRs a function's ctx.fetch may not reach. ADDED to the built-in
+  /// defaults, never substituted for them.
+  function_egress_blocked_cidrs: string[]
+  /// Explicit opt-out letting functions reach private and loopback addresses.
+  /// Never relaxes the cloud metadata endpoint or link-local.
+  function_egress_allow_private: boolean
 }
 /// One tier of a project's embedding configuration. In `overrides`, an empty
 /// string means the field is inherited from the global settings.
@@ -156,6 +162,21 @@ export interface FunctionDescriptor {
 
 /// A registry row as the list route returns it: no `source`, so the listing
 /// stays small no matter how much code a project holds.
+/// Runner reachability, carried by the functions listing so the page can warn
+/// before someone writes a script rather than only after a push fails.
+export interface RunnerStatus {
+  configured: number;
+  healthy: number;
+}
+
+export interface FunctionsListResponse {
+  functions: FunctionSummary[];
+  runners: RunnerStatus;
+  /// Newest runs kept per function, from the server's own config - not a
+  /// guess at the default.
+  runs_kept: number;
+}
+
 export interface FunctionSummary {
   function_id: string
   path: string