Skip to content

Agent Zero AI framework

Consolidate goal tool

Alessandrobba84d91dd7b
diff --git a/plugins/_goal/AGENTS.md b/plugins/_goal/AGENTS.md
index 0c22ba1f5..758c32cea 100644
--- a/plugins/_goal/AGENTS.md
+++ b/plugins/_goal/AGENTS.md
@@ -8,11 +8,11 @@
## Ownership
- `plugin.yaml` owns the always-enabled `_goal` plugin metadata.
-- `helpers/goals.py` owns file-backed goal storage under `usr/plugins/_goal/goals/` and goal status normalization.
+- `tools/goal.py` owns the single agent-facing goal tool, file-backed state under `usr/plugins/_goal/goals/`, and goal status normalization.
- `api/goal.py` owns the WebUI JSON API for reading, editing, pausing, resuming, and deleting goals.
- `commands/` owns the `/goal` slash command contributed to `_commands`.
- `webui/` and `extensions/webui/` own the composer goal strip and inline controls.
-- `tools/` and `prompts/` own agent-facing goal inspection, creation, and status update behavior.
+- `tools/goal.py` and `prompts/agent.system.tool.goal.md` own agent-facing goal inspection, creation, and status updates.
- `tools/response.py` overrides the core response tool so an active goal continues the current monologue.
- `extensions/python/message_loop_prompts_after/` owns injecting the active goal into agent context.
diff --git a/plugins/_goal/api/goal.py b/plugins/_goal/api/goal.py
index 13a1d2d14..920be6861 100644
--- a/plugins/_goal/api/goal.py
+++ b/plugins/_goal/api/goal.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from helpers.api import ApiHandler, Request, Response
-from plugins._goal.helpers import goals
+from plugins._goal.tools import goal
class Goal(ApiHandler):
@@ -12,7 +12,7 @@ class Goal(ApiHandler):
try:
if action == "get":
- return {"ok": True, "goal": goals.public_goal(goals.get_goal(context_id))}
+ return {"ok": True, "goal": goal.public_goal(goal.get_goal(context_id))}
if action in {"set", "create"}:
return self._set(context_id, input)
if action == "update":
@@ -22,7 +22,7 @@ class Goal(ApiHandler):
if action == "resume":
return self._status(context_id, "active")
if action == "delete":
- goals.delete_goal(context_id)
+ goal.delete_goal(context_id)
return {"ok": True, "goal": None}
except FileNotFoundError:
return Response(status=404, response="Goal not found")
@@ -32,17 +32,17 @@ class Goal(ApiHandler):
return Response(status=400, response=f"Unknown action: {action}")
def _set(self, context_id: str, input: dict) -> dict:
- goal = goals.create_goal(
+ current_goal = goal.create_goal(
context_id,
str(input.get("objective") or ""),
created_by=str(input.get("created_by") or "user"),
token_budget=input.get("token_budget"),
)
- return {"ok": True, "goal": goals.public_goal(goal)}
+ return {"ok": True, "goal": goal.public_goal(current_goal)}
def _update(self, context_id: str, input: dict) -> dict:
- current = goals.get_goal(context_id)
- goal = goals.update_goal(
+ current = goal.get_goal(context_id)
+ updated_goal = goal.update_goal(
context_id,
objective=input.get("objective") if "objective" in input else None,
status=input.get("status") if "status" in input else None,
@@ -51,14 +51,14 @@ class Goal(ApiHandler):
)
return {
"ok": True,
- "goal": goals.public_goal(goal),
+ "goal": goal.public_goal(updated_goal),
"reactivated": (
current is not None
- and current.get("status") in goals.FINAL_STATUSES
- and goal.get("status") == "active"
+ and current.get("status") in goal.FINAL_STATUSES
+ and updated_goal.get("status") == "active"
),
}
def _status(self, context_id: str, status: str) -> dict:
- goal = goals.update_goal(context_id, status=status)
- return {"ok": True, "goal": goals.public_goal(goal)}
+ current_goal = goal.update_goal(context_id, status=status)
+ return {"ok": True, "goal": goal.public_goal(current_goal)}
diff --git a/plugins/_goal/commands/goal_command.py b/plugins/_goal/commands/goal_command.py
index 26bd58a64..f3816b4ae 100644
--- a/plugins/_goal/commands/goal_command.py
+++ b/plugins/_goal/commands/goal_command.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from typing import Any
-from plugins._goal.helpers import goals
+from plugins._goal.tools import goal
def run(payload: dict[str, Any]) -> dict[str, Any]:
@@ -18,33 +18,33 @@ def run(payload: dict[str, Any]) -> dict[str, Any]:
try:
if action in {"", "status", "show"}:
- return _show_markdown("Goal", goals.summarize_goal(goals.get_goal(context_id)))
+ return _show_markdown("Goal", goal.summarize_goal(goal.get_goal(context_id)))
if action in {"pause", "paused"}:
- goal = goals.update_goal(context_id, status="paused")
- return _changed("Goal paused.", goal)
+ current_goal = goal.update_goal(context_id, status="paused")
+ return _changed("Goal paused.", current_goal)
if action in {"resume", "start", "active"}:
- goal = goals.update_goal(context_id, status="active")
- return _changed("Goal resumed.", goal)
+ current_goal = goal.update_goal(context_id, status="active")
+ return _changed("Goal resumed.", current_goal)
if action in {"delete", "clear", "remove"}:
- goals.delete_goal(context_id)
+ goal.delete_goal(context_id)
return _changed("Goal deleted.", None)
if action in {"complete", "done"}:
- goal = goals.update_goal(context_id, status="complete")
- return _changed("Goal marked complete.", goal)
+ current_goal = goal.update_goal(context_id, status="complete")
+ return _changed("Goal marked complete.", current_goal)
if action == "blocked":
note = raw_args.split(None, 1)[1].strip() if len(tokens) > 1 else ""
- goal = goals.update_goal(context_id, status="blocked", note=note)
- return _changed("Goal marked blocked.", goal)
+ current_goal = goal.update_goal(context_id, status="blocked", note=note)
+ return _changed("Goal marked blocked.", current_goal)
if action == "edit":
objective = raw_args.split(None, 1)[1].strip() if len(tokens) > 1 else ""
- goal = goals.update_goal(context_id, objective=objective, status="active")
- return _changed("Goal updated.", goal)
+ current_goal = goal.update_goal(context_id, objective=objective, status="active")
+ return _changed("Goal updated.", current_goal)
if action in {"auto", "ask", "model"}:
hint = raw_args.split(None, 1)[1].strip() if len(tokens) > 1 else ""
return _auto_prompt(hint)
- goal = goals.create_goal(context_id, raw_args, created_by="user")
- return _changed("Goal set.", goal, send_text=raw_args)
+ current_goal = goal.create_goal(context_id, raw_args, created_by="user")
+ return _changed("Goal set.", current_goal, send_text=raw_args)
except FileNotFoundError:
return _effects(_toast("No goal is set for this chat.", level="error"))
except ValueError as error:
@@ -62,10 +62,10 @@ def _auto_prompt(hint: str) -> dict[str, Any]:
return {"text": prompt, "effects": []}
-def _changed(message: str, goal: dict[str, Any] | None, *, send_text: str = "") -> dict[str, Any]:
+def _changed(message: str, current_goal: dict[str, Any] | None, *, send_text: str = "") -> dict[str, Any]:
return _effects(
_toast(message),
- {"type": "goal_changed", "goal": goals.public_goal(goal)},
+ {"type": "goal_changed", "goal": goal.public_goal(current_goal)},
{"type": "send_message", "text": send_text} if send_text else {},
)
diff --git a/plugins/_goal/extensions/python/message_loop_prompts_after/_50_include_goal.py b/plugins/_goal/extensions/python/message_loop_prompts_after/_50_include_goal.py
index e18ac7080..207be41bc 100644
--- a/plugins/_goal/extensions/python/message_loop_prompts_after/_50_include_goal.py
+++ b/plugins/_goal/extensions/python/message_loop_prompts_after/_50_include_goal.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from agent import LoopData
from helpers.extension import Extension
-from plugins._goal.helpers import goals
+from plugins._goal.tools import goal
class IncludeGoal(Extension):
@@ -11,18 +11,18 @@ class IncludeGoal(Extension):
return
try:
- goal = goals.get_goal(self.agent.context.id)
+ current_goal = goal.get_goal(self.agent.context.id)
except ValueError:
- goal = None
+ current_goal = None
- if not goal or goal.get("status") != "active":
+ if not current_goal or current_goal.get("status") != "active":
loop_data.extras_temporary.pop("current_goal", None)
return
loop_data.extras_temporary["current_goal"] = self.agent.read_prompt(
"agent.extras.goal.md",
- status=goal.get("status", ""),
- objective=goal.get("objective", ""),
- created_by=goal.get("created_by", ""),
- updated_at=goal.get("updated_at", ""),
+ status=current_goal.get("status", ""),
+ objective=current_goal.get("objective", ""),
+ created_by=current_goal.get("created_by", ""),
+ updated_at=current_goal.get("updated_at", ""),
)
diff --git a/plugins/_goal/helpers/__init__.py b/plugins/_goal/helpers/__init__.py
deleted file mode 100644
index 8b1378917..000000000
--- a/plugins/_goal/helpers/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/plugins/_goal/prompts/agent.extras.goal.md b/plugins/_goal/prompts/agent.extras.goal.md
index eb8350f2f..b9bbbff98 100644
--- a/plugins/_goal/prompts/agent.extras.goal.md
+++ b/plugins/_goal/prompts/agent.extras.goal.md
@@ -4,4 +4,4 @@ objective: {{objective}}
created by: {{created_by}}
updated: {{updated_at}}
-Keep working autonomously while this goal is active. Treat ordinary choices, confirmations, and recoverable external gates as yours to resolve safely within the user's scope; do not hand them back to the user. A `response` call is only an intermediate update and will not end the run. Call `update_goal` with `status="complete"` once you judge the objective achieved. Call `update_goal` with `status="blocked"` only after retrying viable alternatives and no safe, in-scope action can continue without unavailable information or an external-state change.
+Keep working autonomously while this goal is active. Treat ordinary choices, confirmations, and recoverable external gates as yours to resolve safely within the user's scope; do not hand them back to the user. A `response` call is only an intermediate update and will not end the run. Call `goal` with `action="update"` and `status="complete"` once you judge the objective achieved. Use `status="blocked"` only after retrying viable alternatives and no safe, in-scope action can continue without unavailable information or an external-state change.
diff --git a/plugins/_goal/prompts/agent.system.tool.create_goal.md b/plugins/_goal/prompts/agent.system.tool.create_goal.md
deleted file mode 100644
index 38919d228..000000000
--- a/plugins/_goal/prompts/agent.system.tool.create_goal.md
+++ /dev/null
@@ -1,23 +0,0 @@
-### create_goal
-Create or replace the current chat goal.
-
-Use only when the user asks for a goal, asks you to manage a goal, or `/goal auto` asks you to create one.
-
-Args: `objective`, optional `token_budget`.
-
-Rules:
-- Create one concise objective that describes the current work, not a generic plan.
-- The new goal becomes active.
-- Do not create goals for casual replies or ordinary one-shot answers.
-
-Example:
-~~~json
-{
- "thoughts": ["The user asked me to manage this task as a goal."],
- "headline": "Creating goal",
- "tool_name": "create_goal",
- "tool_args": {
- "objective": "Add the built-in goal plugin with a Web UI strip and slash command"
- }
-}
-~~~
diff --git a/plugins/_goal/prompts/agent.system.tool.get_goal.md b/plugins/_goal/prompts/agent.system.tool.get_goal.md
deleted file mode 100644
index e178111af..000000000
--- a/plugins/_goal/prompts/agent.system.tool.get_goal.md
+++ /dev/null
@@ -1,10 +0,0 @@
-### get_goal
-Inspect the current chat goal.
-
-Use this when the user asks about the goal, asks you to manage a goal, or you need to check whether a goal already exists before creating one.
-
-Args: none.
-
-Rules:
-- Do not invent a goal if none exists.
-- If a goal is paused, complete, or blocked, treat it as state to report unless the user asks you to resume or replace it.
diff --git a/plugins/_goal/prompts/agent.system.tool.goal.md b/plugins/_goal/prompts/agent.system.tool.goal.md
new file mode 100644
index 000000000..7a4ff265b
--- /dev/null
+++ b/plugins/_goal/prompts/agent.system.tool.goal.md
@@ -0,0 +1,24 @@
+### goal
+Inspect, create, or finish the current chat goal.
+
+Use this only when the user asks for a goal or asks you to manage one. Do not create goals for casual replies or ordinary one-shot answers.
+
+Actions:
+- `get`: inspect the current goal; use this before creating one when its state is unknown.
+- `create`: make the given concise `objective` active; optional positive `token_budget`.
+- `update`: mark the current goal with `status` `complete` or `blocked`; optional revised `objective` and `note`.
+
+Pause, resume, edit, and delete are user controls. Mark `complete` only after achieving the objective; mark `blocked` only after viable alternatives are exhausted and work cannot continue without user input or an external-state change.
+
+Example:
+~~~json
+{
+ "thoughts": ["The user asked me to manage this task as a goal."],
+ "headline": "Creating goal",
+ "tool_name": "goal",
+ "tool_args": {
+ "action": "create",
+ "objective": "Add the built-in goal plugin with a Web UI strip and slash command"
+ }
+}
+~~~
diff --git a/plugins/_goal/prompts/agent.system.tool.update_goal.md b/plugins/_goal/prompts/agent.system.tool.update_goal.md
deleted file mode 100644
index 60c25deef..000000000
--- a/plugins/_goal/prompts/agent.system.tool.update_goal.md
+++ /dev/null
@@ -1,11 +0,0 @@
-### update_goal
-Mark the current chat goal complete or blocked.
-
-Use when the active goal is actually achieved, or when progress is genuinely blocked by missing user input or an external-state change.
-
-Args: `status` (`complete` or `blocked`), optional `objective`, optional `note`.
-
-Rules:
-- Mark `complete` only when the objective has been achieved.
-- Mark `blocked` only when meaningful progress cannot continue without user input or an external-state change.
-- Pause, resume, edit, and delete are user controls; do not claim to perform them with this tool.
diff --git a/plugins/_goal/tests/test_goal_plugin.py b/plugins/_goal/tests/test_goal_plugin.py
index c412665bf..bfae7a43f 100644
--- a/plugins/_goal/tests/test_goal_plugin.py
+++ b/plugins/_goal/tests/test_goal_plugin.py
@@ -6,20 +6,18 @@ from types import SimpleNamespace
import pytest
from helpers import files
-from plugins._goal.api.goal import Goal
+from plugins._goal.api.goal import Goal as GoalApi
from plugins._goal.commands import goal_command
-from plugins._goal.helpers import goals
-from plugins._goal.tools.create_goal import CreateGoal
-from plugins._goal.tools.get_goal import GetGoal
+from plugins._goal.tools import goal
+from plugins._goal.tools.goal import GoalTool
from plugins._goal.tools.response import ResponseTool
-from plugins._goal.tools.update_goal import UpdateGoal
@pytest.fixture()
def context_id():
context_id = f"goal-test-{uuid.uuid4().hex}"
yield context_id
- goals.delete_goal(context_id)
+ goal.delete_goal(context_id)
def _payload(context_id: str, command_text: str) -> dict:
@@ -32,47 +30,47 @@ def _payload(context_id: str, command_text: str) -> dict:
def test_goal_storage_round_trip(context_id: str):
- goal = goals.create_goal(context_id, "Ship the goal plugin", token_budget=1200)
+ current_goal = goal.create_goal(context_id, "Ship the goal plugin", token_budget=1200)
- loaded = goals.get_goal(context_id)
- assert loaded == goal
+ loaded = goal.get_goal(context_id)
+ assert loaded == current_goal
assert loaded["status"] == "active"
assert loaded["token_budget"] == 1200
assert loaded["active_since"]
assert loaded["elapsed_seconds"] == 0
- updated = goals.update_goal(context_id, status="paused", objective="Polish the goal strip")
+ updated = goal.update_goal(context_id, status="paused", objective="Polish the goal strip")
assert updated["status"] == "paused"
assert updated["objective"] == "Polish the goal strip"
assert updated["active_since"] == ""
paused_seconds = updated["elapsed_seconds"]
- resumed = goals.update_goal(context_id, status="active")
+ resumed = goal.update_goal(context_id, status="active")
assert resumed["status"] == "active"
assert resumed["active_since"]
assert resumed["elapsed_seconds"] == paused_seconds
- goals.delete_goal(context_id)
- assert goals.get_goal(context_id) is None
+ goal.delete_goal(context_id)
+ assert goal.get_goal(context_id) is None
def test_goal_command_sets_pauses_resumes_and_deletes(context_id: str):
created = goal_command.run(_payload(context_id, "/goal Add current goal support"))
assert created["effects"][0]["message"] == "Goal set."
assert created["effects"][2] == {"type": "send_message", "text": "Add current goal support"}
- assert goals.get_goal(context_id)["objective"] == "Add current goal support"
+ assert goal.get_goal(context_id)["objective"] == "Add current goal support"
paused = goal_command.run(_payload(context_id, "/goal pause"))
assert paused["effects"][0]["message"] == "Goal paused."
- assert goals.get_goal(context_id)["status"] == "paused"
+ assert goal.get_goal(context_id)["status"] == "paused"
resumed = goal_command.run(_payload(context_id, "/goal resume"))
assert resumed["effects"][0]["message"] == "Goal resumed."
- assert goals.get_goal(context_id)["status"] == "active"
+ assert goal.get_goal(context_id)["status"] == "active"
deleted = goal_command.run(_payload(context_id, "/goal delete"))
assert deleted["effects"][0]["message"] == "Goal deleted."
- assert goals.get_goal(context_id) is None
+ assert goal.get_goal(context_id) is None
def test_goal_auto_fills_prompt(context_id: str):
@@ -84,12 +82,12 @@ def test_goal_auto_fills_prompt(context_id: str):
def test_goal_files_stay_under_user_plugin_state(context_id: str):
- goals.create_goal(context_id, "Keep state in usr")
+ goal.create_goal(context_id, "Keep state in usr")
goal_path = files.get_abs_path(
files.USER_DIR,
files.PLUGINS_DIR,
- goals.PLUGIN_NAME,
- goals.GOALS_DIR,
+ goal.PLUGIN_NAME,
+ goal.GOALS_DIR,
f"{context_id}.json",
)
@@ -98,7 +96,7 @@ def test_goal_files_stay_under_user_plugin_state(context_id: str):
@pytest.mark.asyncio
async def test_goal_api_and_agent_tools(context_id: str):
- handler = object.__new__(Goal)
+ handler = object.__new__(GoalApi)
created = await handler.process(
{
"action": "set",
@@ -111,18 +109,18 @@ async def test_goal_api_and_agent_tools(context_id: str):
assert created["goal"]["objective"] == "Exercise API path"
fake_agent = SimpleNamespace(context=SimpleNamespace(id=context_id))
- get_tool = GetGoal(fake_agent, "get_goal", None, {}, "", None)
+ get_tool = GoalTool(fake_agent, "goal", None, {}, "", None)
get_response = await get_tool.execute()
assert "Exercise API path" in get_response.message
- update_tool = UpdateGoal(fake_agent, "update_goal", None, {}, "", None)
- update_response = await update_tool.execute(status="complete")
+ update_tool = GoalTool(fake_agent, "goal", None, {}, "", None)
+ update_response = await update_tool.execute(action="update", status="complete")
assert "Status: complete" in update_response.message
- create_tool = CreateGoal(fake_agent, "create_goal", None, {}, "", None)
- create_response = await create_tool.execute(objective="Exercise tool path")
+ create_tool = GoalTool(fake_agent, "goal", None, {}, "", None)
+ create_response = await create_tool.execute(action="create", objective="Exercise tool path")
assert "Goal created: Exercise tool path" == create_response.message
- assert goals.get_goal(context_id)["created_by"] == "model"
+ assert goal.get_goal(context_id)["created_by"] == "model"
@pytest.mark.parametrize("terminal_status", ["blocked", "complete"])
@@ -131,10 +129,10 @@ async def test_editing_terminal_goal_requests_agent_reactivation(
context_id: str,
terminal_status: str,
):
- goals.create_goal(context_id, "Initial goal")
- goals.update_goal(context_id, status=terminal_status)
+ goal.create_goal(context_id, "Initial goal")
+ goal.update_goal(context_id, status=terminal_status)
- response = await object.__new__(Goal).process(
+ response = await object.__new__(GoalApi).process(
{
"action": "update",
"context_id": context_id,
@@ -151,7 +149,7 @@ async def test_editing_terminal_goal_requests_agent_reactivation(
@pytest.mark.asyncio
async def test_active_goal_keeps_response_tool_running(context_id: str):
- goals.create_goal(context_id, "Keep going")
+ goal.create_goal(context_id, "Keep going")
recorded = []
fake_agent = SimpleNamespace(
context=SimpleNamespace(id=context_id),
@@ -178,7 +176,7 @@ async def test_active_goal_keeps_response_tool_running(context_id: str):
)
]
- goals.update_goal(context_id, status="complete")
+ goal.update_goal(context_id, status="complete")
response = await tool.execute()
assert response.break_loop is True
assert response.message == "Can you decide?"
diff --git a/plugins/_goal/tools/create_goal.py b/plugins/_goal/tools/create_goal.py
deleted file mode 100644
index 4853ce4fc..000000000
--- a/plugins/_goal/tools/create_goal.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from __future__ import annotations
-
-from helpers.tool import Response, Tool
-from plugins._goal.helpers import goals
-
-
-class CreateGoal(Tool):
- async def execute(
- self,
- objective: str = "",
- token_budget: int | None = None,
- **kwargs,
- ) -> Response:
- goal = goals.create_goal(
- self.agent.context.id,
- objective,
- created_by="model",
- token_budget=token_budget,
- )
- return Response(
- message=f"Goal created: {goal['objective']}",
- break_loop=False,
- )
diff --git a/plugins/_goal/tools/get_goal.py b/plugins/_goal/tools/get_goal.py
deleted file mode 100644
index 8c81f0236..000000000
--- a/plugins/_goal/tools/get_goal.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from __future__ import annotations
-
-from helpers.tool import Response, Tool
-from plugins._goal.helpers import goals
-
-
-class GetGoal(Tool):
- async def execute(self, **kwargs) -> Response:
- goal = goals.get_goal(self.agent.context.id)
- return Response(message=goals.summarize_goal(goal), break_loop=False)
diff --git a/plugins/_goal/helpers/goals.py b/plugins/_goal/tools/goal.py
similarity index 62%
rename from plugins/_goal/helpers/goals.py
rename to plugins/_goal/tools/goal.py
index 840358de8..9a5f14d14 100644
--- a/plugins/_goal/helpers/goals.py
+++ b/plugins/_goal/tools/goal.py
@@ -7,6 +7,7 @@ from pathlib import Path
from typing import Any
from helpers import files
+from helpers.tool import Response, Tool
PLUGIN_NAME = "_goal"
@@ -16,6 +17,55 @@ FINAL_STATUSES = {"complete", "blocked"}
VALID_STATUSES = ACTIVE_STATUSES | FINAL_STATUSES
+class GoalTool(Tool):
+ async def execute(
+ self,
+ action: str = "",
+ objective: str = "",
+ status: str = "",
+ note: str = "",
+ token_budget: int | None = None,
+ **kwargs,
+ ) -> Response:
+ action = str(action or self.args.get("action") or "get").strip().lower()
+ context_id = self.agent.context.id
+
+ try:
+ if action in {"get", "show", "status"}:
+ return Response(message=summarize_goal(get_goal(context_id)), break_loop=False)
+ if action in {"create", "set"}:
+ goal = create_goal(
+ context_id,
+ objective,
+ created_by="model",
+ token_budget=token_budget,
+ )
+ return Response(message=f"Goal created: {goal['objective']}", break_loop=False)
+ if action in {"complete", "blocked"}:
+ status = action
+ if action in {"update", "complete", "blocked"}:
+ status = str(status).strip().lower()
+ if status not in FINAL_STATUSES:
+ return Response(
+ message="Model-managed goal updates may only mark goals complete or blocked.",
+ break_loop=False,
+ )
+ goal = update_goal(
+ context_id,
+ status=status,
+ objective=objective or None,
+ note=note or None,
+ )
+ return Response(message=summarize_goal(goal), break_loop=False)
+ except (FileNotFoundError, ValueError) as error:
+ return Response(message=str(error), break_loop=False)
+
+ return Response(
+ message="Unknown goal action. Supported actions: get, create, update.",
+ break_loop=False,
+ )
+
+
def get_goal(context_id: str) -> dict[str, Any] | None:
context_id = _require_context_id(context_id)
path = _goal_path(context_id)
@@ -30,31 +80,7 @@ def get_goal(context_id: str) -> dict[str, Any] | None:
return None
goal = _normalize_goal(raw, context_id=context_id)
- if not goal.get("objective"):
- return None
- return goal
-
-
-def list_goals() -> list[dict[str, Any]]:
- directory = _goals_dir()
- if not Path(directory).is_dir():
- return []
-
- goals: list[dict[str, Any]] = []
- for goal_file in sorted(Path(directory).glob("*.json")):
- try:
- raw = json.loads(files.read_file(str(goal_file)))
- except (OSError, json.JSONDecodeError):
- continue
- if not isinstance(raw, dict):
- continue
- context_id = str(raw.get("context_id") or "").strip()
- if not context_id:
- continue
- goal = _normalize_goal(raw, context_id=context_id)
- if goal.get("objective"):
- goals.append(goal)
- return goals
+ return goal if goal.get("objective") else None
def create_goal(
@@ -101,17 +127,11 @@ def update_goal(
raise FileNotFoundError("Goal not found")
if objective is not None:
- cleaned_objective = _clean_objective(objective)
- if not cleaned_objective:
- raise ValueError("Goal objective is required")
- goal["objective"] = cleaned_objective
-
+ goal["objective"] = _required_objective(objective)
if status is not None:
_apply_status(goal, _normalize_status(status))
-
if note is not None:
goal["note"] = str(note or "").strip()
-
if token_budget is not None:
goal["token_budget"] = _clean_token_budget(token_budget)
@@ -121,8 +141,7 @@ def update_goal(
def delete_goal(context_id: str) -> None:
- context_id = _require_context_id(context_id)
- files.delete_file(_goal_path(context_id))
+ files.delete_file(_goal_path(_require_context_id(context_id)))
def public_goal(goal: dict[str, Any] | None) -> dict[str, Any] | None:
@@ -146,15 +165,14 @@ def summarize_goal(goal: dict[str, Any] | None) -> str:
if not goal:
return "No goal is set for this chat."
- status = str(goal.get("status") or "active")
- objective = str(goal.get("objective") or "").strip()
- elapsed = _format_elapsed(_elapsed_seconds(goal))
- updated = str(goal.get("updated_at") or "").strip()
- lines = [f"Status: {status}", f"Goal: {objective}", f"Active time: {elapsed}"]
- if updated:
+ lines = [
+ f"Status: {goal.get('status') or 'active'}",
+ f"Goal: {str(goal.get('objective') or '').strip()}",
+ f"Active time: {_format_elapsed(_elapsed_seconds(goal))}",
+ ]
+ if updated := str(goal.get("updated_at") or "").strip():
lines.append(f"Updated: {updated}")
- note = str(goal.get("note") or "").strip()
- if note:
+ if note := str(goal.get("note") or "").strip():
lines.append(f"Note: {note}")
return "\n".join(lines)
@@ -168,9 +186,7 @@ def _write_goal(goal: dict[str, Any]) -> None:
def _normalize_goal(raw: dict[str, Any], *, context_id: str) -> dict[str, Any]:
status = str(raw.get("status") or "active").strip().lower()
- if status not in VALID_STATUSES:
- status = "active"
-
+ status = status if status in VALID_STATUSES else "active"
created_at = str(raw.get("created_at") or "")
updated_at = str(raw.get("updated_at") or "")
active_since = str(raw.get("active_since") or "")
@@ -194,12 +210,12 @@ def _normalize_goal(raw: dict[str, Any], *, context_id: str) -> dict[str, Any]:
}
-def _goals_dir() -> str:
- return files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR, PLUGIN_NAME, GOALS_DIR)
-
-
def _goal_path(context_id: str) -> str:
- return files.get_abs_path(_goals_dir(), f"{_safe_context_id(context_id)}.json")
+ directory = files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR, PLUGIN_NAME, GOALS_DIR)
+ safe = re.sub(r"[^A-Za-z0-9_.-]+", "_", context_id).strip("._")[:180]
+ if not safe:
+ raise ValueError("A chat context is required")
+ return files.get_abs_path(directory, f"{safe}.json")
def _require_context_id(context_id: str) -> str:
@@ -209,37 +225,35 @@ def _require_context_id(context_id: str) -> str:
return context_id
-def _safe_context_id(context_id: str) -> str:
- safe = re.sub(r"[^A-Za-z0-9_.-]+", "_", context_id).strip("._")
- if not safe:
- raise ValueError("A chat context is required")
- return safe[:180]
+def _required_objective(value: str) -> str:
+ objective = _clean_objective(value)
+ if not objective:
+ raise ValueError("Goal objective is required")
+ return objective
-def _clean_objective(objective: str) -> str:
- return re.sub(r"\s+", " ", str(objective or "")).strip()
+def _clean_objective(value: str) -> str:
+ return re.sub(r"\s+", " ", str(value or "")).strip()
def _normalize_status(status: str) -> str:
- cleaned = str(status or "").strip().lower()
- if cleaned not in VALID_STATUSES:
+ status = str(status or "").strip().lower()
+ if status not in VALID_STATUSES:
raise ValueError("Goal status must be active, paused, complete, or blocked")
- return cleaned
+ return status
def _clean_created_by(created_by: str) -> str:
- cleaned = str(created_by or "").strip().lower()
- return cleaned if cleaned in {"user", "model"} else "user"
+ created_by = str(created_by or "").strip().lower()
+ return created_by if created_by in {"user", "model"} else "user"
def _clean_token_budget(token_budget: Any) -> int | None:
- if token_budget in (None, ""):
- return None
try:
- value = int(token_budget)
+ token_budget = int(token_budget)
except (TypeError, ValueError):
return None
- return value if value > 0 else None
+ return token_budget if token_budget > 0 else None
def _apply_status(goal: dict[str, Any], status: str) -> None:
@@ -253,51 +267,41 @@ def _apply_status(goal: dict[str, Any], status: str) -> None:
def _elapsed_seconds(goal: dict[str, Any]) -> int:
- seconds = _clean_elapsed_seconds(goal.get("elapsed_seconds"))
+ elapsed = _clean_elapsed_seconds(goal.get("elapsed_seconds"))
if str(goal.get("status") or "active") == "active":
- seconds += _seconds_between(str(goal.get("active_since") or ""), _now())
- return seconds
+ elapsed += _seconds_between(str(goal.get("active_since") or ""), _now())
+ return elapsed
def _clean_elapsed_seconds(value: Any) -> int:
try:
- seconds = int(value)
+ return max(0, int(value))
except (TypeError, ValueError):
return 0
- return max(0, seconds)
def _seconds_between(start: str, end: str) -> int:
- start_dt = _parse_time(start)
- end_dt = _parse_time(end)
- if not start_dt or not end_dt:
- return 0
- return max(0, int((end_dt - start_dt).total_seconds()))
+ start_dt, end_dt = _parse_time(start), _parse_time(end)
+ return max(0, int((end_dt - start_dt).total_seconds())) if start_dt and end_dt else 0
def _parse_time(value: str) -> datetime | None:
- text = str(value or "").strip()
- if not text:
+ value = str(value or "").strip()
+ if not value:
return None
- if text.endswith("Z"):
- text = f"{text[:-1]}+00:00"
+ if value.endswith("Z"):
+ value = f"{value[:-1]}+00:00"
try:
- parsed = datetime.fromisoformat(text)
+ parsed = datetime.fromisoformat(value)
except ValueError:
return None
- if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
- return parsed.astimezone(timezone.utc)
+ return parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parsed.astimezone(timezone.utc)
def _format_elapsed(seconds: int) -> str:
hours, remainder = divmod(max(0, int(seconds)), 3600)
minutes, seconds = divmod(remainder, 60)
- if hours:
- return f"{hours}h {minutes}m"
- if minutes:
- return f"{minutes}m {seconds}s"
- return f"{seconds}s"
+ return f"{hours}h {minutes}m" if hours else f"{minutes}m {seconds}s" if minutes else f"{seconds}s"
def _now() -> str:
diff --git a/plugins/_goal/tools/response.py b/plugins/_goal/tools/response.py
index 0ecb0ed5e..1ebff61a2 100644
--- a/plugins/_goal/tools/response.py
+++ b/plugins/_goal/tools/response.py
@@ -1,9 +1,10 @@
from __future__ import annotations
from helpers.tool import Response
-from plugins._goal.helpers import goals
from tools import response as core_response
+from plugins._goal.tools import goal
+
_CONTINUE_MARKER = "_goal_continue"
@@ -11,14 +12,14 @@ _CONTINUE_MARKER = "_goal_continue"
class ResponseTool(core_response.ResponseTool):
async def execute(self, **kwargs) -> Response:
response = await super().execute(**kwargs)
- goal = goals.get_goal(self.agent.context.id)
- if not goal or goal.get("status") != "active":
+ current_goal = goal.get_goal(self.agent.context.id)
+ if not current_goal or current_goal.get("status") != "active":
return response
response.break_loop = False
response.message = (
"Goal still active. Continue working autonomously and make safe, in-scope "
- "choices yourself. Call update_goal complete when satisfied, or blocked only "
+ "choices yourself. Call goal update complete when satisfied, or blocked only "
"when no viable in-scope path remains."
)
response.additional = {**(response.additional or {}), _CONTINUE_MARKER: True}
diff --git a/plugins/_goal/tools/update_goal.py b/plugins/_goal/tools/update_goal.py
deleted file mode 100644
index 7caac0b5c..000000000
--- a/plugins/_goal/tools/update_goal.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from __future__ import annotations
-
-from helpers.tool import Response, Tool
-from plugins._goal.helpers import goals
-
-
-class UpdateGoal(Tool):
- async def execute(
- self,
- status: str = "",
- objective: str = "",
- note: str = "",
- **kwargs,
- ) -> Response:
- normalized_status = str(status or "").strip().lower()
- if normalized_status not in {"complete", "blocked"}:
- return Response(
- message="Model-managed goal updates may only mark goals complete or blocked.",
- break_loop=False,
- )
-
- goal = goals.update_goal(
- self.agent.context.id,
- status=normalized_status,
- objective=objective if objective else None,
- note=note if note else None,
- )
- return Response(
- message=goals.summarize_goal(goal),
- break_loop=False,
- )