Repository navigation
Expand file tree
/
Copy pathcraftbot.py
More file actions
2863 lines (2435 loc) · 106 KB
/
Copy pathcraftbot.py
File metadata and controls
2863 lines (2435 loc) · 106 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
"""
CraftBot Service Manager
Run CraftBot as a background process that survives terminal closure,
and optionally register it to auto-start when your system boots.
Commands:
python craftbot.py start [options] Start CraftBot in background
python craftbot.py open Open CraftBot in the browser, starting it
first if it is not running (desktop icon)
python craftbot.py stop Stop CraftBot
python craftbot.py restart [options] Stop then start
python craftbot.py status Show if CraftBot is running
python craftbot.py logs [-n N] Show last N log lines (default: 50)
python craftbot.py tui [options] Open the terminal edition in this console,
starting CraftBot in the background first
if it is not running
python craftbot.py install [options] Register for auto-start on boot/login
python craftbot.py autostart enable Enable automatic startup at login
python craftbot.py autostart disable Disable automatic startup (keep installed)
python craftbot.py autostart status Show automatic startup status
python craftbot.py uninstall Remove auto-start registration
python craftbot.py repair [options] Re-copy current EXE over the installed
copy and restart (frozen EXE only)
python craftbot.py wizard Open the GUI wizard
When running as a frozen EXE (CraftBot.exe with no args), the wizard opens
automatically. Subcommands work the same as in source mode.
Options passed to 'start' / 'install':
--tui Run the terminal edition instead of the browser (the
backend runs in the background; open it with `tui`)
--no-open-browser Don't open browser automatically (default for service)
--frontend-port PORT Frontend port (default: 7925, or the next free pair)
--backend-port PORT Backend port (default: 7926, or the next free pair)
--agent-app-port PORT First Agent App port, apps get PORT to PORT+99 (default: 3100)
--conda Use conda environment
--no-conda Don't use conda
--no-autostart Install without automatic startup at login
'start' waits until CraftBot answers (or prints why it stopped).
Examples:
python craftbot.py start # Start in background (browser mode)
python craftbot.py tui # Open the terminal edition
python craftbot.py install # Auto-start on login (browser mode)
python craftbot.py install --no-open-browser # Auto-start without opening browser
python craftbot.py stop
python craftbot.py logs -n 100
"""
import sys
import os
# In windowed (console=False) PyInstaller builds, sys.stdout and sys.stderr
# are None. Lots of libraries (including run.py at import time) call
# sys.stdout.isatty() unconditionally and crash with AttributeError. Install
# an output handle before ANY other import that might transitively hit
# stdout. Must be the very first thing this module does.
if sys.stdout is None or sys.stderr is None:
# Real handles can also be passed through an interpreter handoff.
output = open(os.devnull, "w", encoding="utf-8")
if sys.stdout is None:
sys.stdout = output
if sys.stderr is None:
sys.stderr = output
import shlex
import shutil
import signal
import subprocess
import time
import webbrowser
from typing import Callable, List, Optional
from installer import helpers as _helpers
from installer import metadata as _metadata
from installer import payload as _payload
from installer import startup as _startup
# Store platform once so static analysers don't short-circuit platform branches
_PLATFORM: str = sys.platform
# ─── Frozen-mode detection ────────────────────────────────────────────────────
# True when running as a PyInstaller-bundled EXE. The frozen EXE is the
# *installer* — a small Tkinter wizard that downloads the agent payload from
# GitHub Releases and installs it into a chosen location. The installer does
# NOT contain the agent itself (no run.py, no openai/anthropic/etc bundled).
IS_FROZEN: bool = bool(getattr(sys, "frozen", False))
EXE_PATH: Optional[str] = sys.executable if IS_FROZEN else None
# --state-root=PATH names this install's data folder. The desktop icon passes
# it because, like a login start, it does not inherit CRAFTBOT_HOME from the
# shell that installed CraftBot. Applied before any app module is imported
# (app.paths resolves STATE_ROOT at import time) and removed from the args.
for _argument in list(sys.argv[1:]):
if _argument.startswith("--state-root="):
os.environ["CRAFTBOT_HOME"] = _argument.split("=", 1)[1]
sys.argv.remove(_argument)
# Single interpreter for every CraftBot process (see app/python_runtime.py).
# Absent in the frozen installer EXE, which bundles no agent code.
try:
from app import python_runtime as _python_runtime
except ImportError:
_python_runtime = None
# Where code and state live, for every install path (see app/paths.py).
# Imported unconditionally — it is stdlib-only, so it is available in the
# frozen installer EXE too, unlike the rest of app/.
from app import paths # noqa: E402
# Agent payload (download/extract/version) lives in craftbot_payload.
# These re-exports keep external callers (e.g. CraftBotInstaller.spec docstring,
# any future tooling) working with the legacy `craftbot.GITHUB_OWNER` etc.
GITHUB_OWNER = _payload.GITHUB_OWNER
GITHUB_REPO = _payload.GITHUB_REPO
# ─── Paths ────────────────────────────────────────────────────────────────────
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def _read_bundled_version() -> str:
return _payload.read_bundled_version(BASE_DIR)
def _user_data_dir() -> str:
"""Return the per-user persistent data directory for CraftBot.
Used for PID file, log file, and install metadata when running as a
frozen EXE (BASE_DIR points at the temp-extracted bundle, which is
wiped between runs). For source installs we keep the legacy behaviour
of writing alongside craftbot.py, since BASE_DIR is already stable.
"""
if not IS_FROZEN:
return BASE_DIR
if _PLATFORM == "win32":
root = os.environ.get("LOCALAPPDATA") or os.path.expanduser(r"~\AppData\Local")
path = os.path.join(root, "CraftBot")
elif _PLATFORM == "darwin":
path = os.path.expanduser("~/Library/Application Support/CraftBot")
else:
root = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
path = os.path.join(root, "craftbot")
os.makedirs(path, exist_ok=True)
return path
# The running CraftBot as seen from outside (app/instance.py). One pid file
# and one log for every launcher: run.py writes the pid file itself, so
# craftbot.py, the desktop launcher and service managers all read the same
# record, in STATE_ROOT next to the user's data.
from app import instance as _instance # noqa: E402
PID_FILE = str(_instance.PID_FILE)
LOG_FILE = str(_instance.LOG_FILE)
INSTALL_METADATA_FILE = os.path.join(_user_data_dir(), "install.json")
# Source-mode only — relative to craftbot.py. The frozen installer never
# uses this; it spawns the installed agent EXE directly.
RUN_SCRIPT = os.path.join(BASE_DIR, "run.py")
def default_install_location() -> str:
"""Return the default install directory used by the wizard's location chooser.
Picks a per-user path that does NOT require admin elevation. The wizard
lets the user override this via filedialog.askdirectory().
"""
if _PLATFORM == "win32":
root = os.environ.get("LOCALAPPDATA") or os.path.expanduser(r"~\AppData\Local")
return os.path.join(root, "Programs", "CraftBot")
if _PLATFORM == "darwin":
return os.path.expanduser("~/Applications/CraftBot")
return os.path.expanduser("~/.local/share/craftbot")
# Install metadata helpers — pure-function impls live in craftbot_metadata.
# We keep these no-arg wrappers so the wizard (and any external caller) can
# use the legacy `craftbot.installed_exe_path()` API without threading the
# metadata-file path through every call site.
def read_install_metadata() -> Optional[dict]:
return _metadata.read(INSTALL_METADATA_FILE)
def write_install_metadata(
installed_path: str,
mode: str,
python: Optional[str] = None,
version: Optional[str] = None,
) -> None:
"""Record what was installed, where, and what runs it.
python/version are schema-2 fields: an install is now a source tree plus
an interpreter, so both have to be recorded for cmd_start and auto-start
registration to reconstruct the launch command.
"""
_metadata.write(
INSTALL_METADATA_FILE, installed_path, mode, python=python, version=version
)
def clear_install_metadata() -> None:
_metadata.clear(INSTALL_METADATA_FILE)
def installed_exe_path() -> Optional[str]:
return _metadata.installed_exe_path(INSTALL_METADATA_FILE)
TASK_NAME = "CraftBot" # Windows Task Scheduler task name
SYSTEMD_SERVICE = "craftbot" # Linux systemd service name
LAUNCHD_LABEL = "com.craftbot.agent" # macOS launchd label
DEFAULT_FRONTEND_PORT = 7925
DEFAULT_BACKEND_PORT = 7926
BROWSER_URL = f"http://localhost:{DEFAULT_FRONTEND_PORT}"
CRAFTBOT_READY_MARKER = "CRAFTBOT IS READY"
SHORTCUT_NAME = "CraftBot.lnk"
# Bundled icons live in sys._MEIPASS in frozen mode (PyInstaller's runtime
# extract dir) and alongside craftbot.py in source mode. _ensure_ico() copies
# the bundled icon to the persistent user data dir during install so the
# desktop shortcut keeps a stable path after _MEIPASS is wiped.
_BUNDLE_DIR = getattr(sys, "_MEIPASS", BASE_DIR)
LOGO_PNG = os.path.join(_BUNDLE_DIR, "craftbot_logo_1.png")
LOGO_ICO = os.path.join(_BUNDLE_DIR, "craftbot_logo_1.ico")
# ─── Terminal colors (orange/white brand palette) ─────────────────────────────
def _enable_windows_vtp() -> None:
if sys.platform != "win32":
return
try:
import ctypes
k32 = ctypes.windll.kernel32
h = k32.GetStdHandle(-11)
m = ctypes.c_ulong()
k32.GetConsoleMode(h, ctypes.byref(m))
k32.SetConsoleMode(h, m.value | 0x0004)
except Exception:
pass
_enable_windows_vtp()
from app.console import configure_console # noqa: E402 -- after windowed stream initialization
configure_console()
_USE_COLOR = sys.stdout.isatty()
def _c(code: str) -> str:
return code if _USE_COLOR else ""
ORANGE = _c("\033[38;2;255;79;24m") # #FF4F18
WHITE = _c("\033[38;2;255;255;255m") # #FFFFFF
BOLD = _c("\033[1m")
DIM = _c("\033[38;2;80;80;80m") # dark gray
GREEN = _c("\033[38;2;80;220;100m")
RED = _c("\033[91m")
RESET = _c("\033[0m")
def _retro_step(num: int, total: int, desc: str) -> None:
"""Print a retro-style step header box."""
W = 62
visible = f" ▸ STEP {num}/{total} ░░ {desc.upper()}"
pad = max(0, W - len(visible))
content = (
f" {ORANGE}▸ STEP {num}/{total}{RESET}"
f" {DIM}░░{RESET}"
f" {WHITE}{desc.upper()}{RESET}" + " " * pad
)
print(f"\n{ORANGE}╔{'═' * W}╗{RESET}")
print(f"{ORANGE}║{RESET}{content}{ORANGE}║{RESET}")
print(f"{ORANGE}╚{'═' * W}╝{RESET}")
# ─── Helpers ──────────────────────────────────────────────────────────────────
def _to_short_path(path: str) -> str:
"""Return the Windows 8.3 short path form to avoid Unicode / long-path
issues when embedding paths inside command strings (e.g. schtasks /tr)."""
if _PLATFORM != "win32":
return path
try:
import ctypes
buf = ctypes.create_unicode_buffer(1024)
if ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf)):
return buf.value
except Exception:
pass
return path
def _warn_path_issues() -> None:
"""Print warnings if BASE_DIR is too long or contains non-ASCII characters."""
if len(BASE_DIR) > 200:
print(f"WARNING: Installation path is very long ({len(BASE_DIR)} chars).")
print(" Windows MAX_PATH limit may cause failures.")
print(" Consider moving CraftBot to a shorter path.\n")
try:
BASE_DIR.encode("ascii")
except UnicodeEncodeError:
print(
"WARNING: Installation path contains non-ASCII characters (e.g. Japanese)."
)
print(
" Some commands may fail. Short paths will be used where possible.\n"
)
def _installed_python() -> str:
"""The single CraftBot interpreter (app/python_runtime.py), else this
process's own. main() re-execs onto it first thing, so normally the two
are the same; the fallback covers the frozen installer EXE."""
if _python_runtime is not None:
return _python_runtime.resolve() or sys.executable
return sys.executable
def _python_exe() -> str:
"""Return the Python executable to use for the service process."""
python = _installed_python()
# On Windows prefer pythonw.exe (no console window): the service never
# talks to a console (the terminal edition's client is `craftbot.py tui`)
if _PLATFORM == "win32":
pythonw = os.path.join(os.path.dirname(python), "pythonw.exe")
if os.path.isfile(pythonw):
return pythonw
return python
# A pid alone is not an identity: once CraftBot exits (crash, reboot) the OS
# reuses the number, and `stop` would kill whatever holds it now — with /T,
# its whole tree. The PID file therefore also records the process's start
# time, and a pid is only treated as CraftBot when both still match.
_START_TIME_TOLERANCE_S = 2.0 # macOS `ps lstart` has 1s resolution
def _read_pid_record() -> Optional[tuple]:
"""(pid, recorded start time or None, file mtime), or None if no file.
Accepts the legacy bare-integer format (no start time)."""
try:
with open(PID_FILE) as f:
raw = f.read().strip()
mtime = os.path.getmtime(PID_FILE)
except OSError:
return None
try:
if raw.startswith("{"):
import json
data = json.loads(raw)
started = data.get("started")
return int(data["pid"]), (float(started) if started else None), mtime
return int(raw), None, mtime
except (ValueError, KeyError, TypeError):
return None
def _owned_pid() -> Optional[int]:
"""The pid in the PID file IF that process is still the CraftBot we
started; otherwise None. A stale record (process gone, or pid reused by
another program) is removed so nothing ever acts on it."""
record = _read_pid_record()
if record is None:
return None
pid, started, mtime = record
actual = _helpers.process_start_time(pid)
if actual is None:
_remove_pid()
return None
if started is not None:
ours = abs(actual - started) <= _START_TIME_TOLERANCE_S
else:
# Legacy file (or start time unreadable at spawn): the file was
# written right after the spawn, so our process started before it.
# A reused pid belongs to a process started after ours died — i.e.
# after the file was written.
ours = actual <= mtime + _START_TIME_TOLERANCE_S
if not ours:
_remove_pid()
return None
return pid
def _write_pid(pid: int) -> None:
import json
with open(PID_FILE, "w") as f:
json.dump({"pid": pid, "started": _helpers.process_start_time(pid)}, f)
def _remove_pid() -> None:
try:
os.remove(PID_FILE)
except FileNotFoundError:
pass
def _claim_service_process() -> bool:
"""Publish a login service's PID without replacing an already running app."""
if _owned_pid():
print("CraftBot is already running; skipping automatic startup.")
return False
_write_pid(os.getpid())
return True
def _release_service_process(pid: int) -> None:
# A manual restart may already have replaced our PID record.
if _owned_pid() == pid:
_remove_pid()
def _parse_port_arg(args: List[str], flag: str, default: int) -> int:
prefix = f"{flag}="
for i, arg in enumerate(args):
value = None
if arg == flag and i + 1 < len(args):
value = args[i + 1]
elif arg.startswith(prefix):
value = arg[len(prefix) :]
if value is not None:
try:
return int(value)
except ValueError:
return default
return default
def _frontend_url(args: List[str]) -> str:
port = _parse_port_arg(args, "--frontend-port", DEFAULT_FRONTEND_PORT)
return f"http://localhost:{port}"
def _backend_url(args: List[str]) -> str:
port = _parse_port_arg(args, "--backend-port", DEFAULT_BACKEND_PORT)
return f"http://localhost:{port}"
def _port_args(args: List[str]) -> List[str]:
result = []
skip_next = False
for i, arg in enumerate(args):
if skip_next:
skip_next = False
continue
if arg in ("--frontend-port", "--backend-port", "--agent-app-port"):
if i + 1 < len(args):
result.extend([arg, args[i + 1]])
skip_next = True
continue
if arg.startswith(("--frontend-port=", "--backend-port=", "--agent-app-port=")):
result.append(arg)
return result
def _tail_log_lines(n: int = 30, start_offset: int = 0) -> str:
if not os.path.isfile(LOG_FILE):
return ""
try:
with open(LOG_FILE, "r", encoding="utf-8", errors="replace") as f:
if start_offset:
f.seek(start_offset)
lines = f.readlines()
except Exception:
return ""
return "".join(lines[-n:])
#: How long cmd_start waits for the agent to finish booting. Minutes, not
#: seconds: a first run downloads the embedding model, and on a slow
#: connection that dominates startup. Running out is not a failure while the
#: process is alive; start then says it is still starting.
BROWSER_READY_TIMEOUT_S = 600
#: How often cmd_start prints a progress line while it waits.
_PROGRESS_EVERY_S = 30
#: Log lines shown when a start fails.
_FAILURE_LOG_LINES = 40
def _clear_agent_ready() -> None:
"""Drop any previous run's readiness marker and ui.json before we launch."""
try:
paths.AGENT_READY_FILE.unlink(missing_ok=True)
except Exception:
pass
_instance.remove_ui()
def _ui_ready(start_offset: int = 0) -> bool:
"""Has this launch reached the point where the UI answers?
run.py writes ui.json once the backend answers, after the agent's own
ready marker. The ready banner in the log is kept only for an older
installed run.py that predates ui.json. (The log used to be the ONLY
signal, and run.py's stdout is a log FILE here, so the banner could sit
unflushed in a buffer long after the agent was serving.)
"""
if _instance.read_ui() is not None:
return True
return CRAFTBOT_READY_MARKER in _tail_log_lines(200, start_offset)
def _wait_until_ready(proc, start_offset: int, timeout: float) -> str:
"""Wait for the CraftBot just launched: "ready", "exited" or "timeout".
Watches the process the whole time. This used to look for an early exit
for 8 seconds only, and then wait up to 10 minutes for readiness without
noticing that the process had died, so a crash at second 9 was reported
as a running CraftBot.
"""
started = time.time()
next_note = started + _PROGRESS_EVERY_S
while True:
if proc.poll() is not None:
return "exited"
if _ui_ready(start_offset):
return "ready"
now = time.time()
if now - started >= timeout:
return "timeout"
if now >= next_note:
print(
f" {DIM}Still starting ({int(now - started)}s)...{RESET}", flush=True
)
next_note += _PROGRESS_EVERY_S
time.sleep(0.5)
def _current_url(args: Optional[List[str]] = None) -> str:
"""Where the UI is. An explicit --frontend-port names it (run.py uses or
refuses the ports it is given); otherwise ui.json of the running
CraftBot does, as its ports move when another program holds 7925/7926;
else the default address."""
args = args or []
if not _parse_port_arg(args, "--frontend-port", 0):
ui = _instance.read_ui()
if ui:
return str(ui["url"])
return _frontend_url(args)
#: How long cmd_start probes the browser UI after run.py reports readiness.
#: The UI should already answer; this absorbs a slow first response.
FRONTEND_READY_TIMEOUT_S = 30
#: Present in the UI's index.html (dev and built). A 200 without it is not
#: the UI — e.g. the directory listing of a dist/ that has no index.html.
_FRONTEND_ROOT_MARKER = b'id="root"'
def _frontend_serving(url: str) -> bool:
"""True only when `url` answers with the CraftBot UI itself.
The agent readiness marker says nothing about the frontend, and a server
that answers is not necessarily one that can serve the page: a 404 is
exactly what the user saw when the URL was shown too early. The opener
raises on every 4xx/5xx, so any HTTP error counts as not ready.
"""
try:
with _instance.loopback_opener().open(url, timeout=2) as resp:
return 200 <= resp.status < 300 and _FRONTEND_ROOT_MARKER in resp.read(
65536
)
except Exception:
return False
def _wait_for_frontend(url: str, timeout: float) -> bool:
"""Poll `url` until it serves the UI. Returns False on timeout."""
deadline = time.time() + timeout
while True:
if _frontend_serving(url):
return True
if time.time() >= deadline:
return False
time.sleep(0.5)
def _is_running(pid: int) -> bool:
"""Return True if a process with the given PID is currently alive."""
return _helpers.process_start_time(pid) is not None
def _orphan_listeners(args: Optional[List[str]] = None) -> List[tuple]:
"""(pid, description) for CraftBots of THIS installation on our ports
that no PID file covers.
Only this state root's own CraftBot counts (app.instance
.belongs_to_this_home). A CraftBot from another checkout or another
CRAFTBOT_HOME on the same port is a separate installation that is
working for someone: it is never reported as an orphan of this one, and
so never stopped by this one.
Read-only — `status` reports them, `stop` acts on them.
"""
try:
from app.process_ledger import craftbot_listeners
except Exception:
return [] # psutil missing (pre-dependency install) — nothing to say
ports = {
_parse_port_arg(args or [], "--frontend-port", DEFAULT_FRONTEND_PORT),
_parse_port_arg(args or [], "--backend-port", DEFAULT_BACKEND_PORT),
}
# The ports the last run actually used, when it had to move.
ui = _instance.read_ui() or {}
for key in ("frontend_port", "backend_port"):
if isinstance(ui.get(key), int):
ports.add(ui[key])
found: List[tuple] = []
for port in sorted(ports):
for pid, description in craftbot_listeners(port):
if pid in {p for p, _ in found}:
continue
if _instance.belongs_to_this_home(pid):
found.append((pid, description))
return found
def _stop_orphan_listeners(args: Optional[List[str]] = None) -> int:
"""Stop CraftBots on our ports that no PID file accounts for.
The PID file is the normal way to find the running agent, and it is not
enough on its own. It lives in STATE_ROOT, so an uninstall deletes it
while the process it described keeps running — after which `stop` says
"not running", `uninstall` leaves it alive, and the next install finds
:7925 taken by something no CraftBot command can reach. The launcher log
shows the other half of it: "could not remove runtime: Access is denied",
because the orphan still has the DLLs open.
Identity still has to be proved (app.process_ledger.identify_craftbot) —
this finds candidates by port but only ever kills a process that
describes itself as CraftBot.
"""
orphans = _orphan_listeners(args)
if not orphans:
return 0
from app.process_ledger import kill_tree
stopped = 0
failures = []
for pid, description in orphans:
print(
f" {ORANGE}▸{RESET} {WHITE}STOPPING ORPHANED CRAFTBOT{RESET}"
f" {DIM}{description}{RESET}"
)
try:
kill_tree(pid)
stopped += 1
except Exception as e:
print(f" {DIM}(could not stop pid {pid}: {e}){RESET}")
failures.append(str(pid))
if failures:
raise RuntimeError(
"Could not stop orphaned CraftBot pids: " + ", ".join(failures)
)
return stopped
def _stop_running_agent_if_alive(
grace_s: float = 1.0, args: Optional[List[str]] = None
) -> bool:
"""If an agent is currently running, stop it and pause briefly so the OS
releases file handles before we try to overwrite the agent EXE. Used by
install/repair so reinstall over a running agent doesn't fail with
"Permission denied" on Windows. Returns True if a process was stopped.
"""
if cmd_stop(quiet=True, args=args):
time.sleep(grace_s)
return True
return False
def _build_run_args(extra: List[str], service_mode: bool = True) -> List[str]:
"""Build the argument list for run.py.
Adds --no-open-browser by default in service mode (auto-start at boot
should not pop open a browser without the user asking). The terminal
edition's service serves the backend only: a background process has no
console for the terminal client, which `craftbot.py tui` attaches.
"""
args = list(extra)
if "--tui" in args:
if "--backend-only" not in args:
args.append("--backend-only")
elif service_mode and "--no-open-browser" not in args:
args.append("--no-open-browser")
return args
# ─── Core operations ──────────────────────────────────────────────────────────
def _open_browser_detached(url: str) -> None:
"""Open the UI in the user's browser.
cmd_start only calls this once run.py has reported the UI as reachable
(ui.json), so there is nothing left to poll for.
"""
try:
webbrowser.open(url)
except Exception as e:
print(f" {DIM}Could not open a browser ({e}). Open {url} yourself.{RESET}")
_CLI_RETIRED = (
"The CLI was replaced by the terminal edition.\n"
" Run it in this terminal: python run.py --tui\n"
" Or as a service: python craftbot.py start --tui, then python craftbot.py tui"
)
def _child_env() -> dict:
"""Environment for a CraftBot Python child (run.py, install.py, checks):
nothing from the user's shell that would make CraftBot's interpreter load
foreign packages (app.python_runtime.isolated_env), no proxy for
loopback, and UTF-8 output."""
if _python_runtime is not None and hasattr(_python_runtime, "isolated_env"):
env = _python_runtime.isolated_env(os.environ)
else:
env = os.environ.copy()
_instance.with_no_proxy(env)
env["PYTHONIOENCODING"] = "utf-8"
env["PYTHONUTF8"] = "1"
return env
def cmd_start(extra_args: List[str]) -> bool:
"""Start CraftBot as a detached background process.
Returns True once the UI answers, or while the process is alive but still
starting when the wait runs out. False when it exits first: then the last
log lines and the log path are printed.
"""
if "--cli" in extra_args:
print(f" {RED}✗{RESET} {WHITE}{_CLI_RETIRED}{RESET}")
return False
# Unconditional, not `if _owned_pid()`: the thing most likely to be
# holding our port is the CraftBot this install has no PID file for.
cmd_stop(quiet=True, args=extra_args)
run_args = _build_run_args(extra_args, service_mode=False)
terminal_edition = "--tui" in run_args
# Always pass --no-open-browser to run.py; craftbot.py handles opening the browser
if not terminal_edition and "--no-open-browser" not in run_args:
run_args.append("--no-open-browser")
if IS_FROZEN:
# Launching an install is metadata.launch_command()'s job — it is the
# only place that knows the difference between a schema-2 install
# ([python, run.py]) and a legacy schema-1 frozen bundle ([agent.exe]).
# Spreading that knowledge is how the entry points drifted before.
launch = _metadata.launch_command(INSTALL_METADATA_FILE)
if not launch:
print("Error: no usable install found. Run install first.")
return False
cmd = launch + run_args
else:
cmd = [_python_exe(), RUN_SCRIPT] + run_args
# Clear the readiness marker and ui.json BEFORE launching, so what the
# previous run left cannot make this one look instantly ready.
_clear_agent_ready()
# UTF-8 with replace so the agent's Unicode banner / box-drawing chars
# don't crash on Windows where the default file encoding is cp1252.
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
log_fh = open(LOG_FILE, "a", encoding="utf-8", errors="replace")
log_fh.write(f"\n{'=' * 60}\n")
log_fh.write(f"CraftBot service started at {_timestamp()}\n")
log_fh.write(f"Command: {' '.join(cmd)}\n")
log_fh.write(f"{'=' * 60}\n")
log_fh.flush()
ready_log_offset = log_fh.tell()
kwargs = dict(
cwd=BASE_DIR,
stdout=log_fh,
stderr=subprocess.STDOUT,
stdin=subprocess.DEVNULL,
env=_child_env(),
**_helpers.detached_popen_flags(new_process_group=True),
)
try:
proc = subprocess.Popen(cmd, **kwargs)
except (FileNotFoundError, OSError) as e:
log_fh.close()
print(f" {RED}✗{RESET} {WHITE}Could not launch CraftBot: {e}{RESET}")
return False
# Parent closes its copy — the child process (run.py) keeps the fd open
log_fh.close()
print(
f" {DIM}Starting CraftBot. This can take a few minutes on the first start.{RESET}"
)
state = _wait_until_ready(proc, ready_log_offset, BROWSER_READY_TIMEOUT_S)
if state == "exited":
# run.py removes its pid file on a clean exit; a crash may leave one.
if _owned_pid() is None:
_remove_pid()
print(
f" {RED}✗{RESET} {WHITE}CraftBot failed to start{RESET}"
f" {DIM}exit {proc.returncode}{RESET}"
)
log_tail = _tail_log_lines(_FAILURE_LOG_LINES)
if log_tail:
print(f"\n{DIM}Last log lines:{RESET}\n{log_tail}", end="")
if not log_tail.endswith("\n"):
print()
print(f"\nFull log: {LOG_FILE}")
return False
# run.py writes its own pid (after any interpreter hop) as it starts; an
# older run.py does not, so record the process we launched instead.
pid = _owned_pid()
if pid is None:
_write_pid(proc.pid)
pid = proc.pid
browser_url = _current_url(extra_args)
if state == "timeout":
print(
f" {GREEN}▸{RESET} {WHITE}CRAFTBOT IS STILL STARTING{RESET} {DIM}PID {pid}{RESET}"
)
where = (
"with: python craftbot.py tui" if terminal_edition else f"at {browser_url}"
)
print(
f" {DIM}It will be available {where} when it finishes. "
f"Follow its progress with: python craftbot.py logs{RESET}"
)
return True
print(f" {GREEN}▸{RESET} {WHITE}CRAFTBOT STARTED{RESET} {DIM}PID {pid}{RESET}")
if terminal_edition:
# No web UI and no desktop icon: the client is `craftbot.py tui`.
print(f" {DIM}░░{RESET} {WHITE}Open it with: python craftbot.py tui{RESET}")
return True
print(f" {DIM}░░ Waiting for the browser interface...{RESET}", flush=True)
if not _wait_for_frontend(browser_url, FRONTEND_READY_TIMEOUT_S):
print(
f" {RED}✗{RESET} {WHITE}The browser interface is not responding"
f" at {browser_url}{RESET}"
)
print(f" {DIM}Check progress: {sys.executable} craftbot.py logs{RESET}")
return True
print(f" {DIM}░░{RESET} {ORANGE}{browser_url}{RESET}")
# Create a desktop shortcut so the user can reopen the browser anytime
if _PLATFORM == "win32":
_create_desktop_shortcut_windows(extra_args)
else:
_create_desktop_shortcut_unix(extra_args)
if "--no-open-browser" not in extra_args:
_open_browser_detached(browser_url)
return True
def cmd_tui(extra_args: List[str]) -> int:
"""Open the terminal edition in this console.
Attaches to the CraftBot this state root is running, whichever edition its
backend serves, on the port its ui.json names. When none runs, starts the
terminal edition in the background first. Quitting the client leaves the
service running, so scheduled and proactive work goes on; `craftbot.py
stop` stops it.
"""
from app import edition, node_runtime
ui = _instance.read_ui()
if ui is None or not _instance.http_answers(str(ui["url"])):
if _owned_pid() is not None and _wait_for_running(
_owned_pid(), extra_args, lambda text: None
):
ui = _instance.read_ui()
else:
start_args = list(extra_args)
if "--tui" not in start_args:
start_args.append("--tui")
if not cmd_start(start_args):
return 1
ui = _instance.read_ui()
port = (
int(ui["backend_port"])
if ui and isinstance(ui.get("backend_port"), int)
else _parse_port_arg(extra_args, "--backend-port", DEFAULT_BACKEND_PORT)
)
bundle = edition.terminal_client_bundle()
node = node_runtime.node_cmd()
if not node:
print(f" {RED}✗{RESET} {WHITE}Node.js 24 or later is required{RESET}")
print(f" {DIM}Run `python craftbot.py install` to set it up.{RESET}")
return 1
if not bundle.is_file():
print(f" {RED}✗{RESET} {WHITE}The terminal client is not built{RESET}")
print(f" {DIM}Restart it: python craftbot.py restart --tui{RESET}")
return 1
try:
return subprocess.run(
[
node,
str(bundle),
"--port",
str(port),
"--state-dir",
str(paths.STATE_ROOT),
"--log",
LOG_FILE,
],
env=node_runtime.child_env(),
).returncode
except KeyboardInterrupt:
return 130
def _running_ui_url(args: List[str]) -> Optional[str]:
"""The address of THIS install's CraftBot when it answers, else None.
ui.json is written by this state root's run.py once its UI answers, so it
names our CraftBot even when its ports moved. Without one (an older
run.py), a listener that app.instance proves to be ours counts too. A
program on 7925 that is not this CraftBot never does.
"""
ui = _instance.read_ui()
if ui and _instance.http_answers(str(ui["url"])):
return str(ui["url"])
if _orphan_listeners(args):
url = _current_url(args)
if _instance.http_answers(url):
return url
return None
def _wait_for_running(pid: int, args: List[str], status) -> Optional[str]:
"""Wait for a CraftBot that is already starting (a login start, or a
second click on the icon) instead of starting another one. Its address
once it answers; None when it exits or never answers."""
started = time.time()
while time.time() - started < BROWSER_READY_TIMEOUT_S:
url = _running_ui_url(args)
if url:
return url
if not _is_running(pid):
return None
status("CraftBot is starting. Your browser opens when it is ready.")
time.sleep(1)
return None
def _start_lock() -> str:
return str(paths.STATE_ROOT / ".opening.lock")
def _claim_start() -> Optional[int]:
"""Become the one icon click that starts CraftBot.
None when this process holds the lock now; otherwise the pid of the
click that is already starting CraftBot. People double-click an icon
twice: without this both clicks started CraftBot, and the second start's
cleanup stopped the first one. A lock whose holder is gone is taken over.
"""
for _ in range(2):
try:
fd = os.open(_start_lock(), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
try:
with open(_start_lock(), encoding="utf-8") as f:
holder = int(f.read().strip() or 0)
except (OSError, ValueError):
holder = 0
if holder and holder != os.getpid() and _is_running(holder):
return holder
try:
os.remove(_start_lock())
except OSError:
pass
continue
except OSError:
return None # an unwritable state root must not block the start
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(str(os.getpid()))