fetch-hackkit 0.1.0__tar.gz
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.
- fetch_hackkit-0.1.0/.gitignore +12 -0
- fetch_hackkit-0.1.0/LICENSE +21 -0
- fetch_hackkit-0.1.0/PKG-INFO +72 -0
- fetch_hackkit-0.1.0/README.md +48 -0
- fetch_hackkit-0.1.0/pyproject.toml +39 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/__init__.py +33 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/agent.py +340 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/asi1.py +294 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/cards.py +526 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/cli.py +90 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/doctor.py +209 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/mcp.py +93 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/payments.py +264 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/peers.py +40 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/py.typed +0 -0
- fetch_hackkit-0.1.0/src/fetch_hackkit/register.py +240 -0
- fetch_hackkit-0.1.0/tests/conftest.py +49 -0
- fetch_hackkit-0.1.0/tests/test_agent.py +116 -0
- fetch_hackkit-0.1.0/tests/test_asi1.py +127 -0
- fetch_hackkit-0.1.0/tests/test_cards.py +143 -0
- fetch_hackkit-0.1.0/tests/test_payments.py +139 -0
- fetch_hackkit-0.1.0/tests/test_register_doctor_mcp.py +133 -0
|
@@ -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.
|
|
@@ -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,48 @@
|
|
|
1
|
+
# fetch-hackkit
|
|
2
|
+
|
|
3
|
+
Batteries for [Fetch.ai](https://fetch.ai) hackathon agents. Build a uAgent that works inside ASI:One in a few lines:
|
|
4
|
+
|
|
5
|
+
- **Chat protocol** done for you: acknowledgements, sessions, `@mention` stripping, friendly error replies.
|
|
6
|
+
- **ASI:One interactive cards**: typed builders for carousel, detail, form, review and custom cards, plus validation and tap parsing (JSON *and* planner prose).
|
|
7
|
+
- **ASI:One LLM**: `ask`, `structured` (Pydantic) and `run_tools`, which turns plain Python functions into tools.
|
|
8
|
+
- **Payments**: `@agent.paid(...)` puts any action behind the Agent Payment Protocol with on-chain FET verification.
|
|
9
|
+
- **MCP**: use any remote MCP server's tools from your agent.
|
|
10
|
+
- **Multi-agent**: `ask_agent(ctx, "@handle", "question")`.
|
|
11
|
+
- **Agentverse**: mailbox auto-connect with name, `@handle`, description and README, plus the `hackkit doctor` pre-submission checks.
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install fetch-hackkit # or: pip install "fetch-hackkit[mcp]"
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from fetch_hackkit import HackAgent, cards
|
|
19
|
+
|
|
20
|
+
agent = HackAgent(name="Trip Planner", handle="trip-planner", readme_path="README.md")
|
|
21
|
+
|
|
22
|
+
@agent.on_text
|
|
23
|
+
async def on_text(ctx, msg):
|
|
24
|
+
return cards.carousel("Pick a city", [cards.item("sf", "San Francisco", action="plan")])
|
|
25
|
+
|
|
26
|
+
@agent.on_action("plan")
|
|
27
|
+
async def plan(ctx, msg, sel):
|
|
28
|
+
return f"Planning {sel['id']}..."
|
|
29
|
+
|
|
30
|
+
agent.run()
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Environment (`.env` is loaded automatically):
|
|
34
|
+
- `AGENT_SEED_PHRASE` (required; generate with `hackkit seed`)
|
|
35
|
+
- `ASI_ONE_API_KEY`
|
|
36
|
+
- `AGENTVERSE_API_KEY`
|
|
37
|
+
- `AGENT_HANDLE`
|
|
38
|
+
|
|
39
|
+
## CLI
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
hackkit seed generate a secure seed phrase (+ its address and wallet)
|
|
43
|
+
hackkit whoami address, wallet and Agentverse profile URL for your seed
|
|
44
|
+
hackkit handle NAME is @NAME free on Agentverse?
|
|
45
|
+
hackkit doctor check the agent against hackathon submission requirements
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
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,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fetch-hackkit"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Batteries for Fetch.ai hackathon agents: chat protocol, ASI:One interactive cards, ASI:One LLM + tools, payments, MCP, and Agentverse registration."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
keywords = ["fetch.ai", "uagents", "agentverse", "asi1", "agents", "hackathon"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Topic :: Software Development :: Libraries",
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"uagents>=0.26.1,<0.28",
|
|
21
|
+
"uagents-core>=0.4.12",
|
|
22
|
+
"openai>=1.50",
|
|
23
|
+
"httpx>=0.27",
|
|
24
|
+
"python-dotenv>=1.0",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://github.com/adylagad/fetch-hackathon-starter"
|
|
29
|
+
Documentation = "https://github.com/adylagad/fetch-hackathon-starter/blob/main/AGENTS.md"
|
|
30
|
+
Issues = "https://github.com/adylagad/fetch-hackathon-starter/issues"
|
|
31
|
+
|
|
32
|
+
[project.optional-dependencies]
|
|
33
|
+
mcp = ["mcp>=2.0,<3"]
|
|
34
|
+
|
|
35
|
+
[project.scripts]
|
|
36
|
+
hackkit = "fetch_hackkit.cli:main"
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["src/fetch_hackkit"]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""fetch-hackkit: batteries for Fetch.ai hackathon agents.
|
|
2
|
+
|
|
3
|
+
from fetch_hackkit import HackAgent, cards, ASI1
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from . import cards
|
|
7
|
+
from .agent import HackAgent, Inbound, Reply, text_message
|
|
8
|
+
from .asi1 import ASI1, ASI1Error, Tool, history, remember, tool
|
|
9
|
+
from .cards import Card, CardError, parse_selection
|
|
10
|
+
from .register import connect_mailbox, handle_available, resolve, validate_handle
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ASI1",
|
|
16
|
+
"ASI1Error",
|
|
17
|
+
"Card",
|
|
18
|
+
"CardError",
|
|
19
|
+
"HackAgent",
|
|
20
|
+
"Inbound",
|
|
21
|
+
"Reply",
|
|
22
|
+
"Tool",
|
|
23
|
+
"cards",
|
|
24
|
+
"connect_mailbox",
|
|
25
|
+
"handle_available",
|
|
26
|
+
"history",
|
|
27
|
+
"parse_selection",
|
|
28
|
+
"remember",
|
|
29
|
+
"resolve",
|
|
30
|
+
"text_message",
|
|
31
|
+
"tool",
|
|
32
|
+
"validate_handle",
|
|
33
|
+
]
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""``HackAgent``: a uAgent that already speaks the Agent Chat Protocol.
|
|
2
|
+
|
|
3
|
+
What you get over a plain ``uagents.Agent``:
|
|
4
|
+
|
|
5
|
+
* the chat protocol is included and its manifest published (ASI:One needs this);
|
|
6
|
+
* every message is acknowledged, session start/end content is handled;
|
|
7
|
+
* ``@agent.on_text`` receives clean text (leading ``@handle`` mentions removed);
|
|
8
|
+
* ``@agent.on_action("name")`` receives interactive-card taps, already parsed;
|
|
9
|
+
* handlers just *return* a reply: ``str``, :class:`~fetch_hackkit.cards.Card`,
|
|
10
|
+
``ChatMessage``, or a list of those;
|
|
11
|
+
* if a handler raises, the user gets a friendly message instead of silence;
|
|
12
|
+
* ``@agent.paid(...)`` puts any action behind the Payment Protocol;
|
|
13
|
+
* with ``AGENTVERSE_API_KEY`` set, a mailbox agent connects itself to
|
|
14
|
+
Agentverse on startup (no inspector click), with name, ``@handle``,
|
|
15
|
+
description and README.
|
|
16
|
+
|
|
17
|
+
It *is* a ``uagents.Agent``, so ``on_interval``, ``storage``, ``include`` and
|
|
18
|
+
everything else still work.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import inspect
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import warnings
|
|
28
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
from datetime import UTC, datetime
|
|
31
|
+
from typing import TYPE_CHECKING, Any, TypeAlias
|
|
32
|
+
from uuid import uuid4
|
|
33
|
+
|
|
34
|
+
from dotenv import find_dotenv, load_dotenv
|
|
35
|
+
from uagents import Agent, Context, Protocol
|
|
36
|
+
from uagents_core.contrib.protocols.chat import (
|
|
37
|
+
ChatAcknowledgement,
|
|
38
|
+
ChatMessage,
|
|
39
|
+
EndSessionContent,
|
|
40
|
+
MetadataContent,
|
|
41
|
+
StartSessionContent,
|
|
42
|
+
TextContent,
|
|
43
|
+
chat_protocol_spec,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
from .cards import Card, collect_actions, parse_selection, strip_mention
|
|
47
|
+
from .register import validate_handle
|
|
48
|
+
|
|
49
|
+
if TYPE_CHECKING:
|
|
50
|
+
from .payments import Paywall
|
|
51
|
+
|
|
52
|
+
DEFAULT_ERROR_MESSAGE = (
|
|
53
|
+
"Sorry, something went wrong on my side while handling that. Please try again in a moment."
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
ReplyPart: TypeAlias = str | Card | ChatMessage
|
|
57
|
+
Reply: TypeAlias = ReplyPart | Sequence[ReplyPart] | None
|
|
58
|
+
TextHandler: TypeAlias = Callable[[Context, "Inbound"], Awaitable[Reply]]
|
|
59
|
+
ActionHandler: TypeAlias = Callable[[Context, "Inbound", dict[str, Any]], Awaitable[Reply]]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class Inbound:
|
|
64
|
+
"""One user message, already unpacked."""
|
|
65
|
+
|
|
66
|
+
sender: str
|
|
67
|
+
text: str
|
|
68
|
+
"""Text with leading ``@handle`` mentions stripped."""
|
|
69
|
+
session: str
|
|
70
|
+
"""Conversation id; use it to key per-conversation state in ``ctx.storage``."""
|
|
71
|
+
raw: ChatMessage
|
|
72
|
+
metadata: dict[str, str] = field(default_factory=dict)
|
|
73
|
+
selection: dict[str, Any] = field(default_factory=dict)
|
|
74
|
+
"""Parsed card tap (``{}`` for ordinary text)."""
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def action(self) -> str | None:
|
|
78
|
+
value = self.selection.get("action")
|
|
79
|
+
return str(value) if value else None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def text_message(text: str, *, end_session: bool = False) -> ChatMessage:
|
|
83
|
+
"""A plain chat-protocol text message."""
|
|
84
|
+
content: list[Any] = [TextContent(type="text", text=text)]
|
|
85
|
+
if end_session:
|
|
86
|
+
content.append(EndSessionContent(type="end-session"))
|
|
87
|
+
return ChatMessage(timestamp=datetime.now(UTC), msg_id=uuid4(), content=content)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def to_messages(reply: Reply) -> list[ChatMessage]:
|
|
91
|
+
"""Normalise anything a handler may return into chat messages."""
|
|
92
|
+
if reply is None:
|
|
93
|
+
return []
|
|
94
|
+
parts: Sequence[ReplyPart] = (
|
|
95
|
+
[reply] if isinstance(reply, str | Card | ChatMessage) else reply # type: ignore[list-item]
|
|
96
|
+
)
|
|
97
|
+
out: list[ChatMessage] = []
|
|
98
|
+
for part in parts:
|
|
99
|
+
if isinstance(part, ChatMessage):
|
|
100
|
+
out.append(part)
|
|
101
|
+
elif isinstance(part, Card):
|
|
102
|
+
out.append(part.to_message())
|
|
103
|
+
elif isinstance(part, str):
|
|
104
|
+
if part.strip():
|
|
105
|
+
out.append(text_message(part))
|
|
106
|
+
else:
|
|
107
|
+
raise TypeError(f"handlers must return str, Card or ChatMessage, got {type(part)!r}")
|
|
108
|
+
return out
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _event_loop() -> asyncio.AbstractEventLoop:
|
|
112
|
+
"""The loop uAgents should use. On Python 3.14+ there is no implicit main-thread
|
|
113
|
+
loop, and ``uagents.Agent()`` at module level crashes without this."""
|
|
114
|
+
try:
|
|
115
|
+
return asyncio.get_running_loop()
|
|
116
|
+
except RuntimeError:
|
|
117
|
+
pass
|
|
118
|
+
try:
|
|
119
|
+
with warnings.catch_warnings():
|
|
120
|
+
warnings.simplefilter("ignore", DeprecationWarning)
|
|
121
|
+
return asyncio.get_event_loop_policy().get_event_loop()
|
|
122
|
+
except RuntimeError:
|
|
123
|
+
loop = asyncio.new_event_loop()
|
|
124
|
+
asyncio.set_event_loop(loop)
|
|
125
|
+
return loop
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def _maybe_await(value: Any) -> Any:
|
|
129
|
+
return await value if inspect.isawaitable(value) else value
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class HackAgent(Agent):
|
|
133
|
+
"""A chat-protocol-ready ``uagents.Agent``. See the module docstring."""
|
|
134
|
+
|
|
135
|
+
def __init__(
|
|
136
|
+
self,
|
|
137
|
+
name: str,
|
|
138
|
+
*,
|
|
139
|
+
seed: str | None = None,
|
|
140
|
+
port: int | None = None,
|
|
141
|
+
mailbox: bool = True,
|
|
142
|
+
handle: str | None = None,
|
|
143
|
+
description: str | None = None,
|
|
144
|
+
readme_path: str | None = None,
|
|
145
|
+
avatar_url: str | None = None,
|
|
146
|
+
error_message: str = DEFAULT_ERROR_MESSAGE,
|
|
147
|
+
auto_connect: bool = True,
|
|
148
|
+
**agent_kwargs: Any,
|
|
149
|
+
) -> None:
|
|
150
|
+
load_dotenv(find_dotenv(usecwd=True))
|
|
151
|
+
seed = seed or os.getenv("AGENT_SEED_PHRASE")
|
|
152
|
+
if not seed:
|
|
153
|
+
raise ValueError(
|
|
154
|
+
"No seed phrase. Set AGENT_SEED_PHRASE in .env to any long random phrase and keep "
|
|
155
|
+
"it secret: the seed *is* your agent's identity (address + wallet). "
|
|
156
|
+
"Run `hackkit seed` to generate one."
|
|
157
|
+
)
|
|
158
|
+
if handle:
|
|
159
|
+
validate_handle(handle)
|
|
160
|
+
agent_kwargs.setdefault("loop", _event_loop())
|
|
161
|
+
super().__init__(
|
|
162
|
+
name=name,
|
|
163
|
+
seed=seed,
|
|
164
|
+
port=port or int(os.getenv("AGENT_PORT", "8000")),
|
|
165
|
+
mailbox=mailbox,
|
|
166
|
+
handle=handle,
|
|
167
|
+
description=description,
|
|
168
|
+
readme_path=readme_path,
|
|
169
|
+
avatar_url=avatar_url,
|
|
170
|
+
publish_agent_details=True,
|
|
171
|
+
**agent_kwargs,
|
|
172
|
+
)
|
|
173
|
+
self.error_message = error_message
|
|
174
|
+
self._text_handler: TextHandler | None = None
|
|
175
|
+
self._action_handlers: dict[str, ActionHandler] = {}
|
|
176
|
+
self._known_actions: set[str] = set()
|
|
177
|
+
self._paywall: Paywall | None = None
|
|
178
|
+
|
|
179
|
+
self.chat_protocol = Protocol(spec=chat_protocol_spec)
|
|
180
|
+
self.chat_protocol.on_message(ChatMessage)(self._on_chat_message)
|
|
181
|
+
self.chat_protocol.on_message(ChatAcknowledgement)(self._on_chat_ack)
|
|
182
|
+
self.include(self.chat_protocol, publish_manifest=True)
|
|
183
|
+
|
|
184
|
+
if mailbox and auto_connect:
|
|
185
|
+
self.on_event("startup")(self._auto_connect)
|
|
186
|
+
|
|
187
|
+
# ------------------------------------------------------------------ #
|
|
188
|
+
# Decorators
|
|
189
|
+
# ------------------------------------------------------------------ #
|
|
190
|
+
|
|
191
|
+
def on_text(self, func: TextHandler) -> TextHandler:
|
|
192
|
+
"""Handle ordinary text (and card taps with no matching ``on_action``)."""
|
|
193
|
+
self._text_handler = func
|
|
194
|
+
return func
|
|
195
|
+
|
|
196
|
+
def on_action(self, name: str) -> Callable[[ActionHandler], ActionHandler]:
|
|
197
|
+
"""Handle card taps whose selection has ``{"action": name}``."""
|
|
198
|
+
|
|
199
|
+
def decorator(func: ActionHandler) -> ActionHandler:
|
|
200
|
+
self._action_handlers[name] = func
|
|
201
|
+
self._known_actions.add(name)
|
|
202
|
+
return func
|
|
203
|
+
|
|
204
|
+
return decorator
|
|
205
|
+
|
|
206
|
+
def paid(
|
|
207
|
+
self,
|
|
208
|
+
name: str,
|
|
209
|
+
*,
|
|
210
|
+
amount: str,
|
|
211
|
+
currency: str = "FET",
|
|
212
|
+
description: str | None = None,
|
|
213
|
+
) -> Callable[[ActionHandler], ActionHandler]:
|
|
214
|
+
"""Put action ``name`` behind a payment. The handler runs only after payment.
|
|
215
|
+
|
|
216
|
+
Tapping a button with ``action=name`` (or calling :meth:`charge`) sends the
|
|
217
|
+
user a ``RequestPayment``; when the user's ``CommitPayment`` verifies
|
|
218
|
+
on-chain, the handler runs with the original message and selection.
|
|
219
|
+
"""
|
|
220
|
+
from .payments import Paywall, Product
|
|
221
|
+
|
|
222
|
+
if self._paywall is None:
|
|
223
|
+
self._paywall = Paywall(self)
|
|
224
|
+
paywall = self._paywall
|
|
225
|
+
|
|
226
|
+
def decorator(func: ActionHandler) -> ActionHandler:
|
|
227
|
+
paywall.add(
|
|
228
|
+
Product(
|
|
229
|
+
name=name,
|
|
230
|
+
amount=amount,
|
|
231
|
+
currency=currency,
|
|
232
|
+
description=description or name,
|
|
233
|
+
handler=func,
|
|
234
|
+
)
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
async def request(ctx: Context, msg: Inbound, sel: dict[str, Any]) -> Reply:
|
|
238
|
+
return await paywall.request(ctx, msg, name, sel)
|
|
239
|
+
|
|
240
|
+
self._action_handlers[name] = request
|
|
241
|
+
self._known_actions.add(name)
|
|
242
|
+
return func
|
|
243
|
+
|
|
244
|
+
return decorator
|
|
245
|
+
|
|
246
|
+
async def charge(
|
|
247
|
+
self, ctx: Context, msg: Inbound, product: str, sel: dict[str, Any] | None = None
|
|
248
|
+
) -> Reply:
|
|
249
|
+
"""Start the payment flow for a ``@paid`` product from your own code."""
|
|
250
|
+
if self._paywall is None:
|
|
251
|
+
raise ValueError(f"no @agent.paid product named {product!r}")
|
|
252
|
+
return await self._paywall.request(ctx, msg, product, sel or {})
|
|
253
|
+
|
|
254
|
+
# ------------------------------------------------------------------ #
|
|
255
|
+
# Sending
|
|
256
|
+
# ------------------------------------------------------------------ #
|
|
257
|
+
|
|
258
|
+
async def reply(self, ctx: Context, to: str, reply: Reply) -> None:
|
|
259
|
+
"""Send a reply (any handler return value) to ``to``."""
|
|
260
|
+
for message in to_messages(reply):
|
|
261
|
+
for content in message.content:
|
|
262
|
+
if isinstance(content, MetadataContent) and "card_payload" in content.metadata:
|
|
263
|
+
self._known_actions |= collect_actions(
|
|
264
|
+
json.loads(content.metadata["card_payload"])
|
|
265
|
+
)
|
|
266
|
+
await ctx.send(to, message)
|
|
267
|
+
|
|
268
|
+
# ------------------------------------------------------------------ #
|
|
269
|
+
# Protocol plumbing
|
|
270
|
+
# ------------------------------------------------------------------ #
|
|
271
|
+
|
|
272
|
+
async def _on_chat_ack(self, ctx: Context, sender: str, msg: ChatAcknowledgement) -> None:
|
|
273
|
+
ctx.logger.debug(f"ack from {sender} for {msg.acknowledged_msg_id}")
|
|
274
|
+
|
|
275
|
+
async def _on_chat_message(self, ctx: Context, sender: str, msg: ChatMessage) -> None:
|
|
276
|
+
await ctx.send(
|
|
277
|
+
sender,
|
|
278
|
+
ChatAcknowledgement(timestamp=datetime.now(UTC), acknowledged_msg_id=msg.msg_id),
|
|
279
|
+
)
|
|
280
|
+
texts: list[str] = []
|
|
281
|
+
metadata: dict[str, str] = {}
|
|
282
|
+
for content in msg.content:
|
|
283
|
+
if isinstance(content, TextContent):
|
|
284
|
+
texts.append(content.text)
|
|
285
|
+
elif isinstance(content, MetadataContent):
|
|
286
|
+
metadata.update(content.metadata)
|
|
287
|
+
elif isinstance(content, StartSessionContent):
|
|
288
|
+
ctx.logger.info(f"session start from {sender}")
|
|
289
|
+
elif isinstance(content, EndSessionContent):
|
|
290
|
+
ctx.logger.info(f"session end from {sender}")
|
|
291
|
+
raw_text = "\n".join(texts).strip()
|
|
292
|
+
if not raw_text:
|
|
293
|
+
return
|
|
294
|
+
|
|
295
|
+
inbound = Inbound(
|
|
296
|
+
sender=sender,
|
|
297
|
+
text=strip_mention(raw_text),
|
|
298
|
+
session=str(ctx.session),
|
|
299
|
+
raw=msg,
|
|
300
|
+
metadata=metadata,
|
|
301
|
+
selection=parse_selection(raw_text, self._known_actions),
|
|
302
|
+
)
|
|
303
|
+
ctx.logger.info(f"<- {sender[:16]}…: {inbound.text[:200]!r}")
|
|
304
|
+
try:
|
|
305
|
+
reply = await self._dispatch(ctx, inbound)
|
|
306
|
+
except Exception:
|
|
307
|
+
ctx.logger.exception("handler failed")
|
|
308
|
+
reply = self.error_message
|
|
309
|
+
try:
|
|
310
|
+
await self.reply(ctx, sender, reply)
|
|
311
|
+
except Exception:
|
|
312
|
+
ctx.logger.exception("could not send reply")
|
|
313
|
+
await ctx.send(sender, text_message(self.error_message))
|
|
314
|
+
|
|
315
|
+
async def _dispatch(self, ctx: Context, inbound: Inbound) -> Reply:
|
|
316
|
+
action = inbound.action
|
|
317
|
+
if action and action in self._action_handlers:
|
|
318
|
+
return await _maybe_await(
|
|
319
|
+
self._action_handlers[action](ctx, inbound, inbound.selection)
|
|
320
|
+
)
|
|
321
|
+
if self._text_handler is not None:
|
|
322
|
+
return await _maybe_await(self._text_handler(ctx, inbound))
|
|
323
|
+
return "Hi! This agent has no @agent.on_text handler yet."
|
|
324
|
+
|
|
325
|
+
async def _auto_connect(self, ctx: Context) -> None:
|
|
326
|
+
from .register import connect_mailbox
|
|
327
|
+
|
|
328
|
+
if not os.getenv("AGENTVERSE_API_KEY"):
|
|
329
|
+
ctx.logger.warning(
|
|
330
|
+
"AGENTVERSE_API_KEY not set: open the inspector link above and click Connect "
|
|
331
|
+
"(mailbox), or set the key so the agent connects itself."
|
|
332
|
+
)
|
|
333
|
+
return
|
|
334
|
+
result = await connect_mailbox(self)
|
|
335
|
+
if result.ok:
|
|
336
|
+
ctx.logger.info(f"Connected to Agentverse as {result.profile_url}")
|
|
337
|
+
if result.detail:
|
|
338
|
+
ctx.logger.warning(result.detail)
|
|
339
|
+
else:
|
|
340
|
+
ctx.logger.error(f"Agentverse connect failed: {result.detail}")
|