The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor: resolve runtime temp paths via tempfile/TMPDIR instead of literal /tmp
teknium1e16fee4db11c
diff --git a/acp_adapter/server.py b/acp_adapter/server.pyindex f2a0ed4731e..482e6abe33d 100644--- a/acp_adapter/server.py+++ b/acp_adapter/server.py@@ -238,7 +238,7 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):"accept_edits": ("workspace_session","Accept Edits",- "Auto-allow workspace and /tmp edits; still asks for sensitive paths.",+ "Auto-allow workspace and temp-dir edits; still asks for sensitive paths.",),"dont_ask": ("session", "Don't Ask", "Auto-allow file edits for this session except sensitive paths."diff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.pyindex 39e4e197e64..fcb98f08240 100644--- a/agent/copilot_acp_client.py+++ b/agent/copilot_acp_client.py@@ -14,6 +14,7 @@ import queueimport reimport shleximport subprocess+import tempfileimport threadingimport timefrom collections import deque@@ -103,7 +104,7 @@ def _acp_supported(command: str, args: list[str]) -> bool | None:def _resolve_home_dir() -> str:- """Stable HOME for child ACP processes; /tmp as a last resort so the child never starts HOME-less."""+ """Stable HOME for child ACP processes; the temp dir as a last resort so the child never starts HOME-less."""if home := os.environ.get("HOME", "").strip():return homeif (expanded := os.path.expanduser("~")) and expanded != "~":@@ -111,9 +112,9 @@ def _resolve_home_dir() -> str:try:import pwd- return pwd.getpwuid(os.getuid()).pw_dir.strip() or "/tmp" # windows-footgun: ok — POSIX fallback inside try/except (pwd import fails on Windows)+ return pwd.getpwuid(os.getuid()).pw_dir.strip() or tempfile.gettempdir() # windows-footgun: ok — POSIX fallback inside try/except (pwd import fails on Windows)except Exception:- return "/tmp"+ return tempfile.gettempdir()def _build_subprocess_env() -> dict[str, str]:diff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.pyindex 34e1435cd70..900b8153871 100644--- a/hermes_cli/hooks.py+++ b/hermes_cli/hooks.py@@ -156,7 +156,7 @@ _DEFAULT_PAYLOADS = {"child_summary": "Synthetic summary for hooks test", "child_status": "completed","tool_call_history": [{"tool_name": "write_file",- "tool_input": {"argument_keys": ["content", "path"], "targets": {"path": "/tmp/report.txt"}},+ "tool_input": {"argument_keys": ["content", "path"], "targets": {"path": "notes/report.txt"}},"input_bytes": 128, "output_bytes": 32, "status": "ok",}],"duration_ms": 1234,diff --git a/hermes_cli/send_cmd.py b/hermes_cli/send_cmd.pyindex ec3c5efc39c..efb9ba62dd0 100644--- a/hermes_cli/send_cmd.py+++ b/hermes_cli/send_cmd.py@@ -281,10 +281,10 @@ def register_send_subparser(subparsers) -> argparse.ArgumentParser:"Examples:\n"" hermes send --to telegram \"deploy finished\"\n"" echo \"RAM 92%\" | hermes send --to telegram:-1001234567890\n"- " hermes send --to discord:#ops --file /tmp/report.md\n"+ " hermes send --to discord:#ops --file ./report.md\n"" hermes send --to slack:#eng --subject \"[CI]\" --file build.log\n"" hermes send --to whatsapp:[email protected] --mention 15551234567 \"@15551234567 hello\"\n"- " hermes send --to telegram \"MEDIA:/tmp/chart.png\" # send a media attachment\n"+ " hermes send --to telegram \"MEDIA:./chart.png\" # send a media attachment\n"" hermes send --list # all platforms\n"" hermes send --list telegram # filter by platform\n""\n"diff --git a/hermes_cli/subcommands/approvals.py b/hermes_cli/subcommands/approvals.pyindex b5cb6ff4896..eeb2f8704c3 100644--- a/hermes_cli/subcommands/approvals.py+++ b/hermes_cli/subcommands/approvals.py@@ -52,7 +52,7 @@ def build_approvals_parser(subparsers, *, cmd_approvals: Callable) -> None:"executing the command, prompting anyone, or persisting anything. ""Exit codes: 0 allow, 2 ask-approval, 3 deny (hardline or user ""deny rule). Tip: use `--` before the command so its own flags "- "aren't parsed: hermes approvals test -- rm -rf /tmp/x")+ "aren't parsed: hermes approvals test -- rm -rf ./build")test_parser.add_argument("--env-type", dest="env_type", default="local",help="Terminal backend type to evaluate against (default: local; "diff --git a/mini_swe_runner.py b/mini_swe_runner.pyindex 62fb8179a8e..62410d8e33d 100644--- a/mini_swe_runner.py+++ b/mini_swe_runner.py@@ -8,7 +8,7 @@ trajectory_compressor.py. Supports single tasks and JSONL batch mode.Usage:python mini_swe_runner.py --task "Create a hello world Python script" --env local- python mini_swe_runner.py --task "List files in /tmp" --env docker --image python:3.11-slim+ python mini_swe_runner.py --task "List files in the working directory" --env docker --image python:3.11-slimpython mini_swe_runner.py --prompts_file prompts.jsonl --output_file trajectories.jsonl --env docker"""@@ -16,6 +16,7 @@ import importlibimport jsonimport loggingimport os+import tempfilefrom datetime import datetimefrom typing import List, Dict, Any, Optional@@ -96,13 +97,17 @@ HERMES_SYSTEM_SUFFIX = (_OPENROUTER_URL = "https://openrouter.ai/api/v1"-def create_environment(env_type: str = "local", image: str = "python:3.11-slim", cwd: str = "/tmp", timeout: int = 60, **kwargs):- """Create a Hermes execution environment (``local`` ignores ``image``/``kwargs``)."""+def create_environment(env_type: str = "local", image: str = "python:3.11-slim", cwd: str | None = None, timeout: int = 60, **kwargs):+ """Create a Hermes execution environment (``local`` ignores ``image``/``kwargs``).++ ``cwd=None`` means the host temp dir locally and the sandbox's own ``/tmp`` inside a container.+ """if env_type == "local":from tools.environments.local import LocalEnvironment- return LocalEnvironment(cwd=cwd, timeout=timeout)+ return LocalEnvironment(cwd=cwd or tempfile.gettempdir(), timeout=timeout)if env_type not in ("docker", "modal"):raise ValueError(f"Unknown environment type: {env_type}. Use 'local', 'docker', or 'modal'")+ cwd = cwd or "/tmp" # container-side path, not the host temp dirmodule = importlib.import_module(f"tools.environments.{env_type}")return getattr(module, f"{env_type.capitalize()}Environment")(image=image, cwd=cwd, timeout=timeout, **kwargs)@@ -126,7 +131,7 @@ class MiniSWERunner:"""Tool-calling agent loop over a Hermes execution environment, emitting Hermes trajectories."""def __init__(self, model: str = "anthropic/claude-sonnet-4.6", base_url: str = None, api_key: str = None,- env_type: str = "local", image: str = "python:3.11-slim", cwd: str = "/tmp",+ env_type: str = "local", image: str = "python:3.11-slim", cwd: str | None = None,max_iterations: int = 15, command_timeout: int = 60, verbose: bool = False):self.model, self.max_iterations, self.command_timeout, self.verbose = model, max_iterations, command_timeout, verboseself.env_type, self.image, self.cwd = env_type, image, cwd@@ -349,7 +354,7 @@ def main(api_key: str = None,env: str = "local",image: str = "python:3.11-slim",- cwd: str = "/tmp",+ cwd: str | None = None,max_iterations: int = 15,timeout: int = 60,verbose: bool = False,@@ -366,7 +371,7 @@ def main(api_key: API key (optional, uses env vars)env: Environment type - "local", "docker", or "modal"image: Docker/Modal image (default: python:3.11-slim)- cwd: Working directory (default: /tmp)+ cwd: Working directory (default: host temp dir locally, /tmp inside a container)max_iterations: Maximum tool-calling iterations (default: 15)timeout: Command timeout in seconds (default: 60)verbose: Enable verbose loggingdiff --git a/plugins/google_meet/meet_bot.py b/plugins/google_meet/meet_bot.pyindex 35124408d95..5c65f434812 100644--- a/plugins/google_meet/meet_bot.py+++ b/plugins/google_meet/meet_bot.py@@ -4,7 +4,7 @@ Standalone subprocess spawned by ``process_manager.py``; configured via ``HERMESstatus + transcript written under ``$HERMES_MEET_OUT_DIR`` (filesystem is the only IPC).No WebRTC audio parsing: Meet's live captions are watched via a MutationObserver — lossy andEnglish-biased, but deterministic (no STT billing) and stable thanks to the ARIA role.-Debug: ``HERMES_MEET_URL=... HERMES_MEET_OUT_DIR=/tmp/x HERMES_MEET_HEADED=1 \\+Debug: ``HERMES_MEET_URL=... HERMES_MEET_OUT_DIR=./meet-out HERMES_MEET_HEADED=1 \\python -m plugins.google_meet.meet_bot``"""diff --git a/scripts/ci/live_comment.py b/scripts/ci/live_comment.pyindex 708906d3ae6..f710b855e2f 100644--- a/scripts/ci/live_comment.py+++ b/scripts/ci/live_comment.py@@ -58,6 +58,7 @@ import jsonimport osimport shutilimport sys+import tempfileimport timeimport urllib.errorimport urllib.request@@ -451,7 +452,7 @@ def fetch_all_review_statuses(Artifacts that don't exist yet or fail to parse are silently skipped."""all_statuses: list[dict] = []- temp_base = Path("/tmp/review-status-artifacts")+ temp_base = Path(tempfile.gettempdir()) / "review-status-artifacts"try:artifacts = _list_artifacts(token, repo, run_id)diff --git a/scripts/desktop-update/repro.sh b/scripts/desktop-update/repro.shindex f2d39a3bf8d..55bb8ecd383 100755--- a/scripts/desktop-update/repro.sh+++ b/scripts/desktop-update/repro.sh@@ -2,7 +2,7 @@# repro.sh -- reproduce desktop-update paths against a sandboxed HERMES_HOME.## Nothing here touches your real ~/.hermes or checkout. Each mode builds (or-# reuses) a disposable install under /tmp and drives the REAL code path --+# reuses) a disposable install under $TMPDIR and drives the REAL code path --# the actual installer, the actual orchestrator, the actual `hermes update`.## repro.sh shim shim UI only: success event after 6s@@ -18,7 +18,7 @@# sandbox preflight, opt-out fallbacks) -- asserts# every outcome without touching a real install#-# The sandbox persists between runs (~/tmp is fine to nuke): fresh reuses+# The sandbox persists between runs (the scratch dir is fine to nuke): fresh reuses# nothing, behind/error reuse the last sandbox install when present because# a from-scratch install is minutes.#@@ -93,9 +93,9 @@ case "$MODE" in;;gate)# Pure-decision matrix for the linux relaunch gate. Builds a fake- # checkout layout under /tmp; --self-test-gate prints the decision and+ # checkout layout under $TMPDIR; --self-test-gate prints the decision and# exits without running an update.- G="/tmp/hermes-gate-test.$$"+ G="$(mktemp -d -t hermes-gate-test.XXXXXX)"UNPACKED="$G/hermes-agent/apps/desktop/release/linux-unpacked"mkdir -p "$UNPACKED"touch "$UNPACKED/hermes" && chmod +x "$UNPACKED/hermes"@@ -136,7 +136,7 @@ case "$MODE" in# of the outcome. Each case runs the REAL orchestrator (--no-ui) against# a fake install whose `hermes` stub exits 0 instantly, so the flow# reaches finish() with FINAL_CODE=0 and exercises the launch leg.- L="/tmp/hermes-launch-test.$$"+ L="$(mktemp -d -t hermes-launch-test.XXXXXX)"fails=0expect_msg() { # name python-exprif python3 -c "import json,sys; d=json.load(open('$L/.hermes-update-result.json')); sys.exit(0 if ($2) else 1)"; thendiff --git a/scripts/install.sh b/scripts/install.shindex 93167399966..a53eef68962 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -610,8 +610,8 @@ install_uv() {# `curl | sh` masks curl failures (sh exits 0 on empty stdin)# and conflates network errors with installer errors.local _uv_install_log _uv_installer- _uv_install_log="$(mktemp 2>/dev/null || echo "/tmp/hermes-uv-install.$$.log")"- _uv_installer="$(mktemp 2>/dev/null || echo "/tmp/hermes-uv-installer.$$.sh")"+ _uv_install_log="$(mktemp 2>/dev/null || echo "${TMPDIR:-$HERMES_HOME}/hermes-uv-install.$$.log")"+ _uv_installer="$(mktemp 2>/dev/null || echo "${TMPDIR:-$HERMES_HOME}/hermes-uv-installer.$$.sh")"if ! curl -LsSf https://astral.sh/uv/install.sh -o "$_uv_installer" 2>"$_uv_install_log"; thenlog_error "Failed to download uv installer from https://astral.sh/uv/install.sh"log_info "curl output:"diff --git a/scripts/launch_capture_probe.sh b/scripts/launch_capture_probe.shindex 45dc5ee06fb..e630040ef95 100755--- a/scripts/launch_capture_probe.sh+++ b/scripts/launch_capture_probe.sh@@ -39,18 +39,20 @@ echo "OK"echo "--- treatment 1: source shape (npm exec -- electron .) captured, not spawned"rm -f "$WORK"/spec.json*run_py yes -c '-import subprocess-r = subprocess.run(["npm", "exec", "--", "electron", "."], cwd="/tmp", env={"HERMES_DESKTOP_CWD": "/tmp", "PATH": "/usr/bin"})+import subprocess, tempfile+tmp = tempfile.gettempdir()+r = subprocess.run(["npm", "exec", "--", "electron", "."], cwd=tmp, env={"HERMES_DESKTOP_CWD": tmp, "PATH": "/usr/bin"})assert r.returncode == 0, r'[ -e "$WORK/spec.json" ] || fail "treatment 1: no spec written"[ "$(cat "$WORK/spec.json.captured")" = "source" ] || fail "treatment 1: wrong shape"python3 - "$WORK/spec.json" <<'EOF'-import json, sys+import json, sys, tempfile+tmp = tempfile.gettempdir()spec = json.load(open(sys.argv[1]))assert spec["argv"] == ["npm", "exec", "--", "electron", "."], spec["argv"]-assert spec["cwd"] == "/tmp", spec["cwd"]-assert spec["env"]["HERMES_DESKTOP_CWD"] == "/tmp", "env= kwarg not captured"+assert spec["cwd"] == tmp, spec["cwd"]+assert spec["env"]["HERMES_DESKTOP_CWD"] == tmp, "env= kwarg not captured"assert spec["matchedShape"] == "source"print("spec contents OK")EOF@@ -59,9 +61,9 @@ echo "OK"echo "--- treatment 2: packaged shape captured, not spawned"rm -f "$WORK"/spec.json*run_py yes -c '-import subprocess+import subprocess, tempfileexe = "/x/apps/desktop/release/linux-unpacked/Hermes"-r = subprocess.run([exe, "--no-sandbox"], cwd="/tmp", env={"PATH": "/usr/bin"})+r = subprocess.run([exe, "--no-sandbox"], cwd=tempfile.gettempdir(), env={"PATH": "/usr/bin"})assert r.returncode == 0, r # a real spawn of this path would ENOENT'[ "$(cat "$WORK/spec.json.captured")" = "packaged" ] || fail "treatment 2: wrong shape"diff --git a/scripts/profile-tui.py b/scripts/profile-tui.pyindex 4d86aa057bf..d13fb70cac9 100755--- a/scripts/profile-tui.py+++ b/scripts/profile-tui.py@@ -31,6 +31,7 @@ import selectimport signalimport sqlite3import sys+import tempfileimport timefrom pathlib import Pathfrom typing import Any@@ -487,9 +488,9 @@ def main() -> int:p.add_argument("--tui-dir", default=str(DEFAULT_TUI_DIR))p.add_argument("--log", default=str(DEFAULT_LOG))p.add_argument("--save", metavar="LABEL",- help="save the final metrics as /tmp/perf-<LABEL>.json for later --compare")+ help="save the final metrics as <tempdir>/perf-<LABEL>.json for later --compare")p.add_argument("--compare", metavar="LABEL",- help="diff against /tmp/perf-<LABEL>.json after running")+ help="diff against <tempdir>/perf-<LABEL>.json after running")p.add_argument("--loop", action="store_true",help="watch for source changes, rebuild, rerun, and diff vs previous run")p.add_argument("--extra-flag", dest="extra_flags", action="append", default=[],@@ -507,17 +508,17 @@ def main() -> int:metrics = key_metrics(data)if args.save:- path = Path(f"/tmp/perf-{args.save}.json")+ path = Path(tempfile.gettempdir()) / f"perf-{args.save}.json"path.write_text(json.dumps(metrics, indent=2), encoding="utf-8")print(f"\n• saved: {path}")if args.compare:- path = Path(f"/tmp/perf-{args.compare}.json")+ path = Path(tempfile.gettempdir()) / f"perf-{args.compare}.json"if not path.exists():print(f"\n⚠ no baseline at {path} — run with --save {args.compare} first")else:before = json.loads(path.read_text(encoding="utf-8"))- print(f"\n═══ A/B diff vs /tmp/perf-{args.compare}.json ═══")+ print(f"\n═══ A/B diff vs {path} ═══")print(format_diff(before, metrics))if not data["react"] and not data["frame"]:diff --git a/setup-hermes.sh b/setup-hermes.shindex 218cfb13f12..149640c3c61 100755--- a/setup-hermes.sh+++ b/setup-hermes.sh@@ -87,8 +87,8 @@ else# full, etc.) instead of "✗ Failed to install uv" with zero# diagnostic. Two-stage to avoid `curl | sh` masking curl# failures (sh exits 0 on empty stdin under no pipefail).- _uv_log="$(mktemp 2>/dev/null || echo "/tmp/hermes-uv-install.$$.log")"- _uv_installer="$(mktemp 2>/dev/null || echo "/tmp/hermes-uv-installer.$$.sh")"+ _uv_log="$(mktemp 2>/dev/null || echo "${TMPDIR:-${HERMES_HOME:-$HOME/.hermes}}/hermes-uv-install.$$.log")"+ _uv_installer="$(mktemp 2>/dev/null || echo "${TMPDIR:-${HERMES_HOME:-$HOME/.hermes}}/hermes-uv-installer.$$.sh")"if ! curl -LsSf https://astral.sh/uv/install.sh -o "$_uv_installer" 2>"$_uv_log"; thenecho -e "${RED}✗${NC} Failed to download uv installer."sed 's/^/ /' "$_uv_log" >&2diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.pyindex 894e7a21105..9ba2739f6ce 100644--- a/tools/code_execution_tool.py+++ b/tools/code_execution_tool.py@@ -469,7 +469,7 @@ def _env_temp_dir(env: Any) -> str:for candidate in (temp_dir, tempfile.gettempdir()):if isinstance(candidate, str) and candidate.startswith("/"):return candidate.rstrip("/") or "/"- return "/tmp"+ return tempfile.gettempdir()def _format_interrupted_output(stdout_text: str) -> str:diff --git a/tools/process_registry.py b/tools/process_registry.pyindex 601f7308aed..d300eaed215 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -14,6 +14,7 @@ import shleximport signalimport statimport subprocess+import tempfileimport threadingimport timeimport uuid@@ -965,7 +966,7 @@ class ProcessRegistry(ProcessCheckpointMixin):return temp_dir.rstrip("/") or "/"except Exception as exc:logger.debug("Could not resolve environment temp dir: %s", exc)- return "/tmp"+ return tempfile.gettempdir()def _scope_argv(self, session: ProcessSession, safe_command: str, unit_suffix: str, label: str) -> List[str]:"""Login-shell argv for *safe_command* (parity with LocalEnvironment: rc filesdiff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.pyindex e8ad2a0ccb9..f00a3a79dc7 100644--- a/tools/tool_result_storage.py+++ b/tools/tool_result_storage.py@@ -10,6 +10,7 @@ import loggingimport osimport reimport shlex+import tempfileimport threadingimport time@@ -18,7 +19,7 @@ from tools.budget_config import DEFAULT_PREVIEW_SIZE_CHARS, BudgetConfig, DEFAULlogger = logging.getLogger(__name__)PERSISTED_OUTPUT_TAG = "<persisted-output>"PERSISTED_OUTPUT_CLOSING_TAG = "</persisted-output>"-STORAGE_DIR = "/tmp/hermes-results"+STORAGE_DIR = os.path.join(tempfile.gettempdir(), "hermes-results")SPILLOVER_SUBDIR = "cache/spillover"SPILLOVER_MAX_AGE_HOURS = 24_BUDGET_TOOL_NAME = "__budget_enforcement__"diff --git a/tools/voice_mode.py b/tools/voice_mode.pyindex b420132774f..62690dade22 100644--- a/tools/voice_mode.py+++ b/tools/voice_mode.py@@ -320,13 +320,13 @@ def detect_audio_environment() -> dict:"Voice INPUT (recording) still requires a PulseAudio bridge:\n"" 1. Set PULSE_SERVER=unix:/mnt/wslg/PulseServer\n"" 2. Create ~/.asoundrc pointing ALSA at PulseAudio\n"- " 3. Verify with: arecord -d 3 /tmp/test.wav && aplay /tmp/test.wav")+ " 3. Verify with: arecord -d 3 test.wav && aplay test.wav")else:warnings.append("Running in WSL -- audio requires a forwarded sound server.\n"" PulseAudio: export PULSE_SERVER=unix:/mnt/wslg/PulseServer\n"" PipeWire: export PIPEWIRE_REMOTE=$XDG_RUNTIME_DIR/pipewire-0\n"- " Then verify: arecord -d 3 /tmp/test.wav && aplay /tmp/test.wav")+ " Then verify: arecord -d 3 test.wav && aplay test.wav")_probe_audio_libraries(warnings, notices, has_forwarded_audio=has_forwarded_audio,termux_mic_cmd=termux_mic_cmd, termux_app_installed=termux_app_installed)