The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): redact child output before parent consumers
helix4u9ed387ce2301
diff --git a/tests/tools/test_async_delegation_worker_routing.py b/tests/tools/test_async_delegation_worker_routing.pyindex e642dd62cce..1f70a666d7b 100644--- a/tests/tools/test_async_delegation_worker_routing.py+++ b/tests/tools/test_async_delegation_worker_routing.py@@ -18,6 +18,8 @@ class Store:def _apply(self, operation, payload):self.calls.append((operation, payload))+ if operation == 'delegation.read':+ return {'value': {'delegation_id': payload['delegation_id'], 'result': {'summary': 'done'}}}return {'value': True}diff --git a/tests/tools/test_delegated_output_redaction.py b/tests/tools/test_delegated_output_redaction.pynew file mode 100644index 00000000000..18a9c3cc9ea--- /dev/null+++ b/tests/tools/test_delegated_output_redaction.py@@ -0,0 +1,417 @@+"""Completed child output must be redacted before delegation consumers (#137594)."""++import json+import queue+import time+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from tools import async_delegation as ad+from tools import delegate_tool as delegate+from tools import delegate_tool_results as results+from tools.process_registry import process_registry+from tests.tools.test_delegate_output_schema import _StubChild, _StubParent++SECRET = "sk-ant-" + "syntheticdelegationcredential" * 3+PEM = (+ "-----BEGIN PRIVATE KEY-----\n"+ + "c3ludGhldGlj" * 100+ + "\n-----END PRIVATE KEY-----"+)++[email protected](autouse=True)+def isolated(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ ad._reset_for_tests()+ yield+ ad._reset_for_tests()+++class _Parent(_StubParent):+ session_id = "parent-session"++ def __init__(self):+ self._memory_manager = SimpleNamespace(on_delegation=Mock())++[email protected]("text", [SECRET, PEM])+def test_child_result_events_memory_hooks_and_spill_use_redacted_output(+ text, tmp_path, monkeypatch+):+ import hermes_cli.plugins+ from agent.redact import redact_for_egress++ hooks = Mock()+ monkeypatch.setattr(hermes_cli.plugins, "invoke_hook", hooks)+ monkeypatch.setattr(delegate, "_load_config", lambda: {"max_summary_chars": 2000})+ events = []+ summary = text + "\n" + "ordinary explanation\n" * 180+ child = _StubChild([summary])+ child.tool_progress_callback = lambda event, **kw: events.append((event, kw))+ parent = _Parent()++ entry = results._run_child_lifecycle(0, "summarize the task", child, parent)++ assert entry["status"] == "completed"+ assert text not in entry["summary"]+ completion = next(+ payload for name, payload in events if name == "subagent.complete"+ )+ assert completion["preview"] == redact_for_egress(summary)[:160]+ assert text not in parent._memory_manager.on_delegation.call_args.kwargs["result"]+ stop = next(+ call.kwargs for call in hooks.call_args_list if call.args[0] == "subagent_stop"+ )+ assert text not in stop["child_summary"]+ spills = list((tmp_path / "cache" / "delegation").glob("subagent-summary-*.txt"))+ assert spills+ assert text not in spills[0].read_text(encoding="utf-8")+++def _record():+ record = {+ "delegation_id": "synthetic-delegation",+ "dispatched_at": time.time(),+ "session_key": "agent:example:dm:route",+ "origin_session_id": "origin-session",+ "parent_session_id": "parent-session",+ "goal": "retain the parent goal",+ "context": "retain the parent context",+ "model": "test-model",+ }+ ad._persist_dispatch(record)+ return record+++def test_async_queue_and_durable_result_redact_child_output_without_changing_routing(+ monkeypatch,+):+ record = _record()+ target = queue.Queue()+ monkeypatch.setattr(process_registry, "completion_queue", target)+ payload = {+ "status": "completed",+ "summary": SECRET,+ "error": SECRET,+ "future_child_field": SECRET,+ }++ ad._push_completion_event(record, payload, "completed")++ event = target.get_nowait()+ assert SECRET not in json.dumps(event)+ assert all(+ event[key] == record[key]+ for key in ("delegation_id", "session_key", "goal", "context")+ )+ stored = ad.get_durable_delegation(record["delegation_id"])+ assert stored is not None+ assert SECRET not in json.dumps(stored["result"])+ assert payload["summary"] == SECRET # the producer's own value is not mutated+ with ad._transaction() as conn:+ row = conn.execute(+ "SELECT event_json,result_json FROM async_delegations"+ ).fetchone()+ assert SECRET not in "".join(row)+++def test_old_durable_results_are_redacted_on_read_replay_and_failure_roster():+ record = _record()+ event = {+ **record,+ "type": "async_delegation",+ "status": "failed",+ "summary": SECRET,+ "error": SECRET,+ }+ result = {"status": "failed", "summary": SECRET, "error": SECRET}+ with ad._transaction() as conn:+ conn.execute(+ "UPDATE async_delegations SET state='failed',completed_at=?,event_json=?,result_json=?",+ (time.time(), json.dumps(event), json.dumps(result)),+ )++ stored = ad.get_durable_delegation(record["delegation_id"])+ assert stored is not None+ assert SECRET not in json.dumps(stored["result"])+ target = queue.Queue()+ assert ad.restore_undelivered_completions(target) == 1+ replay = target.get_nowait()+ assert replay["restored"] is True+ assert replay["session_key"] == record["session_key"]+ assert SECRET not in json.dumps(replay)+ failures = ad.failed_delegations_for_session(parent_session_id="parent-session")+ assert len(failures) == 1 and failures[0]["goal"] == record["goal"]+ assert SECRET not in json.dumps(failures)+++def test_partial_child_receipt_is_sanitized_before_recovery_storage():+ record = _record()+ entry = {+ "task_index": 0,+ "status": "completed",+ "summary": SECRET,+ "schema_valid": True,+ }++ ad.record_unit_child(record["delegation_id"], entry)++ saved = ad.get_durable_delegation(record["delegation_id"])+ assert saved is not None+ stored = saved["result"]+ assert SECRET not in json.dumps(stored)+ assert stored["results"][0]["schema_valid"] is False+++def test_redacted_schema_verdict_describes_delivered_summary_without_rerunning_child():+ child = _StubChild([json.dumps({"value": SECRET})])+ child._delegate_output_schema = {+ "type": "object",+ "properties": {"value": {"const": SECRET}},+ "required": ["value"],+ }++ entry = delegate._run_single_child(0, "produce structured output", child, _Parent())++ assert entry["status"] == "completed"+ assert entry["schema_valid"] is False+ assert SECRET not in json.dumps(entry)+ assert len(child.calls) == 1+++def test_redacted_json_can_still_satisfy_its_schema():+ child = _StubChild([json.dumps({"value": SECRET})])+ child._delegate_output_schema = {+ "type": "object",+ "properties": {"value": {"type": "string"}},+ "required": ["value"],+ }++ entry = delegate._run_single_child(0, "produce structured output", child, _Parent())++ assert entry["schema_valid"] is True+ assert SECRET not in entry["summary"]+ assert "schema_note" not in entry and len(child.calls) == 1+++def test_schema_revalidation_fault_does_not_leak_the_exception_or_raw_summary(+ monkeypatch,+):+ from tools.delegation_redaction import redact_child_result+ import tools.delegation_output_schema as schema++ def fail(*args):+ raise RuntimeError(SECRET)++ monkeypatch.setattr(schema, "validate_output", fail)+ entry = redact_child_result({"summary": SECRET, "schema_valid": True}, {})++ assert entry["schema_valid"] is False+ assert SECRET not in json.dumps(entry)+ assert "unavailable" in entry["schema_errors"][0]+++def test_redactor_failure_never_falls_back_to_raw_output(monkeypatch):+ import agent.redact++ def fail(*args, **kwargs):+ raise RuntimeError(SECRET)++ monkeypatch.setattr(agent.redact, "redact_sensitive_text", fail)+ child = _StubChild([SECRET])+ events = []+ child.tool_progress_callback = lambda name, **kw: events.append((name, kw))+ entry = delegate._run_single_child(0, "finish safely", child, _Parent())+ assert SECRET not in json.dumps(entry)+ assert agent.redact.REDACTION_UNAVAILABLE in entry["summary"]+ assert entry["status"] == "completed"+ completion = next(kw for name, kw in events if name == "subagent.complete")+ assert completion["status"] == "completed"+ assert agent.redact.REDACTION_UNAVAILABLE in completion["preview"]+ assert SECRET not in json.dumps(completion)+++def test_ordinary_text_and_accounting_survive_redaction():+ child = _StubChild(["Completed the requested analysis."])+ entry = delegate._run_single_child(0, "ordinary task", child, _Parent())+ assert entry["summary"] == "Completed the requested analysis."+ assert entry["status"] == "completed"+ assert entry["api_calls"] == 1+ assert "schema_valid" not in entry+++def test_raised_child_error_and_completion_event_are_scrubbed():+ child = _StubChild([])+ child.run_conversation = Mock(side_effect=RuntimeError(SECRET))+ events = []+ child.tool_progress_callback = lambda name, **kw: events.append((name, kw))++ entry = delegate._run_single_child(0, "finish the task", child, _Parent())++ assert entry["status"] == "error"+ assert entry["error"] and SECRET not in json.dumps(entry)+ complete = next(kw for name, kw in events if name == "subagent.complete")+ assert complete["status"] == "error"+ assert complete["preview"] and SECRET not in json.dumps(complete)+++def test_tool_preview_and_hook_targets_are_redacted_before_shortening():+ from agent.redact import redact_for_egress++ tail = results._extract_output_tail(+ {"messages": [{"role": "tool", "content": PEM}]}, max_chars=160+ )+ assert tail[0]["preview"] == redact_for_egress(PEM)[:160]+ arguments = json.dumps({"path": PEM, PEM: "ordinary payload"})+ summary = results._summarize_tool_arguments(arguments)+ assert summary["targets"]["path"] == redact_for_egress(PEM)[:1024]+ assert summary["argument_keys"] == [redact_for_egress(PEM)[:128], "path"]+ history = results._subagent_stop_tool_call_history(+ [{"tool": "read_file", "input_summary": summary}]+ )+ assert "c3ludGhldGlj" not in json.dumps(history)+++def test_process_receipts_redact_complete_buffers_before_taking_tails(monkeypatch):+ from agent.redact import redact_for_egress+ from tools.delegate_tool_child_run import _ChildRun++ child = _StubChild([])+ run = _ChildRun(child, _Parent(), 0, "task", None, None)+ process = SimpleNamespace(+ id="process-id",+ command=PEM,+ started_at=time.time(),+ exit_code=0,+ output_buffer=PEM,+ )+ monkeypatch.setattr(process_registry, "running_owned_by", lambda _: [process])+ monkeypatch.setattr(+ process_registry, "unread_completions_owned_by", lambda _: [process]+ )+ entry = {}++ run.account_background_processes(entry)++ assert entry["orphaned_processes"][0]["command"] == redact_for_egress(PEM)[:200]+ receipt = entry["unread_completions"][0]+ assert receipt["output_tail"] == redact_for_egress(PEM)[-600:]+ assert receipt["session_id"] == "process-id" and receipt["exit_code"] == 0+++def test_parent_instructions_and_delivery_identity_are_not_redacted():+ from tools.delegation_redaction import redact_completion_event++ parent_fields = {+ key: SECRET+ for key in (+ "delegation_id",+ "session_key",+ "parent_session_id",+ "origin_session_id",+ "origin_ui_session_id",+ "goal",+ "context",+ "model",+ "scope_id",+ "user_id",+ "user_name",+ "group",+ )+ }+ event = {**parent_fields, "goals": [SECRET], "results": [{"summary": SECRET}]}++ cleaned = redact_completion_event(event)++ assert all(cleaned[key] == value for key, value in parent_fields.items())+ assert cleaned["goals"] == [SECRET]+ assert SECRET not in json.dumps(cleaned["results"])+ assert event["results"][0]["summary"] == SECRET+++def test_worker_ipc_receives_only_redacted_results_and_events(monkeypatch):+ remote = Mock()+ monkeypatch.setattr(ad, "worker_ledger", lambda: remote)++ ad._persist_completion({"goal": SECRET, "summary": SECRET}, {"summary": SECRET})+ ad.record_unit_child("delegation-id", {"task_index": 2, "summary": SECRET})++ event, result = remote.complete.call_args.args+ assert event["goal"] == SECRET+ assert SECRET not in event["summary"] and SECRET not in result["summary"]+ assert SECRET not in json.dumps(remote.child.call_args.args[1])+ remote.read.return_value = {"result": {"summary": SECRET}, "origin_session": SECRET}+ saved = ad.get_durable_delegation("delegation-id")+ assert saved is not None+ assert saved["origin_session"] == SECRET+ assert SECRET not in saved["result"]["summary"]+++def test_owner_recovery_sanitizes_old_partial_results_and_diagnostics(monkeypatch):+ import tools.async_delegation_recovery_hints as hints++ record = _record()+ with ad._transaction() as conn:+ conn.execute(+ "UPDATE async_delegations SET task_json=?,result_json=?",+ (+ json.dumps({"is_batch": True, "goals": [record["goal"]]}),+ json.dumps(+ {+ "partial": True,+ "results": [+ {"task_index": 0, "summary": SECRET, "status": "completed"}+ ],+ }+ ),+ ),+ )+ monkeypatch.setattr(ad, "_owner_liveness", lambda: lambda *_: False)+ monkeypatch.setattr(hints, "transcript_tails", lambda _: {"0": SECRET})+ monkeypatch.setattr(hints, "git_state_hint", lambda _: {"status": SECRET})++ assert ad.recover_abandoned_delegations() == 1++ with ad._transaction() as conn:+ event_json, result_json = conn.execute(+ "SELECT event_json,result_json FROM async_delegations"+ ).fetchone()+ assert SECRET not in event_json + result_json+ assert json.loads(result_json)["results"][0]["status"] == "completed"+++def test_batch_failure_notice_scrubs_entry_without_finishing_batch(monkeypatch):+ record = _record()+ record["status"] = "running"+ with ad._records_lock:+ ad._records[record["delegation_id"]] = record+ target = queue.Queue()+ monkeypatch.setattr(process_registry, "completion_queue", target)++ ad.push_task_failure_notice(+ record["delegation_id"],+ {"task_index": 1, "status": "failed", "error": SECRET},+ n_tasks=2,+ )++ event = target.get_nowait()+ assert event["status"] == "running" and event["task_failure_notice"] is True+ assert event["results"][0]["status"] == "failed"+ assert SECRET not in json.dumps(event)+ assert ad._records[record["delegation_id"]]["status"] == "running"+++def test_forced_redaction_does_not_follow_optional_display_setting(monkeypatch):+ from agent.redact import redact_sensitive_text++ monkeypatch.setattr("agent.redact._redact_enabled", lambda: False)+ assert redact_sensitive_text(SECRET) == SECRET+ entry = delegate._run_single_child(+ 0, "finish the task", _StubChild([SECRET]), _Parent()+ )+ assert entry["status"] == "completed" and SECRET not in entry["summary"]diff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex d36e9fd1509..55be32d3d6a 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -24,6 +24,7 @@ from hermes_constants import get_hermes_home, hermes_home_keyfrom tools.daemon_pool import DaemonThreadPoolExecutorfrom tools.thread_context import propagate_context_to_threadfrom tools.async_delegation_worker import worker_ledger, require_ledger_owner+from tools.delegation_redaction import redact_child_result, redact_completion_eventlogger = logging.getLogger(__name__)@@ -211,6 +212,7 @@ def _prune_durable_records() -> None:def _persist_completion(event: dict[str, Any], result: dict[str, Any]) -> None:+ event, result = redact_completion_event(event), redact_child_result(result)if remote := worker_ledger():return remote.complete(event, result)now = time.time()@@ -227,6 +229,7 @@ def record_unit_child(delegation_id: str, entry: dict[str, Any]) -> None:the unit joins loses only the children that had not finished. Stored in ``result_json`` (overwritten by the realresult at finalize); ``recover_abandoned_delegations`` replays it. Best-effort: a failed write costs recoveryfidelity, never the live result."""+ entry = redact_child_result(entry)if remote := worker_ledger():return remote.child(delegation_id, entry)try:@@ -235,7 +238,7 @@ def record_unit_child(delegation_id: str, entry: dict[str, Any]) -> None:(delegation_id,)).fetchone()if row is None:return- partial = json.loads(row[0] or "{}") or {}+ partial = redact_child_result(json.loads(row[0] or "{}") or {})results = [r for r in partial.get("results") or [] if r.get("task_index") != entry.get("task_index")]results.append(entry)conn.execute("UPDATE async_delegations SET result_json=?, updated_at=? WHERE delegation_id=? AND state='running'",@@ -312,6 +315,7 @@ def recover_abandoned_delegations() -> int:**{k: task[k] for k in _ROUTING_KEYS if task.get(k)}}result = {"status": "unknown", "summary": None, "error": event["error"], **diagnostics,**({"results": recovered_results} if recovered_results else {})}+ event, result = redact_completion_event(event), redact_child_result(result)conn.execute("""UPDATE async_delegations SET state='unknown', completed_at=?,updated_at=?, event_json=?, result_json=?, delivery_state='pending'WHERE delegation_id=?""", (now, now, json.dumps(event), json.dumps(result), delegation_id))@@ -373,6 +377,7 @@ def _replay_pending(conn, rows, target_queue, now: float) -> int:continueevt = json.loads(payload)if isinstance(evt, dict):+ evt = redact_completion_event(evt)evt["restored"] = Truetarget_queue.put(evt)with _orphan_lock:@@ -613,7 +618,10 @@ def _event_delivery(fn, evt: dict[str, Any], claim_id: str) -> None:def get_durable_delegation(delegation_id: str) -> Optional[dict[str, Any]]:if remote := worker_ledger():- return remote.read(delegation_id)+ saved = remote.read(delegation_id)+ if saved is not None and saved.get("result") is not None:+ return {**saved, "result": redact_child_result(saved["result"])}+ return savedwith _DB_LOCK, _transaction() as conn:row = conn.execute("""SELECT origin_session, state, dispatched_at, completed_at,result_json, delivery_state, delivery_attempts,@@ -621,7 +629,7 @@ def get_durable_delegation(delegation_id: str) -> Optional[dict[str, Any]]:FROM async_delegations WHERE delegation_id=?""", (delegation_id,)).fetchone()return None if row is None else {"delegation_id": delegation_id, "origin_session": row[0], "state": row[1], "dispatched_at": row[2],- "completed_at": row[3], "result": json.loads(row[4]) if row[4] else None, "delivery_state": row[5],+ "completed_at": row[3], "result": redact_child_result(json.loads(row[4])) if row[4] else None, "delivery_state": row[5],"delivery_attempts": row[6], "origin_session_id": row[7] or ""}@@ -661,7 +669,7 @@ def failed_delegations_for_session((*(val for _, val in selectors), cutoff, limit)).fetchall()failed: list[dict[str, Any]] = []for delegation_id, state, dispatched_at, completed_at, task_json, result_json in rows:- task, result = _json_object(task_json), _json_object(result_json)+ task, result = _json_object(task_json), redact_child_result(_json_object(result_json))goals = task.get("goals") if isinstance(task.get("goals"), list) and task["goals"] else [task.get("goal") or ""]goal_for = dict(zip(task.get("task_indexes") or range(len(goals)), goals))tasks = result["results"] if isinstance(result.get("results"), list) else [] if task.get("is_batch") else [result]@@ -965,6 +973,7 @@ def _push_completion_event(record: dict[str, Any], result: dict[str, Any], statu(``is_batch``) carry the per-task ``results`` list (plus live transcript paths, thefull-fidelity record of each child's run) instead of a single summary. Best-effort: failuremust not crash the worker, but it WOULD mean a silently-lost result, so we log loudly."""+ result = redact_child_result(result)is_batch = bool(record.get("is_batch"))label = " batch" if is_batch else ""try:@@ -1019,6 +1028,7 @@ def push_task_failure_notice(delegation_id: str, entry: dict[str, Any], *, n_tas``type="async_delegation"`` event shape as the batch result (so every drain/route/format pathtreats it identically) with ``task_failure_notice=True`` and a single-entry ``results`` list; thebatch record is NOT finalized and its consolidated result still arrives as before."""+ entry = redact_child_result(entry)with _records_lock:record = _records.get(delegation_id)if record is None or record.get("status") not in _ACTIVE_STATES:diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.pyindex d676408333a..ac33918c283 100644--- a/tools/delegate_tool_child_run.py+++ b/tools/delegate_tool_child_run.py@@ -9,6 +9,8 @@ import jsonimport osimport threadingimport time+from agent.redact import redact_for_egress+from tools.delegation_redaction import redact_child_resultfrom concurrent.futures import TimeoutError as FuturesTimeoutErrorfrom typing import Any, Dict, List, Optionalfrom agent.compression_marker import elide@@ -733,7 +735,7 @@ class _ChildRun:"""Inspect + prune the child worktree, reporting into the entry (no-op without isolation)."""info = self.worktree_infoif info is None:- return entry_dict+ return redact_child_result(entry_dict, getattr(self.child, "_delegate_output_schema", None))from tools import subagent_worktreetry:entry_dict["worktree"] = subagent_worktree.finalize_subagent_worktree(info)@@ -742,7 +744,7 @@ class _ChildRun:# via the shared factory so the two producers never drift.logger.warning("worktree finalize failed: %s", e)entry_dict["worktree"] = subagent_worktree.unproven_worktree_payload(info, f"finalize raised: {e}")- return entry_dict+ return redact_child_result(entry_dict, getattr(self.child, "_delegate_output_schema", None))def seed_workspace(self) -> None:"""Seed cwd/container aliases and optional worktree isolation for the child;@@ -776,8 +778,8 @@ class _ChildRun:"""Shared tail of every failure path: emit ``subagent.complete`` (``status`` defaults to the entry's), notethe steer text that won the race with the failure, report the worktree."""_safe_progress(- self.child_progress_cb, "subagent.complete", preview=preview, status=status or entry["status"],- duration_seconds=entry["duration_seconds"], summary=summary,+ self.child_progress_cb, "subagent.complete", preview=redact_for_egress(preview), status=status or entry["status"],+ duration_seconds=entry["duration_seconds"], summary=redact_for_egress(summary) if summary is not None else None,)_append_missed_steer(entry, late_steer)return self.attach_worktree(entry)@@ -960,7 +962,7 @@ class _ChildRun:"_child_role": getattr(child, "_delegate_role", None),"diagnostic_path": diagnostic_path,}- self.finish_failed(_error_entry, _late_pending_steer, preview=f"Timed out after {duration}s" if is_timeout else str(exc))+ _error_entry = self.finish_failed(_error_entry, _late_pending_steer, preview=f"Timed out after {duration}s" if is_timeout else str(exc))close_deferred = is_timeout and not future.done()if close_deferred:_defer_close_after_timeout(child, future)@@ -999,13 +1001,13 @@ class _ChildRun:leftover = process_registry.running_owned_by(self.child_task_id)if leftover:entry["orphaned_processes"] = [- {"session_id": s.id, "command": s.command[:200], "runtime_seconds": round(time.time() - s.started_at)}+ {"session_id": s.id, "command": redact_for_egress(s.command)[:200], "runtime_seconds": round(time.time() - s.started_at)}for s in leftover]unread = process_registry.unread_completions_owned_by(self.child_task_id)if unread:entry["unread_completions"] = [- {"session_id": s.id, "command": s.command[:200], "exit_code": s.exit_code,- "output_tail": _output_tail(s, 600)} for s in unread]+ {"session_id": s.id, "command": redact_for_egress(s.command)[:200], "exit_code": s.exit_code,+ "output_tail": redact_for_egress(_output_tail(s, len(s.output_buffer)))[-600:]} for s in unread]def emit_complete(self, result: dict[str, Any], entry: dict[str, Any], duration: float) -> None:"""Fire ``subagent.complete`` with the per-branch observability payload (tokens, cost, files touched,@@ -1013,6 +1015,7 @@ class _ChildRun:if not self.child_progress_cb:returnchild = self.child+ entry.update(redact_child_result(entry, getattr(child, "_delegate_output_schema", None)))summary = entry["summary"]_files_read: list = []with _quiet(None):@@ -1040,7 +1043,7 @@ class _ChildRun:if _cost_usd is not None:with _quiet(None):complete_kwargs["cost_usd"] = float(_cost_usd)- _safe_progress(self.child_progress_cb, "subagent.complete", **complete_kwargs)+ _safe_progress(self.child_progress_cb, "subagent.complete", **redact_child_result(complete_kwargs))def cleanup(self, *, heartbeat: _Heartbeat, child_pool: Any, leased_cred_id: Any, close_deferred: bool) -> None:"""Finally-path teardown (idempotent, never raises). Order matters: stop heartbeat → drop registry entry →diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.pyindex a81ca4d34d7..476057ca636 100644--- a/tools/delegate_tool_progress.py+++ b/tools/delegate_tool_progress.py@@ -38,7 +38,8 @@ def _safe_progress(cb: Any, event_type: Any, *args: Any, **kwargs: Any) -> None:def _clean_error_text(error: Any, max_chars: int = 200) -> str:"""Reduce an error payload (traceback / JSON wall) to one clean line: the exception message (last line of atraceback) or the first non-empty line, hard-capped in length."""- lines = [ln.strip() for ln in str(error or "").strip().splitlines() if ln.strip()]+ from agent.redact import redact_for_egress+ lines = [ln.strip() for ln in redact_for_egress(str(error or "")).strip().splitlines() if ln.strip()]if not lines:return ""line = lines[-1] if lines[0].startswith("Traceback") else lines[0]diff --git a/tools/delegate_tool_results.py b/tools/delegate_tool_results.pyindex e771e4dc1f2..947880ef73b 100644--- a/tools/delegate_tool_results.py+++ b/tools/delegate_tool_results.py@@ -7,6 +7,8 @@ import jsonimport threadingfrom typing import Any, Dict, List, Optionalfrom urllib.parse import urlsplit, urlunsplit+from agent.redact import redact_for_egress+from tools.delegation_redaction import redact_child_resultlogger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module@@ -66,7 +68,7 @@ def _extract_output_tail(result: dict[str, Any], *, max_entries: int = 12, max_cbreakif not isinstance(msg, dict) or msg.get("role") != "tool":continue- content = _stringify_tool_content(msg.get("content") or "")+ content = redact_for_egress(_stringify_tool_content(msg.get("content") or ""))tool_name = name_by_call_id.get(msg.get("tool_call_id") or "", "tool")tail.append({"tool": tool_name, "preview": content[:max_chars], "is_error": _looks_like_error_output(content)})tail.reverse()@@ -85,7 +87,7 @@ def _sanitize_tool_target(key: str, value: Any) -> Any:return cleaned or Noneif not isinstance(value, str) or not value:return None- bounded = value[:1024]+ bounded = redact_for_egress(value)[:1024]if key in _TOOL_INPUT_URL_KEYS:try:parsed = urlsplit(bounded)@@ -117,7 +119,7 @@ def _sanitize_targets(mapping: dict[str, Any]) -> dict[str, Any]:def _input_summary(keys: Any, targets: Any) -> dict[str, Any]:"""``{argument_keys, targets}`` with bounded, sanitized contents (empty on bad shapes)."""return {- "argument_keys": [str(key)[:128] for key in keys[:64]] if isinstance(keys, list) else [],+ "argument_keys": [redact_for_egress(str(key))[:128] for key in keys[:64]] if isinstance(keys, list) else [],"targets": _sanitize_targets(targets) if isinstance(targets, dict) else {},}@@ -129,7 +131,7 @@ def _summarize_tool_arguments(arguments: Any) -> dict[str, Any]:parsed = Noneif not isinstance(parsed, dict):return _input_summary([], {})- return _input_summary(sorted(str(key)[:128] for key in parsed), parsed)+ return _input_summary(sorted(str(key) for key in parsed), parsed)def _subagent_stop_tool_call_history(tool_trace: Any) -> list[dict[str, Any]]:"""Detached, metadata-only tool history for lifecycle hooks (input summaries re-sanitized)."""@@ -178,7 +180,7 @@ def _spill_summary_to_file(task_index: int, summary: str) -> Optional[str]:from tools.spill_safety import write_text_exclusive# Exclusive symlink-refusing create; not private because cache/delegation is bind-mounted read-only into# remote backends whose container UID must be able to read it.- write_text_exclusive(path, summary, private=False)+ write_text_exclusive(path, redact_for_egress(summary), private=False)return str(path)except Exception as exc:logger.debug("Failed to spill subagent summary to file: %s", exc)@@ -188,6 +190,7 @@ def _trim_summary_with_footer(summary: str, cap: int, task_index: int) -> tuple["""``(model_text, spill_path)`` for one over-budget summary: a ~75% head / ~25% tail window snapped to lineboundaries (so the opening AND the closing outcomes/files-changed/issues both survive), the full text spilledto disk, and a footer giving the exact ``read_file offset=`` for the omitted middle."""+ summary = redact_for_egress(summary)original_len = len(summary)head_budget = int(cap * 0.75)tail_budget = cap - head_budget@@ -395,8 +398,11 @@ def _finalize_child_results() -> None:"""Apply host-owned summary, memory, hook, and cost contracts once."""with _parent_finalization_lock(parent_agent):- _apply_summary_budget(results, parent_agent)child_by_index = {index: child for index, _task, child in children}+ for entry in results:+ child = child_by_index.get(entry.get("task_index"))+ entry.update(redact_child_result(entry, getattr(child, "_delegate_output_schema", None)))+ _apply_summary_budget(results, parent_agent)_notify_memory_manager(results, task_list, child_by_index, parent_agent)_rollup_children_cost(parent_agent, _fire_subagent_stop_hooks(results, child_by_index, parent_agent))diff --git a/tools/delegation_redaction.py b/tools/delegation_redaction.pynew file mode 100644index 00000000000..53122ff6880--- /dev/null+++ b/tools/delegation_redaction.py@@ -0,0 +1,116 @@+"""Delegation-owned output projections, using the existing forced text redactor.++Child output is scrubbed before it is shortened or handed to another consumer.+Parent-authored instructions and delivery coordinates retain their exact values.+Live streamed text needs its own buffering policy and does not pass through here.+"""++from __future__ import annotations++from typing import Any++from agent.redact import REDACTION_UNAVAILABLE, redact_for_egress++_PARENT_EVENT_FIELDS = frozenset(+ {+ "type",+ "delegation_id",+ "session_key",+ "origin_ui_session_id",+ "origin_session_id",+ "parent_session_id",+ "goal",+ "goals",+ "context",+ "toolsets",+ "role",+ "model",+ "group",+ "scope_id",+ "user_id",+ "user_name",+ "dispatched_at",+ "completed_at",+ }+)+_RESULT_METADATA = frozenset(+ {"task_index", "model", "group", "_child_role", "status", "exit_reason"}+)+++def redact_child_value(value: Any, *, _depth: int = 0) -> Any:+ """Copy JSON-shaped child data; unsupported or excessively deep values are withheld."""+ if _depth > 64:+ return REDACTION_UNAVAILABLE+ if isinstance(value, str):+ return redact_for_egress(value)+ if isinstance(value, dict):+ return {+ redact_for_egress(str(key)): redact_child_value(item, _depth=_depth + 1)+ for key, item in value.items()+ }+ if isinstance(value, (list, tuple)):+ return [redact_child_value(item, _depth=_depth + 1) for item in value]+ if value is None or isinstance(value, (bool, int, float)):+ return value+ return REDACTION_UNAVAILABLE+++def redact_child_result(result: dict[str, Any], output_schema=None) -> dict[str, Any]:+ """Project a result or batch, preserving accounting and host-owned model/task identity.++ Revalidation here is only for a summary changed by redaction. General schema+ revalidation after annotations/truncation belongs to the output-schema owner.+ Old durable entries do not retain the schema, so their previous positive verdict+ cannot certify a newly redacted summary.+ """+ cleaned = {}+ for key, value in result.items():+ if key == "results" and isinstance(value, list):+ cleaned[key] = [+ redact_child_result(entry)+ if isinstance(entry, dict)+ else redact_child_value(entry)+ for entry in value+ ]+ else:+ cleaned[key] = (+ value if key in _RESULT_METADATA else redact_child_value(value)+ )+ if "schema_valid" in result and cleaned.get("summary") != result.get("summary"):+ valid, errors = (+ False,+ [+ "The redacted summary has not been validated against the original output_schema."+ ],+ )+ if isinstance(output_schema, dict):+ from tools.delegation_output_schema import validate_output++ try:+ summary = cleaned.get("summary")+ valid, errors = validate_output(+ summary if isinstance(summary, str) else "", output_schema+ )+ except Exception: # health: allow BLE001 -- validator faults must not restore raw output or render a secret-bearing exception+ errors = ["Output validation was unavailable after secret redaction."]+ cleaned["schema_valid"] = valid+ cleaned.pop("schema_errors", None)+ cleaned.pop("schema_note", None)+ if not valid:+ cleaned["schema_errors"] = redact_child_value(errors)+ cleaned["schema_note"] = (+ "Secret redaction changed the delivered summary; do not treat it as validated output."+ )+ return cleaned+++def redact_completion_event(event: dict[str, Any]) -> dict[str, Any]:+ """Scrub output while leaving parent instructions and routing outside the projection."""+ cleaned = redact_child_result(+ {key: value for key, value in event.items() if key not in _PARENT_EVENT_FIELDS}+ )+ cleaned.update(+ {key: value for key, value in event.items() if key in _PARENT_EVENT_FIELDS}+ )+ return cleaned