langchain-noderings 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.
- langchain_noderings/__init__.py +69 -0
- langchain_noderings/_client.py +63 -0
- langchain_noderings/_errors.py +88 -0
- langchain_noderings/_format.py +292 -0
- langchain_noderings/_safety.py +50 -0
- langchain_noderings/_version.py +1 -0
- langchain_noderings/py.typed +0 -0
- langchain_noderings/toolkit.py +112 -0
- langchain_noderings/tools/__init__.py +91 -0
- langchain_noderings/tools/account.py +22 -0
- langchain_noderings/tools/base.py +236 -0
- langchain_noderings/tools/catalog.py +23 -0
- langchain_noderings/tools/dns.py +279 -0
- langchain_noderings/tools/marketplace.py +139 -0
- langchain_noderings/tools/snapshots.py +48 -0
- langchain_noderings/tools/ssh_keys.py +100 -0
- langchain_noderings/tools/virtual_machines.py +337 -0
- langchain_noderings-0.1.0.dist-info/METADATA +255 -0
- langchain_noderings-0.1.0.dist-info/RECORD +21 -0
- langchain_noderings-0.1.0.dist-info/WHEEL +4 -0
- langchain_noderings-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""LangChain tools for NodeRings.
|
|
2
|
+
|
|
3
|
+
from langchain_noderings import NodeRingsToolkit
|
|
4
|
+
|
|
5
|
+
tools = NodeRingsToolkit().get_tools() # read-only tools; reads NODERINGS_TOKEN on first use
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from ._safety import SafetyPolicy
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .toolkit import TOOL_NAMES, NodeRingsToolkit
|
|
13
|
+
from .tools import (
|
|
14
|
+
NodeRingsBaseTool,
|
|
15
|
+
NodeRingsCompareProvidersTool,
|
|
16
|
+
NodeRingsCreateDNSZoneTool,
|
|
17
|
+
NodeRingsCreateSnapshotTool,
|
|
18
|
+
NodeRingsCreateSSHKeyTool,
|
|
19
|
+
NodeRingsCreateVirtualMachineTool,
|
|
20
|
+
NodeRingsDeleteDNSRecordTool,
|
|
21
|
+
NodeRingsDeleteSSHKeyTool,
|
|
22
|
+
NodeRingsDeleteVirtualMachineTool,
|
|
23
|
+
NodeRingsGetAccountTool,
|
|
24
|
+
NodeRingsGetPlanTool,
|
|
25
|
+
NodeRingsGetVirtualMachineTool,
|
|
26
|
+
NodeRingsListDistrosTool,
|
|
27
|
+
NodeRingsListDNSRecordsTool,
|
|
28
|
+
NodeRingsListDNSZonesTool,
|
|
29
|
+
NodeRingsListLocationsTool,
|
|
30
|
+
NodeRingsListSnapshotsTool,
|
|
31
|
+
NodeRingsListSSHKeysTool,
|
|
32
|
+
NodeRingsListVirtualMachinesTool,
|
|
33
|
+
NodeRingsPowerVirtualMachineTool,
|
|
34
|
+
NodeRingsReinstallVirtualMachineTool,
|
|
35
|
+
NodeRingsSearchPlansTool,
|
|
36
|
+
NodeRingsTagVirtualMachineTool,
|
|
37
|
+
NodeRingsUpsertDNSRecordTool,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"TOOL_NAMES",
|
|
42
|
+
"NodeRingsBaseTool",
|
|
43
|
+
"NodeRingsCompareProvidersTool",
|
|
44
|
+
"NodeRingsCreateDNSZoneTool",
|
|
45
|
+
"NodeRingsCreateSSHKeyTool",
|
|
46
|
+
"NodeRingsCreateSnapshotTool",
|
|
47
|
+
"NodeRingsCreateVirtualMachineTool",
|
|
48
|
+
"NodeRingsDeleteDNSRecordTool",
|
|
49
|
+
"NodeRingsDeleteSSHKeyTool",
|
|
50
|
+
"NodeRingsDeleteVirtualMachineTool",
|
|
51
|
+
"NodeRingsGetAccountTool",
|
|
52
|
+
"NodeRingsGetPlanTool",
|
|
53
|
+
"NodeRingsGetVirtualMachineTool",
|
|
54
|
+
"NodeRingsListDNSRecordsTool",
|
|
55
|
+
"NodeRingsListDNSZonesTool",
|
|
56
|
+
"NodeRingsListDistrosTool",
|
|
57
|
+
"NodeRingsListLocationsTool",
|
|
58
|
+
"NodeRingsListSSHKeysTool",
|
|
59
|
+
"NodeRingsListSnapshotsTool",
|
|
60
|
+
"NodeRingsListVirtualMachinesTool",
|
|
61
|
+
"NodeRingsPowerVirtualMachineTool",
|
|
62
|
+
"NodeRingsReinstallVirtualMachineTool",
|
|
63
|
+
"NodeRingsSearchPlansTool",
|
|
64
|
+
"NodeRingsTagVirtualMachineTool",
|
|
65
|
+
"NodeRingsToolkit",
|
|
66
|
+
"NodeRingsUpsertDNSRecordTool",
|
|
67
|
+
"SafetyPolicy",
|
|
68
|
+
"__version__",
|
|
69
|
+
]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""One lazily built NodeRings client pair, shared by every tool of a toolkit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
|
|
7
|
+
from noderings import AsyncNodeRings, NodeRings
|
|
8
|
+
|
|
9
|
+
from ._version import __version__
|
|
10
|
+
|
|
11
|
+
USER_AGENT = f"langchain-noderings/{__version__}"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ClientProvider:
|
|
15
|
+
"""Builds the sync and async SDK clients on first use.
|
|
16
|
+
|
|
17
|
+
Nothing is read from the environment until a tool runs, so importing the
|
|
18
|
+
package or building a toolkit without a token works. Clients passed in are
|
|
19
|
+
used as they are.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
*,
|
|
25
|
+
token: str | None = None,
|
|
26
|
+
organization_id: str | None = None,
|
|
27
|
+
base_url: str | None = None,
|
|
28
|
+
client: NodeRings | None = None,
|
|
29
|
+
async_client: AsyncNodeRings | None = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
self._token = token
|
|
32
|
+
self._organization_id = organization_id
|
|
33
|
+
self._base_url = base_url
|
|
34
|
+
self._client = client
|
|
35
|
+
self._async_client = async_client
|
|
36
|
+
self._lock = threading.Lock()
|
|
37
|
+
|
|
38
|
+
def __repr__(self) -> str: # never show the token
|
|
39
|
+
return "ClientProvider()"
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def sync(self) -> NodeRings:
|
|
43
|
+
with self._lock:
|
|
44
|
+
if self._client is None:
|
|
45
|
+
self._client = NodeRings(
|
|
46
|
+
self._token,
|
|
47
|
+
organization_id=self._organization_id,
|
|
48
|
+
base_url=self._base_url,
|
|
49
|
+
user_agent=USER_AGENT,
|
|
50
|
+
)
|
|
51
|
+
return self._client
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def async_(self) -> AsyncNodeRings:
|
|
55
|
+
with self._lock:
|
|
56
|
+
if self._async_client is None:
|
|
57
|
+
self._async_client = AsyncNodeRings(
|
|
58
|
+
self._token,
|
|
59
|
+
organization_id=self._organization_id,
|
|
60
|
+
base_url=self._base_url,
|
|
61
|
+
user_agent=USER_AGENT,
|
|
62
|
+
)
|
|
63
|
+
return self._async_client
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Turn SDK exceptions into short messages a model can act on.
|
|
2
|
+
|
|
3
|
+
Messages never contain the token, request headers or request bodies.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from langchain_core.tools import ToolException
|
|
11
|
+
from noderings import (
|
|
12
|
+
APIConnectionError,
|
|
13
|
+
APIError,
|
|
14
|
+
AuthenticationError,
|
|
15
|
+
BadRequestError,
|
|
16
|
+
ConflictError,
|
|
17
|
+
InternalServerError,
|
|
18
|
+
NodeRingsError,
|
|
19
|
+
NotFoundError,
|
|
20
|
+
PermissionDeniedError,
|
|
21
|
+
QuotaExceededError,
|
|
22
|
+
RateLimitError,
|
|
23
|
+
WaitTimeoutError,
|
|
24
|
+
)
|
|
25
|
+
from pydantic import ValidationError
|
|
26
|
+
|
|
27
|
+
PREFIX = "NodeRings error: "
|
|
28
|
+
|
|
29
|
+
MSG_AUTH = "The NodeRings token is missing, invalid or expired. Ask the user to set NODERINGS_TOKEN to a service-account token."
|
|
30
|
+
MSG_BUSY = "Another operation on this resource is still running. Wait and try again."
|
|
31
|
+
MSG_RATE = "NodeRings is rate-limiting requests. Wait a minute before retrying."
|
|
32
|
+
MSG_DOWN = "NodeRings is not reachable right now. Try again later."
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def message_for(exc: BaseException, *, what: str = "resource", ident: str = "") -> str:
|
|
36
|
+
"""The message for ``exc``, starting with ``NodeRings error:``."""
|
|
37
|
+
return PREFIX + _body(exc, what=what, ident=ident)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _body(exc: BaseException, *, what: str, ident: str) -> str:
|
|
41
|
+
if isinstance(exc, AuthenticationError):
|
|
42
|
+
return MSG_AUTH
|
|
43
|
+
if isinstance(exc, PermissionDeniedError):
|
|
44
|
+
code = exc.reason or exc.code.name
|
|
45
|
+
return f"The service account lacks permission for this action ({code}). Ask an organization admin to grant it."
|
|
46
|
+
if isinstance(exc, NotFoundError):
|
|
47
|
+
target = f"{what} {ident}".strip()
|
|
48
|
+
return f"Not found: {target}. List the resources first; do not guess ids."
|
|
49
|
+
if isinstance(exc, QuotaExceededError):
|
|
50
|
+
return f"A plan limit was reached ({exc.reason or 'LIMIT_REACHED'})."
|
|
51
|
+
if isinstance(exc, ConflictError) or (isinstance(exc, APIError) and exc.is_busy):
|
|
52
|
+
return MSG_BUSY
|
|
53
|
+
if isinstance(exc, RateLimitError):
|
|
54
|
+
return MSG_RATE
|
|
55
|
+
if isinstance(exc, BadRequestError):
|
|
56
|
+
return exc.message.strip() or "The request was rejected as invalid."
|
|
57
|
+
if isinstance(exc, (InternalServerError, APIConnectionError)):
|
|
58
|
+
return MSG_DOWN
|
|
59
|
+
if isinstance(exc, APIError):
|
|
60
|
+
# Another 4xx: the API's own message explains it.
|
|
61
|
+
return exc.message.strip() or f"The request failed (HTTP {exc.status_code})."
|
|
62
|
+
if isinstance(exc, WaitTimeoutError):
|
|
63
|
+
last: Any = exc.last
|
|
64
|
+
vm_id = getattr(last, "id", "") or ident
|
|
65
|
+
return (
|
|
66
|
+
f"The VM was created but did not start within the wait time. Its id is {vm_id}; "
|
|
67
|
+
"check it with noderings_get_virtual_machine."
|
|
68
|
+
)
|
|
69
|
+
if isinstance(exc, ValueError) and "token is required" in str(exc):
|
|
70
|
+
# Raised by the SDK client when NODERINGS_TOKEN is not set.
|
|
71
|
+
return MSG_AUTH
|
|
72
|
+
if isinstance(exc, NodeRingsError):
|
|
73
|
+
return MSG_DOWN
|
|
74
|
+
return "Unexpected error."
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def to_tool_exception(exc: BaseException, *, what: str = "resource", ident: str = "") -> ToolException:
|
|
78
|
+
return ToolException(message_for(exc, what=what, ident=ident))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def validation_message(exc: ValidationError) -> str:
|
|
82
|
+
"""List invalid fields without echoing the input (which could hold a secret)."""
|
|
83
|
+
parts = []
|
|
84
|
+
for err in exc.errors(include_url=False, include_input=False):
|
|
85
|
+
loc = ".".join(str(p) for p in err.get("loc", ())) or "input"
|
|
86
|
+
msg = str(err.get("msg", "invalid value"))
|
|
87
|
+
parts.append(f"{loc}: {msg}")
|
|
88
|
+
return PREFIX + "invalid arguments: " + "; ".join(parts)
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Compact, stable JSON summaries of SDK models for tool output.
|
|
2
|
+
|
|
3
|
+
Rules: stable keys, no ``None``/empty-string noise, enum values shortened to
|
|
4
|
+
lower-case words (``OPERATION_STATUS_STARTED`` -> ``started``), unknown enum
|
|
5
|
+
values kept as they are, and lists capped by the caller. Tokens, organization
|
|
6
|
+
ids sent as headers, public key bodies and console URLs are never included.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from collections.abc import Iterable, Mapping
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from decimal import Decimal, InvalidOperation
|
|
15
|
+
from enum import Enum
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from noderings import models as m
|
|
19
|
+
|
|
20
|
+
_ENUM_PREFIXES = (
|
|
21
|
+
"OPERATION_STATUS_",
|
|
22
|
+
"BILLING_TYPE_",
|
|
23
|
+
"BILLING_PERIOD_",
|
|
24
|
+
"PRICING_MODEL_",
|
|
25
|
+
"SNAPSHOT_OPERATION_STATUS_",
|
|
26
|
+
"SNAPSHOT_STATUS_",
|
|
27
|
+
"RESTORE_STATUS_",
|
|
28
|
+
"REINSTALL_STATUS_",
|
|
29
|
+
"DNS_ZONE_STATE_",
|
|
30
|
+
"DNSSEC_MODE_",
|
|
31
|
+
"ORGANIZATION_TYPE_",
|
|
32
|
+
"STATUS_",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def enum_word(value: Any) -> str | None:
|
|
37
|
+
"""``OPERATION_STATUS_STARTED`` -> ``started``; ``*_UNSPECIFIED`` -> ``None``."""
|
|
38
|
+
if value is None:
|
|
39
|
+
return None
|
|
40
|
+
raw = _raw(value)
|
|
41
|
+
if not raw or raw.endswith("UNSPECIFIED"):
|
|
42
|
+
return None
|
|
43
|
+
if not isinstance(value, Enum) or value.name not in type(value).__members__:
|
|
44
|
+
return raw # a value this SDK version does not know: keep it as it is
|
|
45
|
+
for prefix in _ENUM_PREFIXES:
|
|
46
|
+
if raw.startswith(prefix):
|
|
47
|
+
return raw[len(prefix) :].lower()
|
|
48
|
+
return raw
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _raw(value: Any) -> str:
|
|
52
|
+
if value is None:
|
|
53
|
+
return ""
|
|
54
|
+
return str(value.value) if isinstance(value, Enum) else str(value)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def amount(value: str | None) -> str | None:
|
|
58
|
+
"""``"9.000000"`` -> ``"9"``, ``"0.015000"`` -> ``"0.015"``."""
|
|
59
|
+
if not value:
|
|
60
|
+
return None
|
|
61
|
+
try:
|
|
62
|
+
d = Decimal(value)
|
|
63
|
+
except InvalidOperation:
|
|
64
|
+
return value
|
|
65
|
+
return format(d.normalize(), "f")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def ts(value: datetime | None) -> str | None:
|
|
69
|
+
if value is None or value.year <= 1:
|
|
70
|
+
return None
|
|
71
|
+
return value.isoformat().replace("+00:00", "Z")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def clean(value: Any) -> Any:
|
|
75
|
+
"""Drop ``None`` and empty strings from dicts, recursively."""
|
|
76
|
+
if isinstance(value, Mapping):
|
|
77
|
+
out = {}
|
|
78
|
+
for k, v in value.items():
|
|
79
|
+
v = clean(v)
|
|
80
|
+
if v is None or v == "":
|
|
81
|
+
continue
|
|
82
|
+
out[k] = v
|
|
83
|
+
return out
|
|
84
|
+
if isinstance(value, list):
|
|
85
|
+
return [clean(v) for v in value]
|
|
86
|
+
return value
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def dumps(value: Any) -> str:
|
|
90
|
+
return json.dumps(clean(value), ensure_ascii=False, separators=(",", ":"))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def capped(items: Iterable[dict[str, Any]], key: str, limit: int, total: int | None = None) -> dict[str, Any]:
|
|
94
|
+
"""``{key: [...], "total": N, "truncated": bool}`` with at most ``limit`` items."""
|
|
95
|
+
rows = list(items)
|
|
96
|
+
n = len(rows) if total is None else max(total, len(rows))
|
|
97
|
+
kept = rows[:limit]
|
|
98
|
+
return {key: kept, "total": n, "truncated": n > len(kept)}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# --- marketplace -----------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def price_summary(p: m.MarketplaceSearchPlanPriceSummary | None) -> dict[str, Any] | None:
|
|
105
|
+
if p is None:
|
|
106
|
+
return None
|
|
107
|
+
return {
|
|
108
|
+
"amount": amount(p.unit_amount),
|
|
109
|
+
"currency": p.currency,
|
|
110
|
+
"unit": p.unit_name,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def plan_price(p: m.PlanPrice) -> dict[str, Any]:
|
|
115
|
+
return {
|
|
116
|
+
"amount": amount(p.unit_amount),
|
|
117
|
+
"currency": p.currency,
|
|
118
|
+
"unit": p.unit_name,
|
|
119
|
+
"metric": p.metric_name,
|
|
120
|
+
"pricing_model": enum_word(p.pricing_model),
|
|
121
|
+
"minimum_charge": _nonzero(p.minimum_charge),
|
|
122
|
+
"maximum_charge": _nonzero(p.maximum_charge),
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _nonzero(v: str | None) -> str | None:
|
|
127
|
+
a = amount(v)
|
|
128
|
+
return None if a in (None, "0") else a
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _main_price(prices: list[m.PlanPrice]) -> dict[str, Any] | None:
|
|
132
|
+
"""The plan's own price: the first non-zero plan price, else the first one."""
|
|
133
|
+
plan = [p for p in prices if _raw(p.product_type) != "PRODUCT_TYPE_ADDON"] or prices
|
|
134
|
+
for p in plan:
|
|
135
|
+
if _nonzero(p.unit_amount):
|
|
136
|
+
return plan_price(p)
|
|
137
|
+
return plan_price(plan[0]) if plan else None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def search_result(r: m.MarketplaceSearchResult) -> dict[str, Any]:
|
|
141
|
+
return {
|
|
142
|
+
"plan_id": r.plan_id,
|
|
143
|
+
"region_id": r.region_id,
|
|
144
|
+
"plan_code": r.plan_code,
|
|
145
|
+
"provider": r.organization_name,
|
|
146
|
+
"city": r.region_city,
|
|
147
|
+
"country": r.region_country,
|
|
148
|
+
"vcpus": r.vcpus,
|
|
149
|
+
"ram_gb": r.ram_gb,
|
|
150
|
+
"disk_gb": r.disk_gb,
|
|
151
|
+
"billing_type": enum_word(r.billing_type),
|
|
152
|
+
"price": price_summary(r.plan_price),
|
|
153
|
+
"rating": r.rating or None,
|
|
154
|
+
"reviews": r.total_reviews or None,
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def plan(p: m.GetMarketplacePlanResponse) -> dict[str, Any]:
|
|
159
|
+
return {
|
|
160
|
+
"plan_id": p.plan_id,
|
|
161
|
+
"plan_code": p.plan_code,
|
|
162
|
+
"provider": p.organization_name,
|
|
163
|
+
"vcpus": p.vcpus,
|
|
164
|
+
"ram_gb": p.ram_gb,
|
|
165
|
+
"disk_gb": p.disk_gb,
|
|
166
|
+
"billing_type": enum_word(p.billing_type),
|
|
167
|
+
"price": _main_price(p.plan_prices),
|
|
168
|
+
"prices": [plan_price(x) for x in p.plan_prices],
|
|
169
|
+
"rating": p.rating or None,
|
|
170
|
+
"reviews": p.total_reviews or None,
|
|
171
|
+
"regions": [{"region_id": r.region_id, "city": r.city, "country": r.country} for r in p.plan_regions],
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def plan_cost(p: m.GetMarketplacePlanResponse) -> dict[str, Any]:
|
|
176
|
+
"""The part of a plan an agent should quote before ordering."""
|
|
177
|
+
return {
|
|
178
|
+
"plan_code": p.plan_code,
|
|
179
|
+
"provider": p.organization_name,
|
|
180
|
+
"billing_type": enum_word(p.billing_type),
|
|
181
|
+
"price": _main_price(p.plan_prices),
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def provider(p: m.ProviderInfo) -> dict[str, Any]:
|
|
186
|
+
return {
|
|
187
|
+
"provider": p.organization_name,
|
|
188
|
+
"plan_id": p.plan_id,
|
|
189
|
+
"price": _main_price(p.plan_prices),
|
|
190
|
+
"rating": p.rating or None,
|
|
191
|
+
"reviews": p.total_reviews or None,
|
|
192
|
+
"ipv6_available": p.ipv6_available_in_filtered_region,
|
|
193
|
+
"has_capacity": p.has_capacity_in_filtered_region,
|
|
194
|
+
"ddos_protection": p.ddos_provider or None,
|
|
195
|
+
"regions": [{"region_id": r.region_id, "city": r.city, "country": r.country} for r in p.plan_regions],
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# --- catalog, keys, account -----------------------------------------------
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def distro(d: m.DistroCatalogEntry) -> dict[str, Any]:
|
|
203
|
+
return {
|
|
204
|
+
"distro": _raw(d.distro),
|
|
205
|
+
"label": d.label,
|
|
206
|
+
"family": d.family,
|
|
207
|
+
"version": d.version,
|
|
208
|
+
"default": d.is_default or None,
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def ssh_key(k: m.SSHKey) -> dict[str, Any]:
|
|
213
|
+
# The public key body is deliberately left out.
|
|
214
|
+
return {
|
|
215
|
+
"id": k.id,
|
|
216
|
+
"name": k.name,
|
|
217
|
+
"type": k.key_type,
|
|
218
|
+
"fingerprint": k.fingerprint,
|
|
219
|
+
"created": ts(k.timestamps.create_time) if k.timestamps else None,
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def organization(o: m.Organization) -> dict[str, Any]:
|
|
224
|
+
return {"id": o.id, "name": o.name, "type": enum_word(o.type), "verified": o.is_verified}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
# --- virtual machines ------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def virtual_machine(vm: m.VirtualMachine, *, detail: bool = False) -> dict[str, Any]:
|
|
231
|
+
out: dict[str, Any] = {
|
|
232
|
+
"id": vm.id,
|
|
233
|
+
"hostname": vm.hostname,
|
|
234
|
+
"status": enum_word(vm.operation_status),
|
|
235
|
+
"provider": vm.provider_name,
|
|
236
|
+
"city": vm.region_city,
|
|
237
|
+
"country": vm.region_country,
|
|
238
|
+
"plan_code": vm.plan_code,
|
|
239
|
+
"vcpus": vm.cpu or None,
|
|
240
|
+
"memory_mb": vm.memory or None,
|
|
241
|
+
"ipv4": vm.ipv4,
|
|
242
|
+
"ipv6": vm.ipv6,
|
|
243
|
+
"tags": list(vm.tags),
|
|
244
|
+
"created": ts(vm.create_time),
|
|
245
|
+
}
|
|
246
|
+
if detail:
|
|
247
|
+
raw_distro = _raw(vm.distro)
|
|
248
|
+
out.update(
|
|
249
|
+
{
|
|
250
|
+
"plan_id": vm.plan_id,
|
|
251
|
+
"region_id": vm.region_id,
|
|
252
|
+
"storage_mb": vm.storage or None,
|
|
253
|
+
"distro": None if raw_distro in ("", "DISTRO_UNSPECIFIED") else raw_distro,
|
|
254
|
+
"billing_type": enum_word(vm.plan_billing_type),
|
|
255
|
+
"additional_ipv4": [a.ip_address for a in vm.additional_ipv4] or None,
|
|
256
|
+
"instant_app": vm.instant_app_name or None,
|
|
257
|
+
"reinstall_status": enum_word(vm.reinstall_status),
|
|
258
|
+
"backups_enabled": vm.has_active_backup_subscription,
|
|
259
|
+
"compliance_hold": vm.compliance_held or None,
|
|
260
|
+
"updated": ts(vm.update_time),
|
|
261
|
+
}
|
|
262
|
+
)
|
|
263
|
+
return out
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def snapshot(s: m.Snapshot) -> dict[str, Any]:
|
|
267
|
+
return {
|
|
268
|
+
"id": s.id,
|
|
269
|
+
"name": s.name,
|
|
270
|
+
"description": s.description,
|
|
271
|
+
"status": enum_word(s.operation_status),
|
|
272
|
+
"state": enum_word(s.snapshot_status),
|
|
273
|
+
"created": ts(s.created_at) or (ts(s.timestamps.create_time) if s.timestamps else None),
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
# --- DNS -------------------------------------------------------------------
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def dns_zone(z: m.DNSZone) -> dict[str, Any]:
|
|
281
|
+
return {
|
|
282
|
+
"id": z.id,
|
|
283
|
+
"name": z.name,
|
|
284
|
+
"state": enum_word(z.state),
|
|
285
|
+
"nameservers": list(z.assigned_nameservers),
|
|
286
|
+
"delegation_ok": z.delegation_ok,
|
|
287
|
+
"geo_enabled": z.geo_enabled or None,
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def dns_record(r: m.DNSRecord) -> dict[str, Any]:
|
|
292
|
+
return {"name": r.name, "type": r.type, "ttl": r.ttl, "values": list(r.rdata), "system": r.system or None}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""The safety settings every tool checks before it changes anything."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
9
|
+
|
|
10
|
+
ToolKind = Literal["read", "write", "destructive"]
|
|
11
|
+
|
|
12
|
+
_TAG = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:/=+@-]{0,62}$")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SafetyPolicy(BaseModel):
|
|
16
|
+
"""What the tools of one toolkit may do.
|
|
17
|
+
|
|
18
|
+
Tool *selection* (``mode``, ``allow_destructive``, ``include``, ``exclude``)
|
|
19
|
+
is applied by :class:`~langchain_noderings.NodeRingsToolkit`. The fields here
|
|
20
|
+
are enforced inside each write tool on every call.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
24
|
+
|
|
25
|
+
vm_tag_scope: str | None = Field(
|
|
26
|
+
default=None,
|
|
27
|
+
description="Write tools only touch virtual machines that carry this tag; new ones always get it.",
|
|
28
|
+
)
|
|
29
|
+
dry_run: bool = Field(default=False, description="Write tools describe the call instead of making it.")
|
|
30
|
+
max_list_items: int = Field(default=50, ge=1, le=1000, description="Most items a list tool returns.")
|
|
31
|
+
|
|
32
|
+
@field_validator("vm_tag_scope")
|
|
33
|
+
@classmethod
|
|
34
|
+
def _check_tag(cls, v: str | None) -> str | None:
|
|
35
|
+
if v is None:
|
|
36
|
+
return None
|
|
37
|
+
v = v.strip()
|
|
38
|
+
if not _TAG.match(v):
|
|
39
|
+
raise ValueError("vm_tag_scope must be a single tag such as 'agent-managed'")
|
|
40
|
+
return v
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RefusedError(Exception):
|
|
44
|
+
"""A safety check stopped the call before any write request was sent."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def looks_like_private_key(text: str) -> bool:
|
|
48
|
+
"""True when ``text`` looks like a private key in any common format."""
|
|
49
|
+
upper = text.upper()
|
|
50
|
+
return ("-----BEGIN" in upper and "PRIVATE KEY" in upper) or "PUTTY-USER-KEY-FILE" in upper
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0" # x-release-please-version
|
|
File without changes
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""NodeRingsToolkit: picks the tools an agent gets and the safety rules they follow."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
|
|
7
|
+
from langchain_core.tools import BaseTool, BaseToolkit
|
|
8
|
+
from noderings import AsyncNodeRings, NodeRings
|
|
9
|
+
from pydantic import ConfigDict, Field, PrivateAttr, SecretStr, model_validator
|
|
10
|
+
|
|
11
|
+
from ._client import ClientProvider
|
|
12
|
+
from ._safety import SafetyPolicy
|
|
13
|
+
from .tools import ALL_TOOLS, NodeRingsBaseTool, tool_name
|
|
14
|
+
|
|
15
|
+
TOOL_NAMES: tuple[str, ...] = tuple(tool_name(t) for t in ALL_TOOLS)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NodeRingsToolkit(BaseToolkit):
|
|
19
|
+
"""LangChain tools for NodeRings.
|
|
20
|
+
|
|
21
|
+
Read-only by default. Write tools need ``mode="read_write"``; destructive
|
|
22
|
+
tools (delete, reinstall) also need ``allow_destructive=True``. Every write
|
|
23
|
+
tool needs ``confirm=true`` in the call itself, and delete/reinstall also
|
|
24
|
+
need the VM's hostname.
|
|
25
|
+
|
|
26
|
+
Example::
|
|
27
|
+
|
|
28
|
+
toolkit = NodeRingsToolkit() # reads NODERINGS_TOKEN when a tool first runs
|
|
29
|
+
tools = toolkit.get_tools()
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
33
|
+
|
|
34
|
+
token: SecretStr | None = Field(default=None, repr=False, exclude=True, description="Defaults to NODERINGS_TOKEN.")
|
|
35
|
+
organization_id: str | None = Field(default=None, description="Defaults to NODERINGS_ORGANIZATION_ID.")
|
|
36
|
+
base_url: str | None = Field(
|
|
37
|
+
default=None, description="Defaults to NODERINGS_BASE_URL or https://api.noderings.com."
|
|
38
|
+
)
|
|
39
|
+
mode: Literal["read_only", "read_write"] = "read_only"
|
|
40
|
+
include: list[str] | None = Field(default=None, description="Only these tool names.")
|
|
41
|
+
exclude: list[str] | None = Field(default=None, description="Never these tool names.")
|
|
42
|
+
allow_destructive: bool = Field(
|
|
43
|
+
default=False, description="Also return delete and reinstall tools (needs read_write)."
|
|
44
|
+
)
|
|
45
|
+
vm_tag_scope: str | None = Field(default=None, description="Write tools only touch VMs with this tag.")
|
|
46
|
+
dry_run: bool = Field(default=False, description="Write tools describe the call instead of making it.")
|
|
47
|
+
max_list_items: int = Field(default=50, ge=1, le=1000)
|
|
48
|
+
client: NodeRings | None = Field(default=None, repr=False, exclude=True)
|
|
49
|
+
async_client: AsyncNodeRings | None = Field(default=None, repr=False, exclude=True)
|
|
50
|
+
|
|
51
|
+
_policy: SafetyPolicy = PrivateAttr()
|
|
52
|
+
_provider: ClientProvider = PrivateAttr()
|
|
53
|
+
|
|
54
|
+
@model_validator(mode="after")
|
|
55
|
+
def _check(self) -> NodeRingsToolkit:
|
|
56
|
+
for label, names in (("include", self.include), ("exclude", self.exclude)):
|
|
57
|
+
unknown = sorted(set(names or ()) - set(TOOL_NAMES))
|
|
58
|
+
if unknown:
|
|
59
|
+
raise ValueError(f"{label}: unknown tool name(s) {', '.join(unknown)}")
|
|
60
|
+
self._policy = SafetyPolicy(
|
|
61
|
+
vm_tag_scope=self.vm_tag_scope, dry_run=self.dry_run, max_list_items=self.max_list_items
|
|
62
|
+
)
|
|
63
|
+
if self.include:
|
|
64
|
+
hidden = sorted(set(self.include) - {tool_name(t) for t in self._allowed_classes(filter_names=False)})
|
|
65
|
+
if hidden:
|
|
66
|
+
raise ValueError(
|
|
67
|
+
f"include names tool(s) this mode does not allow: {', '.join(hidden)} "
|
|
68
|
+
"(write tools need mode='read_write'; delete/reinstall also need allow_destructive=True)"
|
|
69
|
+
)
|
|
70
|
+
self._provider = ClientProvider(
|
|
71
|
+
token=self.token.get_secret_value() if self.token else None,
|
|
72
|
+
organization_id=self.organization_id,
|
|
73
|
+
base_url=self.base_url,
|
|
74
|
+
client=self.client,
|
|
75
|
+
async_client=self.async_client,
|
|
76
|
+
)
|
|
77
|
+
return self
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def policy(self) -> SafetyPolicy:
|
|
81
|
+
return self._policy
|
|
82
|
+
|
|
83
|
+
def _allowed_classes(self, *, filter_names: bool = True) -> list[type[NodeRingsBaseTool]]:
|
|
84
|
+
out = []
|
|
85
|
+
for cls in ALL_TOOLS:
|
|
86
|
+
if cls.kind != "read" and self.mode != "read_write":
|
|
87
|
+
continue
|
|
88
|
+
if cls.kind == "destructive" and not self.allow_destructive:
|
|
89
|
+
continue
|
|
90
|
+
name = tool_name(cls)
|
|
91
|
+
if filter_names and self.include is not None and name not in self.include:
|
|
92
|
+
continue
|
|
93
|
+
if filter_names and self.exclude is not None and name in self.exclude:
|
|
94
|
+
continue
|
|
95
|
+
out.append(cls)
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
def get_tools(self) -> list[BaseTool]:
|
|
99
|
+
"""The tools allowed by ``mode``, ``allow_destructive``, ``include`` and ``exclude``."""
|
|
100
|
+
kw: dict[str, Any] = {"policy": self._policy, "provider": self._provider}
|
|
101
|
+
return [cls(**kw) for cls in self._allowed_classes()]
|
|
102
|
+
|
|
103
|
+
def write_tool_names(self) -> set[str]:
|
|
104
|
+
"""Names of the returned tools that change something (write and destructive).
|
|
105
|
+
|
|
106
|
+
Use them for ``HumanInTheLoopMiddleware(interrupt_on=...)``.
|
|
107
|
+
"""
|
|
108
|
+
return {tool_name(c) for c in self._allowed_classes() if c.kind != "read"}
|
|
109
|
+
|
|
110
|
+
def destructive_tool_names(self) -> set[str]:
|
|
111
|
+
"""Names of the returned tools that delete or erase something."""
|
|
112
|
+
return {tool_name(c) for c in self._allowed_classes() if c.kind == "destructive"}
|