Skip to content

快速开始

环境要求

  • Node.js >= 18(见 package.jsonengines)。
  • node-pty(必需,唯一后端,无降级)
    • Linux:无预编译二进制,安装时从源码编译,需 g++ 支持 C++20(gcc-10 及以上)。
    • Windows / macOS:提供预编译二进制,开箱即用。
  • @xterm/headless(必需):屏幕渲染后端,纯 JS 无编译负担。

安装

bash
npm install @ai-zen/socket-pty

在仓库内本地使用时,先构建再经 dist/ 引入:

bash
npm install
npm run build
node dist/cli.js serve --cmd bash --socket /tmp/x.sock

快速示例

CLI 启动服务

bash
# Unix domain socket(Linux/macOS 首选)
socket-pty serve --cmd bash --socket /tmp/v.sock

# TCP loopback(Windows 首选)
socket-pty serve --cmd bash --port 5174

# Windows:必须带 .exe 后缀
socket-pty serve --cmd powershell.exe --port 5174
socket-pty serve --cmd cmd.exe --port 5174

启动成功后打印:

text
[socket-pty] 会话已启动,命令: bash
[socket-pty] 连接地址: 127.0.0.1:5174

serve 常用选项:--cmd(必填)、--socket / --port(二选一,必给其一)、--cols / --rows(默认 100 / 30)、--cwd

程序化启动

typescript
import { createSocketPty } from "@ai-zen/socket-pty";

const server = createSocketPty({
  endpoint: { type: "unix", path: "/tmp/v.sock" }, // 或 { type: "tcp", port: 5174, host: "127.0.0.1" }
  command: "bash", // Windows 上请用 "powershell.exe" / "cmd.exe"
  cols: 100,
  rows: 30,
});
const address = await server.listen();
// address: unix:/tmp/v.sock

连接并用 JSON-RPC 2.0 交互

连接建立后,每行一条 JSON-RPC 2.0 报文,以 \n 分帧。以下用裸 JSON-RPC 完成一次读终端:

jsonc
// 查询状态
→ {"jsonrpc":"2.0","method":"pty/status","params":{},"id":1}
← {"jsonrpc":"2.0","result":{"running":true,"exitCode":null,"pid":1234},"id":1}

// 写入一条命令
→ {"jsonrpc":"2.0","method":"pty/write","params":{"action":[{"text":"echo hello"},{"key":"Enter"}]},"id":2}
← {"jsonrpc":"2.0","result":{"written":11},"id":2}

// 等待输出出现
→ {"jsonrpc":"2.0","method":"pty/wait","params":{"match":"hello","timeout":6000},"id":3}
← {"jsonrpc":"2.0","result":{"matched":true,"screen":"...","cursor":{"row":2,"col":1},"size":{"cols":100,"rows":30},"waitedMs":45},"id":3}

// 读取当前屏
→ {"jsonrpc":"2.0","method":"pty/read","params":{},"id":4}
← {"jsonrpc":"2.0","result":{"screen":"...","cursor":{"row":2,"col":1},"size":{"cols":100,"rows":30}},"id":4}

// 终止会话并关闭端点
→ {"jsonrpc":"2.0","method":"pty/kill","params":{},"id":5}
← {"jsonrpc":"2.0","result":{},"id":5}

命令与平台注意事项

command / --cmd 指定被托管的命令,由调用方负责传入当前平台可用的命令:

平台推荐命令说明
Linux / macOSbash也可传 zshshnode -i
Windowspowershell.exe / cmd.exe必须带 .exe 后缀

Windows 上 node-pty(ConPTY)对裸命令名不做 PATH 搜索:传 powershellbash 这类不带 .exe 的名字会报 File not found。应传带后缀的可执行名,或完整路径(如 C:\Program Files\Git\bin\bash.exe)。

下一步

  • 查看协议与 API 参考,了解 pty/readpty/writepty/waitpty/statuspty/resizepty/kill 的完整报文与错误码。
  • 在 MCP 宿主中接入终端能力,详见 MCP 适配

MIT / ISC License