Coverage for app / services / documents.py: 94%
195 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Documents built from what the platform has *stored*, rendered to PDF.
4A PDF is never made from content a client posts. The sources are all
5records: a skill run's outputs, a ```document fence in a chat message (put
6there by svc-ai's ``render_document`` tool; svc-ai's artifact guard removes
7any document fence a model wrote itself), and a dashboard tile's latest
8answer (its fence, or with the tile's PDF on its answer laid out). So a
9downloaded PDF is a rendering of something on record, and its footer says
10which record.
12svc-ai owns the schema (``app/documents/spec.py``) and validates every
13document it renders. This module only assembles the dict and the footer.
15Images: a document's fence names the stored copies of the images its body
16shows (``images[].asset``, the SHA-256 of bytes svc-ai stored when it made
17the document — ``app/util/document_images.py``). The document card draws them
18from here (:func:`image_response`), and only an image a document in that
19record names, whose stored bytes still hash to its id.
20"""
22from __future__ import annotations
24import json
25import logging
26import re
27from datetime import datetime
28from typing import Any
30from app.util import document_images
31from app.util.time import utc_isoformat
33logger = logging.getLogger(__name__)
35#: The report fields a document has (svc-ai ``DocumentSpec``) — and the shape
36#: the built-in report skills return (``system_resources.skillsets``).
37REPORT_TEXT_FIELDS = ("title", "subtitle", "summary", "body")
38REPORT_LIST_FIELDS = ("key_findings", "sources", "open_questions")
39CONFIDENCE_VALUES = frozenset({"low", "medium", "high"})
40#: svc-ai's ``DocumentSpec`` limits, for text assembled here from outputs
41#: that were never written to fit them.
42MAX_TITLE_CHARS = 200
43MAX_BODY_CHARS = 60_000
44_TRUNCATED = "\n\n*(Truncated: the full text is on the run's page.)*"
46_FENCE_RE = re.compile(r"```document[ \t]*\n(.*?)\n```", re.DOTALL)
48#: svc-ai's tool that writes a document (its ``render_document``): what a
49#: dashboard tile with its PDF on asks the agent to finish with.
50DOCUMENT_TOOL = "render_document"
53def document_fences(text: str | None) -> list[dict[str, Any]]:
54 """The ```document fences in ``text``, parsed, in order. A fence that is
55 not a JSON object is skipped; svc-ai validates the rest."""
56 documents: list[dict[str, Any]] = []
57 for match in _FENCE_RE.finditer(text or ""):
58 try:
59 value = json.loads(match.group(1))
60 except ValueError:
61 continue
62 if isinstance(value, dict):
63 documents.append(value)
64 return documents
67def split_document_fences(text: str | None) -> tuple[str, list[str]]:
68 """``text`` without its ```document fences, and those fences as written,
69 in order — each one whose body is a JSON object (the rule
70 :func:`document_fences` reads by), so a fence kept is one that parses."""
71 fences: list[str] = []
72 for match in _FENCE_RE.finditer(text or ""):
73 try:
74 value = json.loads(match.group(1))
75 except ValueError:
76 continue
77 if isinstance(value, dict):
78 fences.append(match.group(0))
79 prose = _FENCE_RE.sub("", text or "")
80 return re.sub(r"\n{3,}", "\n\n", prose).strip(), fences
83def _humanise(key: str) -> str:
84 return key.replace("_", " ").strip().capitalize() or key
87def _as_markdown(value: Any) -> str:
88 if isinstance(value, str):
89 return value
90 if isinstance(value, list) and all(
91 isinstance(v, (str, int, float, bool)) for v in value
92 ):
93 return "\n".join(f"- {v}" for v in value)
94 if isinstance(value, (int, float, bool)):
95 return str(value)
96 return "```\n" + json.dumps(value, ensure_ascii=False, indent=2) + "\n```"
99def _empty(value: Any) -> bool:
100 return value is None or value == "" or value == [] or value == {}
103def from_outputs(outputs: dict[str, Any] | None, *, title: str) -> dict[str, Any]:
104 """A document from a skill's declared outputs.
106 Fields in the report shape are used as they are. Every other output
107 becomes a section of the body, headed by its name, so any skill's run can
108 be downloaded. A report skill's run is its report, and any other skill's
109 run is its outputs laid out. A report field of the wrong type is treated
110 as an ordinary output rather than dropped.
111 """
112 document: dict[str, Any] = {}
113 sections: list[str] = []
114 for key, value in (outputs or {}).items():
115 if _empty(value):
116 continue
117 if key in REPORT_TEXT_FIELDS and isinstance(value, str):
118 document[key] = value
119 elif key in REPORT_LIST_FIELDS and isinstance(value, list):
120 document[key] = [str(v) for v in value if not _empty(v)]
121 elif key in REPORT_LIST_FIELDS and isinstance(value, str):
122 document[key] = [value]
123 elif key == "confidence" and value in CONFIDENCE_VALUES:
124 document[key] = value
125 else:
126 sections.append(f"## {_humanise(key)}\n\n{_as_markdown(value)}")
127 document.setdefault("title", title)
128 body = "\n\n".join(p for p in [document.get("body", ""), *sections] if p)
129 if body:
130 document["body"] = _fit_body(body)
131 document["title"] = str(document["title"])[:MAX_TITLE_CHARS]
132 return document
135def _fit_body(body: str) -> str:
136 if len(body) <= MAX_BODY_CHARS:
137 return body
138 return body[: MAX_BODY_CHARS - len(_TRUNCATED)] + _TRUNCATED
141def for_skill_run(run: Any, index: int = 0) -> dict[str, Any] | None:
142 """The ``index``-th document a finished skill run produced, or None.
144 A ```document fence in the answer (the skill called ``render_document``)
145 is a document, numbered as they appear. A run with none has one: its
146 outputs laid out, or failing those its answer as the body.
147 """
148 fenced = document_fences(run.output)
149 if fenced:
150 return fenced[index] if 0 <= index < len(fenced) else None
151 if index != 0:
152 return None
153 if run.outputs:
154 return from_outputs(run.outputs, title=run.skill_name)
155 if run.output and run.output.strip():
156 return {
157 "title": run.skill_name[:MAX_TITLE_CHARS],
158 "body": _fit_body(run.output),
159 }
160 return None
163def for_swarm_run(run: Any, index: int = 0) -> dict[str, Any] | None:
164 """The ``index``-th document a finished swarm run's answer holds, or None.
166 A ```document fence in the answer (the lead called ``render_document``)
167 is a document, numbered as they appear. An answer with none has one: the
168 answer as the body, titled by the swarm, so every run that answered can
169 be downloaded.
170 """
171 fenced = document_fences(run.output)
172 if fenced:
173 return fenced[index] if 0 <= index < len(fenced) else None
174 if index != 0 or not (run.output or "").strip():
175 return None
176 return {"title": run.swarm_name[:MAX_TITLE_CHARS], "body": _fit_body(run.output)}
179def widget_document(widget: Any, index: int = 0, *, pdf: bool) -> dict | None:
180 """The ``index``-th document a dashboard tile's latest answer holds, or
181 None.
183 A ```document fence in the answer (its agent called ``render_document``)
184 is a document, numbered as they appear. A tile whose PDF is on and whose
185 answer has none has one: its answer as the body, titled by the tile — so
186 every refresh of it can be downloaded, whether or not the agent made a
187 document that time, and a model (which has no tools) can be too.
188 """
189 payload = getattr(widget, "cache_payload", None) or {}
190 markdown = payload.get("markdown") if isinstance(payload, dict) else None
191 if not isinstance(markdown, str):
192 return None
193 fenced = document_fences(markdown)
194 if fenced:
195 return fenced[index] if 0 <= index < len(fenced) else None
196 if index != 0 or not pdf:
197 return None
198 prose, _ = split_document_fences(markdown)
199 if not prose:
200 return None
201 title = str(getattr(widget, "title", "") or "Dashboard tile")
202 return {"title": title[:MAX_TITLE_CHARS], "body": _fit_body(prose)}
205def widget_refreshed_at(widget: Any) -> datetime | None:
206 """When the tile's answer was written: the answer's own ``generated_at``,
207 else the cache's time. Not the cache's time first — a refresh claims the
208 tile by moving it (``refresh.mark_refreshing``) while the answer shown is
209 still the last one."""
210 payload = getattr(widget, "cache_payload", None) or {}
211 raw = payload.get("generated_at") if isinstance(payload, dict) else None
212 if isinstance(raw, str):
213 try:
214 return datetime.fromisoformat(raw)
215 except ValueError:
216 pass
217 return getattr(widget, "cached_at", None)
220def widget_footer(dashboard: Any, widget: Any) -> str:
221 """Which board and tile the document is from, what answered, and when it
222 was refreshed. svc-ai prints the AI disclosure above it."""
223 payload = getattr(widget, "cache_payload", None) or {}
224 runs_on = payload.get("runs_on") if isinstance(payload, dict) else None
225 when = widget_refreshed_at(widget)
226 parts = [
227 "CHAIN-R",
228 f"board “{getattr(dashboard, 'name', '') or 'Dashboard'}”",
229 f"tile “{getattr(widget, 'title', '') or 'Untitled'}”",
230 *([str(runs_on)] if runs_on else []),
231 *([f"refreshed {when.strftime('%d %b %Y %H:%M UTC')}"] if when else []),
232 ]
233 return " · ".join(parts)
236def skill_run_footer(run: Any) -> str:
237 version = f" v{run.skill_version}" if run.skill_version else ""
238 when = (run.finished_at or run.started_at).strftime("%d %b %Y %H:%M UTC")
239 return (
240 f"CHAIN-R · skill “{run.skill_name}”{version} · run {str(run.id)[:8]} · {when}"
241 )
244def swarm_run_footer(run: Any) -> str:
245 """Which swarm revision answered, which run, and when; partial when it
246 answered from part of the work."""
247 version = f" v{run.swarm_version}" if run.swarm_version else ""
248 when = (run.finished_at or run.created_at).strftime("%d %b %Y %H:%M UTC")
249 partial = " · partial" if run.status == "partial" else ""
250 return (
251 f"CHAIN-R · swarm “{run.swarm_name}”{version} · run {str(run.id)[:8]}"
252 f"{partial} · {when}"
253 )
256def message_footer(conversation: Any, message: Any) -> str:
257 """Which agent revision and model wrote the message, and where it is kept.
258 svc-ai prints the AI disclosure above it."""
259 who = getattr(getattr(conversation, "agent", None), "name", None) or "Chat"
260 meta = getattr(message, "meta", None) or {}
261 version = meta.get("agent_version")
262 if isinstance(version, int):
263 who = f"{who} v{version}"
264 model = meta.get("model_name")
265 when = message.sent_at.strftime("%d %b %Y %H:%M UTC") if message.sent_at else ""
266 parts = [
267 "CHAIN-R",
268 who,
269 *([str(model)] if model else []),
270 f"conversation {str(conversation.id)[:8]}",
271 f"message {str(message.id)[:8]}",
272 *([when] if when else []),
273 ]
274 return " · ".join(parts)
277def generated_at(value: Any) -> str | None:
278 return utc_isoformat(value) if value else None
281def filename(document: dict[str, Any]) -> str:
282 stem = re.sub(r"[^A-Za-z0-9]+", "-", str(document.get("title") or "")).strip("-")
283 return f"{stem[:80] or 'document'}.pdf"
286def pdf_response(document: dict[str, Any], *, footer: str, when: Any) -> Any:
287 """Render ``document`` and answer it as a download.
289 422 when svc-ai refuses the document (it no longer validates — a record
290 written before a schema change, say), 502 when svc-ai cannot render.
291 """
292 from fastapi import HTTPException, status
293 from fastapi.responses import Response
295 from app.services import ai_client
297 try:
298 data = ai_client.render_document_pdf(
299 document, footer=footer, generated_at=generated_at(when)
300 )
301 except ai_client.DocumentRejected as exc:
302 raise HTTPException(
303 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
304 detail="This document cannot be rendered: it is not a valid document.",
305 ) from exc
306 except ai_client.AIServiceError as exc:
307 raise HTTPException(
308 status_code=status.HTTP_502_BAD_GATEWAY,
309 detail="The document could not be rendered. Try again shortly.",
310 ) from exc
311 return Response(
312 content=data,
313 media_type="application/pdf",
314 headers={"Content-Disposition": f'attachment; filename="{filename(document)}"'},
315 )
318# --------------------------------------------------------------------------- #
319# The images a document shows
320# --------------------------------------------------------------------------- #
323def referenced_assets(documents: list[dict[str, Any]]) -> set[str]:
324 """The stored images ``documents`` name. Read defensively: a fence is
325 stored data, and only well-formed ids count."""
326 assets: set[str] = set()
327 for document in documents:
328 images = document.get("images")
329 if not isinstance(images, list):
330 continue
331 for entry in images:
332 asset = entry.get("asset") if isinstance(entry, dict) else None
333 if document_images.is_asset_id(asset):
334 assets.add(asset)
335 return assets
338class ImageUnavailable(RuntimeError):
339 """Storage could not be read."""
342def stored_image(asset: str) -> tuple[bytes, str] | None:
343 """The stored copy ``asset`` names and its media type — only when its
344 bytes hash to the id and are a served type. None when it is not stored."""
345 from app.util import minio_client
347 try:
348 data = minio_client.read_named(document_images.object_key(asset))
349 except ValueError:
350 return None
351 except Exception as exc:
352 raise ImageUnavailable("document image storage could not be read") from exc
353 media_type = document_images.verified(asset, data)
354 if data is None or media_type is None:
355 return None
356 return data, media_type
359def image_response(documents: list[dict[str, Any]], asset: str) -> Any:
360 """``asset``, served as an untrusted image, when one of ``documents`` (a
361 record's) names it. 404 for an image the record does not name or that is
362 not stored; 503 when storage cannot be read."""
363 from fastapi import HTTPException, status
365 from app.util.untrusted_image import untrusted_image_response
367 if asset not in referenced_assets(documents):
368 raise HTTPException(
369 status_code=status.HTTP_404_NOT_FOUND, detail="No such image."
370 )
371 try:
372 found = stored_image(asset)
373 except ImageUnavailable as exc:
374 logger.warning("A document image could not be read from storage")
375 raise HTTPException(
376 status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
377 detail="The image is unavailable. Try again shortly.",
378 ) from exc
379 if found is None:
380 raise HTTPException(
381 status_code=status.HTTP_404_NOT_FOUND, detail="No such image."
382 )
383 return untrusted_image_response(*found)