-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathwebchat_server.py
More file actions
4723 lines (4373 loc) · 189 KB
/
Copy pathwebchat_server.py
File metadata and controls
4723 lines (4373 loc) · 189 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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Dulus WebChat — in-process mirror of the terminal agent + Roundtable mode.
"""
from __future__ import annotations
import json
import queue
import threading
import time
import uuid
import webbrowser
import sys
from pathlib import Path
from typing import Any, Generator
from backend.agents_bridge import build_agent_info_list
from backend.context import build_context, build_smart_context, get_compact_context
from backend.personas import create_persona, get_active_persona, get_all_personas, get_persona, load_personas, set_active_persona, update_persona
from backend.plugins import load_all_plugins, get_plugin_info, start_watcher, stop_watcher, watcher_status, reload_plugin, unload_plugin
from task import create_task as task_create, list_tasks as task_list, update_task as task_update, get_task as task_get, delete_task as task_delete
from backend.marketplace import load_registry, search_plugins, get_stats as marketplace_stats, install_plugin, uninstall_plugin
from gui.session_utils import scan_sessions, save_session, delete_session as _delete_session_disk
def _resolve_dashboard_dir() -> Path:
"""Find docs/dashboard whether running from source or installed package."""
# 1. Try source layout (development)
src = Path(__file__).parent / "docs" / "dashboard"
if src.exists():
return src
# 2. Try installed package (docs is now a package)
try:
import docs as _docs_pkg
pkg = Path(_docs_pkg.__file__).parent / "dashboard"
if pkg.exists():
return pkg
except Exception:
pass
# 3. Fallback — will 404 gracefully
return src
def _resolve_webchat_ui_dir() -> Path:
"""Find webchat_ui whether running from source or installed package."""
# 1. Try source layout (development)
src = Path(__file__).parent / "webchat_ui"
if src.exists() and (src / "index.html").exists():
return src
# 2. Try installed package (wheel layout mirrors source)
try:
import webchat_ui as _wui_pkg
pkg = Path(_wui_pkg.__file__).parent
if pkg.exists() and (pkg / "index.html").exists():
return pkg
except Exception:
pass
# 3. Fallback — caller should check existence
return src
DASHBOARD_DIR = _resolve_dashboard_dir()
WEBCHAT_UI_DIR = _resolve_webchat_ui_dir()
from flask import Flask, request, jsonify, Response, stream_with_context, send_from_directory
from flask.typing import ResponseReturnValue
from agent import (
run as agent_run,
AgentState,
TextChunk,
ThinkingChunk,
ToolStart,
ToolEnd,
TurnDone,
PermissionRequest,
)
from context import build_system_prompt
from common import sanitize_text
# Ensure tools are registered
import tools as _tools_init
import memory.tools as _mem_tools_init
import multi_agent.tools as _ma_tools_init
import skill.tools as _sk_tools_init
import dulus_mcp.tools as _mcp_tools_init
import task.tools as _task_tools_init
try:
import tmux_tools as _tmux_tools_init
except Exception:
pass
# ─────────── SSE Broadcast System ───────────
_sse_clients: list[queue.Queue] = []
_sse_lock = threading.Lock()
def _add_sse_client(q: queue.Queue):
with _sse_lock:
_sse_clients.append(q)
def _remove_sse_client(q: queue.Queue):
with _sse_lock:
if q in _sse_clients:
_sse_clients.remove(q)
def broadcast_event(event_type: str, payload: dict):
"""Broadcast JSON event to all connected SSE clients."""
data = json.dumps({"type": event_type, "data": payload, "ts": time.time()})
msg = f"event: {event_type}\ndata: {data}\n\n"
with _sse_lock:
dead = []
for q in _sse_clients:
try:
q.put_nowait(msg)
except queue.Full:
dead.append(q)
for q in dead:
_sse_clients.remove(q)
def _sse_heartbeat():
"""Send periodic ping to keep connections alive."""
while True:
time.sleep(15)
broadcast_event("ping", {"status": "ok"})
threading.Thread(target=_sse_heartbeat, daemon=True, name="sse-heartbeat").start()
# ── shared refs ────────────────────────────────────────────────────────────
STATE: AgentState | None = None
CONFIG: dict | None = None
_LOCK = threading.Lock()
_PENDING_PERMISSIONS: dict[str, tuple[PermissionRequest, threading.Event]] = {}
# ── AskUserQuestion bridge (mirrors the permission flow) ───────────────────
# tools._ask_user_question() blocks a background thread waiting for someone
# to drain tools._pending_questions. In the terminal the REPL does that; in
# the webchat we poll it with a watcher thread, surface the question as an
# SSE event, and answer it via POST /question.
_PENDING_QUESTIONS: dict[str, dict] = {}
# Per-request cancellation tokens for the main WebChat. This mirrors the
# Roundtable's per-agent stop events while keeping concurrent browser turns
# isolated by run_id.
_WEBCHAT_STOP_EVENTS: dict[str, threading.Event] = {}
_WEBCHAT_STOP_EVENTS_LOCK = threading.Lock()
def _start_question_watcher(q: "queue.Queue", stop_evt: threading.Event) -> threading.Thread:
"""Poll tools._pending_questions and forward AskUserQuestion prompts to the
SSE stream as {"type": "question", ...} events (same pattern as permissions)."""
def watcher():
import time as _t_time
import tools as _t
while not stop_evt.is_set():
grabbed: list[dict] = []
try:
with _t._ask_lock:
if _t._pending_questions:
grabbed = list(_t._pending_questions)
_t._pending_questions.clear()
except Exception:
pass
# Purge entries the agent already gave up on (AskUserQuestion
# times out after 300s) so a late click can never land on a dead
# entry and look "answered" while nobody is listening.
try:
with _LOCK:
_now = _t_time.time()
for _qid, _e in list(_PENDING_QUESTIONS.items()):
if _now - float(_e.get("_ts", _now)) > 310:
_PENDING_QUESTIONS.pop(_qid, None)
except Exception:
pass
for entry in grabbed:
entry["_ts"] = _t_time.time()
qid = str(uuid.uuid4())
with _LOCK:
_PENDING_QUESTIONS[qid] = entry
q.put({
"type": "question",
"id": qid,
"question": entry.get("question", ""),
"options": entry.get("options") or [],
"allow_freetext": bool(entry.get("allow_freetext", True)),
})
stop_evt.wait(0.25)
t = threading.Thread(target=watcher, daemon=True)
t.start()
return t
# Session context deferment
_PENDING_HISTORY: list[dict] = []
_PENDING_SESSION_ID: str | None = None
_SERVER_THREAD: threading.Thread | None = None
_SERVER_PORT: int = 5000
_WERKZEUG_SERVER = None
# ── WebChat authentication ─────────────────────────────────────────────────
# This API can run shell (/api/sandbox/exec), read and write files, and spend
# model tokens. That is harmless on loopback, where only you can reach it, and
# dangerous the moment the server binds anything else — a LAN, a container, a
# cloud host. So auth switches itself on exactly when the bind leaves loopback.
#
# DULUS_WEBCHAT_TOKEN — the shared secret. Auto-generated and printed once
# at startup when unset.
# DULUS_WEBCHAT_AUTH — "auto" (default: on only once exposed) | "always" | "off"
#
# Clients may present it as `X-Dulus-Token`, `Authorization: Bearer <tok>`,
# or `?token=`.
import os as _os_env
import secrets as _secrets
from urllib.parse import urlparse as _urlparse
_WEBCHAT_TOKEN: str | None = None
_TOKEN_AUTOGEN = False
_LAN_EXPOSED = False # True once the bind leaves loopback (0.0.0.0 / a LAN IP)
_LOOPBACK_ADDRS = {"127.0.0.1", "::1", "localhost"}
_LOOPBACK_ORIGIN_HOSTS = {"localhost", "127.0.0.1", "::1"}
def _resolve_token() -> tuple[str, bool]:
env_tok = _os_env.environ.get("DULUS_WEBCHAT_TOKEN", "").strip()
if env_tok:
return env_tok, False
return _secrets.token_urlsafe(24), True
def _auth_mode() -> str:
mode = _os_env.environ.get("DULUS_WEBCHAT_AUTH", "auto").strip().lower()
return mode if mode in ("auto", "always", "off") else "auto"
def _auth_active() -> bool:
mode = _auth_mode()
if mode == "always":
return True
if mode == "off":
return False
return _LAN_EXPOSED
def _request_token() -> str:
tok = (request.headers.get("X-Dulus-Token") or "").strip()
if not tok:
auth = (request.headers.get("Authorization") or "").strip()
if auth.lower().startswith("bearer "):
tok = auth[7:].strip()
if not tok:
tok = (request.args.get("token") or "").strip()
return tok
def _token_ok(tok: str) -> bool:
return bool(_WEBCHAT_TOKEN) and bool(tok) and _secrets.compare_digest(tok, _WEBCHAT_TOKEN)
def _cross_site_browser_ride() -> bool:
"""Anti-CSRF: a browser sitting on some other site poking the local server."""
sfs = (request.headers.get("Sec-Fetch-Site") or "").lower()
if sfs == "cross-site":
return True
origin = request.headers.get("Origin")
if origin:
try:
host = (_urlparse(origin).hostname or "").lower()
except Exception:
return True
if host not in _LOOPBACK_ORIGIN_HOSTS:
return True
return False
def _local_ui_exempt() -> bool:
"""The UI this server itself served, over a real loopback socket.
Requires a genuine loopback peer (a remote client cannot forge remote_addr)
plus browser evidence of same-origin. A malicious page sends its own Origin
or a cross-site Sec-Fetch-Site, so it never qualifies.
"""
if (request.remote_addr or "") not in _LOOPBACK_ADDRS:
return False
origin = request.headers.get("Origin")
if origin:
try:
host = (_urlparse(origin).hostname or "").lower()
except Exception:
return False
return host in _LOOPBACK_ORIGIN_HOSTS
sfs = (request.headers.get("Sec-Fetch-Site") or "").lower()
return sfs in ("same-origin", "same-site", "none")
def _is_public_path() -> bool:
"""Health probe and the static UI. Serving the HTML/JS is not privileged —
every functional call it then makes is still gated."""
path = request.path or "/"
if path == "/api/health":
return True
return request.method == "GET" and not path.startswith("/api/") and path != "/chat"
def _require_auth():
"""Gate every request. None to allow, or (response, status) to reject.
Applied as a before_request hook so endpoints added later are protected by
default rather than by remembering to opt in.
"""
if request.method == "OPTIONS" or _is_public_path():
return None
if _token_ok(_request_token()):
return None
if not _auth_active():
# Loopback-only: no token needed, but never let another site ride along.
if _cross_site_browser_ride():
return jsonify(error="forbidden: cross-site request blocked"), 403
return None
if _local_ui_exempt():
return None
return jsonify(error="unauthorized: token required (X-Dulus-Token)"), 401
# ── roundtable state ───────────────────────────────────────────────────────
class RoundtableAgent:
def __init__(self, agent_id: str, model: str):
self.id = agent_id
self.model = model
self.state = AgentState()
ROUNDTABLE_AGENTS: list[RoundtableAgent] = []
ROUNDTABLE_HISTORY: list[dict[str, str]] = [] # {"agent","text","type"} global log
ROUNDTABLE_LOCK = threading.Lock()
# Per-agent cancellation tokens for roundtable
_AGENT_STOP_EVENTS: dict[str, threading.Event] = {}
_STOP_EVENTS_LOCK = threading.Lock()
def _ensure_plugin_tools() -> None:
try:
from plugin.loader import register_plugin_tools
register_plugin_tools()
except Exception:
pass
_ANSI_RE = None
def _strip_ansi(text: str) -> str:
global _ANSI_RE
if _ANSI_RE is None:
import re
_ANSI_RE = re.compile(r'\x1b\[[0-9;]*m')
return _ANSI_RE.sub('', text)
_GOLD_MARKER = "[Golden Memory Loaded:"
_WELCOME_MARKER = "<!-- dulus:welcome -->"
def _preload_gold_memories(state, cfg: dict) -> None:
"""Seed a session with gold *display* copies for the GUI transcript.
Model source of truth is ``build_system_prompt`` → ``gold_system_fragment()``.
These assistant-role blobs only exist so the GUI can render gold in history;
agent.py + lookback strip them before the provider call.
Deliberately NOT gated by ``mem_palace``.
"""
try:
for m in state.messages:
if isinstance(m, dict) and str(m.get("content", "")).startswith(_GOLD_MARKER):
return
token = str(cfg.get("_session_id") or "fresh")
if cfg.get("_gold_preloaded") == token:
return
cfg["_gold_preloaded"] = token
from memory import gold_context_messages
msgs = gold_context_messages()
if not msgs:
return
with _LOCK:
for offset, msg in enumerate(msgs):
state.messages.insert(offset, msg)
except Exception:
pass
def _inject_mempalace(user_input: str, config: dict) -> str:
"""Inject relevant memories from MemPalace into the user message.
Mirrors the logic in dulus.py REPL for consistent behavior.
"""
if not config.get("mem_palace", True):
return user_input
if not user_input or len(user_input.strip()) < 12:
return user_input
_trivial = {"hola", "klk", "gracias", "ok", "si", "no", "dale",
"exit", "quit", "help", "thanks", "bien"}
_first = user_input.strip().lower().split()[0].strip(".,!?;:")
if _first in _trivial:
return user_input
try:
_q = user_input.strip()[:200]
_raw_hits = []
# Primary: query the real MemPalace (~/.mempalace/palace)
try:
from mempalace.searcher import search_memories as _mp_search
from mempalace.config import MempalaceConfig as _MPCfg
_palace = _MPCfg().palace_path
_res = _mp_search(_q, _palace, n_results=3)
for _hit in (_res or {}).get("results", []):
_meta = _hit.get("metadata") or {}
_src = _meta.get("source_file") or _meta.get("name") or "palace"
_name = str(_src).rsplit("/", 1)[-1].rsplit("\\", 1)[-1].rsplit(".", 1)[0]
_vec = max(0.0, 1.0 - float(_hit.get("distance", 1.0)))
_bm = float(_hit.get("bm25_score", 0.0))
_raw_hits.append({
"name": _name,
"description": _meta.get("wing") or _meta.get("room") or "",
"content": _hit.get("text", ""),
"keyword_score": max(_vec, _bm),
})
except Exception:
pass
# Fallback: Dulus's local memory dir
if not _raw_hits:
from memory import find_relevant_memories
_raw_hits = find_relevant_memories(_q, max_results=3)
_MIN_SCORE = 0.15
_kept = [h for h in _raw_hits if float(h.get("keyword_score", 0.0)) >= _MIN_SCORE]
# Skip short_memory/soul — already in system-prompt baseline.
try:
from memory import is_baseline_memory_name
_kept = [
h for h in _kept
if not is_baseline_memory_name(h.get("name"))
]
except Exception:
pass
# Dedup against session cache
import hashlib as _hashlib
def _mp_dedup_key(h):
content = (h.get("content") or "").strip()[:240]
return _hashlib.md5(content.encode("utf-8", errors="ignore")).hexdigest()[:12]
_seen = config.setdefault("_mp_injected_keys", set())
_this_turn = set()
_filtered = []
for _h in _kept:
_k = _mp_dedup_key(_h)
if _k in _seen or _k in _this_turn:
continue
_this_turn.add(_k)
_filtered.append(_h)
_kept = _filtered
if not _kept:
return user_input
_BODY_BUDGET = 1800
_per_hit = max(300, _BODY_BUDGET // len(_kept))
_parts = []
for _i, _h in enumerate(_kept, 1):
_name = _h.get("name", f"hit_{_i}")
_desc = _h.get("description", "")
_body = _h.get("content", "").strip()
_snip = _body[:_per_hit] + ("..." if len(_body) > _per_hit else "")
if _desc:
_parts.append(f"### {_name}\n_{_desc}_\n{_snip}")
else:
_parts.append(f"### {_name}\n{_snip}")
_hits_str = "\n\n".join(_parts)
if len(_hits_str) > 2000:
_hits_str = _hits_str[:2000] + "\n[...truncated]"
_inject = (
"[MemPalace — relevant memories pre-loaded for this turn. "
"Do NOT re-query unless the user explicitly asks for more. "
"The answer to the user's question is very likely already "
"below — read it BEFORE reaching for any tool.]\n\n"
+ _hits_str
)
# Mark these as injected so we don't repeat them next turn
for _h in _kept:
_seen.add(_mp_dedup_key(_h))
return _inject + "\n\n---\n\n[USER MESSAGE]\n" + user_input
except Exception:
return user_input
def _run_slash_command(cmd_line: str) -> tuple[str, str | None]:
"""Run a slash command through the REPL's registered handler,
capturing stdout. Mirrors the Telegram bridge behavior
(dulus.py:_handle_slash_from_telegram).
Returns (output_text, assistant_reply_or_None).
`assistant_reply` is set when the slash triggered a model query
(cmd_type == "query") so the caller can stream it as a separate chunk.
"""
import io
if CONFIG is None:
return ("[webchat] server not initialized", None)
slash_cb = CONFIG.get("_handle_slash_callback")
if not slash_cb:
return (
f"[webchat] slash commands unavailable — REPL not active.\n"
f"Command was: {cmd_line}",
None,
)
old_stdout = sys.stdout
buf = io.StringIO()
sys.stdout = buf
try:
try:
cmd_type = slash_cb(cmd_line)
except Exception as e:
return (f"⚠ Error: {type(e).__name__}: {e}", None)
finally:
sys.stdout = old_stdout
captured = _strip_ansi(buf.getvalue()).strip()
if not captured and cmd_type == "simple":
cmd_name = cmd_line.strip().split()[0]
captured = f"✅ {cmd_name} executed."
assistant_reply: str | None = None
if cmd_type == "query" and STATE is not None and STATE.messages:
for m in reversed(STATE.messages):
if m.get("role") == "assistant":
content = m.get("content", "")
if isinstance(content, list):
parts = []
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
parts.append(block["text"])
elif isinstance(block, str):
parts.append(block)
content = "\n".join(parts)
if content:
assistant_reply = content
break
return (captured, assistant_reply)
def _run_agent_mirror(user_message: str, cancel_check=None) -> Generator:
"""Run the agent loop with shared state/config, yielding all events."""
_ensure_plugin_tools()
if STATE is None or CONFIG is None:
raise RuntimeError("webchat server not initialized")
cfg = CONFIG
state = STATE
user_input = sanitize_text(user_message)
# ── Dulus Bar (Dynamic Island) — live status for single-agent surfaces ──
# WebChat and the desktop GUI both run through this mirror; the Round Table
# uses _run_agent_for_roundtable and is intentionally left out. Lazy-start
# is idempotent. Optional: not enabled / no island / no dulus-bar → no-op.
try:
import dulus_bar_client as _bar
if _bar.enabled(cfg):
_bmodel = cfg.get("model", "")
_bar.get().start(model=_bmodel, session_id=cfg.get("_session_id"))
_bctx = ""
try:
from compaction import estimate_tokens, get_context_limit
_bused = estimate_tokens(state.messages, _bmodel, cfg, fast=True)
_blimit = get_context_limit(_bmodel) or 128000
_bpct = (_bused * 100 / _blimit) if _blimit else 0
_bctx = f"{_bpct:.1f}%" if _bpct < 1 else f"{int(_bpct)}%"
except Exception:
pass
_bar.get().status(model=_bmodel, ctx=_bctx)
except Exception:
pass
_skill_body = cfg.pop("_skill_inject", "")
if _skill_body:
user_input = (
"[SKILL CONTEXT — follow these instructions for this turn]\n\n"
+ _skill_body
+ "\n\n---\n\n[USER MESSAGE]\n"
+ user_input
)
user_input = _inject_mempalace(user_input, cfg)
# Gold display copies for GUI transcript (model gets them via system prompt).
_preload_gold_memories(state, cfg)
system_prompt = build_system_prompt(cfg)
cfg.pop("_in_telegram_turn", None)
cfg["_last_interaction_time"] = time.time()
# ── Handle deferred loading ───────────────────────────────────────
global _PENDING_HISTORY, _PENDING_SESSION_ID
if _PENDING_HISTORY:
with _LOCK:
state.messages.clear()
# Allow next turn to re-seed gold display copies
try:
CONFIG.pop("_gold_preloaded", None)
except Exception:
pass
for m in _PENDING_HISTORY:
state.messages.append(m)
cfg["_session_id"] = _PENDING_SESSION_ID
_PENDING_HISTORY = []
_PENDING_SESSION_ID = None
# track tool calls in this turn to group them if verbose is OFF
_turn_tools = []
_is_verbose = cfg.get("verbose", False)
for event in agent_run(user_input, state, cfg, system_prompt, cancel_check=cancel_check):
if not _is_verbose and isinstance(event, (ToolStart, ToolEnd)):
_turn_tools.append(event)
# If start, we might want to yield a minimal 'working' sign
if isinstance(event, ToolStart):
yield ToolStart(name="working...", inputs={})
continue
if isinstance(event, TurnDone) and not _is_verbose and _turn_tools:
# Yield a summary of grouped tools before finishing
names = list(dict.fromkeys(t.name for t in _turn_tools if isinstance(t, ToolStart)))
summary = f"Used tools: {', '.join(names)}"
yield ToolEnd(name="Summary", result=summary, permitted=True)
_turn_tools = []
yield event
try:
import checkpoint as ckpt
session_id = cfg.get("_session_id", "default")
tracked = ckpt.get_tracked_edits()
last_snaps = ckpt.list_snapshots(session_id)
skip = False
if not tracked and last_snaps:
if len(state.messages) == last_snaps[-1].get("message_index", -1):
skip = True
if not skip:
ckpt.make_snapshot(session_id, state, cfg, user_input, tracked_edits=tracked)
ckpt.reset_tracked()
except Exception:
pass
def _event_to_dict(event, bar_ok: bool = True) -> "dict | tuple | None":
if isinstance(event, TextChunk):
return {"type": "text", "text": event.text}
elif isinstance(event, ThinkingChunk):
return {"type": "thinking", "text": event.text}
elif isinstance(event, ToolStart):
return {"type": "tool_start", "name": event.name, "inputs": event.inputs}
elif isinstance(event, ToolEnd):
return {"type": "tool_end", "name": event.name, "result": event.result, "permitted": event.permitted}
elif isinstance(event, TurnDone):
return {
"type": "turn_done",
"in": event.input_tokens,
"out": event.output_tokens,
"cache_read": getattr(event, "cache_read_tokens", 0),
"cache_write": getattr(event, "cache_creation_tokens", 0),
}
elif isinstance(event, PermissionRequest):
pid = str(uuid.uuid4())
evt = threading.Event()
_PENDING_PERMISSIONS[pid] = (event, evt)
# Dulus Bar: mirror the prompt to the island and let an Allow/Deny click
# there resolve it (single-agent only — bar_ok=False for Round Table).
try:
import dulus_bar_client as _bar
if bar_ok and _bar.enabled(CONFIG):
_bar.get().start(model=(CONFIG or {}).get("model", ""))
_bar.get().tool_request(event.description or "tool")
def _island_resolve(approved, _sid, _evt=evt, _ev=event, _pid=pid):
if _evt.is_set():
return
_ev.granted = bool(approved)
_PENDING_PERMISSIONS.pop(_pid, None)
try:
_bar.get().tool_result(bool(approved))
except Exception:
pass
_evt.set()
_bar.get().on_decision(_island_resolve)
except Exception:
pass
payload = {"type": "permission", "id": pid, "description": event.description}
return payload, evt
return None
def _sanitize_for_api(text: str) -> str:
"""Aggressive sanitize: remove control chars (except \n\r\t), surrogates, and normalize."""
if not isinstance(text, str):
text = str(text)
# Step 1: remove UTF-16 surrogates
text = "".join(c for c in text if not (0xD800 <= ord(c) <= 0xDFFF))
# Step 2: remove control characters except newline, carriage return, tab
text = "".join(c for c in text if ord(c) >= 32 or c in "\n\r\t")
# Step 3: normalize fancy quotes to plain quotes
text = text.replace("\u201c", '"').replace("\u201d", '"')
text = text.replace("\u2018", "'").replace("\u2019", "'")
text = text.replace("\u2013", "-").replace("\u2014", "-")
# Step 4: strip leading/trailing whitespace per line but keep structure
return text.strip()
def _build_roundtable_prompt(agent: RoundtableAgent, user_msg: str, history: list[dict]) -> str:
"""Build a lean prompt with ONLY the last text message per member.
history items: {"agent": str, "text": str}
"""
user_msg = _sanitize_for_api(user_msg)
ctx_parts = []
# history is already pruned to last-message-per-agent before calling this
for item in history:
author = item.get("agent", "")
text = _sanitize_for_api(item.get("text", ""))
if author and text:
ctx_parts.append(f"[{author}]: {text}")
if ctx_parts:
ctx = "\n".join(ctx_parts)
return (
f"[Mesa Redonda]\n"
f"Historial (ultimo mensaje de cada miembro):\n{ctx}\n\n"
f"Usuario ahora: {user_msg}\n\n"
f"Eres el miembro {agent.id}. Responde desde tu perspectiva."
)
return (
f"[Mesa Redonda]\n"
f"Eres parte de una mesa redonda con otros agentes.\n\n"
f"Usuario ahora: {user_msg}\n\n"
f"Eres el miembro {agent.id}. Responde desde tu perspectiva."
)
def _run_agent_for_roundtable(agent: RoundtableAgent, user_msg: str, history: list[dict], q: queue.Queue):
stop_evt = threading.Event()
with _STOP_EVENTS_LOCK:
_AGENT_STOP_EVENTS[agent.id] = stop_evt
try:
_ensure_plugin_tools()
if CONFIG is None:
q.put({"agent": agent.id, "type": "error", "message": "server not initialized"})
return
cfg = dict(CONFIG)
cfg["model"] = agent.model
prompt = _sanitize_for_api(_build_roundtable_prompt(agent, user_msg, history))
system_prompt = build_system_prompt(cfg)
cfg.pop("_in_telegram_turn", None)
cfg["_last_interaction_time"] = time.time()
# DO NOT clear agent.state.messages — we need prior turns for KV cache reuse.
# The prompt itself is lean (only last msg per agent), so context stays small.
# Agent SDK appends user+assistant to .messages automatically, giving cache hits.
stopped = False
for event in agent_run(prompt, agent.state, cfg, system_prompt):
if stop_evt.is_set():
stopped = True
q.put({"agent": agent.id, "type": "agent_stopped"})
break
result = _event_to_dict(event, bar_ok=False) # Round Table: never emit to the island
if result is None:
continue
if isinstance(result, tuple):
payload, evt = result
payload["agent"] = agent.id
q.put(payload)
evt.wait(timeout=300)
_PENDING_PERMISSIONS.pop(payload["id"], None)
continue
payload = result
payload["agent"] = agent.id
q.put(payload)
if not stopped:
final_text = ""
if agent.state.messages:
for msg in reversed(agent.state.messages):
if msg.get("role") == "assistant" and msg.get("content"):
final_text = msg["content"]
break
q.put({"agent": agent.id, "type": "agent_done", "text": final_text})
except Exception as exc:
q.put({"agent": agent.id, "type": "error", "message": f"{type(exc).__name__}: {exc}"})
finally:
with _STOP_EVENTS_LOCK:
_AGENT_STOP_EVENTS.pop(agent.id, None)
# ── Flask app ──────────────────────────────────────────────────────────────
def create_app() -> Flask:
app = Flask(__name__)
import logging as _logging
_logging.getLogger("werkzeug").setLevel(_logging.ERROR)
app.logger.disabled = True
# Gate every request before it reaches a route (see _require_auth). Doing
# it here, rather than per-endpoint, means a route added later is protected
# by default instead of by remembering to opt in.
@app.before_request
def _auth_gate(): # type: ignore[unused-ignore]
denied = _require_auth()
if denied is not None:
body, status = denied
return body, status
return None
# ── CORS: open allow-list for cross-origin clients ───────────────────
# The Android sandbox APK loads its bundled React UI from a synthetic
# https://appassets.androidplatform.net/ origin via WebViewAssetLoader,
# then fetches the daemon's REST/SSE endpoints over LAN HTTP. That's
# a cross-origin request — without these headers Android WebView
# silently drops every response and the in-APK sandbox shows the OS
# shell but every app stays disconnected (the documented symptom).
# Browser-on-phone hits :5000/sandbox/ as same-origin and bypasses
# CORS entirely, which is why it "just works" outside the APK.
@app.after_request
def _cors_headers(resp):
resp.headers["Access-Control-Allow-Origin"] = "*"
resp.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-Requested-With"
resp.headers["Access-Control-Expose-Headers"] = "Content-Type, X-Session-Id"
resp.headers["Access-Control-Max-Age"] = "3600"
return resp
@app.route("/<path:_any>", methods=["OPTIONS"])
@app.route("/", methods=["OPTIONS"])
def _cors_preflight(_any=""):
# OPTIONS preflight comes in before any real call. Return 204 with
# the CORS headers (the after_request hook fills them in).
return ("", 204)
# ───────────────────────── Chat Normal HTML ─────────────────────────
CHAT_PAGE = r"""<!doctype html>
<html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" type="image/png" href="/dulus-bird.png">
<title>Dulus WebChat</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700;800&family=Archivo+Black&display=swap" rel="stylesheet">
<style>
:root{
--bg:#0a0a0a;--bg2:#0f0f12;--bg3:#15151a;--bg4:#1a1a20;
--ink:#f0e8df;--dim:#6a6470;--dim2:#3a3840;
--accent:#ff6b1f;--accent2:#ffb347;
--mono:'JetBrains Mono',monospace;
--display:'Archivo Black','Impact',sans-serif;
--radius:4px;
--green:#7cffb5;--red:#ff5a6e;--yellow:#ffd166;
}
*{box-sizing:border-box;margin:0;padding:0}
html{scroll-behavior:smooth;font-size:16px}
body{background:var(--bg);color:var(--ink);font-family:var(--mono);height:100vh;display:flex;flex-direction:column;position:relative;overflow:hidden}
::-webkit-scrollbar{width:6px}
::-webkit-scrollbar-track{background:var(--bg)}
::-webkit-scrollbar-thumb{background:var(--accent);border-radius:3px}
.grid-bg{
position:fixed;inset:0;pointer-events:none;z-index:0;
background-image:linear-gradient(rgba(255,107,31,.06) 1px,transparent 1px),
linear-gradient(90deg,rgba(255,107,31,.06) 1px,transparent 1px);
background-size:40px 40px;
mask-image:radial-gradient(ellipse at center,black 30%,transparent 80%);
}
#app{display:flex;height:100vh;overflow:hidden;position:relative}
/* ===== Sidebar ===== */
#sidebar{
width:260px;min-width:260px;background:var(--bg2);border-right:1px solid rgba(255,107,31,.12);
display:flex;flex-direction:column;transition:width .25s ease,min-width .25s ease;margin-left:0;
position:relative;z-index:200;height:100vh
}
#sidebar.collapsed{width:48px;min-width:48px}
#sidebar.collapsed .sidebar-expanded{display:none!important}
#sidebar:not(.collapsed) .sidebar-collapsed{display:none!important}
.sidebar-collapsed{display:flex;flex-direction:column;align-items:center;height:100%;padding:12px 0}
.sidebar-logo-btn{
width:32px;height:32px;background:url(/dulus-bird.png) center/contain no-repeat;
display:grid;place-items:center;cursor:pointer;border:none;flex-shrink:0;
font-size:0;color:transparent;padding:0
}
.sidebar-collapsed .sidebar-logo-btn{margin-bottom:auto}
.sidebar-collapsed .sidebar-bottom-btn{
width:32px;height:32px;display:flex;align-items:center;justify-content:center;
background:transparent;border:1px solid var(--dim2);border-radius:var(--radius);
color:var(--dim);cursor:pointer;transition:all .2s;margin-top:6px;padding:0
}
.sidebar-collapsed .sidebar-bottom-btn:hover{border-color:var(--accent);color:var(--accent);background:rgba(255,107,31,.1)}
.sidebar-expanded{display:flex;flex-direction:column;height:100%}
.sidebar-header{
display:flex;align-items:center;gap:10px;padding:16px;border-bottom:1px solid rgba(255,255,255,.05);flex-shrink:0
}
.sidebar-header h2{font-family:var(--display);font-size:14px;letter-spacing:-.01em;color:var(--ink)}
.sidebar-search{padding:12px 16px;border-bottom:1px solid rgba(255,255,255,.05);flex-shrink:0}
.sidebar-search input{
width:100%;background:var(--bg3);color:var(--ink);border:1px solid var(--dim2);padding:8px 12px;
border-radius:var(--radius);font-family:var(--mono);font-size:12px;outline:none;transition:border-color .2s
}
.sidebar-search input:focus{border-color:var(--accent)}
.sidebar-search input::placeholder{color:var(--dim)}
#sessionList{flex:1;overflow-y:auto;padding:8px}
.session-item{
display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:var(--radius);
cursor:pointer;transition:background .15s;border-left:3px solid transparent;margin-bottom:2px;
position:relative;user-select:none
}
.session-item:hover{background:rgba(255,255,255,.03)}
.session-item.active{
background:rgba(255,107,31,.08);border-left-color:var(--accent)
}
.session-icon{
width:28px;height:28px;min-width:28px;border-radius:var(--radius);background:var(--bg3);
display:grid;place-items:center;font-size:12px;color:var(--dim);border:1px solid var(--dim2)
}
.session-item.active .session-icon{border-color:var(--accent);color:var(--accent)}
.session-info{flex:1;min-width:0;overflow:hidden}
.session-title{
font-size:12px;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
font-weight:500;line-height:1.3
}
.session-time{font-size:10px;color:var(--dim);margin-top:2px}
.session-item.active .session-title{color:var(--accent2)}
.session-actions{
display:flex;gap:2px;opacity:0;transition:opacity .15s
}
.session-item:hover .session-actions{opacity:1}
.session-actions button{
width:24px;height:24px;display:flex;align-items:center;justify-content:center;
background:transparent;border:none;color:var(--dim);cursor:pointer;border-radius:3px;transition:all .15s;
padding:0
}
.session-actions button:hover{background:rgba(255,255,255,.08);color:var(--accent)}
.session-item.renaming .session-info{display:none}
.session-item.renaming .session-actions{display:none}
.session-rename-input{
flex:1;background:var(--bg3);color:var(--ink);border:1px solid var(--accent);padding:6px 8px;
border-radius:var(--radius);font-family:var(--mono);font-size:12px;outline:none
}
.sidebar-bottom{
border-top:1px solid rgba(255,255,255,.05);padding:10px 16px;display:flex;gap:6px;flex-shrink:0
}
.sidebar-bottom button{
flex:1;display:flex;align-items:center;justify-content:center;gap:6px;
background:var(--bg3);color:var(--dim);border:1px solid var(--dim2);padding:8px 0;
border-radius:var(--radius);cursor:pointer;font-family:var(--mono);font-size:11px;font-weight:700;
letter-spacing:.05em;text-transform:uppercase;transition:all .2s
}
.sidebar-bottom button:hover{background:rgba(255,107,31,.1);border-color:var(--accent);color:var(--accent)}
.sidebar-bottom button svg{width:14px;height:14px}
/* ===== Main ===== */
#main{flex:1;display:flex;flex-direction:column;min-width:0;position:relative}
/* ===== Header ===== */
header{
padding:0 24px;height:56px;background:rgba(10,10,10,.7);backdrop-filter:blur(16px);
border-bottom:1px solid rgba(255,107,31,.12);display:flex;justify-content:space-between;
align-items:center;gap:10px;position:relative;z-index:100
}
header .header-left{display:flex;align-items:center;gap:12px}
header h1{
font-family:var(--display);font-size:18px;letter-spacing:-.02em;color:var(--ink);
display:flex;align-items:center;gap:12px
}
header h1::before{
content:"";width:32px;height:32px;background:url(/dulus-bird.png) center/contain no-repeat;
display:inline-block;vertical-align:middle
}
header .model{font-size:11px;color:var(--dim)}
header a,header button{
background:var(--bg2);color:var(--dim);border:1px solid var(--dim2);padding:6px 12px;
border-radius:var(--radius);cursor:pointer;font-family:var(--mono);font-size:11px;font-weight:700;
letter-spacing:.1em;text-transform:uppercase;text-decoration:none;transition:background .2s,border-color .2s,color .2s
}
header a:hover,header button:hover{background:rgba(255,107,31,.1);border-color:var(--accent);color:var(--accent)}
#sidebarToggle{
display:none;width:36px;height:36px;align-items:center;justify-content:center;
background:transparent;border:1px solid var(--dim2);border-radius:var(--radius);
color:var(--dim);cursor:pointer;transition:all .2s;padding:0
}
#sidebarToggle:hover{border-color:var(--accent);color:var(--accent)}
/* ===== Log ===== */
#log{flex:1;overflow-y:auto;padding:24px 40px;display:flex;flex-direction:column;gap:16px;position:relative;z-index:1}
.msg{max-width:780px;padding:12px 16px;border-radius:6px;white-space:pre-wrap;word-wrap:break-word;font-size:14px}
.user{align-self:flex-end;background:rgba(255,107,31,.1);border:1px solid rgba(255,107,31,.25)}
.assistant{align-self:flex-start;background:var(--bg3);border:1px solid var(--dim2)}
.meta{font-size:10px;color:var(--dim);margin-top:6px}
.err{color:#ff5a6e;border-color:rgba(255,90,110,.4)!important}
/* ===== Input ===== */
#inputArea{
display:flex;gap:10px;padding:16px 40px;background:var(--bg2);border-top:1px solid var(--dim2);
position:relative;z-index:100
}
textarea{
flex:1;background:var(--bg3);color:var(--ink);border:1px solid var(--dim2);padding:12px;
border-radius:var(--radius);font-family:var(--mono);font-size:14px;resize:none;height:64px;