From 95ff9ae379615c6057c54340c4c2236a518b5ca9 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 22:33:46 +0000 Subject: [PATCH] feat(automations): save automations for their maker, with checks and an API An automation is saved with its triggers, join, If, a Then (a graph saved as a workflow of scope event, or a saved one), namespaces its person can edit, limits and a policy. It is switched on and off (enabled_at records when), deleted with restore as the undo, and only the person in a signed-in session lets a node run on its own. Schedules, webhooks and joins other than any are refused as coming soon until their modules land, and are armed through them once they are there. GET /automations/actions lists the action catalog. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01VCAZ9NEmBJNovqdzxvK3qi --- docs/api.md | 20 + docs/automations.md | 57 +- fastapi_backend/app/api/v1/router.py | 2 + .../app/api/v1/routes/automations.py | 134 + fastapi_backend/app/domain/automations.py | 412 ++ fastapi_backend/app/domain/store.py | 3 + fastapi_backend/app/schemas/automations.py | 119 + fastapi_backend/tests/api/test_automations.py | 243 + .../tests/api/test_event_workflows.py | 5 +- .../tests/domain/test_automation_nodes.py | 4 +- fastapi_backend/tests/helpers.py | 9 + nextjs-frontend/app/openapi-client/index.ts | 51 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 172 + .../app/openapi-client/types.gen.ts | 669 +++ nextjs-frontend/openapi.json | 5337 ++++++++++------- 15 files changed, 5118 insertions(+), 2119 deletions(-) create mode 100644 fastapi_backend/app/api/v1/routes/automations.py create mode 100644 fastapi_backend/app/domain/automations.py create mode 100644 fastapi_backend/app/schemas/automations.py create mode 100644 fastapi_backend/tests/api/test_automations.py diff --git a/docs/api.md b/docs/api.md index e9525b200..648ec2dec 100644 --- a/docs/api.md +++ b/docs/api.md @@ -180,6 +180,26 @@ GET /api/v1/activity/top leaving out the ones you can't see; `estimate` marks a figure as a floor. `/activity/top` lists the costliest resources (admins). +## automations + +``` +GET /api/v1/automations +POST /api/v1/automations +GET /api/v1/automations/actions +GET /api/v1/automations/{id} +PATCH /api/v1/automations/{id} +DELETE /api/v1/automations/{id} +POST /api/v1/automations/{id}/restore +POST /api/v1/automations/{id}/enable +POST /api/v1/automations/{id}/policy +``` + +Automations act for the person who made them in namespaces they can edit ([Saving +automations](automations.md#saving-automations)). Admins see and change all of them; anyone else the ones that work +only in namespaces they can edit (`?removed=true` lists deleted ones, to restore). A save answers `{id, hooks}`. +`/policy` lets an action node run without asking (`auto`) only from a signed-in session in the web app. +`/actions` lists what action nodes can do. + ## activities ``` diff --git a/docs/automations.md b/docs/automations.md index b76b13cdd..9463c78a4 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -34,7 +34,8 @@ merged is called built. | Timers that outlast a restart and fire once across the API and the worker (`app/domain/timers.py`, [Time](#time)) | built | | Schedule, `at` and `relative` triggers, and actions that wait ([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 | +| Saving automations: checks, namespaces, switching on and off, delete and restore, the policy, the API (`app/domain/automations.py`) | built | +| Running automations, joins, approvals, variables, the studio | planned | ## Contract @@ -291,8 +292,8 @@ tree, `path` (when given) is the part of the value the tree tests. Graphs saved ### Automations: triggers and joins -Built as shapes with checks (`app/domain/automation_spec.py`); storing and running automations is planned. Each check -gives a cleaned copy, or a ValueError naming the first problem. +Built as shapes with checks (`app/domain/automation_spec.py`), and saved ([Saving automations](#saving-automations)); +running them is planned. Each check gives a cleaned copy, or a ValueError naming the first problem. ```json {"name": "School emails", "enabled": true, "spaces": [3], "run_as": 1, @@ -578,6 +579,51 @@ def _(db, cfg, payload): ... # payload + late (true - **Light.** No timer exists until an automation uses time. While none waits the thread doesn't query the table: it checks once a minute, and at once when this process sets one. A timer set by the other process (the API, when the worker fires them) can so fire up to a minute late. +## Saving automations + +Built (`app/domain/automations.py`, `POST /api/v1/automations`); running them is planned. An automation acts for the +person who made it (`run_as`), with their permissions, in namespaces they can edit: + +```json +{"name": "Say new assets", "triggers": [{"as": "new", "on": "event", "kinds": ["asset.added"]}], + "if": {"all": [{"path": "event.object.media", "op": "equals", "value": "audio"}]}, + "graph": {"nodes": [{"id": "i", "type": "input", "config": {}}, + {"id": "a", "type": "action", "config": {"action": "log_line", + "params": {"text": "New: {{ event.object.name }}"}}}], + "edges": [{"source": "i", "target": "a"}]}} +``` + +- **Namespaces** (`spaces`): ones its person can edit. Left out, it is each namespace they can edit; an admin's + works in every namespace (`null`), now and to come. +- **The Then** is a `graph` ([The event workflow scope](#the-event-workflow-scope)), saved as a workflow of scope + `event` named after the automation, or a saved event workflow (`workflow`, with `version`, or none to follow the + published one). Saving a new graph saves a new version of its workflow, which it then follows. +- **Credentials** in an `http_request` node's headers ([Calling a web address](#calling-a-web-address)) are sealed + when its graph is saved, with the key of its first namespace (the first there is, for one that works everywhere), + bound to the automation and to the node's `url`. A value holding `{{ }}` is filled in when it runs and stays as + written, and a credential needs the `url` written out, not a template. Reading the automation back gives the sealed + value, and saving that again keeps it. +- **Checks** when it is saved: the triggers, the join and the If as in [the contract](#automations-triggers-and-joins), + the graph, the namespaces, `limits` (`cooldown`, like `10m`, default `0s`; `max_per_hour`, 1 to 3600, default 60) + and the policy. Triggers on `schedule`, `at` and `relative`, and joins other than `any`, are refused as coming soon + until schedules ([Time](#time)) and joins are built; then saving sets its schedules. +- **Webhook triggers** get their address when the automation is saved ([Webhook trigger](#webhook-trigger)): the + answer's `hooks` gives each new one's `url` and signing `secret`, shown this once, and the trigger keeps the hook's + id. Saving it again keeps its address; a webhook trigger dropped (or changed to another kind) loses it at once. +- **Switching** (`POST /automations/{id}/enable {"on": true}`) records when it was last switched on (`enabled_at`): + running it (planned) reacts only to what happens after that, so switching one on never replays old activity. New + automations are on unless `enabled: false`. +- **Deleting** switches it off and hides it; `POST /automations/{id}/restore` brings it back, switched off. +- **The policy** (`{action node id: ask or auto}`): a node whose action reaches outside Lens or other + people, or changes something in Lens other than the event's own object, asks first. Only the person, + signed in to the web app, lets a node run on its own (`POST /automations/{id}/policy {"node": "a", "value": + "auto"}`); API keys, apps and agents get a 403, and saving through any other route refuses `auto` (a node already + on `auto` may stay so). A node that leaves the graph takes its pick with it. +- **Who sees it**: admins see and change every automation; anyone else the ones that work only in namespaces they + can edit. + +`GET /api/v1/automations/actions` lists what an action node can do: each action's params (a JSON Schema), its effect +and what it gives back. ## Refine later @@ -632,3 +678,8 @@ def _(db, cfg, payload): ... # payload + late (true - Chat: recording every message in a room as an activity (opt-in per channel, off by default); a chat user who is also a Lens account as that person; a timeline page of others' private messages is read and left out, up to five source pages, so narrow it by account if that proves slow. +- Deleted automations kept for a time, then removed with their runs (today they stay until restored). +- Credentials in the headers of a saved event workflow an automation follows (`workflow`) sealed too (today only a + graph saved with the automation is; the workflow's are sent as written). +- Webhook triggers: a trigger option for a hook that takes only signed calls (`token_for(..., signed=True)`), and a + new address for a trigger without saving it again. diff --git a/fastapi_backend/app/api/v1/router.py b/fastapi_backend/app/api/v1/router.py index fd5e983da..ddb3e2dcc 100644 --- a/fastapi_backend/app/api/v1/router.py +++ b/fastapi_backend/app/api/v1/router.py @@ -8,6 +8,7 @@ admin, auth, automation_hooks, + automations, backups, batches, browser, @@ -85,6 +86,7 @@ activity, activities, automation_hooks, + automations, budgets, fedora, setup, diff --git a/fastapi_backend/app/api/v1/routes/automations.py b/fastapi_backend/app/api/v1/routes/automations.py new file mode 100644 index 000000000..0a9cfe9bb --- /dev/null +++ b/fastapi_backend/app/api/v1/routes/automations.py @@ -0,0 +1,134 @@ +"""Automations (docs/automations.md, Automations): when something happens, if a test passes, do something, for you in +namespaces you can edit. Admins see and change every automation; anyone else the ones that work only in namespaces +they can edit. Ids use the int convertor, so static paths under /automations never collide with them.""" + +from __future__ import annotations + +from typing import Any + +from fastapi import APIRouter, HTTPException + +from app.api.deps import Acl, Cfg, CurrentUser, Db, Principal, Writer, domain_errors +from app.domain import actions, auth, automations, store +from app.schemas.automations import ( + ActionInfo, + Automation, + AutomationCatalog, + AutomationCreate, + AutomationPolicy, + AutomationSaved, + AutomationSwitch, + AutomationUpdate, +) +from app.schemas.common import Ok + +router = APIRouter(prefix="/automations", tags=["automations"]) + + +def _editable(db: Any, user: Principal, acl: Any) -> list[int]: + return sorted(store.space_names(db)) if user.admin else acl.editable() + + +def _mine(db: Any, user: Principal, acl: Any, aid: int, removed: bool = False) -> dict[str, Any]: + """The automation, if this person may see and change it (404 otherwise, so ids don't leak).""" + try: + a = automations.get(db, aid, removed) + except KeyError: + raise HTTPException(404, "not found") from None + if not automations.manages(a, _editable(db, user, acl), user.admin): + raise HTTPException(404, "not found") + return a + + +def _who(user: Principal) -> dict[str, Any]: + return {"id": user.id, "email": user.email, "name": user.name, "admin": user.admin} + + +@router.get("") +def list_automations(user: CurrentUser, acl: Acl, db: Db, removed: bool = False) -> AutomationCatalog: + """Your automations: every one for an admin, else those that work only in namespaces you can edit. `removed` + lists the deleted ones instead, to restore.""" + spaces = None if user.admin else acl.editable() + return AutomationCatalog(automations=automations.list_automations(db, spaces, removed)) + + +@router.get("/actions") +def list_actions(user: CurrentUser) -> list[ActionInfo]: + """What an action node can do: each action's params (a JSON Schema), what it reaches (its effect) and what it + gives back.""" + return [ActionInfo(**a) for a in actions.catalog()] + + +@router.post("") +def create_automation(body: AutomationCreate, user: Writer, db: Db, cfg: Cfg) -> AutomationSaved: + """A new automation that acts for you. Its Then is a graph (saved as a workflow of scope event) or a saved + workflow; its namespaces default to each one you can edit. Nodes ask first unless you let one run on its own + (POST /automations/{id}/policy).""" + with domain_errors(): + got = automations.create(db, cfg, body.model_dump(exclude_unset=True, by_alias=True), _who(user)) + auth.audit(db, user.as_audit(), "automation.create", f"automation:{got['id']}") + return AutomationSaved(**got) + + +@router.get("/{aid:int}") +def get_automation(aid: int, user: CurrentUser, acl: Acl, db: Db) -> Automation: + return Automation(**_mine(db, user, acl, aid)) + + +@router.patch("/{aid:int}") +def update_automation(aid: int, body: AutomationUpdate, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> AutomationSaved: + """Change what is sent: a new graph is saved as a new version of its workflow; `if: null` drops its If, + `version: null` follows the published version.""" + _mine(db, user, acl, aid) + changes = { + k: v + for k, v in body.model_dump(exclude_unset=True, by_alias=True).items() + if v is not None or k not in ("name", "enabled", "triggers", "graph", "workflow") + } + with domain_errors(): + got = automations.update(db, cfg, aid, changes, user.email) + auth.audit(db, user.as_audit(), "automation.update", f"automation:{aid}") + return AutomationSaved(**got) + + +@router.post("/{aid:int}/enable") +def enable_automation(aid: int, body: AutomationSwitch, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> Ok: + """Switch it on (it reacts to what happens from now on, never to what happened while it was off) or off.""" + _mine(db, user, acl, aid) + with domain_errors(): + automations.enable(db, cfg, aid, body.on, user.email) + auth.audit(db, user.as_audit(), "automation.enable" if body.on else "automation.disable", f"automation:{aid}") + return Ok() + + +@router.delete("/{aid:int}") +def delete_automation(aid: int, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> Ok: + """Delete it: switched off and hidden; POST /automations/{id}/restore undoes it.""" + _mine(db, user, acl, aid) + with domain_errors(): + automations.remove(db, cfg, aid, user.email) + auth.audit(db, user.as_audit(), "automation.delete", f"automation:{aid}") + return Ok() + + +@router.post("/{aid:int}/restore") +def restore_automation(aid: int, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> Ok: + """Undo a delete: it comes back switched off.""" + _mine(db, user, acl, aid, removed=True) + with domain_errors(): + automations.restore(db, cfg, aid, user.email) + auth.audit(db, user.as_audit(), "automation.restore", f"automation:{aid}") + return Ok() + + +@router.post("/{aid:int}/policy") +def set_policy(aid: int, body: AutomationPolicy, user: Writer, acl: Acl, db: Db) -> dict[str, str]: + """Whether an action node asks you first (ask) or runs on its own (auto). Only you, signed in to the web app, + let a node run on its own: never an API key, an app or an agent.""" + _mine(db, user, acl, aid) + if body.value == "auto" and user.via != "access": + raise HTTPException(403, "only you, signed in to the web app, let a node run on its own") + with domain_errors(): + got = automations.set_policy(db, aid, body.node, body.value, user.email) + auth.audit(db, user.as_audit(), "automation.policy", f"automation:{aid}", {"node": body.node, "value": body.value}) + return got diff --git a/fastapi_backend/app/domain/automations.py b/fastapi_backend/app/domain/automations.py new file mode 100644 index 000000000..0d4a4aa5c --- /dev/null +++ b/fastapi_backend/app/domain/automations.py @@ -0,0 +1,412 @@ +"""Automations (docs/automations.md, Automations): when something happens (triggers), if a test passes (the If), do +something (the Then, a workflow of scope event, automation_nodes.py), for one person in some namespaces. + +An automation is an `automation:` row: + +- `name`, `description`, `enabled` (and `enabled_at`, when it was last switched on: it reacts only to what happens + after that), `spaces` (namespace ids, or None for every one: admins only), `run_as` (the account it acts for: its + maker, whose permissions it has), `created_by`, `created_at`, `updated_at`. +- `triggers` and `join` (automation_spec.check_triggers, check_join), `if` (a match tree over the run context, kept + as `condition`), `workflow` (the id of its workflow, scope event) and `version` (None: the published one), + `policy` ({action node id: ask or auto}: only the person, from a signed-in session, sets auto, with set_policy), + `limits` ({cooldown, max_per_hour}). +- What its runs left: `last_run_at`, `last_status`, `counters` ({runs, skipped, limited, missed}). +- `removed_at`: deleted (switched off and hidden; restore brings it back). + +Parts of the studio built in their own steps are called once they are there (automation_nodes.provided): schedules +and times (timers), webhooks (automation_hooks) and joins other than any (match.join_step). Until then a trigger or +join that needs one is refused as coming soon. +""" + +from __future__ import annotations + +from . import actions_web, auth, automation_spec, keyring, store, workflows +from .automation_nodes import provided + +R = store.R +FIELDS = ( + "record::id(id) AS id, name, description, enabled, enabled_at, spaces, run_as, triggers, join, condition, workflow, " + "version, policy, limits, created_by, created_at, updated_at, last_run_at, last_status, counters, removed_at" +) +LIMITS = {"cooldown": "0s", "max_per_hour": 60} +MAX_PER_HOUR = 3600 +COUNTERS = ("runs", "skipped", "limited", "missed") +KEYS = {"name", "description", "enabled", "spaces", "triggers", "join", "if", "graph", "workflow", "version", "policy", "limits"} +SOON = { # what a trigger needs that comes with its own module: (module, function, what) + "schedule": ("timers", "schedule_automation", "schedules"), + "at": ("timers", "schedule_automation", "triggers at a time"), + "relative": ("timers", "relative", "triggers relative to a time"), + "webhook": ("automation_hooks", "token_for", "webhooks"), +} + + +# ---------- checking ---------- +def action_nodes(graph, out=None): + """The ids of every action node in a graph and the bodies inside it.""" + out = [] if out is None else out + for n in (graph or {}).get("nodes") or []: + if n.get("type") == "action": + out.append(n.get("id")) + body = (n.get("config") or {}).get("body") + if isinstance(body, dict): + action_nodes(body, out) + return out + + +def _account(db, uid): + a = auth.get_account(db, uid) if isinstance(uid, int) else None + if not a or a.get("disabled") or a.get("removed_at"): + return None + return a + + +def editable(db, account): + """The namespaces a person can edit (every one for an admin).""" + if account.get("admin"): + return set(store.space_names(db)) + roles = auth.roles(db, account) + return {s for s in roles if auth.allows(roles, s, "editor")} + + +def _check_spaces(db, spaces, account): + """The namespaces an automation works in, as its person may have them: ones they can edit, or every one (None) + for an admin. Not given: every one for an admin, else each namespace they can edit.""" + can = editable(db, account) + if spaces is None: + if account.get("admin"): + return None + if not can: + raise ValueError("you can't edit any namespace, so there's nowhere for an automation to work") + return sorted(can) + if not isinstance(spaces, list) or not spaces or not all(isinstance(s, int) and not isinstance(s, bool) for s in spaces): + raise ValueError("spaces is a list of namespace ids, or none for all of them") + known = set(store.space_names(db)) + for s in spaces: + if s not in known: + raise ValueError(f"no namespace {s}") + if s not in can: + raise ValueError(f"{account.get('name') or account.get('email')} can't edit namespace {s}, so the automation can't work there") + return sorted(set(spaces)) + + +def _check_limits(limits): + if limits is None: + return dict(LIMITS) + if not isinstance(limits, dict): + raise ValueError("limits are {cooldown, max_per_hour}") + extra = sorted(set(limits) - set(LIMITS)) + if extra: + raise ValueError(f"limits have no {extra[0]}") + out = {**LIMITS, **{k: v for k, v in limits.items() if v is not None}} + automation_spec.check_duration(out["cooldown"], what="the cooldown") + n = out["max_per_hour"] + if not isinstance(n, int) or isinstance(n, bool) or not 1 <= n <= MAX_PER_HOUR: + raise ValueError(f"max_per_hour is 1 to {MAX_PER_HOUR} runs") + return out + + +def _soon(triggers, join): + """Refuse what needs a part of the studio that isn't here yet.""" + for t in triggers: + need = SOON.get(t["on"]) + if need and provided(need[0], need[1]) is None: + raise ValueError(f"trigger {t['as']}: {need[2]} are coming soon; use a trigger on event or manual") + if join["mode"] != "any" and provided("match", "join_step") is None: + raise ValueError(f"joins of mode {join['mode']} are coming soon; each trigger starts a run of its own (any)") + + +def _graph(db, d, row): + """(the workflow graph to save as a new version, or None; the workflow id; its version; the graph it will run).""" + if d.get("graph") is not None and d.get("workflow") is not None: + raise ValueError("give the Then as a graph or as a workflow, not both") + if d.get("graph") is not None: + graph = workflows.validate_graph(db, d["graph"], "event") + return graph, (row or {}).get("workflow"), None, graph + if d.get("workflow") is not None or "version" in d: + wid = d.get("workflow", (row or {}).get("workflow")) + version = d.get("version") + if not isinstance(wid, int) or isinstance(wid, bool): + raise ValueError("choose a workflow (scope event) or give the Then as a graph") + if version is not None and (not isinstance(version, int) or isinstance(version, bool)): + raise ValueError("version is a version number, or none to follow the published one") + try: + w = workflows.get(db, wid, version) + except KeyError: + raise ValueError(f"no workflow {wid}" + (f" version {version}" if version else "")) from None + if w["scope"] != "event": + raise ValueError(f"{w['name']} isn't an automation's workflow (scope event)") + return None, wid, version, w["graph"] + if row is None: + raise ValueError("say what it does: a graph of action nodes (the Then)") + return None, row["workflow"], row.get("version"), workflows.get(db, row["workflow"], row.get("version"))["graph"] + + +def _check(db, d, row=None, account=None): + """An automation's settings, checked against what it has (`row`, None for a new one) and the account it acts + for. Returns (the fields to save, a graph to save as a new version of its workflow or None).""" + extra = sorted(set(d) - KEYS) + if extra: + raise ValueError(f"an automation has no {extra[0]}") + out: dict = {} + if "name" in d or row is None: + name = d.get("name") + if not isinstance(name, str) or not name.strip(): + raise ValueError("give the automation a name") + out["name"] = name.strip()[:80] + if "description" in d: + desc = d["description"] + if desc is not None and not isinstance(desc, str): + raise ValueError("the description is text") + out["description"] = (desc or "").strip()[:500] or None + if "enabled" in d: + if not isinstance(d["enabled"], bool): + raise ValueError("enabled is true or false") + out["enabled"] = d["enabled"] + if "spaces" in d or row is None: + out["spaces"] = _check_spaces(db, d.get("spaces"), account) + triggers = automation_spec.check_triggers(d["triggers"]) if "triggers" in d or row is None else row["triggers"] + join = automation_spec.check_join(d.get("join"), [t["as"] for t in triggers]) if "join" in d or row is None else row["join"] + if "triggers" in d or "join" in d or row is None: + hooks = {t["as"]: t.get("hook") for t in (row or {}).get("triggers") or [] if t["on"] == "webhook"} + for t in triggers: + if t["on"] == "webhook": + t["hook"] = hooks.get(t["as"]) # a hook is given when it is saved, never chosen + _soon(triggers, join) + out["triggers"], out["join"] = triggers, join + if "if" in d: + out["condition"] = automation_spec.check_if(d["if"]) + graph, wid, version, runs = _graph(db, d, row) + if graph is None and (wid != (row or {}).get("workflow") or version != (row or {}).get("version")): + out["workflow"], out["version"] = wid, version + nodes = action_nodes(runs) + if "policy" in d or graph is not None or "workflow" in d or "version" in d: + had = dict((row or {}).get("policy") or {}) + want = (d["policy"] or {}) if "policy" in d else had + if not isinstance(want, dict): + raise ValueError("the policy is {node id: ask or auto}") + want = {k: v for k, v in want.items() if k in nodes or "policy" in d} + # only the person sets auto (set_policy); a node already on auto may stay so + changed = {k: v for k, v in want.items() if not (v == "auto" and had.get(k) == "auto" and k in nodes)} + out["policy"] = {**automation_spec.check_policy(changed, nodes), **{k: v for k, v in want.items() if k not in changed}} + if "limits" in d or row is None: + out["limits"] = _check_limits(d.get("limits")) + return out, graph + + +# ---------- saving ---------- +def _seal(db, cfg, graph, aid, spaces): + """The graph as kept: credentials in `http_request` headers sealed with a namespace's key, bound to this + automation and to the address they go to (actions_web.seal_headers). A value holding {{ }} is filled in when it + runs, so it stays as written.""" + nodes = [] + for n in (graph or {}).get("nodes") or []: + conf = n.get("config") or {} + params = conf.get("params") or {} + headers = params.get("headers") + if n.get("type") == "action" and conf.get("action") == "http_request" and isinstance(headers, dict): + fixed = {k: v for k, v in headers.items() if isinstance(v, str) and "{{" not in v} + if any(actions_web.secret(k) and v and not keyring.is_sealed(v) for k, v in fixed.items()): + url = params.get("url") + if not isinstance(url, str) or "{{" in url: + raise ValueError(f"{n.get('id')}: a header with a credential is sealed for one address; give the url as written") + sid = sorted(spaces)[0] if spaces else min(store.space_names(db)) + try: + sealed = actions_web.seal_headers(db, cfg, sid, aid, url, fixed) + except keyring.Locked: + raise ValueError("the namespace's vault is locked; unlock it to save credentials") from None + conf = {**conf, "params": {**params, "headers": {k: sealed.get(k, v) for k, v in headers.items()}}} + if isinstance(conf.get("body"), dict): + conf = {**conf, "body": _seal(db, cfg, conf["body"], aid, spaces)} + nodes.append({**n, "config": conf} if n.get("config") is not None else n) + return {**graph, "nodes": nodes} + + +def create(db, cfg, d, user): + """A new automation for `user` (an account {id, email, name, admin}), who it acts for. Returns {id, hooks}: the + URLs of webhooks it was given, shown this once.""" + account = _account(db, user.get("id")) if isinstance(user, dict) else None + if not account: + raise ValueError("an automation acts for a person; sign in") + fields, graph = _check(db, dict(d), None, account) + t = store.now() + aid = db.next_id("automation") + if graph is not None: + graph = _seal(db, cfg, graph, aid, fields.get("spaces")) + fields["workflow"] = workflows.create(db, fields["name"], graph, fields.get("description"), account["email"], scope="event") + fields["version"] = None + on = fields.get("enabled", True) + row = { + **fields, + "enabled": on, + "enabled_at": t if on else None, + "run_as": account["id"], + "policy": fields.get("policy") or {}, + "counters": dict.fromkeys(COUNTERS, 0), + "created_by": account["email"], + "created_at": t, + "updated_at": t, + } + db.q("CREATE $r CONTENT $d", r=R("automation", aid), d=store.clean(row)) + return {"id": aid, "hooks": _arm(db, cfg, aid)} + + +def update(db, cfg, aid, d, by=None): + """Change an automation (only what `d` names). A new graph is saved as a new version of its workflow, which it + then follows. Returns {id, hooks} like create.""" + row = _row(db, aid) + account = _account(db, row.get("run_as")) + if not account: + raise ValueError("the person this automation acts for has no account any more; make it again as yourself") + fields, graph = _check(db, dict(d), row, account) + if "triggers" in fields: + _revoke(db, _hooks(row["triggers"]) - _hooks(fields["triggers"])) + if graph is not None: + graph = _seal(db, cfg, graph, aid, fields["spaces"] if "spaces" in fields else row.get("spaces")) + workflows.save_version(db, row["workflow"], graph, user=by, publish=True) + fields["version"] = None + if "name" in fields and fields["name"] != row["name"]: + workflows.rename(db, row["workflow"], fields["name"]) + t = store.now() + if fields.get("enabled") and not row.get("enabled"): + fields["enabled_at"] = t + _set(db, aid, {**fields, "updated_at": t}) + return {"id": aid, "hooks": _arm(db, cfg, aid)} + + +def _hooks(triggers): + return {t["hook"] for t in triggers or [] if t.get("on") == "webhook" and t.get("hook") is not None} + + +def _revoke(db, hooks): + """Delete these webhooks: their addresses stop working at once.""" + revoke = provided("automation_hooks", "revoke") + if revoke is not None: + for h in sorted(hooks): + revoke(db, h) + + +def _set(db, aid, fields): + """Replace these fields (None removes one); objects are replaced whole, not merged.""" + if not fields: + return + sets = ", ".join(f"{k} = $v{i}" if v is not None else f"{k} = NONE" for i, (k, v) in enumerate(fields.items())) + db.q(f"UPDATE $r SET {sets}", r=R("automation", int(aid)), **{f"v{i}": v for i, v in enumerate(fields.values()) if v is not None}) + + +def enable(db, cfg, aid, on=True, by=None): + """Switch it on (it reacts to what happens from now on) or off (it keeps everything).""" + row = _row(db, aid) + if on and not _account(db, row.get("run_as")): + raise ValueError("the person this automation acts for has no account any more; make it again as yourself") + if bool(on) != bool(row.get("enabled")): + t = store.now() + _set(db, aid, {"enabled": bool(on), "updated_at": t, **({"enabled_at": t} if on else {})}) + _arm(db, cfg, aid) + + +def remove(db, cfg, aid, by=None): + """Delete it: it is switched off and hidden, and restore brings it back.""" + _row(db, aid) + t = store.now() + _set(db, aid, {"enabled": False, "removed_at": t, "updated_at": t}) + _arm(db, cfg, aid) + + +def restore(db, cfg, aid, by=None): + """Bring a deleted automation back, switched off.""" + row = _row(db, aid, removed=True) + if not row.get("removed_at"): + return + _set(db, aid, {"removed_at": None, "updated_at": store.now()}) + + +def set_policy(db, aid, node, value, by=None): + """Whether an action node asks first (ask) or runs on its own (auto). The one place auto is set: called for a + person in a signed-in session (the automation's page, the approvals inbox's Always).""" + row = _row(db, aid) + nodes = action_nodes(workflows.get(db, row["workflow"], row.get("version"))["graph"]) + got = automation_spec.check_policy({node: value}, nodes, allow_auto=True) + db.q("UPDATE $r SET policy = $p, updated_at = $t", r=R("automation", aid), p={**(row.get("policy") or {}), **got}, t=store.now()) + return {**(row.get("policy") or {}), **got} + + +def _arm(db, cfg, aid): + """After a save, a switch or a delete: set its schedules' timers (or cancel them when it is off), and give each + webhook trigger without one its hook. Returns the new hooks' addresses and signing secrets, shown once.""" + row = _row(db, aid, removed=True) + urls = [] + on = bool(row.get("enabled")) and not row.get("removed_at") + token_for = provided("automation_hooks", "token_for") + if token_for is not None and not row.get("removed_at"): + triggers, changed = [dict(t) for t in row["triggers"]], False + for t in triggers: + if t["on"] == "webhook" and t.get("hook") is None: + got = token_for(db, cfg, aid, t["as"]) + t["hook"], changed = got["hook"], True + urls.append({"as": t["as"], "url": got["url"], "secret": got["secret"]}) + if changed: + db.q("UPDATE $r SET triggers = $t", r=R("automation", aid), t=triggers) + row["triggers"] = triggers + if on: + arm = provided("timers", "schedule_automation") + if arm is not None: + arm(db, view(db, row)) + else: + cancel = provided("timers", "cancel_for") + if cancel is not None: + cancel(db, aid) + return urls + + +# ---------- reading ---------- +def _row(db, aid, removed=False): + row = db.one(f"SELECT {FIELDS} FROM $r", r=R("automation", int(aid))) + if not row or (row.get("removed_at") and not removed): + raise KeyError(aid) + return row + + +def view(db, row, names=None): + names = store.space_names(db) if names is None else names + out = {k: v for k, v in row.items() if k != "condition"} + return { + **out, + "if": row.get("condition"), + "enabled": bool(row.get("enabled")), + "policy": row.get("policy") or {}, + "limits": {**LIMITS, **(row.get("limits") or {})}, + "counters": {**dict.fromkeys(COUNTERS, 0), **(row.get("counters") or {})}, + "namespace_names": None if row.get("spaces") is None else [names.get(s) for s in row["spaces"]], + } + + +def get(db, aid, removed=False): + """One automation, with the graph it runs (KeyError when there's none, or it was deleted).""" + row = view(db, _row(db, aid, removed)) + try: + w = workflows.get(db, row["workflow"], row.get("version")) + row["graph"], row["runs_version"] = w["graph"], w["version"] + except KeyError: + row["graph"], row["runs_version"] = None, None + return row + + +def list_automations(db, spaces=None, removed=False): + """Every automation (deleted ones only with `removed`), or those that work only in namespaces from `spaces`.""" + names = store.space_names(db) + out = [] + for row in db.rows(f"SELECT {FIELDS} FROM automation ORDER BY id"): + if bool(row.get("removed_at")) != bool(removed): + continue + if spaces is not None and (row.get("spaces") is None or not set(row["spaces"]) <= set(spaces)): + continue + out.append(view(db, row, names)) + return out + + +def manages(row, editable_spaces, admin=False): + """Whether someone who can edit `editable_spaces` may see and change this automation: an admin may change any, + anyone else those that work only in namespaces they can edit.""" + if admin: + return True + return row.get("spaces") is not None and set(row["spaces"]) <= set(editable_spaces) diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index 8eec3f5c6..7ebfcd019 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -1276,6 +1276,9 @@ def close(self): "DEFINE INDEX IF NOT EXISTS timer_due ON timer FIELDS status, at", "DEFINE INDEX IF NOT EXISTS timer_automation ON timer FIELDS automation, status", "DEFINE INDEX IF NOT EXISTS timer_done ON timer FIELDS done_at", + # automations (domain/automations.py, docs/automations.md): automation: + "DEFINE TABLE IF NOT EXISTS automation SCHEMALESS", + "DEFINE INDEX IF NOT EXISTS automation_enabled ON automation FIELDS enabled", "DEFINE INDEX IF NOT EXISTS upload_recording ON upload FIELDS recording", # review marks on the timeline (domain/event_marks.py, docs/timeline.md): each person's reviewed, important and # hidden flags on an activity, event_mark: (the id keeps the pair unique) diff --git a/fastapi_backend/app/schemas/automations.py b/fastapi_backend/app/schemas/automations.py new file mode 100644 index 000000000..d2db45cba --- /dev/null +++ b/fastapi_backend/app/schemas/automations.py @@ -0,0 +1,119 @@ +"""Automations (docs/automations.md, Automations): triggers, an If and a Then (a workflow of scope event) that act +for one person in some namespaces; the actions they can take.""" + +from __future__ import annotations + +from typing import Any, Literal + +from pydantic import ConfigDict, Field + +from app.schemas.common import RequestModel, ResponseModel + +TRIGGERS = ( + "each {as, on, ...}: {as, on: event, kinds, where?, from_automations?}, {as, on: manual}; on schedule, at, relative " + "and webhook are coming soon (docs/automations.md, Triggers)" +) +IF = "a match tree over the run context, tested before the Then runs, like {all: [{path, op, value}]}" +GRAPH = "the Then: a workflow graph of scope event (an input node, then action nodes and the flow primitives)" +POLICY = "{action node id: ask}; only you, signed in, let a node run on its own (POST /automations/{id}/policy)" + + +class Automation(ResponseModel): + model_config = ConfigDict(extra="allow", populate_by_name=True, serialize_by_alias=True) + + id: int + name: str + description: str | None = None + enabled: bool + enabled_at: str | None = Field(None, description="when it was last switched on: it reacts only to what happens after") + spaces: list[int] | None = Field(None, description="the namespaces it works in; none for every one (admins)") + namespace_names: list[str | None] | None = None + run_as: int = Field(description="the account it acts for, with that person's permissions: its maker") + triggers: list[dict[str, Any]] = Field(description=TRIGGERS) + join: dict[str, Any] = Field(description="how several triggers make one run: {mode: any} (each on its own)") + if_: dict[str, Any] | None = Field(None, alias="if", description=IF) + workflow: int = Field(description="its workflow (scope event)") + version: int | None = Field(None, description="the workflow version it runs; none follows the published one") + runs_version: int | None = Field(None, description="the version it runs now") + graph: dict[str, Any] | None = Field(None, description=GRAPH) + policy: dict[str, Literal["ask", "auto"]] = Field(default_factory=dict, description="{action node id: ask or auto}") + limits: dict[str, Any] = Field(description="{cooldown (like 10m), max_per_hour}") + counters: dict[str, int] = Field(description="{runs, skipped (its If was false), limited (over a limit), missed}") + last_run_at: str | None = None + last_status: str | None = None + created_by: str | None = None + created_at: str | None = None + updated_at: str | None = None + removed_at: str | None = Field(None, description="when it was deleted (restore brings it back)") + + +class AutomationCatalog(ResponseModel): + automations: list[Automation] + + +class AutomationCreate(RequestModel): + model_config = ConfigDict(extra="forbid", populate_by_name=True) + + name: str + description: str | None = None + enabled: bool = Field(True, description="switched on, it reacts to what happens from now on") + spaces: list[int] | None = Field(None, description="namespace ids you can edit; default: each one you can edit (every one, for admins)") + triggers: list[dict[str, Any]] = Field(description=TRIGGERS) + join: dict[str, Any] | None = Field(None, description="default {mode: any}: each trigger starts a run of its own") + if_: dict[str, Any] | None = Field(None, alias="if", description=IF) + graph: dict[str, Any] | None = Field(None, description=GRAPH + "; or name a saved one in workflow") + workflow: int | None = Field(None, description="a saved workflow of scope event, instead of a graph") + version: int | None = Field(None, description="with workflow: the version to run; none follows the published one") + policy: dict[str, Literal["ask"]] | None = Field(None, description=POLICY) + limits: dict[str, Any] | None = Field(None, description="{cooldown: 0s, max_per_hour: 60}") + + +class AutomationUpdate(RequestModel): + model_config = ConfigDict(extra="forbid", populate_by_name=True) + + name: str | None = None + description: str | None = None + enabled: bool | None = None + spaces: list[int] | None = None + triggers: list[dict[str, Any]] | None = None + join: dict[str, Any] | None = None + if_: dict[str, Any] | None = Field(None, alias="if", description=IF + "; null for none") + graph: dict[str, Any] | None = Field(None, description="a new Then, saved as a new version of its workflow") + workflow: int | None = None + version: int | None = Field(None, description="the workflow version to run; null follows the published one") + policy: dict[str, Literal["ask", "auto"]] | None = Field( + None, description="{action node id: ask}; a node already set to auto may stay auto, and only you set auto (its own route)" + ) + limits: dict[str, Any] | None = None + + +class AutomationSaved(ResponseModel): + id: int + hooks: list[dict[str, str]] = Field( + default_factory=list, description="new webhook triggers' addresses and signing secrets {as, url, secret}, shown this once" + ) + + +class AutomationSwitch(RequestModel): + on: bool = True + + +class AutomationPolicy(RequestModel): + node: str = Field(description="an action node's id") + value: Literal["ask", "auto"] = Field(description="ask: it asks you first; auto: it runs on its own") + + +class ActionInfo(ResponseModel): + model_config = ConfigDict(extra="allow", populate_by_name=True, serialize_by_alias=True) + + name: str + label: str + group: str + description: str = "" + params: dict[str, Any] = Field(description="a JSON Schema (type object) of its params; a string holding {{ }} stands for any type") + required: list[str] = Field(default_factory=list) + effect: Literal["read", "self", "lens", "out", "depends"] = Field( + description="what it reaches: read and self run at once; lens asks unless it changes the event's own object; out asks " + "first unless you let it run on its own; depends: worked out from its params" + ) + output: dict[str, Any] | None = Field(None, description="a JSON Schema of what it gives back, for later nodes (steps.)") diff --git a/fastapi_backend/tests/api/test_automations.py b/fastapi_backend/tests/api/test_automations.py new file mode 100644 index 000000000..f5cd97211 --- /dev/null +++ b/fastapi_backend/tests/api/test_automations.py @@ -0,0 +1,243 @@ +"""Automations over the API (docs/automations.md, Automations): saved with their checks, for the person who made them +in namespaces they can edit; changed, switched, deleted and restored; the policy set only by the person; the actions +catalog; and the parts built in their own modules (schedules, webhooks, joins) called once they are there.""" + +from __future__ import annotations + +import json + +import pytest + +from app.domain import automations, keyring, store, workflows +from tests.helpers import login, make_user, without + +URL = "/api/v1/automations" + + +def node(nid, t, **config): + return {"id": nid, "type": t, "config": config} + + +def edge(a, b): + return {"source": a, "target": b} + + +SAY = { + "nodes": [node("i", "input"), node("a", "action", action="log_line", params={"text": "New: {{ event.object.name }}"})], + "edges": [edge("i", "a")], +} +NEW = [{"as": "new", "on": "event", "kinds": ["asset.added"]}] + + +def body(**over): + return {"name": "Say new assets", "triggers": NEW, "graph": SAY, **over} + + +@pytest.fixture +def env(client, new_client, db): + pods, calls = store.ns_id(db, "pods"), store.ns_id(db, "calls") + make_user(db, "root@x.io", "root password 1", admin=True) + make_user(db, "ed@x.io", "editor password 1", roles={"pods": "editor", "calls": "viewer"}) + make_user(db, "vi@x.io", "viewer password 1", roles={"pods": "viewer"}) + return { + "pods": pods, + "calls": calls, + "hr": login(client, "root@x.io", "root password 1"), + "he": login(new_client(), "ed@x.io", "editor password 1"), + "hv": login(new_client(), "vi@x.io", "viewer password 1"), + } + + +def problem(client, h, json, path=URL, method="post"): + r = getattr(client, method)(path, headers=h, json=json) + assert r.status_code == 400, r.text + return r.json()["detail"] + + +def test_automations_are_saved_for_their_maker_in_namespaces_they_edit(client, db, env): + hr, he, hv = env["hr"], env["he"], env["hv"] + assert client.get(URL).status_code == 401 + # an admin's works everywhere unless they say; its Then is saved as a workflow of scope event + r = client.post(URL, headers=hr, json=body(**{"if": {"all": [{"path": "event.space", "op": "exists"}]}})) + assert r.status_code == 200, r.text + root = r.json()["id"] + a = client.get(f"{URL}/{root}", headers=hr).json() + assert a["spaces"] is None and a["enabled"] and a["enabled_at"] and a["run_as"] and a["version"] is None + assert a["graph"] == workflows.get(db, a["workflow"])["graph"] and a["runs_version"] == 1 and a["if"]["all"][0]["op"] == "exists" + assert a["join"] == {"mode": "any"} and a["limits"] == {"cooldown": "0s", "max_per_hour": 60} and a["counters"]["runs"] == 0 + assert workflows.get(db, a["workflow"])["scope"] == "event" and a["triggers"][0]["from_automations"] is False + # a member's works in the namespaces they can edit, and they see only those + mine = client.post(URL, headers=he, json=body(name="Mine")).json()["id"] + assert client.get(f"{URL}/{mine}", headers=he).json()["spaces"] == [env["pods"]] + assert [x["id"] for x in client.get(URL, headers=he).json()["automations"]] == [mine] + assert client.get(f"{URL}/{root}", headers=he).status_code == 404 + assert [x["id"] for x in client.get(URL, headers=hr).json()["automations"]] == [root, mine] + assert "can't edit namespace" in problem(client, he, body(spaces=[env["calls"]])) + assert "can't edit any namespace" in problem(client, hv, body()) + assert client.get(f"{URL}/{mine}", headers=hv).status_code == 404 + assert client.patch(f"{URL}/{mine}", headers=hv, json={"name": "x"}).status_code == 404 + + +def test_what_an_automation_is_made_of_is_checked(client, db, env, monkeypatch): + without(monkeypatch, "timers", "match") # schedules and joins come with their own modules + hr = env["hr"] + assert "at least one trigger" in problem(client, hr, body(triggers=[])) + assert "kinds" in problem(client, hr, body(triggers=[{"as": "x", "on": "event"}])) + assert "no kind email.nope" in problem(client, hr, body(triggers=[{"as": "x", "on": "event", "kinds": ["email.nope"]}])) + assert "schedules are coming soon" in problem(client, hr, body(triggers=[{"as": "m", "on": "schedule", "cron": "0 7 * * *"}])) + two = [*NEW, {"as": "now", "on": "manual"}] + assert "coming soon" in problem(client, hr, body(triggers=two, join={"mode": "all", "within": "1h"})) + assert "paths start with" in problem(client, hr, body(**{"if": {"all": [{"path": "nope.x", "op": "exists"}]}})) + assert "choose an action" in problem( + client, hr, body(graph={"nodes": [node("i", "input"), node("a", "action", action="nope")], "edges": [edge("i", "a")]}) + ) + assert "say what it does" in problem(client, hr, {"name": "x", "triggers": NEW}) + assert "max_per_hour" in problem(client, hr, body(limits={"max_per_hour": 0})) + assert "cooldown" in problem(client, hr, body(limits={"cooldown": "-5m"})) + assert "isn't in the workflow" in problem(client, hr, body(policy={"zz": "ask"})) + # auto is only the person's own pick, on its own route + assert client.post(URL, headers=hr, json=body(policy={"a": "auto"})).status_code == 422 + # a saved workflow of scope event will do, another scope won't + wid = workflows.create(db, "Say it", SAY, scope="event") + other = workflows.create(db, "Keep", {"nodes": [node("i", "input"), node("o", "output", key="k")], "edges": [edge("i", "o")]}) + assert "scope event" in problem(client, hr, {"name": "x", "triggers": NEW, "workflow": other}) + assert "not both" in problem(client, hr, body(workflow=wid)) + r = client.post(URL, headers=hr, json={"name": "Saved", "triggers": [{"as": "now", "on": "manual"}], "workflow": wid, "version": 1}) + assert r.status_code == 200 and client.get(f"{URL}/{r.json()['id']}", headers=hr).json()["version"] == 1 + + +def test_automations_change_switch_delete_and_come_back(client, db, env): + hr = env["hr"] + aid = client.post(URL, headers=hr, json=body(enabled=False, **{"if": {"all": [{"path": "event.space", "op": "exists"}]}})).json()["id"] + a = client.get(f"{URL}/{aid}", headers=hr).json() + assert not a["enabled"] and a["enabled_at"] is None + # a new graph is a new version of its workflow, which it follows; the name follows too + more = { + "nodes": [*SAY["nodes"], node("b", "action", action="log_line", params={"text": "{{ steps.a.line }}"})], + "edges": [*SAY["edges"], edge("a", "b")], + } + r = client.patch(f"{URL}/{aid}", headers=hr, json={"graph": more, "name": "Say twice", "if": None}) + assert r.status_code == 200, r.text + a = client.get(f"{URL}/{aid}", headers=hr).json() + assert a["runs_version"] == 2 and a["version"] is None and len(a["graph"]["nodes"]) == 3 and a["if"] is None + assert workflows.get(db, a["workflow"])["name"] == "Say twice" + assert "a trigger on event has no cron" in problem( + client, hr, {"triggers": [{"as": "x", "on": "event", "kinds": ["asset.added"], "cron": "0 * * * *"}]}, f"{URL}/{aid}", "patch" + ) + # switched on, it reacts from now on; off keeps everything + assert client.post(f"{URL}/{aid}/enable", headers=hr, json={"on": True}).status_code == 200 + on = client.get(f"{URL}/{aid}", headers=hr).json() + assert on["enabled"] and on["enabled_at"] + client.post(f"{URL}/{aid}/enable", headers=hr, json={"on": False}) + assert client.get(f"{URL}/{aid}", headers=hr).json()["enabled_at"] == on["enabled_at"] + client.post(f"{URL}/{aid}/enable", headers=hr, json={"on": True}) + # deleted: switched off and hidden, and restore undoes it + assert client.delete(f"{URL}/{aid}", headers=hr).status_code == 200 + assert client.get(f"{URL}/{aid}", headers=hr).status_code == 404 and client.get(URL, headers=hr).json()["automations"] == [] + assert [x["id"] for x in client.get(URL, params={"removed": True}, headers=hr).json()["automations"]] == [aid] + assert client.post(f"{URL}/{aid}/restore", headers=hr).status_code == 200 + back = client.get(f"{URL}/{aid}", headers=hr).json() + assert not back["enabled"] and back["removed_at"] is None + assert client.post(f"{URL}/9999/restore", headers=hr).status_code == 404 + + +def test_only_the_person_lets_a_node_run_on_its_own(client, db, env): + hr = env["hr"] + aid = client.post(URL, headers=hr, json=body()).json()["id"] + key = client.post("/api/v1/tokens", headers=hr, json={"name": "agent", "scope": "write"}).json()["token"] + ha = {"Authorization": f"Bearer {key}"} + r = client.post(f"{URL}/{aid}/policy", headers=ha, json={"node": "a", "value": "auto"}) + assert r.status_code == 403 and "signed in" in r.json()["detail"] + assert client.post(f"{URL}/{aid}/policy", headers=ha, json={"node": "a", "value": "ask"}).status_code == 200 + assert client.post(f"{URL}/{aid}/policy", headers=hr, json={"node": "zz", "value": "auto"}).status_code == 400 + assert client.post(f"{URL}/{aid}/policy", headers=hr, json={"node": "a", "value": "auto"}).json() == {"a": "auto"} + # a save that keeps it on auto is fine; nobody else sets it there + assert client.patch(f"{URL}/{aid}", headers=ha, json={"policy": {"a": "auto"}, "name": "Still"}).status_code == 200 + assert client.get(f"{URL}/{aid}", headers=hr).json()["policy"] == {"a": "auto"} + automations.set_policy(db, aid, "a", "ask") + assert "only you can let node a run" in problem(client, ha, {"policy": {"a": "auto"}}, f"{URL}/{aid}", "patch") + # a node that goes away takes its pick with it + client.post(f"{URL}/{aid}/policy", headers=hr, json={"node": "a", "value": "auto"}) + other = {"nodes": [node("i", "input"), node("b", "action", action="log_line", params={"text": "x"})], "edges": [edge("i", "b")]} + client.patch(f"{URL}/{aid}", headers=hr, json={"graph": other}) + assert client.get(f"{URL}/{aid}", headers=hr).json()["policy"] == {} + + +def test_credentials_for_a_web_call_are_sealed_when_it_is_saved(client, db, cfg, env): + he = env["he"] + headers = {"Authorization": "Bearer s3cret", "X-Token": "{{ event.id }}", "Accept": "text/plain"} + call = node("w", "action", action="http_request", params={"url": "https://hooks.example/in", "method": "POST", "headers": headers}) + graph = {"nodes": [node("i", "input"), call], "edges": [edge("i", "w")]} + aid = client.post(URL, headers=he, json=body(graph=graph)).json()["id"] + a = client.get(f"{URL}/{aid}", headers=he).json() + kept = a["graph"]["nodes"][1]["config"]["params"]["headers"] + # bound to this automation and the address, with the namespace's key; a template is filled in when it runs + assert keyring.is_sealed(kept["Authorization"]) and kept["X-Token"] == "{{ event.id }}" and kept["Accept"] == "text/plain" + assert "s3cret" not in json.dumps(a) and kept["Authorization"].split(".")[1] == str(env["pods"]) + got = keyring.unseal(db, cfg, kept["Authorization"], f"automation:{aid}.header:authorization@https://hooks.example:443") + assert got == b"Bearer s3cret" + # saved again as it was read, it is sealed once + r = client.patch(f"{URL}/{aid}", headers=he, json={"graph": a["graph"]}) + assert r.status_code == 200, r.text + assert client.get(f"{URL}/{aid}", headers=he).json()["graph"]["nodes"][1]["config"]["params"]["headers"] == kept + # a credential is sealed for one address, so the address can't be a template + call["config"]["params"]["url"] = "https://{{ event.id }}.example/in" + assert "sealed for one address" in problem(client, he, body(graph=graph)) + + +def test_the_actions_catalog(client, env): + got = client.get(f"{URL}/actions", headers=env["he"]).json() + log_line = next(a for a in got if a["name"] == "log_line") + assert log_line["effect"] == "read" and log_line["required"] == ["text"] and log_line["params"]["type"] == "object" + + +def test_a_webhook_trigger_gets_its_address_when_saved_and_loses_it_when_dropped(client, db, env): + hr = env["hr"] + ts = [*NEW, {"as": "ping", "on": "webhook"}] + r = client.post(URL, headers=hr, json=body(triggers=ts, spaces=[env["pods"]])) + assert r.status_code == 200, r.text + aid, (hook,) = r.json()["id"], r.json()["hooks"] + assert hook["as"] == "ping" and "/api/v1/automations/hooks/lah_" in hook["url"] and hook["secret"] + path = hook["url"][hook["url"].index("/api/v1/") :] + kept = client.get(f"{URL}/{aid}", headers=hr).json()["triggers"][1]["hook"] + assert isinstance(kept, int) + # a call to it is an activity in the automation's namespace + r = client.post(path, json={"door": "open"}) + assert r.status_code == 202, r.text + # saved again, the trigger keeps its address; dropped, the address stops working at once + assert client.patch(f"{URL}/{aid}", headers=hr, json={"triggers": ts}).json()["hooks"] == [] + assert client.post(path, json={"door": "open"}).status_code == 202 + assert client.patch(f"{URL}/{aid}", headers=hr, json={"triggers": NEW}).status_code == 200 + assert client.post(path, json={"door": "open"}).status_code == 401 + + +def test_schedules_and_webhooks_are_armed_once_their_modules_are_there(client, db, env, monkeypatch): + calls = [] + fake = { + ("timers", "schedule_automation"): lambda db, a: calls.append(("arm", a["id"])), + ("timers", "relative"): lambda *a: None, + ("timers", "cancel_for"): lambda db, aid: calls.append(("cancel", aid)), + ("automation_hooks", "token_for"): lambda db, cfg, aid, alias: { + "hook": 70 + aid, + "url": f"https://lens.example/hooks/{alias}-{aid}", + "secret": "whsec_x", + }, + ("match", "join_step"): lambda *a: [], + } + monkeypatch.setattr(automations, "provided", lambda m, fn: fake.get((m, fn))) + hr = env["hr"] + ts = [{"as": "morning", "on": "schedule", "cron": "0 7 * * 1-5", "timezone": "Europe/London"}, {"as": "hook", "on": "webhook"}] + r = client.post(URL, headers=hr, json=body(triggers=ts, join={"mode": "any"})) + assert r.status_code == 200, r.text + aid = r.json()["id"] + assert r.json()["hooks"] == [{"as": "hook", "url": f"https://lens.example/hooks/hook-{aid}", "secret": "whsec_x"}] + assert calls == [("arm", aid)] + a = client.get(f"{URL}/{aid}", headers=hr).json() + assert a["triggers"][1]["hook"] == 70 + aid + # the URL is shown once: saving again keeps the hook, and a hook is never chosen + r = client.patch(f"{URL}/{aid}", headers=hr, json={"triggers": [*ts[:1], {"as": "hook", "on": "webhook", "hook": 5}]}) + assert r.json()["hooks"] == [] and client.get(f"{URL}/{aid}", headers=hr).json()["triggers"][1]["hook"] == 70 + aid + client.post(f"{URL}/{aid}/enable", headers=hr, json={"on": False}) + assert calls[-1] == ("cancel", aid) + two = [*NEW, {"as": "now", "on": "manual"}] + assert client.post(URL, headers=hr, json=body(triggers=two, join={"mode": "all", "within": "1h"})).status_code == 200 diff --git a/fastapi_backend/tests/api/test_event_workflows.py b/fastapi_backend/tests/api/test_event_workflows.py index 359c3cac6..af4fc47d8 100644 --- a/fastapi_backend/tests/api/test_event_workflows.py +++ b/fastapi_backend/tests/api/test_event_workflows.py @@ -5,7 +5,7 @@ from __future__ import annotations from app.domain import ingest -from tests.helpers import login, make_user, seed +from tests.helpers import login, make_user, seed, without URL = "/api/v1/workflows" @@ -29,7 +29,8 @@ def _root(client, db): return login(client, "root@x.io", "root password 1") -def test_event_workflows_are_checked_and_kept_apart(client, db, cfg): +def test_event_workflows_are_checked_and_kept_apart(client, db, cfg, monkeypatch): + without(monkeypatch, "match") # deciding comes with its own module h = _root(client, db) rec = ingest.import_text(db, cfg, "pods", "Alice: Hello.", title="Hello") cat = client.get(URL, headers=h).json() diff --git a/fastapi_backend/tests/domain/test_automation_nodes.py b/fastapi_backend/tests/domain/test_automation_nodes.py index ed08447b4..73bb6650d 100644 --- a/fastapi_backend/tests/domain/test_automation_nodes.py +++ b/fastapi_backend/tests/domain/test_automation_nodes.py @@ -9,6 +9,7 @@ from app.domain import actions, automation_nodes, events, flow, match, workflows from app.domain.actions import ActionSpec +from tests.helpers import without SAMPLE = events.kind_info("asset.added")["sample"] USER = {"id": 1, "email": "sam@x.io", "name": "Sam", "admin": True} @@ -85,7 +86,8 @@ def _problem(db, g): return str(e.value) -def test_event_workflows_are_checked_on_save(db, made): +def test_event_workflows_are_checked_on_save(db, made, monkeypatch): + without(monkeypatch, "timers", "match") # waiting and deciding come with their own modules assert "needs an action node" in _problem(db, graph(node("p", "pick", path="event"), edges=[edge("in", "p")])) assert "choose an action" in _problem(db, graph(node("a", "action", action="nope"), edges=[edge("in", "a")])) assert "needs Line (text)" in _problem(db, graph(node("a", "action", action="log_line"), edges=[edge("in", "a")])) diff --git a/fastapi_backend/tests/helpers.py b/fastapi_backend/tests/helpers.py index d1ba18fb9..4d5e8f89d 100644 --- a/fastapi_backend/tests/helpers.py +++ b/fastapi_backend/tests/helpers.py @@ -216,3 +216,12 @@ def unmark(text): def marked(text, source): """`text` as the model reads it, marked as data from `source`, with its code written as X (unmark).""" return f'\n{text}\n' + + +def without(monkeypatch, *names): + """Hide modules of the workflow studio that land in their own steps (automation_nodes.module), so a check for + "coming soon" holds whether or not they are merged yet.""" + from app.domain import automation_nodes + + real = automation_nodes.module + monkeypatch.setattr(automation_nodes, "module", lambda name: None if name in names else real(name)) diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 056173ad0..5fb1fc3b4 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -65,6 +65,7 @@ export type { AcceptGraphChangeResponses, AccessRequest, AccountToken, + ActionInfo, ActionsData, ActionsError, ActionsErrors, @@ -176,6 +177,13 @@ export type { Attachment, AuditEntry, AuthStatus, + Automation, + AutomationCatalog, + AutomationCreate, + AutomationPolicy, + AutomationSaved, + AutomationSwitch, + AutomationUpdate, Backend, Backup, BackupFileData, @@ -392,6 +400,11 @@ export type { ConversionNodeTestResult, Converters, CopyWork, + CreateAutomationData, + CreateAutomationError, + CreateAutomationErrors, + CreateAutomationResponse, + CreateAutomationResponses, CreateBatchData, CreateBatchError, CreateBatchErrors, @@ -628,6 +641,11 @@ export type { DefineEntityErrors, DefineEntityResponse, DefineEntityResponses, + DeleteAutomationData, + DeleteAutomationError, + DeleteAutomationErrors, + DeleteAutomationResponse, + DeleteAutomationResponses, DeleteBackupData, DeleteBackupError, DeleteBackupErrors, @@ -861,6 +879,11 @@ export type { EmailInfo, EmbedLink, EmbedTestResult, + EnableAutomationData, + EnableAutomationError, + EnableAutomationErrors, + EnableAutomationResponse, + EnableAutomationResponses, EncryptionProgress, EnrichedDate, EnrichedPlace, @@ -1032,6 +1055,11 @@ export type { GetAudioError, GetAudioErrors, GetAudioResponses, + GetAutomationData, + GetAutomationError, + GetAutomationErrors, + GetAutomationResponse, + GetAutomationResponses, GetBatchData, GetBatchError, GetBatchErrors, @@ -1579,6 +1607,9 @@ export type { ListAccessRequestsErrors, ListAccessRequestsResponse, ListAccessRequestsResponses, + ListActionsData, + ListActionsResponse, + ListActionsResponses, ListActivitiesData, ListActivitiesError, ListActivitiesErrors, @@ -1605,6 +1636,11 @@ export type { ListAuditErrors, ListAuditResponse, ListAuditResponses, + ListAutomationsData, + ListAutomationsError, + ListAutomationsErrors, + ListAutomationsResponse, + ListAutomationsResponses, ListBackendsData, ListBackendsResponse, ListBackendsResponses, @@ -2542,6 +2578,11 @@ export type { ResourceTotalsErrors, ResourceTotalsResponse, ResourceTotalsResponses, + RestoreAutomationData, + RestoreAutomationError, + RestoreAutomationErrors, + RestoreAutomationResponse, + RestoreAutomationResponses, RestoreBackupData, RestoreBackupError, RestoreBackupErrors, @@ -2816,6 +2857,11 @@ export type { SetNamespaceFacesModeErrors, SetNamespaceFacesModeResponse, SetNamespaceFacesModeResponses, + SetPolicyData, + SetPolicyError, + SetPolicyErrors, + SetPolicyResponse, + SetPolicyResponses, SetRecordingContentTypeData, SetRecordingContentTypeError, SetRecordingContentTypeErrors, @@ -3194,6 +3240,11 @@ export type { UpdateAssistantMemoryErrors, UpdateAssistantMemoryResponse, UpdateAssistantMemoryResponses, + UpdateAutomationData, + UpdateAutomationError, + UpdateAutomationErrors, + UpdateAutomationResponse, + UpdateAutomationResponses, UpdateChatData, UpdateChatError, UpdateChatErrors, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 697f72c66..ba3aeb143 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -142,6 +142,9 @@ import type { ControlWorkerData, ControlWorkerErrors, ControlWorkerResponses, + CreateAutomationData, + CreateAutomationErrors, + CreateAutomationResponses, CreateBatchData, CreateBatchErrors, CreateBatchResponses, @@ -279,6 +282,9 @@ import type { DefineEntityData, DefineEntityErrors, DefineEntityResponses, + DeleteAutomationData, + DeleteAutomationErrors, + DeleteAutomationResponses, DeleteBackupData, DeleteBackupErrors, DeleteBackupResponses, @@ -416,6 +422,9 @@ import type { EditSegmentData, EditSegmentErrors, EditSegmentResponses, + EnableAutomationData, + EnableAutomationErrors, + EnableAutomationResponses, EntityToTopicData, EntityToTopicErrors, EntityToTopicResponses, @@ -480,6 +489,9 @@ import type { GetAudioData, GetAudioErrors, GetAudioResponses, + GetAutomationData, + GetAutomationErrors, + GetAutomationResponses, GetBatchData, GetBatchErrors, GetBatchResponses, @@ -769,6 +781,8 @@ import type { ListAccessRequestsData, ListAccessRequestsErrors, ListAccessRequestsResponses, + ListActionsData, + ListActionsResponses, ListActivitiesData, ListActivitiesErrors, ListActivitiesResponses, @@ -785,6 +799,9 @@ import type { ListAuditData, ListAuditErrors, ListAuditResponses, + ListAutomationsData, + ListAutomationsErrors, + ListAutomationsResponses, ListBackendsData, ListBackendsResponses, ListBackupsData, @@ -1233,6 +1250,9 @@ import type { ResourceTotalsData, ResourceTotalsErrors, ResourceTotalsResponses, + RestoreAutomationData, + RestoreAutomationErrors, + RestoreAutomationResponses, RestoreBackupData, RestoreBackupErrors, RestoreBackupResponses, @@ -1371,6 +1391,9 @@ import type { SetNamespaceFacesModeData, SetNamespaceFacesModeErrors, SetNamespaceFacesModeResponses, + SetPolicyData, + SetPolicyErrors, + SetPolicyResponses, SetRecordingContentTypeData, SetRecordingContentTypeErrors, SetRecordingContentTypeResponses, @@ -1536,6 +1559,9 @@ import type { UpdateAssistantMemoryData, UpdateAssistantMemoryErrors, UpdateAssistantMemoryResponses, + UpdateAutomationData, + UpdateAutomationErrors, + UpdateAutomationResponses, UpdateChatData, UpdateChatErrors, UpdateChatResponses, @@ -3815,6 +3841,152 @@ export class Automations { }, }); } + + /** + * List Automations + * + * Your automations: every one for an admin, else those that work only in namespaces you can edit. `removed` + * lists the deleted ones instead, to restore. + */ + public static listAutomations( + options?: Options, + ): RequestResult { + return (options?.client ?? client).get({ + url: "/api/v1/automations", + ...options, + }); + } + + /** + * Create Automation + * + * A new automation that acts for you. Its Then is a graph (saved as a workflow of scope event) or a saved + * workflow; its namespaces default to each one you can edit. Nodes ask first unless you let one run on its own + * (POST /automations/{id}/policy). + */ + public static createAutomation( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/automations", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + + /** + * List Actions + * + * What an action node can do: each action's params (a JSON Schema), what it reaches (its effect) and what it + * gives back. + */ + public static listActions( + options?: Options, + ): RequestResult { + return (options?.client ?? client).get({ + url: "/api/v1/automations/actions", + ...options, + }); + } + + /** + * Delete Automation + * + * Delete it: switched off and hidden; POST /automations/{id}/restore undoes it. + */ + public static deleteAutomation( + options: Options, + ): RequestResult { + return (options.client ?? client).delete({ + url: "/api/v1/automations/{aid}", + ...options, + }); + } + + /** + * Get Automation + */ + public static getAutomation( + options: Options, + ): RequestResult { + return (options.client ?? client).get({ + url: "/api/v1/automations/{aid}", + ...options, + }); + } + + /** + * Update Automation + * + * Change what is sent: a new graph is saved as a new version of its workflow; `if: null` drops its If, + * `version: null` follows the published version. + */ + public static updateAutomation( + options: Options, + ): RequestResult { + return (options.client ?? client).patch({ + url: "/api/v1/automations/{aid}", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + + /** + * Enable Automation + * + * Switch it on (it reacts to what happens from now on, never to what happened while it was off) or off. + */ + public static enableAutomation( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/automations/{aid}/enable", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + + /** + * Restore Automation + * + * Undo a delete: it comes back switched off. + */ + public static restoreAutomation( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/automations/{aid}/restore", + ...options, + }); + } + + /** + * Set Policy + * + * Whether an action node asks you first (ask) or runs on its own (auto). Only you, signed in to the web app, + * let a node run on its own: never an API key, an app or an agent. + */ + public static setPolicy( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/automations/{aid}/policy", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } } export class Budgets { diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 0166ad4ce..016f60431 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -108,6 +108,55 @@ export type AccountToken = { [key: string]: unknown; }; +/** + * ActionInfo + */ +export type ActionInfo = { + /** + * Name + */ + name: string; + /** + * Label + */ + label: string; + /** + * Group + */ + group: string; + /** + * Description + */ + description?: string; + /** + * Params + * + * a JSON Schema (type object) of its params; a string holding {{ }} stands for any type + */ + params: { + [key: string]: unknown; + }; + /** + * Required + */ + required?: Array; + /** + * Effect + * + * what it reaches: read and self run at once; lens asks unless it changes the event's own object; out asks first unless you let it run on its own; depends: worked out from its params + */ + effect: "read" | "self" | "lens" | "out" | "depends"; + /** + * Output + * + * a JSON Schema of what it gives back, for later nodes (steps.) + */ + output?: { + [key: string]: unknown; + } | null; + [key: string]: unknown; +}; + /** * ActivityActor */ @@ -1138,6 +1187,369 @@ export type AuthStatus = { [key: string]: unknown; }; +/** + * Automation + */ +export type Automation = { + /** + * Id + */ + id: number; + /** + * Name + */ + name: string; + /** + * Description + */ + description?: string | null; + /** + * Enabled + */ + enabled: boolean; + /** + * Enabled At + * + * when it was last switched on: it reacts only to what happens after + */ + enabled_at?: string | null; + /** + * Spaces + * + * the namespaces it works in; none for every one (admins) + */ + spaces?: Array | null; + /** + * Namespace Names + */ + namespace_names?: Array | null; + /** + * Run As + * + * the account it acts for, with that person's permissions: its maker + */ + run_as: number; + /** + * Triggers + * + * each {as, on, ...}: {as, on: event, kinds, where?, from_automations?}, {as, on: manual}; on schedule, at, relative and webhook are coming soon (docs/automations.md, Triggers) + */ + triggers: Array<{ + [key: string]: unknown; + }>; + /** + * Join + * + * how several triggers make one run: {mode: any} (each on its own) + */ + join: { + [key: string]: unknown; + }; + /** + * If + * + * a match tree over the run context, tested before the Then runs, like {all: [{path, op, value}]} + */ + if?: { + [key: string]: unknown; + } | null; + /** + * Workflow + * + * its workflow (scope event) + */ + workflow: number; + /** + * Version + * + * the workflow version it runs; none follows the published one + */ + version?: number | null; + /** + * Runs Version + * + * the version it runs now + */ + runs_version?: number | null; + /** + * Graph + * + * the Then: a workflow graph of scope event (an input node, then action nodes and the flow primitives) + */ + graph?: { + [key: string]: unknown; + } | null; + /** + * Policy + * + * {action node id: ask or auto} + */ + policy?: { + [key: string]: "ask" | "auto"; + }; + /** + * Limits + * + * {cooldown (like 10m), max_per_hour} + */ + limits: { + [key: string]: unknown; + }; + /** + * Counters + * + * {runs, skipped (its If was false), limited (over a limit), missed} + */ + counters: { + [key: string]: number; + }; + /** + * Last Run At + */ + last_run_at?: string | null; + /** + * Last Status + */ + last_status?: string | null; + /** + * Created By + */ + created_by?: string | null; + /** + * Created At + */ + created_at?: string | null; + /** + * Updated At + */ + updated_at?: string | null; + /** + * Removed At + * + * when it was deleted (restore brings it back) + */ + removed_at?: string | null; + [key: string]: unknown; +}; + +/** + * AutomationCatalog + */ +export type AutomationCatalog = { + /** + * Automations + */ + automations: Array; + [key: string]: unknown; +}; + +/** + * AutomationCreate + */ +export type AutomationCreate = { + /** + * Name + */ + name: string; + /** + * Description + */ + description?: string | null; + /** + * Enabled + * + * switched on, it reacts to what happens from now on + */ + enabled?: boolean; + /** + * Spaces + * + * namespace ids you can edit; default: each one you can edit (every one, for admins) + */ + spaces?: Array | null; + /** + * Triggers + * + * each {as, on, ...}: {as, on: event, kinds, where?, from_automations?}, {as, on: manual}; on schedule, at, relative and webhook are coming soon (docs/automations.md, Triggers) + */ + triggers: Array<{ + [key: string]: unknown; + }>; + /** + * Join + * + * default {mode: any}: each trigger starts a run of its own + */ + join?: { + [key: string]: unknown; + } | null; + /** + * If + * + * a match tree over the run context, tested before the Then runs, like {all: [{path, op, value}]} + */ + if?: { + [key: string]: unknown; + } | null; + /** + * Graph + * + * the Then: a workflow graph of scope event (an input node, then action nodes and the flow primitives); or name a saved one in workflow + */ + graph?: { + [key: string]: unknown; + } | null; + /** + * Workflow + * + * a saved workflow of scope event, instead of a graph + */ + workflow?: number | null; + /** + * Version + * + * with workflow: the version to run; none follows the published one + */ + version?: number | null; + /** + * Policy + * + * {action node id: ask}; only you, signed in, let a node run on its own (POST /automations/{id}/policy) + */ + policy?: { + [key: string]: "ask"; + } | null; + /** + * Limits + * + * {cooldown: 0s, max_per_hour: 60} + */ + limits?: { + [key: string]: unknown; + } | null; +}; + +/** + * AutomationPolicy + */ +export type AutomationPolicy = { + /** + * Node + * + * an action node's id + */ + node: string; + /** + * Value + * + * ask: it asks you first; auto: it runs on its own + */ + value: "ask" | "auto"; +}; + +/** + * AutomationSaved + */ +export type AutomationSaved = { + /** + * Id + */ + id: number; + /** + * Hooks + * + * new webhook triggers' addresses and signing secrets {as, url, secret}, shown this once + */ + hooks?: Array<{ + [key: string]: string; + }>; + [key: string]: unknown; +}; + +/** + * AutomationSwitch + */ +export type AutomationSwitch = { + /** + * On + */ + on?: boolean; +}; + +/** + * AutomationUpdate + */ +export type AutomationUpdate = { + /** + * Name + */ + name?: string | null; + /** + * Description + */ + description?: string | null; + /** + * Enabled + */ + enabled?: boolean | null; + /** + * Spaces + */ + spaces?: Array | null; + /** + * Triggers + */ + triggers?: Array<{ + [key: string]: unknown; + }> | null; + /** + * Join + */ + join?: { + [key: string]: unknown; + } | null; + /** + * If + * + * a match tree over the run context, tested before the Then runs, like {all: [{path, op, value}]}; null for none + */ + if?: { + [key: string]: unknown; + } | null; + /** + * Graph + * + * a new Then, saved as a new version of its workflow + */ + graph?: { + [key: string]: unknown; + } | null; + /** + * Workflow + */ + workflow?: number | null; + /** + * Version + * + * the workflow version to run; null follows the published one + */ + version?: number | null; + /** + * Policy + * + * {action node id: ask}; a node already set to auto may stay auto, and only you set auto (its own route) + */ + policy?: { + [key: string]: "ask" | "auto"; + } | null; + /** + * Limits + */ + limits?: { + [key: string]: unknown; + } | null; +}; + /** * Backend */ @@ -24932,6 +25344,263 @@ export type CallAutomationHookResponses = { export type CallAutomationHookResponse = CallAutomationHookResponses[keyof CallAutomationHookResponses]; +export type ListAutomationsData = { + body?: never; + path?: never; + query?: { + /** + * Removed + */ + removed?: boolean; + }; + url: "/api/v1/automations"; +}; + +export type ListAutomationsErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListAutomationsError = ListAutomationsErrors[keyof ListAutomationsErrors]; + +export type ListAutomationsResponses = { + /** + * Successful Response + */ + 200: AutomationCatalog; +}; + +export type ListAutomationsResponse = ListAutomationsResponses[keyof ListAutomationsResponses]; + +export type CreateAutomationData = { + body: AutomationCreate; + path?: never; + query?: never; + url: "/api/v1/automations"; +}; + +export type CreateAutomationErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type CreateAutomationError = CreateAutomationErrors[keyof CreateAutomationErrors]; + +export type CreateAutomationResponses = { + /** + * Successful Response + */ + 200: AutomationSaved; +}; + +export type CreateAutomationResponse = CreateAutomationResponses[keyof CreateAutomationResponses]; + +export type ListActionsData = { + body?: never; + path?: never; + query?: never; + url: "/api/v1/automations/actions"; +}; + +export type ListActionsResponses = { + /** + * Response Automations-List Actions + * + * Successful Response + */ + 200: Array; +}; + +export type ListActionsResponse = ListActionsResponses[keyof ListActionsResponses]; + +export type DeleteAutomationData = { + body?: never; + path: { + /** + * Aid + */ + aid: number; + }; + query?: never; + url: "/api/v1/automations/{aid}"; +}; + +export type DeleteAutomationErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type DeleteAutomationError = DeleteAutomationErrors[keyof DeleteAutomationErrors]; + +export type DeleteAutomationResponses = { + /** + * Successful Response + */ + 200: Ok; +}; + +export type DeleteAutomationResponse = DeleteAutomationResponses[keyof DeleteAutomationResponses]; + +export type GetAutomationData = { + body?: never; + path: { + /** + * Aid + */ + aid: number; + }; + query?: never; + url: "/api/v1/automations/{aid}"; +}; + +export type GetAutomationErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type GetAutomationError = GetAutomationErrors[keyof GetAutomationErrors]; + +export type GetAutomationResponses = { + /** + * Successful Response + */ + 200: Automation; +}; + +export type GetAutomationResponse = GetAutomationResponses[keyof GetAutomationResponses]; + +export type UpdateAutomationData = { + body: AutomationUpdate; + path: { + /** + * Aid + */ + aid: number; + }; + query?: never; + url: "/api/v1/automations/{aid}"; +}; + +export type UpdateAutomationErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type UpdateAutomationError = UpdateAutomationErrors[keyof UpdateAutomationErrors]; + +export type UpdateAutomationResponses = { + /** + * Successful Response + */ + 200: AutomationSaved; +}; + +export type UpdateAutomationResponse = UpdateAutomationResponses[keyof UpdateAutomationResponses]; + +export type EnableAutomationData = { + body: AutomationSwitch; + path: { + /** + * Aid + */ + aid: number; + }; + query?: never; + url: "/api/v1/automations/{aid}/enable"; +}; + +export type EnableAutomationErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type EnableAutomationError = EnableAutomationErrors[keyof EnableAutomationErrors]; + +export type EnableAutomationResponses = { + /** + * Successful Response + */ + 200: Ok; +}; + +export type EnableAutomationResponse = EnableAutomationResponses[keyof EnableAutomationResponses]; + +export type RestoreAutomationData = { + body?: never; + path: { + /** + * Aid + */ + aid: number; + }; + query?: never; + url: "/api/v1/automations/{aid}/restore"; +}; + +export type RestoreAutomationErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type RestoreAutomationError = RestoreAutomationErrors[keyof RestoreAutomationErrors]; + +export type RestoreAutomationResponses = { + /** + * Successful Response + */ + 200: Ok; +}; + +export type RestoreAutomationResponse = RestoreAutomationResponses[keyof RestoreAutomationResponses]; + +export type SetPolicyData = { + body: AutomationPolicy; + path: { + /** + * Aid + */ + aid: number; + }; + query?: never; + url: "/api/v1/automations/{aid}/policy"; +}; + +export type SetPolicyErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type SetPolicyError = SetPolicyErrors[keyof SetPolicyErrors]; + +export type SetPolicyResponses = { + /** + * Response Automations-Set Policy + * + * Successful Response + */ + 200: { + [key: string]: string; + }; +}; + +export type SetPolicyResponse = SetPolicyResponses[keyof SetPolicyResponses]; + export type RemoveBudgetData = { body?: never; path?: never; diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 0a6d6d491..40f40b3da 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -5289,56 +5289,62 @@ } } }, - "/api/v1/budgets": { + "/api/v1/automations": { "get": { "tags": [ - "budgets" + "automations" + ], + "summary": "List Automations", + "description": "Your automations: every one for an admin, else those that work only in namespaces you can edit. `removed`\nlists the deleted ones instead, to restore.", + "operationId": "list_automations", + "parameters": [ + { + "name": "removed", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "default": false, + "title": "Removed" + } + } ], - "summary": "List Budgets", - "description": "Every budget, with where it stands now.", - "operationId": "list_budgets", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/BudgetStatus" - }, - "title": "Response Budgets-List Budgets" + "$ref": "#/components/schemas/AutomationCatalog" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" } } } } } }, - "put": { + "post": { "tags": [ - "budgets" - ], - "summary": "Set Budget", - "operationId": "set_budget", - "parameters": [ - { - "name": "resource", - "in": "query", - "required": true, - "schema": { - "type": "string", - "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:", - "title": "Resource" - }, - "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:" - } + "automations" ], + "summary": "Create Automation", + "description": "A new automation that acts for you. Its Then is a graph (saved as a workflow of scope event) or a saved\nworkflow; its namespaces default to each one you can edit. Nodes ask first unless you let one run on its own\n(POST /automations/{id}/policy).", + "operationId": "create_automation", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/BudgetSet" + "$ref": "#/components/schemas/AutomationCreate" } } } @@ -5349,7 +5355,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/BudgetStatus" + "$ref": "#/components/schemas/AutomationSaved" } } } @@ -5365,24 +5371,50 @@ } } } - }, - "delete": { + } + }, + "/api/v1/automations/actions": { + "get": { "tags": [ - "budgets" + "automations" ], - "summary": "Remove Budget", - "operationId": "remove_budget", + "summary": "List Actions", + "description": "What an action node can do: each action's params (a JSON Schema), what it reaches (its effect) and what it\ngives back.", + "operationId": "list_actions", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/ActionInfo" + }, + "type": "array", + "title": "Response Automations-List Actions" + } + } + } + } + } + } + }, + "/api/v1/automations/{aid}": { + "get": { + "tags": [ + "automations" + ], + "summary": "Get Automation", + "operationId": "get_automation", "parameters": [ { - "name": "resource", - "in": "query", + "name": "aid", + "in": "path", "required": true, "schema": { - "type": "string", - "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:", - "title": "Resource" - }, - "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:" + "type": "integer", + "title": "Aid" + } } ], "responses": { @@ -5391,7 +5423,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Ok" + "$ref": "#/components/schemas/Automation" } } } @@ -5407,78 +5439,42 @@ } } } - } - }, - "/api/v1/budgets/meter": { - "get": { + }, + "patch": { "tags": [ - "budgets" + "automations" ], - "summary": "Budget Meter", - "description": "What a namespace (or all of Lens) spent this day, week or month, against its budget when it has one: the top\nbar's meter, and with `detail` the costs page. Anyone who can read a namespace sees its meter; admins see all of\nLens's.", - "operationId": "budget_meter", + "summary": "Update Automation", + "description": "Change what is sent: a new graph is saved as a new version of its workflow; `if: null` drops its If,\n`version: null` follows the published version.", + "operationId": "update_automation", "parameters": [ { - "name": "ns", - "in": "query", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "a namespace; none for all of Lens (admins)", - "title": "Ns" - }, - "description": "a namespace; none for all of Lens (admins)" - }, - { - "name": "period", - "in": "query", - "required": false, - "schema": { - "anyOf": [ - { - "enum": [ - "day", - "week", - "month" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "description": "none: the budget's own period, else month", - "title": "Period" - }, - "description": "none: the budget's own period, else month" - }, - { - "name": "detail", - "in": "query", - "required": false, + "name": "aid", + "in": "path", + "required": true, "schema": { - "type": "boolean", - "description": "also by day, by model and what cost most", - "default": false, - "title": "Detail" - }, - "description": "also by day, by model and what cost most" + "type": "integer", + "title": "Aid" + } } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AutomationUpdate" + } + } + } + }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/BudgetMeter" + "$ref": "#/components/schemas/AutomationSaved" } } } @@ -5494,27 +5490,23 @@ } } } - } - }, - "/api/v1/budgets/status": { - "get": { + }, + "delete": { "tags": [ - "budgets" + "automations" ], - "summary": "Budget Status", - "description": "Where a resource's budget stands, and what its next run will likely cost (also without a budget).", - "operationId": "budget_status", + "summary": "Delete Automation", + "description": "Delete it: switched off and hidden; POST /automations/{id}/restore undoes it.", + "operationId": "delete_automation", "parameters": [ { - "name": "resource", - "in": "query", + "name": "aid", + "in": "path", "required": true, "schema": { - "type": "string", - "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:", - "title": "Resource" - }, - "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:" + "type": "integer", + "title": "Aid" + } } ], "responses": { @@ -5523,7 +5515,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/BudgetStatus" + "$ref": "#/components/schemas/Ok" } } } @@ -5541,20 +5533,52 @@ } } }, - "/api/v1/admin/fedora": { - "get": { + "/api/v1/automations/{aid}/enable": { + "post": { "tags": [ - "fedora" + "automations" ], - "summary": "Get Fedora Status", - "operationId": "get_fedora_status", + "summary": "Enable Automation", + "description": "Switch it on (it reacts to what happens from now on, never to what happened while it was off) or off.", + "operationId": "enable_automation", + "parameters": [ + { + "name": "aid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Aid" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AutomationSwitch" + } + } + } + }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FedoraStatus" + "$ref": "#/components/schemas/Ok" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" } } } @@ -5562,75 +5586,32 @@ } } }, - "/api/v1/admin/fedora/sync": { + "/api/v1/automations/{aid}/restore": { "post": { "tags": [ - "fedora" + "automations" + ], + "summary": "Restore Automation", + "description": "Undo a delete: it comes back switched off.", + "operationId": "restore_automation", + "parameters": [ + { + "name": "aid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Aid" + } + } ], - "summary": "Sync Fedora", - "description": "Compare everything with Fedora now and send what differs (the background sync does this every fedora.full_hours).", - "operationId": "sync_fedora", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FedoraSyncResult" - } - } - } - } - } - } - }, - "/api/v1/setup": { - "get": { - "tags": [ - "setup" - ], - "summary": "Get Setup", - "description": "What is set already, and which fields .env or archive.yaml locks.", - "operationId": "get_setup", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetupView" - } - } - } - } - } - } - }, - "/api/v1/setup/namespace": { - "post": { - "tags": [ - "setup" - ], - "summary": "Save Namespace", - "description": "Create the first namespace (or set the graph mode of one that exists).", - "operationId": "save_namespace", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetupNamespace" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetupSaved" + "$ref": "#/components/schemas/Ok" } } } @@ -5648,23 +5629,34 @@ } } }, - "/api/v1/setup/llm": { - "put": { + "/api/v1/automations/{aid}/policy": { + "post": { "tags": [ - "setup" + "automations" + ], + "summary": "Set Policy", + "description": "Whether an action node asks you first (ask) or runs on its own (auto). Only you, signed in to the web app,\nlet a node run on its own: never an API key, an app or an agent.", + "operationId": "set_policy", + "parameters": [ + { + "name": "aid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Aid" + } + } ], - "summary": "Save Llm", - "description": "The model provider: an OpenAI-compatible server's address, the model, and its key (empty: unchanged).", - "operationId": "save_llm", "requestBody": { + "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SetupLlm" + "$ref": "#/components/schemas/AutomationPolicy" } } - }, - "required": true + } }, "responses": { "200": { @@ -5672,7 +5664,11 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SetupSaved" + "type": "object", + "additionalProperties": { + "type": "string" + }, + "title": "Response Automations-Set Policy" } } } @@ -5690,117 +5686,59 @@ } } }, - "/api/v1/setup/llm/detect": { + "/api/v1/budgets": { "get": { "tags": [ - "setup" + "budgets" ], - "summary": "Detect Llm", - "description": "Model servers running on this machine or the Docker host (Ollama, LM Studio, llama.cpp, vLLM, LocalAI), with\ntheir models, so the wizard can offer one instead of asking for an address.", - "operationId": "detect_llm", + "summary": "List Budgets", + "description": "Every budget, with where it stands now.", + "operationId": "list_budgets", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "items": { - "$ref": "#/components/schemas/LocalModelServer" - }, "type": "array", - "title": "Response Setup-Detect Llm" - } - } - } - } - } - } - }, - "/api/v1/setup/llm/providers": { - "get": { - "tags": [ - "setup" - ], - "summary": "Llm Providers", - "description": "Cloud providers with an OpenAI-compatible API (OpenAI, Anthropic, Gemini, ...), each with its address and a\nmodel, so picking one leaves only the API key to paste.", - "operationId": "llm_providers", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { "items": { - "$ref": "#/components/schemas/CloudModelProvider" + "$ref": "#/components/schemas/BudgetStatus" }, - "type": "array", - "title": "Response Setup-Llm Providers" + "title": "Response Budgets-List Budgets" } } } } } - } - }, - "/api/v1/setup/storage": { + }, "put": { "tags": [ - "setup" + "budgets" ], - "summary": "Save Storage", - "description": "The upload limit, and optionally a folder on this machine (inside sources.local_roots) to watch.", - "operationId": "save_storage", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetupStorage" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetupSaved" - } - } - } - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - } + "summary": "Set Budget", + "operationId": "set_budget", + "parameters": [ + { + "name": "resource", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:", + "title": "Resource" + }, + "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:" } - } - } - }, - "/api/v1/setup/telemetry": { - "put": { - "tags": [ - "setup" ], - "summary": "Save Telemetry", - "description": "Opt in to telemetry: traces and metrics sent only to this endpoint (an OTLP collector), and usage statistics\nto your own Google Analytics property when `analytics` is true. Each is off unless chosen.", - "operationId": "save_telemetry", "requestBody": { + "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SetupTelemetry" + "$ref": "#/components/schemas/BudgetSet" } } - }, - "required": true + } }, "responses": { "200": { @@ -5808,7 +5746,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SetupSaved" + "$ref": "#/components/schemas/BudgetStatus" } } } @@ -5824,33 +5762,33 @@ } } } - } - }, - "/api/v1/setup/budget": { - "put": { + }, + "delete": { "tags": [ - "setup" + "budgets" + ], + "summary": "Remove Budget", + "operationId": "remove_budget", + "parameters": [ + { + "name": "resource", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:", + "title": "Resource" + }, + "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:" + } ], - "summary": "Save Budget", - "description": "The overall AI budget: a soft limit that warns and a hard limit where runs wait and paid model calls stop\n(docs/budgets.md#one-budget-for-everything), with the chat model's price so its spending is counted. No hard\nlimit: no budget.", - "operationId": "save_budget", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetupBudget" - } - } - }, - "required": true - }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SetupSaved" + "$ref": "#/components/schemas/Ok" } } } @@ -5868,32 +5806,77 @@ } } }, - "/api/v1/setup/oauth": { - "put": { + "/api/v1/budgets/meter": { + "get": { "tags": [ - "setup" + "budgets" ], - "summary": "Save Oauth", - "description": "Let apps and AI assistants (MCP clients such as Claude or Cursor) sign people in with their Lens account, or\nnot, and how long their tokens last (docs/authentication.md#oauth). On unless turned off.", - "operationId": "save_oauth", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetupOAuth" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetupSaved" - } + "summary": "Budget Meter", + "description": "What a namespace (or all of Lens) spent this day, week or month, against its budget when it has one: the top\nbar's meter, and with `detail` the costs page. Anyone who can read a namespace sees its meter; admins see all of\nLens's.", + "operationId": "budget_meter", + "parameters": [ + { + "name": "ns", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "a namespace; none for all of Lens (admins)", + "title": "Ns" + }, + "description": "a namespace; none for all of Lens (admins)" + }, + { + "name": "period", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "enum": [ + "day", + "week", + "month" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "description": "none: the budget's own period, else month", + "title": "Period" + }, + "description": "none: the budget's own period, else month" + }, + { + "name": "detail", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "description": "also by day, by model and what cost most", + "default": false, + "title": "Detail" + }, + "description": "also by day, by model and what cost most" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BudgetMeter" + } } } }, @@ -5910,31 +5893,34 @@ } } }, - "/api/v1/setup/finish": { - "post": { + "/api/v1/budgets/status": { + "get": { "tags": [ - "setup" + "budgets" + ], + "summary": "Budget Status", + "description": "Where a resource's budget stands, and what its next run will likely cost (also without a budget).", + "operationId": "budget_status", + "parameters": [ + { + "name": "resource", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:", + "title": "Resource" + }, + "description": "all (everything Lens spends), routine:, pipeline:, workflow: or space:" + } ], - "summary": "Finish", - "description": "Finish (or skip) the wizard; the web app stops showing it. Everything stays changeable in Settings. With no\nnamespace yet, the default one is made (saved: [\"namespace\"]).", - "operationId": "finish", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SetupFinish" - } - } - }, - "required": true - }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SetupSaved" + "$ref": "#/components/schemas/BudgetStatus" } } } @@ -5952,42 +5938,84 @@ } } }, - "/api/v1/namespaces": { + "/api/v1/admin/fedora": { "get": { "tags": [ - "namespaces" + "fedora" ], - "summary": "List Namespaces", - "description": "The namespaces you have a role in, with their counts, and those you see only some collections of (`partial`,\nno `role`): counted over those collections, without the namespace-wide people and word cloud.", - "operationId": "list_namespaces", + "summary": "Get Fedora Status", + "operationId": "get_fedora_status", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "items": { - "$ref": "#/components/schemas/Namespace" - }, - "type": "array", - "title": "Response Namespaces-List Namespaces" + "$ref": "#/components/schemas/FedoraStatus" } } } } } - }, + } + }, + "/api/v1/admin/fedora/sync": { "post": { "tags": [ - "namespaces" + "fedora" ], - "summary": "Create Namespace", - "operationId": "create_namespace", + "summary": "Sync Fedora", + "description": "Compare everything with Fedora now and send what differs (the background sync does this every fedora.full_hours).", + "operationId": "sync_fedora", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FedoraSyncResult" + } + } + } + } + } + } + }, + "/api/v1/setup": { + "get": { + "tags": [ + "setup" + ], + "summary": "Get Setup", + "description": "What is set already, and which fields .env or archive.yaml locks.", + "operationId": "get_setup", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetupView" + } + } + } + } + } + } + }, + "/api/v1/setup/namespace": { + "post": { + "tags": [ + "setup" + ], + "summary": "Save Namespace", + "description": "Create the first namespace (or set the graph mode of one that exists).", + "operationId": "save_namespace", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceCreate" + "$ref": "#/components/schemas/SetupNamespace" } } }, @@ -5999,7 +6027,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Created" + "$ref": "#/components/schemas/SetupSaved" } } } @@ -6017,34 +6045,23 @@ } } }, - "/api/v1/namespaces/{name}": { - "patch": { + "/api/v1/setup/llm": { + "put": { "tags": [ - "namespaces" - ], - "summary": "Update Namespace", - "description": "Owners: the graph mode (shared or isolated), the default pipeline (null for the built-in one) and a pipeline per\ncontent type.", - "operationId": "update_namespace", - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "schema": { - "type": "string", - "title": "Name" - } - } + "setup" ], + "summary": "Save Llm", + "description": "The model provider: an OpenAI-compatible server's address, the model, and its key (empty: unchanged).", + "operationId": "save_llm", "requestBody": { - "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceUpdate" + "$ref": "#/components/schemas/SetupLlm" } } - } + }, + "required": true }, "responses": { "200": { @@ -6052,7 +6069,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Ok" + "$ref": "#/components/schemas/SetupSaved" } } } @@ -6070,75 +6087,75 @@ } } }, - "/api/v1/namespaces/{name}/nsfw": { + "/api/v1/setup/llm/detect": { "get": { "tags": [ - "namespaces" - ], - "summary": "Get Namespace Nsfw", - "description": "NSFW classification here (docs/nsfw.md): whether it's on, the threshold and how flagged resources show, what the\nnamespace chose for itself and the archive's settings, and how many resources are classified and flagged.", - "operationId": "get_namespace_nsfw", - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "schema": { - "type": "string", - "title": "Name" - } - } + "setup" ], + "summary": "Detect Llm", + "description": "Model servers running on this machine or the Docker host (Ollama, LM Studio, llama.cpp, vLLM, LocalAI), with\ntheir models, so the wizard can offer one instead of asking for an address.", + "operationId": "detect_llm", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceNsfw" - } - } - } - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" + "items": { + "$ref": "#/components/schemas/LocalModelServer" + }, + "type": "array", + "title": "Response Setup-Detect Llm" } } } } } - }, - "put": { + } + }, + "/api/v1/setup/llm/providers": { + "get": { "tags": [ - "namespaces" + "setup" ], - "summary": "Update Namespace Nsfw", - "description": "Owners: turn NSFW classification on or off for this namespace, or give it its own threshold or display; null\nfollows the archive's setting again. A new threshold re-flags what's classified at once. `classify` also queues the\nnsfw step for its videos, documents and images not classified yet. Audited as `namespace.nsfw`.", - "operationId": "update_namespace_nsfw", - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "schema": { - "type": "string", - "title": "Name" + "summary": "Llm Providers", + "description": "Cloud providers with an OpenAI-compatible API (OpenAI, Anthropic, Gemini, ...), each with its address and a\nmodel, so picking one leaves only the API key to paste.", + "operationId": "llm_providers", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/CloudModelProvider" + }, + "type": "array", + "title": "Response Setup-Llm Providers" + } + } } } + } + } + }, + "/api/v1/setup/storage": { + "put": { + "tags": [ + "setup" ], + "summary": "Save Storage", + "description": "The upload limit, and optionally a folder on this machine (inside sources.local_roots) to watch.", + "operationId": "save_storage", "requestBody": { - "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceNsfwUpdate" + "$ref": "#/components/schemas/SetupStorage" } } - } + }, + "required": true }, "responses": { "200": { @@ -6146,7 +6163,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceNsfw" + "$ref": "#/components/schemas/SetupSaved" } } } @@ -6164,32 +6181,31 @@ } } }, - "/api/v1/namespaces/{name}/nsfw/classify": { - "post": { + "/api/v1/setup/telemetry": { + "put": { "tags": [ - "namespaces" + "setup" ], - "summary": "Classify Namespace Nsfw", - "description": "Editors: queue the nsfw step for the namespace's videos, documents and images not classified yet (those added\nwhile it's on are classified by their pipeline). 409 where classification is off.", - "operationId": "classify_namespace_nsfw", - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "schema": { - "type": "string", - "title": "Name" + "summary": "Save Telemetry", + "description": "Opt in to telemetry: traces and metrics sent only to this endpoint (an OTLP collector), and usage statistics\nto your own Google Analytics property when `analytics` is true. Each is off unless chosen.", + "operationId": "save_telemetry", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetupTelemetry" + } } - } - ], + }, + "required": true + }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/JobsQueued" + "$ref": "#/components/schemas/SetupSaved" } } } @@ -6207,30 +6223,33 @@ } } }, - "/api/v1/namespaces/{name}/wordcloud.svg": { - "get": { + "/api/v1/setup/budget": { + "put": { "tags": [ - "namespaces" + "setup" ], - "summary": "Get Namespace Wordcloud", - "description": "The namespace's word cloud. Accepts a bearer token or the signed link from the namespace list.", - "operationId": "get_namespace_wordcloud", - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "schema": { - "type": "string", - "title": "Name" + "summary": "Save Budget", + "description": "The overall AI budget: a soft limit that warns and a hard limit where runs wait and paid model calls stop\n(docs/budgets.md#one-budget-for-everything), with the chat model's price so its spending is counted. No hard\nlimit: no budget.", + "operationId": "save_budget", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetupBudget" + } } - } - ], + }, + "required": true + }, "responses": { "200": { "description": "Successful Response", "content": { - "image/svg+xml": {} + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetupSaved" + } + } } }, "422": { @@ -6246,84 +6265,31 @@ } } }, - "/api/v1/namespaces/{name}/stats": { - "get": { + "/api/v1/setup/oauth": { + "put": { "tags": [ - "namespaces" + "setup" ], - "summary": "Get Namespace Stats", - "description": "The namespace's numbers for the assets made in a range of days (the Reports overview): how many and how long,\nwho was heard and for how long, and the same per month. Without a range, every asset.", - "operationId": "get_namespace_stats", - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "schema": { - "type": "string", - "title": "Name" + "summary": "Save Oauth", + "description": "Let apps and AI assistants (MCP clients such as Claude or Cursor) sign people in with their Lens account, or\nnot, and how long their tokens last (docs/authentication.md#oauth). On unless turned off.", + "operationId": "save_oauth", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetupOAuth" + } } }, - { - "name": "from", - "in": "query", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string", - "format": "date" - }, - { - "type": "null" - } - ], - "description": "dated on or after this day", - "title": "From" - }, - "description": "dated on or after this day" - }, - { - "name": "to", - "in": "query", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string", - "format": "date" - }, - { - "type": "null" - } - ], - "description": "dated on or before this day", - "title": "To" - }, - "description": "dated on or before this day" - }, - { - "name": "top", - "in": "query", - "required": false, - "schema": { - "type": "integer", - "maximum": 50, - "minimum": 1, - "description": "how many people in `top_speakers`", - "default": 5, - "title": "Top" - }, - "description": "how many people in `top_speakers`" - } - ], + "required": true + }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceStats" + "$ref": "#/components/schemas/SetupSaved" } } } @@ -6341,32 +6307,31 @@ } } }, - "/api/v1/namespaces/{name}/ip-groups": { - "get": { + "/api/v1/setup/finish": { + "post": { "tags": [ - "namespaces" + "setup" ], - "summary": "List Ip Groups", - "description": "The namespace's IP groups (owners), and your address as the server sees it, to check the ranges against.", - "operationId": "list_ip_groups", - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "schema": { - "type": "string", - "title": "Name" + "summary": "Finish", + "description": "Finish (or skip) the wizard; the web app stops showing it. Everything stays changeable in Settings. With no\nnamespace yet, the default one is made (saved: [\"namespace\"]).", + "operationId": "finish", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetupFinish" + } } - } - ], + }, + "required": true + }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IpGroups" + "$ref": "#/components/schemas/SetupSaved" } } } @@ -6382,34 +6347,48 @@ } } } + } + }, + "/api/v1/namespaces": { + "get": { + "tags": [ + "namespaces" + ], + "summary": "List Namespaces", + "description": "The namespaces you have a role in, with their counts, and those you see only some collections of (`partial`,\nno `role`): counted over those collections, without the namespace-wide people and word cloud.", + "operationId": "list_namespaces", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/Namespace" + }, + "type": "array", + "title": "Response Namespaces-List Namespaces" + } + } + } + } + } }, "post": { "tags": [ "namespaces" ], - "summary": "Create Ip Group", - "description": "Add an IP group (owners): visitors from its addresses see all of every asset in the namespace\n(everything), or of the assets chosen on each. Answers with all of the namespace's groups.", - "operationId": "create_ip_group", - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "schema": { - "type": "string", - "title": "Name" - } - } - ], + "summary": "Create Namespace", + "operationId": "create_namespace", "requestBody": { - "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IpGroupCreate" + "$ref": "#/components/schemas/NamespaceCreate" } } - } + }, + "required": true }, "responses": { "200": { @@ -6417,7 +6396,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IpGroups" + "$ref": "#/components/schemas/Created" } } } @@ -6435,14 +6414,14 @@ } } }, - "/api/v1/namespaces/{name}/ip-groups/{gid}": { + "/api/v1/namespaces/{name}": { "patch": { "tags": [ "namespaces" ], - "summary": "Update Ip Group", - "description": "Rename an IP group, change its ranges or what it opens (owners). Choosing assets again after opening\neverything brings back the ones chosen before.", - "operationId": "update_ip_group", + "summary": "Update Namespace", + "description": "Owners: the graph mode (shared or isolated), the default pipeline (null for the built-in one) and a pipeline per\ncontent type.", + "operationId": "update_namespace", "parameters": [ { "name": "name", @@ -6452,15 +6431,6 @@ "type": "string", "title": "Name" } - }, - { - "name": "gid", - "in": "path", - "required": true, - "schema": { - "type": "integer", - "title": "Gid" - } } ], "requestBody": { @@ -6468,7 +6438,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IpGroupUpdate" + "$ref": "#/components/schemas/NamespaceUpdate" } } } @@ -6479,7 +6449,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IpGroups" + "$ref": "#/components/schemas/Ok" } } } @@ -6495,14 +6465,16 @@ } } } - }, - "delete": { + } + }, + "/api/v1/namespaces/{name}/nsfw": { + "get": { "tags": [ "namespaces" ], - "summary": "Delete Ip Group", - "description": "Delete an IP group (owners): its visitors lose what it opened. Answers with the groups left.", - "operationId": "delete_ip_group", + "summary": "Get Namespace Nsfw", + "description": "NSFW classification here (docs/nsfw.md): whether it's on, the threshold and how flagged resources show, what the\nnamespace chose for itself and the archive's settings, and how many resources are classified and flagged.", + "operationId": "get_namespace_nsfw", "parameters": [ { "name": "name", @@ -6512,24 +6484,66 @@ "type": "string", "title": "Name" } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NamespaceNsfw" + } + } + } }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "put": { + "tags": [ + "namespaces" + ], + "summary": "Update Namespace Nsfw", + "description": "Owners: turn NSFW classification on or off for this namespace, or give it its own threshold or display; null\nfollows the archive's setting again. A new threshold re-flags what's classified at once. `classify` also queues the\nnsfw step for its videos, documents and images not classified yet. Audited as `namespace.nsfw`.", + "operationId": "update_namespace_nsfw", + "parameters": [ { - "name": "gid", + "name": "name", "in": "path", "required": true, "schema": { - "type": "integer", - "title": "Gid" + "type": "string", + "title": "Name" } } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NamespaceNsfwUpdate" + } + } + } + }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IpGroups" + "$ref": "#/components/schemas/NamespaceNsfw" } } } @@ -6547,14 +6561,14 @@ } } }, - "/api/v1/namespaces/{name}/assistant": { - "get": { + "/api/v1/namespaces/{name}/nsfw/classify": { + "post": { "tags": [ "namespaces" ], - "summary": "Get Namespace Assistant", - "description": "The namespace's assistant: whether it's on, its name and instructions, and how much it remembers.", - "operationId": "get_namespace_assistant", + "summary": "Classify Namespace Nsfw", + "description": "Editors: queue the nsfw step for the namespace's videos, documents and images not classified yet (those added\nwhile it's on are classified by their pipeline). 409 where classification is off.", + "operationId": "classify_namespace_nsfw", "parameters": [ { "name": "name", @@ -6572,7 +6586,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceAssistant" + "$ref": "#/components/schemas/JobsQueued" } } } @@ -6588,14 +6602,16 @@ } } } - }, - "patch": { + } + }, + "/api/v1/namespaces/{name}/wordcloud.svg": { + "get": { "tags": [ "namespaces" ], - "summary": "Update Namespace Assistant", - "description": "Owners: turn the assistant on or off, name it, or change its instructions.", - "operationId": "update_namespace_assistant", + "summary": "Get Namespace Wordcloud", + "description": "The namespace's word cloud. Accepts a bearer token or the signed link from the namespace list.", + "operationId": "get_namespace_wordcloud", "parameters": [ { "name": "name", @@ -6607,25 +6623,11 @@ } } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/NamespaceAssistantUpdate" - } - } - } - }, "responses": { "200": { "description": "Successful Response", "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/NamespaceAssistant" - } - } + "image/svg+xml": {} } }, "422": { @@ -6641,14 +6643,14 @@ } } }, - "/api/v1/namespaces/{name}/assistant/memories": { + "/api/v1/namespaces/{name}/stats": { "get": { "tags": [ "namespaces" ], - "summary": "List Assistant Memories", - "description": "What the namespace's assistant remembers: pinned first, then newest first (or by `q`).", - "operationId": "list_assistant_memories", + "summary": "Get Namespace Stats", + "description": "The namespace's numbers for the assets made in a range of days (the Reports overview): how many and how long,\nwho was heard and for how long, and the same per month. Without a range, every asset.", + "operationId": "get_namespace_stats", "parameters": [ { "name": "name", @@ -6660,22 +6662,56 @@ } }, { - "name": "q", + "name": "from", "in": "query", "required": false, "schema": { "anyOf": [ { - "type": "string" + "type": "string", + "format": "date" }, { "type": "null" } ], - "description": "only memories with these words, best first", - "title": "Q" + "description": "dated on or after this day", + "title": "From" }, - "description": "only memories with these words, best first" + "description": "dated on or after this day" + }, + { + "name": "to", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string", + "format": "date" + }, + { + "type": "null" + } + ], + "description": "dated on or before this day", + "title": "To" + }, + "description": "dated on or before this day" + }, + { + "name": "top", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 50, + "minimum": 1, + "description": "how many people in `top_speakers`", + "default": 5, + "title": "Top" + }, + "description": "how many people in `top_speakers`" } ], "responses": { @@ -6684,11 +6720,7 @@ "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AssistantMemory" - }, - "title": "Response Namespaces-List Assistant Memories" + "$ref": "#/components/schemas/NamespaceStats" } } } @@ -6704,14 +6736,16 @@ } } } - }, - "post": { + } + }, + "/api/v1/namespaces/{name}/ip-groups": { + "get": { "tags": [ "namespaces" ], - "summary": "Add Assistant Memory", - "description": "Editors: tell the assistant something to remember.", - "operationId": "add_assistant_memory", + "summary": "List Ip Groups", + "description": "The namespace's IP groups (owners), and your address as the server sees it, to check the ranges against.", + "operationId": "list_ip_groups", "parameters": [ { "name": "name", @@ -6723,23 +6757,13 @@ } } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/AssistantMemoryCreate" - } - } - } - }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Created" + "$ref": "#/components/schemas/IpGroups" } } } @@ -6756,13 +6780,13 @@ } } }, - "delete": { + "post": { "tags": [ "namespaces" ], - "summary": "Forget All Assistant Memories", - "description": "Owners: forget everything the assistant remembers.", - "operationId": "forget_all_assistant_memories", + "summary": "Create Ip Group", + "description": "Add an IP group (owners): visitors from its addresses see all of every asset in the namespace\n(everything), or of the assets chosen on each. Answers with all of the namespace's groups.", + "operationId": "create_ip_group", "parameters": [ { "name": "name", @@ -6774,13 +6798,23 @@ } } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IpGroupCreate" + } + } + } + }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Ok" + "$ref": "#/components/schemas/IpGroups" } } } @@ -6798,14 +6832,14 @@ } } }, - "/api/v1/namespaces/{name}/assistant/memories/{mid}": { + "/api/v1/namespaces/{name}/ip-groups/{gid}": { "patch": { "tags": [ "namespaces" ], - "summary": "Update Assistant Memory", - "description": "Editors: correct a memory, or pin it so it's read with every question.", - "operationId": "update_assistant_memory", + "summary": "Update Ip Group", + "description": "Rename an IP group, change its ranges or what it opens (owners). Choosing assets again after opening\neverything brings back the ones chosen before.", + "operationId": "update_ip_group", "parameters": [ { "name": "name", @@ -6817,12 +6851,12 @@ } }, { - "name": "mid", + "name": "gid", "in": "path", "required": true, "schema": { "type": "integer", - "title": "Mid" + "title": "Gid" } } ], @@ -6831,7 +6865,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AssistantMemoryUpdate" + "$ref": "#/components/schemas/IpGroupUpdate" } } } @@ -6842,7 +6876,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AssistantMemory" + "$ref": "#/components/schemas/IpGroups" } } } @@ -6863,9 +6897,9 @@ "tags": [ "namespaces" ], - "summary": "Forget Assistant Memory", - "description": "Editors: forget one memory.", - "operationId": "forget_assistant_memory", + "summary": "Delete Ip Group", + "description": "Delete an IP group (owners): its visitors lose what it opened. Answers with the groups left.", + "operationId": "delete_ip_group", "parameters": [ { "name": "name", @@ -6877,12 +6911,12 @@ } }, { - "name": "mid", + "name": "gid", "in": "path", "required": true, "schema": { "type": "integer", - "title": "Mid" + "title": "Gid" } } ], @@ -6892,7 +6926,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Ok" + "$ref": "#/components/schemas/IpGroups" } } } @@ -6910,14 +6944,14 @@ } } }, - "/api/v1/namespaces/{name}/integrations": { + "/api/v1/namespaces/{name}/assistant": { "get": { "tags": [ "namespaces" ], - "summary": "Get Namespace Integrations", - "description": "Whether the namespace's own MCP server and chat completions are on, their addresses, and the tools offered.", - "operationId": "get_namespace_integrations", + "summary": "Get Namespace Assistant", + "description": "The namespace's assistant: whether it's on, its name and instructions, and how much it remembers.", + "operationId": "get_namespace_assistant", "parameters": [ { "name": "name", @@ -6935,7 +6969,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceIntegrations" + "$ref": "#/components/schemas/NamespaceAssistant" } } } @@ -6956,9 +6990,9 @@ "tags": [ "namespaces" ], - "summary": "Update Namespace Integrations", - "description": "Owners: turn the namespace's own MCP server or chat completions on or off, or pick the read tools the model may\nuse in its chat completions. Off, each answers 403; apps keep their access to the rest of Lens as before.", - "operationId": "update_namespace_integrations", + "summary": "Update Namespace Assistant", + "description": "Owners: turn the assistant on or off, name it, or change its instructions.", + "operationId": "update_namespace_assistant", "parameters": [ { "name": "name", @@ -6975,7 +7009,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceIntegrationsUpdate" + "$ref": "#/components/schemas/NamespaceAssistantUpdate" } } } @@ -6986,7 +7020,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NamespaceIntegrations" + "$ref": "#/components/schemas/NamespaceAssistant" } } } @@ -7004,14 +7038,14 @@ } } }, - "/api/v1/namespaces/{name}/models": { + "/api/v1/namespaces/{name}/assistant/memories": { "get": { "tags": [ - "chat completions" + "namespaces" ], - "summary": "List Completion Models", - "description": "OpenAI's model list for the namespace's chat completions: lens (the configured model) and the models people may\npick in Lens's chat.", - "operationId": "list_completion_models", + "summary": "List Assistant Memories", + "description": "What the namespace's assistant remembers: pinned first, then newest first (or by `q`).", + "operationId": "list_assistant_memories", "parameters": [ { "name": "name", @@ -7021,6 +7055,24 @@ "type": "string", "title": "Name" } + }, + { + "name": "q", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "only memories with these words, best first", + "title": "Q" + }, + "description": "only memories with these words, best first" } ], "responses": { @@ -7029,29 +7081,15 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CompletionModels" + "type": "array", + "items": { + "$ref": "#/components/schemas/AssistantMemory" + }, + "title": "Response Namespaces-List Assistant Memories" } } } }, - "400": { - "description": "OpenAI's error shape: {error: {message, type, code}}" - }, - "401": { - "description": "no token, or one that doesn't open this namespace" - }, - "403": { - "description": "the namespace's chat completions are off" - }, - "404": { - "description": "no such namespace, or not one you can read" - }, - "429": { - "description": "a budget is used up" - }, - "502": { - "description": "the model server failed" - }, "422": { "description": "Validation Error", "content": { @@ -7063,16 +7101,14 @@ } } } - } - }, - "/api/v1/namespaces/{name}/chat/completions": { + }, "post": { "tags": [ - "chat completions" + "namespaces" ], - "summary": "Create Chat Completion", - "description": "OpenAI's chat completions, answered from this namespace alone: the last user message is the question, the\nmessages before it the conversation and system messages the app's instructions. The answer cites what it read as\n[n], with a Sources list after it, `citations` (the n-th link for [n]) and `lens.sources`. With `stream`, it comes\nas OpenAI's chunks (server-sent events) ending in `data: [DONE]`. Off until an owner of the namespace turns it on;\nread-only tokens are enough. 429 when the namespace's budget or Lens's overall one is used up.", - "operationId": "create_chat_completion", + "summary": "Add Assistant Memory", + "description": "Editors: tell the assistant something to remember.", + "operationId": "add_assistant_memory", "parameters": [ { "name": "name", @@ -7089,7 +7125,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ChatCompletionRequest" + "$ref": "#/components/schemas/AssistantMemoryCreate" } } } @@ -7100,29 +7136,11 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ChatCompletion" + "$ref": "#/components/schemas/Created" } } } }, - "400": { - "description": "OpenAI's error shape: {error: {message, type, code}}" - }, - "401": { - "description": "no token, or one that doesn't open this namespace" - }, - "403": { - "description": "the namespace's chat completions are off" - }, - "404": { - "description": "no such namespace, or not one you can read" - }, - "429": { - "description": "a budget is used up" - }, - "502": { - "description": "the model server failed" - }, "422": { "description": "Validation Error", "content": { @@ -7134,16 +7152,14 @@ } } } - } - }, - "/api/v1/namespaces/{name}/collections": { - "get": { + }, + "delete": { "tags": [ "namespaces" ], - "summary": "List Namespace Collections", - "description": "The namespace's collections, depth first and by name, each with its place in the tree, how many assets it\nholds (with and without the collections inside it), and what you may do with it. Someone who sees only some\ncollections of the namespace gets those, starting from the ones they were given.", - "operationId": "list_namespace_collections", + "summary": "Forget All Assistant Memories", + "description": "Owners: forget everything the assistant remembers.", + "operationId": "forget_all_assistant_memories", "parameters": [ { "name": "name", @@ -7161,11 +7177,7 @@ "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CollectionNode" - }, - "title": "Response Namespaces-List Namespace Collections" + "$ref": "#/components/schemas/Ok" } } } @@ -7181,14 +7193,16 @@ } } } - }, - "post": { + } + }, + "/api/v1/namespaces/{name}/assistant/memories/{mid}": { + "patch": { "tags": [ "namespaces" ], - "summary": "Create Namespace Collection", - "description": "Make a collection at the top of the namespace (its editors) or inside `parent` (them, or an admin of `parent`).\nIts name is unique among the collections next to it, ignoring case; collections go at most 8 deep. Audited as\n`collection.create`.", - "operationId": "create_namespace_collection", + "summary": "Update Assistant Memory", + "description": "Editors: correct a memory, or pin it so it's read with every question.", + "operationId": "update_assistant_memory", "parameters": [ { "name": "name", @@ -7198,6 +7212,15 @@ "type": "string", "title": "Name" } + }, + { + "name": "mid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Mid" + } } ], "requestBody": { @@ -7205,7 +7228,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CollectionNodeCreate" + "$ref": "#/components/schemas/AssistantMemoryUpdate" } } } @@ -7216,7 +7239,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CollectionNode" + "$ref": "#/components/schemas/AssistantMemory" } } } @@ -7232,15 +7255,14 @@ } } } - } - }, - "/api/v1/namespaces/{name}/collections/{cid}": { - "get": { + }, + "delete": { "tags": [ "namespaces" ], - "summary": "Get Namespace Collection", - "operationId": "get_namespace_collection", + "summary": "Forget Assistant Memory", + "description": "Editors: forget one memory.", + "operationId": "forget_assistant_memory", "parameters": [ { "name": "name", @@ -7252,12 +7274,12 @@ } }, { - "name": "cid", + "name": "mid", "in": "path", "required": true, "schema": { "type": "integer", - "title": "Cid" + "title": "Mid" } } ], @@ -7267,7 +7289,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CollectionNode" + "$ref": "#/components/schemas/Ok" } } } @@ -7283,14 +7305,16 @@ } } } - }, - "patch": { + } + }, + "/api/v1/namespaces/{name}/integrations": { + "get": { "tags": [ "namespaces" ], - "summary": "Update Namespace Collection", - "description": "Rename it, describe it, move it inside another collection of the namespace (`parent`; null: to the top) or make\nit the default. Editors of the namespace may do all of that; an admin of the collection all but moving it to the\ntop or making it the default, and only into a collection they're an admin of. The assets and collections\ninside it go with it. Audited as `collection.update`.", - "operationId": "update_namespace_collection", + "summary": "Get Namespace Integrations", + "description": "Whether the namespace's own MCP server and chat completions are on, their addresses, and the tools offered.", + "operationId": "get_namespace_integrations", "parameters": [ { "name": "name", @@ -7300,34 +7324,15 @@ "type": "string", "title": "Name" } - }, - { - "name": "cid", - "in": "path", - "required": true, - "schema": { - "type": "integer", - "title": "Cid" - } } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CollectionNodeUpdate" - } - } - } - }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CollectionNode" + "$ref": "#/components/schemas/NamespaceIntegrations" } } } @@ -7344,13 +7349,13 @@ } } }, - "delete": { + "patch": { "tags": [ "namespaces" ], - "summary": "Delete Namespace Collection", - "description": "Delete an empty collection (editors of the namespace, or an admin of it), with the roles given on it: 409 while\nit holds assets or collections, or is the namespace's default. Audited as `collection.delete`.", - "operationId": "delete_namespace_collection", + "summary": "Update Namespace Integrations", + "description": "Owners: turn the namespace's own MCP server or chat completions on or off, or pick the read tools the model may\nuse in its chat completions. Off, each answers 403; apps keep their access to the rest of Lens as before.", + "operationId": "update_namespace_integrations", "parameters": [ { "name": "name", @@ -7360,24 +7365,25 @@ "type": "string", "title": "Name" } - }, - { - "name": "cid", - "in": "path", - "required": true, - "schema": { - "type": "integer", - "title": "Cid" - } } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NamespaceIntegrationsUpdate" + } + } + } + }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Ok" + "$ref": "#/components/schemas/NamespaceIntegrations" } } } @@ -7395,16 +7401,16 @@ } } }, - "/api/v1/namespaces/{name}/collections/{cid}/members": { + "/api/v1/namespaces/{name}/models": { "get": { "tags": [ - "namespaces" + "chat completions" ], - "summary": "List Collection Members", - "description": "Who was given a role on the collection, then who has one through a collection it's inside (owners of the\nnamespace, and admins of the collection). People with a role in the namespace aren't listed: theirs holds in\nevery collection.", - "operationId": "list_collection_members", - "parameters": [ - { + "summary": "List Completion Models", + "description": "OpenAI's model list for the namespace's chat completions: lens (the configured model) and the models people may\npick in Lens's chat.", + "operationId": "list_completion_models", + "parameters": [ + { "name": "name", "in": "path", "required": true, @@ -7412,32 +7418,108 @@ "type": "string", "title": "Name" } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CompletionModels" + } + } + } + }, + "400": { + "description": "OpenAI's error shape: {error: {message, type, code}}" + }, + "401": { + "description": "no token, or one that doesn't open this namespace" + }, + "403": { + "description": "the namespace's chat completions are off" + }, + "404": { + "description": "no such namespace, or not one you can read" + }, + "429": { + "description": "a budget is used up" }, + "502": { + "description": "the model server failed" + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/namespaces/{name}/chat/completions": { + "post": { + "tags": [ + "chat completions" + ], + "summary": "Create Chat Completion", + "description": "OpenAI's chat completions, answered from this namespace alone: the last user message is the question, the\nmessages before it the conversation and system messages the app's instructions. The answer cites what it read as\n[n], with a Sources list after it, `citations` (the n-th link for [n]) and `lens.sources`. With `stream`, it comes\nas OpenAI's chunks (server-sent events) ending in `data: [DONE]`. Off until an owner of the namespace turns it on;\nread-only tokens are enough. 429 when the namespace's budget or Lens's overall one is used up.", + "operationId": "create_chat_completion", + "parameters": [ { - "name": "cid", + "name": "name", "in": "path", "required": true, "schema": { - "type": "integer", - "title": "Cid" + "type": "string", + "title": "Name" } } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatCompletionRequest" + } + } + } + }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CollectionMember" - }, - "title": "Response Namespaces-List Collection Members" + "$ref": "#/components/schemas/ChatCompletion" } } } }, + "400": { + "description": "OpenAI's error shape: {error: {message, type, code}}" + }, + "401": { + "description": "no token, or one that doesn't open this namespace" + }, + "403": { + "description": "the namespace's chat completions are off" + }, + "404": { + "description": "no such namespace, or not one you can read" + }, + "429": { + "description": "a budget is used up" + }, + "502": { + "description": "the model server failed" + }, "422": { "description": "Validation Error", "content": { @@ -7449,14 +7531,16 @@ } } } - }, - "put": { + } + }, + "/api/v1/namespaces/{name}/collections": { + "get": { "tags": [ "namespaces" ], - "summary": "Set Collection Member", - "description": "Give someone a role on the collection (and the collections inside it), change it, or (role null) take it away.\nThey needn't have a role in the namespace: then they see just this collection. Owners of the namespace and admins\nof the collection. Answers with the members; audited as `collection.member`.", - "operationId": "set_collection_member", + "summary": "List Namespace Collections", + "description": "The namespace's collections, depth first and by name, each with its place in the tree, how many assets it\nholds (with and without the collections inside it), and what you may do with it. Someone who sees only some\ncollections of the namespace gets those, starting from the ones they were given.", + "operationId": "list_namespace_collections", "parameters": [ { "name": "name", @@ -7466,14 +7550,50 @@ "type": "string", "title": "Name" } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CollectionNode" + }, + "title": "Response Namespaces-List Namespace Collections" + } + } + } }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "post": { + "tags": [ + "namespaces" + ], + "summary": "Create Namespace Collection", + "description": "Make a collection at the top of the namespace (its editors) or inside `parent` (them, or an admin of `parent`).\nIts name is unique among the collections next to it, ignoring case; collections go at most 8 deep. Audited as\n`collection.create`.", + "operationId": "create_namespace_collection", + "parameters": [ { - "name": "cid", + "name": "name", "in": "path", "required": true, "schema": { - "type": "integer", - "title": "Cid" + "type": "string", + "title": "Name" } } ], @@ -7482,7 +7602,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CollectionMemberSet" + "$ref": "#/components/schemas/CollectionNodeCreate" } } } @@ -7493,11 +7613,7 @@ "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CollectionMember" - }, - "title": "Response Namespaces-Set Collection Member" + "$ref": "#/components/schemas/CollectionNode" } } } @@ -7515,193 +7631,474 @@ } } }, - "/api/v1/resources": { + "/api/v1/namespaces/{name}/collections/{cid}": { "get": { "tags": [ - "resources" + "namespaces" ], - "summary": "List Recordings", - "description": "Assets you can read, newest first by default: those of the namespaces you have a role in, and of the\ncollections you were given a role on. Filters combine with AND; the ``X-Total-Count`` header says how many match in\nall, so pages can be counted. Each row has your `role` on it.", - "operationId": "list_recordings", + "summary": "Get Namespace Collection", + "operationId": "get_namespace_collection", "parameters": [ { - "name": "ns", - "in": "query", - "required": false, + "name": "name", + "in": "path", + "required": true, "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "one namespace (default: every namespace you can read)", - "title": "Ns" - }, - "description": "one namespace (default: every namespace you can read)" + "type": "string", + "title": "Name" + } }, { - "name": "q", - "in": "query", - "required": false, + "name": "cid", + "in": "path", + "required": true, "schema": { - "anyOf": [ - { - "type": "string", - "maxLength": 200 - }, - { - "type": "null" + "type": "integer", + "title": "Cid" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CollectionNode" } - ], - "description": "words that must all appear in the title, the namespace or a person's name", - "title": "Q" - }, - "description": "words that must all appear in the title, the namespace or a person's name" + } + } }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "patch": { + "tags": [ + "namespaces" + ], + "summary": "Update Namespace Collection", + "description": "Rename it, describe it, move it inside another collection of the namespace (`parent`; null: to the top) or make\nit the default. Editors of the namespace may do all of that; an admin of the collection all but moving it to the\ntop or making it the default, and only into a collection they're an admin of. The assets and collections\ninside it go with it. Audited as `collection.update`.", + "operationId": "update_namespace_collection", + "parameters": [ { - "name": "status", - "in": "query", - "required": false, + "name": "name", + "in": "path", + "required": true, "schema": { - "anyOf": [ - { - "type": "array", - "items": { - "enum": [ - "new", - "transcribed", - "diarized", - "analyzed", - "error", - "processing", - "failed" - ], - "type": "string" - } - }, - { - "type": "null" - } - ], - "description": "asset statuses, or processing (a job is queued or running) and failed (the latest job failed); repeat for several (any of them matches)", - "title": "Status" - }, - "description": "asset statuses, or processing (a job is queued or running) and failed (the latest job failed); repeat for several (any of them matches)" + "type": "string", + "title": "Name" + } }, { - "name": "attention", - "in": "query", - "required": false, + "name": "cid", + "in": "path", + "required": true, "schema": { - "type": "boolean", - "description": "only assets that need attention: errored, latest job failed, or a person match to review", - "default": false, - "title": "Attention" - }, - "description": "only assets that need attention: errored, latest job failed, or a person match to review" + "type": "integer", + "title": "Cid" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CollectionNodeUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CollectionNode" + } + } + } }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "delete": { + "tags": [ + "namespaces" + ], + "summary": "Delete Namespace Collection", + "description": "Delete an empty collection (editors of the namespace, or an admin of it), with the roles given on it: 409 while\nit holds assets or collections, or is the namespace's default. Audited as `collection.delete`.", + "operationId": "delete_namespace_collection", + "parameters": [ { - "name": "processing", - "in": "query", - "required": false, + "name": "name", + "in": "path", + "required": true, "schema": { - "type": "boolean", - "description": "only assets with a job queued or running", - "default": false, - "title": "Processing" - }, - "description": "only assets with a job queued or running" + "type": "string", + "title": "Name" + } }, { - "name": "speaker", - "in": "query", - "required": false, + "name": "cid", + "in": "path", + "required": true, "schema": { - "anyOf": [ - { - "type": "array", - "items": { - "type": "integer" - } - }, - { - "type": "null" + "type": "integer", + "title": "Cid" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Ok" } - ], - "description": "person ids; repeat for several (any of them matches)", - "title": "Speaker" - }, - "description": "person ids; repeat for several (any of them matches)" + } + } }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/namespaces/{name}/collections/{cid}/members": { + "get": { + "tags": [ + "namespaces" + ], + "summary": "List Collection Members", + "description": "Who was given a role on the collection, then who has one through a collection it's inside (owners of the\nnamespace, and admins of the collection). People with a role in the namespace aren't listed: theirs holds in\nevery collection.", + "operationId": "list_collection_members", + "parameters": [ { - "name": "from", - "in": "query", - "required": false, + "name": "name", + "in": "path", + "required": true, "schema": { - "anyOf": [ - { - "type": "string", - "format": "date" - }, - { - "type": "null" - } - ], - "description": "recorded on or after this day", - "title": "From" - }, - "description": "recorded on or after this day" + "type": "string", + "title": "Name" + } }, { - "name": "to", - "in": "query", - "required": false, + "name": "cid", + "in": "path", + "required": true, "schema": { - "anyOf": [ - { - "type": "string", - "format": "date" - }, - { - "type": "null" + "type": "integer", + "title": "Cid" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CollectionMember" + }, + "title": "Response Namespaces-List Collection Members" } - ], - "description": "recorded on or before this day", - "title": "To" - }, - "description": "recorded on or before this day" + } + } }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "put": { + "tags": [ + "namespaces" + ], + "summary": "Set Collection Member", + "description": "Give someone a role on the collection (and the collections inside it), change it, or (role null) take it away.\nThey needn't have a role in the namespace: then they see just this collection. Owners of the namespace and admins\nof the collection. Answers with the members; audited as `collection.member`.", + "operationId": "set_collection_member", + "parameters": [ { - "name": "min_duration", - "in": "query", - "required": false, + "name": "name", + "in": "path", + "required": true, "schema": { - "anyOf": [ - { - "type": "integer", - "minimum": 0 - }, - { - "type": "null" - } - ], - "description": "at least this many seconds long", - "title": "Min Duration" - }, - "description": "at least this many seconds long" + "type": "string", + "title": "Name" + } }, { - "name": "max_duration", - "in": "query", - "required": false, + "name": "cid", + "in": "path", + "required": true, "schema": { - "anyOf": [ - { - "type": "integer", - "minimum": 1 + "type": "integer", + "title": "Cid" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CollectionMemberSet" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CollectionMember" + }, + "title": "Response Namespaces-Set Collection Member" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/resources": { + "get": { + "tags": [ + "resources" + ], + "summary": "List Recordings", + "description": "Assets you can read, newest first by default: those of the namespaces you have a role in, and of the\ncollections you were given a role on. Filters combine with AND; the ``X-Total-Count`` header says how many match in\nall, so pages can be counted. Each row has your `role` on it.", + "operationId": "list_recordings", + "parameters": [ + { + "name": "ns", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "one namespace (default: every namespace you can read)", + "title": "Ns" + }, + "description": "one namespace (default: every namespace you can read)" + }, + { + "name": "q", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ], + "description": "words that must all appear in the title, the namespace or a person's name", + "title": "Q" + }, + "description": "words that must all appear in the title, the namespace or a person's name" + }, + { + "name": "status", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "array", + "items": { + "enum": [ + "new", + "transcribed", + "diarized", + "analyzed", + "error", + "processing", + "failed" + ], + "type": "string" + } + }, + { + "type": "null" + } + ], + "description": "asset statuses, or processing (a job is queued or running) and failed (the latest job failed); repeat for several (any of them matches)", + "title": "Status" + }, + "description": "asset statuses, or processing (a job is queued or running) and failed (the latest job failed); repeat for several (any of them matches)" + }, + { + "name": "attention", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "description": "only assets that need attention: errored, latest job failed, or a person match to review", + "default": false, + "title": "Attention" + }, + "description": "only assets that need attention: errored, latest job failed, or a person match to review" + }, + { + "name": "processing", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "description": "only assets with a job queued or running", + "default": false, + "title": "Processing" + }, + "description": "only assets with a job queued or running" + }, + { + "name": "speaker", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "integer" + } + }, + { + "type": "null" + } + ], + "description": "person ids; repeat for several (any of them matches)", + "title": "Speaker" + }, + "description": "person ids; repeat for several (any of them matches)" + }, + { + "name": "from", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string", + "format": "date" + }, + { + "type": "null" + } + ], + "description": "recorded on or after this day", + "title": "From" + }, + "description": "recorded on or after this day" + }, + { + "name": "to", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string", + "format": "date" + }, + { + "type": "null" + } + ], + "description": "recorded on or before this day", + "title": "To" + }, + "description": "recorded on or before this day" + }, + { + "name": "min_duration", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "null" + } + ], + "description": "at least this many seconds long", + "title": "Min Duration" + }, + "description": "at least this many seconds long" + }, + { + "name": "max_duration", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "integer", + "minimum": 1 }, { "type": "null" @@ -28814,94 +29211,740 @@ "$ref": "#/components/schemas/HTTPValidationError" } } - } - } - } - } - }, - "/api/v1/podcasts/{rid}/regenerate": { - "post": { - "tags": [ - "podcasts" - ], - "summary": "Regenerate Podcast", - "description": "Make the episode again from what was asked for, reading its sources afresh (editors). A job already making it\nis returned instead.", - "operationId": "regenerate_podcast", - "parameters": [ - { - "name": "rid", - "in": "path", - "required": true, - "schema": { - "type": "integer", - "title": "Rid" - } + } + } + } + } + }, + "/api/v1/podcasts/{rid}/regenerate": { + "post": { + "tags": [ + "podcasts" + ], + "summary": "Regenerate Podcast", + "description": "Make the episode again from what was asked for, reading its sources afresh (editors). A job already making it\nis returned instead.", + "operationId": "regenerate_podcast", + "parameters": [ + { + "name": "rid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Rid" + } + } + ], + "responses": { + "202": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PodcastJob" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "AccessRequest": { + "properties": { + "recording": { + "type": "integer", + "title": "Recording" + }, + "title": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Title" + }, + "namespace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Namespace" + }, + "account": { + "type": "integer", + "title": "Account" + }, + "email": { + "type": "string", + "title": "Email" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name" + }, + "message": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Message" + }, + "at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "At" + }, + "status": { + "type": "string", + "enum": [ + "pending", + "approved", + "declined" + ], + "title": "Status" + }, + "decided_by": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Decided By" + }, + "decided_at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Decided At" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "recording", + "account", + "email", + "status" + ], + "title": "AccessRequest", + "description": "Someone asking for permission on an asset (docs/access.md)." + }, + "AccountToken": { + "properties": { + "id": { + "type": "integer", + "title": "Id" + }, + "name": { + "type": "string", + "title": "Name" + }, + "scope": { + "type": "string", + "enum": [ + "read", + "write" + ], + "title": "Scope" + }, + "prefix": { + "type": "string", + "title": "Prefix" + }, + "created_at": { + "type": "string", + "title": "Created At" + }, + "expires_at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Expires At" + }, + "last_used_at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Last Used At" + }, + "namespace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Namespace", + "description": "the one namespace it opens (its own servers alone), when it was made for one" + }, + "account": { + "type": "integer", + "title": "Account" + }, + "email": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Email" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id", + "name", + "scope", + "prefix", + "created_at", + "account" + ], + "title": "AccountToken", + "description": "Anyone's key, for admins." + }, + "ActionInfo": { + "properties": { + "name": { + "type": "string", + "title": "Name" + }, + "label": { + "type": "string", + "title": "Label" + }, + "group": { + "type": "string", + "title": "Group" + }, + "description": { + "type": "string", + "title": "Description", + "default": "" + }, + "params": { + "additionalProperties": true, + "type": "object", + "title": "Params", + "description": "a JSON Schema (type object) of its params; a string holding {{ }} stands for any type" + }, + "required": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Required" + }, + "effect": { + "type": "string", + "enum": [ + "read", + "self", + "lens", + "out", + "depends" + ], + "title": "Effect", + "description": "what it reaches: read and self run at once; lens asks unless it changes the event's own object; out asks first unless you let it run on its own; depends: worked out from its params" + }, + "output": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Output", + "description": "a JSON Schema of what it gives back, for later nodes (steps.)" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "name", + "label", + "group", + "params", + "effect" + ], + "title": "ActionInfo" + }, + "ActivityActor": { + "properties": { + "type": { + "type": "string", + "enum": [ + "Service", + "Person", + "Application" + ], + "title": "Type" + }, + "id": { + "type": "string", + "title": "Id", + "description": "a Lens reference, like lens:account/1 or lens:automation/4" + }, + "name": { + "type": "string", + "title": "Name" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "type", + "id", + "name" + ], + "title": "ActivityActor" + }, + "ActivityCosts": { + "properties": { + "period": { + "type": "string", + "title": "Period" + }, + "since": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Since" + }, + "costs": { + "additionalProperties": { + "$ref": "#/components/schemas/ResourceSpend" + }, + "type": "object", + "title": "Costs", + "description": "by resource; ones you can't see are left out" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "period", + "costs" + ], + "title": "ActivityCosts" + }, + "ActivityEntry": { + "properties": { + "id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Id", + "description": "the ledger row's id; none for an audit log entry" + }, + "at": { + "type": "string", + "title": "At" + }, + "kind": { + "type": "string", + "enum": [ + "in", + "out", + "run", + "change" + ], + "title": "Kind", + "description": "in: an API request; out: a call Lens made (a model, embeddings, the decision model, a webhook, a web tool); run: a job or routine run ended; change: an audit log entry, or a change to the entity graph (action `graph.`)" + }, + "action": { + "type": "string", + "title": "Action", + "description": "what it was: `POST /api/v1/routines/{rid}/run`, `model.chat`, `job.succeeded`, `routine.update`" + }, + "resources": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Resources", + "description": "every resource it counts for, as table:id" + }, + "actor": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Actor", + "description": "the account that made it, when a person did" + }, + "email": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Email" + }, + "model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Model" + }, + "tokens_in": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Tokens In" + }, + "tokens_out": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Tokens Out" + }, + "cost_usd": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Cost Usd", + "description": "estimated from the prices in Settings; none when the model has no price" + }, + "ms": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Ms" + }, + "ok": { + "type": "boolean", + "title": "Ok", + "default": true + }, + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Error", + "description": "the error's type or HTTP status; never its message" + }, + "detail": { + "title": "Detail" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "at", + "kind", + "action" + ], + "title": "ActivityEntry" + }, + "ActivityKind": { + "properties": { + "name": { + "type": "string", + "title": "Name" + }, + "label": { + "type": "string", + "title": "Label" + }, + "source": { + "type": "string", + "title": "Source" + }, + "type": { + "type": "string", + "title": "Type", + "description": "the Activity Streams verb its activities have" + }, + "object_type": { + "type": "string", + "title": "Object Type" + }, + "parent": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Parent" + }, + "children": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Children" + }, + "fields": { + "additionalProperties": true, + "type": "object", + "title": "Fields", + "description": "JSON Schemas of its own object, actor or target fields" + }, + "schema": { + "additionalProperties": true, + "type": "object", + "title": "Schema", + "description": "a JSON Schema of its activities, with every field" + }, + "untrusted": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Untrusted" + }, + "noisy": { + "type": "boolean", + "title": "Noisy", + "description": "left out of the timeline unless named", + "default": false + }, + "sample": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Sample" } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "name", + "label", + "source", + "type", + "object_type", + "schema" ], - "responses": { - "202": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PodcastJob" - } + "title": "ActivityKind" + }, + "ActivityLens": { + "properties": { + "source": { + "type": "string", + "title": "Source", + "description": "the source that made it, like recordings or log" + }, + "pos": { + "items": {}, + "type": "array", + "title": "Pos", + "description": "the source's position, [time, id]; for the stream machinery" + }, + "untrusted": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Untrusted", + "description": "dotted paths holding text from outside Lens" + }, + "cause": { + "anyOf": [ + { + "additionalProperties": { + "type": "integer" + }, + "type": "object" + }, + { + "type": "null" } - } + ], + "title": "Cause", + "description": "{automation, run, depth} when an automation caused it" }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } + "spaces": { + "anyOf": [ + { + "items": { + "type": "integer" + }, + "type": "array" + }, + { + "type": "null" } - } - } - } - } - } - }, - "components": { - "schemas": { - "AccessRequest": { - "properties": { - "recording": { - "type": "integer", - "title": "Recording" + ], + "title": "Spaces", + "description": "every namespace it belongs to, when there are several" }, - "title": { + "audience": { "anyOf": [ { - "type": "string" + "type": "string", + "enum": [ + "space", + "owner", + "admins" + ] }, { "type": "null" } ], - "title": "Title" + "title": "Audience", + "description": "who may see it (default: space)" }, - "namespace": { + "owner": { "anyOf": [ { - "type": "string" + "type": "integer" }, { "type": "null" } ], - "title": "Namespace" + "title": "Owner", + "description": "the account that alone sees it, with audience owner" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "source", + "pos" + ], + "title": "ActivityLens" + }, + "ActivityMark": { + "properties": { + "reviewed": { + "type": "boolean", + "title": "Reviewed", + "default": false }, - "account": { - "type": "integer", - "title": "Account" + "important": { + "type": "boolean", + "title": "Important", + "default": false }, - "email": { - "type": "string", - "title": "Email" + "hidden": { + "type": "boolean", + "title": "Hidden", + "default": false }, - "name": { + "at": { "anyOf": [ { "type": "string" @@ -28910,9 +29953,22 @@ "type": "null" } ], - "title": "Name" + "title": "At", + "description": "when you last marked it" + } + }, + "additionalProperties": true, + "type": "object", + "title": "ActivityMark", + "description": "Your own review marks on an activity; nobody else sees them." + }, + "ActivityObject": { + "properties": { + "type": { + "type": "string", + "title": "Type" }, - "message": { + "id": { "anyOf": [ { "type": "string" @@ -28921,9 +29977,10 @@ "type": "null" } ], - "title": "Message" + "title": "Id", + "description": "a Lens reference, like lens:recording/7" }, - "at": { + "name": { "anyOf": [ { "type": "string" @@ -28932,18 +29989,9 @@ "type": "null" } ], - "title": "At" - }, - "status": { - "type": "string", - "enum": [ - "pending", - "approved", - "declined" - ], - "title": "Status" + "title": "Name" }, - "decided_by": { + "url": { "anyOf": [ { "type": "string" @@ -28952,9 +30000,29 @@ "type": "null" } ], - "title": "Decided By" + "title": "Url", + "description": "its page in the web app, relative to it" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "type" + ], + "title": "ActivityObject", + "description": "What the activity is about; each kind adds its own fields (GET /activities/kinds has its schema)." + }, + "ActivityPage": { + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/StreamActivity" + }, + "type": "array", + "title": "Items", + "description": "newest first" }, - "decided_at": { + "next": { "anyOf": [ { "type": "string" @@ -28963,47 +30031,40 @@ "type": "null" } ], - "title": "Decided At" + "title": "Next", + "description": "give it as before for the page after; null at the end" + }, + "namespaces": { + "additionalProperties": { + "type": "string" + }, + "type": "object", + "title": "Namespaces", + "description": "the names of the namespaces in items, by id" + }, + "marks": { + "additionalProperties": { + "$ref": "#/components/schemas/ActivityMark" + }, + "type": "object", + "title": "Marks", + "description": "your marks on items, by id (those you marked)" } }, "additionalProperties": true, "type": "object", "required": [ - "recording", - "account", - "email", - "status" + "items" ], - "title": "AccessRequest", - "description": "Someone asking for permission on an asset (docs/access.md)." + "title": "ActivityPage" }, - "AccountToken": { + "ActivityTop": { "properties": { - "id": { - "type": "integer", - "title": "Id" - }, - "name": { - "type": "string", - "title": "Name" - }, - "scope": { - "type": "string", - "enum": [ - "read", - "write" - ], - "title": "Scope" - }, - "prefix": { - "type": "string", - "title": "Prefix" - }, - "created_at": { + "period": { "type": "string", - "title": "Created At" + "title": "Period" }, - "expires_at": { + "since": { "anyOf": [ { "type": "string" @@ -29012,9 +30073,27 @@ "type": "null" } ], - "title": "Expires At" + "title": "Since" }, - "last_used_at": { + "resources": { + "items": { + "$ref": "#/components/schemas/ResourceCost" + }, + "type": "array", + "title": "Resources" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "period", + "resources" + ], + "title": "ActivityTop" + }, + "ActivityTotals": { + "properties": { + "resource": { "anyOf": [ { "type": "string" @@ -29023,9 +30102,13 @@ "type": "null" } ], - "title": "Last Used At" + "title": "Resource" }, - "namespace": { + "period": { + "type": "string", + "title": "Period" + }, + "since": { "anyOf": [ { "type": "string" @@ -29034,157 +30117,287 @@ "type": "null" } ], - "title": "Namespace", - "description": "the one namespace it opens (its own servers alone), when it was made for one" + "title": "Since" }, - "account": { + "calls": { "type": "integer", - "title": "Account" + "title": "Calls" }, - "email": { + "failed": { + "type": "integer", + "title": "Failed" + }, + "tokens_in": { + "type": "integer", + "title": "Tokens In" + }, + "tokens_out": { + "type": "integer", + "title": "Tokens Out" + }, + "cost_usd": { + "type": "number", + "title": "Cost Usd", + "description": "what its calls cost (run rows repeat their calls' cost and aren't added again)" + }, + "ms": { + "type": "integer", + "title": "Ms" + }, + "unpriced": { + "type": "integer", + "title": "Unpriced", + "description": "calls that cost something but have no figure (a model with no price, a reply without token counts)", + "default": 0 + }, + "estimate": { + "type": "boolean", + "title": "Estimate", + "description": "true when unpriced calls make cost_usd a floor rather than exact", + "default": false + }, + "by_kind": { + "additionalProperties": { + "$ref": "#/components/schemas/KindTotals" + }, + "type": "object", + "title": "By Kind" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "period", + "calls", + "failed", + "tokens_in", + "tokens_out", + "cost_usd", + "ms", + "by_kind" + ], + "title": "ActivityTotals" + }, + "AnalyticsChurn": { + "properties": { + "previous_active": { + "type": "integer", + "title": "Previous Active" + }, + "retained": { + "type": "integer", + "title": "Retained" + }, + "churned": { + "type": "integer", + "title": "Churned" + }, + "rate": { "anyOf": [ { - "type": "string" + "type": "number" }, { "type": "null" } ], - "title": "Email" + "title": "Rate" + }, + "returning": { + "type": "integer", + "title": "Returning" } }, "additionalProperties": true, "type": "object", "required": [ - "id", - "name", - "scope", - "prefix", - "created_at", - "account" + "previous_active", + "retained", + "churned", + "returning" ], - "title": "AccountToken", - "description": "Anyone's key, for admins." + "title": "AnalyticsChurn" }, - "ActivityActor": { + "AnalyticsCohort": { "properties": { - "type": { + "week": { "type": "string", - "enum": [ - "Service", - "Person", - "Application" - ], - "title": "Type" + "title": "Week" }, - "id": { - "type": "string", - "title": "Id", - "description": "a Lens reference, like lens:account/1 or lens:automation/4" + "users": { + "type": "integer", + "title": "Users" }, - "name": { + "retention": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Retention" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "week", + "users", + "retention" + ], + "title": "AnalyticsCohort" + }, + "AnalyticsDay": { + "properties": { + "day": { "type": "string", - "title": "Name" + "title": "Day" + }, + "active_users": { + "type": "integer", + "title": "Active Users" + }, + "actions": { + "type": "integer", + "title": "Actions" } }, "additionalProperties": true, "type": "object", "required": [ - "type", - "id", - "name" + "day", + "active_users", + "actions" ], - "title": "ActivityActor" + "title": "AnalyticsDay" }, - "ActivityCosts": { + "AnalyticsEvent": { "properties": { - "period": { + "name": { "type": "string", - "title": "Period" + "title": "Name" }, - "since": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "title": "Since" + "description": { + "type": "string", + "title": "Description" + }, + "on": { + "type": "boolean", + "title": "On" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "name", + "description", + "on" + ], + "title": "AnalyticsEvent" + }, + "AnalyticsFeature": { + "properties": { + "feature": { + "type": "string", + "title": "Feature" }, - "costs": { - "additionalProperties": { - "$ref": "#/components/schemas/ResourceSpend" - }, - "type": "object", - "title": "Costs", - "description": "by resource; ones you can't see are left out" + "actions": { + "type": "integer", + "title": "Actions" + }, + "users": { + "type": "integer", + "title": "Users" } }, "additionalProperties": true, "type": "object", "required": [ - "period", - "costs" + "feature", + "actions", + "users" ], - "title": "ActivityCosts" + "title": "AnalyticsFeature" }, - "ActivityEntry": { + "AnalyticsMetrics": { "properties": { - "id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "title": "Id", - "description": "the ledger row's id; none for an audit log entry" - }, - "at": { - "type": "string", - "title": "At" + "days": { + "type": "integer", + "title": "Days" }, - "kind": { + "since": { "type": "string", - "enum": [ - "in", - "out", - "run", - "change" - ], - "title": "Kind", - "description": "in: an API request; out: a call Lens made (a model, embeddings, the decision model, a webhook, a web tool); run: a job or routine run ended; change: an audit log entry, or a change to the entity graph (action `graph.`)" + "title": "Since" }, - "action": { + "until": { "type": "string", - "title": "Action", - "description": "what it was: `POST /api/v1/routines/{rid}/run`, `model.chat`, `job.succeeded`, `routine.update`" + "title": "Until" }, - "resources": { + "daily": { "items": { - "type": "string" + "$ref": "#/components/schemas/AnalyticsDay" }, "type": "array", - "title": "Resources", - "description": "every resource it counts for, as table:id" + "title": "Daily" }, - "actor": { + "dau": { + "type": "integer", + "title": "Dau" + }, + "wau": { + "type": "integer", + "title": "Wau" + }, + "mau": { + "type": "integer", + "title": "Mau" + }, + "stickiness": { "anyOf": [ { - "type": "integer" + "type": "number" }, { "type": "null" } ], - "title": "Actor", - "description": "the account that made it, when a person did" + "title": "Stickiness" }, - "email": { + "accounts": { + "type": "integer", + "title": "Accounts" + }, + "active_users": { + "type": "integer", + "title": "Active Users" + }, + "new_users": { + "type": "integer", + "title": "New Users" + }, + "churn": { + "$ref": "#/components/schemas/AnalyticsChurn" + }, + "retention": { + "items": { + "$ref": "#/components/schemas/AnalyticsCohort" + }, + "type": "array", + "title": "Retention" + }, + "features": { + "items": { + "$ref": "#/components/schemas/AnalyticsFeature" + }, + "type": "array", + "title": "Features" + }, + "last_active_day": { "anyOf": [ { "type": "string" @@ -29193,68 +30406,125 @@ "type": "null" } ], - "title": "Email" + "title": "Last Active Day" }, - "model": { + "days_since_active": { "anyOf": [ { - "type": "string" + "type": "integer" }, { "type": "null" } ], - "title": "Model" + "title": "Days Since Active" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "days", + "since", + "until", + "daily", + "dau", + "wau", + "mau", + "accounts", + "active_users", + "new_users", + "churn", + "retention", + "features" + ], + "title": "AnalyticsMetrics", + "description": "Active people, churn, retention and feature use, worked out on this machine from the activity ledger and\nsign-ins (docs/analytics.md#the-numbers)." + }, + "AnalyticsStatus": { + "properties": { + "enabled": { + "type": "boolean", + "title": "Enabled" }, - "tokens_in": { + "configured": { + "type": "boolean", + "title": "Configured" + }, + "measurement_id": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "title": "Tokens In" + "title": "Measurement Id" }, - "tokens_out": { + "client_id": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "title": "Tokens Out" + "title": "Client Id" }, - "cost_usd": { + "last_sent_at": { "anyOf": [ { - "type": "number" + "type": "string" }, { "type": "null" } ], - "title": "Cost Usd", - "description": "estimated from the prices in Settings; none when the model has no price" + "title": "Last Sent At" }, - "ms": { + "last_sent": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Last Sent", + "default": [] + }, + "last_error": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "title": "Ms" + "title": "Last Error" }, + "events": { + "items": { + "$ref": "#/components/schemas/AnalyticsEvent" + }, + "type": "array", + "title": "Events" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "enabled", + "configured", + "events" + ], + "title": "AnalyticsStatus", + "description": "Whether usage statistics go to Google Analytics, and how the last send went (docs/analytics.md)." + }, + "AnalyticsTestResult": { + "properties": { "ok": { "type": "boolean", - "title": "Ok", - "default": true + "title": "Ok" }, "error": { "anyOf": [ @@ -29265,46 +30535,89 @@ "type": "null" } ], - "title": "Error", - "description": "the error's type or HTTP status; never its message" + "title": "Error" + }, + "messages": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Messages", + "default": [] + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "ok" + ], + "title": "AnalyticsTestResult" + }, + "AnswerCheck": { + "properties": { + "claims": { + "type": "integer", + "title": "Claims", + "description": "sentences that cite a source" + }, + "supported": { + "type": "integer", + "title": "Supported", + "description": "claims the cited excerpts support" + }, + "verdicts": { + "items": { + "additionalProperties": true, + "type": "object" + }, + "type": "array", + "title": "Verdicts", + "default": [] }, - "detail": { - "title": "Detail" + "uncited": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Uncited", + "default": [] } }, "additionalProperties": true, "type": "object", "required": [ - "at", - "kind", - "action" + "claims", + "supported" ], - "title": "ActivityEntry" + "title": "AnswerCheck" }, - "ActivityKind": { + "ApiToken": { "properties": { + "id": { + "type": "integer", + "title": "Id" + }, "name": { "type": "string", "title": "Name" }, - "label": { - "type": "string", - "title": "Label" - }, - "source": { + "scope": { "type": "string", - "title": "Source" + "enum": [ + "read", + "write" + ], + "title": "Scope" }, - "type": { + "prefix": { "type": "string", - "title": "Type", - "description": "the Activity Streams verb its activities have" + "title": "Prefix" }, - "object_type": { + "created_at": { "type": "string", - "title": "Object Type" + "title": "Created At" }, - "parent": { + "expires_at": { "anyOf": [ { "type": "string" @@ -29313,208 +30626,152 @@ "type": "null" } ], - "title": "Parent" - }, - "children": { - "items": { - "type": "string" - }, - "type": "array", - "title": "Children" - }, - "fields": { - "additionalProperties": true, - "type": "object", - "title": "Fields", - "description": "JSON Schemas of its own object, actor or target fields" - }, - "schema": { - "additionalProperties": true, - "type": "object", - "title": "Schema", - "description": "a JSON Schema of its activities, with every field" - }, - "untrusted": { - "items": { - "type": "string" - }, - "type": "array", - "title": "Untrusted" + "title": "Expires At" }, - "noisy": { - "type": "boolean", - "title": "Noisy", - "description": "left out of the timeline unless named", - "default": false + "last_used_at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Last Used At" }, - "sample": { + "namespace": { "anyOf": [ { - "additionalProperties": true, - "type": "object" + "type": "string" }, { "type": "null" } ], - "title": "Sample" + "title": "Namespace", + "description": "the one namespace it opens (its own servers alone), when it was made for one" } }, "additionalProperties": true, "type": "object", "required": [ + "id", "name", - "label", - "source", - "type", - "object_type", - "schema" + "scope", + "prefix", + "created_at" ], - "title": "ActivityKind" + "title": "ApiToken" }, - "ActivityLens": { + "ApiTokenCreate": { "properties": { - "source": { + "name": { "type": "string", - "title": "Source", - "description": "the source that made it, like recordings or log" - }, - "pos": { - "items": {}, - "type": "array", - "title": "Pos", - "description": "the source's position, [time, id]; for the stream machinery" - }, - "untrusted": { - "items": { - "type": "string" - }, - "type": "array", - "title": "Untrusted", - "description": "dotted paths holding text from outside Lens" - }, - "cause": { - "anyOf": [ - { - "additionalProperties": { - "type": "integer" - }, - "type": "object" - }, - { - "type": "null" - } - ], - "title": "Cause", - "description": "{automation, run, depth} when an automation caused it" + "title": "Name", + "default": "token" }, - "spaces": { - "anyOf": [ - { - "items": { - "type": "integer" - }, - "type": "array" - }, - { - "type": "null" - } + "scope": { + "type": "string", + "enum": [ + "read", + "write" ], - "title": "Spaces", - "description": "every namespace it belongs to, when there are several" + "title": "Scope", + "default": "read" }, - "audience": { + "namespace": { "anyOf": [ { - "type": "string", - "enum": [ - "space", - "owner", - "admins" - ] + "type": "string" }, { "type": "null" } ], - "title": "Audience", - "description": "who may see it (default: space)" + "title": "Namespace", + "description": "a namespace you can read: the key opens that namespace's own MCP server and chat completions alone, and nothing else in Lens; none: whatever you can reach" }, - "owner": { + "days": { "anyOf": [ { - "type": "integer" + "type": "integer", + "maximum": 3650.0, + "minimum": 0.0 }, { "type": "null" } ], - "title": "Owner", - "description": "the account that alone sees it, with audience owner" + "title": "Days", + "description": "how long it lasts; default: tokens.default_days; 0: never expires, when tokens.never_expire allows" } }, - "additionalProperties": true, + "additionalProperties": false, "type": "object", - "required": [ - "source", - "pos" - ], - "title": "ActivityLens" + "title": "ApiTokenCreate" }, - "ActivityMark": { + "ApiTokenCreated": { "properties": { - "reviewed": { - "type": "boolean", - "title": "Reviewed", - "default": false - }, - "important": { - "type": "boolean", - "title": "Important", - "default": false + "id": { + "type": "integer", + "title": "Id" }, - "hidden": { - "type": "boolean", - "title": "Hidden", - "default": false + "token": { + "type": "string", + "title": "Token" }, - "at": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "title": "At", - "description": "when you last marked it" + "note": { + "type": "string", + "title": "Note", + "default": "copy it now; it won't be shown again" } }, "additionalProperties": true, "type": "object", - "title": "ActivityMark", - "description": "Your own review marks on an activity; nobody else sees them." + "required": [ + "id", + "token" + ], + "title": "ApiTokenCreated" }, - "ActivityObject": { + "ApiTokenRename": { "properties": { - "type": { + "name": { "type": "string", - "title": "Type" - }, + "maxLength": 80, + "minLength": 1, + "title": "Name" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "name" + ], + "title": "ApiTokenRename" + }, + "Approval": { + "properties": { "id": { + "type": "integer", + "title": "Id" + }, + "chat": { "anyOf": [ { - "type": "string" + "type": "integer" }, { "type": "null" } ], - "title": "Id", - "description": "a Lens reference, like lens:recording/7" + "title": "Chat" }, - "name": { + "tool": { + "type": "string", + "title": "Tool" + }, + "summary": { "anyOf": [ { "type": "string" @@ -29523,9 +30780,16 @@ "type": "null" } ], - "title": "Name" + "title": "Summary" }, - "url": { + "estimate": { + "title": "Estimate" + }, + "status": { + "type": "string", + "title": "Status" + }, + "created_at": { "anyOf": [ { "type": "string" @@ -29534,115 +30798,102 @@ "type": "null" } ], - "title": "Url", - "description": "its page in the web app, relative to it" + "title": "Created At" + }, + "result": { + "title": "Result" } }, "additionalProperties": true, "type": "object", "required": [ - "type" + "id", + "tool", + "status" ], - "title": "ActivityObject", - "description": "What the activity is about; each kind adds its own fields (GET /activities/kinds has its schema)." + "title": "Approval" }, - "ActivityPage": { + "ApprovalDecision": { "properties": { - "items": { - "items": { - "$ref": "#/components/schemas/StreamActivity" - }, - "type": "array", - "title": "Items", - "description": "newest first" + "decision": { + "type": "string", + "enum": [ + "approve", + "sample", + "decline" + ], + "title": "Decision", + "default": "approve" + } + }, + "additionalProperties": false, + "type": "object", + "title": "ApprovalDecision" + }, + "ApprovalOutcome": { + "properties": { + "status": { + "type": "string", + "title": "Status" }, - "next": { + "batch": { "anyOf": [ { - "type": "string" + "type": "integer" }, { "type": "null" } ], - "title": "Next", - "description": "give it as before for the page after; null at the end" - }, - "namespaces": { - "additionalProperties": { - "type": "string" - }, - "type": "object", - "title": "Namespaces", - "description": "the names of the namespaces in items, by id" - }, - "marks": { - "additionalProperties": { - "$ref": "#/components/schemas/ActivityMark" - }, - "type": "object", - "title": "Marks", - "description": "your marks on items, by id (those you marked)" + "title": "Batch", + "description": "the batch run started, for run_template" } }, "additionalProperties": true, "type": "object", "required": [ - "items" + "status" ], - "title": "ActivityPage" + "title": "ApprovalOutcome" }, - "ActivityTop": { + "AssistantMemory": { "properties": { - "period": { + "id": { + "type": "integer", + "title": "Id" + }, + "text": { "type": "string", - "title": "Period" + "title": "Text" }, - "since": { + "recording": { "anyOf": [ { - "type": "string" + "type": "integer" }, { "type": "null" } ], - "title": "Since" + "title": "Recording", + "description": "the asset it came from" }, - "resources": { - "items": { - "$ref": "#/components/schemas/ResourceCost" - }, - "type": "array", - "title": "Resources" - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "period", - "resources" - ], - "title": "ActivityTop" - }, - "ActivityTotals": { - "properties": { - "resource": { + "t0": { "anyOf": [ { - "type": "string" + "type": "integer" + }, + { + "type": "number" }, { "type": "null" } ], - "title": "Resource" - }, - "period": { - "type": "string", - "title": "Period" + "title": "T0", + "description": "the moment in that asset (ms)" }, - "since": { + "title": { "anyOf": [ { "type": "string" @@ -29651,287 +30902,207 @@ "type": "null" } ], - "title": "Since" - }, - "calls": { - "type": "integer", - "title": "Calls" - }, - "failed": { - "type": "integer", - "title": "Failed" - }, - "tokens_in": { - "type": "integer", - "title": "Tokens In" - }, - "tokens_out": { - "type": "integer", - "title": "Tokens Out" + "title": "Title", + "description": "that asset's title" }, - "cost_usd": { - "type": "number", - "title": "Cost Usd", - "description": "what its calls cost (run rows repeat their calls' cost and aren't added again)" + "time": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Time", + "description": "that moment as \"12:34\"" }, - "ms": { - "type": "integer", - "title": "Ms" + "chat": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Chat", + "description": "the conversation it was told in" }, - "unpriced": { - "type": "integer", - "title": "Unpriced", - "description": "calls that cost something but have no figure (a model with no price, a reply without token counts)", - "default": 0 + "author": { + "type": "string", + "title": "Author", + "description": "assistant (kept from a conversation) or person (written here)" }, - "estimate": { + "pinned": { "type": "boolean", - "title": "Estimate", - "description": "true when unpriced calls make cost_usd a floor rather than exact", + "title": "Pinned", + "description": "always read with every question", "default": false }, - "by_kind": { - "additionalProperties": { - "$ref": "#/components/schemas/KindTotals" - }, - "type": "object", - "title": "By Kind" - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "period", - "calls", - "failed", - "tokens_in", - "tokens_out", - "cost_usd", - "ms", - "by_kind" - ], - "title": "ActivityTotals" - }, - "AnalyticsChurn": { - "properties": { - "previous_active": { - "type": "integer", - "title": "Previous Active" - }, - "retained": { - "type": "integer", - "title": "Retained" - }, - "churned": { - "type": "integer", - "title": "Churned" + "created_at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Created At" }, - "rate": { + "updated_at": { "anyOf": [ { - "type": "number" + "type": "string" }, { "type": "null" } ], - "title": "Rate" - }, - "returning": { - "type": "integer", - "title": "Returning" - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "previous_active", - "retained", - "churned", - "returning" - ], - "title": "AnalyticsChurn" - }, - "AnalyticsCohort": { - "properties": { - "week": { - "type": "string", - "title": "Week" - }, - "users": { - "type": "integer", - "title": "Users" - }, - "retention": { - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "type": "array", - "title": "Retention" + "title": "Updated At" } }, "additionalProperties": true, "type": "object", "required": [ - "week", - "users", - "retention" + "id", + "text", + "author" ], - "title": "AnalyticsCohort" + "title": "AssistantMemory" }, - "AnalyticsDay": { + "AssistantMemoryCreate": { "properties": { - "day": { + "text": { "type": "string", - "title": "Day" - }, - "active_users": { - "type": "integer", - "title": "Active Users" + "maxLength": 500, + "title": "Text" }, - "actions": { - "type": "integer", - "title": "Actions" + "pinned": { + "type": "boolean", + "title": "Pinned", + "default": false } }, - "additionalProperties": true, + "additionalProperties": false, "type": "object", "required": [ - "day", - "active_users", - "actions" + "text" ], - "title": "AnalyticsDay" + "title": "AssistantMemoryCreate" }, - "AnalyticsEvent": { + "AssistantMemoryUpdate": { "properties": { - "name": { - "type": "string", - "title": "Name" - }, - "description": { - "type": "string", - "title": "Description" + "text": { + "anyOf": [ + { + "type": "string", + "maxLength": 500 + }, + { + "type": "null" + } + ], + "title": "Text" }, - "on": { - "type": "boolean", - "title": "On" + "pinned": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Pinned" } }, - "additionalProperties": true, + "additionalProperties": false, "type": "object", - "required": [ - "name", - "description", - "on" - ], - "title": "AnalyticsEvent" + "title": "AssistantMemoryUpdate" }, - "AnalyticsFeature": { + "AttachedTo": { "properties": { - "feature": { - "type": "string", - "title": "Feature" - }, - "actions": { + "resource": { "type": "integer", - "title": "Actions" + "title": "Resource" }, - "users": { - "type": "integer", - "title": "Users" + "file": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "File" + }, + "title": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Title" } }, "additionalProperties": true, "type": "object", "required": [ - "feature", - "actions", - "users" + "resource" ], - "title": "AnalyticsFeature" + "title": "AttachedTo", + "description": "The email a resource was attached to (it's one of that email's files too)." }, - "AnalyticsMetrics": { + "Attachment": { "properties": { - "days": { - "type": "integer", - "title": "Days" - }, - "since": { + "id": { "type": "string", - "title": "Since" + "title": "Id", + "description": "the upload" }, - "until": { + "filename": { "type": "string", - "title": "Until" - }, - "daily": { - "items": { - "$ref": "#/components/schemas/AnalyticsDay" - }, - "type": "array", - "title": "Daily" - }, - "dau": { - "type": "integer", - "title": "Dau" - }, - "wau": { - "type": "integer", - "title": "Wau" + "title": "Filename" }, - "mau": { + "size": { "type": "integer", - "title": "Mau" + "title": "Size" }, - "stickiness": { + "recording": { "anyOf": [ { - "type": "number" + "type": "integer" }, { "type": "null" } ], - "title": "Stickiness" - }, - "accounts": { - "type": "integer", - "title": "Accounts" - }, - "active_users": { - "type": "integer", - "title": "Active Users" - }, - "new_users": { - "type": "integer", - "title": "New Users" - }, - "churn": { - "$ref": "#/components/schemas/AnalyticsChurn" - }, - "retention": { - "items": { - "$ref": "#/components/schemas/AnalyticsCohort" - }, - "type": "array", - "title": "Retention" - }, - "features": { - "items": { - "$ref": "#/components/schemas/AnalyticsFeature" - }, - "type": "array", - "title": "Features" + "title": "Recording", + "description": "the asset it became, once imported" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id", + "filename", + "size" + ], + "title": "Attachment" + }, + "AuditEntry": { + "properties": { + "at": { + "type": "string", + "title": "At" }, - "last_active_day": { + "email": { "anyOf": [ { "type": "string" @@ -29940,51 +31111,70 @@ "type": "null" } ], - "title": "Last Active Day" + "title": "Email" + }, + "action": { + "type": "string", + "title": "Action" }, - "days_since_active": { + "target": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "title": "Days Since Active" + "title": "Target" + }, + "detail": { + "title": "Detail" } }, "additionalProperties": true, "type": "object", "required": [ - "days", - "since", - "until", - "daily", - "dau", - "wau", - "mau", - "accounts", - "active_users", - "new_users", - "churn", - "retention", - "features" + "at", + "action" ], - "title": "AnalyticsMetrics", - "description": "Active people, churn, retention and feature use, worked out on this machine from the activity ledger and\nsign-ins (docs/analytics.md#the-numbers)." + "title": "AuditEntry" }, - "AnalyticsStatus": { + "AuthStatus": { "properties": { - "enabled": { + "setup_required": { "type": "boolean", - "title": "Enabled" + "title": "Setup Required" }, - "configured": { + "wizard_pending": { "type": "boolean", - "title": "Configured" + "title": "Wizard Pending", + "default": false }, - "measurement_id": { + "passwords": { + "type": "boolean", + "title": "Passwords", + "default": false + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "setup_required" + ], + "title": "AuthStatus" + }, + "Automation": { + "properties": { + "id": { + "type": "integer", + "title": "Id" + }, + "name": { + "type": "string", + "title": "Name" + }, + "description": { "anyOf": [ { "type": "string" @@ -29993,9 +31183,13 @@ "type": "null" } ], - "title": "Measurement Id" + "title": "Description" }, - "client_id": { + "enabled": { + "type": "boolean", + "title": "Enabled" + }, + "enabled_at": { "anyOf": [ { "type": "string" @@ -30004,154 +31198,158 @@ "type": "null" } ], - "title": "Client Id" + "title": "Enabled At", + "description": "when it was last switched on: it reacts only to what happens after" }, - "last_sent_at": { + "spaces": { "anyOf": [ { - "type": "string" + "items": { + "type": "integer" + }, + "type": "array" }, { "type": "null" } ], - "title": "Last Sent At" - }, - "last_sent": { - "items": { - "type": "string" - }, - "type": "array", - "title": "Last Sent", - "default": [] + "title": "Spaces", + "description": "the namespaces it works in; none for every one (admins)" }, - "last_error": { + "namespace_names": { "anyOf": [ { - "type": "string" + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "type": "array" }, { "type": "null" } ], - "title": "Last Error" + "title": "Namespace Names" }, - "events": { + "run_as": { + "type": "integer", + "title": "Run As", + "description": "the account it acts for, with that person's permissions: its maker" + }, + "triggers": { "items": { - "$ref": "#/components/schemas/AnalyticsEvent" + "additionalProperties": true, + "type": "object" }, "type": "array", - "title": "Events" - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "enabled", - "configured", - "events" - ], - "title": "AnalyticsStatus", - "description": "Whether usage statistics go to Google Analytics, and how the last send went (docs/analytics.md)." - }, - "AnalyticsTestResult": { - "properties": { - "ok": { - "type": "boolean", - "title": "Ok" + "title": "Triggers", + "description": "each {as, on, ...}: {as, on: event, kinds, where?, from_automations?}, {as, on: manual}; on schedule, at, relative and webhook are coming soon (docs/automations.md, Triggers)" }, - "error": { + "join": { + "additionalProperties": true, + "type": "object", + "title": "Join", + "description": "how several triggers make one run: {mode: any} (each on its own)" + }, + "if": { "anyOf": [ { - "type": "string" + "additionalProperties": true, + "type": "object" }, { "type": "null" } ], - "title": "Error" + "title": "If", + "description": "a match tree over the run context, tested before the Then runs, like {all: [{path, op, value}]}" }, - "messages": { - "items": { - "type": "string" - }, - "type": "array", - "title": "Messages", - "default": [] - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "ok" - ], - "title": "AnalyticsTestResult" - }, - "AnswerCheck": { - "properties": { - "claims": { + "workflow": { "type": "integer", - "title": "Claims", - "description": "sentences that cite a source" + "title": "Workflow", + "description": "its workflow (scope event)" }, - "supported": { - "type": "integer", - "title": "Supported", - "description": "claims the cited excerpts support" + "version": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Version", + "description": "the workflow version it runs; none follows the published one" }, - "verdicts": { - "items": { - "additionalProperties": true, - "type": "object" - }, - "type": "array", - "title": "Verdicts", - "default": [] + "runs_version": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Runs Version", + "description": "the version it runs now" }, - "uncited": { - "items": { - "type": "string" - }, - "type": "array", - "title": "Uncited", - "default": [] - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "claims", - "supported" - ], - "title": "AnswerCheck" - }, - "ApiToken": { - "properties": { - "id": { - "type": "integer", - "title": "Id" + "graph": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Graph", + "description": "the Then: a workflow graph of scope event (an input node, then action nodes and the flow primitives)" }, - "name": { - "type": "string", - "title": "Name" + "policy": { + "additionalProperties": { + "type": "string", + "enum": [ + "ask", + "auto" + ] + }, + "type": "object", + "title": "Policy", + "description": "{action node id: ask or auto}" }, - "scope": { - "type": "string", - "enum": [ - "read", - "write" - ], - "title": "Scope" + "limits": { + "additionalProperties": true, + "type": "object", + "title": "Limits", + "description": "{cooldown (like 10m), max_per_hour}" }, - "prefix": { - "type": "string", - "title": "Prefix" + "counters": { + "additionalProperties": { + "type": "integer" + }, + "type": "object", + "title": "Counters", + "description": "{runs, skipped (its If was false), limited (over a limit), missed}" }, - "created_at": { - "type": "string", - "title": "Created At" + "last_run_at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Last Run At" }, - "expires_at": { + "last_status": { "anyOf": [ { "type": "string" @@ -30160,9 +31358,9 @@ "type": "null" } ], - "title": "Expires At" + "title": "Last Status" }, - "last_used_at": { + "created_by": { "anyOf": [ { "type": "string" @@ -30171,9 +31369,9 @@ "type": "null" } ], - "title": "Last Used At" + "title": "Created By" }, - "namespace": { + "created_at": { "anyOf": [ { "type": "string" @@ -30182,38 +31380,9 @@ "type": "null" } ], - "title": "Namespace", - "description": "the one namespace it opens (its own servers alone), when it was made for one" - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "id", - "name", - "scope", - "prefix", - "created_at" - ], - "title": "ApiToken" - }, - "ApiTokenCreate": { - "properties": { - "name": { - "type": "string", - "title": "Name", - "default": "token" - }, - "scope": { - "type": "string", - "enum": [ - "read", - "write" - ], - "title": "Scope", - "default": "read" + "title": "Created At" }, - "namespace": { + "updated_at": { "anyOf": [ { "type": "string" @@ -30222,212 +31391,266 @@ "type": "null" } ], - "title": "Namespace", - "description": "a namespace you can read: the key opens that namespace's own MCP server and chat completions alone, and nothing else in Lens; none: whatever you can reach" + "title": "Updated At" }, - "days": { + "removed_at": { "anyOf": [ { - "type": "integer", - "maximum": 3650.0, - "minimum": 0.0 + "type": "string" }, { "type": "null" } ], - "title": "Days", - "description": "how long it lasts; default: tokens.default_days; 0: never expires, when tokens.never_expire allows" - } - }, - "additionalProperties": false, - "type": "object", - "title": "ApiTokenCreate" - }, - "ApiTokenCreated": { - "properties": { - "id": { - "type": "integer", - "title": "Id" - }, - "token": { - "type": "string", - "title": "Token" - }, - "note": { - "type": "string", - "title": "Note", - "default": "copy it now; it won't be shown again" + "title": "Removed At", + "description": "when it was deleted (restore brings it back)" } }, "additionalProperties": true, "type": "object", "required": [ "id", - "token" + "name", + "enabled", + "run_as", + "triggers", + "join", + "workflow", + "limits", + "counters" ], - "title": "ApiTokenCreated" + "title": "Automation" }, - "ApiTokenRename": { + "AutomationCatalog": { "properties": { - "name": { - "type": "string", - "maxLength": 80, - "minLength": 1, - "title": "Name" + "automations": { + "items": { + "$ref": "#/components/schemas/Automation" + }, + "type": "array", + "title": "Automations" } }, - "additionalProperties": false, + "additionalProperties": true, "type": "object", "required": [ - "name" + "automations" ], - "title": "ApiTokenRename" + "title": "AutomationCatalog" }, - "Approval": { + "AutomationCreate": { "properties": { - "id": { - "type": "integer", - "title": "Id" + "name": { + "type": "string", + "title": "Name" }, - "chat": { + "description": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "title": "Chat" + "title": "Description" }, - "tool": { - "type": "string", - "title": "Tool" + "enabled": { + "type": "boolean", + "title": "Enabled", + "description": "switched on, it reacts to what happens from now on", + "default": true }, - "summary": { + "spaces": { "anyOf": [ { - "type": "string" + "items": { + "type": "integer" + }, + "type": "array" }, { "type": "null" } ], - "title": "Summary" + "title": "Spaces", + "description": "namespace ids you can edit; default: each one you can edit (every one, for admins)" }, - "estimate": { - "title": "Estimate" + "triggers": { + "items": { + "additionalProperties": true, + "type": "object" + }, + "type": "array", + "title": "Triggers", + "description": "each {as, on, ...}: {as, on: event, kinds, where?, from_automations?}, {as, on: manual}; on schedule, at, relative and webhook are coming soon (docs/automations.md, Triggers)" }, - "status": { - "type": "string", - "title": "Status" + "join": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Join", + "description": "default {mode: any}: each trigger starts a run of its own" }, - "created_at": { + "if": { "anyOf": [ { - "type": "string" + "additionalProperties": true, + "type": "object" }, { "type": "null" } ], - "title": "Created At" + "title": "If", + "description": "a match tree over the run context, tested before the Then runs, like {all: [{path, op, value}]}" }, - "result": { - "title": "Result" + "graph": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Graph", + "description": "the Then: a workflow graph of scope event (an input node, then action nodes and the flow primitives); or name a saved one in workflow" + }, + "workflow": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Workflow", + "description": "a saved workflow of scope event, instead of a graph" + }, + "version": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Version", + "description": "with workflow: the version to run; none follows the published one" + }, + "policy": { + "anyOf": [ + { + "additionalProperties": { + "type": "string", + "const": "ask" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Policy", + "description": "{action node id: ask}; only you, signed in, let a node run on its own (POST /automations/{id}/policy)" + }, + "limits": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Limits", + "description": "{cooldown: 0s, max_per_hour: 60}" } }, - "additionalProperties": true, + "additionalProperties": false, "type": "object", "required": [ - "id", - "tool", - "status" + "name", + "triggers" ], - "title": "Approval" + "title": "AutomationCreate" }, - "ApprovalDecision": { + "AutomationPolicy": { "properties": { - "decision": { + "node": { + "type": "string", + "title": "Node", + "description": "an action node's id" + }, + "value": { "type": "string", "enum": [ - "approve", - "sample", - "decline" + "ask", + "auto" ], - "title": "Decision", - "default": "approve" + "title": "Value", + "description": "ask: it asks you first; auto: it runs on its own" } }, "additionalProperties": false, "type": "object", - "title": "ApprovalDecision" + "required": [ + "node", + "value" + ], + "title": "AutomationPolicy" }, - "ApprovalOutcome": { + "AutomationSaved": { "properties": { - "status": { - "type": "string", - "title": "Status" + "id": { + "type": "integer", + "title": "Id" }, - "batch": { - "anyOf": [ - { - "type": "integer" + "hooks": { + "items": { + "additionalProperties": { + "type": "string" }, - { - "type": "null" - } - ], - "title": "Batch", - "description": "the batch run started, for run_template" + "type": "object" + }, + "type": "array", + "title": "Hooks", + "description": "new webhook triggers' addresses and signing secrets {as, url, secret}, shown this once" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id" + ], + "title": "AutomationSaved" + }, + "AutomationSwitch": { + "properties": { + "on": { + "type": "boolean", + "title": "On", + "default": true } }, - "additionalProperties": true, + "additionalProperties": false, "type": "object", - "required": [ - "status" - ], - "title": "ApprovalOutcome" + "title": "AutomationSwitch" }, - "AssistantMemory": { + "AutomationUpdate": { "properties": { - "id": { - "type": "integer", - "title": "Id" - }, - "text": { - "type": "string", - "title": "Text" - }, - "recording": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "title": "Recording", - "description": "the asset it came from" - }, - "t0": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "number" - }, - { - "type": "null" - } - ], - "title": "T0", - "description": "the moment in that asset (ms)" - }, - "title": { + "name": { "anyOf": [ { "type": "string" @@ -30436,10 +31659,9 @@ "type": "null" } ], - "title": "Title", - "description": "that asset's title" + "title": "Name" }, - "time": { + "description": { "anyOf": [ { "type": "string" @@ -30448,167 +31670,98 @@ "type": "null" } ], - "title": "Time", - "description": "that moment as \"12:34\"" + "title": "Description" }, - "chat": { + "enabled": { "anyOf": [ { - "type": "integer" + "type": "boolean" }, { "type": "null" } ], - "title": "Chat", - "description": "the conversation it was told in" - }, - "author": { - "type": "string", - "title": "Author", - "description": "assistant (kept from a conversation) or person (written here)" - }, - "pinned": { - "type": "boolean", - "title": "Pinned", - "description": "always read with every question", - "default": false + "title": "Enabled" }, - "created_at": { + "spaces": { "anyOf": [ { - "type": "string" + "items": { + "type": "integer" + }, + "type": "array" }, { "type": "null" } ], - "title": "Created At" + "title": "Spaces" }, - "updated_at": { + "triggers": { "anyOf": [ { - "type": "string" + "items": { + "additionalProperties": true, + "type": "object" + }, + "type": "array" }, { "type": "null" } ], - "title": "Updated At" - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "id", - "text", - "author" - ], - "title": "AssistantMemory" - }, - "AssistantMemoryCreate": { - "properties": { - "text": { - "type": "string", - "maxLength": 500, - "title": "Text" + "title": "Triggers" }, - "pinned": { - "type": "boolean", - "title": "Pinned", - "default": false - } - }, - "additionalProperties": false, - "type": "object", - "required": [ - "text" - ], - "title": "AssistantMemoryCreate" - }, - "AssistantMemoryUpdate": { - "properties": { - "text": { + "join": { "anyOf": [ { - "type": "string", - "maxLength": 500 + "additionalProperties": true, + "type": "object" }, { "type": "null" } ], - "title": "Text" + "title": "Join" }, - "pinned": { + "if": { "anyOf": [ { - "type": "boolean" + "additionalProperties": true, + "type": "object" }, { "type": "null" } ], - "title": "Pinned" - } - }, - "additionalProperties": false, - "type": "object", - "title": "AssistantMemoryUpdate" - }, - "AttachedTo": { - "properties": { - "resource": { - "type": "integer", - "title": "Resource" + "title": "If", + "description": "a match tree over the run context, tested before the Then runs, like {all: [{path, op, value}]}; null for none" }, - "file": { + "graph": { "anyOf": [ { - "type": "integer" + "additionalProperties": true, + "type": "object" }, { "type": "null" } ], - "title": "File" + "title": "Graph", + "description": "a new Then, saved as a new version of its workflow" }, - "title": { + "workflow": { "anyOf": [ { - "type": "string" + "type": "integer" }, { "type": "null" } ], - "title": "Title" - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "resource" - ], - "title": "AttachedTo", - "description": "The email a resource was attached to (it's one of that email's files too)." - }, - "Attachment": { - "properties": { - "id": { - "type": "string", - "title": "Id", - "description": "the upload" - }, - "filename": { - "type": "string", - "title": "Filename" - }, - "size": { - "type": "integer", - "title": "Size" + "title": "Workflow" }, - "recording": { + "version": { "anyOf": [ { "type": "integer" @@ -30617,86 +31770,44 @@ "type": "null" } ], - "title": "Recording", - "description": "the asset it became, once imported" - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "id", - "filename", - "size" - ], - "title": "Attachment" - }, - "AuditEntry": { - "properties": { - "at": { - "type": "string", - "title": "At" + "title": "Version", + "description": "the workflow version to run; null follows the published one" }, - "email": { + "policy": { "anyOf": [ { - "type": "string" + "additionalProperties": { + "type": "string", + "enum": [ + "ask", + "auto" + ] + }, + "type": "object" }, { "type": "null" } ], - "title": "Email" - }, - "action": { - "type": "string", - "title": "Action" + "title": "Policy", + "description": "{action node id: ask}; a node already set to auto may stay auto, and only you set auto (its own route)" }, - "target": { + "limits": { "anyOf": [ { - "type": "string" + "additionalProperties": true, + "type": "object" }, { "type": "null" } ], - "title": "Target" - }, - "detail": { - "title": "Detail" - } - }, - "additionalProperties": true, - "type": "object", - "required": [ - "at", - "action" - ], - "title": "AuditEntry" - }, - "AuthStatus": { - "properties": { - "setup_required": { - "type": "boolean", - "title": "Setup Required" - }, - "wizard_pending": { - "type": "boolean", - "title": "Wizard Pending", - "default": false - }, - "passwords": { - "type": "boolean", - "title": "Passwords", - "default": false + "title": "Limits" } }, - "additionalProperties": true, + "additionalProperties": false, "type": "object", - "required": [ - "setup_required" - ], - "title": "AuthStatus" + "title": "AutomationUpdate" }, "Backend": { "properties": {