@a-tether/pi 0.1.0 → 0.1.1

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.
package/README.md CHANGED
@@ -1,18 +1,16 @@
1
1
  # @a-tether/pi
2
2
 
3
- Pi 插件和启动器,经 SSH 隧道使用另一台电脑(C)上运行 [`@a-tether/server`](https://www.npmjs.com/package/@a-tether/server) 的 Claude Code。
3
+ Pi 插件和启动器:通过端口转发,使用另一台电脑(C)上 [`@a-tether/server`](https://www.npmjs.com/package/@a-tether/server) 提供的 Claude Code。
4
4
 
5
- **需要先自行安装 Pi**(`npm install -g @earendil-works/pi-coding-agent`)。本包不会安装 Pi。
5
+ **需要先自行安装 Pi**(`npm install -g @earendil-works/pi-coding-agent`),本包不会安装 Pi。
6
6
 
7
7
  ```sh
8
- export A_TETHER_URL=http://127.0.0.1:7311 # SSH 隧道在 A 上的端口
9
- export A_TETHER_TOKEN="$(ssh user@C 'cat ~/.config/a-tether/token')"
10
- cd /path/to/your/project
11
- npx -y @a-tether/pi # 启动带插件的 Pi;全局安装后命令为 a-tether-pi
8
+ npx -y @a-tether/pi login <令牌> # 只需一次;命令由 C 端服务首次启动时打印
9
+ pi install npm:@a-tether/pi # 把插件装进 Pi,之后在项目目录直接运行 pi
12
10
  ```
13
11
 
14
- 或者持久安装插件:`pi install npm:@a-tether/pi`,之后直接运行 `pi`。
12
+ 也可以不安装插件,每次用 `npx -y @a-tether/pi` 启动带插件的 Pi;其余参数原样传给 Pi,例如 `npx -y @a-tether/pi --model a-tether/claude-opus-5-5`。
15
13
 
16
- - 其余参数原样传给 Pi,例如 `npx @a-tether/pi --model a-tether/claude-opus-5-5`。
17
- - `pi` 不在 PATH 中时,可设置 `A_TETHER_PI` 为它的绝对路径。
18
- - 在 Pi 中运行 `/a-tether-status` 检查连接。完整配置见 [setup 文档](https://github.com/SandyKidYao/a-tether/blob/main/docs/setup.md)。
14
+ - 令牌和连接地址保存在 `~/.a-tether/settings.json`,默认连接 `http://127.0.0.1:7310`。A 和 C 是同一台电脑时无需 login。
15
+ - 在 Pi 中运行 `/a-tether-status` 检查连接。
16
+ - 完整说明见 [README](https://github.com/SandyKidYao/a-tether#readme)。
@@ -1,22 +1,16 @@
1
- import { defaultUrl, messages } from "../shared/protocol.js";
2
- function endpoint() {
3
- const url = new URL(process.env.A_TETHER_URL || defaultUrl);
4
- if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
5
- throw new Error("A_TETHER_URL 必须指向 SSH 隧道的 http://127.0.0.1:端口");
6
- }
7
- return url.origin;
8
- }
1
+ import { messages } from "../shared/protocol.js";
2
+ import { loadSettings } from "../shared/settings.js";
9
3
  export function errorMessage(code) {
10
4
  return typeof code === "string" && Object.hasOwn(messages, code) ? messages[code] : messages.backend;
11
5
  }
6
+ // Settings are read on every request, so `login` takes effect without restarting Pi.
12
7
  export async function request(path, init = {}) {
13
- const token = process.env.A_TETHER_TOKEN;
8
+ const { token, client } = loadSettings();
14
9
  if (!token)
15
- throw new Error(messages.unauthorized);
16
- const url = endpoint() + path;
10
+ throw new Error(messages.token);
17
11
  let res;
18
12
  try {
19
- res = await fetch(url, { ...init, redirect: "error", headers: { authorization: "Bearer " + token, "content-type": "application/json" } });
13
+ res = await fetch(client.url + path, { ...init, redirect: "error", headers: { authorization: "Bearer " + token, "content-type": "application/json" } });
20
14
  }
21
15
  catch {
22
16
  throw new Error(messages.connection);
@@ -4,6 +4,7 @@ import { spawn } from "node:child_process";
4
4
  import { accessSync, constants, statSync } from "node:fs";
5
5
  import { delimiter, join } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
+ import { displayPath, loadSettings, saveToken } from "../../shared/settings.js";
7
8
  const extension = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./extension.ts" : "./extension.js", import.meta.url));
8
9
  const subcommands = new Set(["install", "remove", "uninstall", "update", "list", "config", "auth", "mcp"]);
9
10
  const windows = process.platform === "win32";
@@ -19,9 +20,9 @@ function executable(file) {
19
20
  return false;
20
21
  }
21
22
  }
22
- export function findPi(env = process.env) {
23
- if (env.A_TETHER_PI)
24
- return executable(env.A_TETHER_PI) ? env.A_TETHER_PI : undefined;
23
+ export function findPi(env = process.env, configured = loadSettings().client.pi) {
24
+ if (configured)
25
+ return executable(configured) ? configured : undefined;
25
26
  const names = windows ? ["pi.cmd", "pi.exe", "pi"] : ["pi"];
26
27
  for (const dir of (env.PATH ?? "").split(delimiter)) {
27
28
  if (!dir)
@@ -39,22 +40,47 @@ export function piArgs(args) {
39
40
  const hasModel = args.some(arg => arg === "--model" || arg.startsWith("--model="));
40
41
  return ["-e", extension, ...(hasModel ? [] : ["--model", "a-tether/default"]), ...args];
41
42
  }
43
+ export function login(args) {
44
+ if (args.length !== 1)
45
+ throw new Error("用法:npx -y @a-tether/pi login <令牌>\n令牌在 C 上运行 npx -y @a-tether/server token 查看。");
46
+ saveToken(args[0]);
47
+ return [
48
+ `令牌已保存到 ${displayPath}。`,
49
+ "接下来在项目目录运行 pi(已用 pi install npm:@a-tether/pi 安装插件时)或 npx -y @a-tether/pi,",
50
+ "在 Pi 中运行 /a-tether-status 检查连接。",
51
+ ].join("\n");
52
+ }
42
53
  function main() {
43
- const pi = findPi();
54
+ const argv = process.argv.slice(2);
55
+ if (argv[0] === "login") {
56
+ try {
57
+ console.log(login(argv.slice(1)));
58
+ }
59
+ catch (error) {
60
+ console.error(error.message);
61
+ process.exitCode = 1;
62
+ }
63
+ return;
64
+ }
65
+ let pi;
66
+ try {
67
+ pi = findPi();
68
+ }
69
+ catch (error) {
70
+ console.error(error.message);
71
+ process.exit(1);
72
+ }
44
73
  if (!pi) {
45
74
  console.error([
46
- "a-tether-pi 需要本机已安装的 Pi,但在 PATH 中找不到 pi 命令。",
75
+ "a-tether-pi 需要本机已安装的 Pi,但找不到 pi 命令。",
47
76
  "请先自行安装 Pi,例如:",
48
77
  " npm install -g @earendil-works/pi-coding-agent",
49
78
  "安装后确认 `pi --version` 可以运行,再重新执行 a-tether-pi。",
50
- "如果 pi 不在 PATH 中,可设置 A_TETHER_PI 为它的绝对路径。",
79
+ `如果 pi 不在 PATH 中,可在 ${displayPath} 的 client.pi 填写它的绝对路径。`,
51
80
  ].join("\n"));
52
81
  process.exit(1);
53
82
  }
54
- const args = piArgs(process.argv.slice(2));
55
- if (!process.env.A_TETHER_TOKEN && args[0] === "-e") {
56
- console.error("提示:未设置 A_TETHER_TOKEN,Pi 将无法连接 C 端服务。");
57
- }
83
+ const args = piArgs(argv);
58
84
  // Windows .cmd shims can only be started through a shell.
59
85
  const shell = windows && /\.cmd$/i.test(pi);
60
86
  const quote = (value) => shell ? `"${value.replace(/"/g, '""')}"` : value;
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { createProvider, createAssistantMessageEventStream } from "@earendil-works/pi-ai";
3
3
  import { api, defaultUrl, generationOptions, messages, providerId } from "../../shared/protocol.js";
4
4
  import { request, errorMessage } from "../../client/http.js";
5
+ import { displayPath, loadSettings } from "../../shared/settings.js";
5
6
  export const remoteStream = (model, context, options) => {
6
7
  const stream = createAssistantMessageEventStream();
7
8
  const id = randomUUID();
@@ -107,18 +108,31 @@ export const remoteStream = (model, context, options) => {
107
108
  export default function extension(pi) {
108
109
  pi.registerProvider(createProvider({
109
110
  id: providerId, name: "A-tether · Remote Claude", baseUrl: defaultUrl,
111
+ // Always report the provider as configured so its models stay listed. A missing
112
+ // or wrong token is explained when Pi starts and on each request instead.
110
113
  auth: { apiKey: {
111
114
  name: "A-tether token",
112
- async check() { return process.env.A_TETHER_TOKEN ? { type: "api_key", source: "A_TETHER_TOKEN" } : undefined; },
113
- async resolve() { return { auth: { apiKey: "a-tether" }, source: "A_TETHER_TOKEN" }; },
115
+ async check() { return { type: "api_key", source: displayPath }; },
116
+ async resolve() { return { auth: { apiKey: "a-tether" }, source: displayPath }; },
114
117
  } },
115
118
  models: [{ id: "default", name: "Default (C)", api, provider: providerId, baseUrl: defaultUrl, reasoning: true,
116
119
  input: ["text", "image"], contextWindow: 200000, maxTokens: 64000, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
117
120
  async fetchModels({ signal }) { return (await request("/v1/models", { signal })).json(); },
118
121
  api: { stream: remoteStream, streamSimple: remoteStream },
119
122
  }));
123
+ pi.on("session_start", (event, ctx) => {
124
+ if (event.reason !== "startup")
125
+ return;
126
+ try {
127
+ if (!loadSettings().token)
128
+ ctx.ui.notify(messages.token, "warning");
129
+ }
130
+ catch (error) {
131
+ ctx.ui.notify(error.message, "error");
132
+ }
133
+ });
120
134
  pi.registerCommand("a-tether-status", {
121
- description: "Check the SSH tunnel and Claude Code login on C",
135
+ description: "Check the connection to C and Claude Code login on C",
122
136
  handler: async (_args, ctx) => {
123
137
  try {
124
138
  const health = await (await request("/v1/health", { signal: ctx.signal })).json();
@@ -3,7 +3,8 @@ export const api = "a-tether-v1";
3
3
  export const defaultUrl = "http://127.0.0.1:7310";
4
4
  export const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
5
5
  export const messages = {
6
- unauthorized: "A-tether 认证失败,请检查两端的 A_TETHER_TOKEN。",
6
+ unauthorized: "A-tether 令牌与 C 端不一致。在 C 上运行 npx -y @a-tether/server token,再在本机运行它给出的 login 命令。",
7
+ token: "A-tether 还没有配置令牌。在 C 上运行 npx -y @a-tether/server token,再在本机运行它给出的 login 命令。",
7
8
  unavailable: "C 上找不到 Claude Code,请检查服务进程的 PATH。",
8
9
  login: "C 上的 Claude Code 尚未登录或登录已失效。",
9
10
  quota: "Claude 额度、速率或计费限制,请在 C 上检查账户。",
@@ -16,7 +17,7 @@ export const messages = {
16
17
  invalid: "请求格式或模型 ID 无效。",
17
18
  duplicate: "请求 ID 已在使用。",
18
19
  large: "请求超过 32 MiB 上限。",
19
- connection: "A-tether 连接中断,请检查 SSH 隧道和 C 端服务。",
20
+ connection: "A-tether 连接中断,请检查端口转发(如 SSH 隧道)和 C 端服务。",
20
21
  };
21
22
  // Runtime whitelist on BOTH ends. In particular, never forward env, headers,
22
23
  // sessionId, filesystem paths, credentials, or callbacks from Pi.
@@ -0,0 +1,108 @@
1
+ // Both ends read ~/.a-tether/settings.json. On one machine they share the file,
2
+ // so the token generated by the server works for the Pi plugin without setup.
3
+ import { randomBytes } from "node:crypto";
4
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
+ import { isIPv4, isIPv6 } from "node:net";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join } from "node:path";
8
+ export const displayPath = "~/.a-tether/settings.json";
9
+ export const settingsPath = () => join(homedir(), ".a-tether", "settings.json");
10
+ export class SettingsError extends Error {
11
+ }
12
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13
+ // Printable ASCII only: the token travels in an HTTP header.
14
+ export const validToken = (value) => typeof value === "string" && /^[\x21-\x7e]{32,}$/.test(value);
15
+ export const generateToken = () => randomBytes(32).toString("hex");
16
+ export const loginCommand = (token) => "npx -y @a-tether/pi login " + token;
17
+ export function isLoopback(host) {
18
+ const h = host.toLowerCase();
19
+ if (h === "localhost")
20
+ return true;
21
+ if (isIPv4(h))
22
+ return h.startsWith("127.");
23
+ return isIPv6(h) && (/^(0{1,4}:){7}0{0,3}1$/.test(h) || h === "::1" || /^::ffff:127\./.test(h));
24
+ }
25
+ function readRaw(file) {
26
+ let text;
27
+ try {
28
+ text = readFileSync(file, "utf8");
29
+ }
30
+ catch (error) {
31
+ if (error.code === "ENOENT")
32
+ return undefined;
33
+ throw new SettingsError(`无法读取 ${file}:${error.message}`);
34
+ }
35
+ let data;
36
+ try {
37
+ data = JSON.parse(text);
38
+ }
39
+ catch {
40
+ throw new SettingsError(`${file} 不是合法的 JSON,请修正或删除后重试。`);
41
+ }
42
+ if (!isObject(data))
43
+ throw new SettingsError(`${file} 的内容必须是一个 JSON 对象。`);
44
+ return data;
45
+ }
46
+ export function loadSettings(file = settingsPath()) {
47
+ const raw = readRaw(file) ?? {};
48
+ const fail = (field, rule) => { throw new SettingsError(`${file} 中的 ${field} ${rule}。`); };
49
+ const section = (name) => {
50
+ const value = raw[name];
51
+ if (value === undefined)
52
+ return {};
53
+ return isObject(value) ? value : fail(name, "必须是对象");
54
+ };
55
+ const text = (obj, field) => {
56
+ const value = obj[field.split(".")[1]];
57
+ if (value === undefined)
58
+ return undefined;
59
+ return typeof value === "string" && value.trim() ? value : fail(field, "必须是非空字符串");
60
+ };
61
+ const server = section("server");
62
+ const client = section("client");
63
+ if (raw.token !== undefined && !validToken(raw.token))
64
+ fail("token", "必须是至少 32 个字符的字符串,只含字母、数字和符号,不含空白");
65
+ const port = server.port ?? 7310;
66
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)
67
+ fail("server.port", "必须是 1–65535 的整数");
68
+ const allowUsageCredits = server.allowUsageCredits ?? false;
69
+ if (typeof allowUsageCredits !== "boolean")
70
+ fail("server.allowUsageCredits", "必须是 true 或 false");
71
+ // Without client.url, Pi on the same machine follows server.port.
72
+ const url = text(client, "client.url") ?? "http://127.0.0.1:" + port;
73
+ let origin = "";
74
+ try {
75
+ const parsed = new URL(url);
76
+ if (parsed.protocol === "http:" && parsed.hostname && !parsed.username && !parsed.password &&
77
+ parsed.pathname === "/" && !parsed.search && !parsed.hash)
78
+ origin = parsed.origin;
79
+ }
80
+ catch { }
81
+ if (!origin)
82
+ fail("client.url", "必须形如 http://127.0.0.1:7310(不带路径和账号密码)");
83
+ return {
84
+ token: raw.token,
85
+ server: { host: text(server, "server.host") ?? "127.0.0.1", port: port,
86
+ claude: text(server, "server.claude") ?? "claude", allowUsageCredits: allowUsageCredits },
87
+ client: { url: origin, pi: text(client, "client.pi") },
88
+ };
89
+ }
90
+ // Replaces only the token and keeps every other field. Writes a private temp
91
+ // file and renames it, so an interrupted write never leaves half a file.
92
+ export function saveToken(token, file = settingsPath()) {
93
+ if (!validToken(token))
94
+ throw new SettingsError("令牌必须是至少 32 个字符的字符串,只含字母、数字和符号,不含空白。请完整复制 C 端打印的令牌。");
95
+ const data = { ...readRaw(file), token };
96
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
97
+ chmodSync(dirname(file), 0o700); // mode above only applies when the directory is new
98
+ const temp = `${file}.${process.pid}.tmp`;
99
+ try {
100
+ writeFileSync(temp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
101
+ chmodSync(temp, 0o600);
102
+ renameSync(temp, file);
103
+ }
104
+ catch (error) {
105
+ rmSync(temp, { force: true });
106
+ throw error;
107
+ }
108
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-tether/pi",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Pi extension and launcher that uses a remote Claude Code through an A-tether SSH tunnel.",
5
5
  "type": "module",
6
6
  "license": "MIT",