-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaemoniq-imp.py
More file actions
2191 lines (1863 loc) · 91 KB
/
daemoniq-imp.py
File metadata and controls
2191 lines (1863 loc) · 91 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
"""
DaemonIQ — Linux Troubleshooting Assistant (Local / Ollama edition)
Single-file edition: demon + CLI + distro detection all in one.
Uses a locally-running Ollama model — no API key or internet required.
Usage:
daemoniq Interactive REPL (auto-starts daemon)
daemoniq "apt gives lock error" One-shot question
daemoniq --exec "fix broken pkg" Ask and auto-apply fix
daemoniq start | stop | restart | status | logs | distro | history
Requires: Python 3.8+, Ollama running locally (https://ollama.com).
No API key or external packages needed.
"""
# ══════════════════════════════════════════════════════════════════════════════
# BRANDING — change these when the product is renamed, nothing else needs to
# ══════════════════════════════════════════════════════════════════════════════
PRODUCT_NAME = "DaemonIQ"
PRODUCT_TAGLINE = "Linux Troubleshooting Assistant"
PRODUCT_VERSION = "0.4.4"
CLI_COMMAND = "daemoniq"
DAEMON_LABEL = "daemoniq-demon"
AI_PERSONA = PRODUCT_NAME
BANNER_LINES = [
r" ██████╗ █████╗ ███████╗███╗ ███╗ ██████╗ ███╗ ██╗██████╗ ██████╗ ",
r" ██╔══██╗██╔══██╗██╔════╝████╗ ████║██╔═══██╗████╗ ██║╚═██╔═╝██╔═══██╗ ",
r" ██║ ██║███████║█████╗ ██╔████╔██║██║ ██║██╔██╗ ██║ ██║ ██║ ██║ ",
r" ██║ ██║██╔══██║██╔══╝ ██║╚██╔╝██║██║ ██║██║╚██╗██║ ██║ ██║▄▄ ██║ ",
r" ██████╔╝██║ ██║███████╗██║ ╚═╝ ██║╚██████╔╝██║ ╚████║██████╗╚██████╔╝ ",
r" ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚══▀▀═╝ ",
]
# ── Runtime paths (all derived from DAEMON_LABEL) ────────────────────────────
import os as _os
SOCKET_PATH = f"/tmp/{DAEMON_LABEL}.sock"
PID_FILE = f"/tmp/{DAEMON_LABEL}.pid"
LOG_FILE = f"/tmp/{DAEMON_LABEL}.log"
HISTORY_FILE = _os.path.expanduser(f"~/.{DAEMON_LABEL}_history")
INSTALL_DIR = _os.path.expanduser(f"~/.{DAEMON_LABEL}")
# ══════════════════════════════════════════════════════════════════════════════
# STDLIB IMPORTS
# ══════════════════════════════════════════════════════════════════════════════
import os
import sys
import json
import socket
import signal
import logging
import threading
import subprocess
import shutil
import time
import re
import argparse
from dataclasses import dataclass
from pathlib import Path
# ══════════════════════════════════════════════════════════════════════════════
# DISTRO DETECTION
# Extend _FAMILIES at the bottom of this section to add new distro support.
# ══════════════════════════════════════════════════════════════════════════════
@dataclass
class DistroInfo:
family: str
distro_id: str
distro_name: str
version_id: str
codename: str
pkg_managers: list
supported: bool
support_note: str
@dataclass
class ExecBlock:
commands: list
description: str
requires_sudo: bool = False
pkg_manager: str = ""
class DistroFamily:
name = "unknown"
FAMILY_IDS: set = set()
def detect(self, ids: set) -> bool:
return bool(ids & self.FAMILY_IDS)
def get_info(self, raw: dict) -> DistroInfo:
raise NotImplementedError
def build_system_prompt_section(self, info: DistroInfo) -> str:
raise NotImplementedError
def sanitize_exec_block(self, block: ExecBlock, info: DistroInfo) -> ExecBlock:
return block
# ── Debian/Ubuntu/Mint/Pop!_OS/Kali/etc. ─────────────────────────────────────
_DEBIAN_IDS = {
"debian",
"ubuntu", "ubuntu-server", "kubuntu", "xubuntu", "lubuntu",
"ubuntu-mate", "ubuntu-budgie", "ubuntu-studio",
"pop", "elementary", "zorin", "neon",
"linuxmint", "mint", "lmde",
"kali", "kali-linux", "parrot", "parrotos",
"raspbian", "raspios",
"deepin", "mx", "antix", "devuan", "pureos",
"tails", "whonix", "armbian", "proxmox",
}
_DEBIAN_ERROR_PATTERNS = [
("dpkg was interrupted", "interrupted dpkg — database is in a broken state"),
("lock.*frontend", "apt/dpkg lock held by another process"),
("lock.*dpkg", "dpkg lock held by another process"),
("Unable to acquire.*lock", "package manager lock conflict"),
("E: Could not get lock", "package manager lock conflict"),
("Sub-process.*dpkg.*returned", "dpkg post-install script failure"),
("held broken packages", "dependency conflict — held broken packages"),
("unmet dependencies", "unresolved dependency tree"),
("404.*Not Found", "repository URL is stale or unreachable"),
("NO_PUBKEY", "missing GPG signing key for a repository"),
("GPG error", "repository GPG verification failure"),
("Hash Sum mismatch", "corrupted or out-of-date package cache"),
("no installation candidate", "package name not found in any enabled repo"),
("dpkg: error processing", "package installation/removal script error"),
("pip.*externally-managed", "pip blocked by PEP 668 (use venv or --break-system-packages)"),
("ModuleNotFoundError", "Python module missing — may need pip install"),
("EXTERNALLY-MANAGED", "pip blocked by PEP 668 (use venv or pipx)"),
("snap.*error", "snap package manager error"),
("Permission denied", "insufficient file permissions or missing sudo"),
("command not found", "binary not installed or not in PATH"),
("Segmentation fault", "program crashed (segfault) — possible corrupt binary or library"),
("error while loading shared", "missing or incompatible shared library (.so)"),
("SIGABRT", "program aborted — likely an assertion failure or libc error"),
]
class DebianFamily(DistroFamily):
name = "debian"
FAMILY_IDS = _DEBIAN_IDS
_PM_CHECKS = [
("apt", "/usr/bin/apt"),
("apt-get", "/usr/bin/apt-get"),
("dpkg", "/usr/bin/dpkg"),
("snap", "/usr/bin/snap"),
("flatpak", "/usr/bin/flatpak"),
("pip", None),
("pip3", None),
("pipx", None),
("npm", None),
("cargo", None),
]
def detect(self, ids: set) -> bool:
return bool(ids & self.FAMILY_IDS) or \
Path("/usr/bin/dpkg").exists() or \
Path("/var/lib/dpkg").exists()
def get_info(self, raw: dict) -> DistroInfo:
pkg_managers = []
for name, path in self._PM_CHECKS:
if (path and Path(path).exists()) or (not path and shutil.which(name)):
pkg_managers.append(name)
return DistroInfo(
family = "debian",
distro_id = raw.get("ID", "debian").lower(),
distro_name = raw.get("PRETTY_NAME", raw.get("NAME", "Debian-based Linux")),
version_id = raw.get("VERSION_ID", "").strip('"'),
codename = (raw.get("VERSION_CODENAME") or raw.get("UBUNTU_CODENAME") or
raw.get("DEBIAN_CODENAME") or "").lower(),
pkg_managers = pkg_managers,
supported = True,
support_note = "",
)
def build_system_prompt_section(self, info: DistroInfo) -> str:
pm_list = ", ".join(info.pkg_managers) or "apt, dpkg"
err_lines = "\n".join(f" - `{p}` → {c}" for p, c in _DEBIAN_ERROR_PATTERNS)
return f"""## System Context
- Distro: {info.distro_name}
- Family: Debian / APT-based
- Codename: {info.codename or "unknown"}
- Package managers: {pm_list}
## Debian/Ubuntu expertise
### APT & DPKG
- `apt` vs `apt-get` vs `aptitude` — when to use each
- `dpkg -i`, `dpkg --configure -a`, `dpkg --audit`
- Sources list: `/etc/apt/sources.list` and `/etc/apt/sources.list.d/`
- PPAs: `add-apt-repository`, signing keys, `signed-by` (apt-key deprecated)
- APT pinning: `/etc/apt/preferences.d/`
- Cache: `apt clean`, `apt autoclean`, `apt autoremove`
- Held packages: `apt-mark hold/unhold`, `dpkg --get-selections`
- Lock files: `/var/lib/dpkg/lock-frontend`, `/var/cache/apt/archives/lock`
### Known error patterns
{err_lines}
### Python packaging
- PEP 668 / EXTERNALLY-MANAGED → use `python3 -m venv`, `pipx`, or `--break-system-packages`
- Prefer `python3-<pkg>` apt packages for system tools; pip inside venvs for dev
### Snap & Flatpak
- Snap: `snap install/remove/refresh/list/logs`
- Flatpak: `flatpak install/uninstall/update`, `flatpak remote-list`
### Shared libraries
- `ldd`, `ldconfig -p | grep <lib>`, `apt-file search <missing.so>`
### Driver management on Debian/Ubuntu
You have deep knowledge of the full Linux driver stack:
#### Kernel modules
- `lsmod` — list loaded modules, `modinfo <module>` — module details
- `modprobe <module>` — load a module, `modprobe -r <module>` — unload
- `modprobe -v <module>` — verbose load (shows dependencies)
- `/etc/modprobe.d/` — persistent module config, blacklisting
- `dmesg | grep -i <device>` — find device errors in kernel log
- `journalctl -k` — kernel log via systemd
#### DKMS (Dynamic Kernel Module Support)
- `dkms status` — list all DKMS modules and their build status
- `dkms install <module>/<version>` — build and install a module
- `dkms remove <module>/<version> --all` — remove a DKMS module
- `apt install linux-headers-$(uname -r)` — install matching kernel headers (required for DKMS)
- Common DKMS packages: `nvidia-dkms-*`, `virtualbox-dkms`, `zfs-dkms`, `broadcom-sta-dkms`
#### GPU drivers
- NVIDIA: `ubuntu-drivers list`, `ubuntu-drivers autoinstall`, `apt install nvidia-driver-<ver>`
- Check: `nvidia-smi`, `lspci | grep -i nvidia`
- Issues: check `/var/log/Xorg.0.log`, `dmesg | grep nvidia`
- Secure Boot conflict: needs MOK enrollment via `mokutil`
- AMD: drivers are in-kernel (amdgpu), firmware in `firmware-amd-graphics` / `amdgpu-dkms`
- Check: `lspci | grep -i amd`, `dmesg | grep amdgpu`
- Intel: in-kernel (i915), firmware in `intel-microcode`, `firmware-misc-nonfree`
- Check: `lspci | grep -i intel`, `dmesg | grep i915`
#### Wi-Fi and network drivers
- `lspci -nnk | grep -A3 -i network` — identify NIC and current driver
- `lsusb` — find USB network adapters
- Common problematic chipsets and their packages:
- Broadcom: `broadcom-sta-dkms` or `firmware-brcm80211`
- Realtek: `firmware-realtek` or `r8168-dkms`
- Intel Wi-Fi: `firmware-iwlwifi`
- Atheros: `firmware-atheros`
- `rfkill list` — check if Wi-Fi is software/hardware blocked
- `rfkill unblock wifi` — unblock software-blocked Wi-Fi
- `iw dev`, `iwconfig` — Wi-Fi interface status
#### Audio drivers
- ALSA: `aplay -l` (list devices), `alsamixer` (levels), `alsactl restore`
- PulseAudio: `pactl info`, `pulseaudio --kill && pulseaudio --start`
- PipeWire: `pw-cli info`, `systemctl --user status pipewire`
- Firmware: `firmware-sof-signed` for Intel Sound Open Firmware
- Check: `dmesg | grep -i snd`, `lspci | grep -i audio`
#### Printer drivers
- CUPS: `lpstat -a`, `lpstat -p -d`, `cupsctl`
- `apt install cups printer-driver-*`
- GUI: `system-config-printer`
#### Firmware (non-module drivers)
- `apt install firmware-linux-nonfree firmware-linux-free` — broad firmware package
- `fwupdmgr get-updates && fwupdmgr update` — firmware updates via LVFS
- `dmesg | grep -i firmware` — find firmware load failures
#### Secure Boot and driver signing
- `mokutil --sb-state` — check if Secure Boot is enabled
- `mokutil --list-enrolled` — list enrolled signing keys
- Third-party drivers (NVIDIA, VirtualBox) need MOK key enrollment when Secure Boot is on
- `update-secureboot-policy --enroll-key` (Ubuntu) — automated MOK enrollment
#### Safe execution rules for driver commands
When emitting DAEMONIQ_EXEC blocks for driver operations:
- Always install `linux-headers-$(uname -r)` before DKMS operations
- Use `--no-install-recommends` sparingly — driver packages often need recommends
- Never unload a module for the active GPU or network interface without warning
- Prefer `ubuntu-drivers autoinstall` over manual driver selection on Ubuntu
- After kernel module changes, always suggest a reboot
### UX recommendations (when asked)
Suggest: nala, unattended-upgrades, needrestart, debsums, btop, ncdu, tldr,
`alias update='sudo apt update && sudo apt upgrade'`
"""
def sanitize_exec_block(self, block: ExecBlock, info: DistroInfo) -> ExecBlock:
BLOCKED = ["rm -rf /", "rm -rf /*", "mkfs", "dd if=", "> /dev/sda", "shred /dev"]
safe = []
for cmd in block.commands:
s = cmd.strip()
for danger in BLOCKED:
if danger in s:
raise ValueError(
f"Blocked dangerous command: `{s}`\n"
f"{PRODUCT_NAME} will not execute commands that could destroy system data."
)
# Inject DEBIAN_FRONTEND=noninteractive for apt commands
if ("apt-get" in s or s.lstrip("sudo ").startswith("apt ")) and \
"DEBIAN_FRONTEND" not in s and \
any(k in s for k in ("install", "upgrade", "dist-upgrade", "remove", "purge")):
s = f"DEBIAN_FRONTEND=noninteractive {s}"
# Inject -y for unattended apt runs
if any(k in s for k in ("install", "upgrade", "remove", "purge")) and \
("apt" in s) and " -y" not in s and "--yes" not in s:
s += " -y"
safe.append(s)
return ExecBlock(
commands = safe,
description = block.description,
requires_sudo = block.requires_sudo,
pkg_manager = block.pkg_manager or ("apt" if "apt" in info.pkg_managers else ""),
)
# ── Future family stubs ───────────────────────────────────────────────────────
# To add a new distro: copy one of these stubs, populate FAMILY_IDS and the
# three methods, then add an instance to _FAMILIES below.
def _coming_soon_info(raw, family_id, name, pm_names, note):
return DistroInfo(
family=family_id, distro_id=raw.get("ID", family_id).lower(),
distro_name=raw.get("PRETTY_NAME", name), version_id=raw.get("VERSION_ID", ""),
codename="", pkg_managers=[p for p in pm_names if shutil.which(p)],
supported=False, support_note=note,
)
def _coming_soon_exec(block, info):
raise ValueError(f"Automatic fix execution is not yet supported on {info.distro_name}.")
class RedHatFamily(DistroFamily):
name = "redhat"
FAMILY_IDS = {"rhel", "centos", "fedora", "rocky", "almalinux", "ol", "scientific", "amzn"}
def get_info(self, raw):
return _coming_soon_info(raw, "redhat", "RHEL-based Linux", ["dnf","yum","rpm"],
"RHEL/Fedora/CentOS support is coming soon. General Linux help is still available.")
def build_system_prompt_section(self, info):
return f"## System Context\n- Distro: {info.distro_name}\n- Family: RHEL/RPM (coming soon)\n"
def sanitize_exec_block(self, block, info): _coming_soon_exec(block, info)
class ArchFamily(DistroFamily):
name = "arch"
FAMILY_IDS = {"arch", "manjaro", "endeavouros", "artix", "garuda", "cachyos"}
def get_info(self, raw):
return _coming_soon_info(raw, "arch", "Arch-based Linux", ["pacman","yay","paru"],
"Arch Linux support is coming soon. General Linux help is still available.")
def build_system_prompt_section(self, info):
return f"## System Context\n- Distro: {info.distro_name}\n- Family: Arch/Pacman (coming soon)\n"
def sanitize_exec_block(self, block, info): _coming_soon_exec(block, info)
class SUSEFamily(DistroFamily):
name = "suse"
FAMILY_IDS = {"opensuse", "opensuse-leap", "opensuse-tumbleweed", "sles", "sled"}
def get_info(self, raw):
return _coming_soon_info(raw, "suse", "SUSE-based Linux", ["zypper","rpm"],
"openSUSE/SLES support is coming soon. General Linux help is still available.")
def build_system_prompt_section(self, info):
return f"## System Context\n- Distro: {info.distro_name}\n- Family: SUSE/Zypper (coming soon)\n"
def sanitize_exec_block(self, block, info): _coming_soon_exec(block, info)
class AlpineFamily(DistroFamily):
name = "alpine"
FAMILY_IDS = {"alpine"}
def get_info(self, raw):
return _coming_soon_info(raw, "alpine", "Alpine Linux", ["apk"],
"Alpine Linux support is coming soon. General Linux help is still available.")
def build_system_prompt_section(self, info):
return f"## System Context\n- Distro: {info.distro_name}\n- Family: Alpine/APK (coming soon)\n"
def sanitize_exec_block(self, block, info): _coming_soon_exec(block, info)
# ── Registry (add new family instances here) ──────────────────────────────────
_FAMILIES = [DebianFamily(), RedHatFamily(), ArchFamily(), SUSEFamily(), AlpineFamily()]
def _parse_os_release() -> dict:
for path in ("/etc/os-release", "/usr/lib/os-release"):
if Path(path).exists():
result = {}
for line in Path(path).read_text(errors="replace").splitlines():
line = line.strip()
if "=" in line and not line.startswith("#"):
k, _, v = line.partition("=")
result[k.strip()] = v.strip().strip('"')
return result
return {}
def detect_distro():
raw = _parse_os_release()
all_ids = {raw.get("ID", "").lower()} | set(raw.get("ID_LIKE", "").lower().split())
for family in _FAMILIES:
if family.detect(all_ids):
return family.get_info(raw), family
# Unknown distro fallback
info = DistroInfo(
family="unknown", distro_id=raw.get("ID","unknown").lower(),
distro_name=raw.get("PRETTY_NAME","Unknown Linux"),
version_id=raw.get("VERSION_ID",""), codename="",
pkg_managers=[], supported=False,
support_note=(
f"Your Linux distribution is not yet fully supported by {PRODUCT_NAME}. "
"General troubleshooting help is still available, but "
"automatic fix execution is disabled."
),
)
stub = DistroFamily()
stub.build_system_prompt_section = lambda i: f"## System Context\n- Distro: {i.distro_name} (unsupported)\n"
stub.sanitize_exec_block = lambda b, i: (_ for _ in ()).throw(
ValueError("Automatic fix execution is not supported on this distribution.")
)
return info, stub
# ══════════════════════════════════════════════════════════════════════════════
# DAEMON — background server (Unix socket, session state, Ollama)
# ══════════════════════════════════════════════════════════════════════════════
MAX_HISTORY = 500
# ── Ollama configuration ──────────────────────────────────────────────────────
# Change OLLAMA_MODEL to any model you have pulled, e.g.:
# ollama pull llama3 (good all-rounder, ~4GB)
# ollama pull mistral (fast, lower RAM)
# ollama pull phi3 (lightweight, works on CPU)
# ollama pull codellama (code-focused)
OLLAMA_HOST = "http://localhost:11434" # default Ollama address
OLLAMA_MODEL = "llama3" # model to use (must be pulled first)
_DISTRO_INFO = None
_DISTRO_FAMILY = None
BASE_PROMPT = f"""You are {AI_PERSONA} — an expert Linux system troubleshooting assistant \
running as a background demon on the user's machine.
Your capabilities:
1. Diagnose problems with installing, upgrading, removing, and running programs.
2. Suggest clear, actionable fixes with explanations.
3. When asked to "apply", "run", or "execute" a fix, output a DAEMONIQ_EXEC block \
so the demon can run it safely on the user's system.
4. Analyze shell command history for patterns, errors, or inefficiencies.
5. Recommend UX and workflow improvements when asked.
## Response format
Use plain text with markdown code blocks for commands.
When you want to EXECUTE commands, include exactly one JSON block:
<DAEMONIQ_EXEC>
{{"commands": ["cmd1", "cmd2"], "description": "Brief description", "requires_sudo": false}}
</DAEMONIQ_EXEC>
Rules:
- Only emit DAEMONIQ_EXEC when the user explicitly asks to apply/run/execute a fix.
- Run commands sequentially; stop on first non-zero exit.
- Never include interactive commands (nano, vim, less, etc.).
- Prefer idempotent commands. Explain what each command does before the block.
- Lead with diagnosis, then the fix. Be concise but thorough.
- Use: ✓ success ✗ error ⚠ warning → step
"""
# ══ HARDWARE & DRIVER CONTEXT ════════════════════════════════════════════════
# Scans the system for hardware and driver state at demon startup.
# Results are cached in hardware_snapshot.json and injected into every
# AI request so the model always knows what is in the machine.
# ═════════════════════════════════════════════════════════════════════════════
HARDWARE_SNAPSHOT_FILE = os.path.join(INSTALL_DIR, "hardware_snapshot.json")
# Commands that are safe to run for read-only hardware discovery
_HW_COMMANDS = {
"pci_devices": ["lspci", "-vmm"],
"usb_devices": ["lsusb"],
"loaded_modules": ["lsmod"],
"kernel_version": ["uname", "-r"],
"kernel_cmdline": ["cat", "/proc/cmdline"],
"dmesg_errors": ["dmesg", "--level=err,warn", "--notime"],
"gpu_info": ["lspci", "-nnk", "-d", "::0300"], # VGA/3D controllers
"network_hw": ["lspci", "-nnk", "-d", "::0200"], # Network controllers
"audio_hw": ["lspci", "-nnk", "-d", "::0401"], # Audio devices
"block_devices": ["lsblk", "-o", "NAME,MODEL,TRAN,SIZE"],
"cpu_info": ["grep", "-m4", "model name\|cpu MHz\|siblings\|cpu cores", "/proc/cpuinfo"],
"memory_info": ["grep", "MemTotal\|MemAvailable", "/proc/meminfo"],
"firmware_info": ["dmesg", "-t", "-l", "err"],
}
# Optional commands — only run if the tool exists
_HW_OPTIONAL = {
"ubuntu_drivers": ["ubuntu-drivers", "list"],
"nvidia_smi": ["nvidia-smi", "-q", "-d", "NAME,DRIVER_VERSION,UTILIZATION"],
"amd_gpu": ["cat", "/sys/class/drm/card0/device/vendor"],
"rfkill": ["rfkill", "list"],
"bluetooth": ["bluetoothctl", "show"],
"printer_drivers": ["lpstat", "-a"],
"dkms_status": ["dkms", "status"],
"kernel_modules_avail":["apt-cache", "search", "--names-only", "linux-modules"],
}
def _run_cmd(args: list, timeout: int = 8) -> str:
"""Run a command and return stdout, or empty string on failure."""
try:
r = subprocess.run(
args, capture_output=True, text=True,
timeout=timeout, errors="replace"
)
return r.stdout.strip()
except Exception:
return ""
def _scan_hardware() -> dict:
"""
Collect hardware and driver state. Returns a dict that is both saved
to hardware_snapshot.json and injected into the system prompt.
"""
snapshot = {"scanned_at": __import__("datetime").datetime.now().isoformat()}
# Required commands
for key, cmd in _HW_COMMANDS.items():
result = _run_cmd(cmd)
if result:
snapshot[key] = result
# Optional commands — skip silently if tool not present
for key, cmd in _HW_OPTIONAL.items():
if shutil.which(cmd[0]):
result = _run_cmd(cmd)
if result:
snapshot[key] = result
# Derive a plain-English hardware summary for the prompt
summary_lines = []
if "kernel_version" in snapshot:
summary_lines.append(f"Kernel: {snapshot['kernel_version']}")
# GPU detection
gpu_raw = snapshot.get("gpu_info", "")
if "nvidia" in gpu_raw.lower():
summary_lines.append("GPU: NVIDIA detected")
elif "amd" in gpu_raw.lower() or "radeon" in gpu_raw.lower():
summary_lines.append("GPU: AMD/Radeon detected")
elif "intel" in gpu_raw.lower():
summary_lines.append("GPU: Intel integrated graphics detected")
# Wi-Fi / network
net_raw = snapshot.get("network_hw", "")
if net_raw:
for line in net_raw.splitlines():
if line.strip():
summary_lines.append(f"Network HW: {line.strip()}")
break
# DKMS
if "dkms_status" in snapshot:
summary_lines.append(f"DKMS modules: {snapshot['dkms_status']}")
# ubuntu-drivers
if "ubuntu_drivers" in snapshot:
summary_lines.append(f"Recommended drivers (ubuntu-drivers): {snapshot['ubuntu_drivers']}")
# nvidia-smi
if "nvidia_smi" in snapshot:
for line in snapshot["nvidia_smi"].splitlines():
if "Driver Version" in line:
summary_lines.append(f"NVIDIA driver: {line.strip()}")
break
snapshot["summary"] = "\n".join(summary_lines)
# Save to disk
try:
json.dump(snapshot, open(HARDWARE_SNAPSHOT_FILE, "w"), indent=2)
log.info(f"Summoned hardware snapshot ({len(snapshot)} fields)")
except Exception as e:
log.warning(f"Could not save hardware snapshot: {e}")
return snapshot
# Global hardware snapshot — populated at demon startup
_HW_SNAPSHOT: dict = {}
def _build_system_prompt(shell_history: list) -> str:
parts = [BASE_PROMPT]
# Inject user-declared distro from setup config (highest priority context)
try:
cfg = json.load(open(CONFIG_FILE))
distro_label = cfg.get("distro_label", "")
distro_key = cfg.get("distro_key", "")
if distro_label and distro_label != "Other / Not listed":
parts.append(
f"## User's Linux Distribution\n"
f"The user is running **{distro_label}** (id: {distro_key}). "
f"Tailor all advice, package manager commands, and file paths to this distro."
)
except Exception:
pass
if _DISTRO_INFO and _DISTRO_FAMILY:
parts.append(_DISTRO_FAMILY.build_system_prompt_section(_DISTRO_INFO))
if not _DISTRO_INFO.supported:
parts.append(
f"\n⚠ SUPPORT NOTE: {_DISTRO_INFO.support_note}\n"
"Do NOT emit DAEMONIQ_EXEC blocks for this distribution."
)
# Inject hardware snapshot if available
if _HW_SNAPSHOT:
hw_parts = ["## Hardware & Driver Context"]
if _HW_SNAPSHOT.get("summary"):
hw_parts.append(_HW_SNAPSHOT["summary"])
if _HW_SNAPSHOT.get("dmesg_errors"):
# Only include last 20 lines of dmesg errors to keep prompt size sane
dmesg_tail = "\n".join(_HW_SNAPSHOT["dmesg_errors"].splitlines()[-20:])
hw_parts.append(f"\nRecent kernel errors/warnings (dmesg):\n```\n{dmesg_tail}\n```")
if _HW_SNAPSHOT.get("loaded_modules"):
# First 30 lines of lsmod is enough for context
lsmod_head = "\n".join(_HW_SNAPSHOT["loaded_modules"].splitlines()[:30])
hw_parts.append(f"\nLoaded kernel modules (lsmod, first 30):\n```\n{lsmod_head}\n```")
if _HW_SNAPSHOT.get("dkms_status"):
hw_parts.append(f"\nDKMS module status:\n```\n{_HW_SNAPSHOT['dkms_status']}\n```")
if _HW_SNAPSHOT.get("ubuntu_drivers"):
hw_parts.append(f"\nRecommended drivers (ubuntu-drivers list):\n```\n{_HW_SNAPSHOT['ubuntu_drivers']}\n```")
parts.append("\n".join(hw_parts))
if shell_history:
recent = shell_history[-50:]
parts.append(
f"\n## User's recent shell history ({len(recent)} commands)\n"
"```bash\n" + "\n".join(recent) + "\n```"
)
return "\n\n".join(parts)
# ── Logging ───────────────────────────────────────────────────────────────────
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.FileHandler(LOG_FILE), logging.StreamHandler(sys.stdout)],
)
log = logging.getLogger(DAEMON_LABEL)
# ── Session state ─────────────────────────────────────────────────────────────
class _SessionState:
def __init__(self):
self._lock = threading.Lock()
self.conversations = {}
self.shell_history = []
self._load_history()
def _load_history(self):
if Path(HISTORY_FILE).exists():
try:
lines = [l.strip() for l in open(HISTORY_FILE) if l.strip()]
self.shell_history = lines
log.info(f"Loaded {len(lines)} history entries")
except Exception as e:
log.warning(f"Could not load history: {e}")
def add_history(self, commands: list):
with self._lock:
self.shell_history.extend(commands)
self.shell_history = self.shell_history[-MAX_HISTORY:]
try:
open(HISTORY_FILE, "w").write("\n".join(self.shell_history) + "\n")
except Exception as e:
log.warning(f"Could not save history: {e}")
def get_messages(self, sid: str) -> list:
with self._lock:
return self.conversations.setdefault(sid, []).copy()
def add_message(self, sid: str, role: str, content: str):
with self._lock:
msgs = self.conversations.setdefault(sid, [])
msgs.append({"role": role, "content": content})
if len(msgs) > 40:
self.conversations[sid] = msgs[-40:]
def clear_session(self, sid: str):
with self._lock:
self.conversations.pop(sid, None)
def list_sessions(self) -> list:
with self._lock:
return list(self.conversations.keys())
_state = _SessionState()
# ── Ollama API ────────────────────────────────────────────────────────────────
def _check_ollama() -> tuple[bool, str]:
"""Return (available, message). Checks Ollama is running and model is pulled."""
import urllib.request, urllib.error
try:
with urllib.request.urlopen(f"{OLLAMA_HOST}/api/tags", timeout=3) as r:
data = json.loads(r.read())
models = [m["name"].split(":")[0] for m in data.get("models", [])]
if OLLAMA_MODEL not in models and f"{OLLAMA_MODEL}:latest" not in [m["name"] for m in data.get("models", [])]:
return False, (
f"Model '{OLLAMA_MODEL}' is not pulled yet.\n"
f" Run: ollama pull {OLLAMA_MODEL}\n"
f" Available models: {', '.join(models) or 'none'}"
)
return True, "ok"
except urllib.error.URLError:
return False, (
f"Ollama is not running. Start it with: ollama serve\n"
f" Install Ollama: https://ollama.com/download"
)
except Exception as e:
return False, f"Could not reach Ollama: {e}"
def _call_api(sid: str, message: str, api_key: str = "") -> str:
"""Call the local Ollama model. api_key is unused but kept for interface compatibility."""
import urllib.request
try:
_state.add_message(sid, "user", message)
# Build messages in OpenAI-compatible format (which Ollama supports)
messages = [{"role": "system", "content": _build_system_prompt(_state.shell_history)}]
messages += _state.get_messages(sid)
payload = json.dumps({
"model": OLLAMA_MODEL,
"messages": messages,
"stream": False,
"options": {"num_predict": 1024, "temperature": 0.2},
}).encode()
req = urllib.request.Request(
f"{OLLAMA_HOST}/api/chat",
data=payload, method="POST",
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=120) as resp:
data = json.loads(resp.read())
reply = data.get("message", {}).get("content", "")
if not reply:
reply = "✗ Empty response from Ollama."
_state.add_message(sid, "assistant", reply)
return reply
except Exception as e:
log.error(f"Ollama error: {e}")
return f"✗ Ollama error: {e}"
# ── Command executor ───────────────────────────────────────────────────────────
def _execute(block: ExecBlock) -> str:
lines = [f"⚡ Executing: {block.description}", "─" * 50]
for cmd in block.commands:
lines.append(f"$ {cmd}")
try:
r = subprocess.run(
cmd, shell=True, capture_output=True, text=True, timeout=120,
env={**os.environ, "DEBIAN_FRONTEND": "noninteractive"},
)
if r.stdout.strip(): lines.append(r.stdout.strip())
if r.stderr.strip(): lines.append(f"[stderr] {r.stderr.strip()}")
lines.append(f"→ exit code: {r.returncode} {'✓' if r.returncode == 0 else '✗'}")
_state.add_history([cmd])
if r.returncode != 0:
lines.append("⚠ Non-zero exit — stopping.")
break
except subprocess.TimeoutExpired:
lines.append("✗ Timed out after 120s"); break
except Exception as e:
lines.append(f"✗ Error: {e}"); break
lines.append("")
return "\n".join(lines)
_EXEC_RE = re.compile(r"<DAEMONIQ_EXEC>\s*(.*?)\s*</DAEMONIQ_EXEC>", re.DOTALL)
def _parse_exec(response: str, auto_exec: bool):
m = _EXEC_RE.search(response)
if not m:
return response, None
clean = _EXEC_RE.sub("", response).strip()
if not auto_exec:
clean += (
f"\n\n⚠ Fix commands ready. Use `exec on` in the REPL or `--exec` flag to apply, "
f"or type `run the fix`."
)
return clean, None
if _DISTRO_INFO and not _DISTRO_INFO.supported:
return clean, f"✗ Auto-execution not supported on {_DISTRO_INFO.distro_name} yet."
try:
raw = json.loads(m.group(1))
block = ExecBlock(
commands=raw.get("commands", []),
description=raw.get("description", ""),
requires_sudo=raw.get("requires_sudo", False),
)
except json.JSONDecodeError as e:
return clean, f"✗ Could not parse exec block: {e}"
try:
block = _DISTRO_FAMILY.sanitize_exec_block(block, _DISTRO_INFO)
except ValueError as e:
return clean, f"✗ Execution blocked: {e}"
return clean, _execute(block)
# ── Socket protocol ───────────────────────────────────────────────────────────
_END = b"\n##END##\n"
def _recv(conn):
data = b""
while True:
chunk = conn.recv(4096)
if not chunk: break
data += chunk
if data.endswith(_END):
return json.loads(data[:-len(_END)].decode())
return json.loads(data.decode())
def _send(conn, obj):
conn.sendall(json.dumps(obj).encode() + _END)
# ── Client handler ────────────────────────────────────────────────────────────
def _handle_client(conn):
try:
req = _recv(conn)
cmd = req.get("cmd", "chat")
sid = req.get("session", "default")
key = req.get("api_key", "")
if cmd == "ping":
_send(conn, {"status": "ok", "pid": os.getpid()})
elif cmd == "chat":
ok, msg = _check_ollama()
if not ok:
_send(conn, {"error": msg}); return
log.info(f"[{sid}] {req.get('message','')[:80]}")
raw_reply = _call_api(sid, req.get("message", ""))
clean, exec_out = _parse_exec(raw_reply, req.get("auto_exec", False))
_send(conn, {"reply": clean, "exec_output": exec_out, "session": sid})
elif cmd == "history_import":
cmds = req.get("commands", [])
_state.add_history(cmds)
_send(conn, {"status": f"Imported {len(cmds)} commands"})
elif cmd == "history_get":
_send(conn, {"history": _state.shell_history[-100:]})
elif cmd == "session_clear":
_state.clear_session(sid)
_send(conn, {"status": f"Session '{sid}' cleared"})
elif cmd == "sessions_list":
_send(conn, {"sessions": _state.list_sessions()})
elif cmd == "distro_info":
if _DISTRO_INFO:
_send(conn, {
"family": _DISTRO_INFO.family, "distro_id": _DISTRO_INFO.distro_id,
"distro_name": _DISTRO_INFO.distro_name, "version_id": _DISTRO_INFO.version_id,
"codename": _DISTRO_INFO.codename, "pkg_managers": _DISTRO_INFO.pkg_managers,
"supported": _DISTRO_INFO.supported, "support_note": _DISTRO_INFO.support_note,
})
else:
_send(conn, {"error": "Distro not yet detected"})
elif cmd == "status":
_send(conn, {
"pid": os.getpid(), "sessions": len(_state.list_sessions()),
"history_entries": len(_state.shell_history), "log": LOG_FILE,
"distro": _DISTRO_INFO.distro_name if _DISTRO_INFO else "unknown",
"supported": _DISTRO_INFO.supported if _DISTRO_INFO else False,
"ai_backend": f"Ollama ({OLLAMA_MODEL} @ {OLLAMA_HOST})",
"hw_summary": _HW_SNAPSHOT.get("summary", "not scanned"),
})
elif cmd == "hardware":
_send(conn, {"snapshot": _HW_SNAPSHOT})
else:
_send(conn, {"error": f"Unknown command: {cmd}"})
except Exception as e:
log.error(f"Client handler error: {e}")
try: _send(conn, {"error": str(e)})
except: pass
finally:
conn.close()
# ── Server loop ───────────────────────────────────────────────────────────────
def _run_server():
open(PID_FILE, "w").write(str(os.getpid()))
Path(SOCKET_PATH).unlink(missing_ok=True)
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
srv.bind(SOCKET_PATH)
os.chmod(SOCKET_PATH, 0o600)
srv.listen(10)
label = (f"{_DISTRO_INFO.distro_name} "
f"[{'SUPPORTED' if _DISTRO_INFO.supported else 'LIMITED'}]"
if _DISTRO_INFO else "unknown distro")
log.info(f"{PRODUCT_NAME} awakened (PID {os.getpid()}) — {label}")
def _shutdown(sig, frame):
log.info("Returning to the void...")
srv.close()
Path(SOCKET_PATH).unlink(missing_ok=True)
Path(PID_FILE).unlink(missing_ok=True)
sys.exit(0)
signal.signal(signal.SIGTERM, _shutdown)
signal.signal(signal.SIGINT, _shutdown)
while True:
try:
conn, _ = srv.accept()
threading.Thread(target=_handle_client, args=(conn,), daemon=True).start()
except OSError:
break
def _daemonize():
if os.fork() > 0: sys.exit(0)
os.setsid()
if os.fork() > 0: sys.exit(0)
sys.stdout.flush(); sys.stderr.flush()
with open(os.devnull) as f:
os.dup2(f.fileno(), sys.stdin.fileno())
with open(LOG_FILE, "a") as f:
os.dup2(f.fileno(), sys.stdout.fileno())
os.dup2(f.fileno(), sys.stderr.fileno())
def _start_daemon_process(foreground=False):
global _DISTRO_INFO, _DISTRO_FAMILY, _HW_SNAPSHOT
_DISTRO_INFO, _DISTRO_FAMILY = detect_distro()
_HW_SNAPSHOT = _scan_hardware()
if not foreground:
_daemonize()
_run_server()
# ══════════════════════════════════════════════════════════════════════════════
# CLI — terminal client and interactive REPL
# ══════════════════════════════════════════════════════════════════════════════
# ── ANSI colours ──────────────────────────────────────────────────────────────
class C:
RESET = "\033[0m"; BOLD = "\033[1m"; DIM = "\033[2m"
GREEN = "\033[38;5;82m"; LGREEN = "\033[38;5;120m"
YELLOW = "\033[38;5;220m"; RED = "\033[38;5;196m"
CYAN = "\033[38;5;51m"; WHITE = "\033[97m"
DGRAY = "\033[38;5;238m"; MGRAY = "\033[38;5;245m"
def _no_color():
for a in [x for x in vars(C) if not x.startswith("_")]:
setattr(C, a, "")
if not sys.stdout.isatty():
_no_color()
def _banner() -> str:
RED = "\033[38;5;196m"
rendered = [f"{RED}{l}{C.RESET}" for l in BANNER_LINES]
art = chr(10).join(rendered)
sub = f" {C.DIM}* {PRODUCT_TAGLINE} * -- v{PRODUCT_VERSION}{C.RESET}"
return f"\n{art}\n{sub}\n"
def _sep():
print(f"{C.DGRAY}{'─' * min(shutil.get_terminal_size((80,20)).columns, 80)}{C.RESET}")
# ── Socket communication ──────────────────────────────────────────────────────
def _request(req: dict, timeout: int = 90) -> dict:
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect(SOCKET_PATH)
s.sendall(json.dumps(req).encode() + _END)
data = b""
while True:
chunk = s.recv(4096)
if not chunk: break
data += chunk