identark 1.2.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.
identark/__init__.py ADDED
@@ -0,0 +1,68 @@
1
+ """
2
+ identark
3
+ ~~~~~~~~~~~~~~
4
+ The AgentGateway Protocol — secure, scalable agent execution infrastructure.
5
+
6
+ Quick start::
7
+
8
+ # Local development
9
+ from openai import AsyncOpenAI
10
+ from identark import DirectGateway, Message, Role
11
+
12
+ gateway = DirectGateway(
13
+ llm_client=AsyncOpenAI(),
14
+ model="gpt-4o",
15
+ )
16
+ response = await gateway.invoke_llm(
17
+ new_messages=[Message(role=Role.USER, content="Hello!")]
18
+ )
19
+
20
+ # Production — two line change, agent code identical
21
+ from identark import ControlPlaneGateway
22
+ gateway = ControlPlaneGateway() # auto-detects env vars in sandbox
23
+
24
+ Full documentation: https://github.com/identark/identark#readme
25
+ GitHub: https://github.com/identark/identark
26
+ """
27
+
28
+ from identark.gateway import AgentGateway
29
+ from identark.gateways.control_plane import ControlPlaneGateway
30
+ from identark.gateways.direct import DirectGateway
31
+ from identark.models import (
32
+ Function,
33
+ LLMResponse,
34
+ Message,
35
+ PresignedURL,
36
+ Role,
37
+ StreamChunk,
38
+ TokenUsage,
39
+ ToolCall,
40
+ )
41
+ from identark.pricing import estimate_cost, get_pricing, set_pricing_table
42
+
43
+ __version__ = "1.2.0"
44
+ __author__ = "Gold Okpa"
45
+ __license__ = "AGPL-3.0-only"
46
+
47
+ __all__ = [
48
+ # Protocol
49
+ "AgentGateway",
50
+ # Implementations
51
+ "DirectGateway",
52
+ "ControlPlaneGateway",
53
+ # Models
54
+ "Message",
55
+ "Role",
56
+ "LLMResponse",
57
+ "StreamChunk",
58
+ "PresignedURL",
59
+ "TokenUsage",
60
+ "ToolCall",
61
+ "Function",
62
+ # Utilities
63
+ "estimate_cost",
64
+ "get_pricing",
65
+ "set_pricing_table",
66
+ # Meta
67
+ "__version__",
68
+ ]
identark/exceptions.py ADDED
@@ -0,0 +1,214 @@
1
+ """
2
+ identark.exceptions
3
+ ~~~~~~~~~~~~~~~~~~~~~
4
+ All exceptions raised by the SDK. Rooted at ``IdentArkError`` so
5
+ callers can catch broadly or specifically.
6
+
7
+ Hierarchy
8
+ ---------
9
+ IdentArkError
10
+ ├── GatewayError
11
+ │ ├── ControlPlaneError
12
+ │ │ ├── AuthenticationError
13
+ │ │ ├── CostCapExceededError
14
+ │ │ └── SessionNotFoundError
15
+ │ └── NetworkError
16
+ ├── LLMError
17
+ │ ├── RateLimitError
18
+ │ ├── ContentPolicyError
19
+ │ └── ProviderError
20
+ ├── FileError
21
+ │ ├── PathNotAllowedError
22
+ │ └── PresignedURLExpiredError
23
+ └── ConfigurationError
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+
29
+ class IdentArkError(Exception):
30
+ """Base class for all SDK exceptions."""
31
+
32
+
33
+ # ── Gateway ───────────────────────────────────────────────────────────────────
34
+
35
+
36
+ class GatewayError(IdentArkError):
37
+ """Raised when a gateway communication operation fails."""
38
+
39
+
40
+ class ControlPlaneError(GatewayError):
41
+ """
42
+ The control plane returned an error response.
43
+
44
+ Attributes:
45
+ status_code: HTTP status code from the control plane.
46
+ error_code: Machine-readable error code string.
47
+ message: Human-readable error description.
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ message: str,
53
+ status_code: int = 0,
54
+ error_code: str = "unknown",
55
+ ) -> None:
56
+ super().__init__(message)
57
+ self.status_code = status_code
58
+ self.error_code = error_code
59
+ self.message = message
60
+
61
+
62
+ class AuthenticationError(ControlPlaneError):
63
+ """
64
+ Session token is invalid or has expired.
65
+
66
+ Attributes:
67
+ session_id: The session ID associated with the failed token.
68
+ reason: A short description of why authentication failed.
69
+ """
70
+
71
+ def __init__(self, message: str, session_id: str = "", reason: str = "") -> None:
72
+ super().__init__(message, status_code=401, error_code="authentication_failed")
73
+ self.session_id = session_id
74
+ self.reason = reason
75
+
76
+
77
+ class CostCapExceededError(ControlPlaneError):
78
+ """
79
+ The session has reached its configured cost cap.
80
+
81
+ Attributes:
82
+ cap_usd: The configured cost ceiling in USD.
83
+ consumed_usd: How much has been spent in this session.
84
+ session_id: The session that hit the cap.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ message: str,
90
+ cap_usd: float = 0.0,
91
+ consumed_usd: float = 0.0,
92
+ session_id: str = "",
93
+ ) -> None:
94
+ super().__init__(message, status_code=402, error_code="cost_cap_exceeded")
95
+ self.cap_usd = cap_usd
96
+ self.consumed_usd = consumed_usd
97
+ self.session_id = session_id
98
+
99
+
100
+ class SessionNotFoundError(ControlPlaneError):
101
+ """Session ID does not exist or has already been terminated."""
102
+
103
+ def __init__(self, session_id: str) -> None:
104
+ super().__init__(
105
+ f"Session '{session_id}' not found or already terminated.",
106
+ status_code=404,
107
+ error_code="session_not_found",
108
+ )
109
+ self.session_id = session_id
110
+
111
+
112
+ class NetworkError(GatewayError):
113
+ """
114
+ All retry attempts to the control plane were exhausted.
115
+
116
+ Attributes:
117
+ attempts: Number of attempts made before giving up.
118
+ last_status_code: HTTP status from the final attempt, if any.
119
+ """
120
+
121
+ def __init__(
122
+ self,
123
+ message: str,
124
+ attempts: int = 0,
125
+ last_status_code: int | None = None,
126
+ ) -> None:
127
+ super().__init__(message)
128
+ self.attempts = attempts
129
+ self.last_status_code = last_status_code
130
+
131
+
132
+ # ── LLM ──────────────────────────────────────────────────────────────────────
133
+
134
+
135
+ class LLMError(IdentArkError):
136
+ """Raised when the LLM provider returns an error."""
137
+
138
+
139
+ class RateLimitError(LLMError):
140
+ """
141
+ The LLM provider's rate limit has been hit.
142
+
143
+ Attributes:
144
+ retry_after_seconds: How long to wait before retrying.
145
+ provider: The provider that issued the rate limit.
146
+ """
147
+
148
+ def __init__(
149
+ self,
150
+ message: str,
151
+ retry_after_seconds: int = 60,
152
+ provider: str = "unknown",
153
+ ) -> None:
154
+ super().__init__(message)
155
+ self.retry_after_seconds = retry_after_seconds
156
+ self.provider = provider
157
+
158
+
159
+ class ContentPolicyError(LLMError):
160
+ """The request was blocked by the provider's content policy."""
161
+
162
+
163
+ class ProviderError(LLMError):
164
+ """An unclassified error returned by the LLM provider."""
165
+
166
+
167
+ # ── File ──────────────────────────────────────────────────────────────────────
168
+
169
+
170
+ class FileError(IdentArkError):
171
+ """Raised when a file operation fails."""
172
+
173
+
174
+ class PathNotAllowedError(FileError):
175
+ """
176
+ The requested file path is outside the allowed workspace.
177
+
178
+ Attributes:
179
+ attempted_path: The path the agent attempted to access.
180
+ allowed_prefix: The only permitted path prefix.
181
+ """
182
+
183
+ def __init__(self, attempted_path: str, allowed_prefix: str = "/workspace/") -> None:
184
+ super().__init__(
185
+ f"Path '{attempted_path}' is not allowed. "
186
+ f"File paths must start with '{allowed_prefix}'."
187
+ )
188
+ self.attempted_path = attempted_path
189
+ self.allowed_prefix = allowed_prefix
190
+
191
+
192
+ class PresignedURLExpiredError(FileError):
193
+ """
194
+ The presigned URL was used after its expiry timestamp.
195
+
196
+ Attributes:
197
+ file_path: The workspace path the URL was for.
198
+ expired_at: ISO 8601 expiry timestamp from the original URL.
199
+ """
200
+
201
+ def __init__(self, file_path: str, expired_at: str) -> None:
202
+ super().__init__(
203
+ f"Presigned URL for '{file_path}' expired at {expired_at}. "
204
+ "Request a new URL via gateway.request_file_url()."
205
+ )
206
+ self.file_path = file_path
207
+ self.expired_at = expired_at
208
+
209
+
210
+ # ── Config ────────────────────────────────────────────────────────────────────
211
+
212
+
213
+ class ConfigurationError(IdentArkError):
214
+ """The gateway was misconfigured at initialisation time."""
identark/gateway.py ADDED
@@ -0,0 +1,158 @@
1
+ """
2
+ identark.gateway
3
+ ~~~~~~~~~~~~~~~~~~
4
+ The AgentGateway Protocol — the core interface of the SDK.
5
+
6
+ Any class that implements the four methods below is a valid gateway,
7
+ whether it comes from this SDK or not. Python's structural subtyping
8
+ (typing.Protocol) means no explicit inheritance is required.
9
+
10
+ Usage::
11
+
12
+ from identark import AgentGateway
13
+
14
+ def run_agent(gateway: AgentGateway) -> None:
15
+ # Works with DirectGateway, ControlPlaneGateway, MockGateway,
16
+ # or any custom implementation.
17
+ ...
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from collections.abc import AsyncGenerator
23
+ from typing import Any, Protocol, runtime_checkable
24
+
25
+ from identark.models import LLMResponse, Message, PresignedURL, StreamChunk
26
+
27
+
28
+ @runtime_checkable
29
+ class AgentGateway(Protocol):
30
+ """
31
+ The AgentGateway protocol defines how an agent communicates
32
+ with the outside world.
33
+
34
+ Implement this protocol to create a custom gateway for any backend.
35
+ All four methods must be ``async``.
36
+
37
+ The gateway is the single boundary between your agent logic and
38
+ everything external: LLM providers, file storage, cost tracking.
39
+ Agents built against this protocol hold no secrets and maintain
40
+ no persistent state themselves.
41
+ """
42
+
43
+ async def invoke_llm(
44
+ self,
45
+ new_messages: list[Message],
46
+ tools: list[dict[str, Any]] | None = None,
47
+ tool_choice: str | dict[str, Any] = "auto",
48
+ ) -> LLMResponse:
49
+ """
50
+ Send new messages to the LLM and receive a response.
51
+
52
+ The gateway is responsible for maintaining and reconstructing
53
+ the full conversation history. Callers should pass only the
54
+ *new* messages for this turn — do not include prior history.
55
+
56
+ Args:
57
+ new_messages: New messages to send this turn.
58
+ tools: OpenAI-format tool/function definitions.
59
+ Pass ``None`` if no tools are available.
60
+ tool_choice: Tool selection mode. One of ``'auto'``,
61
+ ``'none'``, ``'required'``, or a specific
62
+ tool dict ``{"type": "function", "function": {"name": "…"}}``.
63
+
64
+ Returns:
65
+ An :class:`~identark.models.LLMResponse` containing the
66
+ assistant message, cost, finish reason, and token usage.
67
+
68
+ Raises:
69
+ CostCapExceededError: If the session cost cap has been reached.
70
+ RateLimitError: If the provider rate-limits the request.
71
+ LLMError: For any other provider-level error.
72
+ NetworkError: If all retry attempts to the control
73
+ plane are exhausted.
74
+ """
75
+ ...
76
+
77
+ async def persist_messages(self, messages: list[Message]) -> None:
78
+ """
79
+ Persist messages to conversation history without invoking the LLM.
80
+
81
+ Use this to store tool call results, system context, or any
82
+ messages you want the agent to remember on future turns without
83
+ generating a new LLM response.
84
+
85
+ Args:
86
+ messages: Messages to persist. Can include any role.
87
+
88
+ Raises:
89
+ GatewayError: If persistence fails.
90
+ """
91
+ ...
92
+
93
+ async def request_file_url(
94
+ self,
95
+ file_path: str,
96
+ method: str = "PUT",
97
+ ) -> PresignedURL:
98
+ """
99
+ Request a presigned URL for reading or writing a workspace file.
100
+
101
+ The agent never holds cloud storage credentials. The gateway
102
+ generates a time-limited, path-scoped URL on demand.
103
+
104
+ Args:
105
+ file_path: Absolute path to the file in the sandbox workspace.
106
+ Must start with ``/workspace/``.
107
+ method: ``'PUT'`` for upload, ``'GET'`` for download.
108
+
109
+ Returns:
110
+ A :class:`~identark.models.PresignedURL` with the URL,
111
+ expiry timestamp, method, and resolved file path.
112
+
113
+ Raises:
114
+ PathNotAllowedError: If ``file_path`` is outside ``/workspace/``.
115
+ FileError: For any other file-related error.
116
+ """
117
+ ...
118
+
119
+ async def get_session_cost(self) -> float:
120
+ """
121
+ Return the total cost in USD consumed by this session so far.
122
+
123
+ Reflects all :meth:`invoke_llm` calls made through this gateway
124
+ instance. With :class:`~identark.gateways.ControlPlaneGateway`,
125
+ this queries the control plane for the authoritative total.
126
+
127
+ Returns:
128
+ Total accumulated cost in USD as a ``float``.
129
+ """
130
+ ...
131
+
132
+ async def invoke_llm_stream(
133
+ self,
134
+ new_messages: list[Message],
135
+ tools: list[dict[str, Any]] | None = None,
136
+ tool_choice: str | dict[str, Any] = "auto",
137
+ ) -> AsyncGenerator[StreamChunk, None]:
138
+ """
139
+ Stream a response from the LLM token by token.
140
+
141
+ Yields :class:`~identark.models.StreamChunk` objects as they arrive.
142
+ The final chunk has ``finish_reason`` set and ``input_tokens`` /
143
+ ``output_tokens`` populated. All prior chunks have ``finish_reason=None``.
144
+
145
+ Args:
146
+ new_messages: New messages to send this turn.
147
+ tools: OpenAI-format tool/function definitions.
148
+ tool_choice: Tool selection mode.
149
+
150
+ Yields:
151
+ :class:`~identark.models.StreamChunk` — one per token delta.
152
+
153
+ Raises:
154
+ CostCapExceededError: If the session cost cap has been reached.
155
+ RateLimitError: If the provider rate-limits the request.
156
+ ContentPolicyError: If the output is blocked by content filtering.
157
+ """
158
+ ...
@@ -0,0 +1,4 @@
1
+ from identark.gateways.control_plane import ControlPlaneGateway
2
+ from identark.gateways.direct import DirectGateway
3
+
4
+ __all__ = ["DirectGateway", "ControlPlaneGateway"]