seed-kernel 1.0.11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. seed/__init__.py +125 -0
  2. seed/cli.py +102 -0
  3. seed/core/__init__.py +8 -0
  4. seed/core/_session_cache.py +41 -0
  5. seed/core/agent_context.py +163 -0
  6. seed/core/agent_registry.py +180 -0
  7. seed/core/agent_runtime.py +2384 -0
  8. seed/core/chat_events.py +70 -0
  9. seed/core/commands.py +149 -0
  10. seed/core/config_plane.py +537 -0
  11. seed/core/engine.py +150 -0
  12. seed/core/env_access.py +168 -0
  13. seed/core/execution.py +148 -0
  14. seed/core/llm_exec.py +1652 -0
  15. seed/core/llm_presets.py +305 -0
  16. seed/core/llm_sess.py +1094 -0
  17. seed/core/media_store.py +84 -0
  18. seed/core/mem_bridge.py +294 -0
  19. seed/core/mem_sys.py +409 -0
  20. seed/core/model_providers.py +88 -0
  21. seed/core/models.py +211 -0
  22. seed/core/paths.py +109 -0
  23. seed/core/persistence.py +133 -0
  24. seed/core/proj_reg.py +609 -0
  25. seed/core/proj_todos.py +141 -0
  26. seed/core/projection_audit.py +317 -0
  27. seed/core/routing.py +192 -0
  28. seed/core/sess_store.py +44 -0
  29. seed/core/tool_output_cap.py +122 -0
  30. seed/core/tool_runtime.py +330 -0
  31. seed/core/trace_audit.py +123 -0
  32. seed/core/turn_loop.py +750 -0
  33. seed/core/usage_accumulator.py +72 -0
  34. seed/integrations/__init__.py +33 -0
  35. seed/integrations/agent_tools.py +160 -0
  36. seed/integrations/cron_sched.py +773 -0
  37. seed/integrations/env_config.py +77 -0
  38. seed/integrations/exec_backend.py +432 -0
  39. seed/integrations/hooks.py +61 -0
  40. seed/integrations/hooks_config.py +109 -0
  41. seed/integrations/instruction_release.py +256 -0
  42. seed/integrations/lsp_client.py +219 -0
  43. seed/integrations/lsp_config.py +99 -0
  44. seed/integrations/mcp_client.py +1283 -0
  45. seed/integrations/mcp_config.py +208 -0
  46. seed/integrations/mcp_registry.py +154 -0
  47. seed/integrations/message_api.py +16 -0
  48. seed/integrations/prompt_task.py +39 -0
  49. seed/integrations/safety.py +331 -0
  50. seed/integrations/session_title.py +211 -0
  51. seed/integrations/symbol_index.py +311 -0
  52. seed/integrations/task_runner.py +275 -0
  53. seed/integrations/webhook_auth.py +33 -0
  54. seed/integrations/webhook_dedup.py +132 -0
  55. seed/models.py +31 -0
  56. seed_kernel-1.0.11.dist-info/METADATA +17 -0
  57. seed_kernel-1.0.11.dist-info/RECORD +60 -0
  58. seed_kernel-1.0.11.dist-info/WHEEL +5 -0
  59. seed_kernel-1.0.11.dist-info/entry_points.txt +2 -0
  60. seed_kernel-1.0.11.dist-info/top_level.txt +1 -0
seed/__init__.py ADDED
@@ -0,0 +1,125 @@
1
+ """
2
+ Seed — kernel + integrations (``pip install seed``).
3
+
4
+ - ``seed.core`` — orchestrator, sessions, memory, LLM, paths, tool runtime contracts, etc.
5
+ - ``seed.integrations`` — browser, safety bridge, webhooks, cron, env file, …
6
+
7
+ Builtin tool **implementations** live in the separate ``seed-tools`` distribution (``import seed_tools``).
8
+ ``ToolRegistry`` / ``ToolExecutor`` **contracts** are always available from ``seed.core.tool_runtime``
9
+ (and re-exported below as ``SeedToolRegistry`` / ``ToolExecutor``).
10
+ """
11
+
12
+ from seed.core import __version__ as engine_version
13
+ from seed.core.agent_runtime import (
14
+ format_tool_segment_summary,
15
+ registry_to_openai_tools,
16
+ )
17
+ from seed.core.config_plane import (
18
+ build_system_prompt,
19
+ config_dir,
20
+ ensure_default_config_files,
21
+ project_root,
22
+ )
23
+ from seed.core.engine import EngineConfig, QueryEngine
24
+ from seed.core.execution import ExecutionContext, ToolExecution, ToolRegistry
25
+ from seed.core.llm_exec import LLMAPIExecutor, LLMError
26
+ from seed.core.llm_sess import (
27
+ agent_sessions_dir,
28
+ list_stored_session_ids,
29
+ list_stored_sessions_meta,
30
+ load_chat_session_from_disk,
31
+ load_or_create_chat_session,
32
+ load_session_messages,
33
+ migrate_legacy_agent_sessions,
34
+ persist_chat_session,
35
+ save_session_messages,
36
+ )
37
+ from seed.core.mem_sys import MemorySystem, MemorySystemError
38
+ from seed.integrations.safety import (
39
+ check_bash_command,
40
+ enforce_bash_timeout,
41
+ sanitize_assistant_output,
42
+ sanitize_tool_output,
43
+ )
44
+ from seed.core.sess_store import SessionManager, SessionNotFoundError, SessionStore
45
+ from seed.core.tool_runtime import ToolExecutionError, ToolExecutor, ToolRegistry as SeedToolRegistry
46
+ from seed.core.turn_loop import AutonomousAgent, TurnLoopConfig, TurnLoopEngine
47
+ from seed.integrations import (
48
+ compute_webhook_dedup_key,
49
+ dedup_enabled,
50
+ llm_generate_display_title,
51
+ maybe_llm_refresh_session_title,
52
+ reset_webhook_dedup_cache,
53
+ to_openai_chat_payload,
54
+ try_acquire,
55
+ try_acquire_report,
56
+ check_bash_command as services_check_bash,
57
+ enforce_bash_timeout as services_enforce_timeout,
58
+ sanitize_assistant_output as services_sanitize_output,
59
+ sanitize_tool_output as services_sanitize_tool,
60
+ )
61
+
62
+ try:
63
+ from seed_tools import setup_builtin_tools
64
+ except ImportError:
65
+
66
+ def setup_builtin_tools(*args, **kwargs): # type: ignore[no-untyped-def]
67
+ raise RuntimeError(
68
+ "Builtin tools require the seed-tools package: pip install seed-tools",
69
+ ) from None
70
+
71
+
72
+ __all__ = [
73
+ "engine_version",
74
+ "EngineConfig",
75
+ "QueryEngine",
76
+ "TurnLoopEngine",
77
+ "TurnLoopConfig",
78
+ "AutonomousAgent",
79
+ "SessionManager",
80
+ "SessionStore",
81
+ "SessionNotFoundError",
82
+ "MemorySystem",
83
+ "MemorySystemError",
84
+ "LLMAPIExecutor",
85
+ "LLMError",
86
+ "ToolExecution",
87
+ "ExecutionContext",
88
+ "ToolRegistry",
89
+ "build_system_prompt",
90
+ "ensure_default_config_files",
91
+ "project_root",
92
+ "config_dir",
93
+ "registry_to_openai_tools",
94
+ "format_tool_segment_summary",
95
+ "sanitize_assistant_output",
96
+ "sanitize_tool_output",
97
+ "check_bash_command",
98
+ "enforce_bash_timeout",
99
+ "agent_sessions_dir",
100
+ "list_stored_sessions_meta",
101
+ "list_stored_session_ids",
102
+ "load_chat_session_from_disk",
103
+ "load_or_create_chat_session",
104
+ "load_session_messages",
105
+ "migrate_legacy_agent_sessions",
106
+ "persist_chat_session",
107
+ "save_session_messages",
108
+ "BROWSER",
109
+ "ensure_browser_running",
110
+ "BrowserError",
111
+ "compute_webhook_dedup_key",
112
+ "dedup_enabled",
113
+ "reset_webhook_dedup_cache",
114
+ "try_acquire",
115
+ "try_acquire_report",
116
+ "to_openai_chat_payload",
117
+ "llm_generate_display_title",
118
+ "maybe_llm_refresh_session_title",
119
+ "SeedToolRegistry",
120
+ "ToolExecutor",
121
+ "ToolExecutionError",
122
+ "setup_builtin_tools",
123
+ ]
124
+
125
+ __version__ = "1.0.6"
seed/cli.py ADDED
@@ -0,0 +1,102 @@
1
+ """
2
+ Seed CLI — 简单编排入口。
3
+
4
+ 用法:
5
+ seed info 查看各子包版本
6
+ seed check 检查各子包是否可正常导入
7
+ """
8
+
9
+ import importlib
10
+ import sys
11
+
12
+
13
+ def _import_check(name: str) -> bool:
14
+ try:
15
+ importlib.import_module(name)
16
+ return True
17
+ except ImportError:
18
+ return False
19
+
20
+
21
+ def cmd_info():
22
+ """查看各子包版本。"""
23
+ pkgs = {
24
+ "seed.core": "seed.core",
25
+ "seed.integrations": "seed.integrations",
26
+ }
27
+ print("📦 Seed (kernel + integrations)\n")
28
+ for display, mod_name in pkgs.items():
29
+ try:
30
+ mod = importlib.import_module(mod_name)
31
+ ver = getattr(mod, "__version__", "?")
32
+ status = "✅"
33
+ except ImportError:
34
+ ver = "—"
35
+ status = "❌"
36
+ print(f" {status} {display:<22} v{ver}")
37
+
38
+ try:
39
+ import seed_tools # noqa: F401
40
+
41
+ v = getattr(seed_tools, "__version__", "?")
42
+ print(f" ✅ seed_tools (optional) v{v}")
43
+ except ImportError:
44
+ print(" — seed_tools (optional) not installed")
45
+
46
+ try:
47
+ import seed # noqa: F811
48
+
49
+ print(f"\n 🎯 seed (top-level) v{seed.__version__}")
50
+ except ImportError:
51
+ print("\n 🎯 seed (top-level) —")
52
+
53
+
54
+ def cmd_check():
55
+ """检查各组件导入是否正常。"""
56
+ modules = [
57
+ "seed.core",
58
+ "seed.core.tool_runtime",
59
+ "seed.core.agent_runtime",
60
+ "seed.core.llm_sess",
61
+ "seed.core.mem_sys",
62
+ "seed.core.engine",
63
+ "seed.core.turn_loop",
64
+ "seed.core.sess_store",
65
+ "seed.integrations",
66
+ "seed.integrations.safety",
67
+ "seed.integrations.webhook_dedup",
68
+ "seed.models",
69
+ ]
70
+ all_ok = True
71
+ print("🔍 导入检查\n")
72
+ for mod in modules:
73
+ ok = _import_check(mod)
74
+ if not ok:
75
+ all_ok = False
76
+ print(f" {'✅' if ok else '❌'} {mod}")
77
+
78
+ print()
79
+ ok_tools = _import_check("seed_tools")
80
+ if not ok_tools:
81
+ all_ok = False
82
+ print(f" {'✅' if ok_tools else '❌'} seed_tools (install seed-tools if missing)")
83
+ sys.exit(0 if all_ok else 1)
84
+
85
+
86
+ def main():
87
+ if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
88
+ print(__doc__.strip())
89
+ return
90
+ cmd = sys.argv[1]
91
+ if cmd == "info":
92
+ cmd_info()
93
+ elif cmd == "check":
94
+ cmd_check()
95
+ else:
96
+ print(f"未知命令: {cmd}", file=sys.stderr)
97
+ print(__doc__.strip(), file=sys.stderr)
98
+ sys.exit(2)
99
+
100
+
101
+ if __name__ == "__main__":
102
+ main()
seed/core/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Kernel: turn loop, LLM, sessions, memory, config, paths, execution protocol."""
2
+
3
+ __version__ = "1.0.6"
4
+ __description__ = "Seed agent engine"
5
+
6
+ from seed.core.agent_registry import AgentHandle, AgentRegistry
7
+
8
+ __all__ = ["AgentHandle", "AgentRegistry"]
@@ -0,0 +1,41 @@
1
+ """Shared in-memory session state used by server and cron scheduler.
2
+
3
+ This belongs in ``seed.core`` because both the server and ``cron_sched`` need
4
+ access to the same live sessions dict. Keeping it in seed avoids import cycles in host apps.
5
+ a reverse dependency.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import threading
11
+ from collections import defaultdict
12
+ from typing import Any, DefaultDict, Dict, List, Set
13
+
14
+ from seed.core.models import Session
15
+
16
+ # In-memory session cache, keyed by _memkey(agent_id, session_id)
17
+ SESSIONS: Dict[str, Session] = {}
18
+ # Active WebSocket connections by session key
19
+ WS_BY_SESSION: DefaultDict[str, Set[Any]] = defaultdict(set)
20
+ # Cancel events for active chats
21
+ ACTIVE_CHAT_CANCELS: Dict[str, threading.Event] = {}
22
+ # Pending in-flight message injections, keyed by _memkey(agent_id, session_id)
23
+ # When a chat session is busy, new messages are queued here and picked up by
24
+ # the running tool loop at the next round boundary.
25
+ PENDING_INJECTIONS: Dict[str, List[Dict[str, Any]]] = {}
26
+
27
+
28
+ def _memkey(agent_id: str, session_id: str) -> str:
29
+ return f"{(agent_id or 'default').strip() or 'default'}::{session_id}"
30
+
31
+
32
+ def cancel_all_active_chats() -> int:
33
+ """Signal every in-flight chat/tool loop to stop (server shutdown or SIGINT)."""
34
+ n = 0
35
+ for ev in list(ACTIVE_CHAT_CANCELS.values()):
36
+ try:
37
+ ev.set()
38
+ n += 1
39
+ except Exception:
40
+ pass
41
+ return n
@@ -0,0 +1,163 @@
1
+ """Context-local active LLM session id (for tools and logging during a turn).
2
+
3
+ Uses contextvars (not threading.local) so that asyncio.to_thread()
4
+ execution (sync tool handlers) also inherits the active context.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from contextvars import ContextVar
9
+ from typing import Optional
10
+
11
+ _session_id: ContextVar[Optional[str]] = ContextVar("session_id", default=None)
12
+ _episodic_project_scoped: ContextVar[bool] = ContextVar(
13
+ "episodic_project_scoped", default=False
14
+ )
15
+ _episodic_project_id: ContextVar[str] = ContextVar("episodic_project_id", default="")
16
+ _project_workspace_cwd: ContextVar[Optional[str]] = ContextVar(
17
+ "project_workspace_cwd", default=None
18
+ )
19
+ _instruction_bundle: ContextVar[Optional[str]] = ContextVar(
20
+ "instruction_bundle", default=None
21
+ )
22
+ _vision_preset_id: ContextVar[str] = ContextVar("vision_preset_id", default="")
23
+ _image_gen_preset_id: ContextVar[str] = ContextVar("image_gen_preset_id", default="")
24
+ _audio_preset_id: ContextVar[str] = ContextVar("audio_preset_id", default="")
25
+ _music_preset_id: ContextVar[str] = ContextVar("music_preset_id", default="")
26
+ _video_gen_preset_id: ContextVar[str] = ContextVar("video_gen_preset_id", default="")
27
+ _active_agent_id: ContextVar[str] = ContextVar("active_agent_id", default="")
28
+
29
+
30
+ def set_active_llm_session(session_id: Optional[str]) -> None:
31
+ if session_id:
32
+ _session_id.set(session_id)
33
+ else:
34
+ _session_id.set(None)
35
+
36
+
37
+ def get_active_llm_session() -> Optional[str]:
38
+ return _session_id.get()
39
+
40
+
41
+ def set_active_project_episodic(scoped: bool, project_id: str = "") -> None:
42
+ """
43
+ Web UI chat: scoped=True 时 episodic 注入与 memory_search 按 project_id 隔离。
44
+ project_id 为空表示「无项目」会话,只匹配未带 ## Project 的经验文件。
45
+ CLI/cron:不要调用或 scoped=False,保持原有「不按项目过滤」行为。
46
+ """
47
+ _episodic_project_scoped.set(bool(scoped))
48
+ _episodic_project_id.set((project_id or "").strip() if scoped else "")
49
+
50
+
51
+ def clear_active_project_episodic() -> None:
52
+ _episodic_project_scoped.set(False)
53
+ _episodic_project_id.set("")
54
+
55
+
56
+ def episodic_project_scope_active() -> bool:
57
+ return _episodic_project_scoped.get()
58
+
59
+
60
+ def active_episodic_project_id() -> str:
61
+ """当前 Web 请求下的项目 id(仅当 scope 开启时有效;否则返回空字符串)。"""
62
+ if not _episodic_project_scoped.get():
63
+ return ""
64
+ return _episodic_project_id.get() or ""
65
+
66
+
67
+ def set_active_project_workspace(path: Optional[str]) -> None:
68
+ """Web UI chat: default shell cwd when tools omit ``cwd``."""
69
+ p = (path or "").strip()
70
+ _project_workspace_cwd.set(p if p else None)
71
+
72
+
73
+ def get_active_project_workspace_cwd() -> Optional[str]:
74
+ return _project_workspace_cwd.get()
75
+
76
+
77
+ def clear_active_project_workspace() -> None:
78
+ _project_workspace_cwd.set(None)
79
+
80
+
81
+ def set_active_instruction_bundle(bundle: Optional[str]) -> None:
82
+ b = (bundle or "").strip()
83
+ _instruction_bundle.set(b if b else None)
84
+
85
+
86
+ def get_active_instruction_bundle() -> Optional[str]:
87
+ return _instruction_bundle.get()
88
+
89
+
90
+ def clear_active_instruction_bundle() -> None:
91
+ _instruction_bundle.set(None)
92
+
93
+
94
+ def set_active_vision_preset(preset_id: Optional[str]) -> None:
95
+ _vision_preset_id.set((preset_id or "").strip())
96
+
97
+
98
+ def get_active_vision_preset() -> str:
99
+ return _vision_preset_id.get() or ""
100
+
101
+
102
+ def clear_active_vision_preset() -> None:
103
+ _vision_preset_id.set("")
104
+
105
+
106
+ def set_active_image_gen_preset(preset_id: Optional[str]) -> None:
107
+ _image_gen_preset_id.set((preset_id or "").strip())
108
+
109
+
110
+ def get_active_image_gen_preset() -> str:
111
+ return _image_gen_preset_id.get() or ""
112
+
113
+
114
+ def clear_active_image_gen_preset() -> None:
115
+ _image_gen_preset_id.set("")
116
+
117
+
118
+ def set_active_audio_preset(preset_id: Optional[str]) -> None:
119
+ _audio_preset_id.set((preset_id or "").strip())
120
+
121
+
122
+ def get_active_audio_preset() -> str:
123
+ return _audio_preset_id.get() or ""
124
+
125
+
126
+ def clear_active_audio_preset() -> None:
127
+ _audio_preset_id.set("")
128
+
129
+
130
+ def set_active_music_preset(preset_id: Optional[str]) -> None:
131
+ _music_preset_id.set((preset_id or "").strip())
132
+
133
+
134
+ def get_active_music_preset() -> str:
135
+ return _music_preset_id.get() or ""
136
+
137
+
138
+ def clear_active_music_preset() -> None:
139
+ _music_preset_id.set("")
140
+
141
+
142
+ def set_active_video_gen_preset(preset_id: Optional[str]) -> None:
143
+ _video_gen_preset_id.set((preset_id or "").strip())
144
+
145
+
146
+ def get_active_video_gen_preset() -> str:
147
+ return _video_gen_preset_id.get() or ""
148
+
149
+
150
+ def clear_active_video_gen_preset() -> None:
151
+ _video_gen_preset_id.set("")
152
+
153
+
154
+ def set_active_agent_id(agent_id: Optional[str]) -> None:
155
+ _active_agent_id.set((agent_id or "").strip() or "default")
156
+
157
+
158
+ def get_active_agent_id() -> str:
159
+ return _active_agent_id.get() or "default"
160
+
161
+
162
+ def clear_active_agent_id() -> None:
163
+ _active_agent_id.set("")
@@ -0,0 +1,180 @@
1
+ """Agent registry — singleton for registering and looking up agent handles.
2
+
3
+ Seed 是库(内核引擎),不能单独运行。宿主(如 CodeAgent、自定义 CLI 等)
4
+ 负责创建 AutonomousAgent 实例并注册到 AgentRegistry,供团队工具使用。
5
+
6
+ 同进程模式:call_agent = 函数调用(零网络开销)
7
+ 跨进程模式:call_agent = HTTP POST(Phase 1 仅保留接口,Phase 1+ 实现)
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from typing import Any, Dict, Optional
13
+
14
+ from seed.core.turn_loop import AutonomousAgent
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class AgentHandle:
20
+ """Handle to an agent — abstracts same-process vs cross-process access.
21
+
22
+ Usage::
23
+ handle = AgentHandle(agent=some_agent_instance)
24
+ result = handle.run_task("do something")
25
+
26
+ Phase 1 只支持同进程(agent 参数传入 AutonomousAgent 实例)。
27
+ 跨进程(url 参数)仅保留接口,暂不实现。
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ agent: Optional[AutonomousAgent] = None,
33
+ url: Optional[str] = None,
34
+ metadata: Optional[Dict[str, Any]] = None,
35
+ ):
36
+ if agent is None and url is None:
37
+ raise ValueError("Either agent (same-process) or url (cross-process) must be provided")
38
+
39
+ self._agent = agent
40
+ self._url = url
41
+ self.metadata = metadata or {}
42
+
43
+ @property
44
+ def is_same_process(self) -> bool:
45
+ """True if this handle uses same-process function call transport."""
46
+ return self._agent is not None
47
+
48
+ @property
49
+ def agent_id(self) -> str:
50
+ """Return the agent's id string if available."""
51
+ if self._agent and hasattr(self._agent, "agent_id"):
52
+ return str(self._agent.agent_id)
53
+ if self._url:
54
+ return self._url
55
+ return "unknown"
56
+
57
+ def run_task(self, task: str) -> str:
58
+ """Execute a task on the agent and return the result text.
59
+
60
+ Same-process: calls agent.run_task() directly (zero-latency function call).
61
+ Cross-process: would POST to agent's HTTP endpoint (Phase 1 not supported).
62
+
63
+ Args:
64
+ task: Task description to send to the agent.
65
+
66
+ Returns:
67
+ Agent's response text.
68
+ """
69
+ if self._agent is not None:
70
+ return self._run_same_process(task)
71
+ else:
72
+ return self._run_cross_process(task)
73
+
74
+ def _run_same_process(self, task: str) -> str:
75
+ """Same-process: function call, zero network overhead."""
76
+ logger.info(f"AgentHandle.run_task (same-process): {task[:80]}...")
77
+ try:
78
+ result = self._agent.run_task(task)
79
+ content = result.get("content", "")
80
+ if content:
81
+ return content
82
+ error = result.get("error", "")
83
+ if error:
84
+ return f"Error: {error}"
85
+ return "Agent returned no response"
86
+ except Exception as e:
87
+ logger.exception(f"AgentHandle.run_task failed: {e}")
88
+ return f"Error: {e}"
89
+
90
+ def _run_cross_process(self, task: str) -> str:
91
+ """Cross-process placeholder — not implemented in Phase 1."""
92
+ logger.warning(
93
+ f"AgentHandle.run_task (cross-process) not implemented yet. "
94
+ f"Would POST to {self._url}"
95
+ )
96
+ return (
97
+ f"Error: cross-process agent call not implemented. "
98
+ f"Agent URL configured as {self._url}, but Phase 1 only supports same-process calls."
99
+ )
100
+
101
+
102
+ class AgentRegistry:
103
+ """Singleton registry for agent handles.
104
+
105
+ All agents in the same process share this registry.
106
+ Team tools (call_agent, dispatch, parallel) access the registry
107
+ to look up target agents.
108
+
109
+ Usage::
110
+
111
+ AgentRegistry.register("backend", AgentHandle(agent=backend_agent))
112
+ handle = AgentRegistry.get("backend")
113
+ result = handle.run_task("implement login API")
114
+ """
115
+
116
+ _instance: Optional["AgentRegistry"] = None
117
+
118
+ def __new__(cls) -> "AgentRegistry":
119
+ if cls._instance is None:
120
+ cls._instance = super().__new__(cls)
121
+ cls._instance._handles: Dict[str, AgentHandle] = {}
122
+ return cls._instance
123
+
124
+ @classmethod
125
+ def register(cls, agent_id: str, handle: AgentHandle) -> None:
126
+ """Register an agent handle under the given id.
127
+
128
+ Args:
129
+ agent_id: Unique identifier for the agent.
130
+ handle: AgentHandle wrapping the agent instance.
131
+ """
132
+ registry = cls()
133
+ existing = registry._handles.get(agent_id)
134
+ if existing:
135
+ logger.warning(f"Overwriting existing agent '{agent_id}' (was: {existing.agent_id})")
136
+ registry._handles[agent_id] = handle
137
+ logger.info(f"Registered agent '{agent_id}'")
138
+
139
+ @classmethod
140
+ def get(cls, agent_id: str) -> Optional[AgentHandle]:
141
+ """Look up an agent handle by id.
142
+
143
+ Args:
144
+ agent_id: The agent identifier.
145
+
146
+ Returns:
147
+ AgentHandle if found, None otherwise.
148
+ """
149
+ return cls()._handles.get(agent_id)
150
+
151
+ @classmethod
152
+ def list(cls) -> Dict[str, AgentHandle]:
153
+ """Return a copy of all registered agent handles."""
154
+ return dict(cls()._handles)
155
+
156
+ @classmethod
157
+ def unregister(cls, agent_id: str) -> bool:
158
+ """Remove an agent from the registry.
159
+
160
+ Args:
161
+ agent_id: The agent identifier to remove.
162
+
163
+ Returns:
164
+ True if removed, False if not found.
165
+ """
166
+ registry = cls()
167
+ if agent_id in registry._handles:
168
+ del registry._handles[agent_id]
169
+ logger.info(f"Unregistered agent '{agent_id}'")
170
+ return True
171
+ logger.warning(f"Agent '{agent_id}' not found for unregister")
172
+ return False
173
+
174
+ @classmethod
175
+ def clear(cls) -> None:
176
+ """Remove all registered agents (mainly for testing)."""
177
+ cls()._handles.clear()
178
+
179
+ def __repr__(self) -> str:
180
+ return f"AgentRegistry(agents={list(self._handles.keys())})"