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,87 @@
|
|
|
1
|
+
"""Evaluate EdgeCondition against PipelineState.
|
|
2
|
+
|
|
3
|
+
Pure function: no I/O, no randomness. Used by runner to pick conditional
|
|
4
|
+
edges deterministically.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from dap_types import PipelineState
|
|
12
|
+
from dap_types.pipeline import (
|
|
13
|
+
ComparisonCondition,
|
|
14
|
+
ComparisonOperator,
|
|
15
|
+
EdgeCondition,
|
|
16
|
+
LogicalCondition,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def evaluate_condition(condition: EdgeCondition, state: PipelineState) -> bool:
|
|
21
|
+
"""Evaluate the condition against state. Returns True/False deterministically.
|
|
22
|
+
|
|
23
|
+
Unknown fields evaluate to False (the comparison cannot be made).
|
|
24
|
+
"""
|
|
25
|
+
if isinstance(condition, ComparisonCondition):
|
|
26
|
+
return _evaluate_comparison(condition, state)
|
|
27
|
+
if isinstance(condition, LogicalCondition):
|
|
28
|
+
if condition.type == "and":
|
|
29
|
+
return all(evaluate_condition(c, state) for c in condition.children)
|
|
30
|
+
if condition.type == "or":
|
|
31
|
+
return any(evaluate_condition(c, state) for c in condition.children)
|
|
32
|
+
msg = f"Unknown logical operator: {condition.type}"
|
|
33
|
+
raise ValueError(msg)
|
|
34
|
+
msg = f"Unknown condition type: {type(condition).__name__}"
|
|
35
|
+
raise ValueError(msg)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _evaluate_comparison(condition: ComparisonCondition, state: PipelineState) -> bool:
|
|
39
|
+
state_dict = state.model_dump()
|
|
40
|
+
actual = _get_field(state_dict, condition.field)
|
|
41
|
+
if actual is _MISSING:
|
|
42
|
+
return False
|
|
43
|
+
return _apply_operator(actual, condition.operator, condition.value)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_MISSING = object()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _get_field(data: dict[str, Any], field: str) -> Any:
|
|
50
|
+
"""Traverse *data* following dot-separated *field* path.
|
|
51
|
+
|
|
52
|
+
Returns ``_MISSING`` sentinel when any segment is absent or a
|
|
53
|
+
non-dict intermediate is encountered.
|
|
54
|
+
"""
|
|
55
|
+
parts = field.split(".")
|
|
56
|
+
current: Any = data
|
|
57
|
+
for part in parts:
|
|
58
|
+
if not isinstance(current, dict) or part not in current:
|
|
59
|
+
return _MISSING
|
|
60
|
+
current = current[part]
|
|
61
|
+
return current
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
_OPERATORS: dict[ComparisonOperator, Any] = {
|
|
65
|
+
"==": lambda a, b: a == b,
|
|
66
|
+
"!=": lambda a, b: a != b,
|
|
67
|
+
"<": lambda a, b: a < b,
|
|
68
|
+
"<=": lambda a, b: a <= b,
|
|
69
|
+
">": lambda a, b: a > b,
|
|
70
|
+
">=": lambda a, b: a >= b,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _apply_operator(
|
|
75
|
+
actual: Any,
|
|
76
|
+
operator: ComparisonOperator,
|
|
77
|
+
expected: str | int | float | bool | None,
|
|
78
|
+
) -> bool:
|
|
79
|
+
fn = _OPERATORS.get(operator)
|
|
80
|
+
if fn is None:
|
|
81
|
+
msg = f"Unknown operator: {operator}"
|
|
82
|
+
raise ValueError(msg)
|
|
83
|
+
# Ordering ops require comparable types — fall back to False on TypeError.
|
|
84
|
+
try:
|
|
85
|
+
return bool(fn(actual, expected))
|
|
86
|
+
except TypeError:
|
|
87
|
+
return False
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
"""Generic node executor — same function shape for every pipeline node.
|
|
2
|
+
|
|
3
|
+
Each node:
|
|
4
|
+
1. Renders prompt template with state as Jinja context (F4)
|
|
5
|
+
2. Builds RuntimeTask with the rendered XML
|
|
6
|
+
3. Calls runtime adapter (F3)
|
|
7
|
+
4. Records NodeExecutionLog + StateSnapshot
|
|
8
|
+
5. Returns state diff (dict that LangGraph merges into state)
|
|
9
|
+
|
|
10
|
+
For F5 MVP, state diff is `{}` on success and `{"final_status": "failed"}`
|
|
11
|
+
on error. Per-role output parsing (e.g. test_author → state.test_files)
|
|
12
|
+
is a future issue — adapters can opt into structured output by returning
|
|
13
|
+
RuntimeResult.structured with keys matching state fields, and we'll
|
|
14
|
+
merge them.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
import uuid
|
|
21
|
+
from collections.abc import Callable, Coroutine
|
|
22
|
+
from datetime import UTC, datetime
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from dap_prompt_dsl import PromptBuildError, build_prompt
|
|
26
|
+
from dap_runtimes import RuntimeRegistry
|
|
27
|
+
from dap_types import PipelineState, RuntimeResult, RuntimeTask
|
|
28
|
+
from sqlalchemy.orm import Session
|
|
29
|
+
|
|
30
|
+
from dap_engine.execution.output_parser import parse_node_output
|
|
31
|
+
from dap_engine.persistence.models import (
|
|
32
|
+
AgentORM,
|
|
33
|
+
AgentVersionORM,
|
|
34
|
+
NodeExecutionLogORM,
|
|
35
|
+
StateSnapshotORM,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger("dap.engine.execution")
|
|
39
|
+
|
|
40
|
+
NodeFn = Callable[[PipelineState], Coroutine[Any, Any, dict[str, Any]]]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class NodeContext:
|
|
44
|
+
"""Bound context for a single pipeline node — captured in node closure."""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
*,
|
|
49
|
+
run_id: str,
|
|
50
|
+
node_id: str,
|
|
51
|
+
agent: AgentORM,
|
|
52
|
+
agent_version: AgentVersionORM,
|
|
53
|
+
registry: RuntimeRegistry,
|
|
54
|
+
session: Session,
|
|
55
|
+
runtime_overrides: dict[str, Any] | None = None,
|
|
56
|
+
timeout_override_ms: int | None = None,
|
|
57
|
+
project_working_directory: str | None = None,
|
|
58
|
+
project_env_vars: dict[str, str] | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
self.run_id = run_id
|
|
61
|
+
self.node_id = node_id
|
|
62
|
+
self.agent = agent
|
|
63
|
+
self.agent_version = agent_version
|
|
64
|
+
self.registry = registry
|
|
65
|
+
self.session = session
|
|
66
|
+
self.runtime_overrides = runtime_overrides or {}
|
|
67
|
+
self.timeout_override_ms = timeout_override_ms
|
|
68
|
+
# Project context (#65) — propagated into RuntimeTask so adapters
|
|
69
|
+
# can run subprocesses in the right cwd with the right env.
|
|
70
|
+
# ``None`` / ``{}`` for ad-hoc runs without a project.
|
|
71
|
+
self.project_working_directory = project_working_directory
|
|
72
|
+
self.project_env_vars = project_env_vars or {}
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def merged_runtime_config(self) -> dict[str, Any]:
|
|
76
|
+
"""Agent's runtime_config merged with per-node overrides."""
|
|
77
|
+
return {**self.agent_version.runtime_config, **self.runtime_overrides}
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def timeout_ms(self) -> int:
|
|
81
|
+
return self.timeout_override_ms or self.agent_version.timeout_ms
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def make_node_fn(ctx: NodeContext) -> NodeFn:
|
|
85
|
+
"""Build an async node function bound to this NodeContext.
|
|
86
|
+
|
|
87
|
+
The returned function is what LangGraph calls during graph execution.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
async def node_fn(state: PipelineState) -> dict[str, Any]:
|
|
91
|
+
started_at = datetime.now(UTC)
|
|
92
|
+
execution_id = str(uuid.uuid4())
|
|
93
|
+
|
|
94
|
+
# 1. Render prompt — scoped to declared inputs when the agent
|
|
95
|
+
# version carries a contract (v0.5+); legacy dict-shaped or
|
|
96
|
+
# missing schemas pass through with full state visibility.
|
|
97
|
+
raw_input_schema = ctx.agent_version.input_schema
|
|
98
|
+
input_schema = list(raw_input_schema) if isinstance(raw_input_schema, list) else None
|
|
99
|
+
try:
|
|
100
|
+
build_result = build_prompt(
|
|
101
|
+
ctx.agent_version.prompt_template,
|
|
102
|
+
state.model_dump(),
|
|
103
|
+
input_schema=input_schema,
|
|
104
|
+
# Auto-inject agent identity (#113) so templates can use
|
|
105
|
+
# ``{{ role }}`` without forcing every agent to declare
|
|
106
|
+
# ``role`` as an input. ``PipelineState`` doesn't carry
|
|
107
|
+
# it; ``role`` lives on the parent ``AgentORM`` (not
|
|
108
|
+
# the version row, which is per-revision data).
|
|
109
|
+
agent_metadata={"role": ctx.agent.role},
|
|
110
|
+
)
|
|
111
|
+
except PromptBuildError as exc:
|
|
112
|
+
return _record_failure(
|
|
113
|
+
ctx=ctx,
|
|
114
|
+
started_at=started_at,
|
|
115
|
+
execution_id=execution_id,
|
|
116
|
+
prompt_xml="",
|
|
117
|
+
error=f"Prompt build failed: {exc}",
|
|
118
|
+
state=state,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
if not build_result.valid:
|
|
122
|
+
return _record_failure(
|
|
123
|
+
ctx=ctx,
|
|
124
|
+
started_at=started_at,
|
|
125
|
+
execution_id=execution_id,
|
|
126
|
+
prompt_xml=build_result.xml,
|
|
127
|
+
error=f"Invalid prompt XML: {'; '.join(build_result.errors)}",
|
|
128
|
+
state=state,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
prompt_xml = build_result.xml
|
|
132
|
+
|
|
133
|
+
# 2. Build RuntimeTask. ``working_directory`` defaults to the
|
|
134
|
+
# project's ``working_directory`` when bound (#65), falling back
|
|
135
|
+
# to the legacy ``"."`` for ad-hoc runs.
|
|
136
|
+
task = RuntimeTask(
|
|
137
|
+
execution_id=execution_id,
|
|
138
|
+
prompt_xml=prompt_xml,
|
|
139
|
+
working_directory=ctx.project_working_directory or ".",
|
|
140
|
+
timeout_ms=ctx.timeout_ms,
|
|
141
|
+
# Inject full pipeline state so python-func callables can access
|
|
142
|
+
# top-level and extensions fields without a separate state fetch.
|
|
143
|
+
runtime_config={
|
|
144
|
+
**ctx.merged_runtime_config,
|
|
145
|
+
"__pipeline_state": state.model_dump(mode="json"),
|
|
146
|
+
},
|
|
147
|
+
project_env_vars=ctx.project_env_vars,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# 3. Call adapter
|
|
151
|
+
adapter = ctx.registry.get(ctx.agent_version.runtime_id)
|
|
152
|
+
result: RuntimeResult = await adapter.execute(task)
|
|
153
|
+
ended_at = datetime.now(UTC)
|
|
154
|
+
|
|
155
|
+
if not result.success:
|
|
156
|
+
error_msg = "; ".join(result.errors) if result.errors else "Unknown error"
|
|
157
|
+
state_diff: dict[str, Any] = {
|
|
158
|
+
"final_status": "failed",
|
|
159
|
+
"verification_reason": f"Node {ctx.node_id} failed: {error_msg}",
|
|
160
|
+
}
|
|
161
|
+
else:
|
|
162
|
+
# python-func adapter wraps the callable's return dict in
|
|
163
|
+
# structured["state_delta"]. When that key is present, route the
|
|
164
|
+
# full delta through _route_extensions so Cortex-specific keys
|
|
165
|
+
# (task_assignments, decisions, issue_comments, …) land in
|
|
166
|
+
# extensions instead of being silently dropped by
|
|
167
|
+
# _merge_structured_into_state (which only keeps PipelineState
|
|
168
|
+
# top-level fields).
|
|
169
|
+
#
|
|
170
|
+
# Other adapters (bash, claude_code, api-call) put state-shaped
|
|
171
|
+
# keys directly at the top level of structured — use the existing
|
|
172
|
+
# merge + per-role parse path for those.
|
|
173
|
+
state_delta = (result.structured or {}).get("state_delta")
|
|
174
|
+
if state_delta is not None:
|
|
175
|
+
state_diff = _route_extensions(state, state_delta)
|
|
176
|
+
else:
|
|
177
|
+
# Adapter-supplied structured fields + per-role output parse.
|
|
178
|
+
state_diff = _merge_structured_into_state(result.structured)
|
|
179
|
+
parsed_diff = _parse_agent_output(ctx, result.output)
|
|
180
|
+
state_diff.update(parsed_diff)
|
|
181
|
+
state_diff = _route_extensions(state, state_diff)
|
|
182
|
+
|
|
183
|
+
# 4. Record execution log + snapshot, then commit immediately.
|
|
184
|
+
# Committing per-node rather than once at the end of the run means
|
|
185
|
+
# logs survive a CancelledError (pause/abort) that would otherwise
|
|
186
|
+
# roll back the bg_session before it could commit (#162).
|
|
187
|
+
# expire_on_commit=False (set on the session factory) ensures the
|
|
188
|
+
# in-memory pipeline/agent objects remain usable after the commit.
|
|
189
|
+
merged_state = state.model_copy(update=state_diff)
|
|
190
|
+
_save_execution_log(
|
|
191
|
+
ctx=ctx,
|
|
192
|
+
execution_id=execution_id,
|
|
193
|
+
started_at=started_at,
|
|
194
|
+
ended_at=ended_at,
|
|
195
|
+
prompt_xml=prompt_xml,
|
|
196
|
+
result=result,
|
|
197
|
+
)
|
|
198
|
+
_save_snapshot(ctx=ctx, state=merged_state)
|
|
199
|
+
ctx.session.commit()
|
|
200
|
+
|
|
201
|
+
return state_diff
|
|
202
|
+
|
|
203
|
+
return node_fn
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _record_failure(
|
|
207
|
+
*,
|
|
208
|
+
ctx: NodeContext,
|
|
209
|
+
started_at: datetime,
|
|
210
|
+
execution_id: str,
|
|
211
|
+
prompt_xml: str,
|
|
212
|
+
error: str,
|
|
213
|
+
state: PipelineState,
|
|
214
|
+
) -> dict[str, Any]:
|
|
215
|
+
ended_at = datetime.now(UTC)
|
|
216
|
+
log = NodeExecutionLogORM(
|
|
217
|
+
id=execution_id,
|
|
218
|
+
run_id=ctx.run_id,
|
|
219
|
+
node_id=ctx.node_id,
|
|
220
|
+
agent_id=ctx.agent.id,
|
|
221
|
+
runtime_id=ctx.agent_version.runtime_id,
|
|
222
|
+
started_at=started_at,
|
|
223
|
+
ended_at=ended_at,
|
|
224
|
+
prompt_xml=prompt_xml,
|
|
225
|
+
stdout="",
|
|
226
|
+
stderr="",
|
|
227
|
+
output_json=None,
|
|
228
|
+
tokens_used=0,
|
|
229
|
+
cost_usd=0.0,
|
|
230
|
+
duration_ms=int((ended_at - started_at).total_seconds() * 1000),
|
|
231
|
+
status="failed",
|
|
232
|
+
error_message=error,
|
|
233
|
+
extra_data=None,
|
|
234
|
+
)
|
|
235
|
+
ctx.session.add(log)
|
|
236
|
+
state_diff = {
|
|
237
|
+
"final_status": "failed",
|
|
238
|
+
"verification_reason": f"Node {ctx.node_id}: {error}",
|
|
239
|
+
}
|
|
240
|
+
_save_snapshot(ctx=ctx, state=state.model_copy(update=state_diff))
|
|
241
|
+
ctx.session.commit()
|
|
242
|
+
logger.warning("node %s failed: %s", ctx.node_id, error)
|
|
243
|
+
return state_diff
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _save_execution_log(
|
|
247
|
+
*,
|
|
248
|
+
ctx: NodeContext,
|
|
249
|
+
execution_id: str,
|
|
250
|
+
started_at: datetime,
|
|
251
|
+
ended_at: datetime,
|
|
252
|
+
prompt_xml: str,
|
|
253
|
+
result: RuntimeResult,
|
|
254
|
+
) -> None:
|
|
255
|
+
log = NodeExecutionLogORM(
|
|
256
|
+
id=execution_id,
|
|
257
|
+
run_id=ctx.run_id,
|
|
258
|
+
node_id=ctx.node_id,
|
|
259
|
+
agent_id=ctx.agent.id,
|
|
260
|
+
runtime_id=ctx.agent_version.runtime_id,
|
|
261
|
+
started_at=started_at,
|
|
262
|
+
ended_at=ended_at,
|
|
263
|
+
prompt_xml=prompt_xml,
|
|
264
|
+
stdout=result.output,
|
|
265
|
+
stderr="",
|
|
266
|
+
output_json=result.structured,
|
|
267
|
+
tokens_used=result.tokens_used or 0,
|
|
268
|
+
cost_usd=result.cost_usd or 0.0,
|
|
269
|
+
duration_ms=result.duration_ms,
|
|
270
|
+
status="success" if result.success else "failed",
|
|
271
|
+
error_message="; ".join(result.errors) if result.errors else None,
|
|
272
|
+
# ``extra_data`` stores domain-specific audit metadata produced by
|
|
273
|
+
# python-func adapters. A python-func node signals audit data by
|
|
274
|
+
# including an ``__audit`` key in its return dict; the adapter moves
|
|
275
|
+
# that dict to ``result.structured["audit"]`` before returning.
|
|
276
|
+
# CLI/LLM adapters never set "audit", so this evaluates to ``None``
|
|
277
|
+
# for those runtimes. The shape is intentionally open — see
|
|
278
|
+
# ``NodeExecutionLog.extra_data`` for documented common keys.
|
|
279
|
+
extra_data=result.structured.get("audit") if result.structured else None,
|
|
280
|
+
)
|
|
281
|
+
ctx.session.add(log)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _save_snapshot(*, ctx: NodeContext, state: PipelineState) -> None:
|
|
285
|
+
snapshot = StateSnapshotORM(
|
|
286
|
+
id=str(uuid.uuid4()),
|
|
287
|
+
run_id=ctx.run_id,
|
|
288
|
+
node_id=ctx.node_id,
|
|
289
|
+
timestamp=datetime.now(UTC),
|
|
290
|
+
state=state.model_dump(mode="json"),
|
|
291
|
+
)
|
|
292
|
+
ctx.session.add(snapshot)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _merge_structured_into_state(structured: dict[str, Any] | None) -> dict[str, Any]:
|
|
296
|
+
"""Merge adapter's structured output into state diff.
|
|
297
|
+
|
|
298
|
+
Only keys that exist in PipelineState are merged. Foreign keys are ignored.
|
|
299
|
+
Permissive — strict per-agent validation lives in `_parse_agent_output`.
|
|
300
|
+
"""
|
|
301
|
+
if not structured:
|
|
302
|
+
return {}
|
|
303
|
+
state_fields = set(PipelineState.model_fields.keys())
|
|
304
|
+
return {k: v for k, v in structured.items() if k in state_fields}
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _route_extensions(state: PipelineState, diff: dict[str, Any]) -> dict[str, Any]:
|
|
308
|
+
"""Route unknown keys in *diff* into ``extensions`` instead of rejecting them.
|
|
309
|
+
|
|
310
|
+
Known top-level keys are passed through unchanged. Unknown keys (those not
|
|
311
|
+
in ``PipelineState.model_fields``) are merged into the existing
|
|
312
|
+
``state.extensions`` dict so callers don't need to know the field name.
|
|
313
|
+
The sentinel key ``__audit`` is silently dropped here — it has already
|
|
314
|
+
been extracted into ``NodeExecutionLogORM.extra_data`` by
|
|
315
|
+
``_save_execution_log`` and must not propagate into pipeline state.
|
|
316
|
+
"""
|
|
317
|
+
known = set(PipelineState.model_fields.keys())
|
|
318
|
+
top_level = {k: v for k, v in diff.items() if k in known}
|
|
319
|
+
extra = {k: v for k, v in diff.items() if k not in known and k != "__audit"}
|
|
320
|
+
if not extra:
|
|
321
|
+
return top_level
|
|
322
|
+
return {
|
|
323
|
+
**top_level,
|
|
324
|
+
"extensions": {**state.extensions, **extra},
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _parse_agent_output(ctx: NodeContext, output: str) -> dict[str, Any]:
|
|
329
|
+
"""Apply per-agent output parsing when the agent declares a schema.
|
|
330
|
+
|
|
331
|
+
Resolves via :func:`parse_node_output`: the version's
|
|
332
|
+
``output_schema`` wins; falls back to ``ROLE_FIELDS[agent.role]``
|
|
333
|
+
for legacy agents with no declared schema. Parse failures are
|
|
334
|
+
logged but don't fail the run — the user can inspect the node log
|
|
335
|
+
and use retry-node / skip-node to recover (issue #33). The
|
|
336
|
+
resulting diff overrides adapter-supplied structured fields on
|
|
337
|
+
conflict so an agent's intentional response wins over telemetry.
|
|
338
|
+
|
|
339
|
+
Legacy DB rows may still hold a dict-shaped ``output_schema`` (the
|
|
340
|
+
pre-v0.5 placeholder format). Coerce those back to ``[]`` here so
|
|
341
|
+
``list(dict)`` (= dict keys) doesn't accidentally land in the
|
|
342
|
+
parser as a per-agent contract.
|
|
343
|
+
"""
|
|
344
|
+
raw_schema = ctx.agent_version.output_schema
|
|
345
|
+
output_schema = (
|
|
346
|
+
list(raw_schema) if isinstance(raw_schema, list) else []
|
|
347
|
+
) # legacy dict / None / anything else → fall back to ROLE_FIELDS
|
|
348
|
+
parse_result = parse_node_output(
|
|
349
|
+
ctx.agent.role,
|
|
350
|
+
output_schema,
|
|
351
|
+
output,
|
|
352
|
+
)
|
|
353
|
+
if parse_result.skipped:
|
|
354
|
+
return {}
|
|
355
|
+
if not parse_result.success:
|
|
356
|
+
logger.warning(
|
|
357
|
+
"node %s (role=%s) output parse failed: %s",
|
|
358
|
+
ctx.node_id,
|
|
359
|
+
ctx.agent.role,
|
|
360
|
+
"; ".join(parse_result.errors),
|
|
361
|
+
)
|
|
362
|
+
return {}
|
|
363
|
+
return parse_result.parsed
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Per-agent output parsing — turns raw adapter text into a state diff.
|
|
2
|
+
|
|
3
|
+
The api-call adapter returns raw LLM text in ``RuntimeResult.output``.
|
|
4
|
+
For deterministic pipelines we want each agent to write a *known subset*
|
|
5
|
+
of ``PipelineState`` fields. The subset is resolved from
|
|
6
|
+
``Agent.output_schema`` (preferred) or ``ROLE_FIELDS[agent.role]``
|
|
7
|
+
(legacy fallback) — see :mod:`dap_types.role_outputs`.
|
|
8
|
+
|
|
9
|
+
This module:
|
|
10
|
+
1. Pulls the JSON payload out of the LLM's text (XML wrapper or markdown
|
|
11
|
+
fence — whichever the prompt template requested).
|
|
12
|
+
2. Resolves the validator via :func:`resolve_output_validator` — the
|
|
13
|
+
per-agent ``output_schema`` wins; falls back to
|
|
14
|
+
``ROLE_FIELDS[role]``; returns ``None`` for custom roles with no
|
|
15
|
+
declared schema (caller falls back to permissive merging).
|
|
16
|
+
3. Returns a ``ParseResult`` with the parsed fields and any errors so the
|
|
17
|
+
caller can decide whether to log + continue, or fail the node.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import logging
|
|
24
|
+
import re
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from dap_types.role_outputs import resolve_output_validator
|
|
29
|
+
from pydantic import ValidationError
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger("dap.engine.execution.output_parser")
|
|
32
|
+
|
|
33
|
+
# <output>{...}</output> — the canonical wrapper recommended by the
|
|
34
|
+
# stock prompt templates. Uses non-greedy + DOTALL so multi-line JSON works.
|
|
35
|
+
OUTPUT_TAG_PATTERN = re.compile(
|
|
36
|
+
r"<output>\s*(.*?)\s*</output>",
|
|
37
|
+
re.DOTALL,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# ```json\n{...}\n``` — accepted as a fallback because LLMs reach for it
|
|
41
|
+
# when not given an explicit format instruction.
|
|
42
|
+
JSON_FENCE_PATTERN = re.compile(
|
|
43
|
+
r"```(?:json)?\s*\n(.*?)\n```",
|
|
44
|
+
re.DOTALL,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class ParseResult:
|
|
50
|
+
"""Outcome of parsing one node's raw output for state-merge candidates."""
|
|
51
|
+
|
|
52
|
+
success: bool
|
|
53
|
+
parsed: dict[str, Any] = field(default_factory=dict)
|
|
54
|
+
errors: list[str] = field(default_factory=list)
|
|
55
|
+
# When the role has no declared schema we skip parsing entirely;
|
|
56
|
+
# the caller distinguishes this from a real failure to decide whether
|
|
57
|
+
# to log a warning.
|
|
58
|
+
skipped: bool = False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def parse_node_output(
|
|
62
|
+
role: str,
|
|
63
|
+
output_schema: list[str],
|
|
64
|
+
output: str,
|
|
65
|
+
) -> ParseResult:
|
|
66
|
+
"""Extract a state-diff dict from ``output`` according to the contract.
|
|
67
|
+
|
|
68
|
+
Resolution order (delegated to :func:`resolve_output_validator`):
|
|
69
|
+
|
|
70
|
+
1. ``output_schema`` (per-agent declared subset) wins when non-empty.
|
|
71
|
+
2. Otherwise falls back to ``ROLE_FIELDS[role]`` for legacy
|
|
72
|
+
hardcoded contracts.
|
|
73
|
+
3. Returns ``ParseResult(skipped=True)`` for custom roles with no
|
|
74
|
+
declared schema — caller should fall back to permissive merging.
|
|
75
|
+
|
|
76
|
+
Takes the contract as two scalars rather than an ``Agent`` instance
|
|
77
|
+
so callers holding an ORM split (logical agent + version row) don't
|
|
78
|
+
need to construct a Pydantic Agent just to parse output.
|
|
79
|
+
"""
|
|
80
|
+
validator = resolve_output_validator(role, output_schema)
|
|
81
|
+
if validator is None:
|
|
82
|
+
return ParseResult(success=True, skipped=True)
|
|
83
|
+
|
|
84
|
+
label = role # for error messages — role is more user-meaningful than id
|
|
85
|
+
|
|
86
|
+
raw = _extract_json_block(output)
|
|
87
|
+
if raw is None:
|
|
88
|
+
return ParseResult(
|
|
89
|
+
success=False,
|
|
90
|
+
errors=[
|
|
91
|
+
"No JSON payload found in output. Expected <output>{...}</output>, "
|
|
92
|
+
"a ```json fence, or a bare {...} JSON object."
|
|
93
|
+
],
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
payload = json.loads(raw)
|
|
98
|
+
except json.JSONDecodeError as exc:
|
|
99
|
+
return ParseResult(
|
|
100
|
+
success=False,
|
|
101
|
+
errors=[f"Output is not valid JSON: {exc.msg} (pos={exc.pos})"],
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
if not isinstance(payload, dict):
|
|
105
|
+
return ParseResult(
|
|
106
|
+
success=False,
|
|
107
|
+
errors=[f"Output JSON must be an object; got {type(payload).__name__}"],
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
validated = validator.model_validate(payload)
|
|
112
|
+
except ValidationError as exc:
|
|
113
|
+
return ParseResult(
|
|
114
|
+
success=False,
|
|
115
|
+
errors=[_format_validation_error(label, e) for e in exc.errors()],
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
# Drop the None defaults so we only carry fields the agent actually
|
|
119
|
+
# wrote — keeps node snapshots minimal and avoids clobbering state
|
|
120
|
+
# with explicit nulls.
|
|
121
|
+
parsed = {k: v for k, v in validated.model_dump().items() if v is not None}
|
|
122
|
+
return ParseResult(success=True, parsed=parsed)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _extract_json_block(text: str) -> str | None:
|
|
126
|
+
"""Pull the first JSON payload from text. Prefers <output> over markdown fences."""
|
|
127
|
+
if not text:
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
tag_match = OUTPUT_TAG_PATTERN.search(text)
|
|
131
|
+
if tag_match is not None:
|
|
132
|
+
candidate = tag_match.group(1).strip()
|
|
133
|
+
if candidate:
|
|
134
|
+
return candidate
|
|
135
|
+
|
|
136
|
+
fence_match = JSON_FENCE_PATTERN.search(text)
|
|
137
|
+
if fence_match is not None:
|
|
138
|
+
candidate = fence_match.group(1).strip()
|
|
139
|
+
if candidate:
|
|
140
|
+
return candidate
|
|
141
|
+
|
|
142
|
+
# Last resort: maybe the whole text is JSON (some templates ask for that).
|
|
143
|
+
stripped = text.strip()
|
|
144
|
+
if stripped.startswith("{") and stripped.endswith("}"):
|
|
145
|
+
return stripped
|
|
146
|
+
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _format_validation_error(label: str, error: Any) -> str:
|
|
151
|
+
"""Pretty-print a single Pydantic validation error for the agent schema.
|
|
152
|
+
|
|
153
|
+
`error` is a Pydantic v2 ErrorDetails (TypedDict-ish); typed as Any to
|
|
154
|
+
avoid coupling to a private import. ``label`` is the agent's role —
|
|
155
|
+
surfaced in messages because it's the most user-meaningful identifier
|
|
156
|
+
when reading a stack of validation errors from a run log.
|
|
157
|
+
"""
|
|
158
|
+
loc = ".".join(str(p) for p in error.get("loc", ())) or "<root>"
|
|
159
|
+
msg = error.get("msg", "validation error")
|
|
160
|
+
err_type = error.get("type", "")
|
|
161
|
+
suffix = f" [{err_type}]" if err_type else ""
|
|
162
|
+
return f"{label}.{loc}: {msg}{suffix}"
|