-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
255 lines (219 loc) · 7.98 KB
/
Copy pathtools.py
File metadata and controls
255 lines (219 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
"""Hermes async tool handlers for nostrwalletconnect.
All tools open a fresh NWCClient per call (NIP-47 connections are cheap).
The wallet URI is read from the ``NWC_URI`` env var — never accepted as
a tool argument, so it never enters the LLM context. Without
``NWC_URI`` set, every tool errors with a clear message pointing at
the env var.
"""
from __future__ import annotations
import os
from dataclasses import asdict, is_dataclass
from typing import Any
from nostrwalletconnect import NWCClient
from tools.registry import tool_error, tool_result
def _get_uri() -> str | None:
uri = os.environ.get("NWC_URI", "").strip()
return uri or None
def _no_uri_error() -> str:
return tool_error(
"NWC_URI env var is not set. Provide a `nostr+walletconnect://...` URI "
"from your wallet service (Alby, Mutiny, LNbits, etc.) and restart Hermes."
)
def _serialize(obj: Any) -> Any:
if is_dataclass(obj):
return asdict(obj)
if isinstance(obj, list):
return [_serialize(x) for x in obj]
if isinstance(obj, dict):
return {k: _serialize(v) for k, v in obj.items()}
return obj
# -----------------------------
# nwc_get_info
# -----------------------------
NWC_GET_INFO_SCHEMA = {
"type": "function",
"function": {
"name": "nwc_get_info",
"description": (
"Return the connected wallet's capabilities (alias, color, pubkey, "
"supported NIP-47 methods, network). Use this once to confirm the "
"wallet supports the operations you plan to call."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
}
async def handle_nwc_get_info(args: dict[str, Any], **kw) -> str:
uri = _get_uri()
if not uri:
return _no_uri_error()
try:
async with NWCClient(uri) as nwc:
info = await nwc.get_info()
return tool_result(_serialize(info))
except Exception as e:
return tool_error(f"nwc_get_info failed: {type(e).__name__}: {e}")
# -----------------------------
# nwc_balance
# -----------------------------
NWC_BALANCE_SCHEMA = {
"type": "function",
"function": {
"name": "nwc_balance",
"description": (
"Return the connected wallet's current balance in millisatoshis "
"and satoshis. Read-only."
),
"parameters": {"type": "object", "properties": {}, "required": []},
},
}
async def handle_nwc_balance(args: dict[str, Any], **kw) -> str:
uri = _get_uri()
if not uri:
return _no_uri_error()
try:
async with NWCClient(uri) as nwc:
resp = await nwc.get_balance()
msats = int(resp.balance)
return tool_result({"balance_msats": msats, "balance_sats": msats // 1000})
except Exception as e:
return tool_error(f"nwc_balance failed: {type(e).__name__}: {e}")
# -----------------------------
# nwc_pay_invoice
# -----------------------------
NWC_PAY_INVOICE_SCHEMA = {
"type": "function",
"function": {
"name": "nwc_pay_invoice",
"description": (
"Pay a Lightning BOLT11 invoice from the connected wallet. Returns "
"the payment preimage on success. ⚠ This SPENDS funds — confirm with "
"the operator before calling for non-trivial amounts."
),
"parameters": {
"type": "object",
"properties": {
"invoice": {
"type": "string",
"description": "BOLT11 invoice string (starts with 'lnbc' on mainnet, 'lntb' on testnet).",
},
"amount_msats": {
"type": "integer",
"description": "Optional amount in millisatoshis. Only set for zero-amount invoices.",
},
},
"required": ["invoice"],
},
},
}
async def handle_nwc_pay_invoice(args: dict[str, Any], **kw) -> str:
uri = _get_uri()
if not uri:
return _no_uri_error()
invoice = args.get("invoice")
if not invoice or not isinstance(invoice, str):
return tool_error("invoice is required and must be a BOLT11 string")
amount = args.get("amount_msats")
try:
async with NWCClient(uri) as nwc:
resp = await nwc.pay_invoice(invoice, amount=amount)
return tool_result(_serialize(resp))
except Exception as e:
return tool_error(f"nwc_pay_invoice failed: {type(e).__name__}: {e}")
# -----------------------------
# nwc_make_invoice
# -----------------------------
NWC_MAKE_INVOICE_SCHEMA = {
"type": "function",
"function": {
"name": "nwc_make_invoice",
"description": (
"Create a BOLT11 Lightning invoice on the connected wallet to "
"receive payment. Returns the invoice string and payment hash."
),
"parameters": {
"type": "object",
"properties": {
"amount_msats": {
"type": "integer",
"description": "Amount in millisatoshis. (1 sat = 1000 msats.)",
},
"description": {
"type": "string",
"description": "Memo/description shown to the payer. Defaults to empty string.",
},
"expiry_seconds": {
"type": "integer",
"description": "Invoice expiry in seconds. Defaults to wallet's default (typically 1 hour).",
},
},
"required": ["amount_msats"],
},
},
}
async def handle_nwc_make_invoice(args: dict[str, Any], **kw) -> str:
uri = _get_uri()
if not uri:
return _no_uri_error()
amount = args.get("amount_msats")
if not isinstance(amount, int) or amount <= 0:
return tool_error("amount_msats is required and must be a positive integer")
description = args.get("description") or ""
expiry = args.get("expiry_seconds")
try:
async with NWCClient(uri) as nwc:
kwargs = {"amount": amount, "description": description}
if expiry is not None:
kwargs["expiry"] = expiry
resp = await nwc.make_invoice(**kwargs)
return tool_result(_serialize(resp))
except Exception as e:
return tool_error(f"nwc_make_invoice failed: {type(e).__name__}: {e}")
# -----------------------------
# nwc_list_transactions
# -----------------------------
NWC_LIST_TRANSACTIONS_SCHEMA = {
"type": "function",
"function": {
"name": "nwc_list_transactions",
"description": (
"Return recent transactions from the connected wallet, "
"newest first. Each entry includes type (incoming/outgoing), "
"amount in msats, settled timestamp, and payment hash."
),
"parameters": {
"type": "object",
"properties": {
"limit": {
"type": "integer",
"description": "Max transactions to return. Defaults to 10. Cap 50.",
"default": 10,
},
"type": {
"type": "string",
"enum": ["incoming", "outgoing"],
"description": "Optional filter by direction.",
},
},
"required": [],
},
},
}
async def handle_nwc_list_transactions(args: dict[str, Any], **kw) -> str:
uri = _get_uri()
if not uri:
return _no_uri_error()
limit = args.get("limit", 10)
try:
limit = max(1, min(50, int(limit)))
except (TypeError, ValueError):
limit = 10
tx_type = args.get("type")
try:
async with NWCClient(uri) as nwc:
kwargs = {"limit": limit}
if tx_type in ("incoming", "outgoing"):
kwargs["type"] = tx_type
resp = await nwc.list_transactions(**kwargs)
return tool_result(_serialize(resp))
except Exception as e:
return tool_error(f"nwc_list_transactions failed: {type(e).__name__}: {e}")