dap-engine 0.3.0__py3-none-any.whl
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.
- dap_engine/__init__.py +3 -0
- dap_engine/__main__.py +80 -0
- dap_engine/api/__init__.py +0 -0
- dap_engine/api/agents.py +546 -0
- dap_engine/api/deps.py +60 -0
- dap_engine/api/health.py +20 -0
- dap_engine/api/pipelines.py +428 -0
- dap_engine/api/projects.py +191 -0
- dap_engine/api/runs.py +694 -0
- dap_engine/api/runtimes.py +29 -0
- dap_engine/api/schemas.py +331 -0
- dap_engine/api/settings.py +288 -0
- dap_engine/app.py +438 -0
- dap_engine/auth/__init__.py +23 -0
- dap_engine/auth/admin_users_routes.py +134 -0
- dap_engine/auth/api_token_routes.py +345 -0
- dap_engine/auth/api_tokens.py +147 -0
- dap_engine/auth/audit.py +91 -0
- dap_engine/auth/audit_routes.py +125 -0
- dap_engine/auth/db.py +135 -0
- dap_engine/auth/oauth.py +41 -0
- dap_engine/auth/policies.py +64 -0
- dap_engine/auth/schemas.py +37 -0
- dap_engine/auth/users.py +400 -0
- dap_engine/contracts.py +205 -0
- dap_engine/execution/__init__.py +30 -0
- dap_engine/execution/conditions.py +87 -0
- dap_engine/execution/node_executor.py +363 -0
- dap_engine/execution/output_parser.py +162 -0
- dap_engine/execution/run_orchestrator.py +213 -0
- dap_engine/execution/run_registry.py +158 -0
- dap_engine/execution/runner.py +422 -0
- dap_engine/execution/validator.py +580 -0
- dap_engine/persistence/__init__.py +0 -0
- dap_engine/persistence/_common.py +24 -0
- dap_engine/persistence/agents.py +410 -0
- dap_engine/persistence/db.py +179 -0
- dap_engine/persistence/migrations.py +739 -0
- dap_engine/persistence/models.py +569 -0
- dap_engine/persistence/pipelines.py +328 -0
- dap_engine/persistence/projects.py +256 -0
- dap_engine/persistence/repository.py +101 -0
- dap_engine/persistence/runs.py +482 -0
- dap_engine/py.typed +0 -0
- dap_engine-0.3.0.dist-info/METADATA +49 -0
- dap_engine-0.3.0.dist-info/RECORD +48 -0
- dap_engine-0.3.0.dist-info/WHEEL +4 -0
- dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from dap_runtimes import RuntimeRegistry
|
|
6
|
+
from fastapi import APIRouter, Depends, HTTPException
|
|
7
|
+
|
|
8
|
+
from dap_engine.api.deps import get_registry
|
|
9
|
+
|
|
10
|
+
router = APIRouter(prefix="/runtimes", tags=["runtimes"])
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@router.get("")
|
|
14
|
+
async def list_runtimes(
|
|
15
|
+
registry: RuntimeRegistry = Depends(get_registry),
|
|
16
|
+
) -> list[dict[str, Any]]:
|
|
17
|
+
return [{"id": a.id, "displayName": a.display_name, "kind": a.kind} for a in registry.list()]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@router.get("/{runtime_id}/health")
|
|
21
|
+
async def runtime_health(
|
|
22
|
+
runtime_id: str,
|
|
23
|
+
registry: RuntimeRegistry = Depends(get_registry),
|
|
24
|
+
) -> dict[str, Any]:
|
|
25
|
+
if not registry.has(runtime_id):
|
|
26
|
+
raise HTTPException(status_code=404, detail=f"Runtime not found: {runtime_id}")
|
|
27
|
+
adapter = registry.get(runtime_id)
|
|
28
|
+
health = await adapter.healthcheck()
|
|
29
|
+
return health.model_dump(exclude_none=True)
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""API-only response and ancillary request types for the engine REST API.
|
|
2
|
+
|
|
3
|
+
Cross-layer request contracts (the bodies of POST/PUT mutations that
|
|
4
|
+
persistence and execution layers consume) live in
|
|
5
|
+
:mod:`dap_engine.contracts`. This module contains the rest: response
|
|
6
|
+
shapes, exports, dry-run payloads, pagination wrappers — anything that
|
|
7
|
+
should never be imported outside ``api/``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any, Final, Literal, Self
|
|
13
|
+
|
|
14
|
+
from dap_types.agent import coerce_legacy_field_list, validate_field_list
|
|
15
|
+
from dap_types.pipeline import PipelineDefaults, PipelineEdge, PipelineNode
|
|
16
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
17
|
+
|
|
18
|
+
AGENT_EXPORT_SCHEMA_VERSION = "agent-export/1"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AgentExportPayload(BaseModel):
|
|
22
|
+
"""The portable subset of an agent — no per-installation fields.
|
|
23
|
+
|
|
24
|
+
Mirrors :class:`AgentCreate` field-by-field minus the fields the
|
|
25
|
+
server fills in (id, version, timestamps, archived_at). Reuses the
|
|
26
|
+
same ``input_schema`` / ``output_schema`` validators so an
|
|
27
|
+
exported agent that's importable here is also creatable directly
|
|
28
|
+
via ``POST /agents``.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
model_config = ConfigDict(extra="forbid")
|
|
32
|
+
|
|
33
|
+
name: str = Field(min_length=1, max_length=200)
|
|
34
|
+
role: str = Field(min_length=1, max_length=100)
|
|
35
|
+
|
|
36
|
+
runtime_id: str
|
|
37
|
+
runtime_config: dict[str, Any] = Field(default_factory=dict)
|
|
38
|
+
prompt_template: str
|
|
39
|
+
|
|
40
|
+
input_schema: list[str] = Field(default_factory=list)
|
|
41
|
+
output_schema: list[str] = Field(default_factory=list)
|
|
42
|
+
constraints: list[str] = Field(default_factory=list)
|
|
43
|
+
|
|
44
|
+
budget_limit_usd: float | None = None
|
|
45
|
+
timeout_ms: int = Field(default=60_000, gt=0)
|
|
46
|
+
|
|
47
|
+
@field_validator("input_schema", "output_schema", mode="before")
|
|
48
|
+
@classmethod
|
|
49
|
+
def _coerce_legacy_dict_schema(cls, value: Any) -> Any:
|
|
50
|
+
return coerce_legacy_field_list(value)
|
|
51
|
+
|
|
52
|
+
@field_validator("input_schema", "output_schema")
|
|
53
|
+
@classmethod
|
|
54
|
+
def _check_known_fields(cls, value: list[str]) -> list[str]:
|
|
55
|
+
return validate_field_list(value)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class AgentExport(BaseModel):
|
|
59
|
+
"""Response shape of ``GET /agents/{id}/export``.
|
|
60
|
+
|
|
61
|
+
Versioned so future format changes can be detected at import time
|
|
62
|
+
rather than silently producing odd state.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
model_config = ConfigDict(extra="forbid")
|
|
66
|
+
|
|
67
|
+
schema_version: str = AGENT_EXPORT_SCHEMA_VERSION
|
|
68
|
+
agent: AgentExportPayload
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class AgentImportRequest(BaseModel):
|
|
72
|
+
"""Body of ``POST /agents/import`` — same shape as :class:`AgentExport`."""
|
|
73
|
+
|
|
74
|
+
model_config = ConfigDict(extra="forbid")
|
|
75
|
+
|
|
76
|
+
schema_version: str
|
|
77
|
+
agent: AgentExportPayload
|
|
78
|
+
|
|
79
|
+
@field_validator("schema_version")
|
|
80
|
+
@classmethod
|
|
81
|
+
def _check_schema_version(cls, value: str) -> str:
|
|
82
|
+
if value != AGENT_EXPORT_SCHEMA_VERSION:
|
|
83
|
+
msg = (
|
|
84
|
+
f"Unsupported schema_version '{value}'. This engine accepts "
|
|
85
|
+
f"'{AGENT_EXPORT_SCHEMA_VERSION}'."
|
|
86
|
+
)
|
|
87
|
+
raise ValueError(msg)
|
|
88
|
+
return value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ``Final`` narrows the inferred type to ``Literal["pipeline-export/1"]``
|
|
92
|
+
# so the constant is assignable to the ``Literal`` schema_version
|
|
93
|
+
# fields below without mypy complaining. Same string, stronger type.
|
|
94
|
+
PIPELINE_EXPORT_SCHEMA_VERSION: Final = "pipeline-export/1"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class PipelineExportPayload(BaseModel):
|
|
98
|
+
"""The portable subset of a pipeline — no per-installation fields.
|
|
99
|
+
|
|
100
|
+
Mirrors :class:`PipelineCreate` field-by-field minus the fields
|
|
101
|
+
the server fills in (``id``, ``version``, timestamps,
|
|
102
|
+
``archived_at``). Reuses the same node / edge / defaults shapes
|
|
103
|
+
so an exported pipeline that's importable here is also creatable
|
|
104
|
+
directly via ``POST /pipelines``.
|
|
105
|
+
|
|
106
|
+
``node.agent_id`` references the *source installation's* agent
|
|
107
|
+
ids. The importer doesn't rewrite them — the existing DAG
|
|
108
|
+
validator (#120) returns 422 if any referenced agent is missing
|
|
109
|
+
or archived in the target DB. Bundling the referenced agents
|
|
110
|
+
into the export envelope (so import auto-creates them and
|
|
111
|
+
rewrites the references) is a separate follow-up.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
model_config = ConfigDict(extra="forbid")
|
|
115
|
+
|
|
116
|
+
name: str = Field(min_length=1, max_length=200)
|
|
117
|
+
description: str = ""
|
|
118
|
+
|
|
119
|
+
schema_version: Literal["langgraph/1.0"] = "langgraph/1.0"
|
|
120
|
+
state_schema_ref: str = Field(min_length=1)
|
|
121
|
+
entry_point: str = Field(min_length=1)
|
|
122
|
+
|
|
123
|
+
nodes: list[PipelineNode]
|
|
124
|
+
edges: list[PipelineEdge]
|
|
125
|
+
defaults: PipelineDefaults = Field(default_factory=PipelineDefaults)
|
|
126
|
+
# Dashboard-private layout metadata (node positions, etc.). Included in
|
|
127
|
+
# exports so positions survive round-trips through export/import (#226).
|
|
128
|
+
ui_metadata: dict[str, Any] | None = None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class PipelineExport(BaseModel):
|
|
132
|
+
"""Response shape of ``GET /pipelines/{id}/export``.
|
|
133
|
+
|
|
134
|
+
Versioned so future format changes can be detected at import
|
|
135
|
+
time rather than silently producing odd state. The ``Literal``
|
|
136
|
+
type locks the response contract — clients reading the OpenAPI
|
|
137
|
+
schema see a single accepted value, and constructing a
|
|
138
|
+
``PipelineExport`` instance with anything else fails Pydantic
|
|
139
|
+
validation at the call site.
|
|
140
|
+
|
|
141
|
+
``bundled_agents`` (#126) ships the agents this pipeline
|
|
142
|
+
references so a target installation that doesn't have them yet
|
|
143
|
+
can import the whole thing in one shot. Keys are the *source*
|
|
144
|
+
installation's agent ids — the importer rewrites every
|
|
145
|
+
``node.agent_id`` in the pipeline payload to the freshly
|
|
146
|
+
assigned local id before the DAG validator runs. ``None``
|
|
147
|
+
means the export is pipeline-only (default behaviour, backward
|
|
148
|
+
compat with Phase 1 exports).
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
model_config = ConfigDict(extra="forbid")
|
|
152
|
+
|
|
153
|
+
schema_version: Literal["pipeline-export/1"] = PIPELINE_EXPORT_SCHEMA_VERSION
|
|
154
|
+
pipeline: PipelineExportPayload
|
|
155
|
+
bundled_agents: dict[str, AgentExportPayload] | None = None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class PipelineImportRequest(BaseModel):
|
|
159
|
+
"""Body of ``POST /pipelines/import`` — same shape as :class:`PipelineExport`.
|
|
160
|
+
|
|
161
|
+
Pydantic enforces ``schema_version`` against the literal — a
|
|
162
|
+
different value comes back as a 422 from FastAPI's standard
|
|
163
|
+
request-validation error path with the offending value visible
|
|
164
|
+
in the detail. No custom validator needed.
|
|
165
|
+
|
|
166
|
+
``bundled_agents`` mirrors :class:`PipelineExport` — when
|
|
167
|
+
present the importer creates each agent, builds an
|
|
168
|
+
``old_id → new_id`` map, and rewrites ``node.agent_id`` before
|
|
169
|
+
persisting the pipeline. Missing field = legacy pipeline-only
|
|
170
|
+
import (referenced agents must already exist locally).
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
model_config = ConfigDict(extra="forbid")
|
|
174
|
+
|
|
175
|
+
schema_version: Literal["pipeline-export/1"]
|
|
176
|
+
pipeline: PipelineExportPayload
|
|
177
|
+
bundled_agents: dict[str, AgentExportPayload] | None = None
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class ProjectRunRequest(BaseModel):
|
|
181
|
+
"""POST /projects/{project_id}/run/{kind} body — convenience trigger.
|
|
182
|
+
|
|
183
|
+
All fields optional: the project resolves the bound pipeline_id
|
|
184
|
+
from ``kind`` and seeds ``repo`` / ``branch`` defaults; the caller
|
|
185
|
+
only supplies what they want to override per-call.
|
|
186
|
+
"""
|
|
187
|
+
|
|
188
|
+
model_config = ConfigDict(extra="forbid")
|
|
189
|
+
|
|
190
|
+
pipeline_version: int | None = None
|
|
191
|
+
initial_state: dict[str, Any] = Field(default_factory=dict)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class RenderPreviewRequest(BaseModel):
|
|
195
|
+
"""Body for POST /agents/{id}/render-preview."""
|
|
196
|
+
|
|
197
|
+
model_config = ConfigDict(extra="forbid")
|
|
198
|
+
|
|
199
|
+
context: dict[str, Any] = Field(default_factory=dict)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class RenderPreviewResponse(BaseModel):
|
|
203
|
+
"""Response from render-preview — XML output + validation outcome."""
|
|
204
|
+
|
|
205
|
+
model_config = ConfigDict(extra="forbid")
|
|
206
|
+
|
|
207
|
+
rendered_xml: str
|
|
208
|
+
valid: bool
|
|
209
|
+
warnings: list[str] = Field(default_factory=list)
|
|
210
|
+
errors: list[str] = Field(default_factory=list)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# ---------------------------------------------------------------------------
|
|
214
|
+
# Agent dry-run (#103) — execute one agent against sample context without
|
|
215
|
+
# creating an Agent version, a Run row, or a NodeExecutionLog. Used by the
|
|
216
|
+
# agent create/edit Test panel to validate prompt + runtime behaviour
|
|
217
|
+
# before saving.
|
|
218
|
+
# ---------------------------------------------------------------------------
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class AgentDryRunDraft(BaseModel):
|
|
222
|
+
"""Inline agent definition for dry-runs from an unsaved form (``/agents/new``).
|
|
223
|
+
|
|
224
|
+
Mirrors :class:`AgentCreate` field-by-field — same constraints, same
|
|
225
|
+
field validators — so a draft that dry-runs cleanly is also creatable
|
|
226
|
+
via ``POST /agents``. We don't reuse ``AgentCreate`` directly only to
|
|
227
|
+
keep the type independent of any future create-only fields.
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
model_config = ConfigDict(extra="forbid")
|
|
231
|
+
|
|
232
|
+
name: str = Field(min_length=1, max_length=200)
|
|
233
|
+
role: str = Field(min_length=1, max_length=100)
|
|
234
|
+
|
|
235
|
+
runtime_id: str
|
|
236
|
+
runtime_config: dict[str, Any] = Field(default_factory=dict)
|
|
237
|
+
prompt_template: str
|
|
238
|
+
|
|
239
|
+
input_schema: list[str] = Field(default_factory=list)
|
|
240
|
+
output_schema: list[str] = Field(default_factory=list)
|
|
241
|
+
constraints: list[str] = Field(default_factory=list)
|
|
242
|
+
|
|
243
|
+
budget_limit_usd: float | None = None
|
|
244
|
+
timeout_ms: int = Field(default=60_000, gt=0)
|
|
245
|
+
|
|
246
|
+
@field_validator("input_schema", "output_schema", mode="before")
|
|
247
|
+
@classmethod
|
|
248
|
+
def _coerce_legacy_dict_schema(cls, value: Any) -> Any:
|
|
249
|
+
return coerce_legacy_field_list(value)
|
|
250
|
+
|
|
251
|
+
@field_validator("input_schema", "output_schema")
|
|
252
|
+
@classmethod
|
|
253
|
+
def _check_known_fields(cls, value: list[str]) -> list[str]:
|
|
254
|
+
return validate_field_list(value)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class AgentDryRunRequest(BaseModel):
|
|
258
|
+
"""Body of ``POST /agents/dry-run``.
|
|
259
|
+
|
|
260
|
+
Exactly one of ``agent_id`` (saved) or ``draft`` (unsaved form) must
|
|
261
|
+
be set. ``context`` is the sample state the prompt template renders
|
|
262
|
+
against — same projection rule as a real run: when ``input_schema``
|
|
263
|
+
is non-empty, keys outside it are dropped before render so the
|
|
264
|
+
template only sees declared inputs; when ``input_schema`` is empty
|
|
265
|
+
(legacy / contract-less agents), the context is passed through
|
|
266
|
+
unchanged.
|
|
267
|
+
"""
|
|
268
|
+
|
|
269
|
+
model_config = ConfigDict(extra="forbid")
|
|
270
|
+
|
|
271
|
+
agent_id: str | None = None
|
|
272
|
+
agent_version: int | None = None
|
|
273
|
+
draft: AgentDryRunDraft | None = None
|
|
274
|
+
context: dict[str, Any] = Field(default_factory=dict)
|
|
275
|
+
|
|
276
|
+
@model_validator(mode="after")
|
|
277
|
+
def _check_exactly_one_source(self) -> Self:
|
|
278
|
+
if (self.agent_id is None) == (self.draft is None):
|
|
279
|
+
msg = "exactly one of 'agent_id' or 'draft' must be set (got both or neither)"
|
|
280
|
+
raise ValueError(msg)
|
|
281
|
+
return self
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
class OutputSchemaValidation(BaseModel):
|
|
285
|
+
"""Soft check of the runtime's structured output against ``output_schema``.
|
|
286
|
+
|
|
287
|
+
Not fatal — a missing field is a warning, not a 422. The point is to
|
|
288
|
+
surface it in the Test panel so the operator can adjust either the
|
|
289
|
+
prompt or the schema.
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
model_config = ConfigDict(extra="forbid")
|
|
293
|
+
|
|
294
|
+
valid: bool
|
|
295
|
+
checked: bool
|
|
296
|
+
missing_fields: list[str] = Field(default_factory=list)
|
|
297
|
+
extra_fields: list[str] = Field(default_factory=list)
|
|
298
|
+
note: str | None = None
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class AgentDryRunResponse(BaseModel):
|
|
302
|
+
"""Response from ``POST /agents/dry-run``."""
|
|
303
|
+
|
|
304
|
+
model_config = ConfigDict(extra="forbid")
|
|
305
|
+
|
|
306
|
+
rendered_xml: str
|
|
307
|
+
prompt_warnings: list[str] = Field(default_factory=list)
|
|
308
|
+
prompt_errors: list[str] = Field(default_factory=list)
|
|
309
|
+
runtime_result: dict[str, Any]
|
|
310
|
+
output_schema_validation: OutputSchemaValidation
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class PaginatedAgents(BaseModel):
|
|
314
|
+
items: list[Any] # dap_types.Agent — Any to avoid circular import in this layer
|
|
315
|
+
total: int
|
|
316
|
+
offset: int
|
|
317
|
+
limit: int
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class PaginatedPipelines(BaseModel):
|
|
321
|
+
items: list[Any]
|
|
322
|
+
total: int
|
|
323
|
+
offset: int
|
|
324
|
+
limit: int
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class PaginatedRuns(BaseModel):
|
|
328
|
+
items: list[Any]
|
|
329
|
+
total: int
|
|
330
|
+
offset: int
|
|
331
|
+
limit: int
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""GET /settings — snapshot of operator-facing engine configuration.
|
|
2
|
+
|
|
3
|
+
Read-only by design (per #55): the dashboard reads this to populate the
|
|
4
|
+
``/settings`` page; actual configuration lives in env vars and the
|
|
5
|
+
launch flags. One endpoint avoids the dashboard fanning out to N
|
|
6
|
+
healthcheck calls in serial.
|
|
7
|
+
|
|
8
|
+
Returns three sections:
|
|
9
|
+
|
|
10
|
+
- ``runtimes`` — id / display_name / kind / availability / version /
|
|
11
|
+
missing-env list for every registered runtime adapter.
|
|
12
|
+
- ``providers`` — per-api-call provider: id, display name, default
|
|
13
|
+
env var name, whether that env var is currently set.
|
|
14
|
+
- ``engine`` — version, configured DB paths, recursion limit.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import logging
|
|
21
|
+
import os
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from dap_runtimes import RuntimeRegistry
|
|
26
|
+
from dap_runtimes.adapters._providers import PROVIDER_REGISTRY
|
|
27
|
+
from dap_types import HealthStatus, RuntimeAdapter
|
|
28
|
+
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
|
29
|
+
from sqlalchemy.engine import make_url
|
|
30
|
+
from sqlalchemy.exc import ArgumentError
|
|
31
|
+
|
|
32
|
+
from dap_engine.api.deps import get_registry
|
|
33
|
+
from dap_engine.auth.users import current_active_user
|
|
34
|
+
from dap_engine.execution.runner import DEFAULT_RECURSION_LIMIT
|
|
35
|
+
from dap_engine.persistence.db import detect_dialect
|
|
36
|
+
from dap_engine.persistence.models import UserORM
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger("dap.engine.api.settings")
|
|
39
|
+
|
|
40
|
+
router = APIRouter(tags=["settings"])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@router.get("/settings")
|
|
44
|
+
async def get_settings(
|
|
45
|
+
request: Request,
|
|
46
|
+
registry: RuntimeRegistry = Depends(get_registry),
|
|
47
|
+
) -> dict[str, Any]:
|
|
48
|
+
"""Assemble the operator settings view (runtimes + providers + engine)."""
|
|
49
|
+
runtimes = await _collect_runtimes(registry)
|
|
50
|
+
providers = _collect_providers()
|
|
51
|
+
engine = _collect_engine_info(request)
|
|
52
|
+
return {
|
|
53
|
+
"runtimes": runtimes,
|
|
54
|
+
"providers": providers,
|
|
55
|
+
"engine": engine,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
async def _collect_runtimes(registry: RuntimeRegistry) -> list[dict[str, Any]]:
|
|
60
|
+
"""One row per registered runtime adapter.
|
|
61
|
+
|
|
62
|
+
Healthchecks fan out concurrently — some adapters shell out to a CLI
|
|
63
|
+
for ``--version`` and have multi-second timeouts; serialising them
|
|
64
|
+
would make ``/settings`` add up to those latencies. A single adapter
|
|
65
|
+
that throws is reported as unavailable rather than failing the whole
|
|
66
|
+
endpoint, so the operator still sees the rest of the table.
|
|
67
|
+
"""
|
|
68
|
+
adapters = registry.list()
|
|
69
|
+
healths = await asyncio.gather(
|
|
70
|
+
*(_safe_healthcheck(adapter) for adapter in adapters),
|
|
71
|
+
return_exceptions=False,
|
|
72
|
+
)
|
|
73
|
+
rows: list[dict[str, Any]] = []
|
|
74
|
+
for adapter, health in zip(adapters, healths, strict=True):
|
|
75
|
+
rows.append(
|
|
76
|
+
{
|
|
77
|
+
"id": adapter.id,
|
|
78
|
+
"display_name": adapter.display_name,
|
|
79
|
+
"kind": adapter.kind,
|
|
80
|
+
"available": health.available,
|
|
81
|
+
"version": health.version,
|
|
82
|
+
"missing": health.missing,
|
|
83
|
+
}
|
|
84
|
+
)
|
|
85
|
+
rows.sort(key=lambda row: row["id"])
|
|
86
|
+
return rows
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
async def _safe_healthcheck(adapter: RuntimeAdapter) -> HealthStatus:
|
|
90
|
+
"""Call ``adapter.healthcheck()`` but never propagate exceptions.
|
|
91
|
+
|
|
92
|
+
A buggy adapter shouldn't take down the entire settings page.
|
|
93
|
+
"""
|
|
94
|
+
try:
|
|
95
|
+
return await adapter.healthcheck()
|
|
96
|
+
except Exception as exc:
|
|
97
|
+
logger.exception("healthcheck failed for runtime %s", adapter.id)
|
|
98
|
+
return HealthStatus(
|
|
99
|
+
available=False,
|
|
100
|
+
missing=[f"healthcheck raised: {type(exc).__name__}: {exc}"],
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _collect_providers() -> list[dict[str, Any]]:
|
|
105
|
+
"""One row per api-call provider; uses the registry metadata only.
|
|
106
|
+
|
|
107
|
+
Reading metadata avoids importing the SDK for every provider on the
|
|
108
|
+
settings request — same reason ``ApiCallAdapter.healthcheck`` reads
|
|
109
|
+
the registry instead of dispatching to each provider module.
|
|
110
|
+
"""
|
|
111
|
+
rows: list[dict[str, Any]] = []
|
|
112
|
+
for provider_id, info in PROVIDER_REGISTRY.items():
|
|
113
|
+
configured: bool
|
|
114
|
+
if info.default_env_var is None:
|
|
115
|
+
# openai-compat: per-agent env var, not knowable here.
|
|
116
|
+
configured = False
|
|
117
|
+
else:
|
|
118
|
+
configured = bool(os.environ.get(info.default_env_var))
|
|
119
|
+
rows.append(
|
|
120
|
+
{
|
|
121
|
+
"id": provider_id,
|
|
122
|
+
"display_name": info.display_name,
|
|
123
|
+
"default_env_var": info.default_env_var,
|
|
124
|
+
"configured": configured,
|
|
125
|
+
}
|
|
126
|
+
)
|
|
127
|
+
rows.sort(key=lambda row: row["id"])
|
|
128
|
+
return rows
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _collect_engine_info(request: Request) -> dict[str, Any]:
|
|
132
|
+
"""Engine-level details — paths, version, recursion cap.
|
|
133
|
+
|
|
134
|
+
``version`` is the value passed to ``FastAPI(version=...)`` in
|
|
135
|
+
``app.py`` so we share a single source of truth with /health.
|
|
136
|
+
"""
|
|
137
|
+
config = request.app.state.config
|
|
138
|
+
db_path = Path(config.db_path).resolve()
|
|
139
|
+
checkpoint_db_path = db_path.with_suffix(".checkpoints.db")
|
|
140
|
+
return {
|
|
141
|
+
"version": request.app.version,
|
|
142
|
+
"db_path": str(db_path),
|
|
143
|
+
"checkpoint_db_path": str(checkpoint_db_path),
|
|
144
|
+
"recursion_limit": DEFAULT_RECURSION_LIMIT,
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ---------------------------------------------------------------------------
|
|
149
|
+
# Admin-only instance settings view (#301, sub-C5, closes #331)
|
|
150
|
+
# ---------------------------------------------------------------------------
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@router.get("/settings/admin")
|
|
154
|
+
async def get_admin_settings(
|
|
155
|
+
request: Request,
|
|
156
|
+
user: UserORM = Depends(current_active_user),
|
|
157
|
+
) -> dict[str, Any]:
|
|
158
|
+
"""Read-only snapshot of instance-wide config for the admin panel.
|
|
159
|
+
|
|
160
|
+
Distinct from ``GET /settings`` (runtime / provider health) — this
|
|
161
|
+
surface is for security-sensitive operator knobs the admin needs
|
|
162
|
+
to verify at a glance: JWT lifetime, OAuth wiring, CORS allow-list,
|
|
163
|
+
reset-token logging flag, storage backend. No mutations; instance
|
|
164
|
+
config is env-var driven and requires a restart to change.
|
|
165
|
+
|
|
166
|
+
Anti-enumeration: non-admins get ``404`` (mirrors the rest of the
|
|
167
|
+
admin surface — sub-A4b2 series). Anonymous gets ``401`` from
|
|
168
|
+
``current_active_user``.
|
|
169
|
+
|
|
170
|
+
**Never exposes secrets.** OAuth client_secrets and the JWT
|
|
171
|
+
secret are presence-only — the response says ``True`` /
|
|
172
|
+
``False`` for whether they're configured, never the value.
|
|
173
|
+
Mirrors the rule the ``/audit/events`` route applies to its
|
|
174
|
+
own ``event_data`` payloads.
|
|
175
|
+
"""
|
|
176
|
+
if not user.is_superuser:
|
|
177
|
+
raise HTTPException(
|
|
178
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
179
|
+
detail="Not Found",
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
config = request.app.state.config
|
|
183
|
+
|
|
184
|
+
db_backend, db_location = _describe_database(config)
|
|
185
|
+
cors = _describe_cors(config)
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
"auth": {
|
|
189
|
+
"jwt_secret_configured": bool(config.auth_jwt_secret),
|
|
190
|
+
"access_ttl_seconds": config.auth_access_ttl_seconds,
|
|
191
|
+
# Security-relevant: reset-token logging is dev-only.
|
|
192
|
+
# The dashboard surfaces a warning when this is on.
|
|
193
|
+
"log_reset_tokens": config.auth_log_reset_tokens,
|
|
194
|
+
},
|
|
195
|
+
"oauth": {
|
|
196
|
+
"github": {
|
|
197
|
+
"configured": bool(
|
|
198
|
+
config.oauth_github_client_id and config.oauth_github_client_secret
|
|
199
|
+
),
|
|
200
|
+
"client_id_configured": bool(config.oauth_github_client_id),
|
|
201
|
+
"client_secret_configured": bool(config.oauth_github_client_secret),
|
|
202
|
+
},
|
|
203
|
+
"google": {
|
|
204
|
+
"configured": bool(
|
|
205
|
+
config.oauth_google_client_id and config.oauth_google_client_secret
|
|
206
|
+
),
|
|
207
|
+
"client_id_configured": bool(config.oauth_google_client_id),
|
|
208
|
+
"client_secret_configured": bool(config.oauth_google_client_secret),
|
|
209
|
+
},
|
|
210
|
+
"redirect_url": config.auth_oauth_redirect_url,
|
|
211
|
+
},
|
|
212
|
+
"cors": cors,
|
|
213
|
+
"storage": {
|
|
214
|
+
"backend": db_backend,
|
|
215
|
+
"location": db_location,
|
|
216
|
+
},
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _describe_cors(config: Any) -> dict[str, Any]:
|
|
221
|
+
"""Return the *effective* CORS configuration.
|
|
222
|
+
|
|
223
|
+
The engine treats ``cors_origins=None`` as "fall back to
|
|
224
|
+
``DEFAULT_CORS_ORIGINS`` (the local-dev allow-list)", **not**
|
|
225
|
+
"permissive / all origins". Earlier sub-C5 versions exposed the
|
|
226
|
+
raw config value, which let the dashboard mis-report unset config
|
|
227
|
+
as "all origins" (Copilot review on PR #332).
|
|
228
|
+
|
|
229
|
+
Now we resolve to what ``CORSMiddleware`` will actually use, plus
|
|
230
|
+
a ``using_default`` flag the dashboard renders as a chip so an
|
|
231
|
+
operator knows the value came from defaults rather than an
|
|
232
|
+
explicit env var.
|
|
233
|
+
"""
|
|
234
|
+
# Import locally to avoid a circular import with ``app.py``.
|
|
235
|
+
from dap_engine.app import DEFAULT_CORS_ORIGINS # noqa: PLC0415
|
|
236
|
+
|
|
237
|
+
if config.cors_origins is None:
|
|
238
|
+
return {
|
|
239
|
+
"origins": list(DEFAULT_CORS_ORIGINS),
|
|
240
|
+
"using_default": True,
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
"origins": list(config.cors_origins),
|
|
244
|
+
"using_default": False,
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _describe_database(config: Any) -> tuple[str, str]:
|
|
249
|
+
"""Return ``(backend, location)`` with credentials redacted.
|
|
250
|
+
|
|
251
|
+
Uses ``persistence.db.detect_dialect`` for backend detection —
|
|
252
|
+
the same helper ``create_app`` uses — so the answer matches
|
|
253
|
+
what's actually running. Naively treating any non-None
|
|
254
|
+
``database_url`` as PostgreSQL (Copilot review on PR #332)
|
|
255
|
+
would mis-label SQLite URLs and break the dashboard display.
|
|
256
|
+
"""
|
|
257
|
+
url = getattr(config, "database_url", None)
|
|
258
|
+
if url is None:
|
|
259
|
+
# No DATABASE_URL set → engine uses the SQLite file at db_path.
|
|
260
|
+
return "sqlite", str(Path(config.db_path).resolve())
|
|
261
|
+
backend = detect_dialect(url)
|
|
262
|
+
if backend == "sqlite":
|
|
263
|
+
# SQLite-via-URL is rare but supported; show the path the
|
|
264
|
+
# way an operator would type it.
|
|
265
|
+
return "sqlite", url
|
|
266
|
+
return "postgresql", _redact_database_url(url)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _redact_database_url(url: str) -> str:
|
|
270
|
+
"""Mask the password in a database URL.
|
|
271
|
+
|
|
272
|
+
Uses SQLAlchemy's ``make_url`` + ``render_as_string(hide_password=True)``
|
|
273
|
+
so URL-encoded passwords, IPv6 hosts, query params, and other
|
|
274
|
+
quirks of real-world database URLs round-trip safely (Copilot
|
|
275
|
+
review on PR #332). A previous string-splitting version would
|
|
276
|
+
leak credentials on URLs whose password contained ``@`` or other
|
|
277
|
+
edge characters.
|
|
278
|
+
|
|
279
|
+
Falls back to the input string if SQLAlchemy can't parse the URL
|
|
280
|
+
— better to show a raw value than to silently strip something
|
|
281
|
+
important. The endpoint's secret-redaction test asserts the
|
|
282
|
+
happy path, and the engine refuses to start with an unparseable
|
|
283
|
+
URL anyway.
|
|
284
|
+
"""
|
|
285
|
+
try:
|
|
286
|
+
return make_url(url).render_as_string(hide_password=True)
|
|
287
|
+
except ArgumentError:
|
|
288
|
+
return url
|