talkops-opscloud 0.3.0b1__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 (309) hide show
  1. opscloud/__init__.py +5 -0
  2. opscloud/__main__.py +6 -0
  3. opscloud/_constants.py +53 -0
  4. opscloud/_debug.py +145 -0
  5. opscloud/_debug_buffer.py +250 -0
  6. opscloud/_textual_patches.py +367 -0
  7. opscloud/_version.py +15 -0
  8. opscloud/agent/__init__.py +27 -0
  9. opscloud/agent/config.py +168 -0
  10. opscloud/agent/factory.py +1103 -0
  11. opscloud/approval_mode.py +44 -0
  12. opscloud/backend/__init__.py +49 -0
  13. opscloud/backend/composite.py +89 -0
  14. opscloud/backend/local.py +183 -0
  15. opscloud/backend/registry.py +79 -0
  16. opscloud/backend/sandbox_config.py +107 -0
  17. opscloud/backend/sandbox_factory.py +432 -0
  18. opscloud/built_in_skills/remember/SKILL.md +124 -0
  19. opscloud/built_in_skills/skill-creator/SKILL.md +348 -0
  20. opscloud/built_in_skills/skill-creator/scripts/init_skill.py +371 -0
  21. opscloud/built_in_skills/skill-creator/scripts/quick_validate.py +165 -0
  22. opscloud/cli/__init__.py +1 -0
  23. opscloud/cli/commands/__init__.py +15 -0
  24. opscloud/cli/commands/auth.py +45 -0
  25. opscloud/cli/commands/doctor.py +100 -0
  26. opscloud/cli/commands/mcp.py +137 -0
  27. opscloud/cli/commands/threads.py +51 -0
  28. opscloud/cli/interactive.py +154 -0
  29. opscloud/cli/main.py +903 -0
  30. opscloud/cli/non_interactive.py +425 -0
  31. opscloud/cli/server_manager.py +58 -0
  32. opscloud/commands/__init__.py +19 -0
  33. opscloud/commands/_base.py +110 -0
  34. opscloud/commands/_guards.py +52 -0
  35. opscloud/commands/_router.py +146 -0
  36. opscloud/commands/_types.py +36 -0
  37. opscloud/commands/core/__init__.py +47 -0
  38. opscloud/commands/core/auth.py +94 -0
  39. opscloud/commands/core/bug.py +46 -0
  40. opscloud/commands/core/clear.py +106 -0
  41. opscloud/commands/core/cloud.py +185 -0
  42. opscloud/commands/core/compact.py +128 -0
  43. opscloud/commands/core/config_cmd.py +120 -0
  44. opscloud/commands/core/context.py +220 -0
  45. opscloud/commands/core/cost.py +44 -0
  46. opscloud/commands/core/doctor.py +535 -0
  47. opscloud/commands/core/effort.py +108 -0
  48. opscloud/commands/core/exit_cmd.py +41 -0
  49. opscloud/commands/core/fast.py +148 -0
  50. opscloud/commands/core/help_cmd.py +94 -0
  51. opscloud/commands/core/mcp.py +134 -0
  52. opscloud/commands/core/model.py +109 -0
  53. opscloud/commands/core/permissions.py +196 -0
  54. opscloud/commands/core/plugins.py +92 -0
  55. opscloud/commands/core/pool.py +108 -0
  56. opscloud/commands/core/resume.py +97 -0
  57. opscloud/commands/core/skills.py +178 -0
  58. opscloud/commands/power/__init__.py +51 -0
  59. opscloud/commands/power/agents.py +98 -0
  60. opscloud/commands/power/btw.py +85 -0
  61. opscloud/commands/power/copy.py +97 -0
  62. opscloud/commands/power/goal.py +548 -0
  63. opscloud/commands/power/loop.py +295 -0
  64. opscloud/commands/power/memory.py +287 -0
  65. opscloud/commands/power/review.py +152 -0
  66. opscloud/commands/power/rubric.py +287 -0
  67. opscloud/commands/power/runtime.py +321 -0
  68. opscloud/commands/power/skill_creator.py +70 -0
  69. opscloud/commands/power/skill_invoke.py +165 -0
  70. opscloud/commands/power/tasks.py +209 -0
  71. opscloud/commands/power/trace.py +117 -0
  72. opscloud/commands/power/ui_toggles.py +135 -0
  73. opscloud/commands/power/version.py +52 -0
  74. opscloud/commands/registry.py +176 -0
  75. opscloud/config/__init__.py +114 -0
  76. opscloud/config/adapters/__init__.py +5 -0
  77. opscloud/config/adapters/postgres.py +776 -0
  78. opscloud/config/adapters/sqlite.py +769 -0
  79. opscloud/config/aws.py +248 -0
  80. opscloud/config/cloud_profiles.py +437 -0
  81. opscloud/config/env_vars.py +81 -0
  82. opscloud/config/langsmith.py +319 -0
  83. opscloud/config/manifest.py +817 -0
  84. opscloud/config/metadata.py +205 -0
  85. opscloud/config/paths.py +604 -0
  86. opscloud/config/plugins.py +130 -0
  87. opscloud/config/settings.py +834 -0
  88. opscloud/config/store.py +453 -0
  89. opscloud/config/store_factory.py +97 -0
  90. opscloud/config/toml_config.py +562 -0
  91. opscloud/editor.py +173 -0
  92. opscloud/exceptions.py +65 -0
  93. opscloud/file_ops.py +217 -0
  94. opscloud/hooks/__init__.py +139 -0
  95. opscloud/hooks/env.py +44 -0
  96. opscloud/hooks/interrupt.py +121 -0
  97. opscloud/hooks/models/__init__.py +109 -0
  98. opscloud/hooks/models/adapters.py +19 -0
  99. opscloud/hooks/models/config.py +79 -0
  100. opscloud/hooks/models/domain.py +434 -0
  101. opscloud/hooks/models/transport.py +37 -0
  102. opscloud/hooks/tools.py +231 -0
  103. opscloud/input.py +48 -0
  104. opscloud/integrations/__init__.py +80 -0
  105. opscloud/integrations/base.py +153 -0
  106. opscloud/integrations/content_filter.py +119 -0
  107. opscloud/integrations/event_bus.py +480 -0
  108. opscloud/integrations/hooks.py +238 -0
  109. opscloud/integrations/identity.py +181 -0
  110. opscloud/integrations/notifications.py +134 -0
  111. opscloud/integrations/stream_bridge.py +397 -0
  112. opscloud/integrations/thread_store.py +81 -0
  113. opscloud/json_types.py +20 -0
  114. opscloud/mcp/__init__.py +57 -0
  115. opscloud/mcp/config.py +203 -0
  116. opscloud/mcp/discovery.py +229 -0
  117. opscloud/mcp/mcp_info.py +109 -0
  118. opscloud/mcp/middleware.py +102 -0
  119. opscloud/mcp/preload.py +505 -0
  120. opscloud/mcp/raw_config.py +149 -0
  121. opscloud/mcp/semantic_profiler.py +305 -0
  122. opscloud/mcp/session_manager.py +727 -0
  123. opscloud/mcp/trust.py +105 -0
  124. opscloud/memory/__init__.py +27 -0
  125. opscloud/memory/branch.py +61 -0
  126. opscloud/memory/guard.py +19 -0
  127. opscloud/memory/onboarding.py +120 -0
  128. opscloud/memory/registry.py +134 -0
  129. opscloud/memory/store.py +223 -0
  130. opscloud/middleware/__init__.py +106 -0
  131. opscloud/middleware/_repository_bounds.py +459 -0
  132. opscloud/middleware/ask_user.py +152 -0
  133. opscloud/middleware/auto_mode.py +60 -0
  134. opscloud/middleware/auto_mode_hitl.py +2434 -0
  135. opscloud/middleware/compaction.py +566 -0
  136. opscloud/middleware/configurable_model.py +233 -0
  137. opscloud/middleware/cost_tracking.py +1021 -0
  138. opscloud/middleware/glm_stall_recovery.py +109 -0
  139. opscloud/middleware/goal_criteria.py +1234 -0
  140. opscloud/middleware/goal_state_notice.py +712 -0
  141. opscloud/middleware/goal_tools.py +407 -0
  142. opscloud/middleware/headless_mcp_guard.py +88 -0
  143. opscloud/middleware/jev_model_router.py +1018 -0
  144. opscloud/middleware/local_context.py +460 -0
  145. opscloud/middleware/mcp_context.py +151 -0
  146. opscloud/middleware/mcp_middleware.py +146 -0
  147. opscloud/middleware/memory_guard.py +393 -0
  148. opscloud/middleware/model_retry.py +205 -0
  149. opscloud/middleware/registry.py +137 -0
  150. opscloud/middleware/reliable_rubric.py +709 -0
  151. opscloud/middleware/resume_state.py +91 -0
  152. opscloud/middleware/server_hooks.py +1189 -0
  153. opscloud/middleware/shell_allow_list.py +90 -0
  154. opscloud/middleware/skills.py +382 -0
  155. opscloud/middleware/subagent_artifacts.py +84 -0
  156. opscloud/middleware/subagent_telemetry.py +261 -0
  157. opscloud/middleware/subagents.py +243 -0
  158. opscloud/middleware/tool_filter.py +384 -0
  159. opscloud/middleware/unified_system_message.py +62 -0
  160. opscloud/model/__init__.py +37 -0
  161. opscloud/model/config.py +2992 -0
  162. opscloud/model/factory.py +477 -0
  163. opscloud/model/pool.py +459 -0
  164. opscloud/model/reasoning.py +282 -0
  165. opscloud/offload.py +173 -0
  166. opscloud/output.py +64 -0
  167. opscloud/plugins/__init__.py +189 -0
  168. opscloud/plugins/_json.py +22 -0
  169. opscloud/plugins/adapters/__init__.py +13 -0
  170. opscloud/plugins/adapters/agents.py +112 -0
  171. opscloud/plugins/adapters/commands.py +190 -0
  172. opscloud/plugins/adapters/mcp.py +363 -0
  173. opscloud/plugins/adapters/skills.py +132 -0
  174. opscloud/plugins/commands_cli.py +541 -0
  175. opscloud/plugins/discovery.py +512 -0
  176. opscloud/plugins/manifest.py +335 -0
  177. opscloud/plugins/marketplace.py +893 -0
  178. opscloud/plugins/models.py +334 -0
  179. opscloud/plugins/project_plugins.py +317 -0
  180. opscloud/plugins/protocol.py +31 -0
  181. opscloud/plugins/store.py +905 -0
  182. opscloud/plugins/substitution.py +122 -0
  183. opscloud/project_utils.py +145 -0
  184. opscloud/prompts/__init__.py +37 -0
  185. opscloud/prompts/system.py +483 -0
  186. opscloud/prompts/templates/system_prompt.md +166 -0
  187. opscloud/prompts/types.py +54 -0
  188. opscloud/rubrics/__init__.py +42 -0
  189. opscloud/rubrics/evaluator.py +404 -0
  190. opscloud/rubrics/evidence_extractor.py +229 -0
  191. opscloud/rubrics/generator.py +239 -0
  192. opscloud/rubrics/jev_compiler.py +175 -0
  193. opscloud/rubrics/jev_grader.py +297 -0
  194. opscloud/rubrics/middleware.py +8 -0
  195. opscloud/schema/__init__.py +107 -0
  196. opscloud/schema/interrupts.py +981 -0
  197. opscloud/security/__init__.py +91 -0
  198. opscloud/security/approval_mode.py +528 -0
  199. opscloud/security/approval_mode_source.py +230 -0
  200. opscloud/security/cli_ast_evaluator.py +552 -0
  201. opscloud/security/jev_classifier.py +651 -0
  202. opscloud/security/shell_safety.py +340 -0
  203. opscloud/security/unicode_security.py +439 -0
  204. opscloud/security/url_validation.py +160 -0
  205. opscloud/server/__init__.py +13 -0
  206. opscloud/server/_server_config.py +158 -0
  207. opscloud/server/server.py +242 -0
  208. opscloud/server/server_graph.py +93 -0
  209. opscloud/skills/__init__.py +91 -0
  210. opscloud/skills/commands.py +1099 -0
  211. opscloud/skills/invocation.py +200 -0
  212. opscloud/skills/load.py +388 -0
  213. opscloud/skills/loader.py +23 -0
  214. opscloud/skills/merge.py +65 -0
  215. opscloud/skills/registry.py +263 -0
  216. opscloud/skills/sources.py +174 -0
  217. opscloud/skills/trust.py +417 -0
  218. opscloud/state/__init__.py +142 -0
  219. opscloud/state/base.py +154 -0
  220. opscloud/state/cloud_context.py +262 -0
  221. opscloud/state/goal_channels.py +124 -0
  222. opscloud/state/goal_state_limits.py +175 -0
  223. opscloud/state/resume_state.py +58 -0
  224. opscloud/state/service_context.py +281 -0
  225. opscloud/state/session.py +957 -0
  226. opscloud/state/state_migration.py +86 -0
  227. opscloud/subagents/__init__.py +30 -0
  228. opscloud/subagents/loader.py +331 -0
  229. opscloud/subagents/subagents_parser.py +117 -0
  230. opscloud/subagents/types.py +25 -0
  231. opscloud/tools/__init__.py +36 -0
  232. opscloud/tools/catalog.py +37 -0
  233. opscloud/tools/display.py +24 -0
  234. opscloud/tools/fetch_url.py +176 -0
  235. opscloud/tools/goal_tools.py +423 -0
  236. opscloud/tools/registry.py +105 -0
  237. opscloud/tools/thread.py +32 -0
  238. opscloud/tools/web_search.py +215 -0
  239. opscloud/ui/__init__.py +119 -0
  240. opscloud/ui/app.py +5400 -0
  241. opscloud/ui/app.tcss +479 -0
  242. opscloud/ui/clipboard.py +147 -0
  243. opscloud/ui/command_registry.py +482 -0
  244. opscloud/ui/message_store.py +152 -0
  245. opscloud/ui/permission_store.py +360 -0
  246. opscloud/ui/preferences.py +113 -0
  247. opscloud/ui/prompt_manager.py +96 -0
  248. opscloud/ui/remote_client.py +505 -0
  249. opscloud/ui/textual_adapter.py +1269 -0
  250. opscloud/ui/theme.py +728 -0
  251. opscloud/ui/ui_help.py +415 -0
  252. opscloud/ui/widgets/__init__.py +383 -0
  253. opscloud/ui/widgets/_ask_user_types.py +81 -0
  254. opscloud/ui/widgets/_copy_spans.py +52 -0
  255. opscloud/ui/widgets/_inline_prompt.py +290 -0
  256. opscloud/ui/widgets/_js_eval_display.py +139 -0
  257. opscloud/ui/widgets/_links.py +175 -0
  258. opscloud/ui/widgets/_tool_stream.py +308 -0
  259. opscloud/ui/widgets/agent_selector.py +297 -0
  260. opscloud/ui/widgets/approval.py +741 -0
  261. opscloud/ui/widgets/ask_user.py +539 -0
  262. opscloud/ui/widgets/auth.py +695 -0
  263. opscloud/ui/widgets/auth_manager.py +214 -0
  264. opscloud/ui/widgets/auto_mode_notice.py +146 -0
  265. opscloud/ui/widgets/autocomplete.py +709 -0
  266. opscloud/ui/widgets/chat_input.py +805 -0
  267. opscloud/ui/widgets/cloud_selector.py +528 -0
  268. opscloud/ui/widgets/config_manager.py +652 -0
  269. opscloud/ui/widgets/debug_console.py +1269 -0
  270. opscloud/ui/widgets/devops_renderers.py +184 -0
  271. opscloud/ui/widgets/diff.py +237 -0
  272. opscloud/ui/widgets/effort_selector.py +166 -0
  273. opscloud/ui/widgets/goal_review.py +612 -0
  274. opscloud/ui/widgets/goal_status.py +57 -0
  275. opscloud/ui/widgets/infra_panel.py +141 -0
  276. opscloud/ui/widgets/install_confirm.py +114 -0
  277. opscloud/ui/widgets/loading.py +170 -0
  278. opscloud/ui/widgets/mcp_viewer.py +1204 -0
  279. opscloud/ui/widgets/messages.py +4461 -0
  280. opscloud/ui/widgets/model_selector.py +863 -0
  281. opscloud/ui/widgets/notification_center.py +108 -0
  282. opscloud/ui/widgets/notification_settings.py +119 -0
  283. opscloud/ui/widgets/operation_card.py +106 -0
  284. opscloud/ui/widgets/permissions_manager.py +667 -0
  285. opscloud/ui/widgets/plugin_manager.py +1212 -0
  286. opscloud/ui/widgets/pool_selector.py +376 -0
  287. opscloud/ui/widgets/preamble.py +53 -0
  288. opscloud/ui/widgets/skills_viewer.py +432 -0
  289. opscloud/ui/widgets/status.py +1037 -0
  290. opscloud/ui/widgets/subagent_panel.py +927 -0
  291. opscloud/ui/widgets/theme_selector.py +232 -0
  292. opscloud/ui/widgets/thread_selector.py +358 -0
  293. opscloud/ui/widgets/toast.py +31 -0
  294. opscloud/ui/widgets/tool_display.py +325 -0
  295. opscloud/ui/widgets/tool_renderers.py +234 -0
  296. opscloud/ui/widgets/tool_widgets.py +278 -0
  297. opscloud/ui/widgets/welcome.py +421 -0
  298. opscloud/ui/widgets/welcome_popup.py +102 -0
  299. opscloud/utils/__init__.py +24 -0
  300. opscloud/utils/cost_estimation.py +169 -0
  301. opscloud/utils/git.py +390 -0
  302. opscloud/utils/logger.py +571 -0
  303. opscloud/utils/session_stats.py +115 -0
  304. opscloud/utils/startup_error.py +37 -0
  305. talkops_opscloud-0.3.0b1.dist-info/METADATA +449 -0
  306. talkops_opscloud-0.3.0b1.dist-info/RECORD +309 -0
  307. talkops_opscloud-0.3.0b1.dist-info/WHEEL +4 -0
  308. talkops_opscloud-0.3.0b1.dist-info/entry_points.txt +2 -0
  309. talkops_opscloud-0.3.0b1.dist-info/licenses/LICENSE +175 -0
@@ -0,0 +1,905 @@
1
+ """State storage for OpsCloud plugin marketplaces, installs, and enablement."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import tempfile
9
+ from contextlib import contextmanager, suppress
10
+ from hashlib import sha256
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, Any, Never, cast
13
+
14
+ from opscloud.utils.logger import get_logger
15
+
16
+ from opscloud.plugins.models import (
17
+ InstallScope,
18
+ InstalledPluginEntry,
19
+ MarketplaceRecord,
20
+ MarketplaceSourceType,
21
+ split_plugin_id,
22
+ )
23
+
24
+ if TYPE_CHECKING:
25
+ from collections.abc import Callable, Iterator
26
+
27
+ logger = get_logger(__name__)
28
+ _STORAGE_VERSION = 1
29
+ _INSTALLED_STORAGE_VERSION = 2
30
+ _UNVERSIONED_CACHE_KEY = "unversioned"
31
+ _CACHE_SLUG_LENGTH = 48
32
+ _CACHE_DIGEST_LENGTH = 32
33
+ SUPPORTED_MARKETPLACE_SOURCE_TYPES: frozenset[MarketplaceSourceType] = frozenset(
34
+ {"directory", "file", "github", "git", "url"}
35
+ )
36
+
37
+
38
+ class PluginStateError(OSError):
39
+ """Raised when existing plugin state cannot be safely modified."""
40
+
41
+
42
+ def plugin_storage_root() -> Path:
43
+ """Return the plugin storage root directory."""
44
+ from opscloud.config.paths import PLUGINS_DIR
45
+
46
+ raw = os.environ.get("OPSCLOUD_PLUGIN_DIR") or os.environ.get("PLUGIN_CACHE_DIR")
47
+ if raw:
48
+ return Path(raw).expanduser()
49
+ return PLUGINS_DIR
50
+
51
+
52
+ @contextmanager
53
+ def plugin_mutation_lock(*, timeout: float = -1) -> Iterator[None]:
54
+ """Serialize plugin mutations across threads and opscloud processes.
55
+
56
+ The lock is reentrant within one thread so compound operations such as
57
+ marketplace removal can call the normal uninstall path while holding it.
58
+ """
59
+ from filelock import FileLock
60
+
61
+ root = plugin_storage_root()
62
+ root.mkdir(parents=True, exist_ok=True)
63
+ lock = FileLock(str(root / ".mutation.lock"), is_singleton=True)
64
+ with lock.acquire(timeout=timeout):
65
+ yield
66
+
67
+
68
+ def plugin_data_dir(plugin_id: str) -> Path:
69
+ """Return the data directory path for a plugin id without creating it."""
70
+ return plugin_storage_root() / "data" / sanitize_plugin_id(plugin_id)
71
+
72
+
73
+ def ensure_plugin_data_dir(plugin_id: str) -> Path:
74
+ """Return the lazily-created data directory for a plugin id."""
75
+ data_dir = plugin_data_dir(plugin_id)
76
+ data_dir.mkdir(parents=True, exist_ok=True)
77
+ return data_dir
78
+
79
+
80
+ def sanitize_plugin_id(value: str) -> str:
81
+ """Return a bounded, collision-resistant filesystem key."""
82
+ slug = "".join(
83
+ ch if ch.isascii() and (ch.isalnum() or ch in {"_", "-"}) else "-"
84
+ for ch in value
85
+ )
86
+ slug = slug.strip("-")[:_CACHE_SLUG_LENGTH] or "plugin"
87
+ digest = sha256(value.encode()).hexdigest()[:_CACHE_DIGEST_LENGTH]
88
+ return f"{slug}-{digest}"
89
+
90
+
91
+ def opaque_cache_key(value: str) -> str:
92
+ """Return a cache key that cannot disclose source credentials."""
93
+ return sha256(value.encode()).hexdigest()
94
+
95
+
96
+ def ensure_marketplace_cache_dir() -> Path:
97
+ """Return the marketplace cache directory."""
98
+ path = plugin_storage_root() / "marketplaces"
99
+ path.mkdir(parents=True, exist_ok=True)
100
+ return path
101
+
102
+
103
+ def ensure_plugin_install_cache_dir() -> Path:
104
+ """Return the versioned plugin install cache root."""
105
+ path = plugin_storage_root() / "cache"
106
+ path.mkdir(parents=True, exist_ok=True)
107
+ return path
108
+
109
+
110
+ def versioned_cache_path(plugin_id: str, version: str | None) -> Path:
111
+ """Return the versioned cache path for a plugin id."""
112
+ plugin_name, marketplace = split_plugin_id(plugin_id)
113
+ safe_version = sanitize_plugin_id(version or _UNVERSIONED_CACHE_KEY)
114
+ return (
115
+ ensure_plugin_install_cache_dir()
116
+ / sanitize_plugin_id(marketplace)
117
+ / sanitize_plugin_id(plugin_name)
118
+ / safe_version
119
+ )
120
+
121
+
122
+ def _state_dir() -> Path:
123
+ from opscloud.config.paths import STATE_DIR
124
+
125
+ return STATE_DIR
126
+
127
+
128
+ def _marketplaces_path() -> Path:
129
+ from opscloud.config.paths import PLUGIN_MARKETPLACES_PATH
130
+
131
+ return PLUGIN_MARKETPLACES_PATH
132
+
133
+
134
+ def _plugin_state_path() -> Path:
135
+ from opscloud.config.paths import PLUGIN_STATE_PATH
136
+
137
+ return PLUGIN_STATE_PATH
138
+
139
+
140
+ def _installed_plugins_path() -> Path:
141
+ from opscloud.config.paths import PLUGIN_INSTALLED_PATH
142
+
143
+ return PLUGIN_INSTALLED_PATH
144
+
145
+
146
+ def _user_settings_path() -> Path:
147
+ from opscloud.config.paths import USER_SETTINGS_PATH
148
+
149
+ return USER_SETTINGS_PATH
150
+
151
+
152
+ def _invalid_state(
153
+ path: Path, detail: str, *, strict: bool, cause: Exception | None = None
154
+ ) -> dict[str, Any]:
155
+ msg = f"Plugin state file {path} {detail}"
156
+ if strict:
157
+ raise PluginStateError(msg) from cause
158
+ logger.warning("%s", msg)
159
+ return {}
160
+
161
+
162
+ def _load_json(
163
+ path: Path,
164
+ *,
165
+ max_version: int = _STORAGE_VERSION,
166
+ strict: bool = False,
167
+ ) -> dict[str, Any]:
168
+ if not path.exists():
169
+ return {}
170
+ try:
171
+ data = json.loads(path.read_text(encoding="utf-8"))
172
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
173
+ return _invalid_state(
174
+ path, f"could not be read: {exc}", strict=strict, cause=exc
175
+ )
176
+ if not isinstance(data, dict):
177
+ return _invalid_state(path, "is not a JSON object", strict=strict)
178
+ version = data.get("version")
179
+ if version is not None and (
180
+ not isinstance(version, int)
181
+ or isinstance(version, bool)
182
+ or version > max_version
183
+ ):
184
+ return _invalid_state(
185
+ path, f"has unsupported version {version!r}", strict=strict
186
+ )
187
+ return data
188
+
189
+
190
+ def _raise_state_shape(path: Path, detail: str) -> Never:
191
+ msg = f"Plugin state file {path} {detail}"
192
+ raise PluginStateError(msg)
193
+
194
+
195
+ def _atomic_write_json(path: Path, data: dict[str, Any]) -> None:
196
+ path.parent.mkdir(parents=True, exist_ok=True)
197
+ fd, tmp_name = tempfile.mkstemp(
198
+ prefix=f".{path.name}.", suffix=".tmp", dir=path.parent
199
+ )
200
+ try:
201
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
202
+ json.dump(data, f, indent=2, sort_keys=True)
203
+ f.write("\n")
204
+ Path(tmp_name).replace(path)
205
+ except Exception:
206
+ with suppress(OSError):
207
+ Path(tmp_name).unlink()
208
+ raise
209
+
210
+
211
+ def load_marketplace_records(
212
+ *, project_root: Path | None = None, strict: bool = False
213
+ ) -> dict[str, MarketplaceRecord]:
214
+ """Load persisted marketplace records, plus any project-local marketplace."""
215
+ data = _load_json(_marketplaces_path(), strict=strict)
216
+ raw_records = data.get("marketplaces", {})
217
+ if not isinstance(raw_records, dict):
218
+ if strict:
219
+ _raise_state_shape(_marketplaces_path(), "has invalid marketplaces data")
220
+ return {}
221
+ records: dict[str, MarketplaceRecord] = {}
222
+ for name, record in raw_records.items():
223
+ if not isinstance(name, str) or not isinstance(record, dict):
224
+ continue
225
+ source_type = record.get("source_type")
226
+ source = record.get("source")
227
+ if (
228
+ not isinstance(source_type, str)
229
+ or source_type not in SUPPORTED_MARKETPLACE_SOURCE_TYPES
230
+ or not isinstance(source, str)
231
+ or not isinstance(record.get("install_location", source), str)
232
+ ):
233
+ logger.debug("Skipping unsupported marketplace record %r", name)
234
+ continue
235
+ ref = record.get("ref")
236
+ is_default = bool(record.get("is_default", False))
237
+ plugin_count = int(record.get("plugin_count", 0))
238
+ records[name] = MarketplaceRecord(
239
+ name=name,
240
+ source_type=cast(MarketplaceSourceType, source_type),
241
+ source=source,
242
+ install_location=record.get("install_location", source),
243
+ ref=ref if isinstance(ref, str) else None,
244
+ plugin_count=plugin_count,
245
+ is_default=is_default,
246
+ )
247
+
248
+ # Seed default marketplaces if missing and not explicitly removed by the user
249
+ from opscloud.config.plugins import DEFAULT_MARKETPLACE_CONFIGS
250
+
251
+ removed_defaults = set(data.get("removed_defaults", []))
252
+ for default_cfg in DEFAULT_MARKETPLACE_CONFIGS:
253
+ if default_cfg.name not in records and default_cfg.name not in removed_defaults:
254
+ default_dir = ensure_marketplace_cache_dir() / default_cfg.name
255
+ records[default_cfg.name] = MarketplaceRecord(
256
+ name=default_cfg.name,
257
+ source_type="git",
258
+ source=default_cfg.repository_url,
259
+ install_location=str(default_dir),
260
+ ref=default_cfg.ref,
261
+ is_default=True,
262
+ )
263
+
264
+ # Auto-detect project marketplace record if available
265
+ target_root = project_root
266
+ if target_root is None:
267
+ try:
268
+ cwd = Path.cwd()
269
+ if (
270
+ (cwd / ".opscloud").is_dir()
271
+ or (cwd / ".opscode").is_dir()
272
+ or (cwd / ".claude-plugin").is_dir()
273
+ or (cwd / "marketplace.json").is_file()
274
+ ):
275
+ target_root = cwd
276
+ except (OSError, RuntimeError):
277
+ pass
278
+
279
+ if target_root is not None:
280
+ try:
281
+ from opscloud.plugins.marketplace import (
282
+ _load_marketplace_file,
283
+ find_marketplace_manifest,
284
+ )
285
+
286
+ manifest_path = (
287
+ find_marketplace_manifest(target_root / ".opscloud")
288
+ or find_marketplace_manifest(target_root / ".opscode")
289
+ or find_marketplace_manifest(target_root)
290
+ )
291
+ if manifest_path is not None:
292
+ mp = _load_marketplace_file(manifest_path)
293
+ if mp.name not in records:
294
+ records[mp.name] = MarketplaceRecord(
295
+ name=mp.name,
296
+ source_type="file",
297
+ source=str(manifest_path),
298
+ install_location=str(manifest_path),
299
+ )
300
+ except Exception as exc:
301
+ logger.debug("Could not auto-discover project marketplace record: %s", exc)
302
+
303
+ return records
304
+
305
+
306
+ def save_marketplace_record(record: MarketplaceRecord) -> None:
307
+ """Persist a marketplace record."""
308
+ data = _load_json(_marketplaces_path(), strict=True)
309
+ marketplaces = data.get("marketplaces")
310
+ if marketplaces is None:
311
+ marketplaces = {}
312
+ elif not isinstance(marketplaces, dict):
313
+ _raise_state_shape(_marketplaces_path(), "has invalid marketplaces data")
314
+ entry_dict: dict[str, Any] = {
315
+ "install_location": record.install_location,
316
+ "source_type": record.source_type,
317
+ "source": record.source,
318
+ }
319
+ from opscloud.config.plugins import is_default_marketplace
320
+
321
+ if record.ref:
322
+ entry_dict["ref"] = record.ref
323
+ if record.plugin_count:
324
+ entry_dict["plugin_count"] = record.plugin_count
325
+ if record.is_default or is_default_marketplace(record.name):
326
+ entry_dict["is_default"] = True
327
+ marketplaces[record.name] = entry_dict
328
+
329
+ payload: dict[str, Any] = {
330
+ "version": _STORAGE_VERSION,
331
+ "marketplaces": marketplaces,
332
+ }
333
+ removed_defaults = [d for d in data.get("removed_defaults", []) if d != record.name]
334
+ if removed_defaults:
335
+ payload["removed_defaults"] = removed_defaults
336
+
337
+ _atomic_write_json(_marketplaces_path(), payload)
338
+
339
+
340
+ def remove_marketplace_record(name: str) -> bool:
341
+ """Remove a marketplace record."""
342
+ data = _load_json(_marketplaces_path(), strict=True)
343
+ marketplaces = data.get("marketplaces")
344
+ if marketplaces is None:
345
+ marketplaces = {}
346
+ elif not isinstance(marketplaces, dict):
347
+ _raise_state_shape(_marketplaces_path(), "has invalid marketplaces data")
348
+
349
+ from opscloud.config.plugins import is_default_marketplace
350
+
351
+ if name not in marketplaces and not is_default_marketplace(name):
352
+ return False
353
+ removed_record = marketplaces.pop(name, None)
354
+ payload: dict[str, Any] = {
355
+ "version": _STORAGE_VERSION,
356
+ "marketplaces": marketplaces,
357
+ }
358
+ is_default = (
359
+ is_default_marketplace(name)
360
+ or (isinstance(removed_record, dict) and removed_record.get("is_default", False))
361
+ )
362
+ if is_default:
363
+ existing_removed = data.get("removed_defaults", [])
364
+ if name not in existing_removed:
365
+ payload["removed_defaults"] = [*existing_removed, name]
366
+ else:
367
+ payload["removed_defaults"] = existing_removed
368
+ elif "removed_defaults" in data:
369
+ payload["removed_defaults"] = data["removed_defaults"]
370
+
371
+ _atomic_write_json(_marketplaces_path(), payload)
372
+ return True
373
+
374
+
375
+ # ── Scoped Settings / Enablement ──────────────────────────────
376
+
377
+
378
+ def _load_settings_enabled_plugins(path: Path) -> frozenset[str]:
379
+ """Read enabled plugins (where value is True) from a settings JSON file."""
380
+ m = _load_settings_enabled_plugins_map(path)
381
+ return frozenset(k for k, v in m.items() if v is True)
382
+
383
+
384
+ def _load_settings_enabled_plugins_map(path: Path) -> dict[str, bool]:
385
+ """Read ``enabledPlugins`` map from a settings JSON file."""
386
+ if not path.exists():
387
+ return {}
388
+ try:
389
+ data = json.loads(path.read_text(encoding="utf-8"))
390
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
391
+ logger.warning("Could not read settings file %s", path)
392
+ return {}
393
+ if not isinstance(data, dict):
394
+ return {}
395
+ enabled = data.get("enabledPlugins", {})
396
+ if not isinstance(enabled, dict):
397
+ return {}
398
+ return {
399
+ key: value
400
+ for key, value in enabled.items()
401
+ if isinstance(key, str) and isinstance(value, bool)
402
+ }
403
+
404
+
405
+ def _load_settings_disabled_plugins(path: Path) -> frozenset[str]:
406
+ """Read explicitly disabled plugins (value is False) from settings JSON."""
407
+ m = _load_settings_enabled_plugins_map(path)
408
+ return frozenset(k for k, v in m.items() if v is False)
409
+
410
+
411
+ def load_all_disabled_plugin_ids(
412
+ project_root: Path | None = None,
413
+ ) -> frozenset[str]:
414
+ """Merged union of user + project + local explicitly disabled plugin ids."""
415
+ from opscloud.config.settings import settings
416
+
417
+ effective_root = (
418
+ project_root if isinstance(project_root, Path) else settings.effective_project_root
419
+ )
420
+ result = set(_load_settings_disabled_plugins(_user_settings_path()))
421
+ if isinstance(effective_root, Path):
422
+ from opscloud.config.paths import (
423
+ project_local_settings_path,
424
+ project_settings_path,
425
+ )
426
+
427
+ result |= set(
428
+ _load_settings_disabled_plugins(project_settings_path(effective_root))
429
+ )
430
+ result |= set(
431
+ _load_settings_disabled_plugins(project_local_settings_path(effective_root))
432
+ )
433
+ return frozenset(result)
434
+
435
+
436
+ def _write_settings_enabled_plugins(path: Path, enabled_ids: set[str]) -> None:
437
+ """Write ``enabledPlugins`` to a settings JSON file, preserving other keys."""
438
+ existing: dict[str, Any] = {}
439
+ if path.exists():
440
+ try:
441
+ existing = json.loads(path.read_text(encoding="utf-8"))
442
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
443
+ pass
444
+ if not isinstance(existing, dict):
445
+ existing = {}
446
+ existing["enabledPlugins"] = dict.fromkeys(sorted(enabled_ids), True)
447
+ _atomic_write_json(path, existing)
448
+
449
+
450
+ def _write_settings_plugin_enabled_state(
451
+ path: Path, plugin_id: str, enabled: bool
452
+ ) -> None:
453
+ """Set a single plugin's enabled boolean state in a settings JSON file."""
454
+ existing: dict[str, Any] = {}
455
+ if path.exists():
456
+ try:
457
+ existing = json.loads(path.read_text(encoding="utf-8"))
458
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
459
+ pass
460
+ if not isinstance(existing, dict):
461
+ existing = {}
462
+
463
+ current_map: dict[str, Any] = existing.get("enabledPlugins", {})
464
+ if not isinstance(current_map, dict):
465
+ current_map = {}
466
+
467
+ current_map[plugin_id] = enabled
468
+ existing["enabledPlugins"] = current_map
469
+ _atomic_write_json(path, existing)
470
+
471
+
472
+ def load_user_enabled_plugin_ids() -> frozenset[str]:
473
+ """Read enabledPlugins from ``~/.opscloud/settings.json``."""
474
+ return _load_settings_enabled_plugins(_user_settings_path())
475
+
476
+
477
+ def load_project_enabled_plugin_ids(project_root: Path) -> frozenset[str]:
478
+ """Read enabledPlugins from ``{project}/.opscloud/settings.json``."""
479
+ if not isinstance(project_root, Path):
480
+ return frozenset()
481
+ from opscloud.config.paths import project_settings_path
482
+
483
+ return _load_settings_enabled_plugins(project_settings_path(project_root))
484
+
485
+
486
+ def load_local_enabled_plugin_ids(project_root: Path) -> frozenset[str]:
487
+ """Read enabledPlugins from ``{project}/.opscloud/settings.local.json``."""
488
+ if not isinstance(project_root, Path):
489
+ return frozenset()
490
+ from opscloud.config.paths import project_local_settings_path
491
+
492
+ return _load_settings_enabled_plugins(project_local_settings_path(project_root))
493
+
494
+
495
+ def load_all_enabled_plugin_ids(
496
+ project_root: Path | None = None,
497
+ ) -> frozenset[str]:
498
+ """Merged union of user + project + local enabled plugin ids."""
499
+ from opscloud.config.settings import settings
500
+
501
+ effective_root = (
502
+ project_root if isinstance(project_root, Path) else settings.effective_project_root
503
+ )
504
+ result = set(load_user_enabled_plugin_ids())
505
+ if isinstance(effective_root, Path):
506
+ result |= load_project_enabled_plugin_ids(effective_root)
507
+ result |= load_local_enabled_plugin_ids(effective_root)
508
+ return frozenset(result)
509
+
510
+
511
+ def load_enabled_plugin_ids(*, strict: bool = False) -> frozenset[str]:
512
+ """Load enabled plugin ids (user scope backward-compatible entry point)."""
513
+ return load_user_enabled_plugin_ids()
514
+
515
+
516
+ def set_plugin_enabled_for_scope(
517
+ plugin_id: str,
518
+ enabled: bool,
519
+ scope: InstallScope = "user",
520
+ project_root: Path | None = None,
521
+ ) -> None:
522
+ """Write enablement to the correct settings file for the given scope."""
523
+ from opscloud.config.paths import (
524
+ project_local_settings_path,
525
+ project_settings_path,
526
+ )
527
+
528
+ if scope in {"user", "global"}:
529
+ path = _user_settings_path()
530
+ elif scope == "project":
531
+ if project_root is None:
532
+ raise ValueError("project_root required for project scope")
533
+ path = project_settings_path(project_root)
534
+ elif scope == "local":
535
+ if project_root is None:
536
+ raise ValueError("project_root required for local scope")
537
+ path = project_local_settings_path(project_root)
538
+ _ensure_local_settings_gitignored(project_root)
539
+ else:
540
+ path = _user_settings_path()
541
+
542
+ _write_settings_plugin_enabled_state(path, plugin_id, enabled)
543
+
544
+
545
+ def set_plugin_enabled(plugin_id: str, enabled: bool) -> None:
546
+ """Persist a plugin enablement value (user scope)."""
547
+ set_plugin_enabled_for_scope(plugin_id, enabled, scope="user")
548
+
549
+
550
+ def _ensure_local_settings_gitignored(project_root: Path) -> None:
551
+ """Add ``settings.local.json`` to git excludes."""
552
+ pattern = "**/.opscloud/settings.local.json"
553
+
554
+ # Project-local git exclude
555
+ git_info_exclude = project_root / ".git" / "info" / "exclude"
556
+ if git_info_exclude.parent.is_dir():
557
+ try:
558
+ content = (
559
+ git_info_exclude.read_text(encoding="utf-8")
560
+ if git_info_exclude.exists()
561
+ else ""
562
+ )
563
+ if pattern not in content:
564
+ git_info_exclude.parent.mkdir(parents=True, exist_ok=True)
565
+ with git_info_exclude.open("a", encoding="utf-8") as f:
566
+ f.write(f"\n{pattern}\n")
567
+ except OSError:
568
+ logger.debug("Could not add project git exclude for %s", pattern)
569
+
570
+
571
+ # ── Installed Plugins Registry ────────────────────────────────
572
+
573
+
574
+ def _parse_installed_plugin_json_entry(
575
+ persisted_entry: object,
576
+ ) -> InstalledPluginEntry | None:
577
+ """Parse a single install entry from persisted JSON."""
578
+ if not isinstance(persisted_entry, dict):
579
+ return None
580
+ install_path = persisted_entry.get("installPath") or persisted_entry.get(
581
+ "install_path"
582
+ )
583
+ version = persisted_entry.get("version")
584
+ if (
585
+ not isinstance(install_path, str)
586
+ or not install_path
587
+ or (version is not None and (not isinstance(version, str) or not version))
588
+ ):
589
+ return None
590
+ scope_raw = persisted_entry.get("scope", "user")
591
+ scope: InstallScope = (
592
+ cast(InstallScope, scope_raw)
593
+ if scope_raw in {"user", "project", "local", "global"}
594
+ else "user"
595
+ )
596
+ project_path = persisted_entry.get("projectPath")
597
+ installed_at = persisted_entry.get("installedAt")
598
+ last_updated = persisted_entry.get("lastUpdated")
599
+ git_commit_sha = persisted_entry.get("gitCommitSha")
600
+ return InstalledPluginEntry(
601
+ install_path=install_path,
602
+ version=version if isinstance(version, str) else None,
603
+ scope=scope,
604
+ project_path=project_path if isinstance(project_path, str) else None,
605
+ installed_at=installed_at if isinstance(installed_at, str) else None,
606
+ last_updated=last_updated if isinstance(last_updated, str) else None,
607
+ git_commit_sha=git_commit_sha if isinstance(git_commit_sha, str) else None,
608
+ )
609
+
610
+
611
+ def load_installed_plugin_entries(
612
+ *, strict: bool = False
613
+ ) -> dict[str, list[InstalledPluginEntry]]:
614
+ """Load installed plugin records as arrays per plugin ID."""
615
+ data = _load_json(
616
+ _installed_plugins_path(),
617
+ max_version=_INSTALLED_STORAGE_VERSION,
618
+ strict=strict,
619
+ )
620
+ raw_plugins = data.get("plugins", {})
621
+ if not isinstance(raw_plugins, dict):
622
+ if strict:
623
+ _raise_state_shape(_installed_plugins_path(), "has invalid plugins data")
624
+ return {}
625
+ result: dict[str, list[InstalledPluginEntry]] = {}
626
+ for plugin_id, entries in raw_plugins.items():
627
+ if not isinstance(plugin_id, str) or not isinstance(entries, list):
628
+ if strict:
629
+ _raise_state_shape(
630
+ _installed_plugins_path(), "has malformed plugin entries"
631
+ )
632
+ continue
633
+ parsed_entries = [
634
+ entry
635
+ for item in entries
636
+ if (entry := _parse_installed_plugin_json_entry(item)) is not None
637
+ ]
638
+ if parsed_entries:
639
+ result[plugin_id] = parsed_entries
640
+ elif strict:
641
+ _raise_state_shape(
642
+ _installed_plugins_path(), f"has malformed entry for {plugin_id!r}"
643
+ )
644
+ return result
645
+
646
+
647
+ def load_installed_plugins(*, strict: bool = False) -> dict[str, InstalledPluginEntry]:
648
+ """Load installed plugin records (first entry per plugin, backward-compat)."""
649
+ all_entries = load_installed_plugin_entries(strict=strict)
650
+ return {
651
+ plugin_id: entries[0]
652
+ for plugin_id, entries in all_entries.items()
653
+ if entries
654
+ }
655
+
656
+
657
+ def _entry_to_json(entry: InstalledPluginEntry) -> dict[str, Any]:
658
+ """Serialize an install entry to JSON (Claude Code camelCase keys)."""
659
+ payload: dict[str, Any] = {
660
+ "scope": entry.scope,
661
+ "installPath": entry.install_path,
662
+ }
663
+ if entry.project_path is not None:
664
+ payload["projectPath"] = entry.project_path
665
+ if entry.version is not None:
666
+ payload["version"] = entry.version
667
+ if entry.installed_at is not None:
668
+ payload["installedAt"] = entry.installed_at
669
+ if entry.last_updated is not None:
670
+ payload["lastUpdated"] = entry.last_updated
671
+ if entry.git_commit_sha is not None:
672
+ payload["gitCommitSha"] = entry.git_commit_sha
673
+ return payload
674
+
675
+
676
+ def _write_installed_plugins_raw(
677
+ plugins: dict[str, list[InstalledPluginEntry]],
678
+ ) -> None:
679
+ """Write the full installed-plugins registry (array-per-plugin)."""
680
+ _atomic_write_json(
681
+ _installed_plugins_path(),
682
+ {
683
+ "version": _INSTALLED_STORAGE_VERSION,
684
+ "plugins": {
685
+ plugin_id: [_entry_to_json(e) for e in entries]
686
+ for plugin_id, entries in sorted(plugins.items())
687
+ },
688
+ },
689
+ )
690
+
691
+
692
+ def _write_installed_plugins(
693
+ plugins: dict[str, InstalledPluginEntry],
694
+ ) -> None:
695
+ """Write installed plugins (single-entry compat wrapper)."""
696
+ _write_installed_plugins_raw(
697
+ {pid: [entry] for pid, entry in plugins.items()}
698
+ )
699
+
700
+
701
+ def _now_iso() -> str:
702
+ """Return current UTC timestamp in ISO 8601 format."""
703
+ from datetime import datetime, timezone
704
+
705
+ return (
706
+ datetime.now(timezone.utc)
707
+ .isoformat(timespec="milliseconds")
708
+ .replace("+00:00", "Z")
709
+ )
710
+
711
+
712
+ def add_installed_plugin(
713
+ plugin_id: str,
714
+ *,
715
+ install_path: str,
716
+ version: str | None = None,
717
+ scope: InstallScope = "user",
718
+ project_root: Path | None = None,
719
+ git_commit_sha: str | None = None,
720
+ ) -> InstalledPluginEntry:
721
+ """Add a scoped install entry for ``plugin_id``."""
722
+ all_entries = load_installed_plugin_entries(strict=True)
723
+ now = _now_iso()
724
+ project_path = str(project_root) if project_root is not None else None
725
+
726
+ entry = InstalledPluginEntry(
727
+ install_path=install_path,
728
+ version=version,
729
+ scope=scope,
730
+ project_path=project_path,
731
+ installed_at=now,
732
+ last_updated=now,
733
+ git_commit_sha=git_commit_sha,
734
+ )
735
+
736
+ existing = all_entries.get(plugin_id, [])
737
+ updated = [
738
+ e
739
+ for e in existing
740
+ if not (e.scope == scope and e.project_path == project_path)
741
+ ]
742
+ updated.append(entry)
743
+ all_entries[plugin_id] = updated
744
+ _write_installed_plugins_raw(all_entries)
745
+ return entry
746
+
747
+
748
+ def get_primary_install_entry(plugin_id: str) -> InstalledPluginEntry | None:
749
+ """Return the first install entry for a plugin id."""
750
+ return load_installed_plugins().get(plugin_id)
751
+
752
+
753
+ def remove_installed_plugin(
754
+ plugin_id: str,
755
+ *,
756
+ scope: InstallScope | None = None,
757
+ project_root: Path | None = None,
758
+ ) -> InstalledPluginEntry | None:
759
+ """Remove install record(s) for a plugin."""
760
+ all_entries = load_installed_plugin_entries(strict=True)
761
+ existing = all_entries.get(plugin_id)
762
+ if not existing:
763
+ return None
764
+
765
+ if scope is None:
766
+ removed = existing[0] if existing else None
767
+ del all_entries[plugin_id]
768
+ else:
769
+ project_path = (
770
+ str(project_root)
771
+ if (scope != "user" and project_root is not None)
772
+ else None
773
+ )
774
+ removed = None
775
+ remaining = []
776
+ for e in existing:
777
+ if e.scope == scope and (scope == "user" or e.project_path == project_path):
778
+ removed = e
779
+ else:
780
+ remaining.append(e)
781
+ if remaining:
782
+ all_entries[plugin_id] = remaining
783
+ else:
784
+ all_entries.pop(plugin_id, None)
785
+
786
+ _write_installed_plugins_raw(all_entries)
787
+ return removed
788
+
789
+
790
+ def cache_and_register_plugin(
791
+ plugin_id: str,
792
+ source_dir: Path,
793
+ *,
794
+ version: str | None = None,
795
+ scope: InstallScope = "user",
796
+ project_root: Path | None = None,
797
+ validate: Callable[[Path], None] | None = None,
798
+ ) -> Path:
799
+ """Copy a plugin into the versioned cache and register the install."""
800
+ source = source_dir.resolve()
801
+ if not source.is_dir():
802
+ msg = f"Plugin source directory not found: {source}"
803
+ raise FileNotFoundError(msg)
804
+
805
+ cache_path = versioned_cache_path(plugin_id, version)
806
+ if cache_path.exists() and version is not None:
807
+ try:
808
+ if any(cache_path.iterdir()):
809
+ add_installed_plugin(
810
+ plugin_id,
811
+ install_path=str(cache_path),
812
+ version=version,
813
+ scope=scope,
814
+ project_root=project_root,
815
+ )
816
+ return cache_path
817
+ except OSError:
818
+ pass
819
+
820
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
821
+ temp_dir = cache_path.parent / f".{cache_path.name}.tmp-{os.getpid()}"
822
+ backup_dir = cache_path.parent / f".{cache_path.name}.backup-{os.getpid()}"
823
+ if temp_dir.exists():
824
+ shutil.rmtree(temp_dir, ignore_errors=True)
825
+ if backup_dir.exists():
826
+ shutil.rmtree(backup_dir, ignore_errors=True)
827
+ try:
828
+ shutil.copytree(source, temp_dir, symlinks=True, dirs_exist_ok=False)
829
+ git_dir = temp_dir / ".git"
830
+ if git_dir.exists():
831
+ shutil.rmtree(git_dir, ignore_errors=True)
832
+ if validate is not None:
833
+ validate(temp_dir)
834
+ if cache_path.exists():
835
+ cache_path.replace(backup_dir)
836
+ try:
837
+ temp_dir.replace(cache_path)
838
+ except OSError:
839
+ if backup_dir.exists() and not cache_path.exists():
840
+ backup_dir.replace(cache_path)
841
+ raise
842
+ shutil.rmtree(backup_dir, ignore_errors=True)
843
+ except Exception:
844
+ shutil.rmtree(temp_dir, ignore_errors=True)
845
+ raise
846
+
847
+ add_installed_plugin(
848
+ plugin_id,
849
+ install_path=str(cache_path.resolve()),
850
+ version=version,
851
+ scope=scope,
852
+ project_root=project_root,
853
+ )
854
+ return cache_path.resolve()
855
+
856
+
857
+ def uninstall_plugin(
858
+ plugin_id: str,
859
+ *,
860
+ scope: InstallScope | None = None,
861
+ project_root: Path | None = None,
862
+ ) -> None:
863
+ """Disable a plugin, remove install records, and delete orphaned cache dirs."""
864
+ from opscloud.config.settings import settings
865
+ from opscloud.skills.registry import SkillRegistry
866
+
867
+ effective_root = (
868
+ project_root if isinstance(project_root, Path) else settings.effective_project_root
869
+ )
870
+ load_installed_plugin_entries(strict=True)
871
+
872
+ removed = remove_installed_plugin(
873
+ plugin_id, scope=scope, project_root=effective_root
874
+ )
875
+
876
+ if scope is not None:
877
+ set_plugin_enabled_for_scope(
878
+ plugin_id, False, scope=scope, project_root=effective_root
879
+ )
880
+ else:
881
+ set_plugin_enabled_for_scope(plugin_id, False, scope="user")
882
+ if effective_root:
883
+ with suppress(Exception):
884
+ set_plugin_enabled_for_scope(
885
+ plugin_id, False, scope="project", project_root=effective_root
886
+ )
887
+ with suppress(Exception):
888
+ set_plugin_enabled_for_scope(
889
+ plugin_id, False, scope="local", project_root=effective_root
890
+ )
891
+
892
+ if removed is not None:
893
+ all_after = load_installed_plugin_entries()
894
+ all_paths_after = {
895
+ e.install_path
896
+ for entries in all_after.values()
897
+ for e in entries
898
+ }
899
+ if removed.install_path not in all_paths_after:
900
+ path = Path(removed.install_path)
901
+ if path.is_dir():
902
+ shutil.rmtree(path, ignore_errors=True)
903
+
904
+ with suppress(Exception):
905
+ SkillRegistry.get_instance().discover_skills(force=True)