harborrag-runtime 2.0.0__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 (271) hide show
  1. harborrag_runtime/__init__.py +22 -0
  2. harborrag_runtime/application/README.md +39 -0
  3. harborrag_runtime/application/__init__.py +39 -0
  4. harborrag_runtime/application/chat/__init__.py +7 -0
  5. harborrag_runtime/application/chat/citations.py +149 -0
  6. harborrag_runtime/application/chat/client.py +201 -0
  7. harborrag_runtime/application/chat/completion.py +92 -0
  8. harborrag_runtime/application/chat/completion_request.py +130 -0
  9. harborrag_runtime/application/chat/evidence.py +202 -0
  10. harborrag_runtime/application/chat/options.py +43 -0
  11. harborrag_runtime/application/chat/preparation.py +135 -0
  12. harborrag_runtime/application/chat/presenters.py +130 -0
  13. harborrag_runtime/application/chat/prompting.py +127 -0
  14. harborrag_runtime/application/chat/query_scope.py +146 -0
  15. harborrag_runtime/application/chat/replay.py +141 -0
  16. harborrag_runtime/application/chat/request_filters.py +134 -0
  17. harborrag_runtime/application/chat/retrieval.py +127 -0
  18. harborrag_runtime/application/chat/service.py +371 -0
  19. harborrag_runtime/application/composition/__init__.py +1 -0
  20. harborrag_runtime/application/composition/factories.py +106 -0
  21. harborrag_runtime/application/composition/resources.py +141 -0
  22. harborrag_runtime/application/composition/selection.py +65 -0
  23. harborrag_runtime/application/composition/service.py +550 -0
  24. harborrag_runtime/application/composition/tenant_models.py +45 -0
  25. harborrag_runtime/application/control_plane/__init__.py +1 -0
  26. harborrag_runtime/application/control_plane/active_runs.py +38 -0
  27. harborrag_runtime/application/control_plane/connection_models.py +109 -0
  28. harborrag_runtime/application/control_plane/connection_testing.py +91 -0
  29. harborrag_runtime/application/control_plane/connection_writes.py +227 -0
  30. harborrag_runtime/application/control_plane/connections.py +749 -0
  31. harborrag_runtime/application/control_plane/effect_recovery.py +235 -0
  32. harborrag_runtime/application/control_plane/projects.py +313 -0
  33. harborrag_runtime/application/control_plane/settings_import.py +239 -0
  34. harborrag_runtime/application/control_plane/settings_service.py +233 -0
  35. harborrag_runtime/application/control_plane/tenants.py +55 -0
  36. harborrag_runtime/application/errors.py +110 -0
  37. harborrag_runtime/application/ingestion/__init__.py +1 -0
  38. harborrag_runtime/application/ingestion/client.py +65 -0
  39. harborrag_runtime/application/ingestion/connection_sources.py +96 -0
  40. harborrag_runtime/application/ingestion/direct.py +120 -0
  41. harborrag_runtime/application/ingestion/follower.py +83 -0
  42. harborrag_runtime/application/ingestion/ports.py +174 -0
  43. harborrag_runtime/application/ingestion/progress_bridge.py +221 -0
  44. harborrag_runtime/application/ingestion/retry_selection.py +71 -0
  45. harborrag_runtime/application/ingestion/service.py +564 -0
  46. harborrag_runtime/application/ingestion/starter.py +78 -0
  47. harborrag_runtime/application/memory/__init__.py +21 -0
  48. harborrag_runtime/application/memory/client.py +114 -0
  49. harborrag_runtime/application/memory/composition.py +90 -0
  50. harborrag_runtime/application/memory/context.py +45 -0
  51. harborrag_runtime/application/memory/sessions.py +117 -0
  52. harborrag_runtime/application/ports.py +133 -0
  53. harborrag_runtime/application/retrieval/__init__.py +1 -0
  54. harborrag_runtime/application/retrieval/access.py +26 -0
  55. harborrag_runtime/application/scheduling/service.py +58 -0
  56. harborrag_runtime/application/schemas.py +15 -0
  57. harborrag_runtime/chat/README.md +40 -0
  58. harborrag_runtime/chat/__init__.py +18 -0
  59. harborrag_runtime/chat/composition.py +53 -0
  60. harborrag_runtime/chat/facade.py +46 -0
  61. harborrag_runtime/chat/service.py +183 -0
  62. harborrag_runtime/chat/tenant_clients.py +341 -0
  63. harborrag_runtime/chat/tenant_config.py +235 -0
  64. harborrag_runtime/chat/tenant_models.py +22 -0
  65. harborrag_runtime/composition/__init__.py +5 -0
  66. harborrag_runtime/composition/config_store.py +53 -0
  67. harborrag_runtime/composition/connection_removal.py +120 -0
  68. harborrag_runtime/composition/connection_stores.py +107 -0
  69. harborrag_runtime/composition/control_plane.py +401 -0
  70. harborrag_runtime/composition/mcp_auth.py +39 -0
  71. harborrag_runtime/composition/readers.py +113 -0
  72. harborrag_runtime/composition/resources.py +336 -0
  73. harborrag_runtime/composition/storage_providers.py +113 -0
  74. harborrag_runtime/config/__init__.py +84 -0
  75. harborrag_runtime/config/checkout.py +212 -0
  76. harborrag_runtime/config/chunking.py +167 -0
  77. harborrag_runtime/config/connectors/__init__.py +19 -0
  78. harborrag_runtime/config/connectors/fingerprints.py +54 -0
  79. harborrag_runtime/config/connectors/importing.py +611 -0
  80. harborrag_runtime/config/connectors/loader.py +95 -0
  81. harborrag_runtime/config/connectors/models/__init__.py +30 -0
  82. harborrag_runtime/config/connectors/models/atlassian.py +199 -0
  83. harborrag_runtime/config/connectors/models/builder.py +208 -0
  84. harborrag_runtime/config/connectors/models/common.py +45 -0
  85. harborrag_runtime/config/connectors/models/fields.py +134 -0
  86. harborrag_runtime/config/connectors/models/github.py +143 -0
  87. harborrag_runtime/config/connectors/models/local_file.py +119 -0
  88. harborrag_runtime/config/connectors/models/registry.py +149 -0
  89. harborrag_runtime/config/connectors/models/sharepoint.py +186 -0
  90. harborrag_runtime/config/connectors/models/spec.py +563 -0
  91. harborrag_runtime/config/connectors/parsing.py +275 -0
  92. harborrag_runtime/config/connectors/providers.py +177 -0
  93. harborrag_runtime/config/connectors/schemas.py +215 -0
  94. harborrag_runtime/config/errors.py +26 -0
  95. harborrag_runtime/config/graph_build.py +335 -0
  96. harborrag_runtime/config/graph_build_loading.py +38 -0
  97. harborrag_runtime/config/loading.py +245 -0
  98. harborrag_runtime/config/models.py +95 -0
  99. harborrag_runtime/config/ontology_loading.py +76 -0
  100. harborrag_runtime/config/parsers/__init__.py +19 -0
  101. harborrag_runtime/config/parsers/loader.py +85 -0
  102. harborrag_runtime/config/parsers/parsing.py +285 -0
  103. harborrag_runtime/config/parsers/providers.py +305 -0
  104. harborrag_runtime/config/parsers/schemas.py +614 -0
  105. harborrag_runtime/config/settings.py +378 -0
  106. harborrag_runtime/config/settings_document.py +133 -0
  107. harborrag_runtime/config/temporal.py +331 -0
  108. harborrag_runtime/config/temporal_loading.py +310 -0
  109. harborrag_runtime/config_store/__init__.py +5 -0
  110. harborrag_runtime/config_store/defaults.py +47 -0
  111. harborrag_runtime/config_store/provider.py +153 -0
  112. harborrag_runtime/config_store/run_settings.py +72 -0
  113. harborrag_runtime/connections/__init__.py +27 -0
  114. harborrag_runtime/connections/secrets.py +348 -0
  115. harborrag_runtime/contracts.py +237 -0
  116. harborrag_runtime/document_stage_catalog.py +82 -0
  117. harborrag_runtime/errors.py +64 -0
  118. harborrag_runtime/events/__init__.py +3 -0
  119. harborrag_runtime/events/in_process.py +100 -0
  120. harborrag_runtime/execution/__init__.py +26 -0
  121. harborrag_runtime/execution/contracts.py +32 -0
  122. harborrag_runtime/execution/direct.py +169 -0
  123. harborrag_runtime/execution/gateway.py +97 -0
  124. harborrag_runtime/execution/source_conversion.py +61 -0
  125. harborrag_runtime/execution/source_submission.py +278 -0
  126. harborrag_runtime/execution/submission.py +64 -0
  127. harborrag_runtime/execution/task_registry.py +387 -0
  128. harborrag_runtime/execution/temporal.py +165 -0
  129. harborrag_runtime/ingestion/README.md +79 -0
  130. harborrag_runtime/ingestion/__init__.py +59 -0
  131. harborrag_runtime/ingestion/chunking_profile.py +97 -0
  132. harborrag_runtime/ingestion/composition.py +279 -0
  133. harborrag_runtime/ingestion/connection_checks.py +239 -0
  134. harborrag_runtime/ingestion/connections.py +507 -0
  135. harborrag_runtime/ingestion/document/__init__.py +1 -0
  136. harborrag_runtime/ingestion/document/normalization.py +14 -0
  137. harborrag_runtime/ingestion/document/normalizers/__init__.py +9 -0
  138. harborrag_runtime/ingestion/document/normalizers/builtins.py +39 -0
  139. harborrag_runtime/ingestion/document/normalizers/transform.py +30 -0
  140. harborrag_runtime/ingestion/document/run_tools.py +152 -0
  141. harborrag_runtime/ingestion/failure_classification.py +82 -0
  142. harborrag_runtime/ingestion/field_indexes.py +56 -0
  143. harborrag_runtime/ingestion/maintenance/__init__.py +1 -0
  144. harborrag_runtime/ingestion/maintenance/connection_removal.py +115 -0
  145. harborrag_runtime/ingestion/maintenance/projection_admin.py +180 -0
  146. harborrag_runtime/ingestion/maintenance/relation_repair.py +555 -0
  147. harborrag_runtime/ingestion/maintenance/retention.py +353 -0
  148. harborrag_runtime/ingestion/observability.py +3 -0
  149. harborrag_runtime/ingestion/profiles.py +127 -0
  150. harborrag_runtime/ingestion/runtime_builder.py +339 -0
  151. harborrag_runtime/ingestion/source/__init__.py +1 -0
  152. harborrag_runtime/ingestion/source/descriptor_mapping.py +144 -0
  153. harborrag_runtime/ingestion/source/discovery.py +290 -0
  154. harborrag_runtime/ingestion/source/documents.py +184 -0
  155. harborrag_runtime/ingestion/source/finalization.py +288 -0
  156. harborrag_runtime/ingestion/source/operations.py +175 -0
  157. harborrag_runtime/ingestion/source/plan.py +413 -0
  158. harborrag_runtime/ingestion/source/retry.py +150 -0
  159. harborrag_runtime/ingestion/source/service.py +470 -0
  160. harborrag_runtime/ingestion/source/skips.py +172 -0
  161. harborrag_runtime/ingestion_contracts.py +107 -0
  162. harborrag_runtime/memory/__init__.py +81 -0
  163. harborrag_runtime/memory/access.py +47 -0
  164. harborrag_runtime/memory/administration.py +460 -0
  165. harborrag_runtime/memory/context/__init__.py +5 -0
  166. harborrag_runtime/memory/context/result.py +20 -0
  167. harborrag_runtime/memory/directory.py +166 -0
  168. harborrag_runtime/memory/erasure.py +122 -0
  169. harborrag_runtime/memory/locks.py +170 -0
  170. harborrag_runtime/memory/messages.py +202 -0
  171. harborrag_runtime/memory/presenters.py +117 -0
  172. harborrag_runtime/memory/projects.py +38 -0
  173. harborrag_runtime/memory/tiers/__init__.py +1 -0
  174. harborrag_runtime/memory/tiers/in_memory.py +491 -0
  175. harborrag_runtime/memory/titles.py +32 -0
  176. harborrag_runtime/memory/usage.py +131 -0
  177. harborrag_runtime/observability/__init__.py +1 -0
  178. harborrag_runtime/observability/connector_metrics.py +14 -0
  179. harborrag_runtime/observability/discovery_metrics.py +46 -0
  180. harborrag_runtime/observability/model.py +410 -0
  181. harborrag_runtime/observability/observability_types.py +47 -0
  182. harborrag_runtime/observability/stage_observation.py +96 -0
  183. harborrag_runtime/observability/tool_audit.py +17 -0
  184. harborrag_runtime/plugins.py +56 -0
  185. harborrag_runtime/rate_limiting.py +39 -0
  186. harborrag_runtime/reader_contracts.py +149 -0
  187. harborrag_runtime/retrieval/__init__.py +1 -0
  188. harborrag_runtime/retrieval/composition.py +174 -0
  189. harborrag_runtime/retrieval/facades.py +224 -0
  190. harborrag_runtime/scheduling/__init__.py +48 -0
  191. harborrag_runtime/scheduling/config.py +185 -0
  192. harborrag_runtime/scheduling/errors.py +37 -0
  193. harborrag_runtime/scheduling/models.py +146 -0
  194. harborrag_runtime/scheduling/service.py +297 -0
  195. harborrag_runtime/scheduling/validation.py +213 -0
  196. harborrag_runtime/sdk/__init__.py +86 -0
  197. harborrag_runtime/sdk/configuration.py +44 -0
  198. harborrag_runtime/sdk/facades.py +47 -0
  199. harborrag_runtime/sdk/runtime.py +242 -0
  200. harborrag_runtime/security/__init__.py +1 -0
  201. harborrag_runtime/security/api_key_operations.py +236 -0
  202. harborrag_runtime/serialization.py +35 -0
  203. harborrag_runtime/temporal/__init__.py +19 -0
  204. harborrag_runtime/temporal/activity_observability.py +313 -0
  205. harborrag_runtime/temporal/client.py +580 -0
  206. harborrag_runtime/temporal/connection.py +39 -0
  207. harborrag_runtime/temporal/conversion.py +147 -0
  208. harborrag_runtime/temporal/dispatch.py +38 -0
  209. harborrag_runtime/temporal/document_workflow.py +154 -0
  210. harborrag_runtime/temporal/failure_handling.py +68 -0
  211. harborrag_runtime/temporal/gateway.py +121 -0
  212. harborrag_runtime/temporal/heartbeats.py +67 -0
  213. harborrag_runtime/temporal/identity.py +14 -0
  214. harborrag_runtime/temporal/ingestion_activities.py +435 -0
  215. harborrag_runtime/temporal/maintenance_activities.py +251 -0
  216. harborrag_runtime/temporal/maintenance_schemas.py +88 -0
  217. harborrag_runtime/temporal/optional.py +19 -0
  218. harborrag_runtime/temporal/plan_resolver.py +149 -0
  219. harborrag_runtime/temporal/policies.py +18 -0
  220. harborrag_runtime/temporal/reindex_workflow.py +71 -0
  221. harborrag_runtime/temporal/retry_activities.py +147 -0
  222. harborrag_runtime/temporal/retry_workflow.py +222 -0
  223. harborrag_runtime/temporal/sandbox.py +51 -0
  224. harborrag_runtime/temporal/schedules.py +341 -0
  225. harborrag_runtime/temporal/schemas.py +482 -0
  226. harborrag_runtime/temporal/source_activities.py +590 -0
  227. harborrag_runtime/temporal/source_batch_workflow.py +226 -0
  228. harborrag_runtime/temporal/source_workflow.py +908 -0
  229. harborrag_runtime/temporal/submission.py +23 -0
  230. harborrag_runtime/temporal/worker.py +478 -0
  231. harborrag_runtime/temporal/worker_registry.py +141 -0
  232. harborrag_runtime/temporal_models.py +227 -0
  233. harborrag_runtime/testing/chat_fakes.py +309 -0
  234. harborrag_runtime/testing/chat_service_double.py +126 -0
  235. harborrag_runtime/testing/connection_fakes.py +278 -0
  236. harborrag_runtime/testing/memory_fakes.py +128 -0
  237. harborrag_runtime/topology/__init__.py +1 -0
  238. harborrag_runtime/topology/budgeted_extractor.py +110 -0
  239. harborrag_runtime/topology/chunk_runner.py +41 -0
  240. harborrag_runtime/topology/composition.py +168 -0
  241. harborrag_runtime/topology/configuration.py +126 -0
  242. harborrag_runtime/topology/contextual.py +140 -0
  243. harborrag_runtime/topology/derived.py +238 -0
  244. harborrag_runtime/topology/derived_coverage.py +5 -0
  245. harborrag_runtime/topology/derived_dispatch.py +63 -0
  246. harborrag_runtime/topology/derived_factory.py +175 -0
  247. harborrag_runtime/topology/derived_models.py +251 -0
  248. harborrag_runtime/topology/derived_projection.py +127 -0
  249. harborrag_runtime/topology/description_factory.py +81 -0
  250. harborrag_runtime/topology/embedding_profile.py +85 -0
  251. harborrag_runtime/topology/entity_summary_index.py +304 -0
  252. harborrag_runtime/topology/maintenance.py +126 -0
  253. harborrag_runtime/topology/operations.py +277 -0
  254. harborrag_runtime/topology/parent_materializer.py +167 -0
  255. harborrag_runtime/topology/run_cost.py +43 -0
  256. harborrag_runtime/topology/security_operations.py +46 -0
  257. harborrag_runtime/topology/service.py +349 -0
  258. harborrag_runtime/topology/summary_factory.py +164 -0
  259. harborrag_runtime/topology/summary_inputs.py +129 -0
  260. harborrag_runtime/topology/summary_operations.py +128 -0
  261. harborrag_runtime/topology/summary_policy.py +39 -0
  262. harborrag_runtime/topology/summary_products.py +43 -0
  263. harborrag_runtime/topology/summary_service.py +625 -0
  264. harborrag_runtime/topology/summary_worker.py +129 -0
  265. harborrag_runtime/topology/summary_workflow.py +32 -0
  266. harborrag_runtime/topology/worker.py +101 -0
  267. harborrag_runtime/topology/workflow.py +32 -0
  268. harborrag_runtime-2.0.0.dist-info/METADATA +267 -0
  269. harborrag_runtime-2.0.0.dist-info/RECORD +271 -0
  270. harborrag_runtime-2.0.0.dist-info/WHEEL +4 -0
  271. harborrag_runtime-2.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,242 @@
1
+ """Stable async SDK façade for HarborRAG runtime services."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import AsyncIterator, Awaitable, Callable
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, cast
9
+
10
+ from harborrag_core.ingestion import ExecutionCapabilityError
11
+ from harborrag_core.invariants import HarborInvariantError
12
+ from harborrag_core.models.chat import HarborChatRequest, HarborChatResponse, HarborChatStreamChunk
13
+ from harborrag_engine.retrieval import RetrievalLane as RetrievalLane
14
+
15
+ from ..chat import ChatFacade, ChatPrompt, RuntimeChatService, TenantModelSources
16
+ from ..contracts import (
17
+ ExecutionMode,
18
+ IngestionRequest,
19
+ IngestionResult,
20
+ IngestionStatus,
21
+ IngestionTaskReference,
22
+ )
23
+ from ..contracts import (
24
+ GraphPathRequest as GraphPathRequest,
25
+ )
26
+ from ..contracts import (
27
+ GraphPathResponse as GraphPathResponse,
28
+ )
29
+ from ..contracts import (
30
+ GraphSubgraphRequest as GraphSubgraphRequest,
31
+ )
32
+ from ..contracts import (
33
+ GraphSubgraphResponse as GraphSubgraphResponse,
34
+ )
35
+ from ..contracts import (
36
+ GraphTripletRequest as GraphTripletRequest,
37
+ )
38
+ from ..contracts import (
39
+ GraphTripletResponse as GraphTripletResponse,
40
+ )
41
+ from ..contracts import (
42
+ RetrievalRequest as RetrievalRequest,
43
+ )
44
+ from ..contracts import (
45
+ RetrievalResponse as RetrievalResponse,
46
+ )
47
+ from ..execution import IngestionExecutor, build_ingestion_executor
48
+ from ..execution.contracts import DurableIngestionExecutor
49
+ from .configuration import HarborRAGConfig
50
+ from .facades import GraphFacade, IngestionFacade, KnowledgeFacade, RetrievalFacade
51
+
52
+ if TYPE_CHECKING:
53
+ from harborrag_engine.retrieval.service.service import RuntimeRetrievalService
54
+
55
+ from ..config.settings import RuntimeSettings
56
+
57
+ type ExecutorFactory = Callable[[ExecutionMode, "RuntimeSettings"], IngestionExecutor]
58
+ type RetrievalFactory = Callable[["RuntimeSettings"], Awaitable["RuntimeRetrievalService"]]
59
+ type ChatRuntimeFactory = Callable[["RuntimeSettings"], RuntimeChatService]
60
+
61
+
62
+ async def _connect_retrieval(settings: RuntimeSettings) -> RuntimeRetrievalService:
63
+ from ..retrieval.composition import connect_retrieval_service
64
+
65
+ return await connect_retrieval_service(settings)
66
+
67
+
68
+ class HarborRAG:
69
+ """Coordinate execution and retrieval behind narrow service façades."""
70
+
71
+ def __init__(
72
+ self,
73
+ config: HarborRAGConfig,
74
+ *,
75
+ executor_factory: ExecutorFactory = build_ingestion_executor,
76
+ retrieval_factory: RetrievalFactory = _connect_retrieval,
77
+ chat_runtime_factory: ChatRuntimeFactory = RuntimeChatService,
78
+ ) -> None:
79
+ self.config = config
80
+ self.chat = ChatFacade(self)
81
+ self.ingestion = IngestionFacade(self)
82
+ self.retrieval = RetrievalFacade(self)
83
+ self.graph = GraphFacade(self)
84
+ self.knowledge = KnowledgeFacade(self)
85
+ self._executor: IngestionExecutor | None = None
86
+ self._executor_started = False
87
+ self._plugins_discovered = False
88
+ self._lifecycle_lock = asyncio.Lock()
89
+ self._retrieval: RuntimeRetrievalService | None = None
90
+ self._executor_factory = executor_factory
91
+ self._retrieval_factory = retrieval_factory
92
+ self._chat_runtime_factory = chat_runtime_factory
93
+ self._chat_runtime: RuntimeChatService | None = None
94
+ self._retrieval_lock = asyncio.Lock()
95
+
96
+ @classmethod
97
+ def from_config(cls, path: str | Path) -> HarborRAG:
98
+ return cls(HarborRAGConfig.from_file(path))
99
+
100
+ async def __aenter__(self) -> HarborRAG:
101
+ await self.start()
102
+ return self
103
+
104
+ async def __aexit__(self, *exc: object) -> None:
105
+ del exc
106
+ await self.aclose()
107
+
108
+ async def start(self) -> None:
109
+ async with self._lifecycle_lock:
110
+ if self._executor_started:
111
+ return
112
+ # Retain ownership when a previous startup's cleanup failed, and
113
+ # finish that cleanup before constructing a replacement.
114
+ await self._close_executor()
115
+ self._discover_plugins()
116
+ self._executor = self._executor_factory(
117
+ self.config.execution_mode,
118
+ self.config.runtime,
119
+ )
120
+ try:
121
+ await self._executor.start()
122
+ except BaseException as startup_error:
123
+ try:
124
+ await self._close_executor()
125
+ except BaseException as cleanup_error:
126
+ raise BaseExceptionGroup(
127
+ "HarborRAG startup and cleanup failed",
128
+ [startup_error, cleanup_error],
129
+ ) from None
130
+ raise
131
+ self._executor_started = True
132
+
133
+ async def _ingestion_run(self, request: IngestionRequest) -> IngestionResult:
134
+ await self.start()
135
+ if self._executor is None:
136
+ raise HarborInvariantError("self._executor must not be None here")
137
+ return await self._executor.run(request)
138
+
139
+ async def _ingestion_submit(self, request: IngestionRequest) -> IngestionTaskReference:
140
+ executor = await self._durable_executor(
141
+ "direct execution supports ingestion.run(), not submit()"
142
+ )
143
+ return await executor.submit(request)
144
+
145
+ async def _ingestion_status(self, task_id: str) -> IngestionStatus:
146
+ executor = await self._durable_executor("direct execution has no durable task status")
147
+ return await executor.status(task_id)
148
+
149
+ async def _ingestion_control(self, task_id: str, operation: str) -> None:
150
+ executor = await self._durable_executor(
151
+ f"direct execution cannot {operation} a durable task"
152
+ )
153
+ controls = {
154
+ "pause": executor.pause,
155
+ "resume": executor.resume,
156
+ "cancel": executor.cancel,
157
+ }
158
+ await controls[operation](task_id)
159
+
160
+ async def _durable_executor(
161
+ self,
162
+ capability_error: str,
163
+ ) -> DurableIngestionExecutor:
164
+ await self.start()
165
+ if self.config.execution_mode is not ExecutionMode.TEMPORAL:
166
+ raise ExecutionCapabilityError(capability_error)
167
+ if self._executor is None:
168
+ raise HarborInvariantError("self._executor must not be None here")
169
+ return cast("DurableIngestionExecutor", self._executor)
170
+
171
+ async def _retrieval_service(self) -> RuntimeRetrievalService:
172
+ async with self._retrieval_lock:
173
+ if self._retrieval is None:
174
+ self._discover_plugins()
175
+ self._retrieval = await self._retrieval_factory(self.config.runtime)
176
+ return self._retrieval
177
+
178
+ def _discover_plugins(self) -> None:
179
+ if self.config.discover_plugins and not self._plugins_discovered:
180
+ from ..plugins import discover_runtime_plugins
181
+
182
+ discover_runtime_plugins()
183
+ self._plugins_discovered = True
184
+
185
+ def configure_tenant_models(self, sources: TenantModelSources) -> None:
186
+ """Let chat resolve each tenant's own models, once, at composition.
187
+
188
+ Optional by construction: the SDK is built from settings alone, so a
189
+ deployment that wires no control plane -- or has per-tenant catalogs
190
+ switched off -- never calls this and keeps the single process-wide
191
+ chat client it has always had.
192
+ """
193
+
194
+ self._chat_service().configure_tenant_models(sources)
195
+
196
+ async def _chat_validate_model(self, model: str | None, *, tenant_id: str | None) -> None:
197
+ await self._chat_service().validate_model(model, tenant_id=tenant_id)
198
+
199
+ async def _chat_complete(
200
+ self,
201
+ request: HarborChatRequest,
202
+ *,
203
+ prompt: ChatPrompt | None = None,
204
+ ) -> HarborChatResponse:
205
+ return await self._chat_service().complete(request, prompt=prompt)
206
+
207
+ def _chat_stream(
208
+ self,
209
+ request: HarborChatRequest,
210
+ *,
211
+ prompt: ChatPrompt | None = None,
212
+ ) -> AsyncIterator[HarborChatStreamChunk]:
213
+ return self._chat_service().stream(request, prompt=prompt)
214
+
215
+ def _chat_service(self) -> RuntimeChatService:
216
+ if self._chat_runtime is None:
217
+ self._chat_runtime = self._chat_runtime_factory(self.config.runtime)
218
+ return self._chat_runtime
219
+
220
+ async def aclose(self) -> None:
221
+ async with self._lifecycle_lock:
222
+ results = await asyncio.gather(
223
+ *([self._chat_runtime.aclose()] if self._chat_runtime is not None else []),
224
+ self._close_retrieval(),
225
+ self._close_executor(),
226
+ return_exceptions=True,
227
+ )
228
+ failures = [result for result in results if isinstance(result, BaseException)]
229
+ if failures:
230
+ raise BaseExceptionGroup("HarborRAG resource close failed", failures)
231
+
232
+ async def _close_retrieval(self) -> None:
233
+ async with self._retrieval_lock:
234
+ if self._retrieval is not None:
235
+ await self._retrieval.aclose()
236
+ self._retrieval = None
237
+
238
+ async def _close_executor(self) -> None:
239
+ self._executor_started = False
240
+ if self._executor is not None:
241
+ await self._executor.aclose()
242
+ self._executor = None
@@ -0,0 +1 @@
1
+ """Operator-side security operations wired to the runtime's settings."""
@@ -0,0 +1,236 @@
1
+ """Operator entry points for MCP reader keys, one coroutine per CLI command.
2
+
3
+ Each call opens the control-plane database with the operator's own credentials,
4
+ runs one management operation and closes the engine again. Nothing here prints
5
+ or logs a raw key: ``create_key`` returns it once inside ``CreatedKey`` and the
6
+ CLI is responsible for delivering it to a file.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import UTC, datetime, timedelta
12
+ from typing import TYPE_CHECKING, Any, Literal
13
+
14
+ from harborrag_engine.security import ApiKeyManagementService, CreatedKey
15
+
16
+ KEY_TABLE = "mcp_api_keys"
17
+
18
+
19
+ class ApiKeySchemaMissing(RuntimeError):
20
+ """The control database has not been migrated to the key table yet."""
21
+
22
+ def __init__(self, target: str | None = None) -> None:
23
+ where = f" in {target}" if target else ""
24
+ super().__init__(
25
+ f"the {KEY_TABLE} table does not exist{where}: start the API once (it applies "
26
+ "the control-plane migrations) or re-run with --migrate"
27
+ )
28
+
29
+
30
+ class ApiKeySchemaBehind(RuntimeError):
31
+ """The control database exists but is stamped older than the packaged head."""
32
+
33
+ def __init__(self, target: str | None, current: str | None, head: str) -> None:
34
+ where = f" in {target}" if target else ""
35
+ super().__init__(
36
+ f"the control database{where} is at migration {current or 'none'} but this "
37
+ f"release expects {head}: start the API once (it applies the control-plane "
38
+ "migrations) or re-run with --migrate"
39
+ )
40
+
41
+
42
+ class ApiKeySchemaUnstamped(RuntimeError):
43
+ """The key table exists but alembic never stamped the database, so it cannot migrate."""
44
+
45
+ def __init__(self, target: str | None = None) -> None:
46
+ where = f" in {target}" if target else ""
47
+ super().__init__(
48
+ f"the {KEY_TABLE} table exists{where} but the database has no migration stamp: "
49
+ "stamp it with alembic at the revision its schema matches, then re-run with "
50
+ "--migrate"
51
+ )
52
+
53
+
54
+ class ApiKeyRejected(RuntimeError):
55
+ """The database refused a key row; the SQL error is dropped, it carries bound values."""
56
+
57
+ def __init__(self) -> None:
58
+ super().__init__(
59
+ "the database rejected the key row, which usually means its schema is older than "
60
+ "this release: re-run with --migrate or start the API once to apply migrations"
61
+ )
62
+
63
+
64
+ def describe_target(dsn: str) -> str:
65
+ """``scheme://host:port/database`` with credentials dropped, for messages."""
66
+
67
+ from urllib.parse import urlsplit
68
+
69
+ parts = urlsplit(dsn)
70
+ host = parts.hostname or ""
71
+ port = f":{parts.port}" if parts.port else ""
72
+ return f"{parts.scheme}://{host}{port}{parts.path}"
73
+
74
+
75
+ if TYPE_CHECKING:
76
+ from harborrag_core.ports.api_keys import ApiKeyRecord
77
+ from harborrag_runtime.config.settings import RuntimeSettings
78
+
79
+
80
+ def key_state(record: ApiKeyRecord, *, now: datetime | None = None) -> str:
81
+ """``active``, ``expired`` or ``revoked``; never stored, always derived."""
82
+
83
+ if record.revoked_at is not None:
84
+ return "revoked"
85
+ if record.expires_at <= (now or datetime.now(UTC)):
86
+ return "expired"
87
+ return "active"
88
+
89
+
90
+ def describe(record: ApiKeyRecord) -> dict[str, Any]:
91
+ """The safe, operator-facing view of one key: no hash, no secret."""
92
+
93
+ return {
94
+ "key_id": record.key_id,
95
+ "tenant_id": record.tenant_id,
96
+ "owner": record.owner,
97
+ "name": record.name,
98
+ "environment": record.environment,
99
+ "state": key_state(record),
100
+ "created_at": record.created_at.isoformat(),
101
+ "created_by": record.created_by,
102
+ "expires_at": record.expires_at.isoformat(),
103
+ "revoked_at": record.revoked_at.isoformat() if record.revoked_at else None,
104
+ "revoked_by": record.revoked_by,
105
+ "revocation_reason": record.revocation_reason,
106
+ }
107
+
108
+
109
+ async def _service(settings: RuntimeSettings) -> tuple[ApiKeyManagementService, Any]:
110
+ from harborrag_adapters.repositories.database.control_plane.engine import (
111
+ create_control_plane_engine,
112
+ create_session_factory,
113
+ )
114
+ from harborrag_adapters.repositories.database.control_plane.mcp_api_keys import (
115
+ SqlApiKeyManager,
116
+ )
117
+
118
+ engine = create_control_plane_engine(settings.control_db_url.get_secret_value())
119
+ manager = SqlApiKeyManager(create_session_factory(engine))
120
+ return ApiKeyManagementService(manager, environment=settings.env), engine
121
+
122
+
123
+ async def ensure_key_schema(
124
+ settings: RuntimeSettings, *, migrate: bool, require_head: bool = True
125
+ ) -> bool:
126
+ """Check the control database; with ``migrate`` apply pending migrations instead.
127
+
128
+ Returns True when migrations were applied (the database was behind head).
129
+ With ``migrate``, a key table in a database alembic never stamped raises
130
+ ``ApiKeySchemaUnstamped``: there is no revision to upgrade from.
131
+ Without ``migrate`` nothing is ever changed: a missing key table raises
132
+ ``ApiKeySchemaMissing`` and, when ``require_head``, a database stamped older
133
+ than head raises ``ApiKeySchemaBehind``. ``list`` and ``revoke`` pass
134
+ ``require_head=False``: they only read and update columns every release since
135
+ the key table shipped has, so a database that is merely behind keeps working
136
+ for them, while ``create`` (which writes the newest constraints) insists on head.
137
+ Migrations are the API's job in normal operation; ``--migrate`` is the
138
+ operator's shortcut, run with the same owner credentials the API would use.
139
+ """
140
+
141
+ from sqlalchemy import inspect
142
+
143
+ from harborrag_adapters.repositories.database.control_plane.engine import (
144
+ create_control_plane_engine,
145
+ )
146
+ from harborrag_adapters.repositories.database.control_plane.migrations import (
147
+ current_revision,
148
+ head_revision,
149
+ run_migrations,
150
+ )
151
+
152
+ dsn = settings.control_db_url.get_secret_value()
153
+ head = head_revision(dsn)
154
+ engine = create_control_plane_engine(dsn)
155
+ try:
156
+ async with engine.connect() as connection:
157
+ present = await connection.run_sync(lambda sync: inspect(sync).has_table(KEY_TABLE))
158
+ current = await connection.run_sync(current_revision)
159
+ finally:
160
+ await engine.dispose()
161
+ behind = current != head
162
+ if migrate:
163
+ if present and current is None:
164
+ # Upgrading from "no revision" would re-create the existing table and fail
165
+ # with a raw driver error; name the actual problem instead.
166
+ raise ApiKeySchemaUnstamped(describe_target(dsn))
167
+ if behind:
168
+ run_migrations(dsn)
169
+ return behind
170
+ if not present:
171
+ raise ApiKeySchemaMissing(describe_target(dsn))
172
+ if behind and require_head:
173
+ raise ApiKeySchemaBehind(describe_target(dsn), current, head)
174
+ return False
175
+
176
+
177
+ async def create_key( # noqa: PLR0913 - one argument per CLI option
178
+ settings: RuntimeSettings,
179
+ *,
180
+ operator: str,
181
+ tenant_id: str,
182
+ owner: str,
183
+ name: str,
184
+ lifetime: timedelta,
185
+ ) -> CreatedKey:
186
+ from sqlalchemy.exc import IntegrityError
187
+
188
+ service, engine = await _service(settings)
189
+ try:
190
+ return await service.create_key(
191
+ operator=operator, tenant_id=tenant_id, owner=owner, name=name, lifetime=lifetime
192
+ )
193
+ except IntegrityError:
194
+ raise ApiKeyRejected from None
195
+ finally:
196
+ await engine.dispose()
197
+
198
+
199
+ async def list_keys(settings: RuntimeSettings, tenant_id: str) -> list[dict[str, Any]]:
200
+ service, engine = await _service(settings)
201
+ try:
202
+ return [describe(record) for record in await service.list_keys(tenant_id)]
203
+ finally:
204
+ await engine.dispose()
205
+
206
+
207
+ async def revoke_key(
208
+ settings: RuntimeSettings, *, operator: str, key_id: str, reason: str
209
+ ) -> Literal["revoked", "already_revoked", "not_found"]:
210
+ from harborrag_adapters.repositories.database.control_plane.engine import (
211
+ create_session_factory,
212
+ )
213
+ from harborrag_adapters.repositories.database.control_plane.mcp_api_keys import (
214
+ SqlApiKeyReader,
215
+ )
216
+
217
+ service, engine = await _service(settings)
218
+ try:
219
+ if await service.revoke_key(operator=operator, key_id=key_id, reason=reason):
220
+ return "revoked"
221
+ known = await SqlApiKeyReader(create_session_factory(engine)).get_by_key_id(key_id)
222
+ return "not_found" if known is None else "already_revoked"
223
+ finally:
224
+ await engine.dispose()
225
+
226
+
227
+ async def revoke_owner(
228
+ settings: RuntimeSettings, *, operator: str, tenant_id: str, owner: str, reason: str
229
+ ) -> list[str]:
230
+ service, engine = await _service(settings)
231
+ try:
232
+ return await service.revoke_owner(
233
+ operator=operator, tenant_id=tenant_id, owner=owner, reason=reason
234
+ )
235
+ finally:
236
+ await engine.dispose()
@@ -0,0 +1,35 @@
1
+ """Deterministic conversion of runtime values into JSON-compatible data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping, Sequence
7
+ from datetime import date, datetime
8
+ from enum import Enum
9
+ from pathlib import Path
10
+
11
+ type JsonValue = None | bool | int | float | str | list[JsonValue] | dict[str, JsonValue]
12
+
13
+
14
+ def to_json_value(value: object) -> JsonValue:
15
+ """Convert supported configuration and source metadata without lossy fallbacks."""
16
+
17
+ if value is None or isinstance(value, (bool, float, int, str)):
18
+ return value
19
+ if isinstance(value, (date, datetime)):
20
+ return value.isoformat()
21
+ if isinstance(value, Path):
22
+ return str(value)
23
+ if isinstance(value, Enum):
24
+ return to_json_value(value.value)
25
+ if isinstance(value, Mapping):
26
+ return {str(key): to_json_value(item) for key, item in value.items()}
27
+ if isinstance(value, (set, frozenset)):
28
+ converted = [to_json_value(item) for item in value]
29
+ return sorted(
30
+ converted,
31
+ key=lambda item: json.dumps(item, ensure_ascii=False, sort_keys=True),
32
+ )
33
+ if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray, str)):
34
+ return [to_json_value(item) for item in value]
35
+ raise TypeError(f"{type(value).__name__} is not JSON serializable")
@@ -0,0 +1,19 @@
1
+ """Temporal contracts for the canonical ingestion pipeline."""
2
+
3
+ from harborrag_runtime.temporal.identity import RuntimeWorkflowRef
4
+ from harborrag_runtime.temporal.maintenance_schemas import (
5
+ ReindexInput,
6
+ ReindexResult,
7
+ )
8
+ from harborrag_runtime.temporal.schemas import (
9
+ SourceIngestionInput,
10
+ SourceIngestionResult,
11
+ )
12
+
13
+ __all__ = [
14
+ "ReindexInput",
15
+ "ReindexResult",
16
+ "RuntimeWorkflowRef",
17
+ "SourceIngestionInput",
18
+ "SourceIngestionResult",
19
+ ]