Coverage for app / router / app / swarms / router.py: 75%

352 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""Swarms (``app/services/swarms``, docs/guides/swarms.md): teams of the 

2workspace's agents in a shape, sent on a long task under a budget and a time 

3cap. 

4 

5A swarm is a resource like any other — listed in its workspace, versioned, 

6in the Agents & skills access area. A run belongs to the person who started 

7it, as a skill run does: every run route acts on the caller's own runs only, 

8and another person's reads as not found. 

9 

10Switched off unless ``SWARMS_ENABLED`` (404, as if the routes were not 

11there), until verified live. 

12""" 

13 

14from __future__ import annotations 

15 

16import logging 

17from typing import Any 

18from uuid import UUID 

19 

20from fastapi import ( 

21 APIRouter, 

22 Body, 

23 Depends, 

24 HTTPException, 

25 Path, 

26 Query, 

27 Response, 

28 status, 

29) 

30from pydantic import BaseModel, ConfigDict, Field 

31from sqlalchemy.orm import Session 

32 

33from app.common.settings import get_settings 

34from app.db.postgres.crud_schemas import Schema 

35from app.db.postgres.enums import HistoryEnum 

36from app.db.postgres.models import Swarm, SwarmRun, SwarmTask, User 

37from app.dependency.base import get_db 

38from app.dependency.resource_access import ( 

39 annotated, 

40 scoped, 

41 verify_change_here, 

42 verify_owner_scope, 

43 verify_resource_read, 

44) 

45from app.dependency.user.context import get_current_user 

46from app.dependency.workspace import owner_for, request_workspace 

47from app.router.app.history.router import register_history_routes 

48from app.services import documents as documents_service 

49from app.services import history as history_service 

50from app.services.swarms import advice as advice_service 

51from app.services.swarms import engine, topologies 

52from app.services.swarms import roster as roster_service 

53from app.services.swarms import thread as thread_service 

54from app.util import document_images 

55from app.util.time import UTCDateTime 

56 

57logger = logging.getLogger(__name__) 

58 

59#: How many of a person's runs a list shows, newest first. 

60LIST_LIMIT = 20 

61 

62#: A run that answered: its answer can be downloaded. 

63ANSWERED = frozenset({"completed", "partial"}) 

64 

65#: How much of each request a thread's list on the run page carries. 

66THREAD_TASK_CHARS = 300 

67 

68 

69def require_enabled() -> None: 

70 """404 unless this deployment switches swarms on.""" 

71 if not get_settings().SWARMS_ENABLED: 

72 raise HTTPException( 

73 status_code=status.HTTP_404_NOT_FOUND, 

74 detail="Swarms are switched off on this deployment.", 

75 ) 

76 

77 

78swarms_router = APIRouter( 

79 prefix="/swarms", 

80 tags=["App - Swarms"], 

81 dependencies=[Depends(require_enabled)], 

82) 

83 

84 

85# ── What runs look like on the wire ────────────────────────────────────────── 

86 

87 

88class TaskRead(BaseModel): 

89 """One task of a run, as the run page draws its tree.""" 

90 

91 id: UUID 

92 parent_id: UUID | None = None 

93 seq: int 

94 depth: int 

95 kind: str 

96 handle: str 

97 title: str 

98 role: str 

99 agent_id: UUID | None = None 

100 agent_name: str 

101 tier: str 

102 cost_profile: str | None = None 

103 brief: dict[str, Any] 

104 depends_on: list[str] 

105 status: str 

106 attempts: int 

107 budget_usd: float | None = None 

108 estimate_usd: float | None = None 

109 limit_usd: float | None = None 

110 cost_usd: float 

111 spent_usd: float 

112 llm_calls: int 

113 unpriced_calls: int 

114 input_tokens: int 

115 output_tokens: int 

116 latency_ms: int | None = None 

117 invocation_id: UUID | None = None 

118 output: str | None = None 

119 result: dict[str, Any] | None = None 

120 citations: list[dict[str, Any]] | None = None 

121 questions: dict[str, Any] | None = None 

122 responses: list[dict[str, Any]] | None = None 

123 error: str | None = None 

124 created_at: UTCDateTime 

125 started_at: UTCDateTime | None = None 

126 finished_at: UTCDateTime | None = None 

127 

128 model_config = ConfigDict(from_attributes=True) 

129 

130 

131class RunRead(BaseModel): 

132 """A run as a list shows it.""" 

133 

134 id: UUID 

135 swarm_id: UUID | None = None 

136 swarm_name: str 

137 swarm_version: int | None = None 

138 #: Its thread (``swarms.thread``): the first run's id, its place in it, 

139 #: and the run it follows up. 

140 thread_id: UUID | None = None 

141 thread_seq: int = 1 

142 parent_run_id: UUID | None = None 

143 topology: str 

144 status: str 

145 task: str 

146 budget_usd: float 

147 time_cap_s: int 

148 deadline_at: UTCDateTime 

149 #: Waiting on a person since: its clock is stopped, the deadline not yet 

150 #: moved on by the wait. 

151 paused_at: UTCDateTime | None = None 

152 reserve_usd: float 

153 reserve_s: int 

154 wrap_up_reason: str | None = None 

155 progress: dict[str, Any] 

156 cost_usd: float 

157 spent_usd: float 

158 llm_calls: int 

159 unpriced_calls: int 

160 input_tokens: int 

161 output_tokens: int 

162 error: str | None = None 

163 cancel_requested: bool 

164 created_at: UTCDateTime 

165 finished_at: UTCDateTime | None = None 

166 

167 @classmethod 

168 def fields_of(cls, run: SwarmRun) -> dict[str, Any]: 

169 return { 

170 "id": run.id, 

171 "swarm_id": run.swarm_id, 

172 "swarm_name": run.swarm_name, 

173 "swarm_version": run.swarm_version, 

174 "thread_id": run.thread_id or run.id, 

175 "thread_seq": int(run.thread_seq or 1), 

176 "parent_run_id": run.parent_run_id, 

177 "topology": str((run.config or {}).get("topology") or ""), 

178 "status": run.status, 

179 "task": run.task, 

180 "budget_usd": float(run.budget_usd or 0), 

181 "time_cap_s": run.time_cap_s, 

182 "deadline_at": run.deadline_at, 

183 "paused_at": run.paused_at, 

184 "reserve_usd": float(run.reserve_usd or 0), 

185 "reserve_s": run.reserve_s, 

186 "wrap_up_reason": run.wrap_up_reason, 

187 "progress": run.progress or {}, 

188 "cost_usd": float(run.cost_usd or 0), 

189 "spent_usd": float(run.spent_usd or 0), 

190 "llm_calls": run.llm_calls or 0, 

191 "unpriced_calls": run.unpriced_calls or 0, 

192 "input_tokens": run.input_tokens or 0, 

193 "output_tokens": run.output_tokens or 0, 

194 "error": run.error, 

195 "cancel_requested": bool(run.cancel_requested), 

196 "created_at": run.created_at, 

197 "finished_at": run.finished_at, 

198 } 

199 

200 @classmethod 

201 def of(cls, run: SwarmRun) -> RunRead: 

202 return cls(**cls.fields_of(run)) 

203 

204 

205class ThreadStep(BaseModel): 

206 """One request of a thread, as the run page lists them to move between.""" 

207 

208 id: UUID 

209 seq: int 

210 task: str 

211 status: str 

212 spent_usd: float 

213 created_at: UTCDateTime 

214 finished_at: UTCDateTime | None = None 

215 

216 @classmethod 

217 def of(cls, run: SwarmRun) -> ThreadStep: 

218 return cls( 

219 id=run.id, 

220 seq=int(run.thread_seq or 1), 

221 task=(run.task or "")[:THREAD_TASK_CHARS], 

222 status=run.status, 

223 spent_usd=float(run.spent_usd or 0), 

224 created_at=run.created_at, 

225 finished_at=run.finished_at, 

226 ) 

227 

228 

229class RunDetail(RunRead): 

230 """A run as its page shows it: its plan, ledger, answer and every task, 

231 and the requests of its thread.""" 

232 

233 config: dict[str, Any] 

234 plan: dict[str, Any] | None = None 

235 ledger: dict[str, Any] 

236 output: str | None = None 

237 #: The sources its answer cites, each with the number it cites it by. 

238 citations: list[dict[str, Any]] | None = None 

239 warnings: list[str] | None = None 

240 file_ids: list[str] 

241 tasks: list[TaskRead] 

242 thread: list[ThreadStep] = Field(default_factory=list) 

243 

244 @classmethod 

245 def of(cls, run: SwarmRun, chain: list[SwarmRun] | None = None) -> RunDetail: 

246 return cls( 

247 **RunRead.fields_of(run), 

248 config=run.config or {}, 

249 plan=run.plan, 

250 ledger=run.ledger or {}, 

251 output=run.output, 

252 citations=run.citations, 

253 warnings=run.warnings, 

254 file_ids=[str(f) for f in run.file_ids or []], 

255 tasks=[TaskRead.model_validate(t) for t in run.tasks or []], 

256 thread=[ThreadStep.of(r) for r in chain or [run]], 

257 ) 

258 

259 

260class ThreadRead(BaseModel): 

261 """A thread as a list shows it, one row: its requests, first to latest.""" 

262 

263 thread_id: UUID 

264 swarm_id: UUID | None = None 

265 swarm_name: str 

266 requests: int 

267 open: bool 

268 spent_usd: float 

269 created_at: UTCDateTime 

270 updated_at: UTCDateTime 

271 latest: RunRead 

272 runs: list[RunRead] 

273 

274 @classmethod 

275 def of(cls, runs: list[SwarmRun]) -> ThreadRead: 

276 first, latest = runs[0], runs[-1] 

277 return cls( 

278 thread_id=first.thread_id or first.id, 

279 swarm_id=latest.swarm_id, 

280 swarm_name=latest.swarm_name, 

281 requests=len(runs), 

282 open=any(r.status in engine.OPEN for r in runs), 

283 spent_usd=float(sum(float(r.spent_usd or 0) for r in runs)), 

284 created_at=first.created_at, 

285 updated_at=max(r.created_at for r in runs), 

286 latest=RunRead.of(latest), 

287 runs=[RunRead.of(r) for r in runs], 

288 ) 

289 

290 

291class DispatchBody(BaseModel): 

292 """What to send the swarm on; every setting but the task falls back on 

293 the swarm's defaults.""" 

294 

295 task: str = Field(min_length=1, max_length=20_000) 

296 budget_usd: float | None = None 

297 time_cap_s: int | None = None 

298 max_parallel: int | None = None 

299 require_approval: bool | None = None 

300 may_ask: bool | None = None 

301 file_ids: list[str] = Field(default_factory=list) 

302 

303 def overrides(self) -> dict[str, Any]: 

304 return { 

305 key: value 

306 for key, value in self.model_dump( 

307 include={ 

308 "budget_usd", 

309 "time_cap_s", 

310 "max_parallel", 

311 "require_approval", 

312 "may_ask", 

313 } 

314 ).items() 

315 if value is not None 

316 } 

317 

318 

319class FollowUpBody(DispatchBody): 

320 """A follow-up of a run: what to do next, and whether the person's 

321 documents of the earlier requests go too.""" 

322 

323 carry_files: bool = True 

324 

325 

326class ApproveBody(BaseModel): 

327 """A person's changes to the lead's plan as they approve it.""" 

328 

329 drop: list[str] = Field(default_factory=list) 

330 assign: dict[str, str] = Field(default_factory=dict) 

331 budget_usd: float | None = None 

332 

333 

334def _refused(exc: engine.RunRefused) -> HTTPException: 

335 return HTTPException( 

336 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

337 detail={"message": exc.message, "fields": exc.fields}, 

338 ) 

339 

340 

341def _get_swarm(db: Session, swarm_id: UUID) -> Swarm: 

342 swarm = db.get(Swarm, swarm_id) 

343 if swarm is None: 

344 raise HTTPException( 

345 status_code=status.HTTP_404_NOT_FOUND, detail="Swarm not found" 

346 ) 

347 return swarm 

348 

349 

350def _detail(db: Session, run: SwarmRun) -> RunDetail: 

351 """``run`` as its page shows it, with the requests of its thread.""" 

352 return RunDetail.of(run, thread_service.chain(db, run)) 

353 

354 

355def _own_run(db: Session, run_id: UUID, user: User) -> SwarmRun: 

356 run = db.get(SwarmRun, run_id) 

357 if run is None or run.user_id != user.id: 

358 raise HTTPException( 

359 status_code=status.HTTP_404_NOT_FOUND, detail="Swarm run not found" 

360 ) 

361 return run 

362 

363 

364def _record(db: Session, swarm: Swarm, action: HistoryEnum.Action, user: User) -> None: 

365 history_service.record_version( 

366 db, 

367 resource_type=HistoryEnum.ResourceType.swarm, 

368 model=Swarm, 

369 resource=swarm, 

370 action=action, 

371 actor=user, 

372 ) 

373 

374 

375# ── Literal paths first: they would otherwise be read as a swarm's id ──────── 

376 

377 

378@swarms_router.get("/topologies") 

379def list_topologies( 

380 current_user: User = Depends(get_current_user), 

381) -> list[dict[str, Any]]: 

382 """Every shape a swarm can take: its roles, settings and presets.""" 

383 return topologies.catalogue() 

384 

385 

386@swarms_router.get("/runs", response_model=list[RunRead]) 

387def list_my_runs( 

388 db: Session = Depends(get_db), 

389 current_user: User = Depends(get_current_user), 

390): 

391 """The caller's newest runs of any swarm, in the request's workspace — 

392 what the Swarms tab shows going and done.""" 

393 runs = ( 

394 db.query(SwarmRun) 

395 .filter( 

396 SwarmRun.user_id == current_user.id, 

397 request_workspace(db, current_user).made_here(SwarmRun), 

398 # An evaluation's runs are reached from its cells. 

399 engine.listed(), 

400 ) 

401 .order_by(SwarmRun.created_at.desc()) 

402 .limit(LIST_LIMIT) 

403 .all() 

404 ) 

405 return [RunRead.of(run) for run in runs] 

406 

407 

408@swarms_router.get("/threads", response_model=list[ThreadRead]) 

409def list_my_threads( 

410 db: Session = Depends(get_db), 

411 current_user: User = Depends(get_current_user), 

412): 

413 """The caller's threads of any swarm, in the request's workspace, the 

414 newest activity first: a run and its follow-ups, one item.""" 

415 return [ 

416 ThreadRead.of(runs) 

417 for runs in thread_service.threads( 

418 db, 

419 SwarmRun.user_id == current_user.id, 

420 request_workspace(db, current_user).made_here(SwarmRun), 

421 engine.listed(), 

422 limit=LIST_LIMIT, 

423 ) 

424 ] 

425 

426 

427@swarms_router.post( 

428 "/runs/{run_id}/follow-up", 

429 response_model=RunDetail, 

430 status_code=status.HTTP_202_ACCEPTED, 

431) 

432def follow_up_run( 

433 run_id: UUID, 

434 body: FollowUpBody, 

435 db: Session = Depends(get_db), 

436 current_user: User = Depends(get_current_user), 

437): 

438 """Follow up one of the caller's runs: the swarm, as it is now, sent on 

439 the next request of the run's thread, with what the thread has done. 

440 422 names what cannot run; 409 when the run is not its thread's latest 

441 request, or the caller has as many runs going as they may.""" 

442 parent = _own_run(db, run_id, current_user) 

443 swarm = db.get(Swarm, parent.swarm_id) if parent.swarm_id else None 

444 if swarm is not None: 

445 verify_resource_read(swarm, current_user, db) 

446 try: 

447 run = engine.follow_up( 

448 db, 

449 parent, 

450 current_user, 

451 task=body.task, 

452 overrides=body.overrides(), 

453 file_ids=body.file_ids, 

454 carry_files=body.carry_files, 

455 ) 

456 except engine.RunRefused as exc: 

457 raise _refused(exc) from exc 

458 except (engine.RunInProgress, engine.ThreadMovedOn) as exc: 

459 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) 

460 return _detail(db, run) 

461 

462 

463@swarms_router.get("/runs/{run_id}", response_model=RunDetail) 

464def get_run( 

465 run_id: UUID, 

466 db: Session = Depends(get_db), 

467 current_user: User = Depends(get_current_user), 

468): 

469 """One of the caller's runs, with every task — what the run page polls.""" 

470 return _detail(db, _own_run(db, run_id, current_user)) 

471 

472 

473@swarms_router.get( 

474 "/runs/{run_id}/document.pdf", 

475 response_class=Response, 

476 responses={200: {"content": {"application/pdf": {}}}}, 

477) 

478def download_run_document( 

479 run_id: UUID, 

480 index: int = Query(default=0, ge=0, le=100), 

481 db: Session = Depends(get_db), 

482 current_user: User = Depends(get_current_user), 

483): 

484 """The run's answer as a PDF — rendered from what the run stored, never 

485 from anything sent with the request. Only a run that answered has one; 

486 ``index`` picks among several documents in its answer.""" 

487 run = _own_run(db, run_id, current_user) 

488 if run.status not in ANSWERED: 

489 raise HTTPException( 

490 status_code=status.HTTP_409_CONFLICT, 

491 detail="Only a run that has answered can be downloaded.", 

492 ) 

493 document = documents_service.for_swarm_run(run, index) 

494 if document is None: 

495 raise HTTPException( 

496 status_code=status.HTTP_404_NOT_FOUND, 

497 detail="This run produced nothing to download.", 

498 ) 

499 return documents_service.pdf_response( 

500 document, 

501 footer=documents_service.swarm_run_footer(run), 

502 when=run.finished_at or run.created_at, 

503 ) 

504 

505 

506@swarms_router.get( 

507 "/runs/{run_id}/images/{asset}", 

508 response_class=Response, 

509 responses={200: {"content": {"image/png": {}, "image/jpeg": {}}}}, 

510) 

511def run_document_image( 

512 run_id: UUID, 

513 asset: str = Path(pattern=document_images.ASSET_ID.pattern), 

514 db: Session = Depends(get_db), 

515 current_user: User = Depends(get_current_user), 

516): 

517 """An image a document in the run's answer shows — the copy svc-ai stored 

518 when it made the document. Only one that answer names, for the run's 

519 owner, once it has answered.""" 

520 run = _own_run(db, run_id, current_user) 

521 if run.status not in ANSWERED: 

522 raise HTTPException( 

523 status_code=status.HTTP_409_CONFLICT, 

524 detail="Only a run that has answered has images to show.", 

525 ) 

526 return documents_service.image_response( 

527 documents_service.document_fences(run.output), asset 

528 ) 

529 

530 

531@swarms_router.post("/runs/{run_id}/approve", response_model=RunDetail) 

532def approve_run( 

533 run_id: UUID, 

534 body: ApproveBody = Body(default_factory=ApproveBody), 

535 db: Session = Depends(get_db), 

536 current_user: User = Depends(get_current_user), 

537): 

538 """Approve the lead's plan, with any pieces dropped or reassigned and the 

539 budget changed; the team then starts work. 422 names what does not fit.""" 

540 run = _own_run(db, run_id, current_user) 

541 try: 

542 engine.approve( 

543 db, 

544 run, 

545 current_user, 

546 drop=body.drop, 

547 assign=body.assign, 

548 budget_usd=body.budget_usd, 

549 ) 

550 except engine.RunRefused as exc: 

551 raise _refused(exc) from exc 

552 return _detail(db, run) 

553 

554 

555@swarms_router.post("/runs/{run_id}/reject", response_model=RunDetail) 

556def reject_run( 

557 run_id: UUID, 

558 db: Session = Depends(get_db), 

559 current_user: User = Depends(get_current_user), 

560): 

561 """Decline the lead's plan: the run ends with nothing more spent.""" 

562 run = _own_run(db, run_id, current_user) 

563 try: 

564 engine.reject(db, run, current_user) 

565 except engine.RunRefused as exc: 

566 raise _refused(exc) from exc 

567 return _detail(db, run) 

568 

569 

570@swarms_router.post("/runs/{run_id}/stop", response_model=RunDetail) 

571def stop_run( 

572 run_id: UUID, 

573 db: Session = Depends(get_db), 

574 current_user: User = Depends(get_current_user), 

575): 

576 """Stop the run: no new work starts and it answers from what is done.""" 

577 run = _own_run(db, run_id, current_user) 

578 engine.stop(db, run) 

579 return _detail(db, run) 

580 

581 

582@swarms_router.post("/runs/{run_id}/tasks/{task_id}/respond", response_model=RunDetail) 

583def respond_to_task( 

584 run_id: UUID, 

585 task_id: UUID, 

586 response: dict[str, Any] = Body(...), 

587 db: Session = Depends(get_db), 

588 current_user: User = Depends(get_current_user), 

589): 

590 """Answer a worker's questions; its piece runs again with the answers. 

591 422 names a question the answer does not fit.""" 

592 run = _own_run(db, run_id, current_user) 

593 task = db.get(SwarmTask, task_id) 

594 if task is None or task.run_id != run.id: 

595 raise HTTPException( 

596 status_code=status.HTTP_404_NOT_FOUND, detail="Task not found" 

597 ) 

598 try: 

599 engine.respond(db, run, task, current_user, response) 

600 except engine.RunRefused as exc: 

601 raise _refused(exc) from exc 

602 return _detail(db, run) 

603 

604 

605# ── Swarms ─────────────────────────────────────────────────────────────────── 

606 

607 

608@swarms_router.get("", response_model=list[Schema.Swarm.Read]) 

609def list_swarms( 

610 workspace: str | None = None, 

611 db: Session = Depends(get_db), 

612 current_user: User = Depends(get_current_user), 

613): 

614 """The swarms of the workspace the request names (Personal when none).""" 

615 where, ws = scoped(Swarm, current_user, db, workspace=workspace) 

616 rows = db.query(Swarm).filter(where).order_by(Swarm.name.asc()).all() 

617 return annotated(rows, ws) 

618 

619 

620@swarms_router.post( 

621 "", response_model=Schema.Swarm.Read, status_code=status.HTTP_201_CREATED 

622) 

623def create_swarm( 

624 body: Schema.Swarm.Create, 

625 db: Session = Depends(get_db), 

626 current_user: User = Depends(get_current_user), 

627): 

628 """A new swarm in the request's workspace. 422 names what is wrong with 

629 its shape, settings or roster.""" 

630 data = body.model_dump() 

631 if not data.get("owner_organisation_id") and not data.get("owner_project_id"): 

632 data.update(owner_for(db, current_user, model=Swarm)) 

633 verify_owner_scope(data, current_user, db, model=Swarm) 

634 owner = {k: data.get(k) for k in engine.owner_of(None)} 

635 try: 

636 topology, params, _ = engine.check_swarm( 

637 db, data["topology"], data["params"], data["roster"], owner 

638 ) 

639 except engine.RunRefused as exc: 

640 raise _refused(exc) from exc 

641 defaults, problems = engine.read_defaults(data["defaults"]) 

642 if problems: 

643 raise _refused( 

644 engine.RunRefused("The swarm's defaults are out of bounds.", problems) 

645 ) 

646 swarm = Swarm( 

647 **{ 

648 **data, 

649 "topology": topology.key, 

650 "params": params, 

651 # As checked: notes tidied, keys it does not know dropped. 

652 "roster": roster_service.entries(data["roster"])[0], 

653 "defaults": defaults, 

654 } 

655 ) 

656 try: 

657 db.add(swarm) 

658 db.flush() 

659 _record(db, swarm, HistoryEnum.Action.created, current_user) 

660 db.commit() 

661 db.refresh(swarm) 

662 except Exception: 

663 db.rollback() 

664 logger.exception("Failed to create swarm") 

665 raise 

666 return swarm 

667 

668 

669@swarms_router.get("/{swarm_id}/advice") 

670def get_advice( 

671 swarm_id: UUID, 

672 db: Session = Depends(get_db), 

673 current_user: User = Depends(get_current_user), 

674): 

675 """What the record says about the swarm's shape: read from the caller's 

676 own runs of it and the evaluations that ran it — never from a model.""" 

677 swarm = _get_swarm(db, swarm_id) 

678 verify_resource_read(swarm, current_user, db) 

679 return { 

680 "advice": [ 

681 a.wire() for a in advice_service.for_swarm(db, swarm, current_user.id) 

682 ], 

683 "kinds": advice_service.kinds(), 

684 } 

685 

686 

687@swarms_router.get("/{swarm_id}", response_model=Schema.Swarm.Read) 

688def get_swarm( 

689 swarm_id: UUID, 

690 db: Session = Depends(get_db), 

691 current_user: User = Depends(get_current_user), 

692): 

693 """One swarm: its shape, settings, roster and defaults.""" 

694 swarm = _get_swarm(db, swarm_id) 

695 verify_resource_read(swarm, current_user, db) 

696 return swarm 

697 

698 

699@swarms_router.patch("/{swarm_id}", response_model=Schema.Swarm.Read) 

700def update_swarm( 

701 swarm_id: UUID, 

702 body: Schema.Swarm.Edit, 

703 db: Session = Depends(get_db), 

704 current_user: User = Depends(get_current_user), 

705): 

706 """Change a swarm in its own workspace. Its runs keep what they ran.""" 

707 swarm = _get_swarm(db, swarm_id) 

708 verify_change_here(swarm, current_user, db) 

709 changes = body.model_dump(exclude_unset=True) 

710 merged = { 

711 "topology": changes.get("topology") or swarm.topology, 

712 "params": changes.get("params", swarm.params), 

713 "roster": changes.get("roster", swarm.roster), 

714 } 

715 try: 

716 topology, params, _ = engine.check_swarm( 

717 db, 

718 merged["topology"], 

719 merged["params"], 

720 merged["roster"], 

721 engine.owner_of(swarm), 

722 ) 

723 except engine.RunRefused as exc: 

724 raise _refused(exc) from exc 

725 if "defaults" in changes: 

726 defaults, problems = engine.read_defaults(changes["defaults"]) 

727 if problems: 

728 raise _refused( 

729 engine.RunRefused("The swarm's defaults are out of bounds.", problems) 

730 ) 

731 changes["defaults"] = defaults 

732 changes.update(topology=topology.key, params=params) 

733 if "roster" in changes: 

734 changes["roster"] = roster_service.entries(changes["roster"])[0] 

735 for field, value in changes.items(): 

736 setattr(swarm, field, value) 

737 _record(db, swarm, HistoryEnum.Action.updated, current_user) 

738 try: 

739 db.commit() 

740 db.refresh(swarm) 

741 except Exception: 

742 db.rollback() 

743 logger.exception("Failed to update swarm %s", swarm_id) 

744 raise 

745 return swarm 

746 

747 

748@swarms_router.delete("/{swarm_id}", status_code=status.HTTP_204_NO_CONTENT) 

749def delete_swarm( 

750 swarm_id: UUID, 

751 db: Session = Depends(get_db), 

752 current_user: User = Depends(get_current_user), 

753): 

754 """Delete a swarm; its finished runs stay readable. 409 while a run of 

755 it is going: stop it first.""" 

756 swarm = _get_swarm(db, swarm_id) 

757 verify_change_here(swarm, current_user, db) 

758 going = ( 

759 db.query(SwarmRun) 

760 .filter(SwarmRun.swarm_id == swarm.id, SwarmRun.status.in_(list(engine.OPEN))) 

761 .count() 

762 ) 

763 if going: 

764 raise HTTPException( 

765 status_code=status.HTTP_409_CONFLICT, 

766 detail="A run of this swarm is still going; stop it first.", 

767 ) 

768 _record(db, swarm, HistoryEnum.Action.deleted, current_user) 

769 db.delete(swarm) 

770 db.commit() 

771 

772 

773# ── Its runs ───────────────────────────────────────────────────────────────── 

774 

775 

776@swarms_router.post( 

777 "/{swarm_id}/runs", response_model=RunDetail, status_code=status.HTTP_202_ACCEPTED 

778) 

779def start_run( 

780 swarm_id: UUID, 

781 body: DispatchBody, 

782 db: Session = Depends(get_db), 

783 current_user: User = Depends(get_current_user), 

784): 

785 """Send the swarm on a task. 422 names what cannot run; 409 when the 

786 caller has as many runs going as they may; 403 when a budget of the 

787 workspace is used up.""" 

788 swarm = _get_swarm(db, swarm_id) 

789 verify_resource_read(swarm, current_user, db) 

790 try: 

791 run = engine.start( 

792 db, 

793 swarm, 

794 current_user, 

795 task=body.task, 

796 overrides=body.overrides(), 

797 file_ids=body.file_ids, 

798 ) 

799 except engine.RunRefused as exc: 

800 raise _refused(exc) from exc 

801 except engine.RunInProgress as exc: 

802 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) 

803 return _detail(db, run) 

804 

805 

806@swarms_router.get("/{swarm_id}/runs", response_model=list[RunRead]) 

807def list_runs( 

808 swarm_id: UUID, 

809 db: Session = Depends(get_db), 

810 current_user: User = Depends(get_current_user), 

811): 

812 """The caller's newest runs of this swarm.""" 

813 swarm = _get_swarm(db, swarm_id) 

814 verify_resource_read(swarm, current_user, db) 

815 runs = ( 

816 db.query(SwarmRun) 

817 .filter( 

818 SwarmRun.swarm_id == swarm.id, 

819 SwarmRun.user_id == current_user.id, 

820 engine.listed(), 

821 ) 

822 .order_by(SwarmRun.created_at.desc()) 

823 .limit(LIST_LIMIT) 

824 .all() 

825 ) 

826 return [RunRead.of(run) for run in runs] 

827 

828 

829@swarms_router.get("/{swarm_id}/threads", response_model=list[ThreadRead]) 

830def list_threads( 

831 swarm_id: UUID, 

832 db: Session = Depends(get_db), 

833 current_user: User = Depends(get_current_user), 

834): 

835 """The caller's threads of this swarm, the newest activity first: a run 

836 and its follow-ups, one item.""" 

837 swarm = _get_swarm(db, swarm_id) 

838 verify_resource_read(swarm, current_user, db) 

839 return [ 

840 ThreadRead.of(runs) 

841 for runs in thread_service.threads( 

842 db, 

843 SwarmRun.swarm_id == swarm.id, 

844 SwarmRun.user_id == current_user.id, 

845 engine.listed(), 

846 limit=LIST_LIMIT, 

847 ) 

848 ] 

849 

850 

851register_history_routes( 

852 swarms_router, 

853 resource_type=HistoryEnum.ResourceType.swarm, 

854 model=Swarm, 

855 not_found_detail="Swarm not found", 

856 access_check=verify_resource_read, 

857)