authority-runtime 0.3.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.
- authority_runtime/__init__.py +139 -0
- authority_runtime/approvals.py +267 -0
- authority_runtime/backends/__init__.py +16 -0
- authority_runtime/backends/memory.py +296 -0
- authority_runtime/backends/slos.py +555 -0
- authority_runtime/cli.py +1405 -0
- authority_runtime/compiler.py +719 -0
- authority_runtime/compliance.py +572 -0
- authority_runtime/constraints.py +124 -0
- authority_runtime/crypto.py +212 -0
- authority_runtime/enforce.py +590 -0
- authority_runtime/envelope.py +575 -0
- authority_runtime/keys.py +212 -0
- authority_runtime/langgraph.py +407 -0
- authority_runtime/logging_config.py +71 -0
- authority_runtime/mcp_server.py +1431 -0
- authority_runtime/policy.py +245 -0
- authority_runtime/roles.py +539 -0
- authority_runtime/shell.py +489 -0
- authority_runtime/storage.py +970 -0
- authority_runtime/types.py +281 -0
- authority_runtime/validation.py +428 -0
- authority_runtime/vault_scope.py +175 -0
- authority_runtime-0.3.0.dist-info/METADATA +220 -0
- authority_runtime-0.3.0.dist-info/RECORD +29 -0
- authority_runtime-0.3.0.dist-info/WHEEL +5 -0
- authority_runtime-0.3.0.dist-info/entry_points.txt +2 -0
- authority_runtime-0.3.0.dist-info/licenses/LICENSE +89 -0
- authority_runtime-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sovereign Life OS Backend Adapter
|
|
3
|
+
|
|
4
|
+
Handles:
|
|
5
|
+
- Signed request authentication (_auth header)
|
|
6
|
+
- Policy evaluation (allowed_agents, denied_agents, requires_approval)
|
|
7
|
+
- SLOS URI parsing (slos://vaults/{vault}/{doc_id})
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import base64
|
|
12
|
+
import logging
|
|
13
|
+
import subprocess
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from enum import Enum
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Optional, Any
|
|
19
|
+
|
|
20
|
+
import nacl.signing
|
|
21
|
+
|
|
22
|
+
from ..keys import AgentKeyStore
|
|
23
|
+
from ..crypto import encrypt_document, decrypt_document, is_encrypted
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Decision(Enum):
|
|
29
|
+
"""Policy evaluation result."""
|
|
30
|
+
ALLOW = "allow"
|
|
31
|
+
DENY = "deny"
|
|
32
|
+
REQUIRE_APPROVAL = "require_approval"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class PolicyResult:
|
|
37
|
+
"""Result of policy evaluation."""
|
|
38
|
+
decision: Decision
|
|
39
|
+
reason: str
|
|
40
|
+
metadata: dict
|
|
41
|
+
|
|
42
|
+
def __str__(self) -> str:
|
|
43
|
+
return f"{self.decision.value.upper()}: {self.reason}"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class DocumentMetadata:
|
|
48
|
+
"""SLOS document metadata from frontmatter."""
|
|
49
|
+
uri: str
|
|
50
|
+
id: str
|
|
51
|
+
domain: list[str]
|
|
52
|
+
sensitivity: str
|
|
53
|
+
allowed_agents: list[str]
|
|
54
|
+
denied_agents: list[str]
|
|
55
|
+
requires_approval: list[str]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def parse_slos_uri(uri: str) -> tuple[str, str]:
|
|
59
|
+
"""
|
|
60
|
+
Parse SLOS URI into vault and document ID.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
uri: URI in format slos://vaults/{vault}/{doc_id}
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
Tuple of (vault, doc_id)
|
|
67
|
+
|
|
68
|
+
Raises:
|
|
69
|
+
ValueError: If URI format is invalid
|
|
70
|
+
"""
|
|
71
|
+
if not uri.startswith("slos://vaults/"):
|
|
72
|
+
raise ValueError(f"Invalid SLOS URI: {uri} (must start with slos://vaults/)")
|
|
73
|
+
|
|
74
|
+
parts = uri.replace("slos://vaults/", "").split("/", 1)
|
|
75
|
+
|
|
76
|
+
if len(parts) != 2:
|
|
77
|
+
raise ValueError(f"Invalid SLOS URI: {uri} (expected slos://vaults/{{vault}}/{{doc_id}})")
|
|
78
|
+
|
|
79
|
+
return parts[0], parts[1]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class SlosBackend:
|
|
83
|
+
"""
|
|
84
|
+
Sovereign Life OS backend adapter.
|
|
85
|
+
|
|
86
|
+
Handles:
|
|
87
|
+
- Signing requests with agent Ed25519 keys
|
|
88
|
+
- Calling SLOS MCP tools
|
|
89
|
+
- Evaluating document-level policies
|
|
90
|
+
|
|
91
|
+
Example:
|
|
92
|
+
```python
|
|
93
|
+
backend = SlosBackend(
|
|
94
|
+
config_path="./carryall-integration.json",
|
|
95
|
+
key_store=AgentKeyStore("~/.carryall/keys")
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# List vaults
|
|
99
|
+
vaults = backend.list_vaults("executive-agent")
|
|
100
|
+
|
|
101
|
+
# Check access
|
|
102
|
+
result = backend.check_access(
|
|
103
|
+
envelope=my_envelope,
|
|
104
|
+
action="read",
|
|
105
|
+
uri="slos://vaults/finance/019bf091-..."
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
if result.decision == Decision.ALLOW:
|
|
109
|
+
# Proceed with access
|
|
110
|
+
pass
|
|
111
|
+
elif result.decision == Decision.REQUIRE_APPROVAL:
|
|
112
|
+
# Request human approval
|
|
113
|
+
pass
|
|
114
|
+
else:
|
|
115
|
+
# Access denied
|
|
116
|
+
print(f"Denied: {result.reason}")
|
|
117
|
+
```
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
def __init__(
|
|
121
|
+
self,
|
|
122
|
+
config_path: Optional[str] = None,
|
|
123
|
+
key_store: Optional[AgentKeyStore] = None,
|
|
124
|
+
mcp_command: Optional[list[str]] = None,
|
|
125
|
+
encryption_keys_dir: Optional[str] = None,
|
|
126
|
+
):
|
|
127
|
+
"""
|
|
128
|
+
Initialize SLOS backend.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
config_path: Path to carryall-integration.json from SLOS
|
|
132
|
+
key_store: AgentKeyStore for signing requests
|
|
133
|
+
mcp_command: Command to invoke SLOS MCP server (e.g., ["npx", "slos-mcp"])
|
|
134
|
+
"""
|
|
135
|
+
self.config: dict = {}
|
|
136
|
+
self._config_path = config_path
|
|
137
|
+
if config_path:
|
|
138
|
+
config_file = Path(config_path).expanduser()
|
|
139
|
+
if config_file.exists():
|
|
140
|
+
with open(config_file) as f:
|
|
141
|
+
self.config = json.load(f)
|
|
142
|
+
|
|
143
|
+
self.key_store = key_store or AgentKeyStore()
|
|
144
|
+
|
|
145
|
+
if mcp_command:
|
|
146
|
+
self.mcp_command = mcp_command
|
|
147
|
+
else:
|
|
148
|
+
cmd = self.config.get("mcp_command", "slos-mcp")
|
|
149
|
+
args = self.config.get("mcp_args", [])
|
|
150
|
+
# mcp_command can be a string or list
|
|
151
|
+
self.mcp_command = ([cmd] if isinstance(cmd, str) else cmd) + args
|
|
152
|
+
|
|
153
|
+
# Resolve working directory for subprocess calls
|
|
154
|
+
# mcp_cwd in config is relative to the config file's directory
|
|
155
|
+
mcp_cwd = self.config.get("mcp_cwd")
|
|
156
|
+
if mcp_cwd and config_path:
|
|
157
|
+
config_dir = Path(config_path).expanduser().parent
|
|
158
|
+
self.mcp_cwd = str(config_dir) if mcp_cwd == "." else str(config_dir / mcp_cwd)
|
|
159
|
+
else:
|
|
160
|
+
self.mcp_cwd = None
|
|
161
|
+
|
|
162
|
+
# Encryption keys directory for vault-level encryption at rest
|
|
163
|
+
if encryption_keys_dir:
|
|
164
|
+
self.encryption_keys_dir = Path(encryption_keys_dir).expanduser()
|
|
165
|
+
elif key_store and key_store.keys_dir:
|
|
166
|
+
self.encryption_keys_dir = Path(key_store.keys_dir).expanduser()
|
|
167
|
+
else:
|
|
168
|
+
self.encryption_keys_dir = None
|
|
169
|
+
|
|
170
|
+
def _sign_request(self, agent_id: str, arguments: dict) -> dict:
|
|
171
|
+
"""
|
|
172
|
+
Add _auth header to request arguments.
|
|
173
|
+
|
|
174
|
+
Signature format: sign(agent_id || timestamp || json(arguments))
|
|
175
|
+
"""
|
|
176
|
+
signing_key = self.key_store.load_signing_key(agent_id)
|
|
177
|
+
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
178
|
+
|
|
179
|
+
# Create canonical JSON of arguments (without _auth)
|
|
180
|
+
args_without_auth = {k: v for k, v in arguments.items() if k != "_auth"}
|
|
181
|
+
args_json = json.dumps(args_without_auth, sort_keys=True, separators=(",", ":"))
|
|
182
|
+
|
|
183
|
+
# Sign: agent_id || timestamp || json
|
|
184
|
+
message = f"{agent_id}{timestamp}{args_json}".encode()
|
|
185
|
+
signature = signing_key.sign(message).signature
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
**arguments,
|
|
189
|
+
"_auth": {
|
|
190
|
+
"agent_id": agent_id,
|
|
191
|
+
"timestamp": timestamp,
|
|
192
|
+
"signature": base64.b64encode(signature).decode(),
|
|
193
|
+
},
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
def _call_mcp(self, method: str, params: dict, agent_id: str) -> dict:
|
|
197
|
+
"""
|
|
198
|
+
Call SLOS MCP server with signed request.
|
|
199
|
+
|
|
200
|
+
Uses stdio transport - sends JSON-RPC request to stdin, reads response from stdout.
|
|
201
|
+
SLOS expects MCP protocol: method="tools/call" with tool name in params.name.
|
|
202
|
+
"""
|
|
203
|
+
signed_params = self._sign_request(agent_id, params)
|
|
204
|
+
|
|
205
|
+
request = {
|
|
206
|
+
"jsonrpc": "2.0",
|
|
207
|
+
"id": 1,
|
|
208
|
+
"method": "tools/call",
|
|
209
|
+
"params": {
|
|
210
|
+
"name": method,
|
|
211
|
+
"arguments": signed_params,
|
|
212
|
+
},
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
try:
|
|
216
|
+
result = subprocess.run(
|
|
217
|
+
self.mcp_command,
|
|
218
|
+
input=json.dumps(request),
|
|
219
|
+
capture_output=True,
|
|
220
|
+
text=True,
|
|
221
|
+
timeout=30,
|
|
222
|
+
cwd=self.mcp_cwd,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
if result.returncode != 0:
|
|
226
|
+
raise RuntimeError(f"MCP call failed: {result.stderr}")
|
|
227
|
+
|
|
228
|
+
response = json.loads(result.stdout)
|
|
229
|
+
|
|
230
|
+
if "error" in response:
|
|
231
|
+
raise RuntimeError(f"MCP error: {response['error']}")
|
|
232
|
+
|
|
233
|
+
raw_result = response.get("result", {})
|
|
234
|
+
|
|
235
|
+
# Unwrap MCP content envelope format
|
|
236
|
+
# SLOS returns: {"content": [{"type": "text", "text": "{...}"}]}
|
|
237
|
+
if "content" in raw_result and isinstance(raw_result["content"], list):
|
|
238
|
+
for item in raw_result["content"]:
|
|
239
|
+
if item.get("type") == "text":
|
|
240
|
+
return json.loads(item["text"])
|
|
241
|
+
|
|
242
|
+
return raw_result
|
|
243
|
+
|
|
244
|
+
except subprocess.TimeoutExpired:
|
|
245
|
+
raise RuntimeError("MCP call timed out after 30 seconds")
|
|
246
|
+
except json.JSONDecodeError as e:
|
|
247
|
+
raise RuntimeError(f"Invalid MCP response: {e}")
|
|
248
|
+
|
|
249
|
+
def _call_mcp_mock(self, method: str, params: dict, agent_id: str) -> dict:
|
|
250
|
+
"""
|
|
251
|
+
Mock MCP call for testing without SLOS running.
|
|
252
|
+
|
|
253
|
+
Returns simulated responses based on method.
|
|
254
|
+
"""
|
|
255
|
+
if method == "list_vaults":
|
|
256
|
+
return {"vaults": ["finance", "startup", "health", "personal", "shared"]}
|
|
257
|
+
|
|
258
|
+
if method == "list_vault":
|
|
259
|
+
vault = params.get("vault", "unknown")
|
|
260
|
+
return {
|
|
261
|
+
"vault": vault,
|
|
262
|
+
"documents": [
|
|
263
|
+
{"id": "doc-001", "title": "Test Document 1"},
|
|
264
|
+
{"id": "doc-002", "title": "Test Document 2"},
|
|
265
|
+
],
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if method == "get_metadata":
|
|
269
|
+
uri = params.get("uri", "")
|
|
270
|
+
vault, doc_id = parse_slos_uri(uri) if uri.startswith("slos://") else ("unknown", "unknown")
|
|
271
|
+
|
|
272
|
+
# Simulate document-level policies based on vault
|
|
273
|
+
allowed_agents = []
|
|
274
|
+
denied_agents = []
|
|
275
|
+
requires_approval = []
|
|
276
|
+
|
|
277
|
+
if vault == "finance":
|
|
278
|
+
allowed_agents = ["finance-agent", "executive-agent"]
|
|
279
|
+
denied_agents = ["startup-agent"]
|
|
280
|
+
elif vault == "health":
|
|
281
|
+
allowed_agents = ["health-agent"]
|
|
282
|
+
requires_approval = ["executive-agent"]
|
|
283
|
+
elif vault == "shared":
|
|
284
|
+
allowed_agents = [] # Open to all with scope
|
|
285
|
+
|
|
286
|
+
return {
|
|
287
|
+
"uri": uri,
|
|
288
|
+
"id": doc_id,
|
|
289
|
+
"domain": [vault],
|
|
290
|
+
"sensitivity": "confidential" if vault in ["finance", "health"] else "internal",
|
|
291
|
+
"allowed_agents": allowed_agents,
|
|
292
|
+
"denied_agents": denied_agents,
|
|
293
|
+
"requires_approval": requires_approval,
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return {}
|
|
297
|
+
|
|
298
|
+
def list_vaults(self, agent_id: str = "executive-agent", mock: bool = False) -> list[str]:
|
|
299
|
+
"""
|
|
300
|
+
List available vaults.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
agent_id: Agent to authenticate as
|
|
304
|
+
mock: If True, return simulated data
|
|
305
|
+
|
|
306
|
+
Returns:
|
|
307
|
+
List of vault names
|
|
308
|
+
"""
|
|
309
|
+
call = self._call_mcp_mock if mock else self._call_mcp
|
|
310
|
+
result = call("list_vaults", {}, agent_id)
|
|
311
|
+
return result.get("vaults", [])
|
|
312
|
+
|
|
313
|
+
def list_resources(self, vault: str, agent_id: str, mock: bool = False) -> list[dict]:
|
|
314
|
+
"""
|
|
315
|
+
List documents in a vault.
|
|
316
|
+
|
|
317
|
+
Args:
|
|
318
|
+
vault: Vault name
|
|
319
|
+
agent_id: Agent to authenticate as
|
|
320
|
+
mock: If True, return simulated data
|
|
321
|
+
|
|
322
|
+
Returns:
|
|
323
|
+
List of document metadata dicts
|
|
324
|
+
"""
|
|
325
|
+
call = self._call_mcp_mock if mock else self._call_mcp
|
|
326
|
+
result = call("list_vault", {"vault": vault}, agent_id)
|
|
327
|
+
return result.get("documents", [])
|
|
328
|
+
|
|
329
|
+
def get_metadata(self, uri: str, agent_id: str, mock: bool = False) -> DocumentMetadata:
|
|
330
|
+
"""
|
|
331
|
+
Get document metadata including access policies.
|
|
332
|
+
|
|
333
|
+
Args:
|
|
334
|
+
uri: SLOS URI (slos://vaults/{vault}/{doc_id})
|
|
335
|
+
agent_id: Agent to authenticate as
|
|
336
|
+
mock: If True, return simulated data
|
|
337
|
+
|
|
338
|
+
Returns:
|
|
339
|
+
DocumentMetadata with policy fields
|
|
340
|
+
"""
|
|
341
|
+
call = self._call_mcp_mock if mock else self._call_mcp
|
|
342
|
+
result = call("get_metadata", {"uri": uri}, agent_id)
|
|
343
|
+
|
|
344
|
+
return DocumentMetadata(
|
|
345
|
+
uri=result.get("uri", uri),
|
|
346
|
+
id=result.get("id", ""),
|
|
347
|
+
domain=result.get("domain", []),
|
|
348
|
+
sensitivity=result.get("sensitivity", "unknown"),
|
|
349
|
+
allowed_agents=result.get("allowed_agents", []),
|
|
350
|
+
denied_agents=result.get("denied_agents", []),
|
|
351
|
+
requires_approval=result.get("requires_approval", []),
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
def check_access(
|
|
355
|
+
self,
|
|
356
|
+
envelope: Any, # AuthorityEnvelope
|
|
357
|
+
action: str,
|
|
358
|
+
uri: str,
|
|
359
|
+
mock: bool = False,
|
|
360
|
+
) -> PolicyResult:
|
|
361
|
+
"""
|
|
362
|
+
Main policy evaluation.
|
|
363
|
+
|
|
364
|
+
Evaluates in order:
|
|
365
|
+
1. Explicit deny (denied_agents in document)
|
|
366
|
+
2. Requires approval (requires_approval in document)
|
|
367
|
+
3. Explicit allow (allowed_agents in document)
|
|
368
|
+
4. Scope-based allow (envelope has vault:action scope)
|
|
369
|
+
5. Default deny
|
|
370
|
+
|
|
371
|
+
Args:
|
|
372
|
+
envelope: Authority envelope with agent identity and scopes
|
|
373
|
+
action: Action being requested (read, write, delete)
|
|
374
|
+
uri: SLOS URI of the resource
|
|
375
|
+
|
|
376
|
+
Returns:
|
|
377
|
+
PolicyResult with decision and reason
|
|
378
|
+
"""
|
|
379
|
+
agent_id = envelope.agent_id
|
|
380
|
+
|
|
381
|
+
# Get document metadata (this call is also authenticated)
|
|
382
|
+
try:
|
|
383
|
+
metadata = self.get_metadata(uri, agent_id, mock=mock)
|
|
384
|
+
except FileNotFoundError as e:
|
|
385
|
+
# Agent key not found
|
|
386
|
+
return PolicyResult(
|
|
387
|
+
decision=Decision.DENY,
|
|
388
|
+
reason=f"Agent key not found: {e}",
|
|
389
|
+
metadata={"uri": uri, "error": str(e)},
|
|
390
|
+
)
|
|
391
|
+
except RuntimeError as e:
|
|
392
|
+
# SLOS rejected the request
|
|
393
|
+
return PolicyResult(
|
|
394
|
+
decision=Decision.DENY,
|
|
395
|
+
reason=f"SLOS rejected agent authentication: {e}",
|
|
396
|
+
metadata={"uri": uri, "error": str(e)},
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
# 1. Explicit deny takes precedence
|
|
400
|
+
if agent_id in metadata.denied_agents:
|
|
401
|
+
return PolicyResult(
|
|
402
|
+
decision=Decision.DENY,
|
|
403
|
+
reason=f"Agent '{agent_id}' explicitly denied by document",
|
|
404
|
+
metadata={"uri": uri, "rule": "denied_agents"},
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
# 2. Requires approval
|
|
408
|
+
if agent_id in metadata.requires_approval:
|
|
409
|
+
return PolicyResult(
|
|
410
|
+
decision=Decision.REQUIRE_APPROVAL,
|
|
411
|
+
reason=f"Agent '{agent_id}' requires approval for this document",
|
|
412
|
+
metadata={"uri": uri, "rule": "requires_approval"},
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
# 3. Explicit allow in document
|
|
416
|
+
if metadata.allowed_agents and agent_id in metadata.allowed_agents:
|
|
417
|
+
return PolicyResult(
|
|
418
|
+
decision=Decision.ALLOW,
|
|
419
|
+
reason=f"Agent '{agent_id}' explicitly allowed by document",
|
|
420
|
+
metadata={"uri": uri, "rule": "allowed_agents"},
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
# 4. Fall back to envelope scopes
|
|
424
|
+
vault, _ = parse_slos_uri(uri)
|
|
425
|
+
required_scope = f"vault:{vault}:{action}"
|
|
426
|
+
|
|
427
|
+
if required_scope in envelope.authority.scopes:
|
|
428
|
+
return PolicyResult(
|
|
429
|
+
decision=Decision.ALLOW,
|
|
430
|
+
reason=f"Envelope has scope '{required_scope}'",
|
|
431
|
+
metadata={"uri": uri, "rule": "envelope_scope", "scope": required_scope},
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
# Also check wildcard scopes
|
|
435
|
+
wildcard_scope = f"vault:{vault}:*"
|
|
436
|
+
if wildcard_scope in envelope.authority.scopes:
|
|
437
|
+
return PolicyResult(
|
|
438
|
+
decision=Decision.ALLOW,
|
|
439
|
+
reason=f"Envelope has wildcard scope '{wildcard_scope}'",
|
|
440
|
+
metadata={"uri": uri, "rule": "envelope_scope", "scope": wildcard_scope},
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
# 5. Default deny
|
|
444
|
+
return PolicyResult(
|
|
445
|
+
decision=Decision.DENY,
|
|
446
|
+
reason=f"No permission for {vault}:{action}",
|
|
447
|
+
metadata={"uri": uri, "required_scope": required_scope},
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
def read_document(
|
|
451
|
+
self, document_id: str, purpose: str, agent_id: str,
|
|
452
|
+
domain: Optional[str] = None, mock: bool = False,
|
|
453
|
+
) -> dict:
|
|
454
|
+
"""
|
|
455
|
+
Read document content from SLOS by UUID, decrypting if necessary.
|
|
456
|
+
|
|
457
|
+
Args:
|
|
458
|
+
document_id: Document UUID
|
|
459
|
+
purpose: Why the agent needs this document (audit trail)
|
|
460
|
+
agent_id: Agent to authenticate as
|
|
461
|
+
domain: Vault domain (needed for decryption key lookup)
|
|
462
|
+
mock: If True, return simulated data
|
|
463
|
+
|
|
464
|
+
Returns:
|
|
465
|
+
Dict with document content from SLOS (decrypted if encrypted)
|
|
466
|
+
"""
|
|
467
|
+
call = self._call_mcp_mock if mock else self._call_mcp
|
|
468
|
+
result = call("read_document", {"id": document_id, "purpose": purpose}, agent_id)
|
|
469
|
+
|
|
470
|
+
# Decrypt document body if encrypted
|
|
471
|
+
if self.encryption_keys_dir and domain:
|
|
472
|
+
content = result.get("content", "")
|
|
473
|
+
if isinstance(content, str) and is_encrypted(content):
|
|
474
|
+
try:
|
|
475
|
+
result["content"] = decrypt_document(content, domain, self.encryption_keys_dir)
|
|
476
|
+
logger.debug(f"Decrypted document {document_id} from vault {domain}")
|
|
477
|
+
except Exception as e:
|
|
478
|
+
logger.error(f"Failed to decrypt document {document_id}: {e}")
|
|
479
|
+
raise RuntimeError(f"Decryption failed for document {document_id}: {e}")
|
|
480
|
+
|
|
481
|
+
return result
|
|
482
|
+
|
|
483
|
+
def write_document(
|
|
484
|
+
self,
|
|
485
|
+
domain: str,
|
|
486
|
+
content: str,
|
|
487
|
+
metadata: dict,
|
|
488
|
+
agent_id: str,
|
|
489
|
+
document_id: str = None,
|
|
490
|
+
mock: bool = False,
|
|
491
|
+
) -> dict:
|
|
492
|
+
"""
|
|
493
|
+
Write/create a document in a SLOS vault, encrypting if sensitivity warrants it.
|
|
494
|
+
|
|
495
|
+
Args:
|
|
496
|
+
domain: Vault domain to write to (finance, startup, etc.)
|
|
497
|
+
content: Document content (markdown)
|
|
498
|
+
metadata: Document metadata (title, subpath, sensitivity, data_type)
|
|
499
|
+
agent_id: Agent to authenticate as
|
|
500
|
+
document_id: Optional UUID for updating existing documents
|
|
501
|
+
mock: If True, return simulated data
|
|
502
|
+
|
|
503
|
+
Returns:
|
|
504
|
+
Dict with created document info from SLOS
|
|
505
|
+
"""
|
|
506
|
+
# Encrypt document body before writing to disk
|
|
507
|
+
if self.encryption_keys_dir:
|
|
508
|
+
sensitivity = metadata.get("sensitivity", "internal")
|
|
509
|
+
content, was_encrypted = encrypt_document(
|
|
510
|
+
content, domain, sensitivity, self.encryption_keys_dir
|
|
511
|
+
)
|
|
512
|
+
if was_encrypted:
|
|
513
|
+
metadata["encrypted"] = True
|
|
514
|
+
logger.debug(f"Encrypted document for vault {domain} (sensitivity={sensitivity})")
|
|
515
|
+
|
|
516
|
+
params = {
|
|
517
|
+
"domain": domain,
|
|
518
|
+
"content": content,
|
|
519
|
+
"metadata": metadata,
|
|
520
|
+
}
|
|
521
|
+
if document_id:
|
|
522
|
+
params["id"] = document_id
|
|
523
|
+
call = self._call_mcp_mock if mock else self._call_mcp
|
|
524
|
+
return call("write_document", params, agent_id)
|
|
525
|
+
|
|
526
|
+
def query_documents(
|
|
527
|
+
self,
|
|
528
|
+
domain: str,
|
|
529
|
+
query: str,
|
|
530
|
+
agent_id: str,
|
|
531
|
+
include_content: bool = False,
|
|
532
|
+
limit: int = 10,
|
|
533
|
+
mock: bool = False,
|
|
534
|
+
) -> dict:
|
|
535
|
+
"""
|
|
536
|
+
Query documents within a domain.
|
|
537
|
+
|
|
538
|
+
Args:
|
|
539
|
+
domain: Vault domain to search (finance, startup, etc.)
|
|
540
|
+
query: Search query string
|
|
541
|
+
agent_id: Agent to authenticate as
|
|
542
|
+
include_content: Whether to include document content in results
|
|
543
|
+
limit: Maximum number of results
|
|
544
|
+
mock: If True, return simulated data
|
|
545
|
+
|
|
546
|
+
Returns:
|
|
547
|
+
Dict with matching documents from SLOS
|
|
548
|
+
"""
|
|
549
|
+
call = self._call_mcp_mock if mock else self._call_mcp
|
|
550
|
+
return call("query_documents", {
|
|
551
|
+
"domain": domain,
|
|
552
|
+
"query": query,
|
|
553
|
+
"include_content": include_content,
|
|
554
|
+
"limit": limit,
|
|
555
|
+
}, agent_id)
|