| 1 | from agent import Agent, AgentContext, UserMessage |
| 2 | from helpers import message_queue, persist_chat, projects, subagents |
| 3 | from helpers.errors import RepairableException |
| 4 | from helpers.tool import Tool, Response |
| 5 | from initialize import initialize_agent |
| 6 | from extensions.python.hist_add_tool_result import _90_save_tool_call_file as save_tool_call_file |
| 7 | |
| 8 | |
| 9 | SUBORDINATES_DATA_KEY = "_subordinates" |
| 10 | CHILD_PARENT_CONTEXT_ID_KEY = "parent_context_id" |
| 11 | CHILD_PARENT_AGENT_NUMBER_KEY = "parent_agent_number" |
| 12 | CHILD_PARENT_CONTEXT_KIND_KEY = "parent_context_kind" |
| 13 | CHILD_PARENT_CONTEXT_LABEL_KEY = "parent_context_label" |
| 14 | CHILD_SUBORDINATE_SLOT_KEY = "subordinate_slot" |
| 15 | DEFAULT_SUBORDINATE_SLOT = "default" |
| 16 | |
| 17 | |
| 18 | def _subordinate_profile_labels(agent: Agent) -> dict[str, str]: |
| 19 | project = projects.get_context_project_name(agent.context) if agent.context else None |
| 20 | return { |
| 21 | name: subagent.title or name |
| 22 | for name, subagent in subagents.get_available_agents_dict(project).items() |
| 23 | } |
| 24 | |
| 25 | |
| 26 | def _validate_subordinate_profile(agent: Agent, profile: str) -> str: |
| 27 | agent_profile = str(profile or "").strip() |
| 28 | if not agent_profile: |
| 29 | return "" |
| 30 | |
| 31 | labels = _subordinate_profile_labels(agent) |
| 32 | if agent_profile in labels: |
| 33 | return agent_profile |
| 34 | |
| 35 | available = ", ".join( |
| 36 | f"{key} ({label})" if label and label != key else key |
| 37 | for key, label in sorted(labels.items()) |
| 38 | ) |
| 39 | if not available: |
| 40 | available = "none" |
| 41 | raise RepairableException( |
| 42 | f"Agent profile '{agent_profile}' not found. Use one of the available profiles: {available}." |
| 43 | ) |
| 44 | |
| 45 | |
| 46 | def _register_subordinate(parent: Agent, subordinate: Agent, slot: str) -> None: |
| 47 | subordinates = parent.get_data(SUBORDINATES_DATA_KEY) |
| 48 | if not isinstance(subordinates, dict): |
| 49 | subordinates = {} |
| 50 | parent.set_data(SUBORDINATES_DATA_KEY, subordinates) |
| 51 | subordinates[subordinate.context.id] = subordinate |
| 52 | subordinate.set_data(Agent.DATA_NAME_SUPERIOR, parent) |
| 53 | if slot == DEFAULT_SUBORDINATE_SLOT and subordinate.context is parent.context: |
| 54 | parent.set_data(Agent.DATA_NAME_SUBORDINATE, subordinate) |
| 55 | |
| 56 | |
| 57 | def _is_child_context(context: AgentContext, parent: Agent, slot: str | None = None) -> bool: |
| 58 | if context.get_output_data(CHILD_PARENT_CONTEXT_ID_KEY) != parent.context.id: |
| 59 | return False |
| 60 | if context.get_output_data(CHILD_PARENT_AGENT_NUMBER_KEY) != parent.number: |
| 61 | return False |
| 62 | if context.agent0.number != parent.number + 1: |
| 63 | return False |
| 64 | return slot is None or context.get_output_data(CHILD_SUBORDINATE_SLOT_KEY) == slot |
| 65 | |
| 66 | |
| 67 | def _is_live_context(context: AgentContext) -> bool: |
| 68 | return not isinstance(context, AgentContext) or AgentContext.get(context.id) is context |
| 69 | |
| 70 | |
| 71 | def _find_subordinate(parent: Agent, context_id: str, slot: str) -> Agent | None: |
| 72 | registered = parent.get_data(SUBORDINATES_DATA_KEY) |
| 73 | registered = registered if isinstance(registered, dict) else {} |
| 74 | if context_id: |
| 75 | subordinate = registered.get(context_id) |
| 76 | if ( |
| 77 | subordinate |
| 78 | and _is_live_context(subordinate.context) |
| 79 | and _is_child_context(subordinate.context, parent) |
| 80 | ): |
| 81 | return subordinate |
| 82 | context = AgentContext.get(context_id) |
| 83 | if not context or not _is_child_context(context, parent): |
| 84 | raise RepairableException( |
| 85 | f"Subordinate context '{context_id}' was not found under {parent.agent_name}." |
| 86 | ) |
| 87 | subordinate = context.agent0 |
| 88 | _register_subordinate(parent, subordinate, slot) |
| 89 | return subordinate |
| 90 | |
| 91 | existing = parent.get_data(Agent.DATA_NAME_SUBORDINATE) |
| 92 | if slot == DEFAULT_SUBORDINATE_SLOT and existing is not None: |
| 93 | return existing |
| 94 | |
| 95 | registered_matches = [ |
| 96 | subordinate |
| 97 | for subordinate in registered.values() |
| 98 | if _is_live_context(subordinate.context) |
| 99 | and _is_child_context(subordinate.context, parent, slot) |
| 100 | ] |
| 101 | if registered_matches: |
| 102 | return max( |
| 103 | registered_matches, |
| 104 | key=lambda subordinate: subordinate.context.created_at, |
| 105 | ) |
| 106 | |
| 107 | matches = [ |
| 108 | context |
| 109 | for context in AgentContext.all() |
| 110 | if _is_child_context(context, parent, slot) |
| 111 | ] |
| 112 | if not matches: |
| 113 | return None |
| 114 | subordinate = max(matches, key=lambda context: context.created_at).agent0 |
| 115 | _register_subordinate(parent, subordinate, slot) |
| 116 | return subordinate |
| 117 | |
| 118 | |
| 119 | def get_or_create_subordinate( |
| 120 | parent: Agent, |
| 121 | *, |
| 122 | profile: str = "", |
| 123 | reset: bool | str = False, |
| 124 | context_id: str = "", |
| 125 | name: str = "", |
| 126 | message: str = "", |
| 127 | slot: str = DEFAULT_SUBORDINATE_SLOT, |
| 128 | ) -> Agent: |
| 129 | requested_profile = _validate_subordinate_profile(parent, profile) |
| 130 | target_context_id = str(context_id or "").strip() |
| 131 | reset_requested = str(reset).lower().strip() == "true" |
| 132 | if target_context_id and reset_requested: |
| 133 | raise RepairableException( |
| 134 | "`context_id` continues an existing subordinate and requires reset=false. " |
| 135 | "Omit `context_id` to create a fresh subordinate." |
| 136 | ) |
| 137 | |
| 138 | subordinate = ( |
| 139 | None |
| 140 | if reset_requested |
| 141 | else _find_subordinate(parent, target_context_id, slot) |
| 142 | ) |
| 143 | if subordinate: |
| 144 | current_profile = str(getattr(subordinate.config, "profile", "") or "") |
| 145 | if requested_profile and current_profile != requested_profile: |
| 146 | raise RepairableException( |
| 147 | f"Subordinate already uses profile '{current_profile or 'default'}'. " |
| 148 | f"Set reset=true and omit `context_id` to switch to '{requested_profile}'." |
| 149 | ) |
| 150 | if subordinate.context is not parent.context and subordinate.context.is_running(): |
| 151 | raise RepairableException( |
| 152 | f"Subordinate context '{subordinate.context.id}' is still running. " |
| 153 | "Await or cancel its parallel job before continuing it." |
| 154 | ) |
| 155 | return subordinate |
| 156 | |
| 157 | override_settings = {"agent_profile": requested_profile} if requested_profile else None |
| 158 | subordinate = Agent(parent.number + 1, initialize_agent(override_settings=override_settings)) |
| 159 | context = subordinate.context |
| 160 | context.name = str(name or "").strip() or _short_label(message) or subordinate.agent_name |
| 161 | context.set_output_data(CHILD_PARENT_CONTEXT_ID_KEY, parent.context.id) |
| 162 | context.set_output_data(CHILD_PARENT_AGENT_NUMBER_KEY, parent.number) |
| 163 | context.set_output_data(CHILD_PARENT_CONTEXT_KIND_KEY, "subordinate") |
| 164 | context.set_output_data(CHILD_PARENT_CONTEXT_LABEL_KEY, context.name) |
| 165 | context.set_output_data(CHILD_SUBORDINATE_SLOT_KEY, slot) |
| 166 | |
| 167 | project = projects.get_context_project_name(parent.context) |
| 168 | if project: |
| 169 | projects.activate_project(context.id, project, mark_dirty=False) |
| 170 | model_override = parent.context.get_data("chat_model_override") |
| 171 | if model_override: |
| 172 | context.set_data("chat_model_override", model_override) |
| 173 | |
| 174 | _register_subordinate(parent, subordinate, slot) |
| 175 | return subordinate |
| 176 | |
| 177 | |
| 178 | async def run_subordinate( |
| 179 | parent: Agent, |
| 180 | subordinate: Agent, |
| 181 | message: str, |
| 182 | attachments: list[str] | None = None, |
| 183 | ) -> str: |
| 184 | assignment = str(message or "").strip() |
| 185 | if not assignment: |
| 186 | raise RepairableException("call_subordinate requires a non-empty `message`.") |
| 187 | |
| 188 | attachment_paths = [str(item) for item in attachments or []] |
| 189 | if subordinate.context is not parent.context: |
| 190 | message_queue.log_user_message( |
| 191 | subordinate.context, |
| 192 | assignment, |
| 193 | attachment_paths, |
| 194 | source=" (subordinate)", |
| 195 | ) |
| 196 | subordinate.hist_add_user_message( |
| 197 | UserMessage(message=assignment, attachments=attachment_paths) |
| 198 | ) |
| 199 | if subordinate.context is not parent.context: |
| 200 | persist_chat.save_tmp_chat(subordinate.context) |
| 201 | |
| 202 | try: |
| 203 | result = await subordinate.monologue() |
| 204 | subordinate.history.new_topic() |
| 205 | return result |
| 206 | finally: |
| 207 | if subordinate.context is not parent.context: |
| 208 | persist_chat.save_tmp_chat(subordinate.context) |
| 209 | |
| 210 | |
| 211 | def _short_label(text: str, limit: int = 80) -> str: |
| 212 | return " ".join(str(text or "").split())[:limit].rstrip() |
| 213 | |
| 214 | |
| 215 | class Delegation(Tool): |
| 216 | |
| 217 | async def execute(self, message="", reset="", context_id="", **kwargs): |
| 218 | attachments = kwargs.get("attachments") |
| 219 | attachments = attachments if isinstance(attachments, list) else [] |
| 220 | subordinate = get_or_create_subordinate( |
| 221 | self.agent, |
| 222 | profile=kwargs.get("profile", kwargs.get("agent_profile", "")), |
| 223 | reset=reset, |
| 224 | context_id=context_id or kwargs.get("agent_id", ""), |
| 225 | name=kwargs.get("name", ""), |
| 226 | message=message, |
| 227 | ) |
| 228 | result = await run_subordinate(self.agent, subordinate, message, attachments) |
| 229 | |
| 230 | # hint to use includes for long responses |
| 231 | additional = {"context_id": subordinate.context.id} |
| 232 | if len(result) >= save_tool_call_file.LEN_MIN: |
| 233 | hint = self.agent.read_prompt("fw.hint.call_sub.md") |
| 234 | if hint: |
| 235 | additional["hint"] = hint |
| 236 | |
| 237 | # result |
| 238 | return Response(message=result, break_loop=False, additional=additional) |
| 239 | |
| 240 | def get_log_object(self): |
| 241 | return self.agent.context.log.log( |
| 242 | type="subagent", |
| 243 | heading=f"icon://communication {self.agent.agent_name}: Calling Subordinate Agent", |
| 244 | content="", |
| 245 | kvps=self.args, |
| 246 | ) |