-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathagents.py
More file actions
1693 lines (1488 loc) · 60.9 KB
/
agents.py
File metadata and controls
1693 lines (1488 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections.abc import Sequence
from typing import Any
from agent_control_engine import list_evaluators
from agent_control_models.agent import Agent as APIAgent
from agent_control_models.agent import StepSchema
from agent_control_models.controls import ControlDefinition, ControlDefinitionRuntime
from agent_control_models.errors import ErrorCode, ValidationErrorItem
from agent_control_models.policy import Control as APIControl
from agent_control_models.server import (
AgentControlsResponse,
AgentSummary,
AssocResponse,
ConflictMode,
DeletePolicyResponse,
EvaluatorSchema,
GetAgentPoliciesResponse,
GetAgentResponse,
GetPolicyResponse,
InitAgentEvaluatorRemoval,
InitAgentOverwriteChanges,
InitAgentRequest,
InitAgentResponse,
ListAgentsResponse,
PaginationInfo,
PatchAgentRequest,
PatchAgentResponse,
RemoveAgentControlResponse,
SetPolicyResponse,
StepKey,
)
from fastapi import APIRouter, Depends, Query
from jsonschema_rs import ValidationError as JSONSchemaValidationError
from pydantic import BaseModel, ValidationError
from sqlalchemy import delete, func, select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from ..auth import RequireAPIKey, require_admin_key
from ..db import get_async_db
from ..errors import (
APIValidationError,
BadRequestError,
ConflictError,
DatabaseError,
NotFoundError,
)
from ..logging_utils import get_logger
from ..models import (
Agent,
AgentData,
Control,
Policy,
agent_policies,
)
from ..services.agent_names import normalize_agent_name_or_422
from ..services.controls import (
AgentControlEnabledState,
AgentControlRenderedState,
ControlService,
)
from ..services.evaluator_utils import (
parse_evaluator_ref_full,
validate_config_against_schema,
)
from ..services.query_utils import escape_like_pattern
from ..services.schema_compat import (
check_schema_compatibility,
format_compatibility_error,
)
router = APIRouter(prefix="/agents", tags=["agents"])
_logger = get_logger(__name__)
# Cache for built-in evaluator names (populated on first use)
_BUILTIN_EVALUATOR_NAMES: set[str] | None = None
# Pagination constants
_DEFAULT_PAGINATION_OFFSET = 0
_DEFAULT_PAGINATION_LIMIT = 20
_MAX_PAGINATION_LIMIT = 100
_CORRUPTED_AGENT_DATA_MESSAGE = "Stored agent data is corrupted and cannot be parsed."
type StepKeyTuple = tuple[str, str]
# =============================================================================
# List Agents Models
# =============================================================================
def _get_builtin_evaluator_names() -> set[str]:
"""Get built-in evaluator names (cached)."""
global _BUILTIN_EVALUATOR_NAMES
if _BUILTIN_EVALUATOR_NAMES is None:
_BUILTIN_EVALUATOR_NAMES = set(list_evaluators().keys())
return _BUILTIN_EVALUATOR_NAMES
def _validate_controls_for_agent(agent: Agent, controls: list[Control]) -> list[str]:
"""Validate controls can run on this agent."""
errors: list[str] = []
# Parse agent's registered evaluators
try:
agent_data = AgentData.model_validate(agent.data)
except ValidationError:
return [f"Agent '{agent.name}' has corrupted data"]
agent_evaluators = {e.name: e for e in (agent_data.evaluators or [])}
for control in controls:
# Skip unrendered template controls — they have no evaluators to validate.
if (
isinstance(control.data, dict)
and control.data.get("template") is not None
and control.data.get("condition") is None
):
continue
try:
control_definition = ControlDefinitionRuntime.model_validate(control.data)
except ValidationError:
errors.append(f"Control '{control.name}' has corrupted data")
continue
for _, evaluator_cfg in control_definition.iter_condition_leaf_parts():
evaluator_name = evaluator_cfg.name
parsed = parse_evaluator_ref_full(evaluator_name)
if parsed.type != "agent":
continue # Built-in/external evaluator, already validated at control creation
# Agent-scoped evaluator - check if target matches this agent
if parsed.namespace != agent.name:
errors.append(
f"Control '{control.name}' references evaluator '{evaluator_name}' "
f"which belongs to agent '{parsed.namespace}', not '{agent.name}'"
)
continue
# Check if evaluator exists on this agent
if parsed.local_name not in agent_evaluators:
errors.append(
f"Control '{control.name}' references evaluator '{parsed.local_name}' "
f"which is not registered with agent '{agent.name}'. "
f"Register it via initAgent or use a different evaluator."
)
continue
# Validate config against schema
registered_ev = agent_evaluators[parsed.local_name]
if registered_ev.config_schema:
try:
validate_config_against_schema(
evaluator_cfg.config,
registered_ev.config_schema,
)
except JSONSchemaValidationError as e:
errors.append(
f"Control '{control.name}' invalid config for "
f"'{parsed.local_name}': {e.message}"
)
return errors
def _find_referencing_controls_for_removed_evaluators(
controls: Sequence[APIControl],
agent_name: str,
remove_evaluator_set: set[str],
) -> list[tuple[str, str]]:
"""Return sorted unique control/evaluator pairs blocking evaluator removal."""
referencing_control_set: set[tuple[str, str]] = set()
for ctrl in controls:
if not isinstance(ctrl.control, ControlDefinition):
continue # Skip unrendered template controls
for _, evaluator_spec in ctrl.control.iter_condition_leaf_parts():
evaluator_ref = evaluator_spec.name
if ":" not in evaluator_ref:
continue
ref_agent, ref_eval = evaluator_ref.split(":", 1)
if ref_agent == agent_name and ref_eval in remove_evaluator_set:
referencing_control_set.add((ctrl.name, ref_eval))
return sorted(referencing_control_set, key=lambda item: (item[0], item[1]))
async def _validate_policy_controls_for_agent(
agent: Agent, policy_id: int, db: AsyncSession
) -> list[str]:
"""Validate all controls in a policy can run on this agent."""
controls = await ControlService(db).list_controls_for_policy(policy_id)
return _validate_controls_for_agent(agent, controls)
def _step_registration_changed(existing_step: StepSchema, incoming_step: StepSchema) -> bool:
"""Return True when non-key step registration fields differ."""
return (
existing_step.description != incoming_step.description
or existing_step.input_schema != incoming_step.input_schema
or existing_step.output_schema != incoming_step.output_schema
or existing_step.metadata != incoming_step.metadata
)
def _step_key_model(step_key: StepKeyTuple) -> StepKey:
"""Convert an internal step tuple key to API model."""
step_type, step_name = step_key
return StepKey(type=step_type, name=step_name)
async def _build_overwrite_evaluator_removals(
agent: Agent,
removed_evaluators: set[str],
db: AsyncSession,
) -> list[InitAgentEvaluatorRemoval]:
"""Build evaluator removal details, including active-control references."""
if not removed_evaluators:
return []
try:
controls = await ControlService(db).list_controls_for_agent(
agent.name,
allow_invalid_step_name_regex=True,
)
except APIValidationError:
_logger.warning(
"Skipping evaluator removal reference checks for agent '%s' "
"due to invalid control data",
agent.name,
exc_info=True,
)
return [InitAgentEvaluatorRemoval(name=name) for name in sorted(removed_evaluators)]
references_by_evaluator: dict[str, set[tuple[int, str]]] = {}
for control in controls:
if not isinstance(control.control, ControlDefinition):
continue # Skip unrendered template controls
for _, evaluator_spec in control.control.iter_condition_leaf_parts():
evaluator_ref = evaluator_spec.name
parsed = parse_evaluator_ref_full(evaluator_ref)
if parsed.type != "agent":
continue
if parsed.namespace != agent.name:
continue
if parsed.local_name not in removed_evaluators:
continue
references_by_evaluator.setdefault(parsed.local_name, set()).add(
(control.id, control.name)
)
removals: list[InitAgentEvaluatorRemoval] = []
for evaluator_name in sorted(removed_evaluators):
references = references_by_evaluator.get(evaluator_name)
if references is None:
removals.append(InitAgentEvaluatorRemoval(name=evaluator_name))
continue
sorted_references = sorted(references, key=lambda item: (item[1], item[0]))
removals.append(
InitAgentEvaluatorRemoval(
name=evaluator_name,
referenced_by_active_controls=True,
control_ids=[control_id for control_id, _ in sorted_references],
control_names=[control_name for _, control_name in sorted_references],
)
)
return removals
@router.get(
"",
response_model=ListAgentsResponse,
summary="List all agents",
response_description="Paginated list of agent summaries",
)
async def list_agents(
cursor: str | None = None,
limit: int = _DEFAULT_PAGINATION_LIMIT,
name: str | None = None,
db: AsyncSession = Depends(get_async_db),
) -> ListAgentsResponse:
"""
List all registered agents with cursor-based pagination.
Returns a summary of each agent including identifier, policy associations,
and counts of registered steps and evaluators.
Args:
cursor: Optional cursor for pagination (last agent name from previous page)
limit: Pagination limit (default 20, max 100)
name: Optional name filter (case-insensitive partial match)
db: Database session (injected)
Returns:
ListAgentsResponse with agent summaries and pagination info
"""
# Clamp limit
limit = min(max(1, limit), _MAX_PAGINATION_LIMIT)
# Build base filter for name search
name_filter = (
Agent.name.ilike(f"%{escape_like_pattern(name)}%", escape="\\") if name else None
)
# Get total count (with name filter if provided)
count_query = select(func.count()).select_from(Agent)
if name_filter is not None:
count_query = count_query.where(name_filter)
count_result = await db.execute(count_query)
total = count_result.scalar() or 0
# Build query with cursor-based pagination
# Order by created_at DESC, then by name DESC for stable ordering
query = select(Agent).order_by(Agent.created_at.desc(), Agent.name.desc())
# Apply name filter if provided
if name_filter is not None:
query = query.where(name_filter)
# If cursor provided, filter to get items after the cursor
if cursor:
cursor_name = normalize_agent_name_or_422(cursor, field_name="cursor")
cursor_agent_result = await db.execute(
select(Agent).where(Agent.name == cursor_name)
)
cursor_agent = cursor_agent_result.scalars().first()
if cursor_agent:
query = query.where(
(Agent.created_at < cursor_agent.created_at)
| (
(Agent.created_at == cursor_agent.created_at)
& (Agent.name < cursor_agent.name)
)
)
# Fetch limit + 1 to check if there are more pages
query = query.limit(limit + 1)
result = await db.execute(query)
agents = result.scalars().all()
# Check if there are more pages
has_more = len(agents) > limit
if has_more:
agents = agents[:-1] # Remove the extra item
# Determine next cursor (name of last agent in this page)
next_cursor: str | None = None
if has_more and agents:
next_cursor = agents[-1].name
control_counts_map: dict[str, int] = {}
policy_ids_map: dict[str, list[int]] = {}
control_service = ControlService(db)
if agents:
agent_names = [agent.name for agent in agents]
policy_ids_query = (
select(
agent_policies.c.agent_name,
agent_policies.c.policy_id,
)
.where(agent_policies.c.agent_name.in_(agent_names))
.order_by(agent_policies.c.agent_name, agent_policies.c.policy_id)
)
policy_ids_result = await db.execute(policy_ids_query)
for assoc_agent_name, policy_id in policy_ids_result.all():
policy_ids_map.setdefault(assoc_agent_name, []).append(policy_id)
control_counts_map = await control_service.list_active_control_counts_by_agent(
agent_names
)
# Build summaries
summaries: list[AgentSummary] = []
for agent in agents:
step_count = 0
evaluator_count = 0
# Parse agent data to get counts
try:
data_model = AgentData.model_validate(agent.data)
step_count = len(data_model.steps or [])
evaluator_count = len(data_model.evaluators or [])
except ValidationError:
# If data is corrupted, log and use zero counts
_logger.warning("Agent '%s' has invalid data, using zero counts", agent.name)
# Get active controls count from batched query result
active_controls = control_counts_map.get(agent.name, 0)
policy_ids = policy_ids_map.get(agent.name, [])
summaries.append(
AgentSummary(
agent_name=agent.name,
policy_ids=policy_ids,
created_at=agent.created_at.isoformat() if agent.created_at else None,
step_count=step_count,
evaluator_count=evaluator_count,
active_controls_count=active_controls,
)
)
return ListAgentsResponse(
agents=summaries,
pagination=PaginationInfo(
limit=limit,
total=total,
next_cursor=next_cursor,
has_more=has_more,
),
)
@router.post(
"/initAgent",
response_model=InitAgentResponse,
summary="Initialize or update an agent",
response_description="Agent registration status with active controls",
)
async def init_agent(
request: InitAgentRequest,
client: RequireAPIKey,
db: AsyncSession = Depends(get_async_db),
) -> InitAgentResponse:
"""
Register a new agent or update an existing agent's steps and metadata.
This endpoint is idempotent:
- If the agent name doesn't exist, creates a new agent
- If the agent name exists, updates registration data in place
conflict_mode controls registration conflict handling:
- strict (default): preserve compatibility checks and conflict errors
- overwrite: latest init payload replaces steps/evaluators and returns change summary
Args:
request: Agent metadata and step schemas
db: Database session (injected)
Returns:
InitAgentResponse with created flag and active controls currently associated
through policies or direct links
"""
# Check for evaluator name collisions with built-in evaluators
builtin_names = _get_builtin_evaluator_names()
for ev in request.evaluators:
if ev.name in builtin_names:
raise ConflictError(
error_code=ErrorCode.EVALUATOR_NAME_CONFLICT,
detail=f"Evaluator name '{ev.name}' conflicts with built-in evaluator.",
resource="Evaluator",
resource_id=ev.name,
hint="Choose a different name that does not conflict with built-in evaluators.",
errors=[
ValidationErrorItem(
resource="Evaluator",
field="name",
code="name_conflict",
message=f"Name '{ev.name}' conflicts with a built-in evaluator",
value=ev.name,
)
],
)
# Build incoming_steps_by_key and validate no duplicates in single pass
incoming_steps_by_key: dict[StepKeyTuple, StepSchema] = {}
for step in request.steps:
step_key: StepKeyTuple = (step.type, step.name)
if step_key in incoming_steps_by_key:
raise BadRequestError(
error_code=ErrorCode.VALIDATION_ERROR,
detail=f"Duplicate step name detected: type='{step.type}', name='{step.name}'. "
f"Each step must have a unique (type, name) combination within an agent.",
errors=[
ValidationErrorItem(
resource="Step",
field="name",
code="duplicate_step_name",
message=(
f"Step (type='{step.type}', name='{step.name}') "
f"appears multiple times in request"
),
)
],
)
incoming_steps_by_key[step_key] = step
result = await db.execute(select(Agent).where(Agent.name == request.agent.agent_name))
existing: Agent | None = result.scalars().first()
created = False
if existing is None:
created = True
data_model = AgentData(
agent_metadata=request.agent.model_dump(mode="json"),
steps=list(request.steps),
evaluators=list(request.evaluators),
)
new_agent = Agent(
name=request.agent.agent_name,
data=data_model.model_dump(mode="json"),
)
db.add(new_agent)
try:
await db.commit()
_logger.info(
f"Created agent '{request.agent.agent_name}' with {len(request.steps)} steps, "
f"{len(request.evaluators)} evaluators"
)
except Exception:
await db.rollback()
_logger.error(
f"Failed to create agent '{request.agent.agent_name}' ({request.agent.agent_name})",
exc_info=True,
)
raise DatabaseError(
detail=f"Failed to create agent '{request.agent.agent_name}': database error",
resource="Agent",
operation="create",
)
return InitAgentResponse(created=created, controls=[])
# Parse existing data via AgentData Pydantic model
try:
data_model = AgentData.model_validate(existing.data)
except ValidationError:
if not request.force_replace:
_logger.error(
f"Failed to parse existing agent data for '{request.agent.agent_name}'",
exc_info=True,
)
raise APIValidationError(
error_code=ErrorCode.CORRUPTED_DATA,
detail=(
f"Agent '{request.agent.agent_name}' has corrupted data and cannot be updated"
),
resource="Agent",
hint="Set force_replace=true in the request to replace the corrupted data.",
errors=[
ValidationErrorItem(
resource="Agent",
field="data",
code="corrupted_data",
message=_CORRUPTED_AGENT_DATA_MESSAGE,
)
],
)
# User explicitly requested replacement
_logger.warning(
f"Force-replacing corrupted data for agent '{request.agent.agent_name}' "
"due to force_replace=true.",
exc_info=True,
)
data_model = AgentData(agent_metadata={}, steps=[], evaluators=[])
steps_changed = False
evaluators_changed = False
force_write = request.force_replace # Always persist when force_replace=true
overwrite_applied = False
overwrite_changes = InitAgentOverwriteChanges()
# --- Update agent metadata ---
new_metadata = request.agent.model_dump(mode="json")
metadata_changed = data_model.agent_metadata != new_metadata
if metadata_changed:
data_model.agent_metadata = new_metadata
new_steps: list[StepSchema]
new_evaluators: list[EvaluatorSchema]
if request.conflict_mode == ConflictMode.OVERWRITE:
# Latest-init-wins: overwrite steps/evaluators exactly with incoming payload.
existing_steps = list(data_model.steps or [])
existing_steps_by_key = {(step.type, step.name): step for step in existing_steps}
existing_step_keys = set(existing_steps_by_key)
incoming_step_keys = set(incoming_steps_by_key)
steps_added_keys = sorted(incoming_step_keys - existing_step_keys)
steps_removed_keys = sorted(existing_step_keys - incoming_step_keys)
steps_updated_keys = sorted(
key
for key in (existing_step_keys & incoming_step_keys)
if _step_registration_changed(existing_steps_by_key[key], incoming_steps_by_key[key])
)
existing_evaluators = list(data_model.evaluators or [])
existing_evals_by_name: dict[str, EvaluatorSchema] = {
evaluator.name: evaluator for evaluator in existing_evaluators
}
incoming_evals_by_name: dict[str, EvaluatorSchema] = {
evaluator.name: evaluator for evaluator in request.evaluators
}
existing_eval_names = set(existing_evals_by_name)
incoming_eval_names = set(incoming_evals_by_name)
evaluators_added_names = sorted(incoming_eval_names - existing_eval_names)
evaluators_removed_names = sorted(existing_eval_names - incoming_eval_names)
evaluators_updated_names = sorted(
name
for name in (existing_eval_names & incoming_eval_names)
if (
existing_evals_by_name[name].config_schema
!= incoming_evals_by_name[name].config_schema
or existing_evals_by_name[name].description
!= incoming_evals_by_name[name].description
)
)
evaluator_removals: list[InitAgentEvaluatorRemoval] = []
if evaluators_removed_names:
evaluator_removals = await _build_overwrite_evaluator_removals(
existing,
set(evaluators_removed_names),
db,
)
overwrite_changes = InitAgentOverwriteChanges(
metadata_changed=metadata_changed,
steps_added=[_step_key_model(step_key) for step_key in steps_added_keys],
steps_updated=[_step_key_model(step_key) for step_key in steps_updated_keys],
steps_removed=[_step_key_model(step_key) for step_key in steps_removed_keys],
evaluators_added=evaluators_added_names,
evaluators_updated=evaluators_updated_names,
evaluators_removed=evaluators_removed_names,
evaluator_removals=evaluator_removals,
)
steps_changed = bool(steps_added_keys or steps_updated_keys or steps_removed_keys)
evaluators_changed = bool(
evaluators_added_names or evaluators_updated_names or evaluators_removed_names
)
overwrite_applied = bool(metadata_changed or steps_changed or evaluators_changed)
new_steps = list(request.steps)
new_evaluators = list(request.evaluators)
data_model.steps = new_steps
data_model.evaluators = new_evaluators
else:
# --- Process steps ---
# Note: incoming_steps_by_key already built during validation above
new_steps = []
seen_steps: set[StepKeyTuple] = set()
for step in data_model.steps or []:
key: StepKeyTuple = (step.type, step.name)
if key in incoming_steps_by_key:
if key not in seen_steps:
incoming_step = incoming_steps_by_key[key]
# Compare only schema fields (type/name already matched by key)
# Avoid model_dump() allocations by direct field comparison
if (
step.input_schema != incoming_step.input_schema
or step.output_schema != incoming_step.output_schema
):
raise ConflictError(
error_code=ErrorCode.SCHEMA_INCOMPATIBLE,
detail=(
"Step schema conflict for "
f"(type='{step.type}', name='{step.name}'). "
f"A step with this name already exists with a different schema."
),
resource="Step",
resource_id=step.name,
hint=(
"Please use a different step name or ensure schemas match exactly."
),
errors=[
ValidationErrorItem(
resource="Step",
field="schema",
code="schema_mismatch",
message=(
f"Existing schema differs from incoming schema "
f"for step '{step.name}'"
),
)
],
)
new_steps.append(incoming_step)
seen_steps.add(key)
else:
new_steps.append(step)
for key, step in incoming_steps_by_key.items():
if key not in seen_steps:
new_steps.append(step)
steps_changed = True
data_model.steps = new_steps
# --- Process evaluators with schema compatibility check ---
incoming_evals_by_name = {evaluator.name: evaluator for evaluator in request.evaluators}
existing_evals_by_name = {
evaluator.name: evaluator for evaluator in (data_model.evaluators or [])
}
new_evaluators = []
# Check existing evaluators for compatibility
for name, existing_ev in existing_evals_by_name.items():
if name in incoming_evals_by_name:
incoming_ev = incoming_evals_by_name[name]
old_schema = existing_ev.config_schema
new_schema = incoming_ev.config_schema
# Short-circuit: only check compatibility if schemas differ
if old_schema != new_schema:
is_compatible, compat_errors = check_schema_compatibility(
old_schema, new_schema
)
if not is_compatible:
raise ConflictError(
error_code=ErrorCode.SCHEMA_INCOMPATIBLE,
detail=format_compatibility_error(name, compat_errors),
resource="Evaluator",
resource_id=name,
hint="Ensure backward compatibility or use a new evaluator name.",
errors=[
ValidationErrorItem(
resource="Evaluator",
field="config_schema",
code="schema_incompatible",
message=err,
)
for err in compat_errors
],
)
# Check if evaluator changed (compare fields directly, avoid model_dump())
if (
existing_ev.config_schema != incoming_ev.config_schema
or existing_ev.description != incoming_ev.description
):
evaluators_changed = True
new_evaluators.append(incoming_ev)
else:
# Keep existing evaluator not in incoming request
new_evaluators.append(existing_ev)
# Add new evaluators
for name, evaluator in incoming_evals_by_name.items():
if name not in existing_evals_by_name:
new_evaluators.append(evaluator)
evaluators_changed = True
data_model.evaluators = new_evaluators
if steps_changed or evaluators_changed or metadata_changed or force_write:
existing.data = data_model.model_dump(mode="json")
try:
await db.commit()
_logger.info(
f"Updated agent '{request.agent.agent_name}' with {len(new_steps)} steps, "
f"{len(new_evaluators)} evaluators"
)
except Exception:
await db.rollback()
_logger.error(
f"Failed to update agent '{request.agent.agent_name}' ({request.agent.agent_name})",
exc_info=True,
)
raise DatabaseError(
detail=f"Failed to update agent '{request.agent.agent_name}': database error",
resource="Agent",
operation="update",
)
controls = await ControlService(db).list_controls_for_agent(existing.name)
return InitAgentResponse(
created=created,
controls=controls,
overwrite_applied=overwrite_applied,
overwrite_changes=overwrite_changes,
)
@router.get(
"/{agent_name}",
response_model=GetAgentResponse,
summary="Get agent details",
response_description="Agent metadata and registered steps",
)
async def get_agent(agent_name: str, db: AsyncSession = Depends(get_async_db)) -> GetAgentResponse:
"""
Retrieve agent metadata and all registered steps.
Returns the latest version of each step (deduplicated by type+name).
Args:
agent_name: Agent identifier
db: Database session (injected)
Returns:
GetAgentResponse with agent metadata and step list
Raises:
HTTPException 404: Agent not found
HTTPException 422: Agent data is corrupted
"""
agent_name = normalize_agent_name_or_422(agent_name)
result = await db.execute(select(Agent).where(Agent.name == agent_name))
existing: Agent | None = result.scalars().first()
if existing is None:
raise NotFoundError(
error_code=ErrorCode.AGENT_NOT_FOUND,
detail=f"Agent with name '{agent_name}' not found",
resource="Agent",
resource_id=str(agent_name),
hint=(
"Verify the agent name is correct and the agent has been "
"registered via initAgent."
),
)
try:
data_model = AgentData.model_validate(existing.data)
except ValidationError:
_logger.error(
f"Failed to parse agent data for agent '{existing.name}' ({agent_name})",
exc_info=True,
)
raise APIValidationError(
error_code=ErrorCode.CORRUPTED_DATA,
detail=f"Agent data is corrupted for agent '{existing.name}'",
resource="Agent",
hint="The agent's stored data is invalid. Re-register the agent with initAgent.",
)
try:
steps_by_key: dict[StepKeyTuple, StepSchema] = {}
for step in data_model.steps or []:
key: StepKeyTuple = (step.type, step.name)
steps_by_key[key] = step
latest_steps: list[StepSchema] = list(steps_by_key.values())
agent_meta = APIAgent.model_validate(data_model.agent_metadata)
except ValidationError:
_logger.error(
f"Failed to parse agent metadata for agent '{existing.name}' ({agent_name})",
exc_info=True,
)
raise APIValidationError(
error_code=ErrorCode.CORRUPTED_DATA,
detail=f"Agent metadata is corrupted for agent '{existing.name}'",
resource="Agent",
hint="The agent's metadata is invalid. Re-register the agent with initAgent.",
)
return GetAgentResponse(
agent=agent_meta, steps=latest_steps, evaluators=data_model.evaluators
)
async def _get_agent_or_404(agent_name: str, db: AsyncSession) -> Agent:
"""Get an agent or raise AGENT_NOT_FOUND."""
normalized_agent_name = normalize_agent_name_or_422(agent_name)
result = await db.execute(select(Agent).where(Agent.name == normalized_agent_name))
agent: Agent | None = result.scalars().first()
if agent is None:
raise NotFoundError(
error_code=ErrorCode.AGENT_NOT_FOUND,
detail=f"Agent with name '{normalized_agent_name}' not found",
resource="Agent",
resource_id=normalized_agent_name,
hint="Verify the agent name is correct and the agent has been registered.",
)
return agent
@router.post(
"/{agent_name}/policies/{policy_id}",
dependencies=[Depends(require_admin_key)],
response_model=AssocResponse,
summary="Associate policy with agent",
response_description="Success confirmation",
)
async def add_agent_policy(
agent_name: str, policy_id: int, db: AsyncSession = Depends(get_async_db)
) -> AssocResponse:
"""Associate a policy with an agent (idempotent)."""
agent = await _get_agent_or_404(agent_name, db)
policy_result = await db.execute(select(Policy).where(Policy.id == policy_id))
policy: Policy | None = policy_result.scalars().first()
if policy is None:
raise NotFoundError(
error_code=ErrorCode.POLICY_NOT_FOUND,
detail=f"Policy with ID '{policy_id}' not found",
resource="Policy",
resource_id=str(policy_id),
hint="Verify the policy ID is correct and the policy has been created.",
)
validation_errors = await _validate_policy_controls_for_agent(agent, policy_id, db)
if validation_errors:
raise BadRequestError(
error_code=ErrorCode.POLICY_CONTROL_INCOMPATIBLE,
detail="Policy contains controls incompatible with this agent",
hint="Ensure all controls in the policy are compatible with this agent's evaluators.",
errors=[
ValidationErrorItem(
resource="Control",
field="evaluator",
code="incompatible",
message=err,
)
for err in validation_errors
],
)
try:
stmt = (
pg_insert(agent_policies)
.values(agent_name=agent.name, policy_id=policy_id)
.on_conflict_do_nothing()
)
await db.execute(stmt)
await db.commit()
except Exception:
await db.rollback()
_logger.error(
"Failed to associate policy '%s' with agent '%s'",
policy_id,
agent.name,
exc_info=True,
)
raise DatabaseError(
detail=f"Failed to associate policy with agent '{agent.name}': database error",
resource="Agent",
operation="add policy association",
)
return AssocResponse(success=True)
@router.post(
"/{agent_name}/policy/{policy_id}",
dependencies=[Depends(require_admin_key)],
response_model=SetPolicyResponse,
summary="Assign policy to agent (compatibility)",
response_description="Success status with previous policy ID",
)
async def set_agent_policy(
agent_name: str, policy_id: int, db: AsyncSession = Depends(get_async_db)
) -> SetPolicyResponse:
"""Compatibility endpoint that replaces all policy associations with one policy."""
agent = await _get_agent_or_404(agent_name, db)
policy_result = await db.execute(select(Policy).where(Policy.id == policy_id))
policy: Policy | None = policy_result.scalars().first()
if policy is None:
raise NotFoundError(
error_code=ErrorCode.POLICY_NOT_FOUND,
detail=f"Policy with ID '{policy_id}' not found",
resource="Policy",
resource_id=str(policy_id),
hint="Verify the policy ID is correct and the policy has been created.",
)
validation_errors = await _validate_policy_controls_for_agent(agent, policy_id, db)
if validation_errors:
raise BadRequestError(
error_code=ErrorCode.POLICY_CONTROL_INCOMPATIBLE,
detail="Policy contains controls incompatible with this agent",
hint="Ensure all controls in the policy are compatible with this agent's evaluators.",
errors=[
ValidationErrorItem(
resource="Control",
field="evaluator",
code="incompatible",
message=err,
)
for err in validation_errors
],
)
existing_policies_result = await db.execute(
select(agent_policies.c.policy_id)
.where(agent_policies.c.agent_name == agent.name)
.order_by(agent_policies.c.policy_id)
)
existing_policy_ids = [row[0] for row in existing_policies_result.all()]
old_policy_id = existing_policy_ids[0] if existing_policy_ids else None
try:
await db.execute(delete(agent_policies).where(agent_policies.c.agent_name == agent.name))
await db.execute(
pg_insert(agent_policies)
.values(agent_name=agent.name, policy_id=policy_id)
.on_conflict_do_nothing()
)