8000 feat(circles): rules that share with a circle, asking first until let by adeelahmad · Pull Request #653 · 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
10BC8
Diff view
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,9 @@ listed under [In progress](#in-progress), and what comes next under [Planned](#p
people on the same Lens, and share an activity from your timeline or a resource with a circle and a note: each of
them sees it in their own timeline, and you see it in yours, so nothing is shared behind anyone's back. Share with the
item to also let them open the resource; undo takes it all back, and nothing leaves a vault. In the web app, circles
live under Profile and Share sits on every timeline item and resource. Agents do the same over MCP, and the
assistant asks you first. ([Circles of trust](docs/circles.md);
live under Profile and Share sits on every timeline item and resource. Rules (automations) share what comes in,
like the school's emails, asking you first until you let them run on their own. Agents do the same over MCP, and
the assistant asks you first. ([Circles of trust](docs/circles.md);
[checks](docs/requirements.md#share-with-the-people-close-to-you))
- **See what it costs.** An activity ledger of every model call, with reports, charts and budgets that cap spending.
Setup asks for one overall budget after a cloud model, with a soft limit that warns and a hard limit that stops paid
Expand Down Expand Up @@ -335,9 +336,8 @@ Open pull requests, not yet part of Lens, are listed here; none right now.

Next, and not in a pull request yet; each links to where it is tracked:

- **Circles of trust:** rules for what your agent shares without asking,
asking someone's agent (when they're free, what a trip needs) answered from what they let you see, and circles
across Lens servers over ActivityPub ([circles of trust](docs/circles.md)).
- **Circles of trust:** asking someone's agent (when they're free, what a trip needs) answered from what they let you
see, and circles across Lens servers over ActivityPub ([circles of trust](docs/circles.md)).
- **Notes:** nesting a note under its project or area without a click, pages in the graph, and wiki addresses for
topics, recordings and the other things that have pages ([notes](docs/notes.md)).
- **Local models:** GPU builds of llama.cpp fetched by Lens, and local embedding models
Expand Down
4 changes: 4 additions & 0 deletions changelog.d/circles-rules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- **Share with your circles on their own.** The `share_with_circle` automation action shares what comes in (the
school's emails, a calendar's events, a sensor's alerts) with a circle and a note that can say what came in. It
asks you first, unless you let its node run on its own; it shares as you, only what you can see in the
automation's namespaces, never from a vault ([Rules](docs/circles.md#rules)).
2 changes: 2 additions & 0 deletions docs/automations.md
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,7 @@ or removed does nothing. What it writes is by the automation itself, `automation
| --- | --- | --- | --- |
| `log_line` | puts a line (`text`, `level` info or warning) in the run's log | read | `{line, level}` |
| `notify` | sends `text` (and a `link`; Lens's own paths become full links) `to` `me` (your own chat app), `target:<id>` (one of the namespace's [notification targets](notifications.md)) or `gateway:<name>` (a Matterbridge room) | self for `me`, else out | `{to, text, sent, failed}`: where it went |
| `share_with_circle` | shares the activity (`activity`, by default the run's) or an `asset` with your `circles` (by name or id) and `people` in them, with a `note`, and `with_item` to let them open the asset ([Circles of trust](circles.md#rules)) | out | `{share, circles, people, granted}` |
| `ask_model` | asks the model a `prompt` (with your own `system` instructions and `model` if you like); with `json_schema` (a JSON Schema of type object) the reply is that object | read | `{text}`, or the object the schema describes |
| `call_tool` | calls one of the assistant's tools (`tool`, with `args`) as the automation | read: a change becomes an approval | `{tool, result, summary, approvals}` |
| `ask_agent` | hands what happened (`about`, by default the event) to the agent with your `instructions`, limited to some `tools` if you like, for up to `max_steps` rounds (6, at most 12) | read: changes become approvals | `{answer, chat, approvals, steps}` |
Expand Down Expand Up @@ -1429,6 +1430,7 @@ built yet is in [Refine later](#refine-later); the [Timeline](timeline.md) has i
| Drawing an automation's workflow on the canvas: the actions in the palette, their settings from each action's params, Decide's ports, the leaf rule and a try on a kind's sample ([On the canvas](#on-the-canvas)) | built |
| The action registry with risk from each action's effect, and `log_line`, a line in the run's log (`app/domain/actions.py`) | built |
| Telling a person: the `notify` action and `channels.tell` (their own chat, a notification target, a Matterbridge room) | built |
| Telling your circles: the `share_with_circle` action, which asks first unless you let it run on its own ([Circles of trust](circles.md#rules)) | built |
| The model and the agent: the `ask_model`, `call_tool` and `ask_agent` actions, and prompts with outside text marked | built |
| Templates in params and prompts: the run context, one expression keeping its type, errors that name the nearest variable, saved prompt templates, filters for times, text and addresses ([Variables and templates](#variables-and-templates)) | built |
| Saved variables: `vars` in the run context, the `set_variable` action, the API and MCP tools ([Saved variables](#saved-variables)) | built |
Expand Down
14 changes: 13 additions & 1 deletion docs/circles.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Status: in progress. Circles are built in steps; only what is merged is called b
| --- | --- |
| Circles of people on the same Lens, sharing an activity or a resource with them and a note, with the item or without, undo; API, MCP and the assistant | built |
| Circles under Profile in the web app, and a Share action on timeline items and resource pages | built |
| Rules per circle: what your agent shares without asking (kinds, entities, a match tree) and what it asks you first about | planned |
| Rules: an automation shares what you pick (by kind, sender, entity or the decision model) with a circle, asking you first or on its own | built |
| Asking someone's agent (when are they free, what does the trip need), answered only from what they let that circle see, with citations | planned |
| Circles across Lens servers over ActivityPub: a signed inbox, an outbox and WebFinger handles like `sam@lens.example` | planned |

Expand Down Expand Up @@ -55,6 +55,17 @@ back. Deleting a circle doesn't take back what was shared with it.

**Vaults.** Nothing in a [vault](encryption.md#vaults) can be shared: what's in a vault stays in it.

## Rules

Rules are [automations](automations.md) with the **Share with a circle** action (`share_with_circle`): pick what to
follow with the automation's triggers and conditions (the school's emails, a calendar's events, a sensor's alerts, an
entity), the circles by name, and a note that can say what came in (`New from school: {{ event.object.name }}`).

Sharing reaches other people, so a rule asks you first: the share waits in [Approvals](automations.md#approvals) until
you say yes. Let its node run on its own (only you can, signed in) and it shares as soon as the activity comes in. It
shares as you, only what you can see in the automation's namespaces, never from a vault, and is audited as by the
automation; its share says `via: automation`.

## For agents

Everything here works for agents as it does for people.
Expand All @@ -69,6 +80,7 @@ Everything here works for agents as it does for people.
are about the person, so a namespace's own MCP server doesn't offer them.
- **The assistant:** `circles` reads them, and `share_with_circle` asks the person first: telling other people is
always their pick.
- **Automations:** the `share_with_circle` action ([Rules](#rules)), which agents can add with the automation tools.

## What keeps it safe

Expand Down
1 change: 1 addition & 0 deletions docs/requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ request, to another check that proves the same thing; loosening a requirement or
| Agents make circles and share over MCP; the assistant shares only after the person's yes | [test_circles.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_circles.py) `test_agents_share_too` |
| Circles live under Profile, a suggested circle takes one click and deleting one is undone, not confirmed | [circles-ui.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/circles-ui.test.tsx) `makes a suggested circle in one click`; [circles-ui.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/circles-ui.test.tsx) `deletes a circle with Undo instead of a confirm` |
| Share on a timeline item or a resource picks the only circle, takes a note and is undone from its toast | [circles-ui.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/circles-ui.test.tsx) `picks the only circle, shares with a note, and undoes from the toast` |
| A rule shares what comes in with a circle and a note, asking first until the person lets it run on its own | [test_circles.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_circles.py) `test_rules_share_on_their_own_only_when_let` |

## See what it costs

Expand Down
4 changes: 2 additions & 2 deletions fastapi_backend/app/domain/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
(`person`), with their permissions as they are when it runs (`reach`), and what it writes is by the automation itself
(`actor`). Params marked `"format": "prompt"` are prompts: the engine renders them with `render_prompt`, which wraps
what the run read from outside Lens as data; such a param may name a saved prompt template ({"template": 5}) instead.
`log_line` ships here; the other actions are registered by a module per group, loaded with this one: actions_messages.py (notify), actions_ai.py (ask_model, call_tool, ask_agent),
`log_line` ships here; the other actions are registered by a module per group, loaded with this one: actions_messages.py (notify), actions_circles.py (share_with_circle), actions_ai.py (ask_model, call_tool, ask_agent),
actions_web.py (http_request), actions_run.py (run_workflow, run_pipeline, run_routine), actions_lens.py (set_field, add_to_collection,
write_note), variables.py (set_variable).
"""
Expand Down Expand Up @@ -356,4 +356,4 @@ def _log_line(db, cfg, intent, user, dry):
)


from . import actions_ai, actions_lens, actions_messages, actions_run, actions_web, variables # noqa: E402, F401 - they register their actions; loaded with the catalog
from . import actions_ai, actions_circles, actions_lens, actions_messages, actions_run, actions_web, variables # noqa: E402, F401 - they register their actions; loaded with the catalog
132 changes: 132 additions & 0 deletions fastapi_backend/app/domain/actions_circles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""The automation action that shares with the person's circles (docs/circles.md, Rules): `share_with_circle`.

It is how a person's agent tells their family what they need to know without being asked each time: an automation
that follows the school's emails, a calendar's events or a sensor shares what came in with a circle, with a note. It
reaches other people (effect `out`), so it asks the person first, unless they set that node to run on its own; that
pick is theirs alone (automations.set_policy). It shares as the automation's person, only what they can see now in the
automation's namespaces, never from a vault, and is audited as by the automation.
"""

from __future__ import annotations

from . import actions, auth, circles, events

EVENT = "{{ event.id }}"


def _short(text, n=60):
text = " ".join(str(text or "").split())
return text if len(text) <= n else text[: n - 1] + "…"


def _list(v):
return [v] if isinstance(v, (str, int)) else list(v or [])


def _viewer(db, intent, acc):
"""The timeline as the person reads it within the automation's namespaces (all of theirs when it names none)."""
if acc["admin"] and not intent["spaces"]:
return events.viewer(acc["id"], None, admin=True)
if acc["admin"]:
return events.viewer(acc["id"], set(intent["spaces"]))
readable, _ = actions.reach(db, intent, acc)
return events.viewer(acc["id"], readable)


def _share(db, cfg, intent, user, dry):
p = intent["params"]
acc = actions.person(db, intent, user)
what = {"recording": actions.asset_id(p["asset"])} if p.get("asset") not in (None, "") else {"activity": str(p["activity"])}
args = {
**what,
"circles_": _list(p.get("circles")),
"people_": _list(p.get("people")),
"note": p.get("note"),
"with_item": bool(p.get("with_item")),
"who": _viewer(db, intent, acc),
}
try:
if dry:
got = circles.preview(db, cfg, acc, **args)
return {"would": f"share “{_short(got['object'].get('name'))}” with {', '.join(got['circles'] or ['them'])}", **got}
out = circles.share(db, cfg, acc, **args, via="automation")
except KeyError as e:
missing = str(e.args[0] if e.args else "")
if missing.startswith("circle "):
raise ValueError(f"{acc['name']} has no {missing}") from None
raise ValueError(f"{acc['name']} can't see {missing} in this automation's namespaces") from None
except (circles.Problem, PermissionError) as e:
raise ValueError(str(e)) from None
by = actions.actor(db, intent)
auth.audit(
db,
by,
"circle.share",
f"circle_share:{out['id']}",
{"to": len(out["people"]), "with_item": out["with_item"], "what": what, "for": acc["email"]},
)
return {"share": out["id"], "circles": out["circles"], "people": out["people"], "granted": out["granted"]}


def _describe(p):
whom = ", ".join(map(str, _list(p.get("circles")) + _list(p.get("people")))) or "your circles"
what = "the asset" if p.get("asset") not in (None, "") else "it"
note = f": “{_short(p.get('note'))}”" if p.get("note") else ""
return f"Share {what} with {whom}{note}"


actions.register(
actions.ActionSpec(
name="share_with_circle",
label="Share with a circle",
group="Messages",
description=(
"Shares the activity (or an asset) with your circles and a note: each of them sees it in their own timeline. "
"It asks you first, unless you let it run on its own."
),
params={
"type": "object",
"properties": {
"circles": {
"type": "array",
"title": "Circles",
"items": {"type": "string"},
"description": "your circles, by name or id",
},
"people": {
"type": "array",
"title": "People",
"items": {"type": "string"},
"description": "people in your circles, by email or account id",
},
"note": {"type": "string", "title": "Note", "maxLength": circles.NOTE_MAX},
"activity": {
"type": "string",
"title": "Activity",
"default": EVENT,
"maxLength": 200,
"description": "the activity to share: the one the run is on, unless an asset is given",
},
"asset": actions.asset_param("Asset (instead of the activity)") | {"default": None},
"with_item": {
"type": "boolean",
"title": "With the item",
"default": False,
"description": "also let them open the asset (needs publish in its namespace)",
},
},
},
effect="out",
output={
"type": "object",
"properties": {
"share": {"type": "integer"},
"circles": {"type": "array", "items": {"type": "string"}},
"people": {"type": "array", "items": {"type": "object"}},
"granted": {"type": "integer"},
},
},
perform=_share,
describe=_describe,
)
)
7 changes: 4 additions & 3 deletions fastapi_backend/app/domain/circles.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,13 +249,14 @@ def _from_recording(db, me, who, rid):


def _recipients(db, me, circle_ids, people_ids):
"""(member ids, circle names) for a share: every member of `me`'s circles named, and people in any of their
circles. Problem when that's nobody."""
"""(member ids, circle names) for a share: every member of `me`'s circles named (by id, or by name as automations
name them), and people in any of their circles. Problem when that's nobody."""
rows = db.rows("SELECT record::id(id) AS id, name, members FROM circle WHERE owner = $o", o=me["id"])
mine = {r["id"]: r for r in rows}
out, names = [], []
by_name = {str(r["name"]).casefold(): r for r in rows}
for c in circle_ids or []:
r = mine.get(int(c)) if str(c).strip().isdigit() else None
r = mine.get(int(c)) if str(c).strip().isdigit() else by_name.get(str(c).strip().casefold())
if r is None:
raise KeyError(f"circle {c}")
names.append(r["name"])
Expand Down
Loading
Loading
0