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
13 changes: 7 additions & 6 deletions agent_core/core/impl/action/manager.py
Original file line number Diff line number Diff line change
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 @@ -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
14 changes: 12 additions & 2 deletions agent_core/core/impl/event_stream/event_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -905,7 +905,11 @@ def _extract_keywords(message: str, top_n: int = 5) -> List[str]:
# ───────────────────────── prompt accessors ──────────────────────────

def to_prompt_snapshot(
self, include_summary: bool = True, up_to: Optional[int] = None
self,
include_summary: bool = True,
up_to: Optional[int] = None,
*,
message_overrides: Optional[Dict[Tuple[str, str], str]] = None,
) -> str:
"""
Build a compact, human-readable history for inclusion in LLM prompts.
Expand All @@ -919,6 +923,8 @@ def to_prompt_snapshot(
include_summary: Whether to prepend the rolled-up ``head_summary``.
up_to: Only the first ``up_to`` tail events (the events a request
carries, see get_event_count); None for all of them.
message_overrides: Render-only substitutions keyed by exact event
kind and message. Stored events and cached messages are untouched.

Returns:
A newline-delimited string ready to embed in an LLM request.
Expand All @@ -931,7 +937,11 @@ def to_prompt_snapshot(
recent = self.tail_events[:up_to]
if recent:
lines.append("Recent Event: ")
lines.extend(r.compact_line() for r in recent)
overrides = message_overrides or {}
lines.extend(
r.compact_line(overrides.get((r.event.kind, r.event.message)))
for r in recent
)

return "\n".join(lines) if lines else "(no events)"

Expand Down
12 changes: 9 additions & 3 deletions agent_core/core/impl/event_stream/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from __future__ import annotations
from datetime import datetime
from pathlib import Path
from typing import Callable, Dict, List, Optional
from typing import Callable, Dict, List, Optional, Tuple
import threading

from agent_core.core.impl.event_stream.event_stream import EventStream
Expand Down Expand Up @@ -183,10 +183,16 @@ def snapshot_main(self, include_summary: bool = True) -> str:
include_summary=include_summary
)

def snapshot_by_id(self, session_id: str, include_summary: bool = True) -> str:
def snapshot_by_id(
self,
session_id: str,
include_summary: bool = True,
*,
message_overrides: Optional[Dict[Tuple[str, str], str]] = None,
) -> str:
"""Snapshot a specific session's stream."""
return self.get_stream_by_id(session_id).to_prompt_snapshot(
include_summary=include_summary
include_summary=include_summary, message_overrides=message_overrides
)

def get_all_streams(self) -> list[EventStream]:
Expand Down
14 changes: 12 additions & 2 deletions agent_core/core/impl/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -943,6 +943,14 @@ async def call_tool(
}

result = response.get("result", {})
status = "error" if result.get("isError") is True else "success"
# Presence matters: null, false, zero and empty structured values
# are still evidence. Keep the existing result/raw_content shape.
metadata = {
key: result[key]
for key in ("isError", "structuredContent", "_meta")
if key in result
}

# Extract content from MCP result format
content = result.get("content", [])
Expand All @@ -954,14 +962,16 @@ async def call_tool(
text_parts.append(item.get("text", ""))

return {
"status": "success",
"status": status,
"result": "\n".join(text_parts) if text_parts else result,
"raw_content": content,
**metadata,
}

return {
"status": "success",
"status": status,
"result": result,
**metadata,
}

except Exception as e:
Expand Down
45 changes: 26 additions & 19 deletions agent_core/core/prompts/reasoning.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,32 @@
Your output feeds directly into CraftBot's task pipeline. A poorly written
prompt causes wrong skill selection, wrong action sets, misrouted sessions,
or the agent executing the wrong thing entirely. Your job is to eliminate
every source of ambiguity before the agent ever sees the instruction.
ambiguity that can be resolved from the supplied request without guessing missing details.

<rules>
RULE 1 — PRESERVE INTENT EXACTLY
Never change, expand, or restrict what the user asked for.
Clarify; do not invent. If uncertain, keep the original scope.
Preserve all instructions, constraints, prohibitions, account qualifiers,
approval boundaries, and exact identifiers. Make task-implied execution steps
and verification explicit only when consistent with these requirements.

RULE 2 — NAME THE TARGET EXPLICITLY
Vague references to apps, files, or services cause the agent to guess wrong.
- "my emails" → name the email client (Gmail, Outlook, etc.) if known;
otherwise write "the default email client or browser"
- "that file" → name the file or folder path
- "my emails" → name the email client (Gmail, Outlook, etc.) if supplied;
otherwise retain the user's description without choosing a client
- "that file" → name the file or folder path only if identified in the request
- "send a message" → name the platform (Telegram, WhatsApp, Slack, Discord)
if implied by context; this prevents wrong platform routing
if identified in the supplied request; this prevents wrong platform routing
- "remind me" → write "create a proactive scheduled task"

RULE 3 — STATE THE DONE-CONDITION
The agent verifies tasks against a done-condition. If it is missing, the
agent either over-executes or loops asking for confirmation.
End every enhanced prompt with what success looks like:
Describe completion of the requested task without inventing extra deliverables
or destinations. Use done-conditions consistent with the request, such as:
"...and confirm to me when complete."
"...and save the result to the workspace folder."
"...and save the requested result to the specified location."
"...and send me a summary of what was found."

RULE 4 — SIGNAL TASK COMPLEXITY
Expand All @@ -48,14 +52,17 @@
— this signals complex_task mode

RULE 5 — HONOUR SCHEDULING SIGNALS
CraftBot has a built-in proactive scheduler. If the user implies recurrence
("every day", "each week", "automatically", "whenever X happens"), write
CraftBot has a built-in proactive scheduler. If the user specifies recurrence
("every day", "each week", "whenever X happens"), write
"Set up a recurring proactive task to..." — this ensures the scheduler
system is invoked, not a one-off task.
Preserve supplied timing and one-time or event conditions exactly.
"Automatically" alone does not imply recurrence. Do not invent a time or repeat interval.

RULE 6 — ELIMINATE PRONOUN AMBIGUITY
"it", "this", "that", "them", "there" — replace every pronoun with the
actual noun it refers to, using context from the conversation if available.
"it", "this", "that", "them", "there" — replace a pronoun with its actual
noun only when identified in the supplied request. Otherwise retain the reference
for the executing agent; do not assume unseen conversation history.

RULE 7 — ONE ACTION FRAME
Do not chain unrelated actions into one prompt. If the user asked for one
Expand Down Expand Up @@ -84,9 +91,9 @@
- Do NOT produce bullet lists or numbered steps — output is one prose block
- Do NOT include preamble ("Here is the improved prompt:", "Enhanced:", etc.)
- Do NOT wrap the output in quotes
- Do NOT exceed 4 sentences
- Do NOT drop instructions to shorten the request; there is no sentence limit
- Do NOT use passive voice — use active imperative verbs
- Do NOT leave platform names implicit when a platform is involved
- Do NOT omit supplied platform names or invent missing ones
- Do NOT start using another language other than the one written in by the user initially unless asked for by the user
</anti_patterns>

Expand All @@ -99,14 +106,14 @@

Examples of prompt quality (these are examples only, NOT the required output format):

BAD: "check my emails"
GOOD: "Open Gmail in the browser, check for unread emails received in the last 24 hours, and send me a plain-text summary of any messages that need a reply or action."
INPUT: "review PR #514 for bugs. don't edit files or post comments"
ENHANCED: "Inspect the diff and relevant surrounding code for PR #514, trace the changes for likely bugs, and report findings with file references. Do not edit files or post comments."

BAD: "remind me about the standup"
GOOD: "Create a recurring proactive task that sends me a reminder message 5 minutes before my daily standup meeting, using the schedule defined in my calendar or a fixed daily time I confirm."
INPUT: "remind me about the standup tomorrow at 10am, just once"
ENHANCED: "Create a one-time proactive scheduled task to remind me about the standup tomorrow at 10am, and verify that the reminder is scheduled for that time without recurrence."

BAD: "clean it up"
GOOD: "Open the Downloads folder, identify duplicate files and files not accessed in the last 30 days, list them for my review, and move only the confirmed items to Trash."
INPUT: "fix the failing tests. don't commit"
ENHANCED: "Reproduce the test failures, identify their causes, make the necessary fixes, and rerun the affected tests to verify they pass. Do not commit."

Required output example:
{
Expand Down
9 changes: 6 additions & 3 deletions agent_core/core/protocols/event_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
This module defines protocols for event stream operations.
"""

from typing import List, Optional, Protocol, Tuple, TYPE_CHECKING
from typing import Dict, List, Optional, Protocol, Tuple, TYPE_CHECKING

if TYPE_CHECKING:
from agent_core import EventRecord
Expand Down Expand Up @@ -48,15 +48,18 @@ def log(

def to_prompt_snapshot(
self,
max_events: int = 60,
include_summary: bool = True,
up_to: Optional[int] = None,
*,
message_overrides: Optional[Dict[Tuple[str, str], str]] = None,
) -> str:
"""
Build compact history for LLM prompts.

Args:
max_events: Maximum number of recent events to include.
include_summary: Whether to include the head summary.
up_to: Only include events before this index.
message_overrides: Render-only substitutions by exact kind and message.

Returns:
Formatted string of event history.
Expand Down
18 changes: 15 additions & 3 deletions app/subagent/context_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def make_system_prompt(self, sub: SubAgent) -> str:

def make_first_turn_user_prompt(self, sub: SubAgent) -> str:
"""First-turn user prompt: query + initial event log + decision nudge."""
event_log = self._snapshot_event_log(sub.id)
event_log = self._snapshot_event_log(sub)
return (
f"QUERY FROM SPAWNING AGENT:\n{sub.query}\n\n"
f"YOUR EVENT LOG SO FAR (most recent last):\n{event_log}\n\n"
Expand All @@ -180,9 +180,21 @@ def make_delta_user_prompt(self, delta_events: str) -> str:
# Helpers
# ------------------------------------------------------------------

def _snapshot_event_log(self, sub_id: str) -> str:
def _snapshot_event_log(self, sub: SubAgent) -> str:
# The complete current query is above this snapshot, including after
# a fold or restore. Abbreviate only an exact match; never edit storage.
return (
self.event_stream_manager.snapshot_by_id(sub_id, include_summary=True)
self.event_stream_manager.snapshot_by_id(
sub.id,
include_summary=True,
message_overrides={
(
"subagent_start",
sub.bootstrap_message,
): f"Sub-agent of type '{sub.agent_type}' started. "
"Query: see QUERY FROM SPAWNING AGENT above."
},
)
or "(no events yet)"
)

Expand Down
2 changes: 1 addition & 1 deletion app/subagent/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def spawn(
# The parent stream never sees it.
self.event_stream_manager.log(
kind="subagent_start",
message=(f"Sub-agent of type '{agent_type}' started.\nQuery: {query}"),
message=sub.bootstrap_message,
display_message=f"subagent[{agent_type}] start",
task_id=sub_id,
)
Expand Down
5 changes: 5 additions & 0 deletions app/subagent/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ class SubAgent:
# Mode marker — always ``SUBAGENT_MODE`` so downstream code can detect it.
mode: str = SUBAGENT_MODE

@property
def bootstrap_message(self) -> str:
"""The full diagnostic event, also used for exact prompt deduplication."""
return f"Sub-agent of type '{self.agent_type}' started.\nQuery: {self.query}"

def is_terminal(self) -> bool:
"""True once the sub-agent has reached any terminal status."""
return self.status in SUBAGENT_TERMINAL_STATUSES
Expand Down
Loading