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.
Files changed (48) hide show
  1. dap_engine/__init__.py +3 -0
  2. dap_engine/__main__.py +80 -0
  3. dap_engine/api/__init__.py +0 -0
  4. dap_engine/api/agents.py +546 -0
  5. dap_engine/api/deps.py +60 -0
  6. dap_engine/api/health.py +20 -0
  7. dap_engine/api/pipelines.py +428 -0
  8. dap_engine/api/projects.py +191 -0
  9. dap_engine/api/runs.py +694 -0
  10. dap_engine/api/runtimes.py +29 -0
  11. dap_engine/api/schemas.py +331 -0
  12. dap_engine/api/settings.py +288 -0
  13. dap_engine/app.py +438 -0
  14. dap_engine/auth/__init__.py +23 -0
  15. dap_engine/auth/admin_users_routes.py +134 -0
  16. dap_engine/auth/api_token_routes.py +345 -0
  17. dap_engine/auth/api_tokens.py +147 -0
  18. dap_engine/auth/audit.py +91 -0
  19. dap_engine/auth/audit_routes.py +125 -0
  20. dap_engine/auth/db.py +135 -0
  21. dap_engine/auth/oauth.py +41 -0
  22. dap_engine/auth/policies.py +64 -0
  23. dap_engine/auth/schemas.py +37 -0
  24. dap_engine/auth/users.py +400 -0
  25. dap_engine/contracts.py +205 -0
  26. dap_engine/execution/__init__.py +30 -0
  27. dap_engine/execution/conditions.py +87 -0
  28. dap_engine/execution/node_executor.py +363 -0
  29. dap_engine/execution/output_parser.py +162 -0
  30. dap_engine/execution/run_orchestrator.py +213 -0
  31. dap_engine/execution/run_registry.py +158 -0
  32. dap_engine/execution/runner.py +422 -0
  33. dap_engine/execution/validator.py +580 -0
  34. dap_engine/persistence/__init__.py +0 -0
  35. dap_engine/persistence/_common.py +24 -0
  36. dap_engine/persistence/agents.py +410 -0
  37. dap_engine/persistence/db.py +179 -0
  38. dap_engine/persistence/migrations.py +739 -0
  39. dap_engine/persistence/models.py +569 -0
  40. dap_engine/persistence/pipelines.py +328 -0
  41. dap_engine/persistence/projects.py +256 -0
  42. dap_engine/persistence/repository.py +101 -0
  43. dap_engine/persistence/runs.py +482 -0
  44. dap_engine/py.typed +0 -0
  45. dap_engine-0.3.0.dist-info/METADATA +49 -0
  46. dap_engine-0.3.0.dist-info/RECORD +48 -0
  47. dap_engine-0.3.0.dist-info/WHEEL +4 -0
  48. dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
dap_engine/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from dap_engine.app import create_app
2
+
3
+ __all__ = ["create_app"]
dap_engine/__main__.py ADDED
@@ -0,0 +1,80 @@
1
+ """Standalone entrypoint: `uv run dap-engine` lub `python -m dap_engine`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+
8
+ import uvicorn
9
+
10
+ from dap_engine.app import EngineConfig, create_app, parse_cors_origins
11
+
12
+
13
+ def main() -> None:
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format="%(asctime)s %(levelname)-7s %(name)s | %(message)s",
17
+ datefmt="%H:%M:%S",
18
+ )
19
+
20
+ config = EngineConfig(
21
+ db_path=os.environ.get("DAP_DB_PATH", "./.dap/state.db"),
22
+ # DAP_DATABASE_URL overrides db_path when set.
23
+ # postgresql+asyncpg://user:pass@host:port/db → PostgreSQL backend
24
+ # Leave unset to keep SQLite (default for local dev).
25
+ database_url=os.environ.get("DAP_DATABASE_URL"),
26
+ host=os.environ.get("DAP_ENGINE_HOST", "127.0.0.1"),
27
+ port=int(os.environ.get("DAP_ENGINE_PORT", "7333")),
28
+ dry_run_budget_usd=float(os.environ.get("DAP_DRY_RUN_BUDGET_USD", "0.50")),
29
+ # PG checkpointer pool sizing — only used when DAP_DATABASE_URL is set.
30
+ pg_pool_min_size=int(os.environ.get("DAP_PG_POOL_MIN_SIZE", "4")),
31
+ pg_pool_max_size=int(os.environ.get("DAP_PG_POOL_MAX_SIZE", "10")),
32
+ # Comma-separated CORS allow-list — None falls back to the local-dev
33
+ # default in EngineConfig (#259).
34
+ cors_origins=parse_cors_origins(os.environ.get("DAP_CORS_ORIGINS")),
35
+ # Auth (#299). When unset, the lifespan generates a per-process
36
+ # random — fine for a single-instance local dev, but multi-worker
37
+ # / multi-replica deployments MUST set DAP_AUTH_JWT_SECRET so all
38
+ # workers validate tokens against the same key.
39
+ auth_jwt_secret=os.environ.get("DAP_AUTH_JWT_SECRET"),
40
+ auth_access_ttl_seconds=int(os.environ.get("DAP_AUTH_ACCESS_TTL_SECONDS", "900")),
41
+ # Reset-token logging — opt-in dev convenience documented on
42
+ # ``EngineConfig.auth_log_reset_tokens``. Off unless the env
43
+ # var is set to a truthy string. The /admin/settings page
44
+ # surfaces the resulting value with an amber warning when it's
45
+ # on.
46
+ auth_log_reset_tokens=os.environ.get("DAP_AUTH_LOG_RESET_TOKENS", "").strip().lower()
47
+ in ("1", "true", "yes", "on"),
48
+ # When set, OAuth callbacks redirect the browser here with the
49
+ # JWT in ``?token=`` instead of returning JSON (#300, sub-B5).
50
+ # The dashboard's ``/api/auth/oauth/callback`` reads it and
51
+ # promotes it to an httpOnly cookie.
52
+ #
53
+ # Normalise blank / whitespace-only values to ``None`` — an
54
+ # operator who exports the var but leaves it empty would
55
+ # otherwise hand fastapi-users an invalid empty redirect_url
56
+ # (Copilot review on PR #326).
57
+ auth_oauth_redirect_url=(os.environ.get("DAP_AUTH_OAUTH_REDIRECT_URL", "").strip() or None),
58
+ # OAuth (#299, sub-A2). Each provider activates only when both
59
+ # client_id and client_secret are set; missing or partially-set
60
+ # credentials are ignored without a startup error so a self-host
61
+ # install can run with email+password only.
62
+ oauth_github_client_id=os.environ.get("DAP_OAUTH_GITHUB_CLIENT_ID"),
63
+ oauth_github_client_secret=os.environ.get("DAP_OAUTH_GITHUB_CLIENT_SECRET"),
64
+ oauth_google_client_id=os.environ.get("DAP_OAUTH_GOOGLE_CLIENT_ID"),
65
+ oauth_google_client_secret=os.environ.get("DAP_OAUTH_GOOGLE_CLIENT_SECRET"),
66
+ )
67
+
68
+ app = create_app(config)
69
+
70
+ uvicorn.run(
71
+ app,
72
+ host=config.host,
73
+ port=config.port,
74
+ log_level="info",
75
+ access_log=False,
76
+ )
77
+
78
+
79
+ if __name__ == "__main__":
80
+ main()
File without changes
@@ -0,0 +1,546 @@
1
+ """REST CRUD for agents + prompt render preview + import/export (#94) + dry-run (#103)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ import uuid
7
+ from typing import TYPE_CHECKING, Any, NamedTuple
8
+
9
+ from dap_prompt_dsl import PromptBuildError, build_prompt
10
+ from dap_runtimes import RuntimeRegistry
11
+ from dap_types import Agent, RuntimeTask
12
+ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
13
+ from pydantic import ValidationError
14
+ from sqlalchemy.orm import Session
15
+
16
+ from dap_engine.api.deps import get_engine_config, get_registry, get_session
17
+ from dap_engine.auth.users import current_active_user
18
+ from dap_engine.persistence.models import UserORM
19
+
20
+ if TYPE_CHECKING:
21
+ # Runtime cycle: dap_engine.app imports this router module, so we
22
+ # can't import EngineConfig at runtime. The type is needed only
23
+ # for the dry_run endpoint signature; behaviour is unchanged.
24
+ from dap_engine.app import EngineConfig
25
+ from dap_engine.api.schemas import (
26
+ AGENT_EXPORT_SCHEMA_VERSION,
27
+ AgentDryRunRequest,
28
+ AgentDryRunResponse,
29
+ AgentExport,
30
+ AgentExportPayload,
31
+ AgentImportRequest,
32
+ OutputSchemaValidation,
33
+ RenderPreviewRequest,
34
+ RenderPreviewResponse,
35
+ )
36
+ from dap_engine.contracts import AgentCreate, AgentUpdate
37
+ from dap_engine.persistence import repository as repo
38
+
39
+ router = APIRouter(prefix="/agents", tags=["agents"])
40
+
41
+
42
+ _SECRET_KEY_PATTERNS = (
43
+ "api_key",
44
+ "apikey",
45
+ "token",
46
+ "secret",
47
+ "password",
48
+ "credential",
49
+ )
50
+ _REDACTED_PLACEHOLDER = "<redacted>"
51
+
52
+
53
+ def _scrub_secret_like_keys(value: dict[str, Any]) -> dict[str, Any]:
54
+ """Best-effort redaction of keys whose name suggests a credential.
55
+
56
+ Secrets are *supposed* to live in environment variables — adapters
57
+ read API keys from ``os.environ``, not from ``runtime_config``. But
58
+ nothing in the schema enforces that, so old or hand-edited agents
59
+ may have a literal key sitting in ``runtime_config``. Exports are
60
+ portable artifacts (checked into git, shared between machines), so
61
+ we redact known-suspect keys before serialising.
62
+ """
63
+ redacted: dict[str, Any] = {}
64
+ for key, val in value.items():
65
+ if any(pattern in key.lower() for pattern in _SECRET_KEY_PATTERNS):
66
+ redacted[key] = _REDACTED_PLACEHOLDER
67
+ elif isinstance(val, dict):
68
+ redacted[key] = _scrub_secret_like_keys(val)
69
+ else:
70
+ redacted[key] = val
71
+ return redacted
72
+
73
+
74
+ @router.get("")
75
+ def list_agents(
76
+ session: Session = Depends(get_session),
77
+ user: UserORM = Depends(current_active_user),
78
+ role: str | None = Query(default=None),
79
+ archived: bool = Query(default=False),
80
+ offset: int = Query(default=0, ge=0),
81
+ limit: int = Query(default=50, ge=1, le=500),
82
+ ) -> dict[str, Any]:
83
+ items, total = repo.list_agents(
84
+ session,
85
+ actor_id=user.id,
86
+ is_admin=user.is_superuser,
87
+ role=role,
88
+ archived=archived,
89
+ offset=offset,
90
+ limit=limit,
91
+ )
92
+ usage = repo.count_pipelines_using_agents(session, [a.id for a in items])
93
+ enriched = [a.model_copy(update={"used_in_pipelines": usage.get(a.id, 0)}) for a in items]
94
+ return {
95
+ "items": [a.model_dump(mode="json") for a in enriched],
96
+ "total": total,
97
+ "offset": offset,
98
+ "limit": limit,
99
+ }
100
+
101
+
102
+ @router.post("", status_code=status.HTTP_201_CREATED, response_model=Agent)
103
+ def create_agent(
104
+ payload: AgentCreate,
105
+ session: Session = Depends(get_session),
106
+ user: UserORM = Depends(current_active_user),
107
+ ) -> Agent:
108
+ return repo.create_agent(session, payload, user_id=user.id)
109
+
110
+
111
+ @router.post(
112
+ "/import",
113
+ status_code=status.HTTP_201_CREATED,
114
+ response_model=Agent,
115
+ )
116
+ def import_agent(
117
+ payload: AgentImportRequest,
118
+ session: Session = Depends(get_session),
119
+ registry: RuntimeRegistry = Depends(get_registry),
120
+ user: UserORM = Depends(current_active_user),
121
+ ) -> Agent:
122
+ """Create a new agent (v1) from an exported JSON payload (#94).
123
+
124
+ ``schema_version`` and field-list validators run during request
125
+ parsing (Pydantic). The runtime_id check happens here because it
126
+ needs the runtime registry. Everything else delegates to the
127
+ standard create flow — same validation, same versioning, same
128
+ response shape.
129
+ """
130
+ if not registry.has(payload.agent.runtime_id):
131
+ raise HTTPException(
132
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
133
+ detail=(
134
+ f"Unknown runtime_id '{payload.agent.runtime_id}' — "
135
+ "this engine has no adapter registered with that id."
136
+ ),
137
+ )
138
+
139
+ # Round-trip through model_dump → model_validate so that any future
140
+ # field added to AgentExportPayload/AgentCreate flows automatically,
141
+ # rather than relying on this function to be edited in lockstep.
142
+ try:
143
+ create_payload = AgentCreate.model_validate(payload.agent.model_dump())
144
+ except ValidationError as exc:
145
+ raise HTTPException(
146
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
147
+ detail=exc.errors(),
148
+ ) from exc
149
+ return repo.create_agent(session, create_payload, user_id=user.id)
150
+
151
+
152
+ @router.get("/{agent_id}", response_model=Agent)
153
+ def get_agent(
154
+ agent_id: str,
155
+ session: Session = Depends(get_session),
156
+ user: UserORM = Depends(current_active_user),
157
+ ) -> Agent:
158
+ try:
159
+ return repo.get_agent(session, agent_id, actor_id=user.id, is_admin=user.is_superuser)
160
+ except repo.NotFoundError as exc:
161
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
162
+
163
+
164
+ @router.put("/{agent_id}", response_model=Agent)
165
+ def update_agent(
166
+ agent_id: str,
167
+ payload: AgentUpdate,
168
+ session: Session = Depends(get_session),
169
+ user: UserORM = Depends(current_active_user),
170
+ ) -> Agent:
171
+ try:
172
+ return repo.update_agent(
173
+ session,
174
+ agent_id,
175
+ payload,
176
+ actor_id=user.id,
177
+ is_admin=user.is_superuser,
178
+ )
179
+ except repo.NotFoundError as exc:
180
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
181
+
182
+
183
+ @router.delete("/{agent_id}", status_code=status.HTTP_204_NO_CONTENT)
184
+ def archive_agent(
185
+ agent_id: str,
186
+ session: Session = Depends(get_session),
187
+ user: UserORM = Depends(current_active_user),
188
+ ) -> Response:
189
+ # Ownership gate first — otherwise the 409-precheck below leaks info
190
+ # about foreign agents (id existence + names of blocking pipelines).
191
+ # The cheapest gate is a get_agent() call: it returns the row only if
192
+ # the caller owns it (or is admin) and raises NotFoundError otherwise,
193
+ # which we surface as 404 — same response a non-existent id gets.
194
+ try:
195
+ repo.get_agent(session, agent_id, actor_id=user.id, is_admin=user.is_superuser)
196
+ except repo.NotFoundError as exc:
197
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
198
+
199
+ blocking = repo.pipelines_using_agent(session, agent_id)
200
+ if blocking:
201
+ raise HTTPException(
202
+ status_code=status.HTTP_409_CONFLICT,
203
+ detail={
204
+ "message": (
205
+ f"Agent is referenced by {len(blocking)} active pipeline"
206
+ f"{'s' if len(blocking) != 1 else ''}. Remove or replace the "
207
+ "node(s) before archiving."
208
+ ),
209
+ "blocking_pipelines": [{"id": pid, "name": pname} for pid, pname in blocking],
210
+ },
211
+ )
212
+ try:
213
+ repo.archive_agent(session, agent_id, actor_id=user.id, is_admin=user.is_superuser)
214
+ except repo.NotFoundError as exc:
215
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
216
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
217
+
218
+
219
+ @router.get("/{agent_id}/versions", response_model=list[Agent])
220
+ def list_agent_versions(
221
+ agent_id: str,
222
+ session: Session = Depends(get_session),
223
+ user: UserORM = Depends(current_active_user),
224
+ ) -> list[Agent]:
225
+ try:
226
+ return repo.list_agent_versions(
227
+ session, agent_id, actor_id=user.id, is_admin=user.is_superuser
228
+ )
229
+ except repo.NotFoundError as exc:
230
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
231
+
232
+
233
+ @router.get("/{agent_id}/versions/{version}", response_model=Agent)
234
+ def get_agent_version(
235
+ agent_id: str,
236
+ version: int,
237
+ session: Session = Depends(get_session),
238
+ user: UserORM = Depends(current_active_user),
239
+ ) -> Agent:
240
+ try:
241
+ return repo.get_agent_version(
242
+ session, agent_id, version, actor_id=user.id, is_admin=user.is_superuser
243
+ )
244
+ except repo.NotFoundError as exc:
245
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
246
+
247
+
248
+ @router.get("/{agent_id}/export", response_model=AgentExport)
249
+ def export_agent(
250
+ agent_id: str,
251
+ session: Session = Depends(get_session),
252
+ user: UserORM = Depends(current_active_user),
253
+ ) -> AgentExport:
254
+ """Return a portable JSON shape of the agent (#94).
255
+
256
+ Strips per-installation fields (id, version, timestamps,
257
+ archived_at) so the result can move between DAP installations
258
+ or be checked into git. Secrets stay in env — adapters read API
259
+ keys from process env, not from the exported JSON. As a
260
+ belt-and-suspenders defence, ``runtime_config`` is also walked
261
+ for keys that look like credentials (``api_key``, ``token``,
262
+ ``secret``, ``password``, ``credential``) and their values are
263
+ replaced with ``<redacted>`` before serialisation.
264
+ """
265
+ try:
266
+ agent = repo.get_agent(session, agent_id, actor_id=user.id, is_admin=user.is_superuser)
267
+ except repo.NotFoundError as exc:
268
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
269
+
270
+ return AgentExport(
271
+ schema_version=AGENT_EXPORT_SCHEMA_VERSION,
272
+ agent=build_agent_export_payload(agent),
273
+ )
274
+
275
+
276
+ def build_agent_export_payload(agent: Agent) -> AgentExportPayload:
277
+ """Project an :class:`Agent` ORM-backed model onto its portable shape.
278
+
279
+ Strips per-installation fields (id, version, timestamps,
280
+ archived_at) and scrubs ``runtime_config`` for credential-shaped
281
+ keys (``api_key`` / ``token`` / ``secret`` / ``password`` /
282
+ ``credential``). Used both by the standalone agent export
283
+ endpoint and the pipeline bundle export (#126).
284
+
285
+ Raises ``HTTPException(500)`` when the stored shape can't be
286
+ re-validated against ``AgentExportPayload`` — a real defence
287
+ against a future migration introducing data we can't export,
288
+ not a routine error path.
289
+ """
290
+ try:
291
+ return AgentExportPayload(
292
+ name=agent.name,
293
+ role=agent.role,
294
+ runtime_id=agent.runtime_id,
295
+ runtime_config=_scrub_secret_like_keys(agent.runtime_config),
296
+ prompt_template=agent.prompt_template,
297
+ input_schema=list(agent.input_schema),
298
+ output_schema=list(agent.output_schema),
299
+ constraints=list(agent.constraints),
300
+ budget_limit_usd=agent.budget_limit_usd,
301
+ timeout_ms=agent.timeout_ms,
302
+ )
303
+ except ValidationError as exc:
304
+ raise HTTPException(
305
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
306
+ detail=f"Stored agent could not be re-validated for export: {exc.errors()}",
307
+ ) from exc
308
+
309
+
310
+ @router.post("/{agent_id}/render-preview", response_model=RenderPreviewResponse)
311
+ def render_preview(
312
+ agent_id: str,
313
+ payload: RenderPreviewRequest,
314
+ version: int | None = Query(default=None, description="Agent version (default: current)"),
315
+ session: Session = Depends(get_session),
316
+ user: UserORM = Depends(current_active_user),
317
+ ) -> RenderPreviewResponse:
318
+ """Render the agent's prompt_template with the supplied context.
319
+
320
+ Returns the XML output even when invalid so callers can see the diagnostics.
321
+ Returns 422 only for hard rendering errors (Jinja syntax / undefined vars).
322
+ """
323
+ try:
324
+ agent = (
325
+ repo.get_agent_version(
326
+ session, agent_id, version, actor_id=user.id, is_admin=user.is_superuser
327
+ )
328
+ if version is not None
329
+ else repo.get_agent(session, agent_id, actor_id=user.id, is_admin=user.is_superuser)
330
+ )
331
+ except repo.NotFoundError as exc:
332
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
333
+
334
+ try:
335
+ result = build_prompt(
336
+ agent.prompt_template,
337
+ payload.context,
338
+ input_schema=agent.input_schema or None,
339
+ agent_metadata={"role": agent.role},
340
+ )
341
+ except PromptBuildError as exc:
342
+ raise HTTPException(
343
+ status_code=422, # Unprocessable Content
344
+ detail=str(exc),
345
+ ) from exc
346
+
347
+ return RenderPreviewResponse(
348
+ rendered_xml=result.xml,
349
+ valid=result.valid,
350
+ warnings=result.warnings,
351
+ errors=result.errors,
352
+ )
353
+
354
+
355
+ # ---------------------------------------------------------------------------
356
+ # Dry-run (#103) — execute the agent end-to-end against sample context
357
+ # without persisting anything. The Test panel on the agent create/edit
358
+ # pages is the primary caller.
359
+ # ---------------------------------------------------------------------------
360
+
361
+
362
+ class _DryRunSource(NamedTuple):
363
+ """Resolved fields needed to execute one dry-run.
364
+
365
+ Sourced from either a saved agent (``agent_id`` path) or an inline
366
+ draft (``draft`` path). Bundled into a NamedTuple so adding a new
367
+ field doesn't keep widening a positional return tuple at the call
368
+ site.
369
+ """
370
+
371
+ runtime_id: str
372
+ role: str
373
+ prompt_template: str
374
+ input_schema: list[str]
375
+ output_schema: list[str]
376
+ runtime_config: dict[str, Any]
377
+ timeout_ms: int
378
+ agent_budget_usd: float | None
379
+
380
+
381
+ def _resolve_dryrun_source(
382
+ payload: AgentDryRunRequest,
383
+ session: Session,
384
+ *,
385
+ actor_id: uuid.UUID,
386
+ is_admin: bool,
387
+ ) -> _DryRunSource:
388
+ """Resolve the agent fields needed for a dry-run.
389
+
390
+ Fetches a saved agent or unwraps the inline draft; the schema
391
+ validator on ``AgentDryRunRequest`` guarantees exactly one path
392
+ is taken.
393
+ """
394
+ if payload.draft is not None:
395
+ d = payload.draft
396
+ return _DryRunSource(
397
+ runtime_id=d.runtime_id,
398
+ role=d.role,
399
+ prompt_template=d.prompt_template,
400
+ input_schema=list(d.input_schema),
401
+ output_schema=list(d.output_schema),
402
+ runtime_config=dict(d.runtime_config),
403
+ timeout_ms=d.timeout_ms,
404
+ agent_budget_usd=d.budget_limit_usd,
405
+ )
406
+ assert payload.agent_id is not None
407
+ try:
408
+ agent = (
409
+ repo.get_agent_version(
410
+ session,
411
+ payload.agent_id,
412
+ payload.agent_version,
413
+ actor_id=actor_id,
414
+ is_admin=is_admin,
415
+ )
416
+ if payload.agent_version is not None
417
+ else repo.get_agent(session, payload.agent_id, actor_id=actor_id, is_admin=is_admin)
418
+ )
419
+ except repo.NotFoundError as exc:
420
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
421
+ return _DryRunSource(
422
+ runtime_id=agent.runtime_id,
423
+ role=agent.role,
424
+ prompt_template=agent.prompt_template,
425
+ input_schema=list(agent.input_schema),
426
+ output_schema=list(agent.output_schema),
427
+ runtime_config=dict(agent.runtime_config),
428
+ timeout_ms=agent.timeout_ms,
429
+ agent_budget_usd=agent.budget_limit_usd,
430
+ )
431
+
432
+
433
+ def _validate_output_schema(
434
+ structured: dict[str, Any] | None, expected: list[str]
435
+ ) -> OutputSchemaValidation:
436
+ """Soft-check the runtime's structured output against ``output_schema``.
437
+
438
+ No declared schema → ``checked=False`` (we don't pretend to validate).
439
+ No structured output (CLI returned plain text) → ``checked=False`` with
440
+ a note so the panel can explain why nothing was checked.
441
+ """
442
+ if not expected:
443
+ return OutputSchemaValidation(
444
+ valid=True,
445
+ checked=False,
446
+ note="output_schema is empty — nothing to validate against",
447
+ )
448
+ if structured is None:
449
+ return OutputSchemaValidation(
450
+ valid=False,
451
+ checked=False,
452
+ missing_fields=list(expected),
453
+ note="runtime did not return a structured payload — output schema cannot be checked",
454
+ )
455
+ expected_set = set(expected)
456
+ actual_set = set(structured.keys())
457
+ missing = sorted(expected_set - actual_set)
458
+ extras = sorted(actual_set - expected_set)
459
+ return OutputSchemaValidation(
460
+ valid=not missing,
461
+ checked=True,
462
+ missing_fields=missing,
463
+ extra_fields=extras,
464
+ )
465
+
466
+
467
+ @router.post("/dry-run", response_model=AgentDryRunResponse)
468
+ async def dry_run_agent(
469
+ payload: AgentDryRunRequest,
470
+ session: Session = Depends(get_session),
471
+ registry: RuntimeRegistry = Depends(get_registry),
472
+ config: EngineConfig = Depends(get_engine_config),
473
+ user: UserORM = Depends(current_active_user),
474
+ ) -> AgentDryRunResponse:
475
+ """Execute one agent end-to-end without persisting anything (#103).
476
+
477
+ Runs in a fresh ``tempfile.TemporaryDirectory`` so CLI runtimes that
478
+ edit files (claude-code, aider, codex, bash) do their work in a
479
+ sandbox that's discarded on response. No ``Run`` row, no
480
+ ``NodeExecutionLog`` row — the result is returned only to the
481
+ caller.
482
+
483
+ Auth handled by the runtime adapter itself (env key OR stored OAuth
484
+ session — see #99).
485
+ """
486
+ source = _resolve_dryrun_source(payload, session, actor_id=user.id, is_admin=user.is_superuser)
487
+
488
+ if not registry.has(source.runtime_id):
489
+ raise HTTPException(
490
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
491
+ detail=(
492
+ f"Unknown runtime_id '{source.runtime_id}' — no adapter registered. "
493
+ "Install the adapter or pick a different runtime."
494
+ ),
495
+ )
496
+
497
+ # Budget cap. The lower of agent's own ``budget_limit_usd`` and the
498
+ # engine-wide ``dry_run_budget_usd`` wins; if either declares a
499
+ # value above the engine cap, refuse before invocation.
500
+ cap = config.dry_run_budget_usd
501
+ agent_budget = source.agent_budget_usd
502
+ if agent_budget is not None and agent_budget > cap:
503
+ raise HTTPException(
504
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
505
+ detail=(
506
+ f"Agent budget_limit_usd ({agent_budget:.4f}) exceeds the "
507
+ f"dry-run cap ({cap:.4f}). Lower the agent's budget or raise "
508
+ "DAP_DRY_RUN_BUDGET_USD on the engine."
509
+ ),
510
+ )
511
+ effective_budget = min(agent_budget, cap) if agent_budget is not None else cap
512
+
513
+ try:
514
+ build_result = build_prompt(
515
+ source.prompt_template,
516
+ payload.context,
517
+ input_schema=source.input_schema or None,
518
+ agent_metadata={"role": source.role},
519
+ )
520
+ except PromptBuildError as exc:
521
+ raise HTTPException(
522
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)
523
+ ) from exc
524
+
525
+ adapter = registry.get(source.runtime_id)
526
+
527
+ with tempfile.TemporaryDirectory(prefix="dap-dryrun-") as workdir:
528
+ task = RuntimeTask(
529
+ execution_id=f"dryrun-{uuid.uuid4().hex[:12]}",
530
+ prompt_xml=build_result.xml,
531
+ working_directory=workdir,
532
+ timeout_ms=source.timeout_ms,
533
+ budget_usd=effective_budget,
534
+ runtime_config=source.runtime_config,
535
+ )
536
+ runtime_result = await adapter.execute(task)
537
+
538
+ output_check = _validate_output_schema(runtime_result.structured, source.output_schema)
539
+
540
+ return AgentDryRunResponse(
541
+ rendered_xml=build_result.xml,
542
+ prompt_warnings=list(build_result.warnings),
543
+ prompt_errors=list(build_result.errors),
544
+ runtime_result=runtime_result.model_dump(mode="json"),
545
+ output_schema_validation=output_check,
546
+ )
dap_engine/api/deps.py ADDED
@@ -0,0 +1,60 @@
1
+ """FastAPI dependencies — DB session, runtime registry, run registry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from dap_runtimes import RuntimeRegistry
9
+ from fastapi import Request
10
+ from langgraph.checkpoint.base import BaseCheckpointSaver
11
+ from sqlalchemy.orm import Session, sessionmaker
12
+
13
+ from dap_engine.execution import RunRegistry
14
+
15
+ if TYPE_CHECKING:
16
+ # Runtime cycle: dap_engine.app imports the api routers (which
17
+ # import this module). TYPE_CHECKING keeps the type information
18
+ # without the import-time edge.
19
+ from dap_engine.app import EngineConfig
20
+
21
+
22
+ def get_session(request: Request) -> Iterator[Session]:
23
+ """Yield a transactional Session — commit on success, rollback on error."""
24
+ factory: sessionmaker[Session] = request.app.state.session_factory
25
+ session = factory()
26
+ try:
27
+ yield session
28
+ session.commit()
29
+ except Exception:
30
+ session.rollback()
31
+ raise
32
+ finally:
33
+ session.close()
34
+
35
+
36
+ def get_session_factory(request: Request) -> sessionmaker[Session]:
37
+ """Return the session factory — used by background tasks that need a fresh session."""
38
+ factory: sessionmaker[Session] = request.app.state.session_factory
39
+ return factory
40
+
41
+
42
+ def get_registry(request: Request) -> RuntimeRegistry:
43
+ registry: RuntimeRegistry = request.app.state.runtime_registry
44
+ return registry
45
+
46
+
47
+ def get_run_registry(request: Request) -> RunRegistry:
48
+ run_registry: RunRegistry = request.app.state.run_registry
49
+ return run_registry
50
+
51
+
52
+ def get_checkpointer(request: Request) -> BaseCheckpointSaver[Any]:
53
+ checkpointer: BaseCheckpointSaver[Any] = request.app.state.checkpointer
54
+ return checkpointer
55
+
56
+
57
+ def get_engine_config(request: Request) -> EngineConfig:
58
+ """Return the active ``EngineConfig`` for endpoints that need its values."""
59
+ config: EngineConfig = request.app.state.config
60
+ return config