Repository navigation
Closed
1 / 11 of 1 issue completedClosed
1 / 11 of 1 issue completed
Copy link
Labels
complexity-mediumComplexity: medium (board points 5-8)priority-p1Critical paththeme-infrastructureTheme: Infrastructuretype-epicParent epic issue (groups child sub-issues)type-featureNew functionality
Description
Summary
Add a platform-level file storage service that agents can upload files to and receive secure one-time download URLs. This enables agents to share files with users via Slack, email, or any channel without requiring direct container access.
Motivation
Agents generate files (reports, images, exports, code artifacts) but have no way to share them externally. Current workarounds (base64 in chat, Slack file upload) are fragile and channel-specific. A platform file storage service provides a universal mechanism: upload a file, get a URL, share it anywhere.
Design
Architecture
Agent → Upload file via MCP tool → Platform storage → Returns one-time URL
User clicks URL → File downloaded → Link expires/invalidated
Storage
- Platform-level storage at
/data/files/(bind mount, survives restarts) - Files stored with UUID filenames (no path traversal risk)
- Metadata in SQLite: original filename, uploader agent, content type, size, expiration, download status
MCP Tool
upload_file(
file_path: string, # Path in agent container to upload
filename: string, # Display filename for download
content_type?: string, # MIME type (auto-detected if omitted)
expires_in?: number, # Seconds until link expires (default: 24h)
one_time?: boolean # Invalidate after first download (default: true)
) → { url: string, file_id: string, expires_at: string }
REST Endpoints
| Method | Path | Auth | Description |
|---|---|---|---|
| POST | /api/files/upload |
JWT/MCP | Upload file (multipart or from agent path) |
| GET | /api/files/{file_id}/{token} |
None (token) | Download file (public, one-time) |
| GET | /api/files |
JWT | List uploaded files (admin/owner) |
| DELETE | /api/files/{file_id} |
JWT | Delete file |
Download URL Format
https://{domain}/api/files/{file_id}/{download_token}
download_token= HMAC-SHA256(file_id + expiration, secret)- No authentication required — the token IS the auth
- One-time: marked as downloaded after first successful GET
- Expired files return 410 Gone
Database
CREATE TABLE platform_files (
id TEXT PRIMARY KEY,
agent_name TEXT NOT NULL,
original_filename TEXT NOT NULL,
stored_filename TEXT NOT NULL, -- UUID on disk
content_type TEXT,
size_bytes INTEGER,
download_token TEXT NOT NULL,
one_time INTEGER DEFAULT 1,
downloaded INTEGER DEFAULT 0,
downloaded_at TEXT,
expires_at TEXT,
created_at TEXT NOT NULL,
created_by TEXT -- user or agent
);Cleanup
- Background task purges expired files (both DB record and disk file)
- Configurable max storage size per agent and platform-wide
- Files older than 7 days auto-expire regardless of download status
Security
- HMAC token prevents URL guessing
- One-time download prevents link sharing/reuse
- File size limit (default: 100MB per file)
- Content-type validation (block executables by default)
- Files stored outside web root, served via streaming endpoint
- No directory listing or traversal possible
Acceptance Criteria
- Agents can upload files via MCP tool and receive a download URL
- One-time download links work without authentication
- Links expire after configured duration
- Downloaded/expired files return appropriate HTTP status
- Cleanup task removes expired files from disk and DB
- File list visible in UI for admins/owners
- File size limits enforced
- MCP tool available for agent-to-platform file upload
Sub-issues
Collapse Sub-issuesSub-issues
Loading 1 sub-issues
Metadata
Metadata
Assignees
Labels
complexity-mediumComplexity: medium (board points 5-8)priority-p1Critical paththeme-infrastructureTheme: Infrastructuretype-epicParent epic issue (groups child sub-issues)type-featureNew functionality
Activity
pavshulin commentedon Apr 24, 2026
Implemented as FILES-001 on branch
feature/295-files-outbound-sharing.Scope shipped (Steps 1–6)
agent-{name}-publicmounted at/home/developer/public/)share_fileMCP tool (agent-scoped) — 73 tools total in MCP server after this additionPOST /api/internal/agent-files/share(agent-server path,X-Internal-Secretauth)POST /api/agents/{name}/shared-files(owner/admin + same-agent defense)GET /api/files/{file_id}?sig={token}with token auth, constant-time compare, streaming, attachment disposition, HEAD handler, dedicated rate-limit bucket, audit eventfile_share_downloadcleanup_service.pyfor expired + old-revoked sharesDivergences from original spec
/api/files/{id}?sig={token}(not/api/files/{id}/{token}) — chosen to traverse the existing/api/*proxy rules on Vite dev + prod nginx without new proxy config. Query param issig(notdownload_token) to avoid the credential sanitizer redacting the token in agent transcripts./data/agent-files/{uuid}on backend side (rather than single shared/data/files/). Cleaner tenancy; FK cascade on agent delete.one_time,consumed_at) for future re-enablement.Docs / tests
docs/memory/requirements.md)docs/memory/architecture.md)docs/memory/feature-flows/file-sharing-outbound.mddocs/drafts/amazing-file-outbound.mddocs/drafts/amazing-file-outbound-production-readiness.mdFollow-ups
Filed as separate issues (see production-readiness plan §4):
G1 stream extraction, G2 directory sharding, G3 platform-wide quota, G4 audit file_id column, G5 endpoint pytest coverage, G6 URL sanitization in transcripts, G7 one-time + unfurl defense, G8 remove
?download_token=alias, G9 UI polish, G10 OTel spans, G11 PRAGMA foreign_keys (platform-wide), G12 unify request models.Closing as implemented.
pavshulin commentedon Apr 24, 2026
Implementation notes (additive — not replacing the original)
Collecting how we actually built this, known flaws/concerns, and deployment considerations so reviewers and future maintainers have the full picture alongside the close summary above.
How we built it
Delivered across 6 scoped steps rather than a single big bang, each verified end-to-end before the next one landed. This let us catch two real bugs (agent-delete cascade missing; URL format incompatible with proxy + sanitizer) during build rather than after merge.
agent_shared_filestable + migration +file_sharing_enabledcolumn. FK declaredON DELETE/UPDATE CASCADE(aspirational — see §Concerns).e47c688PUT /api/agents/{name}/file-sharing) + Docker volumeagent-{name}-publicmounted at/home/developer/public/. Mirrors the existing shared-folders expose pattern.e47c688POST /api/internal/agent-files/share(agent-server-path,X-Internal-Secretauth) + extraction via Docker SDKget_archive(backend never mounts agent workspace).e47c688GET /api/files/{id}?sig={token}— streaming response, constant-time token compare, revoked/expired gates,Content-Disposition: attachment,nosniff, audit event.e47c688share_fileMCP tool (agent-scoped) + backend endpointPOST /api/agents/{name}/shared-files(owner-only + same-agent defense for agent-scoped keys).e47c688e47c688shutil.disk_usagepre-check, cleanup sweep for expired/old-revoked rows, dedicated rate-limit bucket, HEAD handler, tightened list to owner+admin, system-wide prompt nudge for agents.1e0567b→07ca083(9 commits)Key architectural choices
/home/developer/public/(Docker volume, only mounted into the agent); backend extracts on demand into/data/agent-files/{uuid}. Backend filesystem never touches the agent workspace — path-traversal escapes can't reach.env/.credentials.encetc./api/files/{id}?sig=...not/files/{id}/{token}as the original spec called for. Two reasons discovered during testing:/files/*→ backend; they only proxy/api/*. Using/api/files/...means zero new proxy rules..*TOKEN.*=valuequery pair from agent-response transcripts. We renamed the param fromdownload_token→sigto escape the pattern.one_time,consumed_at) retained but the MCP tool + request/response shape doesn't expose them yet. Explicitly filed as a discussion item in FILES-001 follow-ups — needs refinement before pickup (12 items) #490 (G7) — re-enabling is ~40 lines because the columns are already there.POST /api/agents/{name}/shared-filesenforcescurrent_user.agent_name == path agent_namefor agent-scoped MCP keys so Agent A's key can't share files from Agent B's publish volume, even when both are owned by the same user.Problems we hit during implementation
1. FK cascade declared but not enforced
Discovered during live test: after
DELETE /api/agents/{name},agent_shared_filesrows for that agent remained in the DB, disk files stayed on/data/agent-files/, volume stayed on the host. Root cause: Trinity'sdb/connection.pydoesn't setPRAGMA foreign_keys = ONper connection — so everyON DELETE/UPDATE CASCADEacross the schema is aspirational andrename_agent()manually updates all 16 child tables.Fix: added explicit cleanup in the agent delete handler (DB rows → disk unlinks → volume remove) matching the platform-wide manual-cascade pattern. Platform-wide fix filed as G11 in #490.
2. URL format broken through the frontend proxy
Initial URL was
{host}/files/{id}?t={token}. That returned 200 fromlocalhost:8000but 404 when hit throughfrontend:80(Vite dev proxy) or the prod nginx. Plus even when the path was fixed, the credential sanitizer was stripping?download_token=values (pattern.*TOKEN.*).Fix: changed
build_download_url()to/api/files/{id}?sig={token}. Accept legacy?download_token=as an alias on the endpoint for backward compat with any URLs minted during the brief window before the fix.3.
/home/developer/test.pdf≠ publish dirAn agent produced a file at
/home/developer/test.pdfand said "done, here's the link" — without ever callingshare_file. Obvious in hindsight: agents don't know to write to/home/developer/public/unless told.Fix: C8 added a section to the system-wide Trinity prompt (
platform_prompt_service.py:PLATFORM_INSTRUCTIONS) instructing every agent on the publish dir +share_filetool. Applies immediately to every agent — no rebuild needed.Known flaws and concerns
Ranked by severity. All deferred items are tracked in #490.
MEDIUM
?sig=...) in their response text, which gets persisted inchat_messages/schedule_executionsrows for up to 7 days. Anyone with DB read access can reuse the URLs until expiration.?sig=specifically avoids the credential sanitizer pattern, so the token is NOT stripped. → FILES-001 follow-ups — needs refinement before pickup (12 items) #490 G6./datamount. The backend's SQLite DB, Vector logs, and agent-files storage all sit on the same/datamount. Even with C3'sshutil.disk_usagepre-check (blocks writes when free space < 500 MB), a sufficiently fast fill could starve the DB. → mitigated but not eliminated. A platform-wide storage cap (G3) would close this further.get_archivereads the tar into abytearray(up to 50 MB), thentarfile.extractfile().read()holds another copy. Under concurrent shares this stacks. → FILES-001 follow-ups — needs refinement before pickup (12 items) #490 G1 (streaming extraction).PRAGMA foreign_keysisn't enabled, so our FK (and every other FK in the schema) is decorative. Not introduced by this feature. → FILES-001 follow-ups — needs refinement before pickup (12 items) #490 G11.LOW
/data/agent-files/directory. ext4 directory lookups degrade past ~10k entries. → FILES-001 follow-ups — needs refinement before pickup (12 items) #490 G2 (UUID-prefix sharding).file_idin JSONdetails. Admin lookup-by-file-id needsjson_extractrather than an indexed column. → FILES-001 follow-ups — needs refinement before pickup (12 items) #490 G4.file_downloads:{ip}bucket). Not a deployment concern.?download_token=legacy alias still accepted for backward compat. → FILES-001 follow-ups — needs refinement before pickup (12 items) #490 G8 to remove.INFO
withAudit(), soshare_fileis audit-logged for free. We did not add an explicit span aroundcreate_share()service logic. → FILES-001 follow-ups — needs refinement before pickup (12 items) #490 G10.ShareFileRequest(internal) andShareFileMcpRequest(MCP) are near-identical. Intentional for type-clarity but could be consolidated. → FILES-001 follow-ups — needs refinement before pickup (12 items) #490 G12.Deployment notes
What changes in prod
agent_shared_filesruns on backend startup (idempotent, name-keyed). Adds 1 table, 3 indexes, 1 column onagent_ownership.docker-compose.yml,docker-compose.prod.ymlboth untouched). Thetrinity-datamount already exists in both; our/data/agent-files/subdirectory is created on first share.share_filetool +createFileToolsregistration).FileSharingPanel.vuecomponent + store methods + embed inSharingPanel.vue).Rollout order (recommended)
main. CI builds all three images.share_file; agents reconnecting to MCP pick up the new tool).Risk profile
file_sharing_enableddefaults to 0). Deployment cannot regress existing agents — worst case is the new UI panel shows up and the agent owner doesn't touch the toggle./api/files/{id}endpoint failure would take out file downloads but leave every other agent interaction intact. An MCP tool registration failure would gracefully degrade — agents would get "tool not found" when they try to callshare_file, but chat/tasks/collaboration all keep working.delete_expired_and_revokedsweep will eventually clean them up regardless of rollback. Disk storage is within/dataso no host cleanup needed.What to watch post-deploy
/data/agent-files/total size — confirm cleanup sweep is running (log line every cycle if anything was purged)./api/files/{id}— if the dedicated bucket hits limits, it's either legitimate traffic or the per-IP threshold needs tuning.file_share_downloadevents — confirm auditing is picking up downloads.agent_shared_files— should stabilize at "active shares + last 24h revoked" thanks to the cleanup sweep.Things that WILL surface on prod that we haven't hit in dev
/api/files/{id}from public internet — we only tested via Tailscale. Check for 403/404/500s in logs immediately after first deploy.share_fileuntil it next executes a task.