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,200 @@
1
+ """Helpers for loading and formatting skill invocations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import os
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ from opscloud.config.env_vars import EXTRA_SKILLS_DIRS
11
+ from opscloud.config.paths import (
12
+ get_built_in_skills_dir,
13
+ get_project_agent_skills_dir,
14
+ get_project_claude_skills_dir,
15
+ get_project_skills_dir,
16
+ get_user_agent_skills_dir,
17
+ get_user_claude_skills_dir,
18
+ get_user_skills_dir,
19
+ )
20
+
21
+ if TYPE_CHECKING:
22
+ from opscloud.skills.load import ExtendedSkillMetadata
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class SkillInvocationEnvelope:
27
+ """Structured prompt and checkpoint metadata for a skill invocation.
28
+
29
+ Attributes:
30
+ prompt: Composed prompt that wraps `SKILL.md` content with
31
+ invocation instructions.
32
+ message_kwargs: Extra fields merged into the initial HumanMessage.
33
+ skill_name: Invoked skill name for trace attribution.
34
+ """
35
+
36
+ prompt: str
37
+ message_kwargs: dict[str, Any]
38
+ skill_name: str
39
+
40
+
41
+ def discover_skills_and_roots(
42
+ assistant_id: str = "opscloud",
43
+ *,
44
+ plugin_skill_sources: tuple[tuple[Path, str], ...] = (),
45
+ plugin_skill_roots: tuple[Path, ...] = (),
46
+ path_base: Path | None = None,
47
+ ) -> tuple[list[ExtendedSkillMetadata], list[Path]]:
48
+ """Discover skills and build pre-resolved containment roots.
49
+
50
+ Args:
51
+ assistant_id: Agent identifier used to resolve user skill directories.
52
+ plugin_skill_sources: Plugin-owned skill directories and namespaces.
53
+ plugin_skill_roots: Plugin-owned roots allowed for content loading.
54
+ path_base: User working directory for resolving relative skill roots.
55
+
56
+ Returns:
57
+ Tuple of `(skill metadata list, pre-resolved containment roots)`.
58
+ """
59
+ from opscloud.config.settings import settings
60
+ from opscloud.skills.load import list_skills
61
+ from opscloud.skills.trust import load_trusted_skill_dirs
62
+
63
+ effective_project_root = settings.project_root
64
+
65
+ # Auto-resolve plugin skills if none provided
66
+ p_sources = list(plugin_skill_sources)
67
+ p_roots = list(plugin_skill_roots)
68
+ if not p_sources:
69
+ try:
70
+ from opscloud.plugins.adapters.skills import discover_plugin_skill_sources_and_roots
71
+
72
+ discovered_p_sources, discovered_p_roots = discover_plugin_skill_sources_and_roots(
73
+ project_root=effective_project_root
74
+ )
75
+ p_sources.extend(discovered_p_sources)
76
+ p_roots.extend(discovered_p_roots)
77
+ except Exception:
78
+ pass
79
+
80
+ skills = list_skills(
81
+ built_in_skills_dir=get_built_in_skills_dir(),
82
+ plugin_skill_sources=p_sources,
83
+ user_skills_dir=get_user_skills_dir(assistant_id),
84
+ project_skills_dir=get_project_skills_dir(effective_project_root),
85
+ user_agent_skills_dir=get_user_agent_skills_dir(),
86
+ project_agent_skills_dir=get_project_agent_skills_dir(effective_project_root),
87
+ user_claude_skills_dir=get_user_claude_skills_dir(),
88
+ project_claude_skills_dir=get_project_claude_skills_dir(effective_project_root),
89
+ )
90
+
91
+ roots = [
92
+ path.resolve()
93
+ for path in (
94
+ get_built_in_skills_dir(),
95
+ *p_roots,
96
+ get_user_skills_dir(assistant_id),
97
+ get_project_skills_dir(effective_project_root),
98
+ get_user_agent_skills_dir(),
99
+ get_project_agent_skills_dir(effective_project_root),
100
+ get_user_claude_skills_dir(),
101
+ get_project_claude_skills_dir(effective_project_root),
102
+ )
103
+ if path is not None and path.exists()
104
+ ]
105
+
106
+ # Add extra skills dirs from environment and settings
107
+ extra_dirs_val = os.environ.get(EXTRA_SKILLS_DIRS, "")
108
+ if extra_dirs_val:
109
+ base = path_base or Path.cwd()
110
+ for part in extra_dirs_val.split(os.pathsep):
111
+ part = part.strip()
112
+ if part:
113
+ p = (base / part).resolve() if not os.path.isabs(part) else Path(part).resolve()
114
+ if p.is_dir():
115
+ roots.append(p)
116
+
117
+ extra_settings_dirs = getattr(settings, "extra_skills_dirs", None)
118
+ if extra_settings_dirs and isinstance(extra_settings_dirs, (list, tuple)):
119
+ base = path_base or Path.cwd()
120
+ for item in extra_settings_dirs:
121
+ p = (base / item).resolve() if not os.path.isabs(str(item)) else Path(item).resolve()
122
+ if p.is_dir():
123
+ roots.append(p)
124
+
125
+ # Persisted in-the-moment approvals extend the containment allowlist
126
+ roots.extend(load_trusted_skill_dirs())
127
+
128
+ return skills, roots
129
+
130
+
131
+ def build_skill_invocation_envelope(
132
+ skill: ExtendedSkillMetadata | dict[str, Any],
133
+ content: str,
134
+ args: str = "",
135
+ ) -> SkillInvocationEnvelope:
136
+ """Build the wrapped prompt and persisted metadata for a skill.
137
+
138
+ Args:
139
+ skill: Loaded skill metadata.
140
+ content: Raw `SKILL.md` content.
141
+ args: Optional user request appended after the skill body.
142
+
143
+ Returns:
144
+ A `SkillInvocationEnvelope` with the composed prompt and
145
+ `message_kwargs` containing persisted skill metadata.
146
+ """
147
+ skill_name = str(skill.get("name", "unknown"))
148
+ prompt = (
149
+ f"I'm invoking the skill `{skill_name}`. "
150
+ "Below are the full instructions from the skill's SKILL.md file. "
151
+ "Follow these instructions to complete the task.\n\n"
152
+ f"---\n{content}\n---"
153
+ )
154
+ skill_path = str(skill.get("path", "") or "")
155
+ if skill_path:
156
+ skill_p = Path(skill_path)
157
+ skill_dir = skill_p.parent if skill_p.is_file() else skill_p
158
+ prompt += f"\n\nSkill directory on disk: `{skill_dir}`"
159
+ if args:
160
+ prompt += f"\n\n**User request:** {args}"
161
+
162
+ message_kwargs = {
163
+ "additional_kwargs": {
164
+ "__skill": {
165
+ "name": skill_name,
166
+ "description": str(skill.get("description", "")),
167
+ "source": str(skill.get("source", "")),
168
+ "args": args,
169
+ },
170
+ },
171
+ }
172
+ return SkillInvocationEnvelope(
173
+ prompt=prompt,
174
+ message_kwargs=message_kwargs,
175
+ skill_name=skill_name,
176
+ )
177
+
178
+
179
+ def parse_skill_command(command: str) -> tuple[str, str]:
180
+ """Extract skill name and args from a ``/skill:<name>`` command."""
181
+ if not command.startswith("/skill:"):
182
+ return "", ""
183
+ after_prefix = command[len("/skill:") :].strip()
184
+ parts = after_prefix.split(maxsplit=1)
185
+ if not parts or not parts[0]:
186
+ return "", ""
187
+ skill_name = parts[0].lower()
188
+ args = parts[1] if len(parts) > 1 else ""
189
+ return skill_name, args
190
+
191
+
192
+ STATIC_SKILL_ALIASES: frozenset[str] = frozenset({"remember", "skill-creator"})
193
+
194
+ __all__ = [
195
+ "STATIC_SKILL_ALIASES",
196
+ "SkillInvocationEnvelope",
197
+ "build_skill_invocation_envelope",
198
+ "discover_skills_and_roots",
199
+ "parse_skill_command",
200
+ ]
@@ -0,0 +1,388 @@
1
+ """Skill loader for CLI commands and agent runtime.
2
+
3
+ This module provides filesystem-based skill discovery across built-in, plugin,
4
+ user, project, and experimental Claude skill locations. It wraps prebuilt
5
+ middleware functionality from deepagents.middleware.skills and adapts it for
6
+ direct filesystem access needed by CLI commands and runtime discovery.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import logging
13
+ from pathlib import Path
14
+ import re
15
+ from typing import TYPE_CHECKING, Any, Literal, cast
16
+
17
+ from deepagents.backends.filesystem import FilesystemBackend
18
+ from deepagents.middleware.skills import (
19
+ SkillMetadata,
20
+ _list_skills as list_skills_from_backend,
21
+ )
22
+ import yaml
23
+
24
+ from opscloud._version import __version__ as _cli_version
25
+ from opscloud.config import paths
26
+ from opscloud.config.env_vars import EXTRA_SKILLS_DIRS
27
+ from opscloud.skills.merge import merge_skill
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import Sequence
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ class ExtendedSkillMetadata(SkillMetadata, total=False):
36
+ """Extended skill metadata for CLI display and runtime, adding source tracking.
37
+
38
+ Attributes:
39
+ source: Origin of the skill. One of `'built-in'`, `'plugin'`, `'user'`,
40
+ `'project'`, or `'claude (experimental)'`.
41
+ """
42
+
43
+ source: Literal["built-in", "plugin", "user", "project", "claude (experimental)", "subagent"]
44
+ location: str
45
+ virtual_path: str
46
+ scope: str
47
+ plugin_id: str | None
48
+ plugin_type: str | None
49
+ domain: str
50
+ tags: list[str]
51
+ preview: str
52
+ enabled: bool
53
+ frontmatter: dict[str, Any]
54
+
55
+
56
+ def _parse_skill_file(skill_md: Path) -> dict[str, Any]:
57
+ """Parse SKILL.md for frontmatter and markdown preview."""
58
+ meta: dict[str, Any] = {
59
+ "description": "",
60
+ "license": None,
61
+ "compatibility": None,
62
+ "tags": [],
63
+ "domain": "",
64
+ "preview": "",
65
+ "frontmatter": {},
66
+ }
67
+ if not skill_md.is_file():
68
+ return meta
69
+
70
+ try:
71
+ content = skill_md.read_text(encoding="utf-8")
72
+ match = re.match(r"^---\s*\n(.*?)\n---\s*\n?(.*)$", content, re.DOTALL)
73
+ if match:
74
+ fm_text, body_text = match.group(1), match.group(2)
75
+ fm = yaml.safe_load(fm_text)
76
+ if isinstance(fm, dict):
77
+ meta["frontmatter"] = fm
78
+ meta["description"] = str(fm.get("description") or "").strip()
79
+ meta["license"] = fm.get("license")
80
+ meta["compatibility"] = fm.get("compatibility")
81
+ raw_tags = fm.get("tags") or []
82
+ meta["tags"] = [str(t) for t in raw_tags] if isinstance(raw_tags, (list, tuple)) else []
83
+ meta["domain"] = str(fm.get("domain") or "")
84
+
85
+ body_clean = body_text.strip()
86
+ body_lines = [
87
+ line.strip()
88
+ for line in body_clean.splitlines()
89
+ if line.strip() and not line.strip().startswith("#")
90
+ ]
91
+ if body_lines:
92
+ meta["preview"] = "\n".join(body_lines[:4])
93
+ else:
94
+ meta["preview"] = meta["description"]
95
+ else:
96
+ lines = [
97
+ line_item.strip()
98
+ for line_item in content.splitlines()
99
+ if line_item.strip() and not line_item.strip().startswith("#")
100
+ ]
101
+ meta["preview"] = "\n".join(lines[:4]) if lines else ""
102
+ except Exception as exc:
103
+ logger.debug("Failed parsing skill metadata from %s: %s", skill_md, exc)
104
+
105
+ return meta
106
+
107
+
108
+ def list_skills(
109
+ *,
110
+ built_in_skills_dir: Path | None = None,
111
+ plugin_skill_sources: Sequence[tuple[Path, str]] = (),
112
+ user_skills_dir: Path | None = None,
113
+ project_skills_dir: Path | None = None,
114
+ user_agent_skills_dir: Path | None = None,
115
+ project_agent_skills_dir: Path | None = None,
116
+ user_claude_skills_dir: Path | None = None,
117
+ project_claude_skills_dir: Path | None = None,
118
+ include_plugins: bool = True,
119
+ include_subagents: bool = False,
120
+ project_root: Path | None = None,
121
+ store: Any = None,
122
+ ) -> list[ExtendedSkillMetadata]:
123
+ """List skills from built-in, plugin, user, and/or project directories.
124
+
125
+ Precedence order (lowest to highest):
126
+ 0. `built_in_skills_dir` (`<package>/built_in_skills/`)
127
+ 1. `plugin_skill_sources`
128
+ 2. `user_skills_dir` (`~/.opscloud/{agent}/skills/` or `~/.opscloud/skills/`)
129
+ 3. `user_agent_skills_dir` (`~/.agents/skills/`)
130
+ 4. `project_skills_dir` (`.opscloud/skills/`)
131
+ 5. `project_agent_skills_dir` (`.agents/skills/`)
132
+ 6. `user_claude_skills_dir` (`~/.claude/skills/`, experimental)
133
+ 7. `project_claude_skills_dir` (`.claude/skills/`, experimental)
134
+
135
+ Skills from higher-precedence directories override those with the same name.
136
+
137
+ Returns:
138
+ Merged list of skill metadata from all sources.
139
+ """
140
+ all_skills: dict[str, ExtendedSkillMetadata] = {}
141
+ merged_source_labels: dict[str, str | None] = {}
142
+
143
+ effective_root = project_root
144
+ if effective_root is None:
145
+ try:
146
+ from opscloud.config.settings import settings
147
+
148
+ effective_root = settings.project_root or paths.find_project_root()
149
+ except Exception:
150
+ effective_root = paths.find_project_root()
151
+
152
+ bi_dir = built_in_skills_dir or paths.get_built_in_skills_dir()
153
+ u_dir = user_skills_dir or paths.get_user_skills_dir("opscloud")
154
+ ua_dir = user_agent_skills_dir or paths.get_user_agent_skills_dir()
155
+ p_dir = project_skills_dir or paths.get_project_skills_dir(effective_root)
156
+ pa_dir = project_agent_skills_dir or paths.get_project_agent_skills_dir(effective_root)
157
+ uc_dir = user_claude_skills_dir or paths.get_user_claude_skills_dir()
158
+ pc_dir = project_claude_skills_dir or paths.get_project_claude_skills_dir(effective_root)
159
+
160
+ sources: list[tuple[Path | None, str, bool, str]] = []
161
+ has_custom_dirs = any(
162
+ x is not None
163
+ for x in (
164
+ built_in_skills_dir,
165
+ user_skills_dir,
166
+ project_skills_dir,
167
+ user_agent_skills_dir,
168
+ project_agent_skills_dir,
169
+ user_claude_skills_dir,
170
+ project_claude_skills_dir,
171
+ )
172
+ ) or bool(plugin_skill_sources)
173
+
174
+ if has_custom_dirs:
175
+ plugin_sources = list(plugin_skill_sources)
176
+ if not plugin_sources and include_plugins:
177
+ try:
178
+ from opscloud.plugins.adapters.skills import discover_plugin_skill_sources_and_roots
179
+
180
+ p_srcs, _ = discover_plugin_skill_sources_and_roots(
181
+ project_root=effective_root,
182
+ include_subagent_skills=include_subagents,
183
+ )
184
+ plugin_sources.extend(p_srcs)
185
+ except Exception as exc:
186
+ logger.debug("Could not resolve plugin skill sources in list_skills: %s", exc)
187
+
188
+ sources = [
189
+ (bi_dir, "built-in", False, ""),
190
+ *[(path, "plugin", False, namespace) for path, namespace in plugin_sources],
191
+ (u_dir, "user", False, ""),
192
+ (ua_dir, "user", False, ""),
193
+ (p_dir, "project", False, ""),
194
+ (pa_dir, "project", False, ""),
195
+ (uc_dir, "claude (experimental)", True, ""),
196
+ (pc_dir, "claude (experimental)", True, ""),
197
+ ]
198
+ else:
199
+ from opscloud.skills.sources import get_skill_sources
200
+
201
+ code_sources = get_skill_sources(
202
+ project_root=effective_root,
203
+ include_subagent_skills=include_subagents,
204
+ store=store,
205
+ )
206
+ for s in code_sources:
207
+ path_obj = Path(s[0])
208
+ lbl = s[1].lower()
209
+ is_plugin = len(s) == 3
210
+ is_claude = "claude" in lbl
211
+ ns = s[2] if len(s) == 3 else ""
212
+ if "subagent" in lbl:
213
+ src_type = "subagent"
214
+ elif is_plugin:
215
+ src_type = "plugin"
216
+ elif "user" in lbl:
217
+ src_type = "user"
218
+ elif "project" in lbl:
219
+ src_type = "project"
220
+ elif "built-in" in lbl:
221
+ src_type = "built-in"
222
+ elif is_claude:
223
+ src_type = "claude (experimental)"
224
+ else:
225
+ src_type = "user"
226
+ sources.append((path_obj, src_type, is_claude, ns))
227
+
228
+ for skill_dir, source_label, experimental, namespace in sources:
229
+ if not skill_dir or not skill_dir.exists():
230
+ continue
231
+ try:
232
+ backend = FilesystemBackend(root_dir=str(skill_dir), virtual_mode=False)
233
+ if namespace:
234
+ from opscloud.middleware.skills import load_namespaced_skills
235
+
236
+ skills = load_namespaced_skills(
237
+ backend, str(skill_dir.resolve()), namespace
238
+ )
239
+ else:
240
+ skills = list_skills_from_backend(backend=backend, source_path=".")
241
+
242
+ if experimental and skills:
243
+ logger.debug(
244
+ "Discovered %d skill(s) from experimental Claude path: %s",
245
+ len(skills),
246
+ skill_dir,
247
+ )
248
+
249
+ for skill in skills:
250
+ extra: dict[str, object] = {
251
+ "source": source_label,
252
+ "scope": source_label.upper(),
253
+ }
254
+ if source_label == "built-in":
255
+ extra["metadata"] = {
256
+ **(skill.get("metadata") or {}),
257
+ "opscloud-version": _cli_version,
258
+ }
259
+
260
+ name = skill.get("name", "")
261
+ skill_path = Path(skill.get("path", "")) if skill.get("path") else (skill_dir / name)
262
+ skill_md_path = skill_path if skill_path.is_file() else (skill_path / "SKILL.md")
263
+
264
+ parsed_meta = _parse_skill_file(skill_md_path)
265
+ desc = parsed_meta["description"] or skill.get("description", "")
266
+
267
+ extended = cast(
268
+ "ExtendedSkillMetadata",
269
+ {
270
+ **skill,
271
+ **extra,
272
+ "name": name,
273
+ "description": desc,
274
+ "path": str(skill_md_path if skill_md_path.is_file() else skill_path),
275
+ "location": str(skill_path.resolve() if skill_path.is_dir() else skill_path.parent.resolve()),
276
+ "virtual_path": f"/skills/{name}/SKILL.md",
277
+ "plugin_id": namespace or None,
278
+ "license": parsed_meta.get("license") or skill.get("license"),
279
+ "compatibility": parsed_meta.get("compatibility") or skill.get("compatibility"),
280
+ "tags": parsed_meta.get("tags") or [],
281
+ "domain": parsed_meta.get("domain") or "",
282
+ "preview": parsed_meta.get("preview") or desc[:150],
283
+ "enabled": True,
284
+ "frontmatter": parsed_meta.get("frontmatter") or {},
285
+ },
286
+ )
287
+ merge_skill(
288
+ all_skills,
289
+ merged_source_labels,
290
+ extended,
291
+ source_label=source_label,
292
+ )
293
+ except Exception:
294
+ logger.warning(
295
+ "Could not load skills from %s",
296
+ skill_dir,
297
+ exc_info=True,
298
+ )
299
+
300
+ return list(all_skills.values())
301
+
302
+
303
+ def load_skill_content(
304
+ skill_path: str,
305
+ *,
306
+ allowed_roots: Sequence[Path] = (),
307
+ ) -> str | None:
308
+ """Read full raw SKILL.md content for a skill, verifying containment safety (SSRF/traversal prevention).
309
+
310
+ Args:
311
+ skill_path: Path to the SKILL.md file or skill directory.
312
+ allowed_roots: Skill root directories the resolved path must be contained within.
313
+
314
+ Returns:
315
+ Full text content of the SKILL.md file, or None on read failure.
316
+
317
+ Raises:
318
+ PermissionError: If the resolved path is outside all allowed_roots.
319
+ """
320
+ path = Path(skill_path).resolve()
321
+ if path.is_dir():
322
+ path = path / "SKILL.md"
323
+
324
+ if allowed_roots:
325
+ resolved_roots = [root.resolve() for root in allowed_roots]
326
+ if not any(path.is_relative_to(root) for root in resolved_roots):
327
+ logger.warning(
328
+ "Skill path %s is outside all allowed roots, refusing to read",
329
+ skill_path,
330
+ )
331
+ msg = (
332
+ f"Skill path {skill_path} resolves outside all allowed skill "
333
+ "directories. If this is a symlink, add the target directory to "
334
+ f"{EXTRA_SKILLS_DIRS} or [skills].extra_allowed_dirs "
335
+ f"in {paths.PATHS.display(paths.CONFIG_PATH)}."
336
+ )
337
+ raise PermissionError(msg)
338
+
339
+ try:
340
+ return path.read_text(encoding="utf-8")
341
+ except (OSError, UnicodeDecodeError):
342
+ logger.warning(
343
+ "Could not read skill content from %s", skill_path, exc_info=True
344
+ )
345
+ return None
346
+
347
+
348
+ def get_skill_by_name(
349
+ name: str,
350
+ *,
351
+ project_root: Path | None = None,
352
+ store: Any = None,
353
+ ) -> ExtendedSkillMetadata | None:
354
+ """Get a single skill's metadata by name."""
355
+ skills = list_skills(project_root=project_root, store=store, include_subagents=True)
356
+ normalized = name.strip().lower()
357
+ for s in skills:
358
+ s_name = s.get("name", "").lower()
359
+ if s_name == normalized or (":" in s_name and s_name.rsplit(":", 1)[-1] == normalized):
360
+ return s
361
+ return None
362
+
363
+
364
+ def get_skill_content_by_name(
365
+ name: str,
366
+ *,
367
+ project_root: Path | None = None,
368
+ store: Any = None,
369
+ ) -> tuple[ExtendedSkillMetadata | None, str | None]:
370
+ """Get skill metadata and its raw markdown content by name."""
371
+ skill = get_skill_by_name(name, project_root=project_root, store=store)
372
+ if not skill:
373
+ return None, None
374
+ skill_path = skill.get("path")
375
+ if not skill_path:
376
+ return skill, None
377
+ content = load_skill_content(skill_path)
378
+ return skill, content
379
+
380
+
381
+ __all__ = [
382
+ "ExtendedSkillMetadata",
383
+ "SkillMetadata",
384
+ "get_skill_by_name",
385
+ "get_skill_content_by_name",
386
+ "list_skills",
387
+ "load_skill_content",
388
+ ]
@@ -0,0 +1,23 @@
1
+ """Compatibility shim for opscloud.skills.loader -> opscloud.skills.load."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from opscloud.skills.load import (
6
+ ExtendedSkillMetadata,
7
+ SkillMetadata,
8
+ _parse_skill_file,
9
+ get_skill_by_name,
10
+ get_skill_content_by_name,
11
+ list_skills,
12
+ load_skill_content,
13
+ )
14
+
15
+ __all__ = [
16
+ "ExtendedSkillMetadata",
17
+ "SkillMetadata",
18
+ "_parse_skill_file",
19
+ "get_skill_by_name",
20
+ "get_skill_content_by_name",
21
+ "list_skills",
22
+ "load_skill_content",
23
+ ]
@@ -0,0 +1,65 @@
1
+ """Shared skill-merge helper with override (name-collision) debug logging.
2
+
3
+ Both skill discovery paths — the CLI `skills list` loader
4
+ (`opscloud.skills.load`) and the runtime agent loader
5
+ (`opscloud.middleware.skills.PluginSkillsMiddleware`) —
6
+ merge skills from multiple sources by precedence, last-one-wins, keyed on skill
7
+ name. A higher-precedence skill replaces a lower-precedence skill with the same
8
+ name. That override behavior is intentional; this helper leaves it unchanged and
9
+ makes each replacement observable in debug logs.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ from collections.abc import Mapping
16
+ from typing import TYPE_CHECKING
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import MutableMapping
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def merge_skill[SkillT: Mapping[str, object]](
25
+ merged: MutableMapping[str, SkillT],
26
+ source_labels: MutableMapping[str, str | None],
27
+ skill: SkillT,
28
+ *,
29
+ source_label: str | None = None,
30
+ ) -> None:
31
+ """Merge one skill into `merged` by name, last-one-wins.
32
+
33
+ Emits one `DEBUG` log whenever a skill replaces an already-merged skill with
34
+ the same name, recording the skill name plus the previous and replacement
35
+ source paths and labels so the winning definition is unambiguous. Nothing is
36
+ logged when there is no collision.
37
+
38
+ Callers must iterate sources in ascending precedence order so the replacing
39
+ skill is always the higher-precedence one.
40
+
41
+ Args:
42
+ merged: Accumulator mapping skill name to merged metadata; mutated in
43
+ place.
44
+ source_labels: Parallel accumulator mapping skill name to the label of
45
+ the source that last supplied it; mutated in place so the previous
46
+ label is available on the next collision.
47
+ skill: Skill metadata to merge. Must expose `name`; `path`, when present,
48
+ is included in the override log to identify the colliding files.
49
+ source_label: Human-readable label for the source supplying `skill`,
50
+ when known. A missing or empty label renders as `"unknown"` in the
51
+ log.
52
+ """
53
+ name = str(skill["name"])
54
+ previous = merged.get(name)
55
+ if previous is not None:
56
+ logger.debug(
57
+ "Skill %r override: %s (source: %s) replaced by %s (source: %s)",
58
+ name,
59
+ previous.get("path"),
60
+ source_labels.get(name) or "unknown",
61
+ skill.get("path"),
62
+ source_label or "unknown",
63
+ )
64
+ merged[name] = skill
65
+ source_labels[name] = source_label