Files
ai-agent/backend/plugins/hubfiles.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

175 lines
6.6 KiB
Python

"""``hostfiles.read``, ``context.read`` and ``context.write`` — hub bridges
for the ``file-explorer`` and ``context-editor`` live plugins.
* ``hostfiles.read`` (caller-scoped; guests reach their granted projects only,
the owner every served root; secrets & noise dirs always 404):
- ``GET …/hub/host-file?path=`` → one file's metadata + text content (≤ 512 KB)
- ``GET …/hub/host-files?path=`` → one directory listing (folders first)
- ``GET …/hub/host-files/recent?project=&limit=`` → a project's recent docs
- ``GET …/hub/host-files/roots`` → where the caller may start browsing
* ``context.read`` (owner-only, operator approval):
- ``GET …/hub/context/bundle`` → the workspace context catalog (metadata +
real token counts + cost totals + pricing)
- ``GET …/hub/context/file?path=`` → one context file with content
* ``context.write`` (owner-only, operator approval, handler-only):
- ``PUT …/hub/context/file`` ``{"path", "content", "create"?}`` → save an
editable context file and refresh the file index; ``create: true`` makes
a missing agent definition (``.claude/agents/<name>.md`` — the cron-jobs
plugin's new job stub), nothing else
A paired machine's proxy token (``via == "worker"`` — an owner's worker reads
as the owner on the tool-proxy door) is refused on all of them: the retired
``/api/host-file`` / ``/api/bundle`` never answered a machine, nothing on a
machine needs these, and an owner's devbox must not read ``~/homelab``.
"""
from __future__ import annotations
import json
from typing import Any
from fastapi import APIRouter, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from plugins.hubbridge import _caller_for_who, _check_cap
from plugins.proxyroutes import _error
router = APIRouter(include_in_schema=False)
_BASE = "/proxy/tools/plugins/{pid}/hub"
CAP_HOST = "hostfiles.read"
CAP_CTX_READ = "context.read"
CAP_CTX_WRITE = "context.write"
def _gate(request: Request, pid: str, cap: str, **kw):
"""``_check_cap`` plus: no machine token (see the module docstring)."""
deps, who, rec, err = _check_cap(request, pid, cap, **kw)
if not err and getattr(who, "via", None) == "worker":
err = _error(403, f"{cap} isn't open to a machine's token", "capability")
return deps, who, rec, err
def _http_err(e: HTTPException):
d = e.detail
msg = d.get("message") if isinstance(d, dict) else str(d)
kind = (d.get("kind") if isinstance(d, dict) else None) or (
"not_found" if e.status_code == 404
else "forbidden" if e.status_code == 403
else "bad_request" if e.status_code == 400
else "error"
)
return _error(e.status_code, str(msg or "error"), kind)
async def _json_body(request: Request) -> dict[str, Any] | None:
try:
body = await request.json()
except (ValueError, json.JSONDecodeError):
return None
return body if isinstance(body, dict) else None
# ── hostfiles.read (caller-scoped: owner + guests) ───────────────────────────
async def _run_host(request: Request, pid: str, fn):
deps, who, _rec, err = _gate(request, pid, CAP_HOST)
if err:
return err
caller = _caller_for_who(deps, who)
if caller is None:
return _error(403, "unknown user", "auth")
try:
return await run_in_threadpool(fn, caller)
except HTTPException as e:
return _http_err(e)
@router.get(_BASE + "/host-file")
async def hub_host_file(pid: str, request: Request, path: str = ""):
from files.hostfiles import file_payload, resolve
def _call(caller):
r = resolve(caller, path)
if r is None or not r.abs.is_file():
raise HTTPException(404, "file not found")
return file_payload(r)
return await _run_host(request, pid, _call)
@router.get(_BASE + "/host-files")
async def hub_host_files(pid: str, request: Request, path: str = ""):
from files.hostfiles import list_dir, resolve
def _call(caller):
r = resolve(caller, path)
if r is None or not r.abs.is_dir():
raise HTTPException(404, "folder not found")
return list_dir(r)
return await _run_host(request, pid, _call)
@router.get(_BASE + "/host-files/recent")
async def hub_host_files_recent(pid: str, request: Request, project: str = "", limit: int = 12):
from files.hostfiles import project_root, recent_documents
def _call(caller):
r = project_root(caller, project)
if r is None or not r.abs.is_dir():
raise HTTPException(404, "project not found")
return {"root": r.host, "project": project,
"entries": recent_documents(r, max(1, min(limit, 50)))}
return await _run_host(request, pid, _call)
@router.get(_BASE + "/host-files/roots")
async def hub_host_files_roots(pid: str, request: Request):
from files.hostfiles import roots
return await _run_host(request, pid, lambda caller: {"roots": roots(caller)})
# ── context.read / context.write (owner-only) ────────────────────────────────
@router.get(_BASE + "/context/bundle")
async def hub_context_bundle(pid: str, request: Request):
deps, _who, _rec, err = _gate(request, pid, CAP_CTX_READ, owner_only=True)
if err:
return err
from files.routes import bundle_data
return await run_in_threadpool(bundle_data, deps)
@router.get(_BASE + "/context/file")
async def hub_context_file(pid: str, request: Request, path: str = ""):
deps, _who, _rec, err = _gate(request, pid, CAP_CTX_READ, owner_only=True)
if err:
return err
if not path:
return _error(400, "path is required", "bad_request")
from files.routes import read_context_file
try:
return await run_in_threadpool(read_context_file, deps, path)
except HTTPException as e:
return _http_err(e)
@router.put(_BASE + "/context/file")
async def hub_context_file_put(pid: str, request: Request):
deps, _who, _rec, err = _gate(request, pid, CAP_CTX_WRITE,
owner_only=True, handler_only=True)
if err:
return err
body = await _json_body(request)
if body is None or not isinstance(body.get("path"), str) or not isinstance(body.get("content"), str):
return _error(400, "path and content strings are required", "bad_request")
from files.routes import write_context_file
try:
return await run_in_threadpool(lambda: write_context_file(
deps, body["path"], body["content"], create=body.get("create") is True))
except HTTPException as e:
return _http_err(e)