Skip to content

Agent Zero AI framework

Keep goals active and resolve trailing slash commands

Alessandro22e76197196a
diff --git a/plugins/_commands/AGENTS.md b/plugins/_commands/AGENTS.md
index 05d0e992a..061f2ce02 100644
--- a/plugins/_commands/AGENTS.md
+++ b/plugins/_commands/AGENTS.md
@@ -12,7 +12,7 @@
- `api/commands.py` owns the Commands API actions used by the WebUI.
- `webui/` owns the manager/editor modal stores, HTML surfaces, and thumbnail asset.
- `commands/` owns bundled read-only slash command definitions shipped by `_commands`.
-- `extensions/` owns the chat composer slash picker.
+- `extensions/` owns the chat composer slash picker and incoming-message command resolution.
- `extensions/python/startup_migration/` owns one-time migration from the legacy community `commands` plugin namespace.
- `skills/commands-create-slash-command/` owns the agent-facing authoring workflow for reusable slash commands.
- `tests/` owns regression coverage for parsing, CRUD, scope precedence, plugin-distributed commands, legacy migration, and skill discovery.
@@ -30,6 +30,8 @@
- On startup, `_commands` copies legacy `usr/plugins/commands` command and skill files into `usr/plugins/_commands` without overwriting existing files, copies scoped legacy command folders to `_commands`, and disables the legacy `commands` plugin roots to prevent duplicate WebUI popovers.
- Script commands must expose `run(payload)` and return a string or a dict with `text` and optional `effects`; `show_markdown` effects render as auto-dismissing toast notifications.
- Script commands may emit `send_message` with `text` to submit the rendered composer text immediately after command resolution.
+- Commands accept prefix syntax (`/goal objective`) and exact postfix syntax (`objective /goal`); ordinary mid-sentence mentions are not invocations.
+- WebUI sends resolve through the picker effect path, while backend-originated messages resolve before reaching the agent.
- Built-in `/computer-use on|off` emits a bounded `computer_use` effect. A
Launcher-owned WebUI applies it to that tab's Host access lease; an ordinary
WebUI directs the user to run the same command in A0 CLI.
diff --git a/plugins/_commands/README.md b/plugins/_commands/README.md
index 68e16352a..8d66cdd32 100644
--- a/plugins/_commands/README.md
+++ b/plugins/_commands/README.md
@@ -7,7 +7,7 @@ This plugin lets you define reusable `/commands` as `.command.yaml` files with e
- a `.txt` template body
- a `.py` script hook
-Commands are managed from the plugin modal and can be inserted directly from the chat composer when the first token starts with `/`.
+Commands are managed from the plugin modal and can be inserted directly from the chat composer with prefix syntax (`/goal objective`) or an exact trailing command (`objective /goal`).
## Features
@@ -15,6 +15,7 @@ Commands are managed from the plugin modal and can be inserted directly from the
- Text template commands with `{}` placeholders and parsed args
- Python hook commands with parsed args and optional chat history payload
- Unified parser for positional args, free-form tail, and flags
+- Prefix and postfix command resolution for WebUI and remote/AI-sent messages
- Scope-aware command resolution across project and global scopes
- Built-in A0 CLI connector command pack for common session, queue, model, project, browser, and connector status commands
- Slash picker in the chat composer with keyboard navigation and create-on-empty flow
@@ -75,6 +76,7 @@ def run(payload):
The parser supports:
- Positional input: `/scan https://github.com/org/repo`
+- Postfix input: `https://github.com/org/repo /scan`
- Long flags: `/scan --git-url https://github.com/org/repo`
- Long flags with equals: `/scan --git-url=https://github.com/org/repo`
- Short flags and bundles: `/scan -v -q` or `/scan -vq`
@@ -138,7 +140,7 @@ When the built-in `_commands` plugin starts, it migrates files from the older co
## UI Surfaces
- Plugin modal: manage project/global commands and create editable same-name overrides of bundled commands
-- Chat composer: type `/` at the start of the inline input to browse commands
+- Chat composer: type `/` at the start or as the final token to browse commands
## Agent Skill
diff --git a/plugins/_commands/extensions/python/_functions/agent/AgentContext/_process_chain/start/_10_resolve_slash_command.py b/plugins/_commands/extensions/python/_functions/agent/AgentContext/_process_chain/start/_10_resolve_slash_command.py
new file mode 100644
index 000000000..a0197b55b
--- /dev/null
+++ b/plugins/_commands/extensions/python/_functions/agent/AgentContext/_process_chain/start/_10_resolve_slash_command.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+from typing import Any
+
+from helpers.extension import Extension
+from plugins._commands.helpers import commands
+
+
+class ResolveSlashCommand(Extension):
+ async def execute(self, data: dict[str, Any] | None = None, **kwargs: Any) -> None:
+ if not isinstance(data, dict):
+ return
+
+ args = data.get("args")
+ if not isinstance(args, tuple) or len(args) < 3:
+ return
+
+ context, message = args[0], args[2]
+ raw_message = getattr(message, "message", None)
+ if not isinstance(raw_message, str):
+ return
+
+ resolution = await commands.resolve_message_command(
+ raw_message,
+ context_id=str(getattr(context, "id", "") or ""),
+ )
+ if not resolution:
+ return
+
+ result = resolution.get("result") or {}
+ next_text = str(result.get("text") or "")
+ notes: list[str] = []
+ unsupported = False
+
+ for effect in result.get("effects") or []:
+ if not isinstance(effect, dict):
+ continue
+ effect_type = str(effect.get("type") or "").strip().lower()
+ if effect_type == "replace_input":
+ next_text = str(effect.get("text") or "")
+ elif effect_type == "append_input":
+ chunk = str(effect.get("text") or "")
+ next_text = f"{next_text}\n{chunk}" if next_text else chunk
+ elif effect_type == "send_message":
+ next_text = str(effect.get("text") or next_text)
+ elif effect_type == "toast":
+ notes.append(str(effect.get("message") or ""))
+ elif effect_type == "show_markdown":
+ notes.append(str(effect.get("content") or ""))
+ elif effect_type != "goal_changed":
+ unsupported = True
+
+ command_name = str((resolution.get("command") or {}).get("name") or "command")
+ if unsupported:
+ data["result"] = f"/{command_name} requires the WebUI."
+ elif next_text.strip():
+ message.message = next_text
+ else:
+ data["result"] = "\n\n".join(note for note in notes if note) or f"/{command_name} complete."
diff --git a/plugins/_commands/extensions/webui/send_message_before/_10_resolve_slash_command.js b/plugins/_commands/extensions/webui/send_message_before/_10_resolve_slash_command.js
new file mode 100644
index 000000000..a13fa77d6
--- /dev/null
+++ b/plugins/_commands/extensions/webui/send_message_before/_10_resolve_slash_command.js
@@ -0,0 +1,5 @@
+import { store } from "/plugins/_commands/webui/commands-slash-store.js";
+
+export default async function resolveSlashCommand(sendCtx) {
+ await store.resolveBeforeSend(sendCtx);
+}
diff --git a/plugins/_commands/helpers/commands.py b/plugins/_commands/helpers/commands.py
index 1c3b95e30..c5068ec3c 100644
--- a/plugins/_commands/helpers/commands.py
+++ b/plugins/_commands/helpers/commands.py
@@ -91,12 +91,23 @@ def parse_slash_invocation(raw_message: str, *, fallback_command: str = "") -> d
"""
text = (raw_message or "").strip()
slash_match = re.match(r"^/([^\s]+)(?:\s+([\s\S]*))?$", text)
+ postfix_match = (
+ None
+ if slash_match
+ else re.match(r"^([\s\S]*\S)\s+/([^\s]+)\s*$", text)
+ )
if slash_match:
try:
command_name = sanitize_command_name(slash_match.group(1))
except ValueError:
command_name = sanitize_command_name(fallback_command) if fallback_command else ""
raw_arguments = (slash_match.group(2) or "").strip()
+ elif postfix_match:
+ try:
+ command_name = sanitize_command_name(postfix_match.group(2))
+ except ValueError:
+ command_name = sanitize_command_name(fallback_command) if fallback_command else ""
+ raw_arguments = postfix_match.group(1).strip()
else:
command_name = sanitize_command_name(fallback_command) if fallback_command else ""
raw_arguments = text
@@ -566,6 +577,31 @@ async def resolve_command_invocation(
}
+async def resolve_message_command(
+ raw_message: str,
+ *,
+ context_id: str = "",
+) -> dict[str, Any] | None:
+ """Resolve a known prefix or postfix slash command from an incoming message."""
+ invocation = parse_slash_invocation(raw_message)
+ command_name = invocation["command_name"]
+ if not command_name:
+ return None
+
+ project_name = get_context_scope(context_id)["project_name"]
+ effective, _ = list_effective_commands(project_name)
+ command = next((item for item in effective if item["name"] == command_name), None)
+ if not command:
+ return None
+
+ return await resolve_command_invocation(
+ path=command["path"],
+ slash_text=raw_message,
+ project_name=project_name,
+ context_id=context_id,
+ )
+
+
def _build_command_config(
*,
name: str,
diff --git a/plugins/_commands/tests/test_commands_plugin.py b/plugins/_commands/tests/test_commands_plugin.py
index 037f9d5fe..a1799149b 100644
--- a/plugins/_commands/tests/test_commands_plugin.py
+++ b/plugins/_commands/tests/test_commands_plugin.py
@@ -5,6 +5,7 @@ import uuid
from dataclasses import dataclass, field
from pathlib import Path
import sys
+from types import SimpleNamespace
import pytest
from flask import Flask
@@ -18,6 +19,9 @@ from helpers import files, projects, skills as skills_helper
from initialize import initialize_agent
from plugins._commands.api.commands import Commands
from plugins._commands.commands import connector_commands
+from plugins._commands.extensions.python._functions.agent.AgentContext._process_chain.start._10_resolve_slash_command import (
+ ResolveSlashCommand,
+)
from plugins._commands.helpers import commands as commands_helper
@@ -148,6 +152,36 @@ def test_parse_arguments_and_render_template_support_flags() -> None:
invalid_invocation = commands_helper.parse_slash_invocation("/?")
assert invalid_invocation["command_name"] == ""
+ postfix_invocation = commands_helper.parse_slash_invocation(
+ "Make goal execution tenacious\n/goal"
+ )
+ assert postfix_invocation["command_name"] == "goal"
+ assert postfix_invocation["raw_arguments"] == "Make goal execution tenacious"
+
+
+async def test_incoming_postfix_command_is_resolved_before_the_agent(
+ scope_fixture: ScopeFixture,
+) -> None:
+ command = _save_command(
+ scope_fixture,
+ name=f"Resolve {scope_fixture.prefix}",
+ description="Resolve a postfix command.",
+ body="Resolved: {raw}",
+ )
+ message = SimpleNamespace(message=f"from an AI /{command['name']}")
+ data = {
+ "args": (
+ SimpleNamespace(id=f"missing-{uuid.uuid4().hex}"),
+ None,
+ message,
+ )
+ }
+
+ await ResolveSlashCommand(agent=None).execute(data=data)
+
+ assert message.message == "Resolved: from an AI"
+
def test_list_effective_commands_project_overrides_global(
scope_fixture: ScopeFixture,
diff --git a/plugins/_commands/webui/commands-slash-store.js b/plugins/_commands/webui/commands-slash-store.js
index 89e8920b9..b33e945ef 100644
--- a/plugins/_commands/webui/commands-slash-store.js
+++ b/plugins/_commands/webui/commands-slash-store.js
@@ -24,8 +24,11 @@ function sanitizeCommandName(rawName) {
function parseSlashInput(message) {
const text = String(message || "");
- const match = text.match(/^\s*\/([^\s]*)(?:\s+([\s\S]*))?$/);
- if (!match) {
+ const prefixMatch = text.match(/^\s*\/([^\s]*)(?:\s+([\s\S]*))?$/);
+ const postfixMatch = prefixMatch
+ ? null
+ : text.match(/^([\s\S]*\S)\s+\/([^\s]*)\s*$/);
+ if (!prefixMatch && !postfixMatch) {
return {
active: false,
query: "",
@@ -36,8 +39,8 @@ function parseSlashInput(message) {
return {
active: true,
- query: (match[1] || "").trim().toLowerCase(),
- rawArguments: match[2] || "",
+ query: (prefixMatch?.[1] || postfixMatch?.[2] || "").trim().toLowerCase(),
+ rawArguments: prefixMatch?.[2] || postfixMatch?.[1]?.trim() || "",
rawMessage: text,
};
}
@@ -251,6 +254,23 @@ const model = {
void this.loadCommands();
},
+ async resolveBeforeSend(sendCtx) {
+ if (!sendCtx || this.applying) return;
+
+ const parsed = parseSlashInput(sendCtx.message);
+ const commandName = sanitizeCommandName(parsed.query);
+ if (!parsed.active || !commandName) return;
+
+ await this.loadCommands();
+ const command = this.commands.find((item) => item.name === commandName);
+ if (!command || !this.getInputElement()) return;
+
+ this.rawMessage = parsed.rawMessage;
+ this.rawArguments = parsed.rawArguments;
+ sendCtx.cancel = true;
+ await this.applySelection(command);
+ },
+
handleKeydown(event) {
const input = this.getInputElement();
if (!this.menuVisible || !input || document.activeElement !== input) return;
diff --git a/plugins/_goal/AGENTS.md b/plugins/_goal/AGENTS.md
index cd797adad..3a9a48c46 100644
--- a/plugins/_goal/AGENTS.md
+++ b/plugins/_goal/AGENTS.md
@@ -13,6 +13,7 @@
- `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/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.
## Local Contracts
@@ -23,6 +24,7 @@
- User controls may pause, resume, edit, or delete a goal; destructive delete uses inline confirmation. Model tools may create goals and mark them complete or blocked.
- `/goal <objective>` creates the goal and sends the objective as the user message so the agent starts working immediately.
- `/goal auto` fills the composer with a prompt asking the agent to create and manage its own goal instead of silently sending a message.
+- While a goal is active, response-tool calls are intermediate updates; only completing or blocking the goal restores normal loop termination.
- Goal UI feedback uses toast notifications and inline controls, not modal dialogs.
## Work Guidance
diff --git a/plugins/_goal/prompts/agent.extras.goal.md b/plugins/_goal/prompts/agent.extras.goal.md
index d1c0f88a7..eb8350f2f 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}}
-Follow this goal while it is active. When the work is complete, call `update_goal` with `status="complete"` before your final answer. If progress is genuinely blocked, call `update_goal` with `status="blocked"` and explain what is missing.
+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.
diff --git a/plugins/_goal/tests/test_goal_plugin.py b/plugins/_goal/tests/test_goal_plugin.py
index 6754f2974..ebf36d859 100644
--- a/plugins/_goal/tests/test_goal_plugin.py
+++ b/plugins/_goal/tests/test_goal_plugin.py
@@ -11,6 +11,7 @@ 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.response import ResponseTool
from plugins._goal.tools.update_goal import UpdateGoal
@@ -122,3 +123,38 @@ async def test_goal_api_and_agent_tools(context_id: str):
create_response = await create_tool.execute(objective="Exercise tool path")
assert "Goal created: Exercise tool path" == create_response.message
assert goals.get_goal(context_id)["created_by"] == "model"
+
+
+async def test_active_goal_keeps_response_tool_running(context_id: str):
+ goals.create_goal(context_id, "Keep going")
+ recorded = []
+ fake_agent = SimpleNamespace(
+ context=SimpleNamespace(id=context_id),
+ hist_add_tool_result=lambda *args, **kwargs: recorded.append((args, kwargs)),
+ )
+ loop_data = SimpleNamespace(params_temporary={})
+ tool = ResponseTool(
+ fake_agent,
+ "response",
+ None,
+ {"text": "Can you decide?"},
+ "",
+ loop_data,
+ )
+
+ response = await tool.execute()
+ assert response.break_loop is False
+ response.additional["_responses_output_item"] = {"type": "function_call_output"}
+ await tool.after_execution(response)
+ assert recorded == [
+ (
+ ("response", response.message),
+ {"_responses_output_item": {"type": "function_call_output"}},
+ )
+ ]
+
+ goals.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/response.py b/plugins/_goal/tools/response.py
new file mode 100644
index 000000000..0ecb0ed5e
--- /dev/null
+++ b/plugins/_goal/tools/response.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from helpers.tool import Response
+from plugins._goal.helpers import goals
+from tools import response as core_response
+
+
+_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":
+ 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 "
+ "when no viable in-scope path remains."
+ )
+ response.additional = {**(response.additional or {}), _CONTINUE_MARKER: True}
+ return response
+
+ async def after_execution(self, response: Response, **kwargs):
+ additional = response.additional or {}
+ if additional.pop(_CONTINUE_MARKER, False):
+ self.agent.hist_add_tool_result(self.name, response.message, **additional)
+ await super().after_execution(response, **kwargs)