margin-api 0.1.0__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.0 → margin_api-0.1.2}/.gitignore +2 -0
- margin_api-0.1.2/CHANGELOG.md +61 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/PKG-INFO +23 -7
- {margin_api-0.1.0 → margin_api-0.1.2}/README.md +20 -4
- {margin_api-0.1.0 → margin_api-0.1.2}/pyproject.toml +3 -3
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/__init__.py +1 -1
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/app.py +188 -11
- margin_api-0.1.2/src/margin_api/files.py +104 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/jobs.py +123 -30
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/settings.py +10 -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.0 → margin_api-0.1.2}/src/margin_api/ui/index.html +2 -2
- {margin_api-0.1.0 → margin_api-0.1.2}/tests/test_api.py +297 -9
- margin_api-0.1.0/CHANGELOG.md +0 -13
- margin_api-0.1.0/src/margin_api/ui/assets/index-DIeVYF0g.js +0 -11
- margin_api-0.1.0/src/margin_api/ui/assets/index-Do_ARaDC.css +0 -1
- {margin_api-0.1.0 → margin_api-0.1.2}/LICENSE +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/llm_settings.py +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/main.py +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/py.typed +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/fonts/OFL-fraunces.txt +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/fonts/OFL-instrument-sans.txt +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/fonts/OFL-jetbrains-mono.txt +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/fonts/fraunces-latin-ext.woff2 +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/fonts/fraunces-latin.woff2 +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/fonts/instrument-sans-latin-ext.woff2 +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/fonts/instrument-sans-latin.woff2 +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/fonts/jetbrains-mono-latin.woff2 +0 -0
- {margin_api-0.1.0 → margin_api-0.1.2}/src/margin_api/ui/mark.svg +0 -0
|
@@ -75,6 +75,8 @@ tmp/
|
|
|
75
75
|
|
|
76
76
|
# Private planning notes (kept locally, not published)
|
|
77
77
|
PLAN.md
|
|
78
|
+
# notes for Claude Code sessions; a CLAUDE.md in the repo is one of the detector's markers
|
|
79
|
+
CLAUDE.md
|
|
78
80
|
|
|
79
81
|
# the web UI bundled into margin-api at release time (scripts/build_release.py)
|
|
80
82
|
packages/api/src/margin_api/ui/
|
|
@@ -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,18 +43,20 @@ 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. |
|
|
56
57
|
| `MARGIN_API_MAX_BODY_BYTES` | `1000000` | Largest accepted request body. |
|
|
57
58
|
| `MARGIN_API_CANCEL_GRACE_S` | `30` | Time a cancelled run gets to stop on its own before it is stopped. |
|
|
59
|
+
| `MARGIN_API_ANSWER_TIMEOUT_S` | `3600` | How long a run waits for answers to its questions before it stops. |
|
|
58
60
|
|
|
59
61
|
Model settings (`DEFAULT_LLM_PROVIDER`, `LOCAL_LLM_BASE_URL`, ...) are the same as for the CLI.
|
|
60
62
|
|
|
@@ -66,8 +68,9 @@ Model settings (`DEFAULT_LLM_PROVIDER`, `LOCAL_LLM_BASE_URL`, ...) are the same
|
|
|
66
68
|
| `GET /agents` | Installed agents with their input and output JSON schemas, plus any that failed to load. |
|
|
67
69
|
| `GET /agents/{id}` | One agent. |
|
|
68
70
|
| `POST /agents/{id}/runs` | Start a run. The body is the agent's input as JSON; `?provider=` and `?model=` choose the model for this run only. Answers `202` with the `run_id`. |
|
|
69
|
-
| `GET /runs/{run_id}` | Status (`queued`, `running`, `done`, `cancelled`), queue position, latest progress and, when done, the result. |
|
|
70
|
-
| `GET /runs/{run_id}/events` | Server-sent events: `status`, `progress`, then one final `result`. |
|
|
71
|
+
| `GET /runs/{run_id}` | Status (`queued`, `running`, `waiting`, `done`, `cancelled`), queue position, latest progress, the open questions while `waiting` and, when done, the result. |
|
|
72
|
+
| `GET /runs/{run_id}/events` | Server-sent events: `status`, `progress`, `question` when the agent asks something, then one final `result`. |
|
|
73
|
+
| `POST /runs/{run_id}/answers` | Answer a waiting run: `{"batch": "<question.id>", "answers": {"<question id>": value}}`. A question left out takes its default. `422` if an answer does not fit, `409` if the run is not waiting for these questions. |
|
|
71
74
|
| `DELETE /runs/{run_id}` | Cancel a run. |
|
|
72
75
|
| `GET /runs` | Recent runs. |
|
|
73
76
|
| `GET /settings/llm` | Model settings: the provider in use, each provider's model, whether a key is set (with its last four characters, never the key), and where each value comes from. |
|
|
@@ -108,8 +111,21 @@ When an agent fails, the run still finishes as `done`; the failure is in its res
|
|
|
108
111
|
agent or run, `422` for input that doesn't match the agent's schema, `413` for a body that's
|
|
109
112
|
too large, and `500` for an agent that failed to load.
|
|
110
113
|
|
|
114
|
+
Some agents stop to ask a question. The run then moves to `waiting`, sends a `question`
|
|
115
|
+
event, and its `GET /runs/{run_id}` view carries the questions. A waiting run gives up its
|
|
116
|
+
place in the queue, so a question nobody answers never holds the GPU. Once you post the
|
|
117
|
+
answers it goes back to `queued` and continues when a place is free. A run nobody answers
|
|
118
|
+
stops after an hour (`MARGIN_API_ANSWER_TIMEOUT_S`) with an error result.
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
curl -s -X POST http://127.0.0.1:8000/runs/342e1c.../answers \
|
|
122
|
+
-H 'content-type: application/json' \
|
|
123
|
+
-d '{"batch": "9f2c...", "answers": {"style": "capitals"}}'
|
|
124
|
+
```
|
|
125
|
+
|
|
111
126
|
Cancelling asks the agent to stop at its next checkpoint. A model call already under way is
|
|
112
127
|
allowed to finish, and an agent that still hasn't stopped after the grace period is stopped.
|
|
128
|
+
A waiting run stops at once.
|
|
113
129
|
|
|
114
130
|
Runs live in memory. They're gone after an hour, or when the server restarts, so export a
|
|
115
131
|
result if you want to keep it.
|
|
@@ -13,18 +13,20 @@ 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. |
|
|
26
27
|
| `MARGIN_API_MAX_BODY_BYTES` | `1000000` | Largest accepted request body. |
|
|
27
28
|
| `MARGIN_API_CANCEL_GRACE_S` | `30` | Time a cancelled run gets to stop on its own before it is stopped. |
|
|
29
|
+
| `MARGIN_API_ANSWER_TIMEOUT_S` | `3600` | How long a run waits for answers to its questions before it stops. |
|
|
28
30
|
|
|
29
31
|
Model settings (`DEFAULT_LLM_PROVIDER`, `LOCAL_LLM_BASE_URL`, ...) are the same as for the CLI.
|
|
30
32
|
|
|
@@ -36,8 +38,9 @@ Model settings (`DEFAULT_LLM_PROVIDER`, `LOCAL_LLM_BASE_URL`, ...) are the same
|
|
|
36
38
|
| `GET /agents` | Installed agents with their input and output JSON schemas, plus any that failed to load. |
|
|
37
39
|
| `GET /agents/{id}` | One agent. |
|
|
38
40
|
| `POST /agents/{id}/runs` | Start a run. The body is the agent's input as JSON; `?provider=` and `?model=` choose the model for this run only. Answers `202` with the `run_id`. |
|
|
39
|
-
| `GET /runs/{run_id}` | Status (`queued`, `running`, `done`, `cancelled`), queue position, latest progress and, when done, the result. |
|
|
40
|
-
| `GET /runs/{run_id}/events` | Server-sent events: `status`, `progress`, then one final `result`. |
|
|
41
|
+
| `GET /runs/{run_id}` | Status (`queued`, `running`, `waiting`, `done`, `cancelled`), queue position, latest progress, the open questions while `waiting` and, when done, the result. |
|
|
42
|
+
| `GET /runs/{run_id}/events` | Server-sent events: `status`, `progress`, `question` when the agent asks something, then one final `result`. |
|
|
43
|
+
| `POST /runs/{run_id}/answers` | Answer a waiting run: `{"batch": "<question.id>", "answers": {"<question id>": value}}`. A question left out takes its default. `422` if an answer does not fit, `409` if the run is not waiting for these questions. |
|
|
41
44
|
| `DELETE /runs/{run_id}` | Cancel a run. |
|
|
42
45
|
| `GET /runs` | Recent runs. |
|
|
43
46
|
| `GET /settings/llm` | Model settings: the provider in use, each provider's model, whether a key is set (with its last four characters, never the key), and where each value comes from. |
|
|
@@ -78,8 +81,21 @@ When an agent fails, the run still finishes as `done`; the failure is in its res
|
|
|
78
81
|
agent or run, `422` for input that doesn't match the agent's schema, `413` for a body that's
|
|
79
82
|
too large, and `500` for an agent that failed to load.
|
|
80
83
|
|
|
84
|
+
Some agents stop to ask a question. The run then moves to `waiting`, sends a `question`
|
|
85
|
+
event, and its `GET /runs/{run_id}` view carries the questions. A waiting run gives up its
|
|
86
|
+
place in the queue, so a question nobody answers never holds the GPU. Once you post the
|
|
87
|
+
answers it goes back to `queued` and continues when a place is free. A run nobody answers
|
|
88
|
+
stops after an hour (`MARGIN_API_ANSWER_TIMEOUT_S`) with an error result.
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
curl -s -X POST http://127.0.0.1:8000/runs/342e1c.../answers \
|
|
92
|
+
-H 'content-type: application/json' \
|
|
93
|
+
-d '{"batch": "9f2c...", "answers": {"style": "capitals"}}'
|
|
94
|
+
```
|
|
95
|
+
|
|
81
96
|
Cancelling asks the agent to stop at its next checkpoint. A model call already under way is
|
|
82
97
|
allowed to finish, and an agent that still hasn't stopped after the grace period is stopped.
|
|
98
|
+
A waiting run stops at once.
|
|
83
99
|
|
|
84
100
|
Runs live in memory. They're gone after an hour, or when the server restarts, so export a
|
|
85
101
|
result if you want to keep it.
|
|
@@ -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
|
|
@@ -23,16 +27,18 @@ from margin_core import (
|
|
|
23
27
|
BaseAgent,
|
|
24
28
|
InputValidationError,
|
|
25
29
|
ProgressEvent,
|
|
30
|
+
QuestionBatch,
|
|
26
31
|
default_registry,
|
|
27
32
|
)
|
|
28
33
|
from margin_core.config import get_settings
|
|
29
34
|
from margin_core.llm import LLMClient, create_llm
|
|
30
35
|
from margin_core.logging import get_logger
|
|
31
|
-
from pydantic import BaseModel, Field
|
|
36
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
32
37
|
from sse_starlette.sse import EventSourceResponse
|
|
33
38
|
|
|
34
39
|
from margin_api import __version__
|
|
35
|
-
from margin_api.
|
|
40
|
+
from margin_api.files import OUTPUT_FORMAT, FileStore, RunFile, fields_with_format
|
|
41
|
+
from margin_api.jobs import NotWaitingError, Run, RunManager, RunStatus
|
|
36
42
|
from margin_api.llm_settings import router as llm_settings_router
|
|
37
43
|
from margin_api.settings import ApiSettings, load_settings
|
|
38
44
|
|
|
@@ -74,6 +80,32 @@ class RunView(BaseModel):
|
|
|
74
80
|
finished_at: datetime | None
|
|
75
81
|
result: AgentResult | None = Field(description="Present once the run is done.")
|
|
76
82
|
llm: RunModel | None = Field(default=None, description="The model this run uses, if any.")
|
|
83
|
+
question: QuestionBatch | None = Field(
|
|
84
|
+
default=None, description="What the run is asking; present only while it is waiting."
|
|
85
|
+
)
|
|
86
|
+
last_event: int = Field(
|
|
87
|
+
default=0, description="Number of the latest event; this view already includes it."
|
|
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
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class AnswersBody(BaseModel):
|
|
102
|
+
model_config = ConfigDict(extra="forbid")
|
|
103
|
+
|
|
104
|
+
batch: str = Field(description="The id of the questions being answered (`question.id`).")
|
|
105
|
+
answers: dict[str, Any] = Field(
|
|
106
|
+
default_factory=dict,
|
|
107
|
+
description="Answers by question id. A question left out takes its default.",
|
|
108
|
+
)
|
|
77
109
|
|
|
78
110
|
|
|
79
111
|
class _BodyLimit:
|
|
@@ -83,12 +115,17 @@ class _BodyLimit:
|
|
|
83
115
|
error raised while the app reads its body would be reported as a generic 400.
|
|
84
116
|
"""
|
|
85
117
|
|
|
86
|
-
def __init__(self, app: Any, limit: int) -> None:
|
|
118
|
+
def __init__(self, app: Any, limit: int, exempt: tuple[str, ...] = ()) -> None:
|
|
87
119
|
self.app = app
|
|
88
120
|
self.limit = limit
|
|
121
|
+
self.exempt = exempt # paths that stream their body and limit it themselves
|
|
89
122
|
|
|
90
123
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
91
|
-
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
|
+
):
|
|
92
129
|
await self.app(scope, receive, send)
|
|
93
130
|
return
|
|
94
131
|
headers = dict(scope.get("headers") or [])
|
|
@@ -128,6 +165,39 @@ class _BodyLimit:
|
|
|
128
165
|
await send({"type": "http.response.body", "body": body})
|
|
129
166
|
|
|
130
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
|
+
|
|
131
201
|
LLMFactory = Callable[[str | None, str | None], LLMClient | None]
|
|
132
202
|
|
|
133
203
|
|
|
@@ -144,7 +214,13 @@ def create_app(
|
|
|
144
214
|
) -> FastAPI:
|
|
145
215
|
settings = settings or load_settings()
|
|
146
216
|
registry = registry or default_registry()
|
|
147
|
-
|
|
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
|
+
)
|
|
148
224
|
|
|
149
225
|
@asynccontextmanager
|
|
150
226
|
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
|
@@ -153,6 +229,7 @@ def create_app(
|
|
|
153
229
|
yield
|
|
154
230
|
finally:
|
|
155
231
|
await manager.stop()
|
|
232
|
+
store.close()
|
|
156
233
|
|
|
157
234
|
app = FastAPI(
|
|
158
235
|
title="margin API",
|
|
@@ -170,11 +247,12 @@ def create_app(
|
|
|
170
247
|
allow_methods=["GET", "POST", "PUT", "DELETE"],
|
|
171
248
|
allow_headers=["Content-Type", "Last-Event-ID"],
|
|
172
249
|
)
|
|
173
|
-
app.add_middleware(_BodyLimit, limit=settings.max_body_bytes)
|
|
250
|
+
app.add_middleware(_BodyLimit, limit=settings.max_body_bytes, exempt=("/uploads",))
|
|
174
251
|
ui_dir = Path(settings.ui_dir) if settings.ui_dir else _bundled_ui()
|
|
175
252
|
ui_root = _ui_root(ui_dir) if ui_dir is not None else None
|
|
176
253
|
if ui_root is not None:
|
|
177
254
|
app.add_middleware(_UIPages, root=ui_root)
|
|
255
|
+
app.add_middleware(_OriginCheck, allowed=settings.cors_origins)
|
|
178
256
|
# Only answer requests addressed to this machine by name. Without this, a web page could
|
|
179
257
|
# use DNS rebinding to reach the API through a domain of its own and read local results.
|
|
180
258
|
app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.allowed_hosts)
|
|
@@ -201,7 +279,8 @@ def create_app(
|
|
|
201
279
|
queue_position=manager.queue_position(run), progress=run.progress,
|
|
202
280
|
created_at=run.created_at, started_at=run.started_at,
|
|
203
281
|
finished_at=run.finished_at, result=run.result,
|
|
204
|
-
llm=llm,
|
|
282
|
+
llm=llm, question=run.question, last_event=run.last_event,
|
|
283
|
+
files=store.run_files(run.id) if run.status == "done" else [],
|
|
205
284
|
) # fmt: skip
|
|
206
285
|
|
|
207
286
|
@app.get("/health", tags=["meta"])
|
|
@@ -235,6 +314,15 @@ def create_app(
|
|
|
235
314
|
),
|
|
236
315
|
) -> RunCreated:
|
|
237
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))}
|
|
238
326
|
try:
|
|
239
327
|
parsed = cls.parse_input(body)
|
|
240
328
|
except InputValidationError as exc:
|
|
@@ -248,7 +336,7 @@ def create_app(
|
|
|
248
336
|
if provider or model: # a choice made for this run must work, or say why
|
|
249
337
|
raise HTTPException(422, f"Cannot use that model: {exc}") from exc
|
|
250
338
|
logger.warning("No model client for %s: %s", agent_id, exc)
|
|
251
|
-
run = manager.submit(cls, parsed, llm=llm, provider=resolved)
|
|
339
|
+
run = manager.submit(cls, parsed, llm=llm, provider=resolved, run_id=run_id)
|
|
252
340
|
return RunCreated(
|
|
253
341
|
run_id=run.id,
|
|
254
342
|
status=run.status,
|
|
@@ -271,11 +359,91 @@ def create_app(
|
|
|
271
359
|
await manager.cancel(run)
|
|
272
360
|
return view(run)
|
|
273
361
|
|
|
362
|
+
@app.post(
|
|
363
|
+
"/runs/{run_id}/answers",
|
|
364
|
+
response_model=RunView,
|
|
365
|
+
status_code=202,
|
|
366
|
+
tags=["runs"],
|
|
367
|
+
responses={
|
|
368
|
+
409: {"description": "The run is not waiting for these answers"},
|
|
369
|
+
422: {"description": "The answers do not fit the questions"},
|
|
370
|
+
},
|
|
371
|
+
)
|
|
372
|
+
async def answer_run(run_id: str, body: AnswersBody) -> RunView:
|
|
373
|
+
"""Answer the questions a waiting run asked; the run then carries on."""
|
|
374
|
+
run = find_run(run_id)
|
|
375
|
+
try:
|
|
376
|
+
manager.answer(run, body.batch, body.answers)
|
|
377
|
+
except NotWaitingError as exc:
|
|
378
|
+
raise HTTPException(409, str(exc)) from exc
|
|
379
|
+
except ValueError as exc:
|
|
380
|
+
raise HTTPException(422, f"Invalid answers: {exc}") from exc
|
|
381
|
+
return view(run)
|
|
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
|
+
|
|
274
442
|
@app.get(
|
|
275
443
|
"/runs/{run_id}/events",
|
|
276
444
|
tags=["runs"],
|
|
277
445
|
response_class=EventSourceResponse,
|
|
278
|
-
responses={200: {"description": "Server-sent events: status, progress, result"}},
|
|
446
|
+
responses={200: {"description": "Server-sent events: status, progress, question, result"}},
|
|
279
447
|
)
|
|
280
448
|
async def run_events(run_id: str, request: Request) -> EventSourceResponse:
|
|
281
449
|
run = find_run(run_id)
|
|
@@ -312,6 +480,8 @@ class _UIPages:
|
|
|
312
480
|
"""
|
|
313
481
|
|
|
314
482
|
API_PAGES = ("/docs", "/redoc", "/openapi.json")
|
|
483
|
+
DOWNLOADS = re.compile(r"^/runs/[^/]+/files/") # a download link also asks for HTML
|
|
484
|
+
PAGE_HEADERS = {"Vary": "Accept", "Cache-Control": "no-cache"}
|
|
315
485
|
|
|
316
486
|
def __init__(self, app: Any, root: Path) -> None:
|
|
317
487
|
self.app = app
|
|
@@ -323,10 +493,17 @@ class _UIPages:
|
|
|
323
493
|
headers = dict(scope.get("headers") or [])
|
|
324
494
|
accept = headers.get(b"accept", b"").decode("latin-1")
|
|
325
495
|
path = str(scope.get("path", "/"))
|
|
326
|
-
if
|
|
496
|
+
if (
|
|
497
|
+
"text/html" in accept
|
|
498
|
+
and not path.startswith(self.API_PAGES)
|
|
499
|
+
and not self.DOWNLOADS.match(path)
|
|
500
|
+
):
|
|
327
501
|
candidate = (self.root / path.lstrip("/")).resolve()
|
|
328
502
|
if not (candidate.is_file() and self.root in candidate.parents):
|
|
329
|
-
|
|
503
|
+
# the page shares its URL with the API's JSON: without Vary the browser
|
|
504
|
+
# would answer the UI's own fetch of /runs/<id> with this cached page
|
|
505
|
+
page = FileResponse(self.index, headers=self.PAGE_HEADERS)
|
|
506
|
+
await page(scope, receive, send)
|
|
330
507
|
return
|
|
331
508
|
await self.app(scope, receive, send)
|
|
332
509
|
|
|
@@ -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)
|