Skip to content

The agent that grows with you

Setup: start the user scan when the setup profile is ensured (#129240)

Siddharth Balyan0756232f448e
diff --git a/agent/initiate_setup_prompt.py b/agent/initiate_setup_prompt.py
index b78bb1d6681..ce30d1df56b 100644
--- a/agent/initiate_setup_prompt.py
+++ b/agent/initiate_setup_prompt.py
@@ -3,9 +3,11 @@ from __future__ import annotations
import importlib.util
import json
import re
+import threading
from pathlib import Path
+from typing import NamedTuple
-from hermes_constants import get_optional_skills_dir
+from hermes_constants import get_optional_skills_dir, hermes_home_key
HEADER = "[/initiate-setup]"
@@ -14,15 +16,45 @@ HEADER = "[/initiate-setup]"
_HOST_FACTS_HOOK = re.compile(r"^!`[^`\n]*scripts/host_facts\.py`$", re.M)
+class _ScanJob(NamedTuple):
+ thread: threading.Thread
+ box: dict
+
+
+# One user scan in flight per Hermes home. host_facts.py is loaded fresh on every call, so the jobs live here.
+_SCANS: dict[str, _ScanJob] = {}
+_SCANS_LOCK = threading.Lock()
+
+
def _skill_dir() -> Path:
return get_optional_skills_dir(Path(__file__).resolve().parent.parent / "optional-skills") / "productivity" / "initiate-setup"
-def _host_facts(skill_dir: Path) -> dict:
+def _host_facts_module(skill_dir: Path):
spec = importlib.util.spec_from_file_location("initiate_setup_host_facts", skill_dir / "scripts" / "host_facts.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
- return module.collect()
+ return module
+
+
+def start_user_scan() -> _ScanJob:
+ """Start the user scan for the bound Hermes home unless one is already running there.
+
+ The worker inherits the caller's profile scope, so the scan caches into that home's
+ ``insights/profile.json``. A finished job is not reused: the next start reads that cache.
+ Another process that scans the same home waits on this one through the scan's lease file.
+ """
+ from agent.memory_provider import spawn_context_thread
+
+ key = hermes_home_key()
+ with _SCANS_LOCK:
+ job = _SCANS.get(key)
+ if job is None or not job.thread.is_alive():
+ box: dict = {}
+ scan = _host_facts_module(_skill_dir()).scan_into
+ job = _SCANS[key] = _ScanJob(spawn_context_thread(scan, name="initiate-setup-scan", args=(box,)), box)
+ job.thread.start()
+ return job
def build_initiate_setup_prompt(surface: str, tools, primary_profile: str) -> str:
@@ -35,8 +67,11 @@ def build_initiate_setup_prompt(surface: str, tools, primary_profile: str) -> st
"primary_profile": primary_profile,
"guest_free_tier": free_tier_route(),
}
+ host_facts = _host_facts_module(skill_dir)
+ # Waits on the scan the setup profile started at creation instead of scanning a second time.
+ scanned = host_facts.scan_outcome(*start_user_scan())
# Same bytes the hook prints when the skill loads through inline shell.
- host = json.dumps(_host_facts(skill_dir), ensure_ascii=False, separators=(",", ":"))
+ host = json.dumps(host_facts.collect(scanned), ensure_ascii=False, separators=(",", ":"))
skill = (skill_dir / "SKILL.md").read_text(encoding="utf-8-sig").strip()
skill = _HOST_FACTS_HOOK.sub(lambda _: host, skill)
facts = json.dumps(block, indent=2, ensure_ascii=False)
diff --git a/optional-skills/productivity/initiate-setup/scripts/host_facts.py b/optional-skills/productivity/initiate-setup/scripts/host_facts.py
index 23201a9832f..a9498bf72be 100644
--- a/optional-skills/productivity/initiate-setup/scripts/host_facts.py
+++ b/optional-skills/productivity/initiate-setup/scripts/host_facts.py
@@ -25,6 +25,7 @@ import re
import sys
import threading
import time
+from contextlib import suppress
from datetime import datetime, timezone
from pathlib import Path
@@ -49,6 +50,10 @@ SCAN_DIR = Path(__file__).resolve().parent / "userscan"
SCAN_TIER = "T1"
SCAN_CACHE_MAX_AGE_S = 24 * 3600
SCAN_DEADLINE_S = 11
+# Another process scanning the same home holds ``profile.json.scanning``. Its scan can overrun a
+# waiter's deadline, so the lease counts as abandoned only after twice that.
+SCAN_LEASE_STALE_S = 2 * SCAN_DEADLINE_S
+_LEASE_POLL_S = 0.1
SETTLING_DAYS = 120
_NOT_VISIBLE_T1 = [
@@ -325,6 +330,38 @@ def _cache_is_fresh(profile: dict, version: str) -> bool:
and 0 <= (datetime.now(timezone.utc) - started).total_seconds() < SCAN_CACHE_MAX_AGE_S)
+def _published(path: Path, seen: datetime | None, version: str) -> dict | None:
+ """The fresh profile another scan wrote to ``path`` after the one started at ``seen``."""
+ done = _read_json(path)
+ return done if done and _started(done) != seen and _cache_is_fresh(done, version) else None
+
+
+def _await_lease(lease: Path, path: Path, seen: datetime | None, version: str) -> None:
+ """Wait while another process scans this home: until it publishes, or its lease is gone or stale."""
+ while _published(path, seen, version) is None:
+ try:
+ age = time.time() - lease.stat().st_mtime
+ except OSError:
+ return
+ if age >= SCAN_LEASE_STALE_S:
+ with suppress(OSError):
+ lease.unlink()
+ return
+ time.sleep(_LEASE_POLL_S)
+
+
+def _full_scan(run, path: Path | None) -> dict:
+ started = datetime.now(timezone.utc).isoformat(timespec="seconds")
+ profile = run(max_tier=SCAN_TIER)
+ profile["run"]["started"] = started
+ if path is not None:
+ try:
+ _write_private(path, profile)
+ except OSError:
+ pass
+ return profile
+
+
def _scan_now() -> tuple[dict, str]:
if str(SCAN_DIR) not in sys.path:
sys.path.insert(0, str(SCAN_DIR))
@@ -343,34 +380,55 @@ def _scan_now() -> tuple[dict, str]:
if p.level == "L1" and p.os in ("any", here)}))
if _l1_fired(l1) == _l1_fired(cached):
return cached, "cache"
- started = datetime.now(timezone.utc).isoformat(timespec="seconds")
- profile = run(max_tier=SCAN_TIER)
- profile["run"]["started"] = started
- if path is not None:
+ if path is None:
+ return _full_scan(run, None), "fresh"
+ # One full scan per home across processes: the setup RPC and the setup chat run in different
+ # backends on the desktop, and the inline-shell hook runs this file as its own process.
+ lease = path.with_name(f"{path.name}.scanning")
+ seen = _started(cached) if cached else None
+ while (done := _published(path, seen, __version__)) is None:
try:
- _write_private(path, profile)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd = os.open(lease, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ except FileExistsError:
+ _await_lease(lease, path, seen, __version__)
+ continue
except OSError:
- pass
- return profile, "fresh"
-
-
-def _scan() -> tuple[dict | None, str]:
- box: dict = {}
-
- def work() -> None:
+ return _full_scan(run, path), "fresh"
try:
- box["result"] = _scan_now()
- except Exception as exc:
- box["error"] = type(exc).__name__
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump({"pid": os.getpid(), "started": time.time()}, handle)
+ return _full_scan(run, path), "fresh"
+ finally:
+ with suppress(OSError):
+ lease.unlink()
+ return done, "cache"
+
+
+def scan_into(box: dict) -> None:
+ """Scan and put ``result`` or ``error`` in ``box``. The ``/initiate-setup`` builder runs
+ this as its shared background job, so the first turn does not wait for a second scan."""
+ try:
+ box["result"] = _scan_now()
+ except Exception as exc:
+ box["error"] = type(exc).__name__
- worker = threading.Thread(target=work, daemon=True)
- worker.start()
+
+def scan_outcome(worker: threading.Thread, box: dict) -> tuple[dict | None, str]:
+ """Wait up to the deadline for ``worker`` running :func:`scan_into` on ``box``."""
worker.join(SCAN_DEADLINE_S)
if "result" in box:
return box["result"]
return None, box.get("error", "timeout")
+def _scan() -> tuple[dict | None, str]:
+ box: dict = {}
+ worker = threading.Thread(target=scan_into, args=(box,), daemon=True)
+ worker.start()
+ return scan_outcome(worker, box)
+
+
def _value(profile: dict, fid: str) -> dict | None:
record = profile.get("facts", {}).get(fid)
if isinstance(record, dict) and record.get("status") == "ok" and isinstance(record.get("value"), dict):
@@ -559,12 +617,10 @@ def _machine_state(scan: dict | None, age: int | None) -> tuple[str, int | None]
return ("fresh" if age <= NEW_MACHINE_DAYS else "settling" if age < SETTLING_DAYS else "established"), age
-def collect(scan_json: Path | None = None) -> dict:
- """Return the fact block the ``/initiate-setup`` first turn embeds."""
- if scan_json is not None:
- profile, source = _read_json(scan_json), "file"
- else:
- profile, source = _scan()
+def collect(scanned: tuple[dict | None, str] | None = None) -> dict:
+ """Return the fact block the ``/initiate-setup`` first turn embeds. ``scanned`` is a
+ ``(profile, source)`` pair from a scan already run; without it this scans now."""
+ profile, source = scanned if scanned is not None else _scan()
scan = interpret(profile, source) if profile else {"source": "unavailable", "reason": source}
os_family = facts.os_family()
@@ -625,7 +681,8 @@ def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--from-json", type=Path, help="interpret this saved scan instead of scanning")
args = parser.parse_args()
- print(json.dumps(collect(args.from_json), ensure_ascii=False, separators=(",", ":")))
+ scanned = (_read_json(args.from_json), "file") if args.from_json else None
+ print(json.dumps(collect(scanned), ensure_ascii=False, separators=(",", ":")))
if __name__ == "__main__":
diff --git a/tui_gateway/methods_onboarding.py b/tui_gateway/methods_onboarding.py
index fef089c732a..1c0eac0c78b 100644
--- a/tui_gateway/methods_onboarding.py
+++ b/tui_gateway/methods_onboarding.py
@@ -13,6 +13,7 @@ def _(rid, params: dict) -> dict:
_mirror_launch_credentials(setup.path, {"share_auth": True})
except Exception as e:
return _err(rid, 5073, str(e))
+ _start_setup_scan(setup.path)
return _ok(rid, {"name": setup.name, "path": str(setup.path), "created": setup.created})
@@ -36,6 +37,7 @@ def _(rid, params: dict) -> dict:
release_or_close(db)
except Exception as e:
return _err(rid, 5075, str(e))
+ _start_setup_scan(setup.path)
return _ok(rid, {"profile": setup.name, "session_id": row["id"], "empty": not row["message_count"]})
@@ -71,6 +73,18 @@ def _(rid, params: dict) -> dict:
return _ok(rid, {"name": setup.name, "path": str(setup.path), "reset": True})
+def _start_setup_scan(profile_dir) -> None:
+ """Scan the machine while the fixed beats play, so ``/initiate-setup`` reads the setup
+ home's cache (or joins this scan) instead of scanning on the first model turn."""
+ from agent.initiate_setup_prompt import start_user_scan
+ try:
+ with _session_profile_runtime_scope({"profile_home": str(profile_dir)}, hydrate_secrets=False):
+ start_user_scan()
+ except Exception:
+ # The first turn scans on its own, so a failed prescan costs only time.
+ logger.warning("setup user scan did not start", exc_info=True)
+
+
def _onboarding_state_result(rid, change) -> dict:
from hermes_cli.setup_profile import find_setup_profile, onboarding_eligible
try: