Local Agent

通过 RPC 与 HTTP 暴露 Agent

使用 @downcity/server 提供的 AgentRPC 和 AgentHTTP 把本地 Agent 暴露成网络服务

通过 RPC 与 HTTP 暴露 Agent

@downcity/agent 只负责构造 Agent 和运行会话。网络暴露能力放在独立包 @downcity/server 里,按需引入。

pnpm add @downcity/agent @downcity/server

Agent 不再有 start()

new Agent(...) 之后,plugin lifecycle 和 ActionSchedule 会自动启动。无需再手动调用 start()

  • await agent.ready():等待后台服务启动完成。在构造之后立刻读取 plugin 状态时使用。
  • await agent.dispose():释放后台资源(plugins、ActionSchedule、shell)。

RPC 与 HTTP 不再是 Agent 的职责。

AgentRPC:暴露为本机 RPC

AgentRPCAgent 通过 NDJSON-over-TCP 暴露给 RemoteAgent("rpc://...") 使用。

import { Agent } from "@downcity/agent";
import { AgentRPC } from "@downcity/server";

const agent = new Agent({
  id,
  path,
  prepare_session: async (session) => await session.set({ model }),
});
await agent.ready();

const rpc = new AgentRPC(agent);
const binding = await rpc.listen({ host: "127.0.0.1", port: 15314 });
console.log(binding.url); // rpc://127.0.0.1:15314

// 关闭
await rpc.close();
await agent.dispose();

AgentRPC 默认监听 127.0.0.1:15314,协议为 NDJSON,无鉴权,仅用于本机或可信网络。

AgentHTTP:暴露最小 SDK HTTP 表面

AgentHTTP 提供 RemoteAgent HTTP 客户端所需的最小 HTTP 表面(/api/sdk/sessions/*)。两种用法二选一。

方式 1:独立 HTTP server

import { Agent } from "@downcity/agent";
import { AgentHTTP } from "@downcity/server";

const agent = new Agent({
  id,
  path,
  prepare_session: async (session) => await session.set({ model }),
});
await agent.ready();

const http = new AgentHTTP(agent);
const binding = await http.server().listen({ host: "127.0.0.1", port: 5314 });
console.log(binding.url); // http://127.0.0.1:5314

// 关闭
await http.close();
await agent.dispose();

方式 2:挂载到你自己的 Hono server

AgentHTTP.router() 返回一个 Hono 子路由,可以直接挂载:

import { Hono } from "hono";
import { AgentHTTP } from "@downcity/server";

const app = new Hono();
const http = new AgentHTTP(agent);
app.route("/", http.router());

CORS / logger / 鉴权等中间件由你自行决定。AgentHTTP 不会附带任何中间件。

与 Downcity、RemoteAgent 的关系

  • downcity agent start 内部就是把 Agent + AgentRPC + AgentHTTP.router() 组装起来,再叠加 Downcity 自己的控制 / 静态资源路由。
  • RemoteAgent 客户端可以连到 AgentRPC.listen() 暴露的 rpc:// 地址,或 AgentHTTP 暴露的 HTTP 表面。

相关文档