@a-tether/server 0.1.2 → 0.2.0
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/dist/backends/claude-code/claude-process.js +14 -7
- package/dist/backends/claude-code/claude-turn.js +106 -84
- package/dist/backends/claude-code/index.js +3 -0
- package/dist/backends/claude-code/live.js +298 -0
- package/dist/backends/claude-code/transcript.js +91 -0
- package/dist/server/http.js +2 -1
- package/dist/server.js +5 -1
- package/dist/shared/protocol.js +2 -1
- package/dist/shared/settings.js +5 -1
- package/dist/shared/version.js +5 -0
- package/package.json +1 -1
- package/dist/backends/claude-code/tool-catalog.mjs +0 -15
|
@@ -23,9 +23,9 @@ function settingsToken(env) {
|
|
|
23
23
|
return undefined;
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
// Starts the configured CLI in its own process group with an isolated environment.
|
|
27
|
+
// `closed` settles once the process and its pipes are gone; `stop` kills the group.
|
|
28
|
+
export function spawnClaude(args, options) {
|
|
29
29
|
const env = { ...process.env, ...options.env };
|
|
30
30
|
const command = loadSettings().server.claude;
|
|
31
31
|
delete env.ANTHROPIC_API_KEY;
|
|
@@ -67,19 +67,26 @@ export async function invoke(args, options) {
|
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
69
|
};
|
|
70
|
-
// A CLI launcher can exit while
|
|
70
|
+
// A CLI launcher can exit while a descendant still owns its pipes.
|
|
71
71
|
if (process.platform !== "win32")
|
|
72
72
|
child.once("exit", stop);
|
|
73
|
-
signal?.addEventListener("abort", stop, { once: true });
|
|
74
|
-
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
75
73
|
child.stdin.on("error", () => { }); // A short-lived CLI can exit before consuming stdin.
|
|
74
|
+
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
75
|
+
return { child, closed, stop, lines, stderr: () => stderr.trim() };
|
|
76
|
+
}
|
|
77
|
+
// One-shot invocation: write the whole input, read every line, wait for exit.
|
|
78
|
+
export async function invoke(args, options) {
|
|
79
|
+
const { signal } = options;
|
|
80
|
+
signal?.throwIfAborted();
|
|
81
|
+
const { child, closed, stop, lines, stderr } = spawnClaude(args, options);
|
|
82
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
76
83
|
try {
|
|
77
84
|
child.stdin.end(options.input);
|
|
78
85
|
const output = (async () => { for await (const line of lines)
|
|
79
86
|
options.onLine(line); })();
|
|
80
87
|
const [code] = await Promise.all([closed, output]);
|
|
81
88
|
signal?.throwIfAborted();
|
|
82
|
-
return { code, stderr: stderr
|
|
89
|
+
return { code, stderr: stderr() };
|
|
83
90
|
}
|
|
84
91
|
finally {
|
|
85
92
|
stop();
|
|
@@ -1,47 +1,20 @@
|
|
|
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
1
|
import { calculateCost, createAssistantMessageEventStream, getCurrentSystemPrompt, getCurrentTools } from "@earendil-works/pi-ai";
|
|
6
|
-
import {
|
|
2
|
+
import { LiveClaude, admit, reuse } from "./live.js";
|
|
3
|
+
import { messageKey, normalizeMessages, transcript } from "./transcript.js";
|
|
7
4
|
import { loadSettings } from "../../shared/settings.js";
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
for (const msg of context.messages) {
|
|
15
|
-
if (msg.role === "system")
|
|
16
|
-
continue;
|
|
17
|
-
const parts = typeof msg.content === "string" ? [{ type: "text", text: msg.content }] : msg.content;
|
|
18
|
-
const content = parts.flatMap((p) => {
|
|
19
|
-
if (p.type === "image")
|
|
20
|
-
return [{ type: "image", attachment: true }];
|
|
21
|
-
if (p.type === "thinking")
|
|
22
|
-
return [];
|
|
23
|
-
if (p.type === "toolCall")
|
|
24
|
-
return [{ ...p, name: toolName(p.name) }];
|
|
25
|
-
return [p];
|
|
26
|
-
});
|
|
27
|
-
const record = msg.role === "toolResult"
|
|
28
|
-
? { role: msg.role, toolCallId: msg.toolCallId, name: toolName(msg.toolName), isError: msg.isError, content }
|
|
29
|
-
: { role: msg.role, content };
|
|
30
|
-
blocks.push({ type: "text", text: JSON.stringify(record) });
|
|
31
|
-
for (const p of parts)
|
|
32
|
-
if (p.type === "image") {
|
|
33
|
-
blocks.push({ type: "image", source: { type: "base64", media_type: p.mimeType, data: p.data } });
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
return JSON.stringify({ type: "user", message: { role: "user", content: blocks } }) + "\n";
|
|
37
|
-
}
|
|
5
|
+
// Claude Code adds an Environment section about C (its temporary directory, OS, date)
|
|
6
|
+
// even with a replaced system prompt; without this note the model mistakes it for A.
|
|
7
|
+
const instructions = "You are the assistant in a Pi conversation. Pi runs on computer A, executes the tether tools there and returns their results. " +
|
|
8
|
+
"When a user message holds JSON records, they are the earlier conversation in chronological order: continue from the last record. " +
|
|
9
|
+
"The Environment section of this prompt describes the machine that hosts this model process, not computer A. " +
|
|
10
|
+
"For paths, the working directory and the platform, follow Pi's instructions, such as its <cwd>.";
|
|
38
11
|
export function streamClaudeCode(model, context, options, route = model.id) {
|
|
39
12
|
const stream = createAssistantMessageEventStream();
|
|
40
13
|
const message = { role: "assistant", api: model.api, provider: model.provider, model: model.id,
|
|
41
14
|
timestamp: Date.now(), content: [], stopReason: "pending",
|
|
42
15
|
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
43
16
|
async function generate() {
|
|
44
|
-
const { allowUsageCredits } = loadSettings().server;
|
|
17
|
+
const { allowUsageCredits, claude } = loadSettings().server;
|
|
45
18
|
const tools = getCurrentTools(context.messages);
|
|
46
19
|
const reserved = new Set(tools.map(tool => tool.name));
|
|
47
20
|
function transportName(name, index) {
|
|
@@ -58,30 +31,58 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
58
31
|
description: tool.description, inputSchema: tool.parameters,
|
|
59
32
|
}));
|
|
60
33
|
const claudeNames = new Map(tools.map((tool, i) => [tool.name, "mcp__tether__" + catalog[i].name]));
|
|
34
|
+
const known = new Map(catalog.map((tool, i) => ["mcp__tether__" + tool.name, tools[i].name]));
|
|
61
35
|
// A model sometimes drops the MCP prefix. Map bare names back as well; any other
|
|
62
36
|
// name goes to Pi unchanged, which answers it with a "not found" tool result.
|
|
63
|
-
const names = new Map(tools.flatMap((tool, i) => [
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const
|
|
37
|
+
const names = new Map([...tools.flatMap((tool, i) => [[tool.name, tool.name], [catalog[i].name, tool.name]]), ...known]);
|
|
38
|
+
const conversation = normalizeMessages(context.messages);
|
|
39
|
+
const keys = conversation.map(messageKey);
|
|
40
|
+
const spec = { command: claude, route, system: getCurrentSystemPrompt(context.messages) + "\n\n" + instructions,
|
|
41
|
+
effort: options.reasoning ? (options.reasoning === "minimal" ? "low" : options.reasoning) : undefined,
|
|
42
|
+
maxTokens: options.maxTokens, tools: catalog };
|
|
43
|
+
options.signal?.throwIfAborted();
|
|
44
|
+
let lease = reuse(spec, keys, conversation);
|
|
45
|
+
if (lease?.toolsChanged) {
|
|
46
|
+
try {
|
|
47
|
+
await lease.live.setTools(catalog);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
lease.live.kill();
|
|
51
|
+
lease = undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const live = lease?.live ?? await LiveClaude.start(spec, admit());
|
|
55
|
+
const input = lease?.input ?? { kind: "user", content: transcript(conversation, name => claudeNames.get(name) ?? name) };
|
|
56
|
+
stream.push({ type: "start", partial: message });
|
|
67
57
|
try {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
58
|
+
await live.run(input, translate(), options.signal);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
live.kill(error);
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
live.release([...keys, messageKey(message)]);
|
|
65
|
+
// One request's share of the CLI output: a single model call, which ends at its
|
|
66
|
+
// message_stop. Streams that bring only final messages end at the first tool call
|
|
67
|
+
// or the turn's result.
|
|
68
|
+
function translate() {
|
|
79
69
|
let stopReason = "";
|
|
80
70
|
let cliError = "";
|
|
71
|
+
let started = false;
|
|
81
72
|
let hasAssistant = false;
|
|
73
|
+
let usageFinal = false;
|
|
74
|
+
let diverged = false;
|
|
82
75
|
const callsSeen = new Set();
|
|
83
76
|
const positions = new Map();
|
|
84
77
|
const pendingFinal = [];
|
|
78
|
+
const calls = () => message.content.flatMap(b => b.type === "toolCall" ? [b.id] : []);
|
|
79
|
+
function usage(u) {
|
|
80
|
+
Object.assign(message.usage, { input: u.input_tokens ?? 0, output: u.output_tokens ?? 0,
|
|
81
|
+
cacheRead: u.cache_read_input_tokens ?? 0, cacheWrite: u.cache_creation_input_tokens ?? 0 });
|
|
82
|
+
const { input, output, cacheRead, cacheWrite } = message.usage;
|
|
83
|
+
message.usage.totalTokens = input + output + cacheRead + cacheWrite;
|
|
84
|
+
calculateCost(model, message.usage);
|
|
85
|
+
}
|
|
85
86
|
function finishText(kind, text, signature, redacted = false) {
|
|
86
87
|
let i = pendingFinal.shift();
|
|
87
88
|
if (i === undefined) {
|
|
@@ -114,21 +115,48 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
114
115
|
else
|
|
115
116
|
throw new Error("Claude final content differs from stream");
|
|
116
117
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
118
|
+
// turnOver: the CLI already ended its turn, so it will not wait for tool results.
|
|
119
|
+
function finish(turnOver) {
|
|
120
|
+
if (pendingFinal.length)
|
|
121
|
+
throw new Error("Claude did not finish");
|
|
122
|
+
if (cliError)
|
|
123
|
+
throw new Error(cliError);
|
|
124
|
+
if (stopReason === "refusal")
|
|
125
|
+
throw new Error("Claude refused this request");
|
|
126
|
+
const ids = calls();
|
|
127
|
+
message.stopReason = stopReason === "max_tokens" ? "length" : ids.length ? "toolUse" : "stop";
|
|
128
|
+
if (ids.length && message.stopReason === "toolUse" && !turnOver)
|
|
129
|
+
return { state: "awaitingTools", pending: ids };
|
|
130
|
+
if (ids.length)
|
|
131
|
+
diverged = true;
|
|
132
|
+
return turnOver ? { state: "idle" } : { state: "finishing" };
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
get diverged() { return diverged; },
|
|
136
|
+
onToolCall() { return !started && calls().length ? finish(false) : undefined; },
|
|
137
|
+
onEvent(envelope) {
|
|
128
138
|
if (envelope.parent_tool_use_id)
|
|
129
139
|
return;
|
|
130
140
|
if (envelope.type === "stream_event") {
|
|
131
141
|
const e = envelope.event;
|
|
142
|
+
if (e.type === "message_start") {
|
|
143
|
+
// Each request covers one model call; a second means the CLI went on alone.
|
|
144
|
+
if (started)
|
|
145
|
+
throw new Error("Claude continued without Pi");
|
|
146
|
+
started = true;
|
|
147
|
+
message.responseId = e.message?.id ?? message.responseId;
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (e.type === "message_delta") {
|
|
151
|
+
stopReason = e.delta?.stop_reason || stopReason;
|
|
152
|
+
if (e.usage) {
|
|
153
|
+
usage(e.usage);
|
|
154
|
+
usageFinal = true;
|
|
155
|
+
}
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (e.type === "message_stop")
|
|
159
|
+
return finish(false);
|
|
132
160
|
if (e.type === "content_block_start") {
|
|
133
161
|
const b = e.content_block;
|
|
134
162
|
const i = message.content.length;
|
|
@@ -169,8 +197,10 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
169
197
|
return;
|
|
170
198
|
}
|
|
171
199
|
hasAssistant = true;
|
|
172
|
-
message.responseId
|
|
200
|
+
message.responseId ??= envelope.message.id;
|
|
173
201
|
stopReason = envelope.message.stop_reason || stopReason;
|
|
202
|
+
if (!usageFinal && envelope.message.usage)
|
|
203
|
+
usage(envelope.message.usage);
|
|
174
204
|
for (const b of envelope.message.content) {
|
|
175
205
|
if (b.type === "text") {
|
|
176
206
|
finishText("text", b.text);
|
|
@@ -191,6 +221,9 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
191
221
|
if (callsSeen.has(b.id))
|
|
192
222
|
continue;
|
|
193
223
|
callsSeen.add(b.id);
|
|
224
|
+
// The CLI answers a name it does not list by itself and carries on.
|
|
225
|
+
if (!known.has(b.name))
|
|
226
|
+
diverged = true;
|
|
194
227
|
// Pi owns the tools: it rejects unknown names and validates arguments,
|
|
195
228
|
// and the model corrects itself on the next turn.
|
|
196
229
|
const name = names.get(b.name) ?? b.name;
|
|
@@ -202,32 +235,21 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
202
235
|
}
|
|
203
236
|
}
|
|
204
237
|
else if (envelope.type === "result") {
|
|
205
|
-
const
|
|
206
|
-
completed = envelope.subtype === "success" && !envelope.is_error || calls && envelope.subtype === "error_max_turns";
|
|
238
|
+
const completed = envelope.subtype === "success" && !envelope.is_error || calls().length && envelope.subtype === "error_max_turns";
|
|
207
239
|
stopReason = envelope.stop_reason || stopReason;
|
|
208
240
|
if (!completed)
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
calculateCost(model, message.usage);
|
|
241
|
+
throw new Error([cliError, JSON.stringify(envelope.errors || envelope.result)].filter(Boolean).join("; "));
|
|
242
|
+
if (!usageFinal && envelope.usage)
|
|
243
|
+
usage(envelope.usage);
|
|
244
|
+
if (!hasAssistant)
|
|
245
|
+
throw new Error("Claude did not finish");
|
|
246
|
+
return finish(true);
|
|
216
247
|
}
|
|
217
|
-
else if (envelope.type === "rate_limit_event" && envelope.rate_limit_info?.isUsingOverage &&
|
|
218
|
-
!allowUsageCredits) {
|
|
248
|
+
else if (envelope.type === "rate_limit_event" && envelope.rate_limit_info?.isUsingOverage && !allowUsageCredits) {
|
|
219
249
|
throw new Error("Claude billing limit");
|
|
220
250
|
}
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
if (pendingFinal.length || !hasAssistant || !completed || cliError || (code && !calls))
|
|
224
|
-
throw new Error([cliError || "Claude did not finish", "exit " + code, stderr].filter(Boolean).join("; "));
|
|
225
|
-
if (stopReason === "refusal")
|
|
226
|
-
throw new Error("Claude refused this request");
|
|
227
|
-
message.stopReason = stopReason === "max_tokens" ? "length" : calls ? "toolUse" : "stop";
|
|
228
|
-
}
|
|
229
|
-
finally {
|
|
230
|
-
await rm(dir, { recursive: true, force: true });
|
|
251
|
+
},
|
|
252
|
+
};
|
|
231
253
|
}
|
|
232
254
|
}
|
|
233
255
|
void generate().then(() => {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { discoverClaudeModels, getClaudeStatus } from "./claude-process.js";
|
|
2
2
|
import { streamClaudeCode } from "./claude-turn.js";
|
|
3
|
+
import { livePool, liveStats, shutdownLive } from "./live.js";
|
|
3
4
|
export function backendCode(detail) {
|
|
4
5
|
if (/prompt is too long|context.(length|window)|too many tokens|maximum context/i.test(detail))
|
|
5
6
|
return "context";
|
|
@@ -19,4 +20,6 @@ export const claudeCode = {
|
|
|
19
20
|
models: (signal) => discoverClaudeModels(process.env, signal),
|
|
20
21
|
stream: (model, context, options) => streamClaudeCode(model, context, options, model.route),
|
|
21
22
|
errorCode: backendCode,
|
|
23
|
+
stats: () => ({ processes: livePool().length, ...liveStats }),
|
|
24
|
+
close: shutdownLive,
|
|
22
25
|
};
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
// Long-lived Claude Code processes, one per Pi conversation. Each keeps its native
|
|
2
|
+
// transcript; tools reach Pi through an "sdk" MCP server whose calls stay open until
|
|
3
|
+
// Pi sends the results with its next request. See docs/dev/live-session.md.
|
|
4
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { isolated, spawnClaude, streaming } from "./claude-process.js";
|
|
9
|
+
import { mcpResult, userContent } from "./transcript.js";
|
|
10
|
+
import { loadSettings } from "../../shared/settings.js";
|
|
11
|
+
const server = "tether";
|
|
12
|
+
const toolListTimeout = 5000;
|
|
13
|
+
let idleMs = 60 * 60_000; // Claude Code's prompt cache lives one hour
|
|
14
|
+
const pool = new Set();
|
|
15
|
+
// Counts for /v1/health: processes started and requests served by an existing one.
|
|
16
|
+
export const liveStats = { started: 0, reused: 0 };
|
|
17
|
+
export class LiveClaude {
|
|
18
|
+
spec;
|
|
19
|
+
pooled;
|
|
20
|
+
proc;
|
|
21
|
+
dir;
|
|
22
|
+
state = "generating";
|
|
23
|
+
consumed = [];
|
|
24
|
+
pending = [];
|
|
25
|
+
busy = true;
|
|
26
|
+
lastUsed = Date.now();
|
|
27
|
+
diverged = false;
|
|
28
|
+
reason;
|
|
29
|
+
failing = false;
|
|
30
|
+
held = new Map();
|
|
31
|
+
buffered = new Map();
|
|
32
|
+
active;
|
|
33
|
+
toolsListed;
|
|
34
|
+
timer;
|
|
35
|
+
constructor(spec, pooled, proc, dir) {
|
|
36
|
+
this.spec = spec;
|
|
37
|
+
this.pooled = pooled;
|
|
38
|
+
this.proc = proc;
|
|
39
|
+
this.dir = dir;
|
|
40
|
+
}
|
|
41
|
+
static async start(spec, pooled) {
|
|
42
|
+
const dir = await mkdtemp(join(tmpdir(), "a-tether-turn-"));
|
|
43
|
+
try {
|
|
44
|
+
const system = join(dir, "system.txt");
|
|
45
|
+
await writeFile(system, spec.system, { mode: 0o600 });
|
|
46
|
+
const args = [...isolated, ...streaming, "--include-partial-messages", "--model", spec.route,
|
|
47
|
+
"--allowedTools", "mcp__" + server, "--mcp-config", JSON.stringify({ mcpServers: { [server]: { type: "sdk", name: server } } }),
|
|
48
|
+
"--system-prompt-file", system, ...(spec.effort ? ["--effort", spec.effort] : [])];
|
|
49
|
+
const env = { DISABLE_AUTO_COMPACT: "1", MCP_TOOL_TIMEOUT: String(2 * idleMs),
|
|
50
|
+
...(spec.maxTokens ? { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(spec.maxTokens) } : {}) };
|
|
51
|
+
const live = new LiveClaude(spec, pooled, spawnClaude(args, { cwd: dir, env }), dir);
|
|
52
|
+
liveStats.started++;
|
|
53
|
+
if (pooled)
|
|
54
|
+
pool.add(live);
|
|
55
|
+
void live.read();
|
|
56
|
+
return live;
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
await rm(dir, { recursive: true, force: true });
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
get pid() { return this.proc.child.pid; }
|
|
64
|
+
// Feeds this request's input and resolves when its segment of output is over.
|
|
65
|
+
run(input, segment, signal) {
|
|
66
|
+
signal?.throwIfAborted();
|
|
67
|
+
if (this.state === "dead")
|
|
68
|
+
throw this.reason;
|
|
69
|
+
clearTimeout(this.timer);
|
|
70
|
+
this.state = "generating";
|
|
71
|
+
this.pending = [];
|
|
72
|
+
const done = new Promise((resolve, reject) => { this.active = { segment, resolve, reject }; });
|
|
73
|
+
const abort = () => this.kill(signal?.reason);
|
|
74
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
75
|
+
if (input.kind === "user")
|
|
76
|
+
this.send({ type: "user", message: { role: "user", content: input.content } });
|
|
77
|
+
else
|
|
78
|
+
for (const [id, result] of input.results) {
|
|
79
|
+
const call = this.held.get(id);
|
|
80
|
+
if (call) {
|
|
81
|
+
this.held.delete(id);
|
|
82
|
+
this.answer(call, result);
|
|
83
|
+
}
|
|
84
|
+
else
|
|
85
|
+
this.buffered.set(id, result);
|
|
86
|
+
}
|
|
87
|
+
return done.finally(() => signal?.removeEventListener("abort", abort));
|
|
88
|
+
}
|
|
89
|
+
// Replaces the tool catalog; the CLI refetches it before its next model call.
|
|
90
|
+
async setTools(tools) {
|
|
91
|
+
this.spec.tools = tools;
|
|
92
|
+
const listed = new Promise((resolve, reject) => {
|
|
93
|
+
const timer = setTimeout(() => reject(new Error("Claude did not reload the tools")), toolListTimeout);
|
|
94
|
+
this.toolsListed = () => { clearTimeout(timer); resolve(); };
|
|
95
|
+
});
|
|
96
|
+
this.send({ type: "control_request", request_id: randomUUID(), request: { subtype: "mcp_message", server_name: server,
|
|
97
|
+
message: { jsonrpc: "2.0", method: "notifications/tools/list_changed" } } });
|
|
98
|
+
try {
|
|
99
|
+
await listed;
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
this.toolsListed = undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// Called after a request succeeds, with the history the process now holds.
|
|
106
|
+
release(consumed) {
|
|
107
|
+
this.consumed = consumed;
|
|
108
|
+
this.busy = false;
|
|
109
|
+
this.lastUsed = Date.now();
|
|
110
|
+
if (!this.pooled || this.diverged)
|
|
111
|
+
return this.kill();
|
|
112
|
+
this.timer = setTimeout(() => this.kill(), idleMs).unref();
|
|
113
|
+
}
|
|
114
|
+
kill(reason) {
|
|
115
|
+
if (this.state !== "dead") {
|
|
116
|
+
this.state = "dead";
|
|
117
|
+
this.reason = reason ?? new Error(["Claude process ended", this.proc.stderr()].filter(Boolean).join("; "));
|
|
118
|
+
clearTimeout(this.timer);
|
|
119
|
+
pool.delete(this);
|
|
120
|
+
this.proc.stop();
|
|
121
|
+
void this.proc.closed.catch(() => { }).finally(() => rm(this.dir, { recursive: true, force: true }));
|
|
122
|
+
}
|
|
123
|
+
const active = this.active;
|
|
124
|
+
this.active = undefined;
|
|
125
|
+
active?.reject(this.reason);
|
|
126
|
+
}
|
|
127
|
+
get closed() { return this.proc.closed.catch(() => -1); }
|
|
128
|
+
send(message) { this.proc.child.stdin.write(JSON.stringify(message) + "\n"); }
|
|
129
|
+
reply(requestId, response) {
|
|
130
|
+
this.send({ type: "control_response", response: { subtype: "success", request_id: requestId, response } });
|
|
131
|
+
}
|
|
132
|
+
answer(call, result) {
|
|
133
|
+
this.reply(call.requestId, { mcp_response: { jsonrpc: "2.0", id: call.rpcId, result } });
|
|
134
|
+
}
|
|
135
|
+
async read() {
|
|
136
|
+
try {
|
|
137
|
+
for await (const line of this.proc.lines) {
|
|
138
|
+
let event;
|
|
139
|
+
try {
|
|
140
|
+
event = JSON.parse(line);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
continue;
|
|
144
|
+
} // ignore non-JSON noise on stdout
|
|
145
|
+
this.handle(event);
|
|
146
|
+
}
|
|
147
|
+
await this.proc.closed;
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
this.kill(error);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
this.kill();
|
|
154
|
+
}
|
|
155
|
+
handle(event) {
|
|
156
|
+
if (event.type === "control_request") {
|
|
157
|
+
if (event.request?.subtype === "mcp_message" && event.request.server_name === server)
|
|
158
|
+
this.mcp(event.request_id, event.request.message);
|
|
159
|
+
else
|
|
160
|
+
this.send({ type: "control_response", response: { subtype: "error", request_id: event.request_id, error: "Unsupported request" } });
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (event.type === "control_response" || this.failing)
|
|
164
|
+
return;
|
|
165
|
+
// The CLI must never compact on its own: Pi owns the history (DISABLE_AUTO_COMPACT).
|
|
166
|
+
if (event.type === "system" && event.subtype === "compact_boundary")
|
|
167
|
+
this.diverged = true;
|
|
168
|
+
const active = this.active;
|
|
169
|
+
if (!active) {
|
|
170
|
+
if (event.type === "result" && this.state === "finishing") {
|
|
171
|
+
if (event.subtype === "success" && !event.is_error)
|
|
172
|
+
this.state = "idle";
|
|
173
|
+
else
|
|
174
|
+
this.kill();
|
|
175
|
+
}
|
|
176
|
+
else if (["stream_event", "assistant", "result"].includes(event.type)) {
|
|
177
|
+
this.kill(); // output nobody asked for: the CLI went on without Pi
|
|
178
|
+
}
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
this.end(active.segment.onEvent(event));
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
this.fail(error);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// A failed reply ends the process. Give the CLI a moment to finish its stderr and
|
|
189
|
+
// exit, so the C diagnostic line carries the exit code and the CLI's own error.
|
|
190
|
+
fail(error) {
|
|
191
|
+
const active = this.active;
|
|
192
|
+
this.active = undefined;
|
|
193
|
+
this.failing = true;
|
|
194
|
+
const exited = this.proc.closed.then(code => code, () => undefined);
|
|
195
|
+
void Promise.race([exited, new Promise(resolve => setTimeout(() => resolve(undefined), 1000).unref())]).then(code => {
|
|
196
|
+
const detail = [error instanceof Error ? error.message : String(error), code === undefined ? "" : "exit " + code, this.proc.stderr()];
|
|
197
|
+
this.kill();
|
|
198
|
+
active?.reject(new Error(detail.filter(Boolean).join("; ")));
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
mcp(requestId, message) {
|
|
202
|
+
if (message?.id === undefined)
|
|
203
|
+
return this.reply(requestId, { mcp_response: { jsonrpc: "2.0", id: 0, result: {} } });
|
|
204
|
+
const respond = (result) => this.answer({ requestId, rpcId: message.id }, result);
|
|
205
|
+
if (message.method === "initialize") {
|
|
206
|
+
return respond({ protocolVersion: message.params?.protocolVersion, serverInfo: { name: "a-tether", version: "0.2.0" }, capabilities: { tools: { listChanged: true } } });
|
|
207
|
+
}
|
|
208
|
+
if (message.method === "tools/list") {
|
|
209
|
+
respond({ tools: this.spec.tools });
|
|
210
|
+
this.toolsListed?.();
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (message.method === "ping")
|
|
214
|
+
return respond({});
|
|
215
|
+
if (message.method !== "tools/call") {
|
|
216
|
+
return this.reply(requestId, { mcp_response: { jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Method not found" } } });
|
|
217
|
+
}
|
|
218
|
+
const id = message.params?._meta?.["claudecode/toolUseId"];
|
|
219
|
+
if (typeof id !== "string") {
|
|
220
|
+
this.diverged = true;
|
|
221
|
+
return respond({ isError: true, content: [{ type: "text", text: "Tool call without an ID" }] });
|
|
222
|
+
}
|
|
223
|
+
const result = this.buffered.get(id);
|
|
224
|
+
if (result !== undefined) {
|
|
225
|
+
this.buffered.delete(id);
|
|
226
|
+
respond(result);
|
|
227
|
+
}
|
|
228
|
+
else
|
|
229
|
+
this.held.set(id, { requestId, rpcId: message.id });
|
|
230
|
+
const active = this.active;
|
|
231
|
+
if (active)
|
|
232
|
+
try {
|
|
233
|
+
this.end(active.segment.onToolCall());
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
this.fail(error);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
end(end) {
|
|
240
|
+
const active = this.active;
|
|
241
|
+
if (!end || !active)
|
|
242
|
+
return;
|
|
243
|
+
if (active.segment.diverged)
|
|
244
|
+
this.diverged = true;
|
|
245
|
+
this.active = undefined;
|
|
246
|
+
this.state = end.state;
|
|
247
|
+
this.pending = end.state === "awaitingTools" ? end.pending : [];
|
|
248
|
+
active.resolve();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const sameSpec = (a, b) => a.command === b.command && a.route === b.route && a.system === b.system &&
|
|
252
|
+
a.effort === b.effort && a.maxTokens === b.maxTokens;
|
|
253
|
+
// Finds an idle process whose history is a prefix of this request's and whose next
|
|
254
|
+
// input is exactly what the request adds: the results it waits for, or new user messages.
|
|
255
|
+
export function reuse(spec, keys, conversation) {
|
|
256
|
+
const candidates = [...pool].filter(p => !p.busy && sameSpec(p.spec, spec) &&
|
|
257
|
+
p.consumed.length < keys.length && p.consumed.every((key, i) => key === keys[i]));
|
|
258
|
+
for (const live of candidates.sort((a, b) => b.lastUsed - a.lastUsed)) {
|
|
259
|
+
const delta = conversation.slice(live.consumed.length);
|
|
260
|
+
let input;
|
|
261
|
+
if (live.state === "awaitingTools") {
|
|
262
|
+
const results = delta.filter((m) => m.role === "toolResult");
|
|
263
|
+
const ids = new Set(results.map(m => m.toolCallId));
|
|
264
|
+
if (results.length === delta.length && results.length === live.pending.length && live.pending.every(id => ids.has(id))) {
|
|
265
|
+
input = { kind: "results", results: new Map(results.map(m => [m.toolCallId, mcpResult(m)])) };
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
else if (live.state === "idle" && delta.every(m => m.role === "user")) {
|
|
269
|
+
input = { kind: "user", content: userContent(delta) };
|
|
270
|
+
}
|
|
271
|
+
if (!input)
|
|
272
|
+
continue;
|
|
273
|
+
live.busy = true;
|
|
274
|
+
liveStats.reused++;
|
|
275
|
+
return { live, input, toolsChanged: JSON.stringify(live.spec.tools) !== JSON.stringify(spec.tools) };
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
// Whether a new process may join the pool, evicting the least recently used idle one
|
|
279
|
+
// when full. With every slot busy the request runs in a process of its own.
|
|
280
|
+
export function admit() {
|
|
281
|
+
const max = loadSettings().server.maxSessions;
|
|
282
|
+
while (pool.size >= max) {
|
|
283
|
+
const victim = [...pool].filter(p => !p.busy).sort((a, b) => a.lastUsed - b.lastUsed)[0];
|
|
284
|
+
if (!victim)
|
|
285
|
+
return false;
|
|
286
|
+
victim.kill();
|
|
287
|
+
}
|
|
288
|
+
return max > 0;
|
|
289
|
+
}
|
|
290
|
+
export async function shutdownLive() {
|
|
291
|
+
const all = [...pool];
|
|
292
|
+
for (const live of all)
|
|
293
|
+
live.kill();
|
|
294
|
+
await Promise.all(all.map(live => live.closed));
|
|
295
|
+
}
|
|
296
|
+
// Tests shorten the idle timeout instead of waiting an hour.
|
|
297
|
+
export function setIdleTimeout(ms) { idleMs = ms; }
|
|
298
|
+
export const livePool = () => [...pool];
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Pi history as Claude Code receives it: normalized like Pi's own providers, keyed for
|
|
2
|
+
// matching a live process, and rendered either as text records or as native content.
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
// Pi's providers skip failed or aborted replies, whose partial content must not be
|
|
5
|
+
// replayed, and answer tool calls that never got a result. pi-ai does not export the
|
|
6
|
+
// helper that does this, so the same rule lives here.
|
|
7
|
+
export function normalizeMessages(messages) {
|
|
8
|
+
const out = [];
|
|
9
|
+
let pending = [];
|
|
10
|
+
const answered = new Set();
|
|
11
|
+
const close = () => {
|
|
12
|
+
for (const call of pending)
|
|
13
|
+
if (!answered.has(call.id))
|
|
14
|
+
out.push({ role: "toolResult", toolCallId: call.id,
|
|
15
|
+
toolName: call.name, content: [{ type: "text", text: "No result provided" }], isError: true, timestamp: Date.now() });
|
|
16
|
+
pending = [];
|
|
17
|
+
answered.clear();
|
|
18
|
+
};
|
|
19
|
+
for (const msg of messages) {
|
|
20
|
+
if (msg.role === "system")
|
|
21
|
+
continue;
|
|
22
|
+
if (msg.role === "assistant") {
|
|
23
|
+
close();
|
|
24
|
+
if (msg.stopReason === "error" || msg.stopReason === "aborted")
|
|
25
|
+
continue;
|
|
26
|
+
pending = msg.content.flatMap(b => b.type === "toolCall" ? [{ id: b.id, name: b.name }] : []);
|
|
27
|
+
out.push(msg);
|
|
28
|
+
}
|
|
29
|
+
else if (msg.role === "toolResult") {
|
|
30
|
+
answered.add(msg.toolCallId);
|
|
31
|
+
out.push(msg);
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
close();
|
|
35
|
+
out.push(msg);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
close();
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("base64url");
|
|
42
|
+
// A live process matches a request when its keys are a prefix of the request's keys.
|
|
43
|
+
// Replies are keyed by response and call IDs only: a Pi tool may rewrite its call's
|
|
44
|
+
// arguments in place (edit parses a JSON-string `edits`), so their content can differ.
|
|
45
|
+
export function messageKey(msg) {
|
|
46
|
+
if (msg.role === "assistant") {
|
|
47
|
+
const calls = msg.content.flatMap(b => b.type === "toolCall" ? [b.id] : []).join(",");
|
|
48
|
+
return msg.responseId ? `a:${msg.responseId}:${calls}` : "a#" + digest(msg.content);
|
|
49
|
+
}
|
|
50
|
+
if (msg.role === "toolResult")
|
|
51
|
+
return `r:${msg.toolCallId}:` + digest([msg.content, msg.isError]);
|
|
52
|
+
return "u:" + digest(msg.content);
|
|
53
|
+
}
|
|
54
|
+
// A new or rebuilt process gets the whole history as text records in one user message,
|
|
55
|
+
// retaining call IDs and images. History names tools the way Claude must call them,
|
|
56
|
+
// so the model does not copy Pi's bare names into new calls.
|
|
57
|
+
export function transcript(messages, toolName) {
|
|
58
|
+
const blocks = [];
|
|
59
|
+
for (const msg of messages) {
|
|
60
|
+
const parts = typeof msg.content === "string" ? [{ type: "text", text: msg.content }] : msg.content;
|
|
61
|
+
const content = parts.flatMap((p) => {
|
|
62
|
+
if (p.type === "image")
|
|
63
|
+
return [{ type: "image", attachment: true }];
|
|
64
|
+
if (p.type === "thinking")
|
|
65
|
+
return [];
|
|
66
|
+
if (p.type === "toolCall")
|
|
67
|
+
return [{ ...p, name: toolName(p.name) }];
|
|
68
|
+
return [p];
|
|
69
|
+
});
|
|
70
|
+
const record = msg.role === "toolResult"
|
|
71
|
+
? { role: msg.role, toolCallId: msg.toolCallId, name: toolName(msg.toolName), isError: msg.isError, content }
|
|
72
|
+
: { role: msg.role, content };
|
|
73
|
+
blocks.push({ type: "text", text: JSON.stringify(record) });
|
|
74
|
+
for (const p of parts)
|
|
75
|
+
if (p.type === "image")
|
|
76
|
+
blocks.push({ type: "image", source: { type: "base64", media_type: p.mimeType, data: p.data } });
|
|
77
|
+
}
|
|
78
|
+
return blocks;
|
|
79
|
+
}
|
|
80
|
+
// Later user messages reach a live process as ordinary content.
|
|
81
|
+
export function userContent(messages) {
|
|
82
|
+
return messages.flatMap(msg => typeof msg.content === "string" ? [{ type: "text", text: msg.content }]
|
|
83
|
+
: msg.content.map(p => p.type === "image" ? { type: "image", source: { type: "base64", media_type: p.mimeType, data: p.data } } : { type: "text", text: p.text }));
|
|
84
|
+
}
|
|
85
|
+
// A Pi tool result as the MCP result of the call Claude Code is waiting on.
|
|
86
|
+
export function mcpResult(msg) {
|
|
87
|
+
return {
|
|
88
|
+
content: msg.content.map(p => p.type === "image" ? { type: "image", data: p.data, mimeType: p.mimeType } : { type: "text", text: p.text }),
|
|
89
|
+
...(msg.isError ? { isError: true } : {}),
|
|
90
|
+
};
|
|
91
|
+
}
|
package/dist/server/http.js
CHANGED
|
@@ -101,7 +101,7 @@ export async function runServer(backend, { token, host, port }) {
|
|
|
101
101
|
const signal = controller.signal;
|
|
102
102
|
if (req.method === "GET" && req.url === "/v1/health") {
|
|
103
103
|
const { available, loggedIn, diagnostic } = await backend.status(signal);
|
|
104
|
-
return json(res, 200, { available, loggedIn, diagnostic });
|
|
104
|
+
return json(res, 200, { available, loggedIn, diagnostic, ...(backend.stats ? { sessions: backend.stats() } : {}) });
|
|
105
105
|
}
|
|
106
106
|
if (req.method === "GET" && req.url === "/v1/models")
|
|
107
107
|
return json(res, 200, (await models(signal)).map(({ route, ...model }) => model));
|
|
@@ -211,6 +211,7 @@ export async function runServer(backend, { token, host, port }) {
|
|
|
211
211
|
}
|
|
212
212
|
finally {
|
|
213
213
|
await Promise.allSettled(pending);
|
|
214
|
+
await backend.close?.();
|
|
214
215
|
process.chdir(tmpdir());
|
|
215
216
|
await rm(directory, { recursive: true, force: true });
|
|
216
217
|
}
|
package/dist/server.js
CHANGED
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
import { claudeCode } from "./backends/claude-code/index.js";
|
|
3
3
|
import { runServer } from "./server/http.js";
|
|
4
4
|
import { displayPath, generateToken, loadSettings, loginCommand, saveToken } from "./shared/settings.js";
|
|
5
|
+
import { isVersionFlag, version } from "./shared/version.js";
|
|
5
6
|
const showToken = "npx -y @a-tether/server token";
|
|
6
7
|
function main(args) {
|
|
8
|
+
// Before reading settings, so a broken settings.json still shows the version.
|
|
9
|
+
if (isVersionFlag(args))
|
|
10
|
+
return console.log("a-tether-server " + version);
|
|
7
11
|
const settings = loadSettings();
|
|
8
12
|
if (args[0] === "token" && args.length === 1) {
|
|
9
13
|
if (!settings.token)
|
|
@@ -12,7 +16,7 @@ function main(args) {
|
|
|
12
16
|
return;
|
|
13
17
|
}
|
|
14
18
|
if (args.length)
|
|
15
|
-
throw new Error("用法:a-tether-server
|
|
19
|
+
throw new Error("用法:a-tether-server 启动服务\n a-tether-server token 显示 A 端的配置命令\n a-tether-server --version 显示版本");
|
|
16
20
|
let token = settings.token;
|
|
17
21
|
if (token)
|
|
18
22
|
console.log(`令牌:已配置(${displayPath})。查看 A 端配置命令:${showToken}`);
|
package/dist/shared/protocol.js
CHANGED
|
@@ -10,7 +10,8 @@ export const messages = {
|
|
|
10
10
|
quota: "Claude 额度、速率或计费限制,请在 C 上检查账户。",
|
|
11
11
|
backend: "C 上的 Claude Code 调用失败,具体原因见 C 端服务控制台。",
|
|
12
12
|
overloaded: "模型服务繁忙或暂时不可用,请稍后重试。",
|
|
13
|
-
|
|
13
|
+
// Pi recognizes an overflow by English provider phrases and then compacts and retries.
|
|
14
|
+
context: "请求超出模型的上下文长度(prompt is too long)。Pi 开启自动压缩时会压缩后重试,否则请运行 /compact 或减少输入。",
|
|
14
15
|
discovery: "C 无法获取 Claude 模型目录,请检查 CLI 版本和连接。",
|
|
15
16
|
cancelled: "请求已取消。",
|
|
16
17
|
timeout: "C 上的请求超时。",
|
package/dist/shared/settings.js
CHANGED
|
@@ -68,6 +68,9 @@ export function loadSettings(file = settingsPath()) {
|
|
|
68
68
|
const allowUsageCredits = server.allowUsageCredits ?? false;
|
|
69
69
|
if (typeof allowUsageCredits !== "boolean")
|
|
70
70
|
fail("server.allowUsageCredits", "必须是 true 或 false");
|
|
71
|
+
const maxSessions = server.maxSessions ?? 16;
|
|
72
|
+
if (typeof maxSessions !== "number" || !Number.isInteger(maxSessions) || maxSessions < 0 || maxSessions > 256)
|
|
73
|
+
fail("server.maxSessions", "必须是 0–256 的整数");
|
|
71
74
|
// Without client.url, Pi on the same machine follows server.port.
|
|
72
75
|
const url = text(client, "client.url") ?? "http://127.0.0.1:" + port;
|
|
73
76
|
let origin = "";
|
|
@@ -83,7 +86,8 @@ export function loadSettings(file = settingsPath()) {
|
|
|
83
86
|
return {
|
|
84
87
|
token: raw.token,
|
|
85
88
|
server: { host: text(server, "server.host") ?? "127.0.0.1", port: port,
|
|
86
|
-
claude: text(server, "server.claude") ?? "claude", allowUsageCredits: allowUsageCredits
|
|
89
|
+
claude: text(server, "server.claude") ?? "claude", allowUsageCredits: allowUsageCredits,
|
|
90
|
+
maxSessions: maxSessions },
|
|
87
91
|
client: { url: origin, pi: text(client, "client.pi") },
|
|
88
92
|
};
|
|
89
93
|
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
// The repository keeps package.json one level above src/, and each published package
|
|
3
|
+
// one level above dist/, so the same relative path works in both.
|
|
4
|
+
export const version = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
5
|
+
export const isVersionFlag = (args) => args.length === 1 && (args[0] === "--version" || args[0] === "-v");
|
package/package.json
CHANGED
|
@@ -1,15 +0,0 @@
|
|
|
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
|
-
}
|