margin-api 0.1.0__tar.gz → 0.1.1__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 (30) hide show
  1. {margin_api-0.1.0 → margin_api-0.1.1}/.gitignore +2 -0
  2. margin_api-0.1.1/CHANGELOG.md +33 -0
  3. {margin_api-0.1.0 → margin_api-0.1.1}/PKG-INFO +19 -4
  4. {margin_api-0.1.0 → margin_api-0.1.1}/README.md +17 -2
  5. {margin_api-0.1.0 → margin_api-0.1.1}/pyproject.toml +2 -2
  6. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/__init__.py +1 -1
  7. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/app.py +47 -5
  8. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/jobs.py +103 -26
  9. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/settings.py +1 -0
  10. margin_api-0.1.1/src/margin_api/ui/assets/index-CDckCtOp.css +1 -0
  11. margin_api-0.1.1/src/margin_api/ui/assets/index-CP-J9KRj.js +11 -0
  12. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/index.html +2 -2
  13. {margin_api-0.1.0 → margin_api-0.1.1}/tests/test_api.py +117 -4
  14. margin_api-0.1.0/CHANGELOG.md +0 -13
  15. margin_api-0.1.0/src/margin_api/ui/assets/index-DIeVYF0g.js +0 -11
  16. margin_api-0.1.0/src/margin_api/ui/assets/index-Do_ARaDC.css +0 -1
  17. {margin_api-0.1.0 → margin_api-0.1.1}/LICENSE +0 -0
  18. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/llm_settings.py +0 -0
  19. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/main.py +0 -0
  20. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/py.typed +0 -0
  21. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/fonts/OFL-fraunces.txt +0 -0
  22. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/fonts/OFL-instrument-sans.txt +0 -0
  23. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/fonts/OFL-jetbrains-mono.txt +0 -0
  24. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/fonts/fraunces-latin-ext.woff2 +0 -0
  25. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/fonts/fraunces-latin.woff2 +0 -0
  26. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/fonts/instrument-sans-latin-ext.woff2 +0 -0
  27. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/fonts/instrument-sans-latin.woff2 +0 -0
  28. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  29. {margin_api-0.1.0 → margin_api-0.1.1}/src/margin_api/ui/fonts/jetbrains-mono-latin.woff2 +0 -0
  30. {margin_api-0.1.0 → margin_api-0.1.1}/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,33 @@
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.1] - 2026-10-29
8
+
9
+ ### Added
10
+ - Runs can stop to ask a question. A run whose agent asks moves to the new `waiting` status,
11
+ sends a `question` event and shows the questions in `GET /runs/{run_id}`;
12
+ `POST /runs/{run_id}/answers` answers them. While waiting, a run gives its place in the
13
+ queue to others, and it stops after `MARGIN_API_ANSWER_TIMEOUT_S` (an hour) without answers.
14
+ - `last_event` in the run view: the number of the latest event it already includes, so a
15
+ client can tell replayed events from new ones.
16
+ - The web UI shows an agent's questions as a form on the run page, and every result lists
17
+ the answers and who gave them.
18
+
19
+ ### Changed
20
+ - `waiting` is a new run status. A client that lists every status must handle it.
21
+
22
+ ### Fixed
23
+ - Opening a run page directly (a link or a reload) with the UI served by the API showed
24
+ "Can't reach the API": the browser answered the UI's own request for the run with the
25
+ cached page. Page loads now send `Vary: Accept` and `Cache-Control: no-cache`.
26
+
27
+ ## [0.1.0] - 2026-10-21
28
+
29
+ ### Added
30
+ - Background runs with live progress (server-sent events), queue positions and cancellation.
31
+ - Model settings over HTTP: provider, models, keys (never returned), live model lists and a connection test.
32
+ - The web UI, bundled in the package and served from the same address.
33
+ - 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.0
3
+ Version: 0.1.1
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
@@ -22,7 +22,7 @@ Classifier: Typing :: Typed
22
22
  Requires-Python: >=3.11
23
23
  Requires-Dist: fastapi>=0.111.0
24
24
  Requires-Dist: httpx>=0.27.0
25
- Requires-Dist: margin-core<0.2,>=0.1.0
25
+ Requires-Dist: margin-core<0.2,>=0.1.2
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
@@ -55,6 +55,7 @@ that and a few other things with `MARGIN_API_` environment variables (or a `.env
55
55
  | `MARGIN_API_RESULT_TTL_S` | `3600` | Seconds a finished run is kept. |
56
56
  | `MARGIN_API_MAX_BODY_BYTES` | `1000000` | Largest accepted request body. |
57
57
  | `MARGIN_API_CANCEL_GRACE_S` | `30` | Time a cancelled run gets to stop on its own before it is stopped. |
58
+ | `MARGIN_API_ANSWER_TIMEOUT_S` | `3600` | How long a run waits for answers to its questions before it stops. |
58
59
 
59
60
  Model settings (`DEFAULT_LLM_PROVIDER`, `LOCAL_LLM_BASE_URL`, ...) are the same as for the CLI.
60
61
 
@@ -66,8 +67,9 @@ Model settings (`DEFAULT_LLM_PROVIDER`, `LOCAL_LLM_BASE_URL`, ...) are the same
66
67
  | `GET /agents` | Installed agents with their input and output JSON schemas, plus any that failed to load. |
67
68
  | `GET /agents/{id}` | One agent. |
68
69
  | `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`. |
70
+ | `GET /runs/{run_id}` | Status (`queued`, `running`, `waiting`, `done`, `cancelled`), queue position, latest progress, the open questions while `waiting` and, when done, the result. |
71
+ | `GET /runs/{run_id}/events` | Server-sent events: `status`, `progress`, `question` when the agent asks something, then one final `result`. |
72
+ | `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
73
  | `DELETE /runs/{run_id}` | Cancel a run. |
72
74
  | `GET /runs` | Recent runs. |
73
75
  | `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 +110,21 @@ When an agent fails, the run still finishes as `done`; the failure is in its res
108
110
  agent or run, `422` for input that doesn't match the agent's schema, `413` for a body that's
109
111
  too large, and `500` for an agent that failed to load.
110
112
 
113
+ Some agents stop to ask a question. The run then moves to `waiting`, sends a `question`
114
+ event, and its `GET /runs/{run_id}` view carries the questions. A waiting run gives up its
115
+ place in the queue, so a question nobody answers never holds the GPU. Once you post the
116
+ answers it goes back to `queued` and continues when a place is free. A run nobody answers
117
+ stops after an hour (`MARGIN_API_ANSWER_TIMEOUT_S`) with an error result.
118
+
119
+ ```bash
120
+ curl -s -X POST http://127.0.0.1:8000/runs/342e1c.../answers \
121
+ -H 'content-type: application/json' \
122
+ -d '{"batch": "9f2c...", "answers": {"style": "capitals"}}'
123
+ ```
124
+
111
125
  Cancelling asks the agent to stop at its next checkpoint. A model call already under way is
112
126
  allowed to finish, and an agent that still hasn't stopped after the grace period is stopped.
127
+ A waiting run stops at once.
113
128
 
114
129
  Runs live in memory. They're gone after an hour, or when the server restarts, so export a
115
130
  result if you want to keep it.
@@ -25,6 +25,7 @@ that and a few other things with `MARGIN_API_` environment variables (or a `.env
25
25
  | `MARGIN_API_RESULT_TTL_S` | `3600` | Seconds a finished run is kept. |
26
26
  | `MARGIN_API_MAX_BODY_BYTES` | `1000000` | Largest accepted request body. |
27
27
  | `MARGIN_API_CANCEL_GRACE_S` | `30` | Time a cancelled run gets to stop on its own before it is stopped. |
28
+ | `MARGIN_API_ANSWER_TIMEOUT_S` | `3600` | How long a run waits for answers to its questions before it stops. |
28
29
 
29
30
  Model settings (`DEFAULT_LLM_PROVIDER`, `LOCAL_LLM_BASE_URL`, ...) are the same as for the CLI.
30
31
 
@@ -36,8 +37,9 @@ Model settings (`DEFAULT_LLM_PROVIDER`, `LOCAL_LLM_BASE_URL`, ...) are the same
36
37
  | `GET /agents` | Installed agents with their input and output JSON schemas, plus any that failed to load. |
37
38
  | `GET /agents/{id}` | One agent. |
38
39
  | `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`. |
40
+ | `GET /runs/{run_id}` | Status (`queued`, `running`, `waiting`, `done`, `cancelled`), queue position, latest progress, the open questions while `waiting` and, when done, the result. |
41
+ | `GET /runs/{run_id}/events` | Server-sent events: `status`, `progress`, `question` when the agent asks something, then one final `result`. |
42
+ | `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
43
  | `DELETE /runs/{run_id}` | Cancel a run. |
42
44
  | `GET /runs` | Recent runs. |
43
45
  | `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 +80,21 @@ When an agent fails, the run still finishes as `done`; the failure is in its res
78
80
  agent or run, `422` for input that doesn't match the agent's schema, `413` for a body that's
79
81
  too large, and `500` for an agent that failed to load.
80
82
 
83
+ Some agents stop to ask a question. The run then moves to `waiting`, sends a `question`
84
+ event, and its `GET /runs/{run_id}` view carries the questions. A waiting run gives up its
85
+ place in the queue, so a question nobody answers never holds the GPU. Once you post the
86
+ answers it goes back to `queued` and continues when a place is free. A run nobody answers
87
+ stops after an hour (`MARGIN_API_ANSWER_TIMEOUT_S`) with an error result.
88
+
89
+ ```bash
90
+ curl -s -X POST http://127.0.0.1:8000/runs/342e1c.../answers \
91
+ -H 'content-type: application/json' \
92
+ -d '{"batch": "9f2c...", "answers": {"style": "capitals"}}'
93
+ ```
94
+
81
95
  Cancelling asks the agent to stop at its next checkpoint. A model call already under way is
82
96
  allowed to finish, and an agent that still hasn't stopped after the grace period is stopped.
97
+ A waiting run stops at once.
83
98
 
84
99
  Runs live in memory. They're gone after an hour, or when the server restarts, so export a
85
100
  result if you want to keep it.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "margin-api"
3
- version = "0.1.0"
3
+ version = "0.1.1"
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,7 +20,7 @@ classifiers = [
20
20
  "Environment :: Web Environment",
21
21
  ]
22
22
  dependencies = [
23
- "margin-core>=0.1.0,<0.2",
23
+ "margin-core>=0.1.2,<0.2", # 0.1.2: questions (ctx.ask)
24
24
  "fastapi>=0.111.0",
25
25
  "uvicorn>=0.30.0",
26
26
  "sse-starlette>=2.1.0",
@@ -1,3 +1,3 @@
1
1
  """HTTP API for margin."""
2
2
 
3
- __version__ = "0.1.0"
3
+ __version__ = "0.1.1"
@@ -23,16 +23,17 @@ from margin_core import (
23
23
  BaseAgent,
24
24
  InputValidationError,
25
25
  ProgressEvent,
26
+ QuestionBatch,
26
27
  default_registry,
27
28
  )
28
29
  from margin_core.config import get_settings
29
30
  from margin_core.llm import LLMClient, create_llm
30
31
  from margin_core.logging import get_logger
31
- from pydantic import BaseModel, Field
32
+ from pydantic import BaseModel, ConfigDict, Field
32
33
  from sse_starlette.sse import EventSourceResponse
33
34
 
34
35
  from margin_api import __version__
35
- from margin_api.jobs import Run, RunManager, RunStatus
36
+ from margin_api.jobs import NotWaitingError, Run, RunManager, RunStatus
36
37
  from margin_api.llm_settings import router as llm_settings_router
37
38
  from margin_api.settings import ApiSettings, load_settings
38
39
 
@@ -74,6 +75,22 @@ class RunView(BaseModel):
74
75
  finished_at: datetime | None
75
76
  result: AgentResult | None = Field(description="Present once the run is done.")
76
77
  llm: RunModel | None = Field(default=None, description="The model this run uses, if any.")
78
+ question: QuestionBatch | None = Field(
79
+ default=None, description="What the run is asking; present only while it is waiting."
80
+ )
81
+ last_event: int = Field(
82
+ default=0, description="Number of the latest event; this view already includes it."
83
+ )
84
+
85
+
86
+ class AnswersBody(BaseModel):
87
+ model_config = ConfigDict(extra="forbid")
88
+
89
+ batch: str = Field(description="The id of the questions being answered (`question.id`).")
90
+ answers: dict[str, Any] = Field(
91
+ default_factory=dict,
92
+ description="Answers by question id. A question left out takes its default.",
93
+ )
77
94
 
78
95
 
79
96
  class _BodyLimit:
@@ -201,7 +218,7 @@ def create_app(
201
218
  queue_position=manager.queue_position(run), progress=run.progress,
202
219
  created_at=run.created_at, started_at=run.started_at,
203
220
  finished_at=run.finished_at, result=run.result,
204
- llm=llm,
221
+ llm=llm, question=run.question, last_event=run.last_event,
205
222
  ) # fmt: skip
206
223
 
207
224
  @app.get("/health", tags=["meta"])
@@ -271,11 +288,32 @@ def create_app(
271
288
  await manager.cancel(run)
272
289
  return view(run)
273
290
 
291
+ @app.post(
292
+ "/runs/{run_id}/answers",
293
+ response_model=RunView,
294
+ status_code=202,
295
+ tags=["runs"],
296
+ responses={
297
+ 409: {"description": "The run is not waiting for these answers"},
298
+ 422: {"description": "The answers do not fit the questions"},
299
+ },
300
+ )
301
+ async def answer_run(run_id: str, body: AnswersBody) -> RunView:
302
+ """Answer the questions a waiting run asked; the run then carries on."""
303
+ run = find_run(run_id)
304
+ try:
305
+ manager.answer(run, body.batch, body.answers)
306
+ except NotWaitingError as exc:
307
+ raise HTTPException(409, str(exc)) from exc
308
+ except ValueError as exc:
309
+ raise HTTPException(422, f"Invalid answers: {exc}") from exc
310
+ return view(run)
311
+
274
312
  @app.get(
275
313
  "/runs/{run_id}/events",
276
314
  tags=["runs"],
277
315
  response_class=EventSourceResponse,
278
- responses={200: {"description": "Server-sent events: status, progress, result"}},
316
+ responses={200: {"description": "Server-sent events: status, progress, question, result"}},
279
317
  )
280
318
  async def run_events(run_id: str, request: Request) -> EventSourceResponse:
281
319
  run = find_run(run_id)
@@ -312,6 +350,7 @@ class _UIPages:
312
350
  """
313
351
 
314
352
  API_PAGES = ("/docs", "/redoc", "/openapi.json")
353
+ PAGE_HEADERS = {"Vary": "Accept", "Cache-Control": "no-cache"}
315
354
 
316
355
  def __init__(self, app: Any, root: Path) -> None:
317
356
  self.app = app
@@ -326,7 +365,10 @@ class _UIPages:
326
365
  if "text/html" in accept and not path.startswith(self.API_PAGES):
327
366
  candidate = (self.root / path.lstrip("/")).resolve()
328
367
  if not (candidate.is_file() and self.root in candidate.parents):
329
- await FileResponse(self.index)(scope, receive, send)
368
+ # the page shares its URL with the API's JSON: without Vary the browser
369
+ # would answer the UI's own fetch of /runs/<id> with this cached page
370
+ page = FileResponse(self.index, headers=self.PAGE_HEADERS)
371
+ await page(scope, receive, send)
330
372
  return
331
373
  await self.app(scope, receive, send)
332
374
 
@@ -4,6 +4,10 @@ A run moves through ``queued -> running -> done`` (or ``cancelled``). A run whos
4
4
  fails still ends as ``done``: the failure is in its result (``status="error"``), not in the
5
5
  run's state. Progress events are numbered and kept in a bounded buffer, so a client that
6
6
  connects late (or reconnects) gets everything it missed.
7
+
8
+ When the agent asks a question, the run goes ``running -> waiting`` and gives its place in
9
+ the pool to the next run, so a question nobody answers never holds the GPU. Once answered
10
+ it goes back to ``queued`` and runs again when a place is free.
7
11
  """
8
12
 
9
13
  from __future__ import annotations
@@ -13,27 +17,40 @@ import contextlib
13
17
  import time
14
18
  import uuid
15
19
  from collections import deque
16
- from collections.abc import AsyncIterator
20
+ from collections.abc import AsyncIterator, Mapping
17
21
  from dataclasses import dataclass, field
18
22
  from datetime import UTC, datetime
19
23
  from typing import Any, Literal
20
24
 
21
- from margin_core import AgentRegistry, AgentResult, BaseAgent, ProgressEvent, RunContext
25
+ from margin_core import (
26
+ AgentRegistry,
27
+ AgentResult,
28
+ BaseAgent,
29
+ NoAnswerError,
30
+ ProgressEvent,
31
+ QuestionBatch,
32
+ RunContext,
33
+ )
22
34
  from margin_core.llm import LLMClient
23
35
  from margin_core.logging import get_logger
24
36
  from pydantic import BaseModel
25
37
 
26
38
  from margin_api.settings import ApiSettings
27
39
 
28
- RunStatus = Literal["queued", "running", "done", "cancelled"]
40
+ RunStatus = Literal["queued", "running", "waiting", "done", "cancelled"]
41
+ EventKind = Literal["status", "progress", "question", "result"]
29
42
  FINISHED: frozenset[str] = frozenset({"done", "cancelled"})
30
43
  logger = get_logger("api.jobs")
31
44
 
32
45
 
46
+ class NotWaitingError(Exception):
47
+ """Answers were posted to a run that is not waiting for them."""
48
+
49
+
33
50
  @dataclass
34
51
  class RunEvent:
35
52
  seq: int
36
- kind: Literal["status", "progress", "result"]
53
+ kind: EventKind
37
54
  data: dict[str, Any]
38
55
 
39
56
 
@@ -55,12 +72,21 @@ class Run:
55
72
  llm_provider: str | None = None
56
73
  llm_model: str | None = None
57
74
  finished_monotonic: float | None = None
75
+ question: QuestionBatch | None = None # what the run is waiting on
76
+ answer: asyncio.Future[Mapping[str, Any]] | None = None
77
+ holds_slot: bool = False # whether it has a place in its pool right now
58
78
  _seq: int = 0
59
79
  _changed: asyncio.Event = field(default_factory=asyncio.Event)
60
80
 
61
- def add_event(
62
- self, kind: Literal["status", "progress", "result"], data: dict[str, Any]
63
- ) -> None:
81
+ @property
82
+ def last_event(self) -> int:
83
+ return self._seq
84
+
85
+ def set_status(self, status: RunStatus) -> None:
86
+ self.status = status
87
+ self.add_event("status", {"status": status})
88
+
89
+ def add_event(self, kind: EventKind, data: dict[str, Any]) -> None:
64
90
  self._seq += 1
65
91
  self.events.append(RunEvent(self._seq, kind, data))
66
92
  # wake every waiting subscriber, then arm a fresh event for the next change
@@ -140,27 +166,43 @@ class RunManager:
140
166
  def queue_position(self, run: Run) -> int | None:
141
167
  return self.pools[run.pool].position(run.id) if run.status == "queued" else None
142
168
 
143
- async def _execute(self, run: Run, agent_cls: type[BaseAgent], parsed: BaseModel) -> None:
169
+ async def _take_slot(self, run: Run) -> None:
170
+ """Wait in line for a place in the run's pool."""
144
171
  pool = self.pools[run.pool]
172
+ if run.id not in pool.waiting:
173
+ pool.waiting.append(run.id)
145
174
  try:
146
- async with pool.semaphore:
147
- with contextlib.suppress(ValueError):
148
- pool.waiting.remove(run.id)
149
- if run.token.cancelled:
150
- self._finish(run, None, cancelled=True)
151
- return
152
- run.status = "running"
153
- run.started_at = datetime.now(UTC)
154
- run.add_event("status", {"status": "running"})
155
-
156
- def on_progress(event: ProgressEvent) -> None:
157
- run.progress = event
158
- run.add_event("progress", event.model_dump(mode="json"))
159
-
160
- agent = agent_cls(llm=run.llm)
161
- ctx = RunContext(progress=on_progress, cancel_token=run.token)
162
- result = await agent.execute(parsed, ctx)
163
- self._finish(run, result, cancelled=run.token.cancelled)
175
+ await pool.semaphore.acquire()
176
+ finally:
177
+ with contextlib.suppress(ValueError):
178
+ pool.waiting.remove(run.id)
179
+ run.holds_slot = True
180
+
181
+ def _free_slot(self, run: Run) -> None:
182
+ if run.holds_slot:
183
+ run.holds_slot = False
184
+ self.pools[run.pool].semaphore.release()
185
+
186
+ async def _execute(self, run: Run, agent_cls: type[BaseAgent], parsed: BaseModel) -> None:
187
+ try:
188
+ await self._take_slot(run)
189
+ if run.token.cancelled:
190
+ self._finish(run, None, cancelled=True)
191
+ return
192
+ run.started_at = datetime.now(UTC)
193
+ run.set_status("running")
194
+
195
+ def on_progress(event: ProgressEvent) -> None:
196
+ run.progress = event
197
+ run.add_event("progress", event.model_dump(mode="json"))
198
+
199
+ async def ask(batch: QuestionBatch) -> Mapping[str, Any]:
200
+ return await self._wait_for_answers(run, batch)
201
+
202
+ agent = agent_cls(llm=run.llm)
203
+ ctx = RunContext(progress=on_progress, cancel_token=run.token, responder=ask)
204
+ result = await agent.execute(parsed, ctx)
205
+ self._finish(run, result, cancelled=run.token.cancelled)
164
206
  except asyncio.CancelledError:
165
207
  self._finish(run, None, cancelled=True)
166
208
  except Exception as exc: # noqa: BLE001 - never lose a run silently
@@ -176,6 +218,41 @@ class RunManager:
176
218
  ), # fmt: skip
177
219
  cancelled=False,
178
220
  )
221
+ finally:
222
+ self._free_slot(run)
223
+
224
+ # ---- questions ------------------------------------------------------------------
225
+
226
+ async def _wait_for_answers(self, run: Run, batch: QuestionBatch) -> Mapping[str, Any]:
227
+ """The run's responder: pause, free the pool place, and wait for answers."""
228
+ run.answer = asyncio.get_running_loop().create_future()
229
+ run.question = batch
230
+ self._free_slot(run)
231
+ run.set_status("waiting")
232
+ run.add_event("question", batch.model_dump(mode="json"))
233
+ try:
234
+ answers = await asyncio.wait_for(run.answer, self.settings.answer_timeout_s)
235
+ except TimeoutError:
236
+ limit = self.settings.answer_timeout_s
237
+ span = f"{round(limit / 60)} minutes" if limit >= 120 else f"{limit:g} seconds"
238
+ raise NoAnswerError(f"No answer came within {span}, so the run stopped.") from None
239
+ finally:
240
+ run.question = None
241
+ run.answer = None
242
+ run.set_status("queued")
243
+ await self._take_slot(run)
244
+ run.set_status("running")
245
+ return answers
246
+
247
+ def answer(self, run: Run, batch_id: str, answers: Mapping[str, Any]) -> None:
248
+ """Resume a waiting run. Raises :class:`NotWaitingError`, or ``ValueError`` for
249
+ answers that do not fit the questions (nothing is changed then)."""
250
+ if run.status != "waiting" or run.question is None or run.answer is None:
251
+ raise NotWaitingError("This run is not waiting for answers")
252
+ if batch_id != run.question.id or run.answer.done():
253
+ raise NotWaitingError("These questions have already been answered")
254
+ run.question.resolve(answers, "user")
255
+ run.answer.set_result(dict(answers))
179
256
 
180
257
  def _finish(self, run: Run, result: AgentResult | None, *, cancelled: bool) -> None:
181
258
  if run.status in FINISHED:
@@ -25,6 +25,7 @@ class ApiSettings(BaseSettings):
25
25
  max_runs: int = 1000 # stored runs, finished ones are dropped oldest first
26
26
  event_buffer: int = 200 # progress events kept per run for late subscribers
27
27
  cancel_grace_s: float = 30.0 # time a cancelled run gets to stop on its own
28
+ answer_timeout_s: float = 3600.0 # a run waiting for answers stops after this
28
29
 
29
30
 
30
31
  def load_settings() -> ApiSettings: