Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions loopx/control_plane/agents/workspace_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ def _is_same_or_child_path(path: Path, root: Path) -> bool:


def _git_command_output(path: Path, *args: str) -> str | None:
from ...extensions.process_runtime import no_console_creationflags

try:
result = subprocess.run(
["git", "-C", str(path), *args],
Expand All @@ -47,6 +49,7 @@ def _git_command_output(path: Path, *args: str) -> str | None:
stderr=subprocess.DEVNULL,
text=True, encoding="utf-8", errors="replace",
timeout=1.5,
creationflags=no_console_creationflags(),
)
except (OSError, subprocess.TimeoutExpired):
return None
Expand Down Expand Up @@ -134,11 +137,14 @@ def _capture_local_goal_workspace(

def _git_origin_is_absent(path: Path) -> bool:
"""Only Git's missing-key result permits local fallback; errors do not."""
from ...extensions.process_runtime import no_console_creationflags

try:
result = subprocess.run(
["git", "-C", str(path), "config", "--get", "remote.origin.url"],
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
timeout=1.5,
creationflags=no_console_creationflags(),
)
except (OSError, subprocess.TimeoutExpired):
return False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export class ResearchTerminalEvidenceHost {
}
this.child = spawn(python, ["-m", "loopx.capabilities.explore.research_snapshot_host"], {
stdio: ["pipe", "pipe", "pipe"], env: {...process.env, PYTHONPATH: fileURLToPath(new URL("../../../", import.meta.url))},
windowsHide: true,
});
this.exited = new Promise(resolve => this.child!.once("close", () => resolve()));
this.child.on("error", () => {}); this.child.stdin.on("error", () => {}); this.child.stderr.resume();
Expand Down
2 changes: 1 addition & 1 deletion loopx/control_plane/coordination/nokv_jsonl_transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export class NoKVJsonLinesTransport implements NoKVBlobTransport {
positiveSafeInteger(this.requestTimeoutMs, "NoKV helper request timeout");
positiveSafeInteger(this.maxResponseBytes, "NoKV helper max response bytes");
const factory = options.process_factory ?? ((command, args, spawnOptions) =>
spawn(command, args, { ...spawnOptions, stdio: ["pipe", "pipe", "pipe"] }));
spawn(command, args, { ...spawnOptions, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }));
const [command, ...args] = options.argv;
try {
this.child = factory(command!, args, {
Expand Down
1 change: 1 addition & 0 deletions loopx/control_plane/coordination/shadow_drain_files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export class DrainKernelLockHost {
if (!this.child) {
this.child = spawn(this.python, ["-m", "loopx.control_plane.coordination.shadow_lock_host"], {
stdio: ["pipe", "pipe", "pipe"], env: {...process.env, PYTHONPATH: fileURLToPath(new URL("../../../", import.meta.url))},
windowsHide: true,
});
this.exited = new Promise(resolve => this.child!.once("close", () => resolve()));
this.child.on("error", () => {}); // The closed reply stream reports an unavailable host.
Expand Down
4 changes: 4 additions & 0 deletions loopx/control_plane/effect_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1604,6 +1604,9 @@ def _start_runtime(*, fingerprint: str, info_path: Path) -> _RuntimeInfo:
# is an unlinked temporary file, so it cannot deadlock the child on a
# full pipe and it leaves no stale path behind.
with tempfile.TemporaryFile() as startup_stderr:
# Keep cold import paths (loopx.contract) free of the process transport.
from ..extensions.process_runtime import no_console_creationflags

try:
process = subprocess.Popen(
_runtime_command(
Expand All @@ -1613,6 +1616,7 @@ def _start_runtime(*, fingerprint: str, info_path: Path) -> _RuntimeInfo:
),
env=environment, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=startup_stderr, start_new_session=os.name != "nt", close_fds=True,
creationflags=no_console_creationflags(),
# The host outlives the command that started it. On Windows
# a live child whose working directory is the caller's
# directory keeps that directory (and its ancestors) from
Expand Down
3 changes: 3 additions & 0 deletions loopx/control_plane/goals/planning_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,8 @@ def inspect_state(self) -> PlanningFrontierSnapshot:
}

def _call(self, *args: str) -> dict[str, object]:
from ...extensions.process_runtime import no_console_creationflags

process = subprocess.run(
[*self.cli, *args],
cwd=self.cwd,
Expand All @@ -709,6 +711,7 @@ def _call(self, *args: str) -> dict[str, object]:
encoding="utf-8",
capture_output=True,
timeout=120,
creationflags=no_console_creationflags(),
)
try:
result = json.loads(process.stdout)
Expand Down
5 changes: 4 additions & 1 deletion loopx/control_plane/heartbeat/installed_prompt_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,11 +187,14 @@ def update_with_prompts(payload: dict, *, registry: Path, runtime_root: str | No
command += ["--runtime-root", runtime_root]
command += ["automation-prompts", "sync-installed", "--codex-home", str(home),
"--plan-file", str(plan_file), "--execute"]
from loopx.extensions.process_runtime import no_console_creationflags

try:
# Do not accidentally import a checkout through the parent's PYTHONPATH.
env = {key: value for key, value in os.environ.items() if key != "PYTHONPATH"}
result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace", env=env,
timeout=timeout_seconds, cwd=directory)
timeout=timeout_seconds, cwd=directory,
creationflags=no_console_creationflags())
report = json.loads(result.stdout)
if not isinstance(report, dict) or "results" not in report:
raise ValueError("new runtime returned no prompt migration result")
Expand Down
3 changes: 3 additions & 0 deletions loopx/control_plane/quota/scheduler_ack.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,8 @@ def _run_native_followup(
/ "heartbeat_followup_cli.ts"
),
]
from ...extensions.process_runtime import no_console_creationflags

try:
completed = subprocess.run(
command,
Expand All @@ -234,6 +236,7 @@ def _run_native_followup(
text=True,
encoding="utf-8",
timeout=30,
creationflags=no_console_creationflags(),
)
except (OSError, subprocess.TimeoutExpired) as exc:
raise RuntimeError("native scheduler follow-up command failed") from exc
Expand Down
6 changes: 6 additions & 0 deletions loopx/control_plane/runtime/node_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ def recommended_action(self) -> str | None:


def probe_node(*, timeout: float = STARTUP_READY_TIMEOUT_SECONDS) -> NodeProbe:
# Pure callers import this module cold; the process transport stays
# unselected until a probe actually launches a child (see
# tests/test_process_runtime_loading.py).
from ...extensions.process_runtime import no_console_creationflags

executable = shutil.which("node")
if executable is None:
return NodeProbe(NodeProbeOutcome.MISSING)
Expand All @@ -121,6 +126,7 @@ def probe_node(*, timeout: float = STARTUP_READY_TIMEOUT_SECONDS) -> NodeProbe:
completed = subprocess.run(
[executable, "--version"], check=False, capture_output=True,
text=True, encoding="utf-8", errors="replace", timeout=timeout,
creationflags=no_console_creationflags(),
)
except subprocess.TimeoutExpired:
return NodeProbe(NodeProbeOutcome.TIMED_OUT, executable)
Expand Down
3 changes: 2 additions & 1 deletion loopx/control_plane/runtime/validation_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

# Keep the historical exports and caller patch points, but select the OS
# transport only when used. Decisions and deadlines remain with the caller.
_PROCESS_RUNTIME_EXPORTS = ("terminate_process_tree",)
_PROCESS_RUNTIME_EXPORTS = ("no_console_creationflags", "terminate_process_tree")


def __getattr__(name: str) -> Any:
Expand Down Expand Up @@ -195,6 +195,7 @@ def _direct_validation(argv: list[str], workspace: Path, timeout_seconds: int) -
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
start_new_session=os.name == "posix",
creationflags=_export("no_console_creationflags")(),
) as process:
try:
# Output is transient and never part of the public receipt.
Expand Down
5 changes: 4 additions & 1 deletion loopx/control_plane/state_recovery_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,16 @@ def _runtime(method: str, request: dict[str, Any]) -> dict[str, Any]:


def _audit_owners(request: dict[str, Any]) -> dict[str, Any]:
from ..extensions.process_runtime import no_console_creationflags

command = [_node_executable(), "--no-warnings", "--max-old-space-size=512",
"--experimental-sqlite", "--experimental-strip-types",
*node_typescript_flags(),
str(Path(__file__).with_name("state_recovery_worker.ts"))]
try:
completed = subprocess.run(command, input=json.dumps(request), text=True, encoding="utf-8",
capture_output=True, timeout=_OWNER_TIMEOUT_SECONDS, check=False)
capture_output=True, timeout=_OWNER_TIMEOUT_SECONDS, check=False,
creationflags=no_console_creationflags())
except subprocess.TimeoutExpired as exc:
# subprocess.run kills and waits for this child only, never the daemon.
raise StateRecoveryError("recovery_owner_timeout") from exc
Expand Down
5 changes: 4 additions & 1 deletion loopx/control_plane/status/goal_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,11 @@ def _text(value, field, limit=4096):


def _run(argv, *, env=None):
from ...extensions.process_runtime import no_console_creationflags

# Diagnostics can contain private paths; callers must not return stderr.
result = subprocess.run(argv, env=env, capture_output=True, check=True, timeout=25)
result = subprocess.run(argv, env=env, capture_output=True, check=True, timeout=25,
creationflags=no_console_creationflags())
if len(result.stdout) > _MAX_BYTES:
raise ValueError("Source read exceeds the display limit")
return result.stdout.decode("utf-8")
Expand Down
2 changes: 2 additions & 0 deletions loopx/control_plane/todos/completion_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def _workspace_failure(label: str, *, status: str, summary: str) -> dict[str, An

def _git_workspace_is_clean(path: Path) -> bool | None:
"""Return clean/dirty without exposing local paths or command output."""
from ...extensions.process_runtime import no_console_creationflags

try:
result = subprocess.run(
Expand All @@ -106,6 +107,7 @@ def _git_workspace_is_clean(path: Path) -> bool | None:
stderr=subprocess.DEVNULL,
text=True, encoding="utf-8", errors="replace",
timeout=2,
creationflags=no_console_creationflags(),
)
except (OSError, subprocess.TimeoutExpired):
return None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,13 @@ def compact_execution_preparation_request(
def _default_runner(
command: Sequence[str], *, cwd: Path, timeout: float,
) -> subprocess.CompletedProcess[str]:
from ...extensions.process_runtime import no_console_creationflags

completed = subprocess.run(
list(command), cwd=str(cwd), capture_output=True, text=False,
timeout=timeout,
check=False,
creationflags=no_console_creationflags(),
)
# The receipt is protocol data and must decode exactly. Stderr is only
# diagnostic output from the launcher; an unrelated invalid byte there
Expand Down
3 changes: 3 additions & 0 deletions loopx/control_plane/turn_driver/codex_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ def spawn(
) -> StdioNativeGoalTransport:
if not command:
raise ValueError("command must be non-empty")
from ...extensions.process_runtime import no_console_creationflags

process = subprocess.Popen(
list(command),
cwd=cwd,
Expand All @@ -82,6 +84,7 @@ def spawn(
text=True,
encoding="utf-8",
bufsize=1,
creationflags=no_console_creationflags(),
)
return cls(process, response_timeout_sec=response_timeout_sec)

Expand Down
3 changes: 3 additions & 0 deletions loopx/control_plane/turn_driver/command_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ def validate(
_plan: Mapping[str, Any],
result: Mapping[str, Any],
) -> Mapping[str, Any]:
from ...extensions.process_runtime import no_console_creationflags

try:
completed = subprocess.run(
normalized,
Expand All @@ -137,6 +139,7 @@ def validate(
stderr=subprocess.DEVNULL,
timeout=max(1.0, timeout_seconds),
check=False,
creationflags=no_console_creationflags(),
)
except (OSError, subprocess.TimeoutExpired):
return {
Expand Down
3 changes: 3 additions & 0 deletions loopx/control_plane/turn_driver/host_process_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,8 @@ def run_host_process(
launch_deadline = time.monotonic() + launch_budget if launch_guard is not None else None
launch_arguments = (["--guarded-launch", str((time.time() + launch_budget) * 1000)]
if launch_guard is not None else [])
from ...extensions.process_runtime import no_console_creationflags

with ExitStack() as containment:
windows_job = None
if sys.platform == "win32":
Expand All @@ -360,6 +362,7 @@ def run_host_process(
errors="strict",
start_new_session=True,
env=bridge_environment,
creationflags=no_console_creationflags(),
)
assert proc.stdin is not None and proc.stdout is not None
result: dict[str, Any] | None = None
Expand Down
4 changes: 3 additions & 1 deletion loopx/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ def main(argv: list[str] | None = None) -> int:
# Windows execv does not propagate the replaced process's status.
# Wait for the typed owner so rejected writes remain CLI failures.
import subprocess
return subprocess.call(native_argv)

from .extensions.process_runtime import no_console_creationflags
return subprocess.call(native_argv, creationflags=no_console_creationflags())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 用户在附有控制台的 Windows PowerShell 或 cmd 中直接执行生成的 scheduler-ack-current 或 scheduler-fail-current。这个启动点无条件应用 CREATE_NO_WINDOW,也没有转发 stdout。Win32 由此去掉子进程继承的控制台,调度器写入 stdout 的回执可能从终端消失,父进程仍只接收退出码。保留前台调度分支的控制台继承,仅在无控制台宿主使用抑制参数,或显式转发可读的 stdout/stderr。补一项 Windows 前台回执和无控制台重定向回执对照。 Win32 进程创建语义

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed on b35624d7b. The flag is no longer passed to an attached parent: no_console_creationflags() returns CREATE_NO_WINDOW only when the parent has no console, so the entrypoint.py:155 call keeps creationflags == 0 there and the scheduler child inherits the console its receipt is printed on. The fix, the host-agnostic tests, the unrun-on-Windows disclosure and a two-line check for both branches are in my comment above.

os.execv(native_argv[0], native_argv)

from .cli_runtime import main as runtime_main
Expand Down
50 changes: 50 additions & 0 deletions loopx/extensions/process_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,56 @@
_PROCESS_GROUP_STOP_TIMEOUT_SECONDS = 1.0


def _console_attached(kernel32: Any) -> bool:
"""Report whether the calling process owns a Win32 console.

Either query succeeding means a console is attached. A process without one
fails both, and treating any success as attached keeps the answer on the
safe side: the only cost of a wrong "attached" is an unsuppressed window.
"""
return bool(kernel32.GetConsoleCP()) or bool(kernel32.GetConsoleWindow())


def _parent_has_console() -> bool:
"""Report whether this process owns a console; an unanswerable query is yes."""
try:
import ctypes

kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.GetConsoleCP.restype = ctypes.c_uint
kernel32.GetConsoleWindow.restype = ctypes.c_void_p
except (AttributeError, ImportError, OSError):
# The console query only refines the spawn options, so a host that
# cannot answer it keeps the child's behavior exactly as it was.
return True
return _console_attached(kernel32)


def no_console_creationflags() -> int:
"""Creation flags that stop a console-subsystem child from opening a console.

Windows allocates a visible console host window for every console-subsystem
child of a parent that has no console, so short-lived helpers such as node,
python or git flash a black window on console-less hosts. CREATE_NO_WINDOW
suppresses that allocation without touching handle inheritance or stdio.

The flag is returned only when this process has no console, because that is
the only case in which Windows would allocate a new one. A child of a
process attached to a console inherits that console and never opens a
window; passing the flag there would instead detach the child from the
console its output is being read from, and the child's writes to an
inherited stdout would vanish without an error.

Every other platform reports 0, which is subprocess's default and leaves
behavior unchanged.
"""
if os.name != "nt":
return 0
if _parent_has_console():
return 0
return int(getattr(subprocess, "CREATE_NO_WINDOW", 0))


def write_process_stdin_before_deadline(
process: subprocess.Popen[str], text: str, *, deadline: float,
cancel_and_reap: Callable[[], None],
Expand Down
2 changes: 2 additions & 0 deletions loopx/hosts/pi/loopx-goal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ async function runLoopxCli(args: string[], directory: string): Promise<string> {
cwd: directory,
timeout: LOOPX_CLI_TIMEOUT_MS,
maxBuffer: 8 * 1024 * 1024,
windowsHide: true,
});
return stdout;
}
Expand Down Expand Up @@ -208,6 +209,7 @@ async function runLoopxTaskLeaseCli(
cwd: directory,
timeout: LOOPX_CLI_TIMEOUT_MS,
maxBuffer: 8 * 1024 * 1024,
windowsHide: true,
});
return { stdout, returncode: 0 };
} catch (error) {
Expand Down
4 changes: 4 additions & 0 deletions loopx/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,9 @@ def unavailable() -> dict[str, Any]:
}

def run_git(*args: str, cwd: Path = probe_dir) -> subprocess.CompletedProcess[str] | None:
# Select the OS transport only when a probe actually launches a child.
from .extensions.process_runtime import no_console_creationflags

# A probe that times out must retire everything it started. `run` kills
# only the leader, so a Git that fanned out into a helper, a hook or a
# remote would outlive the deadline on every later status read.
Expand All @@ -159,6 +162,7 @@ def run_git(*args: str, cwd: Path = probe_dir) -> subprocess.CompletedProcess[st
start_new_session=os.name == "posix",
creationflags=(
int(getattr(subprocess, "CREATE_NEW_PROCESS_GROUP"))
| no_console_creationflags()
if os.name == "nt" else 0
),
)
Expand Down
Loading
Loading