The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): a profile child's lease and schema retry run as that profile
Teknium36ba523cefe8
diff --git a/tests/tools/test_delegation_profile_route.py b/tests/tools/test_delegation_profile_route.pyindex 55a70ed0ca5..5e0c4f6b1af 100644--- a/tests/tools/test_delegation_profile_route.py+++ b/tests/tools/test_delegation_profile_route.py@@ -133,3 +133,41 @@ def test_secret_missing_from_target_profile_never_falls_back_to_the_launch_env(tassert get_secret("PROBE_SECRET") is None # launch value sits in os.environ; never borrowedassert get_secret("PROBE_SECRET") == "launch-secret"assert json.loads(json.dumps(_snapshot()))["model"] == "launch-model"+++def test_profile_child_lease_and_schema_retry_run_inside_the_target_profile(two_profiles):+ """The startup lease (``_swap_credential`` reloads TLS/headers from config) and the output_schema retry turn+ are child work: they run as the routed profile, like the first conversation."""+ from types import SimpleNamespace++ from tools.delegate_tool_child_run import _lease_child_credential, _validate_child_output_schema++ launch, coder = two_profiles+ seen = {}++ class _Pool:+ def acquire_lease(self, credential_id=None):+ return "e1"++ def entries(self):+ return [SimpleNamespace(id="e1", base_url="https://coder.invalid/v1", last_status=None)]++ class _Child:+ base_url, session_id, _delegate_profile_home = "https://coder.invalid/v1", "child-1", coder+ _credential_pool, _delegate_output_schema = _Pool(), {"type": "object", "required": ["ok"]}++ def _swap_credential(self, entry):+ seen["lease"] = _snapshot()+ return True++ def run_conversation(self, user_message, **kw):+ seen["retry"] = _snapshot()+ return {"final_response": '{"ok": true}', "api_calls": 1}++ child = _Child()+ _lease_child_credential(child)+ outcome = _validate_child_output_schema(child, {"final_response": "not json"}, 0, "t-1", None)+ assert outcome.valid and outcome.retries == 1+ assert seen["lease"]["home"] == str(coder) and seen["lease"]["model"] == "coder-model"+ assert seen["retry"] == {"home": str(coder), "secret": "coder-secret", "model": "coder-model"}+ assert _snapshot() == {"home": str(launch), "secret": "launch-secret", "model": "launch-model"}diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex c7861541195..b7cb06449ae 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -140,7 +140,7 @@ no `delegate_task`, `clarify`, `memory`, `send_message`, `cronjob`; keeps `execusubagent_auto_approve, inherit_mcp_toolsets, max_iterations, backend`. **Routes:** `delegation.backend` picks adelegation provider (`agent/delegation_provider.py`, `ctx.register_delegation_provider`) that answers each task's route(`tools/delegate_tool_routes.py`: model/provider fields resolved like the `delegation` section, or `profile` → the child-is built and converses inside that profile's scope) and may add enum-checked per-task schema params; it never owns+is built, leases and converses inside that profile's scope) and may add enum-checked per-task schema params; it never ownslifecycle. Internal `credentials_cfg` callers (/review) and the lifecycle API bypass it. **Child processes:** a child's backgroundprocesses are killed at its teardown and their notices are suppressed in the parent; `process_manage(action="handoff")`(children only) flips `ProcessSession.owner_task_id` to the parent under the registry lockdiff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.pyindex addbaa5f876..ad1b3dca9a8 100644--- a/tools/delegate_tool_child_run.py+++ b/tools/delegate_tool_child_run.py@@ -436,27 +436,31 @@ def _defer_close_after_timeout(child: Any, child_future: Any) -> None:def _lease_child_credential(child: Any) -> tuple[Any, Optional[str]]:"""Lease a credential from the child's pool (if any) and bind it; ``(pool, lease_id)``. The bound entry mustserve the child's endpoint: on a mixed same-provider pool the least-leased pick may target another host, so it is- released and an endpoint-matching entry is leased by id instead (#68237)."""+ released and an endpoint-matching entry is leased by id instead (#68237). Child work, so it runs in the child's+ profile scope: a lease may refresh that profile's OAuth entries, and ``_swap_credential`` re-reads TLS/header+ config for the bound endpoint."""child_pool = getattr(child, "_credential_pool", None)if child_pool is None:return None, Nonefrom agent.credential_pool import credential_pool_entry_serves_endpoint as _entry_serves_endpoint+ from tools.delegate_tool_routes import child_profile_scopebase_url = getattr(child, "base_url", None)- leased_cred_id = child_pool.acquire_lease()- if leased_cred_id is not None:- with _quiet("Failed to bind child to leased credential: %s"):- # Resolve the leased entry by id: the pool is shared with the parent/siblings, so current() is a- # mutable cursor that may already point at someone else's pick.- leased_entry = next((e for e in child_pool.entries() if e.id == leased_cred_id), None)- if not _entry_serves_endpoint(leased_entry, base_url):- child_pool.release_lease(leased_cred_id)- leased_entry = next(- (e for e in child_pool.entries() if e.last_status != "dead" and _entry_serves_endpoint(e, base_url)),- None,- )- leased_cred_id = child_pool.acquire_lease(leased_entry.id) if leased_entry is not None else None- if leased_entry is not None and hasattr(child, "_swap_credential"):- child._swap_credential(leased_entry)+ with child_profile_scope(child):+ leased_cred_id = child_pool.acquire_lease()+ if leased_cred_id is not None:+ with _quiet("Failed to bind child to leased credential: %s"):+ # Resolve the leased entry by id: the pool is shared with the parent/siblings, so current() is a+ # mutable cursor that may already point at someone else's pick.+ leased_entry = next((e for e in child_pool.entries() if e.id == leased_cred_id), None)+ if not _entry_serves_endpoint(leased_entry, base_url):+ child_pool.release_lease(leased_cred_id)+ leased_entry = next(+ (e for e in child_pool.entries() if e.last_status != "dead" and _entry_serves_endpoint(e, base_url)),+ None,+ )+ leased_cred_id = child_pool.acquire_lease(leased_entry.id) if leased_entry is not None else None+ if leased_entry is not None and hasattr(child, "_swap_credential"):+ child._swap_credential(leased_entry)return child_pool, leased_cred_iddef _merge_late_steer(result: dict[str, Any], subagent_id: Optional[str], child: Any) -> None:@@ -497,7 +501,8 @@ def _validate_child_output_schema(# Same identity as the main child turn: this runs on the parent worker's thread, and an# unmarked turn is misread as the dispatcher-owned worker by every HERMES_KANBAN_* gate.from agent.delegation_context import delegated_child_context- with delegated_child_context(str(getattr(child, "session_id", "") or "")):+ from tools.delegate_tool_routes import child_profile_scope+ with child_profile_scope(child), delegated_child_context(str(getattr(child, "session_id", "") or "")):_retry_result = child.run_conversation(user_message=build_retry_message(_schema_errors), task_id=child_task_id,stream_callback=relay_child_text,@@ -860,10 +865,9 @@ class _ChildRun:def _run_with_thread_capture():worker_thread_holder["t"] = threading.current_thread()from agent.delegation_context import delegated_child_context- from tools.delegate_tool_routes import delegated_profile_scope+ from tools.delegate_tool_routes import child_profile_scope# A profile-routed child converses as that profile (config, secrets, skills, terminal policy).- with delegated_profile_scope(getattr(child, "_delegate_profile_home", None)), \- delegated_child_context(str(getattr(child, "session_id", "") or "")):+ with child_profile_scope(child), delegated_child_context(str(getattr(child, "session_id", "") or "")):return child.run_conversation(user_message=user_message, task_id=self.child_task_id, stream_callback=self.relay_text,)diff --git a/tools/delegate_tool_routes.py b/tools/delegate_tool_routes.pyindex c288b79d14c..1d43c37aeb4 100644--- a/tools/delegate_tool_routes.py+++ b/tools/delegate_tool_routes.py@@ -135,6 +135,13 @@ def delegated_profile_scope(home: Any) -> Iterator[None]:reset_hermes_home_override(home_token)+def child_profile_scope(child: Any) -> contextlib.AbstractContextManager:+ """The profile scope a built child's own work runs in (its startup credential lease, every conversation turn+ incl. the output_schema retry); a no-op for children without a profile route. Parent bookkeeping (registry,+ heartbeat, progress, result assembly) stays outside it."""+ return delegated_profile_scope(getattr(child, "_delegate_profile_home", None))++def _profile_route(home: Path, label: Optional[str]) -> TaskRoute:"""The profile's own primary route, resolved inside its scope (its config.yaml + secrets). Thechild never borrows the launching profile's key, pool or fallback chain."""