-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmesh-api.py
More file actions
6005 lines (5677 loc) · 296 KB
/
mesh-api.py
File metadata and controls
6005 lines (5677 loc) · 296 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
import meshtastic
import meshtastic.serial_interface
from meshtastic import BROADCAST_ADDR
from pubsub import pub
import json
import requests
import time
from datetime import datetime, timedelta, timezone # Added timezone import
import time
import threading
import os
import smtplib
from email.mime.text import MIMEText
import logging
import traceback
from flask import Flask, request, jsonify, redirect, url_for, stream_with_context, Response, send_file
import sys
import socket # for socket error checking
import re
import io
import zipfile
import subprocess
import platform
import tempfile
import shutil
import errno
from twilio.rest import Client # for Twilio SMS support
from unidecode import unidecode # Added unidecode import for Ollama text normalization
from google.protobuf.message import DecodeError
import re
# Make sure DEBUG_ENABLED exists before any logger/filter classes use it
# -----------------------------
# Global Debug & Noise Patterns
# -----------------------------
# Debug flag loaded later from config.json
DEBUG_ENABLED = False
# Unique AI marker used to identify AI-originated messages (NOT configurable by design)
# Keep this at 3 characters max to minimize payload overhead.
AI_PREFIX_TAG = "m@i- "
# Track nodes that appear to be AI (sent messages starting with AI_PREFIX_TAG)
AI_NODE_IDS = set()
# Suppress these protobuf messages unless DEBUG_ENABLED=True
NOISE_PATTERNS = (
"Error while parsing FromRadio",
"Error parsing message with type 'meshtastic.protobuf.FromRadio'",
"Traceback",
"meshtastic/stream_interface.py",
"meshtastic/mesh_interface.py",
)
class _ProtoNoiseFilter(logging.Filter):
NOISY = (
"Error while parsing FromRadio",
"Error parsing message with type 'meshtastic.protobuf.FromRadio'",
)
def filter(self, rec: logging.LogRecord) -> bool:
noisy = any(s in rec.getMessage() for s in self.NOISY)
return DEBUG_ENABLED or not noisy # show only in debug mode
root_log = logging.getLogger() # the root logger
meshtastic_log = logging.getLogger("meshtastic")
for lg in (root_log, meshtastic_log):
lg.addFilter(_ProtoNoiseFilter())
def dprint(*args, **kwargs):
if DEBUG_ENABLED:
print(*args, **kwargs)
def info_print(*args, **kwargs):
if not DEBUG_ENABLED:
print(*args, **kwargs)
# -----------------------------
# Verbose Logging Setup
# -----------------------------
SCRIPT_LOG_FILE = "script.log"
script_logs = [] # In-memory log entries (most recent 200)
server_start_time = datetime.now(timezone.utc) # Now using UTC time
restart_count = 0
def add_script_log(message):
# drop protobuf noise if debug is off
NOISE_PATTERNS = (
"Error while parsing FromRadio",
"Error parsing message with type 'meshtastic.protobuf.FromRadio'",
"Traceback",
"meshtastic/stream_interface.py",
"meshtastic/mesh_interface.py",
)
if not DEBUG_ENABLED and any(p in message for p in NOISE_PATTERNS):
return
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
log_entry = f"{timestamp} - {message}"
script_logs.append(log_entry)
if len(script_logs) > 200:
script_logs.pop(0)
try:
# Truncate file if larger than 100 MB (keep last 100 lines)
if os.path.exists(SCRIPT_LOG_FILE):
filesize = os.path.getsize(SCRIPT_LOG_FILE)
if filesize > 100 * 1024 * 1024:
with open(SCRIPT_LOG_FILE, "r", encoding="utf-8") as f:
lines = f.readlines()
last_lines = lines[-100:] if len(lines) >= 100 else lines
with open(SCRIPT_LOG_FILE, "w", encoding="utf-8") as f:
f.writelines(last_lines)
with open(SCRIPT_LOG_FILE, "a", encoding="utf-8") as f:
# append a real newline
f.write(log_entry + "\n")
except Exception as e:
print(f"⚠️ Could not write to {SCRIPT_LOG_FILE}: {e}")
# Redirect stdout and stderr to our log while still printing to terminal.
class StreamToLogger(object):
def __init__(self, logger_func):
self.logger_func = logger_func
self.terminal = sys.__stdout__
# reuse noise patterns from the Proto filter
self.noise_patterns = _ProtoNoiseFilter.NOISY if ' _ProtoNoiseFilter' in globals() else []
def write(self, buf):
# still print everything to the terminal...
self.terminal.write(buf)
text = buf.strip()
if not text:
return
# only log to script_logs if not noisy, or if debug is on
if DEBUG_ENABLED or not any(p in text for p in self.noise_patterns):
self.logger_func(text)
def flush(self):
self.terminal.flush()
sys.stdout = StreamToLogger(add_script_log)
sys.stderr = StreamToLogger(add_script_log)
# -----------------------------
# Global Connection & Reset Status
# -----------------------------
connection_status = "Disconnected"
last_error_message = ""
reset_event = threading.Event() # Global event to signal a fatal error and trigger reconnect
# Persistent HTTP session for AI providers (connection pooling)
http_session = requests.Session()
http_session.headers.update({"Content-Type": "application/json"})
# -----------------------------
# Meshtastic and Flask Setup
# -----------------------------
try:
from meshtastic.tcp_interface import TCPInterface
except ImportError:
TCPInterface = None
try:
from meshtastic.ble_interface import BLEInterface
BLE_INTERFACE_AVAILABLE = True
except ImportError:
BLEInterface = None
BLE_INTERFACE_AVAILABLE = False
try:
from meshtastic.mesh_interface import MeshInterface
MESH_INTERFACE_AVAILABLE = True
except ImportError:
MESH_INTERFACE_AVAILABLE = False
log = logging.getLogger('werkzeug')
log.disabled = True
BANNER = (
"\033[38;5;214m"
"""
███╗ ███╗███████╗███████╗██╗ ██╗ █████╗ ██████╗ ██╗
████╗ ████║██╔════╝██╔════╝██║ ██║ ██╔══██╗██╔══██╗██║
██╔████╔██║█████╗ ███████╗███████║█████╗███████║██████╔╝██║
██║╚██╔╝██║██╔══╝ ╚════██║██╔══██║╚════╝██╔══██║██╔═══╝ ██║
██║ ╚═╝ ██║███████╗███████║██║ ██║ ██║ ██║██║ ██║
╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝
MESH-API v0.6.0 by: MR_TBOT (https://mr-tbot.com)
https://mesh-api.dev - (https://github.com/mr-tbot/mesh-api/)
\033[32m
Messaging Dashboard Access: http://localhost:5000/dashboard \033[38;5;214m
"""
"\033[0m"
"\033[31m"
"""
DISCLAIMER: This is beta software - NOT ASSOCIATED with the official Meshtastic (https://meshtastic.org/) project.
It should not be relied upon for mission critical tasks or emergencies.
Modification of this code for nefarious purposes is strictly frowned upon. Please use responsibly.
(Use at your own risk. For feedback or issues, visit https://mesh-api.dev or the links above.)
"""
"\033[0m"
)
print(BANNER)
add_script_log("Script started.")
# -----------------------------
# Load Config Files
# -----------------------------
CONFIG_FILE = "config.json"
COMMANDS_CONFIG_FILE = "commands_config.json"
MOTD_FILE = "motd.json"
LOG_FILE = "messages.log"
ARCHIVE_FILE = "messages_archive.json"
print("Loading config files...")
def safe_load_json(path, default_value):
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
print(f"⚠️ {path} not found. Using defaults.")
except Exception as e:
print(f"⚠️ Could not load {path}: {e}")
return default_value
_BUSY_ERRNOS = {
errno.EACCES,
errno.EBUSY,
errno.EPERM,
16, # POSIX EBUSY on some platforms
26, # DOS sharing violation equivalents
32, # Windows ERROR_SHARING_VIOLATION
}
def _replace_with_retries(src_path: str, dest_path: str, attempts: int = 10, base_delay: float = 0.15):
"""Atomically replace dest_path with src_path, retrying if the destination is busy.
Windows can momentarily lock files (antivirus, indexing, other processes). We retry a
few times with incremental backoff before surfacing the original exception. As a last
resort we fall back to copying the file contents in-place (non-atomic but better than
failing outright).
"""
last_exc: OSError | None = None
for attempt in range(attempts):
try:
os.replace(src_path, dest_path)
return
except OSError as exc:
last_exc = exc
err_no = getattr(exc, "errno", None)
if err_no not in _BUSY_ERRNOS:
break
time.sleep(base_delay * (attempt + 1))
if last_exc is not None:
err_no = getattr(last_exc, "errno", None)
if err_no in _BUSY_ERRNOS:
try:
with open(src_path, "rb") as src, open(dest_path, "wb") as dest:
shutil.copyfileobj(src, dest)
os.remove(src_path)
return
except Exception as fallback_exc:
last_exc = fallback_exc if isinstance(fallback_exc, OSError) else last_exc
raise last_exc
raise RuntimeError("_replace_with_retries reached an impossible state")
def _atomic_write_json(path: str, obj: dict):
"""Write JSON to `path` using a temporary file + atomic replace with retries."""
dir_name = os.path.dirname(path) or "."
prefix = os.path.basename(path) + "."
fd, tmp_path = tempfile.mkstemp(prefix=prefix, suffix=".tmp", dir=dir_name)
try:
with os.fdopen(fd, "w", encoding="utf-8") as tmp_file:
json.dump(obj, tmp_file, ensure_ascii=False, indent=2)
_replace_with_retries(tmp_path, path)
except Exception:
try:
os.remove(tmp_path)
except OSError:
pass
raise
def _atomic_write_text(path: str, text: str):
"""Write plain text to `path` atomically with retry-aware replacement."""
dir_name = os.path.dirname(path) or "."
prefix = os.path.basename(path) + "."
fd, tmp_path = tempfile.mkstemp(prefix=prefix, suffix=".tmp", dir=dir_name)
try:
with os.fdopen(fd, "w", encoding="utf-8") as tmp_file:
tmp_file.write(text)
_replace_with_retries(tmp_path, path)
except Exception:
try:
os.remove(tmp_path)
except OSError:
pass
raise
config = safe_load_json(CONFIG_FILE, {})
commands_config = safe_load_json(COMMANDS_CONFIG_FILE, {"commands": []})
try:
with open(MOTD_FILE, "r", encoding="utf-8") as f:
motd_content = f.read()
except FileNotFoundError:
print(f"⚠️ {MOTD_FILE} not found.")
motd_content = "No MOTD available."
# Config Editor endpoints are defined after app initialization below
# -----------------------------
# AI Provider & Other Config Vars
# -----------------------------
DEBUG_ENABLED = bool(config.get("debug", False))
AI_PROVIDER = config.get("ai_provider", "lmstudio").lower()
SYSTEM_PROMPT = config.get("system_prompt", "You are a helpful assistant responding to mesh network chats.")
LMSTUDIO_URL = config.get("lmstudio_url", "http://localhost:1234/v1/chat/completions")
LMSTUDIO_TIMEOUT = config.get("lmstudio_timeout", 60)
LMSTUDIO_CHAT_MODEL = config.get(
"lmstudio_chat_model",
"llama-3.2-1b-instruct-uncensored",
)
LMSTUDIO_EMBEDDING_MODEL = config.get(
"lmstudio_embedding_model",
"text-embedding-nomic-embed-text-v1.5",
)
OPENAI_API_KEY = config.get("openai_api_key", "")
OPENAI_MODEL = config.get("openai_model", "gpt-3.5-turbo")
OPENAI_TIMEOUT = config.get("openai_timeout", 30)
OLLAMA_URL = config.get("ollama_url", "http://localhost:11434/api/generate")
OLLAMA_MODEL = config.get("ollama_model", "llama2")
OLLAMA_TIMEOUT = config.get("ollama_timeout", 60)
# Optional advanced Ollama settings to improve stability/quality
OLLAMA_OPTIONS = config.get("ollama_options", {}) # e.g., {"temperature": 0.7}
OLLAMA_KEEP_ALIVE = config.get("ollama_keep_alive", "10m") # keep model loaded
CLAUDE_API_KEY = config.get("claude_api_key", "")
CLAUDE_MODEL = config.get("claude_model", "claude-sonnet-4-20250514")
CLAUDE_TIMEOUT = config.get("claude_timeout", 60)
GEMINI_API_KEY = config.get("gemini_api_key", "")
GEMINI_MODEL = config.get("gemini_model", "gemini-2.0-flash")
GEMINI_TIMEOUT = config.get("gemini_timeout", 60)
GROK_API_KEY = config.get("grok_api_key", "")
GROK_MODEL = config.get("grok_model", "grok-3")
GROK_TIMEOUT = config.get("grok_timeout", 60)
OPENROUTER_API_KEY = config.get("openrouter_api_key", "")
OPENROUTER_MODEL = config.get("openrouter_model", "openai/gpt-4.1-mini")
OPENROUTER_TIMEOUT = config.get("openrouter_timeout", 60)
GROQ_API_KEY = config.get("groq_api_key", "")
GROQ_MODEL = config.get("groq_model", "llama-3.3-70b-versatile")
GROQ_TIMEOUT = config.get("groq_timeout", 60)
DEEPSEEK_API_KEY = config.get("deepseek_api_key", "")
DEEPSEEK_MODEL = config.get("deepseek_model", "deepseek-chat")
DEEPSEEK_TIMEOUT = config.get("deepseek_timeout", 60)
MISTRAL_API_KEY = config.get("mistral_api_key", "")
MISTRAL_MODEL = config.get("mistral_model", "mistral-small-latest")
MISTRAL_TIMEOUT = config.get("mistral_timeout", 60)
OPENAI_COMPAT_API_KEY = config.get("openai_compatible_api_key", "")
OPENAI_COMPAT_URL = config.get("openai_compatible_url", "")
OPENAI_COMPAT_MODEL = config.get("openai_compatible_model", "")
OPENAI_COMPAT_TIMEOUT = config.get("openai_compatible_timeout", 60)
HOME_ASSISTANT_URL = config.get("home_assistant_url", "")
HOME_ASSISTANT_TOKEN = config.get("home_assistant_token", "")
HOME_ASSISTANT_TIMEOUT = config.get("home_assistant_timeout", 30)
HOME_ASSISTANT_ENABLE_PIN = bool(config.get("home_assistant_enable_pin", False))
HOME_ASSISTANT_SECURE_PIN = str(config.get("home_assistant_secure_pin", "1234"))
HOME_ASSISTANT_ENABLED = bool(config.get("home_assistant_enabled", False))
HOME_ASSISTANT_CHANNEL_INDEX = int(config.get("home_assistant_channel_index", -1))
MAX_CHUNK_SIZE = config.get("chunk_size", 200)
MAX_CHUNKS = int(config.get("max_ai_chunks", 5))
CHUNK_DELAY = config.get("chunk_delay", 10)
MAX_RESPONSE_LENGTH = MAX_CHUNK_SIZE * MAX_CHUNKS
LOCAL_LOCATION_STRING = config.get("local_location_string", "Unknown Location")
AI_NODE_NAME = config.get("ai_node_name", "AI-Bot")
FORCE_NODE_NUM = config.get("force_node_num", None)
ENABLE_DISCORD = config.get("enable_discord", False)
DISCORD_WEBHOOK_URL = config.get("discord_webhook_url", None)
DISCORD_SEND_EMERGENCY = config.get("discord_send_emergency", False)
DISCORD_SEND_AI = config.get("discord_send_ai", False)
DISCORD_SEND_ALL = config.get("discord_send_all", False)
DISCORD_RESPONSE_CHANNEL_INDEX = config.get("discord_response_channel_index", None)
DISCORD_RECEIVE_ENABLED = config.get("discord_receive_enabled", True)
# New variable for inbound routing
DISCORD_INBOUND_CHANNEL_INDEX = config.get("discord_inbound_channel_index", None)
if DISCORD_INBOUND_CHANNEL_INDEX is not None:
DISCORD_INBOUND_CHANNEL_INDEX = int(DISCORD_INBOUND_CHANNEL_INDEX)
# For polling Discord messages (optional)
DISCORD_BOT_TOKEN = config.get("discord_bot_token", None)
DISCORD_CHANNEL_ID = config.get("discord_channel_id", None)
ENABLE_TWILIO = config.get("enable_twilio", False)
ENABLE_SMTP = config.get("enable_smtp", False)
ALERT_PHONE_NUMBER = config.get("alert_phone_number", None)
TWILIO_SID = config.get("twilio_sid", None)
TWILIO_AUTH_TOKEN = config.get("twilio_auth_token", None)
TWILIO_FROM_NUMBER = config.get("twilio_from_number", None)
SMTP_HOST = config.get("smtp_host", None)
SMTP_PORT = config.get("smtp_port", 587)
SMTP_USER = config.get("smtp_user", None)
SMTP_PASS = config.get("smtp_pass", None)
ALERT_EMAIL_TO = config.get("alert_email_to", None)
SERIAL_PORT = config.get("serial_port", "")
SERIAL_BAUD = int(config.get("serial_baud", 921600)) # ← NEW ● default 921600
USE_WIFI = bool(config.get("use_wifi", False))
WIFI_HOST = config.get("wifi_host", None)
WIFI_PORT = int(config.get("wifi_port", 4403))
USE_BLUETOOTH = bool(config.get("use_bluetooth", False))
BLE_ADDRESS = config.get("ble_address", "")
USE_MESH_INTERFACE = bool(config.get("use_mesh_interface", False))
# Safeguards and network behavior toggles
# - ai_respond_on_longfast: if False (default), the bot will NOT reply on channel 0 (LongFast)
# - respond_to_mqtt_messages: if False (default), the bot will ignore messages received via MQTT
AI_RESPOND_ON_LONGFAST = bool(config.get("ai_respond_on_longfast", False))
RESPOND_TO_MQTT_MESSAGES = bool(config.get("respond_to_mqtt_messages", False))
# Randomized, per-install AI command alias. Generated on first run to reduce collisions
def _ensure_ai_command_alias():
alias = config.get("ai_command")
# Enforce a randomized alias; do not allow bare "/ai" as a default
if isinstance(alias, str) and alias.startswith("/") and len(alias) <= 12:
# Disallow bare "/ai" and "/ai-"
if alias.lower() not in ("/ai", "/ai-"):
return alias
import random, string
# Build a short alias like /ai-x7 or /ai5k
suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=2))
alias = f"/ai-{suffix}"
config["ai_command"] = alias
try:
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(config, f, ensure_ascii=False, indent=2)
print(f"Generated randomized AI command alias: {alias} (saved to {CONFIG_FILE})")
except Exception as e:
print(f"⚠️ Could not persist ai_command alias to {CONFIG_FILE}: {e}")
return alias
AI_COMMAND_ALIAS = _ensure_ai_command_alias()
# Derive unique suffix from the alias
# Support both old style ("/ai9z") and new dashed style ("/ai-9z") for parsing
_m = re.match(r"^(?:/ai-([a-z0-9]+)|/ai([a-z0-9]+))$", AI_COMMAND_ALIAS or "", re.IGNORECASE)
AI_SUFFIX = (_m.group(1) or _m.group(2)) if _m else ""
# Canonical, dashed AI alias for display (always shows as /ai-xx)
AI_ALIAS_CANONICAL = f"/ai-{AI_SUFFIX}" if AI_SUFFIX else AI_COMMAND_ALIAS
# Only dashed suffixed commands are allowed (no bare defaults)
AI_COMMANDS = [
f"/ai-{AI_SUFFIX}",
f"/bot-{AI_SUFFIX}",
f"/query-{AI_SUFFIX}",
f"/data-{AI_SUFFIX}",
]
# SMS also requires the unique dashed suffix
SMS_COMMAND = f"/sms-{AI_SUFFIX}"
# Other built-ins that must also use the unique dashed suffix
ABOUT_COMMAND = f"/about-{AI_SUFFIX}"
WHEREAMI_COMMAND = f"/whereami-{AI_SUFFIX}"
TEST_COMMAND = None # /test remains unsuffixed by request
HELP_COMMAND = f"/help-{AI_SUFFIX}"
MOTD_COMMAND = f"/motd-{AI_SUFFIX}"
app = Flask(__name__)
messages = []
interface = None
STARTUP_INFO_PRINTED = False # guard to avoid duplicate startup prints
lastDMNode = None
lastChannelIndex = None
# -----------------------------
# Extension System Initialisation
# -----------------------------
EXTENSIONS_PATH = config.get("extensions_path", "./extensions")
extension_loader = None # initialised in main() after helpers are defined
# -----------------------------
# Location Lookup Function
# -----------------------------
def get_node_location(node_id):
if interface and hasattr(interface, "nodes") and node_id in interface.nodes:
pos = interface.nodes[node_id].get("position", {})
lat = pos.get("latitude")
lon = pos.get("longitude")
tstamp = pos.get("time")
return lat, lon, tstamp
return None, None, None
# -----------------------------
# Config Editor Endpoints (after app creation)
# -----------------------------
@app.route("/config_editor/load", methods=["GET"])
def config_editor_load():
try:
cfg = safe_load_json(CONFIG_FILE, {})
cmds = safe_load_json(COMMANDS_CONFIG_FILE, {"commands": []})
try:
with open(MOTD_FILE, "r", encoding="utf-8") as f:
motd = f.read()
except FileNotFoundError:
motd = ""
return jsonify({"config": cfg, "commands_config": cmds, "motd": motd})
except Exception as e:
return jsonify({"message": str(e)}), 500
@app.route("/config_editor/save", methods=["POST"])
def config_editor_save():
try:
data = request.get_json(force=True) or {}
cfg = data.get("config", {})
cmds = data.get("commands_config", {})
motd = data.get("motd", "")
if not isinstance(cfg, dict):
return jsonify({"message": "config must be a JSON object"}), 400
if not isinstance(cmds, dict):
return jsonify({"message": "commands_config must be a JSON object"}), 400
_atomic_write_json(CONFIG_FILE, cfg)
_atomic_write_json(COMMANDS_CONFIG_FILE, cmds)
_atomic_write_text(MOTD_FILE, motd)
return jsonify({"status": "ok"})
except Exception as e:
return jsonify({"message": str(e)}), 500
# --- Config backup: return a ZIP of config and logs that matter ---
@app.route("/config_editor/backup", methods=["GET"])
def config_editor_backup():
try:
mem = io.BytesIO()
with zipfile.ZipFile(mem, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
# Add core config files if present
for p in (CONFIG_FILE, COMMANDS_CONFIG_FILE, MOTD_FILE):
if os.path.exists(p):
zf.write(p, arcname=f"config/{os.path.basename(p)}")
# Add last logs if present
if os.path.exists(LOG_FILE):
zf.write(LOG_FILE, arcname=f"logs/{os.path.basename(LOG_FILE)}")
if os.path.exists(SCRIPT_LOG_FILE):
zf.write(SCRIPT_LOG_FILE, arcname=f"logs/{os.path.basename(SCRIPT_LOG_FILE)}")
if os.path.exists(ARCHIVE_FILE):
zf.write(ARCHIVE_FILE, arcname=f"logs/{os.path.basename(ARCHIVE_FILE)}")
mem.seek(0)
ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
return send_file(mem, as_attachment=True, download_name=f"mesh-api-backup-{ts}.zip", mimetype="application/zip")
except Exception as e:
return jsonify({"message": str(e)}), 500
# --- Extension Management API Endpoints ---
@app.route("/extensions/status", methods=["GET"])
def extensions_status():
"""Return status of all extensions (loaded and available)."""
if not extension_loader:
return jsonify({"loaded": {}, "available": {}})
loaded_info = {}
for slug, ext in extension_loader.loaded.items():
loaded_info[slug] = {
"name": ext.name,
"version": ext.version,
"enabled": True,
"commands": list(ext.commands.keys()),
}
return jsonify({"loaded": loaded_info, "available": extension_loader.available})
@app.route("/extensions/config/<slug>", methods=["GET"])
def extensions_config_get(slug):
"""Return the config.json for a specific extension."""
ext_path = os.path.join(os.path.abspath(EXTENSIONS_PATH), slug, "config.json")
if not os.path.isfile(ext_path):
return jsonify({"message": f"Extension '{slug}' config not found"}), 404
try:
with open(ext_path, "r", encoding="utf-8") as f:
ext_config = json.load(f)
return jsonify(ext_config)
except Exception as e:
return jsonify({"message": str(e)}), 500
@app.route("/extensions/config/<slug>", methods=["PUT", "POST"])
def extensions_config_save(slug):
"""Save updated config.json for a specific extension."""
# Validate slug to prevent path traversal
if "/" in slug or "\\" in slug or ".." in slug:
return jsonify({"message": "Invalid extension name"}), 400
ext_path = os.path.join(os.path.abspath(EXTENSIONS_PATH), slug, "config.json")
if not os.path.isfile(ext_path):
return jsonify({"message": f"Extension '{slug}' config not found"}), 404
try:
data = request.get_json(force=True)
if not isinstance(data, dict):
return jsonify({"message": "Config must be a JSON object"}), 400
_atomic_write_json(ext_path, data)
add_script_log(f"[WebUI] Extension '{slug}' config saved.")
return jsonify({"status": "ok"})
except Exception as e:
return jsonify({"message": str(e)}), 500
@app.route("/extensions/toggle/<slug>", methods=["POST"])
def extensions_toggle(slug):
"""Toggle an extension's enabled state and return new state."""
if "/" in slug or "\\" in slug or ".." in slug:
return jsonify({"message": "Invalid extension name"}), 400
ext_path = os.path.join(os.path.abspath(EXTENSIONS_PATH), slug, "config.json")
if not os.path.isfile(ext_path):
return jsonify({"message": f"Extension '{slug}' config not found"}), 404
try:
with open(ext_path, "r", encoding="utf-8") as f:
ext_config = json.load(f)
ext_config["enabled"] = not ext_config.get("enabled", False)
_atomic_write_json(ext_path, ext_config)
new_state = ext_config["enabled"]
add_script_log(f"[WebUI] Extension '{slug}' {'enabled' if new_state else 'disabled'}.")
return jsonify({"status": "ok", "enabled": new_state, "note": "Restart required for changes to take effect."})
except Exception as e:
return jsonify({"message": str(e)}), 500
@app.route("/extensions/reload", methods=["POST"])
def extensions_reload():
"""Hot-reload all extensions."""
if not extension_loader:
return jsonify({"message": "Extension system not available"}), 503
try:
extension_loader.reload()
add_script_log("[WebUI] Extensions hot-reloaded.")
return jsonify({"status": "ok"})
except Exception as e:
return jsonify({"message": str(e)}), 500
# --- Soft restart: signal reconnect and reload config ---
@app.route("/restart", methods=["POST"])
def restart_service():
try:
data = request.get_json(silent=True) or {}
mode = (data.get("mode") or "soft").lower()
if mode == "hard":
add_script_log("Hard restart requested via WebUI.")
# Spawn a fresh process and exit current one
python = sys.executable
args = [python, os.path.abspath(__file__)]
creationflags = 0
# On Windows, detach new console to avoid blocking
if platform.system() == 'Windows':
creationflags = getattr(subprocess, 'CREATE_NEW_CONSOLE', 0)
subprocess.Popen(args, close_fds=True, creationflags=creationflags)
# Delay exit slightly to allow HTTP response to flush
threading.Timer(0.5, lambda: os._exit(0)).start()
return jsonify({"status": "hard-restarting"})
else:
# Soft restart: signal interface loop to reconnect
reset_event.set()
add_script_log("Soft restart requested via WebUI.")
return jsonify({"status": "soft-restarting"})
except Exception as e:
return jsonify({"message": str(e)}), 500
def load_archive():
global messages
if os.path.exists(ARCHIVE_FILE):
try:
with open(ARCHIVE_FILE, "r", encoding="utf-8") as f:
arr = json.load(f)
if isinstance(arr, list):
messages = arr
print(f"Loaded {len(messages)} messages from archive.")
except Exception as e:
print(f"⚠️ Could not load archive {ARCHIVE_FILE}: {e}")
else:
print("No archive found; starting fresh.")
def save_archive():
try:
with open(ARCHIVE_FILE, "w", encoding="utf-8") as f:
json.dump(messages, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"⚠️ Could not save archive to {ARCHIVE_FILE}: {e}")
def parse_node_id(node_str_or_int):
if isinstance(node_str_or_int, int):
return node_str_or_int
if isinstance(node_str_or_int, str):
if node_str_or_int == '^all':
return BROADCAST_ADDR
if node_str_or_int.lower() in ['!ffffffff', '!ffffffffl']:
return BROADCAST_ADDR
if node_str_or_int.startswith('!'):
hex_part = node_str_or_int[1:]
try:
return int(hex_part, 16)
except ValueError:
dprint(f"parse_node_id: Unable to parse hex from {node_str_or_int}")
return None
try:
return int(node_str_or_int)
except ValueError:
dprint(f"parse_node_id: {node_str_or_int} not recognized as int or hex.")
return None
return None
def get_node_fullname(node_id):
"""Return the full (long) name if available, otherwise the short name."""
if interface and hasattr(interface, "nodes") and node_id in interface.nodes:
user_dict = interface.nodes[node_id].get("user", {})
return user_dict.get("longName", user_dict.get("shortName", f"Node_{node_id}"))
return f"Node_{node_id}"
def get_node_shortname(node_id):
if interface and hasattr(interface, "nodes") and node_id in interface.nodes:
user_dict = interface.nodes[node_id].get("user", {})
return user_dict.get("shortName", f"Node_{node_id}")
return f"Node_{node_id}"
def log_message(node_id, text, is_emergency=False, reply_to=None, direct=False, channel_idx=None):
if node_id != "WebUI":
display_id = f"{get_node_shortname(node_id)} ({node_id})"
else:
display_id = "WebUI"
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
entry = {
"timestamp": timestamp,
"node": display_id,
"node_id": None if node_id == "WebUI" else node_id,
"message": text,
"emergency": is_emergency,
"reply_to": reply_to,
"direct": direct,
"channel_idx": channel_idx
}
messages.append(entry)
if len(messages) > 100:
messages.pop(0)
try:
with open(LOG_FILE, "a", encoding="utf-8") as logf:
logf.write(f"{timestamp} | {display_id} | EMERGENCY={is_emergency} | {text}\n")
except Exception as e:
print(f"⚠️ Could not write to {LOG_FILE}: {e}")
save_archive()
return entry
def split_message(text):
if not text:
return []
chunks = []
remaining = text
for _ in range(MAX_CHUNKS):
if not remaining:
break
if len(remaining) <= MAX_CHUNK_SIZE:
chunks.append(remaining)
break
# Try to split at a word boundary
slice_end = MAX_CHUNK_SIZE
space_idx = remaining.rfind(' ', 0, slice_end)
if space_idx > slice_end // 2:
slice_end = space_idx
chunks.append(remaining[:slice_end].rstrip())
remaining = remaining[slice_end:].lstrip()
return chunks
def add_ai_prefix(text: str) -> str:
"""Prefix AI marker if not already present."""
t = (text or "").lstrip()
if t.startswith(AI_PREFIX_TAG):
return text
# Tag already includes trailing hyphen and space
return f"{AI_PREFIX_TAG}{text}" if text else text
def sanitize_model_output(text: str) -> str:
"""Remove any 'thinking' style tags/blocks and normalize output for mesh.
Strips XML-like think tags, fenced blocks labeled as thinking/analysis/etc.,
bracketed/parenthesized meta notes, YAML/JSON-style reasoning fields, and
common heading lines like "Thought:". Also normalizes to printable ASCII
and collapses whitespace.
"""
if not text:
return ""
s = str(text)
try:
# XML-like think blocks
s = re.sub(r"<(?:think|thought|chain[ _\s-]*of[ _\s-]*thought)[^>]*>.*?</(?:think|thought|chain[ _\s-]*of[ _\s-]*thought)>", "", s, flags=re.IGNORECASE | re.DOTALL)
# Fenced blocks labeled as thinking/meta
s = re.sub(r"```[ \t]*(?:thinking|analysis|reasoning|plan|thoughts?|cot|chain[ _\s-]*of[ _\s-]*thought|inner(?:\s|-)?monologue|reflection|critique)\b[\s\S]*?```", "", s, flags=re.IGNORECASE)
# Inline meta markers
s = re.sub(r"\[(?:\s*(?:think|thinking|thoughts?|reasoning|analysis|plan|critique|reflection)[^\]]*)\]", "", s, flags=re.IGNORECASE)
s = re.sub(r"\((?:\s*(?:think|thinking|thoughts?|reasoning|analysis|plan|critique|reflection)[^\)]*)\)", "", s, flags=re.IGNORECASE)
# Fullwidth bracket meta
s = re.sub(r"【[^】]*】", "", s)
# Heading lines like "Thought:", "Reasoning:", etc.
s = re.sub(r"(?mi)^\s*(?:Thoughts?|Thinking|Reasoning|Analysis|Reflection|Critique|Self-critique|Chain\s*of\s*Thought|COT|Inner\s*Monologue|Plan|System|Tool|Action|Observation)\s*:\s*.*$\n?", "", s)
# YAML-like sections (reasoning: | then indented lines)
s = re.sub(r"(?mis)^\s*(?:reasoning|analysis|thoughts?|plan|critique|inner[ _-]?monologue|chain[ _-]?of[ _-]?thought|cot)\s*:\s*(?:\|\s*)?(?:\n(?:\s{2,}.+))*", "", s)
# [BEGIN REASONING] ... [END REASONING]
s = re.sub(r"\[\s*BEGIN[^\]]*(?:REASONING|THINKING|ANALYSIS)[^\]]*\][\s\S]*?\[\s*END[^\]]*\]", "", s, flags=re.IGNORECASE)
# JSON-like meta fields
s = re.sub(r"\"(?:reasoning|analysis|thoughts?|plan|critique|inner[_\s-]?monologue)\"\s*:\s*\"(?:\\\"|[^\"])*\"\s*,?", "", s, flags=re.IGNORECASE)
# Normalize and collapse
s = unidecode(s)
s = ''.join(ch for ch in s if ch.isprintable())
s = ' '.join(s.split())
return s
except Exception:
return s
def send_broadcast_chunks(interface, text, channelIndex):
dprint(f"send_broadcast_chunks: text='{text}', channelIndex={channelIndex}")
info_print(f"[Info] Sending broadcast on channel {channelIndex} → '{text}'")
if interface is None:
print("❌ Cannot send broadcast: interface is None.")
return
if not text:
return
chunks = split_message(text)
for i, chunk in enumerate(chunks):
try:
interface.sendText(chunk, destinationId=BROADCAST_ADDR, channelIndex=channelIndex, wantAck=True)
time.sleep(CHUNK_DELAY)
except (ConnectionResetError, BrokenPipeError, ConnectionAbortedError, TimeoutError) as e:
print(f"❌ Connection error sending broadcast chunk: {e}")
reset_event.set()
break
except Exception as e:
print(f"❌ Error sending broadcast chunk: {e}")
error_code = getattr(e, 'errno', None) or getattr(e, 'winerror', None)
if error_code in (10053, 10054, 10060):
reset_event.set()
break
else:
info_print(f"[Info] Successfully sent chunk {i+1}/{len(chunks)} on ch={channelIndex}.")
def send_direct_chunks(interface, text, destinationId):
dprint(f"send_direct_chunks: text='{text}', destId={destinationId}")
info_print(f"[Info] Sending direct message to node {destinationId} => '{text}'")
if interface is None:
print("❌ Cannot send direct message: interface is None.")
return
if not text:
return
ephemeral_ok = hasattr(interface, "sendDirectText")
chunks = split_message(text)
for i, chunk in enumerate(chunks):
try:
if ephemeral_ok:
interface.sendDirectText(destinationId, chunk, wantAck=True)
else:
interface.sendText(chunk, destinationId=destinationId, wantAck=True)
time.sleep(CHUNK_DELAY)
except (ConnectionResetError, BrokenPipeError, ConnectionAbortedError, TimeoutError) as e:
print(f"❌ Connection error sending direct chunk: {e}")
reset_event.set()
break
except Exception as e:
print(f"❌ Error sending direct chunk: {e}")
error_code = getattr(e, 'errno', None) or getattr(e, 'winerror', None)
if error_code in (10053, 10054, 10060):
reset_event.set()
break
else:
info_print(f"[Info] Direct chunk {i+1}/{len(chunks)} to {destinationId} sent.")
def send_to_lmstudio(user_message: str):
"""Chat/completion request to LM Studio with explicit model name."""
dprint(f"send_to_lmstudio: user_message='{user_message}'")
info_print("[Info] Routing user message to LMStudio…")
payload = {
"model": LMSTUDIO_CHAT_MODEL, # **mandatory when multiple models loaded**
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message},
],
"max_tokens": MAX_RESPONSE_LENGTH,
}
try:
response = requests.post(LMSTUDIO_URL, json=payload, timeout=LMSTUDIO_TIMEOUT)
if response.status_code == 200:
j = response.json()
dprint(f"LMStudio raw ⇒ {j}")
ai_resp = (
j.get("choices", [{}])[0]
.get("message", {})
.get("content", "🤖 [No response]")
)
ai_resp = sanitize_model_output(ai_resp)
return ai_resp[:MAX_RESPONSE_LENGTH]
else:
print(f"⚠️ LMStudio error: {response.status_code} - {response.text}")
return None
except Exception as e:
print(f"⚠️ LMStudio request failed: {e}")
return None
def lmstudio_embed(text: str):
"""Return an embedding vector (if you ever need it)."""
payload = {
"model": LMSTUDIO_EMBEDDING_MODEL,
"input": text,
}
try:
r = requests.post(
"http://localhost:1234/v1/embeddings",
json=payload,
timeout=LMSTUDIO_TIMEOUT,
)
if r.status_code == 200:
vec = r.json().get("data", [{}])[0].get("embedding")
return vec
else:
dprint(f"LMStudio embed error {r.status_code}: {r.text}")
except Exception as exc:
dprint(f"LMStudio embed exception: {exc}")
return None
def send_to_openai(user_message):
dprint(f"send_to_openai: user_message='{user_message}'")
info_print("[Info] Routing user message to OpenAI...")
if not OPENAI_API_KEY:
print("⚠️ No OpenAI API key provided.")
return None
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
payload = {
"model": OPENAI_MODEL,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message}
],
"max_tokens": MAX_RESPONSE_LENGTH
}
try:
r = requests.post(url, headers=headers, json=payload, timeout=OPENAI_TIMEOUT)
if r.status_code == 200:
jr = r.json()
dprint(f"OpenAI raw => {jr}")
content = (
jr.get("choices", [{}])[0]
.get("message", {})
.get("content", "🤖 [No response]")
)
content = sanitize_model_output(content)
return content[:MAX_RESPONSE_LENGTH]
else:
print(f"⚠️ OpenAI error: {r.status_code} => {r.text}")
return None
except Exception as e:
print(f"⚠️ OpenAI request failed: {e}")
return None
def send_to_ollama(user_message):
dprint(f"send_to_ollama: user_message='{user_message}'")
info_print("[Info] Routing user message to Ollama...")
# Normalize text for non-ASCII characters using unidecode
user_message = unidecode(user_message)
combined_prompt = f"{SYSTEM_PROMPT}\n{user_message}"
payload = {
"prompt": combined_prompt,
"model": OLLAMA_MODEL,
"stream": False, # Disable streaming responses for simpler parsing
"keep_alive": OLLAMA_KEEP_ALIVE,
"options": OLLAMA_OPTIONS,
}
# Simple retry for transient failures
def _sanitize(text: str) -> str:
try:
t = text or ""
# Normalize weird unicode and strip control chars
t = unidecode(t)
t = ''.join(ch for ch in t if ch.isprintable())
# Collapse excessive whitespace
return ' '.join(t.split())
except Exception:
return text or ""
# Hint Ollama to limit token generation to avoid wasting time on text that gets truncated
payload["options"] = dict(payload.get("options") or {})
payload["options"].setdefault("num_predict", MAX_RESPONSE_LENGTH)
for attempt in range(2): # up to 2 attempts
try:
r = http_session.post(OLLAMA_URL, json=payload, timeout=OLLAMA_TIMEOUT)
if r.status_code == 200:
jr = r.json()
dprint(f"Ollama raw => {jr}")
resp = jr.get("response", "")
clean = sanitize_model_output(_sanitize(resp))
return (clean if clean else "🤖 [No response]")[:MAX_RESPONSE_LENGTH]
else:
print(f"⚠️ Ollama error: {r.status_code} => {r.text}")
except Exception as e:
print(f"⚠️ Ollama request failed (attempt {attempt+1}): {e}")
time.sleep(0.5 * (attempt + 1))
return None