margin-api 0.1.1__tar.gz → 0.1.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- margin_api-0.1.2/CHANGELOG.md +61 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/PKG-INFO +6 -5
- {margin_api-0.1.1 → margin_api-0.1.2}/README.md +3 -2
- {margin_api-0.1.1 → margin_api-0.1.2}/pyproject.toml +3 -3
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/__init__.py +1 -1
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/app.py +141 -6
- margin_api-0.1.2/src/margin_api/files.py +104 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/jobs.py +21 -5
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/settings.py +9 -4
- margin_api-0.1.2/src/margin_api/ui/assets/index-9-YUxWG8.css +1 -0
- margin_api-0.1.2/src/margin_api/ui/assets/index-DZlrymYA.js +11 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/index.html +2 -2
- {margin_api-0.1.1 → margin_api-0.1.2}/tests/test_api.py +182 -7
- margin_api-0.1.1/CHANGELOG.md +0 -33
- margin_api-0.1.1/src/margin_api/ui/assets/index-CDckCtOp.css +0 -1
- margin_api-0.1.1/src/margin_api/ui/assets/index-CP-J9KRj.js +0 -11
- {margin_api-0.1.1 → margin_api-0.1.2}/.gitignore +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/LICENSE +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/llm_settings.py +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/main.py +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/py.typed +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/fonts/OFL-fraunces.txt +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/fonts/OFL-instrument-sans.txt +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/fonts/OFL-jetbrains-mono.txt +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/fonts/fraunces-latin-ext.woff2 +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/fonts/fraunces-latin.woff2 +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/fonts/instrument-sans-latin-ext.woff2 +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/fonts/instrument-sans-latin.woff2 +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/fonts/jetbrains-mono-latin.woff2 +0 -0
- {margin_api-0.1.1 → margin_api-0.1.2}/src/margin_api/ui/mark.svg +0 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this package are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.2] - 2026-11-02
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
- Uploads: `POST /uploads?name=<file>` saves the request body as a file and returns its path,
|
|
13
|
+
for an agent's input. Uploads have their own size limit, `MARGIN_API_MAX_UPLOAD_BYTES`
|
|
14
|
+
(200 MB), and are deleted after the result TTL.
|
|
15
|
+
- Run files: an input field marked `"format": "output-dir"` and left empty gets a folder of
|
|
16
|
+
the run's own. The run view lists what the run wrote there (`files`), and
|
|
17
|
+
`GET /runs/{run_id}/files/{name}` downloads it. The folder goes when the run is forgotten.
|
|
18
|
+
- `MARGIN_API_FILES_DIR` sets where uploads and run files are kept (a temporary folder,
|
|
19
|
+
removed on shutdown, when not set).
|
|
20
|
+
- The web UI uploads a file for an input field marked `"format": "file-path"` (drop it or
|
|
21
|
+
choose it, on the agent page and in the home page launcher), and offers a run's files for
|
|
22
|
+
download next to the JSON and Markdown exports.
|
|
23
|
+
|
|
24
|
+
### Security
|
|
25
|
+
- Requests that change something are refused with 403 if they come from another web page. CORS
|
|
26
|
+
only hid the answer, so any site you visited could upload files. Requires FastAPI 0.132 or
|
|
27
|
+
later, which also stops a page from starting a run with a JSON body and no `Content-Type`.
|
|
28
|
+
- `MARGIN_API_CORS_ORIGINS` is now empty by default. The UI the API serves itself is unaffected;
|
|
29
|
+
to use the UI's dev server, add `http://localhost:3000` (see `ui/README.md`).
|
|
30
|
+
- An output folder can no longer be chosen over HTTP (422), so a caller can't write files
|
|
31
|
+
elsewhere on the machine. Each run writes to its own folder.
|
|
32
|
+
- A `.env` in the current folder is no longer read, because it could open the server to the
|
|
33
|
+
network. Name a file with `MARGIN_ENV_FILE`.
|
|
34
|
+
|
|
35
|
+
## [0.1.1] - 2026-10-29
|
|
36
|
+
|
|
37
|
+
### Added
|
|
38
|
+
- Runs can stop to ask a question. A run whose agent asks moves to the new `waiting` status,
|
|
39
|
+
sends a `question` event and shows the questions in `GET /runs/{run_id}`;
|
|
40
|
+
`POST /runs/{run_id}/answers` answers them. While waiting, a run gives its place in the
|
|
41
|
+
queue to others, and it stops after `MARGIN_API_ANSWER_TIMEOUT_S` (an hour) without answers.
|
|
42
|
+
- `last_event` in the run view: the number of the latest event it already includes, so a
|
|
43
|
+
client can tell replayed events from new ones.
|
|
44
|
+
- The web UI shows an agent's questions as a form on the run page, and every result lists
|
|
45
|
+
the answers and who gave them.
|
|
46
|
+
|
|
47
|
+
### Changed
|
|
48
|
+
- `waiting` is a new run status. A client that lists every status must handle it.
|
|
49
|
+
|
|
50
|
+
### Fixed
|
|
51
|
+
- Opening a run page directly (a link or a reload) with the UI served by the API showed
|
|
52
|
+
"Can't reach the API": the browser answered the UI's own request for the run with the
|
|
53
|
+
cached page. Page loads now send `Vary: Accept` and `Cache-Control: no-cache`.
|
|
54
|
+
|
|
55
|
+
## [0.1.0] - 2026-10-21
|
|
56
|
+
|
|
57
|
+
### Added
|
|
58
|
+
- Background runs with live progress (server-sent events), queue positions and cancellation.
|
|
59
|
+
- Model settings over HTTP: provider, models, keys (never returned), live model lists and a connection test.
|
|
60
|
+
- The web UI, bundled in the package and served from the same address.
|
|
61
|
+
- Answers only to `localhost` by default (protects against DNS rebinding).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: margin-api
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: margin's HTTP API and web UI: run agents in the background, follow them live, read their evidence.
|
|
5
5
|
Project-URL: Homepage, https://github.com/Waddah0-0/margin
|
|
6
6
|
Project-URL: Source, https://github.com/Waddah0-0/margin/tree/main/packages/api
|
|
@@ -20,9 +20,9 @@ Classifier: Programming Language :: Python :: 3.11
|
|
|
20
20
|
Classifier: Programming Language :: Python :: 3.12
|
|
21
21
|
Classifier: Typing :: Typed
|
|
22
22
|
Requires-Python: >=3.11
|
|
23
|
-
Requires-Dist: fastapi>=0.
|
|
23
|
+
Requires-Dist: fastapi>=0.132.0
|
|
24
24
|
Requires-Dist: httpx>=0.27.0
|
|
25
|
-
Requires-Dist: margin-core<0.2,>=0.1.
|
|
25
|
+
Requires-Dist: margin-core<0.2,>=0.1.3
|
|
26
26
|
Requires-Dist: pydantic-settings>=2.2.0
|
|
27
27
|
Requires-Dist: sse-starlette>=2.1.0
|
|
28
28
|
Requires-Dist: uvicorn>=0.30.0
|
|
@@ -43,13 +43,14 @@ margin-api # open http://127.0.0.1:8000 (API docs at /docs)
|
|
|
43
43
|
|
|
44
44
|
The web UI comes inside the package, so that one address is the whole app. The server only
|
|
45
45
|
listens on `127.0.0.1`, which means nothing else on your network can reach it. You can change
|
|
46
|
-
that and a few other things with `MARGIN_API_` environment variables (or a
|
|
46
|
+
that and a few other things with `MARGIN_API_` environment variables (or a file named by
|
|
47
|
+
`MARGIN_ENV_FILE`; a `.env` in the current folder is not read):
|
|
47
48
|
|
|
48
49
|
| Setting | Default | Meaning |
|
|
49
50
|
|---|---|---|
|
|
50
51
|
| `MARGIN_API_HOST` / `MARGIN_API_PORT` | `127.0.0.1` / `8000` | Where to listen. Change the host only if you mean to expose it. |
|
|
51
52
|
| `MARGIN_API_ALLOWED_HOSTS` | `["127.0.0.1", "localhost"]` | Host names the API answers to. This blocks DNS-rebinding attacks from web pages; add your host name if you expose the API. |
|
|
52
|
-
| `MARGIN_API_CORS_ORIGINS` | `[
|
|
53
|
+
| `MARGIN_API_CORS_ORIGINS` | `[]` | Other web pages allowed to call it (JSON list). The built-in UI needs none. Changes from any other page are refused. |
|
|
53
54
|
| `MARGIN_API_LLM_CONCURRENCY` | `1` | Runs of agents that use a model, at once (one local GPU). |
|
|
54
55
|
| `MARGIN_API_OTHER_CONCURRENCY` | `4` | Runs of other agents, at once. |
|
|
55
56
|
| `MARGIN_API_RESULT_TTL_S` | `3600` | Seconds a finished run is kept. |
|
|
@@ -13,13 +13,14 @@ margin-api # open http://127.0.0.1:8000 (API docs at /docs)
|
|
|
13
13
|
|
|
14
14
|
The web UI comes inside the package, so that one address is the whole app. The server only
|
|
15
15
|
listens on `127.0.0.1`, which means nothing else on your network can reach it. You can change
|
|
16
|
-
that and a few other things with `MARGIN_API_` environment variables (or a
|
|
16
|
+
that and a few other things with `MARGIN_API_` environment variables (or a file named by
|
|
17
|
+
`MARGIN_ENV_FILE`; a `.env` in the current folder is not read):
|
|
17
18
|
|
|
18
19
|
| Setting | Default | Meaning |
|
|
19
20
|
|---|---|---|
|
|
20
21
|
| `MARGIN_API_HOST` / `MARGIN_API_PORT` | `127.0.0.1` / `8000` | Where to listen. Change the host only if you mean to expose it. |
|
|
21
22
|
| `MARGIN_API_ALLOWED_HOSTS` | `["127.0.0.1", "localhost"]` | Host names the API answers to. This blocks DNS-rebinding attacks from web pages; add your host name if you expose the API. |
|
|
22
|
-
| `MARGIN_API_CORS_ORIGINS` | `[
|
|
23
|
+
| `MARGIN_API_CORS_ORIGINS` | `[]` | Other web pages allowed to call it (JSON list). The built-in UI needs none. Changes from any other page are refused. |
|
|
23
24
|
| `MARGIN_API_LLM_CONCURRENCY` | `1` | Runs of agents that use a model, at once (one local GPU). |
|
|
24
25
|
| `MARGIN_API_OTHER_CONCURRENCY` | `4` | Runs of other agents, at once. |
|
|
25
26
|
| `MARGIN_API_RESULT_TTL_S` | `3600` | Seconds a finished run is kept. |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "margin-api"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.2"
|
|
4
4
|
description = "margin's HTTP API and web UI: run agents in the background, follow them live, read their evidence."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.11"
|
|
@@ -20,8 +20,8 @@ classifiers = [
|
|
|
20
20
|
"Environment :: Web Environment",
|
|
21
21
|
]
|
|
22
22
|
dependencies = [
|
|
23
|
-
"margin-core>=0.1.
|
|
24
|
-
"fastapi>=0.
|
|
23
|
+
"margin-core>=0.1.3,<0.2", # 0.1.3: security fixes
|
|
24
|
+
"fastapi>=0.132.0", # older ones read JSON with no Content-Type, which skips the CORS check
|
|
25
25
|
"uvicorn>=0.30.0",
|
|
26
26
|
"sse-starlette>=2.1.0",
|
|
27
27
|
"httpx>=0.27.0",
|
|
@@ -3,11 +3,15 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import json
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import uuid
|
|
6
9
|
from collections.abc import AsyncIterator, Awaitable, Callable, MutableMapping
|
|
7
10
|
from contextlib import asynccontextmanager
|
|
8
11
|
from datetime import datetime
|
|
9
12
|
from pathlib import Path
|
|
10
13
|
from typing import Any, Literal
|
|
14
|
+
from urllib.parse import urlsplit
|
|
11
15
|
|
|
12
16
|
from fastapi import FastAPI, HTTPException, Query, Request
|
|
13
17
|
from fastapi.middleware.cors import CORSMiddleware
|
|
@@ -33,6 +37,7 @@ from pydantic import BaseModel, ConfigDict, Field
|
|
|
33
37
|
from sse_starlette.sse import EventSourceResponse
|
|
34
38
|
|
|
35
39
|
from margin_api import __version__
|
|
40
|
+
from margin_api.files import OUTPUT_FORMAT, FileStore, RunFile, fields_with_format
|
|
36
41
|
from margin_api.jobs import NotWaitingError, Run, RunManager, RunStatus
|
|
37
42
|
from margin_api.llm_settings import router as llm_settings_router
|
|
38
43
|
from margin_api.settings import ApiSettings, load_settings
|
|
@@ -81,6 +86,16 @@ class RunView(BaseModel):
|
|
|
81
86
|
last_event: int = Field(
|
|
82
87
|
default=0, description="Number of the latest event; this view already includes it."
|
|
83
88
|
)
|
|
89
|
+
files: list[RunFile] = Field(
|
|
90
|
+
default_factory=list,
|
|
91
|
+
description="Files the run wrote to its own folder; download from /runs/{id}/files/{name}.",
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Upload(BaseModel):
|
|
96
|
+
path: str = Field(description="Where the file was saved; give this to the agent's input.")
|
|
97
|
+
name: str
|
|
98
|
+
size: int
|
|
84
99
|
|
|
85
100
|
|
|
86
101
|
class AnswersBody(BaseModel):
|
|
@@ -100,12 +115,17 @@ class _BodyLimit:
|
|
|
100
115
|
error raised while the app reads its body would be reported as a generic 400.
|
|
101
116
|
"""
|
|
102
117
|
|
|
103
|
-
def __init__(self, app: Any, limit: int) -> None:
|
|
118
|
+
def __init__(self, app: Any, limit: int, exempt: tuple[str, ...] = ()) -> None:
|
|
104
119
|
self.app = app
|
|
105
120
|
self.limit = limit
|
|
121
|
+
self.exempt = exempt # paths that stream their body and limit it themselves
|
|
106
122
|
|
|
107
123
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
108
|
-
if
|
|
124
|
+
if (
|
|
125
|
+
scope["type"] != "http"
|
|
126
|
+
or scope.get("method") in {"GET", "HEAD", "DELETE", "OPTIONS"}
|
|
127
|
+
or scope.get("path") in self.exempt
|
|
128
|
+
):
|
|
109
129
|
await self.app(scope, receive, send)
|
|
110
130
|
return
|
|
111
131
|
headers = dict(scope.get("headers") or [])
|
|
@@ -145,6 +165,39 @@ class _BodyLimit:
|
|
|
145
165
|
await send({"type": "http.response.body", "body": body})
|
|
146
166
|
|
|
147
167
|
|
|
168
|
+
class _OriginCheck:
|
|
169
|
+
"""Refuse changes asked for by another web page, with 403.
|
|
170
|
+
|
|
171
|
+
CORS only stops a page from reading the answer. A plain POST still reaches the server, so
|
|
172
|
+
without this any site you visit could fill the disk through ``/uploads``. Programs send no
|
|
173
|
+
``Origin`` and aren't affected; the UI's own requests come from the address they go to.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
READS = {"GET", "HEAD", "OPTIONS"}
|
|
177
|
+
|
|
178
|
+
def __init__(self, app: Any, allowed: list[str]) -> None:
|
|
179
|
+
self.app = app
|
|
180
|
+
self.allowed = allowed
|
|
181
|
+
|
|
182
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
183
|
+
if scope["type"] == "http" and scope.get("method") not in self.READS:
|
|
184
|
+
headers = dict(scope.get("headers") or [])
|
|
185
|
+
origin = headers.get(b"origin", b"").decode("latin-1")
|
|
186
|
+
host = headers.get(b"host", b"").decode("latin-1")
|
|
187
|
+
if origin and not self._allowed(origin, host):
|
|
188
|
+
body = json.dumps({"detail": "Requests from other web pages are refused"}).encode()
|
|
189
|
+
await send({"type": "http.response.start", "status": 403,
|
|
190
|
+
"headers": [(b"content-type", b"application/json")]}) # fmt: skip
|
|
191
|
+
await send({"type": "http.response.body", "body": body})
|
|
192
|
+
return
|
|
193
|
+
await self.app(scope, receive, send)
|
|
194
|
+
|
|
195
|
+
def _allowed(self, origin: str, host: str) -> bool:
|
|
196
|
+
if origin in self.allowed or "*" in self.allowed:
|
|
197
|
+
return True
|
|
198
|
+
return bool(host) and urlsplit(origin).netloc == host # "null" has no address
|
|
199
|
+
|
|
200
|
+
|
|
148
201
|
LLMFactory = Callable[[str | None, str | None], LLMClient | None]
|
|
149
202
|
|
|
150
203
|
|
|
@@ -161,7 +214,13 @@ def create_app(
|
|
|
161
214
|
) -> FastAPI:
|
|
162
215
|
settings = settings or load_settings()
|
|
163
216
|
registry = registry or default_registry()
|
|
164
|
-
|
|
217
|
+
store = FileStore(settings.files_dir)
|
|
218
|
+
manager = RunManager(
|
|
219
|
+
registry,
|
|
220
|
+
settings,
|
|
221
|
+
on_forget=store.forget_run,
|
|
222
|
+
on_sweep=lambda: store.sweep_uploads(settings.result_ttl_s),
|
|
223
|
+
)
|
|
165
224
|
|
|
166
225
|
@asynccontextmanager
|
|
167
226
|
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
|
@@ -170,6 +229,7 @@ def create_app(
|
|
|
170
229
|
yield
|
|
171
230
|
finally:
|
|
172
231
|
await manager.stop()
|
|
232
|
+
store.close()
|
|
173
233
|
|
|
174
234
|
app = FastAPI(
|
|
175
235
|
title="margin API",
|
|
@@ -187,11 +247,12 @@ def create_app(
|
|
|
187
247
|
allow_methods=["GET", "POST", "PUT", "DELETE"],
|
|
188
248
|
allow_headers=["Content-Type", "Last-Event-ID"],
|
|
189
249
|
)
|
|
190
|
-
app.add_middleware(_BodyLimit, limit=settings.max_body_bytes)
|
|
250
|
+
app.add_middleware(_BodyLimit, limit=settings.max_body_bytes, exempt=("/uploads",))
|
|
191
251
|
ui_dir = Path(settings.ui_dir) if settings.ui_dir else _bundled_ui()
|
|
192
252
|
ui_root = _ui_root(ui_dir) if ui_dir is not None else None
|
|
193
253
|
if ui_root is not None:
|
|
194
254
|
app.add_middleware(_UIPages, root=ui_root)
|
|
255
|
+
app.add_middleware(_OriginCheck, allowed=settings.cors_origins)
|
|
195
256
|
# Only answer requests addressed to this machine by name. Without this, a web page could
|
|
196
257
|
# use DNS rebinding to reach the API through a domain of its own and read local results.
|
|
197
258
|
app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.allowed_hosts)
|
|
@@ -219,6 +280,7 @@ def create_app(
|
|
|
219
280
|
created_at=run.created_at, started_at=run.started_at,
|
|
220
281
|
finished_at=run.finished_at, result=run.result,
|
|
221
282
|
llm=llm, question=run.question, last_event=run.last_event,
|
|
283
|
+
files=store.run_files(run.id) if run.status == "done" else [],
|
|
222
284
|
) # fmt: skip
|
|
223
285
|
|
|
224
286
|
@app.get("/health", tags=["meta"])
|
|
@@ -252,6 +314,15 @@ def create_app(
|
|
|
252
314
|
),
|
|
253
315
|
) -> RunCreated:
|
|
254
316
|
cls = agent_class(agent_id)
|
|
317
|
+
run_id = uuid.uuid4().hex
|
|
318
|
+
# an output folder is always the run's own, so its files can be downloaded and a caller
|
|
319
|
+
# can't write over files elsewhere on this machine
|
|
320
|
+
for name in fields_with_format(cls.InputModel.model_json_schema(), OUTPUT_FORMAT):
|
|
321
|
+
if body.get(name) not in (None, ""):
|
|
322
|
+
raise HTTPException(
|
|
323
|
+
422, f"{name} can't be set over HTTP: each run writes to its own folder"
|
|
324
|
+
)
|
|
325
|
+
body = {**body, name: str(store.run_dir(run_id))}
|
|
255
326
|
try:
|
|
256
327
|
parsed = cls.parse_input(body)
|
|
257
328
|
except InputValidationError as exc:
|
|
@@ -265,7 +336,7 @@ def create_app(
|
|
|
265
336
|
if provider or model: # a choice made for this run must work, or say why
|
|
266
337
|
raise HTTPException(422, f"Cannot use that model: {exc}") from exc
|
|
267
338
|
logger.warning("No model client for %s: %s", agent_id, exc)
|
|
268
|
-
run = manager.submit(cls, parsed, llm=llm, provider=resolved)
|
|
339
|
+
run = manager.submit(cls, parsed, llm=llm, provider=resolved, run_id=run_id)
|
|
269
340
|
return RunCreated(
|
|
270
341
|
run_id=run.id,
|
|
271
342
|
status=run.status,
|
|
@@ -309,6 +380,65 @@ def create_app(
|
|
|
309
380
|
raise HTTPException(422, f"Invalid answers: {exc}") from exc
|
|
310
381
|
return view(run)
|
|
311
382
|
|
|
383
|
+
@app.get(
|
|
384
|
+
"/runs/{run_id}/files/{name}",
|
|
385
|
+
tags=["runs"],
|
|
386
|
+
response_class=FileResponse,
|
|
387
|
+
responses={404: {"description": "No such file in the run's folder"}},
|
|
388
|
+
)
|
|
389
|
+
def run_file(run_id: str, name: str) -> FileResponse:
|
|
390
|
+
"""Download a file the run wrote to its own folder (see the run's ``files``)."""
|
|
391
|
+
run = find_run(run_id)
|
|
392
|
+
path = store.run_file(run.id, name)
|
|
393
|
+
if path is None:
|
|
394
|
+
raise HTTPException(404, f"Run {run_id!r} has no file {name!r}")
|
|
395
|
+
return FileResponse(path, filename=path.name)
|
|
396
|
+
|
|
397
|
+
@app.post(
|
|
398
|
+
"/uploads",
|
|
399
|
+
status_code=201,
|
|
400
|
+
response_model=Upload,
|
|
401
|
+
tags=["files"],
|
|
402
|
+
openapi_extra={
|
|
403
|
+
"requestBody": {
|
|
404
|
+
"required": True,
|
|
405
|
+
"content": {
|
|
406
|
+
"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}
|
|
407
|
+
},
|
|
408
|
+
}
|
|
409
|
+
},
|
|
410
|
+
responses={413: {"description": "The file is larger than MARGIN_API_MAX_UPLOAD_BYTES"}},
|
|
411
|
+
)
|
|
412
|
+
async def upload(
|
|
413
|
+
request: Request,
|
|
414
|
+
name: str = Query(min_length=1, max_length=255, description="The file's name."),
|
|
415
|
+
) -> Upload:
|
|
416
|
+
"""Save a file for a run to read. Send the file as the raw request body.
|
|
417
|
+
|
|
418
|
+
The response's ``path`` goes into the agent's input. Uploads are deleted after the
|
|
419
|
+
result TTL.
|
|
420
|
+
"""
|
|
421
|
+
limit = settings.max_upload_bytes
|
|
422
|
+
declared = request.headers.get("content-length", "")
|
|
423
|
+
too_big = f"The file is larger than the {limit // 1_000_000} MB limit"
|
|
424
|
+
if declared.isdigit() and int(declared) > limit:
|
|
425
|
+
raise HTTPException(413, too_big)
|
|
426
|
+
path = store.new_upload(name)
|
|
427
|
+
size = 0
|
|
428
|
+
try:
|
|
429
|
+
with path.open("wb") as out:
|
|
430
|
+
async for chunk in request.stream():
|
|
431
|
+
size += len(chunk)
|
|
432
|
+
if size > limit:
|
|
433
|
+
raise HTTPException(413, too_big)
|
|
434
|
+
out.write(chunk)
|
|
435
|
+
if size == 0:
|
|
436
|
+
raise HTTPException(422, "The file is empty")
|
|
437
|
+
except BaseException:
|
|
438
|
+
shutil.rmtree(path.parent, ignore_errors=True)
|
|
439
|
+
raise
|
|
440
|
+
return Upload(path=str(path), name=path.name, size=size)
|
|
441
|
+
|
|
312
442
|
@app.get(
|
|
313
443
|
"/runs/{run_id}/events",
|
|
314
444
|
tags=["runs"],
|
|
@@ -350,6 +480,7 @@ class _UIPages:
|
|
|
350
480
|
"""
|
|
351
481
|
|
|
352
482
|
API_PAGES = ("/docs", "/redoc", "/openapi.json")
|
|
483
|
+
DOWNLOADS = re.compile(r"^/runs/[^/]+/files/") # a download link also asks for HTML
|
|
353
484
|
PAGE_HEADERS = {"Vary": "Accept", "Cache-Control": "no-cache"}
|
|
354
485
|
|
|
355
486
|
def __init__(self, app: Any, root: Path) -> None:
|
|
@@ -362,7 +493,11 @@ class _UIPages:
|
|
|
362
493
|
headers = dict(scope.get("headers") or [])
|
|
363
494
|
accept = headers.get(b"accept", b"").decode("latin-1")
|
|
364
495
|
path = str(scope.get("path", "/"))
|
|
365
|
-
if
|
|
496
|
+
if (
|
|
497
|
+
"text/html" in accept
|
|
498
|
+
and not path.startswith(self.API_PAGES)
|
|
499
|
+
and not self.DOWNLOADS.match(path)
|
|
500
|
+
):
|
|
366
501
|
candidate = (self.root / path.lstrip("/")).resolve()
|
|
367
502
|
if not (candidate.is_file() and self.root in candidate.parents):
|
|
368
503
|
# the page shares its URL with the API's JSON: without Vary the browser
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Files that runs read and write: uploads from the web UI, and each run's own folder.
|
|
2
|
+
|
|
3
|
+
Both live under one root that the API owns (a temporary folder unless ``MARGIN_API_FILES_DIR``
|
|
4
|
+
says otherwise). An upload is kept until it is older than the result TTL; a run's folder goes
|
|
5
|
+
when the run is forgotten. Files are only ever served from a run's own folder, by name.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
import shutil
|
|
12
|
+
import tempfile
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from pydantic import BaseModel
|
|
19
|
+
|
|
20
|
+
# a JSON Schema ``format`` an agent puts on an input field (``json_schema_extra``)
|
|
21
|
+
UPLOAD_FORMAT = "file-path" # the UI offers to upload a file and fills in where it was saved
|
|
22
|
+
OUTPUT_FORMAT = "output-dir" # left empty, the API fills in the run's own folder
|
|
23
|
+
|
|
24
|
+
_UNSAFE = re.compile(r"[^\w.\- ()]+")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class RunFile(BaseModel):
|
|
28
|
+
name: str
|
|
29
|
+
size: int
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def safe_name(name: str) -> str:
|
|
33
|
+
"""A file name with no folders and no characters that mean something to a shell or OS."""
|
|
34
|
+
base = re.split(r"[\\/]", name)[-1]
|
|
35
|
+
cleaned = _UNSAFE.sub("_", base).strip(" .")[:120]
|
|
36
|
+
return cleaned or "upload"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def fields_with_format(schema: dict[str, Any], fmt: str) -> list[str]:
|
|
40
|
+
"""Input fields whose schema (or one of its variants) has ``format: fmt``."""
|
|
41
|
+
found = []
|
|
42
|
+
for name, prop in (schema.get("properties") or {}).items():
|
|
43
|
+
variants = [prop, *(prop.get("anyOf") or []), *(prop.get("oneOf") or [])]
|
|
44
|
+
if any(isinstance(v, dict) and v.get("format") == fmt for v in variants):
|
|
45
|
+
found.append(name)
|
|
46
|
+
return found
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class FileStore:
|
|
50
|
+
def __init__(self, root: str | None = None) -> None:
|
|
51
|
+
self._owned = root is None
|
|
52
|
+
self.root = Path(root or tempfile.mkdtemp(prefix="margin-api-")).resolve()
|
|
53
|
+
self.uploads = self.root / "uploads"
|
|
54
|
+
self.runs = self.root / "runs"
|
|
55
|
+
self.uploads.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
self.runs.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
|
|
58
|
+
def new_upload(self, name: str) -> Path:
|
|
59
|
+
"""Where to save an upload: its own folder, so two files with one name never clash."""
|
|
60
|
+
folder = self.uploads / uuid.uuid4().hex
|
|
61
|
+
folder.mkdir()
|
|
62
|
+
return folder / safe_name(name)
|
|
63
|
+
|
|
64
|
+
def run_dir(self, run_id: str) -> Path:
|
|
65
|
+
return self.runs / run_id
|
|
66
|
+
|
|
67
|
+
def run_files(self, run_id: str) -> list[RunFile]:
|
|
68
|
+
folder = self.run_dir(run_id)
|
|
69
|
+
if not folder.is_dir():
|
|
70
|
+
return []
|
|
71
|
+
return [
|
|
72
|
+
RunFile(name=p.name, size=p.stat().st_size)
|
|
73
|
+
for p in sorted(folder.iterdir())
|
|
74
|
+
if p.is_file()
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
def run_file(self, run_id: str, name: str) -> Path | None:
|
|
78
|
+
"""A file a run wrote, or None. Only plain names inside the run's own folder."""
|
|
79
|
+
if name != safe_name(name):
|
|
80
|
+
return None
|
|
81
|
+
folder = self.run_dir(run_id).resolve()
|
|
82
|
+
path = (folder / name).resolve()
|
|
83
|
+
return path if path.parent == folder and path.is_file() else None
|
|
84
|
+
|
|
85
|
+
def forget_run(self, run_id: str) -> None:
|
|
86
|
+
shutil.rmtree(self.run_dir(run_id), ignore_errors=True)
|
|
87
|
+
|
|
88
|
+
def sweep_uploads(self, max_age_s: float) -> int:
|
|
89
|
+
"""Delete uploads older than ``max_age_s``. Returns how many were removed."""
|
|
90
|
+
cutoff = time.time() - max_age_s
|
|
91
|
+
removed = 0
|
|
92
|
+
for folder in self.uploads.iterdir():
|
|
93
|
+
try:
|
|
94
|
+
if folder.stat().st_mtime < cutoff:
|
|
95
|
+
shutil.rmtree(folder, ignore_errors=True)
|
|
96
|
+
removed += 1
|
|
97
|
+
except OSError:
|
|
98
|
+
continue
|
|
99
|
+
return removed
|
|
100
|
+
|
|
101
|
+
def close(self) -> None:
|
|
102
|
+
"""Remove the root if the API made it (a folder it was given is left in place)."""
|
|
103
|
+
if self._owned:
|
|
104
|
+
shutil.rmtree(self.root, ignore_errors=True)
|
|
@@ -17,7 +17,7 @@ import contextlib
|
|
|
17
17
|
import time
|
|
18
18
|
import uuid
|
|
19
19
|
from collections import deque
|
|
20
|
-
from collections.abc import AsyncIterator, Mapping
|
|
20
|
+
from collections.abc import AsyncIterator, Callable, Mapping
|
|
21
21
|
from dataclasses import dataclass, field
|
|
22
22
|
from datetime import UTC, datetime
|
|
23
23
|
from typing import Any, Literal
|
|
@@ -109,9 +109,18 @@ class _Pool:
|
|
|
109
109
|
|
|
110
110
|
|
|
111
111
|
class RunManager:
|
|
112
|
-
def __init__(
|
|
112
|
+
def __init__(
|
|
113
|
+
self,
|
|
114
|
+
registry: AgentRegistry,
|
|
115
|
+
settings: ApiSettings,
|
|
116
|
+
*,
|
|
117
|
+
on_forget: Callable[[str], None] | None = None,
|
|
118
|
+
on_sweep: Callable[[], object] | None = None,
|
|
119
|
+
) -> None:
|
|
113
120
|
self.registry = registry
|
|
114
121
|
self.settings = settings
|
|
122
|
+
self.on_forget = on_forget # called with the id of each run that is forgotten
|
|
123
|
+
self.on_sweep = on_sweep # called on every sweep, for other housekeeping
|
|
115
124
|
self.runs: dict[str, Run] = {}
|
|
116
125
|
self.pools = {
|
|
117
126
|
"llm": _Pool(settings.llm_concurrency), # runs on the local model (one GPU)
|
|
@@ -140,6 +149,7 @@ class RunManager:
|
|
|
140
149
|
*,
|
|
141
150
|
llm: LLMClient | None = None,
|
|
142
151
|
provider: str | None = None,
|
|
152
|
+
run_id: str | None = None,
|
|
143
153
|
) -> Run:
|
|
144
154
|
"""Queue a run. ``llm`` is this run's model client (created from the current
|
|
145
155
|
settings, so a change in settings applies to the next run); ``provider`` decides the
|
|
@@ -147,7 +157,7 @@ class RunManager:
|
|
|
147
157
|
from margin_core import CancellationToken
|
|
148
158
|
|
|
149
159
|
pool = "llm" if agent_cls.uses_llm and provider == "local" else "other"
|
|
150
|
-
run = Run(id=uuid.uuid4().hex, agent_id=agent_cls.id, pool=pool)
|
|
160
|
+
run = Run(id=run_id or uuid.uuid4().hex, agent_id=agent_cls.id, pool=pool)
|
|
151
161
|
if agent_cls.uses_llm:
|
|
152
162
|
run.llm, run.llm_provider = llm, provider
|
|
153
163
|
run.llm_model = llm.model if llm is not None else None
|
|
@@ -310,7 +320,11 @@ class RunManager:
|
|
|
310
320
|
key=lambda r: r.finished_monotonic or 0.0,
|
|
311
321
|
)
|
|
312
322
|
while len(self.runs) > self.settings.max_runs and finished:
|
|
313
|
-
self.
|
|
323
|
+
self._forget(finished.pop(0).id)
|
|
324
|
+
|
|
325
|
+
def _forget(self, run_id: str) -> None:
|
|
326
|
+
if self.runs.pop(run_id, None) is not None and self.on_forget is not None:
|
|
327
|
+
self.on_forget(run_id)
|
|
314
328
|
|
|
315
329
|
def sweep(self) -> int:
|
|
316
330
|
"""Forget finished runs older than the TTL. Returns how many were removed."""
|
|
@@ -321,7 +335,9 @@ class RunManager:
|
|
|
321
335
|
and now - r.finished_monotonic > self.settings.result_ttl_s
|
|
322
336
|
] # fmt: skip
|
|
323
337
|
for run_id in expired:
|
|
324
|
-
self.
|
|
338
|
+
self._forget(run_id)
|
|
339
|
+
if self.on_sweep is not None:
|
|
340
|
+
self.on_sweep()
|
|
325
341
|
return len(expired)
|
|
326
342
|
|
|
327
343
|
async def _sweep_forever(self) -> None:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""API server settings, from ``MARGIN_API_*`` environment variables (and
|
|
1
|
+
"""API server settings, from ``MARGIN_API_*`` environment variables (and ``MARGIN_ENV_FILE``)."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
@@ -12,13 +12,18 @@ class ApiSettings(BaseSettings):
|
|
|
12
12
|
|
|
13
13
|
host: str = "127.0.0.1" # not exposed on the network unless you choose to
|
|
14
14
|
port: int = 8000
|
|
15
|
-
|
|
15
|
+
# Other web pages allowed to call the API. The UI it serves itself needs none; the UI's dev
|
|
16
|
+
# server does (see ui/README.md).
|
|
17
|
+
cors_origins: list[str] = []
|
|
16
18
|
# Host names the API answers to (protects against DNS rebinding). Add yours if you
|
|
17
19
|
# change ``host`` to expose the API on a network.
|
|
18
20
|
allowed_hosts: list[str] = ["127.0.0.1", "localhost"]
|
|
19
21
|
# A built web UI (ui/dist) to serve from the same address, so one server is the whole app.
|
|
20
22
|
ui_dir: str | None = None
|
|
21
23
|
max_body_bytes: int = 1_000_000
|
|
24
|
+
# uploads from the web UI and the files runs write; a temporary folder when not set
|
|
25
|
+
files_dir: str | None = None
|
|
26
|
+
max_upload_bytes: int = 200_000_000
|
|
22
27
|
llm_concurrency: int = 1 # runs of agents that use a model (a local model has one GPU)
|
|
23
28
|
other_concurrency: int = 4 # runs of agents that do not
|
|
24
29
|
result_ttl_s: float = 3600.0 # finished runs are forgotten after this
|
|
@@ -29,5 +34,5 @@ class ApiSettings(BaseSettings):
|
|
|
29
34
|
|
|
30
35
|
|
|
31
36
|
def load_settings() -> ApiSettings:
|
|
32
|
-
|
|
33
|
-
return ApiSettings(_env_file=
|
|
37
|
+
# never a .env in the current folder: it could open the server to the network
|
|
38
|
+
return ApiSettings(_env_file=os.environ.get("MARGIN_ENV_FILE") or None) # type: ignore[call-arg]
|