Skip to content
2 changes: 1 addition & 1 deletion .docs/wiki/Agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ The server is `POST /mcp` on the engine: Streamable HTTP in stateless JSON, prot
| Allowed | Changes to the library go ahead. An export or an import still asks. |
| Blocked | Every agent is refused, reads included, and so are the agents in the terminal panel. Questions that were waiting are answered Deny. |

The choice is kept in `settings.json` beside the library setting. Where the system has a keychain, it is sealed with a key kept there; a change made outside the app that allows agents is ignored, the app asks again, and Preferences says so. An agent in one of the panel's own tabs carries a token for that tab: its library changes are not asked about, and an export or an import still is.
The choice is kept in `settings.json` beside the library setting. It is sealed with a key kept in the system keychain; a change made outside the app that allows agents is ignored, the app asks again, and Preferences says so. With no system keyring at all (some Linux setups without a secret service), a stored Allowed reads as Ask, Allowed cannot be chosen, the question in the window has no Always allow, and Preferences says that these need a system keyring on this computer. An agent in one of the panel's own tabs carries a token for that tab: its library changes are not asked about, and an export or an import still is.

## Connecting a client

Expand Down
10 changes: 10 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ Last updated: 2026-11-27 · scenes of your own

---

## unreleased · with no system keyring a stored Allowed reads as Ask

- refers-to: core/seal.py :: _ring, effective; services/agent_access.py :: NeedsKeyring, can_allow, state, set_choice; routers/mcp.py :: _gate
- kind: decision
- logged: 2026-11-28

- Replaces "without a keychain the value is used as written" below. When no system keyring answers at all (a Linux desktop with no secret service, for example), the seal cannot be made, so a yes in settings.json cannot be told apart from one written by another program. `effective` then reads `agentsAllowed` as false (`seal: unavailable`), Ask and Blocked read as written, and the file is left as it is. `set_choice("allowed")` raises `NeedsKeyring` (the route answers 422 with a plain reason), and the question in the window offers only Deny and Allow once, so an Always answer cannot be given. `GET /api/agents` carries `keyring: false`, and Preferences shows a note and greys out Allowed. When a keyring is there nothing changes.
- `_ring()` is the one place keyring is imported, so the tests swap in an in-memory keyring (tests/conftest.py, autouse) and never reach the system one.
- A keyring that answers but refuses the key or does not keep it counts as none: `_load(True)` then marks the seal unavailable. `set_choice("allowed")` first makes the key (`seal.ready()`) and raises `NeedsKeyring` when it cannot, so an unsealed yes is never written, and an Always answer in that case counts as Allow once.

## unreleased · a save never replaces a different movie

- refers-to: routers/library.py :: _all_movies, _lands_on_other_movie, write_project
Expand Down
33 changes: 25 additions & 8 deletions backend/app/core/seal.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""The seal on the outside-agents choice in settings.json: an HMAC whose key lives in the system keychain, so a change
made to the file outside the app cannot turn outside agents on. FormDeck 0.46.3's core/seal.py with this app's names."""
made to the file outside the app cannot turn outside agents on. FormDeck 0.46.3's core/seal.py with this app's names.
With no system keyring at all nothing can be sealed, so a stored Allowed reads as Ask."""
import hashlib
import hmac
import json
Expand All @@ -24,20 +25,29 @@ def _no_ld_probe() -> None:
ctypes.util._findLib_ld = lambda name: None


def _ring():
_no_ld_probe()
import keyring

return keyring


def _load(create: bool) -> bytes | None:
if _CACHE["tried"] and (_CACHE["key"] is not None or not _CACHE["available"] or not create):
return _CACHE["key"]
_CACHE["tried"] = True
try:
_no_ld_probe()
import keyring

stored = keyring.get_password(SERVICE, ACCOUNT)
ring = _ring()
stored = ring.get_password(SERVICE, ACCOUNT)
if not stored and create:
keyring.set_password(SERVICE, ACCOUNT, secrets.token_hex(32))
stored = keyring.get_password(SERVICE, ACCOUNT)
ring.set_password(SERVICE, ACCOUNT, secrets.token_hex(32))
stored = ring.get_password(SERVICE, ACCOUNT)
key = bytes.fromhex(stored) if stored else None
except Exception:
key = None
create = True
if create and key is None:
# a keyring that refuses the key or does not keep it cannot seal anything, so it counts as none
_CACHE.update(available=False, key=None)
return None
_CACHE.update(available=True, key=key)
Expand All @@ -49,6 +59,11 @@ def available() -> bool:
return _CACHE["available"]


def ready() -> bool:
"""True when the key is in the keyring, made now if need be, so a choice can be sealed."""
return _load(True) is not None


def sealed(values: dict) -> dict:
blocked = {"agentsBlocked": True} if values.get("agentsBlocked") is True else {}
return {"agentsAllowed": bool(values.get("agentsAllowed")), **blocked}
Expand All @@ -67,7 +82,9 @@ def effective(stored: dict) -> dict:
out = {k: v for k, v in stored.items() if k != FIELD}
key = _load(False)
if not _CACHE["available"]:
return {**out, "seal": "unavailable", "sealBroken": False}
# fail closed: with no keyring a yes in the file cannot be told apart from one written outside the app
held = {"agentsAllowed": False} if loosened(stored) else {}
return {**out, **held, "seal": "unavailable", "sealBroken": False}
mark = stored.get(FIELD)
if key is not None and isinstance(mark, str) and hmac.compare_digest(mark, digest(stored, key)):
return {**out, "seal": "ok", "sealBroken": False}
Expand Down
11 changes: 8 additions & 3 deletions backend/app/routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,15 +243,20 @@ async def _gate(a: Agent, kind: str, what: str) -> str | None:
return OFF
if time.monotonic() < _declined[0]:
return DECLINED
offers = ["deny", "once"] if kind == "asks" else ["deny", "once", "always"]
# a standing yes needs a keyring to seal it, so without one the window offers only this once
always = kind == "changes" and agent_access.can_allow()
offers = ["deny", "once", "always"] if always else ["deny", "once"]
said = await bridge.ask("" if a.inapp else a.name, what, offers, CONSENT_WAIT)
if said is None:
return f"Nobody answered in the FormMorpheus window within {int(CONSENT_WAIT // 60)} minutes, so nothing was done. Ask the person to answer there, then retry."
if said == "deny":
_declined[0] = time.monotonic() + DECLINE_PAUSE
return "The person said no in the FormMorpheus window, so nothing was done."
if said == "always" and kind == "changes":
agent_access.set_choice("allowed")
if said == "always" and always:
try:
agent_access.set_choice("allowed")
except agent_access.NeedsKeyring:
pass # the keyring would not keep the key, so this answer counts as once
return None


Expand Down
12 changes: 11 additions & 1 deletion backend/app/services/agent_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,18 @@
CHOICES = ("ask", "allowed", "blocked")


class NeedsKeyring(ValueError):
"""Allowed cannot be kept: with no system keyring it could not be sealed, and an unsealed yes reads as Ask."""


def can_allow() -> bool:
return seal.available()


def state() -> dict:
s = seal.effective(config.read_settings())
value = "blocked" if s.get("agentsBlocked") is True else "allowed" if s.get("agentsAllowed") is True else "ask"
return {"choice": value, "changedOutside": bool(s.get("sealBroken")), "seal": s.get("seal")}
return {"choice": value, "changedOutside": bool(s.get("sealBroken")), "seal": s.get("seal"), "keyring": s.get("seal") != "unavailable"}


def choice() -> str:
Expand All @@ -18,6 +26,8 @@ def choice() -> str:
def set_choice(value: str) -> dict:
if value not in CHOICES:
raise ValueError(f"The choice is one of {', '.join(CHOICES)}.")
if value == "allowed" and not seal.ready():
raise NeedsKeyring("Allowed needs a system keyring on this computer, and none was found, so outside agents keep asking.")
mark = {"allowed": {"agentsAllowed": True}, "blocked": {"agentsBlocked": True}}.get(value, {})

def change(settings: dict) -> dict:
Expand Down
36 changes: 36 additions & 0 deletions backend/tests/agents/test_agents_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,39 @@ def test_a_valid_answer_reaches_the_bridge(client, world):
res = client.post("/api/agents/consent/q1", json={"choice": "once"})
assert res.status_code == 200 and res.json() == {"ok": True}
assert world["answered"] == [("q1", "once")]


def test_state_says_a_keyring_is_there(client, world):
assert client.get("/api/agents").json()["keyring"] is True


def test_without_a_keyring_a_stored_allowed_reads_as_ask(data_dir, no_ring):
config.write_settings({"agentsAllowed": True})
assert agent_access.state() == {"choice": "ask", "changedOutside": False, "seal": "unavailable", "keyring": False}
assert config.read_settings() == {"agentsAllowed": True}


def test_without_a_keyring_blocked_still_blocks(data_dir, no_ring):
agent_access.set_choice("blocked")
assert agent_access.choice() == "blocked"


def test_without_a_keyring_allowed_cannot_be_chosen(data_dir, no_ring):
agent_access.set_choice("ask")
with pytest.raises(agent_access.NeedsKeyring):
agent_access.set_choice("allowed")
assert "agentsAllowed" not in config.read_settings()
assert agent_access.choice() == "ask"


def test_without_a_keyring_the_route_refuses_allowed_with_a_plain_reason(client, world, no_ring):
res = client.post("/api/agents/choice", json={"value": "allowed"})
assert res.status_code == 422
assert "keyring" in res.json()["detail"]
assert client.get("/api/agents").json()["choice"] == "ask"


def test_a_keyring_that_keeps_nothing_refuses_allowed(data_dir, forgetful_ring):
with pytest.raises(agent_access.NeedsKeyring):
agent_access.set_choice("allowed")
assert agent_access.state() == {"choice": "ask", "changedOutside": False, "seal": "unavailable", "keyring": False}
42 changes: 42 additions & 0 deletions backend/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,48 @@ def data_dir(tmp_path, monkeypatch) -> Path:
return path


@pytest.fixture(autouse=True)
def ring(monkeypatch) -> dict:
"""An in-memory keyring for the settings seal, so no test reaches the system one."""
from types import SimpleNamespace

from app.core import seal

store: dict = {}
fake = SimpleNamespace(
get_password=lambda service, account: store.get((service, account)),
set_password=lambda service, account, value: store.__setitem__((service, account), value),
)
monkeypatch.setattr(seal, "_ring", lambda: fake)
monkeypatch.setattr(seal, "_CACHE", {"tried": False, "available": False, "key": None})
return store


@pytest.fixture
def no_ring(monkeypatch) -> None:
"""A computer with no system keyring at all."""
from types import SimpleNamespace

from app.core import seal

def missing(*args):
raise RuntimeError("no keyring")

monkeypatch.setattr(seal, "_ring", lambda: SimpleNamespace(get_password=missing, set_password=missing))
monkeypatch.setattr(seal, "_CACHE", {"tried": False, "available": False, "key": None})


@pytest.fixture
def forgetful_ring(monkeypatch) -> None:
"""A keyring that answers but keeps nothing it is given."""
from types import SimpleNamespace

from app.core import seal

monkeypatch.setattr(seal, "_ring", lambda: SimpleNamespace(get_password=lambda *a: None, set_password=lambda *a: None))
monkeypatch.setattr(seal, "_CACHE", {"tried": False, "available": False, "key": None})


@pytest.fixture
def window_headers() -> dict:
from app.core import window_key
Expand Down
55 changes: 26 additions & 29 deletions backend/tests/core/test_seal.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,6 @@
import sys
from types import SimpleNamespace

import pytest

from app.core import seal


@pytest.fixture
def ring(monkeypatch):
store = {}
fake = SimpleNamespace(
get_password=lambda service, account: store.get((service, account)),
set_password=lambda service, account, value: store.__setitem__((service, account), value),
)
monkeypatch.setitem(sys.modules, "keyring", fake)
monkeypatch.setattr(seal, "_no_ld_probe", lambda: None)
monkeypatch.setattr(seal, "_CACHE", {"tried": False, "available": False, "key": None})
return store


@pytest.fixture
def no_ring(monkeypatch):
def broken(*args):
raise RuntimeError("no keychain")

monkeypatch.setitem(sys.modules, "keyring", SimpleNamespace(get_password=broken, set_password=broken))
monkeypatch.setattr(seal, "_no_ld_probe", lambda: None)
monkeypatch.setattr(seal, "_CACHE", {"tried": False, "available": False, "key": None})
# the ring and no_ring fixtures live in tests/conftest.py


def test_only_the_agent_choice_is_sealed():
Expand Down Expand Up @@ -89,14 +63,37 @@ def test_agents_cannot_be_on_before_any_key_exists(ring):
assert seen["seal"] == "broken"


def test_without_a_keychain_the_seal_is_reported_unavailable(no_ring):
def test_without_a_keyring_a_stored_allowed_reads_as_ask(no_ring):
assert seal.available() is False
assert seal.effective({"agentsAllowed": True, "seal": "x"}) == {"agentsAllowed": True, "seal": "unavailable", "sealBroken": False}
assert seal.effective({"agentsAllowed": True, "seal": "x"}) == {"agentsAllowed": False, "seal": "unavailable", "sealBroken": False}
assert seal.effective({"agentsAllowed": True, "theme": "dark"})["agentsAllowed"] is False
assert seal.sign({"agentsAllowed": True, "seal": "old"}) == {"agentsAllowed": True}


def test_without_a_keyring_ask_and_blocked_read_as_written(no_ring):
assert seal.effective({"theme": "dark"}) == {"theme": "dark", "seal": "unavailable", "sealBroken": False}
assert seal.effective({"agentsBlocked": True}) == {"agentsBlocked": True, "seal": "unavailable", "sealBroken": False}


def test_with_a_keyring_a_sealed_allowed_is_unchanged(ring):
signed = seal.sign({"agentsAllowed": True})
assert seal.effective(signed)["agentsAllowed"] is True
assert seal.effective(signed)["seal"] == "ok"


def test_reset_forgets_what_was_learnt_about_the_keychain(ring):
seal.sign({"agentsAllowed": True})
assert seal._CACHE["key"] is not None
seal.reset()
assert seal._CACHE == {"tried": False, "available": False, "key": None}


def test_a_keyring_that_keeps_nothing_counts_as_none(forgetful_ring):
assert seal.ready() is False
assert seal.available() is False
assert seal.effective({"agentsAllowed": True})["seal"] == "unavailable"


def test_ready_makes_the_key_when_a_keyring_is_there(ring):
assert seal.ready() is True
assert seal.available() is True
33 changes: 33 additions & 0 deletions backend/tests/mcp/test_mcp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,36 @@ def test_inside_refuses_a_path_that_climbs_out_of_the_folder(tmp_path):
assert mcp._inside(folder / "a.fmo", folder) is True
assert mcp._inside(folder, folder) is True
assert mcp._inside(folder / ".." / "secret.txt", folder) is False


def test_without_a_keyring_a_stored_allowed_still_asks(client, no_ring):
from app.core import config

config.write_settings({"agentsAllowed": True})
result = call(client, "manage_movie", {"action": "create", "name": "First"})
assert result["isError"] is True
assert text(result) == mcp.OFF
assert names(client) == []


def test_without_a_keyring_the_window_does_not_offer_always(client, monkeypatch, no_ring):
seen = []
answer_with(monkeypatch, "once", seen)
call(client, "manage_movie", {"action": "create", "name": "First"})
assert seen[0][2] == ["deny", "once"]
assert names(client) == ["First"]


def test_without_a_keyring_an_always_answer_counts_as_once(client, monkeypatch, no_ring):
answer_with(monkeypatch, "always")
result = call(client, "manage_movie", {"action": "create", "name": "First"})
assert "isError" not in result
assert agent_access.choice() == "ask"


def test_an_always_answer_the_keyring_cannot_keep_counts_as_once(client, monkeypatch, forgetful_ring):
answer_with(monkeypatch, "always")
result = call(client, "manage_movie", {"action": "create", "name": "First"})
assert "isError" not in result
assert names(client) == ["First"]
assert agent_access.state()["keyring"] is False
4 changes: 2 additions & 2 deletions docs/MANUAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -850,7 +850,7 @@ Open Preferences (Ctrl+,) and choose **Agents**. **Outside agents** has three ch
| Allowed | Changes to the library go ahead without asking. An export or an import still asks each time. |
| Blocked | Every agent is refused, reads included, and so are the agents in the terminal panel. A question that was waiting is answered Deny. |

An agent you open yourself in the terminal panel is treated as yours: under Ask or Allowed it makes library changes without asking, and an export or an import still asks. Where the system has a keychain, FormMorpheus seals the choice with a key kept there. If the setting is changed from outside the app to allow agents, FormMorpheus ignores that change, asks again, and says so in Preferences.
An agent you open yourself in the terminal panel is treated as yours: under Ask or Allowed it makes library changes without asking, and an export or an import still asks. FormMorpheus seals the choice with a key kept in the system keychain. If the setting is changed from outside the app to allow agents, FormMorpheus ignores that change, asks again, and says so in Preferences. On a computer with no system keyring at all, such as some Linux setups without a secret service, Allowed cannot be sealed, so it is not offered: outside agents ask each time, the question in the window has no Always allow, and Preferences says that Allowed and Always allow need a system keyring on this computer.

### Connect a client

Expand All @@ -872,7 +872,7 @@ When an agent needs your yes, a box opens in the middle of the FormMorpheus wind

- **Deny**: nothing is done. For the next 2 minutes the agent's requests that need your yes are refused without asking again. Escape also denies.
- **Allow once**: this one request goes ahead.
- **Always allow all outside agents**: sets Outside agents to Allowed. It is not offered for an export or an import, which always ask.
- **Always allow all outside agents**: sets Outside agents to Allowed. It is not offered for an export or an import, which always ask, nor on a computer with no system keyring.

If nobody answers within 2 minutes, the question closes and nothing is done.

Expand Down
9 changes: 5 additions & 4 deletions frontend/src/dock-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,13 @@ export const outsideAgents = {
for (const request of had.requests ?? []) outsideAgents.show(request);
} catch { return; }
},
async get(): Promise<StoredChoiceState> {
/** `keyring` false: this computer has no system keyring, so Allowed cannot be kept and the engine asks each time. */
async get(): Promise<StoredChoiceState & { keyring: boolean }> {
try {
const s = await call<{ choice?: unknown; changedOutside?: unknown }>('/api/agents');
const s = await call<{ choice?: unknown; changedOutside?: unknown; keyring?: unknown }>('/api/agents');
choice = s.choice === 'blocked' || s.choice === 'allowed' ? s.choice : 'ask';
return { value: choice, changedOutside: s.changedOutside === true };
} catch { return { value: choice, changedOutside: false }; }
return { value: choice, changedOutside: s.changedOutside === true, keyring: s.keyring !== false };
} catch { return { value: choice, changedOutside: false, keyring: true }; }
},
async set(value: StoredChoice): Promise<void> {
await call('/api/agents/choice', 'POST', { value });
Expand Down
Loading
Loading