Coverage for app / services / scenarios / provision.py: 89%
72 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Making what a scenario talks to: a personal project of the run's own, the
2scenario's agents in it with their repositories granted, and its swarms of
3those agents.
5A fresh project per run, so memory, recommendations and figures start
6empty and two runs of one file can be compared. Everything is made the way
7the pages make it — the project with its creator as admin
8(``services/projects``), each agent with its ``created`` version and one
9version per grant (``services/agent_grants``) — so the run's agents read
10like any of the person's own.
11"""
13from __future__ import annotations
15from dataclasses import dataclass, field
16from datetime import datetime
17from typing import Any
18from uuid import UUID
20from sqlalchemy.orm import Session
22from app.db.postgres.enums import HistoryEnum
23from app.db.postgres.models import Agent, KnowledgeRepository, Project, Swarm, User
24from app.services import agent_grants
25from app.services import history as history_service
26from app.services import projects as projects_service
27from app.services.knowledge import built_in_crawls
28from app.services.scenarios.schema import ScenarioFile, ScenarioInvalid
29from app.services.workspace import Workspace, WorkspaceKind
31#: A project's name holds at most this many characters of the scenario's.
32NAME_CHARS = 60
35@dataclass(frozen=True)
36class Provisioned:
37 project_id: UUID
38 workspace_key: str
39 #: Each agent's id by its key in the file.
40 agents: dict[str, UUID]
41 #: Each swarm's id by its key in the file.
42 swarms: dict[str, UUID] = field(default_factory=dict)
45def project_name(scenario: str, when: datetime, run_id: UUID) -> str:
46 """ "Scenario · builtin-knowledge · 27 Oct 14:05 · 3fa2": unique per
47 owner, as a project name must be, by the run's id."""
48 return f"Scenario · {scenario[:NAME_CHARS]} · {when:%d %b %H:%M} · {run_id.hex[:4]}"
51def resolve_model(name: str | None, catalogue: list[dict]) -> UUID | None:
52 """The catalogue model named ``name`` (its ``model_name``, or its
53 display name), or None for the deployment's default. One it does not
54 hold, or one this deployment cannot run, is ``ScenarioInvalid``."""
55 if name is None:
56 return None
57 for model in catalogue:
58 if name in (model.get("model_name"), model.get("display_name")):
59 if model.get("is_available") is False:
60 raise ScenarioInvalid(f"Model {name!r} cannot run on this deployment.")
61 return UUID(str(model["id"]))
62 runnable = sorted(
63 str(m.get("model_name"))
64 for m in catalogue
65 if m.get("model_name") and m.get("is_available") is not False
66 )
67 raise ScenarioInvalid(
68 f"Model {name!r} is not in the catalogue. Choose from: {', '.join(runnable)}."
69 )
72def provision(
73 db: Session,
74 user: User,
75 scenario: ScenarioFile,
76 repositories: dict[str, Any],
77 *,
78 run_id: UUID,
79 now: datetime,
80 catalogue: list[dict] | None = None,
81) -> Provisioned:
82 """The run's project and agents, committed. ``repositories`` are the
83 file's built-ins by name (``schema.resolve_repositories``);
84 ``catalogue`` svc-ai's models, needed only when an agent names one."""
85 models = {
86 spec.key: resolve_model(spec.model, catalogue or []) for spec in scenario.agents
87 }
88 project = projects_service.create(
89 db,
90 user,
91 name=project_name(scenario.name, now, run_id),
92 description=(scenario.description or None),
93 owner_user_id=user.id,
94 )
95 agents: dict[str, UUID] = {}
96 for spec in scenario.agents:
97 agent = Agent(
98 name=spec.name,
99 description=spec.description or None,
100 system_prompt=spec.instructions,
101 ai_model_id=models[spec.key],
102 cost_profile=spec.cost_profile,
103 clarify_scope=spec.clarify_scope,
104 owner_project_id=project.id,
105 )
106 db.add(agent)
107 db.flush()
108 history_service.record_version(
109 db,
110 resource_type=HistoryEnum.ResourceType.agent,
111 model=Agent,
112 resource=agent,
113 action=HistoryEnum.Action.created,
114 actor=user,
115 children_resolver=lambda a=agent: agent_grants.children_snapshot(db, a.id),
116 )
117 for name in spec.repositories:
118 repository = db.get(KnowledgeRepository, repositories[name].id)
119 if repository is None:
120 raise ScenarioInvalid(
121 f"The built-in {name!r} is not provisioned on this deployment."
122 )
123 agent_grants.grant_repository(db, agent, repository, user)
124 agents[spec.key] = agent.id
125 swarms = {
126 spec.key: _swarm(db, user, spec, agents, project.id) for spec in scenario.swarms
127 }
128 db.commit()
129 # A built-in website repository nobody had granted holds nothing until
130 # its first crawl; the run waits for it (``readiness``).
131 built_in_crawls.start_for(db, [r.id for r in repositories.values()])
132 return Provisioned(
133 project_id=project.id,
134 workspace_key=Workspace(kind=WorkspaceKind.project, id=project.id).key,
135 agents=agents,
136 swarms=swarms,
137 )
140def _swarm(
141 db: Session, user: User, spec: Any, agents: dict[str, UUID], project_id: UUID
142) -> UUID:
143 """One of the file's swarms, in the run's project, checked as the Swarms
144 page checks one (``engine.check_swarm``) and versioned as it versions
145 one. A shape, setting or roster that does not fit is ``ScenarioInvalid``."""
146 from app.services.swarms import engine
147 from app.services.swarms import roster as roster_service
149 raw = [
150 {
151 "role": member.role,
152 "agent_id": str(agents[member.agent]),
153 "spawn": member.spawn,
154 **({"note": member.note} if member.note else {}),
155 }
156 for member in spec.roster
157 ]
158 try:
159 topology, params, _ = engine.check_swarm(
160 db, spec.topology, spec.params, raw, {"owner_project_id": project_id}
161 )
162 except engine.RunRefused as exc:
163 problems = "; ".join(f"{k}: {v}" for k, v in exc.fields.items())
164 raise ScenarioInvalid(f"Swarm {spec.key!r}: {problems or exc}") from exc
165 swarm = Swarm(
166 name=spec.name,
167 topology=topology.key,
168 params=params,
169 roster=roster_service.entries(raw)[0],
170 # Unattended: nobody approves a plan or answers a question.
171 defaults={"require_approval": False, "may_ask": False},
172 owner_project_id=project_id,
173 )
174 db.add(swarm)
175 db.flush()
176 history_service.record_version(
177 db,
178 resource_type=HistoryEnum.ResourceType.swarm,
179 model=Swarm,
180 resource=swarm,
181 action=HistoryEnum.Action.created,
182 actor=user,
183 )
184 return swarm.id
187def remove(db: Session, project_id: UUID | None, actor: User) -> bool:
188 """Delete the run's project, its agents and what they remembered; False
189 when it has already gone."""
190 project = db.get(Project, project_id) if project_id else None
191 if project is None:
192 return False
193 projects_service.delete(db, project, actor)
194 return True