Spaces:
Running
Running
Download patch_fix_approval_waiting.py from bep40/ml-intern: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/spaces/bep40/ml-intern/resolve/main/patch_fix_approval_waiting.py
- Command line
-
hf download hf://spaces/bep40/ml-intern/patch_fix_approval_waiting.py
-
curl -L -o patch_fix_approval_waiting.py https://huggingface.co/spaces/bep40/ml-intern/resolve/main/patch_fix_approval_waiting.py
14.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| Patch: Fix 'waiting approval' after Space rebuild/session restore. | |
| Root cause: | |
| When a Space restarts, sessions are restored from the HF dataset via: | |
| - patch_catch_up_context_restore.py -> ensure_session_loaded() + seed_from_summary() | |
| - patch_restore_from_dataset.py -> seed_from_dataset() | |
| However, the auto_approval dict (set by patch_agent_backend.py in | |
| Session.__init__) is NOT preserved in these restore paths. The frontend | |
| checks auto_approval.enabled to auto-approve tool calls, and without it | |
| the frontend shows 'waiting approval' and the accept/reject buttons | |
| never appear (because the model never actually makes tool calls when | |
| stuck in approval limbo). | |
| Fix: | |
| 1. session_manager.py: In ensure_session_loaded(), set auto_approval | |
| on restored session metadata. | |
| 2. session_manager.py: In seed_from_summary() and seed_from_dataset(), | |
| set auto_approval on the session.agent_session object. | |
| 3. session.py: Add ensure_auto_approval() method to guarantee validity. | |
| 4. routes/agent.py: Include auto_approval in SSE session update events. | |
| Runs during Docker build -- never fails the build. | |
| """ | |
| import ast | |
| import os | |
| PATCHED_MARKER = "# === PATCH: fix-approval-waiting ===" | |
| def _read(path): | |
| with open(path, encoding="utf-8") as f: | |
| return f.read() | |
| def _write(path, content): | |
| with open(path, "w", encoding="utf-8") as f: | |
| f.write(content) | |
| def _replace(content, old, new): | |
| if old in content: | |
| return content.replace(old, new, 1), True | |
| return content, False | |
| # --- Patch session_manager.py --- | |
| SESSION_MANAGER = "/app/backend/session_manager.py" | |
| if os.path.exists(SESSION_MANAGER): | |
| content = _read(SESSION_MANAGER) | |
| changed = False | |
| if PATCHED_MARKER not in content: | |
| # 1. In ensure_session_loaded, after restoring from dataset, set auto_approval | |
| old_restore_end = ( | |
| " except Exception as e:\n" | |
| " logger.debug(\"Dataset restore fallback failed for %s: %s\", session_id, e)\n" | |
| " if not loaded:\n" | |
| " return None\n" | |
| ) | |
| new_restore_end = ( | |
| " except Exception as e:\n" | |
| " logger.debug(\"Dataset restore fallback failed for %s: %s\", session_id, e)\n" | |
| "\n" | |
| " # === PATCH: fix-approval-waiting ===\n" | |
| " if loaded:\n" | |
| " if isinstance(loaded, dict):\n" | |
| " meta = loaded.setdefault('metadata', {})\n" | |
| " if isinstance(meta, dict):\n" | |
| " meta.setdefault('auto_approval', {\n" | |
| " 'enabled': True,\n" | |
| " 'cost_cap_usd': None,\n" | |
| " 'estimated_spend_usd': 0.0,\n" | |
| " 'remaining_usd': None,\n" | |
| " })\n" | |
| " if not loaded:\n" | |
| " return None\n" | |
| ) | |
| content, ok = _replace(content, old_restore_end, new_restore_end) | |
| if ok: | |
| print("+ ensure_session_loaded sets auto_approval on restored sessions") | |
| changed = True | |
| # 2. Patch seed_from_summary to set auto_approval | |
| old_seed_dataset = ( | |
| " if seeded_from_dataset:\n" | |
| " self._touch(agent_session)\n" | |
| " await self.persist_session_snapshot(agent_session, runtime_state=\"idle\")\n" | |
| " return seeded_from_dataset\n" | |
| ) | |
| new_seed_dataset = ( | |
| " if seeded_from_dataset:\n" | |
| " # === PATCH: fix-approval-waiting ===\n" | |
| " if not getattr(agent_session, 'auto_approval', None):\n" | |
| " agent_session.auto_approval = {\n" | |
| " 'enabled': True,\n" | |
| " 'cost_cap_usd': None,\n" | |
| " 'estimated_spend_usd': 0.0,\n" | |
| " 'remaining_usd': None,\n" | |
| " }\n" | |
| " self._touch(agent_session)\n" | |
| " await self.persist_session_snapshot(agent_session, runtime_state=\"idle\")\n" | |
| " return seeded_from_dataset\n" | |
| ) | |
| content, ok = _replace(content, old_seed_dataset, new_seed_dataset) | |
| if ok: | |
| print("+ seed_from_summary sets auto_approval on session") | |
| changed = True | |
| # 3. Patch seed_from_dataset (from patch_restore_from_dataset.py) | |
| old_seed_from_ds = ( | |
| " self._touch(agent_session)\n" | |
| " await self.persist_session_snapshot(agent_session, runtime_state=\"idle\")\n" | |
| " try:\n" | |
| " await self.record_catchup_done(session_id)\n" | |
| " except Exception:\n" | |
| " pass\n" | |
| " return seeded\n" | |
| ) | |
| new_seed_from_ds = ( | |
| " self._touch(agent_session)\n" | |
| " await self.persist_session_snapshot(agent_session, runtime_state=\"idle\")\n" | |
| " try:\n" | |
| " await self.record_catchup_done(session_id)\n" | |
| " except Exception:\n" | |
| " pass\n" | |
| " # === PATCH: fix-approval-waiting ===\n" | |
| " if not getattr(agent_session, 'auto_approval', None):\n" | |
| " agent_session.auto_approval = {\n" | |
| " 'enabled': True,\n" | |
| " 'cost_cap_usd': None,\n" | |
| " 'estimated_spend_usd': 0.0,\n" | |
| " 'remaining_usd': None,\n" | |
| " }\n" | |
| " return seeded\n" | |
| ) | |
| content, ok = _replace(content, old_seed_from_ds, new_seed_from_ds) | |
| if ok: | |
| print("+ seed_from_dataset sets auto_approval on session") | |
| changed = True | |
| # 4. Also patch the fallback in seed_from_summary | |
| old_fallback = ( | |
| " for msg in parsed:\n" | |
| " session.context_manager.items.append(msg)\n" | |
| " self._touch(agent_session)\n" | |
| " await self.persist_session_snapshot(agent_session, runtime_state=\"idle\")\n" | |
| " return len(parsed)\n" | |
| ) | |
| new_fallback = ( | |
| " for msg in parsed:\n" | |
| " session.context_manager.items.append(msg)\n" | |
| " # === PATCH: fix-approval-waiting ===\n" | |
| " if not getattr(agent_session, 'auto_approval', None):\n" | |
| " agent_session.auto_approval = {\n" | |
| " 'enabled': True,\n" | |
| " 'cost_cap_usd': None,\n" | |
| " 'estimated_spend_usd': 0.0,\n" | |
| " 'remaining_usd': None,\n" | |
| " }\n" | |
| " self._touch(agent_session)\n" | |
| " await self.persist_session_snapshot(agent_session, runtime_state=\"idle\")\n" | |
| " return len(parsed)\n" | |
| ) | |
| content, ok = _replace(content, old_fallback, new_fallback) | |
| if ok: | |
| print("+ seed_from_summary fallback sets auto_approval on session") | |
| changed = True | |
| if changed: | |
| try: | |
| ast.parse(content) | |
| _write(SESSION_MANAGER, content) | |
| print("OK: session_manager.py patched (fix-approval-waiting)") | |
| except SyntaxError as e: | |
| print(f"FAIL: session_manager.py syntax: {e}") | |
| else: | |
| print("SKIP: session_manager.py no changes needed") | |
| else: | |
| print("SKIP: session_manager.py already patched (fix-approval-waiting)") | |
| else: | |
| print("SKIP: session_manager.py not found") | |
| # --- Patch session.py: add ensure_auto_approval method --- | |
| SESSION = "/app/agent/core/session.py" | |
| if os.path.exists(SESSION): | |
| content = _read(SESSION) | |
| changed = False | |
| if PATCHED_MARKER not in content: | |
| if "def ensure_auto_approval" not in content: | |
| init_patterns = [ | |
| " # === PATCH: Auto-approve for free models ===", | |
| " self.auto_approval = {", | |
| ] | |
| for pattern in init_patterns: | |
| idx = content.find(pattern) | |
| if idx > 0: | |
| next_methods = [" async def start(", " def send_event(", " def send_message(", " @property", " def __enter__"] | |
| best_idx = -1 | |
| for nm in next_methods: | |
| ni = content.find(nm, idx) | |
| if ni > 0: | |
| if best_idx < 0 or ni < best_idx: | |
| best_idx = ni | |
| if best_idx > 0: | |
| helper = ( | |
| "\n" | |
| " def ensure_auto_approval(self) -> None:\n" | |
| " \"\"\"Ensure auto_approval is always enabled after dataset restore.\"\"\"\n" | |
| " # === PATCH: fix-approval-waiting ===\n" | |
| " if not hasattr(self, 'auto_approval') or not self.auto_approval:\n" | |
| " self.auto_approval = {\n" | |
| " 'enabled': True,'cost_cap_usd': None,'estimated_spend_usd': 0.0,'remaining_usd': None,\n" | |
| " }\n" | |
| " elif isinstance(self.auto_approval, dict):\n" | |
| " self.auto_approval.setdefault('enabled', True)\n" | |
| " elif isinstance(self.auto_approval, bool):\n" | |
| " self.auto_approval = {'enabled': bool(self.auto_approval),'cost_cap_usd': None,'estimated_spend_usd': 0.0,'remaining_usd': None}\n" | |
| " # === PATCH: fix-approval-waiting ===\n" | |
| ) | |
| content = content[:best_idx] + helper + content[best_idx:] | |
| print("+ session.py: added ensure_auto_approval() method") | |
| changed = True | |
| break | |
| # Add marker after auto_approval init | |
| old_auto = ( | |
| " # === PATCH: Auto-approve for free models ===\n" | |
| " self.auto_approval = {\n" | |
| ' "enabled": True,\n' | |
| ' "cost_cap_usd": None,\n' | |
| ' "estimated_spend_usd": 0.0,\n' | |
| ' "remaining_usd": None,\n' | |
| " }\n" | |
| ) | |
| new_auto = ( | |
| " # === PATCH: Auto-approve for free models ===\n" | |
| " self.auto_approval = {\n" | |
| ' "enabled": True,\n' | |
| ' "cost_cap_usd": None,\n' | |
| ' "estimated_spend_usd": 0.0,\n' | |
| ' "remaining_usd": None,\n' | |
| " }\n" | |
| " # === PATCH: fix-approval-waiting ===\n" | |
| ) | |
| content, ok = _replace(content, old_auto, new_auto) | |
| if ok: | |
| print("+ session.py: added fix-approval marker") | |
| changed = True | |
| if changed: | |
| try: | |
| ast.parse(content) | |
| _write(SESSION, content) | |
| print("OK: session.py patched (fix-approval-waiting)") | |
| except SyntaxError as e: | |
| print(f"FAIL: session.py syntax: {e}") | |
| else: | |
| print("SKIP: session.py no changes needed") | |
| else: | |
| print("SKIP: session.py already patched (fix-approval-waiting)") | |
| else: | |
| print("SKIP: session.py not found") | |
| # --- Patch routes/agent.py: include auto_approval in SSE events --- | |
| AGENT_FILE = "/app/backend/routes/agent.py" | |
| if os.path.exists(AGENT_FILE): | |
| content = _read(AGENT_FILE) | |
| changed = False | |
| if PATCHED_MARKER not in content: | |
| if '"sessionInfo"' in content and '"auto_approval"' not in content: | |
| old_si = '"sessionInfo": {' | |
| new_si = '"sessionInfo": {\n "auto_approval": {"enabled": True, "cost_cap_usd": None, "estimated_spend_usd": 0.0, "remaining_usd": None},' | |
| content, ok = _replace(content, old_si, new_si) | |
| if ok: | |
| print("+ routes/agent.py: added auto_approval to sessionInfo") | |
| changed = True | |
| if '"isActive": True' in content and '"auto_approval"' not in content: | |
| old_active = '"isActive": True,' | |
| new_active = '"isActive": True,\n "auto_approval": {"enabled": True, "cost_cap_usd": None, "estimated_spend_usd": 0.0, "remaining_usd": None},' | |
| content, ok = _replace(content, old_active, new_active) | |
| if ok: | |
| print("+ routes/agent.py: added auto_approval to session response") | |
| changed = True | |
| if changed: | |
| try: | |
| ast.parse(content) | |
| _write(AGENT_FILE, content) | |
| print("OK: routes/agent.py patched (fix-approval-waiting)") | |
| except SyntaxError as e: | |
| print(f"FAIL: routes/agent.py syntax: {e}") | |
| else: | |
| print("SKIP: routes/agent.py no changes needed or patterns not found") | |
| else: | |
| print("SKIP: routes/agent.py already patched (fix-approval-waiting)") | |
| else: | |
| print("SKIP: routes/agent.py not found") | |
| # --- Patch Dockerfile: move patch_fix_approval_waiting.py AFTER restore patches --- | |
| DOCKERFILE = "/Dockerfile" | |
| # Note: This won't exist in the build container, but we need to check if the | |
| # Dockerfile in the Space repo has the correct ordering | |
| print("\n=== All fix-approval-waiting patches applied ===") | |