session.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. """ACP session manager — maps ACP sessions to Hermes AIAgent instances.
  2. Sessions are persisted to the shared SessionDB (``~/.hermes/state.db``) so they
  3. survive process restarts and appear in ``session_search``; ``load_session`` /
  4. ``resume_session`` after an editor reconnect restore the full history from there.
  5. """
  6. from __future__ import annotations
  7. from hermes_constants import get_hermes_home, translate_cwd_for_wsl_backend, windows_path_to_wsl
  8. import copy
  9. import json
  10. import logging
  11. import os
  12. import re
  13. import sys
  14. import threading
  15. import time
  16. import uuid
  17. from datetime import datetime, timezone, UTC
  18. from dataclasses import dataclass, field
  19. from typing import Any, Dict, List, Optional
  20. logger = logging.getLogger(__name__)
  21. def _translate_acp_cwd(cwd: str) -> str:
  22. """Translate Windows ACP cwd values (``E:\\Projects``, ``\\\\wsl.localhost\\``) to POSIX form
  23. when Hermes runs in WSL so agents, tools, and persisted sessions agree; no-op elsewhere."""
  24. return translate_cwd_for_wsl_backend(str(cwd))
  25. def _normalize_cwd_for_compare(cwd: str | None) -> str:
  26. expanded = os.path.expanduser(str(cwd or ".").strip() or ".")
  27. # Windows drive paths -> WSL mount form so history filters match across hosts.
  28. translated = windows_path_to_wsl(expanded)
  29. if translated is not None:
  30. expanded = translated
  31. elif re.match(r"^/mnt/[A-Za-z]/", expanded):
  32. expanded = f"/mnt/{expanded[5].lower()}/{expanded[7:]}"
  33. # realpath resolves symlink aliases (macOS ``/var`` vs ``/private/var``, ``/tmp`` vs
  34. # ``/private/tmp``) that otherwise drop a workspace's own sessions; it is lexical
  35. # for missing paths (e.g. WSL-translated drives).
  36. try:
  37. # Resolve symlink aliases so equivalent spellings of the same directory compare equal — macOS
  38. # reports editor workspaces as ``/var/...`` while sessions get stored under ``/private/var/...``
  39. # (and ``/tmp`` vs ``/private/tmp``), which made ACP history filters silently drop a workspace's own
  40. # sessions. WSL-translated Windows drives — keep the previous normpath behavior. Ported from
  41. # PrimeIntellect-ai/prime-agent#628.
  42. return os.path.realpath(expanded)
  43. except OSError:
  44. return os.path.normpath(expanded)
  45. def _build_session_title(title: Any, preview: Any, cwd: str | None) -> str:
  46. leaf = os.path.basename(str(cwd or "").rstrip("/\\"))
  47. return str(title or "").strip() or str(preview or "").strip() or leaf or "New thread"
  48. def _format_updated_at(value: Any) -> str | None:
  49. if value is None or (isinstance(value, str) and value.strip()):
  50. return value
  51. try:
  52. return datetime.fromtimestamp(float(value), tz=UTC).isoformat()
  53. except Exception:
  54. return None
  55. def _updated_at_sort_key(value: Any) -> float:
  56. if isinstance(value, (int, float)):
  57. return float(value)
  58. raw = str(value).strip() if value is not None else ""
  59. if not raw:
  60. return float("-inf")
  61. for parse in (lambda s: datetime.fromisoformat(s).timestamp(), float):
  62. try:
  63. return parse(raw)
  64. except Exception:
  65. continue
  66. return float("-inf")
  67. def _acp_stderr_print(*args, **kwargs) -> None:
  68. """Route incidental AIAgent output to stderr; ACP reserves stdout for JSON-RPC."""
  69. kwargs.setdefault("file", sys.stderr)
  70. print(*args, **kwargs)
  71. def _register_task_cwd(task_id: str, cwd: str) -> None:
  72. """Bind a task/session id to the editor cwd for tools. Zed may send a Windows cwd while
  73. the ACP process runs in WSL; tools need the WSL mount or subprocess creation fails."""
  74. if not task_id:
  75. return
  76. try:
  77. from tools.terminal_tool import register_task_env_overrides
  78. register_task_env_overrides(task_id, {"cwd": _translate_acp_cwd(cwd)})
  79. except Exception:
  80. logger.debug("Failed to register ACP task cwd override", exc_info=True)
  81. def _expand_acp_enabled_toolsets(toolsets: list[str] | None = None,
  82. mcp_server_names: list[str] | None = None) -> list[str]:
  83. """Return ACP toolsets plus explicit MCP server toolsets for this session."""
  84. names = [n for n in (["hermes-acp"] if toolsets is None else toolsets) if n]
  85. names += [f"mcp-{s}" for s in (mcp_server_names or []) if s]
  86. return list(dict.fromkeys(names))
  87. def _parse_model_config(mc: Any) -> dict:
  88. """Decode a persisted model_config JSON blob; ``{}`` when absent/invalid/non-dict."""
  89. try:
  90. meta = json.loads(mc) if mc else None
  91. except (json.JSONDecodeError, TypeError):
  92. meta = None
  93. return meta if isinstance(meta, dict) else {}
  94. def _session_info(sid: str, cwd: str, model: Any, history_len: int, title: Any, preview: Any,
  95. updated_at: Any) -> dict[str, Any]:
  96. return {"session_id": sid, "cwd": cwd, "model": model, "history_len": history_len,
  97. "title": _build_session_title(title, preview, cwd), "updated_at": _format_updated_at(updated_at)}
  98. def _first_user_preview(history: list[dict[str, Any]], default: str) -> str:
  99. return next((str(m.get("content") or "").strip() for m in history
  100. if m.get("role") == "user" and str(m.get("content") or "").strip()), default)
  101. @dataclass
  102. class SessionState:
  103. """Tracks per-session state for an ACP-managed Hermes agent."""
  104. session_id: str
  105. agent: Any # AIAgent instance
  106. cwd: str = "."
  107. model: str = ""
  108. history: list[dict[str, Any]] = field(default_factory=list)
  109. cancel_event: Any = None # threading.Event
  110. is_running: bool = False
  111. # A state-mutating slash command (/reset, /compress, /model) is in flight. Turn claims
  112. # must queue behind it: /compress's LLM call and /model's agent rebuild take seconds, so
  113. # a bare is_running check in the slash thread would leave a check-then-act window where
  114. # a prompt claims the turn mid-mutation.
  115. command_op: bool = False
  116. queued_prompts: list[str] = field(default_factory=list)
  117. runtime_lock: Any = field(default_factory=threading.Lock)
  118. current_prompt_text: str = ""
  119. interrupted_prompt_text: str = ""
  120. # Per-session allocator for ACP assistant messageIds (lazily created by
  121. # the server so streamed chunks group into distinct assistant replies).
  122. message_ids: Any = None
  123. class SessionManager:
  124. """Thread-safe manager for ACP sessions backed by Hermes AIAgent instances.
  125. Sessions are held in-memory for fast access **and** persisted to the shared
  126. SessionDB so they survive restarts and are searchable via ``session_search``."""
  127. def __init__(self, agent_factory=None, db=None):
  128. """``agent_factory``: AIAgent-like factory (tests); default builds a real AIAgent from
  129. the runtime provider config. ``db``: SessionDB; default lazily opens ``~/.hermes/state.db``."""
  130. self._sessions: dict[str, SessionState] = {}
  131. self._lock = threading.Lock()
  132. # Serializes DB restores: session construction runs off the event loop, so two
  133. # overlapping session/load for one id must share a single agent build.
  134. self._restore_lock = threading.Lock()
  135. self._agent_factory = agent_factory
  136. self._db_instance = db # None → lazy-init on first use
  137. self._cwd_backfilled = False
  138. # ---- public API ---------------------------------------------------------
  139. def create_session(self, cwd: str = ".") -> SessionState:
  140. """Create a new session with a unique ID and a fresh AIAgent."""
  141. cwd = _translate_acp_cwd(cwd)
  142. session_id = str(uuid.uuid4())
  143. agent = self._make_agent(session_id=session_id, cwd=cwd)
  144. state = self._install_state(session_id, agent, cwd, getattr(agent, "model", "") or "", [])
  145. logger.info("Created ACP session %s (cwd=%s)", session_id, cwd)
  146. return state
  147. def get_session(self, session_id: str) -> Optional[SessionState]:
  148. """Return the session, transparently restoring it from the DB (e.g. after
  149. a process restart) when it is not in memory; ``None`` if unknown."""
  150. with self._lock:
  151. state = self._sessions.get(session_id)
  152. if state is not None:
  153. return state
  154. with self._restore_lock:
  155. with self._lock:
  156. state = self._sessions.get(session_id) # a concurrent restore may have installed it
  157. return state if state is not None else self._restore(session_id)
  158. def fork_session(self, session_id: str, cwd: str = ".") -> Optional[SessionState]:
  159. """Deep-copy a session's history into a new session."""
  160. cwd = _translate_acp_cwd(cwd)
  161. original = self.get_session(session_id) # checks DB too
  162. if original is None:
  163. return None
  164. new_id = str(uuid.uuid4())
  165. agent = self._make_agent(session_id=new_id, cwd=cwd, model=original.model or None)
  166. model = getattr(agent, "model", original.model) or original.model
  167. state = self._install_state(new_id, agent, cwd, model, copy.deepcopy(original.history))
  168. logger.info("Forked ACP session %s -> %s", session_id, new_id)
  169. return state
  170. def list_sessions(self, cwd: str | None = None) -> list[dict[str, Any]]:
  171. """Return lightweight info dicts for all sessions (memory + database)."""
  172. normalized_cwd = _normalize_cwd_for_compare(cwd) if cwd else None
  173. persisted_rows = self._catalog_rows()
  174. def _matches(session_cwd: str) -> bool:
  175. return not normalized_cwd or _normalize_cwd_for_compare(session_cwd) == normalized_cwd
  176. # In-memory sessions first.
  177. with self._lock:
  178. seen_ids = set(self._sessions.keys())
  179. results = []
  180. for s in self._sessions.values():
  181. if not s.history or not _matches(s.cwd):
  182. continue
  183. persisted = persisted_rows.get(s.session_id, {})
  184. results.append(_session_info(
  185. s.session_id, s.cwd, s.model, len(s.history), persisted.get("title"),
  186. _first_user_preview(s.history, persisted.get("preview") or ""),
  187. persisted.get("last_active") or persisted.get("started_at") or time.time(),
  188. ))
  189. # Then persisted sessions not currently in memory.
  190. for sid, row in persisted_rows.items():
  191. message_count = int(row.get("message_count") or 0)
  192. session_cwd = _parse_model_config(row.get("model_config")).get("cwd", ".")
  193. if sid in seen_ids or message_count <= 0 or not _matches(session_cwd):
  194. continue
  195. results.append(_session_info(
  196. sid, session_cwd, row.get("model") or "", message_count, row.get("title"),
  197. row.get("preview"), row.get("last_active") or row.get("started_at"),
  198. ))
  199. results.sort(key=lambda item: _updated_at_sort_key(item.get("updated_at")), reverse=True)
  200. return results
  201. def _catalog_rows(self) -> dict[str, dict[str, Any]]:
  202. from acp_adapter.catalog import read_catalog_rows
  203. from pathlib import Path
  204. path = Path(self._db_instance.db_path) if self._db_instance is not None else get_hermes_home() / "state.db"
  205. return read_catalog_rows(path)
  206. def update_cwd(self, session_id: str, cwd: str) -> Optional[SessionState]:
  207. """Update the working directory for a session and its tool overrides."""
  208. cwd = _translate_acp_cwd(cwd)
  209. state = self.get_session(session_id) # checks DB too
  210. if state is None:
  211. return None
  212. state.cwd = cwd
  213. _register_task_cwd(session_id, cwd)
  214. self._persist(state)
  215. # Promote the authoritative column and claim an ordering generation, the
  216. # same contract tui_gateway/session_workdir.py uses: a git probe may only
  217. # publish while its generation is still current, so a slow probe for a
  218. # previous workspace cannot overwrite a newer claim (A -> B -> A).
  219. self._schedule_git_metadata(state, self._claim_cwd_generation(state))
  220. return state
  221. def save_session(self, session_id: str) -> None:
  222. """Persist a session; called by the server after prompt completion,
  223. history-mutating slash commands, and model switches."""
  224. with self._lock:
  225. state = self._sessions.get(session_id)
  226. if state is not None:
  227. self._persist(state)
  228. def end_all_sessions(self, end_reason: str = "acp_disconnect") -> int:
  229. """Stamp ``ended_at`` on every live session (#118216).
  230. ACP v0.9 has no per-session destroy, so the stdio shutdown that ends
  231. this process is the session end: the client that drove the
  232. conversation is gone. Without this writer, source='acp' rows keep
  233. ``ended_at`` NULL forever and the ended-session guard shared by
  234. prune/archive (``hermes_state_maintenance``) can never reach them.
  235. A later load/resume reopens the row (see ``_restore``), the same
  236. contract the TUI gateway's resume path uses. Best-effort: teardown
  237. must never raise. Returns the number of sessions ended.
  238. """
  239. db = self._get_db()
  240. if db is None:
  241. return 0
  242. with self._lock:
  243. session_ids = list(self._sessions.keys())
  244. ended = 0
  245. for session_id in session_ids:
  246. try:
  247. db.end_session(session_id, end_reason)
  248. ended += 1
  249. except Exception:
  250. logger.debug("Failed to end ACP session %s", session_id, exc_info=True)
  251. if ended:
  252. logger.info("Ended %d ACP session(s) on shutdown (%s)", ended, end_reason)
  253. return ended
  254. # ---- persistence via SessionDB ------------------------------------------
  255. def _install_state(self, session_id: str, agent: Any, cwd: str, model: str,
  256. history: list[dict[str, Any]], *, persist: bool = True) -> SessionState:
  257. """Build a SessionState, register it in memory, bind its cwd for tools, optionally persist."""
  258. state = SessionState(session_id=session_id, agent=agent, cwd=cwd, model=model,
  259. history=history, cancel_event=threading.Event())
  260. with self._lock:
  261. self._sessions[session_id] = state
  262. _register_task_cwd(session_id, cwd)
  263. if persist:
  264. self._persist(state)
  265. return state
  266. def _get_db(self):
  267. """Lazily acquire the process-shared SessionDB; ``None`` if unavailable (e.g. import
  268. error in a minimal test env). ``HERMES_HOME`` is resolved here, not via the import-time
  269. ``DEFAULT_DB_PATH``, so test fixtures that change the env var later are honoured. The
  270. registry handle is the one in-process tools (delegation, session_search, goals) also
  271. acquire, so the ACP server holds ONE writer on state.db instead of two (#100896)."""
  272. if self._db_instance is None:
  273. try:
  274. from hermes_state_registry import acquire
  275. self._db_instance = acquire(get_hermes_home() / "state.db")
  276. except Exception:
  277. logger.debug("SessionDB unavailable for ACP persistence", exc_info=True)
  278. if self._db_instance is not None and not self._cwd_backfilled:
  279. # Rows minted before the adapter wrote the cwd column still carry the workspace
  280. # in model_config; one idempotent UPDATE per process repairs them (#115705).
  281. self._cwd_backfilled = True
  282. try:
  283. repaired = self._db_instance.backfill_acp_session_cwd()
  284. if repaired:
  285. logger.info("Backfilled cwd for %d ACP session(s) from model_config", repaired)
  286. except Exception:
  287. logger.debug("ACP session cwd backfill failed", exc_info=True)
  288. return self._db_instance
  289. def _persist(self, state: SessionState) -> None:
  290. """Create/update the session record, then sync the live message set."""
  291. db = self._get_db()
  292. if db is None:
  293. return
  294. # Ensure model is a plain string (not a MagicMock or other proxy).
  295. model_str = str(state.model) if state.model else None
  296. session_meta = {"cwd": state.cwd}
  297. for key in ("provider", "base_url", "api_mode"):
  298. value = getattr(state.agent, key, None)
  299. if isinstance(value, str) and value.strip():
  300. session_meta[key] = value.strip()
  301. try:
  302. if db.get_session(state.session_id) is None:
  303. if not state.history:
  304. # Empty editor probes stay ephemeral; copied fork history persists.
  305. return
  306. db.create_session(session_id=state.session_id, source="acp", model=model_str,
  307. model_config=session_meta, cwd=state.cwd or None)
  308. else:
  309. try:
  310. db.update_session_meta(state.session_id, json.dumps(session_meta), model_str)
  311. except Exception:
  312. logger.debug("Failed to update ACP session metadata", exc_info=True)
  313. # The create branch above is not the live path: an agent that owns
  314. # persistence to this same DB flushes the transcript incrementally,
  315. # so the row already exists by the time we get here.
  316. # update_session_meta touches only model_config/model, so without
  317. # this promotion the column stays NULL for the whole session and
  318. # Desktop files it as unassigned. Claiming a generation keeps the
  319. # A -> B -> A ordering contract shared with update_cwd().
  320. if state.cwd:
  321. self._schedule_git_metadata(state, self._claim_cwd_generation(state))
  322. # An agent that owns persistence to this same DB already flushed the transcript
  323. # incrementally (append_message) and keeps pre-compaction turns as archived
  324. # active=0 rows; replace_messages() would DELETE those (and, after a compression
  325. # id rotation, clobber the ended parent transcript). Skip it in that case.
  326. # Calling replace_messages() here would then be a redundant double-write that DELETEs exactly
  327. # those archived rows (and, after a compression-driven id rotation where agent.session_id no
  328. # longer equals state.session_id, clobbers the ended parent transcript) — silent data loss for
  329. # any ACP conversation long enough to compress. Only fall back to the destructive atomic replace
  330. # when the agent is NOT persisting itself to this DB (e.g. a test agent factory, or a fresh
  331. # create/fork whose copied history the agent has not flushed yet). That path still rolls back on
  332. # a mid-rewrite failure so the previously persisted conversation survives (salvaged from
  333. # #13675).
  334. agent = state.agent
  335. if getattr(agent, "_session_db", None) is db and getattr(agent, "_session_db_created", False):
  336. return
  337. # A non-owning agent (model switch, /restore: fresh agent, _session_db_created=False)
  338. # may still sit on archived rows, so replace ONLY the active=1 set: on a fresh
  339. # create/fork every row is active (== full replace), and archived rows survive.
  340. # Unconditional because an existence probe would fail OPEN on DB error and can
  341. # race a concurrent archive_and_compact. Still rolls back on mid-rewrite failure.
  342. db.replace_messages(state.session_id, state.history, active_only=True)
  343. except Exception:
  344. logger.warning("Failed to persist ACP session %s", state.session_id, exc_info=True)
  345. def _claim_cwd_generation(self, state: SessionState) -> Optional[int]:
  346. """Write the cwd column and return its new git-metadata generation.
  347. Returns None when the row does not exist yet (a contentless session is
  348. deliberately ephemeral until it has history) or the DB is unavailable.
  349. """
  350. db = self._get_db()
  351. if db is None or not state.cwd:
  352. return None
  353. try:
  354. return db.update_session_cwd(state.session_id, state.cwd)
  355. except Exception:
  356. logger.debug("Failed to persist ACP session cwd column for %s",
  357. state.session_id, exc_info=True)
  358. return None
  359. def _schedule_git_metadata(self, state: SessionState, generation: Optional[int]) -> None:
  360. """Probe git off the critical path and publish under ``generation``.
  361. ``session/new`` is on the editor's interactive path; ``git rev-parse``
  362. on a cold or networked filesystem is not something to put in front of
  363. the user. The generation guard in ``publish_session_git_metadata``
  364. means a slow probe for a previous workspace is dropped rather than
  365. applied to the new one.
  366. """
  367. if not generation or not state.cwd:
  368. return
  369. session_id, cwd = state.session_id, state.cwd
  370. def _run() -> None:
  371. try:
  372. from tui_gateway import git_probe
  373. branch, root = git_probe.branch(cwd), git_probe.common_repo_root(cwd)
  374. if not (branch or root):
  375. return
  376. db = self._get_db()
  377. if db is not None:
  378. db.publish_session_git_metadata(session_id, cwd, generation, branch, root)
  379. except Exception:
  380. logger.debug("Failed to publish ACP git metadata for %s", session_id, exc_info=True)
  381. threading.Thread(target=_run, name=f"acp-git-meta-{session_id[:8]}", daemon=True).start()
  382. def _restore(self, session_id: str) -> Optional[SessionState]:
  383. """Load an ACP session from the database into memory, recreating the AIAgent."""
  384. db = self._get_db()
  385. if db is None:
  386. return None
  387. try:
  388. row = db.get_session(session_id)
  389. except Exception:
  390. logger.debug("Failed to query DB for ACP session %s", session_id, exc_info=True)
  391. return None
  392. if row is None or row.get("source") != "acp":
  393. return None
  394. # A previous adapter process stamped the row ended at its stdio
  395. # shutdown (#118216); resuming the conversation reopens it, the same
  396. # contract the TUI gateway's cold-resume path uses.
  397. if row.get("ended_at") is not None:
  398. try:
  399. db.reopen_session(session_id)
  400. except Exception:
  401. logger.debug("Failed to reopen ACP session %s", session_id, exc_info=True)
  402. meta = _parse_model_config(row.get("model_config"))
  403. cwd, model = meta.get("cwd", "."), row.get("model") or None
  404. # repair_alternation: this list becomes the resumed agent's LIVE conversation; a durable
  405. # ``user;user`` violation in state.db would otherwise re-fire the pre-request repair every request.
  406. try:
  407. history = db.get_messages_as_conversation(session_id, repair_alternation=True)
  408. except Exception:
  409. logger.warning("Failed to load messages for ACP session %s", session_id, exc_info=True)
  410. history = []
  411. try:
  412. agent = self._make_agent(
  413. session_id=session_id, cwd=cwd, model=model, api_mode=meta.get("api_mode") or None,
  414. requested_provider=meta.get("provider") or row.get("billing_provider"),
  415. base_url=meta.get("base_url") or row.get("billing_base_url"))
  416. except Exception:
  417. logger.warning("Failed to recreate agent for ACP session %s", session_id, exc_info=True)
  418. return None
  419. state = self._install_state(session_id, agent, cwd, model or getattr(agent, "model", "") or "",
  420. history, persist=False)
  421. logger.info("Restored ACP session %s from DB (%d messages)", session_id, len(history))
  422. return state
  423. # ---- internal -----------------------------------------------------------
  424. def _make_agent(self, *, session_id: str, cwd: str, model: str | None = None,
  425. requested_provider: str | None = None, base_url: str | None = None, api_mode: str | None = None,
  426. enabled_toolsets: list[str] | None = None, disabled_toolsets: list[str] | None = None):
  427. """``enabled_toolsets``/``disabled_toolsets`` carry a live session's toolsets into a rebuild; ``None`` derives
  428. them from config (fresh session)."""
  429. if self._agent_factory is not None:
  430. return self._agent_factory()
  431. from run_agent import AIAgent
  432. from agent.skill_utils import parse_config_string_list
  433. from hermes_cli.config import load_config
  434. from hermes_cli.runtime_provider import resolve_runtime_provider
  435. from hermes_cli.tools_config import _get_platform_tools, enabled_mcp_server_names
  436. from hermes_constants import resolve_reasoning_config
  437. config = load_config()
  438. model_cfg = config.get("model")
  439. default_model, config_provider = "", None
  440. if isinstance(model_cfg, dict):
  441. default_model, config_provider = str(model_cfg.get("default") or ""), model_cfg.get("provider")
  442. elif isinstance(model_cfg, str):
  443. default_model = model_cfg.strip()
  444. if enabled_toolsets is None:
  445. # The same per-platform resolver as the gateway/cron/api_server: platform_toolsets.acp wins, else
  446. # hermes-acp; its MCP half (every enabled server, a listed-name allowlist, or none for ``no_mcp``)
  447. # comes back as bare server names, which ACP keys as ``mcp-<server>`` like its session servers.
  448. resolved = _get_platform_tools(config, "acp")
  449. mcp_servers = resolved & enabled_mcp_server_names(config)
  450. enabled_toolsets = _expand_acp_enabled_toolsets(sorted(resolved - mcp_servers), sorted(mcp_servers))
  451. kwargs = {
  452. "platform": "acp", "quiet_mode": True, "session_id": session_id, "session_db": self._get_db(),
  453. "enabled_toolsets": list(enabled_toolsets),
  454. # agent.disabled_toolsets is subtracted at tool granularity by the agent, as on the CLI/gateway/cron.
  455. "disabled_toolsets": (list(disabled_toolsets) if disabled_toolsets is not None
  456. else parse_config_string_list((config.get("agent") or {}).get("disabled_toolsets")) or None),
  457. "model": model or default_model,
  458. "cwd": cwd,
  459. # Same chokepoint as the CLI/gateway/TUI/cron: without it ``agent.reasoning_effort: none`` never
  460. # reaches an ACP session and the transport applies its default effort (a 400 on non-reasoning
  461. # models). Resolved against the session's model so per-model overrides apply.
  462. "reasoning_config": resolve_reasoning_config(config, model or default_model),
  463. }
  464. resolve_error: Exception | None = None
  465. try:
  466. runtime = resolve_runtime_provider(
  467. requested=requested_provider or config_provider, target_model=(model or default_model) or None)
  468. kwargs.update({
  469. "provider": runtime.get("provider"), "api_mode": api_mode or runtime.get("api_mode"),
  470. "base_url": base_url or runtime.get("base_url"), "api_key": runtime.get("api_key"),
  471. "credential_pool": runtime.get("credential_pool"),
  472. "command": runtime.get("command"), "args": list(runtime.get("args") or []),
  473. })
  474. # The resolved provider's request body (a custom entry's extra_body); an explicit base_url pointing
  475. # elsewhere is another endpoint, which must not inherit it.
  476. if runtime.get("request_overrides") and (not base_url or base_url == runtime.get("base_url")):
  477. kwargs["request_overrides"] = runtime["request_overrides"]
  478. except Exception as exc:
  479. resolve_error = exc
  480. logger.debug("ACP session falling back to default provider resolution", exc_info=True)
  481. _register_task_cwd(session_id, cwd)
  482. # Bounded wait for the background MCP discovery started by entry.py: the agent
  483. # snapshots tools once at build and never re-reads the registry, so without this
  484. # join a slow-but-reachable server would be invisible all session. ensure_* also
  485. # (re)starts discovery if the entry spawn never ran or connected zero servers.
  486. # Bounded by ``mcp_discovery_timeout`` (config.yaml, ~1.5s); late servers are
  487. # picked up by HermesACPAgent._schedule_mcp_late_refresh.
  488. try:
  489. from hermes_cli.mcp_startup import ensure_mcp_discovery_before_agent_build
  490. ensure_mcp_discovery_before_agent_build(logger=logger, thread_name="acp-mcp-discovery")
  491. except Exception:
  492. logger.debug("ACP: bounded MCP discovery wait failed", exc_info=True)
  493. try:
  494. agent = AIAgent(**kwargs)
  495. except Exception as exc:
  496. # The bare-AIAgent fallback dies with "No LLM provider configured. Run `hermes setup`" on a
  497. # machine that is configured and was working a call earlier; the swallowed resolution
  498. # failure (revoked OAuth, disabled provider, ...) is the actionable error (#91090).
  499. if resolve_error is not None:
  500. raise resolve_error from exc
  501. raise
  502. # ACP stdio: stdout is protocol-only JSON-RPC; agent chatter goes to stderr.
  503. agent._print_fn = _acp_stderr_print
  504. return agent