Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
5848 lines (5280 loc) · 279 KB
/
Copy pathapp.py
File metadata and controls
5848 lines (5280 loc) · 279 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
# ============================================================================
# SuperGrok Bridge — Qt application
# ---------------------------------------------------------------------------
# Main split-pane bridge window: debug column | chat column | live web pane.
# Hosts grok.com / chatgpt.com / gemini.google.com / claude.ai inside Qt
# WebEngine with a persistent per-provider cookie profile.
#
# Author : Trenton Tompkins <trentontompkins@gmail.com>
# Phone : 724-431-5207
# GitHub : https://github.com/tibberous/SuperGrok
#
# Need help on your next project?
# Call me at 724-431-5207 for a free consultation!
#
# Codex by Claude Opus 4.7 and ChatGPT 5.5.
# ============================================================================
from __future__ import annotations
import builtins
import base64
import hashlib
import html
import json
import mimetypes
import os
import re
import shlex
import shutil
import subprocess
import sys
import time
import traceback
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable
from exception_log import getExceptionDatabase, recordException
from PySide6.QtCore import QObject, QPoint, QProcess, QTimer, QUrl, Qt, Slot, Signal # depcheck-ok
from PySide6.QtGui import QAction, QDesktopServices, QFont, QKeySequence, QTextCursor, QTextDocument
from PySide6.QtWidgets import ( # depcheck-ok
QApplication,
QDialog,
QDockWidget,
QFileDialog,
QHBoxLayout,
QLabel,
QLineEdit,
QListWidget,
QListWidgetItem,
QMainWindow,
QMenu,
QMessageBox,
QPlainTextEdit,
QPushButton,
QSizePolicy,
QSplitter,
QStackedWidget,
QStatusBar,
QToolBar,
QVBoxLayout,
QWidget,
)
from PySide6.QtWebEngineCore import ( # depcheck-ok
QWebEnginePage,
QWebEngineProfile,
QWebEngineScript,
QWebEngineSettings,
QWebEngineUrlRequestInterceptor,
)
from PySide6.QtWebEngineWidgets import QWebEngineView # depcheck-ok
from PySide6.QtWebChannel import QWebChannel # depcheck-ok
from PySide6.QtNetwork import QHostAddress, QTcpServer, QTcpSocket # depcheck-ok
try:
from PySide6.QtTest import QTest # depcheck-ok
except Exception: # swallow-ok
QTest = None
from sqlalchemy import Column, Float, Integer, String, Text, create_engine, or_ # depcheck-ok
from sqlalchemy.orm import declarative_base, sessionmaker # depcheck-ok
HAS_SQLALCHEMY = True
ROOT = Path(__file__).resolve().parent
ASSETS = ROOT / "assets"
PRISM = ASSETS / "prism"
JQUERY = ASSETS / "jquery" / "jquery.min.js"
BRIDGE_JS = ASSETS / "js" / "grok_dom_bridge.js"
SCRIPTS = ROOT / "scripts"
DATA = ROOT / "data"
DEBUG_LOG = ROOT / "debug.log"
SESSION_LOG = ROOT / "session.log"
REQUEST_DB = DATA / "supergrok_bridge.sqlite3"
POLICY_DB = DATA / "toolcall_policy.sqlite3"
UI_STATE_DB = DATA / "supergrok_bridge_ui.sqlite3"
PROCESS_DB = DATA / "supergrok_bridge_processes.sqlite3"
EXCEPTION_DB = DATA / "supergrok_bridge_exceptions.sqlite3"
DEBUGGER_DB = DATA / "supergrok_bridge_debugger.sqlite3"
TRAFFIC_LOG = DATA / "traffic.log"
PROCESS_DEFAULT_TTL_SECONDS = 30
COMMON_COMMANDS = ROOT / "common_commands.txt"
RETURNED_ATTACHMENTS = DATA / "received_attachments"
DEBUGGER_HEARTBEAT_INTERVAL_MS = 1000
DEBUGGER_SURFACES = (
"heartbeat",
"poll",
"vardump",
"accepts-proxy",
"bridge-service",
"chat",
)
SOURCE_SIGNATURE_GLOBS = (
"start.py",
"supergrok_bridge/**/*.py",
"common_commands.txt",
)
CHATGPT_TARGET_ALIASES = {"chatgpt", "chatgtp", "gtp", "gpt", "openai"}
GROK_TARGET_ALIASES = {"grok", "supergrok", "xai"}
GEMINI_TARGET_ALIASES = {"gemini", "gem", "gem-bridge", "gembridge", "google", "googleai", "bard"}
CLAUDE_TARGET_ALIASES = {"claude", "anthropic", "claudeai", "claude-bridge", "claudebridge", "cl"}
def normalizeChatTarget(value: object = "") -> str:
target = str(value or "").strip().lower().replace("_", "-")
if target in CHATGPT_TARGET_ALIASES:
return "chatgpt"
if target in GROK_TARGET_ALIASES:
return "grok"
if target in GEMINI_TARGET_ALIASES:
return "gemini"
if target in CLAUDE_TARGET_ALIASES:
return "claude"
return target or "grok"
def chatTargetFromUrl(url: object = "") -> str:
text = str(url or "").lower()
if "chatgpt.com" in text or "chat.openai.com" in text:
return "chatgpt"
if "gemini.google.com" in text or "bard.google.com" in text:
return "gemini"
if "claude.ai" in text:
return "claude"
return "grok"
def chatProviderLabel(target: object = "") -> str:
t = normalizeChatTarget(target)
if t == "chatgpt":
return "ChatGPT"
if t == "gemini":
return "Gemini"
if t == "claude":
return "Claude"
return "Grok"
def chatProviderHomeUrl(target: object = "") -> str:
t = normalizeChatTarget(target)
if t == "chatgpt":
return "https://chatgpt.com/"
if t == "gemini":
return "https://gemini.google.com/app"
if t == "claude":
return "https://claude.ai/new"
return "https://grok.com/"
def sourceSignaturePaths() -> list[Path]:
paths: list[Path] = []
for pattern in SOURCE_SIGNATURE_GLOBS:
for candidate in ROOT.glob(pattern):
if not candidate.is_file():
continue
if "__pycache__" in candidate.parts:
continue
resolved = candidate.resolve()
if resolved not in paths:
paths.append(resolved)
return sorted(paths, key=lambda item: str(item).lower())
def buildSourceSignature() -> dict[str, Any]:
rows: list[dict[str, Any]] = []
digest = hashlib.sha256()
for path in sourceSignaturePaths():
try:
data = path.read_bytes()
stat = path.stat()
rel = path.relative_to(ROOT).as_posix()
file_sha = hashlib.sha256(data).hexdigest()
row = {
"path": rel,
"size": int(stat.st_size),
"mtimeNs": int(stat.st_mtime_ns),
"sha256": file_sha,
}
except Exception as error: # swallow-ok
row = {"path": str(path), "error": f"{type(error).__name__}: {error}"}
rows.append(row)
digest.update(json.dumps(row, sort_keys=True, ensure_ascii=False).encode("utf-8"))
digest.update(b"\n")
return {
"schema": 1,
"root": str(ROOT.resolve()),
"signature": digest.hexdigest(),
"files": rows,
"capturedAt": time.time(),
"pid": int(os.getpid() or 0),
}
BRIDGE_LOADED_SOURCE_SIGNATURE = buildSourceSignature()
REQUEST_LIST_LIMIT = 100
NETWORK_EVENT_PREFIX = "__SUPERGROK_NETWORK_EVENT__"
CHAT_MODAL_EVENT_PREFIX = "__SUPERGROK_CHAT_MODAL__"
BRIDGE_SERVICE_HOST = "127.0.0.1"
BRIDGE_SERVICE_PORT = int(os.environ.get("SUPERGROK_BRIDGE_PORT", "8767") or "8767")
_ORIGINAL_PRINT = getattr(builtins, "print")
def _appendTextLog(path: Path, text: str) -> None:
"""Append text to a root log without using print or recursively failing."""
try:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8", errors="replace") as handle: # file-io-ok: project debug/session log.
handle.write(text)
except Exception: # swallow-ok
pass
def safeJson(payload: Any) -> str:
try:
return json.dumps(payload, ensure_ascii=False, default=str, sort_keys=True)
except Exception as error: # swallow-ok
return json.dumps({"jsonError": f"{type(error).__name__}: {error}", "repr": repr(payload)}, ensure_ascii=False)
def debugLog(kind: str, text: str) -> None:
stamp = time.strftime("%Y-%m-%d %H:%M:%S")
_appendTextLog(DEBUG_LOG, f"[{stamp}] [{str(kind or 'debug').upper()}] {str(text or '')}\n")
def debugJson(kind: str, payload: dict[str, Any]) -> None:
event = dict(payload or {})
event.setdefault("loggedAt", time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + "Z")
debugLog(kind, safeJson(event))
def clearTextLog(path: Path) -> None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("", encoding="utf-8", errors="replace")
except Exception: # swallow-ok
pass
def clearRunLogs(reason: str = "bridge-app-start") -> None:
if os.environ.get("SUPERGROK_KEEP_LOGS", "").strip().lower() in {"1", "true", "yes", "on"}:
return
for path in (DEBUG_LOG, SESSION_LOG, TRAFFIC_LOG):
clearTextLog(path)
debugJson("log-reset", {"eventType": "log-reset", "reason": reason, "root": str(ROOT), "pid": os.getpid()})
def warnLog(text: str) -> None:
debugLog("warn", text)
try:
_ORIGINAL_PRINT(f"[WARN:supergrok] {text}", file=sys.stderr, flush=True)
except Exception: # swallow-ok
pass
def sessionLog(payload: dict[str, Any]) -> None:
"""Append one structured session event with full request/response content."""
event = dict(payload or {})
event.setdefault("loggedAt", time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + "Z")
_appendTextLog(SESSION_LOG, safeJson(event) + "\n")
def _installPrintTee() -> None:
if bool(getattr(builtins, "_supergrok_print_tee_installed", False)):
return
def teePrint(*args: Any, **kwargs: Any) -> None:
fileObj = kwargs.get("file", sys.stdout)
sep = kwargs.get("sep", " ")
end = kwargs.get("end", "\n")
_ORIGINAL_PRINT(*args, **kwargs)
if fileObj in (None, sys.stdout, sys.stderr):
try:
rendered = str(sep).join(str(arg) for arg in args) + str(end)
_appendTextLog(DEBUG_LOG, rendered)
except Exception: # swallow-ok
pass
setattr(builtins, "_supergrok_print_tee_installed", True) # nopatch
builtins.print = teePrint # nopatch
_installPrintTee()
debugLog("startup", f"SuperGrok Bridge process pid={os.getpid()} root={ROOT}")
def loc(text: str) -> str:
"""Localization seam for user-visible strings.
The app is still English-only, but UI text should pass through one
callable so future language tables can replace it without another UI pass.
"""
return text
def debuggerDatabasePath() -> Path:
"""Return the FlatLine-compatible SQLite DB used by launcher probes."""
configured = os.environ.get("SUPERGROK_DEBUGGER_DB") or os.environ.get("TRIO_DEBUGGER_DB") or os.environ.get("FLATLINE_DEBUGGER_DB")
return Path(configured).expanduser().resolve() if configured else DEBUGGER_DB
class DebuggerHeartbeatDatabase:
"""SQLAlchemy-backed heartbeat store for FlatLine surface probes."""
def __init__(self, path: Path | None = None) -> None:
dbPath = path or debuggerDatabasePath()
dbPath.parent.mkdir(parents=True, exist_ok=True)
self.path = dbPath
self.engine = create_engine(f"sqlite:///{dbPath}", future=True) # noqa: nonconform
self.Base = declarative_base() # noqa: nonconform
class HeartbeatRecord(self.Base): # type: ignore[misc, valid-type]
__tablename__ = "heartbeat"
id = Column(Integer, primary_key=True, autoincrement=True)
created = Column(String(32), nullable=False, index=True)
heartbeat_microtime = Column(Float, nullable=False, index=True)
source = Column(String(128), nullable=False, default="SuperGrok Bridge")
event_kind = Column(String(64), nullable=False, default="heartbeat", index=True)
reason = Column(String(255), nullable=False, default="")
caller = Column(String(255), nullable=False, default="")
phase = Column(String(128), nullable=False, default="") # noqa: redundant
pid = Column(Integer, nullable=False, default=0, index=True)
stack_trace = Column(Text, nullable=False, default="")
var_dump = Column(Text, nullable=False, default="{}")
process_snapshot = Column(Text, nullable=False, default="{}") # noqa: redundant
processed = Column(Integer, nullable=False, default=0, index=True)
self.Record = HeartbeatRecord # noqa: nonconform
self.Base.metadata.create_all(self.engine)
self.Session = sessionmaker(bind=self.engine, future=True) # noqa: nonconform
def emit( # noqa: nonconform
self,
*,
eventKind: str = "heartbeat",
reason: str = "",
caller: str = "",
phase: str = "",
varDump: dict[str, Any] | None = None,
processSnapshot: dict[str, Any] | None = None,
) -> int:
now = time.time()
row = self.Record(
created=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now)),
heartbeat_microtime=float(now),
source="SuperGrok Bridge",
event_kind=str(eventKind or "heartbeat"),
reason=str(reason or ""),
caller=str(caller or ""),
phase=str(phase or ""),
pid=int(os.getpid() or 0),
stack_trace="".join(traceback.format_stack(limit=8)),
var_dump=json.dumps(varDump or {}, ensure_ascii=False, default=str),
process_snapshot=json.dumps(processSnapshot or {}, ensure_ascii=False, default=str),
processed=0,
)
with self.Session() as session:
session.add(row)
session.commit()
return int(row.id)
def close(self) -> None:
self.engine.dispose()
_DEBUGGER_HEARTBEAT_DATABASE: DebuggerHeartbeatDatabase | None = None
def getDebuggerHeartbeatDatabase() -> DebuggerHeartbeatDatabase:
global _DEBUGGER_HEARTBEAT_DATABASE
if _DEBUGGER_HEARTBEAT_DATABASE is None:
_DEBUGGER_HEARTBEAT_DATABASE = DebuggerHeartbeatDatabase()
return _DEBUGGER_HEARTBEAT_DATABASE
def ensureDebuggerHeartbeatSchema(path: Path | None = None) -> Path:
"""Create the minimal heartbeat/poll/vardump surface schema if needed."""
database = DebuggerHeartbeatDatabase(path)
dbPath = database.path
database.close()
return dbPath
def emitDebuggerHeartbeat(
*,
eventKind: str = "heartbeat",
reason: str = "",
caller: str = "",
phase: str = "",
varDump: dict[str, Any] | None = None,
processSnapshot: dict[str, Any] | None = None,
) -> None:
"""Persist a debugger-visible heartbeat row without depending on Qt widgets."""
try:
getDebuggerHeartbeatDatabase().emit(
eventKind=eventKind,
reason=reason,
caller=caller,
phase=phase,
varDump=varDump,
processSnapshot=processSnapshot,
)
except Exception as error:
recordException("supergrok_bridge/app.py:emitDebuggerHeartbeat", error, extra={"handler": "except Exception as error:"})
def tracedReadText(path: Path, *, encoding: str = "utf-8") -> str:
writeTrafficLog({"eventType": "file-read-start", "path": str(path)})
try:
text = path.read_text(encoding=encoding) # lifecycle-file-ok
writeTrafficLog({"eventType": "file-read-complete", "path": str(path), "chars": len(text)})
return text
except Exception as error:
recordException("supergrok_bridge/app.py:tracedReadText", error, extra={"path": str(path)})
writeTrafficLog({"eventType": "file-read-failed", "path": str(path), "error": f"{type(error).__name__}: {error}"})
raise
def tracedWriteText(path: Path, text: str, *, encoding: str = "utf-8") -> None:
writeTrafficLog({"eventType": "file-write-start", "path": str(path), "chars": len(text)})
try:
path.write_text(text, encoding=encoding) # lifecycle-file-ok
writeTrafficLog({"eventType": "file-write-complete", "path": str(path)})
except Exception as error:
recordException("supergrok_bridge/app.py:tracedWriteText", error, extra={"path": str(path)})
writeTrafficLog({"eventType": "file-write-failed", "path": str(path), "error": f"{type(error).__name__}: {error}"})
raise
def tracedAppendJsonLine(path: Path, payload: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
line = json.dumps(payload, ensure_ascii=False) + "\n"
try:
with path.open("a", encoding="utf-8") as handle: # lifecycle-file-ok
handle.write(line)
except Exception as error:
recordException("supergrok_bridge/app.py:tracedAppendJsonLine", error, extra={"path": str(path)})
raise
def managedSubprocessRun(args: list[str], *, timeout: int = 10) -> subprocess.CompletedProcess[str]:
"""Run a controlled child process through the lifecycle-owned subprocess seam."""
writeTrafficLog({"eventType": "managed-subprocess-start", "args": args, "timeout": timeout})
try:
result = subprocess.run(args, capture_output=True, text=True, timeout=timeout) # lifecycle-bypass-ok
writeTrafficLog({"eventType": "managed-subprocess-complete", "args": args, "returnCode": result.returncode})
return result
except Exception as error:
recordException("supergrok_bridge/app.py:managedSubprocessRun", error, extra={"args": args, "timeout": timeout})
writeTrafficLog({"eventType": "managed-subprocess-failed", "args": args, "error": f"{type(error).__name__}: {error}"})
raise
@dataclass
class AppConfig:
initialUrl: str
target: str = "grok"
debug: bool = False
profileDir: str = ""
remoteDebugPort: int = 9222
processTtlSeconds: int = PROCESS_DEFAULT_TTL_SECONDS
serviceMode: bool = False
servicePort: int = BRIDGE_SERVICE_PORT
hideWindow: bool = False
windowMode: str = "visible"
offscreenMode: str = "auto"
def writeTrafficLog(event: dict[str, Any]) -> None:
DATA.mkdir(parents=True, exist_ok=True)
payload = dict(event or {})
payload.setdefault("loggedAt", time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + "Z")
try:
text = safeJson(payload)
tracedAppendJsonLine(TRAFFIC_LOG, payload)
debugLog("traffic", text)
except Exception as error:
recordException("supergrok_bridge/app.py:writeTrafficLog", error, extra={"handler": "except Exception:", "payloadPreview": repr(payload)[:1000]})
debugJson("traffic-log-error", {"eventType": "traffic-log-error", "error": f"{type(error).__name__}: {error}", "traceback": traceback.format_exc(), "payloadPreview": repr(payload)[:2000]})
pass
def clearTrafficLog() -> None:
DATA.mkdir(parents=True, exist_ok=True)
try:
tracedWriteText(TRAFFIC_LOG, "", encoding="utf-8")
except Exception as error:
recordException("supergrok_bridge/app.py:101", error, extra={"handler": "except Exception:"})
pass
def loadCommonCommandRoots() -> set[str]:
roots: set[str] = set()
try:
if COMMON_COMMANDS.exists():
for raw in COMMON_COMMANDS.read_text(encoding="utf-8", errors="replace").splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
roots.add(Path(line).name.lower().removesuffix(".exe"))
except Exception as error:
recordException("supergrok_bridge/app.py:loadCommonCommandRoots", error, extra={"handler": "except Exception as error:"})
roots.update({"python", "python3", "py", "pip", "pip3", "pwsh", "powershell"})
return roots
def isKnownToolCommand(command: str) -> bool:
root = commandRoot(command)
return bool(root and root in loadCommonCommandRoots())
def _stripCommandPromptPrefix(line: str) -> str:
command = str(line or "").strip()
for prefix in ("PS> ", "PS ", "$ ", "> "):
if command.startswith(prefix):
command = command[len(prefix):].strip()
return command
def parseBacktickToolCommands(message: str, policyDb: Any | None = None) -> list[str]:
"""Parse ToolCall command candidates from single, double, and triple backticks.
The intentionally simple contract for the Grok web bridge is: Grok has no
structured API tool_calls field here, so command-looking text in backticks is
treated as a ToolCall when its command root is listed in common_commands.txt
or has previously been whitelisted.
"""
text = str(message or "")
found: list[str] = []
spans: list[tuple[int, int]] = []
def accept(command: str) -> bool:
clean = _stripCommandPromptPrefix(command)
if not clean or clean.startswith("#"):
return False
root = commandRoot(clean)
if not root:
return False
try:
if policyDb is not None and getattr(policyDb, "decisionFor", lambda _root: "")(root) == "always_allow":
return True
except Exception: # swallow-ok
pass
return isKnownToolCommand(clean)
fencePattern = re.compile(r"```(?P<label>[^`\r\n]*)\r?\n(?P<body>[\s\S]*?)```", re.IGNORECASE)
for match in fencePattern.finditer(text):
spans.append(match.span())
body = match.group("body") or ""
for rawLine in body.splitlines():
command = _stripCommandPromptPrefix(rawLine)
if accept(command):
found.append(command)
inlinePattern = re.compile(r"(?<!`)`{1,2}([^`\r\n]{1,500})`{1,2}(?!`)")
for match in inlinePattern.finditer(text):
start = match.start()
if any(a <= start < b for a, b in spans):
continue
command = _stripCommandPromptPrefix(match.group(1))
if accept(command):
found.append(command)
unique: list[str] = []
seen: set[str] = set()
for command in found:
key = command.strip()
if key and key not in seen:
seen.add(key)
unique.append(key)
return unique
def bridgeAttachmentPromptText(message: str, attachments: object = None) -> str:
rows = [str(message or "").strip()]
items = attachments if isinstance(attachments, list) else []
if not items:
return rows[0]
rows.append("\n\n[SuperGrok attached files]")
for index, item in enumerate(items, start=1):
if not isinstance(item, dict):
continue
name = str(item.get("name") or f"attachment-{index}")
mime = str(item.get("mime") or "application/octet-stream")
size = int(item.get("size") or 0)
sha = str(item.get("sha256") or "")
rows.append(f"\n--- Attachment {index}: {name} | {mime} | {size} bytes | sha256={sha} ---")
if item.get("text") is not None:
text = str(item.get("text") or "")
rows.append(text)
if item.get("textTruncated"):
rows.append("\n[Attachment text truncated by SuperGrok]")
elif item.get("base64"):
rows.append(f"[base64 attachment data follows]\n{item.get('base64')}")
else:
rows.append(str(item.get("note") or "[metadata only; attachment was too large to inline]") )
return "\n".join(rows).strip()
def _safeReturnedFilename(name: str, fallback: str = "attachment.txt") -> str:
raw = Path(str(name or fallback).strip().replace("\\", "/")).name
cleaned = re.sub(r"[^A-Za-z0-9._ -]+", "_", raw).strip(" ._")
return cleaned or fallback
def _inferMimeExtension(mime: str, fallback: str = ".bin") -> str:
mime = str(mime or "").split(";", 1)[0].strip().lower()
if mime == "text/plain":
return ".txt"
if mime == "text/html":
return ".html"
if mime == "application/json":
return ".json"
guessed = mimetypes.guess_extension(mime) if mime else ""
return guessed or fallback
def _saveReturnedAttachment(name: str, data: bytes, *, source: str, mime: str = "") -> dict[str, Any]:
RETURNED_ATTACHMENTS.mkdir(parents=True, exist_ok=True)
filename = _safeReturnedFilename(name)
base = Path(filename).stem or "attachment"
suffix = Path(filename).suffix or _inferMimeExtension(mime)
target = RETURNED_ATTACHMENTS / f"{base}{suffix}"
counter = 1
while target.exists():
target = RETURNED_ATTACHMENTS / f"{base}_{counter}{suffix}"
counter += 1
target.write_bytes(data)
return {"name": target.name, "path": str(target), "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(), "mime": mime, "source": source}
def extractReturnedAttachmentsFromAnswer(answer: str) -> list[dict[str, Any]]:
text = str(answer or "")
saved: list[dict[str, Any]] = []
# data URL attachments: data:mime;base64,...
for match in re.finditer(r"data:(?P<mime>[A-Za-z0-9.+/-]+);base64,(?P<data>[A-Za-z0-9+/=\r\n]+)", text):
mime = match.group("mime") or "application/octet-stream"
try:
data = base64.b64decode(re.sub(r"\s+", "", match.group("data") or ""), validate=False)
saved.append(_saveReturnedAttachment("grok_attachment" + _inferMimeExtension(mime), data, source="data-url", mime=mime))
except Exception as error:
recordException("supergrok_bridge/app.py:extractReturnedAttachments.data-url", error, extra={"handler": "except Exception as error:"})
# filename markers around fenced code blocks.
fencePattern = re.compile(r"(?P<prefix>(?:^|\n).{0,160}?(?:file(?:name)?|path)\s*[:=]\s*(?P<name>[A-Za-z0-9._ /\\-]{1,120})\s*)?```(?P<label>[^`\r\n]*)\r?\n(?P<body>[\s\S]*?)```", re.IGNORECASE)
for match in fencePattern.finditer(text):
name = (match.group("name") or "").strip()
body = match.group("body") or ""
label = (match.group("label") or "").strip().lower()
if not name:
first = body.splitlines()[0].strip() if body.splitlines() else ""
marker = re.match(r"(?:#|//|<!--)?\s*(?:file(?:name)?|path)\s*[:=]\s*([A-Za-z0-9._ /\\-]{1,120})", first, re.I)
if marker:
name = marker.group(1).strip().strip("--> ")
body = "\n".join(body.splitlines()[1:])
if not name:
continue
mime = mimetypes.guess_type(name)[0] or ("text/" + label if label and label not in {"text", "txt"} else "text/plain")
try:
saved.append(_saveReturnedAttachment(name, body.encode("utf-8"), source="fenced-block", mime=mime))
except Exception as error:
recordException("supergrok_bridge/app.py:extractReturnedAttachments.fence", error, extra={"handler": "except Exception as error:"})
return saved
def _shellProgramForToolCalls() -> tuple[str, list[str]]:
if os.name == "nt":
program = shutil.which("pwsh") or shutil.which("pwsh.exe") or shutil.which("powershell") or shutil.which("powershell.exe") or "powershell"
return program, ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"]
return "/bin/bash", ["-lc"]
def executeCliToolCallsFromAnswer(answer: str, *, timeoutSeconds: int = PROCESS_DEFAULT_TTL_SECONDS) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
commands = parseBacktickToolCommands(answer)
for command in commands:
root = commandRoot(command)
if not root or not isKnownToolCommand(command):
continue
program, baseArgs = _shellProgramForToolCalls()
started = time.monotonic()
writeTrafficLog({"eventType": "cli-toolcall-start", "command": command, "root": root, "program": program})
try:
completed = subprocess.run([program, *baseArgs, command], cwd=str(ROOT), text=True, encoding="utf-8", errors="replace", stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=max(1, int(timeoutSeconds or PROCESS_DEFAULT_TTL_SECONDS)), check=False) # lifecycle-bypass-ok block-ok main-thread-ok: bounded subprocess.run with explicit timeout for CLI toolcall handler
result = {
"command": command,
"root": root,
"program": program,
"returncode": int(completed.returncode or 0),
"ok": int(completed.returncode or 0) == 0,
"stdout": str(completed.stdout or "")[-20000:],
"stderr": str(completed.stderr or "")[-20000:],
"elapsedSeconds": round(time.monotonic() - started, 3),
}
except subprocess.TimeoutExpired as error:
result = {"command": command, "root": root, "program": program, "returncode": 124, "ok": False, "stdout": str(getattr(error, "stdout", "") or "")[-20000:], "stderr": str(getattr(error, "stderr", "") or "")[-20000:], "error": f"TimeoutExpired after {getattr(error, 'timeout', '?')}s", "elapsedSeconds": round(time.monotonic() - started, 3)}
except Exception as error:
recordException("supergrok_bridge/app.py:executeCliToolCallsFromAnswer", error, extra={"command": command})
result = {"command": command, "root": root, "program": program, "returncode": 1, "ok": False, "stdout": "", "stderr": "", "error": f"{type(error).__name__}: {error}", "elapsedSeconds": round(time.monotonic() - started, 3)}
writeTrafficLog({"eventType": "cli-toolcall-result", **result})
results.append(result)
return results
def commandRoot(command: str) -> str:
text = (command or "").strip()
if not text:
return ""
try:
parts = shlex.split(text, posix=(os.name != "nt"))
if parts:
return Path(parts[0]).name.lower().removesuffix(".exe")
except Exception as error:
recordException("supergrok_bridge/app.py:113", error, extra={"handler": "except Exception:"})
pass
return Path(text.split()[0]).name.lower().removesuffix(".exe") if text.split() else ""
def hasShellControlOperators(command: str) -> bool:
return bool(re.search(r"[;&|<>`]", command or ""))
def displayUrl(url: QUrl | str, maxLength: int = 160) -> str:
"""Return a readable, safer URL for logs without dumping giant OAuth query strings."""
raw = url.toString() if isinstance(url, QUrl) else str(url)
if not raw:
return ""
parsed = QUrl(raw)
if parsed.isValid() and parsed.scheme() and parsed.host():
clean = f"{parsed.scheme()}://{parsed.host()}{parsed.path()}"
if parsed.hasQuery():
clean += "?…"
else:
clean = raw
if len(clean) > maxLength:
clean = clean[: maxLength - 1] + "…"
return clean
def navigationUrl(text: str) -> QUrl:
"""Convert address/search-bar text into a same-session navigable URL."""
value = text.strip()
if not value:
return QUrl()
lower = value.lower()
if lower.startswith(("http://", "https://", "file://", "about:", "devtools:")):
return QUrl.fromUserInput(value)
if "." in value and " " not in value:
return QUrl.fromUserInput(value)
# Search terms stay inside Grok by default, keeping cookies/profile/session untouched.
return QUrl.fromUserInput(f"https://grok.com/?q={value}")
SOURCE_DIALOG_DARK_THEME_CSS = """
html, body { margin:0; min-height:100%; background:#1a1d23; color:#e2e8f0; font-family:Consolas, "Cascadia Mono", "Fira Code", monospace; font-size:13px; }
pre[class*="language-"] { margin:0; padding:14px 18px; background:#1a1d23 !important; white-space:pre-wrap; overflow-wrap:anywhere; }
code[class*="language-"], pre[class*="language-"] { color:#e2e8f0 !important; text-shadow:none !important; font-family:inherit; }
.token.comment, .token.prolog, .token.doctype, .token.cdata { color:#5c6370; font-style:italic; }
.token.punctuation { color:#abb2bf; }
.token.property, .token.tag, .token.boolean, .token.number, .token.constant, .token.symbol, .token.deleted { color:#f78c6c; }
.token.selector, .token.attr-name, .token.string, .token.char, .token.builtin, .token.inserted { color:#c3e88d; }
.token.operator, .token.entity, .token.url, .language-css .token.string, .style .token.string { color:#89ddff; background:transparent; }
.token.atrule, .token.attr-value, .token.keyword { color:#c792ea; }
.token.function, .token.class-name { color:#82aaff; }
.token.regex, .token.important, .token.variable { color:#ffcb6b; }
.line-numbers .line-numbers-rows { border-right-color:#2d313a; }
.line-numbers-rows > span:before { color:#3e4451; }
::selection { background:#3d4451; color:#e2e8f0; }
::-webkit-scrollbar { width:12px; height:12px; }
::-webkit-scrollbar-track { background:#1a1d23; }
::-webkit-scrollbar-thumb { background:#3d4451; border-radius:6px; }
::-webkit-scrollbar-thumb:hover { background:#4d5461; }
"""
class SourceDialog(QDialog):
"""Pretty source viewer with Prism-highlighted view and plain-text fallback.
Default view is a QWebEngineView rendering the source through Prism with a
custom dark "One Dark"-ish theme. A toggle button switches to a plain
QPlainTextEdit if Prism fails to render (older PySide6 builds occasionally
blank-paint a second WebEngine on the same page). Copy/Save/Find work in
both modes and operate against the same backing source string.
"""
def __init__(self, source: str, language: str = "markup", parent: QWidget | None = None) -> None:
super().__init__(parent)
self.source = source or "<!-- empty source -->" # noqa: nonconform
self.language = language or "markup" # noqa: nonconform
self.setWindowTitle(loc(f"View Source — {self.language}"))
self.resize(1120, 780)
self.findBox = QLineEdit(self) # noqa: nonconform
self.findBox.setPlaceholderText(loc("Find in source... Ctrl+F"))
# Plain fallback editor — always built, always works.
self.editor = QPlainTextEdit(self) # noqa: nonconform
self.editor.setReadOnly(True)
self.editor.setPlainText(self.source)
self.editor.setFont(QFont("Consolas", 10))
self.editor.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
self.editor.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.editor.customContextMenuRequested.connect(self.openSourceContextMenu)
# Prism-highlighted view — only created if Prism assets are available.
self.prismView: QWebEngineView | None = None
prismAvailable = (PRISM / "prism.min.css").exists() and (PRISM / "prism.min.js").exists()
if prismAvailable:
try:
self.prismView = QWebEngineView(self)
self.prismView.setHtml(self.buildPrismHtml(self.source, self.language), QUrl.fromLocalFile(str(ROOT / "source_dialog.html")))
except Exception as error:
recordException("supergrok_bridge/app.py:SourceDialog.prism-init", error, extra={"handler": "prism view init"})
self.prismView = None # noqa: nonconform
self.stack = QStackedWidget(self) # noqa: nonconform
if self.prismView is not None:
self.stack.addWidget(self.prismView) # index 0 — Prism
self.stack.addWidget(self.editor) # index 1 — plain fallback
self.stack.setCurrentIndex(0)
else:
self.stack.addWidget(self.editor)
self.stack.setCurrentIndex(0)
saveButton = QPushButton(loc("Save As..."), self)
copyAllButton = QPushButton(loc("Copy All"), self)
closeButton = QPushButton(loc("Close"), self) # noqa: redundant
findNextButton = QPushButton(loc("Find Next"), self) # noqa: redundant
findPreviousButton = QPushButton(loc("Find Prev"), self)
self.toggleButton = QPushButton(loc("Plain"), self) if self.prismView is not None else QPushButton(loc("Plain"), self) # noqa: nonconform
self.toggleButton.setEnabled(self.prismView is not None)
self.toggleButton.setToolTip(loc("Toggle Prism highlight / plain text view"))
saveButton.clicked.connect(self.saveSourceAs)
copyAllButton.clicked.connect(self.copyAllSource)
closeButton.clicked.connect(self.close) # noqa: redundant
self.findBox.returnPressed.connect(self.findNextSource)
findNextButton.clicked.connect(self.findNextSource)
findPreviousButton.clicked.connect(self.findPreviousSource)
self.toggleButton.clicked.connect(self.toggleHighlightMode)
focusFindAction = QAction(loc("Find"), self)
focusFindAction.setShortcut(QKeySequence.StandardKey.Find)
focusFindAction.triggered.connect(lambda: (self.findBox.setFocus(), self.findBox.selectAll()))
self.addAction(focusFindAction)
copyAction = QAction(loc("Copy"), self)
copyAction.setShortcut(QKeySequence.StandardKey.Copy)
copyAction.triggered.connect(self.editor.copy)
self.addAction(copyAction)
selectAllAction = QAction(loc("Select All"), self)
selectAllAction.setShortcut(QKeySequence.StandardKey.SelectAll)
selectAllAction.triggered.connect(self.editor.selectAll)
self.addAction(selectAllAction)
modeLabel = loc("Highlighted source") if self.prismView is not None else loc("Plain source viewer")
buttonRow = QHBoxLayout()
buttonRow.addWidget(QLabel(modeLabel, self))
buttonRow.addWidget(self.findBox, 1)
buttonRow.addWidget(findPreviousButton)
buttonRow.addWidget(findNextButton)
buttonRow.addWidget(self.toggleButton)
buttonRow.addWidget(copyAllButton)
buttonRow.addWidget(saveButton)
buttonRow.addWidget(closeButton) # noqa: redundant
layout = QVBoxLayout(self)
layout.addLayout(buttonRow)
layout.addWidget(self.stack, 1)
def buildPrismHtml(self, source: str, language: str) -> str:
escapedSource = html.escape(source, quote=False)
prismCss = QUrl.fromLocalFile(str(PRISM / "prism.min.css")).toString()
prismJs = QUrl.fromLocalFile(str(PRISM / "prism.min.js")).toString()
# Component scripts are optional — present a small whitelist.
componentTags = []
for name in ("prism-markup.min.js", "prism-javascript.min.js", "prism-css.min.js", "prism-json.min.js", "prism-python.min.js", "prism-bash.min.js", "prism-powershell.min.js", "prism-sql.min.js", "prism-yaml.min.js"):
path = PRISM / "components" / name
if path.exists():
componentTags.append(f'<script src="{html.escape(QUrl.fromLocalFile(str(path)).toString())}"></script>')
cssTag = f'<link rel="stylesheet" href="{html.escape(prismCss)}">'
jsTag = f'<script src="{html.escape(prismJs)}"></script>'
comps = "\n".join(componentTags)
return f'''<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>View Source</title>
{cssTag}
<style>{SOURCE_DIALOG_DARK_THEME_CSS}</style>
</head>
<body>
<pre><code class="language-{html.escape(language)}">{escapedSource}</code></pre>
{jsTag}
{comps}
<script>if (window.Prism) {{ Prism.highlightAll(); }}</script>
</body>
</html>'''
@Slot()
def toggleHighlightMode(self) -> None:
if self.prismView is None:
return
if self.stack.currentIndex() == 0:
self.stack.setCurrentIndex(1)
self.toggleButton.setText(loc("Highlight"))
else:
self.stack.setCurrentIndex(0)
self.toggleButton.setText(loc("Plain"))
def _findInPrism(self, text: str, backward: bool = False) -> None:
if self.prismView is None:
return
try:
flags = QWebEnginePage.FindFlag.FindBackward if backward else QWebEnginePage.FindFlag(0)
self.prismView.findText(text, flags)
except Exception as error:
recordException("supergrok_bridge/app.py:SourceDialog._findInPrism", error, extra={"backward": backward})
@Slot()
def findNextSource(self) -> None:
text = self.findBox.text()
if not text:
return
if self.prismView is not None and self.stack.currentIndex() == 0:
self._findInPrism(text, backward=False)
return
if not self.editor.find(text):
self.editor.moveCursor(QTextCursor.MoveOperation.Start)
self.editor.find(text)
@Slot()
def findPreviousSource(self) -> None:
text = self.findBox.text()
if not text:
return
if self.prismView is not None and self.stack.currentIndex() == 0:
self._findInPrism(text, backward=True)
return
if not self.editor.find(text, QTextDocument.FindFlag.FindBackward):
self.editor.moveCursor(QTextCursor.MoveOperation.End)
self.editor.find(text, QTextDocument.FindFlag.FindBackward)
@Slot(QPoint)
def openSourceContextMenu(self, point: QPoint) -> None:
menu = self.editor.createStandardContextMenu()
menu.addSeparator()
copyAllAction = QAction(loc("Copy All Source"), self)
copyAllAction.triggered.connect(self.copyAllSource)
findAction = QAction(loc("Find..."), self)
findAction.triggered.connect(lambda: (self.findBox.setFocus(), self.findBox.selectAll()))
saveAction = QAction(loc("Save Source As..."), self)
saveAction.triggered.connect(self.saveSourceAs)
menu.addAction(copyAllAction)
menu.addAction(findAction)
menu.addAction(saveAction) # noqa: redundant
menu.exec(self.editor.mapToGlobal(point)) # qt-main-thread-ok
@Slot()
def copyAllSource(self) -> None:
clipboard = QApplication.clipboard()
if clipboard is not None:
clipboard.setText(self.source)
@Slot()
def saveSourceAs(self) -> None:
filename, _selectedFilter = QFileDialog.getSaveFileName(
self,
"Save Source As",
str(Path.home() / "grok_page_source.html"),
"HTML Files (*.html *.htm);;Text Files (*.txt);;All Files (*)",
)
if not filename:
writeTrafficLog({"eventType": "file-save-cancelled", "dialog": "SourceDialog.saveSourceAs"})
return
target = Path(filename)
writeTrafficLog({"eventType": "file-save-start", "dialog": "SourceDialog.saveSourceAs", "path": str(target), "bytes": len(self.source.encode("utf-8", errors="replace"))})