File size: 14,163 Bytes
3161f3f
 
 
 
 
8101daf
 
 
 
 
 
 
 
 
 
3161f3f
 
8101daf
 
 
 
 
 
3161f3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8101daf
3161f3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8101daf
 
 
 
 
 
3161f3f
 
 
 
 
 
 
 
8101daf
 
3161f3f
 
 
 
 
8101daf
3161f3f
 
 
 
 
 
 
 
 
 
 
 
 
8101daf
3161f3f
8101daf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3161f3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8101daf
3161f3f
 
 
 
 
 
8101daf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3161f3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8101daf
 
 
 
 
3161f3f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#!/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 ===")