gts-agency-python-sdk 0.0.1__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.
- agency_sdk/__init__.py +0 -0
- agency_sdk/auth_hooks.py +55 -0
- agency_sdk/client.py +212 -0
- agency_sdk/credentials.py +54 -0
- agency_sdk/delegates/__init__.py +0 -0
- agency_sdk/delegates/annotations_client.py +495 -0
- agency_sdk/delegates/annotations_dto.py +200 -0
- agency_sdk/delegates/base_client.py +126 -0
- agency_sdk/delegates/datasets_client.py +109 -0
- agency_sdk/delegates/datasets_dto.py +81 -0
- agency_sdk/delegates/datasource_client.py +44 -0
- agency_sdk/delegates/datasource_dto.py +107 -0
- agency_sdk/delegates/files_client.py +184 -0
- agency_sdk/delegates/files_dto.py +36 -0
- agency_sdk/delegates/gateway_client.py +81 -0
- agency_sdk/delegates/gateway_dto.py +37 -0
- agency_sdk/delegates/ontology_client.py +203 -0
- agency_sdk/delegates/ontology_dto.py +221 -0
- agency_sdk/delegates/prompts_client.py +56 -0
- agency_sdk/delegates/rules_client.py +33 -0
- agency_sdk/delegates/rules_dto.py +108 -0
- agency_sdk/delegates/session_client.py +95 -0
- agency_sdk/delegates/session_dto.py +94 -0
- agency_sdk/delegates/session_templates_client.py +23 -0
- agency_sdk/delegates/session_templates_dto.py +27 -0
- agency_sdk/delegates/session_vault_client.py +135 -0
- agency_sdk/delegates/session_vault_dto.py +75 -0
- agency_sdk/delegates/work_queue_client.py +230 -0
- agency_sdk/delegates/work_queue_dto.py +127 -0
- agency_sdk/domain.py +140 -0
- agency_sdk/observability/__init__.py +60 -0
- agency_sdk/observability/auth.py +15 -0
- agency_sdk/observability/bootstrap.py +344 -0
- agency_sdk/test/__init__.py +0 -0
- agency_sdk/test/conftest.py +106 -0
- agency_sdk/test/test_annotations_client.py +599 -0
- agency_sdk/test/test_annotations_dto.py +299 -0
- agency_sdk/test/test_base_client.py +153 -0
- agency_sdk/test/test_client_facade.py +105 -0
- agency_sdk/test/test_credentials.py +67 -0
- agency_sdk/test/test_files_client.py +264 -0
- agency_sdk/test/test_files_dto.py +93 -0
- agency_sdk/test/test_gateway_dto.py +70 -0
- agency_sdk/test/test_gateway_facade.py +229 -0
- agency_sdk/test/test_gateway_openai.py +76 -0
- agency_sdk/test/test_observability_auth.py +125 -0
- agency_sdk/test/test_observability_facade_threadsafety.py +50 -0
- agency_sdk/test/test_observability_langfuse.py +76 -0
- agency_sdk/test/test_observability_packaging.py +78 -0
- agency_sdk/test/test_observability_pipeline.py +246 -0
- agency_sdk/test/test_ontology_client.py +152 -0
- agency_sdk/test/test_ontology_dto.py +158 -0
- agency_sdk/test/test_session_client.py +128 -0
- agency_sdk/test/test_session_dto.py +75 -0
- agency_sdk/test/test_session_templates_client.py +36 -0
- agency_sdk/test/test_session_templates_dto.py +45 -0
- agency_sdk/test/test_session_vault_client.py +151 -0
- agency_sdk/test/test_session_vault_dto.py +27 -0
- agency_sdk/test/test_stub_requests.py +39 -0
- agency_sdk/test/test_work_queue_client.py +388 -0
- agency_sdk/test/test_work_queue_dto.py +233 -0
- gts_agency_python_sdk-0.0.1.dist-info/METADATA +221 -0
- gts_agency_python_sdk-0.0.1.dist-info/RECORD +66 -0
- gts_agency_python_sdk-0.0.1.dist-info/WHEEL +5 -0
- gts_agency_python_sdk-0.0.1.dist-info/licenses/LICENSE +201 -0
- gts_agency_python_sdk-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, ConfigDict
|
|
4
|
+
|
|
5
|
+
from agency_sdk.delegates.datasets_dto import Page
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _to_camel(name: str) -> str:
|
|
9
|
+
parts = name.split("_")
|
|
10
|
+
return parts[0] + "".join(p.capitalize() for p in parts[1:])
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RuleSummary(BaseModel):
|
|
14
|
+
model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True)
|
|
15
|
+
|
|
16
|
+
id: str
|
|
17
|
+
organization_id: int
|
|
18
|
+
name: str
|
|
19
|
+
display_name: str | None = None
|
|
20
|
+
description: str | None = None
|
|
21
|
+
active_version: str | None = None
|
|
22
|
+
active_version_status: str | None = None
|
|
23
|
+
has_draft: bool | None = None
|
|
24
|
+
created_at: str
|
|
25
|
+
created_by: str | None = None
|
|
26
|
+
updated_at: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RulesPagedResult(BaseModel):
|
|
30
|
+
page: Page
|
|
31
|
+
items: list[RuleSummary]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class RuleVersionSummary(BaseModel):
|
|
35
|
+
model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True)
|
|
36
|
+
|
|
37
|
+
id: str
|
|
38
|
+
version: str
|
|
39
|
+
status: str
|
|
40
|
+
created_at: str
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RuleVersion(BaseModel):
|
|
44
|
+
model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True)
|
|
45
|
+
|
|
46
|
+
id: str
|
|
47
|
+
version: str
|
|
48
|
+
status: str
|
|
49
|
+
jdm_content: dict[str, Any] | None = None
|
|
50
|
+
input_schema: dict[str, Any] | None = None
|
|
51
|
+
output_schema: dict[str, Any] | None = None
|
|
52
|
+
created_at: str
|
|
53
|
+
created_by: str | None = None
|
|
54
|
+
updated_at: str
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class RuleDetail(BaseModel):
|
|
58
|
+
model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True)
|
|
59
|
+
|
|
60
|
+
id: str
|
|
61
|
+
organization_id: int
|
|
62
|
+
name: str
|
|
63
|
+
display_name: str | None = None
|
|
64
|
+
description: str | None = None
|
|
65
|
+
version: RuleVersion
|
|
66
|
+
versions: list[RuleVersionSummary]
|
|
67
|
+
created_at: str
|
|
68
|
+
created_by: str | None = None
|
|
69
|
+
updated_at: str
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ExecuteRequest(BaseModel):
|
|
73
|
+
model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True)
|
|
74
|
+
|
|
75
|
+
organisation: int
|
|
76
|
+
context: dict[str, Any]
|
|
77
|
+
trace: bool = False
|
|
78
|
+
version_id: str | None = None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ExecutionResult(BaseModel):
|
|
82
|
+
model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True)
|
|
83
|
+
|
|
84
|
+
execution_id: str
|
|
85
|
+
result: dict[str, Any] | None = None
|
|
86
|
+
performance: Any | None = None
|
|
87
|
+
duration_ms: int | None = None
|
|
88
|
+
trace: dict[str, Any] | None = None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ExecutionHistory(BaseModel):
|
|
92
|
+
model_config = ConfigDict(alias_generator=_to_camel, populate_by_name=True)
|
|
93
|
+
|
|
94
|
+
id: str
|
|
95
|
+
decision_model_id: str
|
|
96
|
+
decision_model_version_id: str
|
|
97
|
+
input_context: dict[str, Any] | None = None
|
|
98
|
+
output_result: dict[str, Any] | None = None
|
|
99
|
+
duration_ms: int | None = None
|
|
100
|
+
status: str
|
|
101
|
+
error_message: str | None = None
|
|
102
|
+
executed_at: str
|
|
103
|
+
executed_by: str | None = None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class ExecutionsPagedResult(BaseModel):
|
|
107
|
+
page: Page
|
|
108
|
+
items: list[ExecutionHistory]
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Client for reporting progress on a dispatched control-plane session.
|
|
2
|
+
|
|
3
|
+
An agent NEVER creates its own session. Both the direct-uri and work-queue
|
|
4
|
+
dispatch paths inject the session id into the agent's arguments (the ① worker
|
|
5
|
+
sets ``arguments.session_id``); the agent ``attach``es to that inherited session
|
|
6
|
+
and reports progress via ``update``. Self-registration would mint a second
|
|
7
|
+
session divorced from the work-item card (the "orphan leg ②"), so ``register``
|
|
8
|
+
is intentionally not exposed here — see ``docs/session_reporting_delegate_design.md``.
|
|
9
|
+
|
|
10
|
+
The client only MARSHALS a caller-decided status; it never infers the run
|
|
11
|
+
outcome. Deciding the status (and any terminal payload) stays with the agent.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from agency_sdk.credentials import CredentialsSupplier
|
|
17
|
+
from agency_sdk.delegates.base_client import BaseDelegateClient
|
|
18
|
+
from agency_sdk.delegates.session_dto import SessionCommandResponse, SessionStatus
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AgencySessionClient(BaseDelegateClient):
|
|
22
|
+
api_path = "/api/sessions"
|
|
23
|
+
|
|
24
|
+
def __init__(self, token_supplier: CredentialsSupplier, base_url: str = "http://localhost:9003"):
|
|
25
|
+
super().__init__(token_supplier, base_url=base_url)
|
|
26
|
+
self._session_id: str | None = None
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def session_id(self) -> str | None:
|
|
30
|
+
"""The attached session id, or ``None`` if nothing has been attached yet."""
|
|
31
|
+
return self._session_id
|
|
32
|
+
|
|
33
|
+
def attach(self, session_id: str) -> None:
|
|
34
|
+
"""Bind this client to an EXISTING dispatched session (inherit, not create).
|
|
35
|
+
|
|
36
|
+
Records ``session_id`` as the default target for subsequent ``update``
|
|
37
|
+
calls. No HTTP request — the session already exists; the agent inherits
|
|
38
|
+
it rather than registering a new one.
|
|
39
|
+
"""
|
|
40
|
+
self._session_id = session_id
|
|
41
|
+
|
|
42
|
+
def update(
|
|
43
|
+
self,
|
|
44
|
+
organisation_id: int,
|
|
45
|
+
*,
|
|
46
|
+
status: SessionStatus | int,
|
|
47
|
+
result: dict[str, Any] | None = None,
|
|
48
|
+
events: list[dict[str, Any]] | None = None,
|
|
49
|
+
metrics: dict[str, Any] | None = None,
|
|
50
|
+
error: str | None = None,
|
|
51
|
+
logs: str | None = None,
|
|
52
|
+
session_id: str | None = None,
|
|
53
|
+
) -> SessionCommandResponse:
|
|
54
|
+
"""Report progress on the session via ``POST /{id}/_command {command:"update"}``.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
organisation_id: The organisation ID (query ``o`` and body ``organisation``).
|
|
58
|
+
status: The caller-decided status — a ``SessionStatus`` or a raw int.
|
|
59
|
+
Marshalled as-is (``FAILED`` -1 / ``COMPLETED`` 0 / ``IN_PROGRESS`` 2);
|
|
60
|
+
the SDK never infers it from the other fields.
|
|
61
|
+
result: Optional terminal result payload.
|
|
62
|
+
events: Optional already-serialized analytics events (the agent owns
|
|
63
|
+
batching/serialization; see ``AnalyticsEvent``).
|
|
64
|
+
metrics: Optional run metrics.
|
|
65
|
+
error: Optional failure detail (surfaced in the CP UI's ERRORS tab).
|
|
66
|
+
logs: Optional captured logs (surfaced in the CP UI's LOGS tab).
|
|
67
|
+
session_id: Target session; defaults to the ``attach``ed session. An
|
|
68
|
+
explicit value overrides the attached session for THIS call only —
|
|
69
|
+
it does not rebind ``self._session_id``.
|
|
70
|
+
|
|
71
|
+
Raises:
|
|
72
|
+
ValueError: If no session is attached and no ``session_id`` is given
|
|
73
|
+
(raised before any network call).
|
|
74
|
+
"""
|
|
75
|
+
target = session_id or self._session_id
|
|
76
|
+
if target is None:
|
|
77
|
+
raise ValueError("no session attached; call attach(session_id) first or pass session_id=")
|
|
78
|
+
update: dict[str, Any] = {"status": int(status)}
|
|
79
|
+
if result is not None:
|
|
80
|
+
update["result"] = result
|
|
81
|
+
if events is not None:
|
|
82
|
+
update["events"] = events
|
|
83
|
+
if metrics is not None:
|
|
84
|
+
update["metrics"] = metrics
|
|
85
|
+
if error is not None:
|
|
86
|
+
update["error"] = error
|
|
87
|
+
if logs is not None:
|
|
88
|
+
update["logs"] = logs
|
|
89
|
+
payload = {"command": "update", "organisation": organisation_id, "update": update}
|
|
90
|
+
# retry=True: re-sending the same update is safe (idempotent; ①'s session-status
|
|
91
|
+
# monotonicity guard prevents terminal regression), unlike the work-queue POSTs.
|
|
92
|
+
body = self._make_request(
|
|
93
|
+
"POST", f"/{target}/_command", data=payload, params={"o": str(organisation_id)}, retry=True
|
|
94
|
+
)
|
|
95
|
+
return SessionCommandResponse(**body)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""DTOs for the session-reporting delegate.
|
|
2
|
+
|
|
3
|
+
- ``SessionStatus`` encodes the control-plane status int map the agent reports
|
|
4
|
+
(``failed`` → -1, completed-with-result → 0, in-progress → 2). The
|
|
5
|
+
pipeline-outcome → status DECISION lives in the agent; the SDK only marshals
|
|
6
|
+
the caller-chosen value.
|
|
7
|
+
- ``SessionCommandResponse`` is transcribed from the server's ``_command``
|
|
8
|
+
response schema (``success``/``message`` + an optional command sub-result),
|
|
9
|
+
per the "transcribe an EXISTING endpoint, never assert" rule.
|
|
10
|
+
- ``AnalyticsEvent`` is the cross-agent shared event shape (the fixed
|
|
11
|
+
``%Y-%m-%d %H:%M:%S`` serialization) promoted into the SDK so every agent
|
|
12
|
+
emits one shape.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import uuid
|
|
18
|
+
from datetime import UTC, datetime
|
|
19
|
+
from enum import IntEnum
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from pydantic import BaseModel, Field, field_serializer
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SessionStatus(IntEnum):
|
|
26
|
+
"""The control-plane session status codes an agent reports via ``update``."""
|
|
27
|
+
|
|
28
|
+
FAILED = -1
|
|
29
|
+
COMPLETED = 0
|
|
30
|
+
IN_PROGRESS = 2
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SessionCommandResponse(BaseModel):
|
|
34
|
+
"""The server's response to a session ``_command`` (e.g. ``update``).
|
|
35
|
+
|
|
36
|
+
``update`` carries the command-specific sub-result when present; it is left
|
|
37
|
+
as an opaque dict because the server marks every field of it optional.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
success: bool
|
|
41
|
+
message: str
|
|
42
|
+
update: dict[str, Any] | None = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class AnalyticsEvent(BaseModel):
|
|
46
|
+
"""Platform-wide analytics event — the cross-agent "sibling-contract" shape.
|
|
47
|
+
|
|
48
|
+
The field set and the ``%Y-%m-%d %H:%M:%S`` timestamp serialization are the
|
|
49
|
+
shape every agent emits so control-plane consumers parse one format.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
id: str | None
|
|
53
|
+
correlation: str
|
|
54
|
+
event_type: str
|
|
55
|
+
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
|
56
|
+
payload: dict[str, Any] = Field(default_factory=dict)
|
|
57
|
+
duration_ms: int | None = None
|
|
58
|
+
step_name: str | None = None
|
|
59
|
+
workflow_name: str | None = None
|
|
60
|
+
|
|
61
|
+
@field_serializer("timestamp")
|
|
62
|
+
def serialize_timestamp(self, value: datetime) -> str:
|
|
63
|
+
return value.strftime("%Y-%m-%d %H:%M:%S")
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def new(cls, correlation: str, event_type: str, payload: dict[str, Any] | None = None) -> AnalyticsEvent:
|
|
67
|
+
"""Create an event with a fresh id and default timestamp."""
|
|
68
|
+
return cls(
|
|
69
|
+
id=str(uuid.uuid4()),
|
|
70
|
+
correlation=correlation,
|
|
71
|
+
event_type=event_type,
|
|
72
|
+
payload=payload if payload is not None else {},
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def step_event(
|
|
77
|
+
cls,
|
|
78
|
+
correlation: str,
|
|
79
|
+
event_type: str,
|
|
80
|
+
step_name: str,
|
|
81
|
+
workflow_name: str | None = None,
|
|
82
|
+
duration_ms: int | None = None,
|
|
83
|
+
payload: dict[str, Any] | None = None,
|
|
84
|
+
) -> AnalyticsEvent:
|
|
85
|
+
"""Create a step-scoped event (carries step/workflow/duration metadata)."""
|
|
86
|
+
return cls(
|
|
87
|
+
id=str(uuid.uuid4()),
|
|
88
|
+
correlation=correlation,
|
|
89
|
+
event_type=event_type,
|
|
90
|
+
payload=payload if payload is not None else {},
|
|
91
|
+
duration_ms=duration_ms,
|
|
92
|
+
step_name=step_name,
|
|
93
|
+
workflow_name=workflow_name,
|
|
94
|
+
)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Client for the session-templates API (`/api/session_templates`).
|
|
2
|
+
|
|
3
|
+
A thin read-only delegate whose one job is to list an org's session templates so
|
|
4
|
+
a caller can resolve a template NAME → id at runtime (the guideline-agent
|
|
5
|
+
dispatcher does this instead of hardcoding a template id in its config). Its own
|
|
6
|
+
API domain — distinct from the session-reporting delegate (`/api/sessions`).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from agency_sdk.delegates.base_client import BaseDelegateClient
|
|
10
|
+
from agency_sdk.delegates.session_templates_dto import SessionTemplatesPagedResult
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class AgencySessionTemplatesClient(BaseDelegateClient):
|
|
14
|
+
api_path = "/api/session_templates"
|
|
15
|
+
|
|
16
|
+
def list(self, organisation_id: int, *, page: int = 0, size: int = 50) -> SessionTemplatesPagedResult:
|
|
17
|
+
"""List the org's session templates (paged), for resolving a template NAME → id.
|
|
18
|
+
|
|
19
|
+
Name→id matching (and any cache / not-found / duplicate handling) is the
|
|
20
|
+
caller's job; this returns the raw page.
|
|
21
|
+
"""
|
|
22
|
+
params = {"o": str(organisation_id), "p": str(page), "s": str(size)}
|
|
23
|
+
return SessionTemplatesPagedResult(**self._make_request("GET", "", params=params))
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""DTOs for the session-templates API (`/api/session_templates`, snake_case).
|
|
2
|
+
|
|
3
|
+
Used to resolve a session-template NAME → id (the caller matches by name); the
|
|
4
|
+
list is Page-wrapped like the other paged reads.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
|
|
11
|
+
from agency_sdk.delegates.datasets_dto import Page
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SessionTemplateResponse(BaseModel):
|
|
15
|
+
"""A session template as returned by ``GET /api/session_templates``."""
|
|
16
|
+
|
|
17
|
+
id: str
|
|
18
|
+
name: str
|
|
19
|
+
organisation_id: int
|
|
20
|
+
type: str | None = None
|
|
21
|
+
executed: int | None = None
|
|
22
|
+
audit_data: dict[str, Any] | None = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SessionTemplatesPagedResult(BaseModel):
|
|
26
|
+
page: Page
|
|
27
|
+
items: list[SessionTemplateResponse]
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Client for the session vault API (/api/sessions/{id}/vault).
|
|
2
|
+
|
|
3
|
+
The session vault is an organisation- and session-scoped key/value store of
|
|
4
|
+
serializable JSON, backed by object storage. Autonomous agents use it to
|
|
5
|
+
persist state mid-run — for example, saving a checkpoint before handing off to
|
|
6
|
+
a human-in-the-loop (HITL) and resuming from that state once the human has done
|
|
7
|
+
their part.
|
|
8
|
+
|
|
9
|
+
Entries carry a classification (default ``restricted``): ``public``/``internal``
|
|
10
|
+
are stored as plaintext and viewable; ``confidential``/``restricted`` are
|
|
11
|
+
encrypted at rest. Agents always read plaintext; humans never see ``restricted``
|
|
12
|
+
and may view ``confidential`` only via an audited reveal (``reveal=True``).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from agency_sdk.delegates.base_client import BaseDelegateClient
|
|
18
|
+
from agency_sdk.delegates.session_vault_dto import (
|
|
19
|
+
VaultEntryResponse,
|
|
20
|
+
VaultListResponse,
|
|
21
|
+
VaultSetResponse,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
#: Maximum vault key length (mirrors the server's MAX_KEY_LEN).
|
|
25
|
+
MAX_KEY_LEN = 255
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _validate_key(key: str) -> None:
|
|
29
|
+
"""Validate a vault key client-side, before any network call.
|
|
30
|
+
|
|
31
|
+
Keys map directly onto object-storage paths, so the server restricts them
|
|
32
|
+
to ``[A-Za-z0-9._-]`` (non-empty, <= 255 chars, not "." or "..") to prevent
|
|
33
|
+
path traversal. Mirroring that here fails fast with a clear error.
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
ValueError: If the key is empty, too long, "." / "..", or contains a
|
|
37
|
+
character outside the allowed set.
|
|
38
|
+
"""
|
|
39
|
+
if not key or len(key) > MAX_KEY_LEN or key in (".", ".."):
|
|
40
|
+
raise ValueError(f"Invalid vault key: {key!r}")
|
|
41
|
+
if not all(c.isascii() and (c.isalnum() or c in "-_.") for c in key):
|
|
42
|
+
raise ValueError(f"Invalid vault key: {key!r}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class AgencySessionVaultClient(BaseDelegateClient):
|
|
46
|
+
# vault writes send the raw JSON value (dict, list, or scalar) as the body; the
|
|
47
|
+
# base _make_request already types ``data`` as ``Any``, so no override is needed.
|
|
48
|
+
api_path = "/api/sessions"
|
|
49
|
+
|
|
50
|
+
def list(self, organisation_id: int, session_id: str) -> VaultListResponse:
|
|
51
|
+
"""List all entries in a session vault (metadata only — no values).
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
organisation_id: The organisation ID (must match the session's).
|
|
55
|
+
session_id: The session whose vault to list.
|
|
56
|
+
"""
|
|
57
|
+
params = {"o": str(organisation_id)}
|
|
58
|
+
return VaultListResponse(**self._make_request("GET", f"/{session_id}/vault", params=params))
|
|
59
|
+
|
|
60
|
+
def get(
|
|
61
|
+
self,
|
|
62
|
+
organisation_id: int,
|
|
63
|
+
session_id: str,
|
|
64
|
+
key: str,
|
|
65
|
+
reveal: bool = False,
|
|
66
|
+
) -> VaultEntryResponse:
|
|
67
|
+
"""Read a single vault entry's value.
|
|
68
|
+
|
|
69
|
+
Access depends on the caller and the entry's classification: agents
|
|
70
|
+
always read the plaintext value; a human may read ``public``/``internal``
|
|
71
|
+
freely, must pass ``reveal=True`` for ``confidential`` (audited), and
|
|
72
|
+
cannot read ``restricted`` at all.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
organisation_id: The organisation ID.
|
|
76
|
+
session_id: The session whose vault to read.
|
|
77
|
+
key: The entry key.
|
|
78
|
+
reveal: Pass ``True`` to reveal a ``confidential`` value as a human
|
|
79
|
+
(the access is audited). Ignored for agent callers.
|
|
80
|
+
|
|
81
|
+
Raises:
|
|
82
|
+
ValueError: If the key is invalid (raised before any network call).
|
|
83
|
+
requests.HTTPError: 403 if access is denied by classification, 404
|
|
84
|
+
if the entry does not exist.
|
|
85
|
+
"""
|
|
86
|
+
_validate_key(key)
|
|
87
|
+
params = {"o": str(organisation_id)}
|
|
88
|
+
if reveal:
|
|
89
|
+
params["reveal"] = "true"
|
|
90
|
+
return VaultEntryResponse(**self._make_request("GET", f"/{session_id}/vault/{key}", params=params))
|
|
91
|
+
|
|
92
|
+
def set(
|
|
93
|
+
self,
|
|
94
|
+
organisation_id: int,
|
|
95
|
+
session_id: str,
|
|
96
|
+
key: str,
|
|
97
|
+
value: Any,
|
|
98
|
+
classification: str | None = None,
|
|
99
|
+
) -> VaultSetResponse:
|
|
100
|
+
"""Create or overwrite a vault entry. The body is the raw JSON value.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
organisation_id: The organisation ID.
|
|
104
|
+
session_id: The session whose vault to write to.
|
|
105
|
+
key: The entry key.
|
|
106
|
+
value: Any JSON-serializable value (dict, list, or scalar).
|
|
107
|
+
classification: One of ``public``, ``internal``, ``confidential``,
|
|
108
|
+
``restricted``. Defaults server-side to ``restricted`` when
|
|
109
|
+
omitted. See ``session_vault_dto.Classification``.
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
ValueError: If the key is invalid (raised before any network call).
|
|
113
|
+
requests.HTTPError: 400 if the classification is unknown.
|
|
114
|
+
"""
|
|
115
|
+
_validate_key(key)
|
|
116
|
+
params = {"o": str(organisation_id)}
|
|
117
|
+
if classification is not None:
|
|
118
|
+
params["classification"] = classification
|
|
119
|
+
result = self._make_request("PUT", f"/{session_id}/vault/{key}", data=value, params=params)
|
|
120
|
+
return VaultSetResponse(**result)
|
|
121
|
+
|
|
122
|
+
def delete(self, organisation_id: int, session_id: str, key: str) -> None:
|
|
123
|
+
"""Delete a vault entry. Succeeds even if the entry does not exist.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
organisation_id: The organisation ID.
|
|
127
|
+
session_id: The session whose vault to delete from.
|
|
128
|
+
key: The entry key.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
ValueError: If the key is invalid (raised before any network call).
|
|
132
|
+
"""
|
|
133
|
+
_validate_key(key)
|
|
134
|
+
params = {"o": str(organisation_id)}
|
|
135
|
+
self._make_request("DELETE", f"/{session_id}/vault/{key}", params=params)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""DTOs for the session vault API (snake_case, matching the API).
|
|
2
|
+
|
|
3
|
+
The session vault is an organisation- and session-scoped key/value store of
|
|
4
|
+
serializable JSON, backed by object storage. Each entry carries a
|
|
5
|
+
classification controlling encryption and read access.
|
|
6
|
+
|
|
7
|
+
Wire format: the vault endpoints serialise with plain snake_case field names
|
|
8
|
+
(no camelCase), so these models use raw snake_case fields with no alias
|
|
9
|
+
generator. This intentionally follows the same convention as ``files_dto.py``
|
|
10
|
+
and ``datasets_dto.py`` — not the ``alias_generator=_to_camel`` convention used
|
|
11
|
+
by the camelCase APIs (datasource, ontology, rules). See CLAUDE.md ("DTOs")
|
|
12
|
+
for the split.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from enum import StrEnum
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from pydantic import BaseModel
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Classification(StrEnum):
|
|
22
|
+
"""Vault entry classification levels.
|
|
23
|
+
|
|
24
|
+
``public``/``internal`` are stored as plaintext and viewable by any org
|
|
25
|
+
member; ``confidential``/``restricted`` are encrypted at rest. Agents always
|
|
26
|
+
read plaintext; humans never see ``restricted`` and may view
|
|
27
|
+
``confidential`` only via an audited reveal.
|
|
28
|
+
|
|
29
|
+
A ``StrEnum`` so members are ``str`` (``Classification.PUBLIC == "public"``,
|
|
30
|
+
``str(Classification.PUBLIC) == "public"``) and serialise directly as query
|
|
31
|
+
params, while giving callers a typed, enumerable set of valid values.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
PUBLIC = "public"
|
|
35
|
+
INTERNAL = "internal"
|
|
36
|
+
CONFIDENTIAL = "confidential"
|
|
37
|
+
RESTRICTED = "restricted"
|
|
38
|
+
|
|
39
|
+
#: The default classification when none is supplied (most protective).
|
|
40
|
+
#: An alias of ``RESTRICTED`` (``Classification.DEFAULT is Classification.RESTRICTED``).
|
|
41
|
+
DEFAULT = RESTRICTED
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class VaultEntryMeta(BaseModel):
|
|
45
|
+
"""Metadata for one vault entry as returned by the list endpoint.
|
|
46
|
+
|
|
47
|
+
Never carries the value, so listing exposes nothing sensitive.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
key: str
|
|
51
|
+
#: Size of the stored payload in bytes (ciphertext size for encrypted entries).
|
|
52
|
+
size: int
|
|
53
|
+
updated_at: str
|
|
54
|
+
classification: str
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class VaultListResponse(BaseModel):
|
|
58
|
+
"""Response body for listing all entries in a session vault."""
|
|
59
|
+
|
|
60
|
+
entries: list[VaultEntryMeta]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class VaultEntryResponse(BaseModel):
|
|
64
|
+
"""A single vault entry's (decrypted) value."""
|
|
65
|
+
|
|
66
|
+
key: str
|
|
67
|
+
value: Any
|
|
68
|
+
classification: str
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class VaultSetResponse(BaseModel):
|
|
72
|
+
"""The stored entry's key and classification, returned by a write (PUT)."""
|
|
73
|
+
|
|
74
|
+
key: str
|
|
75
|
+
classification: str
|