marmo-core 0.4.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.
- marmo_core/__init__.py +361 -0
- marmo_core/_version.py +3 -0
- marmo_core/activator.py +247 -0
- marmo_core/adaptive.py +542 -0
- marmo_core/agent_runtime.py +206 -0
- marmo_core/audit.py +236 -0
- marmo_core/cli.py +875 -0
- marmo_core/compiler.py +604 -0
- marmo_core/connectors.py +865 -0
- marmo_core/environment.py +45 -0
- marmo_core/errors.py +51 -0
- marmo_core/evaluator.py +262 -0
- marmo_core/formatting.py +136 -0
- marmo_core/graph_routing.py +301 -0
- marmo_core/hierarchy.py +409 -0
- marmo_core/hitl.py +353 -0
- marmo_core/kernel.py +1892 -0
- marmo_core/llm.py +197 -0
- marmo_core/llm_routing.py +386 -0
- marmo_core/loader.py +311 -0
- marmo_core/markdown_skill.py +238 -0
- marmo_core/mcp.py +360 -0
- marmo_core/models.py +463 -0
- marmo_core/package.py +560 -0
- marmo_core/planner.py +512 -0
- marmo_core/policy.py +310 -0
- marmo_core/providers.py +289 -0
- marmo_core/py.typed +1 -0
- marmo_core/recovery.py +331 -0
- marmo_core/registry.py +181 -0
- marmo_core/rerank.py +156 -0
- marmo_core/retriever.py +485 -0
- marmo_core/safety.py +263 -0
- marmo_core/sample_resources/__init__.py +1 -0
- marmo_core/sample_resources/agents.py +255 -0
- marmo_core/sample_resources/tools.py +341 -0
- marmo_core/secrets.py +259 -0
- marmo_core/security.py +124 -0
- marmo_core/selector.py +578 -0
- marmo_core/semantic.py +235 -0
- marmo_core/state.py +658 -0
- marmo_core/tool_runtime.py +255 -0
- marmo_core-0.4.0.dist-info/METADATA +162 -0
- marmo_core-0.4.0.dist-info/RECORD +48 -0
- marmo_core-0.4.0.dist-info/WHEEL +5 -0
- marmo_core-0.4.0.dist-info/entry_points.txt +3 -0
- marmo_core-0.4.0.dist-info/licenses/LICENSE +201 -0
- marmo_core-0.4.0.dist-info/top_level.txt +1 -0
marmo_core/__init__.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""Marmo-Core public API.
|
|
2
|
+
|
|
3
|
+
v1 covers the unified resource model, local resource loading, cross-kind
|
|
4
|
+
retrieval, rule-based set selection, and the CLI surface. On top of that,
|
|
5
|
+
the guarded execution loop (v2 preview) adds the Resource Activator, Tool and
|
|
6
|
+
Agent Runtimes, Context Compiler, mock LLM provider, and synchronous Kernel.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .adaptive import (
|
|
10
|
+
CaseBasedRouter,
|
|
11
|
+
CaseMember,
|
|
12
|
+
RoutingCase,
|
|
13
|
+
RoutingCaseStore,
|
|
14
|
+
RoutingDecision,
|
|
15
|
+
resolve_case,
|
|
16
|
+
)
|
|
17
|
+
from .activator import (
|
|
18
|
+
Activation,
|
|
19
|
+
BoundAgent,
|
|
20
|
+
BoundTool,
|
|
21
|
+
InjectedMemory,
|
|
22
|
+
LoadedSkill,
|
|
23
|
+
ResourceActivator,
|
|
24
|
+
)
|
|
25
|
+
from .agent_runtime import AgentResponse, AgentResult, AgentRuntime
|
|
26
|
+
from .audit import AuditLog, AuditRecord
|
|
27
|
+
from .compiler import AgentInterface, CompiledContext, CompiledSelectionContext, ContextCompiler
|
|
28
|
+
from .connectors import (
|
|
29
|
+
Connector,
|
|
30
|
+
ConnectorCircuitOpenError,
|
|
31
|
+
ConnectorCommandError,
|
|
32
|
+
ConnectorConfig,
|
|
33
|
+
ConnectorError,
|
|
34
|
+
ConnectorPathError,
|
|
35
|
+
ConnectorRuntime,
|
|
36
|
+
ConnectorTool,
|
|
37
|
+
FileSystemConnector,
|
|
38
|
+
HTTPConnector,
|
|
39
|
+
SQLiteConnector,
|
|
40
|
+
ShellConnector,
|
|
41
|
+
connector_implementations,
|
|
42
|
+
connector_resources,
|
|
43
|
+
connector_tools,
|
|
44
|
+
install_connectors,
|
|
45
|
+
)
|
|
46
|
+
from .evaluator import ExecutionEvaluator, ExecutionOutcome, outcomes_from_audit
|
|
47
|
+
from .errors import (
|
|
48
|
+
ActivationError,
|
|
49
|
+
MarmoError,
|
|
50
|
+
PackageCompatibilityError,
|
|
51
|
+
PackageError,
|
|
52
|
+
PackageIntegrityError,
|
|
53
|
+
ResourceLoadError,
|
|
54
|
+
ResourceNotFoundError,
|
|
55
|
+
ResourceValidationError,
|
|
56
|
+
SecretResolutionError,
|
|
57
|
+
ToolInputError,
|
|
58
|
+
)
|
|
59
|
+
from .hitl import (
|
|
60
|
+
AutoApproveHitlBroker,
|
|
61
|
+
CallbackHitlBroker,
|
|
62
|
+
ConsoleHitlBroker,
|
|
63
|
+
HitlBroker,
|
|
64
|
+
HitlError,
|
|
65
|
+
HitlPolicy,
|
|
66
|
+
HitlRequest,
|
|
67
|
+
HitlResponse,
|
|
68
|
+
PendingHitlBroker,
|
|
69
|
+
)
|
|
70
|
+
from .kernel import Kernel, TaskResult
|
|
71
|
+
from .llm import (
|
|
72
|
+
ChatMessage,
|
|
73
|
+
LLMProvider,
|
|
74
|
+
LLMResponse,
|
|
75
|
+
LLMToolSpec,
|
|
76
|
+
MockLLMProvider,
|
|
77
|
+
ToolCall,
|
|
78
|
+
estimate_tokens,
|
|
79
|
+
tokenize,
|
|
80
|
+
)
|
|
81
|
+
from .graph_routing import CapabilityGraphRetriever
|
|
82
|
+
from .hierarchy import (
|
|
83
|
+
EmbeddingClusterGrouping,
|
|
84
|
+
GroupingStrategy,
|
|
85
|
+
HierarchicalRetriever,
|
|
86
|
+
NamespaceGrouping,
|
|
87
|
+
PermissionGrouping,
|
|
88
|
+
ProviderGrouping,
|
|
89
|
+
RouteDecision,
|
|
90
|
+
)
|
|
91
|
+
from .llm_routing import HydeRetriever, LLMRerankRetriever, LLMSetSelector
|
|
92
|
+
from .loader import load_resource_definitions, load_registry
|
|
93
|
+
from .package import (
|
|
94
|
+
KERNEL_VERSION,
|
|
95
|
+
LOCK_FILENAME,
|
|
96
|
+
MANIFEST_FILENAME,
|
|
97
|
+
LocalResourcePackage,
|
|
98
|
+
PackageDependency,
|
|
99
|
+
PackageLock,
|
|
100
|
+
PackageManifest,
|
|
101
|
+
SemanticVersion,
|
|
102
|
+
VersionRange,
|
|
103
|
+
build_package_lock,
|
|
104
|
+
discover_package_roots,
|
|
105
|
+
read_package_manifest,
|
|
106
|
+
verify_local_package,
|
|
107
|
+
write_package_lock,
|
|
108
|
+
)
|
|
109
|
+
from .models import (
|
|
110
|
+
ResourceDefinition,
|
|
111
|
+
ResourceKind,
|
|
112
|
+
ResourceMetadata,
|
|
113
|
+
ResourceStats,
|
|
114
|
+
SearchQuery,
|
|
115
|
+
SearchResult,
|
|
116
|
+
SelectedResourceSet,
|
|
117
|
+
SelectionResult,
|
|
118
|
+
ValidationIssue,
|
|
119
|
+
)
|
|
120
|
+
from .mcp import (
|
|
121
|
+
MCPError,
|
|
122
|
+
MCPStdioClient,
|
|
123
|
+
MCPToolInfo,
|
|
124
|
+
connect_mcp_server,
|
|
125
|
+
mcp_tool_implementations,
|
|
126
|
+
mcp_tool_resources,
|
|
127
|
+
)
|
|
128
|
+
from .planner import (
|
|
129
|
+
LLMPlanner,
|
|
130
|
+
Plan,
|
|
131
|
+
PlanStep,
|
|
132
|
+
Planner,
|
|
133
|
+
RuleBasedPlanner,
|
|
134
|
+
validate_plan,
|
|
135
|
+
)
|
|
136
|
+
from .policy import PolicyContext, PolicyDecision, PolicyGateway, PolicyRejectedError
|
|
137
|
+
from .providers import AnthropicLLMProvider, OpenAICompatibleLLMProvider
|
|
138
|
+
from .recovery import (
|
|
139
|
+
CircuitBreaker,
|
|
140
|
+
Failure,
|
|
141
|
+
RecoveryDecision,
|
|
142
|
+
RecoveryManager,
|
|
143
|
+
RetryPolicy,
|
|
144
|
+
compensation_for,
|
|
145
|
+
)
|
|
146
|
+
from .registry import ResourceRegistry
|
|
147
|
+
from .rerank import CrossEncoderProvider, CrossEncoderRerankRetriever
|
|
148
|
+
from .retriever import LexicalRetriever, Retriever
|
|
149
|
+
from .selector import (
|
|
150
|
+
BranchAndBoundSetSelector,
|
|
151
|
+
GreedyConstrainedSetSelector,
|
|
152
|
+
RuleBasedSetSelector,
|
|
153
|
+
SelectionContext,
|
|
154
|
+
SetSelector,
|
|
155
|
+
BeamSearchSetSelector,
|
|
156
|
+
)
|
|
157
|
+
from .semantic import (
|
|
158
|
+
EmbeddingProvider,
|
|
159
|
+
HashingEmbeddingProvider,
|
|
160
|
+
HybridRetriever,
|
|
161
|
+
OpenAICompatibleEmbeddingProvider,
|
|
162
|
+
)
|
|
163
|
+
from .safety import SafetyFinding, SafetyInspector
|
|
164
|
+
from .security import (
|
|
165
|
+
CORE_ISOLATION_LEVELS,
|
|
166
|
+
ISOLATION_LEVELS,
|
|
167
|
+
PromptInjectionFinding,
|
|
168
|
+
PromptInjectionInspector,
|
|
169
|
+
label_untrusted_content,
|
|
170
|
+
)
|
|
171
|
+
from .secrets import (
|
|
172
|
+
EnvironmentSecretResolver,
|
|
173
|
+
MappingSecretResolver,
|
|
174
|
+
SecretRef,
|
|
175
|
+
SecretResolver,
|
|
176
|
+
)
|
|
177
|
+
from .state import (
|
|
178
|
+
Checkpoint,
|
|
179
|
+
InMemoryStateStore,
|
|
180
|
+
JsonFileStateStore,
|
|
181
|
+
SQLiteStateStore,
|
|
182
|
+
StateConflictError,
|
|
183
|
+
StateEvent,
|
|
184
|
+
StateStore,
|
|
185
|
+
TaskNotFoundError,
|
|
186
|
+
TaskState,
|
|
187
|
+
)
|
|
188
|
+
from .tool_runtime import ToolResult, ToolRuntime, validate_arguments
|
|
189
|
+
|
|
190
|
+
__all__ = [
|
|
191
|
+
"Activation",
|
|
192
|
+
"ActivationError",
|
|
193
|
+
"AgentResponse",
|
|
194
|
+
"AgentResult",
|
|
195
|
+
"AgentRuntime",
|
|
196
|
+
"AgentInterface",
|
|
197
|
+
"AnthropicLLMProvider",
|
|
198
|
+
"AuditLog",
|
|
199
|
+
"AuditRecord",
|
|
200
|
+
"AutoApproveHitlBroker",
|
|
201
|
+
"BeamSearchSetSelector",
|
|
202
|
+
"BoundTool",
|
|
203
|
+
"BoundAgent",
|
|
204
|
+
"BranchAndBoundSetSelector",
|
|
205
|
+
"CallbackHitlBroker",
|
|
206
|
+
"CapabilityGraphRetriever",
|
|
207
|
+
"CaseBasedRouter",
|
|
208
|
+
"CaseMember",
|
|
209
|
+
"ChatMessage",
|
|
210
|
+
"Checkpoint",
|
|
211
|
+
"CircuitBreaker",
|
|
212
|
+
"CompiledContext",
|
|
213
|
+
"CompiledSelectionContext",
|
|
214
|
+
"ConsoleHitlBroker",
|
|
215
|
+
"ContextCompiler",
|
|
216
|
+
"Connector",
|
|
217
|
+
"ConnectorCircuitOpenError",
|
|
218
|
+
"ConnectorCommandError",
|
|
219
|
+
"ConnectorConfig",
|
|
220
|
+
"ConnectorError",
|
|
221
|
+
"ConnectorPathError",
|
|
222
|
+
"ConnectorRuntime",
|
|
223
|
+
"ConnectorTool",
|
|
224
|
+
"CORE_ISOLATION_LEVELS",
|
|
225
|
+
"CrossEncoderProvider",
|
|
226
|
+
"CrossEncoderRerankRetriever",
|
|
227
|
+
"EmbeddingClusterGrouping",
|
|
228
|
+
"EmbeddingProvider",
|
|
229
|
+
"EnvironmentSecretResolver",
|
|
230
|
+
"ExecutionEvaluator",
|
|
231
|
+
"ExecutionOutcome",
|
|
232
|
+
"Failure",
|
|
233
|
+
"FileSystemConnector",
|
|
234
|
+
"GreedyConstrainedSetSelector",
|
|
235
|
+
"GroupingStrategy",
|
|
236
|
+
"HashingEmbeddingProvider",
|
|
237
|
+
"HierarchicalRetriever",
|
|
238
|
+
"HitlBroker",
|
|
239
|
+
"HitlError",
|
|
240
|
+
"HitlPolicy",
|
|
241
|
+
"HitlRequest",
|
|
242
|
+
"HitlResponse",
|
|
243
|
+
"HybridRetriever",
|
|
244
|
+
"HydeRetriever",
|
|
245
|
+
"HTTPConnector",
|
|
246
|
+
"InMemoryStateStore",
|
|
247
|
+
"ISOLATION_LEVELS",
|
|
248
|
+
"InjectedMemory",
|
|
249
|
+
"JsonFileStateStore",
|
|
250
|
+
"Kernel",
|
|
251
|
+
"LLMPlanner",
|
|
252
|
+
"LLMProvider",
|
|
253
|
+
"LLMRerankRetriever",
|
|
254
|
+
"LLMResponse",
|
|
255
|
+
"LLMSetSelector",
|
|
256
|
+
"LLMToolSpec",
|
|
257
|
+
"LexicalRetriever",
|
|
258
|
+
"LoadedSkill",
|
|
259
|
+
"MCPError",
|
|
260
|
+
"MCPStdioClient",
|
|
261
|
+
"MCPToolInfo",
|
|
262
|
+
"MarmoError",
|
|
263
|
+
"PackageCompatibilityError",
|
|
264
|
+
"PackageDependency",
|
|
265
|
+
"PackageError",
|
|
266
|
+
"PackageIntegrityError",
|
|
267
|
+
"PackageLock",
|
|
268
|
+
"PackageManifest",
|
|
269
|
+
"LocalResourcePackage",
|
|
270
|
+
"KERNEL_VERSION",
|
|
271
|
+
"LOCK_FILENAME",
|
|
272
|
+
"MANIFEST_FILENAME",
|
|
273
|
+
"MappingSecretResolver",
|
|
274
|
+
"MockLLMProvider",
|
|
275
|
+
"NamespaceGrouping",
|
|
276
|
+
"OpenAICompatibleEmbeddingProvider",
|
|
277
|
+
"OpenAICompatibleLLMProvider",
|
|
278
|
+
"PendingHitlBroker",
|
|
279
|
+
"PermissionGrouping",
|
|
280
|
+
"Plan",
|
|
281
|
+
"PlanStep",
|
|
282
|
+
"Planner",
|
|
283
|
+
"PolicyContext",
|
|
284
|
+
"PolicyDecision",
|
|
285
|
+
"PolicyGateway",
|
|
286
|
+
"PolicyRejectedError",
|
|
287
|
+
"PromptInjectionFinding",
|
|
288
|
+
"PromptInjectionInspector",
|
|
289
|
+
"ProviderGrouping",
|
|
290
|
+
"RecoveryDecision",
|
|
291
|
+
"RecoveryManager",
|
|
292
|
+
"ResourceActivator",
|
|
293
|
+
"ResourceDefinition",
|
|
294
|
+
"ResourceKind",
|
|
295
|
+
"ResourceLoadError",
|
|
296
|
+
"ResourceMetadata",
|
|
297
|
+
"ResourceNotFoundError",
|
|
298
|
+
"ResourceRegistry",
|
|
299
|
+
"ResourceStats",
|
|
300
|
+
"ResourceValidationError",
|
|
301
|
+
"Retriever",
|
|
302
|
+
"RetryPolicy",
|
|
303
|
+
"RouteDecision",
|
|
304
|
+
"RoutingCase",
|
|
305
|
+
"RoutingCaseStore",
|
|
306
|
+
"RoutingDecision",
|
|
307
|
+
"RuleBasedPlanner",
|
|
308
|
+
"SafetyFinding",
|
|
309
|
+
"SafetyInspector",
|
|
310
|
+
"RuleBasedSetSelector",
|
|
311
|
+
"SQLiteStateStore",
|
|
312
|
+
"SQLiteConnector",
|
|
313
|
+
"SearchQuery",
|
|
314
|
+
"SearchResult",
|
|
315
|
+
"SemanticVersion",
|
|
316
|
+
"SecretRef",
|
|
317
|
+
"SecretResolutionError",
|
|
318
|
+
"SecretResolver",
|
|
319
|
+
"ShellConnector",
|
|
320
|
+
"SelectedResourceSet",
|
|
321
|
+
"SelectionContext",
|
|
322
|
+
"SelectionResult",
|
|
323
|
+
"SetSelector",
|
|
324
|
+
"StateConflictError",
|
|
325
|
+
"StateEvent",
|
|
326
|
+
"StateStore",
|
|
327
|
+
"TaskNotFoundError",
|
|
328
|
+
"TaskResult",
|
|
329
|
+
"TaskState",
|
|
330
|
+
"ToolCall",
|
|
331
|
+
"ToolInputError",
|
|
332
|
+
"ToolResult",
|
|
333
|
+
"ToolRuntime",
|
|
334
|
+
"ValidationIssue",
|
|
335
|
+
"VersionRange",
|
|
336
|
+
"build_package_lock",
|
|
337
|
+
"compensation_for",
|
|
338
|
+
"connect_mcp_server",
|
|
339
|
+
"discover_package_roots",
|
|
340
|
+
"estimate_tokens",
|
|
341
|
+
"load_registry",
|
|
342
|
+
"label_untrusted_content",
|
|
343
|
+
"load_resource_definitions",
|
|
344
|
+
"read_package_manifest",
|
|
345
|
+
"mcp_tool_implementations",
|
|
346
|
+
"mcp_tool_resources",
|
|
347
|
+
"outcomes_from_audit",
|
|
348
|
+
"resolve_case",
|
|
349
|
+
"validate_arguments",
|
|
350
|
+
"validate_plan",
|
|
351
|
+
"tokenize",
|
|
352
|
+
"connector_implementations",
|
|
353
|
+
"connector_resources",
|
|
354
|
+
"connector_tools",
|
|
355
|
+
"install_connectors",
|
|
356
|
+
"verify_local_package",
|
|
357
|
+
"write_package_lock",
|
|
358
|
+
"__version__",
|
|
359
|
+
]
|
|
360
|
+
|
|
361
|
+
from ._version import __version__
|
marmo_core/_version.py
ADDED
marmo_core/activator.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Resource Activator: type-specific activation behind the activation gate (4.4).
|
|
2
|
+
|
|
3
|
+
Every activation passes the Policy Gateway activation gate first (F-GATE-01).
|
|
4
|
+
Activation patterns implemented in this phase:
|
|
5
|
+
|
|
6
|
+
- memory -> retrieve and inject (F-ACT-01)
|
|
7
|
+
- skill -> retrieve and load (F-ACT-02)
|
|
8
|
+
- tool -> retrieve and bind (F-ACT-03)
|
|
9
|
+
- agent -> retrieve and bind (F-ACT-04)
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Callable, Mapping
|
|
17
|
+
import importlib
|
|
18
|
+
|
|
19
|
+
from .errors import ActivationError
|
|
20
|
+
from .models import ResourceDefinition, ResourceKind, ResourceMetadata
|
|
21
|
+
from .policy import PolicyContext, PolicyDecision, PolicyGateway
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class InjectedMemory:
|
|
26
|
+
"""Memory content resolved for prompt injection."""
|
|
27
|
+
|
|
28
|
+
definition: ResourceDefinition
|
|
29
|
+
content: str
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def metadata(self) -> ResourceMetadata:
|
|
33
|
+
return self.definition.metadata
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class LoadedSkill:
|
|
38
|
+
"""Skill instructions loaded as guidance text."""
|
|
39
|
+
|
|
40
|
+
definition: ResourceDefinition
|
|
41
|
+
instructions: str
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def metadata(self) -> ResourceMetadata:
|
|
45
|
+
return self.definition.metadata
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class BoundTool:
|
|
50
|
+
"""Tool bound to an executable handler; the handler never reaches the LLM."""
|
|
51
|
+
|
|
52
|
+
definition: ResourceDefinition
|
|
53
|
+
input_schema: dict[str, Any]
|
|
54
|
+
output_schema: dict[str, Any]
|
|
55
|
+
handler: Callable[..., Any]
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def metadata(self) -> ResourceMetadata:
|
|
59
|
+
return self.definition.metadata
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class BoundAgent:
|
|
64
|
+
"""Agent bound as a synchronous tool-style delegate (F-AGENT-01)."""
|
|
65
|
+
|
|
66
|
+
definition: ResourceDefinition
|
|
67
|
+
input_schema: dict[str, Any]
|
|
68
|
+
output_schema: dict[str, Any]
|
|
69
|
+
handler: Callable[..., Any]
|
|
70
|
+
delegation_interface: str = "tool_wrap"
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def metadata(self) -> ResourceMetadata:
|
|
74
|
+
return self.definition.metadata
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class Activation:
|
|
79
|
+
"""Outcome of one gated activation attempt."""
|
|
80
|
+
|
|
81
|
+
definition: ResourceDefinition
|
|
82
|
+
decision: PolicyDecision
|
|
83
|
+
activated: InjectedMemory | LoadedSkill | BoundTool | BoundAgent | None = None
|
|
84
|
+
error: str | None = None
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def ok(self) -> bool:
|
|
88
|
+
return self.activated is not None and self.decision.allowed
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ResourceActivator:
|
|
92
|
+
"""Activate resources per kind after the mandatory activation gate."""
|
|
93
|
+
|
|
94
|
+
def __init__(
|
|
95
|
+
self,
|
|
96
|
+
gateway: PolicyGateway | None = None,
|
|
97
|
+
*,
|
|
98
|
+
tool_implementations: Mapping[str, Callable[..., Any]] | None = None,
|
|
99
|
+
agent_implementations: Mapping[str, Callable[..., Any]] | None = None,
|
|
100
|
+
) -> None:
|
|
101
|
+
self.gateway = gateway or PolicyGateway()
|
|
102
|
+
self.tool_implementations = dict(tool_implementations or {})
|
|
103
|
+
self.agent_implementations = dict(agent_implementations or {})
|
|
104
|
+
|
|
105
|
+
def bind_tool(self, resource_id: str, handler: Callable[..., Any]) -> None:
|
|
106
|
+
self.tool_implementations[resource_id] = handler
|
|
107
|
+
|
|
108
|
+
def bind_agent(self, resource_id: str, handler: Callable[..., Any]) -> None:
|
|
109
|
+
self.agent_implementations[resource_id] = handler
|
|
110
|
+
|
|
111
|
+
def activate(self, definition: ResourceDefinition, context: PolicyContext | None = None) -> Activation:
|
|
112
|
+
decision = self.gateway.evaluate(definition, context, gate="activation")
|
|
113
|
+
if not decision.allowed:
|
|
114
|
+
return Activation(definition=definition, decision=decision)
|
|
115
|
+
try:
|
|
116
|
+
activated = self._activate_allowed(definition)
|
|
117
|
+
except ActivationError as exc:
|
|
118
|
+
return Activation(definition=definition, decision=decision, error=str(exc))
|
|
119
|
+
return Activation(definition=definition, decision=decision, activated=activated)
|
|
120
|
+
|
|
121
|
+
def _activate_allowed(
|
|
122
|
+
self, definition: ResourceDefinition
|
|
123
|
+
) -> InjectedMemory | LoadedSkill | BoundTool | BoundAgent:
|
|
124
|
+
kind = definition.metadata.kind
|
|
125
|
+
if kind == ResourceKind.MEMORY.value:
|
|
126
|
+
return InjectedMemory(definition=definition, content=self._resolve_memory_content(definition))
|
|
127
|
+
if kind == ResourceKind.SKILL.value:
|
|
128
|
+
return LoadedSkill(definition=definition, instructions=self._resolve_skill_instructions(definition))
|
|
129
|
+
if kind == ResourceKind.TOOL.value:
|
|
130
|
+
return self._bind_tool(definition)
|
|
131
|
+
if kind == ResourceKind.AGENT.value:
|
|
132
|
+
return self._bind_agent(definition)
|
|
133
|
+
raise ActivationError(f"{definition.identity}: unsupported resource kind {kind!r}")
|
|
134
|
+
|
|
135
|
+
def _resolve_memory_content(self, definition: ResourceDefinition) -> str:
|
|
136
|
+
content = definition.extras.get("content")
|
|
137
|
+
if isinstance(content, str) and content.strip():
|
|
138
|
+
return content
|
|
139
|
+
if isinstance(content, list) and all(isinstance(item, str) for item in content):
|
|
140
|
+
return "\n".join(content)
|
|
141
|
+
ref = definition.metadata.ref
|
|
142
|
+
if ref.startswith("file:"):
|
|
143
|
+
return _read_ref_file(definition, ref[len("file:"):])
|
|
144
|
+
raise ActivationError(
|
|
145
|
+
f"{definition.identity}: cannot resolve memory content; "
|
|
146
|
+
'add a "content" field to the definition or use a file: ref'
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
def _resolve_skill_instructions(self, definition: ResourceDefinition) -> str:
|
|
150
|
+
instructions = definition.extras.get("instructions")
|
|
151
|
+
if isinstance(instructions, str) and instructions.strip():
|
|
152
|
+
return instructions
|
|
153
|
+
if isinstance(instructions, list) and all(isinstance(item, str) for item in instructions):
|
|
154
|
+
return "\n".join(instructions)
|
|
155
|
+
content = definition.extras.get("content")
|
|
156
|
+
if isinstance(content, str) and content.strip():
|
|
157
|
+
return content
|
|
158
|
+
ref = definition.metadata.ref
|
|
159
|
+
if ref.startswith("file:"):
|
|
160
|
+
return _read_ref_file(definition, ref[len("file:"):])
|
|
161
|
+
return definition.metadata.description
|
|
162
|
+
|
|
163
|
+
def _bind_tool(self, definition: ResourceDefinition) -> BoundTool:
|
|
164
|
+
metadata = definition.metadata
|
|
165
|
+
handler = self.tool_implementations.get(metadata.id)
|
|
166
|
+
if handler is None:
|
|
167
|
+
handler = _resolve_python_ref(definition)
|
|
168
|
+
if handler is None:
|
|
169
|
+
raise ActivationError(
|
|
170
|
+
f"{definition.identity}: no executable implementation; register one with "
|
|
171
|
+
f'tool_implementations={{"{metadata.id}": callable}} or use a python:module:function ref'
|
|
172
|
+
)
|
|
173
|
+
input_schema = definition.extras.get("input_schema")
|
|
174
|
+
output_schema = definition.extras.get("output_schema")
|
|
175
|
+
return BoundTool(
|
|
176
|
+
definition=definition,
|
|
177
|
+
input_schema=dict(input_schema) if isinstance(input_schema, Mapping) else {},
|
|
178
|
+
output_schema=dict(output_schema) if isinstance(output_schema, Mapping) else {},
|
|
179
|
+
handler=handler,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
def _bind_agent(self, definition: ResourceDefinition) -> BoundAgent:
|
|
183
|
+
metadata = definition.metadata
|
|
184
|
+
card = definition.extras.get("agent_card")
|
|
185
|
+
card = card if isinstance(card, Mapping) else {}
|
|
186
|
+
interface = card.get("delegation_interface", definition.extras.get("delegation_interface", "tool_wrap"))
|
|
187
|
+
if interface != "tool_wrap":
|
|
188
|
+
raise ActivationError(
|
|
189
|
+
f"{definition.identity}: delegation_interface {interface!r} is not available in v2; "
|
|
190
|
+
"use 'tool_wrap' (structured_task is planned for v3)"
|
|
191
|
+
)
|
|
192
|
+
handler = self.agent_implementations.get(metadata.id)
|
|
193
|
+
if handler is None:
|
|
194
|
+
handler = _resolve_python_ref(definition)
|
|
195
|
+
if handler is None:
|
|
196
|
+
raise ActivationError(
|
|
197
|
+
f"{definition.identity}: no executable implementation; register one with "
|
|
198
|
+
f'agent_implementations={{"{metadata.id}": callable}} or use a python:module:function ref'
|
|
199
|
+
)
|
|
200
|
+
input_schema = card.get("input_schema", definition.extras.get("input_schema"))
|
|
201
|
+
output_schema = card.get("output_schema", definition.extras.get("output_schema"))
|
|
202
|
+
if not isinstance(input_schema, Mapping):
|
|
203
|
+
input_schema = {
|
|
204
|
+
"type": "object",
|
|
205
|
+
"required": ["goal"],
|
|
206
|
+
"properties": {"goal": {"type": "string"}},
|
|
207
|
+
"additionalProperties": False,
|
|
208
|
+
}
|
|
209
|
+
return BoundAgent(
|
|
210
|
+
definition=definition,
|
|
211
|
+
input_schema=dict(input_schema),
|
|
212
|
+
output_schema=dict(output_schema) if isinstance(output_schema, Mapping) else {},
|
|
213
|
+
handler=handler,
|
|
214
|
+
delegation_interface=str(interface),
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _resolve_python_ref(definition: ResourceDefinition) -> Callable[..., Any] | None:
|
|
219
|
+
ref = definition.metadata.ref
|
|
220
|
+
if not ref.startswith("python:"):
|
|
221
|
+
return None
|
|
222
|
+
target = ref[len("python:"):]
|
|
223
|
+
if ":" not in target:
|
|
224
|
+
raise ActivationError(
|
|
225
|
+
f"{definition.identity}: python ref must be python:module.path:function, got {ref!r}"
|
|
226
|
+
)
|
|
227
|
+
module_name, _, attribute = target.rpartition(":")
|
|
228
|
+
try:
|
|
229
|
+
module = importlib.import_module(module_name)
|
|
230
|
+
except ImportError as exc:
|
|
231
|
+
raise ActivationError(f"{definition.identity}: cannot import module {module_name!r}: {exc}") from exc
|
|
232
|
+
handler = getattr(module, attribute, None)
|
|
233
|
+
if not callable(handler):
|
|
234
|
+
raise ActivationError(f"{definition.identity}: {target!r} is not a callable")
|
|
235
|
+
return handler
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _read_ref_file(definition: ResourceDefinition, raw_path: str) -> str:
|
|
239
|
+
path = Path(raw_path)
|
|
240
|
+
if not path.is_absolute():
|
|
241
|
+
source = definition.source.split("#", 1)[0]
|
|
242
|
+
base = Path(source).parent if source else Path.cwd()
|
|
243
|
+
path = base / path
|
|
244
|
+
try:
|
|
245
|
+
return path.read_text(encoding="utf-8")
|
|
246
|
+
except OSError as exc:
|
|
247
|
+
raise ActivationError(f"{definition.identity}: cannot read ref file {path}: {exc}") from exc
|