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,776 @@
1
+ """PostgreSQL-backed configuration storage adapter.
2
+
3
+ Implements storage for:
4
+ - ``config_store`` — generic key/value configuration settings
5
+ - ``model_preferences`` — default model, recent models MRU, effort-by-model, provider configs
6
+ - ``mcp_servers`` — MCP server configs (matches OpsCode MCPServerConfig)
7
+ - ``plugins`` — installed plugin records with source for redeployment auto-rehydration
8
+ - ``skills`` — skill metadata and content for redeployment auto-rehydration
9
+ - ``subagents`` — subagent metadata and system prompt for redeployment auto-rehydration
10
+ - ``agent_instructions`` — flat file instruction tracking
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import json
17
+ from typing import Any, cast
18
+
19
+ import psycopg
20
+ from psycopg import Connection
21
+ from psycopg.rows import DictRow, dict_row
22
+
23
+ from opscloud.config.store import ConfigCategory, ConfigEntry, ConfigStorageAdapter
24
+ from opscloud.utils.logger import get_logger
25
+
26
+ logger = get_logger(__name__)
27
+
28
+ _SCHEMA_SQL = """
29
+ -- Core config key/value store
30
+ CREATE TABLE IF NOT EXISTS config_store (
31
+ key TEXT PRIMARY KEY,
32
+ value TEXT NOT NULL,
33
+ category TEXT NOT NULL DEFAULT 'system',
34
+ display_name TEXT DEFAULT '',
35
+ description TEXT DEFAULT '',
36
+ is_secret BOOLEAN DEFAULT FALSE,
37
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
38
+ );
39
+
40
+ -- Model preferences & catalog overrides
41
+ CREATE TABLE IF NOT EXISTS model_preferences (
42
+ id TEXT PRIMARY KEY DEFAULT 'current',
43
+ default_model TEXT,
44
+ recent_models TEXT DEFAULT '[]',
45
+ effort_by_model TEXT DEFAULT '{}',
46
+ provider_configs TEXT DEFAULT '{}',
47
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
48
+ );
49
+
50
+ -- MCP server configurations (matches OpsCode MCPServerConfig)
51
+ CREATE TABLE IF NOT EXISTS mcp_servers (
52
+ name TEXT PRIMARY KEY,
53
+ transport TEXT NOT NULL DEFAULT 'stdio',
54
+ command TEXT,
55
+ args TEXT DEFAULT '[]',
56
+ url TEXT,
57
+ env TEXT DEFAULT '{}',
58
+ headers TEXT DEFAULT '{}',
59
+ source TEXT NOT NULL DEFAULT 'user',
60
+ auth_token_env_var TEXT,
61
+ disabled_tools TEXT DEFAULT '[]',
62
+ allowed_tools TEXT DEFAULT '[]',
63
+ enabled BOOLEAN DEFAULT TRUE,
64
+ trusted BOOLEAN DEFAULT FALSE,
65
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
66
+ );
67
+
68
+ -- Marketplace catalog records
69
+ CREATE TABLE IF NOT EXISTS marketplaces (
70
+ name TEXT PRIMARY KEY,
71
+ source_type TEXT NOT NULL DEFAULT 'directory',
72
+ source_value TEXT NOT NULL,
73
+ install_location TEXT NOT NULL,
74
+ ref TEXT,
75
+ plugin_count INTEGER DEFAULT 0,
76
+ is_team BOOLEAN DEFAULT FALSE,
77
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
78
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
79
+ );
80
+
81
+ -- Plugin records with source for redeployment auto-rehydration
82
+ CREATE TABLE IF NOT EXISTS plugins (
83
+ plugin_id TEXT PRIMARY KEY,
84
+ name TEXT NOT NULL,
85
+ marketplace TEXT NOT NULL DEFAULT 'default',
86
+ version TEXT,
87
+ display_name TEXT,
88
+ description TEXT,
89
+ author TEXT,
90
+ skill_count INTEGER DEFAULT 0,
91
+ skill_names TEXT DEFAULT '[]',
92
+ mcp_server_names TEXT DEFAULT '[]',
93
+ install_path TEXT,
94
+ scope TEXT NOT NULL DEFAULT 'user',
95
+ source_type TEXT NOT NULL DEFAULT 'local',
96
+ source_value TEXT,
97
+ enabled BOOLEAN DEFAULT TRUE,
98
+ config TEXT DEFAULT '{}',
99
+ installed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
100
+ last_updated TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
101
+ git_commit_sha TEXT,
102
+ load_error TEXT,
103
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
104
+ );
105
+
106
+ -- Skill metadata with content for redeployment auto-rehydration
107
+ CREATE TABLE IF NOT EXISTS skills (
108
+ name TEXT PRIMARY KEY,
109
+ description TEXT DEFAULT '',
110
+ domain TEXT DEFAULT '',
111
+ path TEXT,
112
+ virtual_path TEXT,
113
+ source TEXT NOT NULL DEFAULT 'built-in',
114
+ content TEXT DEFAULT '',
115
+ enabled BOOLEAN DEFAULT TRUE,
116
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
117
+ );
118
+
119
+ -- Subagent metadata with system_prompt for redeployment auto-rehydration
120
+ CREATE TABLE IF NOT EXISTS subagents (
121
+ name TEXT PRIMARY KEY,
122
+ description TEXT DEFAULT '',
123
+ model TEXT,
124
+ instructions_path TEXT,
125
+ system_prompt TEXT DEFAULT '',
126
+ tools TEXT DEFAULT '[]',
127
+ source TEXT NOT NULL DEFAULT 'built-in',
128
+ enabled BOOLEAN DEFAULT TRUE,
129
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
130
+ );
131
+
132
+ -- Agent instruction tracking
133
+ CREATE TABLE IF NOT EXISTS agent_instructions (
134
+ scope TEXT PRIMARY KEY,
135
+ file_path TEXT NOT NULL,
136
+ checksum TEXT,
137
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
138
+ );
139
+ """
140
+
141
+ _CONFIG_CHANGE_TRIGGER_SQL = """
142
+ CREATE OR REPLACE FUNCTION notify_config_change()
143
+ RETURNS trigger AS $$
144
+ BEGIN
145
+ PERFORM pg_notify('config_change', NEW.key);
146
+ RETURN NEW;
147
+ END;
148
+ $$ LANGUAGE plpgsql;
149
+
150
+ DROP TRIGGER IF EXISTS config_change_trigger ON config_store;
151
+ CREATE TRIGGER config_change_trigger
152
+ AFTER INSERT OR UPDATE ON config_store
153
+ FOR EACH ROW EXECUTE FUNCTION notify_config_change();
154
+ """
155
+
156
+
157
+ class PostgresConfigAdapter(ConfigStorageAdapter):
158
+ """PostgreSQL-backed config storage with pg_notify support."""
159
+
160
+ def __init__(self, connection_uri: str) -> None:
161
+ """Initialize the PostgreSQL configuration storage adapter."""
162
+ self._uri = connection_uri
163
+
164
+ def _connect(self) -> Connection[DictRow]:
165
+ return cast(
166
+ Connection[DictRow],
167
+ psycopg.connect(self._uri, row_factory=cast(Any, dict_row)),
168
+ )
169
+
170
+ async def initialize(self) -> None:
171
+ """Create all tables and notification triggers."""
172
+ with self._connect() as conn:
173
+ conn.execute(_SCHEMA_SQL)
174
+ conn.execute(_CONFIG_CHANGE_TRIGGER_SQL)
175
+ # Add columns if migrating an existing DB
176
+ plugin_migration_stmts = (
177
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS display_name TEXT",
178
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS description TEXT",
179
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS author TEXT",
180
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS skill_count INTEGER DEFAULT 0",
181
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS skill_names TEXT DEFAULT '[]'",
182
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS mcp_server_names TEXT DEFAULT '[]'",
183
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS installed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()",
184
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS last_updated TIMESTAMP WITH TIME ZONE DEFAULT NOW()",
185
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS git_commit_sha TEXT",
186
+ "ALTER TABLE plugins ADD COLUMN IF NOT EXISTS load_error TEXT",
187
+ )
188
+ for stmt in plugin_migration_stmts:
189
+ with contextlib.suppress(Exception):
190
+ conn.execute(stmt)
191
+ with contextlib.suppress(Exception):
192
+ conn.execute("ALTER TABLE skills ADD COLUMN IF NOT EXISTS content TEXT DEFAULT ''")
193
+ with contextlib.suppress(Exception):
194
+ conn.execute("ALTER TABLE subagents ADD COLUMN IF NOT EXISTS system_prompt TEXT DEFAULT ''")
195
+ mcp_migration_stmts = (
196
+ "ALTER TABLE mcp_servers ADD COLUMN IF NOT EXISTS disabled_tools TEXT DEFAULT '[]'",
197
+ "ALTER TABLE mcp_servers ADD COLUMN IF NOT EXISTS allowed_tools TEXT DEFAULT '[]'",
198
+ )
199
+ for stmt in mcp_migration_stmts:
200
+ with contextlib.suppress(Exception):
201
+ conn.execute(stmt)
202
+ conn.execute("INSERT INTO model_preferences (id) VALUES ('current') ON CONFLICT (id) DO NOTHING")
203
+ conn.commit()
204
+ logger.debug("PostgresConfigAdapter initialized")
205
+
206
+ # ── ConfigEntry CRUD ─────────────────────────────────
207
+
208
+ async def load_all(self) -> list[ConfigEntry]:
209
+ """Load all configuration entries from the database."""
210
+ with self._connect() as conn:
211
+ rows = conn.execute(
212
+ "SELECT key, value, category, display_name, description, is_secret FROM config_store ORDER BY key"
213
+ ).fetchall()
214
+ return [self._row_to_entry(row) for row in rows]
215
+
216
+ async def get(self, key: str) -> ConfigEntry | None:
217
+ """Retrieve a single configuration entry by its key."""
218
+ with self._connect() as conn:
219
+ row = conn.execute(
220
+ "SELECT key, value, category, display_name, description, is_secret FROM config_store WHERE key = %s",
221
+ (key,),
222
+ ).fetchone()
223
+ return self._row_to_entry(row) if row else None
224
+
225
+ async def set(self, entry: ConfigEntry) -> None:
226
+ """Store or update a configuration entry."""
227
+ with self._connect() as conn:
228
+ conn.execute(
229
+ """
230
+ INSERT INTO config_store (key, value, category, display_name, description, is_secret, updated_at)
231
+ VALUES (%s, %s, %s, %s, %s, %s, NOW())
232
+ ON CONFLICT(key) DO UPDATE SET
233
+ value = EXCLUDED.value,
234
+ category = EXCLUDED.category,
235
+ display_name = EXCLUDED.display_name,
236
+ description = EXCLUDED.description,
237
+ is_secret = EXCLUDED.is_secret,
238
+ updated_at = NOW()
239
+ """,
240
+ (
241
+ entry.key,
242
+ entry.value,
243
+ entry.category.value,
244
+ entry.display_name,
245
+ entry.description,
246
+ entry.is_secret,
247
+ ),
248
+ )
249
+ conn.commit()
250
+
251
+ async def delete(self, key: str) -> bool:
252
+ """Delete a configuration entry by its key."""
253
+ with self._connect() as conn:
254
+ result = conn.execute("DELETE FROM config_store WHERE key = %s", (key,))
255
+ conn.commit()
256
+ return result.rowcount > 0
257
+
258
+ async def list_by_category(self, category: ConfigCategory) -> list[ConfigEntry]:
259
+ """Retrieve all configuration entries belonging to a category."""
260
+ with self._connect() as conn:
261
+ rows = conn.execute(
262
+ "SELECT key, value, category, display_name, description, is_secret "
263
+ "FROM config_store WHERE category = %s ORDER BY key",
264
+ (category.value,),
265
+ ).fetchall()
266
+ return [self._row_to_entry(row) for row in rows]
267
+
268
+ # ── Model Preferences CRUD ────────────────────
269
+
270
+ async def get_model_preferences(self) -> dict[str, Any]:
271
+ """Retrieve saved model preferences."""
272
+ with self._connect() as conn:
273
+ row = conn.execute(
274
+ "SELECT default_model, recent_models, effort_by_model, provider_configs "
275
+ "FROM model_preferences WHERE id = 'current'"
276
+ ).fetchone()
277
+ if row is None:
278
+ return {
279
+ "default_model": None,
280
+ "recent_models": [],
281
+ "effort_by_model": {},
282
+ "provider_configs": {},
283
+ }
284
+ return {
285
+ "default_model": row["default_model"],
286
+ "recent_models": json.loads(row["recent_models"] or "[]"),
287
+ "effort_by_model": json.loads(row["effort_by_model"] or "{}"),
288
+ "provider_configs": json.loads(row["provider_configs"] or "{}"),
289
+ }
290
+
291
+ async def save_model_preferences(self, prefs: dict[str, Any]) -> None:
292
+ """Save or update model preferences."""
293
+ with self._connect() as conn:
294
+ conn.execute(
295
+ """
296
+ INSERT INTO model_preferences (id, default_model, recent_models, effort_by_model, provider_configs, updated_at)
297
+ VALUES ('current', %s, %s, %s, %s, NOW())
298
+ ON CONFLICT(id) DO UPDATE SET
299
+ default_model = COALESCE(EXCLUDED.default_model, model_preferences.default_model),
300
+ recent_models = COALESCE(EXCLUDED.recent_models, model_preferences.recent_models),
301
+ effort_by_model = COALESCE(EXCLUDED.effort_by_model, model_preferences.effort_by_model),
302
+ provider_configs = COALESCE(EXCLUDED.provider_configs, model_preferences.provider_configs),
303
+ updated_at = NOW()
304
+ """,
305
+ (
306
+ prefs.get("default_model"),
307
+ json.dumps(prefs.get("recent_models", [])) if "recent_models" in prefs else None,
308
+ json.dumps(prefs.get("effort_by_model", {})) if "effort_by_model" in prefs else None,
309
+ json.dumps(prefs.get("provider_configs", {})) if "provider_configs" in prefs else None,
310
+ ),
311
+ )
312
+ conn.commit()
313
+
314
+ # ── MCP Server CRUD ──────────────────────────────────
315
+
316
+ async def list_mcp_servers(self) -> list[dict[str, Any]]:
317
+ """List all configured MCP servers."""
318
+ with self._connect() as conn:
319
+ rows = conn.execute("SELECT * FROM mcp_servers ORDER BY name").fetchall()
320
+ return [
321
+ {
322
+ "name": row["name"],
323
+ "transport": row["transport"],
324
+ "command": row["command"],
325
+ "args": json.loads(row["args"] or "[]") if isinstance(row["args"], str) else (row["args"] or []),
326
+ "url": row["url"],
327
+ "env": json.loads(row["env"] or "{}") if isinstance(row["env"], str) else (row["env"] or {}),
328
+ "headers": json.loads(row["headers"] or "{}")
329
+ if isinstance(row["headers"], str)
330
+ else (row["headers"] or {}),
331
+ "source": row["source"],
332
+ "auth_token_env_var": row["auth_token_env_var"],
333
+ "disabled_tools": json.loads(row["disabled_tools"] or "[]")
334
+ if isinstance(row.get("disabled_tools"), str)
335
+ else (row.get("disabled_tools") or []),
336
+ "allowed_tools": json.loads(row["allowed_tools"] or "[]")
337
+ if isinstance(row.get("allowed_tools"), str)
338
+ else (row.get("allowed_tools") or []),
339
+ "enabled": bool(row["enabled"]),
340
+ "trusted": bool(row["trusted"]),
341
+ }
342
+ for row in rows
343
+ ]
344
+
345
+ async def get_mcp_server(self, name: str) -> dict[str, Any] | None:
346
+ """Retrieve an MCP server configuration by name."""
347
+ with self._connect() as conn:
348
+ row = conn.execute("SELECT * FROM mcp_servers WHERE name = %s", (name,)).fetchone()
349
+ if row is None:
350
+ return None
351
+ return {
352
+ "name": row["name"],
353
+ "transport": row["transport"],
354
+ "command": row["command"],
355
+ "args": json.loads(row["args"] or "[]") if isinstance(row["args"], str) else (row["args"] or []),
356
+ "url": row["url"],
357
+ "env": json.loads(row["env"] or "{}") if isinstance(row["env"], str) else (row["env"] or {}),
358
+ "headers": json.loads(row["headers"] or "{}")
359
+ if isinstance(row["headers"], str)
360
+ else (row["headers"] or {}),
361
+ "source": row["source"],
362
+ "auth_token_env_var": row["auth_token_env_var"],
363
+ "disabled_tools": json.loads(row["disabled_tools"] or "[]")
364
+ if isinstance(row.get("disabled_tools"), str)
365
+ else (row.get("disabled_tools") or []),
366
+ "allowed_tools": json.loads(row["allowed_tools"] or "[]")
367
+ if isinstance(row.get("allowed_tools"), str)
368
+ else (row.get("allowed_tools") or []),
369
+ "enabled": bool(row["enabled"]),
370
+ "trusted": bool(row["trusted"]),
371
+ }
372
+
373
+ async def upsert_mcp_server(self, server: dict[str, Any]) -> None:
374
+ """Create or update an MCP server configuration."""
375
+ with self._connect() as conn:
376
+ conn.execute(
377
+ """
378
+ INSERT INTO mcp_servers (name, transport, command, args, url, env, headers, source, auth_token_env_var, disabled_tools, allowed_tools, enabled, trusted, updated_at)
379
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW())
380
+ ON CONFLICT(name) DO UPDATE SET
381
+ transport = EXCLUDED.transport,
382
+ command = EXCLUDED.command,
383
+ args = EXCLUDED.args,
384
+ url = EXCLUDED.url,
385
+ env = EXCLUDED.env,
386
+ headers = EXCLUDED.headers,
387
+ source = EXCLUDED.source,
388
+ auth_token_env_var = EXCLUDED.auth_token_env_var,
389
+ disabled_tools = EXCLUDED.disabled_tools,
390
+ allowed_tools = EXCLUDED.allowed_tools,
391
+ enabled = EXCLUDED.enabled,
392
+ trusted = EXCLUDED.trusted,
393
+ updated_at = NOW()
394
+ """,
395
+ (
396
+ server["name"],
397
+ server.get("transport", "stdio"),
398
+ server.get("command"),
399
+ json.dumps(server.get("args", [])),
400
+ server.get("url"),
401
+ json.dumps(server.get("env", {})),
402
+ json.dumps(server.get("headers", {})),
403
+ server.get("source", "user"),
404
+ server.get("auth_token_env_var"),
405
+ json.dumps(server.get("disabled_tools", [])),
406
+ json.dumps(server.get("allowed_tools", [])),
407
+ server.get("enabled", True),
408
+ server.get("trusted", False),
409
+ ),
410
+ )
411
+ conn.commit()
412
+
413
+ async def delete_mcp_server(self, name: str) -> bool:
414
+ """Delete an MCP server configuration by name."""
415
+ with self._connect() as conn:
416
+ result = conn.execute("DELETE FROM mcp_servers WHERE name = %s", (name,))
417
+ conn.commit()
418
+ return result.rowcount > 0
419
+
420
+ # ── Marketplace Metadata CRUD ─────────────────────────
421
+
422
+ async def list_marketplaces(self) -> list[dict[str, Any]]:
423
+ """List all configured plugin marketplaces."""
424
+ with self._connect() as conn:
425
+ rows = conn.execute("SELECT * FROM marketplaces ORDER BY name").fetchall()
426
+ return [
427
+ {
428
+ "name": row["name"],
429
+ "source_type": row["source_type"],
430
+ "source_value": row["source_value"],
431
+ "install_location": row["install_location"],
432
+ "ref": row["ref"],
433
+ "plugin_count": row["plugin_count"],
434
+ "is_team": bool(row["is_team"]),
435
+ "created_at": str(row["created_at"]) if row["created_at"] else None,
436
+ "updated_at": str(row["updated_at"]) if row["updated_at"] else None,
437
+ }
438
+ for row in rows
439
+ ]
440
+
441
+ async def get_marketplace(self, name: str) -> dict[str, Any] | None:
442
+ """Retrieve a plugin marketplace by name."""
443
+ with self._connect() as conn:
444
+ row = conn.execute(
445
+ "SELECT * FROM marketplaces WHERE name = %s",
446
+ (name,),
447
+ ).fetchone()
448
+ if not row:
449
+ return None
450
+ return {
451
+ "name": row["name"],
452
+ "source_type": row["source_type"],
453
+ "source_value": row["source_value"],
454
+ "install_location": row["install_location"],
455
+ "ref": row["ref"],
456
+ "plugin_count": row["plugin_count"],
457
+ "is_team": bool(row["is_team"]),
458
+ "created_at": str(row["created_at"]) if row["created_at"] else None,
459
+ "updated_at": str(row["updated_at"]) if row["updated_at"] else None,
460
+ }
461
+
462
+ async def upsert_marketplace(self, marketplace: dict[str, Any]) -> None:
463
+ """Create or update a plugin marketplace record."""
464
+ with self._connect() as conn:
465
+ conn.execute(
466
+ """
467
+ INSERT INTO marketplaces (name, source_type, source_value, install_location, ref, plugin_count, is_team, updated_at)
468
+ VALUES (%s, %s, %s, %s, %s, %s, %s, NOW())
469
+ ON CONFLICT(name) DO UPDATE SET
470
+ source_type = EXCLUDED.source_type,
471
+ source_value = EXCLUDED.source_value,
472
+ install_location = EXCLUDED.install_location,
473
+ ref = EXCLUDED.ref,
474
+ plugin_count = EXCLUDED.plugin_count,
475
+ is_team = EXCLUDED.is_team,
476
+ updated_at = NOW()
477
+ """,
478
+ (
479
+ marketplace["name"],
480
+ marketplace.get("source_type", "directory"),
481
+ marketplace.get("source_value", ""),
482
+ marketplace.get("install_location", ""),
483
+ marketplace.get("ref"),
484
+ int(marketplace.get("plugin_count", 0)),
485
+ bool(marketplace.get("is_team", False)),
486
+ ),
487
+ )
488
+ conn.commit()
489
+
490
+ async def delete_marketplace(self, name: str) -> bool:
491
+ """Delete a plugin marketplace by name."""
492
+ with self._connect() as conn:
493
+ result = conn.execute("DELETE FROM marketplaces WHERE name = %s", (name,))
494
+ conn.commit()
495
+ return result.rowcount > 0
496
+
497
+ # ── Plugin Metadata CRUD ──────────────────────────────
498
+
499
+ def _row_to_plugin(self, row: dict[str, Any]) -> dict[str, Any]:
500
+ return {
501
+ "plugin_id": row["plugin_id"],
502
+ "name": row["name"],
503
+ "marketplace": row["marketplace"],
504
+ "version": row["version"],
505
+ "display_name": row.get("display_name"),
506
+ "description": row.get("description"),
507
+ "author": row.get("author"),
508
+ "skill_count": row.get("skill_count") or 0,
509
+ "skill_names": json.loads(row["skill_names"] or "[]")
510
+ if isinstance(row.get("skill_names"), str)
511
+ else (row.get("skill_names") or []),
512
+ "mcp_server_names": json.loads(row["mcp_server_names"] or "[]")
513
+ if isinstance(row.get("mcp_server_names"), str)
514
+ else (row.get("mcp_server_names") or []),
515
+ "install_path": row["install_path"],
516
+ "scope": row["scope"],
517
+ "source_type": row["source_type"],
518
+ "source_value": row["source_value"],
519
+ "enabled": bool(row["enabled"]),
520
+ "config": json.loads(row["config"] or "{}")
521
+ if isinstance(row.get("config"), str)
522
+ else (row.get("config") or {}),
523
+ "installed_at": str(row["installed_at"]) if row.get("installed_at") else None,
524
+ "last_updated": str(row["last_updated"]) if row.get("last_updated") else None,
525
+ "git_commit_sha": row.get("git_commit_sha"),
526
+ "load_error": row.get("load_error"),
527
+ }
528
+
529
+ async def list_plugins(self) -> list[dict[str, Any]]:
530
+ """List all installed plugin records."""
531
+ with self._connect() as conn:
532
+ rows = conn.execute("SELECT * FROM plugins ORDER BY plugin_id").fetchall()
533
+ return [self._row_to_plugin(row) for row in rows]
534
+
535
+ async def get_plugin(self, plugin_id: str) -> dict[str, Any] | None:
536
+ """Retrieve an installed plugin record by ID."""
537
+ with self._connect() as conn:
538
+ row = conn.execute(
539
+ "SELECT * FROM plugins WHERE plugin_id = %s",
540
+ (plugin_id,),
541
+ ).fetchone()
542
+ if not row:
543
+ return None
544
+ return self._row_to_plugin(row)
545
+
546
+ async def upsert_plugin(self, plugin: dict[str, Any]) -> None:
547
+ """Create or update an installed plugin record."""
548
+ p_id = plugin.get("plugin_id") or f"{plugin['name']}@{plugin.get('marketplace', 'default')}"
549
+ skill_names = plugin.get("skill_names")
550
+ skill_names_json = json.dumps(list(skill_names)) if isinstance(skill_names, (list, tuple)) else json.dumps([])
551
+
552
+ mcp_names = plugin.get("mcp_server_names")
553
+ mcp_names_json = json.dumps(list(mcp_names)) if isinstance(mcp_names, (list, tuple)) else json.dumps([])
554
+
555
+ with self._connect() as conn:
556
+ conn.execute(
557
+ """
558
+ INSERT INTO plugins (
559
+ plugin_id, name, marketplace, version, display_name, description, author,
560
+ skill_count, skill_names, mcp_server_names, install_path, scope,
561
+ source_type, source_value, enabled, config, installed_at, last_updated,
562
+ git_commit_sha, load_error, updated_at
563
+ )
564
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW(), %s, %s, NOW())
565
+ ON CONFLICT(plugin_id) DO UPDATE SET
566
+ name = EXCLUDED.name,
567
+ marketplace = EXCLUDED.marketplace,
568
+ version = EXCLUDED.version,
569
+ display_name = EXCLUDED.display_name,
570
+ description = EXCLUDED.description,
571
+ author = EXCLUDED.author,
572
+ skill_count = EXCLUDED.skill_count,
573
+ skill_names = EXCLUDED.skill_names,
574
+ mcp_server_names = EXCLUDED.mcp_server_names,
575
+ install_path = EXCLUDED.install_path,
576
+ scope = EXCLUDED.scope,
577
+ source_type = EXCLUDED.source_type,
578
+ source_value = EXCLUDED.source_value,
579
+ enabled = EXCLUDED.enabled,
580
+ config = EXCLUDED.config,
581
+ last_updated = NOW(),
582
+ git_commit_sha = EXCLUDED.git_commit_sha,
583
+ load_error = EXCLUDED.load_error,
584
+ updated_at = NOW()
585
+ """,
586
+ (
587
+ p_id,
588
+ plugin["name"],
589
+ plugin.get("marketplace", "default"),
590
+ plugin.get("version"),
591
+ plugin.get("display_name"),
592
+ plugin.get("description"),
593
+ plugin.get("author"),
594
+ int(plugin.get("skill_count", 0)),
595
+ skill_names_json,
596
+ mcp_names_json,
597
+ plugin.get("install_path"),
598
+ plugin.get("scope", "user"),
599
+ plugin.get("source_type", "local"),
600
+ plugin.get("source_value"),
601
+ bool(plugin.get("enabled", True)),
602
+ json.dumps(plugin.get("config", {})),
603
+ plugin.get("git_commit_sha"),
604
+ plugin.get("load_error"),
605
+ ),
606
+ )
607
+ conn.commit()
608
+
609
+ async def delete_plugin(self, plugin_id: str) -> bool:
610
+ """Delete an installed plugin record by ID."""
611
+ with self._connect() as conn:
612
+ result = conn.execute("DELETE FROM plugins WHERE plugin_id = %s", (plugin_id,))
613
+ conn.commit()
614
+ return result.rowcount > 0
615
+
616
+ # ── Skill Metadata CRUD ───────────────────────────────
617
+
618
+ async def list_skills(self) -> list[dict[str, Any]]:
619
+ """List all stored custom skill records."""
620
+ with self._connect() as conn:
621
+ rows = conn.execute("SELECT * FROM skills ORDER BY name").fetchall()
622
+ return [
623
+ {
624
+ "name": row["name"],
625
+ "description": row["description"] or "",
626
+ "domain": row["domain"] or "",
627
+ "path": row["path"],
628
+ "virtual_path": row["virtual_path"],
629
+ "source": row["source"],
630
+ "content": row.get("content") or "",
631
+ "enabled": bool(row["enabled"]),
632
+ }
633
+ for row in rows
634
+ ]
635
+
636
+ async def upsert_skill(self, skill: dict[str, Any]) -> None:
637
+ """Create or update a custom skill record."""
638
+ with self._connect() as conn:
639
+ conn.execute(
640
+ """
641
+ INSERT INTO skills (name, description, domain, path, virtual_path, source, content, enabled, updated_at)
642
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW())
643
+ ON CONFLICT(name) DO UPDATE SET
644
+ description = EXCLUDED.description,
645
+ domain = EXCLUDED.domain,
646
+ path = EXCLUDED.path,
647
+ virtual_path = EXCLUDED.virtual_path,
648
+ source = EXCLUDED.source,
649
+ content = CASE WHEN EXCLUDED.content != '' THEN EXCLUDED.content ELSE skills.content END,
650
+ enabled = EXCLUDED.enabled,
651
+ updated_at = NOW()
652
+ """,
653
+ (
654
+ skill["name"],
655
+ skill.get("description", ""),
656
+ skill.get("domain", ""),
657
+ skill.get("path"),
658
+ skill.get("virtual_path"),
659
+ skill.get("source", "built-in"),
660
+ skill.get("content", ""),
661
+ skill.get("enabled", True),
662
+ ),
663
+ )
664
+ conn.commit()
665
+
666
+ async def delete_skill(self, name: str) -> bool:
667
+ """Delete a custom skill record by name."""
668
+ with self._connect() as conn:
669
+ result = conn.execute("DELETE FROM skills WHERE name = %s", (name,))
670
+ conn.commit()
671
+ return result.rowcount > 0
672
+
673
+ # ── Subagent Metadata CRUD ────────────────────────────
674
+
675
+ async def list_subagents(self) -> list[dict[str, Any]]:
676
+ """List all stored custom subagent records."""
677
+ with self._connect() as conn:
678
+ rows = conn.execute("SELECT * FROM subagents ORDER BY name").fetchall()
679
+ return [
680
+ {
681
+ "name": row["name"],
682
+ "description": row["description"] or "",
683
+ "model": row["model"],
684
+ "instructions_path": row["instructions_path"],
685
+ "system_prompt": row.get("system_prompt") or "",
686
+ "tools": json.loads(row["tools"] or "[]"),
687
+ "source": row["source"],
688
+ "enabled": bool(row["enabled"]),
689
+ }
690
+ for row in rows
691
+ ]
692
+
693
+ async def upsert_subagent(self, subagent: dict[str, Any]) -> None:
694
+ """Create or update a custom subagent record."""
695
+ with self._connect() as conn:
696
+ conn.execute(
697
+ """
698
+ INSERT INTO subagents (name, description, model, instructions_path, system_prompt, tools, source, enabled, updated_at)
699
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW())
700
+ ON CONFLICT(name) DO UPDATE SET
701
+ description = EXCLUDED.description,
702
+ model = EXCLUDED.model,
703
+ instructions_path = EXCLUDED.instructions_path,
704
+ system_prompt = CASE WHEN EXCLUDED.system_prompt != '' THEN EXCLUDED.system_prompt ELSE subagents.system_prompt END,
705
+ tools = EXCLUDED.tools,
706
+ source = EXCLUDED.source,
707
+ enabled = EXCLUDED.enabled,
708
+ updated_at = NOW()
709
+ """,
710
+ (
711
+ subagent["name"],
712
+ subagent.get("description", ""),
713
+ subagent.get("model"),
714
+ subagent.get("instructions_path"),
715
+ subagent.get("system_prompt", ""),
716
+ json.dumps(subagent.get("tools", [])),
717
+ subagent.get("source", "built-in"),
718
+ subagent.get("enabled", True),
719
+ ),
720
+ )
721
+ conn.commit()
722
+
723
+ async def delete_subagent(self, name: str) -> bool:
724
+ """Delete a custom subagent record by name."""
725
+ with self._connect() as conn:
726
+ result = conn.execute("DELETE FROM subagents WHERE name = %s", (name,))
727
+ conn.commit()
728
+ return result.rowcount > 0
729
+
730
+ # ── Agent Instruction Metadata ────────────────────────
731
+
732
+ async def list_agent_instructions(self) -> list[dict[str, Any]]:
733
+ """List custom instructions configured for agents."""
734
+ with self._connect() as conn:
735
+ rows = conn.execute("SELECT * FROM agent_instructions ORDER BY scope").fetchall()
736
+ return [
737
+ {
738
+ "scope": row["scope"],
739
+ "file_path": row["file_path"],
740
+ "checksum": row["checksum"],
741
+ }
742
+ for row in rows
743
+ ]
744
+
745
+ async def upsert_agent_instruction(self, instruction: dict[str, Any]) -> None:
746
+ """Save or update custom instructions for an agent."""
747
+ with self._connect() as conn:
748
+ conn.execute(
749
+ """
750
+ INSERT INTO agent_instructions (scope, file_path, checksum, updated_at)
751
+ VALUES (%s, %s, %s, NOW())
752
+ ON CONFLICT(scope) DO UPDATE SET
753
+ file_path = EXCLUDED.file_path,
754
+ checksum = EXCLUDED.checksum,
755
+ updated_at = NOW()
756
+ """,
757
+ (
758
+ instruction["scope"],
759
+ instruction["file_path"],
760
+ instruction.get("checksum"),
761
+ ),
762
+ )
763
+ conn.commit()
764
+
765
+ # ── Helpers ───────────────────────────────────────────
766
+
767
+ @staticmethod
768
+ def _row_to_entry(row: dict[str, Any]) -> ConfigEntry:
769
+ return ConfigEntry(
770
+ key=row["key"],
771
+ value=row["value"],
772
+ category=ConfigCategory(row["category"]),
773
+ display_name=row.get("display_name") or "",
774
+ description=row.get("description") or "",
775
+ is_secret=bool(row.get("is_secret")),
776
+ )