-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
479 lines (390 loc) · 15.4 KB
/
Copy pathapp.py
File metadata and controls
479 lines (390 loc) · 15.4 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
from flask import Flask, render_template, request, jsonify, Response, stream_with_context
from agents import CLOUD_AGENTS, run_agents, run_free_talk_thread
from memory import save_to_obsidian, get_recent_memory, get_memory_status, search_memory
from customization import load_config, save_config, get_room_config, clamp_free_talk_duration
from deliverables import deliverable_options, generate_deliverable
from project_context import summarize_project
from semantic_memory import search_semantic_memory
from datetime import datetime, timezone
import os
import sys
import json
import queue
import threading
import uuid
import requests as http_requests
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
conversation_history = []
active_project_context = None
MAX_CONVERSATION_HISTORY = 50
MAX_TALK_SESSIONS = 100
talk_sessions = {} # session_id -> queue.Queue
talk_stop_events = {} # session_id -> threading.Event
@app.before_request
def validate_json_fields():
"""Reject malformed API payloads before routes use string operations."""
fields = {
"/chat": ("message",), "/save_memory": ("content", "title"),
"/project_context": ("path",), "/generate_deliverable": ("kind",),
"/memory_search": ("query",), "/semantic_memory_search": ("query",),
"/talk": ("topic",), "/customization": (),
}
if request.method != "POST" or request.path not in fields:
return None
data = request.get_json(silent=True)
if not isinstance(data, dict):
return jsonify({"error": "expected a JSON object"}), 400
for field in fields[request.path]:
if field in data and not isinstance(data[field], str):
return jsonify({"error": f"{field} must be a string"}), 400
return None
def release_talk_session(session_id):
"""Stop further agent turns when a session is no longer consumed."""
event = talk_stop_events.pop(session_id, None)
if event is not None:
event.set()
talk_sessions.pop(session_id, None)
def trim_conversation_history() -> None:
"""Keep only the most recent conversation entries."""
overflow = len(conversation_history) - MAX_CONVERSATION_HISTORY
if overflow > 0:
del conversation_history[:overflow]
def prune_talk_sessions() -> None:
"""Keep room for one more Free Talk session."""
while len(talk_sessions) >= MAX_TALK_SESSIONS:
oldest = next(iter(talk_sessions))
release_talk_session(oldest)
def get_port() -> int:
"""Return the configured HTTP port with a safe default."""
try:
port = int(os.getenv("PORT", "5000"))
except ValueError:
return 5000
if 1 <= port <= 65535:
return port
return 5000
def cloud_agent_status() -> dict:
"""Return configured/unconfigured state for optional cloud agents."""
key_envs = {
"claude": ["ANTHROPIC_API_KEY"],
"codex": ["OPENAI_API_KEY"],
"gemini": ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
}
status = {}
for key, agent in CLOUD_AGENTS.items():
env_names = key_envs.get(key, [])
configured = any(
os.getenv(env_name, "").strip() and not os.getenv(env_name, "").strip().startswith("your_")
for env_name in env_names
)
status[key] = {
"name": agent["name"],
"mention": agent["mention"],
"configured": configured,
}
return status
def markdown_heading(text: str) -> str:
"""Keep generated headings readable even when user content contains hashes."""
return " ".join(str(text or "").replace("#", "").split()) or "Untitled"
def build_transcript_markdown() -> str:
"""Render the current in-memory conversation as a Markdown transcript."""
room = load_config().get("room", {})
room_title = markdown_heading(room.get("title") or "Agent Meeting Room")
generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
lines = [
f"# {room_title} Transcript",
"",
f"- Generated: {generated_at}",
f"- Messages: {len(conversation_history)}",
"",
"## Conversation",
"",
]
if not conversation_history:
lines.append("_No messages yet._")
lines.append("")
return "\n".join(lines)
for index, entry in enumerate(conversation_history, start=1):
role = markdown_heading(entry.get("role", "Unknown"))
content = str(entry.get("content", "")).strip() or "_No content_"
lines.extend([f"### {index}. {role}", "", content, ""])
return "\n".join(lines)
def build_agent_context() -> str:
"""Combine persistent memory and optional project context for agents."""
parts = []
project = active_project_context or {}
if project.get("context"):
parts.append(project["context"])
memory_context = get_recent_memory()
if memory_context:
parts.append(memory_context)
return "\n\n".join(parts)
def transcript_filename() -> str:
stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M")
return f"agent_meeting_room_transcript_{stamp}.md"
# ── Startup checks ────────────────────────────────────────────
def check_ollama() -> bool:
"""Return True if Ollama is reachable on localhost:11434."""
try:
r = http_requests.get("http://localhost:11434", timeout=3)
return 200 <= r.status_code < 300
except Exception:
return False
def check_ollama_models() -> list:
"""Return list of pulled Ollama model names."""
try:
r = http_requests.get("http://localhost:11434/api/tags", timeout=5)
if r.status_code == 200:
return [
model["name"]
for model in r.json().get("models", [])
if isinstance(model, dict) and model.get("name")
]
except Exception:
pass
return []
def _safe_print(message=""):
"""Print startup text even when Windows stdout uses a narrow encoding."""
try:
print(message)
except UnicodeEncodeError:
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
print(str(message).encode(encoding, errors="replace").decode(encoding))
def print_startup_banner(ollama_ok: bool, models: list, memory: dict):
sep = "=" * 50
_safe_print(sep)
_safe_print(" Agent Meeting Room")
_safe_print(sep)
# Ollama
if ollama_ok:
_safe_print(f" ✓ Ollama running ({len(models)} model(s) available)")
if models:
for m in models[:6]:
_safe_print(f" · {m}")
if len(models) > 6:
_safe_print(f" ... and {len(models)-6} more")
else:
_safe_print(" ✗ Ollama NOT found — local agents will not respond")
_safe_print(" → Install: https://ollama.com")
_safe_print(" → Then run: ollama pull mistral")
# Memory
mem_backend = memory["backend"]
if mem_backend == "obsidian":
_safe_print(f" ✓ Memory: Obsidian vault ({memory['path']})")
elif mem_backend == "local":
_safe_print(f" ✓ Memory: local folder ({memory['path']})")
else:
_safe_print(" · Memory: disabled (set MEMORY_BACKEND=local to enable)")
# Cloud agents
for key, cloud in cloud_agent_status().items():
if cloud["configured"]:
_safe_print(f" OK {cloud['name']} key found ({cloud['mention']} available)")
else:
_safe_print(f" .. {cloud['name']} API: no key set ({cloud['mention']} will not respond)")
if key == "claude":
_safe_print(" Add ANTHROPIC_API_KEY to .env for @claude")
elif key == "codex":
_safe_print(" Add OPENAI_API_KEY to .env for @codex")
elif key == "gemini":
_safe_print(" Add GEMINI_API_KEY or GOOGLE_API_KEY to .env for @gemini")
_safe_print(sep)
_safe_print(f" Open: http://localhost:{get_port()}")
_safe_print(sep)
# ── Routes ───────────────────────────────────────────────────
@app.route("/")
def index():
return render_template("index.html")
@app.route("/status")
def status():
"""Health/status endpoint — used by frontend to show live state."""
ollama_ok = check_ollama()
models = check_ollama_models() if ollama_ok else []
memory = get_memory_status()
cloud = cloud_agent_status()
return jsonify({
"ollama": {"running": ollama_ok, "models": models},
"memory": memory,
"cloud_agents": cloud,
"claude": {"configured": cloud["claude"]["configured"]},
"customization": load_config(),
})
@app.route("/customization", methods=["GET"])
def get_customization():
return jsonify(load_config())
@app.route("/customization", methods=["POST"])
def update_customization():
data = request.get_json(silent=True) or {}
return jsonify(save_config(data))
@app.route("/customization/reset", methods=["POST"])
def reset_customization():
from customization import default_config
return jsonify(save_config(default_config()))
@app.route("/chat", methods=["POST"])
def chat():
data = request.get_json(silent=True) or {}
user_msg = data.get("message", "").strip()
if not user_msg:
return jsonify({"error": "empty message"}), 400
conversation_history.append({"role": "user", "content": user_msg})
memory_context = build_agent_context()
responses = run_agents(user_msg, conversation_history, memory_context)
for r in responses:
conversation_history.append({"role": r["agent"], "content": r["message"]})
trim_conversation_history()
return jsonify({"responses": responses})
@app.route("/save_memory", methods=["POST"])
def save_memory():
data = request.get_json(silent=True) or {}
content = data.get("content", "").strip()
title = data.get("title", "Meeting note").strip() or "Meeting note"
if not content:
return jsonify({"error": "empty content"}), 400
result = save_to_obsidian(title, content)
return jsonify({"saved": result, "backend": get_memory_status()["backend"]})
@app.route("/export_transcript")
def export_transcript():
markdown = build_transcript_markdown()
return Response(
markdown,
mimetype="text/markdown; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="{transcript_filename()}"'},
)
@app.route("/history")
def get_history():
return jsonify({"messages": conversation_history})
@app.route("/project_context", methods=["GET"])
def get_project_context():
return jsonify({"project": active_project_context})
@app.route("/project_context", methods=["POST"])
def load_project_context():
global active_project_context
data = request.get_json(silent=True) or {}
path = data.get("path", "").strip()
if not path:
return jsonify({"error": "empty path"}), 400
try:
active_project_context = summarize_project(path)
except ValueError as error:
return jsonify({"error": str(error)}), 400
return jsonify({"project": active_project_context})
@app.route("/project_context", methods=["DELETE"])
def clear_project_context():
global active_project_context
active_project_context = None
return jsonify({"cleared": True})
@app.route("/deliverable_types")
def get_deliverable_types():
return jsonify({"types": deliverable_options()})
@app.route("/generate_deliverable", methods=["POST"])
def generate_structured_deliverable():
data = request.get_json(silent=True) or {}
kind = data.get("kind", "").strip()
room_title = load_config().get("room", {}).get("title") or "Agent Meeting Room"
try:
markdown = generate_deliverable(kind, conversation_history, room_title)
except ValueError:
return jsonify({"error": "unknown deliverable type"}), 400
return jsonify({"markdown": markdown})
@app.route("/memory_search", methods=["POST"])
def memory_search():
data = request.get_json(silent=True) or {}
query = data.get("query", "").strip()
if not query:
return jsonify({"error": "empty query"}), 400
memory = get_memory_status()
return jsonify({
"query": query,
"results": search_memory(query),
"memory": memory,
})
@app.route("/semantic_memory_search", methods=["POST"])
def semantic_memory_search():
data = request.get_json(silent=True) or {}
query = data.get("query", "").strip()
if not query:
return jsonify({"error": "empty query"}), 400
memory = get_memory_status()
if not memory.get("path"):
return jsonify({
"query": query,
"results": [],
"memory": memory,
"semantic": {"available": False, "error": "memory backend disabled"},
})
semantic = search_semantic_memory(memory["path"], query)
return jsonify({
"query": query,
"results": semantic.get("results", []),
"memory": memory,
"semantic": semantic,
})
@app.route("/clear", methods=["POST"])
def clear():
conversation_history.clear()
return jsonify({"cleared": True})
@app.route("/talk", methods=["POST"])
def start_talk():
data = request.get_json(silent=True) or {}
topic = data.get("topic", "").strip()
if not topic:
return jsonify({"error": "no topic"}), 400
conversation_history.append({"role": "user", "content": f"@talk {topic}"})
trim_conversation_history()
session_id = uuid.uuid4().hex[:10]
q = queue.Queue()
stop_event = threading.Event()
duration = clamp_free_talk_duration(
data.get("duration", get_room_config().get("free_talk_duration", 300))
)
prune_talk_sessions()
talk_sessions[session_id] = q
talk_stop_events[session_id] = stop_event
thread = threading.Thread(
target=run_free_talk_thread,
args=(topic, list(conversation_history), q, stop_event, duration, build_agent_context()),
daemon=True
)
thread.start()
return jsonify({"session_id": session_id, "duration": duration})
@app.route("/talk_stream/<session_id>")
def talk_stream(session_id):
q = talk_sessions.get(session_id)
if not q:
return "Session not found", 404
def generate():
try:
while True:
try:
msg = q.get(timeout=180)
except queue.Empty:
break
if msg is None:
yield 'data: {"done": true}\n\n'
break
conversation_history.append({
"role": msg.get("agent", "Agent"),
"content": msg.get("message", ""),
})
trim_conversation_history()
yield f"data: {json.dumps(msg)}\n\n"
finally:
release_talk_session(session_id)
return Response(
stream_with_context(generate()),
mimetype="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}
)
@app.route("/stop_talk/<session_id>", methods=["POST"])
def stop_talk(session_id):
event = talk_stop_events.get(session_id)
if event:
event.set()
return jsonify({"stopped": True})
if __name__ == "__main__":
ollama_ok = check_ollama()
models = check_ollama_models() if ollama_ok else []
memory = get_memory_status()
print_startup_banner(ollama_ok, models, memory)
app.run(debug=False, port=get_port())