main
py 64 lines 2.57 KB
Raw
1 from __future__ import annotations
2
3 from helpers.api import ApiHandler, Request, Response
4
5 from plugins._goal.tools import goal
6
7
8 class Goal(ApiHandler):
9 async def process(self, input: dict, request: Request) -> dict | Response:
10 action = str(input.get("action", "") or "").strip().lower()
11 context_id = str(input.get("context_id", "") or "").strip()
12
13 try:
14 if action == "get":
15 return {"ok": True, "goal": goal.public_goal(goal.get_goal(context_id))}
16 if action in {"set", "create"}:
17 return self._set(context_id, input)
18 if action == "update":
19 return self._update(context_id, input)
20 if action == "pause":
21 return self._status(context_id, "paused")
22 if action == "resume":
23 return self._status(context_id, "active")
24 if action == "delete":
25 goal.delete_goal(context_id)
26 return {"ok": True, "goal": None}
27 except FileNotFoundError:
28 return Response(status=404, response="Goal not found")
29 except ValueError as error:
30 return Response(status=400, response=str(error))
31
32 return Response(status=400, response=f"Unknown action: {action}")
33
34 def _set(self, context_id: str, input: dict) -> dict:
35 current_goal = goal.create_goal(
36 context_id,
37 str(input.get("objective") or ""),
38 created_by=str(input.get("created_by") or "user"),
39 token_budget=input.get("token_budget"),
40 )
41 return {"ok": True, "goal": goal.public_goal(current_goal)}
42
43 def _update(self, context_id: str, input: dict) -> dict:
44 current = goal.get_goal(context_id)
45 updated_goal = goal.update_goal(
46 context_id,
47 objective=input.get("objective") if "objective" in input else None,
48 status=input.get("status") if "status" in input else None,
49 note=input.get("note") if "note" in input else None,
50 token_budget=input.get("token_budget") if "token_budget" in input else None,
51 )
52 return {
53 "ok": True,
54 "goal": goal.public_goal(updated_goal),
55 "reactivated": (
56 current is not None
57 and current.get("status") in goal.FINAL_STATUSES
58 and updated_goal.get("status") == "active"
59 ),
60 }
61
62 def _status(self, context_id: str, status: str) -> dict:
63 current_goal = goal.update_goal(context_id, status=status)
64 return {"ok": True, "goal": goal.public_goal(current_goal)}