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,1293 @@
1
+ """The owner part's resources: vaults, items, agents, approvals, keys, rules, activity."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import builtins
6
+ from datetime import datetime
7
+ from typing import TYPE_CHECKING, Final, Literal, TypeVar, cast, overload
8
+
9
+ from onecli._agent_env import DEFAULT_AGENT_HOME, check_home
10
+ from onecli._async._connected_agent import AsyncConnectedAgent
11
+ from onecli._errors import OneCLIError
12
+ from onecli._js import js_prefix, js_trim
13
+ from onecli._lifetime import iso_datetime, resolve_expiry
14
+ from onecli._wire import NOT_GIVEN, NotGiven, decode, seg, to_wire
15
+ from onecli.types import (
16
+ Activity,
17
+ ActivityResult,
18
+ Agent,
19
+ AgentRuntime,
20
+ ApprovalDecided,
21
+ ApprovalDecision,
22
+ ApprovalList,
23
+ ConnectToken,
24
+ CreatedAgent,
25
+ CreatedConnectToken,
26
+ CreatedOneUseConnectToken,
27
+ InjectionConfig,
28
+ Item,
29
+ ItemDetails,
30
+ ItemPermissions,
31
+ ItemVersion,
32
+ ItemVersionRestored,
33
+ KeptAgent,
34
+ Key,
35
+ LlmProvider,
36
+ OneUseConnectToken,
37
+ OrgRule,
38
+ OrgRuleAction,
39
+ OrgRuleCondition,
40
+ OrgRuleIdentityInput,
41
+ OrgRuleTargetInput,
42
+ Page,
43
+ PermissionLevel,
44
+ RateLimitWindow,
45
+ ToolPermissionWrite,
46
+ Usage,
47
+ UsageDays,
48
+ Vault,
49
+ )
50
+
51
+ if TYPE_CHECKING:
52
+ from collections.abc import AsyncIterator, Mapping, Sequence
53
+
54
+ from onecli._async._http import AsyncHttp
55
+ from onecli._async._io import PageLoader
56
+
57
+ __all__ = [
58
+ "AsyncActivities",
59
+ "AsyncAgents",
60
+ "AsyncApprovals",
61
+ "AsyncConnectTokens",
62
+ "AsyncItems",
63
+ "AsyncKeys",
64
+ "AsyncOneUseConnectTokens",
65
+ "AsyncOrgRules",
66
+ "AsyncVaults",
67
+ "async_create_agent",
68
+ "async_paginate",
69
+ ]
70
+
71
+ _T = TypeVar("_T")
72
+
73
+ # The longest text the server's vault search takes.
74
+ _MAX_SEARCH: Final = 100
75
+
76
+
77
+ def _has_key(value: object, key: str) -> bool:
78
+ """JavaScript's ``key in value`` for a parsed JSON answer."""
79
+ return isinstance(value, dict) and key in cast("dict[str, object]", value)
80
+
81
+
82
+ def _data_of(answer: object) -> object:
83
+ """The ``data`` of an answer that lists everything at once."""
84
+ return cast("dict[str, object]", answer).get("data") if isinstance(answer, dict) else None
85
+
86
+
87
+ def _moment(value: datetime | str | None, name: str) -> str | None:
88
+ """A moment for a query or a body: a string as it is, an aware datetime as ISO 8601."""
89
+ if isinstance(value, datetime):
90
+ return iso_datetime(value, name)
91
+ return value
92
+
93
+
94
+ def _if_match(version: int | None) -> dict[str, str] | None:
95
+ return None if version is None else {"If-Match": f'"{version}"'}
96
+
97
+
98
+ def _body(**fields: object) -> dict[str, object]:
99
+ """A JSON body of the fields that were given. NOT_GIVEN and None are left out."""
100
+ return {k: v for k, v in fields.items() if v is not None and not isinstance(v, NotGiven)}
101
+
102
+
103
+ async def async_paginate(load: PageLoader[Page[_T]]) -> AsyncIterator[_T]:
104
+ """Walk every page of a cursor list."""
105
+ cursor: str | None = None
106
+ seen: set[str] = set()
107
+ while True:
108
+ page = await load(cursor)
109
+ for row in page.data:
110
+ yield row
111
+ if not page.next_cursor:
112
+ return
113
+ if page.next_cursor in seen:
114
+ msg = "The server returned the same page cursor twice."
115
+ raise OneCLIError(msg)
116
+ seen.add(page.next_cursor)
117
+ cursor = page.next_cursor
118
+
119
+
120
+ async def _vault_by_name(
121
+ http: AsyncHttp, name: object, *, timeout: float | None, max_retries: int | None
122
+ ) -> Vault:
123
+ """The one vault with exactly this name.
124
+
125
+ The server's search finds every vault whose name holds the text, so the
126
+ exact ones are picked out here. Names are not unique: more than one match
127
+ is an error that lists the ids.
128
+ """
129
+ wanted = js_trim(name) if isinstance(name, str) else ""
130
+ if wanted == "":
131
+ msg = "A vault name is required."
132
+ raise OneCLIError(msg)
133
+
134
+ async def load(cursor: str | None) -> Page[Vault]:
135
+ # The server counts the search's length in UTF-16 units, as JavaScript does.
136
+ query = {"q": js_trim(js_prefix(wanted, _MAX_SEARCH)), "limit": 100, "cursor": cursor}
137
+ data = await http.json(
138
+ "GET", "/v2/vaults", query=query, timeout=timeout, max_retries=max_retries
139
+ )
140
+ return decode(Page[Vault], data)
141
+
142
+ matches = [vault async for vault in async_paginate(load) if vault.name == wanted]
143
+ if not matches:
144
+ msg = f'No vault is named "{wanted}". The name must match exactly, capital letters too.'
145
+ raise OneCLIError(msg)
146
+ if len(matches) > 1:
147
+ ids = ", ".join(vault.id for vault in matches)
148
+ msg = f'{len(matches)} vaults are named "{wanted}": {ids}. Use a vault\'s id instead.'
149
+ raise OneCLIError(msg)
150
+ return matches[0]
151
+
152
+
153
+ async def async_create_agent(
154
+ http: AsyncHttp,
155
+ *,
156
+ body: dict[str, object],
157
+ expires_at: datetime | str | None,
158
+ held_credential: str | None,
159
+ replace: bool | None,
160
+ timeout: float | None,
161
+ max_retries: int | None,
162
+ ) -> CreatedAgent | KeptAgent:
163
+ """POST /v2/agents.
164
+
165
+ With ``held_credential`` the server may answer 200 with the agent the place
166
+ already holds (no credential) instead of making one.
167
+ """
168
+ sent = dict(body)
169
+ moment = _moment(expires_at, "expires_at")
170
+ if moment is not None:
171
+ sent["expiresAt"] = moment
172
+ if replace is not None:
173
+ sent["replace"] = replace
174
+ headers = {"OneCLI-Agent-Credential": held_credential} if held_credential else None
175
+ data = await http.json(
176
+ "POST", "/v2/agents", body=sent, headers=headers, timeout=timeout, max_retries=max_retries
177
+ )
178
+ if _has_key(data, "credential"):
179
+ return decode(CreatedAgent, data)
180
+ return decode(KeptAgent, data)
181
+
182
+
183
+ class AsyncConnectTokens:
184
+ """A vault's connect token: the one command that connects agents from a sandbox."""
185
+
186
+ def __init__(self, http: AsyncHttp) -> None:
187
+ self._http = http
188
+
189
+ async def get(
190
+ self, vault_id: str, *, timeout: float | None = None, max_retries: int | None = None
191
+ ) -> ConnectToken:
192
+ """Whether the vault's connect command works. Never the token itself."""
193
+ data = await self._http.json(
194
+ "GET",
195
+ f"/v2/vaults/{seg(vault_id)}/connect-token",
196
+ timeout=timeout,
197
+ max_retries=max_retries,
198
+ )
199
+ return decode(ConnectToken, data)
200
+
201
+ async def create(
202
+ self, vault_id: str, *, timeout: float | None = None, max_retries: int | None = None
203
+ ) -> CreatedConnectToken:
204
+ """Make a new connect token (the old one stops).
205
+
206
+ Agents already connected stay connected. The token is in the answer once.
207
+ """
208
+ data = await self._http.json(
209
+ "POST",
210
+ f"/v2/vaults/{seg(vault_id)}/connect-token",
211
+ timeout=timeout,
212
+ max_retries=max_retries,
213
+ )
214
+ return decode(CreatedConnectToken, data)
215
+
216
+ async def disable(
217
+ self, vault_id: str, *, timeout: float | None = None, max_retries: int | None = None
218
+ ) -> None:
219
+ """Turn the vault's connect command off. Connected agents stay connected."""
220
+ await self._http.json(
221
+ "DELETE",
222
+ f"/v2/vaults/{seg(vault_id)}/connect-token",
223
+ timeout=timeout,
224
+ max_retries=max_retries,
225
+ )
226
+
227
+
228
+ class AsyncOneUseConnectTokens:
229
+ """A vault's one-use connect tokens: each connects one agent and then stops."""
230
+
231
+ def __init__(self, http: AsyncHttp) -> None:
232
+ self._http = http
233
+
234
+ async def list(
235
+ self,
236
+ vault_id: str,
237
+ *,
238
+ limit: int | None = None,
239
+ cursor: str | None = None,
240
+ timeout: float | None = None,
241
+ max_retries: int | None = None,
242
+ ) -> Page[OneUseConnectToken]:
243
+ """The one-use tokens of a vault that still work. Never a token itself."""
244
+ data = await self._http.json(
245
+ "GET",
246
+ f"/v2/vaults/{seg(vault_id)}/connect-tokens",
247
+ query={"limit": limit, "cursor": cursor},
248
+ timeout=timeout,
249
+ max_retries=max_retries,
250
+ )
251
+ return decode(Page[OneUseConnectToken], data)
252
+
253
+ def iterate(
254
+ self, vault_id: str, *, timeout: float | None = None, max_retries: int | None = None
255
+ ) -> AsyncIterator[OneUseConnectToken]:
256
+ """Every one-use token of a vault that still works, page by page."""
257
+
258
+ async def load(cursor: str | None) -> Page[OneUseConnectToken]:
259
+ return await self.list(
260
+ vault_id, cursor=cursor, timeout=timeout, max_retries=max_retries
261
+ )
262
+
263
+ return async_paginate(load)
264
+
265
+ async def create(
266
+ self,
267
+ vault_id: str,
268
+ *,
269
+ name: str | None = None,
270
+ provider: str | None = None,
271
+ expires_in_minutes: int | None = None,
272
+ timeout: float | None = None,
273
+ max_retries: int | None = None,
274
+ ) -> CreatedOneUseConnectToken:
275
+ """Make a connect token that connects one agent and then stops.
276
+
277
+ It also stops by itself after ``expires_in_minutes`` (server default
278
+ 15). The token is in the answer once: pass it to the place the agent
279
+ runs in and do not log it. The vault's standing connect token is not
280
+ changed. ``name`` and ``provider`` win over what the connecting place
281
+ sends.
282
+
283
+ This call sends no Idempotency-Key: the server refuses one here.
284
+ """
285
+ body = _body(name=name, provider=provider, expiresInMinutes=expires_in_minutes)
286
+ data = await self._http.json(
287
+ "POST",
288
+ f"/v2/vaults/{seg(vault_id)}/connect-tokens",
289
+ body=body,
290
+ timeout=timeout,
291
+ max_retries=max_retries,
292
+ )
293
+ return decode(CreatedOneUseConnectToken, data)
294
+
295
+ async def revoke(
296
+ self,
297
+ vault_id: str,
298
+ token_id: str,
299
+ *,
300
+ timeout: float | None = None,
301
+ max_retries: int | None = None,
302
+ ) -> None:
303
+ """Turn a one-use connect token off before it is used."""
304
+ await self._http.json(
305
+ "DELETE",
306
+ f"/v2/vaults/{seg(vault_id)}/connect-tokens/{seg(token_id)}",
307
+ timeout=timeout,
308
+ max_retries=max_retries,
309
+ )
310
+
311
+
312
+ class AsyncVaults:
313
+ """Vaults: each holds items, and the agents connected to it use them."""
314
+
315
+ connect_token: AsyncConnectTokens
316
+ """The vault's standing connect token."""
317
+ connect_tokens: AsyncOneUseConnectTokens
318
+ """The vault's one-use connect tokens."""
319
+
320
+ def __init__(self, http: AsyncHttp) -> None:
321
+ self._http = http
322
+ self.connect_token = AsyncConnectTokens(http)
323
+ self.connect_tokens = AsyncOneUseConnectTokens(http)
324
+
325
+ async def list(
326
+ self,
327
+ *,
328
+ q: str | None = None,
329
+ limit: int | None = None,
330
+ cursor: str | None = None,
331
+ timeout: float | None = None,
332
+ max_retries: int | None = None,
333
+ ) -> Page[Vault]:
334
+ """One page of the vaults you can use. ``q`` finds vaults by name."""
335
+ data = await self._http.json(
336
+ "GET",
337
+ "/v2/vaults",
338
+ query={"q": q, "limit": limit, "cursor": cursor},
339
+ timeout=timeout,
340
+ max_retries=max_retries,
341
+ )
342
+ return decode(Page[Vault], data)
343
+
344
+ def iterate(
345
+ self,
346
+ *,
347
+ q: str | None = None,
348
+ limit: int | None = None,
349
+ timeout: float | None = None,
350
+ max_retries: int | None = None,
351
+ ) -> AsyncIterator[Vault]:
352
+ """Every vault you can use, page by page. ``limit`` is the size of each page."""
353
+
354
+ async def load(cursor: str | None) -> Page[Vault]:
355
+ return await self.list(
356
+ q=q, limit=limit, cursor=cursor, timeout=timeout, max_retries=max_retries
357
+ )
358
+
359
+ return async_paginate(load)
360
+
361
+ async def get(
362
+ self, vault_id: str, *, timeout: float | None = None, max_retries: int | None = None
363
+ ) -> Vault:
364
+ """One vault."""
365
+ data = await self._http.json(
366
+ "GET", f"/v2/vaults/{seg(vault_id)}", timeout=timeout, max_retries=max_retries
367
+ )
368
+ return decode(Vault, data)
369
+
370
+ async def get_by_name(
371
+ self, name: str, *, timeout: float | None = None, max_retries: int | None = None
372
+ ) -> Vault:
373
+ """The vault with exactly this name.
374
+
375
+ Raises when no vault has it, and when more than one has it (names are
376
+ not unique, ids are).
377
+ """
378
+ return await _vault_by_name(self._http, name, timeout=timeout, max_retries=max_retries)
379
+
380
+ async def create(
381
+ self,
382
+ *,
383
+ name: str,
384
+ idempotency_key: str | None = None,
385
+ timeout: float | None = None,
386
+ max_retries: int | None = None,
387
+ ) -> Vault:
388
+ """Make a vault.
389
+
390
+ The SDK sends an Idempotency-Key of its own, the same one on every try,
391
+ so the call is safe to try again. Give ``idempotency_key`` only to make
392
+ two separate calls count as one: the same key gives the first answer
393
+ for 24 hours.
394
+ """
395
+ data = await self._http.json(
396
+ "POST",
397
+ "/v2/vaults",
398
+ body={"name": name},
399
+ keyed=True,
400
+ idempotency_key=idempotency_key,
401
+ timeout=timeout,
402
+ max_retries=max_retries,
403
+ )
404
+ return decode(Vault, data)
405
+
406
+ async def rename(
407
+ self,
408
+ vault_id: str,
409
+ *,
410
+ name: str,
411
+ timeout: float | None = None,
412
+ max_retries: int | None = None,
413
+ ) -> Vault:
414
+ """Give a vault a new name."""
415
+ data = await self._http.json(
416
+ "PATCH",
417
+ f"/v2/vaults/{seg(vault_id)}",
418
+ body={"name": name},
419
+ timeout=timeout,
420
+ max_retries=max_retries,
421
+ )
422
+ return decode(Vault, data)
423
+
424
+ async def delete(
425
+ self, vault_id: str, *, timeout: float | None = None, max_retries: int | None = None
426
+ ) -> None:
427
+ """Delete a vault with its items. Every agent on it is disconnected."""
428
+ await self._http.json(
429
+ "DELETE", f"/v2/vaults/{seg(vault_id)}", timeout=timeout, max_retries=max_retries
430
+ )
431
+
432
+
433
+ class AsyncItems:
434
+ """Items: the API keys, LLM keys and apps in a vault. No answer ever holds a value."""
435
+
436
+ def __init__(self, http: AsyncHttp) -> None:
437
+ self._http = http
438
+
439
+ async def list(
440
+ self,
441
+ vault_id: str,
442
+ *,
443
+ deleted: bool | None = None,
444
+ limit: int | None = None,
445
+ cursor: str | None = None,
446
+ timeout: float | None = None,
447
+ max_retries: int | None = None,
448
+ ) -> Page[Item]:
449
+ """One page of a vault's items.
450
+
451
+ ``deleted=True`` lists deleted items (restorable for 30 days) instead of
452
+ live ones.
453
+ """
454
+ data = await self._http.json(
455
+ "GET",
456
+ f"/v2/vaults/{seg(vault_id)}/items",
457
+ query={"deleted": deleted, "limit": limit, "cursor": cursor},
458
+ timeout=timeout,
459
+ max_retries=max_retries,
460
+ )
461
+ return decode(Page[Item], data)
462
+
463
+ def iterate(
464
+ self,
465
+ vault_id: str,
466
+ *,
467
+ deleted: bool | None = None,
468
+ limit: int | None = None,
469
+ timeout: float | None = None,
470
+ max_retries: int | None = None,
471
+ ) -> AsyncIterator[Item]:
472
+ """Every item of a vault, page by page."""
473
+
474
+ async def load(cursor: str | None) -> Page[Item]:
475
+ return await self.list(
476
+ vault_id,
477
+ deleted=deleted,
478
+ limit=limit,
479
+ cursor=cursor,
480
+ timeout=timeout,
481
+ max_retries=max_retries,
482
+ )
483
+
484
+ return async_paginate(load)
485
+
486
+ @overload
487
+ async def create(
488
+ self,
489
+ vault_id: str,
490
+ *,
491
+ kind: Literal["api_key"],
492
+ name: str,
493
+ value: str,
494
+ host_pattern: str,
495
+ path_pattern: str | None = None,
496
+ injection_config: InjectionConfig | Mapping[str, object] | None = None,
497
+ idempotency_key: str | None = None,
498
+ timeout: float | None = None,
499
+ max_retries: int | None = None,
500
+ ) -> Item: ...
501
+
502
+ @overload
503
+ async def create(
504
+ self,
505
+ vault_id: str,
506
+ *,
507
+ kind: Literal["llm_key"],
508
+ provider: LlmProvider,
509
+ value: str,
510
+ name: str | None = None,
511
+ idempotency_key: str | None = None,
512
+ timeout: float | None = None,
513
+ max_retries: int | None = None,
514
+ ) -> Item: ...
515
+
516
+ async def create(
517
+ self,
518
+ vault_id: str,
519
+ *,
520
+ kind: Literal["api_key", "llm_key"],
521
+ value: str,
522
+ name: str | None = None,
523
+ host_pattern: str | None = None,
524
+ path_pattern: str | None = None,
525
+ injection_config: InjectionConfig | Mapping[str, object] | None = None,
526
+ provider: LlmProvider | None = None,
527
+ idempotency_key: str | None = None,
528
+ timeout: float | None = None,
529
+ max_retries: int | None = None,
530
+ ) -> Item:
531
+ """Add an API key or an LLM key to a vault. Apps are connected in their own flow.
532
+
533
+ An API key needs ``name``, ``value`` and ``host_pattern``; an LLM key
534
+ needs ``provider`` and ``value``. ``injection_config`` takes a model or
535
+ a mapping with Python or API names. Safe to try again: the SDK sends an
536
+ Idempotency-Key (see ``vaults.create``).
537
+ """
538
+ body = _body(
539
+ kind=kind,
540
+ name=name,
541
+ value=value,
542
+ hostPattern=host_pattern,
543
+ pathPattern=path_pattern,
544
+ injectionConfig=None
545
+ if injection_config is None
546
+ else to_wire(injection_config, InjectionConfig),
547
+ provider=provider,
548
+ )
549
+ data = await self._http.json(
550
+ "POST",
551
+ f"/v2/vaults/{seg(vault_id)}/items",
552
+ body=body,
553
+ keyed=True,
554
+ idempotency_key=idempotency_key,
555
+ timeout=timeout,
556
+ max_retries=max_retries,
557
+ )
558
+ return decode(Item, data)
559
+
560
+ async def get(
561
+ self, item_id: str, *, timeout: float | None = None, max_retries: int | None = None
562
+ ) -> ItemDetails:
563
+ """One item, with what the vault's agents may do with it."""
564
+ data = await self._http.json(
565
+ "GET", f"/v2/items/{seg(item_id)}", timeout=timeout, max_retries=max_retries
566
+ )
567
+ return decode(ItemDetails, data)
568
+
569
+ async def update(
570
+ self,
571
+ item_id: str,
572
+ *,
573
+ name: str | None = None,
574
+ vault_id: str | None = None,
575
+ allow_plain_http: bool | None = None,
576
+ enabled: bool | None = None,
577
+ if_match: int | None = None,
578
+ timeout: float | None = None,
579
+ max_retries: int | None = None,
580
+ ) -> Item:
581
+ """Exactly one change: rename, move to another vault, plain http, or on/off.
582
+
583
+ ``if_match`` is the item's ``version`` as you read it: a newer one on
584
+ the server answers 409.
585
+ """
586
+ body = _body(name=name, vaultId=vault_id, allowPlainHttp=allow_plain_http, enabled=enabled)
587
+ data = await self._http.json(
588
+ "PATCH",
589
+ f"/v2/items/{seg(item_id)}",
590
+ body=body,
591
+ headers=_if_match(if_match),
592
+ timeout=timeout,
593
+ max_retries=max_retries,
594
+ )
595
+ return decode(Item, data)
596
+
597
+ async def set_value(
598
+ self,
599
+ item_id: str,
600
+ value: str,
601
+ *,
602
+ if_match: int,
603
+ timeout: float | None = None,
604
+ max_retries: int | None = None,
605
+ ) -> ItemDetails:
606
+ """Give a key a new value. ``if_match`` is required: the version you read."""
607
+ data = await self._http.json(
608
+ "PUT",
609
+ f"/v2/items/{seg(item_id)}/value",
610
+ body={"value": value},
611
+ headers=_if_match(if_match),
612
+ timeout=timeout,
613
+ max_retries=max_retries,
614
+ )
615
+ return decode(ItemDetails, data)
616
+
617
+ async def delete(
618
+ self,
619
+ item_id: str,
620
+ *,
621
+ destroy: bool = False,
622
+ timeout: float | None = None,
623
+ max_retries: int | None = None,
624
+ ) -> None:
625
+ """Delete an item (restorable for 30 days).
626
+
627
+ With ``destroy=True``, destroy an item that is already deleted, for good.
628
+ """
629
+ await self._http.json(
630
+ "DELETE",
631
+ f"/v2/items/{seg(item_id)}",
632
+ query={"destroy": "true" if destroy else None},
633
+ timeout=timeout,
634
+ max_retries=max_retries,
635
+ )
636
+
637
+ async def restore(
638
+ self,
639
+ item_id: str,
640
+ *,
641
+ idempotency_key: str | None = None,
642
+ timeout: float | None = None,
643
+ max_retries: int | None = None,
644
+ ) -> Item:
645
+ """Bring a deleted item back."""
646
+ data = await self._http.json(
647
+ "POST",
648
+ f"/v2/items/{seg(item_id)}/restore",
649
+ keyed=True,
650
+ idempotency_key=idempotency_key,
651
+ timeout=timeout,
652
+ max_retries=max_retries,
653
+ )
654
+ return decode(Item, data)
655
+
656
+ async def versions(
657
+ self, item_id: str, *, timeout: float | None = None, max_retries: int | None = None
658
+ ) -> builtins.list[ItemVersion]:
659
+ """The earlier values of a key, newest first. Never a value itself."""
660
+ data = await self._http.json(
661
+ "GET", f"/v2/items/{seg(item_id)}/versions", timeout=timeout, max_retries=max_retries
662
+ )
663
+ return decode(builtins.list[ItemVersion], _data_of(data))
664
+
665
+ async def restore_version(
666
+ self,
667
+ item_id: str,
668
+ version: int,
669
+ *,
670
+ idempotency_key: str | None = None,
671
+ timeout: float | None = None,
672
+ max_retries: int | None = None,
673
+ ) -> ItemVersionRestored:
674
+ """Make an earlier value of a key its current one again."""
675
+ data = await self._http.json(
676
+ "POST",
677
+ f"/v2/items/{seg(item_id)}/versions/{seg(str(version))}/restore",
678
+ keyed=True,
679
+ idempotency_key=idempotency_key,
680
+ timeout=timeout,
681
+ max_retries=max_retries,
682
+ )
683
+ return decode(ItemVersionRestored, data)
684
+
685
+ async def get_permissions(
686
+ self, item_id: str, *, timeout: float | None = None, max_retries: int | None = None
687
+ ) -> ItemPermissions:
688
+ """What every agent on the item's vault may do with it."""
689
+ data = await self._http.json(
690
+ "GET", f"/v2/items/{seg(item_id)}/permissions", timeout=timeout, max_retries=max_retries
691
+ )
692
+ return decode(ItemPermissions, data)
693
+
694
+ async def set_permissions(
695
+ self,
696
+ item_id: str,
697
+ *,
698
+ item: PermissionLevel | None,
699
+ tools: Sequence[ToolPermissionWrite | Mapping[str, object]] | None = None,
700
+ timeout: float | None = None,
701
+ max_retries: int | None = None,
702
+ ) -> ItemPermissions:
703
+ """Set what every agent on the item's vault may do with it.
704
+
705
+ ``item`` is the level for the whole item (None: not set); ``tools`` sets
706
+ one level per tool of an app (server default: none).
707
+ """
708
+ body: dict[str, object] = {"item": item}
709
+ if tools is not None:
710
+ body["tools"] = to_wire(list(tools), ToolPermissionWrite)
711
+ data = await self._http.json(
712
+ "PUT",
713
+ f"/v2/items/{seg(item_id)}/permissions",
714
+ body=body,
715
+ timeout=timeout,
716
+ max_retries=max_retries,
717
+ )
718
+ return decode(ItemPermissions, data)
719
+
720
+
721
+ class AsyncAgents:
722
+ """The agents connected to your vaults."""
723
+
724
+ def __init__(self, http: AsyncHttp) -> None:
725
+ self._http = http
726
+
727
+ async def list(
728
+ self,
729
+ *,
730
+ vault: str | None = None,
731
+ q: str | None = None,
732
+ limit: int | None = None,
733
+ cursor: str | None = None,
734
+ timeout: float | None = None,
735
+ max_retries: int | None = None,
736
+ ) -> Page[Agent]:
737
+ """One page of agents. ``vault``: only agents on this vault. ``q``: find by name."""
738
+ data = await self._http.json(
739
+ "GET",
740
+ "/v2/agents",
741
+ query={"vault": vault, "q": q, "limit": limit, "cursor": cursor},
742
+ timeout=timeout,
743
+ max_retries=max_retries,
744
+ )
745
+ return decode(Page[Agent], data)
746
+
747
+ def iterate(
748
+ self,
749
+ *,
750
+ vault: str | None = None,
751
+ q: str | None = None,
752
+ limit: int | None = None,
753
+ timeout: float | None = None,
754
+ max_retries: int | None = None,
755
+ ) -> AsyncIterator[Agent]:
756
+ """Every agent, page by page."""
757
+
758
+ async def load(cursor: str | None) -> Page[Agent]:
759
+ return await self.list(
760
+ vault=vault,
761
+ q=q,
762
+ limit=limit,
763
+ cursor=cursor,
764
+ timeout=timeout,
765
+ max_retries=max_retries,
766
+ )
767
+
768
+ return async_paginate(load)
769
+
770
+ async def get(
771
+ self, agent_id: str, *, timeout: float | None = None, max_retries: int | None = None
772
+ ) -> Agent:
773
+ """One agent."""
774
+ data = await self._http.json(
775
+ "GET", f"/v2/agents/{seg(agent_id)}", timeout=timeout, max_retries=max_retries
776
+ )
777
+ return decode(Agent, data)
778
+
779
+ @overload
780
+ async def create(
781
+ self,
782
+ *,
783
+ vault_id: str,
784
+ vault_name: None = None,
785
+ name: str | None = None,
786
+ runtime: AgentRuntime | None = None,
787
+ host: str | None = None,
788
+ provider: str | None = None,
789
+ kind: str | None = None,
790
+ ttl_seconds: int | None = None,
791
+ expires_at: datetime | str | None = None,
792
+ no_expiry: bool = False,
793
+ home: str | None = None,
794
+ held_credential: None = None,
795
+ replace: None = None,
796
+ timeout: float | None = None,
797
+ max_retries: int | None = None,
798
+ ) -> AsyncConnectedAgent: ...
799
+
800
+ @overload
801
+ async def create(
802
+ self,
803
+ *,
804
+ vault_name: str,
805
+ vault_id: None = None,
806
+ name: str | None = None,
807
+ runtime: AgentRuntime | None = None,
808
+ host: str | None = None,
809
+ provider: str | None = None,
810
+ kind: str | None = None,
811
+ ttl_seconds: int | None = None,
812
+ expires_at: datetime | str | None = None,
813
+ no_expiry: bool = False,
814
+ home: str | None = None,
815
+ held_credential: None = None,
816
+ replace: None = None,
817
+ timeout: float | None = None,
818
+ max_retries: int | None = None,
819
+ ) -> AsyncConnectedAgent: ...
820
+
821
+ @overload
822
+ async def create(
823
+ self,
824
+ *,
825
+ vault_id: str,
826
+ vault_name: None = None,
827
+ name: str | None = None,
828
+ runtime: AgentRuntime | None = None,
829
+ host: str | None = None,
830
+ provider: str | None = None,
831
+ kind: str | None = None,
832
+ ttl_seconds: int | None = None,
833
+ expires_at: datetime | str | None = None,
834
+ no_expiry: bool = False,
835
+ home: str | None = None,
836
+ held_credential: str,
837
+ replace: bool | None = None,
838
+ timeout: float | None = None,
839
+ max_retries: int | None = None,
840
+ ) -> AsyncConnectedAgent | KeptAgent: ...
841
+
842
+ @overload
843
+ async def create(
844
+ self,
845
+ *,
846
+ vault_name: str,
847
+ vault_id: None = None,
848
+ name: str | None = None,
849
+ runtime: AgentRuntime | None = None,
850
+ host: str | None = None,
851
+ provider: str | None = None,
852
+ kind: str | None = None,
853
+ ttl_seconds: int | None = None,
854
+ expires_at: datetime | str | None = None,
855
+ no_expiry: bool = False,
856
+ home: str | None = None,
857
+ held_credential: str,
858
+ replace: bool | None = None,
859
+ timeout: float | None = None,
860
+ max_retries: int | None = None,
861
+ ) -> AsyncConnectedAgent | KeptAgent: ...
862
+
863
+ async def create(
864
+ self,
865
+ *,
866
+ vault_id: str | None = None,
867
+ vault_name: str | None = None,
868
+ name: str | None = None,
869
+ runtime: AgentRuntime | None = None,
870
+ host: str | None = None,
871
+ provider: str | None = None,
872
+ kind: str | None = None,
873
+ ttl_seconds: int | None = None,
874
+ expires_at: datetime | str | None = None,
875
+ no_expiry: bool = False,
876
+ home: str | None = None,
877
+ held_credential: str | None = None,
878
+ replace: bool | None = None,
879
+ timeout: float | None = None,
880
+ max_retries: int | None = None,
881
+ ) -> AsyncConnectedAgent | KeptAgent:
882
+ """Connect a new agent to a vault, for a sandbox your script starts.
883
+
884
+ The answer has everything the sandbox needs: pass ``agent.env`` when you
885
+ create the sandbox, allow ``agent.allow_hosts`` if you lock its network,
886
+ run ``agent.setup_command`` in it once, and call ``agent.disconnect()``
887
+ when the work is done (or hold the agent with ``async with``).
888
+
889
+ Give the vault by ``vault_id`` or by its exact ``vault_name``. ``name``,
890
+ ``runtime``, ``host``, ``provider`` and ``kind`` describe the agent; none
891
+ of them decides what it may do: its vault does. The agent stops by
892
+ itself after one hour unless you give ``ttl_seconds`` (300 to 7776000)
893
+ or ``expires_at``. It lives until it is disconnected only with
894
+ ``no_expiry=True``. ``home`` is the folder in the sandbox for the
895
+ certificate files (default ``/tmp/onecli``).
896
+
897
+ This call is never sent twice by itself: a second send could make a
898
+ second agent. With ``held_credential`` the server may answer the agent
899
+ the place already holds, which comes with no credential; ``replace``
900
+ then moves it from another vault.
901
+ """
902
+ by_id = isinstance(vault_id, str) and vault_id != ""
903
+ by_name = isinstance(vault_name, str) and vault_name != ""
904
+ if by_id == by_name:
905
+ msg = "agents.create needs a vault_id or a vault_name, and not both."
906
+ raise OneCLIError(msg)
907
+ # Everything that can be refused here is refused before anything is made.
908
+ sandbox_home = check_home(DEFAULT_AGENT_HOME if home is None else home)
909
+ expiry = resolve_expiry(ttl_seconds=ttl_seconds, expires_at=expires_at, no_expiry=no_expiry)
910
+
911
+ if vault_id is not None and by_id:
912
+ vault = vault_id
913
+ else:
914
+ found = await _vault_by_name(
915
+ self._http, vault_name, timeout=timeout, max_retries=max_retries
916
+ )
917
+ vault = found.id
918
+ labels = _body(name=name, runtime=runtime, host=host, provider=provider, kind=kind)
919
+ answer = await async_create_agent(
920
+ self._http,
921
+ body={**labels, "vaultId": vault},
922
+ expires_at=expiry,
923
+ held_credential=held_credential,
924
+ replace=replace,
925
+ timeout=timeout,
926
+ max_retries=max_retries,
927
+ )
928
+ if isinstance(answer, KeptAgent):
929
+ return answer
930
+ return AsyncConnectedAgent(
931
+ answer,
932
+ api_url=self._http.base_url,
933
+ home=sandbox_home,
934
+ disconnect=self.disconnect,
935
+ )
936
+
937
+ async def rename(
938
+ self,
939
+ agent_id: str,
940
+ *,
941
+ name: str,
942
+ timeout: float | None = None,
943
+ max_retries: int | None = None,
944
+ ) -> Agent:
945
+ """Give an agent a new name, 1 to 64 characters."""
946
+ data = await self._http.json(
947
+ "PATCH",
948
+ f"/v2/agents/{seg(agent_id)}",
949
+ body={"name": name},
950
+ timeout=timeout,
951
+ max_retries=max_retries,
952
+ )
953
+ return decode(Agent, data)
954
+
955
+ async def disconnect(
956
+ self, agent_id: str, *, timeout: float | None = None, max_retries: int | None = None
957
+ ) -> None:
958
+ """Disconnect an agent. Its credential stops working within 60 seconds at most."""
959
+ await self._http.json(
960
+ "DELETE", f"/v2/agents/{seg(agent_id)}", timeout=timeout, max_retries=max_retries
961
+ )
962
+
963
+
964
+ class AsyncKeys:
965
+ """Your own managing keys. A key cannot make a key: make one in the dashboard."""
966
+
967
+ def __init__(self, http: AsyncHttp) -> None:
968
+ self._http = http
969
+
970
+ async def list(
971
+ self,
972
+ *,
973
+ limit: int | None = None,
974
+ cursor: str | None = None,
975
+ timeout: float | None = None,
976
+ max_retries: int | None = None,
977
+ ) -> Page[Key]:
978
+ """One page of your keys. Never the key itself."""
979
+ data = await self._http.json(
980
+ "GET",
981
+ "/v2/keys",
982
+ query={"limit": limit, "cursor": cursor},
983
+ timeout=timeout,
984
+ max_retries=max_retries,
985
+ )
986
+ return decode(Page[Key], data)
987
+
988
+ def iterate(
989
+ self, *, timeout: float | None = None, max_retries: int | None = None
990
+ ) -> AsyncIterator[Key]:
991
+ """Every one of your keys, page by page."""
992
+
993
+ async def load(cursor: str | None) -> Page[Key]:
994
+ return await self.list(cursor=cursor, timeout=timeout, max_retries=max_retries)
995
+
996
+ return async_paginate(load)
997
+
998
+ async def get(
999
+ self, key_id: str, *, timeout: float | None = None, max_retries: int | None = None
1000
+ ) -> Key:
1001
+ """One of your keys."""
1002
+ data = await self._http.json(
1003
+ "GET", f"/v2/keys/{seg(key_id)}", timeout=timeout, max_retries=max_retries
1004
+ )
1005
+ return decode(Key, data)
1006
+
1007
+ async def revoke(
1008
+ self, key_id: str, *, timeout: float | None = None, max_retries: int | None = None
1009
+ ) -> None:
1010
+ """Turn one of your keys off for good. It stops at once."""
1011
+ await self._http.json(
1012
+ "DELETE", f"/v2/keys/{seg(key_id)}", timeout=timeout, max_retries=max_retries
1013
+ )
1014
+
1015
+
1016
+ # The lists of a rule, and the shape each entry is read into.
1017
+ _RULE_LISTS: Final[dict[str, object]] = {
1018
+ "targets": OrgRuleTargetInput,
1019
+ "conditions": OrgRuleCondition,
1020
+ "identities": OrgRuleIdentityInput,
1021
+ }
1022
+ # The fields a rule update takes null for: null clears them.
1023
+ _RULE_CLEARABLE: Final = frozenset({"conditions", "description", "rateLimit", "rateLimitWindow"})
1024
+
1025
+
1026
+ def _rule_body(fields: Mapping[str, object], *, clearable: frozenset[str]) -> dict[str, object]:
1027
+ """The JSON body of a rule.
1028
+
1029
+ NOT_GIVEN is left out, and so is None, except for a field in ``clearable``,
1030
+ where it is sent as null.
1031
+ """
1032
+ body: dict[str, object] = {}
1033
+ for key, value in fields.items():
1034
+ if isinstance(value, NotGiven) or (value is None and key not in clearable):
1035
+ continue
1036
+ shape = _RULE_LISTS.get(key)
1037
+ if shape is not None and value is not None:
1038
+ body[key] = to_wire(list(cast("Sequence[object]", value)), shape)
1039
+ else:
1040
+ body[key] = value
1041
+ return body
1042
+
1043
+
1044
+ class AsyncOrgRules:
1045
+ """Rules that hold for every vault of the organization."""
1046
+
1047
+ def __init__(self, http: AsyncHttp) -> None:
1048
+ self._http = http
1049
+
1050
+ async def list(
1051
+ self, *, timeout: float | None = None, max_retries: int | None = None
1052
+ ) -> builtins.list[OrgRule]:
1053
+ """Every rule, in priority order."""
1054
+ data = await self._http.json(
1055
+ "GET", "/v2/org/rules", timeout=timeout, max_retries=max_retries
1056
+ )
1057
+ return decode(builtins.list[OrgRule], _data_of(data))
1058
+
1059
+ async def get(
1060
+ self, rule_id: str, *, timeout: float | None = None, max_retries: int | None = None
1061
+ ) -> OrgRule:
1062
+ """One rule."""
1063
+ data = await self._http.json(
1064
+ "GET", f"/v2/org/rules/{seg(rule_id)}", timeout=timeout, max_retries=max_retries
1065
+ )
1066
+ return decode(OrgRule, data)
1067
+
1068
+ async def create(
1069
+ self,
1070
+ *,
1071
+ name: str,
1072
+ action: OrgRuleAction,
1073
+ targets: Sequence[OrgRuleTargetInput | Mapping[str, object]] | None = None,
1074
+ conditions: Sequence[OrgRuleCondition | Mapping[str, object]] | None = None,
1075
+ description: str | None = None,
1076
+ enabled: bool | None = None,
1077
+ identities: Sequence[OrgRuleIdentityInput | Mapping[str, object]] | None = None,
1078
+ rate_limit: int | None = None,
1079
+ rate_limit_window: RateLimitWindow | None = None,
1080
+ require_approval: bool | None = None,
1081
+ idempotency_key: str | None = None,
1082
+ timeout: float | None = None,
1083
+ max_retries: int | None = None,
1084
+ ) -> OrgRule:
1085
+ """Make a rule. A rule needs at least one target.
1086
+
1087
+ ``targets``, ``conditions`` and ``identities`` take models or mappings
1088
+ with Python or API names. Left out or empty ``identities``: every vault.
1089
+ """
1090
+ fields = {
1091
+ "name": name,
1092
+ "action": action,
1093
+ "targets": targets,
1094
+ "conditions": conditions,
1095
+ "description": description,
1096
+ "enabled": enabled,
1097
+ "identities": identities,
1098
+ "rateLimit": rate_limit,
1099
+ "rateLimitWindow": rate_limit_window,
1100
+ "requireApproval": require_approval,
1101
+ }
1102
+ body = _rule_body(fields, clearable=frozenset())
1103
+ data = await self._http.json(
1104
+ "POST",
1105
+ "/v2/org/rules",
1106
+ body=body,
1107
+ keyed=True,
1108
+ idempotency_key=idempotency_key,
1109
+ timeout=timeout,
1110
+ max_retries=max_retries,
1111
+ )
1112
+ return decode(OrgRule, data)
1113
+
1114
+ async def update(
1115
+ self,
1116
+ rule_id: str,
1117
+ *,
1118
+ name: str | None = None,
1119
+ action: OrgRuleAction | None = None,
1120
+ targets: Sequence[OrgRuleTargetInput | Mapping[str, object]] | None = None,
1121
+ conditions: Sequence[OrgRuleCondition | Mapping[str, object]] | NotGiven | None = NOT_GIVEN,
1122
+ description: str | NotGiven | None = NOT_GIVEN,
1123
+ enabled: bool | None = None,
1124
+ identities: Sequence[OrgRuleIdentityInput | Mapping[str, object]] | None = None,
1125
+ rate_limit: int | NotGiven | None = NOT_GIVEN,
1126
+ rate_limit_window: RateLimitWindow | NotGiven | None = NOT_GIVEN,
1127
+ require_approval: bool | None = None,
1128
+ timeout: float | None = None,
1129
+ max_retries: int | None = None,
1130
+ ) -> OrgRule:
1131
+ """Change a rule. Only the fields you give are sent.
1132
+
1133
+ ``conditions``, ``description``, ``rate_limit`` and
1134
+ ``rate_limit_window`` take None to clear them: leave them out (their
1135
+ default, ``NOT_GIVEN``) to keep them as they are.
1136
+ """
1137
+ fields = {
1138
+ "name": name,
1139
+ "action": action,
1140
+ "targets": targets,
1141
+ "conditions": conditions,
1142
+ "description": description,
1143
+ "enabled": enabled,
1144
+ "identities": identities,
1145
+ "rateLimit": rate_limit,
1146
+ "rateLimitWindow": rate_limit_window,
1147
+ "requireApproval": require_approval,
1148
+ }
1149
+ body = _rule_body(fields, clearable=_RULE_CLEARABLE)
1150
+ data = await self._http.json(
1151
+ "PATCH",
1152
+ f"/v2/org/rules/{seg(rule_id)}",
1153
+ body=body,
1154
+ timeout=timeout,
1155
+ max_retries=max_retries,
1156
+ )
1157
+ return decode(OrgRule, data)
1158
+
1159
+ async def delete(
1160
+ self, rule_id: str, *, timeout: float | None = None, max_retries: int | None = None
1161
+ ) -> None:
1162
+ """Delete a rule."""
1163
+ await self._http.json(
1164
+ "DELETE", f"/v2/org/rules/{seg(rule_id)}", timeout=timeout, max_retries=max_retries
1165
+ )
1166
+
1167
+
1168
+ class AsyncActivities:
1169
+ """The gateway requests agents made, and their counts."""
1170
+
1171
+ def __init__(self, http: AsyncHttp) -> None:
1172
+ self._http = http
1173
+
1174
+ async def list(
1175
+ self,
1176
+ *,
1177
+ vault: str | None = None,
1178
+ agent: str | None = None,
1179
+ result: ActivityResult | None = None,
1180
+ from_: datetime | str | None = None,
1181
+ to: datetime | str | None = None,
1182
+ limit: int | None = None,
1183
+ cursor: str | None = None,
1184
+ timeout: float | None = None,
1185
+ max_retries: int | None = None,
1186
+ ) -> Page[Activity]:
1187
+ """One page of requests, newest first.
1188
+
1189
+ ``from_`` and ``to`` bound them (at or after, at or before): an aware
1190
+ datetime or an ISO 8601 string.
1191
+ """
1192
+ query = {
1193
+ "vault": vault,
1194
+ "agent": agent,
1195
+ "result": result,
1196
+ "from": _moment(from_, "from_"),
1197
+ "to": _moment(to, "to"),
1198
+ "limit": limit,
1199
+ "cursor": cursor,
1200
+ }
1201
+ data = await self._http.json(
1202
+ "GET", "/v2/activity", query=query, timeout=timeout, max_retries=max_retries
1203
+ )
1204
+ return decode(Page[Activity], data)
1205
+
1206
+ def iterate(
1207
+ self,
1208
+ *,
1209
+ vault: str | None = None,
1210
+ agent: str | None = None,
1211
+ result: ActivityResult | None = None,
1212
+ from_: datetime | str | None = None,
1213
+ to: datetime | str | None = None,
1214
+ limit: int | None = None,
1215
+ timeout: float | None = None,
1216
+ max_retries: int | None = None,
1217
+ ) -> AsyncIterator[Activity]:
1218
+ """Every request that fits the filters, page by page."""
1219
+
1220
+ async def load(cursor: str | None) -> Page[Activity]:
1221
+ return await self.list(
1222
+ vault=vault,
1223
+ agent=agent,
1224
+ result=result,
1225
+ from_=from_,
1226
+ to=to,
1227
+ limit=limit,
1228
+ cursor=cursor,
1229
+ timeout=timeout,
1230
+ max_retries=max_retries,
1231
+ )
1232
+
1233
+ return async_paginate(load)
1234
+
1235
+ async def usage(
1236
+ self,
1237
+ *,
1238
+ days: UsageDays | None = None,
1239
+ vault: str | None = None,
1240
+ agent: str | None = None,
1241
+ timeout: float | None = None,
1242
+ max_retries: int | None = None,
1243
+ ) -> Usage:
1244
+ """Request counts over 4 or 30 days, today included (server default 30)."""
1245
+ data = await self._http.json(
1246
+ "GET",
1247
+ "/v2/usage",
1248
+ query={"days": days, "vault": vault, "agent": agent},
1249
+ timeout=timeout,
1250
+ max_retries=max_retries,
1251
+ )
1252
+ return decode(Usage, data)
1253
+
1254
+
1255
+ class AsyncApprovals:
1256
+ """Requests waiting for a person to approve them."""
1257
+
1258
+ def __init__(self, http: AsyncHttp) -> None:
1259
+ self._http = http
1260
+
1261
+ async def list(
1262
+ self,
1263
+ *,
1264
+ vault: str | None = None,
1265
+ timeout: float | None = None,
1266
+ max_retries: int | None = None,
1267
+ ) -> ApprovalList:
1268
+ """The requests waiting for a person, on every vault you can use or on one."""
1269
+ data = await self._http.json(
1270
+ "GET", "/v2/approvals", query={"vault": vault}, timeout=timeout, max_retries=max_retries
1271
+ )
1272
+ # The answer's nextCursor is always null here: only data and truncated are kept.
1273
+ fields = cast("dict[str, object]", data) if isinstance(data, dict) else {}
1274
+ return decode(ApprovalList, {k: fields[k] for k in ("data", "truncated") if k in fields})
1275
+
1276
+ async def decide(
1277
+ self,
1278
+ approval_id: str,
1279
+ *,
1280
+ vault: str,
1281
+ decision: ApprovalDecision,
1282
+ timeout: float | None = None,
1283
+ max_retries: int | None = None,
1284
+ ) -> ApprovalDecided:
1285
+ """Answer one waiting request. ``vault`` is the request's ``vault_id``."""
1286
+ data = await self._http.json(
1287
+ "PATCH",
1288
+ f"/v2/approvals/{seg(approval_id)}",
1289
+ body={"vault": vault, "decision": decision},
1290
+ timeout=timeout,
1291
+ max_retries=max_retries,
1292
+ )
1293
+ return decode(ApprovalDecided, data)