fetch-hackkit 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,240 @@
1
+ """Agentverse registration: mailbox connect, endpoint registration, profile lookup.
2
+
3
+ Where each profile field is set:
4
+
5
+ ================== ===================================== =========================
6
+ Field Set in code (this module / HackAgent) Agentverse MCP tool
7
+ ================== ===================================== =========================
8
+ name ``HackAgent(name=...)`` ``update_user_agent``
9
+ @handle ``HackAgent(handle=...)`` *not available*
10
+ short description ``HackAgent(description=...)`` ``update_user_agent``
11
+ README ``HackAgent(readme_path=...)`` ``update_user_agent``
12
+ avatar ``HackAgent(avatar_url=...)`` ``update_user_agent``
13
+ ================== ===================================== =========================
14
+
15
+ The ``@handle`` is unique across Agentverse (max 40 chars). If it is taken,
16
+ registration fails with HTTP 409.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import re
23
+ from dataclasses import dataclass
24
+ from typing import TYPE_CHECKING, Any
25
+
26
+ import httpx
27
+
28
+ if TYPE_CHECKING:
29
+ from uagents import Agent
30
+
31
+ HANDLE_MAX_LEN = 40
32
+ _HANDLE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
33
+ AGENTVERSE_URL = "https://agentverse.ai"
34
+
35
+
36
+ def validate_handle(handle: str) -> str:
37
+ """Check an Agentverse ``@handle`` locally and return it without a leading ``@``."""
38
+ value = handle.removeprefix("@")
39
+ if not value or len(value) > HANDLE_MAX_LEN:
40
+ raise ValueError(f"handle must be 1-{HANDLE_MAX_LEN} characters, got {len(value)}")
41
+ if not _HANDLE_RE.match(value):
42
+ raise ValueError(
43
+ f"handle {handle!r} may only contain letters, digits, '-', '_' and '.' (no spaces)"
44
+ )
45
+ return value
46
+
47
+
48
+ def profile_url(address: str) -> str:
49
+ return f"{AGENTVERSE_URL}/agents/details/{address}/profile"
50
+
51
+
52
+ def _api_key(api_key: str | None) -> str:
53
+ key = api_key or os.getenv("AGENTVERSE_API_KEY")
54
+ if not key:
55
+ raise ValueError(
56
+ "AGENTVERSE_API_KEY is not set. Create one at https://agentverse.ai/profile/api-keys"
57
+ )
58
+ return key
59
+
60
+
61
+ def _detail(resp: httpx.Response) -> str:
62
+ try:
63
+ body = resp.json()
64
+ detail = body.get("detail", body) if isinstance(body, dict) else body
65
+ except ValueError:
66
+ detail = resp.text
67
+ hint = ""
68
+ if resp.status_code == 401:
69
+ hint = " (invalid or expired AGENTVERSE_API_KEY)"
70
+ elif resp.status_code == 409:
71
+ hint = " (address or @handle already registered by another account; pick another handle)"
72
+ return f"HTTP {resp.status_code}{hint}: {detail}"
73
+
74
+
75
+ @dataclass
76
+ class ConnectResult:
77
+ ok: bool
78
+ detail: str = ""
79
+ address: str = ""
80
+
81
+ @property
82
+ def profile_url(self) -> str:
83
+ return profile_url(self.address)
84
+
85
+
86
+ def _registration_body(agent: Agent, endpoint: str | None) -> str:
87
+ """The same ``RegistrationRequest`` the inspector's Connect button sends."""
88
+ from uagents_core.registration import RegistrationRequest
89
+
90
+ request = RegistrationRequest(
91
+ address=agent.address,
92
+ name=agent.name,
93
+ handle=agent._handle,
94
+ url=endpoint,
95
+ profile=agent._build_registration_profile(),
96
+ endpoints=agent._endpoints,
97
+ protocols=list(agent.protocols.keys()),
98
+ metadata=agent.metadata,
99
+ )
100
+ return request.model_dump_json()
101
+
102
+
103
+ async def connect_mailbox(
104
+ agent: Agent,
105
+ *,
106
+ api_key: str | None = None,
107
+ endpoint: str | None = None,
108
+ timeout: float = 15.0,
109
+ ) -> ConnectResult:
110
+ """Do what the inspector's *Connect* button does, using ``AGENTVERSE_API_KEY``.
111
+
112
+ Proves the agent owns its address (signed challenge), then publishes its
113
+ profile (name, @handle, description, README, protocols) to Agentverse.
114
+ For an agent with its own public URL, use :func:`register_endpoint_agent`.
115
+ """
116
+ key = _api_key(api_key)
117
+ headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
118
+ av = agent._agentverse
119
+ identity = agent._identity
120
+ async with httpx.AsyncClient(timeout=timeout, headers=headers) as client:
121
+ try:
122
+ resp = await client.get(f"{av.identity_api}/{identity.address}/challenge")
123
+ if resp.status_code != 200:
124
+ return ConnectResult(False, "challenge: " + _detail(resp), agent.address)
125
+ challenge = resp.json()["challenge"]
126
+ proof = {
127
+ "address": identity.address,
128
+ "challenge": challenge,
129
+ "challenge_response": identity.sign(challenge.encode()),
130
+ }
131
+ resp = await client.post(av.identity_api, json=proof)
132
+ if resp.status_code != 200:
133
+ return ConnectResult(False, "identity proof: " + _detail(resp), agent.address)
134
+ body = _registration_body(agent, endpoint)
135
+ resp = await client.post(av.agents_api, content=body)
136
+ if resp.status_code not in (200, 201):
137
+ return ConnectResult(False, "register: " + _detail(resp), agent.address)
138
+ handle = agent._handle
139
+ if handle:
140
+ # Agentverse ignores `handle` when it first creates an agent and only
141
+ # applies it on an update, so read it back and send the update if needed.
142
+ record = await client.get(f"{av.agents_api}/{agent.address}")
143
+ if record.status_code == 200 and record.json().get("handle") != handle:
144
+ resp = await client.post(av.agents_api, content=body)
145
+ if resp.status_code not in (200, 201):
146
+ return ConnectResult(False, "set handle: " + _detail(resp), agent.address)
147
+ record = await client.get(f"{av.agents_api}/{agent.address}")
148
+ if record.status_code == 200 and record.json().get("handle") != handle:
149
+ return ConnectResult(
150
+ True,
151
+ f"connected, but Agentverse did not apply @{handle}",
152
+ agent.address,
153
+ )
154
+ except httpx.HTTPError as exc:
155
+ return ConnectResult(False, f"network error: {exc}", agent.address)
156
+ return ConnectResult(True, "", agent.address)
157
+
158
+
159
+ def register_endpoint_agent(agent: Agent, endpoint: str, *, api_key: str | None = None) -> bool:
160
+ """Register an agent that runs at a public URL (Render, Fly, a VM, ...).
161
+
162
+ Uses ``uagents_core``'s ``register_agent`` (which, unlike ``register_chat_agent``,
163
+ accepts a ``handle``). Raises ``AgentverseRequestError`` on failure.
164
+ """
165
+ from uagents_core.config import AgentverseConfig
166
+ from uagents_core.utils.registration import (
167
+ AgentverseRegistrationRequest,
168
+ RegistrationRequestCredentials,
169
+ register_agent,
170
+ )
171
+
172
+ profile = agent._build_registration_profile()
173
+ request = AgentverseRegistrationRequest(
174
+ name=agent.name,
175
+ endpoint=endpoint,
176
+ protocols=list(agent.protocols.keys()),
177
+ description=profile.description or None,
178
+ readme=profile.readme or None,
179
+ avatar_url=profile.avatar_url or None,
180
+ handle=agent._handle,
181
+ active=True,
182
+ )
183
+ seed = os.getenv("AGENT_SEED_PHRASE")
184
+ if not seed:
185
+ raise ValueError("AGENT_SEED_PHRASE is not set")
186
+ credentials = RegistrationRequestCredentials(
187
+ agentverse_api_key=_api_key(api_key), agent_seed_phrase=seed
188
+ )
189
+ ok = register_agent(request, AgentverseConfig(), credentials)
190
+ record = lookup_agent(agent.address, api_key=api_key) if agent._handle else None
191
+ if record is not None and record.get("handle") != agent._handle:
192
+ # The handle only applies on update (see connect_mailbox).
193
+ ok = register_agent(request, AgentverseConfig(), credentials)
194
+ return ok
195
+
196
+
197
+ def lookup_agent(address: str, *, api_key: str | None = None) -> dict[str, Any] | None:
198
+ """Your Agentverse record for ``address`` (``None`` if it is not on your account)."""
199
+ resp = httpx.get(
200
+ f"{AGENTVERSE_URL}/v2/agents/{address}",
201
+ headers={"Authorization": f"Bearer {_api_key(api_key)}"},
202
+ timeout=15.0,
203
+ )
204
+ if resp.status_code == 404:
205
+ return None
206
+ if resp.status_code != 200:
207
+ raise RuntimeError(_detail(resp))
208
+ data = resp.json()
209
+ return data if isinstance(data, dict) else None
210
+
211
+
212
+ def resolve(identifier: str) -> dict[str, Any] | None:
213
+ """Public Almanac lookup by address, ``@handle`` or domain; ``None`` if unassigned.
214
+
215
+ Returns ``{"address", "status", "type", "protocols", "endpoints", "expiry", ...}``.
216
+ """
217
+ ident = identifier.removeprefix("@")
218
+ resp = httpx.get(f"{AGENTVERSE_URL}/v2/almanac/resolve/{ident}", timeout=15.0)
219
+ if resp.status_code == 404:
220
+ return None
221
+ if resp.status_code != 200:
222
+ raise RuntimeError(_detail(resp))
223
+ data = resp.json()
224
+ return data if isinstance(data, dict) else None
225
+
226
+
227
+ def handle_available(handle: str, *, mine: str | None = None) -> bool:
228
+ """True if nobody (other than address ``mine``) has taken ``handle``."""
229
+ record = resolve(validate_handle(handle))
230
+ return record is None or (mine is not None and record.get("address") == mine)
231
+
232
+
233
+ def resolve_address(identifier: str) -> str:
234
+ """``agent1...`` passes through; ``@handle``/domain is looked up on the Almanac."""
235
+ if identifier.startswith(("agent1", "test-agent1")):
236
+ return identifier
237
+ record = resolve(identifier)
238
+ if not record or not record.get("address"):
239
+ raise ValueError(f"no agent found for {identifier!r}")
240
+ return str(record["address"])
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.5
2
+ Name: fetch-hackkit
3
+ Version: 0.1.0
4
+ Summary: Batteries for Fetch.ai hackathon agents: chat protocol, ASI:One interactive cards, ASI:One LLM + tools, payments, MCP, and Agentverse registration.
5
+ Project-URL: Homepage, https://github.com/adylagad/fetch-hackathon-starter
6
+ Project-URL: Documentation, https://github.com/adylagad/fetch-hackathon-starter/blob/main/AGENTS.md
7
+ Project-URL: Issues, https://github.com/adylagad/fetch-hackathon-starter/issues
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,agentverse,asi1,fetch.ai,hackathon,uagents
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: httpx>=0.27
17
+ Requires-Dist: openai>=1.50
18
+ Requires-Dist: python-dotenv>=1.0
19
+ Requires-Dist: uagents-core>=0.4.12
20
+ Requires-Dist: uagents<0.28,>=0.26.1
21
+ Provides-Extra: mcp
22
+ Requires-Dist: mcp<3,>=2.0; extra == 'mcp'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # fetch-hackkit
26
+
27
+ Batteries for [Fetch.ai](https://fetch.ai) hackathon agents. Build a uAgent that works inside ASI:One in a few lines:
28
+
29
+ - **Chat protocol** done for you: acknowledgements, sessions, `@mention` stripping, friendly error replies.
30
+ - **ASI:One interactive cards**: typed builders for carousel, detail, form, review and custom cards, plus validation and tap parsing (JSON *and* planner prose).
31
+ - **ASI:One LLM**: `ask`, `structured` (Pydantic) and `run_tools`, which turns plain Python functions into tools.
32
+ - **Payments**: `@agent.paid(...)` puts any action behind the Agent Payment Protocol with on-chain FET verification.
33
+ - **MCP**: use any remote MCP server's tools from your agent.
34
+ - **Multi-agent**: `ask_agent(ctx, "@handle", "question")`.
35
+ - **Agentverse**: mailbox auto-connect with name, `@handle`, description and README, plus the `hackkit doctor` pre-submission checks.
36
+
37
+ ```bash
38
+ pip install fetch-hackkit # or: pip install "fetch-hackkit[mcp]"
39
+ ```
40
+
41
+ ```python
42
+ from fetch_hackkit import HackAgent, cards
43
+
44
+ agent = HackAgent(name="Trip Planner", handle="trip-planner", readme_path="README.md")
45
+
46
+ @agent.on_text
47
+ async def on_text(ctx, msg):
48
+ return cards.carousel("Pick a city", [cards.item("sf", "San Francisco", action="plan")])
49
+
50
+ @agent.on_action("plan")
51
+ async def plan(ctx, msg, sel):
52
+ return f"Planning {sel['id']}..."
53
+
54
+ agent.run()
55
+ ```
56
+
57
+ Environment (`.env` is loaded automatically):
58
+ - `AGENT_SEED_PHRASE` (required; generate with `hackkit seed`)
59
+ - `ASI_ONE_API_KEY`
60
+ - `AGENTVERSE_API_KEY`
61
+ - `AGENT_HANDLE`
62
+
63
+ ## CLI
64
+
65
+ ```
66
+ hackkit seed generate a secure seed phrase (+ its address and wallet)
67
+ hackkit whoami address, wallet and Agentverse profile URL for your seed
68
+ hackkit handle NAME is @NAME free on Agentverse?
69
+ hackkit doctor check the agent against hackathon submission requirements
70
+ ```
71
+
72
+ The starter repo, full docs and showcase agent are at https://github.com/adylagad/fetch-hackathon-starter. Requires Python 3.11+, `uagents` 0.26+ and `uagents-core` 0.4.12+. MIT licensed.
@@ -0,0 +1,16 @@
1
+ fetch_hackkit/__init__.py,sha256=10LI3Rm0c-VmnMeweOoq37-_euhtjIRZaxhb6t-7-w4,729
2
+ fetch_hackkit/agent.py,sha256=06tUKS_tURCJelGw4JV57MaYR5rGdWSi_AALBGFahtg,12865
3
+ fetch_hackkit/asi1.py,sha256=CUH6GG7DqEQF3bC4srZ3Wlr6GGeKxi1J7Pkwxomf1N8,11321
4
+ fetch_hackkit/cards.py,sha256=nPYfLFFMkHz5HPmCt3CuhackYO0E49uUl7gLhFT2sCI,18618
5
+ fetch_hackkit/cli.py,sha256=9sbIxNTmT_Zr-5TaDMXdScDPfTYHS83lSZTee7tEEhY,3047
6
+ fetch_hackkit/doctor.py,sha256=HbyNLhM_VDTTmS3NhbNWCZzE0PSgNVORrgCkUYs3ZpY,7374
7
+ fetch_hackkit/mcp.py,sha256=ZdU_xTShDS50WTkvncARGxUXB0IgLxhfvxhI6m3l8ec,3273
8
+ fetch_hackkit/payments.py,sha256=k0M-n8Yh5HHKarVR1XpxHXIgWKHt5ZR5l5hef8wzJ3c,9780
9
+ fetch_hackkit/peers.py,sha256=pnfdw86KjAXtcJmKOtgsG0xQSmW22PAywH2967JaDf8,1399
10
+ fetch_hackkit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ fetch_hackkit/register.py,sha256=ZTRsM-zfAvXg_7VtuE76TEXLLU2dk9fB_OCU5kjHj6k,9610
12
+ fetch_hackkit-0.1.0.dist-info/METADATA,sha256=fBofvP5BVsDD0dRWzLHxPsLE61bEvHrAffCEkfo0NxY,3100
13
+ fetch_hackkit-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
14
+ fetch_hackkit-0.1.0.dist-info/entry_points.txt,sha256=q4jE2XuDrXcHO9S2PB2j-G4w1zaXu2I7KnZNnzGx-NY,51
15
+ fetch_hackkit-0.1.0.dist-info/licenses/LICENSE,sha256=5gBVHjA8rbq1fHVmCGulYLk0PujDeuPnj-TS9HnhhTc,1065
16
+ fetch_hackkit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ hackkit = fetch_hackkit.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 adylagad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.