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
2 changes: 2 additions & 0 deletions agent_core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@
# Event stream
EVENT_STREAM_SUMMARIZATION_PROMPT,
# Action prompts
SELECT_ACTION_INSTRUCTIONS,
SELECT_ACTION_PROMPT,
# Context prompts
AGENT_ROLE_PROMPT,
Expand Down Expand Up @@ -365,6 +366,7 @@
# Prompts - Event stream
"EVENT_STREAM_SUMMARIZATION_PROMPT",
# Prompts - Action
"SELECT_ACTION_INSTRUCTIONS",
"SELECT_ACTION_PROMPT",
# Prompts - Context
"AGENT_ROLE_PROMPT",
Expand Down
53 changes: 42 additions & 11 deletions agent_core/core/action_framework/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@
This module owns the canonical compact representation used to describe
available actions to the LLM. It is intentionally tight on tokens:

- One JSON object per action with ``name``, ``description``, ``params``.
- Each parameter collapses to a single string ``"<type>, required|optional - <desc>"``.
- One JSON object per action with ``name``, ``description``, ``params``,
one action per line, without padding whitespace.
- Each parameter collapses to a single string ``"<type>, required|optional - <desc>"``,
required or optional as its schema's ``required`` flag declares.
- A parameter every action of the list takes, with the same text, is written
once above the list instead of in each action (e.g. an integration's
``account``).
- No ``example`` fields, no nested type-definitions.

Both ``ActionRouter`` (main agent) and ``SubAgentContextEngine`` (sub-agents)
Expand Down Expand Up @@ -53,7 +58,8 @@ def format_action_candidates(candidates: List[Dict[str, Any]]) -> str:
to build entries from ``Action`` objects.

Returns:
A JSON-formatted string (pretty-printed) describing the candidates.
A JSON array of the candidates, one per line, preceded by a line
listing the parameters every candidate takes when there are any.
Returns ``"[]"`` when the list is empty.
"""
if not candidates:
Expand All @@ -67,13 +73,14 @@ def format_action_candidates(candidates: List[Dict[str, Any]]) -> str:
if isinstance(param_def, dict):
ptype = param_def.get("type", "any")
desc = param_def.get("description", "") or ""
# Match the heuristic used by ActionRouter._format_candidates:
# treat parameters whose description mentions "default" or
# "optional" as optional, everything else required.
low = desc.lower()
is_optional = "default" in low or "optional" in low
req = "optional" if is_optional else "required"
params[param_name] = f"{ptype}, {req} - {desc}"
# Required or optional as the schema declares it. A schema
# that declares neither gets no label: nothing is inferred.
required = param_def.get("required")
if isinstance(required, bool):
req = "required" if required else "optional"
params[param_name] = f"{ptype}, {req} - {desc}"
else:
params[param_name] = f"{ptype} - {desc}"
else:
params[param_name] = str(param_def)

Expand All @@ -85,7 +92,31 @@ def format_action_candidates(candidates: List[Dict[str, Any]]) -> str:
}
)

return json.dumps(compact, indent=2, ensure_ascii=False)
shared = _params_every_action_takes(compact)
for entry in compact:
for param_name in shared:
del entry["params"][param_name]

def dump(value) -> str:
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))

block = "[\n" + ",\n".join(dump(entry) for entry in compact) + "\n]"
if shared:
block = f"Every action below also takes these params: {dump(shared)}\n{block}"
return block


def _params_every_action_takes(compact: List[Dict[str, Any]]) -> Dict[str, str]:
"""The parameters (name and rendered text) every action of the list has,
in the first action's order. A list of one action shares nothing."""
if len(compact) < 2:
return {}
first, rest = compact[0]["params"], compact[1:]
return {
name: text
for name, text in first.items()
if all(entry["params"].get(name) == text for entry in rest)
}


def format_actions_by_name(
Expand Down
24 changes: 22 additions & 2 deletions agent_core/core/event_stream/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@

SEVERITIES = ("DEBUG", "INFO", "WARN", "ERROR")

# The key the action runtime adds to every action's input
# (ActionManager.execute_action): the session the action runs in. The model
# never writes it, so an executed input is compared with the model's
# parameters without it (EventStream's delta rendering).
SESSION_ID_INPUT_KEY = "_session_id"


class EventType(str, Enum):
"""Closed set of event categories.
Expand Down Expand Up @@ -66,6 +72,11 @@ class EventType(str, Enum):
# add_action_sets (and by skills / runs that declare sets). LLM-facing
# reference material; `Event.schema_actions` names the actions it covers.
ACTION_SCHEMAS = "action_schemas"
# A skill's instructions, logged when it is loaded into a session (and
# its unload marker). The stream keeps the newest instructions of every
# loaded skill verbatim across folds; `Event.skill_name` names the skill.
SKILL_INSTRUCTIONS = "skill_instructions"
SKILL_UNLOADED = "skill_unloaded"


# Legacy `kind` → `event_type` mapping. NEW code MUST NOT call this.
Expand Down Expand Up @@ -156,6 +167,8 @@ class Event:
actions whose schemas the message carries. The event stream keeps
the event across a fold while any of these actions appears in the
kept tail. None for every other event.
skill_name: For SKILL_INSTRUCTIONS and SKILL_UNLOADED events only:
the skill they concern. None for every other event.
"""

message: str
Expand All @@ -174,6 +187,7 @@ class Event:
question: Optional[Dict[str, Any]] = None
ui_artifact: Optional[Dict[str, Any]] = None
schema_actions: Optional[List[str]] = None
skill_name: Optional[str] = None

def display_text(self) -> Optional[str]:
"""
Expand Down Expand Up @@ -209,6 +223,7 @@ def to_dict(self) -> Dict[str, Any]:
"question": self.question,
"ui_artifact": self.ui_artifact,
"schema_actions": self.schema_actions,
"skill_name": self.skill_name,
}

@classmethod
Expand Down Expand Up @@ -251,6 +266,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "Event":
question=data.get("question"),
ui_artifact=data.get("ui_artifact"),
schema_actions=data.get("schema_actions"),
skill_name=data.get("skill_name"),
)

@property
Expand Down Expand Up @@ -308,7 +324,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "EventRecord":
repeat_count=data.get("repeat_count", 1),
)

def compact_line(self) -> str:
def compact_line(self, message: Optional[str] = None) -> str:
"""
Generate a compact single-line representation of this event.

Expand All @@ -318,11 +334,15 @@ def compact_line(self) -> str:
current-datetime block reports (and with the log files a human reads
alongside). A naive ts (legacy persisted data) is assumed local.

Args:
message: Shown in place of the event's message (a delta refers to
an action input the model's own reply already holds).

Returns:
Compact string representation
"""
t = self.ts.astimezone().strftime("%H:%M:%S")
k = self.event.kind
msg = self.event.message
msg = self.event.message if message is None else message
suffix = f" x{self.repeat_count}" if self.repeat_count > 1 else ""
return f"{t} [{k}]: {msg}{suffix}"
17 changes: 9 additions & 8 deletions agent_core/core/impl/action/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from agent_core.core.protocols.state import StateManagerProtocol
from agent_core.core.impl.action.executor import ActionExecutor
from agent_core.core.impl.action.idempotency import IdempotencyGuard
from agent_core.core.event_stream.event import EventType
from agent_core.core.event_stream.event import SESSION_ID_INPUT_KEY, EventType
from agent_core.utils.logger import logger

# ============================================================================
Expand Down Expand Up @@ -132,10 +132,11 @@ async def _compat_wait_for(fut, timeout):
# ============================================================================


def _to_pretty_json(value: Any) -> str:
"""Serialize a value to pretty-printed JSON for readable logs and event streams."""
def _to_json(value: Any, *, compact: bool = False) -> str:
"""Serialize event data; compact new results without changing string contents."""
try:
return json.dumps(value, indent=2, ensure_ascii=False, default=str)
layout = {"separators": (",", ":")} if compact else {"indent": 2}
return json.dumps(value, ensure_ascii=False, default=str, **layout)
except (TypeError, ValueError):
return str(value)

Expand Down Expand Up @@ -261,7 +262,7 @@ async def execute_action(
if input_data is None:
input_data = {}
if session_id:
input_data["_session_id"] = session_id
input_data[SESSION_ID_INPUT_KEY] = session_id

logger.debug(f"[INPUT DATA] {input_data}")

Expand Down Expand Up @@ -354,7 +355,7 @@ async def execute_action(
# Log to event stream
# Only pass session_id when is_running_task=True (task stream exists)
# When no task exists, use global stream by not passing task_id
pretty_input = _to_pretty_json(input_data)
pretty_input = _to_json(input_data)
self._log_event_stream(
is_gui_task=is_gui_task,
event_kind="action_start",
Expand Down Expand Up @@ -478,12 +479,12 @@ async def execute_action(
display_status = (
"failed" if (status == "error" or output_has_error) else "completed"
)
pretty_output = _to_pretty_json(outputs)
rendered_output = _to_json(outputs, compact=True)
self._log_event_stream(
is_gui_task=is_gui_task,
event_kind="action_end",
event_type=EventType.ACTION_END,
event=f"Action {action.name} completed with output: {pretty_output}.",
event=f"Action {action.name} completed with output: {rendered_output}.",
display_message=f"{action.display_name} → {display_status}",
action_name=action.name,
action_display_name=action.display_name,
Expand Down
Loading
Loading