summaryrefslogtreecommitdiff
path: root/timelord/core/process.py
blob: b708c85faa0bea59f2b352e4b0bb067f33b6299f (plain)
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
"""
Process Execution Engine: Interactive Subshell warp and concurrent command execution.
"""

import os
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional

from timelord.core.engine import ChronoEngine
from timelord.core.multiverse import MultiverseManager
from timelord.ui.theme import console


class ProcessRunner:
    def __init__(self, engine: ChronoEngine):
        self.engine = engine
        self.multiverse = MultiverseManager(engine)

    def enter_universe_shell(self, universe_name: str) -> int:
        """
        Launches an interactive subshell inside the parallel universe
        with a customized shell prompt and temporal environment variables.
        """
        universe = self.multiverse.get_universe(universe_name)
        if not universe:
            raise ValueError(f"Universe '{universe_name}' not found.")

        universe_dir = Path(universe["path"])
        if not universe_dir.is_dir():
            raise FileNotFoundError(f"Universe directory missing: {universe_dir}")

        shell = os.environ.get("SHELL", "/bin/zsh")
        user_env = os.environ.copy()

        # Inject temporal context
        user_env["TIMELORD_UNIVERSE"] = universe_name
        user_env["TIMELORD_PRIME_PATH"] = str(self.engine.project_root)
        user_env["TIMELORD_IS_PARALLEL"] = "1"

        if universe.get("port_offset"):
            user_env["TIMELORD_PORT_OFFSET"] = str(universe["port_offset"])

        # Styled prompt
        custom_prompt = f"🌌 [TIMELORD: {universe_name}] % "
        if "zsh" in shell:
            user_env["PROMPT"] = f"%F{{magenta}}🌌 [TIMELORD: {universe_name}]%f %1~ %# "
        elif "bash" in shell:
            user_env["PS1"] = f"\\[\\033[1;35m\\]🌌 [TIMELORD: {universe_name}]\\[\\033[0m\\] \\W \\$ "

        console.print(
            f"\n[bold magenta]⚡ WARPING INTO PARALLEL UNIVERSE: [bold white]{universe_name}[/bold white][/bold magenta]"
        )
        console.print(f"[dim]Working directory: {universe_dir}[/dim]")
        if universe.get("port_offset"):
            console.print(f"[yellow]Port offset active: +{universe['port_offset']}[/yellow]")
        console.print("[dim]Type [bold white]exit[/bold white] or press [bold white]Ctrl+D[/bold white] to return to Prime.[/dim]\n")

        # Launch subshell
        try:
            res = subprocess.run([shell, "-i"], cwd=str(universe_dir), env=user_env)
            console.print(
                f"\n[bold bright_green]✔ Returned to Prime Continuum ({self.engine.get_config().get('prime_timeline_name', 'Earth-616')}).[/bold bright_green]\n"
            )
            return res.returncode
        except Exception as e:
            console.print(f"[bold red]Temporal warp disrupted:[/bold red] {e}")
            return 1

    def run_in_universe(
        self,
        universe_name: str,
        command: List[str],
    ) -> int:
        """Runs a one-off command inside the parallel universe."""
        universe = self.multiverse.get_universe(universe_name)
        if not universe:
            raise ValueError(f"Universe '{universe_name}' not found.")

        universe_dir = Path(universe["path"])
        if not universe_dir.is_dir():
            raise FileNotFoundError(f"Universe directory missing: {universe_dir}")

        user_env = os.environ.copy()
        user_env["TIMELORD_UNIVERSE"] = universe_name
        user_env["TIMELORD_PRIME_PATH"] = str(self.engine.project_root)
        user_env["TIMELORD_IS_PARALLEL"] = "1"
        if universe.get("port_offset"):
            user_env["TIMELORD_PORT_OFFSET"] = str(universe["port_offset"])

        try:
            res = subprocess.run(
                command,
                cwd=str(universe_dir),
                env=user_env,
                text=True,
            )
            return res.returncode
        except Exception as e:
            console.print(f"[bold red]Command failed to execute in universe {universe_name}:[/bold red] {e}")
            return 1