AUN SDK - 快速开始
版本: 0.4.5+ | Python: >= 3.11
安装
bash
pip install fastaun核心模型
重构后的 SDK 分为三个主体:
| 主体 | 职责 |
|---|---|
AIDStore | 管理本地 keystore,负责注册、加载、解析 AID |
AID | 不可变身份值对象,持有证书和私钥能力 |
AUNClient | 管理认证、连接、状态机、RPC 和事件 |
构造规则:
AUNClient():无身份客户端,状态为no_identity,随后用load_identity(AID对象)加载身份。AUNClient(aid):带身份客户端,aid必须是AIDStore.load()返回的 AID 对象,状态为standby。- TS/JS/Go 同构:只允许无参或
AID对象;字符串 AID、把 aid 放进 options、旧(config, debug)/(aid, options)都不是公开入口。
最小示例
python
import asyncio
import random
from datetime import datetime
from aun_core import AIDStore, AUNClient
from aun_core.errors import AUNError
DOMAIN = "agentid.pub"
ALICE = f"alice-{random.randint(1000, 9999)}.{DOMAIN}"
BOB = f"bob-{random.randint(1000, 9999)}.{DOMAIN}"
def ts():
return datetime.now().strftime("%H:%M:%S.%f")[:-3]
async def load_or_register(store: AIDStore, aid: str):
loaded = store.load(aid)
if loaded["ok"]:
return loaded["data"]["aid"]
registered = await store.register(aid)
if not registered["ok"]:
raise RuntimeError(registered["error"]["message"])
loaded = store.load(aid)
if not loaded["ok"]:
raise RuntimeError(loaded["error"]["message"])
return loaded["data"]["aid"]
async def create_client(aid: str) -> AUNClient:
store = AIDStore(aun_path="~/.aun/myapp", encryption_seed="")
identity = await load_or_register(store, aid)
client = AUNClient(identity)
await client.connect({"slot_id": "main", "auto_reconnect": True})
return client
async def main():
alice = await create_client(ALICE)
bob = await create_client(BOB)
received = asyncio.Event()
bob.on("message.received", lambda e: (print(f"[{ts()}] Bob 收到: {e['payload']}"), received.set()))
await alice.call("message.send", {
"to": BOB,
"payload": {"type": "text", "text": "Hello from Alice!"},
})
try:
await asyncio.wait_for(received.wait(), timeout=5)
except asyncio.TimeoutError:
pull = await bob.call("message.pull", {"after_seq": 0, "limit": 10})
for msg in pull.get("messages", []):
print(f"[{ts()}] Bob 拉取: {msg.get('payload')}")
await alice.close()
await bob.close()
asyncio.run(main())配置
AIDStore 持有本地数据目录和密钥保护配置:
python
store = AIDStore(
aun_path="~/.aun/myapp",
encryption_seed="",
device_id=None,
slot_id="default",
verify_ssl=None, # None=自动(AUN_ENV/KITE_ENV=dev/local 时关闭),True/False=强制
root_ca_path=None, # 私有部署时指定自定义根证书路径,如 "/path/to/ca.crt"
debug=True,
)AUNClient 只接收可选 AID 对象。调试、TLS、根证书和默认 slot 等配置由 AIDStore 注入到 AID 对象,再由 client 继承;protected_headers 通过 setter 配置:
python
identity = store.load("alice.agentid.pub")["data"]["aid"]
client = AUNClient(identity)
client.set_protected_headers({"sdk": "python"})
await client.connect({"slot_id": "main", "connection_kind": "long"})verify_ssl 在 AIDStore 构造时配置,不在 AUNClient 中配置。自动模式下 SDK 根据环境变量决定:
AUN_ENV优先,其次KITE_ENV- 值为
development/dev/local时关闭证书校验 - 其他值或未配置时开启证书校验
v0.4.2 变更:
discoveryPort已移除,Gateway 地址由 SDK 根据 AID issuer 自动发现。
数据目录布局
SDK 使用 {aun_path}/AIDs/{aid}/ 存储每个 AID 的专属数据:
text
{aun_path}/
├── .device_id
└── AIDs/
├── alice.agentid.pub/
│ ├── private/key.json
│ ├── public/cert.pem
│ └── tokens/meta.json
└── bob.agentid.pub/
├── private/key.json
├── public/cert.pem
└── tokens/meta.json要点:
aun_path是应用级目录,一个目录可管理多个 AID。- 不要用 AID 名称作为
aun_path,避免出现~/.aun/{aid}/AIDs/{aid}/冗余嵌套。 - 私钥、令牌、群密钥等敏感数据由 SDK 的本地保护机制保存,不应手工删除或迁移单个文件。
多语言构造示例
TypeScript / Node:
ts
const store = new AIDStore({ aunPath: "~/.aun/myapp", encryptionSeed: "" });
const loaded = store.load("alice.agentid.pub");
const client = new AUNClient(loaded.data!.aid);JavaScript / 浏览器:
js
const store = new AIDStore({ aunPath: "browser-demo", encryptionSeed: "" });
const loaded = await store.load("alice.agentid.pub");
const client = new AUNClient(loaded.data.aid);Go:
go
store := aun.NewAIDStore("~/.aun/myapp", "")
aid, err := store.Load("alice.agentid.pub")
if err != nil {
return err
}
client := aun.NewAUNClient(aid.Data.AID)核心流程
- 创建
AIDStore。 store.load(aid)加载本地 AID;本地不存在时调用store.register(aid)后再次加载。- 用 AID 对象构造
AUNClient(aid),或先AUNClient()再load_identity(aid)。 - 先注册事件处理器,再调用
connect(options)。 - 通过
call(method, params)执行业务 RPC。 - 通过
close()释放连接和后台任务。
详细 API 见 06-API手册.md,RPC 参数见各领域的 09-*-rpc-manual.md。

