onecli-sdk 0.1.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.
onecli/gateway.py ADDED
@@ -0,0 +1,454 @@
1
+ """Typed bodies of the errors the OneCLI gateway returns on proxied agent traffic.
2
+
3
+ The management API's errors use the ``{"error": {"code", "message"}}`` envelope
4
+ instead and are raised as :class:`onecli.OneCLIApiError`.
5
+
6
+ Agent requests reach providers through the gateway, so these bodies arrive on
7
+ ordinary HTTP responses inside agent code. Most carry ``x-should-retry:
8
+ false``: an unchanged retry will not succeed, and the fix is the one the body
9
+ names (add the connection header, attach the credential, open the URL).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Final, Literal, NotRequired, TypedDict, cast
15
+
16
+ __all__ = [
17
+ "CONNECTIONS_HEADER",
18
+ "CONNECTION_ID_HEADER",
19
+ "GATEWAY_ERROR_CODES",
20
+ "AccessRestrictedError",
21
+ "AppNotConnectedError",
22
+ "ApprovalStoreUnavailableError",
23
+ "BadGatewayError",
24
+ "BlockedByDefaultPolicyError",
25
+ "BlockedByPolicyError",
26
+ "CleartextRefusedError",
27
+ "ConnectionHostMismatchError",
28
+ "ConnectionNeedsReconnectError",
29
+ "ConnectionNotFoundError",
30
+ "CredentialNotFoundError",
31
+ "CredentialUnavailableError",
32
+ "DestinationLookupTimeoutError",
33
+ "DestinationNotAllowedError",
34
+ "GatewayConnectionChoice",
35
+ "GatewayError",
36
+ "GatewayRestartingError",
37
+ "GithubOrgAccessRequiredError",
38
+ "InvalidProxyTargetError",
39
+ "ManualApprovalDeniedError",
40
+ "MethodOverrideRefusedError",
41
+ "MultipleConnectionsError",
42
+ "MultipleProvidersError",
43
+ "ProxyNotServedError",
44
+ "RateLimitedError",
45
+ "ResolutionFailedError",
46
+ "ThrottledError",
47
+ "UnauthenticatedError",
48
+ "UpstreamTimeoutError",
49
+ "UpstreamUnreachableError",
50
+ "UseTlsError",
51
+ "parse_gateway_error",
52
+ ]
53
+
54
+
55
+ class GatewayConnectionChoice(TypedDict):
56
+ """One connectable account, as listed in disambiguation answers and ``x-onecli-connections``."""
57
+
58
+ id: str
59
+ label: str | None
60
+ provider: str
61
+ display_name: str | None
62
+ host: NotRequired[str]
63
+ """The host the account's credential is bound to. Only for providers that bind one."""
64
+
65
+
66
+ CONNECTION_ID_HEADER: Final = "x-onecli-connection-id"
67
+ """Request header naming which account a proxied request should use."""
68
+
69
+ CONNECTIONS_HEADER: Final = "x-onecli-connections"
70
+ """Response header listing the available accounts on forwarded answers.
71
+
72
+ A JSON array of :class:`GatewayConnectionChoice`.
73
+ """
74
+
75
+
76
+ class MultipleConnectionsError(TypedDict):
77
+ """409: two or more accounts of the same app could serve the request.
78
+
79
+ Send the same request again with :data:`CONNECTION_ID_HEADER` set to one
80
+ of the listed ``connections[].id``.
81
+ """
82
+
83
+ error: Literal["multiple_connections"]
84
+ message: str
85
+ connections: list[GatewayConnectionChoice]
86
+ header: str
87
+ example: str
88
+
89
+
90
+ class MultipleProvidersError(TypedDict):
91
+ """409: accounts of different apps both match the request. Retry as for multiple_connections."""
92
+
93
+ error: Literal["multiple_providers"]
94
+ message: str
95
+ connections: list[GatewayConnectionChoice]
96
+ header: str
97
+ example: str
98
+
99
+
100
+ class ConnectionNotFoundError(TypedDict):
101
+ """404: the id sent in :data:`CONNECTION_ID_HEADER` names no available connection.
102
+
103
+ It is stale or removed. Pick again from ``connections``.
104
+ """
105
+
106
+ error: Literal["connection_not_found"]
107
+ message: str
108
+ connections: list[GatewayConnectionChoice]
109
+ header: str
110
+
111
+
112
+ class ConnectionHostMismatchError(TypedDict):
113
+ """421: the request went to a host none of the agent's accounts is bound to.
114
+
115
+ Send it to the bound host instead.
116
+ """
117
+
118
+ error: Literal["connection_host_mismatch"]
119
+ message: str
120
+ requested_host: str
121
+ provider: str
122
+ connections: list[GatewayConnectionChoice]
123
+ header: str
124
+
125
+
126
+ class ConnectionNeedsReconnectError(TypedDict):
127
+ """401: the provider rejected the connection's saved login. ``connect_url`` reconnects it."""
128
+
129
+ error: Literal["connection_needs_reconnect"]
130
+ message: str
131
+ provider: str
132
+ connection_id: str
133
+ connect_url: str
134
+
135
+
136
+ class AccessRestrictedError(TypedDict):
137
+ """401/403 (the upstream status is kept): the agent cannot use the credential for this host.
138
+
139
+ ``manage_url`` opens the page that turns it on for the agent.
140
+ ``connect_url`` is set for apps, to connect another account.
141
+ """
142
+
143
+ error: Literal["access_restricted"]
144
+ message: str
145
+ provider: str
146
+ manage_url: str
147
+ connect_url: NotRequired[str]
148
+
149
+
150
+ class CredentialUnavailableError(TypedDict):
151
+ """401/403 (the upstream status is kept): the stored value could not be read.
152
+
153
+ The request went out without it. ``manage_url`` is where the value is entered again.
154
+ """
155
+
156
+ error: Literal["credential_unavailable"]
157
+ message: str
158
+ provider: str
159
+ manage_url: str
160
+
161
+
162
+ class CredentialNotFoundError(TypedDict):
163
+ """401/403 (the upstream status is kept): no credential exists for the host.
164
+
165
+ ``secret_url`` is a ready-made create link.
166
+ """
167
+
168
+ error: Literal["credential_not_found"]
169
+ message: str
170
+ hostname: str
171
+ path: str
172
+ secret_url: str
173
+
174
+
175
+ class AppNotConnectedError(TypedDict):
176
+ """401/403 (the upstream status is kept): no app is connected for this host.
177
+
178
+ ``provider`` is set for a known app, ``hostname`` for an unknown one.
179
+ """
180
+
181
+ error: Literal["app_not_connected"]
182
+ message: str
183
+ provider: NotRequired[str]
184
+ hostname: NotRequired[str]
185
+ connect_url: str
186
+
187
+
188
+ class GithubOrgAccessRequiredError(TypedDict):
189
+ """403: a GitHub organization refused the connection's token."""
190
+
191
+ error: Literal["github_org_access_required"]
192
+ message: str
193
+ provider: str
194
+ org: str
195
+ reason: Literal["approval_required", "sso_required"]
196
+ connect_url: str
197
+
198
+
199
+ class CleartextRefusedError(TypedDict):
200
+ """403: the gateway does not send a credential over plain HTTP."""
201
+
202
+ error: Literal["cleartext_refused"]
203
+ message: str
204
+ host: str
205
+ https_url: str
206
+
207
+
208
+ class BlockedByPolicyError(TypedDict):
209
+ """403: a policy rule blocked the request."""
210
+
211
+ error: Literal["blocked_by_policy"]
212
+ message: str
213
+ rule_name: str
214
+ method: str
215
+ path: str
216
+ dashboard_url: str
217
+
218
+
219
+ class BlockedByDefaultPolicyError(TypedDict):
220
+ """403: nothing allowed the request under a deny-by-default posture."""
221
+
222
+ error: Literal["blocked_by_default_policy"]
223
+ message: str
224
+ method: str
225
+ host: str
226
+ path: str
227
+ dashboard_url: str
228
+
229
+
230
+ class MethodOverrideRefusedError(TypedDict):
231
+ """403: the request asks the service to run it as another method.
232
+
233
+ A method override header or parameter. Send the real method instead.
234
+ """
235
+
236
+ error: Literal["method_override_refused"]
237
+ message: str
238
+ method: str
239
+ path: str
240
+ override: str
241
+
242
+
243
+ class RateLimitedError(TypedDict):
244
+ """429: a policy rule's rate limit was reached. Retry-After says when to retry."""
245
+
246
+ error: Literal["rate_limited"]
247
+ message: str
248
+ limit: int
249
+ window: str
250
+
251
+
252
+ class ManualApprovalDeniedError(TypedDict):
253
+ """403: a person declined the request, or its approval expired."""
254
+
255
+ error: Literal["manual_approval_denied"]
256
+ message: str
257
+ reason: Literal["declined", "expired"]
258
+ approval_id: str
259
+
260
+
261
+ class GatewayRestartingError(TypedDict):
262
+ """503: the gateway restarted while the request waited for approval."""
263
+
264
+ error: Literal["gateway_restarting"]
265
+ message: str
266
+ approval_id: str
267
+
268
+
269
+ class ApprovalStoreUnavailableError(TypedDict):
270
+ """502: the approval service could not be reached. Do not retry on your own."""
271
+
272
+ error: Literal["approval_store_unavailable"]
273
+ message: str
274
+ approval_id: NotRequired[str]
275
+
276
+
277
+ class DestinationNotAllowedError(TypedDict):
278
+ """403: the destination resolves to a private, loopback or link-local address."""
279
+
280
+ error: Literal["destination_not_allowed"]
281
+ message: str
282
+ host: str
283
+
284
+
285
+ class DestinationLookupTimeoutError(TypedDict):
286
+ """504: the destination could not be looked up in time. Safe to send again."""
287
+
288
+ error: Literal["destination_lookup_timeout"]
289
+ message: str
290
+ host: str
291
+
292
+
293
+ class UpstreamUnreachableError(TypedDict):
294
+ """502: the destination could not be reached (DNS, connection or TLS)."""
295
+
296
+ error: Literal["upstream_unreachable"]
297
+ message: str
298
+ host: str
299
+
300
+
301
+ class UpstreamTimeoutError(TypedDict):
302
+ """504: the destination took too long to answer. It may have run the request."""
303
+
304
+ error: Literal["upstream_timeout"]
305
+ message: str
306
+
307
+
308
+ class ResolutionFailedError(TypedDict):
309
+ """502: the gateway could not work out the rules for this request."""
310
+
311
+ error: Literal["resolution_failed"]
312
+ message: str
313
+
314
+
315
+ class BadGatewayError(TypedDict):
316
+ """502: an error inside the gateway."""
317
+
318
+ error: Literal["bad_gateway"]
319
+ message: str
320
+
321
+
322
+ class InvalidProxyTargetError(TypedDict):
323
+ """400: the proxy target is not a plain host[:port]."""
324
+
325
+ error: Literal["invalid_proxy_target"]
326
+ message: str
327
+
328
+
329
+ class ProxyNotServedError(TypedDict):
330
+ """400: this gateway port does not serve proxy requests."""
331
+
332
+ error: Literal["proxy_not_served"]
333
+ message: str
334
+
335
+
336
+ class UseTlsError(TypedDict):
337
+ """401/407: the agent credential was sent in plain text to a gateway that takes TLS only.
338
+
339
+ Use the https proxy URL.
340
+ """
341
+
342
+ error: Literal["use_tls"]
343
+ message: str
344
+
345
+
346
+ class UnauthenticatedError(TypedDict):
347
+ """401: no agent credential, or one that did not check out."""
348
+
349
+ error: Literal["unauthenticated"]
350
+ message: str
351
+
352
+
353
+ class ThrottledError(TypedDict):
354
+ """429: too many refused credentials from this address. Retry-After says when."""
355
+
356
+ error: Literal["throttled"]
357
+ message: str
358
+
359
+
360
+ GatewayError = (
361
+ MultipleConnectionsError
362
+ | MultipleProvidersError
363
+ | ConnectionNotFoundError
364
+ | ConnectionHostMismatchError
365
+ | ConnectionNeedsReconnectError
366
+ | AccessRestrictedError
367
+ | CredentialUnavailableError
368
+ | CredentialNotFoundError
369
+ | AppNotConnectedError
370
+ | GithubOrgAccessRequiredError
371
+ | CleartextRefusedError
372
+ | BlockedByPolicyError
373
+ | BlockedByDefaultPolicyError
374
+ | MethodOverrideRefusedError
375
+ | RateLimitedError
376
+ | ManualApprovalDeniedError
377
+ | GatewayRestartingError
378
+ | ApprovalStoreUnavailableError
379
+ | DestinationNotAllowedError
380
+ | DestinationLookupTimeoutError
381
+ | UpstreamUnreachableError
382
+ | UpstreamTimeoutError
383
+ | ResolutionFailedError
384
+ | BadGatewayError
385
+ | InvalidProxyTargetError
386
+ | ProxyNotServedError
387
+ | UseTlsError
388
+ | UnauthenticatedError
389
+ | ThrottledError
390
+ )
391
+ """Any error body the gateway writes. Narrow it on ``error``."""
392
+
393
+ GATEWAY_ERROR_CODES: Final = frozenset(
394
+ {
395
+ "multiple_connections",
396
+ "multiple_providers",
397
+ "connection_not_found",
398
+ "connection_host_mismatch",
399
+ "connection_needs_reconnect",
400
+ "access_restricted",
401
+ "credential_unavailable",
402
+ "credential_not_found",
403
+ "app_not_connected",
404
+ "github_org_access_required",
405
+ "cleartext_refused",
406
+ "blocked_by_policy",
407
+ "blocked_by_default_policy",
408
+ "method_override_refused",
409
+ "rate_limited",
410
+ "manual_approval_denied",
411
+ "gateway_restarting",
412
+ "approval_store_unavailable",
413
+ "destination_not_allowed",
414
+ "destination_lookup_timeout",
415
+ "upstream_unreachable",
416
+ "upstream_timeout",
417
+ "resolution_failed",
418
+ "bad_gateway",
419
+ "invalid_proxy_target",
420
+ "proxy_not_served",
421
+ "use_tls",
422
+ "unauthenticated",
423
+ "throttled",
424
+ }
425
+ )
426
+ """Every ``error`` code of :data:`GatewayError`. A test keeps the two the same."""
427
+
428
+
429
+ def parse_gateway_error(body: object) -> GatewayError | None:
430
+ """Narrow an already-parsed answer body to a typed gateway error.
431
+
432
+ None when the body is not one: an ordinary provider error, a management
433
+ API envelope, or not an object. A gateway body always has a string
434
+ ``message``, so a provider body that only shares a code name, like
435
+ ``{"error": "rate_limited"}``, is not taken for one.
436
+
437
+ ```python
438
+ response = httpx.get("https://gmail.googleapis.com/gmail/v1/users/me")
439
+ if response.is_error:
440
+ error = parse_gateway_error(response.json())
441
+ if error is not None and error["error"] == "multiple_connections":
442
+ # Send again with {CONNECTION_ID_HEADER: error["connections"][0]["id"]}.
443
+ ...
444
+ ```
445
+ """
446
+ if not isinstance(body, dict):
447
+ return None
448
+ fields = cast("dict[str, object]", body)
449
+ code = fields.get("error")
450
+ if not isinstance(code, str) or not isinstance(fields.get("message"), str):
451
+ return None
452
+ if code not in GATEWAY_ERROR_CODES:
453
+ return None
454
+ return cast("GatewayError", body)
onecli/py.typed ADDED
File without changes
@@ -0,0 +1,229 @@
1
+ """The shapes of the OneCLI API: what calls answer and what nested inputs take.
2
+
3
+ Every model here is made from the server's API description (openapi/v2.json),
4
+ the way node-sdk's ``v2/types.ts`` is. Attributes have Python names
5
+ (``vault.agent_count``); ``model_dump(by_alias=True)`` gives the API's names.
6
+ A field or enum value the SDK does not know yet is kept, never refused.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Generic, Literal, TypeVar
12
+
13
+ from pydantic import Field
14
+
15
+ from onecli.types._base import Model
16
+ from onecli.types._openapi import (
17
+ Activity,
18
+ Agent,
19
+ AgentCheck,
20
+ AgentCheckUnknown,
21
+ AgentCreatedBy,
22
+ AgentGateway,
23
+ AgentItem,
24
+ AgentSelf,
25
+ AgentVault,
26
+ ApiKeyCreate,
27
+ Approval,
28
+ ApprovalDecided,
29
+ AppTarget,
30
+ ConnectionTarget,
31
+ ConnectToken,
32
+ CreatedAgent,
33
+ CreatedConnectToken,
34
+ CreatedOneUseConnectToken,
35
+ Error,
36
+ ErrorDetail,
37
+ GroupRuleIdentity,
38
+ HeaderInjection,
39
+ Health,
40
+ Item,
41
+ ItemDetails,
42
+ ItemPermissions,
43
+ ItemVersion,
44
+ ItemVersionRestored,
45
+ KeptAgent,
46
+ Key,
47
+ LlmKeyCreate,
48
+ NetworkTarget,
49
+ OneUseConnectToken,
50
+ OrgRule,
51
+ OrgRuleAppTarget,
52
+ OrgRuleCondition,
53
+ OrgRuleConnectionTarget,
54
+ OrgRuleIdentity,
55
+ OrgRuleNetworkTarget,
56
+ OrgRuleSecretTarget,
57
+ PathRegexInjection,
58
+ PathTemplateInjection,
59
+ PermissionSummary,
60
+ QueryParamInjection,
61
+ SecretTarget,
62
+ ToolPermission,
63
+ ToolPermissionWrite,
64
+ Usage,
65
+ UserRuleIdentity,
66
+ Vault,
67
+ VaultMember,
68
+ VaultRuleIdentity,
69
+ )
70
+
71
+ __all__ = [
72
+ "Activity",
73
+ "ActivityResult",
74
+ "Agent",
75
+ "AgentCheck",
76
+ "AgentCheckDecision",
77
+ "AgentCheckUnknown",
78
+ "AgentCreatedBy",
79
+ "AgentGateway",
80
+ "AgentItem",
81
+ "AgentItemRequest",
82
+ "AgentRuntime",
83
+ "AgentSelf",
84
+ "AgentStatus",
85
+ "AgentVault",
86
+ "ApiErrorBody",
87
+ "ApiErrorCode",
88
+ "ApiErrorDetail",
89
+ "ApiKeyCreate",
90
+ "AppTarget",
91
+ "Approval",
92
+ "ApprovalDecided",
93
+ "ApprovalDecision",
94
+ "ApprovalList",
95
+ "ConnectToken",
96
+ "ConnectionTarget",
97
+ "CreatedAgent",
98
+ "CreatedConnectToken",
99
+ "CreatedOneUseConnectToken",
100
+ "GroupRuleIdentity",
101
+ "HeaderInjection",
102
+ "Health",
103
+ "InjectionConfig",
104
+ "Item",
105
+ "ItemDetails",
106
+ "ItemKind",
107
+ "ItemPermissions",
108
+ "ItemState",
109
+ "ItemVersion",
110
+ "ItemVersionRestored",
111
+ "KeptAgent",
112
+ "Key",
113
+ "LlmKeyCreate",
114
+ "LlmProvider",
115
+ "Model",
116
+ "NetworkTarget",
117
+ "OneUseConnectToken",
118
+ "OrgRule",
119
+ "OrgRuleAction",
120
+ "OrgRuleAppTarget",
121
+ "OrgRuleCondition",
122
+ "OrgRuleConnectionTarget",
123
+ "OrgRuleIdentity",
124
+ "OrgRuleIdentityInput",
125
+ "OrgRuleNetworkTarget",
126
+ "OrgRuleSecretTarget",
127
+ "OrgRuleTarget",
128
+ "OrgRuleTargetInput",
129
+ "Page",
130
+ "PathRegexInjection",
131
+ "PathTemplateInjection",
132
+ "PermissionLevel",
133
+ "PermissionSummary",
134
+ "QueryParamInjection",
135
+ "RateLimitWindow",
136
+ "SecretTarget",
137
+ "ToolPermission",
138
+ "ToolPermissionWrite",
139
+ "Usage",
140
+ "UsageDays",
141
+ "UserRuleIdentity",
142
+ "Vault",
143
+ "VaultMember",
144
+ "VaultRuleIdentity",
145
+ ]
146
+
147
+ _T = TypeVar("_T")
148
+
149
+
150
+ class Page(Model, Generic[_T]):
151
+ """One page of a list. Pass ``next_cursor`` as ``cursor`` for the next page."""
152
+
153
+ data: list[_T]
154
+ next_cursor: str | None = Field(alias="nextCursor")
155
+
156
+
157
+ class ApprovalList(Model):
158
+ """The requests waiting for a person."""
159
+
160
+ data: list[Approval]
161
+ truncated: bool
162
+ """True: you can use more vaults than one call reads. Name a vault to read it."""
163
+
164
+
165
+ class AgentItemRequest(Model):
166
+ """What ``agent.request(service)`` gives: a link for the agent's person."""
167
+
168
+ service: str
169
+ vault_id: str = Field(alias="vaultId")
170
+ path: str
171
+ """The dashboard path.
172
+
173
+ For an app id (no dot, like ``github``): the app's connect step in the
174
+ agent's vault, naming the agent. For a host: the vault.
175
+ """
176
+ url: str | None
177
+ """The full link, or None when the dashboard's address is not known."""
178
+ message: str
179
+ """A line to show the person."""
180
+
181
+
182
+ # Names for the server's own error shape, as node-sdk has them.
183
+ ApiErrorBody = Error
184
+ ApiErrorDetail = ErrorDetail
185
+ ApiErrorCode = Literal[
186
+ "bad_request",
187
+ "validation_failed",
188
+ "unauthenticated",
189
+ "forbidden",
190
+ "not_found",
191
+ "conflict",
192
+ "gone",
193
+ "idempotency_conflict",
194
+ "precondition_required",
195
+ "rate_limited",
196
+ "authorization_pending",
197
+ "slow_down",
198
+ "access_denied",
199
+ "expired_token",
200
+ "internal",
201
+ "unavailable",
202
+ ]
203
+
204
+ # The enums of the API, by name. A test keeps each one equal to the spec's.
205
+ ItemKind = Literal["app", "api_key", "llm_key"]
206
+ ItemState = Literal["ready", "reauth_required", "disconnected"]
207
+ PermissionLevel = Literal["allow", "ask", "never"]
208
+ AgentStatus = Literal["active", "expired"]
209
+ AgentRuntime = Literal["docker", "linux", "macos", "windows"]
210
+ ApprovalDecision = Literal["approve", "deny", "always_allow"]
211
+ ActivityResult = Literal["allowed", "blocked", "approval", "rate_limited"]
212
+ AgentCheckDecision = Literal[
213
+ "allowed", "blocked", "needs_approval", "no_item", "destination_refused", "unknown"
214
+ ]
215
+ LlmProvider = Literal["anthropic", "openai"]
216
+ OrgRuleAction = Literal["allow", "block"]
217
+ RateLimitWindow = Literal["minute", "hour", "day"]
218
+ UsageDays = Literal[4, 30]
219
+
220
+ InjectionConfig = HeaderInjection | QueryParamInjection | PathTemplateInjection | PathRegexInjection
221
+ """How an API key goes into a request: a header, a query parameter, or the path."""
222
+ OrgRuleTarget = (
223
+ OrgRuleAppTarget | OrgRuleConnectionTarget | OrgRuleSecretTarget | OrgRuleNetworkTarget
224
+ )
225
+ """What a rule is about, as the server answers it."""
226
+ OrgRuleTargetInput = AppTarget | ConnectionTarget | SecretTarget | NetworkTarget
227
+ """What a rule is about, as you write it."""
228
+ OrgRuleIdentityInput = UserRuleIdentity | GroupRuleIdentity | VaultRuleIdentity
229
+ """Who a rule is for, as you write it."""