"""Keeping what an agent delivered and linking to it (ADR-0004): the store, the signer and the address a caller reaches them at, together.""" from __future__ import annotations import json import logging import re from collections.abc import Mapping from typing import Any from urllib.parse import parse_qs, quote, unquote, urlsplit from orchestration.links import Signer from orchestration.store import Store logger = logging.getLogger(__name__) LOCAL_TENANT = "local" # what is kept for a caller that names no tenant UNASSIGNED = "unassigned" # for a request that names no Customer case # The Orchestration engine's own record that an Execution completed, sent with its # files to the agent that builds on them. RECORD = "execution.json" _NOT_SLUG = re.compile(r"[^A-Za-z0-9._-]+") _KEPT_PATH = re.compile(r"^/tenants/([^/]+)/cases/([^/]+)/(executions|latest)/([^/]+)$") def _slug(value: Any, default: str) -> str: text = _NOT_SLUG.sub("-", str(value or "")).strip("-.") return text or default class Delivery: def __init__(self, store: Store, signer: Signer, public_url: str) -> None: self.store = store self.signer = signer self.public_url = public_url.rstrip("/") @staticmethod def place(fields: Mapping[str, Any]) -> tuple[str, str]: """The tenant and Customer case what a request delivers is kept under.""" return ( _slug(fields.get("tenant_id"), LOCAL_TENANT), _slug(fields.get("customer_case"), UNASSIGNED), ) def keep( self, fields: Mapping[str, Any], *, work: str, execution_id: str, status: str, request: str, files: Mapping[str, str], guide: str | None, ) -> dict[str, Any] | None: """Keep an agent's Execution; None, logged, when it cannot be kept, so a caller still gets the agent's answer.""" tenant, case = self.place(fields) try: return self.store.keep( tenant=tenant, case=case, execution_id=execution_id, work=work, status=status, request=request, files=files, guide=guide, project_id=fields.get("project_id"), ) except (OSError, ValueError): logger.exception("Could not keep %s Execution %s", work, execution_id) return None # --- building on what was kept (phase 2) --------------------------------------- def resolve(self, reference: str, fields: Mapping[str, Any]) -> dict[str, Any]: """The kept Execution a request names in `sources_from`: a link from an earlier document, `latest/`, or an Execution's id in the request's Customer case. Raises ValueError, saying why, for anything else.""" tenant, case = self.place(fields) named_case = fields.get("customer_case") if reference.startswith(("http://", "https://", "/")): url = urlsplit(reference) query = parse_qs(url.query) exp, sig = (query.get(key, [None])[0] for key in ("exp", "sig")) if not self.signer.verify(url.path, exp, sig): raise ValueError("The link in sources_from is not valid.") match = _KEPT_PATH.match(url.path) if not match: raise ValueError("The link in sources_from is not to kept work.") tenant_of, case, kind, ident = match.groups() if fields.get("tenant_id") and tenant_of != tenant: raise ValueError("The link in sources_from is of another tenant.") tenant = tenant_of if named_case and _slug(named_case, UNASSIGNED) != case: raise ValueError( f"The work in sources_from is of the Customer case {case}, " f"not {named_case}." ) ident = unquote(ident) record = ( self.store.record(tenant, case, ident) if kind == "executions" else self.store.latest(tenant, case, ident) ) elif reference.startswith("latest/"): work = reference.removeprefix("latest/") record = self.store.latest(tenant, case, work) if record is None: raise ValueError( f"No {work} work has completed in the Customer case {case}." ) else: record = self.store.record(tenant, case, reference) if record is None: raise ValueError( f"Nothing is kept for {reference!r} in the Customer case {case}." ) if record["status"] != "completed": raise ValueError( f"The {record['work']} work {record['execution_id']} ended " f"{record['status']}; only work that completed is built on." ) return record def sources(self, record: Mapping[str, Any]) -> dict[str, str]: """A kept Execution as an agent's sources: its files, with the record that it completed.""" files = self.store.files( record["tenant"], record["customer_case"], record["execution_id"] ) completion = { "status": record["status"], "customer_case": record["customer_case"] if record["customer_case"] != UNASSIGNED else None, "execution_id": record["execution_id"], "workflow_request": record["request"], "work": record["work"], } files[RECORD] = json.dumps({k: v for k, v in completion.items() if v}) return files # --- addresses ------------------------------------------------------------- @staticmethod def case_path(tenant: str, case: str) -> str: return f"/tenants/{tenant}/cases/{case}" def execution_path(self, tenant: str, case: str, execution_id: str) -> str: return f"{self.case_path(tenant, case)}/executions/{execution_id}" def file_path(self, tenant: str, case: str, execution_id: str, name: str) -> str: return f"{self.execution_path(tenant, case, execution_id)}/files/{quote(name)}" def latest_path(self, tenant: str, case: str, work: str) -> str: return f"{self.case_path(tenant, case)}/latest/{quote(work)}" def link(self, path: str) -> str: return self.signer.link(self.public_url, path) def links(self, record: Mapping[str, Any]) -> dict[str, Any]: """Signed links to a kept Execution: its record, its guide, each file, the latest of its work and its Customer case.""" tenant, case = record["tenant"], record["customer_case"] execution_id = record["execution_id"] files = { name: self.link(self.file_path(tenant, case, execution_id, name)) for name in record["files"] } return { "record": self.link(self.execution_path(tenant, case, execution_id)), "guide": files.get(record.get("guide") or ""), "files": files, "latest": self.link(self.latest_path(tenant, case, record["work"])), "case": self.link(self.case_path(tenant, case)), } def shown(self, record: Mapping[str, Any]) -> dict[str, Any]: """A record as it is served: what was kept, with links, without internals.""" return { **{k: v for k, v in record.items() if k != "kept_ns"}, "links": self.links(record), }