Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(api): allow read-only API without web UI
AkitaOnRails742c372037ef
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5efc0534..0f76fa47 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Added `serve --enable-api` / `AI_MEMORY_ENABLE_API=true` to mount the+ authenticated read-only `/api/v1` surface without the browser UI. Existing+ `--enable-web` behavior is unchanged and still includes the API. Documented+ the acceptance and safety boundary for a repository-backed team-wiki sync+ companion. (#986)- Added `[handoff].claim_on_session_start` (default `true` - unchangedbehavior). When set to `false`, `SessionStart` no longer claims a pendinghandoff automatically; it renders a non-consuming notice naming the exactdiff --git a/README.md b/README.mdindex ad94ee44..2b294e38 100644--- a/README.md+++ b/README.md@@ -404,6 +404,7 @@ Homebrew, but not by the pinned Nixpkgs revision.services.ai-memory = {enable = true;# enableWeb = true; # off by default — the web UI is opt-in+ # enableApi = true; # API-only companions; no browser UIsettings = {allowed_hosts = [ "localhost" "127.0.0.1" "::1" "homelab.example" ];log_level = "info";@@ -564,7 +565,7 @@ diagram, crate breakdown, schema notes, and invariants.| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Operational summary: data flow, crate layout, cross-cutting invariants, schema. || [`docs/design-decisions.md`](docs/design-decisions.md) | The full v1 spec. || [`docs/managed-harness-contributions.md`](docs/managed-harness-contributions.md) | Protocol and acceptance bar for adding managed resume, transcript import, and startup context delivery to another harness. |-| [`docs/companion-crates.md`](docs/companion-crates.md) | Optional companion projects: the [importer](companions/ai-memory-importer) and [external lifecycle relay](companions/ai-memory-relay). |+| [`docs/companion-crates.md`](docs/companion-crates.md) | Optional companion projects: the [importer](companions/ai-memory-importer), [external lifecycle relay](companions/ai-memory-relay), and accepted team-wiki sync boundary. || [`docs/external-lifecycle.md`](docs/external-lifecycle.md) | External lifecycle producers: per-execution native capture suppression, preserved handoffs, batch ingestion and stable retry identity. || [`docs/auto-improvement-loop.md`](docs/auto-improvement-loop.md) | Auto-improvement design notes: scheduled review, auto-approval default, manual review opt-in, pending proposal storage, and curator work. |diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex a60e42d8..7ca8b3c0 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -2960,13 +2960,19 @@ pub struct ServeArgs {/// is public so it can render password login; `/api/v1` and the built-in/// server-rendered wiki remain protected by a web session or machine/// Bearer.- #[arg(long)]+ #[arg(long, env = "AI_MEMORY_ENABLE_WEB")]pub enable_web: bool,+ /// Mount only the read-only `/api/v1` JSON API. Off by default.+ ///+ /// `--enable-web` implies this API as before. Use this flag for+ /// non-browser companions that must not expose the web UI.+ #[arg(long, env = "AI_MEMORY_ENABLE_API")]+ pub enable_api: bool,/// Serve this static directory at /web instead of the built-in UI.////// The read-only /api/v1 frontend API is still mounted when/// --enable-web is set.- #[arg(long)]+ #[arg(long, env = "AI_MEMORY_WEB_UI_DIR")]pub web_ui_dir: Option<PathBuf>,/// Base path the whole HTTP surface is served under. Empty (default)/// keeps every route at the host root — byte-identical to previous@@ -3044,6 +3050,18 @@ mod tests {use clap::{CommandFactory, Parser};use std::collections::BTreeSet;+ #[test]+ fn serve_api_only_flag_does_not_enable_the_web_ui() {+ let parsed =+ Cli::try_parse_from(["ai-memory", "serve", "--transport", "http", "--enable-api"])+ .expect("api-only serve args parse");+ let Command::Serve(args) = parsed.command else {+ panic!("expected serve command");+ };+ assert!(args.enable_api);+ assert!(!args.enable_web);+ }+/// The management surface uses the design's spelling (#708):/// `user grant --user … --workspace … --project … --level …`, `user revoke`,/// and listings under `user grants` / `project grants`. A level is neverdiff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 08d62703..09b17755 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1548,6 +1548,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {store.reader.clone(),wiki.clone(),WebMountSpec {+ enable_api: args.enable_api,web_ui_dir: args.web_ui_dir.as_deref(),cors_origins: &cors_origins,web_slug: &args.web_slug,@@ -4403,6 +4404,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: None,cors_origins: &[],web_slug: "/web",@@ -4489,6 +4491,83 @@ mod tests {);}+ #[tokio::test]+ async fn api_only_mode_keeps_data_authenticated_and_web_absent() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let web = split_web_routers(+ false,+ store.reader.clone(),+ wiki,+ WebMountSpec {+ enable_api: true,+ web_ui_dir: None,+ cors_origins: &[],+ web_slug: "/web",+ base_href: "/web/",+ base_path: "",+ trusted_proxy_identity: false,+ },+ )+ .unwrap();+ assert!(web.html_auth.is_none());+ let auth = Arc::new(AuthState::new(Some("secret".to_string())));+ let router = apply_host_layer(+ web.public+ .merge(web.protected.layer(axum::middleware::from_fn_with_state(+ auth,+ require_dual_auth,+ ))),+ vec!["localhost".to_string()],+ );++ let unauthenticated = router+ .clone()+ .oneshot(+ Request::builder()+ .uri("/api/v1/projects")+ .header("Host", "localhost")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(unauthenticated.status(), StatusCode::UNAUTHORIZED);++ let authenticated = router+ .clone()+ .oneshot(+ Request::builder()+ .uri("/api/v1/projects")+ .header("Host", "localhost")+ .header("Authorization", "Bearer secret")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(authenticated.status(), StatusCode::OK);++ let absent_web = router+ .oneshot(+ Request::builder()+ .uri("/web")+ .header("Host", "localhost")+ .header("Authorization", "Bearer secret")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(absent_web.status(), StatusCode::NOT_FOUND);+ }+#[tokio::test]async fn web_routes_are_inside_auth_layer() {let tmp = TempDir::new().unwrap();@@ -4499,6 +4578,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: None,cors_origins: &[],web_slug: "/web",@@ -4644,6 +4724,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: Some(ui.path()),cors_origins: &[],web_slug: "/web",@@ -4705,6 +4786,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: Some(ui.path()),cors_origins: &[],web_slug: "/",diff --git a/crates/ai-memory-web/src/lib.rs b/crates/ai-memory-web/src/lib.rsindex 439bf1f3..81ec6748 100644--- a/crates/ai-memory-web/src/lib.rs+++ b/crates/ai-memory-web/src/lib.rs@@ -54,9 +54,9 @@ pub fn router(reader: ReaderPool, wiki: Wiki) -> Router {/// Build the read-only JSON API router for third-party web UIs.///-/// The host should `nest("/api/v1", api_router(...))` alongside `/web`-/// so custom frontends can browse memory without reading SQLite or wiki-/// files directly.+/// The host should `nest("/api/v1", api_router(...))` behind its normal auth+/// boundary, with or without `/web`, so external clients can browse memory+/// without reading SQLite or wiki files directly.pub fn api_router(reader: ReaderPool, wiki: Wiki) -> Router {let state = Arc::new(WebState::new(reader, wiki));routes::build_api(state)diff --git a/crates/ai-memory-web/src/mount.rs b/crates/ai-memory-web/src/mount.rsindex 8f4a4ab7..71b6b885 100644--- a/crates/ai-memory-web/src/mount.rs+++ b/crates/ai-memory-web/src/mount.rs@@ -295,6 +295,9 @@ mod web_base_tests {/// [`split_web_routers`] below clippy's `too_many_arguments` threshold/// without hiding the call shape.pub struct WebMountSpec<'a> {+ /// Mount `/api/v1` even when the browser UI is disabled. The browser UI+ /// always implies the API for backward compatibility.+ pub enable_api: bool,/// Operator-supplied custom SPA directory (`--web-ui-dir`). `None`/// mounts the built-in server-rendered wiki browser instead.pub web_ui_dir: Option<&'a Path>,@@ -337,7 +340,7 @@ pub fn split_web_routers(wiki: Wiki,spec: WebMountSpec<'_>,) -> Result<SplitWebRouters> {- if !enable_web {+ if !enable_web && !spec.enable_api {return Ok(SplitWebRouters {public: axum::Router::new(),protected: axum::Router::new(),@@ -346,6 +349,13 @@ pub fn split_web_routers(}let api = build_api_router(&reader, &wiki, spec.cors_origins);let protected_api = axum::Router::new().nest("/api/v1", api);+ if !enable_web {+ return Ok(SplitWebRouters {+ public: axum::Router::new(),+ protected: protected_api,+ html_auth: None,+ });+ }let slug = normalize_prefix(spec.web_slug);let mount = if slug.is_empty() { "/" } else { slug.as_str() };if let Some(dir) = spec.web_ui_dir {@@ -673,6 +683,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: None,cors_origins: &[],web_slug,@@ -1074,6 +1085,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: Some(ui.path()),cors_origins: &[],web_slug: "/web",@@ -1151,6 +1163,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: Some(ui.path()),cors_origins: &[],web_slug: "/web",@@ -1200,6 +1213,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: Some(ui.path()),cors_origins: &[],web_slug: "/web",@@ -1259,6 +1273,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: Some(ui.path()),cors_origins: &[],web_slug: "/",@@ -1347,6 +1362,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: None,cors_origins: &cors_origins,web_slug: "/web",@@ -1403,6 +1419,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: None,cors_origins: &cors_origins,web_slug: "/web",@@ -1448,6 +1465,7 @@ mod tests {store.reader.clone(),wiki,WebMountSpec {+ enable_api: false,web_ui_dir: None,cors_origins: &cors_origins,web_slug: "/web",diff --git a/crates/ai-memory-web/tests/suite/pending.rs b/crates/ai-memory-web/tests/suite/pending.rsindex 9a9f5b05..0acf679e 100644--- a/crates/ai-memory-web/tests/suite/pending.rs+++ b/crates/ai-memory-web/tests/suite/pending.rs@@ -435,6 +435,7 @@ async fn pending_page_gate_sees_the_trusted_proxy_setting_through_the_mount() {f.store.reader.clone(),f.wiki.clone(),WebMountSpec {+ enable_api: false,web_ui_dir: None,cors_origins: &[],web_slug: "/web",diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 0306b689..2173d9cd 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -265,8 +265,9 @@ reads and MCP `memory_read_session_observations` share that summary type; neitheresponse includes provider diagnostics.Tools can use MCP directly to write pages, query knowledge and claim handoffs.-With `--enable-web`, incremental `recent` pages use a bounded `(updated_at, path)`-query in the authorized scope. See [programmatic memory](programmatic-memory.md).+With `--enable-api` (or `--enable-web`, which implies it), incremental `recent`+pages use a bounded `(updated_at, path)` query in the authorized scope. API-only+mode mounts no browser routes. See [programmatic memory](programmatic-memory.md).`GET /identity` is a machine-authenticated route mounted independently of theweb UI. `ai-memory doctor` uses it to show caller identity and capture ownership;diff --git a/docs/companion-crates.md b/docs/companion-crates.mdindex 8f3742fd..1ffd1dcc 100644--- a/docs/companion-crates.md+++ b/docs/companion-crates.md@@ -63,6 +63,22 @@ mutation broker. Browsers should talk to the companion; the companion should talto ai-memory with an operator token. That keeps CSRF, confirmation, audit, ratelimits, and UI-specific policy outside the core server.+Read-only companions can start ai-memory with `serve --enable-api` to mount+`/api/v1` without the browser UI. `--enable-web` still implies the same API.+Both modes use the normal machine Bearer or browser-session auth boundary;+writes continue through MCP or authenticated admin routes.++### Proposed team-wiki sync (#986)++A repository-backed team-wiki sync is accepted as a companion shape, not as a+repo-local storage mode in the core server. A contribution should preserve the+prototype's three-way comparison and clone-local state, sync only explicitly+allowed shared page families, default destructive changes to dry-run, report+divergent edits without choosing a winner, and perform every import through+the public MCP write/delete tools. It must never open the wiki directory or+SQLite directly. The core read seam is `/api/v1` in API-only mode; the supported+MCP page arguments are documented in [programmatic memory](programmatic-memory.md).+## `ai-memory-relay`: external lifecycle delivery[`ai-memory-relay`](../companions/ai-memory-relay) delivers events collected bydiff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex a99c36cc..adcfd3b2 100644--- a/docs/frontend-api.md+++ b/docs/frontend-api.md@@ -606,6 +606,18 @@ historical text. Never cached (`no-store`). Same payload as the MCP tool## 6. Custom UI hosting and base paths+For an API-only companion, mount the protected JSON surface without a browser+UI:++```bash+ai-memory serve --transport http --enable-api+```++`--enable-web` continues to imply `/api/v1` for compatibility. `--enable-api`+alone does not mount `/web`, its login pages, static assets, or the unauthenticated+favicon route. The API uses the same machine Bearer or browser-session auth gate+in either mode.+```bashai-memory serve \--transport http \diff --git a/docs/install.md b/docs/install.mdindex bd62144e..0066cfce 100644--- a/docs/install.md+++ b/docs/install.md@@ -757,7 +757,7 @@ for the flake and module — what CI runs, and what each tier proves.`full-ci` label only.2. **Eval contracts** — `nix build .#checks.x86_64-linux.nixos-module-eval`and `nixos-sandbox-parity`. Cheap Linux-only asserts for enable/bind/- `--config`/secrets wiring, refusal messages (age+sops mutex, secrets in+ `--config`/secrets wiring, API-only vs web mounts, refusal messages (age+sops mutex, secrets in`settings.auth`, `settings.bind`), escaped `ExecStart` (`--data-dir`,`serve`, `--transport http`), default `StateDirectory` vs custom`dataDir` tmpfiles/`ReadWritePaths`, and sandbox key parity with@@ -1741,7 +1741,8 @@ The `serve` subcommand also accepts:| Flag | Env var | What it does ||---|---|---|-| `--enable-web` | `AI_MEMORY_ENABLE_WEB=true` | Mount the read-only web browser + `/api/v1` JSON API. |+| `--enable-web` | `AI_MEMORY_ENABLE_WEB=true` | Mount the read-only web browser and `/api/v1` JSON API. |+| `--enable-api` | `AI_MEMORY_ENABLE_API=true` | Mount only the protected, read-only `/api/v1` JSON API for companions and other non-browser clients. || `--base-path /wiki` | `AI_MEMORY_BASE_PATH` | Host the entire HTTP surface (`/mcp`, `/hook`, `/admin/*`, `/api/v1`, `/web`) under a configurable subpath — useful behind a reverse proxy sharing a hostname. `.` and `..` segments are rejected; unsafe chars cause a fallback to root with a warning. See [`docs/https-via-proxy.md`](https-via-proxy.md#hosting-under-a-subpath). || `--web-slug /web` | `AI_MEMORY_WEB_SLUG` | Where the web UI mounts within the base-path. Default `/web`; set to `/` to mount the UI at the base-path root. || `--web-ui-dir <path>` | `AI_MEMORY_WEB_UI_DIR` | Serve a custom SPA from `<path>` instead of the built-in browser. ai-memory injects `<base href>` and `<meta name="ai-memory-base-path">` so the SPA can build relative URLs and API calls under the configured prefix. |diff --git a/docs/programmatic-memory.md b/docs/programmatic-memory.mdindex 5ffb6d3a..7ddb1c3b 100644--- a/docs/programmatic-memory.md+++ b/docs/programmatic-memory.md@@ -78,8 +78,9 @@ historical text, even after sanitization.## Read changed pages-These JSON endpoints require `serve --enable-web` and the same machine key.-They are read-only; memory writes remain MCP calls.+These JSON endpoints require `serve --enable-api` (or `--enable-web`, which+continues to imply the API) and the same machine key. They are read-only;+memory writes remain MCP calls.```httpGET /api/v1/workspaces/demo/projects/app/recent?updated_since=2026-09-01T00%3A00%3A00Z&limit=100diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 2065ee11..08116adc 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -25,7 +25,7 @@ boundary not yet built.| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can) | STRONG || 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG || 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate | STRONG |-| 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root`; `identity.rs` authorizes `NormalRead` behind the same machine bearer middleware as MCP | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users`; `identity.rs` `identity_real_auth_isolates_users_root_and_revoked_keys`, `identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc` (distinct users and root, invalid/revoked keys, forged headers, anonymous control) | STRONG |+| 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root`; `identity.rs` authorizes `NormalRead` behind the same machine bearer middleware as MCP; `serve.rs` mounts API-only and web+API protected routers behind `require_dual_auth` | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users`; `identity.rs` `identity_real_auth_isolates_users_root_and_revoked_keys`, `identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc` (distinct users and root, invalid/revoked keys, forged headers, anonymous control); `serve.rs` `api_only_mode_keeps_data_authenticated_and_web_absent` (anonymous API read refused, authenticated control admitted, browser route absent; #986) | STRONG || 3b | Browser triage of pending writes (#855) | `ai-memory-web/src/routes/pending.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, trusted-proxy flag from `WebMountSpec`) gates `GET {web_slug}/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect; decisions post to the existing `/admin/pending-writes/{id}/approve\|reject` behind `require_dual_auth` (session + CSRF) and `require_root_for_multiuser_admin`. `ai-memory-web` has no write route | `ai-memory-web` `tests/suite/pending.rs` — anonymous refused (401, login redirect), DB user refused (403, no proposal text, no redirect), trusted-proxy flag reaches the gate, single-operator control admits, POSTs to `/pending*` refused, project filter keys do not collide on `/` in names, projects past the 500-row read cap stay counted and reachable; `ai-memory-mcp` `tests/suite/admin_pending_writes_session.rs` — anonymous and DB-user sessions refused, root session without a matching CSRF header refused (each leaves the proposal pending and no file), root approval keeps `auto_improve_proposal_id`/`auto_improve_run_id` and records the approver, root reject writes no file (each proven to fail with its guard removed) | STRONG || 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff` | STRONG || 4b | Handoff owner-scoped recovery (`any_owner` admin gate) | `ai-memory-mcp/src/server.rs` `require_admin_capability` on `memory_handoff_accept`/`_cancel` `any_owner` | `handoff_admission.rs` — cancel gate + **accept gate** (adversarial: non-admin `any_owner` accept refused) | STRONG |diff --git a/flake.nix b/flake.nixindex b6d80ca6..ae8ba3a0 100644--- a/flake.nix+++ b/flake.nix@@ -94,6 +94,12 @@# wiring, it isn't asserting what the default is.enabled = mkNixos { services.ai-memory = { enable = true; enableWeb = true; }; };disabled = mkNixos { services.ai-memory.enable = false; };+ apiOnly = mkNixos {+ services.ai-memory = {+ enable = true;+ enableApi = true;+ };+ };withSettings = mkNixos {services.ai-memory = {enable = true;@@ -210,6 +216,7 @@settingsExec =withSettings.config.systemd.services.ai-memory.serviceConfig.ExecStart;ipv6Exec = withIpv6Loopback.config.systemd.services.ai-memory.serviceConfig.ExecStart;+ apiOnlyExec = apiOnly.config.systemd.services.ai-memory.serviceConfig.ExecStart;ageUnit = withAge.config.systemd.services.ai-memory;customSc = withCustomDataDir.config.systemd.services.ai-memory.serviceConfig;customTmpfiles = withCustomDataDir.config.systemd.tmpfiles.settings."10-ai-memory";@@ -267,6 +274,8 @@nixosChecks = {nixos-module-eval =assert lib.hasInfix (escapedExecArgs [ "--enable-web" ]) execStart;+ assert lib.hasInfix (escapedExecArgs [ "--enable-api" ]) apiOnlyExec;+ assert !(lib.hasInfix (escapedExecArgs [ "--enable-web" ]) apiOnlyExec);assert lib.hasInfix(escapedExecArgs [ "--bind" "127.0.0.1:49374" ]) execStart;assert lib.hasInfixdiff --git a/nix/nixos-module.nix b/nix/nixos-module.nixindex f80af90a..6d412d14 100644--- a/nix/nixos-module.nix+++ b/nix/nixos-module.nix@@ -92,6 +92,7 @@ let"--bind""${bindHost}:${toString cfg.port}"]+ ++ lib.optionals cfg.enableApi [ "--enable-api" ]++ lib.optionals cfg.enableWeb [ "--enable-web" ];in{@@ -136,6 +137,17 @@ inPass --enable-web (mounts the built-in web UI at /web). Off bydefault, matching the underlying --enable-web CLI flag's owndefault — NOT the packaged FHS systemd unit, which hardcodes it on.+ Enabling the web UI also mounts `/api/v1`; `enableApi` is unnecessary+ in that mode.+ '';+ };++ enableApi = lib.mkOption {+ type = lib.types.bool;+ default = false;+ description = ''+ Pass --enable-api to mount the protected read-only `/api/v1` surface+ without the browser UI. Off by default.'';};@@ -148,7 +160,8 @@ indescription = ''Declarative config.toml fragment (non-secret keys only). Rendered to agenerated file and passed as `--config`. Top-level `bind`, `port`, and- `enableWeb` service options win over duplicate keys here.+ `enableWeb`, and `enableApi` service options win over duplicate keys+ here.A small typed set covers common keys; `freeformType` accepts any otherTOML key. Values here land in a world-readable Nix store path — never