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