project_tools.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. #!/usr/bin/env python3
  2. """Project tools — the agent's INTENTIONAL handle on first-class Projects (per-profile
  3. ``projects.db``, the desktop sidebar's named workspaces). Creating/switching is an explicit
  4. tool call, never a side effect of ``cd``. GUI-only: the `project` toolset stays off
  5. ``_HERMES_CORE_TOOLS``; the desktop/TUI gateway folds it in and wires
  6. ``set_project_workspace_callback`` so the live session's cwd and sidebar follow. A live
  7. session create/switch re-anchors only that session; it must not move the profile-global
  8. Desktop selection shared by concurrent chats."""
  9. import json
  10. import os
  11. from typing import Callable, Optional
  12. from tools.registry import registry
  13. # Set by the GUI gateway: ``(task_id, primary_path, project_name)`` re-anchors that session's
  14. # workspace. ``None`` in CLI/messaging — the DB write still happens, nothing to move.
  15. _workspace_callback: Optional[Callable[[str, str, str], None]] = None
  16. def set_project_workspace_callback(fn: Optional[Callable[[str, str, str], None]]) -> None:
  17. global _workspace_callback
  18. _workspace_callback = fn
  19. def _primary_path(proj) -> Optional[str]:
  20. if getattr(proj, "primary_path", None):
  21. return proj.primary_path
  22. for folder in proj.folders:
  23. if folder.is_primary:
  24. return folder.path
  25. return proj.folders[0].path if proj.folders else None
  26. def _moves_session(task_id: Optional[str], path: Optional[str]) -> bool:
  27. """True when a live GUI session's workspace will follow the project — ``_apply_workspace``'s gate."""
  28. return bool(_workspace_callback and task_id and path)
  29. def _apply_workspace(task_id: Optional[str], path: Optional[str], name: str) -> None:
  30. cb = _workspace_callback
  31. if cb and task_id and path:
  32. try:
  33. cb(task_id, path, name)
  34. except Exception:
  35. pass
  36. def _resolve(conn, token: str):
  37. from hermes_cli import projects_db as pdb
  38. token = (token or "").strip()
  39. if not token:
  40. return None
  41. projects = pdb.list_projects(conn, include_archived=True)
  42. # Exact id / slug / name first, then case-insensitive slug / name.
  43. for proj in projects:
  44. if token in (proj.id, proj.slug) or proj.name == token:
  45. return proj
  46. low = token.lower()
  47. for proj in projects:
  48. if proj.slug.lower() == low or proj.name.lower() == low:
  49. return proj
  50. return None
  51. def _activated(proj, task_id: Optional[str]) -> str:
  52. primary = _primary_path(proj)
  53. _apply_workspace(task_id, primary, proj.name)
  54. return json.dumps({
  55. "success": True, "id": proj.id, "slug": proj.slug, "name": proj.name,
  56. "primary_path": primary})
  57. def _calling_session_project_id(conn, task_id: Optional[str]) -> tuple[bool, Optional[str]]:
  58. """``(scoped, project_id)`` for the calling session. The GUI gateway registers each session's
  59. workspace (``cwd_source``) in the terminal override table; a caller it never registered (CLI,
  60. scripts) is unscoped and falls back to the profile-global pointer."""
  61. from hermes_cli import projects_db as pdb
  62. from tools.terminal_tool import resolve_task_overrides
  63. overrides = resolve_task_overrides(task_id) if task_id else {}
  64. if "cwd_source" not in overrides:
  65. return False, None
  66. cwd = overrides.get("cwd") if overrides["cwd_source"] == "session" else overrides.get("host_workspace")
  67. project = pdb.project_for_path(conn, cwd) if cwd else None
  68. return True, project.id if project else None
  69. def project_list(task_id: Optional[str] = None) -> str:
  70. from hermes_cli import projects_db as pdb
  71. with pdb.connect_closing() as conn:
  72. # Another tab's switch moves the profile-global pointer; this chat's project is its own cwd.
  73. scoped, active = _calling_session_project_id(conn, task_id)
  74. if not scoped:
  75. active = pdb.get_active_id(conn)
  76. projects = pdb.list_projects(conn)
  77. return json.dumps({
  78. "active_id": active,
  79. "projects": [
  80. {
  81. "id": p.id, "slug": p.slug, "name": p.name,
  82. "primary_path": _primary_path(p), "active": p.id == active}
  83. for p in projects]})
  84. def project_create(name: str, path: Optional[str] = None, task_id: Optional[str] = None) -> str:
  85. name = (name or "").strip()
  86. if not name:
  87. return json.dumps({"success": False, "error": "name is required"})
  88. from hermes_cli import projects_db as pdb
  89. folder = (path or "").strip()
  90. if folder:
  91. folder = os.path.abspath(os.path.expanduser(folder))
  92. try:
  93. with pdb.connect_closing() as conn:
  94. existing = pdb.find_by_primary_path(conn, folder) if folder else None
  95. if existing is not None:
  96. # Idempotent create: the folder already belongs to a project. Reusing it beats minting
  97. # a duplicate — duplicated projects render N identical sidebar subtrees (#75820).
  98. proj = existing
  99. else:
  100. pid = pdb.create_project(conn, name=name, folders=[folder] if folder else [], primary_path=folder or None)
  101. proj = pdb.get_project(conn, pid)
  102. # A live session that moves owns its workspace, so it leaves the profile-global pointer
  103. # alone (a background chat would otherwise redirect the sidebar). Anything that can't
  104. # move — CLI/messaging, a pathless project — switches through the pointer instead.
  105. if proj is not None and not _moves_session(task_id, _primary_path(proj)):
  106. pdb.set_active(conn, proj.id)
  107. except ValueError as exc:
  108. return json.dumps({"success": False, "error": str(exc)})
  109. if proj is None:
  110. return json.dumps({"success": False, "error": "project vanished after create"})
  111. return _activated(proj, task_id)
  112. def project_switch(project: str, task_id: Optional[str] = None) -> str:
  113. from hermes_cli import projects_db as pdb
  114. with pdb.connect_closing() as conn:
  115. proj = _resolve(conn, project)
  116. if proj is None:
  117. return json.dumps({"success": False, "error": f"no project matching '{project}'"})
  118. # Same rule as create.
  119. if not _moves_session(task_id, _primary_path(proj)):
  120. pdb.set_active(conn, proj.id)
  121. return _activated(proj, task_id)
  122. _ACTIONS = {
  123. "list": lambda args, tid: project_list(task_id=tid),
  124. "create": lambda args, tid: project_create(
  125. name=args.get("name", ""), path=args.get("path"), task_id=tid),
  126. "switch": lambda args, tid: project_switch(project=args.get("name", ""), task_id=tid)}
  127. def _handle_project(args, **kw):
  128. action = _ACTIONS.get((args.get("action") or "").strip())
  129. if action is None:
  130. return json.dumps({"success": False, "error": "action must be one of: create, switch, list."})
  131. return action(args, kw.get("task_id"))
  132. # One action enum instead of three tools: each re-taught "desktop Projects" (244 -> ~145 tok).
  133. # Consolidated (#95681, maintainer-directed): project_list/create/switch each re-taught "desktop Projects
  134. # (named workspaces)"; one action enum says it once (244 -> ~145 tok).
  135. registry.register(
  136. name="desktop_project",
  137. toolset="project",
  138. schema={
  139. "name": "desktop_project",
  140. "description": (
  141. "Create or switch desktop Projects (named workspaces). create: one and switch "
  142. "this chat into it — pass path to anchor it to a repo/folder (the "
  143. "chat's workspace moves there, the sidebar follows). switch: move "
  144. "this chat into an existing project by name/slug/id — the "
  145. "intentional way to move the session, not `cd`. list: all projects + which one this chat is in."
  146. ),
  147. "parameters": {
  148. "type": "object",
  149. "properties": {
  150. "action": {"type": "string", "enum": ["create", "switch", "list"]},
  151. "name": {"type": "string", "description": "create: human name. switch: name, slug, or id."},
  152. "path": {"type": "string", "description": "create: repo/folder to anchor to."},
  153. },
  154. "required": ["action"],
  155. },
  156. },
  157. handler=_handle_project,
  158. )