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
10 changes: 10 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1376,9 +1376,19 @@ POST /api/v1/chats/{cid}/messages
POST /api/v1/chats/{cid}/stop
POST /api/v1/chats/{cid}/messages/{mid}/check
GET /api/v1/approvals
GET /api/v1/approvals/count
GET /api/v1/approvals/{aid}
POST /api/v1/approvals/{aid}
```

`GET /approvals` lists what waits for your pick and what became of it, newest first: the assistant's proposals and
automations' actions ([Approvals](automations.md#approvals)); filter by `status`, `origin` (`automation` or `chat`),
`automation` or `chat_id`, and page with `before` (the last id of the page before) and `limit`. `/approvals/count`
gives `{waiting, automations}`. `POST /approvals/{aid} {decision, params?}` decides one: `approve`, `sample` (a batch
run on 3 assets first), `decline`, `edit` (an automation's action with `params` changed) or `always` (approved, and
that node runs without asking from now on). Approving, editing and `always` on an automation's action need a signed-in
session (403 for an API key or an app); each approval's `can` says what you may do with it.

`GET /chats/capabilities` tells anyone signed in whether a language model is set up (`configured`), which (`model`),
whether it uses tools (`tools`, `max_steps`), whether answers can be checked (`check`) and the `models` people may pick
(the configured one first; `llm.chat_models`, else the server's list); never the model server's address or key. A
Expand Down
54 changes: 53 additions & 1 deletion docs/automations.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ merged is called built.
| The timers behind schedule, `at` and `relative` triggers, the `clock.tick` kind and what's coming ([Time](#time)); automations set them once they are stored | built |
| Actions that wait (`delay`, `when`) ([Time](#time)) | planned |
| The Timeline page with filters, grouping, review keys and new items, and Home's Latest card ([Timeline](timeline.md)) | built |
| Storing and running automations, joins, approvals, variables, the studio | planned |
| Approvals: an automation's action that asks first waits for your pick (approve, decline, edit, allow from now on), told once in your chat app, capped and expiring (`app/domain/approvals.py`) | built |
| The Approvals page and its badge, a yes in your chat app, approval activities and notifications, agents' approval tools | planned |
| Storing and running automations, joins, variables, the studio | planned |

## Contract

Expand Down Expand Up @@ -564,6 +566,53 @@ everyone who reads the asset sees.
Calendar events aren't written: Lens signs in to Google Calendar read-only, and writing needs a new consent. Meanwhile
the agent can draft an event as a note.

## Approvals

Built: everything that waits for your pick is an approval in one table (`app/domain/approvals.py`): the assistant's
proposals in a conversation, as before, and an automation's actions that ask first. When an action node's intent asks
(its effect is `out`, or `lens` on anything but the event's own object), the engine hands it to
`approvals.ask(db, cfg, intent, event=None)`, which keeps:

| Field | |
| --- | --- |
| `origin` | `{automation, run, node}`: the run that asked (null for the assistant's own approvals) |
| `intent` | the intent, with the params as the run filled them in |
| `summary`, `automation`, `why` | what it would do (the action's `describe`), the automation's name, and the activity that caused it (`{activity, kind, summary, published, url}`) |
| `account`, `space` | the automation's person, whose pick it is, and the namespace it is about |
| `expires_at` | when it expires: `automations.approval_days` (7) after it asked |
| `told` | the chats you were told in |
| `status` | `pending` (waiting), `running`, `done`, `failed`, `declined` or `expired`; `decided_by`, `decided_at`, `result`, `error` |

You are told once, in your own chat app when one is linked ([Telling a person](#telling-a-person)): "School emails
wants to post in the Matterbridge gateway family: “Trip on Friday”. Open <link> to decide." The link opens the approval
in Lens. Handing the same intent over again gives the same approval. At most 100 wait for one automation: past that its
intents are dropped, and the run says so, so a flood of activities can't bury your inbox or your chat.

Deciding (`POST /api/v1/approvals/{aid}`):

- `approve` carries the intent out through `actions.perform`, for its person and as the automation (what it writes is
by `automation:<id>`, model calls count in the activity ledger under the run, and what it causes carries the run as
its cause). Its outcome, `done` with what it gave back or `failed` with why, goes on the approval and on the run.
- `decline` does nothing, and the run says it was declined.
- `edit` with `params` changes them first (a param given as null is left out), checked against the action's schema;
what the run filled in from a template stays as it is now. A credential header shows as `••••`, and given back as
`••••` it keeps its sealed value.
- `always` approves it, then lets that action node run without asking from now on (the automation's policy, `auto`).
Only an action that reaches outside Lens or other people asks each time, so only those can be allowed.

Approving, editing and `always` are yours: signed in to Lens, on the approval's card. An API key, an app, MCP and the
assistant can list and decline approvals, never approve them, since approving is the person's pick; each approval's
`can` says what the caller may do with it. This is the one place where an agent can't do what you can. The
assistant's own approvals in a conversation are decided as before.

Undecided approvals expire after `automations.approval_days` (Settings → Automations, 1–365, default 7): a sweep
called from the scheduler once an hour marks them `expired`, nothing runs, and the run says so. The assistant's own
approvals don't expire.

The inbox reads `GET /api/v1/approvals` (newest first; `status`, `origin=automation|chat`, `automation`, `chat_id`,
and `before` with `limit` to page), `GET /api/v1/approvals/{aid}` and `GET /api/v1/approvals/count` (`{waiting,
automations}`, for a badge).

## Time

Time is a trigger and a step: "every weekday at 7:00", "at 9:00 on the 20th", "30 minutes before a calendar event",
Expand Down Expand Up @@ -694,3 +743,6 @@ timers.clock_state(db, automation) # each schedule and at trigger: wai
source pages, so narrow it by account if that proves slow.
- Lens itself: a run held over budget, waiting for someone's pick, as an activity of its own; backups taken before
upgrades or with `lens backup` (only those from Settings, the API and the schedule are activities today).
- Approvals: a cost estimate on actions that ask (a run on another asset could say what it would cost); buttons in
Telegram and Slack; approvals that need two people; one card for many alike ("approve all 12"); trying a failed one
again; expiring an automation's approvals when it is removed.
5 changes: 3 additions & 2 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -463,13 +463,14 @@ Where namespaces may send notifications ([Notifications](notifications.md)). Set

## Automations

The stream of activities automations follow ([Automations](automations.md#contract)), and their timers. Settings →
Automations:
The stream of activities automations follow ([Automations](automations.md#contract)), their timers, and
how long their [approvals](automations.md#approvals) wait. Settings → Automations:

| Setting | Default | |
|---|---|---|
| `events.poll_seconds` | 5 | how often followers look for new activities when nothing wakes them, 1–3600 |
| `events.keep_days` | 30 | how long activities with no row of their own (the event log) are kept, 1–3650 days |
| `automations.approval_days` | 7 | how long an automation's action waits for your pick before it expires and nothing runs, 1–365 days |
| `automations.catch_up` | `1h` | how late a timer (a schedule, an action that waits) may still fire after Lens was off, `0s` to `7d`; older ones are missed ([Time](automations.md#time)) |

## Trusted proxies
Expand Down
77 changes: 62 additions & 15 deletions fastapi_backend/app/api/v1/routes/chats.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,21 @@
import json
import logging
from collections.abc import Iterator
from typing import Any
from typing import Any, Literal

from fastapi import APIRouter, HTTPException, Request
from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import StreamingResponse
from starlette.concurrency import run_in_threadpool

from app.api.deps import Access, Acl, Cfg, CurrentUser, Db, Principal, Writer
from app.api.media import sign_urls
from app.api.v1.routes.collections import own_collection
from app.domain import ai_tools, auth, auto_scope, browser, chat, llm, store, uploads
from app.domain import ai_tools, approvals, auth, auto_scope, browser, chat, llm, store, uploads
from app.domain.store import DB
from app.schemas.chats import (
AnswerCheck,
Approval,
ApprovalCount,
ApprovalDecision,
ApprovalOutcome,
Chat,
Expand Down Expand Up @@ -397,29 +398,75 @@ def check_message(cid: int, mid: int, user: Writer, db: Db, cfg: Cfg) -> AnswerC
return out


def _via(user: Principal) -> str:
"""Where a pick is made: web for a signed-in session, else token (an API key) or oauth (an app)."""
return "web" if user.via == "access" else user.via


def approval_view(a: dict, via: str = "web") -> Any:
"""An approval as the API shows it: an automation's intent with credentials hidden, and what `via` can do."""
return {**a, "intent": approvals.shown(a.get("intent")), "told": a.get("told") or [], "can": approvals.can(a, via)}


@router.get("/approvals")
def list_approvals(user: CurrentUser, db: Db, chat_id: int | None = None) -> list[Approval]:
"""Work the assistant proposed for you to approve (and what became of it), newest first."""
return db.rows(
"SELECT record::id(id) AS id, chat, tool, summary, estimate, status, created_at, result FROM approval WHERE account = $a"
+ (" AND chat = $c" if chat_id else "")
+ " ORDER BY created_at DESC LIMIT 100",
a=user.id,
c=chat_id,
)
def list_approvals(
user: CurrentUser,
db: Db,
chat_id: int | None = None,
status: Literal["pending", "running", "done", "failed", "declined", "expired"] | None = None,
origin: Literal["automation", "chat"] | None = None,
automation: int | None = None,
before: int | None = Query(default=None, description="ids below this one: the last id of the page before"),
limit: int = Query(default=100, ge=1, le=200),
) -> list[Approval]:
"""What waits for your pick (and what became of it), newest first: the assistant's proposals and automations'
actions. Filter by `status` (pending is waiting), `origin` (automation or chat), one `automation` or one chat
(`chat_id`); page with `before`."""
rows = approvals.listing(db, user.id, status, origin, automation, chat_id, before, limit)
return [approval_view(a, _via(user)) for a in rows]


@router.get("/approvals/count")
def count_approvals(user: CurrentUser, db: Db) -> ApprovalCount:
"""How many approvals wait for you, for the badge in the top bar."""
return approvals.count(db, user.id)


@router.get("/approvals/{aid}")
def get_approval(aid: int, user: CurrentUser, db: Db) -> Approval:
"""One of your approvals."""
a = approvals.get(db, aid)
if not a or a["account"] != user.id:
raise HTTPException(404, "not found")
return approval_view(a, _via(user))


@router.post("/approvals/{aid}")
def decide_approval(aid: int, body: ApprovalDecision, user: Writer, acl: Acl, db: Db, cfg: Cfg, request: Request) -> ApprovalOutcome:
"""Approve (or run a sample of, or decline) something the assistant proposed. Each approval is decided once."""
"""Approve (or run a sample of, or decline) something the assistant proposed or an automation's action. Each
approval is decided once. An automation's action can also be edited (`params`) and then carried out, or allowed
from now on for that automation (`always`); approving one needs you signed in, since it's your pick: an API key
or an app can only decline it."""
a = db.one("SELECT account FROM $r", r=R("approval", aid))
if not a or a["account"] != user.id:
raise HTTPException(404, "not found")
try:
out = ai_tools.approve(
db, cfg, aid, user.as_audit(), set(acl.editable()), body.decision, request.app.state.archive.base, user.admin, set(acl.roles)
db,
cfg,
aid,
user.as_audit(),
set(acl.editable()),
body.decision,
request.app.state.archive.base,
user.admin,
set(acl.roles),
params=body.params,
via=_via(user),
)
except (ValueError, PermissionError, KeyError) as e:
except PermissionError as e:
raise HTTPException(403, str(e)) from None
except (ValueError, KeyError) as e:
raise HTTPException(400, str(e)) from None
auth.audit(db, user.as_audit(), "assistant.approval", f"approval:{aid}", {"decision": body.decision, **out})
request.app.state.graph_cache.clear() # an approved entity or topic change shows in the graph at once
Expand Down
15 changes: 12 additions & 3 deletions fastapi_backend/app/domain/ai_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1436,12 +1436,21 @@ def cited(self, text):
return [{**r, "used": r["n"] in used} for r in self.refs if r["n"] in used]


def approve(db, cfg, aid, user, editable, decision="approve", base=None, admin=False, readable=None):
def approve(db, cfg, aid, user, editable, decision="approve", base=None, admin=False, readable=None, params=None, via="web"):
"""Carry out an approved action: a batch run (or a sample of it), an entity change, a note an automation's agent
proposed, or a change to the server (ops_tools.py: settings, a namespace, importing attached files or web pages)."""
a = db.one("SELECT record::id(id) AS id, chat, account, tool, args, status FROM $r", r=R("approval", int(aid)))
proposed, or a change to the server (ops_tools.py: settings, a namespace, importing attached files or web pages).
An automation's action (an approval with an intent) is decided by approvals.decide: `params` are an edit's, `via`
where the pick was made (web, chat, token, oauth or agent; only the person, signed in or in their own chat,
approves it)."""
from . import approvals # it carries actions out, and actions load the assistant's tools

a = approvals.get(db, aid)
if not a or a["status"] != "pending":
raise ValueError("nothing to approve")
if a.get("intent"):
return approvals.decide(db, cfg, a, user, decision, params, via)
if decision in ("edit", "always"):
raise ValueError("only an automation's action can be edited or allowed from now on")
if decision == "decline":
db.q(
"UPDATE $r SET status = 'declined', decided_at = $t, decided_by = $u", r=R("approval", a["id"]), t=store.now(), u=user["email"]
Expand Down
Loading
Loading