File size: 14,591 Bytes
d7ce722
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
#!/usr/bin/env python3
"""

stdio MCP wrapper — bridges Claude Code's MCP stdio protocol to the

agentmemory Flask HTTP API running on localhost.



Usage: python mcp_stdio.py

"""
import sys
import json
import requests

import os
BASE = os.getenv("AGENTMEMORY_URL", "http://127.0.0.1:3111").rstrip("/")
if not BASE.endswith("/agentmemory"):
    BASE = f"{BASE}/agentmemory"

_secret = os.getenv("AGENTMEMORY_SECRET")

def headers():
    h = {"Content-Type": "application/json"}
    if _secret:
        h["Authorization"] = f"Bearer {_secret}"
    return h

def send(msg):
    line = json.dumps(msg, separators=(",", ":"))
    sys.stdout.write(line + "\n")
    sys.stdout.flush()

def perform_antigravity_sync_local(args):
    import os
    import json
    import glob
    import re
    import requests
    
    mode = args.get("mode") or "current_session"
    current_conversation_id = args.get("currentConversationId")
    current_folder = args.get("currentFolder")

    brain_dir = os.path.join(os.path.expanduser("~"), ".gemini", "antigravity", "brain")
    if not os.path.exists(brain_dir):
        return {
            "content": [{"type": "text", "text": json.dumps({
                "success": False,
                "syncedSessions": [],
                "observationsAdded": 0,
                "error": f"Brain directory not found at {brain_dir}"
            })}]
        }

    pattern = os.path.join(brain_dir, "*", ".system_generated", "logs", "transcript.jsonl")
    files = glob.glob(pattern)
    if not files:
        return {
            "content": [{"type": "text", "text": json.dumps({
                "success": True,
                "syncedSessions": [],
                "observationsAdded": 0
            })}]
        }

    conversations = []
    for fpath in files:
        try:
            mtime = os.path.getmtime(fpath)
            convo_id = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(fpath))))
            conversations.append({
                "id": convo_id,
                "transcriptPath": fpath,
                "mtime": mtime
            })
        except Exception:
            pass

    if not conversations:
        return {
            "content": [{"type": "text", "text": json.dumps({
                "success": True,
                "syncedSessions": [],
                "observationsAdded": 0
            })}]
        }

    conversations.sort(key=lambda x: x["mtime"], reverse=True)

    targets = []
    if mode == "current_session":
        if current_conversation_id:
            match = next((c for c in conversations if c["id"] == current_conversation_id), None)
            if match:
                targets = [match]
        else:
            targets = [conversations[0]]
    elif mode == "current_folder":
        target_folder = current_folder if current_folder else ""
        if not target_folder:
            target_folder = os.getcwd()
            
        target_folder_norm = target_folder.replace("\\", "/").lower().strip()
        
        for convo in conversations:
            try:
                with open(convo["transcriptPath"], "r", encoding="utf-8") as tf:
                    text = tf.read().lower()
                    text_norm = text.replace("\\/", "/").replace("\\\\", "/")
                    if target_folder_norm in text_norm:
                        targets.append(convo)
            except Exception:
                pass
    elif mode == "all":
        targets = conversations
    else:
        return {
            "content": [{"type": "text", "text": json.dumps({
                "success": False,
                "syncedSessions": [],
                "observationsAdded": 0,
                "error": f"Invalid mode: {mode}"
            })}]
        }

    if not targets:
        return {
            "content": [{"type": "text", "text": json.dumps({
                "success": True,
                "syncedSessions": [],
                "processedSessions": [],
                "observationsAdded": 0
            })}]
        }

    synced_sessions = []
    processed_sessions = [convo["id"] for convo in targets]
    observations_added = 0

    headers_dict = headers()

    for convo in targets:
        convo_id = convo["id"]
        tpath = convo["transcriptPath"]
        session_id = f"antigravity_{convo_id[:18].replace('-', '_')}"
        
        project_path = None
        try:
            with open(tpath, "r", encoding="utf-8") as tf:
                first_line = tf.readline()
                if first_line:
                    step = json.loads(first_line)
                    match = re.search(r"\[([^\]]+)\]\s*->\s*\[([^\]]+)\]", step.get("content", ""))
                    if match:
                        project_path = match.group(2)
        except Exception:
            pass
            
        if not project_path:
            project_path = os.getcwd()

        turns = []
        current_prompt = None
        current_timestamp = None

        try:
            with open(tpath, "r", encoding="utf-8") as tf:
                for line in tf:
                    if not line.strip():
                        continue
                    try:
                        step = json.loads(line)
                        step_type = step.get("type")
                        if step_type == "USER_INPUT":
                            p_text = step.get("content", "")
                            if "<USER_REQUEST>" in p_text:
                                parts = p_text.split("<USER_REQUEST>")
                                if len(parts) > 1:
                                    p_text = parts[1]
                            if "</USER_REQUEST>" in p_text:
                                p_text = p_text.split("</USER_REQUEST>")[0]
                            current_prompt = p_text.strip()
                            current_timestamp = step.get("created_at")
                        elif step_type == "PLANNER_RESPONSE" and current_prompt:
                            ts = current_timestamp or step.get("created_at")
                            if not ts:
                                import datetime
                                ts = datetime.datetime.utcnow().isoformat() + "Z"
                            turns.append({
                                "prompt": current_prompt,
                                "response": step.get("content", ""),
                                "timestamp": ts
                            })
                            current_prompt = None
                            current_timestamp = None
                    except Exception:
                        pass
        except Exception:
            continue

        if not turns:
            continue

        existing_inputs = set()
        
        try:
            r = requests.get(f"{BASE}/observations?sessionId={session_id}", headers=headers_dict, timeout=10)
            if r.status_code == 200:
                obs_list = r.json().get("observations", [])
                for obs in obs_list:
                    tool_input = obs.get("toolInput") or (obs.get("raw") or {}).get("tool_input")
                    if tool_input:
                        existing_inputs.add(tool_input.strip())
        except Exception:
            pass

        try:
            sess_check = requests.get(f"{BASE}/sessions", headers=headers_dict, timeout=5)
            session_exists = False
            if sess_check.status_code == 200:
                sessions_list = sess_check.json().get("sessions", [])
                session_exists = any(s.get("id") == session_id for s in sessions_list)
            
            if not session_exists:
                session_payload = {
                    "sessionId": session_id,
                    "project": project_path,
                    "cwd": project_path,
                    "title": f"Antigravity Pair Programming ({convo_id[:8]})",
                    "agentId": "antigravity"
                }
                requests.post(f"{BASE}/session/start", headers=headers_dict, json=session_payload, timeout=10)
        except Exception:
            pass

        convo_synced = False
        for turn in turns:
            prompt = turn["prompt"]
            if prompt.strip() in existing_inputs:
                continue

            payload = {
                "sessionId": session_id,
                "project": project_path,
                "cwd": project_path,
                "hookType": "post_tool_use",
                "timestamp": turn["timestamp"],
                "agentId": "antigravity",
                "data": {
                    "tool_name": "conversation",
                    "tool_input": prompt,
                    "tool_output": turn["response"],
                }
            }
            try:
                requests.post(f"{BASE}/observe", headers=headers_dict, json=payload, timeout=10)
                observations_added += 1
                convo_synced = True
            except Exception:
                pass

        if convo_synced:
            synced_sessions.append(convo_id)

    return {
        "content": [{"type": "text", "text": json.dumps({
            "success": True,
            "syncedSessions": synced_sessions,
            "processedSessions": processed_sessions,
            "observationsAdded": observations_added
        })}]
    }

def perform_antigravity_sync_all_local(args):
    sync_res_outer = perform_antigravity_sync_local(args)
    try:
        sync_res = json.loads(sync_res_outer["content"][0]["text"])
    except Exception as ex:
        return sync_res_outer
        
    if not sync_res.get("success"):
        return sync_res_outer
        
    synced_sessions = sync_res.get("syncedSessions") or []
    processed_sessions = sync_res.get("processedSessions") or synced_sessions
    crystallizations = {}
    reflections = {}
    
    headers_dict = headers()
    
    for cid in processed_sessions:
        session_id = f"antigravity_{cid[:18].replace('-', '_')}"
        
        try:
            r_sum = requests.post(f"{BASE}/summarize", headers=headers_dict, json={"sessionId": session_id}, timeout=30)
            if r_sum.status_code == 200:
                crystallizations[session_id] = r_sum.json()
            else:
                crystallizations[session_id] = {"success": False, "status_code": r_sum.status_code, "error": r_sum.text}
        except Exception as e:
            crystallizations[session_id] = {"success": False, "error": str(e)}
            
        try:
            r_ref = requests.post(f"{BASE}/slot/reflect", headers=headers_dict, json={"sessionId": session_id, "maxObservations": 50}, timeout=30)
            if r_ref.status_code == 200:
                reflections[session_id] = r_ref.json()
            else:
                reflections[session_id] = {"success": False, "status_code": r_ref.status_code, "error": r_ref.text}
        except Exception as e:
            reflections[session_id] = {"success": False, "error": str(e)}
            
    return {
        "content": [{"type": "text", "text": json.dumps({
            "success": True,
            "syncedSessions": synced_sessions,
            "processedSessions": processed_sessions,
            "observationsAdded": sync_res.get("observationsAdded", 0),
            "crystallizations": crystallizations,
            "reflections": reflections
        }, indent=2)}]
    }

def handle(req):
    method = req.get("method", "")
    req_id = req.get("id")
    params = req.get("params") or {}

    if method == "initialize":
        send({
            "jsonrpc": "2.0", "id": req_id,
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": {"tools": {}},
                "serverInfo": {"name": "agentmemory-local", "version": "0.9.8"}
            }
        })

    elif method == "initialized":
        pass  # notification — no response

    elif method == "ping":
        send({"jsonrpc": "2.0", "id": req_id, "result": {}})

    elif method == "tools/list":
        try:
            r = requests.get(f"{BASE}/mcp/tools", headers=headers(), timeout=5)
            tools = r.json().get("tools", [])
            send({"jsonrpc": "2.0", "id": req_id, "result": {"tools": tools}})
        except Exception as e:
            send({"jsonrpc": "2.0", "id": req_id,
                  "error": {"code": -32000, "message": f"agentmemory unreachable: {e}"}})

    elif method == "tools/call":
        name = params.get("name")
        args = params.get("arguments") or {}
        try:
            if name == "memory_antigravity_sync":
                result = perform_antigravity_sync_local(args)
            elif name == "memory_antigravity_sync_all":
                result = perform_antigravity_sync_all_local(args)
            else:
                r = requests.post(f"{BASE}/mcp/tools",
                                  headers=headers(),
                                  json={"name": name, "arguments": args},
                                  timeout=30)
                result = r.json()
                # MCP expects content array
                if "content" not in result:
                    result = {"content": [{"type": "text", "text": json.dumps(result)}]}
            send({"jsonrpc": "2.0", "id": req_id, "result": result})
        except Exception as e:
            send({"jsonrpc": "2.0", "id": req_id,
                  "error": {"code": -32000, "message": str(e)}})

    elif req_id is not None:
        send({"jsonrpc": "2.0", "id": req_id,
              "error": {"code": -32601, "message": "Method not found"}})


def main():
    for raw_line in sys.stdin:
        raw_line = raw_line.strip()
        if not raw_line:
            continue
        try:
            req = json.loads(raw_line)
        except json.JSONDecodeError:
            continue
        try:
            handle(req)
        except Exception as e:
            req_id = req.get("id") if isinstance(req, dict) else None
            if req_id is not None:
                send({"jsonrpc": "2.0", "id": req_id,
                      "error": {"code": -32603, "message": f"Internal error: {e}"}})

if __name__ == "__main__":
    main()