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/__init__.py +97 -0
- onecli/_agent_env.py +238 -0
- onecli/_async/__init__.py +1 -0
- onecli/_async/_client.py +431 -0
- onecli/_async/_connected_agent.py +184 -0
- onecli/_async/_http.py +330 -0
- onecli/_async/_io.py +118 -0
- onecli/_async/_resources.py +1293 -0
- onecli/_errors.py +106 -0
- onecli/_js.py +122 -0
- onecli/_keys.py +101 -0
- onecli/_lifetime.py +110 -0
- onecli/_retry.py +116 -0
- onecli/_sync/__init__.py +1 -0
- onecli/_sync/_client.py +426 -0
- onecli/_sync/_connected_agent.py +185 -0
- onecli/_sync/_http.py +329 -0
- onecli/_sync/_io.py +110 -0
- onecli/_sync/_resources.py +1286 -0
- onecli/_url.py +264 -0
- onecli/_version.py +19 -0
- onecli/_wire.py +469 -0
- onecli/gateway.py +454 -0
- onecli/py.typed +0 -0
- onecli/types/__init__.py +229 -0
- onecli/types/_base.py +42 -0
- onecli/types/_openapi.py +1590 -0
- onecli_sdk-0.1.0.dist-info/METADATA +354 -0
- onecli_sdk-0.1.0.dist-info/RECORD +31 -0
- onecli_sdk-0.1.0.dist-info/WHEEL +4 -0
- onecli_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
onecli/_sync/_client.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
# Made from src/onecli/_async/_client.py by scripts/gen_sync.py. Do not edit.
|
|
2
|
+
"""The two parts of the client: the owner part and the agent part."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from typing import TYPE_CHECKING, Final, NoReturn, Self, cast
|
|
9
|
+
|
|
10
|
+
from onecli._errors import OneCLIApiError, OneCLIError
|
|
11
|
+
from onecli._js import JS_SPACE_CLASS, js_length, js_trim
|
|
12
|
+
from onecli._keys import assert_agent_credential, assert_connect_token, assert_owner_key
|
|
13
|
+
from onecli._retry import DEFAULT_MAX_RETRIES
|
|
14
|
+
from onecli._sync._http import Http
|
|
15
|
+
from onecli._sync._resources import (
|
|
16
|
+
Activities,
|
|
17
|
+
Agents,
|
|
18
|
+
Approvals,
|
|
19
|
+
Items,
|
|
20
|
+
Keys,
|
|
21
|
+
OrgRules,
|
|
22
|
+
Vaults,
|
|
23
|
+
create_agent,
|
|
24
|
+
paginate,
|
|
25
|
+
)
|
|
26
|
+
from onecli._url import parse_http_url
|
|
27
|
+
from onecli._wire import DEFAULT_TIMEOUT, DEFAULT_URL, ResponseHook, decode, form_query, seg
|
|
28
|
+
from onecli.types import (
|
|
29
|
+
AgentCheck,
|
|
30
|
+
AgentCheckUnknown,
|
|
31
|
+
AgentItem,
|
|
32
|
+
AgentItemRequest,
|
|
33
|
+
AgentRuntime,
|
|
34
|
+
AgentSelf,
|
|
35
|
+
CreatedAgent,
|
|
36
|
+
Health,
|
|
37
|
+
KeptAgent,
|
|
38
|
+
Page,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
if TYPE_CHECKING:
|
|
42
|
+
from collections.abc import Iterator
|
|
43
|
+
from datetime import datetime
|
|
44
|
+
from types import TracebackType
|
|
45
|
+
|
|
46
|
+
import httpx2
|
|
47
|
+
|
|
48
|
+
__all__ = ["OneCLI", "OneCLIAgent"]
|
|
49
|
+
|
|
50
|
+
# A service name or host, as `onecli request` takes it.
|
|
51
|
+
_SERVICE_RE: Final = re.compile(r"[a-z0-9][a-z0-9._-]{0,99}")
|
|
52
|
+
# An app id as the registry writes it (github, google-calendar): no dot.
|
|
53
|
+
_APP_ID_RE: Final = re.compile(r"[a-z0-9][a-z0-9-]{0,63}")
|
|
54
|
+
_ID_RE: Final = re.compile(r"[A-Za-z0-9_-]{1,64}")
|
|
55
|
+
_METHOD_RE: Final = re.compile(r"[A-Za-z]{1,16}")
|
|
56
|
+
# JavaScript's /^https?:\/\/[^\s/?#]+/i: ASCII letters in either case, its own spaces.
|
|
57
|
+
_CHECK_URL_RE: Final = re.compile(rf"[Hh][Tt][Tt][Pp][Ss]?://[^{JS_SPACE_CLASS}/?#]+")
|
|
58
|
+
_MAX_CHECK_URL: Final = 8192
|
|
59
|
+
_UNAVAILABLE: Final = 503
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _env(name: str) -> str | None:
|
|
63
|
+
value = os.environ.get(name)
|
|
64
|
+
return None if value is None or value == "" else value
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _field(value: object, name: str) -> object:
|
|
68
|
+
"""A key of a JSON object, or None when the value is not an object."""
|
|
69
|
+
return cast("dict[str, object]", value).get(name) if isinstance(value, dict) else None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _setting(*values: str | None, default: str) -> str:
|
|
73
|
+
"""The first value given, as node-sdk's ``??`` picks it: an empty string counts."""
|
|
74
|
+
return next((v for v in values if v is not None), default)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class OneCLIAgent:
|
|
78
|
+
"""The agent part: what an agent can do with its own credential.
|
|
79
|
+
|
|
80
|
+
It sees the items of its own vault, never a value, and nothing else. Close
|
|
81
|
+
it with ``close()`` or ``with`` when done.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
*,
|
|
87
|
+
credential: str | None = None,
|
|
88
|
+
url: str | None = None,
|
|
89
|
+
timeout: float | None = None,
|
|
90
|
+
max_retries: int | None = None,
|
|
91
|
+
on_response: ResponseHook | None = None,
|
|
92
|
+
http_client: httpx2.Client | None = None,
|
|
93
|
+
) -> None:
|
|
94
|
+
"""The agent part.
|
|
95
|
+
|
|
96
|
+
``credential`` falls back to ``ONECLI_AGENT_CREDENTIAL``; ``url`` to
|
|
97
|
+
``ONECLI_URL``, ``ONECLI_API_HOST``, then ``https://api.onecli.sh``.
|
|
98
|
+
The other settings are the owner part's (see :class:`OneCLI`).
|
|
99
|
+
"""
|
|
100
|
+
given = _setting(credential, _env("ONECLI_AGENT_CREDENTIAL"), default="")
|
|
101
|
+
assert_agent_credential(given)
|
|
102
|
+
base = _setting(url, _env("ONECLI_URL"), _env("ONECLI_API_HOST"), default=DEFAULT_URL)
|
|
103
|
+
self._http = Http(
|
|
104
|
+
base,
|
|
105
|
+
given,
|
|
106
|
+
timeout=DEFAULT_TIMEOUT if timeout is None else timeout,
|
|
107
|
+
max_retries=DEFAULT_MAX_RETRIES if max_retries is None else max_retries,
|
|
108
|
+
on_response=on_response,
|
|
109
|
+
http_client=http_client,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def status(self, *, timeout: float | None = None, max_retries: int | None = None) -> AgentSelf:
|
|
113
|
+
"""Which agent this is, its vault, and where its gateway is (``onecli status``)."""
|
|
114
|
+
data = self._http.json("GET", "/v2/agents/me", timeout=timeout, max_retries=max_retries)
|
|
115
|
+
return decode(AgentSelf, data)
|
|
116
|
+
|
|
117
|
+
def items(
|
|
118
|
+
self,
|
|
119
|
+
*,
|
|
120
|
+
limit: int | None = None,
|
|
121
|
+
cursor: str | None = None,
|
|
122
|
+
timeout: float | None = None,
|
|
123
|
+
max_retries: int | None = None,
|
|
124
|
+
) -> Page[AgentItem]:
|
|
125
|
+
"""One page of what this agent can use (``onecli items``). Never a value."""
|
|
126
|
+
data = self._http.json(
|
|
127
|
+
"GET",
|
|
128
|
+
"/v2/agents/me/items",
|
|
129
|
+
query={"limit": limit, "cursor": cursor},
|
|
130
|
+
timeout=timeout,
|
|
131
|
+
max_retries=max_retries,
|
|
132
|
+
)
|
|
133
|
+
return decode(Page[AgentItem], data)
|
|
134
|
+
|
|
135
|
+
def iterate_items(
|
|
136
|
+
self, *, timeout: float | None = None, max_retries: int | None = None
|
|
137
|
+
) -> Iterator[AgentItem]:
|
|
138
|
+
"""Every item this agent can use, page by page."""
|
|
139
|
+
|
|
140
|
+
def load(cursor: str | None) -> Page[AgentItem]:
|
|
141
|
+
return self.items(cursor=cursor, timeout=timeout, max_retries=max_retries)
|
|
142
|
+
|
|
143
|
+
return paginate(load)
|
|
144
|
+
|
|
145
|
+
def check(
|
|
146
|
+
self,
|
|
147
|
+
method: str,
|
|
148
|
+
url: str,
|
|
149
|
+
*,
|
|
150
|
+
timeout: float | None = None,
|
|
151
|
+
max_retries: int | None = None,
|
|
152
|
+
) -> AgentCheck | AgentCheckUnknown:
|
|
153
|
+
"""Ask what would happen to one call, without sending it (``onecli check``).
|
|
154
|
+
|
|
155
|
+
When the server cannot tell (503), the answer is ``decision="unknown"``.
|
|
156
|
+
"""
|
|
157
|
+
if not _METHOD_RE.fullmatch(method):
|
|
158
|
+
msg = "check: the method must be letters only, like GET."
|
|
159
|
+
raise OneCLIError(msg)
|
|
160
|
+
if not _CHECK_URL_RE.match(url) or js_length(url) > _MAX_CHECK_URL:
|
|
161
|
+
msg = "check: the url must be a full http or https address."
|
|
162
|
+
raise OneCLIError(msg)
|
|
163
|
+
try:
|
|
164
|
+
data = self._http.json(
|
|
165
|
+
"POST",
|
|
166
|
+
"/v2/agents/me/check",
|
|
167
|
+
body={"method": method.upper(), "url": url},
|
|
168
|
+
timeout=timeout,
|
|
169
|
+
max_retries=max_retries,
|
|
170
|
+
)
|
|
171
|
+
except OneCLIApiError as error:
|
|
172
|
+
if error.status_code != _UNAVAILABLE:
|
|
173
|
+
raise
|
|
174
|
+
return AgentCheckUnknown(decision="unknown", reason=error.reason)
|
|
175
|
+
return decode(AgentCheck, data)
|
|
176
|
+
|
|
177
|
+
def request(
|
|
178
|
+
self, service: str, *, timeout: float | None = None, max_retries: int | None = None
|
|
179
|
+
) -> AgentItemRequest:
|
|
180
|
+
"""A link for this agent's person to add an item for ``service`` to its vault.
|
|
181
|
+
|
|
182
|
+
The same link ``onecli request`` prints. For an app id (no dot, like
|
|
183
|
+
``github``) it opens that app's connect step, and names this agent so
|
|
184
|
+
the account connected there is switched on for it, as the gateway's
|
|
185
|
+
``connect_url`` does. For a host it opens the vault. It never asks for
|
|
186
|
+
a key.
|
|
187
|
+
"""
|
|
188
|
+
name = js_trim(service).lower()
|
|
189
|
+
if not _SERVICE_RE.fullmatch(name):
|
|
190
|
+
msg = "request: use a service name like github or a host like api.example.com."
|
|
191
|
+
raise OneCLIError(msg)
|
|
192
|
+
me = self.status(timeout=timeout, max_retries=max_retries)
|
|
193
|
+
vault = getattr(me, "vault", None)
|
|
194
|
+
vault_id = getattr(vault, "id", None)
|
|
195
|
+
if not isinstance(vault_id, str) or not _ID_RE.fullmatch(vault_id):
|
|
196
|
+
msg = "The server's vault id is not safe to use."
|
|
197
|
+
raise OneCLIError(msg)
|
|
198
|
+
path = f"/w/{seg(vault_id)}"
|
|
199
|
+
if _APP_ID_RE.fullmatch(name):
|
|
200
|
+
pairs = [("connect", name), ("source", "agent")]
|
|
201
|
+
agent_name = getattr(me, "name", None)
|
|
202
|
+
agent_id = getattr(me, "id", None)
|
|
203
|
+
if isinstance(agent_name, str) and agent_name:
|
|
204
|
+
pairs.append(("agent_name", agent_name))
|
|
205
|
+
if isinstance(agent_id, str) and agent_id:
|
|
206
|
+
pairs.append(("agent_id", agent_id))
|
|
207
|
+
path += f"/connections?{form_query(pairs)}"
|
|
208
|
+
origin = self._app_origin(timeout=timeout, max_retries=max_retries)
|
|
209
|
+
vault_name = getattr(vault, "name", None)
|
|
210
|
+
return AgentItemRequest(
|
|
211
|
+
service=name,
|
|
212
|
+
vaultId=vault_id,
|
|
213
|
+
path=path,
|
|
214
|
+
url=None if origin is None else origin + path,
|
|
215
|
+
message=(
|
|
216
|
+
f"Ask your person to add an item for {name} to the vault {vault_name}. "
|
|
217
|
+
"Do not ask for a key."
|
|
218
|
+
),
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
def _app_origin(self, *, timeout: float | None, max_retries: int | None) -> str | None:
|
|
222
|
+
"""The dashboard's address, from the server's public instance answer. None when unknown."""
|
|
223
|
+
try:
|
|
224
|
+
data = self._http.json(
|
|
225
|
+
"GET", "/v1/instance", anonymous=True, timeout=timeout, max_retries=max_retries
|
|
226
|
+
)
|
|
227
|
+
except OneCLIError:
|
|
228
|
+
return None
|
|
229
|
+
raw = _field(_field(data, "origins"), "external")
|
|
230
|
+
if not isinstance(raw, str):
|
|
231
|
+
return None
|
|
232
|
+
url = parse_http_url(raw.rstrip("/"))
|
|
233
|
+
if url is None or url.has_userinfo or url.has_query or url.has_fragment:
|
|
234
|
+
return None
|
|
235
|
+
if url.path != "/":
|
|
236
|
+
return None
|
|
237
|
+
return url.origin
|
|
238
|
+
|
|
239
|
+
def close(self) -> None:
|
|
240
|
+
"""Close the connection pool, unless you gave it."""
|
|
241
|
+
self._http.close()
|
|
242
|
+
|
|
243
|
+
def __enter__(self) -> Self:
|
|
244
|
+
return self
|
|
245
|
+
|
|
246
|
+
def __exit__(
|
|
247
|
+
self,
|
|
248
|
+
exc_type: type[BaseException] | None,
|
|
249
|
+
exc: BaseException | None,
|
|
250
|
+
traceback: TracebackType | None,
|
|
251
|
+
) -> None:
|
|
252
|
+
self.close()
|
|
253
|
+
|
|
254
|
+
def __repr__(self) -> str:
|
|
255
|
+
return f"{type(self).__name__}(url={self._http.base_url!r})"
|
|
256
|
+
|
|
257
|
+
def __reduce__(self) -> NoReturn:
|
|
258
|
+
msg = "A OneCLI client cannot be pickled: it holds a credential."
|
|
259
|
+
raise TypeError(msg)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class OneCLI:
|
|
263
|
+
"""The owner part: made with a managing key.
|
|
264
|
+
|
|
265
|
+
It manages vaults, their items, agents and approvals on ``/v2``.
|
|
266
|
+
``OneCLI.agent()`` makes the agent part. Close it with ``close()``
|
|
267
|
+
or ``with`` when done.
|
|
268
|
+
"""
|
|
269
|
+
|
|
270
|
+
vaults: Vaults
|
|
271
|
+
items: Items
|
|
272
|
+
agents: Agents
|
|
273
|
+
approvals: Approvals
|
|
274
|
+
keys: Keys
|
|
275
|
+
org_rules: OrgRules
|
|
276
|
+
activity: Activities
|
|
277
|
+
|
|
278
|
+
def __init__(
|
|
279
|
+
self,
|
|
280
|
+
*,
|
|
281
|
+
key: str | None = None,
|
|
282
|
+
url: str | None = None,
|
|
283
|
+
timeout: float | None = None,
|
|
284
|
+
max_retries: int | None = None,
|
|
285
|
+
on_response: ResponseHook | None = None,
|
|
286
|
+
http_client: httpx2.Client | None = None,
|
|
287
|
+
) -> None:
|
|
288
|
+
"""The owner part.
|
|
289
|
+
|
|
290
|
+
Args:
|
|
291
|
+
key: A managing key (``oc_key_...``) or an older API key. Falls back
|
|
292
|
+
to ``ONECLI_API_KEY``. An agent credential or a connect token is
|
|
293
|
+
refused.
|
|
294
|
+
url: The API's base URL. Falls back to ``ONECLI_URL``, then
|
|
295
|
+
``https://api.onecli.sh``.
|
|
296
|
+
timeout: Seconds one try of a call may take. Default 10.
|
|
297
|
+
max_retries: How often a call that failed is tried again, when
|
|
298
|
+
trying again is safe. Default 2; 0 turns it off. A call that
|
|
299
|
+
could do its work twice, such as ``agents.create``, is tried
|
|
300
|
+
again only when the server was too busy to start it (429).
|
|
301
|
+
on_response: Called after every answer, a retried one too, with a
|
|
302
|
+
:class:`ResponseInfo`: the method, the path, the status, the
|
|
303
|
+
request id, the try's number and how long it took. Never a
|
|
304
|
+
header or a body, so no secret passes through it. What it
|
|
305
|
+
raises is ignored.
|
|
306
|
+
http_client: An ``httpx2.Client`` of your own, for proxies or
|
|
307
|
+
certificates. It stays yours to close.
|
|
308
|
+
"""
|
|
309
|
+
given = _setting(key, _env("ONECLI_API_KEY"), default="")
|
|
310
|
+
assert_owner_key(given)
|
|
311
|
+
base = _setting(url, _env("ONECLI_URL"), default=DEFAULT_URL)
|
|
312
|
+
self._http = Http(
|
|
313
|
+
base,
|
|
314
|
+
given,
|
|
315
|
+
timeout=DEFAULT_TIMEOUT if timeout is None else timeout,
|
|
316
|
+
max_retries=DEFAULT_MAX_RETRIES if max_retries is None else max_retries,
|
|
317
|
+
on_response=on_response,
|
|
318
|
+
http_client=http_client,
|
|
319
|
+
)
|
|
320
|
+
self.vaults = Vaults(self._http)
|
|
321
|
+
self.items = Items(self._http)
|
|
322
|
+
self.agents = Agents(self._http)
|
|
323
|
+
self.approvals = Approvals(self._http)
|
|
324
|
+
self.keys = Keys(self._http)
|
|
325
|
+
self.org_rules = OrgRules(self._http)
|
|
326
|
+
self.activity = Activities(self._http)
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def agent(
|
|
330
|
+
*,
|
|
331
|
+
credential: str | None = None,
|
|
332
|
+
url: str | None = None,
|
|
333
|
+
timeout: float | None = None,
|
|
334
|
+
max_retries: int | None = None,
|
|
335
|
+
on_response: ResponseHook | None = None,
|
|
336
|
+
http_client: httpx2.Client | None = None,
|
|
337
|
+
) -> OneCLIAgent:
|
|
338
|
+
"""The agent part, with the agent's credential or ONECLI_AGENT_CREDENTIAL."""
|
|
339
|
+
return OneCLIAgent(
|
|
340
|
+
credential=credential,
|
|
341
|
+
url=url,
|
|
342
|
+
timeout=timeout,
|
|
343
|
+
max_retries=max_retries,
|
|
344
|
+
on_response=on_response,
|
|
345
|
+
http_client=http_client,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
@staticmethod
|
|
349
|
+
def connect(
|
|
350
|
+
connect_token: str,
|
|
351
|
+
*,
|
|
352
|
+
name: str | None = None,
|
|
353
|
+
runtime: AgentRuntime | None = None,
|
|
354
|
+
expires_at: datetime | str | None = None,
|
|
355
|
+
held_credential: str | None = None,
|
|
356
|
+
replace: bool | None = None,
|
|
357
|
+
url: str | None = None,
|
|
358
|
+
timeout: float | None = None,
|
|
359
|
+
max_retries: int | None = None,
|
|
360
|
+
on_response: ResponseHook | None = None,
|
|
361
|
+
http_client: httpx2.Client | None = None,
|
|
362
|
+
) -> CreatedAgent | KeptAgent:
|
|
363
|
+
"""Connect an agent with a vault's connect token, as ``onecli connect`` does.
|
|
364
|
+
|
|
365
|
+
The vault is the token's. A new agent comes with its credential once.
|
|
366
|
+
With ``held_credential`` for an agent on the same vault, that agent
|
|
367
|
+
comes back with no credential; ``replace`` moves one from another vault.
|
|
368
|
+
``url`` falls back to ``ONECLI_URL``, ``ONECLI_API_HOST``, then
|
|
369
|
+
``https://api.onecli.sh``.
|
|
370
|
+
"""
|
|
371
|
+
assert_connect_token(connect_token)
|
|
372
|
+
base = _setting(url, _env("ONECLI_URL"), _env("ONECLI_API_HOST"), default=DEFAULT_URL)
|
|
373
|
+
http = Http(
|
|
374
|
+
base,
|
|
375
|
+
connect_token,
|
|
376
|
+
timeout=DEFAULT_TIMEOUT if timeout is None else timeout,
|
|
377
|
+
max_retries=DEFAULT_MAX_RETRIES if max_retries is None else max_retries,
|
|
378
|
+
on_response=on_response,
|
|
379
|
+
http_client=http_client,
|
|
380
|
+
)
|
|
381
|
+
body: dict[str, object] = {}
|
|
382
|
+
if name is not None:
|
|
383
|
+
body["name"] = name
|
|
384
|
+
if runtime is not None:
|
|
385
|
+
body["runtime"] = runtime
|
|
386
|
+
try:
|
|
387
|
+
return create_agent(
|
|
388
|
+
http,
|
|
389
|
+
body=body,
|
|
390
|
+
expires_at=expires_at,
|
|
391
|
+
held_credential=held_credential,
|
|
392
|
+
replace=replace,
|
|
393
|
+
timeout=None,
|
|
394
|
+
max_retries=None,
|
|
395
|
+
)
|
|
396
|
+
finally:
|
|
397
|
+
http.close()
|
|
398
|
+
|
|
399
|
+
def health(self, *, timeout: float | None = None, max_retries: int | None = None) -> Health:
|
|
400
|
+
"""Whether the API is up, and its version. Needs no key."""
|
|
401
|
+
data = self._http.json(
|
|
402
|
+
"GET", "/v2/health", anonymous=True, timeout=timeout, max_retries=max_retries
|
|
403
|
+
)
|
|
404
|
+
return decode(Health, data)
|
|
405
|
+
|
|
406
|
+
def close(self) -> None:
|
|
407
|
+
"""Close the connection pool, unless you gave it."""
|
|
408
|
+
self._http.close()
|
|
409
|
+
|
|
410
|
+
def __enter__(self) -> Self:
|
|
411
|
+
return self
|
|
412
|
+
|
|
413
|
+
def __exit__(
|
|
414
|
+
self,
|
|
415
|
+
exc_type: type[BaseException] | None,
|
|
416
|
+
exc: BaseException | None,
|
|
417
|
+
traceback: TracebackType | None,
|
|
418
|
+
) -> None:
|
|
419
|
+
self.close()
|
|
420
|
+
|
|
421
|
+
def __repr__(self) -> str:
|
|
422
|
+
return f"{type(self).__name__}(url={self._http.base_url!r})"
|
|
423
|
+
|
|
424
|
+
def __reduce__(self) -> NoReturn:
|
|
425
|
+
msg = "A OneCLI client cannot be pickled: it holds a key."
|
|
426
|
+
raise TypeError(msg)
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
# Made from src/onecli/_async/_connected_agent.py by scripts/gen_sync.py. Do not edit.
|
|
2
|
+
"""The agent ``agents.create`` answers: the server's answer, plus what a sandbox needs."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from typing import TYPE_CHECKING, NoReturn, Self
|
|
7
|
+
|
|
8
|
+
from onecli._agent_env import SETUP_COMMAND, allow_hosts_for, build_agent_env, gateway_base_url
|
|
9
|
+
from onecli._errors import OneCLIApiError
|
|
10
|
+
from onecli._sync._io import Lock, shielded
|
|
11
|
+
from onecli._wire import Secret
|
|
12
|
+
from onecli.types import AgentGateway
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from types import TracebackType
|
|
17
|
+
|
|
18
|
+
from onecli.types import AgentRuntime, CreatedAgent
|
|
19
|
+
|
|
20
|
+
__all__ = ["ConnectedAgent"]
|
|
21
|
+
|
|
22
|
+
_NOT_FOUND = 404
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ConnectedAgent:
|
|
26
|
+
"""A new agent with its credential.
|
|
27
|
+
|
|
28
|
+
The credential is shown once, here. It never shows in ``repr()``, ``str()``
|
|
29
|
+
or ``vars()``: read ``credential`` or ``env`` to hand it to the sandbox, and
|
|
30
|
+
do not log them. Hold the agent with ``with`` to disconnect it when
|
|
31
|
+
the work is done.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
id: str
|
|
35
|
+
name: str
|
|
36
|
+
vault_id: str
|
|
37
|
+
runtime: AgentRuntime | str | None
|
|
38
|
+
provider: str | None
|
|
39
|
+
kind: str | None
|
|
40
|
+
created_at: str
|
|
41
|
+
expires_at: str | None
|
|
42
|
+
"""When the credential stops by itself. None: only when the agent is disconnected."""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
created: CreatedAgent,
|
|
47
|
+
*,
|
|
48
|
+
api_url: str,
|
|
49
|
+
home: str,
|
|
50
|
+
disconnect: Callable[[str], None],
|
|
51
|
+
) -> None:
|
|
52
|
+
self.id = getattr(created, "id", "")
|
|
53
|
+
self.name = getattr(created, "name", "")
|
|
54
|
+
self.vault_id = getattr(created, "vault_id", "")
|
|
55
|
+
self.runtime = getattr(created, "runtime", None)
|
|
56
|
+
self.provider = getattr(created, "provider", None)
|
|
57
|
+
self.kind = getattr(created, "kind", None)
|
|
58
|
+
self.created_at = getattr(created, "created_at", "")
|
|
59
|
+
self.expires_at = getattr(created, "expires_at", None)
|
|
60
|
+
# A copy no one else holds. An answer with no gateway makes an empty one
|
|
61
|
+
# here, so the agent can still be disconnected: `env` then says why.
|
|
62
|
+
gateway = getattr(created, "gateway", None)
|
|
63
|
+
self._gateway = (
|
|
64
|
+
gateway.model_copy(deep=True)
|
|
65
|
+
if isinstance(gateway, AgentGateway)
|
|
66
|
+
else AgentGateway.model_construct()
|
|
67
|
+
)
|
|
68
|
+
self._credential = Secret(getattr(created, "credential", ""))
|
|
69
|
+
self._api_url = api_url
|
|
70
|
+
self._home = home
|
|
71
|
+
self._disconnect = disconnect
|
|
72
|
+
self._disconnected = False
|
|
73
|
+
self._lock = Lock()
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def gateway(self) -> AgentGateway:
|
|
77
|
+
"""Where the sandbox sends its calls. A copy: changing it changes nothing here."""
|
|
78
|
+
return self._gateway.model_copy(deep=True)
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def credential(self) -> str:
|
|
82
|
+
"""The agent's credential (``oc_agent_...``). Do not log it.
|
|
83
|
+
|
|
84
|
+
The server never shows it again: this is the one place to read it.
|
|
85
|
+
"""
|
|
86
|
+
return self._credential.reveal()
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def env(self) -> dict[str, str]:
|
|
90
|
+
"""The environment for the sandbox.
|
|
91
|
+
|
|
92
|
+
The proxy settings, where the certificate files will be, and the
|
|
93
|
+
credential. Pass it when you create the sandbox, then run
|
|
94
|
+
``setup_command`` once. Do not log it. A new copy each time: the
|
|
95
|
+
credential is never kept in it on the agent, so ``vars()`` cannot show it.
|
|
96
|
+
"""
|
|
97
|
+
return build_agent_env(
|
|
98
|
+
credential=self._credential.reveal(),
|
|
99
|
+
agent_id=self.id,
|
|
100
|
+
vault_id=self.vault_id,
|
|
101
|
+
gateway=self._gateway,
|
|
102
|
+
api_url=self._api_url,
|
|
103
|
+
home=self._home,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def setup_command(self) -> str:
|
|
108
|
+
"""One shell line to run once in the sandbox, after it started with ``env``.
|
|
109
|
+
|
|
110
|
+
It writes the certificate files. It holds no secret, and running it
|
|
111
|
+
twice is safe. Until it has run, every HTTPS call in the sandbox fails
|
|
112
|
+
with a certificate error. For a call that takes a list of arguments:
|
|
113
|
+
``["sh", "-c", agent.setup_command]``.
|
|
114
|
+
"""
|
|
115
|
+
return SETUP_COMMAND
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def allow_hosts(self) -> list[str]:
|
|
119
|
+
"""The hosts the sandbox must reach: the gateway and the API.
|
|
120
|
+
|
|
121
|
+
Enough for an egress allow list.
|
|
122
|
+
"""
|
|
123
|
+
return allow_hosts_for(self._api_url, self._gateway)
|
|
124
|
+
|
|
125
|
+
def base_url(self, host: str) -> str:
|
|
126
|
+
"""A base URL on the gateway for one API's host, for a client that cannot use a proxy.
|
|
127
|
+
|
|
128
|
+
``agent.base_url("api.example.com")``. The client must send the agent's
|
|
129
|
+
credential as ``Authorization: Bearer``. It needs no certificate and no
|
|
130
|
+
setup command, and ``env`` lets a call to it skip the proxy.
|
|
131
|
+
"""
|
|
132
|
+
return gateway_base_url(self._gateway, host)
|
|
133
|
+
|
|
134
|
+
def disconnect(self) -> None:
|
|
135
|
+
"""Disconnect the agent. Its credential stops working within 60 seconds at most.
|
|
136
|
+
|
|
137
|
+
Safe to call twice, and an agent that is already gone counts as done.
|
|
138
|
+
After a failure, calling it again tries again.
|
|
139
|
+
"""
|
|
140
|
+
with self._lock:
|
|
141
|
+
if self._disconnected:
|
|
142
|
+
return
|
|
143
|
+
try:
|
|
144
|
+
self._disconnect(self.id)
|
|
145
|
+
except OneCLIApiError as error:
|
|
146
|
+
if error.status_code != _NOT_FOUND:
|
|
147
|
+
raise
|
|
148
|
+
self._disconnected = True
|
|
149
|
+
|
|
150
|
+
def __enter__(self) -> Self:
|
|
151
|
+
return self
|
|
152
|
+
|
|
153
|
+
def __exit__(
|
|
154
|
+
self,
|
|
155
|
+
exc_type: type[BaseException] | None,
|
|
156
|
+
exc: BaseException | None,
|
|
157
|
+
traceback: TracebackType | None,
|
|
158
|
+
) -> None:
|
|
159
|
+
# Runs to its end when the block was cancelled too: a credential left
|
|
160
|
+
# behind works until it expires. The call has its own deadline.
|
|
161
|
+
with shielded():
|
|
162
|
+
try:
|
|
163
|
+
self.disconnect()
|
|
164
|
+
except Exception as error:
|
|
165
|
+
# A failure replaces the block's own error, as in node-sdk, with
|
|
166
|
+
# the block's error as its context. Never a cancel or an interrupt.
|
|
167
|
+
if exc is None or isinstance(exc, Exception):
|
|
168
|
+
raise
|
|
169
|
+
exc.add_note(f"Disconnecting agent {self.id} failed too: {error}")
|
|
170
|
+
|
|
171
|
+
def __repr__(self) -> str:
|
|
172
|
+
return (
|
|
173
|
+
f"{type(self).__name__}(id={self.id!r}, name={self.name!r}, "
|
|
174
|
+
f"vault_id={self.vault_id!r}, runtime={self.runtime!r}, "
|
|
175
|
+
f"provider={self.provider!r}, kind={self.kind!r}, "
|
|
176
|
+
f"created_at={self.created_at!r}, expires_at={self.expires_at!r}, "
|
|
177
|
+
f"gateway={self._gateway!r}, credential='[redacted]')"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
def __str__(self) -> str:
|
|
181
|
+
return f"{type(self).__name__}({self.id})"
|
|
182
|
+
|
|
183
|
+
def __reduce__(self) -> NoReturn:
|
|
184
|
+
msg = "A connected agent cannot be pickled: it holds a credential."
|
|
185
|
+
raise TypeError(msg)
|