-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2280 lines (2022 loc) · 90.3 KB
/
Copy pathserver.py
File metadata and controls
2280 lines (2022 loc) · 90.3 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
#!/usr/bin/env python3
"""
AI Roundtable — a lightweight local web app for a shared brainstorm between you,
Claude Code, OpenAI Codex, and Grok Build.
The app owns ONE shared transcript. Every turn, the full labeled conversation and
the current participant roster are handed to whichever selected agent is replying,
so active participants can address / question / build on each other.
Replies stream live (NDJSON over a long-lived POST). If you barge in, the browser
aborts the request and the server kills the agent's process group/tree so it stops
generating.
No third-party dependencies: run `python3 server.py` (`py -3 server.py` on Windows),
then open the printed URL.
Auth is reused from your existing `claude`, `codex`, and `grok` CLI logins.
"""
import contextlib
import base64
import hashlib
import hmac
import ipaddress
import json
import os
import queue
import re
import secrets
import shutil
import signal
import socket
import stat
import subprocess
import sys
import tempfile
import threading
import time
import unicodedata
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit
# ---------------------------------------------------------------------------
# Config (env-overridable)
# ---------------------------------------------------------------------------
HOST = os.environ.get("ROUNDTABLE_HOST", "127.0.0.1")
_CLI_PORT = sys.argv[1] if __name__ == "__main__" and len(sys.argv) > 1 else 8765
PORT = int(os.environ.get("ROUNDTABLE_PORT", _CLI_PORT))
HERE = os.path.dirname(os.path.abspath(__file__))
WINDOWS_SHIM_BRIDGE = os.path.join(HERE, "windows_shim.ps1")
WINDOWS_SHIM_PATH_ENV = "AICONVO_SHIM_PATH"
WINDOWS_SHIM_ARGS_ENV = "AICONVO_SHIM_ARGS_JSON"
# Session signing keys are handed to an in-app replacement process through a
# private, one-use file. The environment contains only the file name, never the
# key itself. The legacy direct-token name remains solely so it can be stripped
# from provider environments created by older launchers/configurations.
REMOTE_TOKEN_ENV = "ROUNDTABLE_REMOTE_TOKEN"
REMOTE_TOKEN_FILE_ENV = "ROUNDTABLE_SESSION_SECRET_FILE"
_REMOTE_TOKEN_FILE_PREFIX = ".ai-roundtable-session-"
def _host_is_loopback(value):
if str(value).lower() == "localhost":
return True
try:
return ipaddress.ip_address(value).is_loopback
except ValueError:
return False
def _canonical_bind_host(value):
"""Resolve an IPv4 bind target once so URL and Host checks agree."""
raw = str(value).strip()
if not raw:
return ""
if raw.casefold() == "localhost":
return "127.0.0.1"
try:
address = ipaddress.ip_address(raw)
except ValueError:
try:
candidates = socket.getaddrinfo(
raw, None, socket.AF_INET, socket.SOCK_STREAM,
)
except OSError as exc:
raise ValueError(f"cannot resolve {raw!r}") from exc
if not candidates:
raise ValueError(f"cannot resolve {raw!r} to IPv4")
address = ipaddress.ip_address(candidates[0][4][0])
if address.version != 4:
raise ValueError("IPv6 binds are not supported; use an IPv4 address")
return str(address)
try:
HOST = _canonical_bind_host(HOST)
except ValueError as exc:
raise SystemExit(f"Invalid ROUNDTABLE_HOST: {exc}") from exc
def _is_lan_ipv4(address):
"""Allow private/non-global IPv4, including RFC6598 VPN addresses."""
try:
address = ipaddress.ip_address(address)
except ValueError:
return False
return address.version == 4 and not (
address.is_loopback or address.is_unspecified or address.is_link_local
or address.is_multicast or address.is_global
)
def _consume_remote_token_handoff():
"""Read and remove the one-use session-signing-key restart handoff."""
# Never accept a signing key directly through the environment. Remove the
# obsolete variable in case an older parent process supplied it.
os.environ.pop(REMOTE_TOKEN_ENV, None)
token = ""
path = os.environ.pop(REMOTE_TOKEN_FILE_ENV, "")
if not path:
return token
absolute = os.path.abspath(path)
expected_dir = os.path.realpath(tempfile.gettempdir())
valid_name = (
os.path.realpath(os.path.dirname(absolute)) == expected_dir
and os.path.basename(absolute).startswith(_REMOTE_TOKEN_FILE_PREFIX)
and absolute.endswith(".key")
)
if not valid_name:
return token
owned_file = False
try:
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
fd = os.open(absolute, flags)
try:
info = os.fstat(fd)
if not stat.S_ISREG(info.st_mode) or info.st_size > 1024:
return token
if hasattr(os, "getuid") and info.st_uid != os.getuid():
return token
if os.name != "nt" and info.st_mode & 0o077:
return token
owned_file = True
candidate = os.read(fd, 1025).decode("utf-8")
if candidate:
token = candidate
finally:
os.close(fd)
except (OSError, UnicodeError):
pass
finally:
if owned_file:
try:
os.unlink(absolute)
except OSError:
pass
return token
REMOTE_ACCESS_ENABLED = not _host_is_loopback(HOST)
REMOTE_SESSION_SECRET = _consume_remote_token_handoff() or secrets.token_urlsafe(32)
SERVER_INSTANCE_ID = secrets.token_urlsafe(12)
def _lan_ipv4_addresses():
"""Best-effort LAN addresses for device links, without sending network traffic."""
found = set()
primary = ""
try:
for item in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):
found.add(item[4][0])
except OSError:
pass
try:
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
probe.connect(("192.0.2.1", 9)) # route lookup only; UDP connect sends nothing
primary = probe.getsockname()[0]
found.add(primary)
finally:
probe.close()
except OSError:
pass
result = []
for value in found:
try:
address = ipaddress.ip_address(value)
except ValueError:
continue
if _is_lan_ipv4(address):
result.append(str(address))
return sorted(result, key=lambda value: (value != primary, ipaddress.ip_address(value)))
def _remote_urls(port=None, bind_host=None):
port = PORT if port is None else port
bind_host = HOST if bind_host is None else bind_host
addresses = _lan_ipv4_addresses()
if bind_host not in ("", "0.0.0.0") and not _host_is_loopback(bind_host):
# An explicit single-interface bind must not advertise addresses where
# the listener cannot accept connections.
addresses = [bind_host]
return [f"http://{address}:{port}/" for address in addresses]
def _absolute_user_path(value):
return os.path.abspath(os.path.expanduser(value))
# Directory the agents run in. Read-only tools (file inspection) are scoped here.
AGENT_CWD = _absolute_user_path(os.environ.get("ROUNDTABLE_CWD", HERE))
# Default Claude model. Opus 4.8 for the strongest reasoning; switch to Sonnet in
# the UI for snappier replies. Codex uses its own configured default unless set.
DEFAULT_CLAUDE_MODEL = os.environ.get("ROUNDTABLE_CLAUDE_MODEL", "claude-opus-4-8")
DEFAULT_CODEX_MODEL = os.environ.get("ROUNDTABLE_CODEX_MODEL", "") # "" = codex default
DEFAULT_GROK_MODEL = os.environ.get("ROUNDTABLE_GROK_MODEL", "grok-4.5")
CONFIG_PATH = _absolute_user_path(os.environ.get("ROUNDTABLE_CONFIG", os.path.join(HERE, "config.json")))
CODEX_HOME = _absolute_user_path(os.environ.get("CODEX_HOME", "~/.codex"))
GROK_HOME = _absolute_user_path(os.environ.get("GROK_HOME", "~/.grok"))
DEFAULT_USER_NAME = "You"
MAX_USER_NAME = 64
AI_KEYS = ("claude", "codex", "grok")
LAN_PASSWORD_CONFIG_KEY = "lanPassword"
LAN_PASSWORD_MIN_CHARS = 8
LAN_PASSWORD_MAX_CHARS = 128
LAN_PASSWORD_MAX_BYTES = 512
LAN_PASSWORD_SCRYPT_N = 1 << 15
LAN_PASSWORD_SCRYPT_R = 8
LAN_PASSWORD_SCRYPT_P = 3
LAN_PASSWORD_SALT_BYTES = 16
LAN_PASSWORD_DKLEN = 32
LAN_PASSWORD_SCRYPT_MAXMEM = 128 * 1024 * 1024
REMOTE_SESSION_TTL = 24 * 60 * 60
REMOTE_SESSION_MAX_TOKEN_BYTES = 2048
_SESSION_AUDIENCE = "ai-roundtable-lan-v1"
_AUTH_LOCK = threading.RLock()
LOGIN_RATE_WINDOW = 60.0
LOGIN_RATE_MAX_ATTEMPTS = 5
LOGIN_RATE_GLOBAL_MAX_ATTEMPTS = 20
_LOGIN_ATTEMPTS = {}
_LOGIN_GLOBAL_ATTEMPTS = []
_LOGIN_RATE_LOCK = threading.Lock()
_LOGIN_SCRYPT_SLOTS = threading.BoundedSemaphore(1)
def _b64encode(value):
return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii")
def _b64decode(value):
if not isinstance(value, str) or not value:
raise ValueError("invalid base64 value")
padding = "=" * (-len(value) % 4)
try:
return base64.b64decode(value + padding, altchars=b"-_", validate=True)
except (ValueError, UnicodeEncodeError) as exc:
raise ValueError("invalid base64 value") from exc
def _password_record(config):
"""Return a validated (salt, verifier) pair, or None for malformed data."""
record = config.get(LAN_PASSWORD_CONFIG_KEY) if isinstance(config, dict) else None
if not isinstance(record, dict) or set(record) != {"salt", "verifier"}:
return None
try:
salt = _b64decode(record["salt"])
verifier = _b64decode(record["verifier"])
except ValueError:
return None
if len(salt) != LAN_PASSWORD_SALT_BYTES or len(verifier) != LAN_PASSWORD_DKLEN:
return None
return salt, verifier
def _password_configured(config=None):
with _AUTH_LOCK:
return _password_record(APP_CONFIG if config is None else config) is not None
def _clean_lan_password(value):
if not isinstance(value, str):
raise ValueError("password must be text")
if not value.strip():
raise ValueError("password cannot be blank")
if any(unicodedata.category(char) in ("Cc", "Cf") for char in value):
raise ValueError("password cannot contain control characters")
if len(value) < LAN_PASSWORD_MIN_CHARS:
raise ValueError(f"password must be at least {LAN_PASSWORD_MIN_CHARS} characters")
if len(value) > LAN_PASSWORD_MAX_CHARS or len(value.encode("utf-8")) > LAN_PASSWORD_MAX_BYTES:
raise ValueError(f"password must be {LAN_PASSWORD_MAX_CHARS} characters or fewer")
return value
def _derive_password_verifier(password, salt):
return hashlib.scrypt(
password.encode("utf-8"), salt=salt,
n=LAN_PASSWORD_SCRYPT_N, r=LAN_PASSWORD_SCRYPT_R, p=LAN_PASSWORD_SCRYPT_P,
maxmem=LAN_PASSWORD_SCRYPT_MAXMEM, dklen=LAN_PASSWORD_DKLEN,
)
def _clean_user_name(value):
"""Validate a display name before it reaches HTML, prompts, or disk."""
if not isinstance(value, str):
raise ValueError("name must be text")
if any(unicodedata.category(char) in ("Cc", "Cf") for char in value):
raise ValueError("name must be a single line without control characters")
name = " ".join(value.split())
if not name:
raise ValueError("name cannot be empty")
if len(name) > MAX_USER_NAME:
raise ValueError(f"name must be {MAX_USER_NAME} characters or fewer")
if name.casefold() in AI_KEYS:
raise ValueError("name must be different from Claude, Codex, and Grok")
return name
def _load_app_config(path=None):
path = path or CONFIG_PATH
try:
with open(path, encoding="utf-8") as fh:
config = json.load(fh)
except (OSError, json.JSONDecodeError):
return {}
if not isinstance(config, dict):
return {}
try:
config["userName"] = _clean_user_name(config.get("userName", DEFAULT_USER_NAME))
except ValueError:
config.pop("userName", None)
if LAN_PASSWORD_CONFIG_KEY in config and _password_record(config) is None:
config.pop(LAN_PASSWORD_CONFIG_KEY, None)
return config
def _write_app_config(config, path=None):
"""Atomically replace the local config so interrupted writes cannot corrupt it."""
path = os.path.abspath(path or CONFIG_PATH)
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
fd, pending = tempfile.mkstemp(prefix=".roundtable-config-", suffix=".tmp", dir=directory)
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(config, fh, indent=2, ensure_ascii=False)
fh.write("\n")
fh.flush()
os.fsync(fh.fileno())
os.replace(pending, path)
except Exception:
try:
os.unlink(pending)
except OSError:
pass
raise
APP_CONFIG = _load_app_config()
_CONFIG_LOCK = threading.Lock()
DISPLAY = {
"user": APP_CONFIG.get("userName", DEFAULT_USER_NAME),
"claude": "Claude", "codex": "Codex", "grok": "Grok",
}
def update_user_name(value, path=None):
"""Persist and activate a human display name, leaving memory unchanged on failure."""
name = _clean_user_name(value)
with _CONFIG_LOCK:
updated = dict(APP_CONFIG)
if name == DEFAULT_USER_NAME:
updated.pop("userName", None)
else:
updated["userName"] = name
_write_app_config(updated, path)
APP_CONFIG.clear()
APP_CONFIG.update(updated)
DISPLAY["user"] = name
return name
def configure_lan_password(value, path=None):
"""Persist a new salted verifier. Plaintext never enters config or global state."""
password = _clean_lan_password(value)
salt = secrets.token_bytes(LAN_PASSWORD_SALT_BYTES)
verifier = _derive_password_verifier(password, salt)
record = {"salt": _b64encode(salt), "verifier": _b64encode(verifier)}
with _AUTH_LOCK:
with _CONFIG_LOCK:
updated = dict(APP_CONFIG)
updated[LAN_PASSWORD_CONFIG_KEY] = record
_write_app_config(updated, path)
APP_CONFIG.clear()
APP_CONFIG.update(updated)
return True
def _verify_lan_password(value):
"""Perform the expensive verifier check after the caller applies rate limiting."""
try:
password = _clean_lan_password(value)
except ValueError:
return False
with _AUTH_LOCK:
record = _password_record(APP_CONFIG)
if record is None:
return False
salt, expected = record
actual = _derive_password_verifier(password, salt)
return hmac.compare_digest(actual, expected)
def _authenticate_lan_password(value):
"""Verify and issue without allowing a password/key rotation in between."""
with _AUTH_LOCK:
if not _verify_lan_password(value):
return ""
return _issue_remote_session()
def _rotate_remote_sessions():
global REMOTE_SESSION_SECRET
replacement = secrets.token_urlsafe(32)
with _AUTH_LOCK:
REMOTE_SESSION_SECRET = replacement
return replacement
def _issue_remote_session(now=None):
now = int(time.time() if now is None else now)
payload = {
"aud": _SESSION_AUDIENCE,
"iat": now,
"exp": now + REMOTE_SESSION_TTL,
"nonce": secrets.token_urlsafe(18),
}
encoded = _b64encode(json.dumps(
payload, separators=(",", ":"), sort_keys=True,
).encode("utf-8"))
with _AUTH_LOCK:
key = REMOTE_SESSION_SECRET.encode("utf-8")
signature = _b64encode(hmac.new(key, encoded.encode("ascii"), hashlib.sha256).digest())
return encoded + "." + signature
def _valid_remote_session(value, now=None):
if not isinstance(value, str) or not value or len(value) > REMOTE_SESSION_MAX_TOKEN_BYTES:
return False
try:
encoded, supplied_signature = value.split(".", 1)
supplied = _b64decode(supplied_signature)
payload_bytes = _b64decode(encoded)
except (ValueError, UnicodeError):
return False
with _AUTH_LOCK:
key = REMOTE_SESSION_SECRET.encode("utf-8")
expected = hmac.new(key, encoded.encode("ascii"), hashlib.sha256).digest()
if not hmac.compare_digest(supplied, expected):
return False
try:
payload = json.loads(payload_bytes)
issued = int(payload["iat"])
expires = int(payload["exp"])
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
return False
current = int(time.time() if now is None else now)
return (
payload.get("aud") == _SESSION_AUDIENCE
and isinstance(payload.get("nonce"), str)
and bool(payload["nonce"])
and issued <= current + 60
and issued < expires <= issued + REMOTE_SESSION_TTL
and current < expires
)
def _login_rate_limit(client, now=None):
"""Record one direct-client login attempt; return retry seconds or zero."""
current = time.monotonic() if now is None else float(now)
cutoff = current - LOGIN_RATE_WINDOW
with _LOGIN_RATE_LOCK:
for key, recorded in list(_LOGIN_ATTEMPTS.items()):
active = [stamp for stamp in recorded if stamp > cutoff]
if active:
_LOGIN_ATTEMPTS[key] = active
else:
_LOGIN_ATTEMPTS.pop(key, None)
_LOGIN_GLOBAL_ATTEMPTS[:] = [
stamp for stamp in _LOGIN_GLOBAL_ATTEMPTS if stamp > cutoff
]
attempts = _LOGIN_ATTEMPTS.get(client, [])
if len(attempts) >= LOGIN_RATE_MAX_ATTEMPTS:
return max(1, int(LOGIN_RATE_WINDOW - (current - attempts[0]) + 0.999))
if len(_LOGIN_GLOBAL_ATTEMPTS) >= LOGIN_RATE_GLOBAL_MAX_ATTEMPTS:
return max(1, int(
LOGIN_RATE_WINDOW - (current - _LOGIN_GLOBAL_ATTEMPTS[0]) + 0.999
))
attempts.append(current) # reserve the attempt before the expensive scrypt call
_LOGIN_ATTEMPTS[client] = attempts
_LOGIN_GLOBAL_ATTEMPTS.append(current)
return 0
def _clear_login_rate_limit(client):
with _LOGIN_RATE_LOCK:
_LOGIN_ATTEMPTS.pop(client, None)
# Conversations are stored as JSON files on disk so they survive a browser clear.
CONV_DIR = _absolute_user_path(os.environ.get("ROUNDTABLE_DATA", os.path.join(HERE, "conversations")))
os.makedirs(CONV_DIR, exist_ok=True)
_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
def _conv_path(cid):
return os.path.join(CONV_DIR, cid + ".json")
def derive_title(messages):
for m in messages:
if (m.get("name") or "").lower() not in AI_KEYS:
t = " ".join((m.get("text") or "").split())
if t:
return t[:60]
return "New conversation"
def load_conv(cid):
if not _ID_RE.match(cid or ""):
return None
try:
with open(_conv_path(cid), encoding="utf-8") as fh:
return json.load(fh)
except (OSError, json.JSONDecodeError):
return None
def save_conv(doc):
with open(_conv_path(doc["id"]), "w", encoding="utf-8") as fh:
json.dump(doc, fh, indent=1, ensure_ascii=False)
def list_convs():
out = []
for name in os.listdir(CONV_DIR):
if not name.endswith(".json"):
continue
try:
with open(os.path.join(CONV_DIR, name), encoding="utf-8") as fh:
d = json.load(fh)
except (OSError, json.JSONDecodeError):
continue
out.append({
"id": d.get("id"), "title": d.get("title") or "Untitled",
"updatedAt": d.get("updatedAt", 0), "createdAt": d.get("createdAt", 0),
"count": len(d.get("messages", [])), "pinned": bool(d.get("pinned", False)),
})
out.sort(key=lambda x: (0 if x["pinned"] else 1, -x["updatedAt"])) # pinned first, then recent
return out
# ---------------------------------------------------------------------------
# Prompt construction
# ---------------------------------------------------------------------------
def _normalize_agent_keys(value, field="activeAgents"):
"""Validate and de-duplicate an ordered list of assistant keys."""
if value is None:
return list(AI_KEYS)
if not isinstance(value, (list, tuple)):
raise ValueError(f"{field} must be a list")
result = []
for item in value:
if not isinstance(item, str) or item.lower() not in AI_KEYS:
raise ValueError(f"{field} contains an unknown agent")
key = item.lower()
if key not in result:
result.append(key)
return result
def _join_names(names):
if len(names) < 2:
return "".join(names)
if len(names) == 2:
return " and ".join(names)
return ", ".join(names[:-1]) + ", and " + names[-1]
def build_prompt(self_key, transcript, write=False, active_agents=None):
"""Render the transcript and current turn's exact roster for `self_key`."""
if self_key not in AI_KEYS:
raise ValueError(f"unknown agent {self_key}")
active_keys = _normalize_agent_keys(active_agents)
if self_key not in active_keys:
raise ValueError(f"{self_key} must be included in activeAgents")
self_name = DISPLAY[self_key]
user_name = DISPLAY["user"]
active_peers = [DISPLAY[k] for k in active_keys if k != self_key]
inactive_keys = [k for k in AI_KEYS if k not in active_keys]
status_lines = [f"- {user_name} — the human participant."]
for key in AI_KEYS:
if key in active_keys:
status = ("participating in this round (selected or directly addressed); "
"may already have replied or will reply when scheduled.")
else:
status = "not participating in this round; will not reply."
status_lines.append(f"- {DISPLAY[key]} — an AI assistant; {status}")
participant_status = "\n".join(status_lines)
collaborators = [user_name] + active_peers
collaboration = _join_names(collaborators)
inactive_note = ""
if inactive_keys:
inactive_names = _join_names([DISPLAY[k] for k in inactive_keys])
inactive_note = (
f"\n- Do not address {inactive_names}, ask them questions, wait for them, or comment on "
"their silence; they are not participating in this turn. If they appear in the "
"transcript, treat those earlier messages as context only."
)
lines = []
for msg in transcript:
key = (msg.get("name") or "").lower()
name = DISPLAY[key] if key in AI_KEYS else user_name
text = (msg.get("text") or "").strip()
lines.append(f"{name}: {text}")
convo = "\n\n".join(lines) if lines else "(no messages yet)"
access = ("- You have full read/write access to the working directory: you can read and edit "
"files and run commands (git, tests, builds) when the conversation calls for it."
if write else
"- You may read files in the working directory to inform your answer, but you are "
"read-only — you cannot modify files or run commands that change anything.")
return f"""You are {self_name}, an AI assistant in a live collaborative brainstorm \
happening inside a shared chat app.
Participant status for this turn:
{participant_status}
Every active assistant receives the shared transcript before replying. Collaborate with \
{collaboration}: build on what they said, agree or disagree with specific reasoning, ask \
direct questions, and raise follow-ups. Address people by name when it helps move the idea forward.
Rules:
- Reply ONLY as {self_name}. Never write lines for anyone else.
- Do NOT prefix your message with your own name — the app already labels it.
- Be conversational and concise by default; go deep only when the topic warrants it. \
A single sentence is a fine reply when that's all that's needed.{inactive_note}
{access}
Conversation so far:
----------------------------------------
{convo}
----------------------------------------
Write {self_name}'s next message now."""
# ---------------------------------------------------------------------------
# Agent process helpers
# ---------------------------------------------------------------------------
WINDOWS_NEW_PROCESS_GROUP = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)
_PIPE_EOF = object()
_ACTIVE_PROCESSES = set()
_ACTIVE_PROCESS_LOCK = threading.Lock()
def _is_windows():
return os.name == "nt"
def _platform_key():
if _is_windows():
return "windows"
if sys.platform == "darwin":
return "macos"
return "linux" if sys.platform.startswith("linux") else sys.platform
class DirectoryPickerUnavailable(RuntimeError):
pass
class DirectoryPickerBusy(RuntimeError):
pass
_PICKER_LOCK = threading.Lock()
_PICKER_INITIAL_ENV = "AICONVO_PICKER_INITIAL"
_TK_PICKER_SCRIPT = r"""
import os
import sys
try:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
try:
root.attributes("-topmost", True)
except tk.TclError:
pass
root.update_idletasks()
selected = filedialog.askdirectory(
parent=root,
initialdir=sys.argv[1],
title="Choose the AI Roundtable workspace folder",
mustexist=True,
)
root.destroy()
sys.stdout.buffer.write(os.fsencode(selected))
except Exception as exc:
sys.stderr.write(str(exc))
raise SystemExit(2)
""".strip()
def _picker_initial_directory(value):
"""Use the nearest existing parent so pickers always open somewhere useful."""
try:
path = _absolute_user_path(value.strip()) if value and value.strip() else ""
except (OSError, ValueError):
path = ""
while path and not os.path.isdir(path):
parent = os.path.dirname(path)
if parent == path:
path = ""
break
path = parent
for candidate in (path, AGENT_CWD, os.getcwd()):
if candidate and os.path.isdir(candidate):
return os.path.abspath(candidate)
return os.path.abspath(os.curdir)
def _directory_picker_candidates(initial):
"""Yield native picker commands without passing user paths through a shell."""
platform = _platform_key()
if platform == "windows":
powershell = _windows_powershell_path()
if powershell:
script = (
"Add-Type -AssemblyName System.Windows.Forms; "
"$dialog = New-Object System.Windows.Forms.FolderBrowserDialog; "
"$dialog.Description = 'Choose the AI Roundtable workspace folder'; "
"$dialog.ShowNewFolderButton = $true; "
f"$initial = [Environment]::GetEnvironmentVariable('{_PICKER_INITIAL_ENV}'); "
"if ($initial -and [IO.Directory]::Exists($initial)) { "
"$dialog.SelectedPath = $initial }; "
"if ($dialog.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) { "
"$utf8 = [System.Text.UTF8Encoding]::new($false); "
"[Console]::OutputEncoding = $utf8; "
"[Console]::Write($dialog.SelectedPath) }"
)
yield "Windows folder dialog", [
powershell, "-NoLogo", "-NoProfile", "-STA", "-ExecutionPolicy", "Bypass",
"-Command", script,
], {_PICKER_INITIAL_ENV: initial}
elif platform == "macos":
osascript = "/usr/bin/osascript"
if os.path.isfile(osascript):
script = (
"on run argv\n"
"try\n"
"set startFolder to POSIX file (item 1 of argv)\n"
"set picked to choose folder with prompt "
'"Choose the AI Roundtable workspace folder" default location startFolder\n'
"return POSIX path of picked\n"
"on error number -128\n"
'return ""\n'
"end try\n"
"end run"
)
yield "macOS folder dialog", [osascript, "-e", script, initial], {}
else:
zenity = shutil.which("zenity")
if zenity:
start = initial if initial.endswith(os.sep) else initial + os.sep
yield "Zenity folder dialog", [
zenity, "--file-selection", "--directory",
"--title=Choose the AI Roundtable workspace folder",
"--filename=" + start,
], {}
kdialog = shutil.which("kdialog")
if kdialog:
yield "KDialog folder dialog", [
kdialog, "--getexistingdirectory", initial,
"--title", "Choose the AI Roundtable workspace folder",
], {}
# Tk is deliberately isolated in a child process: GUI toolkits should not be
# initialized inside ThreadingHTTPServer request threads.
if sys.executable:
yield "Tk folder dialog", [sys.executable, "-c", _TK_PICKER_SCRIPT, initial], {}
def pick_directory(value=""):
"""Open one host-native folder dialog; return None when the user cancels."""
if not _PICKER_LOCK.acquire(blocking=False):
raise DirectoryPickerBusy("a folder picker is already open")
try:
initial = _picker_initial_directory(value)
failures = []
for label, command, environment_updates in _directory_picker_candidates(initial):
environment = dict(os.environ)
environment.pop(REMOTE_TOKEN_ENV, None)
environment.pop(REMOTE_TOKEN_FILE_ENV, None)
environment.update(environment_updates)
try:
completed = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=environment,
check=False,
)
except OSError as exc:
failures.append(f"{label}: {exc}")
continue
stdout = completed.stdout.decode("utf-8", "replace").rstrip("\r\n")
stderr = completed.stderr.decode("utf-8", "replace").strip()
if completed.returncode:
# Native dialogs normally use a blank, non-zero result for Cancel.
cancelled = (
"User canceled" in stderr
or "(-128)" in stderr
or (completed.returncode == 1 and label in (
"Zenity folder dialog", "KDialog folder dialog"
))
)
if cancelled:
return None
detail = stderr[-240:] or f"exited with status {completed.returncode}"
failures.append(f"{label}: {detail}")
continue
if not stdout:
return None
try:
selected = _absolute_user_path(stdout)
except (OSError, ValueError) as exc:
raise DirectoryPickerUnavailable(f"folder picker returned an invalid path: {exc}")
if not os.path.isdir(selected):
raise DirectoryPickerUnavailable("folder picker returned a folder that does not exist")
return selected
detail = "; ".join(failures[-2:]) if failures else "no GUI picker is installed"
raise DirectoryPickerUnavailable(detail)
finally:
_PICKER_LOCK.release()
def _windows_native_cli_candidates(name):
"""Known locations used by each provider's official Windows installer."""
user = os.path.expanduser("~")
local = os.environ.get("LOCALAPPDATA", "")
if name == "claude":
return [os.path.join(user, ".local", "bin", "claude.exe")]
if name == "codex":
install = os.environ.get("CODEX_INSTALL_DIR", "")
return [
os.path.join(install, "codex.exe") if install else "",
os.path.join(install, "bin", "codex.exe") if install else "",
os.path.join(local, "Programs", "OpenAI", "Codex", "bin", "codex.exe") if local else "",
]
if name == "grok":
return [os.path.join(GROK_HOME, "bin", "grok.exe")]
return []
def _windows_powershell_path():
"""Find a real PowerShell executable for safe npm .ps1 shim launches."""
root = os.environ.get("SystemRoot", r"C:\Windows")
bundled = os.path.join(
root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"
)
if os.path.isfile(bundled):
return os.path.abspath(bundled)
found = shutil.which("pwsh.exe") or shutil.which("powershell.exe")
return os.path.abspath(found) if found else None
def _safe_windows_shim(path):
"""Return whether a Windows script launcher has a direct, non-cmd path."""
extension = os.path.splitext(path)[1].lower()
if extension == ".cmd":
companion = os.path.splitext(path)[0] + ".ps1"
return bool(
_windows_powershell_path()
and os.path.isfile(companion)
and os.path.isfile(WINDOWS_SHIM_BRIDGE)
)
return extension not in (".bat", ".cmd")
def _cli_path(name):
"""Resolve exactly what will be launched, preferring native Windows binaries."""
if _is_windows():
found = shutil.which(name + ".exe")
if found:
return os.path.abspath(found)
for candidate in _windows_native_cli_candidates(name):
if candidate and os.path.isfile(candidate):
return os.path.abspath(candidate)
found = shutil.which(name)
if not found:
return None
found = os.path.abspath(found)
if _is_windows() and not _safe_windows_shim(found):
return None
return found
def _resolve_cli_command(command):
command = list(command)
resolved = _cli_path(command[0])
if not resolved:
if _is_windows():
raise FileNotFoundError(
f"{command[0]} has no native executable or safe PowerShell shim; "
"install the provider's official Windows executable"
)
return command, {}
command[0] = resolved
# npm creates a same-stem .ps1 beside each .cmd shim. A fixed local bridge
# forces UTF-8 and invokes that script with direct argv, without giving
# cmd.exe a chance to reinterpret &, %, !, carets, parentheses, or paths.
if _is_windows() and os.path.splitext(resolved)[1].lower() == ".cmd":
companion = os.path.splitext(resolved)[0] + ".ps1"
powershell = _windows_powershell_path()
if powershell and os.path.isfile(companion):
# Windows PowerShell 5.1 cannot faithfully forward empty arguments
# or embedded quotes from a script to a native executable. This app
# never generates either (Windows paths cannot contain quotes and
# optional CLI values are omitted), so reject them explicitly.
for value in command[1:]:
value = str(value)
if not value or any(char in value for char in ('"', "\r", "\n", "\0")):
raise ValueError(
"Windows npm-shim arguments cannot be empty or contain quotes/control characters"
)
return [
powershell, "-NoLogo", "-NoProfile", "-NonInteractive",
"-ExecutionPolicy", "Bypass", "-File", WINDOWS_SHIM_BRIDGE,
], {
WINDOWS_SHIM_PATH_ENV: companion,
WINDOWS_SHIM_ARGS_ENV: json.dumps(command[1:], ensure_ascii=False),
}
raise OSError(
f"{resolved} is a batch launcher without a safe PowerShell companion; "
"install the provider's official Windows executable"
)
return command, {}
def _popen_platform_kwargs():
if _is_windows():
return {"creationflags": WINDOWS_NEW_PROCESS_GROUP}
return {"start_new_session": True}
def _spawn_cli(command, **kwargs):
command, environment_updates = _resolve_cli_command(command)
options = _popen_platform_kwargs()
options.update(kwargs)
requested_env = options.get("env")
launch_env = dict(os.environ if requested_env is None else requested_env)
launch_env.pop(REMOTE_TOKEN_ENV, None) # never expose the LAN bearer key to an agent
launch_env.pop(REMOTE_TOKEN_FILE_ENV, None)
launch_env.update(environment_updates)
options["env"] = launch_env
return subprocess.Popen(command, **options)
def _register_process(proc):
with _ACTIVE_PROCESS_LOCK:
_ACTIVE_PROCESSES.add(proc)
def _unregister_process(proc):
with _ACTIVE_PROCESS_LOCK:
_ACTIVE_PROCESSES.discard(proc)
def _taskkill_path():
root = os.environ.get("SystemRoot", r"C:\Windows")
native = os.path.join(root, "System32", "taskkill.exe")
return native if os.path.isfile(native) else (shutil.which("taskkill.exe") or "taskkill.exe")