npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

zai-agent

v0.1.0

Published

Zai agent SDK

Readme

zai-agent

English

zai-agent 是基于 pi coding agent 运行时的 TypeScript SDK,用于构建 AI Agent 应用程序。它负责模型选择、技能加载、会话持久化和事件流处理,让你专注于应用逻辑本身。

安装

npm install zai-agent

需要 Node.js >= 20.6.0。

前置条件

至少需要配置一个 LLM 提供商的 API Key,通过环境变量读取,例如:

export ANTHROPIC_API_KEY=sk-ant-...
export OPENAI_API_KEY=sk-...

完整的提供商列表和环境变量名称请参考 pi-ai 提供商文档

快速开始

import { ZaiAgent } from "zai-agent";

const agent = new ZaiAgent();
const { session } = await agent.createSession();

// 在发送提示前订阅流式事件
const unsubscribe = session.subscribe((event) => {
  if (event.type === "message_update") {
    const content = event.message.content;
    if (Array.isArray(content)) {
      for (const block of content) {
        if (block.type === "text") process.stdout.write(block.text);
      }
    }
  }
  if (event.type === "agent_end") {
    console.log("\n[完成]");
    unsubscribe();
  }
});

await session.prompt("列出当前目录下的文件。");

示例:自定义工具

import { ZaiAgent } from "zai-agent";
import { Type } from "@sinclair/typebox";

const agent = new ZaiAgent({ cwd: process.cwd() });

const { session } = await agent.createSession({
  customTools: [
    {
      name: "get_time",
      label: "获取当前时间",
      description: "返回当前 UTC 时间的 ISO 格式字符串。",
      parameters: Type.Object({}),
      async execute(_id, _params, _signal) {
        return {
          content: [{ type: "text", text: new Date().toISOString() }],
          details: undefined,
        };
      },
    },
  ],
});

const unsubscribe = session.subscribe((event) => {
  if (event.type === "message_update") {
    const content = event.message.content;
    if (Array.isArray(content)) {
      for (const block of content) {
        if (block.type === "text") process.stdout.write(block.text);
      }
    }
  }
  if (event.type === "agent_end") {
    console.log();
    unsubscribe();
  }
});

await session.prompt("现在是几点?");

示例:续接上次会话

import { ZaiAgent } from "zai-agent";

const agent = new ZaiAgent();

// 第一个会话
const { session: s1 } = await agent.createSession();
await s1.prompt("请记住数字 42。");

// 稍后:恢复最近一次会话,继续对话
const { session: s2 } = await agent.createSession({ continueSession: true });
await s2.prompt("我让你记住的是哪个数字?");

示例:指定模型

import { ZaiAgent } from "zai-agent";
import { getModel } from "@mariozechner/pi-ai";

const agent = new ZaiAgent();

const { session } = await agent.createSession({
  model: getModel("anthropic", "claude-opus-4-5"),
  thinkingLevel: "high",
});

await session.prompt("用简单的语言解释量子纠缠。");

API 参考

ZaiAgent

new ZaiAgent(options?: ZaiAgentOptions)

| 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | agentDir | string | ~/.zai | 全局配置目录(存放设置、会话、技能文件) | | cwd | string | process.cwd() | 项目工作目录,用于发现项目级技能文件 |

属性

| 属性 | 类型 | 说明 | |------|------|------| | settingsManager | SettingsManager | 访问或修改 Agent 配置 | | sessions | SessionManager | 访问会话历史与管理功能 |

方法

agent.createSession(options?: ZaiSessionOptions): Promise<ZaiSessionResult>

ZaiSessionOptions

| 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | model | Model<any> | 来自设置 | 使用的 LLM 模型(通过 @mariozechner/pi-aigetModel() 获取) | | thinkingLevel | ThinkingLevel | "medium" | 思考深度:"off""minimal""low""medium""high""xhigh" | | tools | Tool[] | codingTools | 启用的内置工具(read、bash、edit、write) | | customTools | ToolDefinition[] | [] | 额外注册的自定义工具 | | continueSession | boolean | false | 是否续接最近一次已保存的会话 |

ZaiSessionResult

| 字段 | 类型 | 说明 | |------|------|------| | session | AgentSession | 创建好的会话对象 | | skillDiagnostics | ResourceDiagnostic[] | 技能加载时的警告或错误信息 | | modelFallbackMessage | string \| undefined | 若请求的模型不可用并使用了回退模型,则会设置此字段 |

AgentSession(核心方法)

// 发送提示并等待 Agent 完成
session.prompt(text: string, options?: PromptOptions): Promise<void>

// 订阅流式事件,返回取消订阅函数
session.subscribe(listener: (event: AgentSessionEvent) => void): () => void

// 在 Agent 运行中途注入引导消息(steering)
session.steer(text: string): Promise<void>

// 在 Agent 完成后追加一条后续消息(follow-up)
session.followUp(text: string): Promise<void>

事件类型(AgentSessionEvent

| 事件类型 | 触发时机 | |----------|---------| | agent_start | Agent 开始处理一轮对话 | | agent_end | Agent 完成(无更多工具调用或后续消息) | | turn_start | 单次 LLM 调用开始 | | turn_end | 单次 LLM 调用结束(包含工具结果) | | message_start | 新消息开始(流式传输启动) | | message_update | 流式消息收到新内容 | | message_end | 消息完整接收完毕 | | tool_execution_start | 工具调用开始 | | tool_execution_update | 工具流式返回部分结果 | | tool_execution_end | 工具调用完成 | | auto_compaction_start | 上下文窗口压缩开始 | | auto_compaction_end | 上下文窗口压缩结束 |

目录结构

~/.zai/
  settings.json      # 全局配置(模型、快捷键等)
  sessions/          # 已保存的对话会话
  skills/            # 全局技能文件(.md 格式)

<项目目录>/
  .zai/
    skills/          # 项目级技能文件