@a-tether/server 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SandyKid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
1
+ # @a-tether/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A-tether 的 C 端服务:把 C 上已登录的 Claude Code 借给另一台电脑(A)上的 Pi 使用。A 端请使用 [`@a-tether/pi`](https://www.npmjs.com/package/@a-tether/pi)。
4
+
5
+ ```sh
6
+ npx -y @a-tether/server # 全局安装后命令为 a-tether-server
7
+ npx -y @a-tether/server token # 再次显示 A 端的配置命令
8
+ ```
9
+
10
+ - 第一次启动会生成令牌,保存到 `~/.a-tether/settings.json`,并打印一行 `npx -y @a-tether/pi login <令牌>`,到 A 上运行一次即可。A 和 C 是同一台电脑时不需要这一步。
11
+ - 默认只监听 `127.0.0.1:7310`,A 通过 SSH 隧道等端口转发连接。端口、监听地址、`claude` 路径等都在 `~/.a-tether/settings.json` 中配置。
12
+ - 需要 C 上已登录的 `claude` CLI。
13
+ - 请求失败时在终端输出一行脱敏诊断,不记录对话内容或令牌。
14
+ - 完整说明见 [README](https://github.com/SandyKidYao/a-tether#readme)。
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,132 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createInterface } from "node:readline";
3
+ import { randomUUID } from "node:crypto";
4
+ import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
5
+ import { api, providerId, defaultUrl } from "../../shared/protocol.js";
6
+ import { loadSettings } from "../../shared/settings.js";
7
+ export const isolated = ["-p", "--tools", "", "--setting-sources", "", "--strict-mcp-config",
8
+ "--settings", JSON.stringify({ disableAllHooks: true }), "--disable-slash-commands", "--no-session-persistence", "--permission-mode", "dontAsk"];
9
+ export const streaming = ["--verbose", "--input-format", "stream-json", "--output-format", "stream-json"];
10
+ export async function invoke(args, options) {
11
+ const { signal } = options;
12
+ signal?.throwIfAborted();
13
+ const env = { ...process.env, ...options.env };
14
+ const command = loadSettings().server.claude;
15
+ delete env.ANTHROPIC_API_KEY;
16
+ delete env.A_TETHER_TOKEN; // a leftover 0.1.0 variable must not reach Claude either
17
+ if (env.ANTHROPIC_BASE_URL || env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_FOUNDRY_API_KEY ||
18
+ ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"].some(k => env[k] && !["false", "0"].includes(env[k]))) {
19
+ throw new Error("Conflicting backend configuration");
20
+ }
21
+ Object.assign(env, { ENABLE_TOOL_SEARCH: "false", CLAUDE_CODE_DISABLE_FILE_MENTIONS: "1",
22
+ CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1", DISABLE_AUTOUPDATER: "1",
23
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1" });
24
+ const child = spawn(command, args, { cwd: options.cwd, env, detached: process.platform !== "win32", windowsHide: true,
25
+ stdio: ["pipe", "pipe", "pipe"] });
26
+ // Keep only a short stderr tail for the C diagnostic log.
27
+ let stderr = "";
28
+ child.stderr.setEncoding("utf8");
29
+ child.stderr.on("data", (data) => { stderr = (stderr + data).slice(-4096); });
30
+ const closed = new Promise((resolve, reject) => {
31
+ child.once("error", reject);
32
+ child.once("close", code => resolve(code ?? -1));
33
+ });
34
+ const stop = () => {
35
+ if (!child.pid)
36
+ return;
37
+ if (process.platform === "win32") {
38
+ if (child.exitCode !== null || child.signalCode !== null)
39
+ return;
40
+ spawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore", windowsHide: true }).on("error", () => child.kill());
41
+ }
42
+ else {
43
+ try {
44
+ process.kill(-child.pid, "SIGKILL");
45
+ }
46
+ catch {
47
+ child.kill();
48
+ }
49
+ }
50
+ };
51
+ // A CLI launcher can exit while an MCP descendant still owns its pipes.
52
+ if (process.platform !== "win32")
53
+ child.once("exit", stop);
54
+ signal?.addEventListener("abort", stop, { once: true });
55
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
56
+ child.stdin.on("error", () => { }); // A short-lived CLI can exit before consuming stdin.
57
+ try {
58
+ child.stdin.end(options.input);
59
+ const output = (async () => { for await (const line of lines)
60
+ options.onLine(line); })();
61
+ const [code] = await Promise.all([closed, output]);
62
+ signal?.throwIfAborted();
63
+ return { code, stderr: stderr.trim() };
64
+ }
65
+ finally {
66
+ stop();
67
+ await closed.catch(() => { });
68
+ lines.close();
69
+ signal?.removeEventListener("abort", stop);
70
+ }
71
+ }
72
+ function deadline(signal) {
73
+ const timeout = AbortSignal.timeout(20000);
74
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
75
+ }
76
+ export async function getClaudeStatus(env, signal) {
77
+ let data = "";
78
+ let result = { code: 0, stderr: "" };
79
+ try {
80
+ result = await invoke(["auth", "status"], { env, signal: deadline(signal), onLine: line => { data = (data + line).slice(-65536); } });
81
+ const status = JSON.parse(data);
82
+ const diagnostic = typeof status.loggedIn !== "boolean";
83
+ return { available: true, loggedIn: status.loggedIn === true, diagnostic,
84
+ detail: diagnostic ? "unexpected auth status output" : undefined };
85
+ }
86
+ catch (error) {
87
+ signal?.throwIfAborted();
88
+ const available = error.code !== "ENOENT";
89
+ const reason = error?.name === "TimeoutError" ? "claude auth status timed out after 20s"
90
+ : error instanceof SyntaxError ? "claude auth status printed no JSON"
91
+ : error instanceof Error ? error.message : String(error);
92
+ const detail = [reason, result.code ? "exit " + result.code : "", result.stderr].filter(Boolean).join("; ");
93
+ return { available, loggedIn: false, diagnostic: available, detail };
94
+ }
95
+ }
96
+ export async function discoverClaudeModels(env, signal) {
97
+ const request_id = randomUUID();
98
+ const models = new Map();
99
+ const input = JSON.stringify({ type: "control_request", request_id, request: { subtype: "initialize" } }) + "\n";
100
+ const { code, stderr } = await invoke([...isolated, ...streaming, "--mcp-config", '{"mcpServers":{}}'], {
101
+ env, signal: deadline(signal), input, onLine(line) {
102
+ let event;
103
+ try {
104
+ event = JSON.parse(line);
105
+ }
106
+ catch {
107
+ return;
108
+ }
109
+ const reply = event.response;
110
+ if (event.type !== "control_response" || reply?.request_id !== request_id || reply.subtype !== "success")
111
+ return;
112
+ for (const row of reply.response.models) {
113
+ if (typeof row.value !== "string" || typeof row.displayName !== "string")
114
+ continue;
115
+ const model = modelEntry(row);
116
+ models.set(model.id, model);
117
+ }
118
+ },
119
+ });
120
+ if (code || !models.size)
121
+ throw new Error(["Model discovery failed", "exit " + code, stderr].filter(Boolean).join("; "));
122
+ return [...models.values()];
123
+ }
124
+ function modelEntry(row) {
125
+ const resolved = (row.resolvedModel || row.value).replace(/\[1m\]$/i, "");
126
+ const id = row.value === "default" ? "default" : resolved;
127
+ const known = getBuiltinModels("anthropic").find(m => m.id === resolved);
128
+ return { id, route: row.value, name: row.displayName, api, provider: providerId, baseUrl: defaultUrl,
129
+ cost: known?.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, reasoning: row.supportsEffort ?? known?.reasoning ?? false,
130
+ contextWindow: row.resolvedModel?.endsWith("[1m]") ? 1000000 : known?.contextWindow ?? 200000,
131
+ maxTokens: known?.maxTokens ?? 64000, input: ["text", "image"] };
132
+ }
@@ -0,0 +1,231 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { tmpdir } from "node:os";
4
+ import { fileURLToPath } from "node:url";
5
+ import { calculateCost, createAssistantMessageEventStream, getCurrentSystemPrompt, getCurrentTools } from "@earendil-works/pi-ai";
6
+ import { invoke, isolated, streaming } from "./claude-process.js";
7
+ import { loadSettings } from "../../shared/settings.js";
8
+ // Present the conversation in order, retaining call IDs and images. Do not forward
9
+ // provider diagnostics, local tool details, or session bookkeeping to Claude.
10
+ function userInput(context) {
11
+ const blocks = [];
12
+ for (const msg of context.messages) {
13
+ if (msg.role === "system")
14
+ continue;
15
+ const parts = typeof msg.content === "string" ? [{ type: "text", text: msg.content }] : msg.content;
16
+ const content = parts.flatMap((p) => {
17
+ if (p.type === "image")
18
+ return [{ type: "image", attachment: true }];
19
+ if (p.type === "thinking")
20
+ return [];
21
+ return [p];
22
+ });
23
+ const record = msg.role === "toolResult"
24
+ ? { role: msg.role, toolCallId: msg.toolCallId, name: msg.toolName, isError: msg.isError, content }
25
+ : { role: msg.role, content };
26
+ blocks.push({ type: "text", text: JSON.stringify(record) });
27
+ for (const p of parts)
28
+ if (p.type === "image") {
29
+ blocks.push({ type: "image", source: { type: "base64", media_type: p.mimeType, data: p.data } });
30
+ }
31
+ }
32
+ return JSON.stringify({ type: "user", message: { role: "user", content: blocks } }) + "\n";
33
+ }
34
+ export function streamClaudeCode(model, context, options, route = model.id) {
35
+ const stream = createAssistantMessageEventStream();
36
+ const message = { role: "assistant", api: model.api, provider: model.provider, model: model.id,
37
+ timestamp: Date.now(), content: [], stopReason: "pending",
38
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
39
+ async function generate() {
40
+ const { allowUsageCredits } = loadSettings().server;
41
+ const tools = getCurrentTools(context.messages);
42
+ const reserved = new Set(tools.map(tool => tool.name));
43
+ function transportName(name, index) {
44
+ if (/^[a-zA-Z0-9_-]{1,48}$/.test(name))
45
+ return name;
46
+ let replacement = "tool_" + index;
47
+ while (reserved.has(replacement))
48
+ replacement += "_";
49
+ reserved.add(replacement);
50
+ return replacement;
51
+ }
52
+ const catalog = tools.map((tool, index) => ({
53
+ name: transportName(tool.name, index),
54
+ description: tool.description, inputSchema: tool.parameters,
55
+ }));
56
+ const names = new Map(catalog.map((tool, i) => ["mcp__tether__" + tool.name, tools[i].name]));
57
+ const dir = await mkdtemp(join(tmpdir(), "a-tether-turn-"));
58
+ try {
59
+ const file = join(dir, "catalog.json");
60
+ const system = join(dir, "system.txt");
61
+ await writeFile(file, JSON.stringify(catalog), { mode: 0o600 });
62
+ const instructions = "You are the assistant in a Pi conversation. The input records represent the conversation in chronological order. Continue from the last record. Use the available tether tools for actions on computer A; Pi supplies their results on subsequent turns.";
63
+ await writeFile(system, getCurrentSystemPrompt(context.messages) + "\n\n" + instructions, { mode: 0o600 });
64
+ const servers = tools.length ? { tether: { command: process.execPath, args: [fileURLToPath(new URL("./tool-catalog.mjs", import.meta.url)), file] } } : {};
65
+ const args = [...isolated, ...streaming, "--include-partial-messages", "--max-turns", "1", "--model", route,
66
+ "--mcp-config", JSON.stringify({ mcpServers: servers }), "--system-prompt-file", system];
67
+ if (options.reasoning)
68
+ args.push("--effort", options.reasoning === "minimal" ? "low" : options.reasoning);
69
+ let completed = false;
70
+ let stopReason = "";
71
+ let cliError = "";
72
+ let hasAssistant = false;
73
+ const callsSeen = new Set();
74
+ const positions = new Map();
75
+ const pendingFinal = [];
76
+ function finishText(kind, text, signature, redacted = false) {
77
+ let i = pendingFinal.shift();
78
+ if (i === undefined) {
79
+ i = message.content.length;
80
+ if (kind === "text") {
81
+ message.content.push({ type: "text", text: "" });
82
+ stream.push({ type: "text_start", contentIndex: i, partial: message });
83
+ }
84
+ else {
85
+ message.content.push({ type: "thinking", thinking: "", redacted });
86
+ stream.push({ type: "thinking_start", contentIndex: i, partial: message });
87
+ }
88
+ }
89
+ const b = message.content[i];
90
+ if (b.type === "text" && kind === "text" && text.startsWith(b.text)) {
91
+ const delta = text.slice(b.text.length);
92
+ b.text = text;
93
+ if (delta)
94
+ stream.push({ type: "text_delta", delta, contentIndex: i, partial: message });
95
+ stream.push({ type: "text_end", content: text, contentIndex: i, partial: message });
96
+ }
97
+ else if (b.type === "thinking" && kind === "thinking" && text.startsWith(b.thinking)) {
98
+ const delta = text.slice(b.thinking.length);
99
+ b.thinking = text;
100
+ b.thinkingSignature = signature;
101
+ if (delta)
102
+ stream.push({ type: "thinking_delta", delta, contentIndex: i, partial: message });
103
+ stream.push({ type: "thinking_end", content: text, contentIndex: i, partial: message });
104
+ }
105
+ else
106
+ throw new Error("Claude final content differs from stream");
107
+ }
108
+ stream.push({ type: "start", partial: message });
109
+ const { code, stderr } = await invoke(args, { signal: options.signal, cwd: dir, input: userInput(context),
110
+ env: options.maxTokens ? { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(options.maxTokens) } : {}, onLine(line) {
111
+ let envelope;
112
+ try {
113
+ envelope = JSON.parse(line);
114
+ }
115
+ catch {
116
+ return;
117
+ } // ignore non-JSON noise on stdout
118
+ if (envelope.parent_tool_use_id)
119
+ return;
120
+ if (envelope.type === "stream_event") {
121
+ const e = envelope.event;
122
+ if (e.type === "content_block_start") {
123
+ const b = e.content_block;
124
+ const i = message.content.length;
125
+ if (b.type === "text") {
126
+ positions.set(e.index, i);
127
+ pendingFinal.push(i);
128
+ message.content.push({ type: "text", text: b.text || "" });
129
+ stream.push({ type: "text_start", partial: message, contentIndex: i });
130
+ }
131
+ else if (b.type === "thinking") {
132
+ positions.set(e.index, i);
133
+ pendingFinal.push(i);
134
+ message.content.push({ type: "thinking", thinking: b.thinking || "" });
135
+ stream.push({ type: "thinking_start", partial: message, contentIndex: i });
136
+ }
137
+ }
138
+ const i = positions.get(e.index);
139
+ if (i === undefined)
140
+ return;
141
+ const b = message.content[i];
142
+ if (e.type === "content_block_delta") {
143
+ if (b.type === "text" && e.delta.type === "text_delta") {
144
+ b.text += e.delta.text;
145
+ stream.push({ type: "text_delta", partial: message, contentIndex: i, delta: e.delta.text });
146
+ }
147
+ if (b.type === "thinking" && e.delta.type === "thinking_delta") {
148
+ b.thinking += e.delta.thinking;
149
+ stream.push({ type: "thinking_delta", partial: message, contentIndex: i, delta: e.delta.thinking });
150
+ }
151
+ }
152
+ else if (e.type === "content_block_stop") {
153
+ positions.delete(e.index);
154
+ }
155
+ }
156
+ else if (envelope.type === "assistant") {
157
+ if (envelope.error) {
158
+ cliError = String(envelope.error);
159
+ return;
160
+ }
161
+ hasAssistant = true;
162
+ message.responseId = envelope.message.id;
163
+ stopReason = envelope.message.stop_reason || stopReason;
164
+ for (const b of envelope.message.content) {
165
+ if (b.type === "text") {
166
+ finishText("text", b.text);
167
+ continue;
168
+ }
169
+ if (b.type === "thinking") {
170
+ finishText("thinking", b.thinking, b.signature);
171
+ continue;
172
+ }
173
+ if (b.type === "redacted_thinking") {
174
+ finishText("thinking", "", b.data, true);
175
+ continue;
176
+ }
177
+ if (b.type !== "tool_use")
178
+ continue;
179
+ const name = names.get(b.name);
180
+ if (!name)
181
+ throw new Error("Unexpected Claude tool");
182
+ if (typeof b.id !== "string" || !b.input || typeof b.input !== "object" || Array.isArray(b.input))
183
+ throw new Error("Invalid tool call");
184
+ if (callsSeen.has(b.id))
185
+ continue;
186
+ callsSeen.add(b.id);
187
+ const toolCall = { type: "toolCall", id: b.id, name, arguments: b.input };
188
+ const i = message.content.push(toolCall) - 1;
189
+ stream.push({ type: "toolcall_start", contentIndex: i, partial: message });
190
+ stream.push({ type: "toolcall_end", contentIndex: i, toolCall, partial: message });
191
+ }
192
+ }
193
+ else if (envelope.type === "result") {
194
+ const calls = message.content.some(b => b.type === "toolCall");
195
+ completed = envelope.subtype === "success" && !envelope.is_error || calls && envelope.subtype === "error_max_turns";
196
+ stopReason = envelope.stop_reason || stopReason;
197
+ if (!completed)
198
+ cliError = [cliError, JSON.stringify(envelope.errors || envelope.result)].filter(Boolean).join("; ");
199
+ const u = envelope.usage ?? {};
200
+ Object.assign(message.usage, { input: u.input_tokens ?? 0, output: u.output_tokens ?? 0,
201
+ cacheRead: u.cache_read_input_tokens ?? 0, cacheWrite: u.cache_creation_input_tokens ?? 0 });
202
+ const { input, output, cacheRead, cacheWrite } = message.usage;
203
+ message.usage.totalTokens = input + output + cacheRead + cacheWrite;
204
+ calculateCost(model, message.usage);
205
+ }
206
+ else if (envelope.type === "rate_limit_event" && envelope.rate_limit_info?.isUsingOverage &&
207
+ !allowUsageCredits) {
208
+ throw new Error("Claude billing limit");
209
+ }
210
+ } });
211
+ const calls = message.content.some(b => b.type === "toolCall");
212
+ if (pendingFinal.length || !hasAssistant || !completed || cliError || (code && !calls))
213
+ throw new Error([cliError || "Claude did not finish", "exit " + code, stderr].filter(Boolean).join("; "));
214
+ if (stopReason === "refusal")
215
+ throw new Error("Claude refused this request");
216
+ message.stopReason = stopReason === "max_tokens" ? "length" : calls ? "toolUse" : "stop";
217
+ }
218
+ finally {
219
+ await rm(dir, { recursive: true, force: true });
220
+ }
221
+ }
222
+ void generate().then(() => {
223
+ stream.push({ type: "done", reason: message.stopReason, message });
224
+ }).catch(error => {
225
+ const reason = options.signal?.aborted ? "aborted" : "error";
226
+ message.stopReason = reason;
227
+ message.errorMessage = error instanceof Error ? error.message : "Claude request failed";
228
+ stream.push({ type: "error", reason, error: message });
229
+ }).finally(() => stream.end());
230
+ return stream;
231
+ }
@@ -0,0 +1,22 @@
1
+ import { discoverClaudeModels, getClaudeStatus } from "./claude-process.js";
2
+ import { streamClaudeCode } from "./claude-turn.js";
3
+ export function backendCode(detail) {
4
+ if (/prompt is too long|context.(length|window)|too many tokens|maximum context/i.test(detail))
5
+ return "context";
6
+ if (/quota|rate.limit|billing|credit|status 429|usage limit/i.test(detail))
7
+ return "quota";
8
+ if (/not logged in|auth login|unauthorized|authentication.(failed|error)|invalid.api.key|oauth token|status 401/i.test(detail))
9
+ return "login";
10
+ if (/overloaded|status 5\d\d|\b5(00|02|03|04|29)\b|internal server error|service unavailable|bad gateway|api_error|ECONNRESET|ETIMEDOUT|socket hang up/i.test(detail))
11
+ return "overloaded";
12
+ if (/not installed|not found on PATH/i.test(detail))
13
+ return "unavailable";
14
+ return "backend";
15
+ }
16
+ export const claudeCode = {
17
+ name: "Claude Code",
18
+ status: (signal) => getClaudeStatus(process.env, signal),
19
+ models: (signal) => discoverClaudeModels(process.env, signal),
20
+ stream: (model, context, options) => streamClaudeCode(model, context, options, model.route),
21
+ errorCode: backendCode,
22
+ };
@@ -0,0 +1,15 @@
1
+ // A read-only MCP catalog. The only supported operations are discovery and listing.
2
+ import {createInterface} from "node:readline";
3
+ import {readFile} from "node:fs/promises";
4
+ const tools = JSON.parse(await readFile(process.argv[2],"utf8"));
5
+ for await (const line of createInterface({input:process.stdin})) {
6
+ const {id,method,params} = JSON.parse(line);
7
+ if (id === undefined) continue;
8
+ let result;
9
+ if (method === "initialize") {
10
+ result = {protocolVersion:params.protocolVersion,serverInfo:{name:"a-tether",version:"0.1.0"},capabilities:{tools:{}}};
11
+ } else if (method === "tools/list") result = {tools};
12
+ else if (method === "ping") result = {};
13
+ const response = result ? {result} : {error:{code:-32601,message:"Tool execution belongs to Pi on A"}};
14
+ process.stdout.write(JSON.stringify({jsonrpc:"2.0",id,...response})+"\n");
15
+ }
@@ -0,0 +1,217 @@
1
+ import { normalizeContext } from "@earendil-works/pi-ai";
2
+ import { createServer } from "node:http";
3
+ import { createHash, timingSafeEqual } from "node:crypto";
4
+ import { once } from "node:events";
5
+ import { mkdtemp, rm } from "node:fs/promises";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { generationOptions, uuid, wireEvent } from "../shared/protocol.js";
9
+ import { isLoopback, validToken } from "../shared/settings.js";
10
+ function json(res, status, data) {
11
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(data));
12
+ }
13
+ export class Failure extends Error {
14
+ status;
15
+ code;
16
+ detail;
17
+ constructor(status, code, detail = "") {
18
+ super(code);
19
+ this.status = status;
20
+ this.code = code;
21
+ this.detail = detail;
22
+ }
23
+ }
24
+ // C logs one line per failure: time, request ID prefix, code and a clipped
25
+ // diagnostic from Claude Code. Conversation content and tool data are never logged.
26
+ export function clip(text) { return text.replace(/\s+/g, " ").trim().slice(0, 500); }
27
+ function logError(id, code, detail = "") {
28
+ const text = clip(detail);
29
+ console.error(`${new Date().toISOString()} ${id ? id.slice(0, 8) : "--------"} ${code}${text ? ": " + text : ""}`);
30
+ }
31
+ function describe(error) {
32
+ return error instanceof Failure ? error.detail : error instanceof Error ? error.message : typeof error === "string" ? error : "";
33
+ }
34
+ // Keeps the last good catalog when a refresh fails transiently, such as a slow
35
+ // `claude auth status`, and retries soon instead of failing the request.
36
+ export function catalogCache(load, onStale, ttl = 60_000, retry = 10_000, now = Date.now) {
37
+ let catalog = [];
38
+ let refreshAt = 0;
39
+ return async (signal) => {
40
+ if (now() < refreshAt)
41
+ return catalog;
42
+ try {
43
+ catalog = await load(signal);
44
+ refreshAt = now() + ttl;
45
+ }
46
+ catch (error) {
47
+ const transient = error instanceof Failure && (error.code === "backend" || error.code === "discovery");
48
+ if (signal.aborted || !transient || !catalog.length)
49
+ throw error;
50
+ onStale(error.detail);
51
+ refreshAt = now() + retry;
52
+ }
53
+ return catalog;
54
+ };
55
+ }
56
+ async function readRequest(req) {
57
+ const chunks = [];
58
+ let size = 0;
59
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) {
60
+ size += chunk.length;
61
+ if (size > 32 * 1024 * 1024)
62
+ throw new Failure(413, "large");
63
+ chunks.push(chunk);
64
+ }
65
+ try {
66
+ return JSON.parse(Buffer.concat(chunks).toString());
67
+ }
68
+ catch {
69
+ throw new Failure(400, "invalid");
70
+ }
71
+ }
72
+ export async function runServer(backend, { token, host, port }) {
73
+ if (!validToken(token))
74
+ throw new Error("A-tether token must be at least 32 characters without whitespace");
75
+ const digest = (value) => createHash("sha256").update(value).digest();
76
+ const expected = digest("Bearer " + token);
77
+ const directory = await mkdtemp(join(tmpdir(), "a-tether-"));
78
+ process.chdir(directory);
79
+ const active = new Map();
80
+ const pending = new Set();
81
+ const controllers = new Set();
82
+ const models = catalogCache(async (signal) => {
83
+ const health = await backend.status(signal);
84
+ if (!health.available)
85
+ throw new Failure(503, "unavailable", health.detail);
86
+ if (health.diagnostic)
87
+ throw new Failure(502, "backend", "status check failed: " + (health.detail ?? "unknown"));
88
+ if (!health.loggedIn)
89
+ throw new Failure(503, "login");
90
+ try {
91
+ return await backend.models(signal);
92
+ }
93
+ catch (error) {
94
+ signal.throwIfAborted();
95
+ throw new Failure(502, "discovery", describe(error));
96
+ }
97
+ }, detail => logError("", "stale-catalog", detail));
98
+ async function handle(req, res, controller) {
99
+ if (!timingSafeEqual(digest(req.headers.authorization ?? ""), expected))
100
+ throw new Failure(401, "unauthorized");
101
+ const signal = controller.signal;
102
+ if (req.method === "GET" && req.url === "/v1/health") {
103
+ const { available, loggedIn, diagnostic } = await backend.status(signal);
104
+ return json(res, 200, { available, loggedIn, diagnostic });
105
+ }
106
+ if (req.method === "GET" && req.url === "/v1/models")
107
+ return json(res, 200, (await models(signal)).map(({ route, ...model }) => model));
108
+ const cancelId = req.url?.slice("/v1/requests/".length) ?? "";
109
+ if (req.method === "DELETE" && req.url?.startsWith("/v1/requests/") && uuid.test(cancelId)) {
110
+ active.get(cancelId)?.abort("cancelled");
111
+ return json(res, 200, { id: cancelId });
112
+ }
113
+ if (req.method !== "POST" || req.url !== "/v1/requests")
114
+ throw new Failure(404, "invalid");
115
+ const body = await readRequest(req);
116
+ if (!body || typeof body.id !== "string" || !uuid.test(body.id) || !Array.isArray(body.context?.messages))
117
+ throw new Failure(400, "invalid");
118
+ const id = body.id;
119
+ if (active.has(id))
120
+ throw new Failure(409, "duplicate");
121
+ active.set(id, controller);
122
+ const timer = setTimeout(() => controller.abort("timeout"), 300_000);
123
+ try {
124
+ const model = (await models(signal)).find(m => m.id === body.model);
125
+ signal.throwIfAborted();
126
+ if (!model)
127
+ throw new Failure(400, "invalid", "unknown model");
128
+ res.writeHead(200, { "content-type": "application/x-ndjson", "cache-control": "no-store" });
129
+ res.flushHeaders();
130
+ const stream = backend.stream(model, normalizeContext({ messages: body.context.messages }), {
131
+ ...generationOptions(body.options), signal,
132
+ });
133
+ try {
134
+ for await (const event of stream) {
135
+ if (event.type === "error") {
136
+ const code = signal.aborted ? signal.reason : backend.errorCode(event.error.errorMessage ?? "");
137
+ logError(id, code, signal.aborted ? "" : event.error.errorMessage);
138
+ if (!res.destroyed)
139
+ res.write(JSON.stringify({ id, type: "error", code }) + "\n");
140
+ continue;
141
+ }
142
+ if (res.destroyed)
143
+ continue;
144
+ const frame = { id, type: event.type === "done" ? "done" : "event", event: wireEvent(event) };
145
+ if (!res.write(JSON.stringify(frame) + "\n") && !signal.aborted)
146
+ await once(res, "drain", { signal });
147
+ }
148
+ }
149
+ finally {
150
+ controller.abort("cancelled");
151
+ await stream.result();
152
+ }
153
+ res.end();
154
+ }
155
+ catch (error) {
156
+ error.requestId = id;
157
+ throw error;
158
+ }
159
+ finally {
160
+ clearTimeout(timer);
161
+ active.delete(id);
162
+ }
163
+ }
164
+ const server = createServer((req, res) => {
165
+ const controller = new AbortController();
166
+ controllers.add(controller);
167
+ res.once("close", () => controller.abort("cancelled"));
168
+ const task = handle(req, res, controller).catch(error => {
169
+ const reason = controller.signal.reason;
170
+ const failure = error instanceof Failure ? error
171
+ : reason === "timeout" ? new Failure(504, "timeout")
172
+ : reason === "cancelled" ? new Failure(499, "cancelled")
173
+ : new Failure(502, "backend", describe(error));
174
+ logError(error?.requestId ?? "", failure.code, failure.detail);
175
+ if (res.destroyed)
176
+ return;
177
+ if (res.headersSent)
178
+ return res.destroy();
179
+ json(res, failure.status, { code: failure.code });
180
+ }).then(() => { });
181
+ pending.add(task);
182
+ void task.finally(() => { pending.delete(task); controllers.delete(controller); });
183
+ });
184
+ const startup = new AbortController();
185
+ const shutdown = () => {
186
+ startup.abort("cancelled");
187
+ for (const controller of controllers)
188
+ controller.abort("cancelled");
189
+ server.close();
190
+ server.closeAllConnections();
191
+ };
192
+ process.once("SIGINT", shutdown);
193
+ process.once("SIGTERM", shutdown);
194
+ try {
195
+ const health = await backend.status(startup.signal);
196
+ startup.signal.throwIfAborted();
197
+ const state = !health.available ? "missing"
198
+ : health.diagnostic ? "status check failed" + (health.detail ? " (" + clip(health.detail) + ")" : "")
199
+ : health.loggedIn ? "logged in" : "not logged in";
200
+ console.log(backend.name + ":", state);
201
+ server.listen(port, host);
202
+ await once(server, "listening", { signal: startup.signal });
203
+ console.log("A-tether listening on " + (host.includes(":") ? `[${host}]` : host) + ":" + port);
204
+ if (!isLoopback(host))
205
+ console.log("注意:服务监听在非本机地址,令牌以明文 HTTP 传输,同一网络中的设备都能连接。");
206
+ await once(server, "close");
207
+ }
208
+ catch (error) {
209
+ if (!startup.signal.aborted)
210
+ throw error;
211
+ }
212
+ finally {
213
+ await Promise.allSettled(pending);
214
+ process.chdir(tmpdir());
215
+ await rm(directory, { recursive: true, force: true });
216
+ }
217
+ }
package/dist/server.js ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ import { claudeCode } from "./backends/claude-code/index.js";
3
+ import { runServer } from "./server/http.js";
4
+ import { displayPath, generateToken, loadSettings, loginCommand, saveToken } from "./shared/settings.js";
5
+ const showToken = "npx -y @a-tether/server token";
6
+ function main(args) {
7
+ const settings = loadSettings();
8
+ if (args[0] === "token" && args.length === 1) {
9
+ if (!settings.token)
10
+ throw new Error(`还没有令牌。运行 npx -y @a-tether/server 启动服务时会自动生成并保存到 ${displayPath}。`);
11
+ console.log(["在 A 端电脑上运行下面这行(同一台电脑上使用 Pi 无需运行):", "", " " + loginCommand(settings.token), ""].join("\n"));
12
+ return;
13
+ }
14
+ if (args.length)
15
+ throw new Error("用法:a-tether-server 启动服务\n a-tether-server token 显示 A 端的配置命令");
16
+ let token = settings.token;
17
+ if (token)
18
+ console.log(`令牌:已配置(${displayPath})。查看 A 端配置命令:${showToken}`);
19
+ else {
20
+ token = generateToken();
21
+ saveToken(token);
22
+ console.log([
23
+ `已生成 A-tether 令牌,保存在 ${displayPath}。`,
24
+ "在 A 端电脑上运行一次下面这行(同一台电脑上使用 Pi 无需运行):",
25
+ "",
26
+ " " + loginCommand(token),
27
+ "",
28
+ `以后可运行 ${showToken} 再次查看。`,
29
+ ].join("\n"));
30
+ }
31
+ return runServer(claudeCode, { token, host: settings.server.host, port: settings.server.port });
32
+ }
33
+ try {
34
+ await main(process.argv.slice(2));
35
+ }
36
+ catch (error) {
37
+ console.error(error instanceof Error ? error.message : String(error));
38
+ process.exitCode = 1;
39
+ }
@@ -0,0 +1,54 @@
1
+ export const providerId = "a-tether";
2
+ export const api = "a-tether-v1";
3
+ export const defaultUrl = "http://127.0.0.1:7310";
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
+ export const messages = {
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 命令。",
8
+ unavailable: "C 上找不到 Claude Code,请检查服务进程的 PATH。",
9
+ login: "C 上的 Claude Code 尚未登录或登录已失效。",
10
+ quota: "Claude 额度、速率或计费限制,请在 C 上检查账户。",
11
+ backend: "C 上的 Claude Code 调用失败,具体原因见 C 端服务控制台。",
12
+ overloaded: "模型服务繁忙或暂时不可用,请稍后重试。",
13
+ context: "请求超出模型的上下文长度,请在 Pi 中压缩上下文或减少输入。",
14
+ discovery: "C 无法获取 Claude 模型目录,请检查 CLI 版本和连接。",
15
+ cancelled: "请求已取消。",
16
+ timeout: "C 上的请求超时。",
17
+ invalid: "请求格式或模型 ID 无效。",
18
+ duplicate: "请求 ID 已在使用。",
19
+ large: "请求超过 32 MiB 上限。",
20
+ connection: "A-tether 连接中断,请检查端口转发(如 SSH 隧道)和 C 端服务。",
21
+ };
22
+ // Runtime whitelist on BOTH ends. In particular, never forward env, headers,
23
+ // sessionId, filesystem paths, credentials, or callbacks from Pi.
24
+ export function generationOptions(options) {
25
+ const reasoning = options?.reasoning;
26
+ const maxTokens = options?.maxTokens;
27
+ return {
28
+ ...(reasoning && ["minimal", "low", "medium", "high", "xhigh", "max"].includes(reasoning) ? { reasoning } : {}),
29
+ ...(Number.isSafeInteger(maxTokens) && maxTokens > 0 ? { maxTokens } : {}),
30
+ };
31
+ }
32
+ // Pi partials refer to a mutable, cumulative message. Only block boundaries
33
+ // need snapshots on the wire. Streaming deltas carry just the newly arrived data.
34
+ export function wireEvent(event) {
35
+ if (event.type === "done")
36
+ return event;
37
+ const { partial, ...update } = event;
38
+ if (event.type === "start")
39
+ return { ...update, partial: { ...partial, content: [] } };
40
+ const block = partial.content[event.contentIndex];
41
+ switch (event.type) {
42
+ case "toolcall_start":
43
+ if (block.type === "toolCall")
44
+ return { ...update, block: { type: block.type, id: block.id, name: block.name, arguments: {} } };
45
+ break;
46
+ case "thinking_start":
47
+ if (block.type === "thinking")
48
+ return { ...update, block: { type: block.type, thinking: block.redacted ? block.thinking : "", redacted: block.redacted } };
49
+ break;
50
+ case "text_start": return { ...update, block: { type: "text", text: "" } };
51
+ case "thinking_end": return { ...update, signature: block.type === "thinking" ? block.thinkingSignature : undefined };
52
+ }
53
+ return update;
54
+ }
@@ -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,29 @@
1
1
  {
2
2
  "name": "@a-tether/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "A-tether C-side service: lends a logged-in Claude Code to Pi on another machine over an SSH tunnel.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/SandyKidYao/a-tether.git",
10
+ "directory": "packages/server"
11
+ },
12
+ "engines": {
13
+ "node": ">=22.19.0"
14
+ },
15
+ "bin": {
16
+ "a-tether-server": "dist/server.js"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "dependencies": {
24
+ "@earendil-works/pi-ai": "1.5.2"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ }
29
+ }