Files
ai-agent/backend/runs/attachments.py
gabrielvidalandClaude Opus 5.5 5670313285 feat(cron): cron jobs leave the core for the cron-jobs plugin
Owner jobs and guests' own scheduled jobs are the cron-jobs live plugin's
(forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b,
cron-scheduled-in-the-cli-and-mcp_x4nk83). Gone: backend/cron/,
schemas/cron.py, /api/cron*, /api/me/cron*, the cron scheduler thread,
Settings → Cron and the guests' Tâches planifiées pages, `ai-agent cron`
(now a pointer), MCP run_cron_job / set_cron_job / browse cron, the
scheduled-jobs core skill, guestDefaults.cronLimits.

The core keeps thin contracts:
- runs.guest bridge (runs/guestjob.py): a guest's job run as that guest,
  confined by the core from their record; the plugin only names it.
- runs.start's cron stamp → meta.cron.
- delivery of a guest job's result (push, mail, mailHtml) off the stamp.
- « Discuter »: POST /api/cron-runs/discuss.
- runs.cron provider readers (plugins/cron_bridge.py): budget,
  auto-archive, agents catalog, the agents page's Schedule.
- core/cronexpr.py, agents/runconfig.py; context.write create for a new
  agent definition; ui.pages[].unless; setRoute keeps a Settings page
  under /settings/p/.
- carryover.cron_jobs: /data/cron-jobs.json → the plugin's jobs.json,
  cronLimits → limits.json, guests' qwen jobs → sonnet (PR #23's
  decision, superseded).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:57:41 +01:00

207 lines
8.5 KiB
Python

"""Composer attachments, placed where the run can read them.
The composer names an attached file by its place in the hub's uploads store,
``<UPLOADS_REPO_PREFIX>/<batch>/<name>`` (files/assets.py) — a path relative
to the lab's homelab checkout. Before a prompt goes out, each stored file it
names is renamed to an absolute path the run can open:
* on the lab — the store's path on the host (``UPLOADS_HOST_DIR``), so a run
whose cwd isn't the homelab checkout finds it too;
* on the lab for a **guest's** run (a scope naming them, ``git.user``) — the
store is out of its reach (dontAsk: reads only in its project + /tmp, and
:func:`grant` denies the store outright), so the file is hard-linked into
the guest's own folder (``GUEST_UPLOADS_DIR/<guest>/<batch>/<name>``) and
named by its host path there; :func:`grant` lets every run of theirs read
that folder — a follow-up into a live run included, its scope being fixed
at launch;
* on a worker, which has no such file at all — the file is PUT to the worker's
``/uploads`` (sidecar/uploads.py) first, and named by the path it landed at.
That covers a new run, a continue, a live run's inbox and a fork. Nothing
changes on screen: the thread viewer reads the rewritten bullet as an
attachment too (frontend ``lib/attachments``) and shows the gallery, never the
path.
A path naming nothing in the store (typed by hand, pruned) is left as it is.
A file the worker can't take refuses the send — an agent told about a file it
can't open goes looking for it instead of saying so.
"""
from __future__ import annotations
import json
import os
import re
import shutil
import urllib.error
import urllib.parse
import urllib.request
from typing import Callable
from fastapi import HTTPException
from core.config import (GUEST_UPLOADS_DIR, GUEST_UPLOADS_HOST_DIR, UPLOADS_DIR,
UPLOADS_HOST_DIR, UPLOADS_REPO_PREFIX)
from core.state import AppState
# The store's own shapes (files/assets.py): a hex batch, a sanitized name. Not
# after a path character, so an already-absolute path is never matched again.
_PATH_RE = re.compile(rf"(?<![\w./-]){re.escape(UPLOADS_REPO_PREFIX)}"
r"/([A-Za-z0-9_-]+)/([A-Za-z0-9._-]+)")
PUSH_TIMEOUT_S = 120
# A guest id as a folder name (users/store.py ids are short slugs).
_GUEST_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
def named(prompt: str) -> list[tuple[str, str]]:
"""The ``(batch, name)`` of every stored upload the prompt names, once each
— a trailing dot is the sentence's, not the name's."""
out: list[tuple[str, str]] = []
for m in _PATH_RE.finditer(prompt or ""):
key = (m.group(1), m.group(2).rstrip("."))
if key[1] and key not in out and (UPLOADS_DIR / key[0] / key[1]).is_file():
out.append(key)
return out
def _rename(prompt: str, where: Callable[[str, str], str | None]) -> str:
"""Each named upload's path → ``where(batch, name)`` (None keeps it)."""
def swap(m: re.Match) -> str:
name = m.group(2).rstrip(".")
path = where(m.group(1), name) if name else None
return m.group(0) if path is None else path + m.group(2)[len(name):]
return _PATH_RE.sub(swap, prompt)
def guest_of(scope: dict | None) -> str | None:
"""The guest a lab scope confines a run to (``git.user`` — every guest
scope carries it, users/runs.py, runs/guestjob.py), else None."""
user = ((scope or {}).get("git") or {}).get("user")
return user if isinstance(user, str) and _GUEST_RE.match(user) else None
def guest_dir(guest: str) -> str | None:
"""The host path of ``guest``'s attachments folder, made if missing (a
sandboxed run binds it, so it has to exist) — None when the hub doesn't
know its host paths (no ``UPLOADS_HOST_DIR``)."""
if not GUEST_UPLOADS_HOST_DIR or not _GUEST_RE.match(guest or ""):
return None
try:
(GUEST_UPLOADS_DIR / guest).mkdir(parents=True, exist_ok=True)
except OSError:
pass
return f"{GUEST_UPLOADS_HOST_DIR}/{guest}"
def grant(scope: dict | None) -> dict | None:
"""A guest's lab ``scope``, in place: may read their attachments folder
(``readDirs``, sidecar launch.py) and not the hub's store, which holds
everyone's. Anything else (the owner's run, a guest's own computer) is
returned as it is."""
guest = guest_of(scope)
folder = guest_dir(guest) if guest else None
if scope is None or not folder:
return scope
scope["readDirs"] = [folder]
if UPLOADS_HOST_DIR:
deny = f"{UPLOADS_HOST_DIR}/**"
if deny not in (scope.get("denyRead") or []):
scope["denyRead"] = [*(scope.get("denyRead") or []), deny]
return scope
def _link(src, dst) -> None:
"""``dst`` as the same file as ``src`` — a hard link (both live in the one
data volume), a copy where linking fails. Never a symlink: the run's read
rules follow it back into the denied store."""
if dst.is_file():
return
dst.parent.mkdir(parents=True, exist_ok=True)
tmp = dst.with_name(f".{dst.name}.{os.getpid()}.tmp")
try:
try:
os.link(src, tmp)
except OSError:
shutil.copyfile(src, tmp)
os.replace(tmp, dst)
finally:
tmp.unlink(missing_ok=True)
def _for_guest(prompt: str, guest: str, stored: set) -> str:
folder = guest_dir(guest)
if not folder:
return prompt
def where(b: str, n: str) -> str | None:
if (b, n) not in stored:
return None
try:
_link(UPLOADS_DIR / b / n, GUEST_UPLOADS_DIR / guest / b / n)
except OSError as e:
raise HTTPException(500, {"message": f"couldn't hand {n} to this run: {e}",
"kind": "guest_upload"})
return f"{folder}/{b}/{n}"
return _rename(prompt, where)
def for_lab(prompt: str, guest: str | None = None) -> str:
"""``prompt`` with each stored upload it names by its path on the host —
in ``guest``'s own folder for a guest's run."""
if not UPLOADS_HOST_DIR:
return prompt
stored = set(named(prompt))
if guest:
return _for_guest(prompt, guest, stored)
return _rename(prompt, lambda b, n: f"{UPLOADS_HOST_DIR}/{b}/{n}"
if (b, n) in stored else None)
def _push(w: dict, batch: str, name: str) -> str:
"""PUT one stored file to the worker; the absolute path it landed at."""
src = UPLOADS_DIR / batch / name
label = w.get("name") or w.get("id")
url = f"{w['url']}/uploads/{urllib.parse.quote(batch)}/{urllib.parse.quote(name)}"
try:
with open(src, "rb") as f:
req = urllib.request.Request(url, data=f, method="PUT", headers={
"Authorization": f"Bearer {w['token']}",
"Content-Type": "application/octet-stream",
"Content-Length": str(src.stat().st_size)})
with urllib.request.urlopen(req, timeout=PUSH_TIMEOUT_S) as r:
return json.loads(r.read().decode())["path"]
except urllib.error.HTTPError as e:
if e.code in (404, 405):
raise HTTPException(409, {
"message": f"{label} can't receive attached files yet — "
"its worker predates them",
"kind": "worker_outdated",
"hint": "update the worker (Settings → Profiles → Update now), "
"then send again"})
raise HTTPException(502, {"message": f"couldn't copy {name} to {label} "
f"(HTTP {e.code})",
"kind": "worker_upload"})
except (urllib.error.URLError, OSError, ValueError, KeyError) as e:
raise HTTPException(502, {"message": f"couldn't copy {name} to {label}: "
f"{getattr(e, 'reason', e)}",
"kind": "worker_upload"})
def for_worker(deps: AppState, prompt: str, worker: str) -> str:
"""``prompt`` with each stored upload it names copied onto ``worker`` and
named by its path there."""
files = named(prompt)
w = deps.worker_store.get(worker) if files else None
if not w:
return prompt
there = {key: _push(w, *key) for key in files}
return _rename(prompt, lambda b, n: there.get((b, n)))
def place(deps: AppState, prompt: str, worker: str | None,
scope: dict | None = None) -> str:
"""``prompt`` ready for the runner it goes to (the lab when ``worker`` is
None), and for the guest its ``scope`` confines it to."""
return (for_worker(deps, prompt, worker) if worker
else for_lab(prompt, guest_of(scope)))