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