-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
2154 lines (1907 loc) · 79.3 KB
/
Copy pathapi.py
File metadata and controls
2154 lines (1907 loc) · 79.3 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
"""FastAPI server exposing the Canvas assignment workflow orchestrator."""
import asyncio
import logging
import os
from datetime import datetime, timezone
from typing import Any, Optional
from uuid import uuid4
from dotenv import load_dotenv
load_dotenv()
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from app.agent import CanvasGitHubAgent
from app.auth_context import (
USER_STORE,
optional_session_user_id,
session_auth_enabled,
workflow_credentials_for_env,
workflow_credentials_for_http,
)
from app.credentials import WorkflowCredentials, get_canvas_institution_url
from app.delegation_policy import evaluate_delegation_policy
from app.planning import generate_assignment_plan
from app.provenance import build_artifact_provenance
from app.registry import AgentRegistry
from app.remote_agents import (
SmitheryRemoteAgentClient,
delegated_evaluation_enabled_by_default,
delegated_execution_enabled_by_default,
)
from app.task_store import SQLiteTaskStore
from scaffolding.templates import build_service_oasf_record
from tools.canvas_tools import CanvasTools
from tools.course_context_tools import CourseContextTools
from app.user_store import SESSION_COOKIE_NAME, SESSION_TTL_DAYS
logger = logging.getLogger(__name__)
SERVICE_NAME = "Canvas Assignment Workflow"
SERVICE_SLUG = "canvas-assignment-workflow"
SERVICE_VERSION = "0.1.0"
MCP_SERVER_NAME = "canvas-assignment-workflow"
MCP_SERVER_COMMAND = "canvas-github-agent-mcp"
DISCOVERY_SCHEMA = "agent_candidate_v1"
PLAN_SCHEMA = "assignment_plan_v1"
TASK_RESULT_SCHEMA = "task_result_v1"
TASK_STATUS_SCHEMA = "task_status_v1"
TASK_STEP_SCHEMA = "execution_step_v1"
SCORECARD_SCHEMA = "agent_scorecard_v1"
TASK_STORE = SQLiteTaskStore()
AGENT_REGISTRY = AgentRegistry()
REMOTE_AGENT_CLIENT = SmitheryRemoteAgentClient()
def get_allowed_origins() -> list[str]:
"""Resolve frontend origins from env, with local development defaults."""
configured = os.getenv("FRONTEND_ORIGINS", "").strip()
if configured:
return [origin.strip() for origin in configured.split(",") if origin.strip()]
return [
"http://localhost:5173",
"http://127.0.0.1:5173",
"http://localhost:3000",
"http://127.0.0.1:3000",
]
def get_service_base_url() -> str:
"""Resolve the public base URL for this service."""
configured = os.getenv("SERVICE_BASE_URL", "").strip()
if configured:
return configured.rstrip("/")
return "http://localhost:8000"
def build_capabilities_payload() -> dict[str, Any]:
"""Describe the stable service contract for agent discovery and invocation."""
base_url = get_service_base_url()
return {
"service": {
"name": SERVICE_NAME,
"slug": SERVICE_SLUG,
"version": SERVICE_VERSION,
"base_url": base_url,
},
"operations": [
{
"name": "list_courses",
"method": "GET",
"path": "/courses",
"description": "List Canvas courses visible to the configured user.",
},
{
"name": "list_assignments",
"method": "GET",
"path": "/courses/{course_id}/assignments",
"description": "List assignments for a Canvas course.",
},
{
"name": "list_course_modules",
"method": "GET",
"path": "/courses/{course_id}/modules",
"description": "List Canvas modules and module items for a course.",
},
{
"name": "search_course_modules",
"method": "POST",
"path": "/courses/{course_id}/modules/search",
"description": "Search Canvas course module content for assignment-relevant context.",
},
{
"name": "get_oasf_record",
"method": "GET",
"path": "/metadata/oasf-record",
"description": "Return the service-level OASF record.",
},
{
"name": "ingest_course_document",
"method": "POST",
"path": "/courses/{course_id}/documents/ingest",
"description": "Parse a course PDF with Docling and index it into Chroma.",
},
{
"name": "list_course_documents",
"method": "GET",
"path": "/courses/{course_id}/documents",
"description": "List course documents already indexed for retrieval.",
},
{
"name": "search_course_context",
"method": "POST",
"path": "/courses/{course_id}/context/search",
"description": "Search indexed course documents for assignment-relevant context.",
},
{
"name": "discover_agents",
"method": "POST",
"path": "/discover-agents",
"description": "Return ranked external agent candidates for a requested capability family or search query.",
},
{
"name": "plan_assignment",
"method": "POST",
"path": "/plan",
"description": "Analyze an assignment and return a structured execution plan without publishing artifacts.",
},
{
"name": "create_destination",
"method": "POST",
"path": "/create",
"description": (
"Create a GitHub repository for coding assignments or a "
"Notion page for writing assignments."
),
},
{
"name": "submit_task",
"method": "POST",
"path": "/tasks",
"description": "Queue assignment provisioning work for asynchronous execution.",
},
{
"name": "get_task_status",
"method": "GET",
"path": "/tasks/{task_id}",
"description": "Fetch the current status and result of a submitted task.",
},
{
"name": "list_task_steps",
"method": "GET",
"path": "/tasks/{task_id}/steps",
"description": "List the persisted execution_step_v1 records for a task.",
},
{
"name": "list_task_artifacts",
"method": "GET",
"path": "/tasks/{task_id}/artifacts",
"description": "List generated artifacts and provenance for a task.",
},
{
"name": "resume_task",
"method": "POST",
"path": "/tasks/{task_id}/resume",
"description": "Resume a failed or partially completed task, optionally retrying selected steps only.",
},
{
"name": "inspect_task_delegation_tool",
"method": "POST",
"path": "/tasks/{task_id}/inspect-delegation-tool",
"description": "Resolve the schema-compatible remote tool that would be used for a delegated execution or evaluation step.",
},
{
"name": "list_agent_scorecards",
"method": "GET",
"path": "/agents/scorecards",
"description": "List persisted agent delegation scorecards used for ranking feedback.",
},
],
"authentication": {
"service": "session_cookie_optional",
"description": (
"When CREDENTIAL_ENCRYPTION_KEY is set, the web UI uses POST /auth/session "
"with per-user Canvas and GitHub tokens (httpOnly cookie). "
"Otherwise the API uses CANVAS_API_TOKEN and GITHUB_TOKEN from the environment. "
"MCP tools always use environment credentials."
),
"upstream_dependencies": [
"CANVAS_API_TOKEN or browser session token",
"GITHUB_TOKEN or browser session token for coding flow",
"NOTION_TOKEN for writing flow (server env)",
],
},
"transports": {
"http": {
"base_url": base_url,
"health_path": "/health",
"capabilities_path": "/capabilities",
},
"mcp_stdio": {
"server_name": MCP_SERVER_NAME,
"command": MCP_SERVER_COMMAND,
"resources": [
"canvas-assignment-workflow://capabilities",
"canvas-assignment-workflow://metadata/oasf-record",
"canvas-assignment-workflow://schemas/execution-step-v1",
"canvas-assignment-workflow://schemas/agent-scorecard-v1",
"canvas-assignment-workflow://schemas/resume-task-v1",
"canvas-assignment-workflow://schemas/delegation-tool-inspection-v1",
"canvas-assignment-workflow://profiles/smithery-execution-pilot",
],
},
},
"routing": {
"assignment_types": ["coding", "writing"],
"destinations": ["github", "notion"],
"supported_languages": ["python", "r"],
"course_context_backend": "chroma",
"course_context_parser": "docling",
"course_context_sources": ["canvas_modules", "chroma_documents"],
},
"discovery_schema": {
"name": DISCOVERY_SCHEMA,
"top_level_fields": [
"status",
"service",
"query",
"candidates",
],
},
"planning_schema": {
"name": PLAN_SCHEMA,
"top_level_fields": [
"status",
"service",
"request",
"assignment",
"plan",
"recommendations",
"confidence",
],
},
"result_schema": {
"name": TASK_RESULT_SCHEMA,
"top_level_fields": [
"status",
"service",
"request",
"route",
"assignment",
"artifacts",
"details",
],
},
"task_schema": {
"name": TASK_STATUS_SCHEMA,
"top_level_fields": [
"task_id",
"status",
"service",
"request",
"submitted_at",
"started_at",
"completed_at",
"failed_at",
"result",
"error",
],
},
"task_step_schema": {
"name": TASK_STEP_SCHEMA,
"top_level_fields": [
"task_id",
"step_id",
"title",
"position",
"mode",
"capability_family",
"status",
"started_at",
"completed_at",
"failed_at",
"agent",
"policy",
"summary",
"result",
"error",
],
},
"scorecard_schema": {
"name": SCORECARD_SCHEMA,
"top_level_fields": [
"agent_id",
"capability_family",
"success_count",
"failure_count",
"blocked_count",
"total_count",
"success_rate",
"last_status",
"last_tool_name",
"updated_at",
],
},
}
def _utcnow_iso() -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
def _summarize_assignment(assignment: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
if not assignment:
return None
return {
"id": assignment.get("id"),
"name": assignment.get("name"),
"due_at": assignment.get("due_at"),
"workflow_state": assignment.get("workflow_state"),
"is_completed": assignment.get("is_completed"),
}
def _request_payload(req: "CreateRequest") -> dict[str, Any]:
return {
"course_id": req.course_id,
"assignment_id": req.assignment_id,
"language": req.language,
"assignment_type": req.assignment_type,
"notion_content_mode": req.notion_content_mode,
"enable_delegated_evaluation": req.enable_delegated_evaluation,
"evaluation_agent_id": req.evaluation_agent_id,
"evaluation_connection_id": req.evaluation_connection_id,
"evaluation_connection_url": req.evaluation_connection_url,
"evaluation_tool_name": req.evaluation_tool_name,
"evaluation_include_live_results": req.evaluation_include_live_results,
"enable_delegated_execution": req.enable_delegated_execution,
"execution_agent_id": req.execution_agent_id,
"execution_connection_id": req.execution_connection_id,
"execution_connection_url": req.execution_connection_url,
"execution_tool_name": req.execution_tool_name,
"execution_include_live_results": req.execution_include_live_results,
}
def _canvas_tools_from_credentials(creds: WorkflowCredentials) -> CanvasTools:
use_mcp = False if session_auth_enabled() else None
return CanvasTools(canvas_url=creds.canvas_url, canvas_token=creds.canvas_token, use_mcp=use_mcp)
def _assert_task_visible(task: dict[str, Any], request: Optional[Request]) -> None:
if not session_auth_enabled() or request is None:
return
uid = optional_session_user_id(request)
if uid is None:
raise HTTPException(status_code=401, detail="Not authenticated.")
owner = task.get("owner_user_id")
if owner is not None and int(owner) != int(uid):
raise HTTPException(status_code=404, detail="Task not found.")
def _credentials_for_task_owner(owner_user_id: Optional[int]) -> Optional[WorkflowCredentials]:
if owner_user_id is None:
return None
canvas_tok, github_tok, github_user = USER_STORE.decrypt_workflow_tokens(int(owner_user_id))
_org = os.getenv("GITHUB_ORG", "").strip()
github_org = _org if _org and not _org.startswith("#") else ""
return WorkflowCredentials(
canvas_url=get_canvas_institution_url(),
canvas_token=canvas_tok,
github_token=github_tok,
github_username=github_user,
github_org=github_org,
).with_notion_from_env()
def _build_task_response(req: "CreateRequest", result: dict[str, Any]) -> dict[str, Any]:
"""Normalize workflow output into a stable task-result contract."""
destination = result.get("destination")
assignment_type = "coding" if destination == "github" else "writing"
artifacts: list[dict[str, Any]] = []
details: dict[str, Any] = {}
repository = result.get("repository")
if repository:
artifacts.append(
{
"kind": "github_repository",
"url": repository.get("html_url"),
"owner": repository.get("owner", {}).get("login"),
"name": repository.get("name"),
}
)
details["files_created"] = result.get("files_created", [])
details["files_uploaded"] = result.get("files_uploaded", False)
page = result.get("page")
if page:
artifacts.append(
{
"kind": "notion_page",
"url": page.get("url"),
"id": page.get("id"),
}
)
if result.get("course_context"):
details["course_context"] = result["course_context"]
return {
"status": "completed",
"service": {
"name": SERVICE_NAME,
"slug": SERVICE_SLUG,
"version": SERVICE_VERSION,
},
"request": _request_payload(req),
"route": {
"assignment_type": assignment_type,
"destination": destination,
"language": req.language if assignment_type == "coding" else None,
"notion_content_mode": (
req.notion_content_mode or "structured"
if assignment_type == "writing"
else None
),
},
"assignment": _summarize_assignment(result.get("assignment")),
"artifacts": artifacts,
"details": details,
}
def _build_task_status(
*,
task_id: str,
request: dict[str, Any],
status: str,
submitted_at: str,
started_at: Optional[str] = None,
completed_at: Optional[str] = None,
failed_at: Optional[str] = None,
result: Optional[dict[str, Any]] = None,
error: Optional[dict[str, str]] = None,
owner_user_id: Optional[int] = None,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"task_id": task_id,
"status": status,
"service": {
"name": SERVICE_NAME,
"slug": SERVICE_SLUG,
"version": SERVICE_VERSION,
},
"request": request,
"submitted_at": submitted_at,
"started_at": started_at,
"completed_at": completed_at,
"failed_at": failed_at,
"result": result,
"error": error,
}
if owner_user_id is not None:
payload["owner_user_id"] = owner_user_id
return payload
def _build_plan_response(req: "CreateRequest", plan_result: dict[str, Any]) -> dict[str, Any]:
"""Normalize planning output into a stable pre-execution contract."""
return {
"status": "planned",
"service": {
"name": SERVICE_NAME,
"slug": SERVICE_SLUG,
"version": SERVICE_VERSION,
},
"request": _request_payload(req),
"assignment": plan_result["assignment"],
"plan": plan_result["plan"],
"recommendations": plan_result["recommendations"],
"confidence": plan_result["confidence"],
}
def _build_discovery_response(req: "DiscoverAgentsRequest", candidates: list[dict[str, Any]]) -> dict[str, Any]:
"""Normalize discovery output into a stable response contract."""
return {
"status": "ok",
"service": {
"name": SERVICE_NAME,
"slug": SERVICE_SLUG,
"version": SERVICE_VERSION,
},
"query": {
"capability_family": req.capability_family,
"query": req.query,
"limit": req.limit,
"include_live_results": req.include_live_results,
"verified_only": req.verified_only,
},
"candidates": candidates,
}
# Adding execution step schema
def build_execution_step_schema() -> dict[str, Any]:
"""Return a machine-readable schema description for execution_step_v1."""
return {
"name": TASK_STEP_SCHEMA,
"type": "object",
"required": ["task_id", "step_id", "title", "position", "mode", "status"],
"properties": {
"task_id": {"type": "string"},
"step_id": {"type": "string"},
"title": {"type": "string"},
"position": {"type": "integer"},
"mode": {"type": "string"},
"capability_family": {"type": ["string", "null"]},
"status": {"type": "string"},
"started_at": {"type": ["string", "null"]},
"completed_at": {"type": ["string", "null"]},
"failed_at": {"type": ["string", "null"]},
"attempt_count": {"type": "integer"},
"retry_count": {"type": "integer"},
"last_retry_at": {"type": ["string", "null"]},
"retry_history": {"type": "array", "items": {"type": "object"}},
"agent": {"type": ["object", "null"]},
"policy": {"type": ["object", "null"]},
"summary": {"type": ["object", "null"]},
"result": {"type": ["object", "null"]},
"error": {"type": ["object", "null"]},
},
}
def build_agent_scorecard_schema() -> dict[str, Any]:
"""Return a machine-readable schema description for agent_scorecard_v1."""
return {
"name": SCORECARD_SCHEMA,
"type": "object",
"required": ["agent_id", "capability_family", "success_count", "failure_count", "blocked_count", "total_count", "success_rate"],
"properties": {
"agent_id": {"type": "string"},
"capability_family": {"type": "string"},
"success_count": {"type": "integer"},
"failure_count": {"type": "integer"},
"blocked_count": {"type": "integer"},
"total_count": {"type": "integer"},
"success_rate": {"type": "number"},
"last_status": {"type": ["string", "null"]},
"last_tool_name": {"type": ["string", "null"]},
"last_task_id": {"type": ["string", "null"]},
"last_step_id": {"type": ["string", "null"]},
"updated_at": {"type": ["string", "null"]},
},
}
def build_resume_task_schema() -> dict[str, Any]:
"""Return a machine-readable schema description for task resume requests."""
return {
"name": "resume_task_v1",
"type": "object",
"required": [],
"properties": {
"step_ids": {"type": ["array", "null"], "items": {"type": "string"}},
"force_full_rerun": {"type": "boolean"},
},
}
def build_delegation_tool_inspection_schema() -> dict[str, Any]:
"""Return a machine-readable schema description for delegation tool inspection responses."""
return {
"name": "delegation_tool_inspection_v1",
"type": "object",
"required": ["status", "task_id", "capability_family", "candidate", "policy", "requested_tool_name"],
"properties": {
"status": {"type": "string"},
"task_id": {"type": "string"},
"capability_family": {"type": "string"},
"candidate": {"type": "object"},
"policy": {"type": "object"},
"requested_tool_name": {"type": "string"},
"tool_selection": {
"type": ["object", "null"],
"properties": {
"tool_name": {"type": "string"},
"schema": {"type": "object"},
"connection_id": {"type": ["string", "null"]},
"connection_url": {"type": ["string", "null"]},
},
},
},
}
def _create_request_from_payload(payload: dict[str, Any]) -> "CreateRequest":
"""Rehydrate a validated CreateRequest from persisted task request payloads."""
return CreateRequest(**payload)
def _scorecard_bonus(scorecard: dict[str, Any]) -> float:
total_count = int(scorecard.get("total_count") or 0)
if total_count == 0:
return 0.0
success_rate = float(scorecard.get("success_rate") or 0.0)
confidence = min(total_count / 10.0, 1.0)
return round((success_rate - 0.5) * 0.2 * confidence, 3)
def _attach_scorecards_to_candidates(candidates: list[dict[str, Any]]) -> list[dict[str, Any]]:
enriched: list[dict[str, Any]] = []
for candidate in candidates:
candidate_copy = dict(candidate)
ranking = dict(candidate_copy.get("ranking", {}))
original_score = float(ranking.get("score", 0.0) or 0.0)
agent_id = candidate_copy.get("agent_id")
capability_family = candidate_copy.get("capability_family")
explanation = {
"base_score": round(original_score, 3),
"final_score": round(original_score, 3),
"scorecard_bonus": 0.0,
"scorecard_applied": False,
"summary": "Ranked using capability fit and source signals only.",
}
if agent_id and capability_family:
scorecard = TASK_STORE.get_agent_scorecard(agent_id, capability_family)
if scorecard:
candidate_copy["scorecard"] = scorecard
bonus = _scorecard_bonus(scorecard)
ranking["scorecard_bonus"] = bonus
if "score" in ranking:
ranking["score"] = round(float(ranking["score"]) + bonus, 3)
candidate_copy["ranking"] = ranking
explanation = {
"base_score": round(original_score, 3),
"final_score": round(float(ranking.get("score", original_score)), 3),
"scorecard_bonus": bonus,
"scorecard_applied": True,
"summary": (
f"Applied scorecard bonus of {bonus:+.3f} from success_rate="
f"{float(scorecard.get('success_rate') or 0.0):.3f} over "
f"{int(scorecard.get('total_count') or 0)} observed delegations."
),
}
candidate_copy["ranking_explanation"] = explanation
enriched.append(candidate_copy)
enriched.sort(key=lambda item: item.get("ranking", {}).get("score", 0), reverse=True)
return enriched
def _refresh_artifact_provenance(task_response: dict[str, Any]) -> dict[str, Any]:
task_response.setdefault("details", {})["artifact_provenance"] = build_artifact_provenance(
task_response,
delegated_execution=task_response.get("details", {}).get("delegated_execution"),
delegated_evaluation=task_response.get("details", {}).get("delegated_evaluation"),
)
return task_response
def _record_agent_scorecard_event(task_id: Optional[str], result: dict[str, Any], capability_family: str) -> None:
agent = result.get("agent") or {}
agent_id = agent.get("agent_id")
if not agent_id:
return
TASK_STORE.record_agent_scorecard_event(
agent_id=agent_id,
capability_family=capability_family,
status=result.get("status", "failed"),
tool_name=result.get("request_summary", {}).get("tool_name"),
task_id=task_id,
step_id=result.get("subtask_id"),
)
def _build_task_step(
*,
task_id: str,
step_id: str,
title: str,
position: int,
mode: str,
status: str,
capability_family: Optional[str] = None,
started_at: Optional[str] = None,
completed_at: Optional[str] = None,
failed_at: Optional[str] = None,
attempt_count: int = 1,
retry_count: int = 0,
last_retry_at: Optional[str] = None,
retry_history: Optional[list[dict[str, Any]]] = None,
agent: Optional[dict[str, Any]] = None,
policy: Optional[dict[str, Any]] = None,
summary: Optional[dict[str, Any]] = None,
result: Optional[dict[str, Any]] = None,
error: Optional[dict[str, str]] = None,
) -> dict[str, Any]:
return {
"task_id": task_id,
"step_id": step_id,
"title": title,
"position": position,
"mode": mode,
"capability_family": capability_family,
"status": status,
"started_at": started_at,
"completed_at": completed_at,
"failed_at": failed_at,
"attempt_count": attempt_count,
"retry_count": retry_count,
"last_retry_at": last_retry_at,
"retry_history": retry_history or [],
"agent": agent,
"policy": policy,
"summary": summary,
"result": result,
"error": error,
}
def _step_history_entry(step: dict[str, Any]) -> dict[str, Any]:
return {
"status": step.get("status"),
"started_at": step.get("started_at"),
"completed_at": step.get("completed_at"),
"failed_at": step.get("failed_at"),
"summary": step.get("summary"),
"error": step.get("error"),
}
def _merge_step_retry_metadata(task_id: str, step: dict[str, Any]) -> dict[str, Any]:
existing = TASK_STORE.get_step(task_id, str(step.get("step_id") or ""))
if not existing:
step.setdefault("attempt_count", 1)
step.setdefault("retry_count", 0)
step.setdefault("last_retry_at", None)
step.setdefault("retry_history", [])
return step
attempt_count = int(existing.get("attempt_count") or 1)
retry_history = list(existing.get("retry_history") or [])
last_retry_at = existing.get("last_retry_at")
if step.get("status") == "running" and existing.get("status") != "running":
retry_history.append(_step_history_entry(existing))
attempt_count += 1
last_retry_at = step.get("started_at") or _utcnow_iso()
step["attempt_count"] = max(int(step.get("attempt_count") or 0), attempt_count)
step["retry_count"] = max(step["attempt_count"] - 1, 0)
step["last_retry_at"] = step.get("last_retry_at") or last_retry_at
step["retry_history"] = retry_history
return step
def _save_task_step(task_id: str, step: dict[str, Any]) -> None:
TASK_STORE.save_step(task_id, _merge_step_retry_metadata(task_id, dict(step)))
def _delegation_intent_queries(capability_family: str, requested_tool_name: str) -> list[str]:
queries = [requested_tool_name]
if capability_family == "execution":
queries.extend(["execute assignment", "run tests", "execute project", "run benchmark"])
else:
queries.extend(["evaluate assignment", "validate project", "score assignment"])
return list(dict.fromkeys(query for query in queries if query))
async def _inspect_task_delegation_tool(
task_id: str,
req: "CreateRequest",
capability_family: str,
) -> dict[str, Any]:
task = TASK_STORE.get(task_id)
if not task:
raise HTTPException(status_code=404, detail="Task not found.")
task_response = task.get("result") or {}
if not task_response:
raise HTTPException(status_code=409, detail="Task does not have generated artifacts to inspect yet.")
payload = _build_evaluation_payload(task_response)
if capability_family == "execution":
candidate = _resolve_execution_candidate(req)
scorecard = TASK_STORE.get_agent_scorecard(candidate.get("agent_id", ""), "execution") if candidate.get("agent_id") else None
explicit_request = any([req.execution_agent_id, req.execution_connection_id, req.execution_connection_url])
requested_tool_name = req.execution_tool_name
connection_id = req.execution_connection_id
connection_url = req.execution_connection_url
elif capability_family == "evaluation":
candidate = _resolve_evaluation_candidate(req)
scorecard = TASK_STORE.get_agent_scorecard(candidate.get("agent_id", ""), "evaluation") if candidate.get("agent_id") else None
explicit_request = any([req.evaluation_agent_id, req.evaluation_connection_id, req.evaluation_connection_url])
requested_tool_name = req.evaluation_tool_name
connection_id = req.evaluation_connection_id
connection_url = req.evaluation_connection_url
else:
raise HTTPException(status_code=400, detail="capability_family must be 'execution' or 'evaluation'.")
policy = evaluate_delegation_policy(
capability_family=capability_family,
candidate=candidate,
connection_id=connection_id,
connection_url=connection_url,
explicit_request=explicit_request,
scorecard=scorecard,
)
if not policy["allowed"]:
return {
"status": "blocked",
"task_id": task_id,
"capability_family": capability_family,
"candidate": candidate,
"policy": policy,
"requested_tool_name": requested_tool_name,
"tool_selection": None,
}
resolved_connection_id = connection_id or REMOTE_AGENT_CLIENT._connection_id_from_name(
candidate.get("agent_id") or candidate.get("name") or f"{capability_family}-agent"
)
resolved_connection_url = connection_url or candidate.get("invocation", {}).get("connection_url")
inspection = await REMOTE_AGENT_CLIENT.inspect_assignment_tool(
connection_id=resolved_connection_id,
connection_url=resolved_connection_url,
requested_tool_name=requested_tool_name,
payload=payload,
intent_queries=_delegation_intent_queries(capability_family, requested_tool_name),
)
return {
"status": "ready",
"task_id": task_id,
"capability_family": capability_family,
"candidate": candidate,
"policy": policy,
"requested_tool_name": requested_tool_name,
"tool_selection": inspection,
}
def _resolve_delegation_candidate(
*,
capability_family: str,
requested_agent_id: Optional[str],
connection_id: Optional[str],
connection_url: Optional[str],
include_live_results: bool,
default_name: str,
) -> dict[str, Any]:
if requested_agent_id:
candidates = AGENT_REGISTRY.discover_agents(
capability_family=capability_family,
query=requested_agent_id,
limit=10,
include_live_results=include_live_results,
verified_only=False,
)
for candidate in candidates:
agent_id = candidate.get("agent_id", "")
name = candidate.get("name", "")
requested = requested_agent_id.lower()
if requested == agent_id.lower() or requested == name.lower():
return candidate
if candidates:
return candidates[0]
if connection_id or connection_url:
fallback_name = requested_agent_id or connection_id or default_name
return {
"agent_id": requested_agent_id or connection_id or f"custom-{capability_family}-agent",
"name": fallback_name,
"source": "explicit_request",
"capability_family": capability_family,
"capabilities": [capability_family],
"protocols": ["mcp"],
"trust_level": "explicit_request",
"description": f"Explicit delegated {capability_family} target from the request payload.",
"invocation": {
"verified": False,
"connection_url": connection_url,
},
}
candidates = AGENT_REGISTRY.discover_agents(
capability_family=capability_family,
limit=1,
include_live_results=include_live_results,
verified_only=False,
)
if candidates:
return candidates[0]
return {
"agent_id": f"unresolved-{capability_family}-agent",
"name": default_name,
"source": "fallback",
"capability_family": capability_family,
"capabilities": [capability_family],
"protocols": ["mcp"],
"trust_level": "unknown",
"description": f"Fallback placeholder when no {capability_family} candidate could be resolved.",
"invocation": {
"verified": False,
"connection_url": connection_url,
},
}
def _resolve_evaluation_candidate(req: "CreateRequest") -> dict[str, Any]:
"""Resolve a concrete evaluation candidate for delegated validation."""
return _resolve_delegation_candidate(
capability_family="evaluation",
requested_agent_id=req.evaluation_agent_id,
connection_id=req.evaluation_connection_id,
connection_url=req.evaluation_connection_url,
include_live_results=req.evaluation_include_live_results,
default_name="Unresolved Evaluation Agent",
)
def _resolve_execution_candidate(req: "CreateRequest") -> dict[str, Any]:
"""Resolve a concrete execution candidate for delegated execution."""
return _resolve_delegation_candidate(
capability_family="execution",
requested_agent_id=req.execution_agent_id,
connection_id=req.execution_connection_id,
connection_url=req.execution_connection_url,
include_live_results=req.execution_include_live_results,
default_name="Unresolved Execution Agent",
)
def _build_evaluation_payload(task_response: dict[str, Any]) -> dict[str, Any]:
"""Build the delegated evaluation payload from the normalized task result."""
return {
"service": task_response.get("service"),
"assignment": task_response.get("assignment"),
"route": task_response.get("route"),
"artifacts": task_response.get("artifacts", []),
"details": {
"files_created": task_response.get("details", {}).get("files_created", []),
"files_uploaded": task_response.get("details", {}).get("files_uploaded"),
"course_context_count": len(task_response.get("details", {}).get("course_context", [])),
},
}
def _build_delegation_blocked_result(
*,
candidate: dict[str, Any],
payload: dict[str, Any],
tool_name: str,
subtask_id: str,
outcome_field: str,
policy: dict[str, Any],
connection_id: Optional[str],
connection_url: Optional[str],
) -> dict[str, Any]:
now = _utcnow_iso()
return {
"status": "blocked",
"subtask_id": subtask_id,
"agent": {
"agent_id": candidate.get("agent_id"),
"name": candidate.get("name"),
"source": candidate.get("source"),
"protocols": candidate.get("protocols", []),
"connection_id": connection_id,
"connection_url": connection_url or candidate.get("invocation", {}).get("connection_url"),
},
"request_summary": {