Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,38 @@ the start of the entry's title.

### Added

- **`/agent new <type> <objective>`: you start a sub-agent, and its view
opens on its first run.** A type whose `spawnable_by` names `"user"`, in
an app whose policy's `spawn_sources` names it too
(`SubAgentPolicy(spawn_sources={"user"})`), may be started by the user:
`/agent new researcher Find what changed in the 2.0 release.` starts
`researcher-<n>`, its parent the main agent (depth 1, so `max_spawn_depth`
never refuses it), `started_by: user`, its brief the objective (the rest of
the line, as typed), titled with the objective's first line. It is counted
toward no turn's runs, takes a working slot while it works, and an
inheriting type reads the main conversation as the main agent's `task`
would hand it. Its view opens as its run starts and the run streams there,
as a follow-up's does: a line typed steers it, Ctrl+C is your stop (the run
`cancelled`, the sub-agent `stopped`; one pressed before the run started
stops it as it starts, and no view opens), `/back` tells the main agent
once, and, being the main agent's sub-agent, the main agent's
`message_agent` may continue it (when the main agent has the follow-up
tools: `follow_ups`, and a sub-agent it may start or a type agents may
start). A conversation whose only work is a start is stored, titled with
the objective, so `/resume`, `--continue` and `--resume` reach it. In
another sub-agent's view it leaves that one first. A type you cannot start
opens nothing ("You cannot start 'writer' here. Types you can start:
researcher."; "This app lets you start no agent types." when there is
none), and a missing type or objective says
`Usage: /agent new <type> <objective>`. The manager's entry point
(provisional): `start_instance(agent_type, objective)`, a turn of its own
whose first event is the run's start, which names the instance; a refusal
is one `ERROR` ("A new agent needs an objective." for a blank one),
stopping the stream is the user's stop, and `interrupt_instance` ends it as
a process exit does. The app's `start_agent(agent_type, objective)` is what
the command calls; the manager's delegations' `start_by_user`,
`startable_by_user` and `user_start_refused` (provisional) start and refuse
it. On both backends, contract-tested.
- **A skill that starts an agent: the frontmatter key `agent`, on both
backends.** A skill's `SKILL.md` may name one of the app's agent types
at the top of its frontmatter (`agent: researcher`). Where the app
Expand Down
16 changes: 8 additions & 8 deletions CLAUDE.md

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1535,12 +1535,18 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.",
conversation is opened, after a summary and after `/compact`.
- **The user's control.** `/agents` picks a sub-agent and opens its view, as
`/agent <id>` does (next bullet);
`/agent new <type> <objective>` starts a new one of a type the app lets you
start (its `spawnable_by` and the policy's `spawn_sources` both name
`"user"`): its parent is the main agent, its brief the objective (the rest
of the line), and its view opens on its first run, which streams there;
`/agent stop <id>` (its run cancelled by you, `cancelled_by: user`; it is
then `stopped`: its parent's messages are refused, only you can start its
next run) and `/agent close <id>` (it and its own sub-agents). The
manager's entry points (provisional, on the open conversation, any of its
sub-agents): `run_instance(id, message)` (a turn of its own, counted toward
no turn's runs; stopping the stream is your stop of the run),
`start_instance(type, objective)` (your new sub-agent's first run, a turn of
its own as `run_instance`'s, its run's start first),
`interrupt_instance(id)` (that run ends `interrupted`, as at a process
exit, not your stop), `stop_instance(id)`, `close_instance(id)`,
`steer_instance(id, message)`,
Expand Down Expand Up @@ -2406,7 +2412,7 @@ Built-in slash commands available in all apps:
| `/sandbox` | `/sb` | List / reset stateful sandbox sessions |
| `/jobs` | | List and manage long-running background jobs (`/jobs all`, `/jobs <id>`, `/jobs cancel <id>`, `/jobs clean`; `/jobs resume` tells the agent this conversation's finished jobs) |
| `/agents` | | Pick one of this conversation's sub-agents, each under the one that started it: id, type, status (`running`, `idle`, `stopped`, `closed`), title; Enter opens its view (`/agents <id>` shows one instance or run, each run's status and time, the first lines of its result, its error and its tokens by model) |
| `/agent` | | One sub-agent: `/agent <id>` opens its view (a line typed there is its next run, or steers the run that works; `/back` returns), `/agent stop <id>` stops it (its run, if one works; only you can start its next run), `/agent close <id>` closes it and its own sub-agents (no more runs; its work stays readable) |
| `/agent` | | One sub-agent: `/agent <id>` opens its view (a line typed there is its next run, or steers the run that works; `/back` returns), `/agent new <type> <objective>` starts a new one of a type the app lets you start and opens its view on its first run, `/agent stop <id>` stops it (its run, if one works; only you can start its next run), `/agent close <id>` closes it and its own sub-agents (no more runs; its work stays readable) |
| `/papers` | `/docs` | List knowledge-base documents (filter by source, query, --global) |
| `/sessions` | `/sess` | List the saved sessions of every installed backend: backend, title, turns, last update (delete one with `--delete=<id>`; `--backend=<name>` picks one of an id two backends keep); on the memory store it says none are kept |
| `/back` | | Leave a sub-agent's view, back to the main conversation; the main agent is told what you did there |
Expand Down
98 changes: 91 additions & 7 deletions src/agentic_cli/cli/agent_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@
the user's, so the instance stays ``idle``. A closed instance's view is
read-only: no prompt, and a line typed there is refused.

``/agent new <type> <objective>`` starts an instance for the user (the
manager's ``start_instance``: its parent the main agent, ``started_by:
user``) and opens its view once the run's start names it: the run streams
there, in a task the view holds as it holds a follow-up's, so a line typed
steers it, Ctrl+C stops it and ``/back`` tells the main agent of it. In
another view it leaves that one first, as ``/back`` does.

``/back`` leaves: it waits for a run still working, prints ``── back to main
──``, and, when a run the user started there ended since the main agent was
last told, tells the main agent once, in a notice turn (``tell_root`` with
Expand Down Expand Up @@ -97,18 +104,26 @@ class AgentView:
told: The run of the user's whose envelope the main agent knows of
(``instance_result``'s, as the view opened): ``/back`` tells it
only of a later one.
processor: The view's message processor; None: a new one
(``/agent new``'s is the one drawing the instance's first run).
"""

def __init__(
self, app: Any, instance: str, conversation: "SessionRef", told: str | None
self,
app: Any,
instance: str,
conversation: "SessionRef",
told: str | None,
*,
processor: MessageProcessor | None = None,
) -> None:
self.app = app
self.instance = instance
self.conversation = conversation
self.told = told
#: The view's own message processor: its runs' task list is the
#: instance's, never the main agent's task box.
self.processor = MessageProcessor()
self.processor = processor if processor is not None else MessageProcessor()
#: The prompt the app had: put back by ``/back``.
self.prompt_before: Any = None
self._runs: set[asyncio.Task[None]] = set()
Expand Down Expand Up @@ -241,9 +256,14 @@ async def take(self, line: str) -> None:
):
app.session.add_message("system", STEERED.format(instance=self.instance))
return
run = asyncio.create_task(
self.adopt(asyncio.create_task(
self._run(line, self._last), name=f"view run of {self.instance}"
)
))

def adopt(self, run: "asyncio.Task[None]") -> None:
"""Hold ``run``, a task that works for the instance in view: its last,
which a line typed next waits for, stopped by Ctrl+C (``stop``) and
waited for by ``settled``."""
self._last = run
self._runs.add(run)
run.add_done_callback(self._ended)
Expand Down Expand Up @@ -346,14 +366,78 @@ async def open_view(app: Any, instance: str) -> bool:
latest = workflow.instance_result(
instance, session_id=conversation.session_id, user_id=conversation.user_id
)
view = AgentView(app, instance, conversation, told=(latest or {}).get("run"))
_enter(app, AgentView(app, instance, conversation, told=(latest or {}).get("run")), record)
return True


def _enter(app: Any, view: AgentView, record: "InstanceRecord") -> None:
"""Make ``view`` the app's: its rule and recap, its prompt and status bar."""
view.show(record)
view.prompt_before = app.session.message
app._agent_view = view
app._workflow_controller.view_segment = view.status_segment
view.refresh()
logger.info("agent_view_opened", instance=instance)
return True
logger.info("agent_view_opened", instance=view.instance)


async def start_view(app: Any, agent_type: str, objective: str) -> bool:
"""``/agent new <type> <objective>`` (``BaseCLIApp.start_agent``): a new
instance for the user, and its view.

A view open first is left, as ``/back`` leaves it (its run waited for,
the main agent told). The start runs in a task of its own, a write to
the conversation under its turn lock (``ConversationCore.start_instance``)
drawn by a processor of its own; once the run's start names the
instance, its view opens on it, holding that task and that processor,
so the rest of the run streams there as a follow-up's does. This
returns then, or when the start ended without a run (a refusal, said;
a conversation another process has open). Ctrl+C before the view
opened (the command's cancel) stops the run as the view's Ctrl+C does,
and opens none.

Returns:
Whether the new instance's view opened.
"""
if app.agent_view is not None:
await leave_view(app)
processor = MessageProcessor()
opened: asyncio.Future[bool] = asyncio.get_running_loop().create_future()
start: asyncio.Task[None] | None = None

async def opens(instance: str) -> None:
# Called inside the start, once its run's start names the instance.
workflow = app.workflow
conversation = workflow.session_ref(getattr(app, "session_id", None))
record = workflow.agent_runs.instance(conversation, instance)
if record is None or opened.done():
return
view = AgentView(app, instance, conversation, told=None, processor=processor)
assert start is not None
view.adopt(start)
_enter(app, view, record)
opened.set_result(True)

async def run() -> None:
parts = dataclasses.replace(app._turn_parts(), processor=processor)
try:
await app._conversation.start_instance(agent_type, objective, parts, opens=opens)
finally:
if not opened.done():
opened.set_result(False)
view = app.agent_view
if view is not None and view.processor is processor:
view.refresh()

start = asyncio.create_task(run(), name=f"new {agent_type}")
try:
if await asyncio.shield(opened):
return True
except asyncio.CancelledError:
start.cancel()
await asyncio.wait({start})
raise
await start # ended without a run: its failure, if any, is the command's
return False


async def leave_view(app: Any) -> bool:
Expand Down
41 changes: 32 additions & 9 deletions src/agentic_cli/cli/agents_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
its error and its tokens by model.

``/agent <id>`` opens one's view (``cli/agent_view.py``: the user works with
it directly, ``/back`` returns); ``/agent stop <id>`` is the user's stop
of an instance (its run, if one works, cancelled by the user; only the user
may start its next run) and ``/agent close <id>`` the user's close of it and
it directly, ``/back`` returns); ``/agent new <type> <objective>`` starts a
new instance of a type the user may start (its objective the rest of the
line, as typed), whose view opens with its first run; ``/agent stop <id>`` is
the user's stop of an instance (its run, if one works, cancelled by the user;
only the user may start its next run) and ``/agent close <id>`` the user's close of it and
its own sub-agents (no more runs; its work stays readable). Each says what it
did, or why not.

Expand Down Expand Up @@ -70,8 +72,12 @@
#: What ``/agents <id>`` and ``/agent`` say for an id the conversation has no record of.
NO_SUCH_AGENT = "No sub-agent {id} in this conversation. Type /agents for the list."
#: What ``/agent`` alone says, and ``/agent stop`` or ``/agent close`` without an id.
AGENT_USAGE = "Usage: /agent <id> | /agent stop <id> | /agent close <id>"
AGENT_USAGE = (
"Usage: /agent <id> | /agent new <type> <objective> | /agent stop <id> | /agent close <id>"
)
SUBCOMMAND_USAGE = "Usage: /agent {subcommand} <id>"
#: What ``/agent new`` says without a type or an objective.
NEW_USAGE = "Usage: /agent new <type> <objective>"
#: What ``/agent stop`` says it did.
STOPPED_TEXT = "Stopped {instance}: only you can start its next run."
#: What ``/agent stop`` says when the instance ended up closed (a type that takes no more runs).
Expand Down Expand Up @@ -121,23 +127,40 @@ async def execute(self, args: str, app: Any) -> None:


class AgentCommand(Command):
"""Open, stop or close one of the open conversation's sub-agents."""
"""Open, start, stop or close one of the open conversation's sub-agents."""

def __init__(self) -> None:
super().__init__(
name="agent",
description="Open one of this conversation's sub-agents, or stop or close one",
usage="/agent <id> | stop <id> | close <id>",
examples=["/agent researcher-2", "/agent stop researcher-2", "/agent close researcher-2"],
description=(
"Open one of this conversation's sub-agents, start a new one, or stop or close one"
),
usage="/agent <id> | new <type> <objective> | stop <id> | close <id>",
examples=[
"/agent researcher-2",
"/agent new researcher Find what changed in the 2.0 release.",
"/agent stop researcher-2",
"/agent close researcher-2",
],
category=CommandCategory.WORKFLOW,
)

async def execute(self, args: str, app: Any) -> None:
"""``/agent <id>`` opens its view; ``stop <id>`` and ``close <id>`` stop and close it."""
"""``/agent <id>`` opens its view; ``new <type> <objective>`` starts one
and opens its view; ``stop <id>`` and ``close <id>`` stop and close it."""
workflow = _workflow(app)
if workflow is None:
return
conversation = workflow.session_ref(getattr(app, "session_id", None))
words = args.split(None, 1)
if words and words[0] == "new":
# The objective is the rest of the line, as typed.
rest = words[1].split(None, 1) if len(words) > 1 else []
if len(rest) < 2 or not rest[1].strip():
app.session.add_warning(NEW_USAGE)
return
await app.start_agent(rest[0], rest[1].strip())
return
parts = self.parse_args(args).positional.split()
if not parts:
app.session.add_warning(AGENT_USAGE)
Expand Down
16 changes: 15 additions & 1 deletion src/agentic_cli/cli/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

from thinking_prompt import AppInfo, ThinkingPromptSession, ThinkingPromptStyles

from agentic_cli.cli.agent_view import AgentView, bind_ctrl_c, leave_view, open_view
from agentic_cli.cli.agent_view import AgentView, bind_ctrl_c, leave_view, open_view, start_view
from agentic_cli.cli.commands import Command, CommandRegistry
from agentic_cli.cli.dialogs import serialize_dialogs
from agentic_cli.cli.message_processor import MessageProcessor, _says_so_when_stopped
Expand Down Expand Up @@ -653,6 +653,20 @@ async def open_agent_view(self, instance: str) -> bool:
"""
return await open_view(self, instance)

async def start_agent(self, agent_type: str, objective: str) -> bool:
"""Start a new sub-agent of ``agent_type`` on ``objective`` and open its view (provisional).

What ``/agent new <type> <objective>`` calls (``cli/agent_view.py``):
the workflow's ``start_instance``, whose run streams in the new
instance's view. In a view it leaves that one first.

Returns:
Whether the view opened. False, said: a type the user may not
start, a blank objective, or a conversation another process has
open.
"""
return await start_view(self, agent_type, objective)

async def leave_agent_view(self) -> bool:
"""Leave the open sub-agent's view, back to the main conversation
(provisional): what ``/back`` calls.
Expand Down
45 changes: 45 additions & 0 deletions src/agentic_cli/cli/conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,51 @@ async def run_instance(self, instance: str, message: str, parts: TurnParts) -> b
turns=False,
)

async def start_instance(
self,
agent_type: str,
objective: str,
parts: TurnParts,
*,
opens: Callable[[str], Awaitable[None]] | None = None,
) -> bool:
"""Start a new sub-agent instance for the user (``/agent new``), its first run in its view.

A write to the conversation under the turn lock, as ``run_instance``
is: held to write, the conversations ``/new`` left dropped around
it, ``written`` once it reached a ready workflow, not ``turned``.
``opens`` is called with the new instance's id once its run's start
names it (``MessageProcessor.process_start``).

Args:
agent_type: The type to start.
objective: The user's objective for it.
parts: The app's parts it runs on (the new view's processor).
opens: Called once with the new instance's id.

Returns:
Whether it ran: False when another process has the conversation
open (said), and nothing ran.

Raises:
asyncio.CancelledError: Ctrl+C stopped it, as the processor says,
or while it waited for the turn lock.
"""
return await self._write(
parts,
lambda: parts.processor.process_start(
agent_type,
objective,
workflow_controller=parts.controller,
ui=parts.ui,
settings=parts.settings,
usage_tracker=parts.tracker,
session_id=self.session_id,
opens=opens,
),
turns=False,
)

async def tell_root(self, text: str, parts: TurnParts) -> bool:
"""Tell the main agent what the user did in a sub-agent's view, as a turn.

Expand Down
Loading
Loading