Media assets
About 8034 wordsAbout 27 min
Many plugins generate binary output: images from a diffusion API, audio from a TTS service, video from a generative model, screenshots from a headless browser, PDFs from a renderer. Returning raw URLs in plain text gets the job done but produces ugly, non-interactive chat bubbles — and any payload the upstream API hands back as inline bytes (hex or base64) is otherwise lost.
Spora provides a small, opinionated pipeline for this:
binary bytes ─► AssetStore::store() ─► AssetReference (url, mode)
│
ToolResult.content ◄──── MediaEmbed::* ◄──────────┘
│ │
▼ ▼
chat UI renders operators configure
inline media via SPORA_* env varsThis page walks through each piece.
An asset is filed in a folder — a named container scoped to one principal — and carries an advisory kind mark. The folder tree, its two uniqueness rules and the themes that live in a folder are in Media folders.
1. The two ingredients
Spora\Services\AssetStore
A service interface in app/Services/AssetStore.php. Three implementations ship in core:
| Implementation | Mode | Behaviour |
|---|---|---|
DataUrlAssetStore | data_url | Returns the payload inline as data:<mime>;base64,…. No disk write. |
LocalAssetStore | local | Writes to <storage>/assets/<token>.<ext> and returns a URL like /api/v1/assets/<token>.<ext> (served by Spora\Http\AssetController). |
AutoAssetStore | auto (default) | Composes the two above and dispatches per call based on a size threshold. |
The container binds AssetStore::class to whichever mode the operator picks via SPORA_ASSET_STORE_MODE. Plugins depend on the interface, never on a concrete class.
The <ext> half of <storage>/assets/<token>.<ext> comes from the stored filename when it carries an extension, and from the MIME map otherwise — so an upload named photo.jpeg lands as <token>.jpeg, not <token>.jpg. Every reader has to ask for that suffix rather than derive one from the MIME: the image channel and the delete path both go through LocalAssetStore::storedExtension().
Spora\Tools\MediaEmbed
A final, stateless utility class in app/Tools/MediaEmbed.php. These return the canonical HTML the chat UI knows how to render (see Frontend markdown allow-list for the source of truth).
forAsset(MediaAsset $asset, MediaType $type, string $url, string $alt): string is the single MediaType → embed dispatch, and the entry point to prefer. Every operation that surfaces an asset routes through it — get_media, get_embed_code, create_media, create_derivative — so one artifact looks the same however it came to exist. Matching on MediaType at your own call site is how a PDF ends up rendered as a download card by one operation and a bare link by the next.
MediaType | Rendered as |
|---|---|
Image | image() — inline markdown image |
Audio | audioFromUrl() — <audio controls> |
Video | videoFromUrl() — <video controls> |
Document (text/*, application/*) | fileCard() — one-line download card |
Unknown | link() — plain markdown link |
Document is the bucket PDFs and Word documents land in, and the card it produces is styled entirely by Tailwind utilities that spora-frontend registers in src/style.css — see Styling the download card for what that obliges of you if you build your own. AssetController::applyContentDisposition() forces Content-Disposition: attachment server-side, so a card that loses its styling still downloads rather than navigating. Unknown stays a link deliberately: it means the media_type column itself was null or unrecognised, and nothing about such a row is reliably a download.
fileCard() emits one line, and no icon element — the download glyph is a CSS ::before pseudo-element on the link, because aria-hidden is not in the sanitizer’s ALLOWED_ATTR and would be silently stripped, and because a generated text glyph would still be announced by a screen reader. download is likewise omitted, for the same server-side reason.
2. Configuration
| Env var | Default | Effect |
|---|---|---|
SPORA_ASSET_STORE_MODE | auto | auto / data_url / local. Invalid values throw at boot. |
SPORA_ASSET_STORE_AUTO_THRESHOLD_BYTES | 1048576 (1 MiB) | In auto mode, payloads ≤ this many bytes use data_url; larger payloads use local. |
SPORA_ASSET_STORE_MAX_BYTES | 16777216 (16 MiB) | Per-asset ceiling. Matches the MEDIUMBLOB ceiling of media_assets.payload (migration 0064 + MediaArchiveService::DATA_URL_MAX_BYTES); the DatabaseAssetStore factory throws if this is set above 16 MiB. |
Settings are merged from defaults → config.php → env vars, same as every other SPORA_* setting. See ContainerDefinitions::configDefinition() for the merge order.
The 16 MiB default applies to every mode —
data_urlbecause thepayloadBLOB column is MEDIUMBLOB (16 MiB on MySQL/MariaDB; SQLite has no intrinsic cap), andlocalbecause the sameAssetStoreinterface enforces the same ceiling. Operators onlocalmode who need larger individual assets raise this viaSPORA_ASSET_STORE_MAX_BYTES; the factory will fail fast on boot if the value exceeds the column ceiling for the active mode.
3. Pattern A — you have a URL
The simplest case. The upstream API already gave you a CDN URL; just embed it:
use Spora\Tools\MediaEmbed;
$content = "Generated image:\n\n" . MediaEmbed::image($cdnUrl, "alt text");MediaEmbed::image() produces  — standard markdown that the renderer turns into <img>. No AssetStore involvement, no bytes in the DB, no auth surface.
User-supplied filenames flowing into media_assets.filename are scrubbed by Utf8Sanitizer::scrubString in MediaUploadController::store() before MediaIngestRequest is built, with a defensive re-scrub in MediaArchiveService::insertNew(). The serializer re-scrubs on read as defense-in-depth. See UTF-8 sanitizer.
The same pattern works for already-hosted audio and video:
$content = "Here is the audio:\n\n" . MediaEmbed::audioFromUrl($cdnUrl);
$content = "Here is the video:\n\n" . MediaEmbed::videoFromUrl($cdnUrl, 1920, 1080);4. Pattern B — you have bytes (or hex from the API)
The upstream API hands back a blob — either raw bytes (e.g. fetched yourself) or a hex/base64-encoded string in the response body. Two ways to wire it:
Option 1 — call MediaEmbed::*FromBytes() directly
use Spora\Tools\MediaEmbed;
$bytes = hex2bin($response['data']['audio']); // upstream gave us hex
$content = "Synthesized speech.\n\n"
. MediaEmbed::audioFromBytes($bytes, $this->assetStore, 'speech.mp3');MediaEmbed::audioFromBytes() calls AssetStore::store() internally and returns the embedded <audio>. The AssetStore decides between data: URL and /api/v1/assets/… URL based on the operator’s mode setting.
Option 2 — use the StoresBinaryAssets trait (opt-in)
use Spora\Plugins\Concerns\StoresBinaryAssets;
use Spora\Tools\MediaEmbed;
final class MyAudioTool extends AbstractTool {
use StoresBinaryAssets;
protected function doWork(/* … */): ToolResult {
$hex = $this->fetchUpstreamHex();
// Returns [url, mode] — give `mode` to the UI in ToolResult::$data.
[$url, $mode] = $this->embedHex($hex, mime: 'audio/mpeg', filename: 'speech.mp3');
$content = "Audio ready.\n\n" . MediaEmbed::audioFromUrl($url);
return new ToolResult(true, $content, ['asset_mode' => $mode]);
}
}embedHex() does the odd-length-hex guard, hex2bin() decode, and AssetStore::store() in one call. It returns [url, mode] so you can surface mode in ToolResult::$data (the UI may use it to render a “local copy” badge vs. inline).
When to prefer bytes over URL
Most third-party APIs (MiniMax, ElevenLabs, OpenAI TTS) can return either inline bytes or a hosted URL. Prefer the URL when it’s available and the URL will be valid for the duration of the user’s task (typically 24 hours for CDN links). Fall back to bytes + AssetStore when:
- The API only returns inline bytes (e.g. some TTS endpoints).
- The hosted URL expires faster than your tool needs it (e.g. 1-hour URLs for assets you want to keep around for chat history).
- The payload is multi-megabyte and you want to avoid bloating the chat-history DB row with a base64 data URL.
5. Plumbing in your plugin
PHP-DI auto-resolves typed constructor parameters, so:
use Spora\Services\AssetStore;
final class MyTool extends AbstractTool {
public function __construct(
private readonly AssetStore $assetStore,
// … other deps …
) {}
}is enough — the container will inject the configured AssetStore automatically. No plugin-level DI configuration is required.
If your tool uses the StoresBinaryAssets trait, the trait’s setAssetStore(AssetStore) setter is auto-wired by PHP-DI too — you do not need to inject AssetStore explicitly through your constructor (though you can if you want to).
Correcting a coarse sniffed MIME
Uploads are gated on the sniffed MIME (MediaUploadController::checkMimeAllowed()), so a format your libmagic build reports as its container type is rejected outright. Word OOXML is the common case: a 200-byte prefix reads as application/zip, and older libmagic versions report that for every OOXML flavour. MimeSniffer::MAGIC_SIGNATURES cannot help — the PK\x03\x04 local-file-header signature matches every zip archive in existence.
A refiner upgrades the verdict:
final class OfficeMimeRefiner implements Spora\Services\MediaArchive\MediaMimeRefinerInterface
{
// No constructor — see the contract below.
public function refine(string $bytes, ?string $filename, string $sniffedMime): ?string
{
if ($sniffedMime !== 'application/zip') {
return null; // not our concern; decline
}
// `PK\x03\x04` alone proves nothing — check for the part that
// distinguishes Word from xlsx / pptx / epub, or you will relabel
// every spreadsheet upload as a document.
//
// ZipArchive opens a path, not a string, so the bytes have to be
// staged. Bound it: refiners run before any size rejection, so this
// write is on the path for every archive a user ever attaches.
$stagedPath = tempnam(sys_get_temp_dir(), 'spora-refine-');
if ($stagedPath === false || file_put_contents($stagedPath, $bytes) === false) {
return null;
}
$zip = new ZipArchive();
if ($zip->open($stagedPath, ZipArchive::RDONLY) !== true) {
unlink($stagedPath);
return null;
}
try {
return $zip->locateName('word/document.xml') !== false
? 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
: null;
} finally {
$zip->close();
unlink($stagedPath);
}
}
}MediaMimeRefinerDiscovery::add(OfficeMimeRefiner::class);Contract, and the reasons behind each part:
- No-arg constructor, required.
MimeSnifferinstantiates refiners withnew $class()and has no container to resolve their collaborators with, so a refiner that needs a collaborator has to reach for it statically itself. (The sniffer itself is not argument-free — it takes an optional logger, which is why the constraint is on your refiner and not on it.) - Run in registration order until one returns non-
null;nullmeans decline, and the next refiner gets its turn. $bytesis the full payload, not the 4 KiB prefix the sniffer works from — but you should still bound what you do with it. Refiners run inside the upload allowlist gate, before any size rejection, so an unbounded read is on the path for every archive a user ever attaches.- Runs after the built-in Typst
text/plain→text/x-typstupgrade, so$sniffedMimeis the most specific verdict core can produce. - A refiner that throws is caught and declined, not propagated. Plugin code is untrusted: an uncaught exception here would travel through
ingestFromBytes()and fail every media upload in the process over one MIME verdict. The same tolerance applies to the plugin-supplied derivative producer that runs later in the ingest:MediaDerivativeService::ensureTextDerivative()swallows and logs a throw rather than failing the upload.
This is one of two discovery registries — MediaDerivativeProducerDiscovery and MediaMimeRefinerDiscovery — and both share one registration shape through the DiscoversRegistrations trait. They have independent storage, which is worth knowing if you extend them: a private static property declared on a shared parent class would be inherited by every subclass and silently merge the two lists into one.
Filing an asset into a folder
An asset is filed in a folder through core’s Spora\Services\MediaArchive\MediaFolderService, never through a column write:
use Spora\Models\MediaAsset;
use Spora\Services\MediaArchive\MediaFolderService;
final class MyFilingTool extends AbstractTool {
public function __construct(
private readonly MediaFolderService $folders,
) {}
protected function doWork(ToolContext $ctx, array $args): ToolResult {
$asset = MediaAsset::find($args['asset_id']);
if ($asset === null) {
return new ToolResult(false, 'No such asset.');
}
// A null folder id files the asset back into the root.
$this->folders->fileAsset((int) $asset->principal_id, $asset, $args['folder_id'] ?? null);
return new ToolResult(true, 'Filed.');
}
}$asset->fill(['folder_id' => $id]); $asset->save(); does not work. It bypasses the uniqueness rule the service owns and lands on the raw UNIQUE (folder_id, filename) index, so the caller gets a driver-level error — a 500 where the rule says 422.
What the service gives you:
MediaFolderNotFoundException— the folder is not the principal’s. A folder of another principal is reported as missing, not as forbidden.MediaFolderUniquenessException— the folder already holds an asset with that filename.
Both are domain errors; catch them and turn them into a message the operator can act on.
fileTarget($principalId, $folderId, $filename) is the same check without the write: it returns the folder, or raises the two exceptions above. Its fourth argument, $exceptAssetId, exists for the case where the asset already sits in that folder — without it, the asset would conflict with itself.
Deleting a folder does not delete its assets: they fall back to the root, and the subfolders go with it. The service does that move itself, because SQLite cannot add a foreign key to an existing table — the media_assets.folder_id constraint only exists on MySQL/MariaDB — so the behaviour has to be the service’s on every engine.
6. Derivatives
A derivative is a second media_assets row linked back to its parent through the media_derivatives join table. It is a full asset: its own bytes in the same AssetStore the original used, its own UUID, its own asset_url, reachable through the same routes and the “Convert to” dropdown in the operator UI.
Every kind of derivative goes through one owner: Spora\Services\MediaArchive\MediaDerivativeService. The producer registry, the REST controller (MediaDerivativeController), the LLM-facing create_derivative / list_derivatives operations, and the text-extraction path all call into it, so a new producer or a new attribution field is a single-site change.
The producer contract
MediaDerivativeProducerInterface is a model → model contract, not a bytes → string one. That is the whole point of routing extraction through derivatives: a producer receives the parent MediaAsset and returns a DerivativeOutput carrying the bytes plus the metadata needed to populate the new row’s columns.
final class MyOcrProducer implements Spora\Services\MediaArchive\MediaDerivativeProducerInterface
{
public function supportedSourceFormats(): array
{
// MIMEs *and* bare extensions — see the allowlist warning below.
return ['image/png', 'application/pdf', 'png', 'pdf'];
}
public function supportedDerivativeFormats(): array
{
return ['md'];
}
public function pluginSlug(): string { return 'my-ocr'; }
public function operationName(): string { return 'ocr.extract'; }
public function produce(MediaAsset $source, string $format, array $options = []): DerivativeOutput
{
$bytes = file_get_contents($this->resolvePath($source));
return new DerivativeOutput(
bytes: $this->engine->recognise($bytes),
mime: 'text/markdown',
);
}
}DerivativeOutput is immutable and readonly: bytes and mime are required; width, height, and durationSeconds are optional and stay null when your producer does not know them. The service derives byte_size, media_type, and the extension from those two, so a producer never sets them by hand.
- Producers may take constructor arguments. The service resolves each registered class through the DI container, so
TypstRenderProducer’sTypstWorldFactorydependency is wired normally. This is the opposite of the refiner rule above, and worth keeping straight. supportedSourceFormats()/supportedDerivativeFormats()are advisory. The service uses them to short-list candidates;produce()is the source of truth on accept/reject, because the hint list can go stale and a producer may need to introspect bytes the caller never looked at.produce()may throw anyThrowable. The REST layer maps a throw to 422, the LLM tool to aToolResult::fail(). The one exception is the eager text-extraction path, which is best-effort by design — see below.- The filename is derived, not chosen.
MediaDerivativeServicebuilds it from the parent’s basename plus the format slug, so areport.pdfgetsreport.md. A producer that needs a different name has no seam for it; that is intentional, so the join row and the filename stay consistent.
The natural key and attribution
The join row’s natural key is (parent_id, format, producer_plugin, producer_operation). Rendering the same source with the same producer overwrites the existing derivative rather than stacking a second row — which is what makes a blind retry of create_derivative the safe pattern, and what refresh() keys on.
Attribution rides along on the same key, so it is set by the producer rather than by the caller:
| Column | Written from |
|---|---|
producer_plugin | pluginSlug() — your stable plugin slug |
producer_operation | operationName() — a stable operation name |
Both are mirrored onto the derivative’s own media_assets row as plugin_slug and tool_name, matching how core attributes any other asset. Two producers that render the same format from the same source — an OCR producer and a text-layer producer, say — produce two distinct derivatives rather than overwriting each other, which is usually what you want.
Field inheritance
createNew() writes a fresh media_assets row, so it has to decide, field by field, what the derivative inherits from its parent. The per-field table is deliberate; do not “helpfully” copy the whole parent:
| Field | Action | Why |
|---|---|---|
principal_id | precedence chain | Parent’s value wins; else the supplied PrincipalContext; else PrincipalService::ensureUserPrincipal($userId); else null. Same chain the ingest pipeline uses, so LIST and CREATE agree on a row’s principal. |
user_id | inherit | The caller’s userId wins where supplied; otherwise the parent’s. AssetController gates reads on the owner, so a derivative with a null user_id is unreadable by the non-admin who created it. |
agent_id | inherit | MediaTool gates agent-scoped reads on asset.agent_id. Without it a scope=agent agent gets “not found” on a derivative it caused. scope=agent is no longer the default, but an agent explicitly scoped to it still needs this. |
is_temporary | inherit | MediaArchiveRetention’s sweep filters on (user_id, agent_id, is_temporary). A row with null user_id and null agent_id matches no sweep and grows without bound. |
task_id | do not inherit | The derivative outlives the turn. Leaving it null keeps LIST scoping simple. |
tool_call_id | do not inherit | It would collide with the ingest dedup key (tool_call_id, source_url). |
tags / prompt | do not inherit | They describe the source, not a render of it. |
public_access_token | must not inherit | Inheriting it would mint a second unauthenticated read path for a derived document that nobody chose to share. |
The md format, and what gets extracted
md is the format slug for a Markdown derivative: the producer emits text/markdown, and MediaType::fromMime('text/markdown') classifies it as a Document, so it previews and downloads as one. Core registers the slug with a human label so the “Convert to” dropdown reads Markdown, not MD. A derivative’s filename always ends in .md.
md is not a special case — it is the format all text extraction routes through. MediaDerivativeService::ensureTextDerivative(MediaAsset) is the single get-or-create entry point, and it runs at two places: at the end of ingest, and at attach time, on both paths that accept media_ids — POST /api/v1/tasks (create) and POST /api/v1/tasks/{taskId}/continue (the follow-up turn). The attach-time call is what stops a document attached to a running task from arriving with no readable text. It is best-effort: a throw is swallowed and logged, so a corrupt PDF never fails an upload. A scanned PDF with no text layer is the one case nothing rescues — the producer returns nothing, and the operator’s route is to archive a .md alongside it.
ReadUrlTool::fetch_pdf keeps working, and does so through one implementation rather than two: a private core PdfMarkdownExtractor that the md producer and the tool share. It stays SSRF-guarded and still caps fetched PDFs at 50 MiB.
The invariant
A text-ish source within the inline budget is its own text. Anything else gets an
mdderivative — and if it still doesn’t fit, the LLM is told where to read it.
MessageHistoryBuilder applies it in three branches when it turns an attachment into LLM-facing text:
- In-bounds text — a
text/*or allowlisted text-application mime, within the inline budget, with no NUL byte in the first 4 KB — is inlined raw. No derivative, no second copy. This is the branchcreate_mediaand anote.txtland in, and it is why there is deliberately no passthrough producer for text: one that re-emitted in-bounds text would store the same bytes twice, which is the duplication the derivative path exists to avoid. - Binary documents —
application/pdf, docx — are read through theirmdderivative. - Out of bounds — past the budget, NUL-containing text that no byte cap can rescue, or a binary with no
mdderivative to read — falls through to a metadata-only block whose message namesget_source, so the LLM is told where the content is instead of reporting “no extractable text” and stopping.
The inline budget is 512 KB (MAX_INLINE_TEXT_BYTES), and it applies to both the raw-text branch and the derivative branch. The raw-text branch was previously capped at 256 KB, and the derivative branch was not capped at all, which meant a 200-page PDF’s full markdown was inlined uncapped — the latent context bug. The fix loosens text and tightens PDFs in one move: a text source up to 512 KB now arrives inline with no extra tool round-trip, and an oversized PDF’s markdown is bounded.
Two caps still bound the same content and are not interchangeable. The 512 KB inline budget governs what reaches the model in a turn; the ~8 KiB preview cap governs the excerpt get_media inlines next to a binary asset’s card. Do not harmonise them — they answer different questions.
Because the derivative path is a second MediaAsset::find() plus a real file_get_contents() per attachment per turn, it is not a like-for-like swap for a column that was already deserialized: the inline read checks byte_size before touching disk, so an oversized derivative costs a column read rather than a file read.
The producer union is a second allowlist surface
MediaAllowedTypesService builds the upload allowlist from several sources: the static text list, the static audio list, the operator’s image config, the operator’s script-capable toggle, and — the part worth knowing about — the union of every registered producer’s supportedSourceFormats(). Declaring a source format in your producer is what keeps that format uploadable at all, with one deliberate exception: the union drops image/*, because image uploads belong to the agent’s supportsImageInput() gate and the operator’s allowed_image_types config, and a thumbnail producer must not route around that policy. It is also the only reason application/pdf and the docx mime are allowlisted at all, since neither appears in any static list — the pdf one because core registers PdfToMarkdownProducer itself, the docx one because spora-plugin-office registers OfficeToMarkdownProducer.
That makes the union a second, parallel allowlist surface, and it has to stay in sync with the MIME-refiner chain. Nothing structurally enforces the coupling: a .docx that sniffs as application/zip is fixed by OfficeMimeRefiner before the gate and still works, but no code path asserts that a refiner’s target mime is also in some producer’s source list. If you ship a refiner that upgrades a format into a mime, confirm a producer claims that mime yourself: not even a test asserts the pairing, and no owner is designated for the invariant.
supportedSourceFormats() returns bare extensions as well as mimes — TypstRenderProducer returns ['text/x-typst', 'typ'], MarkdownToOfficeProducer returns ['text/markdown', 'md', 'markdown'] — and producer resolution checks both. The allowlist union does not: it must filter on entries containing /, or md, typ, and markdown leak into the LLM-facing Allowed: %s string in create_media’s rejection message. The leak is invisible in the upload UI: allowedExtensions() maps every mime through extensionForMime(), and a bare extension yields null there, so it is dropped from the accept= attribute rather than surfacing as a bogus name. It only ever surfaces in the LLM contract.
The script-capable formats are the operator’s decision
HTML and SVG are the formats that can carry script, and both are governed by an explicit operator toggle rather than by the static lists. SPORA_MEDIA_ARCHIVE_ALLOW_ACTIVE_TYPES decides whether they may exist at all; SPORA_MEDIA_ARCHIVE_ALLOW_EMBED_SCRIPTS decides whether an embedded copy may run them. (The serving boundary also covers XHTML, the XML flavour of HTML; the toggle offers HTML and SVG, not XHTML, and the two lists are deliberately separate.)
“Embedded” is the load-bearing word, and it is not the same thing as “served”. An SVG carries script when it is loaded as a document — framed, or opened from the embed route itself — and a browser refuses to run it when it is loaded as a picture. The archive keeps an SVG as image/svg+xml, so the chat’s own markdown path renders it as an inline <img> and the script does not run there; the embed route serves it as a document, and its script runs if the operator permitted scripts. Measured on the same bytes: SCRIPT LIVE — top level on the embed route, initialising… through an <img>. HTML has no such split — it is a document wherever it is loaded — but its chat markdown is a download card rather than a picture, so the operator sees a link where an SVG would show an inline image.
Both settings, the gate and the serving boundary need the first spora-core release that carries them (spora-core#315); on an earlier core neither setting is declared, a script-capable format is created rather than refused, and its bytes are served unsandboxed.
The reason this is a toggle and not a static rule is the serving side, and it is worth being precise about, because the two settings answer different questions:
- The gate (
MediaAllowedTypesService) governs what may be created.text/htmlwas on the static text list until the toggle existed, which meant any install could store a<script>payload as HTML. - The serving boundary governs what happens to the bytes afterwards, and it does not depend on the toggle. Every media response carries
X-Content-Type-Options: nosniff, and every script-capable one on the download paths additionally carriesContent-Security-Policy: sandbox. The document still renders; it cannot reach the operator’s origin, and its script does not run. The embed route carries its own policy, which is the one exception.
That separation is the whole point, and it is why the gate cannot be the only defence. A rule enforced at one choke point does not cover a path that does not pass through it — which is exactly how the original SVG ban leaked: MediaDerivativeService::createNew() wrote the producer’s MIME onto the row without consulting the allowlist, so a producer emitting SVG created precisely the asset the upload gate refused. The derivative path now consults the same policy — in create(), so a re-render cannot rewrite an existing row’s type either.
The boundary is a helper, not a framework guarantee: MediaScriptableTypes::headersFor() returns the two headers for a MIME type, and every route that serves archive bytes calls it. A plugin that serves its own bytes is covered by its own policy, not by this one — the Typst plugin’s image library serves image types of its own and sandboxes the one that is script-capable.
The one route that may run script is GET /api/v1/media/{id}/embed, and it is narrow on every axis: authenticated only (a public share token does not unlock it), gated on the operator’s toggle, and serving sandbox without allow-same-origin so the framed document gets an opaque origin. It cannot read document.cookie, cannot reach localStorage, cannot touch the parent document, and cannot obtain the X-CSRF-Token every write requires. There is no bridge from the embedded document back to the app.
Discovery: search hides derivatives
MediaArchiveService::list() filters derivative rows out of the query, so a derivative never appears as a top-level library asset. That is correct for the operator grid — a thumbnail next to the source it was derived from is noise, and the operator reaches a derivative through its parent’s detail page and the VersionsStrip.
It is not neutral for the LLM. search is the only way an agent discovers assets it was not handed, and post-cut a PDF’s markdown is not discoverable through it. get_media’s derivatives[] array only appears if the agent already knows the parent id. So the net effect of routing extraction through derivatives is a capability regression: text an LLM used to get for free from an attached PDF now requires it to already hold the parent’s id. list_derivatives is the real discovery path, and the media-library skill tells the agent to use it.
7. What the chat UI does with the HTML
<img>,<audio>,<video>,<source>are in the allow-list.<div>,<span>andclassare in the allow-list too, which is what letsMediaEmbed::fileCard()ship a styled download card as raw HTML rather than markdown.data:URIs are allowed onsrcof<audio>,<video>, and<source>(via a per-call DOMPurify hook) but blocked on<a href>sodata:text/html,…XSS stays closed.downloadandaria-hiddenare not in the allow-list.downloadis harmless here, sinceAssetStreamer::applyContentDisposition()forcesContent-Disposition: attachmentfrommedia_assets.filenameregardless — butaria-hiddenbeing dropped means an icon glyph inside a card cannot be hidden from assistive tech. Use a CSS pseudo-element or a background image instead of an element with a glyph character in it.- Media elements get a sensible default style in
spora-frontend/src/style.cssunder.chat-bubble-content video/.chat-bubble-content audio. - The download card shows the filename and, when the archive knows it, the size. There is no MIME: the extension on the filename already says what the file is, and a long MIME overflowed the row and squeezed the filename to nothing in a narrow bubble.
- The one thing that is not sanitized is the embed. An HTML or SVG asset the operator has permitted is rendered in a real
<iframe>— a Vue component that owns its own element — because the sanitiser’s allow-list carries noiframeand noscript, and widening it would put every chat bubble in scope. The frame’ssandboxattribute mirrors theContent-Security-Policythe embed route sends, so the two agree. The header is the ceiling: the browser takes the union of the response’s forced sandboxing flags and the frame’s own attribute, so the attribute can narrow what the header allows, never widen it. The Media Archive’s own detail page renders the same frame for a permitted HTML or SVG asset (spora-plugin-media-archive-frontend,src/components/MediaEmbedFrame.vue), and the same rule applies there.
Where the frame appears, and where it does not
The frame and the markdown are two renderings of the same asset, and they are in different places — which is worth stating plainly, because “the chat shows a widget” and “the chat shows a download button” are both true at the same time.
| surface | what it shows |
|---|---|
| the tool’s own bubble | the markdown and the frame, in a row that is collapsed until it is expanded |
| the assistant’s message | the markdown, and the frame wherever the message asks for one |
| the Media Archive detail page | the frame alone, as the preview |
The bubble gets the frame without being asked: it reads the tool result’s structured data (embed_descriptor), which the chat never shows the model. The tool’s markdown also carries the line the model is told to echo — create_media and get_media put it in their result — so the bubble shows that reference as a plain link, beside the frame it mounts from the descriptor.
The message gets the frame by being asked for it. A model shows a widget by linking its embed route:
[test-dashboard.html](/api/v1/media/<asset_id>/embed)and the chat renders that link as the live asset, in place, as a block. The model never sees the bytes of the document it is embedding and never writes any markup — a link is the whole request, the way a link to a file is a link and not the file.
The route is the point, and it is a path rather than a fragment: the server is what decides whether the framed document may run script, and it decides by the path it is asked for. A fragment never leaves the browser, so it cannot select a policy. The reference names the asset, and the frame’s src is the server’s own embed URL for it, so the path the server serves is the path the client frames.
Two routes sit next to each other, and only one of them is the embed route:
| route | what it is | in the assistant’s message |
|---|---|---|
/api/v1/assets/<id>.<ext> | the download path — the bytes, sandboxed, no script | a plain link |
/api/v1/media/<id>/embed | the embed path — the bytes, framed, script if the operator permits it | a live frame |
A share link from get_public_url points at /api/v1/public/media/<id>?token=… — the public route, not either of the two above — so it opens the asset and is never framed.
The frame is still a Vue component, so the sanitiser’s allow-list still carries no iframe. The chat renders a message as segments — the markdown, and the frames it asks for — because a component cannot live inside the markup the sanitiser produced. A reference that cannot be framed, because the caller cannot see the asset or the operator has not permitted the format, stays the link the model wrote.
So an HTML widget reaches the operator as a download card in the message unless the model asks for the live one, and an SVG widget as an inline picture — a static one, because the markdown path loads it as an image — unless the model asks for that.
The two places that carry the frame are spora-frontend’s src/components/agent/TaskChat/MediaEmbedFrame.vue, used by the tool stream row and by the message, and spora-plugin-media-archive-frontend’s copy of it, used by the detail page. Both take the descriptor from the server, and both check that its url is a same-origin path before it reaches the frame.
The frame in the message needs the spora-frontend release that carries it (spora-frontend#214), and the descriptor on the ops that show an existing asset needs the spora-core release that carries it (spora-core#318). On an earlier release the frame is in the tool bubble only.
Styling the download card: register your classes
The card’s layout is Tailwind utilities that live in a PHP string, and Tailwind’s scanner only reads this repo — so it never sees them. spora-frontend registers the card’s exact class list with @source inline(...) in src/style.css, and that registration is the only reason the card is styled at all.
This matters for your plugin because the failure mode is silent. A class missing from the list is not generated: no build error, no warning, no failing test, just an unstyled card in the chat. So if you emit card-like markup with utility classes, add every one of them to that list in the same change. MediaEmbedFileCardTest in spora-core asserts that the classes core’s PHP emits are a subset of the registered list — that test covers core’s card, not yours.
Only spora-file-card__glyph is a real class hook: it is not a utility, it names the ::before mask that draws the download glyph, and it is the one card selector in src/style.css besides the colour/underline reset.
That reset is the second hand-written rule, and its reason is worth knowing before you add a third. This stylesheet’s own link styling (.chat-bubble-content a) is unlayered, and unlayered author CSS outranks every layered declaration regardless of specificity — so text-inherit and no-underline on the card lose to it and are undone by a rule instead. Specificity only breaks the tie once the layers match, so do not assume a utility class can win against the bubble’s link styling.
If you emit HTML outside the canonical helpers (MediaEmbed::*), test that the result survives sanitization. Run the frontend tests in spora-frontend/tests/composables/useMarkdown.spec.ts against your markup.
8. inspect_image — the model looks at an archive image
Everything above is about putting media in front of the human. The media tool has one operation that puts an archive image in front of the model: the agent names an asset, and the image itself arrives in the model’s context on the next turn — so the model can describe it, answer a question about it, or QA it, without a human attaching anything.
media inspect_image {asset_id, question?}
│
└─ the tool result carries a reference to the archive image
└─ the bytes are read from storage when the request is built
└─ an image content block on the user turn after the tool resultWhat the task-history row holds is the reference — the asset id and the kind — not the bytes, and the bytes are read off storage when a request is actually built, the same lazy resolution the user-attachment path already does. The archive’s own row is the exception: under data_url storage the image bytes land in media_assets.payload, the MEDIUMBLOB column the configuration table above names.
The image turn follows the whole run of tool results, not just its own. A provider accepts a tool result only directly after the assistant turn that asked for it, so a user turn between two results of the same batch is a 400. With one call the turn lands immediately after its result; with several calls in one batch it lands after the last of them.
The parameters
| Parameter | Type | Required | What it is |
|---|---|---|---|
asset_id | string | yes | The archive asset to look at. One asset per call. |
question | string | no | What to look at. The tool result carries it, so the model knows what it is being asked about. |
It is a read: it asks for no approval and changes nothing in the archive.
The result’s text names the asset and the question:
Attached media asset <id> (<filename>, <mime>, <n> bytes) to this result — you can see it now.
Question: <the question, or "none given.">The structured data carries asset_id, filename, mime_type, byte_size and question — the last one null when no question was given. That copy is stored for the operator’s dashboard and the audit trail; the model reads the text.
Two gates stand in front of it
The operation is off by default. It is absent from the tool schema the model is given until an operator enables it for the agent — the agent’s Tools tab → Media Library → the inspect_image operation’s toggle. An agent that has not been opted in cannot call it at all, and no context is spent on it.
The agent’s LLM must accept image content blocks. The same Allow images setting that governs image uploads governs this, and the resolved value is what counts: the operator’s toggle first, and a model-name heuristic only when the toggle is absent. A deliberately-off toggle blocks; an untouched toggle on a vision-capable model works — every Claude from claude-3 onwards, and the OpenAI families gpt-4o, gpt-4-turbo, gpt-4-vision, gpt-4.1, gpt-5, gpt-6, o1, o3, o4 and chatgpt-4o.
That toggle is a field of the LLM driver configuration — the agent’s LLM config, not its Tools tab, so it is not the field next to the operation toggle above. The refusal names it: Enable “Allow images” on the agent’s LLM configuration.
When the LLM does not take images, the call fails with a message the model reads — one that names the setting, the model, and the remedy, so the agent can tell the operator which switch to flip. It is never a silent failure, and never a success whose image is stripped further down.
One wrinkle worth knowing. The settings form renders an untouched toggle as unset, which for a toggle reads as “off” — the opposite of what runs. An operator looking at a
gpt-4oconfiguration sees “Allow images: off” while the system treats images as allowed. This is pre-existing behaviour, shared with the upload gate.
What it refuses
Every refusal names its reason:
| Refusal | Why |
|---|---|
| The asset’s MIME is not an image | The MIME must be one of the raster formats the providers accept — image/png, image/jpeg, image/webp, image/gif. |
image/svg+xml | SVG is script-capable, not raster, and no registered derivative producer rasterises one — core’s image producer takes PNG, JPEG, WebP and GIF sources only, so create_derivative cannot convert it. The asset has to be rasterised outside Spora, or by the operator, before it can be inspected. |
| The agent’s LLM does not accept image content blocks | The gate above — the failure names the setting and the model. |
| The asset is larger than the endpoint’s per-image ceiling | The provider caps the base64 form of the image, so the file that fits is three-quarters of the stated limit — 20 MB on OpenAI, 10 MB on the Claude API, 5 MB on Bedrock. A stale or missing size is re-measured after the load, so an oversized body cannot slip in through a stale column. The call is refused: the image never becomes an attachment, so there is nothing for a later request to leave out. |
The asset’s storage_mode is external | An external asset has no bytes on hand — the archive holds a link, not the file. |
The two limits, and which one is which
The refusal above is decided in the call. The ceiling is the endpoint’s, and the call reads the asset’s bytes and measures them, so an asset over it never becomes an attachment — there is nothing for a later request to leave out.
The request’s own room is a second limit, and it is decided later, when the request is built. Every image in one request shares it: the ones inspect_image put there and the operator’s own attachments alike, against three-quarters of the provider’s request ceiling — the remaining quarter is the system prompt, the tools and the conversation text. A request that carries more than the endpoint accepts is refused whole, so an image the request has no room for is dropped rather than sent.
The call has already succeeded by then. The tool result’s text still reaches the model, and the result carries a note that the image did not fit in the request and was not sent, so it is not visible in the conversation. What the model loses is the image, not the answer. The note does not say which of the request’s two limits applied — the request’s bytes or the number of images it may carry — and the two need different recoveries: a smaller derivative answers the first and not the second, because a derivative needs a slot of its own.
What it cannot see
The operation obeys the media tool’s Library scope setting (scope), the same one every other read obeys: under principal the agent sees the whole principal’s library — the operator’s own uploads included — and under agent it sees only the media it produced itself.
The default is principal. It was agent until the release that added this operation: the common case is the operator pointing the agent at an image in the library, and an operator’s own upload carries no agent_id to match under scope=agent.
An agent keeps the scope it had. An agent whose scope came from the schema default keeps agent; an agent whose scope was set deliberately — at the agent, global, group, principal or shared-group level — keeps that scope; an agent enabled from now on gets principal.
Migration 0105 is what holds the old reach in place: it materialises scope: 'agent' into the agent’s own settings row for an agent that had the media tool enabled and for which no layer supplies a scope — the agent’s own row, the shared group, the tool global, the group layer or the principal layer — so those agents see exactly what they saw before. The group layer counts only while the group cascade is on (SPORA_TOOLS_GROUP_CASCADE_ENABLED, off by default): with the cascade off, a group principal’s scope governs nothing at runtime, so it does not stop the materialisation. It only adds a scope where none exists, so a deliberate choice is never shadowed, and an agent whose global, principal, shared-group or own setting already supplies a scope is left alone. It is idempotent, its rollback takes back only the scopes it wrote, and it runs like every other migration: php bin/spora spora:install.
Set Library scope to principal on an agent whose scope is agent to give it the wider reach: a global change does not reach an agent that has a scope of its own, because its own agent-level setting overrides the global value. A global change still reaches an agent only when no layer above the global layer sets scope for it: its own agent-level setting, its principal setting or, while SPORA_TOOLS_GROUP_CASCADE_ENABLED is on, its group setting.
An asset outside the scope is not visible, and the failure says so without revealing whether the asset exists. It names the active scope, and it names the remedy the agent can act on: under agent both remedies — call search to list what the agent can see, or ask the operator to set Library scope to principal — and under principal only search, because the scope is already the wider one. That is the difference between a dead end and something the agent can act on.
The re-send cost
The image stays in the task history, and it is re-sent on every subsequent turn of the conversation — exactly like an image the user attached — for as long as the asset is still in the archive and the request has room for it. A long conversation that inspected a large image keeps paying for it in the context window. A compacted conversation loses the image, the same way it loses a user attachment.
An asset the operator removes from the archive is the other way the image stops being sent. The row still declares it, but the bytes are gone, so the block cannot be resolved — and the message that made the claim (“you can see it now”) carries a note saying the image was removed, rather than the model reading a claim the payload no longer supports. The note rides on that message, not on a turn of its own: the message count and the order are the provider’s contract. It names no path and no id beyond what the row already carries.
The media-library skill ships with the release, and it is what the model reads: it carries the operation matrix, the refusals and the scope rule, so the agent knows what inspect_image accepts before it calls it. This page is the reference behind that skill, not the model’s copy of it.
9. Local-mode URLs are stable, not permanent
LocalAssetStore mints a token that embeds a daily-rotating HMAC. A URL generated today is valid until midnight UTC tomorrow; a URL from last week returns 404 even if the file is still on disk.
If you want long-term retention, run php bin/spora assets:gc --max-age-days=N periodically (cron) to free disk. The command does not invalidate URLs that are still in their validity window — it only unlinks files past --max-age-days.
10. End-to-end example
final class TtsTool extends AbstractTool {
use StoresBinaryAssets;
public function __construct(
HttpClientInterface $http,
ToolConfigService $config,
?LoggerInterface $logger = null,
) {
parent::__construct($config, $http, $logger);
}
protected function doWork(ToolContext $ctx, array $args): ToolResult {
$resp = $this->http->request('POST', 'https://api.tts.example/synthesize', [
'json' => ['text' => $args['text']],
'timeout' => 60,
])->toArray();
if (! empty($resp['audio_url'])) {
// Easy path: upstream hosted it.
$embed = MediaEmbed::audioFromUrl($resp['audio_url']);
$mode = null;
} elseif (! empty($resp['audio_hex'])) {
// API returned hex; store via AssetStore, then embed.
[$url, $mode] = $this->embedHex(
$resp['audio_hex'],
mime: 'audio/mpeg',
filename: 'speech.mp3',
);
$embed = MediaEmbed::audioFromUrl($url);
} else {
return new ToolResult(false, 'TTS API returned no audio.');
}
$content = "Synthesized {$resp['usage_characters']} characters.\n\n{$embed}";
return new ToolResult(true, $content, [
'audio_url' => $resp['audio_url'] ?? null,
'asset_mode' => $mode,
]);
}
}That’s the full pattern. Roughly 10 lines per tool beyond the upstream HTTP call.