Skip to content

Commit 2cda53f

Browse files
authored
Merge pull request #84 from Accenture/feat/rest-upload
feat(rest): upload - the bounded form of the engines' multipart upload, and the LLM helper's document intake (RFC-0018)
2 parents b4f9c09 + 5431203 commit 2cda53f

17 files changed

Lines changed: 821 additions & 39 deletions

‎CHANGELOG.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,21 @@
282282
and the 45 tests of `tests/test_rest_automation.py` over HTTP; the demo app gains `hello.rest` at
283283
`GET /api/hello/{name}` with its `resources/rest.yaml`. No new dependency.
284284

285+
14. **Upload in REST automation, and the LLM helper's document intake (RFC-0018; Eric's direction of 2026-11-25:
286+
documents uploaded to the helper for a model to read).** `upload: true` on a `POST` entry is the pack's bounded form
287+
of the engines' streaming upload: the files of a `multipart/form-data` body arrive in the request map under the
288+
engines' keys (`filename`, `file_type`, `file_length`, the `upload` tags, `size`) with their bytes in `contents` -
289+
the stream routes the engines send replaced by the bytes - all together within `rest.upload.max.bytes` (16 MiB; a
290+
413 the moment they exceed it), the form's text fields as query parameters, the body absent; a non-multipart body
291+
on such an entry dispatches as usual. `AsyncHttpRequest.files()` reads them as `UploadedFile` (name, content type,
292+
size, tag, bytes), both exported. The LLM helper gains `llm.upload` behind `POST /api/llm/upload`
293+
(`resources/rest.yaml`, `rest.automation: true` in its `application.yml`): each file is saved under `uploads/`
294+
inside `llm.attachments.root` under a new name and the references returned - the `path` a later `llm.chat` call
295+
names in `attachments`, the kind by the first bytes, the size, the SHA-256 the audit keeps and `attachable`,
296+
whether the model takes the file as it is or a conversion comes first. Pinned by the vector file at version 2
297+
(an upload entry accepted, the request map and the accessors with the bytes as base64 in the file), four tests
298+
over HTTP and `tests/test_llm_upload.py`. The host's static-content rules and the rest of the edge are unchanged.
299+
285300
### Changed
286301

287302
1. **The agent-question app reads the question record and writes nothing: the backend of the React UI (RFC-0014

‎README.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -293,9 +293,13 @@ passes through.
293293
Precedence: a `rest.yaml` entry, then an extension's mounted routes, then the static folder, then
294294
the engines' error shape. Refused by name at load, so the grammar shows the scope fence: a `flow`
295295
binding (`flow:` or `service: http.flow.adapter` — flows run in the engines), the HTTP relay (an
296-
`http(s)://` service) and the A/B dual service. Deferred as in the Rust engine: `upload`,
297-
`custom.content.types`, `mime.types` and XML. With the switch off, the default, the host is exactly
298-
what it was.
296+
`http(s)://` service) and the A/B dual service. `upload: true` on a `POST` entry is the pack's bounded
297+
form of the engines' streaming upload: the files of a `multipart/form-data` body arrive in the request
298+
map under the engines' keys (`filename`, `file_type`, `file_length`, the `upload` tags, `size`) with
299+
their bytes in `contents`, read with `AsyncHttpRequest.files()`, all together within
300+
`rest.upload.max.bytes` (16 MiB; 413 beyond it); the form's text fields become query parameters.
301+
Deferred as in the Rust engine: `custom.content.types`, `mime.types`, XML and request-body
302+
streaming. With the switch off, the default, the host is exactly what it was.
299303

300304
## Wire compatibility
301305

‎extensions/llm-helper/README.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,41 @@ file is kept even when the file is not.
251251
Not on `llm.stream`, where a reply carries no schema, and not on a loop turn: a transcript keeps every turn, so it
252252
would have to keep the files, or references whose files may change between turns.
253253

254+
### Uploading documents
255+
256+
The helper fills its own folder: `POST /api/llm/upload` (a REST automation entry with `upload: true` in
257+
`resources/rest.yaml`, served because `application.yml` sets `rest.automation: true`) takes a
258+
`multipart/form-data` upload - PDFs, images, word-processor files, spreadsheets, any file - saves each file
259+
under `uploads/` inside `llm.attachments.root` under a new name, and returns the references a later
260+
`llm.chat` call names in `attachments`:
261+
262+
```shell
263+
curl -s -F 'doc=@contract.pdf' -F 'image=@table.png' http://127.0.0.1:8086/api/llm/upload
264+
```
265+
266+
```json
267+
{
268+
"files": [
269+
{"path": "uploads/3f2a...-contract.pdf", "filename": "contract.pdf", "media_type": "application/pdf",
270+
"bytes": 48213, "sha256": "9c1e...", "attachable": true},
271+
{"path": "uploads/77b0...-table.png", "filename": "table.png", "media_type": "image/png",
272+
"bytes": 2048, "sha256": "0a4d...", "attachable": true}
273+
]
274+
}
275+
```
276+
277+
`path` is the reference: a graph node that passes it to `llm.chat` as `attachments[0].path` has the model read
278+
the document - for the context, the rules and the formulas it holds. `media_type` is the kind by the first
279+
bytes, else the type the client declared; `attachable` says whether the model takes the file as it is (a PDF
280+
or an image) or a conversion comes first (a word-processor file or a spreadsheet, which `file.extract` of
281+
the agent tools turns into text; a PDF rendering of it is the other way). `sha256` is the hash the audit
282+
keeps, so an exchange can be checked against the file. The saved name is new on every upload (`<id>-<the
283+
original name made safe>`), so nothing is overwritten and a reference stays valid for the audit's retention.
284+
The files of one upload are bounded together by `rest.upload.max.bytes` (16 MiB; 413 beyond it), and the
285+
upload is a 503 by name until `llm.attachments.root` is set. **The folder is readable through the model, and
286+
this entry writes into it:** in production put an authentication function in front of the entry
287+
(`authentication: 'my.auth'`) or the gateway, and give the folder a retention of its own.
288+
254289
## The loop contract
255290
256291
`llm.chat` also serves one model turn of an agent loop. The loop is `llm.run`, a function of the Java and Rust

‎extensions/llm-helper/llm_helper.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,12 @@
5858

5959
from mercury_composable import (
6060
AppException,
61+
AsyncHttpRequest,
6162
Body,
6263
EventEnvelope,
6364
EventStreamWriter,
6465
PostOffice,
66+
UploadedFile,
6567
annotate_trace,
6668
app_config,
6769
default_registry,
@@ -797,6 +799,14 @@ def _plan(request: LlmRequest, backend: Backend) -> tuple[Any, dict[str, Any]]:
797799
# that can reach this app can have a file under the root sent to the provider and read back in
798800
# the reply: the root is deployment configuration, certified with the deployment.
799801

802+
# --- the document intake: llm.upload behind a REST automation entry with upload: true -----
803+
# the files of a multipart upload saved under this folder of the root, each under a new name
804+
UPLOAD_FOLDER = "uploads"
805+
UPLOAD_NO_FILES = (
806+
"upload: no file in the request - send multipart/form-data to an entry with upload: true"
807+
)
808+
_SAFE_NAME = re.compile(r"[^A-Za-z0-9._-]")
809+
800810
_attachments_root: Path | None = None # resolved on first use - module-level so tests can inject
801811

802812

@@ -2482,6 +2492,60 @@ def forward(text: str) -> None:
24822492
out.close(trailing)
24832493

24842494

2495+
def _safe_name(filename: str) -> str:
2496+
"""The uploaded name as a safe suffix of the saved name: the base name only, hidden-entry
2497+
dots stripped (the attachments rules would refuse them), every other character an
2498+
underscore, at most 80 characters."""
2499+
base = Path(filename).name if filename else ""
2500+
return _SAFE_NAME.sub("_", base).lstrip(".")[:80]
2501+
2502+
2503+
def _save_uploads(root: Path, files: list[UploadedFile]) -> list[dict[str, Any]]:
2504+
"""Write each file under a new name in the uploads folder of the root (in a worker thread)
2505+
and return the references a later call names: the path inside the root, the original name,
2506+
the kind by the first bytes (else the declared type), the size, the SHA-256 the audit keeps,
2507+
and whether llm.chat can attach the file as it is."""
2508+
folder = root / UPLOAD_FOLDER
2509+
folder.mkdir(parents=True, exist_ok=True)
2510+
saved: list[dict[str, Any]] = []
2511+
for uploaded in files:
2512+
suffix = _safe_name(uploaded.name)
2513+
name = f"{uuid.uuid4().hex}-{suffix}" if suffix else uuid.uuid4().hex
2514+
with open(folder / name, "xb") as handle: # a new name - never an overwrite
2515+
handle.write(uploaded.content)
2516+
detected = _media_type(uploaded.content[:16])
2517+
saved.append({
2518+
"path": f"{UPLOAD_FOLDER}/{name}",
2519+
"filename": uploaded.name,
2520+
"media_type": detected or uploaded.content_type,
2521+
"bytes": len(uploaded.content),
2522+
"sha256": hashlib.sha256(uploaded.content).hexdigest(),
2523+
"attachable": detected is not None,
2524+
})
2525+
return saved
2526+
2527+
2528+
@preload(route="llm.upload", instances=10)
2529+
async def llm_upload(_headers: dict[str, str], body: Body) -> Any:
2530+
"""The document intake for the attachments folder (RFC-0016): behind a REST automation entry
2531+
with ``upload: true`` (``POST /api/llm/upload`` in resources/rest.yaml), the files of a
2532+
multipart upload are saved under ``uploads/`` inside ``llm.attachments.root``, each under a
2533+
new name, and their references returned - the ``path`` a later ``llm.chat`` call names in
2534+
``attachments``, the kind by the first bytes, the size and the SHA-256 the audit keeps, and
2535+
``attachable``: whether the model takes the file as it is (a PDF or an image) or a conversion
2536+
comes first (a word-processor file, a spreadsheet). The folder is readable through the model:
2537+
put an authentication function or the gateway in front of the entry."""
2538+
request = AsyncHttpRequest(body)
2539+
files = request.files()
2540+
if not files:
2541+
raise AppException(400, UPLOAD_NO_FILES)
2542+
root = attachments_root()
2543+
saved = await asyncio.get_running_loop().run_in_executor(None, _save_uploads, root, files)
2544+
annotate_trace("llm_uploads", len(saved))
2545+
log.info("Uploaded %d file(s), %d bytes", len(saved), sum(item["bytes"] for item in saved))
2546+
return {"files": saved}
2547+
2548+
24852549
@preload(route="llm.health", instances=5, private=True)
24862550
async def llm_health(headers: dict[str, str], _body: Body) -> Any:
24872551
"""Health check speaking the engines' interface contract (type=info / type=health).

‎extensions/llm-helper/resources/application.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,14 @@ llm.fallbacks: 'default'
5959
# bytes of files per call, counted from the files' sizes before they are read (20 MB)
6060
# llm.attachments.max.bytes: 20971520
6161

62+
# --- the document intake: REST automation (the engines' rest.yaml) ----------------------------
63+
# resources/rest.yaml serves POST /api/llm/upload (llm.upload, an entry with upload: true): the
64+
# files of a multipart upload are saved under uploads/ inside llm.attachments.root and their
65+
# references returned for a later llm.chat call's `attachments`. Off by default in the package;
66+
# the helper turns it on. The files of one upload are bounded, all together (16 MiB)
67+
rest.automation: true
68+
# rest.upload.max.bytes: 16777216
69+
6270
# --- the agent loop's turns (llm.chat with tools): the transcript store -------------------
6371
# memory keeps the transcripts in this process - development and a single replica. With more
6472
# than one replica a turn may land on any of them: set redis (the [redis] extra)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#
2+
# REST automation (the engines' rest.yaml) for the LLM helper - the document intake.
3+
#
4+
# A multipart upload to POST /api/llm/upload saves its files under uploads/ inside
5+
# llm.attachments.root (application.yml) and returns the references a later llm.chat call
6+
# names in `attachments`: the path inside the folder, the kind by the first bytes, the size,
7+
# the SHA-256 and whether the file can be attached as it is. The files of one upload are
8+
# bounded by rest.upload.max.bytes (16 MiB by default).
9+
#
10+
# The folder is readable through the model: in production put an authentication function in
11+
# front of the entry (authentication: 'my.auth', a function answering true or false) or the
12+
# gateway. POST /api/event and the actuators stay served as the engines' default entries.
13+
#
14+
rest:
15+
- service: "llm.upload"
16+
methods: ['POST']
17+
url: "/api/llm/upload"
18+
upload: true
19+
timeout: 60s
20+
tracing: true

‎memory/continuity.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@
155155
in the helper's store (`llm.transcript.store`: `memory` or `redis`), the loop holds `conversation` and `turn`, a stale or
156156
ended turn is a 409, the model is pinned at the first turn and no server-side fallback is sent; a second shared vector
157157
file, `llm-loop-vectors.json`, pins it ([[llm-chat-loop-contract]]).
158-
<!-- id: llm-helper-app | created: 2026-10-01 | last_used: 2026-11-24 | uses: 8 | tier: active | origin: 2026-10-02-001146 -->
158+
<!-- id: llm-helper-app | created: 2026-10-01 | last_used: 2026-11-25 | uses: 9 | tier: active | origin: 2026-10-02-001146 -->
159159

160160
- **The MCP binding serves one composable route per allowlisted MCP tool, and the server cannot change a tool under the
161161
graph (RFC-0011 / ADR-0033 step 4; built 2026-11-14, Python first).** `extensions/mcp-binding/mcp_binding.py` on the
@@ -277,7 +277,7 @@
277277
access tokens - and the reply page signs the person in by Authorization Code with PKCE (a shell, `GET /ask/config`,
278278
the wait read from `GET /ask/{ticket}/wait`). **How to apply (amended):** "keeping no store" means no state of the
279279
wait - the record is an audit log, never consulted to render a wait; the agent-question app reads it.
280-
<!-- id: ask-person-main-flow | created: 2026-11-19 | last_used: 2026-11-20 | uses: 6 | tier: active | origin: 2026-11-19-054804 -->
280+
<!-- id: ask-person-main-flow | created: 2026-11-19 | last_used: 2026-11-20 | uses: 6 | tier: archive-candidate | origin: 2026-11-19-054804 -->
281281

282282
- **The agent-question app is the first channel of RFC-0014: a store-and-forward inbox for the person an agent asks,
283283
a standalone application on the package that the main flow knows nothing of (build plan step 3; built here
@@ -362,12 +362,14 @@
362362
(`rest_routing.py`: the parser and its refusals, the matching with the engines' precedence, the header transforms,
363363
the body dispatch by content type, the `Accept` negotiation, the response mapping) is pinned by
364364
`tests/vectors/rest-automation-vectors.json`, shared with the Node twin. Version 1 is the Rust port's subset;
365-
refused by name at load: a flow binding, the HTTP relay, the A/B dual service, `upload`. The edge records
365+
refused by name at load: a flow binding, the HTTP relay, the A/B dual service; `upload: true` is the pack's
366+
bounded form (the files' bytes in the request map within `rest.upload.max.bytes`, `AsyncHttpRequest.files()`;
367+
the LLM helper's `llm.upload` the first intake, 2026-11-25). The edge records
366368
`http.request` and the function's round trip as the engines do, so the forwarder's SERVER kind holds. **How to
367369
apply:** a new endpoint is a `rest.yaml` entry and a `@preload` function reading `AsyncHttpRequest(body)`, never a
368370
mounted route; a behaviour of the edge is first a vector case, then code, in both packs; the grammar's messages
369371
are the engines' and a pack never grows a dialect; what the engines defer stays deferred until a field request.
370-
<!-- id: rest-automation-python | created: 2026-11-25 | last_used: 2026-11-25 | uses: 1 | tier: working | origin: 2026-11-25-005844 -->
372+
<!-- id: rest-automation-python | created: 2026-11-25 | last_used: 2026-11-25 | uses: 2 | tier: active | origin: 2026-11-25-005844 -->
371373

372374
## Conventions
373375

@@ -379,11 +381,11 @@
379381
upstream). Run: `uvx ruff check .` / `uvx basedpyright` / `.venv/bin/pytest -q`.
380382
Unused contract params take the underscore prefix; deliberate suppressions carry
381383
rationale comments (PyBroadException / noqa only where the rule actually fires).
382-
<!-- id: conv-python-quality-gates | created: 2026-08-23 | last_used: 2026-11-25 | uses: 17 | tier: active | origin: 2026-08-23-005709 -->
384+
<!-- id: conv-python-quality-gates | created: 2026-08-23 | last_used: 2026-11-25 | uses: 18 | tier: active | origin: 2026-08-23-005709 -->
383385
- Engine-mirrored configuration/logging/trace conventions (see the invariant above and
384386
`instructions.md`); GitHub flow with tests + a CHANGELOG entry per change
385387
(CONTRIBUTING.md).
386-
<!-- id: conv-github-flow-changelog | created: 2026-08-22 | last_used: 2026-11-25 | uses: 8 | tier: active | origin: 2026-08-22-171555 -->
388+
<!-- id: conv-github-flow-changelog | created: 2026-08-22 | last_used: 2026-11-25 | uses: 9 | tier: active | origin: 2026-08-22-171555 -->
387389
- **Each example app lives in a folder of its own, with a README and its own `resources/` (Eric, 2026-10-01; PR #38).**
388390
`examples/demo-app/` (the minimal polyglot app: `hello.python`, `hello.declarative`, `hello.chain`, `hello.sync.chain`,
389391
`hello.tokens`, the private `demo.suffix.helper` and `demo.health`) and `examples/llm-helper/`; run one as

‎memory/open-threads/thread-bp-llm-attachments-python.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@
2626
or message changed; its PDF library is `@cantoo/pdf-lib`, the maintainer's choice, and a cut is asserted by its
2727
pages, not its bytes. RFC-0016's entry records both steps (mercury-composable #669 and #670).
2828
- **Next:** the schema page in mercury-composable; a live drive on both backends.
29+
- **The folder's first filler, 2026-11-25:** `llm.upload` behind `POST /api/llm/upload` (REST automation's
30+
`upload: true`) saves uploaded documents under `uploads/` inside the root and returns the references a call
31+
names in `attachments` - Eric's AI SDLC use case, documents uploaded to the helper for context, rules and
32+
formula extraction; `attachable` tells a PDF or an image from a file that needs a conversion first; the
33+
object-store download stays the later iteration (branch `feat/rest-upload`).
2934
→ proposal: RFC-0016 (mercury-composable)
3035
→ serves: vision-mercury-python
31-
<!-- id: bp-llm-attachments-python | created: 2026-11-24 | last_used: 2026-11-24 | uses: 1 | tier: working | origin: 2026-11-24-055310 -->
36+
<!-- id: bp-llm-attachments-python | created: 2026-11-24 | last_used: 2026-11-25 | uses: 2 | tier: working | origin: 2026-11-24-055310 -->

‎memory/open-threads/thread-bp-rest-automation-python.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,20 @@
2828
`/index.html` entry leaves `/` to the static folder and the landing page.
2929
- **Next:** the pull request; the Node twin from the same vector file; the engines' polyglot guide and the RFC's
3030
resolution; a live drive through an engine's `async.http.request` with the trace lineage checked.
31+
- **Upload BUILT 2026-11-25 (Eric: "Please add upload feature after this PR"; the use case: documents uploaded
32+
to the LLM helper for a model to read), branch `feat/rest-upload` stacked on the step-1 branch:** `upload: true`
33+
on a POST entry is the pack's bounded form of the engines' streaming upload - the files of a multipart body in
34+
the request map under the engines' keys with their bytes in `contents`, together within
35+
`rest.upload.max.bytes` (16 MiB, 413 beyond it), the form's fields as query parameters; `AsyncHttpRequest.files()`
36+
and `UploadedFile` exported; the LLM helper's `llm.upload` behind `POST /api/llm/upload` saves the files under
37+
`uploads/` inside the attachments root under new names and returns the references (`path`, the kind by the
38+
first bytes, the size, the SHA-256, `attachable`). Vectors version 2 (129 cases), 50 REST tests and
39+
`tests/test_llm_upload.py`; the gates clean; driven live (a PDF and an image uploaded to the running helper,
40+
the saved bytes identical, the trace record left). **Raised as PR #84 against the step-1 branch, 2026-11-25.**
41+
- **Defaults set without a ruling (upload):** one bound for all the files of an upload, 16 MiB; the body absent on
42+
an upload (Java parity) and the bytes in the pack key `contents` in place of the stream routes; multipart on an
43+
entry without `upload` stays raw bytes; the intake's saved name `<id>-<the original name made safe>`, never
44+
overwritten; `attachable` by the first bytes; the helper turns REST automation on in its own application.yml.
3145
→ proposal: RFC-0018 (mercury-composable)
3246
→ serves: vision-mercury-python
33-
<!-- id: bp-rest-automation-python | created: 2026-11-24 | last_used: 2026-11-25 | uses: 2 | tier: working | origin: 2026-11-24-233943 -->
47+
<!-- id: bp-rest-automation-python | created: 2026-11-24 | last_used: 2026-11-25 | uses: 3 | tier: working | origin: 2026-11-24-233943 -->

0 commit comments

Comments
 (0)