8000 feat(sources): shared routing rules for an email account by adeelahmad · Pull Request #597 · adeelahmad/lense · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,10 @@ listed under [In progress](#in-progress), and what comes next under [Planned](#p
[adding an MCP server](docs/assistant.md#adding-an-mcp-server), [the MCP runner](docs/assistant.md#the-mcp-runner);
[checks](docs/requirements.md#extend-the-assistant))
- **Bring in everything.** Watched folders on S3, Dropbox, Google Drive, OneDrive, SFTP, SMB, WebDAV or local disks (a
local folder in four clicks); IMAP mail, Gmail and Google Workspace, iCal calendars, Google Calendar and RSS and Atom
news feeds; a built-in MQTT broker, syslog and webhook streams; import webhooks for scanners and phone shortcuts, which can
hand back the PDFs of Office files and emails a light server can't convert itself.
local folder in four clicks); IMAP mail, Gmail and Google Workspace (routing rules send a shared inbox's mail to the
right namespaces), iCal calendars, Google Calendar and RSS and Atom news feeds; a built-in MQTT broker, syslog and
webhook streams; import webhooks for scanners and phone shortcuts, which can hand back the PDFs of Office files and
emails a light server can't convert itself.
Google accounts connect with Connect with Google once Lens has a Google client, and Dropbox, OneDrive and Google
Drive can sign in through rclone on the Lens server, with no app of your own to register. Upload audio, video, PDFs,
Office files, photos, JSON and zip or tar archives, and, with an Apache Tika server (an opt-in extra), documents
Expand Down
7 changes: 7 additions & 0 deletions changelog.d/imap-shared-routes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
- **Shared routing rules for an email account.** An IMAP or Gmail account can carry routing rules that every watch
on it uses, so a shared inbox's policy (support@ to support, newsletters skipped) is written once rather than on
each mailbox's watch. A watch tries its own rules first, then the account's, then its namespace; with no shared
rules nothing changes. They're edited from the account's More menu on the Sources page or saved with
`PUT /api/v1/sources/{id}/routes`; the routes preview takes `shared_routes` and says which list decided, and agents
read and change every account's and watch's rules with the MCP tools `mail_routing` and `set_mail_routing`
([Email](docs/processing.md#email-imap-calendar-feeds-ical-and-google-calendar)).
4 changes: 3 additions & 1 deletion docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ For an app that speaks OpenAI's API rather than MCP, the namespace can also answ
| `news_feeds` | the news feeds (RSS or Atom) Lens follows, the namespaces each brings posts into and how the last scan went; addresses stay sealed. Admins only |
| `subscribe_feed` | follow a news feed into a namespace in one step: its address or a page of the site, read first and kept only if it works; `backfill` also brings in the posts it lists now ([News feeds](processing.md#news-feeds-rss-and-atom)). Admins only, with a write-scope token |
| `unsubscribe_feed` | stop following a news feed; the posts it brought in stay. Admins only, with a write-scope token |
| `mail_routing` | each email account's shared routing rules and each watch's own, as lines like `from: *@acme.com = finance` ([Email](processing.md#email-imap-calendar-feeds-ical-and-google-calendar)). Admins only |
| `set_mail_routing` | replace an email account's shared routing rules, or one watch's own; they apply to messages that arrive afterwards. Admins only, with a write-scope token |
| `propose_graph_change` | ask for two entities to be merged or linked; it waits in Proposed changes unless `apply` makes it at once (it can be undone). Needs a write-scope token and editor access |
| `undo_graph_change` | take back a merge or link `propose_graph_change` made. Needs a write-scope token and editor access |
| `edit_entity` | rename an entity, change its type, describe it, set the other ways it's said, or hide or show it. Needs a write-scope token and editor access | 8000
Expand All @@ -186,7 +188,7 @@ queues an episode, `create_feed` and `publish_to_feed`, which make and fill a [p
editors), `enhance`, which enhances an image and reads it again (the process permission),
`set_namespace_integrations`, which turns a namespace's own MCP server or chat completions on or off (owners), `set_picture_descriptions`, which changes what describes pictures (admins), `set_file_storage`, which changes where new files are kept (admins), `set_secret_reference`, which points a secret field at a password manager's item (admins), `install_plugin`, which
installs a plugin from a marketplace as your own extension, `add_mcp_server`, which adds an
MCP server (admins), `subscribe_feed` and `unsubscribe_feed`, which follow and stop following news feeds (admins), and `set_monitoring`, `set_service`,
MCP server (admins), `subscribe_feed` and `unsubscribe_feed`, which follow and stop following news feeds (admins), `set_mail_routing`, which changes where an email account's messages go (admins), and `set_monitoring`, `set_service`,
`set_sandbox_gateway` (the [code sandbox](assistant.md#code-sandbox)'s gateway) and `set_install_settings`, which have the machine change how Lens runs (admins).
Importing stays in the web app and the API.

Expand Down
7 changes: 7 additions & 0 deletions docs/processing.md
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,13 @@ importing chosen ones and watching work as above. [News feeds](#news-feeds-rss-a
exists (rules never create one); mail for a namespace deleted since goes to the watch's. Rules apply to messages that
arrive after they're saved. `POST /api/v1/watches/routes/preview` shows where the latest messages would go before
saving, and a scan's stats count the messages `routed` elsewhere.
An email account can also carry **shared rules**, written once for every watch on it (in the web app the account's
More menu on the Sources page, Routing rules; or `PUT /api/v1/sources/{id}/routes`): mail to support@ goes to support, newsletters are skipped, whichever mailbox a watch
takes. A watch tries its own rules first, then the account's, then sends the message to its namespace, so a watch's
rule can make an exception to the account's. With no shared rules nothing changes. The preview uses the saved
shared rules, or `shared_routes` to try ones not saved yet, and says which list decided (`shared`). Agents read
every account's and watch's rules with the MCP tool `mail_routing` and change them with `set_mail_routing`, as
lines like `from: *@acme.com; subject: invoice = finance`.
- **Gmail and Google Workspace**: see [below](#gmail-and-google-workspace).
- **Calendar feed (iCal)**: the calendar's iCal address (`https://` or `webcal://`; a user and password if it asks for
one). The address is kept encrypted like a password and never shown again, since a private calendar's address is
Expand Down
1 change: 1 addition & 0 deletions docs/requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ request, to another check that proves the same thing; loosening a requirement or
| A local folder in four clicks | [journeys.mjs](https://github.com/adeelahmad/lense/blob/main/ci/clicks/journeys.mjs) `source-folder`; [baseline.json](https://github.com/adeelahmad/lense/blob/main/ci/clicks/baseline.json) `source-folder` ≤ 4 clicks; [watch-folder.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/watch-folder.test.tsx) |
| A watched folder on each kind of storage connection, run against rclone in CI | No check yet ([#486](https://github.com/adeelahmad/lense/issues/486)) |
| IMAP mail, Gmail and Google Workspace | [test_mail_calendar_sources.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_mail_calendar_sources.py) `test_an_imap_account_as_a_source`, `test_an_imap_message_is_an_email_document_with_its_attachments`; [test_gmail_source.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_gmail_source.py) `test_a_workspace_mailbox_through_the_gmail_api`, `test_a_connected_google_account` |
| A shared inbox's mail routed to namespaces, or skipped, by rules on a watch and shared rules on the email account that every watch on it tries after its own; agents read and change them over MCP | [test_mail_routes.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_mail_routes.py) `test_a_shared_inbox_routed_to_namespaces`, `test_an_accounts_shared_rules_apply_to_every_watch`, `test_agents_read_and_change_routing_rules` |
| iCal calendars and Google Calendar | [test_mail_calendar_sources.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_mail_calendar_sources.py) `test_a_calendar_feed_as_a_source`; [test_google_calendar_source.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_google_calendar_source.py) `test_a_shared_calendar_read_as_a_service_account`, `test_a_connected_google_account` |
| RSS and Atom news feeds: a feed or a site's page as a source, each post imported as text with its link, author and date; private networks only when allowed | [test_news_feed_source.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_news_feed_source.py) `test_a_news_feed_as_a_source`, `test_feed_addresses`, `test_what_a_feed_holds_stays_data`, `test_a_feed_file_imported_as_text` |
| Agents follow news feeds in one step: MCP `subscribe_feed` checks a feed and watches it into a namespace, `news_feeds` lists them with addresses sealed, `unsubscribe_feed` stops one; 8BD0 the assistant's tools ask first | [test_news_feed_source.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_news_feed_source.py) `test_subscribing_in_one_step`; [test_setup_assistant.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_setup_assistant.py) `test_the_assistant_follows_news_feeds` |
Expand Down
84 changes: 84 additions & 0 deletions fastapi_backend/app/api/mcp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
graph_history,
integrations,
library,
mail_routes,
manual,
mcp_servers,
monitoring,
Expand Down Expand Up @@ -3496,6 +3497,89 @@ def unsubscribe_feed(ctx: Context, feed: int) -> dict[str, Any]:
return {"unsubscribed": feed}


# ---------- mail routing rules (admins) ----------
def _routing_admin(ctx: Context, write: bool = False) -> None:
if not ctx.user.admin:
raise ToolError("only admins see or change where email accounts' messages go")
if write and not ctx.user.can_write:
raise ToolError("this token is read-only: ask for a token with the write scope to change mail routing rules")


def _lines(rules: list[dict[str, Any]]) -> list[str]:
return [mail_routes.line({**r, "namespace": r["namespace"] or "(deleted namespace)"}) for r in rules]


@tool(
"mail_routing",
"Mail routing rules",
"Where the messages of each email account (IMAP or Gmail) go: the account's shared routing rules, which every "
"watch on it uses, and each watch's own rules and namespace. A new message is sent by the first of the watch's "
"rules that matches, else the first of the account's, else it goes to the watch's namespace. Rules are lines like "
"from: *@acme.com, *@acme.org; subject: invoice = finance (conditions on from, to, subject, list or mailbox joined "
"by ;, patterns by a comma, then = a namespace or = skip). Admins only.",
admin=True,
)
def mail_routing(ctx: Context) -> dict[str, Any]:
_routing_admin(ctx)
watches = sources.list_watches(ctx.db)
accounts = [
{
"account": s["id"],
"name": s["name"],
"type": s["type"],
"shared_rules": _lines(s["routes"]),
"watches": [
{"watch": w["id"], "path": w["path"] or "(every mailbox)", "namespace": w["namespace"], "rules": _lines(w["routes"])}
for w in watches
if w["source"] == s["id"]
],
}
for s in sources.list_sources(ctx.db)
if feeds.is_email(s)
]
return {"accounts": accounts, "settings": f"{ctx.web}/sources"}


@tool(
"set_mail_routing",
"Change mail routing rules",
"Replace an email account's shared routing rules (account, from mail_routing), or with watch one watch's own "
"rules, by rules: lines as mail_routing shows them, tried in order; an empty list removes them. A rule names a "
"namespace that exists. They apply to messages that arrive afterwards. Admins only, with a token that has the "
"write scope.",
Arg("account", "integer", "the email account's id, from mail_routing", required=True),
Arg("rules", "string[]", "the rules, like from: *@acme.com = finance or list: * = skip; [] for none", required=True, default=[]),
Arg("watch", "integer", "a watch on that account whose own rules to replace (else the account's shared ones)"),
writes=True,
admin=True,
)
def set_mail_routing(ctx: Context, account: int, rules: list[str], watch: int | None = None) -> dict[str, Any]:
_routing_admin(ctx, write=True)
try:
src = sources.get(ctx.db, int(account))
except KeyError:
raise ToolError(f"there's no source {account}") from None
if not feeds.is_email(src):
raise ToolError("that source isn't an email account")
if not isinstance(rules, list) or len(rules) > mail_routes.MAX_RULES or not all(isinstance(r, str) for r in rules):
raise ToolError(f"rules is a list of up to {mail_routes.MAX_RULES} lines, like from: *@acme.com = finance")
try:
parsed = [mail_routes.parse_line(r) for r in rules if r.strip()]
if watch is None:
saved = sources.set_shared_routes(ctx.db, src["id"], parsed)
auth.audit(ctx.db, ctx.user.as_audit(), "source.routes", f"storage_source:{src['id']}", ["mcp"])
return {"account": src["id"], "shared_rules": _lines(saved)}
w = ctx.db.one("SELECT source FROM $r", r=R("watch_path", int(watch)))
if not w or w["source"] != src["id"]:
raise ToolError(f"account {src['id']} has no watch {watch}")
sources.update_watch(ctx.db, int(watch), routes=parsed)
auth.audit(ctx.db, ctx.user.as_audit(), "watch.update", f"watch_path:{watch}", ["mcp"])
except ValueError as e:
raise ToolError(str(e)) from None
w = next(x for x in sources.list_watches(ctx.db) if x["id"] == int(watch))
return {"account": src["id"], "watch": w["id"], "rules": _lines(w["routes"])}


# ---------- the stream of activities ----------
@tool(
"timeline",
Expand Down
18 changes: 17 additions & 1 deletion fastapi_backend/app/api/v1/routes/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
RcloneSignInState,
RoutedMessage,
RoutePreviewRequest,
RouteView,
SharedRoutes,
Source,
SourceCreate,
SourceCreated,
Expand Down Expand Up @@ -88,6 +90,19 @@ def update_source(sid: int, body: SourceUpdate, user: AdminWriter, db: Db, cfg:
return SourceUpdated(health=sources.test(db, cfg, sid))


@router.put("/sources/{sid}/routes")
def set_shared_routes(sid: int, body: SharedRoutes, user: AdminWriter, db: Db) -> list[RouteView]:
"""Save an email account's shared routing rules, which every watch on it tries after its own (none: unchanged
behaviour). They apply to messages that arrive after they're saved."""
_source(db, sid)
try:
rules = sources.set_shared_routes(db, sid, [r.model_dump() for r in body.routes])
except ValueError as e:
raise HTTPException(400, str(e)) from None
auth.audit(db, user.as_audit(), "source.routes", f"storage_source:{sid}")
return [RouteView(**r) for r in rules]


@router.post("/sources/rclone-signin")
def start_rclone_signin(body: RcloneSignInStart, user: AdminWriter, db: Db, cfg: Cfg) -> RcloneSignIn:
"""Connect Google Drive (with no Google app set up here), Dropbox or OneDrive by signing in through rclone on this
Expand Down Expand Up @@ -247,7 +262,8 @@ def preview_watch(body: WatchPreviewRequest, user: AdminWriter, db: Db, cfg: Cfg
def preview_routes(body: RoutePreviewRequest, user: AdminWriter, db: Db, cfg: Cfg) -> list[RoutedMessage]:
"""Where the latest messages of an email account would go under these routing rules, before saving them."""
try:
rows = sources.preview_routes(db, cfg, body.source, body.path, [r.model_dump() for r in body.routes], body.namespace)
shared = None if body.shared_routes is None else [r.model_dump() for r in body.shared_routes]
rows = sources.preview_routes(db, cfg, body.source, body.path, [r.model_dump() for r in body.routes], body.namespace, shared=shared)
except KeyError:
raise HTTPException(400, "no such source") from None
except (ValueError, RuntimeError) as e:
Expand Down
16 changes: 15 additions & 1 deletion fastapi_backend/app/domain/mail_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
match all of it (`*@acme.com`). `to` covers To, Cc and the address the inbox received the message at (Delivered-To,
X-Original-To), which is how mail sent to an alias of a shared inbox is told apart.

Rules are kept on the watch with namespace ids (a renamed namespace keeps its mail), and shown with names.
An email account (the source) can carry shared rules too, which every watch on it uses: an admin writes the
account's policy once (support@ to support, newsletters skipped) instead of copying it onto each mailbox's watch. A
watch's own rules are tried first, then the account's, then the message goes to the watch's namespace (`decide`).

Rules are kept with namespace ids (a renamed namespace keeps its mail), and shown with names.
"""

from __future__ import annotations
Expand Down Expand Up @@ -110,6 +114,16 @@ def route(rules, mail, home, spaces):
return home, None


def decide(own, shared, mail, home, spaces):
"""Where a message goes under a watch's own rules, then its account's shared ones: (namespace id, or None to skip
it; the number of the rule that decided, within its list, or None; whether that rule is a shared one)."""
space, n = route(own, mail, home, spaces)
if n is not None or not shared:
return space, n, False
space, n = route(shared, mail, home, spaces)
return space, n, n is not None


# ---------- rules written as lines (the assistant's mailbox: mailbox.py) ----------
def parse_line(text):
"""A rule written as a line, "from: *@acme.com, *@acme.org; subject: invoice = finance" (conditions joined by ;,
Expand Down
Loading
Loading
0