margin-api 0.1.1__tar.gz → 0.1.3__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.
Files changed (46) hide show
  1. {margin_api-0.1.1 → margin_api-0.1.3}/.gitignore +3 -0
  2. margin_api-0.1.3/CHANGELOG.md +78 -0
  3. {margin_api-0.1.1 → margin_api-0.1.3}/PKG-INFO +6 -5
  4. {margin_api-0.1.1 → margin_api-0.1.3}/README.md +3 -2
  5. {margin_api-0.1.1 → margin_api-0.1.3}/pyproject.toml +3 -3
  6. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/__init__.py +1 -1
  7. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/app.py +150 -6
  8. margin_api-0.1.3/src/margin_api/files.py +110 -0
  9. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/jobs.py +22 -5
  10. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/settings.py +9 -4
  11. margin_api-0.1.3/src/margin_api/ui/assets/DetectorIntro-CZqT1q7b.css +1 -0
  12. margin_api-0.1.3/src/margin_api/ui/assets/DetectorIntro-oYcans9E.js +1 -0
  13. margin_api-0.1.3/src/margin_api/ui/assets/DetectorResult-Bl7coSts.js +1 -0
  14. margin_api-0.1.3/src/margin_api/ui/assets/DetectorResult-C4-rIW-m.css +1 -0
  15. margin_api-0.1.3/src/margin_api/ui/assets/HistoryResult-DQAIY3S5.js +1 -0
  16. margin_api-0.1.3/src/margin_api/ui/assets/HistoryResult-H34WYgcB.css +1 -0
  17. margin_api-0.1.3/src/margin_api/ui/assets/StorytellerResult-B16gafwk.css +1 -0
  18. margin_api-0.1.3/src/margin_api/ui/assets/StorytellerResult-CZQJD__F.js +1 -0
  19. margin_api-0.1.3/src/margin_api/ui/assets/index-B3Snzalk.js +12 -0
  20. margin_api-0.1.3/src/margin_api/ui/assets/index-DjLxjAZZ.css +1 -0
  21. margin_api-0.1.1/src/margin_api/ui/fonts/OFL-fraunces.txt → margin_api-0.1.3/src/margin_api/ui/fonts/OFL-archivo.txt +1 -1
  22. margin_api-0.1.1/src/margin_api/ui/fonts/OFL-instrument-sans.txt → margin_api-0.1.3/src/margin_api/ui/fonts/OFL-newsreader.txt +3 -3
  23. margin_api-0.1.3/src/margin_api/ui/fonts/archivo-latin-ext.woff2 +0 -0
  24. margin_api-0.1.3/src/margin_api/ui/fonts/archivo-latin.woff2 +0 -0
  25. margin_api-0.1.3/src/margin_api/ui/fonts/newsreader-italic-latin-ext.woff2 +0 -0
  26. margin_api-0.1.3/src/margin_api/ui/fonts/newsreader-italic-latin.woff2 +0 -0
  27. margin_api-0.1.3/src/margin_api/ui/fonts/newsreader-latin-ext.woff2 +0 -0
  28. margin_api-0.1.3/src/margin_api/ui/fonts/newsreader-latin.woff2 +0 -0
  29. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/ui/index.html +2 -2
  30. margin_api-0.1.3/src/margin_api/ui/mark.svg +1 -0
  31. {margin_api-0.1.1 → margin_api-0.1.3}/tests/test_api.py +198 -7
  32. margin_api-0.1.1/CHANGELOG.md +0 -33
  33. margin_api-0.1.1/src/margin_api/ui/assets/index-CDckCtOp.css +0 -1
  34. margin_api-0.1.1/src/margin_api/ui/assets/index-CP-J9KRj.js +0 -11
  35. margin_api-0.1.1/src/margin_api/ui/fonts/fraunces-latin-ext.woff2 +0 -0
  36. margin_api-0.1.1/src/margin_api/ui/fonts/fraunces-latin.woff2 +0 -0
  37. margin_api-0.1.1/src/margin_api/ui/fonts/instrument-sans-latin-ext.woff2 +0 -0
  38. margin_api-0.1.1/src/margin_api/ui/fonts/instrument-sans-latin.woff2 +0 -0
  39. margin_api-0.1.1/src/margin_api/ui/mark.svg +0 -1
  40. {margin_api-0.1.1 → margin_api-0.1.3}/LICENSE +0 -0
  41. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/llm_settings.py +0 -0
  42. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/main.py +0 -0
  43. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/py.typed +0 -0
  44. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/ui/fonts/OFL-jetbrains-mono.txt +0 -0
  45. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/ui/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  46. {margin_api-0.1.1 → margin_api-0.1.3}/src/margin_api/ui/fonts/jetbrains-mono-latin.woff2 +0 -0
@@ -80,3 +80,6 @@ CLAUDE.md
80
80
 
81
81
  # the web UI bundled into margin-api at release time (scripts/build_release.py)
82
82
  packages/api/src/margin_api/ui/
83
+
84
+ # local agent plugins and state
85
+ .agents/
@@ -0,0 +1,78 @@
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
+ ## [0.1.3] - 2026-11-20
8
+
9
+ ### Added
10
+ - `RunView.input`: the input as the caller sent it, without the run's own output folder.
11
+ Sending it again repeats the run; the web UI uses it for "Run again".
12
+ - The bundled web UI names each browser tab after its page; a run's tab shows its progress or
13
+ that it needs an answer.
14
+ - The bundled web UI has a view for the Commit Graph agent: the history drawn as a tree with
15
+ notes in the margin, a replay slider, chapters, and findings or a file lit up on the tree.
16
+
17
+ ### Changed
18
+ - The bundled web UI is redesigned around a ruled margin: notes on the left, content on the
19
+ right, red for what was flagged and blue for what was checked.
20
+ - Result views load only when first shown.
21
+
22
+ ### Fixed
23
+ - An upload named after a Windows device, such as `NUL` or `con.csv`, gets a `_` in front, so
24
+ Windows saves it as a file instead of throwing it away.
25
+
26
+ ## [0.1.2] - 2026-11-02
27
+
28
+ ### Added
29
+ - Uploads: `POST /uploads?name=<file>` saves the request body as a file and returns its path,
30
+ for an agent's input. Uploads have their own size limit, `MARGIN_API_MAX_UPLOAD_BYTES`
31
+ (200 MB), and are deleted after the result TTL.
32
+ - Run files: an input field marked `"format": "output-dir"` and left empty gets a folder of
33
+ the run's own. The run view lists what the run wrote there (`files`), and
34
+ `GET /runs/{run_id}/files/{name}` downloads it. The folder goes when the run is forgotten.
35
+ - `MARGIN_API_FILES_DIR` sets where uploads and run files are kept (a temporary folder,
36
+ removed on shutdown, when not set).
37
+ - The web UI uploads a file for an input field marked `"format": "file-path"` (drop it or
38
+ choose it, on the agent page and in the home page launcher), and offers a run's files for
39
+ download next to the JSON and Markdown exports.
40
+
41
+ ### Security
42
+ - Requests that change something are refused with 403 if they come from another web page. CORS
43
+ only hid the answer, so any site you visited could upload files. Requires FastAPI 0.132 or
44
+ later, which also stops a page from starting a run with a JSON body and no `Content-Type`.
45
+ - `MARGIN_API_CORS_ORIGINS` is now empty by default. The UI the API serves itself is unaffected;
46
+ to use the UI's dev server, add `http://localhost:3000` (see `ui/README.md`).
47
+ - An output folder can no longer be chosen over HTTP (422), so a caller can't write files
48
+ elsewhere on the machine. Each run writes to its own folder.
49
+ - A `.env` in the current folder is no longer read, because it could open the server to the
50
+ network. Name a file with `MARGIN_ENV_FILE`.
51
+
52
+ ## [0.1.1] - 2026-10-29
53
+
54
+ ### Added
55
+ - Runs can stop to ask a question. A run whose agent asks moves to the new `waiting` status,
56
+ sends a `question` event and shows the questions in `GET /runs/{run_id}`;
57
+ `POST /runs/{run_id}/answers` answers them. While waiting, a run gives its place in the
58
+ queue to others, and it stops after `MARGIN_API_ANSWER_TIMEOUT_S` (an hour) without answers.
59
+ - `last_event` in the run view: the number of the latest event it already includes, so a
60
+ client can tell replayed events from new ones.
61
+ - The web UI shows an agent's questions as a form on the run page, and every result lists
62
+ the answers and who gave them.
63
+
64
+ ### Changed
65
+ - `waiting` is a new run status. A client that lists every status must handle it.
66
+
67
+ ### Fixed
68
+ - Opening a run page directly (a link or a reload) with the UI served by the API showed
69
+ "Can't reach the API": the browser answered the UI's own request for the run with the
70
+ cached page. Page loads now send `Vary: Accept` and `Cache-Control: no-cache`.
71
+
72
+ ## [0.1.0] - 2026-10-21
73
+
74
+ ### Added
75
+ - Background runs with live progress (server-sent events), queue positions and cancellation.
76
+ - Model settings over HTTP: provider, models, keys (never returned), live model lists and a connection test.
77
+ - The web UI, bundled in the package and served from the same address.
78
+ - 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.1
3
+ Version: 0.1.3
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.111.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.2
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 `.env` file):
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` | `["http://localhost:3000", "http://127.0.0.1:3000"]` | Web pages allowed to call it (JSON list). |
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 `.env` file):
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` | `["http://localhost:3000", "http://127.0.0.1:3000"]` | Web pages allowed to call it (JSON list). |
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.1"
3
+ version = "0.1.3"
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.2,<0.2", # 0.1.2: questions (ctx.ask)
24
- "fastapi>=0.111.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",
@@ -1,3 +1,3 @@
1
1
  """HTTP API for margin."""
2
2
 
3
- __version__ = "0.1.1"
3
+ __version__ = "0.1.3"
@@ -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,21 @@ 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
+ input: dict[str, Any] = Field(
94
+ default_factory=dict,
95
+ description="The input as the caller sent it, without the run's own output folder. "
96
+ "Send it again to repeat the run.",
97
+ )
98
+
99
+
100
+ class Upload(BaseModel):
101
+ path: str = Field(description="Where the file was saved; give this to the agent's input.")
102
+ name: str
103
+ size: int
84
104
 
85
105
 
86
106
  class AnswersBody(BaseModel):
@@ -100,12 +120,17 @@ class _BodyLimit:
100
120
  error raised while the app reads its body would be reported as a generic 400.
101
121
  """
102
122
 
103
- def __init__(self, app: Any, limit: int) -> None:
123
+ def __init__(self, app: Any, limit: int, exempt: tuple[str, ...] = ()) -> None:
104
124
  self.app = app
105
125
  self.limit = limit
126
+ self.exempt = exempt # paths that stream their body and limit it themselves
106
127
 
107
128
  async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
108
- if scope["type"] != "http" or scope.get("method") in {"GET", "HEAD", "DELETE", "OPTIONS"}:
129
+ if (
130
+ scope["type"] != "http"
131
+ or scope.get("method") in {"GET", "HEAD", "DELETE", "OPTIONS"}
132
+ or scope.get("path") in self.exempt
133
+ ):
109
134
  await self.app(scope, receive, send)
110
135
  return
111
136
  headers = dict(scope.get("headers") or [])
@@ -145,6 +170,39 @@ class _BodyLimit:
145
170
  await send({"type": "http.response.body", "body": body})
146
171
 
147
172
 
173
+ class _OriginCheck:
174
+ """Refuse changes asked for by another web page, with 403.
175
+
176
+ CORS only stops a page from reading the answer. A plain POST still reaches the server, so
177
+ without this any site you visit could fill the disk through ``/uploads``. Programs send no
178
+ ``Origin`` and aren't affected; the UI's own requests come from the address they go to.
179
+ """
180
+
181
+ READS = {"GET", "HEAD", "OPTIONS"}
182
+
183
+ def __init__(self, app: Any, allowed: list[str]) -> None:
184
+ self.app = app
185
+ self.allowed = allowed
186
+
187
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
188
+ if scope["type"] == "http" and scope.get("method") not in self.READS:
189
+ headers = dict(scope.get("headers") or [])
190
+ origin = headers.get(b"origin", b"").decode("latin-1")
191
+ host = headers.get(b"host", b"").decode("latin-1")
192
+ if origin and not self._allowed(origin, host):
193
+ body = json.dumps({"detail": "Requests from other web pages are refused"}).encode()
194
+ await send({"type": "http.response.start", "status": 403,
195
+ "headers": [(b"content-type", b"application/json")]}) # fmt: skip
196
+ await send({"type": "http.response.body", "body": body})
197
+ return
198
+ await self.app(scope, receive, send)
199
+
200
+ def _allowed(self, origin: str, host: str) -> bool:
201
+ if origin in self.allowed or "*" in self.allowed:
202
+ return True
203
+ return bool(host) and urlsplit(origin).netloc == host # "null" has no address
204
+
205
+
148
206
  LLMFactory = Callable[[str | None, str | None], LLMClient | None]
149
207
 
150
208
 
@@ -161,7 +219,13 @@ def create_app(
161
219
  ) -> FastAPI:
162
220
  settings = settings or load_settings()
163
221
  registry = registry or default_registry()
164
- manager = RunManager(registry, settings)
222
+ store = FileStore(settings.files_dir)
223
+ manager = RunManager(
224
+ registry,
225
+ settings,
226
+ on_forget=store.forget_run,
227
+ on_sweep=lambda: store.sweep_uploads(settings.result_ttl_s),
228
+ )
165
229
 
166
230
  @asynccontextmanager
167
231
  async def lifespan(_: FastAPI) -> AsyncIterator[None]:
@@ -170,6 +234,7 @@ def create_app(
170
234
  yield
171
235
  finally:
172
236
  await manager.stop()
237
+ store.close()
173
238
 
174
239
  app = FastAPI(
175
240
  title="margin API",
@@ -187,11 +252,12 @@ def create_app(
187
252
  allow_methods=["GET", "POST", "PUT", "DELETE"],
188
253
  allow_headers=["Content-Type", "Last-Event-ID"],
189
254
  )
190
- app.add_middleware(_BodyLimit, limit=settings.max_body_bytes)
255
+ app.add_middleware(_BodyLimit, limit=settings.max_body_bytes, exempt=("/uploads",))
191
256
  ui_dir = Path(settings.ui_dir) if settings.ui_dir else _bundled_ui()
192
257
  ui_root = _ui_root(ui_dir) if ui_dir is not None else None
193
258
  if ui_root is not None:
194
259
  app.add_middleware(_UIPages, root=ui_root)
260
+ app.add_middleware(_OriginCheck, allowed=settings.cors_origins)
195
261
  # Only answer requests addressed to this machine by name. Without this, a web page could
196
262
  # use DNS rebinding to reach the API through a domain of its own and read local results.
197
263
  app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.allowed_hosts)
@@ -219,6 +285,8 @@ def create_app(
219
285
  created_at=run.created_at, started_at=run.started_at,
220
286
  finished_at=run.finished_at, result=run.result,
221
287
  llm=llm, question=run.question, last_event=run.last_event,
288
+ files=store.run_files(run.id) if run.status == "done" else [],
289
+ input=run.input,
222
290
  ) # fmt: skip
223
291
 
224
292
  @app.get("/health", tags=["meta"])
@@ -252,6 +320,17 @@ def create_app(
252
320
  ),
253
321
  ) -> RunCreated:
254
322
  cls = agent_class(agent_id)
323
+ run_id = uuid.uuid4().hex
324
+ output_fields = fields_with_format(cls.InputModel.model_json_schema(), OUTPUT_FORMAT)
325
+ sent = {k: v for k, v in body.items() if k not in output_fields}
326
+ # an output folder is always the run's own, so its files can be downloaded and a caller
327
+ # can't write over files elsewhere on this machine
328
+ for name in output_fields:
329
+ if body.get(name) not in (None, ""):
330
+ raise HTTPException(
331
+ 422, f"{name} can't be set over HTTP: each run writes to its own folder"
332
+ )
333
+ body = {**body, name: str(store.run_dir(run_id))}
255
334
  try:
256
335
  parsed = cls.parse_input(body)
257
336
  except InputValidationError as exc:
@@ -265,7 +344,8 @@ def create_app(
265
344
  if provider or model: # a choice made for this run must work, or say why
266
345
  raise HTTPException(422, f"Cannot use that model: {exc}") from exc
267
346
  logger.warning("No model client for %s: %s", agent_id, exc)
268
- run = manager.submit(cls, parsed, llm=llm, provider=resolved)
347
+ run = manager.submit(cls, parsed, llm=llm, provider=resolved, run_id=run_id)
348
+ run.input = sent
269
349
  return RunCreated(
270
350
  run_id=run.id,
271
351
  status=run.status,
@@ -309,6 +389,65 @@ def create_app(
309
389
  raise HTTPException(422, f"Invalid answers: {exc}") from exc
310
390
  return view(run)
311
391
 
392
+ @app.get(
393
+ "/runs/{run_id}/files/{name}",
394
+ tags=["runs"],
395
+ response_class=FileResponse,
396
+ responses={404: {"description": "No such file in the run's folder"}},
397
+ )
398
+ def run_file(run_id: str, name: str) -> FileResponse:
399
+ """Download a file the run wrote to its own folder (see the run's ``files``)."""
400
+ run = find_run(run_id)
401
+ path = store.run_file(run.id, name)
402
+ if path is None:
403
+ raise HTTPException(404, f"Run {run_id!r} has no file {name!r}")
404
+ return FileResponse(path, filename=path.name)
405
+
406
+ @app.post(
407
+ "/uploads",
408
+ status_code=201,
409
+ response_model=Upload,
410
+ tags=["files"],
411
+ openapi_extra={
412
+ "requestBody": {
413
+ "required": True,
414
+ "content": {
415
+ "application/octet-stream": {"schema": {"type": "string", "format": "binary"}}
416
+ },
417
+ }
418
+ },
419
+ responses={413: {"description": "The file is larger than MARGIN_API_MAX_UPLOAD_BYTES"}},
420
+ )
421
+ async def upload(
422
+ request: Request,
423
+ name: str = Query(min_length=1, max_length=255, description="The file's name."),
424
+ ) -> Upload:
425
+ """Save a file for a run to read. Send the file as the raw request body.
426
+
427
+ The response's ``path`` goes into the agent's input. Uploads are deleted after the
428
+ result TTL.
429
+ """
430
+ limit = settings.max_upload_bytes
431
+ declared = request.headers.get("content-length", "")
432
+ too_big = f"The file is larger than the {limit // 1_000_000} MB limit"
433
+ if declared.isdigit() and int(declared) > limit:
434
+ raise HTTPException(413, too_big)
435
+ path = store.new_upload(name)
436
+ size = 0
437
+ try:
438
+ with path.open("wb") as out:
439
+ async for chunk in request.stream():
440
+ size += len(chunk)
441
+ if size > limit:
442
+ raise HTTPException(413, too_big)
443
+ out.write(chunk)
444
+ if size == 0:
445
+ raise HTTPException(422, "The file is empty")
446
+ except BaseException:
447
+ shutil.rmtree(path.parent, ignore_errors=True)
448
+ raise
449
+ return Upload(path=str(path), name=path.name, size=size)
450
+
312
451
  @app.get(
313
452
  "/runs/{run_id}/events",
314
453
  tags=["runs"],
@@ -350,6 +489,7 @@ class _UIPages:
350
489
  """
351
490
 
352
491
  API_PAGES = ("/docs", "/redoc", "/openapi.json")
492
+ DOWNLOADS = re.compile(r"^/runs/[^/]+/files/") # a download link also asks for HTML
353
493
  PAGE_HEADERS = {"Vary": "Accept", "Cache-Control": "no-cache"}
354
494
 
355
495
  def __init__(self, app: Any, root: Path) -> None:
@@ -362,7 +502,11 @@ class _UIPages:
362
502
  headers = dict(scope.get("headers") or [])
363
503
  accept = headers.get(b"accept", b"").decode("latin-1")
364
504
  path = str(scope.get("path", "/"))
365
- if "text/html" in accept and not path.startswith(self.API_PAGES):
505
+ if (
506
+ "text/html" in accept
507
+ and not path.startswith(self.API_PAGES)
508
+ and not self.DOWNLOADS.match(path)
509
+ ):
366
510
  candidate = (self.root / path.lstrip("/")).resolve()
367
511
  if not (candidate.is_file() and self.root in candidate.parents):
368
512
  # the page shares its URL with the API's JSON: without Vary the browser
@@ -0,0 +1,110 @@
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
+ # names Windows keeps for devices: a file called NUL is thrown away as it's written
26
+ _DEVICES = frozenset(
27
+ {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(10)), *(f"LPT{i}" for i in range(10))}
28
+ )
29
+
30
+
31
+ class RunFile(BaseModel):
32
+ name: str
33
+ size: int
34
+
35
+
36
+ def safe_name(name: str) -> str:
37
+ """A file name with no folders and no characters that mean something to a shell or OS."""
38
+ base = re.split(r"[\\/]", name)[-1]
39
+ cleaned = _UNSAFE.sub("_", base).strip(" .")[:120]
40
+ if cleaned.split(".")[0].rstrip().upper() in _DEVICES:
41
+ cleaned = "_" + cleaned
42
+ return cleaned or "upload"
43
+
44
+
45
+ def fields_with_format(schema: dict[str, Any], fmt: str) -> list[str]:
46
+ """Input fields whose schema (or one of its variants) has ``format: fmt``."""
47
+ found = []
48
+ for name, prop in (schema.get("properties") or {}).items():
49
+ variants = [prop, *(prop.get("anyOf") or []), *(prop.get("oneOf") or [])]
50
+ if any(isinstance(v, dict) and v.get("format") == fmt for v in variants):
51
+ found.append(name)
52
+ return found
53
+
54
+
55
+ class FileStore:
56
+ def __init__(self, root: str | None = None) -> None:
57
+ self._owned = root is None
58
+ self.root = Path(root or tempfile.mkdtemp(prefix="margin-api-")).resolve()
59
+ self.uploads = self.root / "uploads"
60
+ self.runs = self.root / "runs"
61
+ self.uploads.mkdir(parents=True, exist_ok=True)
62
+ self.runs.mkdir(parents=True, exist_ok=True)
63
+
64
+ def new_upload(self, name: str) -> Path:
65
+ """Where to save an upload: its own folder, so two files with one name never clash."""
66
+ folder = self.uploads / uuid.uuid4().hex
67
+ folder.mkdir()
68
+ return folder / safe_name(name)
69
+
70
+ def run_dir(self, run_id: str) -> Path:
71
+ return self.runs / run_id
72
+
73
+ def run_files(self, run_id: str) -> list[RunFile]:
74
+ folder = self.run_dir(run_id)
75
+ if not folder.is_dir():
76
+ return []
77
+ return [
78
+ RunFile(name=p.name, size=p.stat().st_size)
79
+ for p in sorted(folder.iterdir())
80
+ if p.is_file()
81
+ ]
82
+
83
+ def run_file(self, run_id: str, name: str) -> Path | None:
84
+ """A file a run wrote, or None. Only plain names inside the run's own folder."""
85
+ if name != safe_name(name):
86
+ return None
87
+ folder = self.run_dir(run_id).resolve()
88
+ path = (folder / name).resolve()
89
+ return path if path.parent == folder and path.is_file() else None
90
+
91
+ def forget_run(self, run_id: str) -> None:
92
+ shutil.rmtree(self.run_dir(run_id), ignore_errors=True)
93
+
94
+ def sweep_uploads(self, max_age_s: float) -> int:
95
+ """Delete uploads older than ``max_age_s``. Returns how many were removed."""
96
+ cutoff = time.time() - max_age_s
97
+ removed = 0
98
+ for folder in self.uploads.iterdir():
99
+ try:
100
+ if folder.stat().st_mtime < cutoff:
101
+ shutil.rmtree(folder, ignore_errors=True)
102
+ removed += 1
103
+ except OSError:
104
+ continue
105
+ return removed
106
+
107
+ def close(self) -> None:
108
+ """Remove the root if the API made it (a folder it was given is left in place)."""
109
+ if self._owned:
110
+ 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
@@ -59,6 +59,7 @@ class Run:
59
59
  id: str
60
60
  agent_id: str
61
61
  pool: str
62
+ input: dict[str, Any] = field(default_factory=dict) # as the caller sent it
62
63
  status: RunStatus = "queued"
63
64
  created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
64
65
  started_at: datetime | None = None
@@ -109,9 +110,18 @@ class _Pool:
109
110
 
110
111
 
111
112
  class RunManager:
112
- def __init__(self, registry: AgentRegistry, settings: ApiSettings) -> None:
113
+ def __init__(
114
+ self,
115
+ registry: AgentRegistry,
116
+ settings: ApiSettings,
117
+ *,
118
+ on_forget: Callable[[str], None] | None = None,
119
+ on_sweep: Callable[[], object] | None = None,
120
+ ) -> None:
113
121
  self.registry = registry
114
122
  self.settings = settings
123
+ self.on_forget = on_forget # called with the id of each run that is forgotten
124
+ self.on_sweep = on_sweep # called on every sweep, for other housekeeping
115
125
  self.runs: dict[str, Run] = {}
116
126
  self.pools = {
117
127
  "llm": _Pool(settings.llm_concurrency), # runs on the local model (one GPU)
@@ -140,6 +150,7 @@ class RunManager:
140
150
  *,
141
151
  llm: LLMClient | None = None,
142
152
  provider: str | None = None,
153
+ run_id: str | None = None,
143
154
  ) -> Run:
144
155
  """Queue a run. ``llm`` is this run's model client (created from the current
145
156
  settings, so a change in settings applies to the next run); ``provider`` decides the
@@ -147,7 +158,7 @@ class RunManager:
147
158
  from margin_core import CancellationToken
148
159
 
149
160
  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)
161
+ run = Run(id=run_id or uuid.uuid4().hex, agent_id=agent_cls.id, pool=pool)
151
162
  if agent_cls.uses_llm:
152
163
  run.llm, run.llm_provider = llm, provider
153
164
  run.llm_model = llm.model if llm is not None else None
@@ -310,7 +321,11 @@ class RunManager:
310
321
  key=lambda r: r.finished_monotonic or 0.0,
311
322
  )
312
323
  while len(self.runs) > self.settings.max_runs and finished:
313
- self.runs.pop(finished.pop(0).id, None)
324
+ self._forget(finished.pop(0).id)
325
+
326
+ def _forget(self, run_id: str) -> None:
327
+ if self.runs.pop(run_id, None) is not None and self.on_forget is not None:
328
+ self.on_forget(run_id)
314
329
 
315
330
  def sweep(self) -> int:
316
331
  """Forget finished runs older than the TTL. Returns how many were removed."""
@@ -321,7 +336,9 @@ class RunManager:
321
336
  and now - r.finished_monotonic > self.settings.result_ttl_s
322
337
  ] # fmt: skip
323
338
  for run_id in expired:
324
- self.runs.pop(run_id, None)
339
+ self._forget(run_id)
340
+ if self.on_sweep is not None:
341
+ self.on_sweep()
325
342
  return len(expired)
326
343
 
327
344
  async def _sweep_forever(self) -> None:
@@ -1,4 +1,4 @@
1
- """API server settings, from ``MARGIN_API_*`` environment variables (and ``.env``)."""
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
- cors_origins: list[str] = ["http://localhost:3000", "http://127.0.0.1:3000"]
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
- env_file = os.environ.get("MARGIN_ENV_FILE", ".env")
33
- return ApiSettings(_env_file=env_file or None) # type: ignore[call-arg]
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]
@@ -0,0 +1 @@
1
+ ._intro_gl36d_1{grid-template-columns:minmax(0,1fr) minmax(0,1.1fr);align-items:start;gap:32px 56px;display:grid}._steps_gl36d_8{counter-reset:step;gap:16px;display:grid}._steps_gl36d_8 li{color:var(--ink-2);counter-increment:step;padding-left:30px;font-size:14.5px;line-height:22px;position:relative}._steps_gl36d_8 li:before{content:counter(step);font-family:var(--font-mono);color:var(--ink-3);font-size:12px;position:absolute;left:0}._steps_gl36d_8 b{color:var(--ink)}._specimen_gl36d_36 figcaption{color:var(--ink-3);margin-top:8px;font-size:12px;line-height:17px}._sheet_gl36d_43{border:1px solid var(--rule-2);border-radius:var(--radius);background:var(--paper-raised);grid-template-columns:minmax(0,1fr) 200px;font-size:12px;line-height:20px;display:grid}._lines_gl36d_53{padding-block:10px;overflow:hidden}._line_gl36d_53{border-left:2px solid #0000;grid-template-columns:40px minmax(0,1fr);display:grid}._line_gl36d_53 span{font-family:var(--font-mono);color:var(--ink-3);text-align:right;padding-right:10px}._line_gl36d_53 code{white-space:pre;font-size:12px}._line_gl36d_53[data-side=for]{border-left-color:var(--red);background:var(--red-tint)}._line_gl36d_53[data-side=against]{border-left-color:var(--blue);background:var(--blue-tint)}._notes_gl36d_86{border-left:1px solid var(--margin-line);color:var(--ink-2);grid-template-rows:repeat(6,20px);margin-block:10px;padding-left:12px;font-size:11.5px;line-height:14px;display:grid}._notes_gl36d_86 p{padding-top:3px}._notes_gl36d_86 b{font-family:var(--font-mono);font-weight:500}._notes_gl36d_86 [data-side=for] b{color:var(--red)}._notes_gl36d_86 [data-side=against] b{color:var(--blue)}._caveat_gl36d_114{max-width:760px;color:var(--ink-2);margin-top:28px;font-size:13.5px}._caveat_gl36d_114 .icon{margin-left:4px}@media (width<=1000px){._intro_gl36d_1{grid-template-columns:minmax(0,1fr)}}
@@ -0,0 +1 @@
1
+ import{d as e,f as t,l as n}from"./index-B3Snzalk.js";var r={intro:`_intro_gl36d_1`,steps:`_steps_gl36d_8`,specimen:`_specimen_gl36d_36`,sheet:`_sheet_gl36d_43`,lines:`_lines_gl36d_53`,line:`_line_gl36d_53`,notes:`_notes_gl36d_86`,caveat:`_caveat_gl36d_114`},i=t(),a=`https://github.com/Waddah0-0/margin/blob/main/docs/methodology.md`,o=[{no:41,text:`def total(items):`},{no:42,text:` # add up the prices`,side:`for`},{no:43,text:` result = 0`},{no:44,text:` for item in items:`},{no:45,text:` result += item.price * 1.0825`,side:`against`},{no:46,text:` return result`}];function s(){return(0,i.jsxs)(n,{label:`How it reads code`,note:`It estimates; it never proves`,children:[(0,i.jsxs)(`div`,{className:r.intro,children:[(0,i.jsxs)(`ol`,{className:r.steps,children:[(0,i.jsxs)(`li`,{children:[(0,i.jsx)(`b`,{children:`A local model reads a sample of files`}),` and points at lines that suggest AI or a person. The quotes come from the file itself, never from the model.`]}),(0,i.jsxs)(`li`,{children:[(0,i.jsx)(`b`,{children:`Every Python, JavaScript and TypeScript file is checked`}),` for habits such as comments that restate the code or leftover debugging.`]}),(0,i.jsxs)(`li`,{children:[(0,i.jsx)(`b`,{children:`The answer is a range, not a verdict`}),`, with a confidence level and the reasons for it. Evidence for and against is shown side by side.`]})]}),(0,i.jsxs)(`figure`,{className:r.specimen,"aria-hidden":`true`,children:[(0,i.jsxs)(`div`,{className:r.sheet,children:[(0,i.jsx)(`div`,{className:r.lines,children:o.map(e=>(0,i.jsxs)(`div`,{className:r.line,"data-side":e.side,children:[(0,i.jsx)(`span`,{children:e.no}),(0,i.jsx)(`code`,{children:e.text})]},e.no))}),(0,i.jsxs)(`div`,{className:r.notes,children:[(0,i.jsxs)(`p`,{"data-side":`for`,style:{gridRow:2},children:[(0,i.jsx)(`b`,{children:`+0.42`}),` comment restates the code`]}),(0,i.jsxs)(`p`,{"data-side":`against`,style:{gridRow:5},children:[(0,i.jsx)(`b`,{children:`−0.18`}),` hand-tuned constant`]})]})]}),(0,i.jsx)(`figcaption`,{children:`What a result looks like: marked lines, and the reason beside each.`})]})]}),(0,i.jsxs)(`p`,{className:r.caveat,children:[`Use it to start a conversation, not to accuse anyone.`,` `,(0,i.jsxs)(`a`,{className:`link`,href:a,target:`_blank`,rel:`noreferrer`,children:[`How it scores, and how well it did in testing`,(0,i.jsx)(e,{name:`open`,size:12})]})]})]})}export{s as DetectorIntro};