@pontia/claude-client 0.8.6 → 0.8.8

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.
@@ -0,0 +1,283 @@
1
+ import { RpcError } from "./rpc-error.js";
2
+ export { RpcError } from "./rpc-error.js";
3
+ import { createConnection } from "node:net";
4
+ import { isAbsolute, join } from "node:path";
5
+ import { statSync } from "node:fs";
6
+ export const CONTROL_VERSION = 8;
7
+ export const MAX_CONTROL_FRAME_BYTES = 64 * 1024;
8
+ // Match the former HTTP event body limit, including the RPC envelope.
9
+ export const MAX_RPC_FRAME_BYTES = 2 * 1024 * 1024 + 1024;
10
+ const REQUEST_TIMEOUT_MS = 5_000;
11
+ export function controlSocketPath(pontiaHome) {
12
+ if (!isAbsolute(pontiaHome) || pontiaHome.includes("\0"))
13
+ throw new Error("Control home requires an absolute path without NUL");
14
+ const home = statSync(pontiaHome, { bigint: true });
15
+ return join(`/tmp/pontia-control-${home.uid}-${home.dev.toString(16)}-${home.ino.toString(16)}`, "rpc.sock");
16
+ }
17
+ class RpcSocket {
18
+ sequence = 0;
19
+ pending = new Map();
20
+ buffered = Buffer.alloc(0);
21
+ failed = false;
22
+ socket;
23
+ onRequest;
24
+ keepAlive;
25
+ constructor(socket, onRequest, keepAlive) {
26
+ this.socket = socket;
27
+ this.onRequest = onRequest;
28
+ this.keepAlive = keepAlive;
29
+ socket.on("data", (chunk) => this.receive(chunk));
30
+ socket.on("error", (error) => this.fail(error));
31
+ socket.on("close", () => this.fail(new Error("Control RPC connection closed; requests were not replayed")));
32
+ }
33
+ close() {
34
+ this.fail(new Error("Control RPC connection closed"));
35
+ }
36
+ request(method, params) {
37
+ if (this.failed)
38
+ return Promise.reject(new Error("Control RPC connection is closed"));
39
+ const id = `runtime:${this.sequence++}`;
40
+ const encoded = this.encode({ jsonrpc: "2.0", id, method, params });
41
+ return new Promise((resolve, reject) => {
42
+ const timer = setTimeout(() => this.fail(new Error("Control RPC timed out; request was not replayed")), REQUEST_TIMEOUT_MS);
43
+ timer.unref();
44
+ // RPC mode installs its stdin listener only after extension registration.
45
+ this.socket.ref();
46
+ this.pending.set(id, { resolve, reject, timer });
47
+ this.write(encoded);
48
+ });
49
+ }
50
+ encode(value) {
51
+ const encoded = JSON.stringify(value);
52
+ if (Buffer.byteLength(encoded) > MAX_RPC_FRAME_BYTES)
53
+ throw new RpcError(-32602, "Control RPC frame exceeds size limit");
54
+ return `${encoded}\n`;
55
+ }
56
+ write(encoded, afterWrite) {
57
+ if (this.socket.writableLength + Buffer.byteLength(encoded) > 2 * MAX_RPC_FRAME_BYTES) {
58
+ this.fail(new Error("Control RPC backpressure limit reached"));
59
+ return;
60
+ }
61
+ this.socket.write(encoded, afterWrite);
62
+ }
63
+ fail(error) {
64
+ if (this.failed)
65
+ return;
66
+ this.failed = true;
67
+ for (const pending of this.pending.values()) {
68
+ clearTimeout(pending.timer);
69
+ pending.reject(error);
70
+ }
71
+ this.pending.clear();
72
+ this.socket.destroy();
73
+ }
74
+ receive(chunk) {
75
+ let offset = 0;
76
+ try {
77
+ while (offset < chunk.length && !this.failed) {
78
+ const newline = chunk.indexOf(10, offset);
79
+ const end = newline === -1 ? chunk.length : newline;
80
+ const part = chunk.subarray(offset, end);
81
+ if (this.buffered.length + part.length > MAX_RPC_FRAME_BYTES)
82
+ throw new Error("Control RPC frame exceeds size limit");
83
+ this.buffered = Buffer.concat([this.buffered, part]);
84
+ if (newline === -1)
85
+ return;
86
+ const frame = this.buffered;
87
+ this.buffered = Buffer.alloc(0);
88
+ this.handle(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(frame)));
89
+ offset = newline + 1;
90
+ }
91
+ }
92
+ catch (error) {
93
+ this.fail(error instanceof Error ? error : new Error(String(error)));
94
+ }
95
+ }
96
+ handle(value) {
97
+ if (!value || typeof value !== "object" || Array.isArray(value))
98
+ throw new Error("Invalid Control RPC frame");
99
+ const message = value;
100
+ if (message.jsonrpc !== "2.0")
101
+ throw new Error("Invalid Control RPC version");
102
+ if (Object.hasOwn(message, "method")) {
103
+ if (typeof message.method !== "string" ||
104
+ Object.hasOwn(message, "result") ||
105
+ Object.hasOwn(message, "error") ||
106
+ (message.id !== undefined &&
107
+ typeof message.id !== "string" &&
108
+ typeof message.id !== "number")) {
109
+ throw new Error("Invalid Control RPC request");
110
+ }
111
+ const respond = (body, afterWrite) => {
112
+ if (message.id !== undefined)
113
+ this.write(this.encode({ jsonrpc: "2.0", id: message.id, ...body }), afterWrite);
114
+ else
115
+ afterWrite?.();
116
+ };
117
+ const error = (code, message) => respond({ error: { code, message } });
118
+ const params = message.params === undefined ? {} : message.params;
119
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
120
+ error(-32602, "Expected named parameters");
121
+ return;
122
+ }
123
+ this.onRequest(message.method, params, respond, error, Buffer.byteLength(JSON.stringify(message)));
124
+ return;
125
+ }
126
+ if (Object.hasOwn(message, "result") === Object.hasOwn(message, "error") ||
127
+ (message.error !== undefined &&
128
+ (!message.error ||
129
+ !Number.isInteger(message.error.code) ||
130
+ typeof message.error.message !== "string"))) {
131
+ throw new Error("Invalid Control RPC response");
132
+ }
133
+ const pending = this.pending.get(message.id);
134
+ if (!pending)
135
+ throw new Error("Unexpected Control RPC response ID");
136
+ this.pending.delete(message.id);
137
+ if (!this.pending.size && !this.keepAlive)
138
+ this.socket.unref();
139
+ clearTimeout(pending.timer);
140
+ if (message.error)
141
+ pending.reject(new RpcError(message.error.code, message.error.message));
142
+ else
143
+ pending.resolve(message.result);
144
+ }
145
+ }
146
+ export async function connectRuntime(pontiaHome, onError, onRequest, onReconnect, onDisconnect, keepAlive = false) {
147
+ const path = controlSocketPath(pontiaHome);
148
+ let identity;
149
+ let stopped = false;
150
+ let retry;
151
+ let current;
152
+ const connecting = new Set();
153
+ const peers = new Set();
154
+ let reconnectRejected = false;
155
+ let attached = false;
156
+ let delay = 250;
157
+ const waiting = new Set();
158
+ async function ready() {
159
+ if (!identity || attached || stopped || reconnectRejected)
160
+ return;
161
+ await new Promise((resolve, reject) => {
162
+ const wake = () => {
163
+ clearTimeout(timer);
164
+ waiting.delete(wake);
165
+ resolve();
166
+ };
167
+ const timer = setTimeout(() => {
168
+ waiting.delete(wake);
169
+ reject(new Error("Control reconnect timed out"));
170
+ }, REQUEST_TIMEOUT_MS);
171
+ waiting.add(wake);
172
+ });
173
+ }
174
+ function wakeRequests() {
175
+ for (const wake of waiting)
176
+ wake();
177
+ }
178
+ async function open() {
179
+ const socket = createConnection(path);
180
+ connecting.add(socket);
181
+ if (!keepAlive)
182
+ socket.unref();
183
+ try {
184
+ await new Promise((resolve, reject) => {
185
+ const timer = setTimeout(() => socket.destroy(new Error("Control socket connection timed out")), REQUEST_TIMEOUT_MS);
186
+ socket.once("error", reject);
187
+ socket.once("connect", () => {
188
+ clearTimeout(timer);
189
+ socket.off("error", reject);
190
+ resolve();
191
+ });
192
+ socket.once("close", () => {
193
+ clearTimeout(timer);
194
+ reject(new Error("Control socket closed during connect"));
195
+ });
196
+ });
197
+ }
198
+ finally {
199
+ connecting.delete(socket);
200
+ }
201
+ if (stopped) {
202
+ socket.destroy();
203
+ throw new Error("Control connection is closed");
204
+ }
205
+ const peer = new RpcSocket(socket, onRequest, keepAlive);
206
+ peers.add(peer);
207
+ socket.once("close", () => {
208
+ peers.delete(peer);
209
+ if (current === peer) {
210
+ current = undefined;
211
+ attached = false;
212
+ onDisconnect?.();
213
+ reconnect();
214
+ }
215
+ });
216
+ return peer;
217
+ }
218
+ function reconnect() {
219
+ if (stopped || reconnectRejected || !identity || retry)
220
+ return;
221
+ retry = setTimeout(async () => {
222
+ retry = undefined;
223
+ try {
224
+ const peer = await open();
225
+ current = peer;
226
+ const result = (await peer.request("runtime.attach", {
227
+ version: CONTROL_VERSION,
228
+ session_id: identity.sessionId,
229
+ runtime_id: identity.runtimeId,
230
+ client_session_key: identity.clientSessionKey,
231
+ }));
232
+ if (result?.session_id !== identity.sessionId ||
233
+ result?.runtime_id !== identity.runtimeId) {
234
+ throw new RpcError(-32009, "Control reconnect identity mismatch");
235
+ }
236
+ attached = true;
237
+ delay = 250;
238
+ wakeRequests();
239
+ await onReconnect?.();
240
+ }
241
+ catch (error) {
242
+ onError(error instanceof Error ? error : new Error(String(error)));
243
+ // A rejected identity cannot be repaired by repeating registration.
244
+ if (error instanceof RpcError && error.code !== -32603) {
245
+ reconnectRejected = true;
246
+ wakeRequests();
247
+ }
248
+ current?.close();
249
+ current = undefined;
250
+ delay = Math.min(delay * 2, 5000);
251
+ reconnect();
252
+ }
253
+ }, delay);
254
+ if (!keepAlive)
255
+ retry.unref();
256
+ }
257
+ current = await open();
258
+ return {
259
+ async request(method, params) {
260
+ await ready();
261
+ if (!current || stopped)
262
+ return Promise.reject(new Error("Control connection is unavailable"));
263
+ return current.request(method, params);
264
+ },
265
+ registered(value) {
266
+ identity = value;
267
+ attached = !!current;
268
+ if (!current)
269
+ reconnect();
270
+ },
271
+ async close() {
272
+ stopped = true;
273
+ wakeRequests();
274
+ if (retry)
275
+ clearTimeout(retry);
276
+ for (const socket of connecting)
277
+ socket.destroy();
278
+ for (const peer of peers)
279
+ peer.close();
280
+ current = undefined;
281
+ },
282
+ };
283
+ }
@@ -0,0 +1,7 @@
1
+ export class RpcError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.code = code;
6
+ }
7
+ }
package/dist/src/host.js CHANGED
@@ -206,10 +206,8 @@ export class Host {
206
206
  this.controlConnected = false;
207
207
  this.permissions.expire();
208
208
  }
209
- controlRestored(factsCaughtUp) {
210
- // No replay buffer: only a controller that has already ingested every emitted
211
- // fact can resume input. Before the first input, there cannot be a fact gap.
212
- this.controlConnected = !this.execution || factsCaughtUp;
209
+ controlRestored() {
210
+ this.controlConnected = true;
213
211
  }
214
212
  acceptsControl() {
215
213
  return !this.closed && !this.closing && !this.unavailable && this.controlConnected;
package/dist/src/main.js CHANGED
@@ -29,22 +29,11 @@ async function main() {
29
29
  }
30
30
  const config = bootstrap(data);
31
31
  await serve(config);
32
- process.stdout.write('{"listening":true}\n');
33
32
  return;
34
33
  }
35
34
  throw new Error("bootstrap_missing");
36
35
  }
37
- main().catch((error) => {
38
- if (process.argv[2] !== "preflight" &&
39
- process.argv[2] !== "history" &&
40
- process.argv[2] !== "models") {
41
- const systemCode = error instanceof Error && "code" in error ? error.code : undefined;
42
- const code = typeof systemCode === "string" &&
43
- ["EACCES", "EADDRINUSE", "EINVAL", "ENOENT", "ENAMETOOLONG", "ENOTDIR", "EPERM"].includes(systemCode)
44
- ? systemCode
45
- : "HOST_START_FAILED";
46
- process.stdout.write(JSON.stringify({ listening: false, code }) + "\n");
47
- }
36
+ main().catch(() => {
48
37
  process.stderr.write("Claude Code host could not start.\n");
49
38
  process.exitCode = 1;
50
39
  });
@@ -1,10 +1,6 @@
1
- import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
2
- import { chmod, lstat } from "node:fs/promises";
3
- import { createServer } from "node:net";
4
- import { dirname } from "node:path";
1
+ import { randomUUID } from "node:crypto";
2
+ import { connectRuntime, CONTROL_VERSION, } from "../shared/control-socket.js";
5
3
  import { Host, ControlError } from "./host.js";
6
- const MAX_FRAME = 1024 * 1024;
7
- const RECEIPTS = 128;
8
4
  function object(value) {
9
5
  if (!value || typeof value !== "object" || Array.isArray(value))
10
6
  throw new ControlError("rejected", "invalid_request");
@@ -20,8 +16,7 @@ export function bootstrap(value) {
20
16
  const result = {
21
17
  session_id: string(data.session_id),
22
18
  runtime_id: string(data.runtime_id),
23
- socket_path: string(data.socket_path),
24
- token: string(data.token),
19
+ pontia_home: string(data.pontia_home),
25
20
  cwd: string(data.cwd),
26
21
  };
27
22
  if (data.system_prompt !== undefined)
@@ -49,42 +44,33 @@ export function bootstrap(value) {
49
44
  yolo: policy.yolo,
50
45
  };
51
46
  }
52
- if (!/^[0-9a-f]{64}$/.test(result.token))
53
- throw new ControlError("rejected", "invalid_token");
54
47
  return result;
55
48
  }
56
49
  export async function serve(config, factory) {
57
- const directory = await lstat(dirname(config.socket_path));
58
- if (!directory.isDirectory() ||
59
- directory.isSymbolicLink() ||
60
- (directory.mode & 0o077) !== 0 ||
61
- directory.uid !== process.getuid?.())
62
- throw new Error("socket_directory_not_private");
63
50
  const generation = randomUUID();
64
- let current;
51
+ let connected = false;
65
52
  let sequence = 0;
66
- let highWater = 0;
67
- let stopped = false;
68
- const sockets = new Set();
69
- const receipts = new Map();
70
- const send = (socket, data) => {
71
- const frame = JSON.stringify(data) + "\n";
72
- if (Buffer.byteLength(frame) > MAX_FRAME ||
73
- socket.writableLength + Buffer.byteLength(frame) > MAX_FRAME) {
74
- socket.destroy();
75
- if (current === socket) {
76
- current = undefined;
77
- host.controlLost();
78
- }
79
- return;
80
- }
81
- if (!socket.destroyed)
82
- socket.write(frame);
53
+ let connection;
54
+ const reports = new Set();
55
+ const identity = {
56
+ sessionId: config.session_id,
57
+ runtimeId: config.runtime_id,
58
+ clientSessionKey: undefined,
83
59
  };
84
60
  const host = new Host(config, (event) => {
85
- sequence += 1;
86
- if (current)
87
- send(current, { type: "event", host_id: generation, sequence, event });
61
+ sequence++;
62
+ if (event.kind === "ready")
63
+ identity.clientSessionKey = event.native_session_id;
64
+ if (!connected)
65
+ return;
66
+ const report = connection.request("host.event", { host_id: generation, sequence, event });
67
+ reports.add(report);
68
+ void report
69
+ .catch(() => {
70
+ console.error("Claude host fact delivery failed");
71
+ })
72
+ .finally(() => reports.delete(report));
73
+ connection.registered(identity);
88
74
  }, factory);
89
75
  const invoke = async (request) => {
90
76
  try {
@@ -120,132 +106,77 @@ export async function serve(config, factory) {
120
106
  : { status: "unknown", reason: "operation_unconfirmed" };
121
107
  }
122
108
  };
123
- const server = createServer((socket) => {
124
- sockets.add(socket);
125
- let authenticated = false;
126
- let buffer = Buffer.alloc(0);
127
- socket.on("error", () => { });
128
- socket.on("close", () => {
129
- sockets.delete(socket);
130
- if (current === socket) {
131
- current = undefined;
132
- if (!stopped && !host.status().closed)
133
- host.controlLost();
134
- }
135
- });
136
- socket.on("data", (chunk) => {
137
- buffer = Buffer.concat([buffer, Buffer.from(chunk)]);
138
- for (;;) {
139
- const newline = buffer.indexOf(10);
140
- if (newline < 0) {
141
- if (buffer.length > MAX_FRAME)
142
- socket.destroy();
143
- return;
144
- }
145
- if (newline + 1 > MAX_FRAME) {
146
- socket.destroy();
147
- return;
148
- }
149
- const line = buffer.subarray(0, newline).toString("utf8");
150
- buffer = buffer.subarray(newline + 1);
151
- try {
152
- const request = object(JSON.parse(line));
153
- if (!authenticated) {
154
- const token = Buffer.from(typeof request.token === "string" ? request.token : "");
155
- const expected = Buffer.from(config.token);
156
- if (request.method !== "attach" ||
157
- request.session_id !== config.session_id ||
158
- request.runtime_id !== config.runtime_id ||
159
- token.length !== expected.length ||
160
- !timingSafeEqual(token, expected)) {
161
- socket.destroy();
162
- return;
163
- }
164
- if (current) {
165
- // A replacement does not inherit pending replies or replay missed facts.
166
- current.destroy();
167
- current = undefined;
168
- host.controlLost();
169
- }
170
- current = socket;
171
- host.controlRestored(request.last_host_id === generation && request.last_sequence === sequence);
172
- authenticated = true;
173
- send(socket, {
174
- type: "attached",
175
- host_id: generation,
176
- sequence,
177
- high_water: highWater,
178
- ...host.status(),
179
- });
180
- continue;
181
- }
182
- if (current !== socket || request.host_id !== generation) {
183
- socket.destroy();
184
- return;
185
- }
186
- const id = request.id;
187
- if (typeof id !== "number" || !Number.isSafeInteger(id) || id < 1)
188
- throw new ControlError("rejected", "invalid_request_id");
189
- const hash = createHash("sha256").update(line).digest("hex");
190
- let receipt = receipts.get(id);
191
- if (receipt) {
192
- if (receipt.hash !== hash)
193
- throw new ControlError("rejected", "request_id_reused");
194
- }
195
- else {
196
- if (id <= highWater)
197
- throw new ControlError("rejected", "request_expired");
198
- highWater = id;
199
- receipt = { hash, response: invoke(request) };
200
- receipts.set(id, receipt);
201
- if (receipts.size > RECEIPTS)
202
- receipts.delete(receipts.keys().next().value);
203
- }
204
- void receipt.response.then((response) => {
205
- if (current === socket && !socket.destroyed) {
206
- send(socket, { type: "response", host_id: generation, id, ...response });
207
- }
208
- if (request.method === "close" && response.status === "accepted" && !stopped) {
209
- stopped = true;
210
- server.close();
211
- for (const peer of sockets)
212
- peer.destroySoon();
213
- }
214
- });
215
- }
216
- catch (error) {
217
- // Malformed or ambiguous requests are never executed, nor echoed into diagnostics.
218
- send(socket, {
219
- type: "error",
220
- status: "rejected",
221
- reason: error instanceof ControlError ? error.reason : "invalid_request",
222
- });
223
- }
109
+ connection = await connectRuntime(config.pontia_home, () => console.error("Claude host control connection unavailable"), (method, params, respond, error) => {
110
+ if (method === "host.status") {
111
+ respond({
112
+ result: {
113
+ host_id: generation,
114
+ ...host.status(),
115
+ launch: {
116
+ cwd: config.cwd,
117
+ config_dir: process.env.CLAUDE_CONFIG_DIR,
118
+ model: config.model,
119
+ resume: config.resume,
120
+ },
121
+ },
122
+ });
123
+ return;
124
+ }
125
+ if (method !== "host.command") {
126
+ error(-32601, "Unknown host method");
127
+ return;
128
+ }
129
+ connected = true;
130
+ host.controlRestored();
131
+ void invoke(params)
132
+ .then(async (result) => {
133
+ if (params.method === "close" && result.status === "accepted") {
134
+ await Promise.allSettled(reports);
135
+ respond({ result }, () => {
136
+ void connection.close();
137
+ });
224
138
  }
225
- });
226
- });
227
- await new Promise((resolve, reject) => {
228
- server.once("error", reject);
229
- server.listen(config.socket_path, () => {
230
- server.off("error", reject);
231
- resolve();
232
- });
233
- });
234
- // Parent directory already excludes other users during the bind/chmod window.
139
+ else
140
+ respond({ result });
141
+ })
142
+ .catch(() => error(-32603, "Host control failed"));
143
+ }, async () => {
144
+ connected = true;
145
+ host.controlRestored();
146
+ }, () => {
147
+ connected = false;
148
+ host.controlLost();
149
+ }, true);
235
150
  try {
236
- await chmod(config.socket_path, 0o600);
151
+ const attached = (await connection.request("runtime.attach", {
152
+ version: CONTROL_VERSION,
153
+ session_id: config.session_id,
154
+ runtime_id: config.runtime_id,
155
+ client_session_key: identity.clientSessionKey,
156
+ }));
157
+ if (attached.session_id !== config.session_id || attached.runtime_id !== config.runtime_id)
158
+ throw new Error("runtime_identity_mismatch");
159
+ connection.registered(identity);
160
+ connected = true;
161
+ host.controlRestored();
237
162
  }
238
163
  catch (error) {
239
- server.close();
164
+ await connection.close();
240
165
  throw error;
241
166
  }
242
- return {
243
- async close() {
244
- stopped = true;
245
- await host.close();
246
- for (const socket of sockets)
247
- socket.destroy();
248
- await new Promise((resolve) => server.close(() => resolve()));
249
- },
167
+ const terminate = () => {
168
+ void close();
250
169
  };
170
+ process.once("SIGTERM", terminate);
171
+ async function close() {
172
+ process.off("SIGTERM", terminate);
173
+ try {
174
+ await host.close();
175
+ }
176
+ finally {
177
+ await Promise.allSettled(reports);
178
+ await connection.close();
179
+ }
180
+ }
181
+ return { close };
251
182
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pontia/claude-client",
3
- "version": "0.8.6",
3
+ "version": "0.8.8",
4
4
  "description": "Claude Code client for Pontia",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -10,7 +10,8 @@
10
10
  },
11
11
  "files": [
12
12
  "dist/src",
13
- "LICENSE"
13
+ "LICENSE",
14
+ "dist/shared"
14
15
  ],
15
16
  "type": "module",
16
17
  "main": "dist/src/main.js",