Repository navigation
Expand file tree
/
Copy pathllama_shell.py
More file actions
2061 lines (1774 loc) · 70.3 KB
/
Copy pathllama_shell.py
File metadata and controls
2061 lines (1774 loc) · 70.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
import os
import subprocess
from pathlib import Path
import shutil
import time
import readline
import re
import sys
import shlex
import json
import base64
import struct
from datetime import datetime
from rich.console import Console
import termios
import requests
import pty, select
always_execute = False
from configuration_variables import *
from ai_display import stream_response
from prompt_toolkit.formatted_text import ANSI
from prompt_toolkit.document import Document
from prompt_toolkit.completion import PathCompleter, Completion, Completer
from google import genai
from google.genai import types
import signal
from prompt_toolkit import PromptSession
#colors
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
ESPRESSO = "\033[38;2;60;30;10m"
MOCHA = "\033[38;2;130;80;40m"
CARAMEL = "\033[38;2;198;140;70m"
CREAM = "\033[38;2;230;210;220m"
LATTE = "\033[38;2;230;210;220m"
FOAM = "\033[38;2;230;210;220m"
CINNAMON = "\033[38;2;180;80;30m"
STEAM = "\033[38;2;160;145;130m"
GREEN = "\033[38;2;120;160;80m"
RED = "\033[38;2;190;70;50m"
YELLOW = "\033[38;2;210;170;60m"
CYAN = CARAMEL
WHITE = CREAM
GREY = STEAM
BLUE = LATTE
console = Console()
#Completion
class Kompleter(Completer):
def get_completions(self, document, complete_event):
text_to_parse = document.text_before_cursor
if not text_to_parse:
for command in ["cat", "cd", "ls", "nano", "rm", "vim", "whoami",
"id", "clear", "systemctl", "source", "open",
"bash", "ASK()", "FLAGS()", "INCLUDE()", "CLEAR()", "BUMP()", "LOAD()", "ESC()",
"TOOL()", "ADD_TOOL()", "BANNER()", "RESET()", "HELP"]:
yield Completion(command, start_position=0)
return
token_start = len(text_to_parse)
in_quote = None
for i in range(len(text_to_parse) - 1, -1, -1):
char = text_to_parse[i]
if char in ('"', "'"):
if in_quote == char:
in_quote = None
elif in_quote is None:
in_quote = char
if in_quote is None and char.isspace():
break
token_start = i
token = text_to_parse[token_start:]
is_first_token = not text_to_parse[:token_start].strip()
if is_first_token:
for command in ["cat", "cd", "ls", "nano", "rm", "vim", "whoami",
"id", "clear", "systemctl", "source", "open",
"bash", "ASK()", "FLAGS()", "INCLUDE()", "CLEAR()", "BUMP()", "LOAD()", "ESC()",
"TOOL()", "ADD_TOOL()", "BANNER()", "RESET()", "HELP"]:
if command.startswith(token):
yield Completion(command, start_position=-len(token))
if token or text_to_parse[-1] == " ":
if is_first_token and token == "cd":
path_completer = PathCompleter(expanduser=True, only_directories=True)
elif not is_first_token and text_to_parse.split()[0] == "cd":
path_completer = PathCompleter(expanduser=True, only_directories=True)
else:
path_completer = PathCompleter(expanduser=True)
subdocument = Document(text=token, cursor_position=len(token))
for comp in path_completer.get_completions(subdocument, complete_event):
yield Completion(comp.text, start_position=comp.start_position)
session = PromptSession(completer=Kompleter())
#small helpers
def visible_len(text):
return len(re.sub(r'\x1b\[[0-9;]*[JKm]', '', text))
def extract_bash_blocks(text: str) -> list[str]: #Get bash blocks
lines = text.split("\n")
blocks, stack, outer_lang, buf = [], [], None, []
for line in lines:
stripped = line.strip()
if stripped.startswith("```"):
lang_word = stripped[3:].strip()
if not stack:
outer_lang = lang_word or "text"
stack.append(outer_lang)
buf = []
elif lang_word:
stack.append(lang_word)
buf.append(line)
else:
stack.pop()
if stack:
buf.append(line)
else:
if outer_lang == "bash":
blocks.append("\n".join(buf))
buf, outer_lang = [], None
else:
if stack:
buf.append(line)
return blocks
def _iter_sse_json(response):
"""Yield JSON objects from an OpenAI/Anthropic-style SSE or NDJSON stream."""
for raw in response.iter_lines(decode_unicode=True):
if not raw:
continue
line = raw.strip()
if line.startswith(":"):
continue # SSE comment / keepalive
if line.startswith("data:"):
data = line[5:].strip()
if not data or data == "[DONE]":
if data == "[DONE]":
return
continue
try:
yield json.loads(data)
except json.JSONDecodeError:
continue
elif line.startswith("{"):
# Plain NDJSON fallback (some proxies)
try:
yield json.loads(line)
except json.JSONDecodeError:
continue
def _openai_delta_text(chunk: dict) -> str:
"""Extract assistant text from an OpenAI chat.completions stream chunk."""
choices = chunk.get("choices") or []
if not choices:
# Non-stream style body sometimes returned by misconfigured proxies
msg = chunk.get("message") or {}
if isinstance(msg, dict) and msg.get("content"):
return msg["content"]
return ""
choice = choices[0] or {}
delta = choice.get("delta") or {}
content = delta.get("content")
if content:
return content
# Non-streaming / final message shape nested in stream (rare)
message = choice.get("message") or {}
return message.get("content") or ""
def openai_http(messages, model=OPENAI_MODEL, url=OPENAI_URL_ENDPOINT):
"""OpenAI Chat Completions compatible streaming client (Omniroute, Ollama /v1, etc.)."""
payload = {
"model": model,
"messages": messages,
"stream": True,
"temperature": 0.2,
"top_p": 0.9,
"reasoning_effort": REASON,
}
headers = {"Content-Type": "application/json"}
if OPENAI_API:
if not OPENAI_URL_API:
raise RuntimeError(
"OPENAI_API=True but OPENAI_URL_API is empty. "
"Set the bearer token in .env (see .env.example)."
)
headers["Authorization"] = f"Bearer {OPENAI_URL_API}"
try:
with requests.post(url, json=payload, headers=headers, stream=True, timeout=AI_HTTP_TIMEOUT) as r:
r.raise_for_status()
for chunk in _iter_sse_json(r):
tokens = _openai_delta_text(chunk)
if tokens:
yield tokens
except requests.RequestException as e:
raise RuntimeError(f"OpenAI-compatible request failed: {e}") from e
def _split_system_messages(messages):
"""Anthropic wants system as a top-level field, not a message role."""
system_parts = []
chat = []
for msg in messages:
role = (msg.get("role") or "user").lower()
content = msg.get("content", "")
if role == "system":
if content:
system_parts.append(content)
continue
if role not in ("user", "assistant"):
role = "user"
chat.append({"role": role, "content": content})
return "\n\n".join(system_parts) if system_parts else None, chat
def _anthropic_delta_text(event: dict) -> str:
"""Extract text from Anthropic Messages SSE event payloads."""
etype = event.get("type")
if etype == "content_block_delta":
delta = event.get("delta") or {}
if delta.get("type") == "text_delta":
return delta.get("text") or ""
# Some Anthropic-compatible proxies mirror OpenAI deltas
if "choices" in event:
return _openai_delta_text(event)
return ""
def anthropic_http(messages, model=ANTHROPIC_MODEL, url=ANTHROPIC_URL_ENDPOINT):
"""Anthropic Messages API compatible streaming client."""
system, chat_messages = _split_system_messages(messages)
if not chat_messages:
return
payload = {
"model": model,
"messages": chat_messages,
"max_tokens": ANTHROPIC_MAX_TOKENS,
"stream": True,
"temperature": 0.2,
}
if system:
payload["system"] = system
headers = {
"Content-Type": "application/json",
"anthropic-version": ANTHROPIC_VERSION,
}
if ANTHROPIC_API:
if not ANTHROPIC_URL_API:
raise RuntimeError(
"ANTHROPIC_API=True but ANTHROPIC_URL_API is empty. "
"Set the API key in .env (see .env.example)."
)
headers["x-api-key"] = ANTHROPIC_URL_API
# Some OpenAI→Anthropic bridges also accept Bearer
headers.setdefault("Authorization", f"Bearer {ANTHROPIC_URL_API}")
try:
with requests.post(url, json=payload, headers=headers, stream=True, timeout=AI_HTTP_TIMEOUT) as r:
r.raise_for_status()
for event in _iter_sse_json(r):
tokens = _anthropic_delta_text(event)
if tokens:
yield tokens
except requests.RequestException as e:
raise RuntimeError(f"Anthropic-compatible request failed: {e}") from e
_gemini_ready = False
_gemini_client = None
def _ensure_gemini():
global _gemini_client
if _gemini_client is not None:
return _gemini_client
if not GEMINI_API:
raise RuntimeError(
"GEMINI_API is not set. Put it in .env or the environment "
"(see .env.example). Rotate any key that was previously hardcoded."
)
_gemini_client = genai.Client(api_key=GEMINI_API)
return _gemini_client
#gemini experimental convert.
def convert_to_gemini(messages):
system_instruction = None
gemini_history = []
for msg in messages:
role = msg.get("role", "user").lower()
content = msg.get("content", "")
if role == "system":
system_instruction = (system_instruction + "\n\n" + content) if system_instruction else content
continue
mapped_role = "model" if role in ("assistant", "model") else "user"
if gemini_history and gemini_history[-1]["role"] == mapped_role:
gemini_history[-1]["parts"][0] += f"\n\n{content}"
else:
gemini_history.append({"role": mapped_role, "parts": [content]})
return system_instruction, gemini_history
def gemini_stream(prompt):
client = _ensure_gemini()
system, contents = convert_to_gemini(prompt)
if not contents:
return
normalized = [
types.Content(
role=msg["role"],
parts=[types.Part(text=p) if isinstance(p, str) else p for p in msg["parts"]],
)
for msg in contents
]
response = client.models.generate_content_stream(
model=GEMINI_MODEL,
contents=normalized,
config=types.GenerateContentConfig(
system_instruction=system,
),
)
for chunk in response:
if chunk.text:
yield chunk.text
#Router
def ai_response(prompt):
kind = API_TYPE.lower()
if kind in ("openai_http", "ollama_http"): # ollama_http kept as alias
return openai_http(prompt)
if kind == "anthropic_http":
return anthropic_http(prompt)
if kind == "gemini":
return gemini_stream(prompt)
raise RuntimeError(f"Unknown API_TYPE: {API_TYPE!r}")
#Model should have context (filled in main())
history = []
# Persistent bash — created in start_bash_session() / main()
bashcmd = None
def start_bash_session():
global bashcmd
bashcmd = subprocess.Popen(
["/bin/bash", "-s"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=current_dir,
text=True,
errors="replace",
bufsize=1,
preexec_fn=os.setpgrp,
env=env,
)
return bashcmd
#banner
def show_header():
W = 72
def row(left="", right="", fill=" "):
v_left = visible_len(left)
v_right = visible_len(right)
inner = left + fill * (W - v_left - v_right) + right
return f"{MOCHA}│{RESET}{inner}{MOCHA}│{RESET}"
def rule(l="╭", m="─", r="╮"):
return f"{MOCHA}{l}{m * W}{r}{RESET}"
print()
print(rule("╭", "─", "╮"))
print(row())
print(row(
f" {CARAMEL}{BOLD} llama_term{RESET} "
f"{DIM}{STEAM}AI-assisted interactive shell{RESET}"
))
print(row(
f" {DIM}{STEAM}by Kelvin Rutatina · "
))
print(row())
print(f"{MOCHA}├{'─' * W}┤{RESET}")
print(row())
print(row(f" {LATTE}Quick reference{RESET}"))
print(row())
cmds = [
("ASK()", "Ask the AI — it generates commands from live context"),
("FLAGS()", "Toggle repeat/embed/exitcode context markers"),
("BUMP()", "Reset model context — clears hallucinations"),
("LOAD()", "Warm up and load your AI model"),
("TOOL()", "List (numbered) or switch active tool"),
("BANNER()", "Redisplay this banner"),
("RESET()", "Restart the shell session"),
("HELP", "Show the full command reference"),
("Ctrl+C", "Cancel the current running task"),
]
for cmd, desc in cmds:
label = f"{CARAMEL}{BOLD}{cmd}{RESET}"
note = f"{DIM}{STEAM}{desc}{RESET}"
pad = W - len(cmd) - len(desc) - 7
print(f"{MOCHA}│{RESET} {label} {LATTE}→{RESET} {note}{' ' * max(pad, 0)}{MOCHA}│{RESET}")
print(row())
print(rule("╰", "─", "╯"))
print(f"\n {DIM}{STEAM}Terminal ready.{RESET}\n")
#help text
def show_help():
W = 68
def section(title):
print(f"\n {CARAMEL}{BOLD}{title}{RESET}")
print(f" {MOCHA}{'─' * (len(title))}{RESET}")
def entry(cmd, desc):
pad = 18
print(f" {CREAM}{cmd:<{pad}}{RESET}{DIM}{STEAM}{desc}{RESET}")
title = f" {CARAMEL}{BOLD} llama_term — Command Reference{RESET}"
v_title = visible_len(title)
padding = (W + 2) - v_title
print(f"\n{MOCHA}╭{'─' * (W + 2)}╮{RESET}")
print(f"{MOCHA}│{RESET}{title}{' ' * padding}{MOCHA}│{RESET}")
print(f"{MOCHA}╰{'─' * (W + 2)}╯{RESET}")
section("Built-in Shell Commands")
entry("help / HELP", "Show this reference")
entry("clear / cls", "Clear the terminal screen")
entry("exit / quit", "Close llama_term")
section("AI Controls")
entry("ESC()", "Instantly stop a waiting loop; sentence goes to the AI")
entry("ASK() …", "Ask the model — generates bash from live host/tool context")
entry("FLAGS()", "Show context markers (repeat / embed / exitcode)")
entry("FLAGS() …", "FLAGS() repeat|embed|exitcode on|off or FLAGS() all on|off")
entry("BUMP()", "Wipe chat turns — keeps tool prompt + live embeds")
entry("LOAD()", "Pre-warm the AI model (faster first response)")
entry("BANNER()", "Redisplay the startup banner")
entry("RESET()", "Restart the underlying bash session")
entry("INCLUDE() …", "Attach file(s): INCLUDE() a b or INCLUDE() {a,b}")
section("How Error Handling Works")
print(f" {DIM}{STEAM}When a command exits non-zero, the AI analyses the"
f" failure and{RESET}")
print(f" {DIM}{STEAM}proposes a fix. You choose y / n / a (always){RESET}")
print(f" {DIM}{STEAM}before anything is executed.{RESET}")
print(f" {DIM}{STEAM}ASK() does the same without needing a failed command.{RESET}")
print(f" {DIM}{STEAM}Lines flagged as risky are highlighted in"
f" {CINNAMON}amber{RESET}{DIM}{STEAM} and force a prompt.{RESET}")
section("Confirming AI Scripts")
entry("y", "Run the suggestion")
entry("n", "Skip it")
entry("a", "Auto-run non-risky suggestions for this session")
entry("c", "Copy the suggested script to the clipboard")
entry("v", "View the exact script before deciding")
entry("t", "Run on a real PTY; attach output transcript to AI context")
entry("1-9", "With multiple blocks: run just that block")
print(f" {DIM}{STEAM}Risky lines always force an explicit y — 'a' can never bypass them.{RESET}")
section("Real TTY Mode")
print(f" {DIM}{STEAM}AI scripts run on their own throwaway PTY (no state kept), so{RESET}")
print(f" {DIM}{STEAM}colors, loading bars and TUIs render as usual; [t] tees the{RESET}")
print(f" {DIM}{STEAM}transcript to a tmp buffer for the AI. Editors, pagers and REPLs{RESET}")
print(f" {DIM}{STEAM}you type yourself are wrapped in script(1) inside the persistent{RESET}")
print(f" {DIM}{STEAM}shell — LLAMA_REALTTY=auto|always|off.{RESET}")
section("Logging")
print(f" {DIM}{STEAM}Approved AI scripts append to {LATTE}{LOG_FILE}{RESET}")
print(f" {DIM}{STEAM}Do not put secrets in included files sent to cloud providers.{RESET}")
section("Tools")
entry("TOOL()", "List available tools (numbered)")
entry("TOOL() NAME", "Switch active tool (e.g. TOOL() GIT)")
entry("TOOL() :N", "Switch to list position N (e.g. TOOL() :1)")
entry("ADD_TOOL() NAME", "AI-draft a new tool, review in editor, save")
print(f" {DIM}{STEAM}Tools are markdown system prompts stored in {LATTE}{HISTORY_DIR}{RESET}{DIM}{STEAM}.{RESET}")
print(f" {DIM}{STEAM}Current tool: {CARAMEL}{CURRENT_TOOL_NAME}{RESET}")
section("Setup")
entry("OpenAI-compat", "API_TYPE=openai_http (Omniroute / Ollama /v1 / OpenAI)")
entry("Anthropic", "API_TYPE=anthropic_http")
entry("Default model", f"{OPENAI_MODEL}")
entry("Secrets", "Copy .env.example → .env (OPENAI_URL_API, ANTHROPIC_URL_API, GEMINI_API)")
print()
import termios, tty, signal
import fcntl
#pty setup — only used when executing an approved AI script
def make_preexec(fd):
def preexec():
os.setsid()
try:
fcntl.ioctl(fd, termios.TIOCSCTTY, 0)
except OSError:
pass
return preexec
def _set_pty_size(master_fd):
"""Mirror the real terminal size onto the PTY so bars/TUIs render right."""
cols, rows = shutil.get_terminal_size((120, 36))
if cols <= 0 or rows <= 0:
cols, rows = 120, 36
try:
fcntl.ioctl(
master_fd, termios.TIOCSWINSZ,
struct.pack("HHHH", rows, cols, 0, 0),
)
except OSError:
pass
def _write_all(fd, data: bytes):
view = memoryview(data)
while view:
try:
n = os.write(fd, view)
except OSError:
return
view = view[n:]
_ANSI_RE = re.compile(
r"\x1b\[[0-9;?]*[ -/]*[@-~]" # CSI sequences (colors, cursor…)
r"|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?" # OSC (window title, clipboard…)
r"|\x1b[@-Z\\-_]" # other single-char escapes
)
def _clean_capture(raw: bytes, limit: int) -> str:
"""PTY transcript → plain text for the AI: strip escapes, collapse \\r frames."""
text = _ANSI_RE.sub("", raw.decode("utf-8", errors="replace"))
# PTY line discipline turns \n into \r\n — normalize FIRST or every line
# would end in \r and collapse to "". \r+ handles bar-frame + "\n"
# combos (\r\r\n); lone bare-\r redraw frames are collapsed per-line below
text = re.sub(r"\r+\n", "\n", text)
lines = []
for line in text.split("\n"):
if "\r" in line:
# bare-\r progress-bar redraws: keep only the final frame
line = line.rsplit("\r", 1)[-1]
lines.append(line.rstrip())
out = re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip("\n")
if len(out) > limit:
out = out[:limit] + "\n…[truncated]"
return out
def run_ai_script_pty(script_path: Path, capture: bool = False):
"""Run an approved AI script on its own real PTY — no session persistence,
except $PWD and env are captured via an out-of-band fd and merged back
into the caller's global state.
Returns (returncode, transcript_or_None).
"""
global current_dir, env
master_fd, slave_fd = pty.openpty()
_set_pty_size(master_fd)
result = None
old_tty = None
old_winch = None
cap_buf = bytearray()
child_env = dict(env)
child_env.setdefault("TERM", "xterm-256color")
# out-of-band pipe for final $PWD + env, kept off the PTY byte stream
state_r, state_w = os.pipe()
os.set_inheritable(state_w, True)
# wrapper sources the real script (so cd/export stay visible to us),
# then reports state on fd `state_w`, then exits with the real rc
wrapper_path = script_path.with_suffix(script_path.suffix + ".wrap.sh")
wrapper_path.write_text(
f"source {shlex.quote(str(script_path))}\n"
f"__rc=$?\n"
f"{{ printf '%s\\0' \"$PWD\"; env -0; }} >&{state_w}\n"
f"exec {state_w}>&-\n" # close it explicitly so EOF is prompt
f"exit $__rc\n"
)
try:
result = subprocess.Popen(
["/bin/bash", str(wrapper_path)],
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
pass_fds=(state_w,),
close_fds=True,
cwd=current_dir,
preexec_fn=make_preexec(slave_fd),
env=child_env,
)
os.close(slave_fd)
slave_fd = -1
os.close(state_w) # parent doesn't write; drop its copy so EOF works
state_w = -1
interactive = sys.stdin.isatty() and sys.stdout.isatty()
if interactive:
old_tty = termios.tcgetattr(0)
tty.setraw(0)
def _on_winch(signum, frame):
_set_pty_size(master_fd)
if interactive:
try:
old_winch = signal.signal(signal.SIGWINCH, _on_winch)
except (ValueError, OSError):
old_winch = None
stop = False
while not stop:
try:
readers = [master_fd] + ([0] if interactive else [])
r, _, _ = select.select(readers, [], [], 0.1)
except (ValueError, OSError):
break
if master_fd in r:
try:
data = os.read(master_fd, PTY_READ_BYTES)
except OSError:
data = b""
if data:
if capture:
cap_buf.extend(data)
_write_all(1, data)
else:
stop = True
if interactive and 0 in r:
try:
user_input = os.read(0, PTY_READ_BYTES)
except OSError:
user_input = b""
if user_input:
_write_all(master_fd, user_input)
if result.poll() is not None and not r:
stop = True
finally:
if old_winch is not None:
try:
signal.signal(signal.SIGWINCH, old_winch)
except (ValueError, OSError):
pass
if old_tty is not None:
try:
termios.tcsetattr(0, termios.TCSADRAIN, old_tty)
except termios.error:
pass
try:
os.close(master_fd)
except OSError:
pass
if slave_fd >= 0:
try:
os.close(slave_fd)
except OSError:
pass
if state_w >= 0:
try:
os.close(state_w)
except OSError:
pass
if result is not None:
try:
result.wait(timeout=5)
except Exception:
try:
result.kill()
except Exception:
pass
result.wait()
wrapper_path.unlink(missing_ok=True)
# drain state pipe now that the child (and its fd copy) is gone
state_data = b""
try:
while True:
chunk = os.read(state_r, 65536)
if not chunk:
break
state_data += chunk
except OSError:
pass
finally:
try:
os.close(state_r)
except OSError:
pass
if state_data:
parts = state_data.split(b"\0")
if parts and parts[0]:
new_dir = parts[0].decode(errors="replace").strip()
if new_dir and os.path.isdir(new_dir) and new_dir != current_dir:
current_dir = new_dir
try:
bashcmd.stdin.write(f"cd {shlex.quote(current_dir)}\n")
bashcmd.stdin.flush()
except (BrokenPipeError, AttributeError):
pass
# remaining null-separated KEY=VALUE pairs are the env
new_env = {}
for pair in parts[1:]:
if b"=" in pair:
k, _, v = pair.partition(b"=")
new_env[k.decode(errors="replace")] = v.decode(errors="replace")
if new_env:
env.update(new_env)
rc = result.returncode if result is not None else -1
return rc, (_clean_capture(bytes(cap_buf), AI_CAPTURE_MAX_CHARS) if capture else None)
LIVE_CONTEXT_MARKER = "# === LIVE HOST / TOOL CONTEXT"
# ── AI-script action helpers ────────────────────────────────────────────────
def copy_to_clipboard(text: str) -> str:
"""Copy text to the system clipboard; returns the method used.
Tries native tools first, falls back to OSC 52 (works over SSH on
modern terminals: kitty, alacritty, wezterm, tmux w/ set-clipboard).
"""
for cmd in (["wl-copy"], ["xclip", "-selection", "clipboard"],
["xsel", "--clipboard", "--input"], ["pbcopy"]):
if shutil.which(cmd[0]):
try:
subprocess.run(cmd, input=text, text=True, check=True, timeout=5)
return cmd[0]
except Exception:
continue
b64 = base64.b64encode(text.encode("utf-8")).decode("ascii")
sys.stdout.write(f"\033]52;c;{b64}\a")
sys.stdout.flush()
return "osc52"
def _write_temp_script(blocks: list[str]) -> None:
"""Write selected bash blocks to TEMP_SCRIPT.
No session trailers: AI scripts run on a throwaway PTY (state is not
persisted), so the output stream stays pure for bars/TUIs and the
exit code comes straight from the process.
"""
with open(TEMP_SCRIPT, "w") as tmp:
tmp.write("\n".join(blocks))
tmp.write("\n")
#AI invoke — used on command failure and ASK()
def _messages_for_ai():
"""History view sent to the model, honoring INCLUDE_EMBEDDING."""
if INCLUDE_EMBEDDING:
return history
return [
m for m in history
if not (
m.get("role") == "system"
and LIVE_CONTEXT_MARKER in m.get("content", "")
)
]
def _fmt_flag(v: bool) -> str:
return f"{GREEN}on{RESET}" if v else f"{CINNAMON}off{RESET}"
def show_flags():
print(f"\n{LATTE}AI context flags{RESET} {DIM}{STEAM}(FLAGS() <name> on|off){RESET}")
print(f" {CREAM}repeat{RESET} {_fmt_flag(REPEAT_EMBEDDING)}"
f" {DIM}{STEAM}— re-run embeds every AI call{RESET}")
print(f" {CREAM}embed{RESET} {_fmt_flag(INCLUDE_EMBEDDING)}"
f" {DIM}{STEAM}— include LIVE CONTEXT in model prompt{RESET}")
print(f" {CREAM}exitcode{RESET} {_fmt_flag(INCLUDE_EXIT_CODE)}"
f" {DIM}{STEAM}— include exit code on failures{RESET}")
print()
def set_flag(name: str, value: bool) -> bool:
global REPEAT_EMBEDDING, INCLUDE_EMBEDDING, INCLUDE_EXIT_CODE
key = name.strip().lower()
aliases = {
"repeat": "repeat",
"repeat_embedding": "repeat",
"embedding_repeat": "repeat",
"embed": "embed",
"embedding": "embed",
"include_embedding": "embed",
"include": "embed",
"exitcode": "exitcode",
"exit_code": "exitcode",
"exit": "exitcode",
"include_exit_code": "exitcode",
}
canon = aliases.get(key)
if canon == "repeat":
REPEAT_EMBEDDING = value
elif canon == "embed":
INCLUDE_EMBEDDING = value
elif canon == "exitcode":
INCLUDE_EXIT_CODE = value
else:
return False
return True
def handle_flags(args: list[str]):
if not args:
show_flags()
return
if len(args) == 1 and args[0].lower() in ("all", "show", "list", "status"):
show_flags()
return
if len(args) == 2 and args[0].lower() == "all":
val = args[1].lower()
if val not in ("on", "off", "1", "0", "true", "false"):
print(f"{STEAM}{DIM}Usage: FLAGS() all on|off{RESET}")
return
on = val in ("on", "1", "true")
set_flag("repeat", on)
set_flag("embed", on)
set_flag("exitcode", on)
show_flags()
return
if len(args) != 2:
print(f"{STEAM}{DIM}Usage: FLAGS() | FLAGS() repeat|embed|exitcode on|off | FLAGS() all on|off{RESET}")
return
name, raw = args[0], args[1].lower()
if raw not in ("on", "off", "1", "0", "true", "false"):
print(f"{STEAM}{DIM}Value must be on|off{RESET}")
return
if not set_flag(name, raw in ("on", "1", "true")):
print(f"{RED}[ERROR] Unknown flag: {name}{RESET} "
f"{DIM}{STEAM}(repeat | embed | exitcode){RESET}")
return
show_flags()
def invoke_ai(user_text: str, *, refresh: bool | None = None):
"""Send user_text to the model (with live embeds), stream reply, optional run."""
global history, current_dir, always_execute
risk_counter = 0
flagged_lines = []
# Decision markers: include embedding? repeat (refresh) embedding?
do_include = INCLUDE_EMBEDDING
if refresh is None:
do_refresh = do_include and REPEAT_EMBEDDING
else:
do_refresh = bool(refresh) and do_include
if do_include and do_refresh:
try:
n = refresh_live_context()
if n:
print(f"{DIM}{STEAM}Live context refreshed ({n} embed item(s)).{RESET}")
except NameError:
pass
except Exception as e:
print(f"{STEAM}{DIM}Live context refresh skipped: {e}{RESET}")
elif do_include and not do_refresh:
# Keep cached LIVE CONTEXT if present; bootstrap once if missing
has_live = any(
m.get("role") == "system" and LIVE_CONTEXT_MARKER in m.get("content", "")
for m in history
)
if not has_live:
try:
n = refresh_live_context()
if n:
print(f"{DIM}{STEAM}Live context loaded once ({n} embed item(s)).{RESET}")
except Exception as e:
print(f"{STEAM}{DIM}Live context load skipped: {e}{RESET}")
else:
print(f"{DIM}{STEAM}Live context reused (repeat=off).{RESET}")
else:
print(f"{DIM}{STEAM}Embeddings omitted (embed=off).{RESET}")
_trim_history()
history.append({"role": "user", "content": user_text})
try:
start_time = time.time()
full_response, flagged_lines, risk_counter = stream_response(
ai_response(_messages_for_ai()), keywords=keywords
)
elapsed = time.time() - start_time
bash_blocks = extract_bash_blocks(full_response)
_write_temp_script(bash_blocks)
history.append({"role": "assistant", "content": full_response})
except KeyboardInterrupt:
print(f"\n{DIM}{STEAM}Cancelled.{RESET}")
return
except (subprocess.CalledProcessError, RuntimeError, requests.RequestException, Exception) as e:
print(f"{RED}[ERROR] AI backend: {e}{RESET}")
return
if not TEMP_SCRIPT.exists():
print(f"{RED}[ERROR] No AI response generated.{RESET}")
return
if not bash_blocks:
print(f"\n{LATTE}Done ({elapsed:.3f}s) {DIM}{STEAM}(no bash block to run){RESET}")
return
if risk_counter:
print(f"\n{CARAMEL}Suggestion ready ({elapsed:.3f}s) "
f"{CINNAMON}⚠ {risk_counter} risky line(s):{RESET}")
print(f"{CINNAMON}" + "\n".join(flagged_lines) + RESET)
print(f"{DIM}{STEAM}Keyword scan is a convenience aid — not a security guarantee.{RESET}")
else:
print(f"\n{LATTE}Suggestion ready ({elapsed:.3f}s){RESET}")
execute_now = False
capture_run = False
n_blocks = len(bash_blocks)
# High-risk always requires an explicit confirm (FIX.md)
force_confirm = risk_counter >= 1
if n_blocks > 1:
print(f"{DIM}{STEAM}{n_blocks} bash blocks — pick one by number:{RESET}")
for i, b in enumerate(bash_blocks, 1):
first = next((ln.strip() for ln in b.splitlines() if ln.strip()), "")
print(f" {CREAM}[{i}]{RESET} {DIM}{STEAM}{first[:72]}{RESET}")
def _menu_hint() -> str:
opts = "[y] yes [n] no"
if not force_confirm:
opts += " [a] always"
opts += " [c] copy(no run) [v] view(no run) [t] run+capture → AI"
if n_blocks > 1:
opts += f" [1-{n_blocks}] one block"
return opts
if always_execute and not force_confirm and ALLOW_SESSION_AUTORUN:
execute_now = True
print(f"{DIM}{STEAM}Auto-run (session): executing without prompt.{RESET}")
else:
print()
while True:
try:
tag = f"{CINNAMON}HIGH-RISK {RESET}" if force_confirm else ""
choice = input(
f" {tag}{CREAM}Run it?{RESET} {DIM}{_menu_hint()}{RESET} › "
).strip().lower()
print()
except KeyboardInterrupt:
print(f"\n{DIM}{STEAM}Cancelled.{RESET}")
TEMP_SCRIPT.unlink(missing_ok=True)
return
if _is_escape(choice):
_print_do_sentence("\n".join(bash_blocks))
TEMP_SCRIPT.unlink(missing_ok=True)
TEMP_ERROR_LOG.unlink(missing_ok=True)
return
if choice == "v":
script_txt = TEMP_SCRIPT.read_text(errors="replace").rstrip()
for ln in script_txt.splitlines():
sys.stdout.write(f" {STEAM}{DIM}| {ln}{RESET}\n")
sys.stdout.flush()
continue