Populate ``AGENTSPEX_RUN_*`` env vars and return ``(run_id, host_run_dir)``. This is the single point where per-run paths are decided. All entry points (``agentspex run``, ``agentspex cli``, ``run_agent.sh`` via Python) call this before YAML parsing so workflow authors can use ``${A
(
task_name: str,
override_run_id: Optional[str] = None,
resume: bool = False,
)
| 127 | |
| 128 | |
| 129 | def init_run_env( |
| 130 | task_name: str, |
| 131 | override_run_id: Optional[str] = None, |
| 132 | resume: bool = False, |
| 133 | ) -> tuple[str, Path]: |
| 134 | """Populate ``AGENTSPEX_RUN_*`` env vars and return ``(run_id, host_run_dir)``. |
| 135 | |
| 136 | This is the single point where per-run paths are decided. All entry |
| 137 | points (``agentspex run``, ``agentspex cli``, ``run_agent.sh`` via |
| 138 | Python) call this before YAML parsing so workflow authors can use |
| 139 | ``${AGENTSPEX_RUN_SANDBOX_DIR_ABS}`` in their YAML and it resolves to |
| 140 | a run-scoped directory on both the host and the sandbox. |
| 141 | |
| 142 | Resolution order for the run id: |
| 143 | 1. ``override_run_id`` (caller-provided — used by tests or external schedulers). |
| 144 | 2. Existing ``AGENTSPEX_RUN_ID`` in the environment (idempotent when |
| 145 | called multiple times in one process, or when a parent shell has |
| 146 | already decided the id). |
| 147 | 3. On ``resume=True``, the dirname of the most recent matching run dir. |
| 148 | 4. Otherwise, a fresh ``<task_name>_<YYYYMMDD-HHMMSS>`` id. |
| 149 | """ |
| 150 | ensure_runtime_dirs() |
| 151 | |
| 152 | existing = os.environ.get("AGENTSPEX_RUN_ID") |
| 153 | if override_run_id: |
| 154 | run_id = override_run_id |
| 155 | elif existing: |
| 156 | run_id = existing |
| 157 | elif resume: |
| 158 | latest = find_latest_run_dir(task_name) |
| 159 | run_id = latest.name if latest is not None else ( |
| 160 | f"{task_name}_{datetime.now().strftime(RUN_TIMESTAMP_FMT)}" |
| 161 | ) |
| 162 | else: |
| 163 | run_id = f"{task_name}_{datetime.now().strftime(RUN_TIMESTAMP_FMT)}" |
| 164 | |
| 165 | sandbox_rel = f"outputs/{run_id}" |
| 166 | sandbox_abs = f"/workspace/{sandbox_rel}" |
| 167 | host_run = outputs_root() / run_id |
| 168 | host_run.mkdir(parents=True, exist_ok=True) |
| 169 | |
| 170 | os.environ["AGENTSPEX_RUN_ID"] = run_id |
| 171 | os.environ["AGENTSPEX_RUN_SANDBOX_DIR"] = sandbox_rel |
| 172 | os.environ["AGENTSPEX_RUN_SANDBOX_DIR_ABS"] = sandbox_abs |
| 173 | os.environ["AGENTSPEX_RUN_HOST_DIR"] = str(host_run) |
| 174 | |
| 175 | return run_id, host_run |
| 176 | |
| 177 | |
| 178 | def ensure_runtime_dirs() -> None: |
no test coverage detected