autobyteus 1.1.0__py3-none-any.whl → 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. autobyteus/agent/bootstrap_steps/agent_bootstrapper.py +1 -1
  2. autobyteus/agent/bootstrap_steps/agent_runtime_queue_initialization_step.py +1 -1
  3. autobyteus/agent/bootstrap_steps/base_bootstrap_step.py +1 -1
  4. autobyteus/agent/bootstrap_steps/system_prompt_processing_step.py +1 -1
  5. autobyteus/agent/bootstrap_steps/workspace_context_initialization_step.py +1 -1
  6. autobyteus/agent/context/__init__.py +0 -5
  7. autobyteus/agent/context/agent_config.py +6 -2
  8. autobyteus/agent/context/agent_context.py +2 -5
  9. autobyteus/agent/context/agent_phase_manager.py +105 -5
  10. autobyteus/agent/context/agent_runtime_state.py +2 -2
  11. autobyteus/agent/context/phases.py +2 -0
  12. autobyteus/agent/events/__init__.py +0 -11
  13. autobyteus/agent/events/agent_events.py +0 -37
  14. autobyteus/agent/events/notifiers.py +25 -7
  15. autobyteus/agent/events/worker_event_dispatcher.py +1 -1
  16. autobyteus/agent/factory/agent_factory.py +6 -2
  17. autobyteus/agent/group/agent_group.py +16 -7
  18. autobyteus/agent/handlers/approved_tool_invocation_event_handler.py +28 -14
  19. autobyteus/agent/handlers/lifecycle_event_logger.py +1 -1
  20. autobyteus/agent/handlers/llm_complete_response_received_event_handler.py +4 -2
  21. autobyteus/agent/handlers/tool_invocation_request_event_handler.py +40 -15
  22. autobyteus/agent/handlers/tool_result_event_handler.py +12 -7
  23. autobyteus/agent/hooks/__init__.py +7 -0
  24. autobyteus/agent/hooks/base_phase_hook.py +11 -2
  25. autobyteus/agent/hooks/hook_definition.py +36 -0
  26. autobyteus/agent/hooks/hook_meta.py +37 -0
  27. autobyteus/agent/hooks/hook_registry.py +118 -0
  28. autobyteus/agent/input_processor/base_user_input_processor.py +6 -3
  29. autobyteus/agent/input_processor/passthrough_input_processor.py +2 -1
  30. autobyteus/agent/input_processor/processor_meta.py +1 -1
  31. autobyteus/agent/input_processor/processor_registry.py +19 -0
  32. autobyteus/agent/llm_response_processor/base_processor.py +6 -3
  33. autobyteus/agent/llm_response_processor/processor_meta.py +1 -1
  34. autobyteus/agent/llm_response_processor/processor_registry.py +19 -0
  35. autobyteus/agent/llm_response_processor/provider_aware_tool_usage_processor.py +2 -1
  36. autobyteus/agent/message/context_file_type.py +2 -3
  37. autobyteus/agent/phases/__init__.py +18 -0
  38. autobyteus/agent/phases/discover.py +52 -0
  39. autobyteus/agent/phases/manager.py +265 -0
  40. autobyteus/agent/phases/phase_enum.py +49 -0
  41. autobyteus/agent/phases/transition_decorator.py +40 -0
  42. autobyteus/agent/phases/transition_info.py +33 -0
  43. autobyteus/agent/remote_agent.py +1 -1
  44. autobyteus/agent/runtime/agent_runtime.py +4 -6
  45. autobyteus/agent/runtime/agent_worker.py +1 -1
  46. autobyteus/agent/streaming/agent_event_stream.py +58 -5
  47. autobyteus/agent/streaming/stream_event_payloads.py +24 -13
  48. autobyteus/agent/streaming/stream_events.py +14 -11
  49. autobyteus/agent/system_prompt_processor/base_processor.py +6 -3
  50. autobyteus/agent/system_prompt_processor/processor_meta.py +1 -1
  51. autobyteus/agent/system_prompt_processor/tool_manifest_injector_processor.py +45 -31
  52. autobyteus/agent/tool_invocation.py +29 -3
  53. autobyteus/agent/utils/wait_for_idle.py +1 -1
  54. autobyteus/agent/workspace/__init__.py +2 -0
  55. autobyteus/agent/workspace/base_workspace.py +33 -11
  56. autobyteus/agent/workspace/workspace_config.py +160 -0
  57. autobyteus/agent/workspace/workspace_definition.py +36 -0
  58. autobyteus/agent/workspace/workspace_meta.py +37 -0
  59. autobyteus/agent/workspace/workspace_registry.py +72 -0
  60. autobyteus/cli/__init__.py +4 -3
  61. autobyteus/cli/agent_cli.py +25 -207
  62. autobyteus/cli/cli_display.py +205 -0
  63. autobyteus/events/event_manager.py +2 -1
  64. autobyteus/events/event_types.py +3 -1
  65. autobyteus/llm/api/autobyteus_llm.py +2 -12
  66. autobyteus/llm/api/deepseek_llm.py +5 -5
  67. autobyteus/llm/api/grok_llm.py +5 -5
  68. autobyteus/llm/api/mistral_llm.py +4 -4
  69. autobyteus/llm/api/ollama_llm.py +2 -2
  70. autobyteus/llm/extensions/token_usage_tracking_extension.py +11 -1
  71. autobyteus/llm/llm_factory.py +106 -42
  72. autobyteus/llm/models.py +25 -29
  73. autobyteus/llm/ollama_provider.py +6 -2
  74. autobyteus/llm/ollama_provider_resolver.py +44 -0
  75. autobyteus/tools/__init__.py +2 -0
  76. autobyteus/tools/base_tool.py +7 -1
  77. autobyteus/tools/functional_tool.py +20 -5
  78. autobyteus/tools/mcp/call_handlers/stdio_handler.py +15 -1
  79. autobyteus/tools/mcp/config_service.py +106 -127
  80. autobyteus/tools/mcp/registrar.py +247 -59
  81. autobyteus/tools/mcp/types.py +5 -3
  82. autobyteus/tools/registry/tool_definition.py +8 -1
  83. autobyteus/tools/registry/tool_registry.py +18 -0
  84. autobyteus/tools/tool_category.py +11 -0
  85. autobyteus/tools/tool_meta.py +3 -1
  86. autobyteus/tools/tool_state.py +20 -0
  87. autobyteus/tools/usage/parsers/default_json_tool_usage_parser.py +3 -3
  88. autobyteus/tools/usage/parsers/default_xml_tool_usage_parser.py +2 -1
  89. autobyteus/tools/usage/parsers/gemini_json_tool_usage_parser.py +17 -19
  90. autobyteus/tools/usage/parsers/openai_json_tool_usage_parser.py +126 -77
  91. {autobyteus-1.1.0.dist-info → autobyteus-1.1.1.dist-info}/METADATA +11 -11
  92. {autobyteus-1.1.0.dist-info → autobyteus-1.1.1.dist-info}/RECORD +95 -78
  93. {autobyteus-1.1.0.dist-info → autobyteus-1.1.1.dist-info}/WHEEL +0 -0
  94. {autobyteus-1.1.0.dist-info → autobyteus-1.1.1.dist-info}/licenses/LICENSE +0 -0
  95. {autobyteus-1.1.0.dist-info → autobyteus-1.1.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,160 @@
1
+ # file: autobyteus/autobyteus/agent/workspace/workspace_config.py
2
+ import logging
3
+ import json
4
+ from typing import Dict, Any, Mapping
5
+ from collections.abc import Mapping as MappingABC
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ def _default_serializer(obj: Any) -> Any:
10
+ """
11
+ A robust serializer for objects that might not be JSON-serializable,
12
+ ensuring a stable representation for hashing and comparison.
13
+ """
14
+ try:
15
+ # For common un-serializable collection types, convert to a sorted list
16
+ # to ensure a stable representation.
17
+ if isinstance(obj, set):
18
+ return sorted(list(obj))
19
+ # For other objects, repr() is often a good choice for a unique,
20
+ # and often reconstructible, string representation.
21
+ return repr(obj)
22
+ except Exception:
23
+ # Fallback for any object that fails repr() or other serialization.
24
+ return f"<unrepresentable object of type {type(obj).__name__}>"
25
+
26
+
27
+ class WorkspaceConfig:
28
+ """
29
+ An immutable, hashable configuration class for agent workspaces.
30
+
31
+ This class stores workspace configuration parameters. It is immutable, meaning
32
+ that methods like `set` or `update` return a new `WorkspaceConfig` instance
33
+ rather than modifying the existing one.
34
+
35
+ This immutability makes `WorkspaceConfig` instances hashable, allowing them to
36
+ be used as dictionary keys for caching and reusing workspace instances.
37
+ """
38
+ _params: Dict[str, Any]
39
+ _canonical_rep: str
40
+
41
+ def __init__(self, params: Mapping[str, Any] = None):
42
+ """
43
+ Initializes the WorkspaceConfig.
44
+
45
+ Args:
46
+ params: A dictionary of configuration parameters. A copy is stored.
47
+ """
48
+ self._params = dict(params or {})
49
+
50
+ # Pre-compute canonical representation for hashing and equality.
51
+ try:
52
+ self._canonical_rep = json.dumps(self._params, sort_keys=True, default=_default_serializer)
53
+ except Exception as e:
54
+ logger.error(f"Failed to create canonical representation for WorkspaceConfig: {e}", exc_info=True)
55
+ # Fallback for extreme cases
56
+ self._canonical_rep = repr(self._params)
57
+
58
+ logger.debug(f"WorkspaceConfig initialized with params keys: {list(self._params.keys())}")
59
+
60
+ def __hash__(self) -> int:
61
+ return hash(self._canonical_rep)
62
+
63
+ def __eq__(self, other: object) -> bool:
64
+ if not isinstance(other, WorkspaceConfig):
65
+ return NotImplemented
66
+ return self._canonical_rep == other._canonical_rep
67
+
68
+ def to_dict(self) -> Dict[str, Any]:
69
+ """
70
+ Convert the WorkspaceConfig to a dictionary representation.
71
+
72
+ Returns:
73
+ Dict[str, Any]: A copy of the configuration parameters.
74
+ """
75
+ return self._params.copy()
76
+
77
+ @classmethod
78
+ def from_dict(cls, config_data: Dict[str, Any]) -> 'WorkspaceConfig':
79
+ """
80
+ Create a WorkspaceConfig instance from a dictionary.
81
+
82
+ Args:
83
+ config_data: Dictionary containing configuration parameters.
84
+
85
+ Returns:
86
+ A new, immutable WorkspaceConfig instance.
87
+ """
88
+ if not isinstance(config_data, dict):
89
+ raise TypeError("config_data must be a dictionary")
90
+ return cls(params=config_data)
91
+
92
+ def merge(self, other: 'WorkspaceConfig') -> 'WorkspaceConfig':
93
+ """
94
+ Merge this WorkspaceConfig with another, with the other taking precedence.
95
+
96
+ Args:
97
+ other: WorkspaceConfig to merge with this one.
98
+
99
+ Returns:
100
+ A new, merged WorkspaceConfig instance.
101
+ """
102
+ if not isinstance(other, WorkspaceConfig):
103
+ raise TypeError("Can only merge with another WorkspaceConfig instance")
104
+
105
+ merged_params = self._params.copy()
106
+ merged_params.update(other._params)
107
+ return WorkspaceConfig(params=merged_params)
108
+
109
+ def get(self, key: str, default: Any = None) -> Any:
110
+ """
111
+ Get a configuration parameter.
112
+
113
+ Args:
114
+ key: The parameter key.
115
+ default: Default value if key doesn't exist.
116
+
117
+ Returns:
118
+ The parameter value or default.
119
+ """
120
+ return self._params.get(key, default)
121
+
122
+ def set(self, key: str, value: Any) -> 'WorkspaceConfig':
123
+ """
124
+ Return a new WorkspaceConfig with a key set to a new value.
125
+
126
+ Args:
127
+ key: The parameter key.
128
+ value: The parameter value.
129
+
130
+ Returns:
131
+ A new WorkspaceConfig instance with the updated parameter.
132
+ """
133
+ new_params = self._params.copy()
134
+ new_params[key] = value
135
+ return WorkspaceConfig(params=new_params)
136
+
137
+ def update(self, params: Mapping[str, Any]) -> 'WorkspaceConfig':
138
+ """
139
+ Return a new WorkspaceConfig with multiple updated parameters.
140
+
141
+ Args:
142
+ params: Dictionary of parameters to update.
143
+
144
+ Returns:
145
+ A new WorkspaceConfig instance with the updated parameters.
146
+ """
147
+ if not isinstance(params, MappingABC):
148
+ raise TypeError("params must be a mapping (e.g., a dictionary)")
149
+ new_params = self._params.copy()
150
+ new_params.update(params)
151
+ return WorkspaceConfig(params=new_params)
152
+
153
+ def __repr__(self) -> str:
154
+ return f"WorkspaceConfig(params={self._params})"
155
+
156
+ def __len__(self) -> int:
157
+ return len(self._params)
158
+
159
+ def __bool__(self) -> bool:
160
+ return bool(self._params)
@@ -0,0 +1,36 @@
1
+ """
2
+ This module defines the WorkspaceDefinition class, which encapsulates the metadata
3
+ for a specific type of agent workspace.
4
+ """
5
+ import logging
6
+ from typing import Type, Optional, TYPE_CHECKING
7
+ from autobyteus.tools.parameter_schema import ParameterSchema
8
+
9
+ if TYPE_CHECKING:
10
+ from autobyteus.agent.workspace.base_workspace import BaseAgentWorkspace
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ class WorkspaceDefinition:
15
+ """Represents the definition of a discoverable and creatable agent workspace type."""
16
+ def __init__(self,
17
+ workspace_type_name: str,
18
+ description: str,
19
+ workspace_class: Type['BaseAgentWorkspace'],
20
+ config_schema: ParameterSchema):
21
+ if not all([workspace_type_name, description, workspace_class, config_schema is not None]):
22
+ raise ValueError("All parameters for WorkspaceDefinition are required.")
23
+
24
+ self.workspace_type_name = workspace_type_name
25
+ self.description = description
26
+ self.workspace_class = workspace_class
27
+ self.config_schema = config_schema
28
+ logger.debug(f"WorkspaceDefinition created for type '{workspace_type_name}'.")
29
+
30
+ def to_dict(self) -> dict:
31
+ """Serializes the definition to a dictionary for API exposure."""
32
+ return {
33
+ "workspace_type_name": self.workspace_type_name,
34
+ "description": self.description,
35
+ "config_schema": self.config_schema.to_dict()
36
+ }
@@ -0,0 +1,37 @@
1
+ """
2
+ This module contains the metaclass for BaseAgentWorkspace for automatic registration.
3
+ """
4
+ import logging
5
+ from abc import ABCMeta
6
+ from .workspace_registry import default_workspace_registry
7
+ from .workspace_definition import WorkspaceDefinition
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ class WorkspaceMeta(ABCMeta):
12
+ """Metaclass to automatically register concrete BaseAgentWorkspace subclasses."""
13
+ def __init__(cls, name, bases, dct):
14
+ super().__init__(name, bases, dct)
15
+
16
+ if name == 'BaseAgentWorkspace' or getattr(cls, "__abstractmethods__", None):
17
+ logger.debug(f"Skipping registration for abstract workspace class: {name}")
18
+ return
19
+
20
+ try:
21
+ workspace_type_name = cls.get_workspace_type_name()
22
+ description = cls.get_description()
23
+ config_schema = cls.get_config_schema()
24
+
25
+ definition = WorkspaceDefinition(
26
+ workspace_type_name=workspace_type_name,
27
+ description=description,
28
+ workspace_class=cls,
29
+ config_schema=config_schema
30
+ )
31
+ default_workspace_registry.register(definition)
32
+ config_params_info = f"config_params: {len(config_schema) if config_schema else 0}"
33
+ logger.info(f"Auto-registered workspace: '{workspace_type_name}' from class {name} ({config_params_info})")
34
+ except AttributeError as e:
35
+ logger.error(f"Workspace class {name} is missing a required static/class method ({e}). Skipping registration.")
36
+ except Exception as e:
37
+ logger.error(f"Failed to auto-register workspace class {name}: {e}", exc_info=True)
@@ -0,0 +1,72 @@
1
+ """
2
+ This module provides a central registry for agent workspace types.
3
+ """
4
+ import logging
5
+ from typing import Dict, Any, Optional, List, TYPE_CHECKING
6
+ from autobyteus.utils.singleton import SingletonMeta
7
+ from .workspace_definition import WorkspaceDefinition
8
+ from .workspace_config import WorkspaceConfig
9
+
10
+ if TYPE_CHECKING:
11
+ from .base_workspace import BaseAgentWorkspace
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ class WorkspaceRegistry(metaclass=SingletonMeta):
16
+ """
17
+ A singleton registry for WorkspaceDefinition objects. Workspaces are
18
+ typically auto-registered via WorkspaceMeta.
19
+ """
20
+ def __init__(self):
21
+ self._definitions: Dict[str, WorkspaceDefinition] = {}
22
+ logger.info("Core WorkspaceRegistry initialized.")
23
+
24
+ def register(self, definition: WorkspaceDefinition):
25
+ """Registers a workspace definition."""
26
+ if not isinstance(definition, WorkspaceDefinition):
27
+ raise TypeError("Can only register WorkspaceDefinition objects.")
28
+ if definition.workspace_type_name in self._definitions:
29
+ logger.warning(f"Overwriting workspace definition for type '{definition.workspace_type_name}'.")
30
+ self._definitions[definition.workspace_type_name] = definition
31
+
32
+ def get_definition(self, workspace_type_name: str) -> Optional[WorkspaceDefinition]:
33
+ """Retrieves a workspace definition by its unique type name."""
34
+ return self._definitions.get(workspace_type_name)
35
+
36
+ def get_all_definitions(self) -> List[WorkspaceDefinition]:
37
+ """Returns a list of all registered workspace definitions."""
38
+ return list(self._definitions.values())
39
+
40
+ def create_workspace(self, workspace_type_name: str, config: WorkspaceConfig) -> 'BaseAgentWorkspace':
41
+ """
42
+ Creates an instance of a workspace.
43
+
44
+ Args:
45
+ workspace_type_name (str): The unique type name of the workspace to create.
46
+ config (WorkspaceConfig): The configuration object for the workspace.
47
+
48
+ Returns:
49
+ An instance of a BaseAgentWorkspace subclass.
50
+
51
+ Raises:
52
+ ValueError: If the type is unknown or parameters are invalid.
53
+ """
54
+ definition = self.get_definition(workspace_type_name)
55
+ if not definition:
56
+ raise ValueError(f"Unknown workspace type: '{workspace_type_name}'")
57
+
58
+ is_valid, errors = definition.config_schema.validate_config(config.to_dict())
59
+ if not is_valid:
60
+ error_str = ", ".join(errors)
61
+ raise ValueError(f"Invalid parameters for workspace type '{workspace_type_name}': {error_str}")
62
+
63
+ try:
64
+ workspace_class = definition.workspace_class
65
+ instance = workspace_class(config=config)
66
+ logger.info(f"Successfully created instance of workspace type '{workspace_type_name}'.")
67
+ return instance
68
+ except Exception as e:
69
+ logger.error(f"Failed to instantiate workspace class '{definition.workspace_class.__name__}': {e}", exc_info=True)
70
+ raise RuntimeError(f"Workspace instantiation failed for type '{workspace_type_name}': {e}") from e
71
+
72
+ default_workspace_registry = WorkspaceRegistry()
@@ -2,9 +2,10 @@
2
2
  """
3
3
  Command-Line Interface (CLI) utilities for interacting with AutoByteUs components.
4
4
  """
5
- from . import agent_cli
5
+ from .agent_cli import run
6
+ from .cli_display import InteractiveCLIDisplay
6
7
 
7
8
  __all__ = [
8
- "agent_cli",
9
+ "run",
10
+ "InteractiveCLIDisplay",
9
11
  ]
10
-
@@ -1,212 +1,41 @@
1
1
  import asyncio
2
2
  import logging
3
3
  import sys
4
- from typing import Optional, List, Dict, Any
5
- import json
4
+ from typing import Optional
6
5
 
7
6
  from autobyteus.agent.agent import Agent
8
- from autobyteus.agent.context.phases import AgentOperationalPhase
9
7
  from autobyteus.agent.message.agent_input_user_message import AgentInputUserMessage
10
8
  from autobyteus.agent.streaming.agent_event_stream import AgentEventStream
11
- from autobyteus.agent.streaming.stream_events import StreamEvent, StreamEventType
12
- from autobyteus.agent.streaming.stream_event_payloads import (
13
- AssistantChunkData,
14
- AssistantCompleteResponseData,
15
- ToolInvocationApprovalRequestedData,
16
- ToolInteractionLogEntryData,
17
- AgentOperationalPhaseTransitionData,
18
- ErrorEventData,
19
- )
9
+ from .cli_display import InteractiveCLIDisplay
20
10
 
21
11
  logger = logging.getLogger(__name__)
22
12
 
23
- class InteractiveCLIManager:
24
- """
25
- Manages the state and rendering logic for the interactive CLI session.
26
- Input reading is handled by the main `run` loop. This class only handles output.
13
+ async def run(agent: Agent, show_tool_logs: bool = True, show_token_usage: bool = False, initial_prompt: Optional[str] = None):
27
14
  """
28
- def __init__(self, agent_turn_complete_event: asyncio.Event, show_tool_logs: bool, show_token_usage: bool):
29
- self.agent_turn_complete_event = agent_turn_complete_event
30
- self.show_tool_logs = show_tool_logs
31
- self.show_token_usage = show_token_usage
32
- self.current_line_empty = True
33
- self.agent_has_spoken_this_turn = False
34
- self.pending_approval_data: Optional[ToolInvocationApprovalRequestedData] = None
35
- self.is_thinking = False
36
- self.is_in_content_block = False
37
-
38
- def reset_turn_state(self):
39
- """Resets flags that are tracked on a per-turn basis."""
40
- self._end_thinking_block()
41
- self.agent_has_spoken_this_turn = False
42
- self.is_in_content_block = False
43
-
44
- def _ensure_new_line(self):
45
- """Ensures the cursor is on a new line if the current one isn't empty."""
46
- if not self.current_line_empty:
47
- sys.stdout.write("\n")
48
- sys.stdout.flush()
49
- self.current_line_empty = True
50
-
51
- def _end_thinking_block(self):
52
- """Closes the <Thinking> block if it was active."""
53
- if self.is_thinking:
54
- sys.stdout.write("\n</Thinking>")
55
- sys.stdout.flush()
56
- self.is_thinking = False
57
- self.current_line_empty = False
58
-
59
- def _display_tool_approval_prompt(self):
60
- """Displays the tool approval prompt using stored pending data."""
61
- if not self.pending_approval_data:
62
- return
63
-
64
- try:
65
- args_str = json.dumps(self.pending_approval_data.arguments, indent=2)
66
- except TypeError:
67
- args_str = str(self.pending_approval_data.arguments)
68
-
69
- self._ensure_new_line()
70
- prompt_message = (
71
- f"Tool Call: '{self.pending_approval_data.tool_name}' requests permission to run with arguments:\n"
72
- f"{args_str}\nApprove? (y/n): "
73
- )
74
- sys.stdout.write(prompt_message)
75
- sys.stdout.flush()
76
- self.current_line_empty = False
77
-
78
- async def handle_stream_event(self, event: StreamEvent):
79
- """Processes a single StreamEvent and updates the CLI display."""
80
- # A block of thinking ends if any event other than a reasoning chunk arrives.
81
- is_reasoning_only_chunk = (
82
- event.event_type == StreamEventType.ASSISTANT_CHUNK and
83
- isinstance(event.data, AssistantChunkData) and
84
- bool(event.data.reasoning) and not bool(event.data.content)
85
- )
86
- if not is_reasoning_only_chunk:
87
- self._end_thinking_block()
88
-
89
- # Most events should start on a new line.
90
- if event.event_type != StreamEventType.ASSISTANT_CHUNK:
91
- self._ensure_new_line()
92
-
93
- if event.event_type in [
94
- StreamEventType.AGENT_IDLE,
95
- StreamEventType.ERROR_EVENT,
96
- StreamEventType.TOOL_INVOCATION_APPROVAL_REQUESTED,
97
- ]:
98
- self.agent_turn_complete_event.set()
99
-
100
- if event.event_type == StreamEventType.ASSISTANT_CHUNK and isinstance(event.data, AssistantChunkData):
101
- # If this is the first output from the agent this turn, print the "Agent: " prefix.
102
- if not self.agent_has_spoken_this_turn:
103
- self._ensure_new_line()
104
- sys.stdout.write("Agent:\n")
105
- sys.stdout.flush()
106
- self.agent_has_spoken_this_turn = True
107
- self.current_line_empty = True
108
-
109
- # Stream reasoning to stdout without logger formatting.
110
- if event.data.reasoning:
111
- if not self.is_thinking:
112
- sys.stdout.write("<Thinking>\n")
113
- sys.stdout.flush()
114
- self.is_thinking = True
115
- self.current_line_empty = True # We just printed a newline
116
-
117
- sys.stdout.write(event.data.reasoning)
118
- sys.stdout.flush()
119
- self.current_line_empty = event.data.reasoning.endswith('\n')
15
+ Runs an interactive command-line interface for a single agent.
120
16
 
121
- # Stream content to stdout.
122
- if event.data.content:
123
- if not self.is_in_content_block:
124
- self._ensure_new_line() # Ensures content starts on a new line after </Thinking>
125
- self.is_in_content_block = True
126
- sys.stdout.write(event.data.content)
127
- sys.stdout.flush()
128
- self.current_line_empty = event.data.content.endswith('\n')
129
-
130
- if self.show_token_usage and event.data.is_complete and event.data.usage:
131
- self._ensure_new_line()
132
- usage = event.data.usage
133
- logger.info(
134
- f"[Token Usage: Prompt={usage.prompt_tokens}, "
135
- f"Completion={usage.completion_tokens}, Total={usage.total_tokens}]"
136
- )
137
-
138
- elif event.event_type == StreamEventType.ASSISTANT_COMPLETE_RESPONSE and isinstance(event.data, AssistantCompleteResponseData):
139
- # The reasoning has already been streamed. Do not log it again.
140
-
141
- if not self.agent_has_spoken_this_turn:
142
- # This case handles responses that might not have streamed any content chunks (e.g., only a tool call).
143
- # We still need to ensure the agent's turn is visibly terminated with a newline.
144
- self._ensure_new_line()
145
-
146
- # If there's final content that wasn't in a chunk, print it.
147
- if event.data.content:
148
- sys.stdout.write(f"Agent: {event.data.content}\n")
149
- sys.stdout.flush()
150
-
151
- if self.show_token_usage and event.data.usage:
152
- self._ensure_new_line()
153
- usage = event.data.usage
154
- logger.info(
155
- f"[Token Usage: Prompt={usage.prompt_tokens}, "
156
- f"Completion={usage.completion_tokens}, Total={usage.total_tokens}]"
157
- )
158
-
159
- self.current_line_empty = True
160
- self.reset_turn_state() # Reset for next turn
17
+ This function orchestrates the agent's lifecycle, user input, and event streaming
18
+ for an interactive session.
161
19
 
162
- elif event.event_type == StreamEventType.TOOL_INVOCATION_APPROVAL_REQUESTED and isinstance(event.data, ToolInvocationApprovalRequestedData):
163
- self.pending_approval_data = event.data
164
- self._display_tool_approval_prompt()
165
-
166
- elif event.event_type == StreamEventType.TOOL_INTERACTION_LOG_ENTRY and isinstance(event.data, ToolInteractionLogEntryData):
167
- if self.show_tool_logs:
168
- logger.info(f"[Tool Log: {event.data.log_entry}]")
169
-
170
- elif event.event_type == StreamEventType.AGENT_OPERATIONAL_PHASE_TRANSITION and isinstance(event.data, AgentOperationalPhaseTransitionData):
171
- if event.data.new_phase == AgentOperationalPhase.EXECUTING_TOOL:
172
- tool_name = event.data.tool_name or "a tool"
173
- sys.stdout.write(f"Agent: Waiting for tool '{tool_name}' to complete...\n")
174
- sys.stdout.flush()
175
- self.current_line_empty = True
176
- self.agent_has_spoken_this_turn = True
177
- elif event.data.new_phase == AgentOperationalPhase.BOOTSTRAPPING:
178
- logger.info("[Agent is initializing...]")
179
- else:
180
- phase_msg = f"[Agent Status: {event.data.new_phase.value}"
181
- if event.data.tool_name:
182
- phase_msg += f" ({event.data.tool_name})"
183
- phase_msg += "]"
184
- logger.info(phase_msg)
185
-
186
- elif event.event_type == StreamEventType.ERROR_EVENT and isinstance(event.data, ErrorEventData):
187
- logger.error(f"[Error: {event.data.message} (Source: {event.data.source})]")
188
-
189
- elif event.event_type == StreamEventType.AGENT_IDLE:
190
- logger.info("[Agent is now idle.]")
191
-
192
- else:
193
- # Add logging for unhandled events for better debugging
194
- logger.debug(f"CLI Manager: Unhandled StreamEvent type: {event.event_type.value}")
195
-
196
-
197
- async def run(agent: Agent, show_tool_logs: bool = True, show_token_usage: bool = False, initial_prompt: Optional[str] = None):
20
+ Args:
21
+ agent: The agent instance to run.
22
+ show_tool_logs: If True, displays detailed logs from tool interactions.
23
+ show_token_usage: If True, displays token usage information after each LLM call.
24
+ initial_prompt: An optional initial prompt to send to the agent automatically.
25
+ """
198
26
  if not isinstance(agent, Agent):
199
27
  raise TypeError(f"Expected an Agent instance, got {type(agent).__name__}")
200
28
 
201
29
  logger.info(f"Starting interactive CLI session for agent '{agent.agent_id}'.")
202
30
  agent_turn_complete_event = asyncio.Event()
203
- cli_manager = InteractiveCLIManager(agent_turn_complete_event, show_tool_logs, show_token_usage)
31
+ cli_display = InteractiveCLIDisplay(agent_turn_complete_event, show_tool_logs, show_token_usage)
204
32
  streamer = AgentEventStream(agent)
205
33
 
206
34
  async def process_agent_events():
35
+ """Task to continuously process and display events from the agent."""
207
36
  try:
208
37
  async for event in streamer.all_events():
209
- await cli_manager.handle_stream_event(event)
38
+ await cli_display.handle_stream_event(event)
210
39
  except asyncio.CancelledError:
211
40
  logger.info("CLI event processing task cancelled.")
212
41
  except Exception as e:
@@ -226,35 +55,29 @@ async def run(agent: Agent, show_tool_logs: bool = True, show_token_usage: bool
226
55
  await asyncio.wait_for(agent_turn_complete_event.wait(), timeout=30.0)
227
56
  except asyncio.TimeoutError:
228
57
  logger.error(f"Agent did not become idle within 30 seconds. Exiting.")
229
- # Gracefully exit if agent fails to start
230
58
  return
231
59
 
232
60
  if initial_prompt:
233
61
  logger.info(f"Initial prompt provided: '{initial_prompt}'")
234
- print(f"You: {initial_prompt}") # Mirroring user input is fine with print
62
+ print(f"You: {initial_prompt}")
235
63
  agent_turn_complete_event.clear()
236
- cli_manager.reset_turn_state()
64
+ cli_display.reset_turn_state()
237
65
  await agent.post_user_message(AgentInputUserMessage(content=initial_prompt))
238
66
  await agent_turn_complete_event.wait()
239
67
 
68
+ # Main input loop
240
69
  while True:
241
70
  agent_turn_complete_event.clear()
242
71
 
243
- if cli_manager.pending_approval_data:
244
- logger.debug("Waiting for tool approval from user...")
72
+ if cli_display.pending_approval_data:
245
73
  approval_input = await asyncio.get_event_loop().run_in_executor(None, sys.stdin.readline)
246
74
  approval_input = approval_input.strip().lower()
247
75
 
248
- approval_data = cli_manager.pending_approval_data
249
- cli_manager.pending_approval_data = None
76
+ approval_data = cli_display.pending_approval_data
77
+ cli_display.pending_approval_data = None
250
78
 
251
79
  is_approved = approval_input in ["y", "yes"]
252
80
  reason = "User approved via CLI" if is_approved else "User denied via CLI"
253
-
254
- if is_approved:
255
- logger.info(f"User approved tool invocation '{approval_data.invocation_id}'.")
256
- else:
257
- logger.info(f"User denied tool invocation '{approval_data.invocation_id}'.")
258
81
 
259
82
  await agent.post_tool_execution_approval(approval_data.invocation_id, is_approved, reason)
260
83
 
@@ -265,35 +88,30 @@ async def run(agent: Agent, show_tool_logs: bool = True, show_token_usage: bool
265
88
  user_input = user_input.rstrip('\n')
266
89
 
267
90
  if user_input.lower().strip() in ["/quit", "/exit"]:
268
- logger.info("Exit command received.")
269
91
  break
270
92
  if not user_input.strip():
271
93
  continue
272
94
 
273
- logger.debug(f"User input received, posting to agent: '{user_input}'")
274
- cli_manager.reset_turn_state()
95
+ cli_display.reset_turn_state()
275
96
  await agent.post_user_message(AgentInputUserMessage(content=user_input))
276
97
 
277
98
  await agent_turn_complete_event.wait()
278
- logger.debug("Agent turn complete, looping.")
279
99
 
280
100
  except (KeyboardInterrupt, EOFError):
281
- logger.info("Exit signal received. Shutting down CLI.")
101
+ logger.info("Exit signal received.")
282
102
  except Exception as e:
283
103
  logger.error(f"An unexpected error occurred in the CLI main loop: {e}", exc_info=True)
284
104
  finally:
285
- logger.info("Cleaning up and shutting down interactive session...")
105
+ logger.info("Shutting down interactive session...")
286
106
  if not event_task.done():
287
107
  event_task.cancel()
288
108
  try:
289
109
  await event_task
290
110
  except asyncio.CancelledError:
291
- pass # This is expected
111
+ pass
292
112
 
293
113
  if agent.is_running:
294
- logger.info("Stopping agent...")
295
114
  await agent.stop()
296
115
 
297
- logger.info("Closing event stream...")
298
116
  await streamer.close()
299
117
  logger.info("Interactive session finished.")