symphony-server 0.0.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sarthak Chauhan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: symphony-server
3
+ Version: 0.0.1
4
+ Summary: FastAPI framework for managed Symphony chat runs and replayable harness events (import as core_server)
5
+ Author: Sarthak Chauhan
6
+ Author-email: Sarthak Chauhan <sarthakchauhann@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: symphony-core>=0.0.10
10
+ Requires-Dist: symphony-harness>=0.0.13
11
+ Requires-Dist: dotenv>=0.9.9
12
+ Requires-Dist: fastapi>=0.115.0
13
+ Requires-Dist: uvicorn[standard]>=0.32.0
14
+ Requires-Python: >=3.11
15
+ Project-URL: Homepage, https://github.com/Sarthakischauhan/symphony
16
+ Project-URL: Documentation, https://github.com/Sarthakischauhan/symphony/blob/main/docs/developer-guide.md#core-server
17
+ Project-URL: Source, https://github.com/Sarthakischauhan/symphony/tree/main/core_server
18
+ Description-Content-Type: text/markdown
19
+
20
+ # core-server
21
+
22
+ A FastAPI service for creating harness runs and streaming their events over Server-Sent Events (SSE). Import the application from `core_server`. The distribution is named `symphony-server`; its Python import is `core_server` and its CLI is `core-server`.
23
+
24
+ ## Run from the repository
25
+
26
+ ```sh
27
+ uv sync
28
+ uv run --package symphony-server core-server
29
+ ```
30
+
31
+ The default bind address is `127.0.0.1:8000`. `core-server --version` prints the installed version, and `--cors ORIGIN` (repeatable) allows a browser origin; none is allowed by default. Do not expose the service to an untrusted network without adding authentication; the server has no built-in authentication. See [SECURITY.md](../SECURITY.md).
32
+
33
+ ## Continue
34
+
35
+ - [Server guide](../docs/developer-guide.md#core-server): endpoints, run lifecycle, sessions, and request policy.
36
+ - [`openapi.json`](openapi.json): the HTTP API. Regenerate it with `uv run python core_server/scripts/generate_openapi.py`; CI fails when it is stale.
37
+ - [CLI reference](../docs/reference.md#core-server)
38
+ - [Harness events](../docs/developer-guide.md#control-plane-events-overview)
39
+ - [Source installation](../docs/user-guide.md#install-symphony)
@@ -0,0 +1,20 @@
1
+ # core-server
2
+
3
+ A FastAPI service for creating harness runs and streaming their events over Server-Sent Events (SSE). Import the application from `core_server`. The distribution is named `symphony-server`; its Python import is `core_server` and its CLI is `core-server`.
4
+
5
+ ## Run from the repository
6
+
7
+ ```sh
8
+ uv sync
9
+ uv run --package symphony-server core-server
10
+ ```
11
+
12
+ The default bind address is `127.0.0.1:8000`. `core-server --version` prints the installed version, and `--cors ORIGIN` (repeatable) allows a browser origin; none is allowed by default. Do not expose the service to an untrusted network without adding authentication; the server has no built-in authentication. See [SECURITY.md](../SECURITY.md).
13
+
14
+ ## Continue
15
+
16
+ - [Server guide](../docs/developer-guide.md#core-server): endpoints, run lifecycle, sessions, and request policy.
17
+ - [`openapi.json`](openapi.json): the HTTP API. Regenerate it with `uv run python core_server/scripts/generate_openapi.py`; CI fails when it is stale.
18
+ - [CLI reference](../docs/reference.md#core-server)
19
+ - [Harness events](../docs/developer-guide.md#control-plane-events-overview)
20
+ - [Source installation](../docs/user-guide.md#install-symphony)
@@ -0,0 +1,46 @@
1
+ [project]
2
+ name = "symphony-server"
3
+ version = "0.0.1"
4
+ description = "FastAPI framework for managed Symphony chat runs and replayable harness events (import as core_server)"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = [
10
+ "symphony-core>=0.0.10",
11
+ "symphony-harness>=0.0.13",
12
+ "dotenv>=0.9.9",
13
+ "fastapi>=0.115.0",
14
+ "uvicorn[standard]>=0.32.0",
15
+ ]
16
+
17
+ [[project.authors]]
18
+ name = "Sarthak Chauhan"
19
+ email = "sarthakchauhann@gmail.com"
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/Sarthakischauhan/symphony"
23
+ Documentation = "https://github.com/Sarthakischauhan/symphony/blob/main/docs/developer-guide.md#core-server"
24
+ Source = "https://github.com/Sarthakischauhan/symphony/tree/main/core_server"
25
+
26
+ [project.scripts]
27
+ core-server = "core_server.__main__:main"
28
+
29
+ [tool.uv.sources.symphony-core]
30
+ workspace = true
31
+
32
+ [tool.uv.sources.symphony-harness]
33
+ workspace = true
34
+
35
+ [tool.uv.build-backend]
36
+ module-name = "core_server"
37
+
38
+ [dependency-groups]
39
+ dev = [
40
+ "httpx>=0.28.1",
41
+ "pytest>=9.1.1",
42
+ ]
43
+
44
+ [build-system]
45
+ requires = ["uv_build>=0.9.8,<0.10.0"]
46
+ build-backend = "uv_build"
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "symphony-server"
3
+ version = "0.0.1"
4
+ description = "FastAPI framework for managed Symphony chat runs and replayable harness events (import as core_server)"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "Sarthak Chauhan", email = "sarthakchauhann@gmail.com" }
10
+ ]
11
+ requires-python = ">=3.11"
12
+ dependencies = [
13
+ "symphony-core>=0.0.10",
14
+ "symphony-harness>=0.0.13",
15
+ "dotenv>=0.9.9",
16
+ "fastapi>=0.115.0",
17
+ "uvicorn[standard]>=0.32.0",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/Sarthakischauhan/symphony"
22
+ Documentation = "https://github.com/Sarthakischauhan/symphony/blob/main/docs/developer-guide.md#core-server"
23
+ Source = "https://github.com/Sarthakischauhan/symphony/tree/main/core_server"
24
+
25
+ [project.scripts]
26
+ core-server = "core_server.__main__:main"
27
+
28
+ [tool.uv.sources]
29
+ symphony-core = { workspace = true }
30
+ symphony-harness = { workspace = true }
31
+
32
+ [dependency-groups]
33
+ dev = [
34
+ "httpx>=0.28.1",
35
+ "pytest>=9.1.1",
36
+ ]
37
+
38
+ [build-system]
39
+ requires = ["uv_build>=0.9.8,<0.10.0"]
40
+ build-backend = "uv_build"
41
+
42
+ [tool.uv.build-backend]
43
+ module-name = "core_server"
@@ -0,0 +1,23 @@
1
+ """core_server: a FastAPI service that runs ``core_harness`` agents and streams their events over SSE.
2
+
3
+ ``config`` holds the wire models, ``ServerConfig`` and the model catalog;
4
+ ``runs`` the run manager and backends; ``app`` the routes and middleware.
5
+ """
6
+
7
+ from core_server.app import PACKAGE_VERSION, create_app, create_router, encode_sse, install_middlewares
8
+ from core_server.config import (DEFAULT_SYSTEM_PROMPT, AddonFactory, AnswerRequest, ModelRegistryResponse,
9
+ RegistryModel, RegistryProvider, RunAccepted, RunAuthorizer, RunContext,
10
+ RunContextResolver, RunInterrupted, RunRequest, RunStatus, RunStatusResponse,
11
+ RunSubmission, ServerConfig, SubagentFactory, SupportedModel, ThinkingLevel,
12
+ allow_run_access, anonymous_run_context, build_config)
13
+ from core_server.runs import (InProcessRunBackend, RunBackend, RunCapacityError, RunControl, RunExecutor,
14
+ RunManager, RunState)
15
+
16
+ __all__ = [
17
+ "AddonFactory", "AnswerRequest", "DEFAULT_SYSTEM_PROMPT", "InProcessRunBackend", "ModelRegistryResponse",
18
+ "PACKAGE_VERSION", "RegistryModel", "RegistryProvider", "RunAccepted", "RunAuthorizer", "RunBackend",
19
+ "RunCapacityError", "RunContext", "RunContextResolver", "RunControl", "RunExecutor", "RunInterrupted",
20
+ "RunManager", "RunRequest", "RunState", "RunStatus", "RunStatusResponse", "RunSubmission", "ServerConfig",
21
+ "SubagentFactory", "SupportedModel", "ThinkingLevel", "allow_run_access", "anonymous_run_context",
22
+ "build_config", "create_app", "create_router", "encode_sse", "install_middlewares",
23
+ ]
@@ -0,0 +1,35 @@
1
+ """``core-server`` / ``python -m core_server``: serve the default app with uvicorn."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from typing import Sequence
7
+
8
+ import uvicorn
9
+ from dotenv import load_dotenv
10
+
11
+ from core_server.app import PACKAGE_VERSION, create_app
12
+ from core_server.config import build_config
13
+
14
+
15
+ def main(argv: Sequence[str] | None = None) -> None:
16
+ parser = argparse.ArgumentParser(prog="core-server", description="Symphony core-server")
17
+ parser.add_argument("--version", action="version", version=f"%(prog)s {PACKAGE_VERSION}")
18
+ parser.add_argument("--host", default="127.0.0.1")
19
+ parser.add_argument("--port", type=int, default=8000)
20
+ parser.add_argument("--model", default=None, help="Model id (default: OPENAI_MODEL)")
21
+ parser.add_argument("--system-prompt", default=None, help="Override the default system prompt")
22
+ parser.add_argument("--cors", action="append", default=[], metavar="ORIGIN",
23
+ help="Allowed CORS origin (repeat for multiple origins; default: none)")
24
+ args = parser.parse_args(argv)
25
+ if "*" in args.cors:
26
+ parser.error("--cors '*' would let any website start runs, and core-server has no authentication; "
27
+ "pass each allowed origin instead")
28
+ load_dotenv(override=True)
29
+ prompt = {} if args.system_prompt is None else {"system_prompt": args.system_prompt}
30
+ config = build_config(model_id=args.model, cors_origins=args.cors, **prompt)
31
+ uvicorn.run(create_app(config), host=args.host, port=args.port)
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main()
@@ -0,0 +1,196 @@
1
+ """HTTP API: start runs, read their status, stream events over SSE, and answer or interrupt them."""
2
+
3
+ import json
4
+ from contextlib import asynccontextmanager
5
+ from importlib.metadata import PackageNotFoundError, version
6
+ from typing import Annotated, Any, AsyncIterator, Optional
7
+
8
+ from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException, Query, Request, status
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.responses import Response, StreamingResponse
11
+
12
+ from core_harness import ControlPlaneEvent
13
+
14
+ from core_server.config import (AnswerRequest, ModelRegistryResponse, RunAccepted, RunInterrupted, RunRequest,
15
+ RunStatusResponse, RunSubmission, ServerConfig, is_accepted_model,
16
+ model_registry_response)
17
+ from core_server.runs import (InProcessRunBackend, RunBackend, RunCapacityError, RunControl, RunExecutor, RunManager,
18
+ RunNotFoundError, RunState, parse_last_event_id)
19
+
20
+ try:
21
+ PACKAGE_VERSION = version("symphony-server")
22
+ except PackageNotFoundError: # a source tree that was never installed
23
+ PACKAGE_VERSION = "unknown"
24
+
25
+ _SSE_HEADERS = {"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"}
26
+
27
+
28
+ def encode_sse(event: ControlPlaneEvent, *, event_id: Optional[str] = None) -> str:
29
+ """One SSE frame. The id defaults to ``<run_id>:<seq>`` from the payload."""
30
+ run_id, seq = event.payload.get("run_id"), event.payload.get("seq")
31
+ event_id = event_id or (f"{run_id}:{seq}" if run_id is not None and seq is not None else None)
32
+ id_line = f"id: {event_id}\n" if event_id else ""
33
+ return f"{id_line}event: {event.event_type}\ndata: {json.dumps(event.model_dump(), ensure_ascii=False)}\n\n"
34
+
35
+
36
+ def _validate_request(run: RunRequest, config: ServerConfig) -> None:
37
+ history = run.conversation or []
38
+ if len(run.message) > config.max_message_chars:
39
+ raise HTTPException(status_code=413, detail="Message is too large")
40
+ if len(history) > config.max_history_messages:
41
+ raise HTTPException(status_code=413, detail="Conversation has too many messages")
42
+ if sum(len(message.model_dump_json()) for message in history) > config.max_history_chars:
43
+ raise HTTPException(status_code=413, detail="Conversation history is too large")
44
+ if run.model_id and not is_accepted_model(config, run.model_id):
45
+ raise HTTPException(status_code=422, detail="Unsupported model_id")
46
+
47
+
48
+ def create_router(config: ServerConfig, *, run_backend: RunBackend, prefix: str = "") -> APIRouter:
49
+ """Routes for an application-owned FastAPI app, which must call ``run_backend.shutdown()`` on exit."""
50
+ router = APIRouter(prefix=prefix)
51
+
52
+ async def authorized(run_id: str, request: Request) -> RunState:
53
+ """The run behind ``{run_id}``; 404 when it is missing or the caller may not see it."""
54
+ try:
55
+ record = await run_backend.get(run_id)
56
+ except RunNotFoundError:
57
+ raise HTTPException(status_code=404, detail="Run not found") from None
58
+ if not await config.authorize_run(request, record.context):
59
+ raise HTTPException(status_code=404, detail="Run not found")
60
+ return record
61
+
62
+ AuthorizedRun = Annotated[RunState, Depends(authorized)]
63
+
64
+ @router.get("/health")
65
+ def health() -> dict[str, object]:
66
+ return {"ok": True, "version": PACKAGE_VERSION}
67
+
68
+ # A model without a known context window omits ``contextWindow``.
69
+ @router.get("/models", response_model=ModelRegistryResponse, response_model_exclude_none=True)
70
+ def models() -> ModelRegistryResponse:
71
+ return model_registry_response(config)
72
+
73
+ @router.post("/runs", response_model=RunAccepted, status_code=status.HTTP_202_ACCEPTED)
74
+ async def start_run(run: RunRequest, request: Request) -> RunAccepted:
75
+ _validate_request(run, config)
76
+ context = await config.resolve_run_context(request, run.session_id)
77
+ if not context.session_id.strip():
78
+ raise HTTPException(status_code=500, detail="Run context has an empty session_id")
79
+ try:
80
+ record = await run_backend.submit(RunSubmission(context=context, request=run))
81
+ except RunCapacityError:
82
+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Run capacity is full",
83
+ headers={"Retry-After": "1"}) from None
84
+ return RunAccepted(run_id=record.run_id, session_id=context.session_id, status=record.status,
85
+ events_url=request.url_for("stream_run_events", run_id=record.run_id).path)
86
+
87
+ @router.get("/runs/{run_id}", response_model=RunStatusResponse)
88
+ async def get_run(run_id: str, request: Request) -> RunStatusResponse:
89
+ return (await authorized(run_id, request)).response()
90
+
91
+ @router.get("/runs/{run_id}/events")
92
+ async def stream_run_events(run_id: str, request: Request, after: int = Query(default=0, ge=0),
93
+ last_event_id: str | None = Header(default=None, alias="Last-Event-ID"),
94
+ ) -> StreamingResponse:
95
+ await authorized(run_id, request)
96
+ cursor = max(after, parse_last_event_id(last_event_id, run_id))
97
+
98
+ async def frames() -> AsyncIterator[str]:
99
+ async for ordinal, event in run_backend.events(run_id, after=cursor):
100
+ yield encode_sse(event, event_id=f"{run_id}:{ordinal}")
101
+
102
+ return StreamingResponse(frames(), media_type="text/event-stream", headers=_SSE_HEADERS)
103
+
104
+ @router.post("/runs/{run_id}/cancel", response_model=RunStatusResponse)
105
+ async def cancel_run(run_id: str, request: Request) -> RunStatusResponse:
106
+ await authorized(run_id, request)
107
+ return (await run_backend.cancel(run_id)).response()
108
+
109
+ if isinstance(run_backend, RunControl):
110
+ control = run_backend
111
+ conflict = {"description": "No open question has that request_id: it is stale or already answered"}
112
+
113
+ @router.post("/runs/{run_id}/answer", status_code=status.HTTP_204_NO_CONTENT, response_class=Response,
114
+ responses={status.HTTP_409_CONFLICT: conflict})
115
+ async def answer_run(run_id: str, answer: AnswerRequest, authorized: AuthorizedRun) -> Response:
116
+ if not await control.answer(run_id, answer.request_id, answer.value):
117
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="No open question with that request_id")
118
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
119
+
120
+ @router.post("/runs/{run_id}/interrupt", response_model=RunInterrupted)
121
+ async def interrupt_run(run_id: str, authorized: AuthorizedRun) -> RunInterrupted:
122
+ return RunInterrupted(interrupted=await control.interrupt(run_id))
123
+
124
+ return router
125
+
126
+
127
+ class RequestSizeLimitMiddleware:
128
+ """Reject an oversized ``POST`` body to ``path`` with 413, by header or while it streams in."""
129
+
130
+ class _TooLarge(Exception):
131
+ pass
132
+
133
+ def __init__(self, app: Any, *, max_bytes: int, path: str = "/runs") -> None:
134
+ self.app, self.max_bytes, self.path = app, max_bytes, path
135
+
136
+ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
137
+ if (scope.get("type"), scope.get("method"), scope.get("path")) != ("http", "POST", self.path):
138
+ return await self.app(scope, receive, send)
139
+ for name, value in scope.get("headers", []):
140
+ if name.lower() == b"content-length" and value.isdigit() and int(value) > self.max_bytes:
141
+ return await self._reject(send)
142
+ received, started = 0, False
143
+
144
+ async def limited_receive() -> dict[str, Any]:
145
+ nonlocal received
146
+ message = await receive()
147
+ if message.get("type") == "http.request":
148
+ received += len(message.get("body", b""))
149
+ if received > self.max_bytes:
150
+ raise self._TooLarge
151
+ return message
152
+
153
+ async def tracked_send(message: dict[str, Any]) -> None:
154
+ nonlocal started
155
+ started = started or message.get("type") == "http.response.start"
156
+ await send(message)
157
+
158
+ try:
159
+ await self.app(scope, limited_receive, tracked_send)
160
+ except self._TooLarge:
161
+ if started:
162
+ raise
163
+ await self._reject(send)
164
+
165
+ @staticmethod
166
+ async def _reject(send: Any) -> None:
167
+ body = json.dumps({"detail": "Request body is too large"}).encode()
168
+ await send({"type": "http.response.start", "status": 413, "headers": [
169
+ (b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]})
170
+ await send({"type": "http.response.body", "body": body})
171
+
172
+
173
+ def install_middlewares(app: FastAPI, config: ServerConfig, *, prefix: str = "") -> None:
174
+ """Request-size limit on ``POST {prefix}/runs`` and CORS for ``config.cors_origins``."""
175
+ app.add_middleware(RequestSizeLimitMiddleware, max_bytes=config.max_request_bytes,
176
+ path=f"{prefix.rstrip('/')}/runs")
177
+ app.add_middleware(CORSMiddleware, allow_origins=config.cors_origins, allow_methods=["*"], allow_headers=["*"])
178
+
179
+
180
+ def create_app(config: ServerConfig, *, run_backend: RunBackend | None = None,
181
+ run_manager: RunManager | None = None) -> FastAPI:
182
+ """A standalone app; embedding applications should use ``create_router``."""
183
+ if run_backend is not None and run_manager is not None:
184
+ raise ValueError("pass run_backend or run_manager, not both")
185
+ backend = run_backend if run_backend is not None else InProcessRunBackend(RunExecutor(config), manager=run_manager)
186
+
187
+ @asynccontextmanager
188
+ async def lifespan(_: FastAPI) -> AsyncIterator[None]:
189
+ yield
190
+ await backend.shutdown()
191
+
192
+ app = FastAPI(title="core-server", version=PACKAGE_VERSION, lifespan=lifespan)
193
+ app.state.run_backend = backend
194
+ install_middlewares(app, config)
195
+ app.include_router(create_router(config, run_backend=backend))
196
+ return app
@@ -0,0 +1,315 @@
1
+ """Request and response models, ``ServerConfig``, and the model catalog served at ``GET /models``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import uuid
7
+ from dataclasses import dataclass, field, fields
8
+ from typing import Any, Awaitable, Callable, Dict, List, Literal, Mapping, Optional
9
+
10
+ from fastapi import Request
11
+ from pydantic import BaseModel, ConfigDict, Field
12
+
13
+ from core_ai.models import ModelInfo
14
+ from core_ai.providers.catalog import get_provider
15
+ from core_ai.registry import ModelRegistry
16
+ from core_ai.types import Message
17
+ from core_harness import (Addon, HarnessConfig, Persistence, PersistenceAddon, SubagentAddon, Tool,
18
+ compaction_from_config)
19
+
20
+ ThinkingLevel = Literal["none", "minimal", "low", "medium", "high", "xhigh", "max"]
21
+ RunStatus = Literal["queued", "running", "completed", "failed", "cancelled"]
22
+ DEFAULT_SYSTEM_PROMPT = "You are a helpful agent."
23
+ _MODEL_ENV = ("SYMPHONY_MODEL", "OPENAI_MODEL", "ANTHROPIC_MODEL", "GEMINI_MODEL", "GROK_MODEL", "XAI_MODEL",
24
+ "OPENROUTER_MODEL", "VERCEL_MODEL", "AI_GATEWAY_MODEL", "OLLAMA_MODEL", "LOCAL_MODEL")
25
+
26
+ # --- wire models ------------------------------------------------------------------
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class RunContext:
31
+ """Application-resolved identity and storage session for a run.
32
+
33
+ Applications should use ``principal_id`` and/or an opaque, namespaced
34
+ ``session_id`` to keep tenant conversations isolated.
35
+ """
36
+
37
+ session_id: str
38
+ principal_id: Optional[str] = None
39
+ metadata: Mapping[str, Any] = field(default_factory=dict)
40
+
41
+
42
+ class RunRequest(BaseModel):
43
+ model_config = ConfigDict(extra="forbid")
44
+
45
+ message: str = Field(..., min_length=1)
46
+ conversation: Optional[List[Message]] = None
47
+ session_id: Optional[str] = Field(default=None, min_length=1)
48
+ model_id: Optional[str] = Field(default=None, min_length=1)
49
+ reasoning_effort: Optional[ThinkingLevel] = None
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class RunSubmission:
54
+ """Accepted request plus resolved identity, suitable for queue serialization."""
55
+
56
+ context: RunContext
57
+ request: RunRequest
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class SupportedModel:
62
+ """An allowlist entry: only these ``provider:model`` slugs are advertised and accepted."""
63
+
64
+ slug: str
65
+ label: str = ""
66
+
67
+ def __post_init__(self) -> None:
68
+ slug = self.slug.strip()
69
+ if not slug:
70
+ raise ValueError("model slug must not be empty")
71
+ object.__setattr__(self, "slug", slug)
72
+ object.__setattr__(self, "label", self.label.strip() or slug)
73
+
74
+
75
+ class RegistryModel(BaseModel):
76
+ model_config = ConfigDict(populate_by_name=True)
77
+
78
+ id: str
79
+ label: str
80
+ thinking_levels: List[ThinkingLevel] = Field(alias="thinkingLevels")
81
+ # The model's context window in tokens; omitted when the catalog has none.
82
+ context_window: Optional[int] = Field(default=None, alias="contextWindow")
83
+
84
+
85
+ class RegistryProvider(BaseModel):
86
+ model_config = ConfigDict(populate_by_name=True)
87
+
88
+ id: str
89
+ label: str
90
+ logo: str
91
+ default_model: str = Field(alias="defaultModel")
92
+ models: List[RegistryModel]
93
+
94
+
95
+ class ModelRegistryResponse(BaseModel):
96
+ model_config = ConfigDict(populate_by_name=True)
97
+
98
+ default_provider_id: str = Field(alias="defaultProviderId")
99
+ providers: List[RegistryProvider]
100
+
101
+
102
+ class RunAccepted(BaseModel):
103
+ run_id: str
104
+ session_id: str
105
+ status: RunStatus
106
+ events_url: str
107
+
108
+
109
+ class AnswerRequest(BaseModel):
110
+ """Reply to the ``question_asked`` event with this ``request_id``."""
111
+
112
+ model_config = ConfigDict(extra="forbid")
113
+
114
+ request_id: str = Field(min_length=1)
115
+ value: str = ""
116
+
117
+
118
+ class RunInterrupted(BaseModel):
119
+ """``interrupted`` is false when the run had no active turn to stop."""
120
+
121
+ interrupted: bool
122
+
123
+
124
+ class RunStatusResponse(BaseModel):
125
+ run_id: str
126
+ session_id: str
127
+ status: RunStatus
128
+ created_at: float
129
+ started_at: Optional[float] = None
130
+ finished_at: Optional[float] = None
131
+ error: Optional[str] = None
132
+
133
+
134
+ # --- server configuration -----------------------------------------------------------
135
+
136
+ AddonFactory = Callable[[RunContext], Addon]
137
+ SubagentFactory = Callable[[RunContext], SubagentAddon]
138
+ RunContextResolver = Callable[[Request, Optional[str]], Awaitable[RunContext]]
139
+ RunAuthorizer = Callable[[Request, RunContext], Awaitable[bool]]
140
+
141
+
142
+ async def anonymous_run_context(request: Request, requested_session_id: Optional[str]) -> RunContext:
143
+ """Single-tenant default; authenticated apps should replace this resolver."""
144
+ return RunContext(session_id=requested_session_id or str(uuid.uuid4()))
145
+
146
+
147
+ async def allow_run_access(request: Request, context: RunContext) -> bool:
148
+ """Single-tenant default authorizer."""
149
+ return True
150
+
151
+
152
+ @dataclass
153
+ class ServerConfig:
154
+ """Everything needed to build a ``CoreHarness`` per run, plus HTTP request policy.
155
+
156
+ ``supported_models`` is an optional allowlist on top of the live registry.
157
+ The harness-named fields (``max_turns`` … ``max_parallel_tool_calls``) are
158
+ passed through to ``HarnessConfig``.
159
+ """
160
+
161
+ registry: ModelRegistry
162
+ model_id: str
163
+ supported_models: List[SupportedModel] = field(default_factory=list)
164
+ system_prompt: str = DEFAULT_SYSTEM_PROMPT
165
+ tools: List[Tool] = field(default_factory=list)
166
+ persistence: Optional[Persistence] = None
167
+ addon_factories: List[AddonFactory] = field(default_factory=list)
168
+ enable_subagents: bool = False
169
+ subagent_factory: Optional[SubagentFactory] = None
170
+ resolve_run_context: RunContextResolver = anonymous_run_context
171
+ authorize_run: RunAuthorizer = allow_run_access
172
+ reasoning_effort: Optional[ThinkingLevel] = None
173
+ max_turns: int = 8
174
+ max_tool_calls: Optional[int] = None
175
+ max_runtime_seconds: Optional[float] = None
176
+ max_tokens: Optional[int] = None
177
+ context_limits: Optional[Dict[str, int]] = None
178
+ context_warn_threshold: Optional[int] = None
179
+ context_compact_ratio: Optional[float] = 0.8
180
+ tool_result_max_chars: Optional[int] = 32_000
181
+ context_target_tokens: Optional[int] = None
182
+ compaction_keep_recent_tools: int = 32
183
+ max_spawn_depth: int = 1
184
+ spawn_max_turns: Optional[int] = None
185
+ max_parallel_tool_calls: int = 3
186
+ cors_origins: List[str] = field(default_factory=list)
187
+ max_request_bytes: int = 1_048_576
188
+ max_message_chars: int = 32_000
189
+ max_history_messages: int = 100
190
+ max_history_chars: int = 500_000
191
+
192
+ def __post_init__(self) -> None:
193
+ for name in ("supported_models", "tools", "addon_factories", "cors_origins"):
194
+ setattr(self, name, list(getattr(self, name) or []))
195
+ slugs = [model.slug for model in self.supported_models]
196
+ if len(slugs) != len(set(slugs)):
197
+ raise ValueError("supported model slugs must be unique")
198
+ if slugs and self.model_id not in slugs:
199
+ raise ValueError("model_id must be present in supported_models")
200
+ for name in ("max_turns", "compaction_keep_recent_tools", "max_parallel_tool_calls", "max_request_bytes",
201
+ "max_message_chars", "max_history_messages", "max_history_chars"):
202
+ if getattr(self, name) <= 0:
203
+ raise ValueError(f"{name} must be positive")
204
+ if self.spawn_max_turns is not None and self.spawn_max_turns <= 0:
205
+ raise ValueError("spawn_max_turns must be positive")
206
+ if self.max_spawn_depth < 0:
207
+ raise ValueError("max_spawn_depth must be non-negative")
208
+
209
+ def to_harness_config(self) -> HarnessConfig:
210
+ values = {f.name: getattr(self, f.name) for f in fields(self) if f.name in HarnessConfig.model_fields}
211
+ if values["context_limits"] is None:
212
+ del values["context_limits"]
213
+ return HarnessConfig(**values)
214
+
215
+ def addons_for_run(self, context: RunContext) -> list[Addon]:
216
+ """Persistence, compaction, subagents, then each ``addon_factories`` add-on."""
217
+ addons: list[Addon] = []
218
+ if self.persistence is not None:
219
+ addons.append(PersistenceAddon(self.persistence))
220
+ if self.context_compact_ratio is not None:
221
+ addons.append(compaction_from_config(self.to_harness_config()))
222
+ if self.enable_subagents or self.subagent_factory is not None:
223
+ addons.append((self.subagent_factory or (lambda _: SubagentAddon()))(context))
224
+ return addons + [factory(context) for factory in self.addon_factories]
225
+
226
+
227
+ def build_config(*, registry: Optional[ModelRegistry] = None, model_id: Optional[str] = None,
228
+ **settings: Any) -> ServerConfig:
229
+ """A ``ServerConfig`` with the default provider registry and a model from the environment when not given."""
230
+ if registry is None:
231
+ from core_ai.providers.defaults import build_default_registry
232
+
233
+ registry = build_default_registry()
234
+ return ServerConfig(registry=registry, model_id=_resolve_model_id(registry, model_id), **settings)
235
+
236
+
237
+ def _resolve_model_id(registry: ModelRegistry, model_id: Optional[str]) -> str:
238
+ selected = model_id or next((os.environ[name] for name in _MODEL_ENV if os.getenv(name)), None)
239
+ if selected:
240
+ if ":" in selected:
241
+ return selected
242
+ provider = next((p for prefix, p in (("claude-", "anthropic"), ("gemini-", "gemini"), ("grok-", "grok"))
243
+ if selected.startswith(prefix)), "openai")
244
+ return f"{provider}:{selected}"
245
+ from core_ai.providers.defaults import default_model_id
246
+
247
+ try:
248
+ return default_model_id(registry)
249
+ except RuntimeError:
250
+ return "openai:gpt-5.6-luna"
251
+
252
+
253
+ # --- model catalog --------------------------------------------------------------------
254
+
255
+ _MODEL_LABELS = {"gpt-4.1": "GPT-4.1", "claude-3-7-sonnet-20250219": "Claude 3.7 Sonnet"}
256
+
257
+
258
+ def is_accepted_model(config: ServerConfig, model_id: str) -> bool:
259
+ """A ``provider:model`` id routed by a registered provider and, if set, on the allowlist."""
260
+ provider, separator, _ = model_id.partition(":")
261
+ if not separator or provider not in config.registry.namespaces():
262
+ return False
263
+ return not config.supported_models or any(model.slug == model_id for model in config.supported_models)
264
+
265
+
266
+ def model_registry_response(config: ServerConfig) -> ModelRegistryResponse:
267
+ providers = [provider for provider_id in config.registry.namespaces()
268
+ if (provider := _provider_response(config, provider_id)) is not None]
269
+ selected = config.model_id.partition(":")[0]
270
+ default = next((p.id for p in providers if p.id == selected), providers[0].id if providers else "")
271
+ return ModelRegistryResponse(default_provider_id=default, providers=providers)
272
+
273
+
274
+ def _provider_response(config: ServerConfig, provider_id: str) -> Optional[RegistryProvider]:
275
+ models = _registry_models(config, provider_id)
276
+ if not models:
277
+ return None
278
+ try:
279
+ info = get_provider(provider_id)
280
+ label, default_model = info.label, info.default_model
281
+ except KeyError:
282
+ label, default_model = provider_id.replace("-", " ").title(), ""
283
+ if config.model_id.startswith(f"{provider_id}:"):
284
+ default_model = config.model_id
285
+ if default_model not in {model.id for model in models}:
286
+ default_model = models[0].id
287
+ logo = {"gemini": "google", "grok": "xai"}.get(provider_id, provider_id)
288
+ return RegistryProvider(id=provider_id, label=label, logo=f"https://models.dev/logos/{logo}.svg",
289
+ default_model=default_model, models=models)
290
+
291
+
292
+ def _registry_models(config: ServerConfig, provider_id: str) -> list[RegistryModel]:
293
+ catalog = {model.full_id: model for model in config.registry.models(provider_id)}
294
+ if config.supported_models:
295
+ choices = [(m.slug, m.label) for m in config.supported_models if m.slug.startswith(f"{provider_id}:")]
296
+ else:
297
+ choices = [(slug, _model_label(model.id)) for slug, model in catalog.items()]
298
+ if config.model_id.startswith(f"{provider_id}:") and config.model_id not in catalog:
299
+ choices.append((config.model_id, _model_label(config.model_id.partition(":")[2])))
300
+ return [RegistryModel(id=slug, label=label, thinking_levels=_thinking_levels(catalog.get(slug)),
301
+ context_window=(catalog[slug].context_limit or None) if slug in catalog else None)
302
+ for slug, label in choices]
303
+
304
+
305
+ def _thinking_levels(model: Optional[ModelInfo]) -> list[ThinkingLevel]:
306
+ if model is None:
307
+ return []
308
+ return ["none" if level == "off" else level for level, value in model.thinking_level_map if value is not None]
309
+
310
+
311
+ def _model_label(model_id: str) -> str:
312
+ if model_id in _MODEL_LABELS:
313
+ return _MODEL_LABELS[model_id]
314
+ words = model_id.replace("-", " ").replace("_", " ").split()
315
+ return " ".join(w.upper() if w.lower() in {"gpt", "o1", "o3", "o4"} else w.capitalize() for w in words)
File without changes
@@ -0,0 +1,338 @@
1
+ """Runs that outlive the HTTP request: scheduling, replayable events, and live control.
2
+
3
+ ``RunManager`` owns run tasks and their event logs. ``RunExecutor`` builds and
4
+ runs one harness. ``InProcessRunBackend`` joins them and is the default
5
+ ``RunBackend``; applications may supply their own (for example a queue).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import time
13
+ import uuid
14
+ from collections import deque
15
+ from contextlib import nullcontext
16
+ from dataclasses import dataclass, field
17
+ from typing import Any, AsyncIterator, Awaitable, Callable, Optional, Protocol, runtime_checkable
18
+
19
+ from core_harness import (Answer, ControlPlaneEvent, CoreHarness, EventSink, HarnessCancelled, HarnessLimitExceeded,
20
+ HumanInteraction, Interrupt)
21
+
22
+ from core_server.config import RunContext, RunStatus, RunStatusResponse, RunSubmission, ServerConfig
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ RunCoroutine = Callable[[str, EventSink], Awaitable[None]]
27
+ FINISHED = {"completed", "failed", "cancelled"}
28
+ _TERMINAL_EVENTS: dict[str, RunStatus] = {"run_completed": "completed", "run_failed": "failed",
29
+ "run_cancelled": "cancelled", "run_limit_exceeded": "failed"}
30
+
31
+
32
+ @dataclass
33
+ class RunRecord:
34
+ run_id: str
35
+ context: RunContext
36
+ status: RunStatus = "queued"
37
+ created_at: float = field(default_factory=time.time)
38
+ started_at: Optional[float] = None
39
+ finished_at: Optional[float] = None
40
+ error: Optional[str] = None
41
+ events: list[ControlPlaneEvent] = field(default_factory=list)
42
+ task: Optional[asyncio.Task[None]] = None
43
+ condition: asyncio.Condition = field(default_factory=asyncio.Condition)
44
+
45
+ def response(self) -> RunStatusResponse:
46
+ return RunStatusResponse(run_id=self.run_id, session_id=self.context.session_id, status=self.status,
47
+ created_at=self.created_at, started_at=self.started_at,
48
+ finished_at=self.finished_at, error=self.error)
49
+
50
+ def finish(self, status: RunStatus, error: Optional[str] = None) -> None:
51
+ self.status, self.error, self.finished_at = status, error, time.time()
52
+
53
+
54
+ class RunState(Protocol):
55
+ """Read-only run state the router needs for responses and authorization."""
56
+
57
+ run_id: str
58
+ context: RunContext
59
+ status: RunStatus
60
+
61
+ def response(self) -> RunStatusResponse: ...
62
+
63
+
64
+ class RunBackend(Protocol):
65
+ """Storage and scheduling behind the router."""
66
+
67
+ async def submit(self, submission: RunSubmission) -> RunState:
68
+ """Accept the request or raise ``RunCapacityError``."""
69
+ ...
70
+
71
+ async def get(self, run_id: str) -> RunState: ...
72
+
73
+ def events(self, run_id: str, *, after: int = 0) -> AsyncIterator[tuple[int, ControlPlaneEvent]]:
74
+ """Replay events after the given one-based ordinal, then follow live ones."""
75
+ ...
76
+
77
+ async def cancel(self, run_id: str) -> RunState: ...
78
+
79
+ async def shutdown(self) -> None: ...
80
+
81
+
82
+ @runtime_checkable
83
+ class RunControl(Protocol):
84
+ """Optional live-run operations. The router adds ``/answer`` and ``/interrupt`` only for these backends."""
85
+
86
+ async def answer(self, run_id: str, request_id: str, value: str) -> bool:
87
+ """Answer the run's open question. False when none has ``request_id``."""
88
+ ...
89
+
90
+ async def interrupt(self, run_id: str) -> bool:
91
+ """Stop the active turn, or cancel a queued run. False once it has finished."""
92
+ ...
93
+
94
+
95
+ class RunCapacityError(Exception):
96
+ """The backend has reached its run capacity."""
97
+
98
+
99
+ class RunNotFoundError(KeyError):
100
+ pass
101
+
102
+
103
+ class ManagedEventSink(EventSink):
104
+ """Append a run's events to its record; the root agent's terminal event sets the run status.
105
+
106
+ The root is the ``agent_id`` of the first unparented ``run_started``.
107
+ Subagent events (``parent_id`` set, or another agent) share the sink but
108
+ never finish the run. Until the root is known, only an event with no
109
+ ``agent_id`` counts as the root's.
110
+ """
111
+
112
+ def __init__(self, record: RunRecord) -> None:
113
+ super().__init__()
114
+ self.record = record
115
+ self.root_agent_id: Any = None
116
+ self._root_known = False
117
+ self.terminal_status: Optional[RunStatus] = None
118
+ self.terminal_error: Optional[str] = None
119
+
120
+ def from_root(self, event_type: str, payload: dict[str, Any]) -> bool:
121
+ if payload.get("parent_id"):
122
+ return False
123
+ agent_id = payload.get("agent_id")
124
+ if event_type == "run_started" and agent_id is not None and not self._root_known:
125
+ self.root_agent_id, self._root_known = agent_id, True
126
+ return agent_id == self.root_agent_id if self._root_known else agent_id is None
127
+
128
+ async def deliver(self, event_type: str, payload: dict[str, Any]) -> None:
129
+ async with self.record.condition:
130
+ self.record.events.append(ControlPlaneEvent.typed(event_type, payload))
131
+ status = _TERMINAL_EVENTS.get(event_type)
132
+ # from_root runs for every event: it learns the root from run_started.
133
+ if self.from_root(event_type, payload) and status is not None:
134
+ self.terminal_status = status
135
+ if status == "failed":
136
+ self.terminal_error = str(payload.get("message") or "run failed")
137
+ self.record.condition.notify_all()
138
+
139
+
140
+ class RunManager:
141
+ """Run tasks one session at a time, bounded by concurrency and backlog limits.
142
+
143
+ Finished runs stay readable until ``max_finished_runs`` newer runs have
144
+ finished (``None`` keeps all). A session's lock is dropped once it has no
145
+ queued or running run.
146
+ """
147
+
148
+ def __init__(self, *, max_concurrent_runs: int | None = 64, max_outstanding_runs: int | None = 1024,
149
+ max_finished_runs: int | None = 1024) -> None:
150
+ for name, value in (("max_concurrent_runs", max_concurrent_runs),
151
+ ("max_outstanding_runs", max_outstanding_runs), ("max_finished_runs", max_finished_runs)):
152
+ if value is not None and value <= 0:
153
+ raise ValueError(f"{name} must be positive or None")
154
+ self._runs: dict[str, RunRecord] = {}
155
+ self._session_locks: dict[str, asyncio.Lock] = {}
156
+ self._finished: deque[str] = deque()
157
+ self._max_finished_runs = max_finished_runs
158
+ self._max_outstanding_runs = max_outstanding_runs
159
+ self._lock = asyncio.Lock()
160
+ self._run_slots = asyncio.Semaphore(max_concurrent_runs) if max_concurrent_runs is not None else None
161
+
162
+ async def start(self, context: RunContext, run: RunCoroutine) -> RunRecord:
163
+ record = RunRecord(run_id=str(uuid.uuid4()), context=context)
164
+ async with self._lock:
165
+ outstanding = sum(item.status in {"queued", "running"} for item in self._runs.values())
166
+ if self._max_outstanding_runs is not None and outstanding >= self._max_outstanding_runs:
167
+ raise RunCapacityError("run capacity is full")
168
+ self._runs[record.run_id] = record
169
+ session_lock = self._session_locks.setdefault(context.session_id, asyncio.Lock())
170
+ record.task = asyncio.create_task(self._execute(record, session_lock, run),
171
+ name=f"core-server-run:{record.run_id}")
172
+ return record
173
+
174
+ async def get(self, run_id: str) -> RunRecord:
175
+ async with self._lock:
176
+ record = self._runs.get(run_id)
177
+ if record is None:
178
+ raise RunNotFoundError(run_id)
179
+ return record
180
+
181
+ async def cancel(self, run_id: str) -> RunRecord:
182
+ record = await self.get(run_id)
183
+ if record.task is not None and not record.task.done():
184
+ record.task.cancel()
185
+ try:
186
+ await record.task
187
+ except asyncio.CancelledError:
188
+ pass
189
+ await self._finish_unstarted(record)
190
+ return record
191
+
192
+ async def events(self, run_id: str, *, after: int = 0) -> AsyncIterator[tuple[int, ControlPlaneEvent]]:
193
+ record = await self.get(run_id)
194
+ cursor = max(after, 0)
195
+ while True:
196
+ async with record.condition:
197
+ await record.condition.wait_for(lambda: cursor < len(record.events) or record.status in FINISHED)
198
+ available = list(enumerate(record.events[cursor:], start=cursor + 1))
199
+ terminal = record.status in FINISHED
200
+ for cursor, event in available:
201
+ yield cursor, event
202
+ if terminal and cursor >= len(record.events):
203
+ return
204
+
205
+ async def shutdown(self) -> None:
206
+ async with self._lock:
207
+ active = [record for record in self._runs.values() if record.task is not None and not record.task.done()]
208
+ for record in active:
209
+ record.task.cancel()
210
+ await asyncio.gather(*(record.task for record in active), return_exceptions=True)
211
+ for record in active:
212
+ await self._finish_unstarted(record)
213
+
214
+ async def _execute(self, record: RunRecord, session_lock: asyncio.Lock, run: RunCoroutine) -> None:
215
+ try:
216
+ async with session_lock, self._run_slots or nullcontext():
217
+ record.status, record.started_at = "running", time.time()
218
+ sink = ManagedEventSink(record)
219
+ await run(record.run_id, sink)
220
+ if record.status == "running":
221
+ record.finish(sink.terminal_status or "completed", sink.terminal_error)
222
+ except asyncio.CancelledError:
223
+ if record.status not in FINISHED:
224
+ record.finish("cancelled")
225
+ raise
226
+ except Exception as exc:
227
+ record.finish("failed", str(exc) or type(exc).__name__)
228
+ finally:
229
+ self._retire(record)
230
+ async with record.condition:
231
+ record.condition.notify_all()
232
+
233
+ async def _finish_unstarted(self, record: RunRecord) -> None:
234
+ """A task cancelled before its first step never reaches ``_execute``'s cleanup; do it here."""
235
+ if record.status != "queued":
236
+ return
237
+ record.finish("cancelled")
238
+ self._retire(record)
239
+ async with record.condition:
240
+ record.condition.notify_all()
241
+
242
+ def _retire(self, record: RunRecord) -> None:
243
+ """Drop an idle session's lock and forget the oldest finished runs. Never awaits."""
244
+ session_id = record.context.session_id
245
+ if not any(item.context.session_id == session_id and item.status in {"queued", "running"}
246
+ for item in self._runs.values()):
247
+ self._session_locks.pop(session_id, None)
248
+ self._finished.append(record.run_id)
249
+ while self._max_finished_runs is not None and len(self._finished) > self._max_finished_runs:
250
+ self._runs.pop(self._finished.popleft(), None)
251
+
252
+
253
+ def parse_last_event_id(value: Optional[str], run_id: str) -> int:
254
+ """The ordinal from a ``<run_id>:<ordinal>`` SSE id, or 0."""
255
+ event_run_id, separator, ordinal = (value or "").rpartition(":")
256
+ if not separator or event_run_id != run_id:
257
+ return 0
258
+ try:
259
+ return max(int(ordinal), 0)
260
+ except ValueError:
261
+ return 0
262
+
263
+
264
+ class RunExecutor:
265
+ """Build and run one harness from a ``RunSubmission``; usable by queue workers too."""
266
+
267
+ def __init__(self, config: ServerConfig) -> None:
268
+ self.config = config
269
+
270
+ async def execute(self, run_id: str, submission: RunSubmission, sink: EventSink) -> None:
271
+ await self.run(self.build(run_id, submission, sink), run_id, submission)
272
+
273
+ def build(self, run_id: str, submission: RunSubmission, sink: EventSink) -> CoreHarness:
274
+ config, request, context = self.config, submission.request, submission.context
275
+ return CoreHarness(
276
+ registry=config.registry, model_id=request.model_id or config.model_id,
277
+ system_prompt=config.system_prompt, config=config.to_harness_config(),
278
+ reasoning_effort=request.reasoning_effort or config.reasoning_effort, tools=list(config.tools),
279
+ sink=sink, session_id=context.session_id, agent_id=run_id,
280
+ addons=config.addons_for_run(context) or None,
281
+ )
282
+
283
+ async def run(self, harness: CoreHarness, run_id: str, submission: RunSubmission) -> None:
284
+ """Run to the terminal event. The harness has already reported any failure as an event."""
285
+ try:
286
+ await harness.run(submission.request.message, conversation=submission.request.conversation,
287
+ session_id=submission.context.session_id)
288
+ except HarnessCancelled:
289
+ logger.info("Harness run %s cancelled", run_id)
290
+ except HarnessLimitExceeded as exc:
291
+ logger.warning("Harness run %s limit exceeded: %s", run_id, exc)
292
+ except Exception:
293
+ logger.exception("Harness run %s failed", run_id)
294
+
295
+
296
+ class InProcessRunBackend:
297
+ """Runs as local asyncio tasks. Also a ``RunControl``: questions wait for ``answer``."""
298
+
299
+ def __init__(self, executor: RunExecutor, *, manager: RunManager | None = None) -> None:
300
+ self.executor = executor
301
+ self.manager = manager or RunManager()
302
+ self._harnesses: dict[str, CoreHarness] = {}
303
+
304
+ async def submit(self, submission: RunSubmission) -> RunRecord:
305
+ async def execute(run_id: str, sink: EventSink) -> None:
306
+ sink.interaction = HumanInteraction(sink)
307
+ harness = self._harnesses[run_id] = self.executor.build(run_id, submission, sink)
308
+ try:
309
+ await self.executor.run(harness, run_id, submission)
310
+ finally:
311
+ del self._harnesses[run_id]
312
+
313
+ return await self.manager.start(submission.context, execute)
314
+
315
+ async def get(self, run_id: str) -> RunRecord:
316
+ return await self.manager.get(run_id)
317
+
318
+ async def events(self, run_id: str, *, after: int = 0) -> AsyncIterator[tuple[int, ControlPlaneEvent]]:
319
+ async for event in self.manager.events(run_id, after=after):
320
+ yield event
321
+
322
+ async def cancel(self, run_id: str) -> RunRecord:
323
+ return await self.manager.cancel(run_id)
324
+
325
+ async def answer(self, run_id: str, request_id: str, value: str) -> bool:
326
+ harness = self._harnesses.get(run_id)
327
+ return harness is not None and harness.submit(Answer(request_id=request_id, value=value))
328
+
329
+ async def interrupt(self, run_id: str) -> bool:
330
+ harness = self._harnesses.get(run_id)
331
+ if harness is not None:
332
+ return harness.submit(Interrupt())
333
+ if (await self.manager.get(run_id)).status != "queued":
334
+ return False
335
+ return (await self.manager.cancel(run_id)).status == "cancelled"
336
+
337
+ async def shutdown(self) -> None:
338
+ await self.manager.shutdown()