Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(agent-core): run command jobs on Windows (#2479)

Call White2993c2557a46
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 9d552c224..ac68ca140 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -816,3 +816,13 @@ jobs:
- name: Verify Vibey's tool lines
run: python -m pytest -q -ra tests/test_vibey_agent.py -k relative_tool_path
+
+ # The job host's Windows backend: a job object instead of a process
+ # group, and job files replaced and read in a way that cannot collide.
+ - name: Verify the job host
+ run: python -m pytest -q -ra tests/agent_core/tools/test_jobs_windows.py
+
+ # Its job object is the one the watch worker uses; no other job runs
+ # this file on Windows.
+ - name: Verify the watch worker's job object
+ run: python -m pytest -q -ra tests/test_watch_worker.py
diff --git a/core/agent_core/tools/job_wrapper.py b/core/agent_core/tools/job_wrapper.py
index 81ffee9f4..ce5345468 100644
--- a/core/agent_core/tools/job_wrapper.py
+++ b/core/agent_core/tools/job_wrapper.py
@@ -1,13 +1,21 @@
"""The process that runs one job's command (``LocalJobHost``'s ``pipe`` backend).
-Run as ``python -I -S job_wrapper.py avibe-job <job_dir> <shell> <command>
+Run as ``python -I -S -B job_wrapper.py avibe-job <job_dir> <shell> <command>
<decision_timeout_s> <head_cap> <tail_cap> <deadline_epoch_s or ->`` in a new
session, so its pid is the job's process group. Standard library only: ``-S``
skips site-packages.
+On Windows the tree is held by a job object instead of a process group: the
+wrapper creates ``Local\\avibe-job-<job_id>`` with ``KILL_ON_JOB_CLOSE`` and
+joins it before it writes ``pid``, so every process the command starts is in it,
+and none outlives the wrapper (``windows_job.py``). Files are replaced with
+POSIX semantics (``windows_files.py``), so a host reading ``tail.log`` never
+makes its replacement fail.
+
1. Write ``pid`` (temporary file, rename).
2. Wait for ``decision``, at most ``decision_timeout_s``; on timeout, decide
- ``abandon`` itself through the same exclusive ``link(2)`` the host uses.
+ ``abandon`` itself through the same exclusive ``link(2)`` the host uses (on
+ Windows a rename, which never replaces there).
3. Only on ``go``: run ``<shell> -c <command>`` with stdin closed and stdout and
stderr into one pipe.
4. Keep the output bounded on disk: the first ``head_cap`` bytes are appended
@@ -22,7 +30,11 @@ skips site-packages.
a catchable signal reaches the wrapper alone (``pkill -f python``), write
``stopped`` (``timeout``, ``wrapper_error``, or ``killed``) and end the whole
process group: SIGTERM, then SIGKILL after 3 s. The wrapper decides timeout
- versus exit, and it looks at the shell first.
+ versus exit, and it looks at the shell first. On Windows the job object ends
+ at once, with no graceful phase.
+7. Windows only: once the shell has exited and its output is closed, stay
+ while processes it started still run. They are in the job, which ends with
+ its last handle, the wrapper's; on POSIX they run on in the process group.
Every wait is bounded or watches the deadline: the decision wait (30 s), the
check just before the shell is spawned, the read loop, the wait after the
@@ -39,8 +51,9 @@ import subprocess
import sys
import time
import traceback
-from typing import Optional
+from typing import Any, Optional
+_WINDOWS = os.name == "nt"
_SNAPSHOT_INTERVAL_S = 0.25
_DRAIN_LIMIT_S = 0.5
_TERMINATE_GRACE_S = 3.0
@@ -49,29 +62,54 @@ _TERMINATE_GRACE_S = 3.0
# "killed" instead. Python already ignores SIGPIPE and SIGXFSZ; SIGKILL cannot be caught.
_STOP_SIGNALS = tuple(
getattr(signal, name)
- for name in "SIGTERM SIGHUP SIGINT SIGQUIT SIGUSR1 SIGUSR2 SIGALRM SIGVTALRM SIGPROF SIGXCPU SIGPWR SIGIO".split()
+ for name in (
+ "SIGTERM SIGHUP SIGINT SIGQUIT SIGUSR1 SIGUSR2 SIGALRM SIGVTALRM SIGPROF SIGXCPU SIGPWR SIGIO SIGBREAK"
+ ).split()
if hasattr(signal, name)
)
+#: Polling the output pipe on Windows, where ``select`` takes only sockets.
+_PIPE_POLL_S = 0.01
+
+
+def _load_beside(name: str) -> Any:
+ """A module beside this file, by its path: ``-I -S`` leaves the package and site-packages off ``sys.path``."""
+ import importlib.util
+
+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), f"{name}.py")
+ spec = importlib.util.spec_from_file_location(f"avibe_{name}", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+_job_objects = _load_beside("windows_job") if _WINDOWS else None
+_files = _load_beside("windows_files") if _WINDOWS else None
+#: Windows: the handle of the job object that holds this wrapper and its command's tree.
+_job: Optional[int] = None
def _write_atomic(path: str, data: bytes) -> None:
tmp = f"{path}.{os.getpid()}.tmp"
with open(tmp, "wb") as handle:
handle.write(data)
- os.replace(tmp, path)
+ (_files.replace if _WINDOWS else os.replace)(tmp, path)
def _create_once(path: str, value: str) -> None:
- """Create ``path`` holding ``value`` unless it exists: ``link(2)`` of a written temp file, as the host does."""
+ """Create ``path`` holding ``value`` unless it exists: ``link(2)`` of a written temp file, as the host does.
+
+ On Windows a rename, which never replaces there, and works on volumes without hard links (FAT).
+ """
tmp = f"{path}.{value}.{os.getpid()}.tmp"
with open(tmp, "w") as handle:
handle.write(f"{value}\n")
try:
- os.link(tmp, path)
+ (os.rename if _WINDOWS else os.link)(tmp, path)
except FileExistsError:
pass
finally:
- os.unlink(tmp)
+ with contextlib.suppress(FileNotFoundError):
+ os.unlink(tmp)
def _wait_for_decision(job_dir: str, timeout_s: float) -> str:
@@ -84,13 +122,17 @@ def _wait_for_decision(job_dir: str, timeout_s: float) -> str:
break
time.sleep(delay)
delay = min(delay * 2, 0.05)
- with open(decision) as handle:
- return handle.read(64).strip()
+ # With delete sharing, as Avibe reads every job file: on Windows the host creates ``decision`` by a rename,
+ # whose handle asks for delete until it closes, and a plain ``open`` meanwhile is a sharing violation.
+ fd = _files.open_for_reading(decision) if _WINDOWS else os.open(decision, os.O_RDONLY)
+ with os.fdopen(fd, "rb") as handle:
+ return handle.read(64).decode("ascii", "replace").strip()
class _BoundedLog:
def __init__(self, job_dir: str, head_cap: int, tail_cap: int) -> None:
- self._fd = os.open(os.path.join(job_dir, "output.log"), os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
+ flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_BINARY", 0)
+ self._fd = os.open(os.path.join(job_dir, "output.log"), flags, 0o600)
self._tail_path = os.path.join(job_dir, "tail.log")
self._head_cap = head_cap
self._tail_cap = tail_cap
@@ -119,11 +161,43 @@ class _BoundedLog:
if not self._dirty or (not force and now - self._last_snapshot < _SNAPSHOT_INTERVAL_S):
return
kept = bytes(self._tail[-self._tail_cap :])
- _write_atomic(self._tail_path, b"[output from byte %d]\n" % (self._total - len(kept)) + kept)
+ data = b"[output from byte %d]\n" % (self._total - len(kept)) + kept
+ try:
+ _write_atomic(self._tail_path, data)
+ except PermissionError:
+ # Windows: another program holds tail.log open without sharing delete (an editor, ``Get-Content
+ # -Wait``). The tail is still here, so a periodic snapshot leaves it to the next one. The last one
+ # cannot wait: it goes into the file itself, which such a program shares for writing; one that shares
+ # neither keeps the previous tail while it holds the file, and the command's exit still stands.
+ if not _WINDOWS:
+ raise
+ if not (force and _rewrite_in_place(self._tail_path, data)):
+ self._last_snapshot = now
+ return
self._dirty = False
self._last_snapshot = now
+def _rewrite_in_place(path: str, data: bytes) -> bool:
+ """Windows: write ``data`` over the existing file ``path`` itself; whether its readers' sharing allowed it.
+
+ Not atomic: a reader in the middle of it may see part of each, so it stands in only for the last
+ snapshot, which cannot wait for the next.
+ """
+ try:
+ fd = os.open(path, os.O_WRONLY | os.O_BINARY)
+ except PermissionError:
+ return False
+ try:
+ view = memoryview(data)
+ while view:
+ view = view[os.write(fd, view) :]
+ os.ftruncate(fd, len(data))
+ finally:
+ os.close(fd)
+ return True
+
+
def _stop_group(job_dir: str, reason: str, proc: Optional[subprocess.Popen]) -> None:
"""Record why, then end the whole process group, this wrapper included; never returns.
@@ -136,6 +210,11 @@ def _stop_group(job_dir: str, reason: str, proc: Optional[subprocess.Popen]) ->
_create_once(os.path.join(job_dir, "stopped"), reason) # the first stopper's reason wins
except OSError:
pass # the kill matters more than the record
+ if _WINDOWS:
+ if _job is not None:
+ with contextlib.suppress(OSError):
+ _job_objects.terminate_job(_job) # every process of the job, this wrapper included
+ os._exit(1) # no job yet, or it could not be ended: its last handle closes with us (KILL_ON_JOB_CLOSE)
group = os.getpgrp()
with contextlib.suppress(OSError):
os.killpg(group, signal.SIGTERM)
@@ -145,6 +224,19 @@ def _stop_group(job_dir: str, reason: str, proc: Optional[subprocess.Popen]) ->
os.killpg(group, signal.SIGKILL)
+def _readable(fd: int, timeout_s: float) -> bool:
+ """Whether reading ``fd``, the command's output pipe, would not block, waiting at most ``timeout_s``."""
+ if not _WINDOWS:
+ return bool(select.select([fd], [], [], timeout_s)[0])
+ end = time.monotonic() + timeout_s
+ while not _job_objects.pipe_readable(fd):
+ remaining = end - time.monotonic()
+ if remaining <= 0:
+ return False
+ time.sleep(min(remaining, _PIPE_POLL_S))
+ return True
+
+
def _run(job_dir: str, proc: subprocess.Popen, log: _BoundedLog, deadline: Optional[float]) -> None:
fd = proc.stdout.fileno()
exit_written = False
@@ -163,8 +255,7 @@ def _run(job_dir: str, proc: subprocess.Popen, log: _BoundedLog, deadline: Optio
while not eof:
enforce_deadline()
- ready, _, _ = select.select([fd], [], [], 0.05)
- if ready:
+ if _readable(fd, 0.05):
chunk = os.read(fd, 65536)
if chunk:
log.write(chunk)
@@ -173,7 +264,7 @@ def _run(job_dir: str, proc: subprocess.Popen, log: _BoundedLog, deadline: Optio
if not exit_written and proc.poll() is not None:
# Everything the shell wrote is in the pipe by now; take it before reporting the exit.
drain_until = time.monotonic() + _DRAIN_LIMIT_S
- while not eof and time.monotonic() < drain_until and select.select([fd], [], [], 0)[0]:
+ while not eof and time.monotonic() < drain_until and _readable(fd, 0):
chunk = os.read(fd, 65536)
if chunk:
log.write(chunk)
@@ -192,6 +283,17 @@ def _run(job_dir: str, proc: subprocess.Popen, log: _BoundedLog, deadline: Optio
write_exit()
+def _stay_while_the_job_runs() -> None:
+ """Windows: keep the job object open while processes the command started still run in it.
+
+ The job ends with its last handle, this wrapper's, so a background process the command left running
+ would die with the wrapper. On POSIX it runs on in the process group, where ``kill`` still reaches it;
+ here the wrapper stays, so ``kill`` reaches it through the job.
+ """
+ while _job_objects.active_processes(_job) > 1:
+ time.sleep(_SNAPSHOT_INTERVAL_S)
+
+
def main(argv: list[str]) -> int:
if len(argv) != 9 or argv[1] != "avibe-job":
return 64
@@ -205,6 +307,11 @@ def main(argv: list[str]) -> int:
for signum in _STOP_SIGNALS:
signal.signal(signum, stop_on_signal)
+ if _WINDOWS:
+ global _job
+ # Before ``pid``: the host records the identity only of a wrapper that is in its job (J2). The host
+ # names it the same way (``jobs._job_object_name``).
+ _job = _job_objects.create_kill_on_close_job(f"avibe-job-{os.path.basename(job_dir)}")
_write_atomic(os.path.join(job_dir, "pid"), b"%d\n" % os.getpid())
if _wait_for_decision(job_dir, decision_timeout_s) != "go":
return 0
@@ -217,6 +324,8 @@ def main(argv: list[str]) -> int:
[shell, "-c", command], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
_run(job_dir, proc, log, deadline)
+ if _WINDOWS:
+ _stay_while_the_job_runs()
except BaseException:
# A wrapper that cannot follow its command (a full disk, a bug) must not leave it running unmanaged.
# The diagnostics may fail for the same reason (ENOSPC), so they can never stand in the way.
diff --git a/core/agent_core/tools/jobs.py b/core/agent_core/tools/jobs.py
index cd0f15343..77396de58 100644
--- a/core/agent_core/tools/jobs.py
+++ b/core/agent_core/tools/jobs.py
@@ -14,7 +14,8 @@ wrapper writes ``pid`` and waits for ``decision``; the host records the process
identity in ``meta.json`` (J2), then decides ``go``; the wrapper runs the
command only on ``go``, and decides ``abandon`` itself if no decision comes in
time. A decision is created exclusively, through ``link(2)`` of a written
-temporary file, so exactly one side decides and nobody reads it half-written.
+temporary file (on Windows a rename, which never replaces there), so exactly
+one side decides and nobody reads it half-written.
Recovery decides ``abandon`` for a job that has none; a missing or late
``pid`` proves nothing.
@@ -28,13 +29,21 @@ J3: ``meta.json.deadline_at`` is absolute. The wrapper enforces it itself, so
it holds while no host runs; ``wait`` and ``enforce_deadline`` are a second,
idempotent owner. Whoever kills records ``stopped`` first.
-POSIX only in v1.
+Windows: the tree is the wrapper's job object, ``Local\\avibe-job-<job_id>``,
+which the wrapper creates and joins before it writes ``pid`` and which ends its
+members when the wrapper's handle closes (``windows_job``). J2 then asks for a
+wrapper that is a member of that job instead of a group leader, and a kill
+terminates the job. Nothing outlives the wrapper, so a job whose wrapper is
+gone is gone. Job files are replaced with POSIX semantics and read shared for
+delete (``windows_files``): a reader of ``tail.log``, which the wrapper
+replaces a few times a second, would otherwise make the replace fail.
"""
from __future__ import annotations
import asyncio
import contextlib
+import io
import json
import logging
import os
@@ -51,6 +60,7 @@ from typing import Any, Awaitable, Callable, Mapping, Optional
import psutil
+from core.agent_core.tools import windows_files, windows_job
from core.agent_core.tools.base import CallInstance, JobStatus
from core.agent_core.tools.paths import os_reason, run_to_end
from core.process_isolation import (
@@ -91,6 +101,7 @@ STOP_KILLED = "killed"
#: The wrapper itself failed (a full disk, a bug) and stopped the command it could no longer follow.
STOP_WRAPPER_ERROR = "wrapper_error"
+_WINDOWS = os.name == "nt"
_WRAPPER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "job_wrapper.py")
#: How long past the deadline the host leaves a live wrapper to decide (its poll interval, its
#: 0.5 s drain, and margin) before stopping the job itself.
@@ -114,13 +125,28 @@ class JobHandOverUnavailable(RuntimeError):
"""This host has no Watch to hand a job to."""
-def default_shell() -> str:
- """Pi's choice: ``/bin/bash``, then ``bash`` on PATH, then ``sh``."""
+def default_shell() -> Optional[str]:
+ """Pi's choice: ``/bin/bash``, then ``bash`` on PATH, then ``sh``. None on Windows, which has no such shell."""
+ if _WINDOWS:
+ return None
if os.path.exists("/bin/bash"):
return "/bin/bash"
return shutil.which("bash") or "sh"
+def _job_object_name(job_id: str) -> str:
+ """The Windows job object of a job's tree; the wrapper creates it under the same name."""
+ return f"avibe-job-{job_id}"
+
+
+def _open_for_reading(path: str, *, binary: bool = False) -> Any:
+ """A job file, open for reading. On Windows it is shared for delete, so a writer can still replace it."""
+ if not _WINDOWS:
+ return open(path, "rb") if binary else open(path, encoding="utf-8", errors="replace")
+ handle = os.fdopen(windows_files.open_for_reading(path), "rb")
+ return handle if binary else io.TextIOWrapper(handle, encoding="utf-8", errors="replace")
+
+
def _iso(moment: datetime) -> str:
return moment.isoformat(timespec="milliseconds").replace("+00:00", "Z")
@@ -139,7 +165,7 @@ def _write_atomic(path: str, data: str) -> None:
tmp = f"{path}.{secrets.token_hex(4)}.tmp"
with open(tmp, "w", encoding="utf-8") as handle:
handle.write(data)
- os.replace(tmp, path)
+ (windows_files.replace if _WINDOWS else os.replace)(tmp, path)
def _meta_text(meta: Mapping[str, Any]) -> str:
@@ -160,7 +186,7 @@ def _read_text(path: str) -> Optional[str]:
"""A small state file (``pid``, ``decision``, ``exit``, ``stopped``), read in a bound: the job's
directory is one its command can write to."""
try:
- with open(path, encoding="utf-8", errors="replace") as handle:
+ with _open_for_reading(path) as handle:
return handle.read(_STATE_FILE_CHARS).strip()
except FileNotFoundError:
return None
@@ -217,7 +243,7 @@ class LocalJobHost:
"""The job's metadata. Read in a bound: the job's directory is one its command can write to, and a
file over the bound is refused as corrupt (``ValueError``), as unreadable JSON is."""
try:
- with open(self._path(job_id, "meta.json"), encoding="utf-8", errors="replace") as handle:
+ with _open_for_reading(self._path(job_id, "meta.json")) as handle:
text = handle.read(_META_CHARS + 1)
except FileNotFoundError:
raise KeyError(job_id) from None
@@ -253,14 +279,15 @@ class LocalJobHost:
def _create_once(self, job_id: str, name: str, value: str) -> str:
"""Create ``name`` holding ``value`` unless it exists; return what it holds, ours or the earlier writer's.
- ``link(2)`` of a written temporary file: exclusive, and never visible half-written.
+ ``link(2)`` of a written temporary file: exclusive, and never visible half-written. On Windows a rename,
+ which never replaces there, and works on volumes without hard links (FAT).
"""
target = self._path(job_id, name)
tmp = f"{target}.{value}.{secrets.token_hex(4)}.tmp"
with open(tmp, "w", encoding="utf-8") as handle:
handle.write(f"{value}\n")
try:
- os.link(tmp, target)
+ (os.rename if os.name == "nt" else os.link)(tmp, target)
except FileExistsError:
return _read_text(target) or value
finally:
@@ -301,8 +328,8 @@ class LocalJobHost:
Raises ``JobStartError`` when the command did not start.
"""
- if os.name != "posix":
- raise JobStartError("Command jobs are not supported on Windows yet.")
+ if self._shell is None:
+ raise JobStartError("No shell is available to run the command.")
if not sys.executable:
raise JobStartError("No Python interpreter is available to run the command.")
# The host's own steps are small and synchronous, so the only await is the wait for the pid: a cancel
@@ -368,6 +395,7 @@ class LocalJobHost:
sys.executable,
"-I",
"-S",
+ "-B", # on Windows the wrapper loads its helpers by path: no bytecode written into the install
_WRAPPER,
"avibe-job",
job_dir,
@@ -379,7 +407,16 @@ class LocalJobHost:
repr(deadline.timestamp()) if deadline is not None else "-",
]
open(self.output_path(job_id), "ab").close()
- diagnostics = os.open(self._path(job_id, "wrapper.log"), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
+ diagnostics = os.open(
+ self._path(job_id, "wrapper.log"),
+ os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, "O_BINARY", 0),
+ 0o600,
+ )
+ # Windows: its own process group, so no console control event of the service reaches it, and no console
+ # window, which its shell and every console program under it share.
+ windows = (
+ {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW} if _WINDOWS else {}
+ )
try:
proc = subprocess.Popen(
argv,
@@ -389,6 +426,7 @@ class LocalJobHost:
stdout=diagnostics,
stderr=diagnostics,
start_new_session=True,
+ **windows,
)
except OSError as exc:
self._create_decision(job_id, _ABANDON)
@@ -414,11 +452,10 @@ class LocalJobHost:
while time.monotonic() < deadline:
text = _read_text(pid_path)
if text:
- try:
- pgid = os.getpgid(proc.pid)
- except ProcessLookupError:
+ heads = _heads_its_tree(job_id, proc.pid)
+ if heads is None:
return None
- if text != str(proc.pid) or pgid != proc.pid:
+ if text != str(proc.pid) or not heads:
logger.error("Job %s wrapper reported pid %s, expected %s", job_id, text, proc.pid)
return None
return capture_spawned_process_identity(proc.pid, marker)
@@ -471,12 +508,12 @@ class LocalJobHost:
self.meta(job_id)
return b"", since
if since < head_size:
- with open(head_path, "rb") as handle:
+ with _open_for_reading(head_path, binary=True) as handle:
handle.seek(since)
data = handle.read(min(OUTPUT_CHUNK_BYTES, head_size - since))
return data, since + len(data)
try:
- with open(self._path(job_id, "tail.log"), "rb") as handle:
+ with _open_for_reading(self._path(job_id, "tail.log"), binary=True) as handle:
header = _TAIL_HEADER.fullmatch(handle.readline(64))
if header is None:
raise ValueError("tail.log header")
@@ -502,7 +539,10 @@ class LocalJobHost:
identity = self._verify_for_kill(job_id, reason)
if identity is None:
return
- if not await _terminate_group(identity.pid):
+ if _WINDOWS:
+ if not await _terminate_job(job_id, identity.pid):
+ logger.warning("Job %s job object survived termination", job_id)
+ elif not await _terminate_group(identity.pid):
logger.warning("Job %s process group %s survived termination", job_id, identity.pid)
def _verify_for_kill(self, job_id: str, reason: str) -> Optional[PersistedProcessIdentity]:
@@ -514,7 +554,7 @@ class LocalJobHost:
logger.warning("Job %s has no recorded process identity; not signaling", job_id)
return None
if not (self._alive(job_id) or self._group_carries_marker(identity)):
- if _group_exists(identity.pid):
+ if not _WINDOWS and _group_exists(identity.pid):
logger.warning("Job %s process group %s cannot be verified; not signaling", job_id, identity.pid)
return None
try:
@@ -622,6 +662,8 @@ class LocalJobHost:
identity = self._identity(job_id)
if identity is None:
return False
+ if _WINDOWS and not windows_job.process_running(identity.pid):
+ return False # an ended process stays readable for a moment, and its object for as long as it is held
try:
argv = psutil.Process(identity.pid).cmdline()
except (psutil.Error, OSError):
@@ -631,7 +673,12 @@ class LocalJobHost:
return any(argv[i : i + 2] == ["avibe-job", job_dir] for i in range(len(argv) - 1))
def _orphaned_group_runs(self, job_id: str) -> bool:
- """The wrapper was killed on its own (SIGKILL), but its group still provably runs the job."""
+ """The wrapper was killed on its own (SIGKILL), but its group still provably runs the job.
+
+ Never on Windows: the tree ends with the wrapper's handle to its job object.
+ """
+ if _WINDOWS:
+ return False
identity = self._identity(job_id)
return identity is not None and _group_exists(identity.pid) and self._group_carries_marker(identity)
@@ -645,6 +692,49 @@ class LocalJobHost:
del self._children[job_id]
+def _heads_its_tree(job_id: str, pid: int) -> Optional[bool]:
+ """Whether the wrapper ``pid`` heads the job's tree: it leads its own process group, or on Windows it is
+ in the job object it creates before it writes ``pid``. ``None`` when the process is already gone."""
+ if _WINDOWS:
+ job = windows_job.open_job(_job_object_name(job_id))
+ if job is None:
+ return False
+ try:
+ return windows_job.job_contains(job, pid)
+ finally:
+ windows_job.close_handle(job)
+ try:
+ return os.getpgid(pid) == pid
+ except ProcessLookupError:
+ return None
+
+
+async def _terminate_job(
+ job_id: str, wrapper_pid: int, timeout_s: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS
+) -> bool:
+ """Windows: end the verified job's tree through its job object; ``True`` once none of it runs.
+
+ The job is ended only while the wrapper is one of its members. A job that cannot be opened, or that the
+ wrapper has left, has lost or is losing its last handle, and with it every member (``KILL_ON_JOB_CLOSE``).
+ """
+ job = windows_job.open_job(_job_object_name(job_id))
+ if job is None:
+ return True
+ try:
+ if not windows_job.job_contains(job, wrapper_pid):
+ return True
+ windows_job.terminate_job(job)
+ deadline = time.monotonic() + timeout_s
+ # The job counts a process out before the process has ended; ``status`` asks the wrapper itself.
+ while windows_job.active_processes(job) or windows_job.process_running(wrapper_pid):
+ if time.monotonic() >= deadline:
+ return False
+ await asyncio.sleep(0.02)
+ return True
+ finally:
+ windows_job.close_handle(job)
+
+
def _group_exists(pgid: int) -> bool:
try:
os.killpg(pgid, 0)
diff --git a/core/agent_core/tools/paths.py b/core/agent_core/tools/paths.py
index 7b213e32c..a5fe32239 100644
--- a/core/agent_core/tools/paths.py
+++ b/core/agent_core/tools/paths.py
@@ -21,6 +21,7 @@ from concurrent.futures import Executor
from typing import Any, AsyncIterator, Awaitable, Callable, Literal, Optional, TypeVar
from urllib.parse import unquote
+from core.agent_core.tools import windows_files
from core.agent_core.tools.args import ToolInputError
T = TypeVar("T")
@@ -227,8 +228,14 @@ def open_regular(path: str, flags: int = os.O_RDONLY) -> int:
kind is taken from the descriptor (``fstat``), so sizes and contents come from the same file.
Windows has no FIFO to block on, and needs ``O_BINARY``: a text-mode descriptor would drop CRs
and stop reading at the first 0x1A byte. Raises ``NotRegularFile`` or the ``OSError`` of the open.
+
+ On Windows a file is opened for reading shared for delete, as POSIX always shares it, so a job's
+ wrapper can still replace the ``tail.log`` the model is told to read (``windows_files``).
"""
- fd = os.open(path, flags | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) | getattr(os, "O_CLOEXEC", 0))
+ if os.name == "nt" and flags == os.O_RDONLY:
+ fd = windows_files.open_for_reading(path)
+ else:
+ fd = os.open(path, flags | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) | getattr(os, "O_CLOEXEC", 0))
try:
mode = os.fstat(fd).st_mode
if not stat.S_ISREG(mode):
diff --git a/core/agent_core/tools/windows_files.py b/core/agent_core/tools/windows_files.py
index ada4352c3..fba1acfbe 100644
--- a/core/agent_core/tools/windows_files.py
+++ b/core/agent_core/tools/windows_files.py
@@ -7,8 +7,14 @@ POSIX gives them two guarantees by default that Windows gives only on request:
- a change time: ``stat`` reports the creation time as ``st_ctime`` on Python before 3.12.
An existing file is rewritten in place (C-7 tools.md section 3): a replacement would be a new file
-object, which keeps none of the old one's owner, security, streams, or links. Importing this module
-works everywhere; calling it works only on Windows.
+object, which keeps none of the old one's owner, security, streams, or links.
+
+A job's own files are another matter. A file opened with Python's ``open`` or ``os.open`` cannot be
+renamed over until it is closed: a reader opened here can be (``open_for_reading``), but only by a
+rename with POSIX semantics (``replace``); ``os.replace`` fails even then.
+
+Standard library only: the job wrapper beside it runs as ``python -I -S`` and loads this file by its
+path. Importing it works everywhere; calling it works only on Windows.
"""
from __future__ import annotations
@@ -19,7 +25,9 @@ from typing import Any, Optional
_FILE_WRITE_DATA = 0x0002
_FILE_READ_ATTRIBUTES = 0x0080
+_GENERIC_READ = 0x80000000
_GENERIC_WRITE = 0x40000000
+_DELETE = 0x00010000
_FILE_SHARE_READ = 0x1
_FILE_SHARE_READ_WRITE = 0x1 | 0x2
_FILE_SHARE_READ_WRITE_DELETE = 0x1 | 0x2 | 0x4
@@ -27,7 +35,13 @@ _CREATE_NEW = 1
_OPEN_EXISTING = 3
_FILE_ATTRIBUTE_NORMAL = 0x80
_FILE_ATTRIBUTE_REPARSE_POINT = 0x400
+_FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
_FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
+_FILE_RENAME_INFO_EX = 22
+_FILE_RENAME_FLAG_REPLACE_IF_EXISTS = 0x1
+_FILE_RENAME_FLAG_POSIX_SEMANTICS = 0x2
+_ERROR_NOT_SUPPORTED = 50
+_ERROR_INVALID_PARAMETER = 87
_FILE_BASIC_INFO = 0
_FILE_ATTRIBUTE_TAG_INFO = 9
# IsReparseTagNameSurrogate: the reparse point names another file (a symbolic link, a junction).
@@ -69,6 +83,8 @@ def _kernel32() -> Any:
wintypes.DWORD,
]
kernel32.GetFileInformationByHandleEx.restype = wintypes.BOOL
+ kernel32.SetFileInformationByHandle.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]
+ kernel32.SetFileInformationByHandle.restype = wintypes.BOOL
kernel32.LocalFree.argtypes = [ctypes.c_void_p]
kernel32.LocalFree.restype = ctypes.c_void_p
advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
@@ -258,3 +274,72 @@ def change_time_ns(fd: int) -> int:
information = _basic_information(msvcrt.get_osfhandle(fd), f"<descriptor {fd}>")
return (information.ChangeTime - _UNIX_EPOCH_FILETIME) * 100
+
+
+def open_for_reading(path: str) -> int:
+ """A binary, read-only descriptor of the file ``path``, shared for delete, so ``replace`` can still
+ rename a new file onto its name; this reader keeps reading the file it opened. Raises ``OSError`` as
+ ``open`` does (``FileNotFoundError`` for a missing file)."""
+ import msvcrt
+
+ kernel32 = _kernel32()
+ handle = kernel32.CreateFileW(path, _GENERIC_READ, _FILE_SHARE_READ_WRITE_DELETE, None, _OPEN_EXISTING, 0, None)
+ if _invalid(handle):
+ raise _error(path)
+ try:
+ return msvcrt.open_osfhandle(handle, os.O_RDONLY | os.O_BINARY)
+ except BaseException:
+ kernel32.CloseHandle(handle)
+ raise
+
+
+def replace(source: str, destination: str) -> None:
+ """``os.replace``, with POSIX semantics where the filesystem has them (NTFS, Windows 10 1607 and later).
+
+ It succeeds while readers hold ``destination`` open through ``open_for_reading``, where ``os.replace``
+ fails. A reader that did not share delete (Python's ``open``) still makes it fail. A filesystem without
+ POSIX semantics (FAT, some network shares) gets ``os.replace``. For a job's own files, which carry no
+ metadata of their own; a user's file is rewritten in place instead.
+ """
+ from ctypes import wintypes
+
+ kernel32 = _kernel32()
+
+ class RenameInformation(ctypes.Structure):
+ _fields_ = [
+ ("Flags", wintypes.DWORD),
+ ("RootDirectory", wintypes.HANDLE),
+ ("FileNameLength", wintypes.DWORD),
+ ("FileName", wintypes.WCHAR * 1),
+ ]
+
+ name = os.path.abspath(destination)
+ size = RenameInformation.FileName.offset + (len(name) + 1) * ctypes.sizeof(wintypes.WCHAR)
+ buffer = ctypes.create_string_buffer(size)
+ information = RenameInformation.from_buffer(buffer)
+ information.Flags = _FILE_RENAME_FLAG_REPLACE_IF_EXISTS | _FILE_RENAME_FLAG_POSIX_SEMANTICS
+ information.FileNameLength = len(name) * ctypes.sizeof(wintypes.WCHAR)
+ ctypes.memmove(
+ ctypes.addressof(information) + RenameInformation.FileName.offset,
+ ctypes.create_unicode_buffer(name),
+ (len(name) + 1) * ctypes.sizeof(wintypes.WCHAR),
+ )
+ handle = kernel32.CreateFileW(
+ source,
+ _DELETE,
+ _FILE_SHARE_READ_WRITE_DELETE,
+ None,
+ _OPEN_EXISTING,
+ _FILE_FLAG_BACKUP_SEMANTICS | _FILE_FLAG_OPEN_REPARSE_POINT,
+ None,
+ )
+ if _invalid(handle):
+ raise _error(source)
+ try:
+ if kernel32.SetFileInformationByHandle(handle, _FILE_RENAME_INFO_EX, buffer, size):
+ return
+ if ctypes.get_last_error() not in (_ERROR_INVALID_PARAMETER, _ERROR_NOT_SUPPORTED):
+ raise _error(destination)
+ finally:
+ kernel32.CloseHandle(handle)
+ os.replace(source, destination)
diff --git a/core/agent_core/tools/windows_job.py b/core/agent_core/tools/windows_job.py
new file mode 100644
index 000000000..51d170ff3
--- /dev/null
+++ b/core/agent_core/tools/windows_job.py
@@ -0,0 +1,236 @@
+"""Windows Job Objects, and the pipe check the job wrapper needs, through ``ctypes`` alone.
+
+Standard library only: the job wrapper beside it runs as ``python -I -S`` and loads this file by its
+path, and ``core/watch_worker.py`` imports it. Importing it works everywhere; calling it works only
+on Windows.
+
+A job object holds a process tree as a POSIX session does, and more strictly. A process started by
+a member is a member, and it cannot leave, since no job here allows breakaway. With
+``KILL_ON_JOB_CLOSE``, every member ends when the last handle to the job closes, so a tree never
+outlives the process that holds the handle. Nested jobs need Windows 8 or later.
+"""
+
+from __future__ import annotations
+
+import ctypes
+from typing import Any, Optional
+
+_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
+_JOB_OBJECT_BASIC_ACCOUNTING_INFORMATION = 1
+_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
+_JOB_OBJECT_QUERY = 0x0004
+_JOB_OBJECT_TERMINATE = 0x0008
+_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
+_SYNCHRONIZE = 0x00100000
+_WAIT_TIMEOUT = 0x102
+_ERROR_FILE_NOT_FOUND = 2
+_ERROR_BROKEN_PIPE = 109
+_ERROR_ALREADY_EXISTS = 183
+
+_api: Any = None
+
+
+def _kernel32() -> Any:
+ """kernel32 with the signatures used here, set up on first use."""
+ global _api
+ if _api is not None:
+ return _api
+ from ctypes import wintypes
+
+ class BasicLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("PerProcessUserTimeLimit", ctypes.c_longlong),
+ ("PerJobUserTimeLimit", ctypes.c_longlong),
+ ("LimitFlags", wintypes.DWORD),
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
+ ("ActiveProcessLimit", wintypes.DWORD),
+ ("Affinity", ctypes.c_size_t),
+ ("PriorityClass", wintypes.DWORD),
+ ("SchedulingClass", wintypes.DWORD),
+ ]
+
+ class IoCounters(ctypes.Structure):
+ _fields_ = [
+ ("ReadOperationCount", ctypes.c_ulonglong),
+ ("WriteOperationCount", ctypes.c_ulonglong),
+ ("OtherOperationCount", ctypes.c_ulonglong),
+ ("ReadTransferCount", ctypes.c_ulonglong),
+ ("WriteTransferCount", ctypes.c_ulonglong),
+ ("OtherTransferCount", ctypes.c_ulonglong),
+ ]
+
+ class ExtendedLimitInformation(ctypes.Structure):
+ _fields_ = [
+ ("BasicLimitInformation", BasicLimitInformation),
+ ("IoInfo", IoCounters),
+ ("ProcessMemoryLimit", ctypes.c_size_t),
+ ("JobMemoryLimit", ctypes.c_size_t),
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
+ ]
+
+ class BasicAccountingInformation(ctypes.Structure):
+ _fields_ = [
+ ("TotalUserTime", ctypes.c_longlong),
+ ("TotalKernelTime", ctypes.c_longlong),
+ ("ThisPeriodTotalUserTime", ctypes.c_longlong),
+ ("ThisPeriodTotalKernelTime", ctypes.c_longlong),
+ ("TotalPageFaultCount", wintypes.DWORD),
+ ("TotalProcesses", wintypes.DWORD),
+ ("ActiveProcesses", wintypes.DWORD),
+ ("TotalTerminatedProcesses", wintypes.DWORD),
+ ]
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ signatures = {
+ "CreateJobObjectW": ([ctypes.c_void_p, wintypes.LPCWSTR], wintypes.HANDLE),
+ "OpenJobObjectW": ([wintypes.DWORD, wintypes.BOOL, wintypes.LPCWSTR], wintypes.HANDLE),
+ "SetInformationJobObject": ([wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD], wintypes.BOOL),
+ "QueryInformationJobObject": (
+ [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.c_void_p],
+ wintypes.BOOL,
+ ),
+ "AssignProcessToJobObject": ([wintypes.HANDLE, wintypes.HANDLE], wintypes.BOOL),
+ "TerminateJobObject": ([wintypes.HANDLE, wintypes.UINT], wintypes.BOOL),
+ "IsProcessInJob": ([wintypes.HANDLE, wintypes.HANDLE, ctypes.POINTER(wintypes.BOOL)], wintypes.BOOL),
+ "OpenProcess": ([wintypes.DWORD, wintypes.BOOL, wintypes.DWORD], wintypes.HANDLE),
+ "GetCurrentProcess": ([], wintypes.HANDLE),
+ "WaitForSingleObject": ([wintypes.HANDLE, wintypes.DWORD], wintypes.DWORD),
+ "CloseHandle": ([wintypes.HANDLE], wintypes.BOOL),
+ "PeekNamedPipe": (
+ [
+ wintypes.HANDLE,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ctypes.c_void_p,
+ ctypes.POINTER(wintypes.DWORD),
+ ctypes.c_void_p,
+ ],
+ wintypes.BOOL,
+ ),
+ }
+ for name, (argtypes, restype) in signatures.items():
+ function = getattr(kernel32, name)
+ function.argtypes = argtypes
+ function.restype = restype
+ kernel32.ExtendedLimitInformation = ExtendedLimitInformation
+ kernel32.BasicAccountingInformation = BasicAccountingInformation
+ kernel32.BOOL = wintypes.BOOL
+ kernel32.DWORD = wintypes.DWORD
+ _api = kernel32
+ return kernel32
+
+
+def _job_name(name: str) -> str:
+ # Local\ is this logon session's namespace, which needs no privilege to create in.
+ return f"Local\\{name}"
+
+
+def create_kill_on_close_job(name: Optional[str] = None) -> int:
+ """Create a job whose members all end when its last handle closes, and make this process a member.
+
+ Returns the handle, which the caller keeps open for as long as the tree may run. A name that is
+ already taken is refused (``FileExistsError``) rather than joined, so no other job is ever taken
+ for this one.
+ """
+ kernel32 = _kernel32()
+ ctypes.set_last_error(0)
+ job = kernel32.CreateJobObjectW(None, _job_name(name) if name is not None else None)
+ error = ctypes.get_last_error()
+ if not job:
+ raise ctypes.WinError(error)
+ try:
+ if error == _ERROR_ALREADY_EXISTS:
+ raise FileExistsError(error, "a job object of this name already exists", name)
+ information = kernel32.ExtendedLimitInformation()
+ information.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ if not kernel32.SetInformationJobObject(
+ job, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION, ctypes.byref(information), ctypes.sizeof(information)
+ ):
+ raise ctypes.WinError(ctypes.get_last_error())
+ if not kernel32.AssignProcessToJobObject(job, kernel32.GetCurrentProcess()):
+ raise ctypes.WinError(ctypes.get_last_error())
+ except BaseException:
+ kernel32.CloseHandle(job)
+ raise
+ return job
+
+
+def open_job(name: str) -> Optional[int]:
+ """A handle that can query and terminate the job ``name``; ``None`` once no such job exists."""
+ kernel32 = _kernel32()
+ job = kernel32.OpenJobObjectW(_JOB_OBJECT_QUERY | _JOB_OBJECT_TERMINATE, False, _job_name(name))
+ if job:
+ return job
+ error = ctypes.get_last_error()
+ if error == _ERROR_FILE_NOT_FOUND:
+ return None
+ raise ctypes.WinError(error)
+
+
+def job_contains(job: int, pid: int) -> bool:
+ """Whether the process ``pid`` is a member of ``job``; ``False`` once no such process exists."""
+ kernel32 = _kernel32()
+ process = kernel32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
+ if not process:
+ return False
+ try:
+ member = kernel32.BOOL()
+ if not kernel32.IsProcessInJob(process, job, ctypes.byref(member)):
+ raise ctypes.WinError(ctypes.get_last_error())
+ return bool(member.value)
+ finally:
+ kernel32.CloseHandle(process)
+
+
+def process_running(pid: int) -> bool:
+ """Whether the process ``pid`` exists and has not ended.
+
+ Its object is signaled once it has ended, which is the last step of its exit: a job counts a process out,
+ and its command line stops being readable, a little earlier.
+ """
+ kernel32 = _kernel32()
+ process = kernel32.OpenProcess(_SYNCHRONIZE, False, pid)
+ if not process:
+ return False
+ try:
+ return kernel32.WaitForSingleObject(process, 0) == _WAIT_TIMEOUT
+ finally:
+ kernel32.CloseHandle(process)
+
+
+def active_processes(job: int) -> int:
+ """How many processes of ``job`` are still running."""
+ kernel32 = _kernel32()
+ information = kernel32.BasicAccountingInformation()
+ if not kernel32.QueryInformationJobObject(
+ job, _JOB_OBJECT_BASIC_ACCOUNTING_INFORMATION, ctypes.byref(information), ctypes.sizeof(information), None
+ ):
+ raise ctypes.WinError(ctypes.get_last_error())
+ return int(information.ActiveProcesses)
+
+
+def terminate_job(job: int, exit_code: int = 1) -> None:
+ """End every process of ``job``, the caller included when it is a member."""
+ kernel32 = _kernel32()
+ if not kernel32.TerminateJobObject(job, exit_code):
+ raise ctypes.WinError(ctypes.get_last_error())
+
+
+def close_handle(handle: int) -> None:
+ _kernel32().CloseHandle(handle)
+
+
+def pipe_readable(fd: int) -> bool:
+ """Whether reading the pipe ``fd`` would not block: bytes are waiting, or every writer has closed it."""
+ import msvcrt
+
+ kernel32 = _kernel32()
+ available = kernel32.DWORD()
+ if not kernel32.PeekNamedPipe(msvcrt.get_osfhandle(fd), None, 0, None, ctypes.byref(available), None):
+ error = ctypes.get_last_error()
+ if error == _ERROR_BROKEN_PIPE:
+ return True # the read returns end of file at once
+ raise ctypes.WinError(error)
+ return available.value > 0
diff --git a/core/watch_worker.py b/core/watch_worker.py
index 2e2e673da..b528c9bce 100644
--- a/core/watch_worker.py
+++ b/core/watch_worker.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import ctypes
import json
import os
import signal
@@ -174,78 +173,9 @@ def _read_watch_worker_spec() -> tuple[list[str], str | None]:
def _install_windows_kill_on_close_job() -> Any:
if os.name != "nt":
return None
+ from core.agent_core.tools import windows_job
- from ctypes import wintypes
-
- class JobObjectBasicLimitInformation(ctypes.Structure):
- _fields_ = [
- ("PerProcessUserTimeLimit", ctypes.c_longlong),
- ("PerJobUserTimeLimit", ctypes.c_longlong),
- ("LimitFlags", wintypes.DWORD),
- ("MinimumWorkingSetSize", ctypes.c_size_t),
- ("MaximumWorkingSetSize", ctypes.c_size_t),
- ("ActiveProcessLimit", wintypes.DWORD),
- ("Affinity", ctypes.c_size_t),
- ("PriorityClass", wintypes.DWORD),
- ("SchedulingClass", wintypes.DWORD),
- ]
-
- class IoCounters(ctypes.Structure):
- _fields_ = [
- ("ReadOperationCount", ctypes.c_ulonglong),
- ("WriteOperationCount", ctypes.c_ulonglong),
- ("OtherOperationCount", ctypes.c_ulonglong),
- ("ReadTransferCount", ctypes.c_ulonglong),
- ("WriteTransferCount", ctypes.c_ulonglong),
- ("OtherTransferCount", ctypes.c_ulonglong),
- ]
-
- class JobObjectExtendedLimitInformation(ctypes.Structure):
- _fields_ = [
- ("BasicLimitInformation", JobObjectBasicLimitInformation),
- ("IoInfo", IoCounters),
- ("ProcessMemoryLimit", ctypes.c_size_t),
- ("JobMemoryLimit", ctypes.c_size_t),
- ("PeakProcessMemoryUsed", ctypes.c_size_t),
- ("PeakJobMemoryUsed", ctypes.c_size_t),
- ]
-
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
- kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
- kernel32.CreateJobObjectW.restype = wintypes.HANDLE
- kernel32.SetInformationJobObject.argtypes = [
- wintypes.HANDLE,
- ctypes.c_int,
- ctypes.c_void_p,
- wintypes.DWORD,
- ]
- kernel32.SetInformationJobObject.restype = wintypes.BOOL
- kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
- kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
- kernel32.GetCurrentProcess.restype = wintypes.HANDLE
- kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
- kernel32.CloseHandle.restype = wintypes.BOOL
-
- job = kernel32.CreateJobObjectW(None, None)
- if not job:
- raise ctypes.WinError(ctypes.get_last_error())
-
- information = JobObjectExtendedLimitInformation()
- information.BasicLimitInformation.LimitFlags = 0x00002000
- if not kernel32.SetInformationJobObject(
- job,
- 9,
- ctypes.byref(information),
- ctypes.sizeof(information),
- ):
- error = ctypes.get_last_error()
- kernel32.CloseHandle(job)
- raise ctypes.WinError(error)
- if not kernel32.AssignProcessToJobObject(job, kernel32.GetCurrentProcess()):
- error = ctypes.get_last_error()
- kernel32.CloseHandle(job)
- raise ctypes.WinError(error)
- return job
+ return windows_job.create_kill_on_close_job()
def _forward_stream(source: BinaryIO, target: BinaryIO) -> None:
diff --git a/docs/plans/agent-core-contracts/tools.md b/docs/plans/agent-core-contracts/tools.md
index 56fb5036f..397676cf3 100644
--- a/docs/plans/agent-core-contracts/tools.md
+++ b/docs/plans/agent-core-contracts/tools.md
@@ -235,7 +235,7 @@ backend they are required.
| Operation | v1 | Meaning |
| --- | --- | --- |
-| `start(command, cwd, env, timeout, call)` → `job_id` | yes | create the job directory and metadata for the call instance `call`, then spawn the wrapper in its own session |
+| `start(command, cwd, env, timeout, call)` → `job_id` | yes | create the job directory and metadata for the call instance `call`, then spawn the wrapper in its own session (on Windows, its own job object) |
| `status(job_id)` | yes | `running`, `exited{code}`, or `gone` (ended without an exit code) |
| `wait(job_id, deadline_s)` | yes | until exit, or at most `deadline_s` seconds from now (`None`: until exit) |
| `output_path(job_id)` | yes | absolute path of `output.log`, named in truncated and handover results |
@@ -255,6 +255,20 @@ at most once and recovery can always decide whether it did; its identity is reco
absolute deadline that survives handover and restarts; output on disk is bounded; files are kept until the call is
durably settled; handover creates at most one Watch per job.
+On Windows the wrapper's tree is a job object it creates and joins before it can run the command, named after the
+job and ended when the wrapper's handle to it closes. Every process the command starts is in it and cannot leave it.
+`kill` terminates the job object; a kill of the wrapper alone (`TerminateProcess`, which nothing can catch) also ends
+the tree but records no reason, so T2 settles that call as interrupted rather than `killed`. A process the command
+leaves running keeps the wrapper, and so the job, alive until it ends or is killed; on POSIX it runs on in the process
+group. On both, the deadline is the command's (J3): once the shell has exited, it reaches no such process. Job files are replaced with POSIX rename semantics and Avibe reads them with delete sharing, so no reader of
+Avibe's makes the wrapper's replacement of `tail.log` fail; while another program holds it open without that sharing,
+the wrapper keeps the tail and writes it at a later snapshot. The last snapshot, taken when the command exits, cannot
+wait: it is written into `tail.log` itself, which such a program shares for writing (Python's `open`,
+`Get-Content -Wait`); one that shares neither leaves the previous tail there while it holds the file. The command's
+exit stands either way.
+A decision or a stop reason is created once by a rename, which never replaces on Windows, rather than by a hard link,
+so job files work on a volume without hard links (FAT, exFAT).
+
## 8. Environment section
Changing facts do not go into the system prompt, which stays stable and cacheable. When the loop consumes an input
diff --git a/tests/agent_core/tools/test_jobs_windows.py b/tests/agent_core/tools/test_jobs_windows.py
new file mode 100644
index 000000000..8fce49d13
--- /dev/null
+++ b/tests/agent_core/tools/test_jobs_windows.py
@@ -0,0 +1,596 @@
+"""``LocalJobHost`` on Windows, where a job object holds the tree (``recovery.md`` J1-J6, T2).
+
+Python is the shell here (``python -c``), so a command means the same on every Windows; the shell
+the ``bash`` tool runs on Windows brings its own tests. A "crash" or "restart" is a new
+``LocalJobHost`` over the same directory, or a host process that is terminated outright.
+
+Every test ends the jobs it started: ``_end_every_job`` terminates each job object left under the
+test's jobs directory, whatever the test did.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import os
+import secrets
+import shutil
+import subprocess
+import sys
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+
+import psutil
+import pytest
+
+import core.agent_core.tools.jobs as jobs_module
+from core.agent_core.tools import windows_job
+from core.agent_core.cancel import CancelToken
+from core.agent_core.tools.base import ToolContext
+from core.agent_core.tools.bash import BashTool, settle_bash_call
+from core.agent_core.tools.jobs import JobStartError, LocalJobHost
+from tests.agent_core.tools.conftest import instance, result_text
+
+pytestmark = pytest.mark.skipif(os.name != "nt", reason="the Windows job host")
+
+REPO = Path(__file__).resolve().parents[3]
+
+
+class Crash(Exception):
+ pass
+
+
[email protected](autouse=True)
+def _end_every_job(tmp_path):
+ yield
+ jobs_dir = tmp_path / "jobs"
+ for entry in jobs_dir.iterdir() if jobs_dir.is_dir() else ():
+ job = windows_job.open_job(f"avibe-job-{entry.name}")
+ if job is not None:
+ try:
+ windows_job.terminate_job(job)
+ finally:
+ windows_job.close_handle(job)
+
+
+def make_ctx(tmp_path):
+ """The tools' context with the whole environment: Python on Windows needs more of it than ``PATH``."""
+
+ def make(*, tool_call_id="toolu_1"):
+ return ToolContext(
+ session_id="ses_test",
+ tool_call_id=tool_call_id,
+ call=instance(tool_call_id),
+ cwd=str(tmp_path),
+ env=dict(os.environ),
+ cancel=CancelToken(),
+ on_progress=None,
+ )
+
+ return make
+
+
+def _host(tmp_path, **kwargs):
+ return LocalJobHost(str(tmp_path / "jobs"), shell=sys.executable, **kwargs)
+
+
+async def _start(host, tmp_path, script, *, tool_call_id="toolu_1", response_seq=1, timeout_s=None):
+ return await host.start(
+ script,
+ cwd=str(tmp_path),
+ env=dict(os.environ),
+ timeout_s=timeout_s,
+ call=instance(tool_call_id, response_seq=response_seq),
+ )
+
+
+def _wait_until(predicate, timeout_s=10.0):
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ if predicate():
+ return True
+ time.sleep(0.02)
+ return False
+
+
+def _gone(pid):
+ return not psutil.pid_exists(pid)
+
+
+def _wrapper_pid(host, job_id):
+ return int(open(os.path.join(host.job_dir(job_id), "pid")).read())
+
+
+def _pid_written(path):
+ assert _wait_until(lambda: path.exists() and path.read_text().strip())
+ return int(path.read_text())
+
+
+def _tree(tmp_path, *, then="import time; time.sleep(60)"):
+ """A command that records its pid, starts a detached grandchild that records its own, then runs ``then``.
+
+ ``DETACHED_PROCESS`` is how ``Start-Process`` and services leave a console; it does not leave a job.
+ """
+ grandchild = f"import os, time; open(r'{tmp_path / 'grandchild.pid'}', 'w').write(str(os.getpid())); time.sleep(60)"
+ return (
+ "import os, subprocess, sys\n"
+ f"open(r'{tmp_path / 'shell.pid'}', 'w').write(str(os.getpid()))\n"
+ f"subprocess.Popen([sys.executable, '-c', {grandchild!r}], creationflags=subprocess.DETACHED_PROCESS)\n"
+ f"{then}\n"
+ )
+
+
+def _tree_pids(tmp_path):
+ return _pid_written(tmp_path / "shell.pid"), _pid_written(tmp_path / "grandchild.pid")
+
+
+def _counter(tmp_path):
+ path = tmp_path / "counter"
+ return len(path.read_text().splitlines()) if path.exists() else 0
+
+
+_COUNT = "open(r'{path}', 'a').write('ran\\n')"
+
+
+def _crash_on_meta_write(monkeypatch, number):
+ original = LocalJobHost._write_meta
+ calls = []
+
+ def write(self, job_id, meta):
+ original(self, job_id, meta)
+ calls.append(job_id)
+ if len(calls) == number:
+ raise Crash
+
+ monkeypatch.setattr(LocalJobHost, "_write_meta", write)
+
+
+async def test_a_command_runs_in_its_own_job_object_and_its_output_is_kept_byte_for_byte(tmp_path):
+ host = _host(tmp_path)
+ job_id = await _start(
+ host,
+ tmp_path,
+ "import sys\n"
+ "sys.stdout.buffer.write(b'a\\nb\\r\\n\\x1a\\nend\\n'); sys.stdout.flush()\n"
+ f"open(r'{tmp_path / 'member'}', 'w').write('started')\n"
+ "import time; time.sleep(60)",
+ )
+ assert _wait_until(lambda: (tmp_path / "member").exists() and host.output(job_id)[1] == 11)
+ job = windows_job.open_job(f"avibe-job-{job_id}")
+ try:
+ assert windows_job.job_contains(job, _wrapper_pid(host, job_id))
+ assert windows_job.active_processes(job) == 2 # the wrapper and its shell
+ finally:
+ windows_job.close_handle(job)
+ await host.kill(job_id)
+
+ # The log is binary: no CRLF added, and 0x1A (Ctrl-Z) is not the end.
+ assert host.output(job_id) == (b"a\nb\r\n\x1a\nend\n", 11)
+ meta = host.meta(job_id)
+ assert meta["process"]["pgid"] == meta["process"]["pid"] == _wrapper_pid(host, job_id)
+
+
+async def test_an_exit_code_is_reported_in_full(tmp_path):
+ host = _host(tmp_path)
+ job_id = await _start(host, tmp_path, "import sys; sys.exit(7)")
+
+ assert await host.wait(job_id, deadline_s=10) == jobs_module.JobStatus("exited", 7)
+
+
+ "crash_point",
+ ["after_meta_before_spawn", "after_spawn_before_pid", "after_identity_before_go", "after_go"],
+)
+async def test_a_crash_at_any_launch_step_runs_the_command_at_most_once(tmp_path, monkeypatch, crash_point):
+ """J1."""
+ host = _host(tmp_path)
+ if crash_point == "after_meta_before_spawn":
+ _crash_on_meta_write(monkeypatch, 1)
+ elif crash_point == "after_spawn_before_pid":
+
+ async def crash(self, *args):
+ raise Crash
+
+ monkeypatch.setattr(LocalJobHost, "_await_pid", crash)
+ elif crash_point == "after_identity_before_go":
+ _crash_on_meta_write(monkeypatch, 2)
+
+ with pytest.raises(Crash) if crash_point != "after_go" else contextlib.nullcontext():
+ await _start(host, tmp_path, _COUNT.format(path=tmp_path / "counter"))
+ monkeypatch.undo()
+
+ recovery = _host(tmp_path)
+ job_id = recovery.find_job(instance())
+ may_have_started = recovery.started(job_id)
+ if crash_point != "after_meta_before_spawn":
+ pid_file = Path(recovery.job_dir(job_id)) / "pid"
+ assert _wait_until(lambda: not pid_file.exists() or _gone(int(pid_file.read_text())))
+
+ assert may_have_started is (crash_point == "after_go")
+ assert _counter(tmp_path) == (1 if may_have_started else 0)
+ assert recovery.status(job_id).state == ("exited" if may_have_started else "gone")
+
+
+async def test_a_wrapper_left_without_a_decision_abandons_and_never_runs_the_command(tmp_path, monkeypatch):
+ """J1: the wrapper decides ``abandon`` itself when no decision comes in time."""
+ monkeypatch.setattr(jobs_module, "DECISION_TIMEOUT_S", 0.05)
+ original = LocalJobHost._await_pid
+
+ async def slow_host(self, *args):
+ identity = await original(self, *args)
+ await asyncio.sleep(0.5)
+ return identity
+
+ monkeypatch.setattr(LocalJobHost, "_await_pid", slow_host)
+ host = _host(tmp_path)
+
+ with pytest.raises(JobStartError):
+ await _start(host, tmp_path, _COUNT.format(path=tmp_path / "counter"))
+
+ job_id = host.find_job(instance())
+ assert _wait_until(lambda: _gone(_wrapper_pid(host, job_id)))
+ assert not host.started(job_id)
+ assert _counter(tmp_path) == 0
+
+
+async def test_a_recorded_pid_outside_the_job_is_neither_reported_nor_killed(tmp_path):
+ """J2: the pid on record now belongs to a process that is not in the job's job object."""
+ host = _host(tmp_path)
+ job_id = await _start(host, tmp_path, "import time; time.sleep(60)")
+ await host.kill(job_id)
+ stranger = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ try:
+ meta = host.meta(job_id)
+ meta["process"].update(pid=stranger.pid, pgid=stranger.pid)
+ host._write_meta(job_id, meta)
+
+ recovery = _host(tmp_path)
+ assert recovery.status(job_id).state == "gone"
+ await recovery.kill(job_id)
+
+ time.sleep(0.2)
+ assert stranger.poll() is None
+ finally:
+ stranger.kill()
+ stranger.wait()
+
+
+async def test_kill_ends_the_whole_tree_and_no_process_can_leave_the_job(tmp_path):
+ host = _host(tmp_path)
+ breakaway = (
+ "try:\n"
+ " subprocess.Popen([sys.executable, '-c', 'pass'], creationflags=subprocess.CREATE_BREAKAWAY_FROM_JOB)\n"
+ f" open(r'{tmp_path / 'breakaway'}', 'w').write('escaped')\n"
+ "except OSError:\n"
+ f" open(r'{tmp_path / 'breakaway'}', 'w').write('refused')\n"
+ "import time; time.sleep(60)"
+ )
+ job_id = await _start(host, tmp_path, _tree(tmp_path, then=breakaway))
+ shell, grandchild = _tree_pids(tmp_path)
+ assert _wait_until((tmp_path / "breakaway").exists)
+
+ await host.kill(job_id, reason="aborted")
+
+ assert _wait_until(lambda: _gone(shell) and _gone(grandchild) and _gone(_wrapper_pid(host, job_id)))
+ assert (tmp_path / "breakaway").read_text() == "refused"
+ assert host.status(job_id).state == "gone"
+ assert host.stop_reason(job_id) == "aborted"
+
+
+async def test_the_wrapper_enforces_the_deadline_while_no_host_runs(tmp_path):
+ """J3: the host is gone right after the start; the deadline still ends the tree and is recorded."""
+ host = _host(tmp_path)
+ job_id = await _start(host, tmp_path, _tree(tmp_path), timeout_s=3)
+ wrapper = _wrapper_pid(host, job_id)
+ shell, grandchild = _tree_pids(tmp_path)
+ del host
+
+ assert _wait_until(lambda: _gone(wrapper), timeout_s=15)
+ restarted = _host(tmp_path)
+ assert restarted.status(job_id).state == "gone"
+ assert restarted.stop_reason(job_id) == "timeout"
+ assert _wait_until(lambda: _gone(shell) and _gone(grandchild))
+
+
+async def test_terminating_the_wrapper_ends_its_tree_and_records_no_reason(tmp_path):
+ """``TerminateProcess`` cannot be caught: the job object ends the tree, and T2 settles the call as interrupted."""
+ host = _host(tmp_path)
+ job_id = await _start(host, tmp_path, _tree(tmp_path))
+ shell, grandchild = _tree_pids(tmp_path)
+
+ psutil.Process(_wrapper_pid(host, job_id)).kill() # TerminateProcess
+
+ assert _wait_until(lambda: _gone(shell) and _gone(grandchild))
+ recovery = _host(tmp_path)
+ assert recovery.status(job_id).state == "gone"
+ assert recovery.stop_reason(job_id) is None
+ assert await settle_bash_call(recovery, instance()) is None # the caller commits the interrupted result
+
+
+async def test_a_job_outlives_the_host_process_that_started_it(tmp_path):
+ """A restart: the service process is terminated outright, and its job keeps running for the next host."""
+ script = (
+ "import asyncio, os, sys\n"
+ "from core.agent_core.tools.base import CallInstance\n"
+ "from core.agent_core.tools.jobs import LocalJobHost\n"
+ "async def main():\n"
+ f" host = LocalJobHost(r'{tmp_path / 'jobs'}', shell=sys.executable)\n"
+ f" job_id = await host.start({_tree(tmp_path)!r}, cwd=r'{tmp_path}', env=dict(os.environ),"
+ " timeout_s=None, call=CallInstance('ses_test', 'msg_1', 1, 'toolu_1'))\n"
+ " print(job_id, flush=True)\n"
+ " await asyncio.sleep(60)\n"
+ "asyncio.run(main())\n"
+ )
+ service = subprocess.Popen([sys.executable, "-c", script], cwd=REPO, stdout=subprocess.PIPE, text=True)
+ try:
+ job_id = (await asyncio.wait_for(asyncio.to_thread(service.stdout.readline), 60)).strip()
+ shell, grandchild = _tree_pids(tmp_path)
+ service.kill() # TerminateProcess: no cleanup runs
+ service.wait()
+ finally:
+ if service.poll() is None:
+ service.kill()
+ service.wait()
+
+ restarted = _host(tmp_path)
+ assert restarted.status(job_id).state == "running"
+ assert not _gone(shell) and not _gone(grandchild)
+ await restarted.kill(job_id)
+ assert _wait_until(lambda: _gone(shell) and _gone(grandchild))
+ assert restarted.stop_reason(job_id) == "killed"
+
+
+async def test_a_reader_holding_the_logs_open_never_stops_the_command(tmp_path, monkeypatch):
+ """J4: the wrapper replaces tail.log a few times a second; a host reading it must not make that fail."""
+ monkeypatch.setattr(jobs_module, "OUTPUT_HEAD_BYTES", 1000)
+ monkeypatch.setattr(jobs_module, "OUTPUT_TAIL_BYTES", 2000)
+ host = _host(tmp_path)
+ job_id = await _start(
+ host,
+ tmp_path,
+ "import sys, time\n"
+ "for i in range(1, 3001):\n"
+ " sys.stdout.buffer.write(b'%d\\n' % i)\n"
+ " if i % 100 == 0:\n"
+ " sys.stdout.flush(); time.sleep(0.05)\n",
+ )
+ tail = os.path.join(host.job_dir(job_id), "tail.log")
+ assert _wait_until(lambda: os.path.exists(tail))
+ held = jobs_module._open_for_reading(tail, binary=True)
+ try:
+ offset, seen = 0, []
+ while host.status(job_id).state == "running":
+ data, offset = host.output(job_id, offset)
+ seen.append(data)
+ await asyncio.sleep(0.01)
+ status = await host.wait(job_id, deadline_s=10)
+ finally:
+ held.close()
+
+ assert status == jobs_module.JobStatus("exited", 0)
+ assert host.stop_reason(job_id) is None
+ assert os.path.getsize(host.output_path(job_id)) == 1000
+ while True:
+ data, offset = host.output(job_id, offset)
+ if not data:
+ break
+ seen.append(data)
+ total = sum(len(b"%d\n" % i) for i in range(1, 3001))
+ assert offset == total
+ assert b"".join(seen).endswith(b"2999\n3000\n")
+
+
+async def test_a_program_holding_tail_log_open_only_delays_its_refresh(tmp_path, monkeypatch):
+ """Python's ``open`` does not share delete, so no replace can land while it holds tail.log: the wrapper
+ keeps the tail and writes it at the next snapshot, instead of stopping the command."""
+ monkeypatch.setattr(jobs_module, "OUTPUT_HEAD_BYTES", 1000)
+ host = _host(tmp_path)
+ job_id = await _start(
+ host,
+ tmp_path,
+ "import sys, time\n"
+ "for i in range(1, 3001):\n"
+ " sys.stdout.buffer.write(b'%d\\n' % i)\n"
+ " if i % 100 == 0:\n"
+ " sys.stdout.flush(); time.sleep(0.05)\n",
+ )
+ tail = os.path.join(host.job_dir(job_id), "tail.log")
+ assert _wait_until(lambda: os.path.exists(tail))
+ with open(tail, "rb"):
+ await asyncio.sleep(0.6) # several snapshots come due meanwhile
+
+ assert await host.wait(job_id, deadline_s=15) == jobs_module.JobStatus("exited", 0)
+ assert host.stop_reason(job_id) is None
+ data, _ = host.output(job_id, os.path.getsize(host.output_path(job_id)))
+ assert data.endswith(b"2999\n3000\n")
+
+
+def _hold(path, sharing):
+ """``path`` open for reading in another program's way: sharing reading and writing (Python's ``open``,
+ ``Get-Content -Wait``) or reading alone, and never delete."""
+ if sharing == "reading and writing":
+ return open(path, "rb")
+ import ctypes
+ import msvcrt
+ from ctypes import wintypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p] + [
+ wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE
+ ]
+ kernel32.CreateFileW.restype = wintypes.HANDLE
+ handle = kernel32.CreateFileW(path, 0x80000000, 0x1, None, 3, 0, None) # GENERIC_READ, FILE_SHARE_READ
+ assert handle not in (None, ctypes.c_void_p(-1).value), ctypes.get_last_error()
+ return os.fdopen(msvcrt.open_osfhandle(handle, os.O_RDONLY), "rb")
+
+
[email protected]("sharing", ["reading and writing", "reading alone"])
+async def test_a_program_holding_tail_log_when_the_command_exits_leaves_its_exit_as_it_is(
+ tmp_path, monkeypatch, sharing
+):
+ """The last tail cannot be renamed into place then: it is written into the file itself, which such a program
+ shares for writing, and one that shares neither keeps the tail before it while it holds the file. The exit is
+ the command's either way."""
+ monkeypatch.setattr(jobs_module, "OUTPUT_HEAD_BYTES", 10)
+ host = _host(tmp_path)
+ release = tmp_path / "release"
+ job_id = await _start(
+ host,
+ tmp_path,
+ "import os, sys, time\n"
+ "sys.stdout.buffer.write(b'x' * 100 + b'\\nfirst\\n'); sys.stdout.flush()\n"
+ f"while not os.path.exists(r'{release}'): time.sleep(0.01)\n"
+ "sys.stdout.buffer.write(b'last\\n'); sys.stdout.flush()\n"
+ "sys.exit(3)\n",
+ )
+ assert _wait_until(lambda: host.output(job_id, 10)[0].endswith(b"first\n"))
+ held = _hold(os.path.join(host.job_dir(job_id), "tail.log"), sharing)
+ try:
+ release.write_text("")
+ status = await host.wait(job_id, deadline_s=15)
+ data, _ = host.output(job_id, 10)
+ finally:
+ held.close()
+
+ assert status == jobs_module.JobStatus("exited", 3)
+ assert host.stop_reason(job_id) is None
+ assert data.endswith(b"first\nlast\n" if sharing == "reading and writing" else b"first\n")
+
+
[email protected](not os.environ.get("AVIBE_TEST_FAT_DIR"), reason="needs a FAT volume (AVIBE_TEST_FAT_DIR)")
+async def test_jobs_run_with_their_files_on_a_volume_without_hard_links(tmp_path):
+ """FAT has no hard links: a decision and a stop reason are each created once by a rename instead."""
+ jobs_dir = Path(os.environ["AVIBE_TEST_FAT_DIR"]) / f"jobs-{secrets.token_hex(4)}"
+ host = LocalJobHost(str(jobs_dir), shell=sys.executable)
+ try:
+ done = await _start(host, tmp_path, "import sys; sys.stdout.buffer.write(b'ran\\n')")
+ assert await host.wait(done, deadline_s=15) == jobs_module.JobStatus("exited", 0)
+ assert host.output(done)[0] == b"ran\n"
+ running = await _start(host, tmp_path, "import time; time.sleep(60)", tool_call_id="toolu_2")
+ await host.kill(running)
+ assert host.stop_reason(running) == "killed"
+ assert (await host.wait(running, deadline_s=15)).state == "gone"
+ finally:
+ for entry in jobs_dir.iterdir():
+ job = windows_job.open_job(f"avibe-job-{entry.name}")
+ if job is not None:
+ try:
+ windows_job.terminate_job(job)
+ finally:
+ windows_job.close_handle(job)
+ shutil.rmtree(jobs_dir, ignore_errors=True)
+
+
+async def test_a_process_the_command_leaves_running_keeps_the_job_until_it_ends_or_is_killed(tmp_path):
+ """POSIX leaves it in the process group; here the wrapper stays, so its job, and ``kill``, still hold it."""
+ host = _host(tmp_path)
+ job_id = await _start(host, tmp_path, _tree(tmp_path, then="pass"))
+ shell, grandchild = _tree_pids(tmp_path)
+
+ assert await host.wait(job_id, deadline_s=10) == jobs_module.JobStatus("exited", 0)
+ assert _wait_until(lambda: _gone(shell))
+ assert not _gone(grandchild) and not _gone(_wrapper_pid(host, job_id))
+ assert host.prune(lambda meta: True, older_than_s=-60) == []
+
+ await host.kill(job_id)
+ assert _wait_until(lambda: _gone(grandchild) and _gone(_wrapper_pid(host, job_id)))
+
+
+async def test_job_files_stay_until_the_call_is_settled(tmp_path):
+ """J5."""
+ host = _host(tmp_path)
+ finished = await _start(host, tmp_path, "pass", tool_call_id="finished")
+ running = await _start(host, tmp_path, "import time; time.sleep(60)", tool_call_id="running")
+ await host.wait(finished, deadline_s=10)
+ assert _wait_until(lambda: _gone(_wrapper_pid(host, finished)))
+
+ assert host.prune(lambda meta: False, older_than_s=0) == []
+ assert host.prune(lambda meta: True, older_than_s=0) == [finished]
+ assert os.path.isdir(host.job_dir(running))
+ await host.kill(running)
+
+
+async def test_hand_over_gives_a_job_at_most_one_watch(tmp_path, monkeypatch):
+ """J6."""
+ watches: dict[str, str] = {}
+
+ async def adopt_or_create(meta):
+ return watches.setdefault(meta["job_id"], f"wch_{len(watches) + 1}")
+
+ host = _host(tmp_path, on_hand_over=adopt_or_create)
+ job_id = await _start(host, tmp_path, "import time; time.sleep(60)")
+ _crash_on_meta_write(monkeypatch, 1)
+ with pytest.raises(Crash):
+ await host.hand_over(job_id)
+ monkeypatch.undo()
+
+ recovery = _host(tmp_path, on_hand_over=adopt_or_create)
+ assert await recovery.hand_over(job_id) == "wch_1"
+ assert await recovery.hand_over(job_id) == "wch_1"
+ assert watches == {job_id: "wch_1"}
+ await recovery.kill(job_id)
+
+
+async def test_settlement_reports_each_job_state(tmp_path, make_ctx):
+ """T2: exited, running (handed over), stopped with a reason, and unknown, after a restart."""
+ by_job: dict[str, str] = {}
+
+ async def watches(meta):
+ return by_job.setdefault(meta["job_id"], f"wch_{len(by_job) + 1}")
+
+ host = _host(tmp_path, on_hand_over=watches)
+ foreground = await BashTool(host).execute(
+ {"command": "import sys; sys.stdout.write('out\\n'); sys.exit(4)"}, make_ctx(tool_call_id="exited")
+ )
+ await BashTool(host, foreground_window_s=0.2).execute(
+ {"command": "import time; print('still', flush=True); time.sleep(60)"}, make_ctx(tool_call_id="running")
+ )
+
+ recovery = _host(tmp_path, on_hand_over=watches)
+ exited = await settle_bash_call(recovery, instance("exited"))
+ assert (result_text(exited), exited.is_error) == (result_text(foreground), True)
+ running = await settle_bash_call(recovery, instance("running"))
+ assert result_text(running).startswith("Command is still running and is now Watch wch_1.")
+ assert await settle_bash_call(recovery, instance("unknown")) is None
+ await recovery.kill(running.details["job_id"], reason="aborted")
+ stopped = await settle_bash_call(recovery, instance("running"))
+ assert result_text(stopped).endswith("Stopped by the user; the command was terminated.")
+
+
+async def test_a_timeout_holds_across_handover_and_a_restart(tmp_path, make_ctx):
+ """J3: the deadline is the job's, so the next owner enforces it."""
+ by_job: dict[str, str] = {}
+
+ async def watches(meta):
+ return by_job.setdefault(meta["job_id"], f"wch_{len(by_job) + 1}")
+
+ result = await BashTool(_host(tmp_path, on_hand_over=watches)).execute(
+ {"command": _tree(tmp_path), "timeout": 60, "watch": True}, make_ctx()
+ )
+ job_id = result.details["job_id"]
+ shell, grandchild = _tree_pids(tmp_path)
+ restarted = _host(tmp_path)
+ meta = restarted.meta(job_id)
+ meta["deadline_at"] = jobs_module._iso(datetime.now(timezone.utc))
+ restarted._write_meta(job_id, meta)
+
+ status = await asyncio.wait_for(restarted.wait(job_id, deadline_s=None), timeout=15)
+
+ assert status.state == "gone"
+ assert restarted.stop_reason(job_id) == "timeout"
+ assert _wait_until(lambda: _gone(shell) and _gone(grandchild))
+
+
+async def test_vibe_stop_ends_every_running_job(tmp_path):
+ from core.watches import JOB_STOP_VIBE_STOP, stop_all_jobs
+
+ host = _host(tmp_path)
+ job_id = await _start(host, tmp_path, _tree(tmp_path))
+ shell, grandchild = _tree_pids(tmp_path)
+
+ await asyncio.to_thread(stop_all_jobs, jobs_dir=tmp_path / "jobs")
+
+ assert _wait_until(lambda: _gone(shell) and _gone(grandchild))
+ assert host.stop_reason(job_id) == JOB_STOP_VIBE_STOP
diff --git a/tests/agent_core/tools/test_read.py b/tests/agent_core/tools/test_read.py
index 8871468fc..99cad01c7 100644
--- a/tests/agent_core/tools/test_read.py
+++ b/tests/agent_core/tools/test_read.py
@@ -279,6 +279,24 @@ async def test_a_fifo_swapped_in_after_the_check_does_not_block_read(tmp_path, m
assert (result.is_error, result_text(result)) == (True, "Cannot read p: it is not a regular file.")
[email protected](os.name != "nt", reason="POSIX never stops a rename onto an open file")
+def test_a_file_being_read_can_still_be_replaced(tmp_path):
+ """Windows refuses a replace onto a name held open without ``FILE_SHARE_DELETE``: a job's wrapper replaces
+ the ``tail.log`` the model reads, and a failed replace stops the job's command."""
+ from core.agent_core.tools import windows_files
+ from core.agent_core.tools.paths import open_regular
+
+ (tmp_path / "tail.log").write_bytes(b"old")
+ (tmp_path / "next").write_bytes(b"new")
+ fd = open_regular(str(tmp_path / "tail.log"))
+ try:
+ windows_files.replace(str(tmp_path / "next"), str(tmp_path / "tail.log"))
+ assert os.read(fd, 10) == b"old"
+ finally:
+ os.close(fd)
+ assert (tmp_path / "tail.log").read_bytes() == b"new"
+
+
async def test_a_huge_png_shaped_file_is_classified_without_walking_it(tmp_path, make_ctx):
"""A sparse file of empty PNG chunks: image work is bounded by the cap, not by the file."""
path = tmp_path / "huge.png"