@pontia/claude-client 0.8.8 → 0.8.9

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.
@@ -8,6 +8,8 @@ export const MAX_CONTROL_FRAME_BYTES = 64 * 1024;
8
8
  // Match the former HTTP event body limit, including the RPC envelope.
9
9
  export const MAX_RPC_FRAME_BYTES = 2 * 1024 * 1024 + 1024;
10
10
  const REQUEST_TIMEOUT_MS = 5_000;
11
+ export class AttachmentRejected extends Error {
12
+ }
11
13
  export function controlSocketPath(pontiaHome) {
12
14
  if (!isAbsolute(pontiaHome) || pontiaHome.includes("\0"))
13
15
  throw new Error("Control home requires an absolute path without NUL");
@@ -151,7 +153,7 @@ export async function connectRuntime(pontiaHome, onError, onRequest, onReconnect
151
153
  let current;
152
154
  const connecting = new Set();
153
155
  const peers = new Set();
154
- let reconnectRejected = false;
156
+ let reconnectRejected;
155
157
  let attached = false;
156
158
  let delay = 250;
157
159
  const waiting = new Set();
@@ -236,13 +238,13 @@ export async function connectRuntime(pontiaHome, onError, onRequest, onReconnect
236
238
  attached = true;
237
239
  delay = 250;
238
240
  wakeRequests();
239
- await onReconnect?.();
241
+ void onReconnect?.().catch(onError);
240
242
  }
241
243
  catch (error) {
242
244
  onError(error instanceof Error ? error : new Error(String(error)));
243
245
  // A rejected identity cannot be repaired by repeating registration.
244
246
  if (error instanceof RpcError && error.code !== -32603) {
245
- reconnectRejected = true;
247
+ reconnectRejected = new AttachmentRejected(error.message);
246
248
  wakeRequests();
247
249
  }
248
250
  current?.close();
@@ -257,8 +259,15 @@ export async function connectRuntime(pontiaHome, onError, onRequest, onReconnect
257
259
  current = await open();
258
260
  return {
259
261
  async request(method, params) {
260
- await ready();
261
- if (!current || stopped)
262
+ if (method === "event.report" || method === "host.event")
263
+ await ready();
264
+ else if (identity && !attached)
265
+ throw new Error("Control connection is unavailable");
266
+ if (reconnectRejected)
267
+ throw reconnectRejected;
268
+ if (stopped)
269
+ throw new AttachmentRejected("Control connection closed");
270
+ if (!current)
262
271
  return Promise.reject(new Error("Control connection is unavailable"));
263
272
  return current.request(method, params);
264
273
  },
@@ -0,0 +1,33 @@
1
+ import { setTimeout } from "node:timers/promises";
2
+ import { AttachmentRejected, RpcError } from "./control-socket.js";
3
+ // A queue belongs to one runtime attachment. Its owner captures the fact and key
4
+ // before enqueueing so every retry sends the same observation.
5
+ export class ReportQueue {
6
+ tail = Promise.resolve();
7
+ rejected;
8
+ drained() {
9
+ return this.tail;
10
+ }
11
+ enqueue(send) {
12
+ const result = this.tail.then(async () => {
13
+ let delay = 250;
14
+ for (;;) {
15
+ if (this.rejected)
16
+ throw this.rejected;
17
+ try {
18
+ return await send();
19
+ }
20
+ catch (error) {
21
+ if (error instanceof AttachmentRejected)
22
+ this.rejected = error;
23
+ if (this.rejected || (error instanceof RpcError && error.code !== -32603))
24
+ throw error;
25
+ await setTimeout(delay, undefined, { ref: false });
26
+ delay = Math.min(delay * 2, 5000);
27
+ }
28
+ }
29
+ });
30
+ this.tail = result.then(() => { }, () => { });
31
+ return result;
32
+ }
33
+ }
package/dist/src/facts.js CHANGED
@@ -1,3 +1,31 @@
1
+ function reportKey(host, sequence, event) {
2
+ switch (event.kind) {
3
+ case "permission_requested":
4
+ return `claude:${host}:${event.permission_id}`;
5
+ case "permission_settled":
6
+ return `claude:${host}:${event.permission_id}:settled`;
7
+ case "started":
8
+ return `claude:${host}:${event.input_id}:start`;
9
+ case "finished":
10
+ return `claude:${host}:${event.result_id}`;
11
+ case "model":
12
+ case "context_usage":
13
+ case "compaction":
14
+ case "ready":
15
+ return `claude:${host}:${sequence}`;
16
+ }
17
+ }
18
+ export function hostObservation(host, sequence, event) {
19
+ return {
20
+ host_id: host,
21
+ sequence,
22
+ report_key: reportKey(host, sequence, event),
23
+ ...(event.kind === "permission_settled"
24
+ ? { registration_key: `claude:${host}:${event.permission_id}` }
25
+ : {}),
26
+ event,
27
+ };
28
+ }
1
29
  export class FactError extends Error {
2
30
  result;
3
31
  constructor(reason, message) {
package/dist/src/host.js CHANGED
@@ -101,7 +101,7 @@ export class Host {
101
101
  ...(policy?.disable_mcp ? ["mcp__*"] : []),
102
102
  ],
103
103
  canUseTool: (tool, input, context) => {
104
- if (!this.acceptsControl())
104
+ if (this.closed || this.closing || this.unavailable)
105
105
  return Promise.resolve({ behavior: "deny", message: "Tool approval is unavailable." });
106
106
  if (policy?.yolo)
107
107
  return Promise.resolve({ behavior: "allow", updatedInput: input });
@@ -176,6 +176,12 @@ export class Host {
176
176
  }
177
177
  // The result, not this acknowledgement, decides whether interruption won.
178
178
  }
179
+ hasPermission(id) {
180
+ return this.permissions.has(id);
181
+ }
182
+ cancelPermission(id) {
183
+ this.permissions.cancel(id);
184
+ }
179
185
  resolvePermission(id, option) {
180
186
  if (!this.acceptsControl() || !this.permissions.resolve(id, option))
181
187
  throw new ControlError("rejected", "permission_expired_or_invalid");
@@ -204,7 +210,6 @@ export class Host {
204
210
  }
205
211
  controlLost() {
206
212
  this.controlConnected = false;
207
- this.permissions.expire();
208
213
  }
209
214
  controlRestored() {
210
215
  this.controlConnected = true;
@@ -1,59 +1,85 @@
1
- import { randomUUID } from "node:crypto";
2
- // Native callbacks stay in memory and are never reconstructed from persisted Interactions.
1
+ import { createHash } from "node:crypto";
2
+ // Object member order is immaterial. Array order, tool arguments and SDK permission
3
+ // context are part of the authorization. The signal and correlation ID are transport state.
4
+ function digest(tool, input, context) {
5
+ const content = JSON.stringify({ tool, input, context }, (_key, value) => {
6
+ if (typeof value !== "object" || value === null || Array.isArray(value))
7
+ return value;
8
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
9
+ });
10
+ return createHash("sha256").update(content).digest("hex");
11
+ }
3
12
  export class Permissions {
4
13
  emit;
5
14
  pending = new Map();
6
15
  constructor(emit) {
7
16
  this.emit = emit;
8
17
  }
9
- request = (tool, _input, options) => {
10
- if (tool === "AskUserQuestion" || options.signal.aborted) {
18
+ request = (tool, input, { signal, requestId: id, ...context }) => {
19
+ if (tool === "AskUserQuestion" || signal.aborted) {
11
20
  return Promise.resolve({
12
21
  behavior: "deny",
13
22
  message: "This interaction is unsupported or expired.",
14
23
  });
15
24
  }
16
- const id = randomUUID();
17
- return new Promise((resolve) => {
18
- const abort = () => finish();
19
- const finish = (option) => {
20
- if (!this.pending.delete(id))
21
- return;
22
- options.signal.removeEventListener("abort", abort);
23
- this.emit({
24
- kind: "permission_settled",
25
- permission_id: id,
26
- outcome: option ? "resolved" : "expired",
27
- });
28
- resolve(option === "allow"
29
- ? { behavior: "allow" }
30
- : {
31
- behavior: "deny",
32
- message: option === "deny" ? "User denied this tool use." : "Tool approval expired.",
33
- });
34
- };
35
- this.pending.set(id, finish);
36
- options.signal.addEventListener("abort", abort, { once: true });
37
- // No arguments, paths, SDK payloads or permission-rule suggestions enter storage.
38
- // A sub-agent callback is still an ordinary Session Interaction, but does not
39
- // establish that the foreground Agent is blocked.
25
+ const authorization_digest = digest(tool, input, context);
26
+ const requested = {
27
+ kind: "permission_requested",
28
+ permission_id: id,
29
+ tool: tool.slice(0, 256),
30
+ blocking: !context.agentID,
31
+ authorization_digest,
32
+ };
33
+ const existing = this.pending.get(id);
34
+ if (existing) {
35
+ if (existing.digest !== authorization_digest) {
36
+ this.emit(requested);
37
+ existing.finish();
38
+ }
39
+ return existing.answer;
40
+ }
41
+ let settle;
42
+ const answer = new Promise((resolve) => {
43
+ settle = resolve;
44
+ });
45
+ const abort = () => finish();
46
+ const finish = (option) => {
47
+ if (!this.pending.delete(id))
48
+ return;
49
+ signal.removeEventListener("abort", abort);
40
50
  this.emit({
41
- kind: "permission_requested",
51
+ kind: "permission_settled",
42
52
  permission_id: id,
43
- tool: tool.slice(0, 256),
44
- blocking: !options.agentID,
53
+ authorization_digest,
54
+ outcome: option ? "resolved" : "expired",
45
55
  });
46
- });
56
+ settle(option === "allow"
57
+ ? { behavior: "allow" }
58
+ : {
59
+ behavior: "deny",
60
+ message: option === "deny" ? "User denied this tool use." : "Tool approval expired.",
61
+ });
62
+ };
63
+ this.pending.set(id, { digest: authorization_digest, answer, finish });
64
+ signal.addEventListener("abort", abort, { once: true });
65
+ this.emit(requested);
66
+ return answer;
47
67
  };
48
68
  resolve(id, option) {
49
- const finish = this.pending.get(id);
50
- if (!finish || (option !== "allow" && option !== "deny"))
69
+ const pending = this.pending.get(id);
70
+ if (!pending || (option !== "allow" && option !== "deny"))
51
71
  return false;
52
- finish(option);
72
+ pending.finish(option);
53
73
  return true;
54
74
  }
75
+ has(id) {
76
+ return this.pending.has(id);
77
+ }
78
+ cancel(id) {
79
+ this.pending.get(id)?.finish();
80
+ }
55
81
  expire() {
56
- for (const finish of this.pending.values())
57
- finish();
82
+ for (const pending of this.pending.values())
83
+ pending.finish();
58
84
  }
59
85
  }
@@ -1,6 +1,8 @@
1
+ import { ReportQueue } from "../shared/report-queue.js";
1
2
  import { randomUUID } from "node:crypto";
2
- import { connectRuntime, CONTROL_VERSION, } from "../shared/control-socket.js";
3
+ import { connectRuntime, RpcError, CONTROL_VERSION, } from "../shared/control-socket.js";
3
4
  import { Host, ControlError } from "./host.js";
5
+ import { hostObservation } from "./facts.js";
4
6
  function object(value) {
5
7
  if (!value || typeof value !== "object" || Array.isArray(value))
6
8
  throw new ControlError("rejected", "invalid_request");
@@ -49,6 +51,7 @@ export function bootstrap(value) {
49
51
  export async function serve(config, factory) {
50
52
  const generation = randomUUID();
51
53
  let connected = false;
54
+ let generationOfConnection = 0;
52
55
  let sequence = 0;
53
56
  let connection;
54
57
  const reports = new Set();
@@ -57,27 +60,72 @@ export async function serve(config, factory) {
57
60
  runtimeId: config.runtime_id,
58
61
  clientSessionKey: undefined,
59
62
  };
63
+ const queue = new ReportQueue();
64
+ const acknowledged = new Map();
65
+ let pendingReady;
66
+ let submitted;
67
+ function deliver(params) {
68
+ const event = params.event;
69
+ const report = queue
70
+ .enqueue(async () => {
71
+ const receipt = object(await connection.request("host.event", params));
72
+ if (receipt.accepted !== true)
73
+ throw new RpcError(-32602, "Invalid Claude fact acknowledgement");
74
+ if (event.kind === "ready")
75
+ pendingReady = undefined;
76
+ if (event.kind === "permission_requested" && host.hasPermission(event.permission_id)) {
77
+ if (receipt.ended === true)
78
+ host.cancelPermission(event.permission_id);
79
+ else
80
+ acknowledged.set(event.permission_id, params);
81
+ }
82
+ })
83
+ .catch((error) => {
84
+ console.error("Claude host fact discarded", params.report_key, String(error));
85
+ if (event.kind === "permission_requested")
86
+ host.cancelPermission(event.permission_id);
87
+ });
88
+ reports.add(report);
89
+ void report.finally(() => reports.delete(report));
90
+ }
60
91
  const host = new Host(config, (event) => {
61
- sequence++;
62
- if (event.kind === "ready")
92
+ const params = hostObservation(generation, ++sequence, event);
93
+ if (event.kind === "started" && submitted?.id === event.input_id) {
94
+ Object.assign(params.event, { input: submitted.metadata });
95
+ submitted = undefined;
96
+ }
97
+ if (event.kind === "ready") {
63
98
  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);
99
+ pendingReady = {
100
+ report_key: params.report_key,
101
+ native_session_id: event.native_session_id,
102
+ };
103
+ }
104
+ if (event.kind === "permission_settled")
105
+ acknowledged.delete(event.permission_id);
106
+ if (params.report_key || event.kind === "closed" || event.kind === "unavailable") {
107
+ deliver(params);
108
+ }
109
+ else if (connected) {
110
+ const current = generationOfConnection;
111
+ void queue
112
+ .drained()
113
+ .then(() => {
114
+ if (connected && current === generationOfConnection)
115
+ return connection.request("host.event", params);
116
+ })
117
+ .catch(() => { });
118
+ }
74
119
  }, factory);
75
120
  const invoke = async (request) => {
76
121
  try {
77
122
  switch (request.method) {
78
- case "input":
79
- host.submit(string(request.input_id), string(request.text));
123
+ case "input": {
124
+ const input = { id: string(request.input_id), metadata: object(request.input) };
125
+ host.submit(input.id, string(request.text));
126
+ submitted = input;
80
127
  break;
128
+ }
81
129
  case "steer":
82
130
  host.steer(string(request.target_input_id), string(request.input_id), string(request.text));
83
131
  break;
@@ -112,6 +160,7 @@ export async function serve(config, factory) {
112
160
  result: {
113
161
  host_id: generation,
114
162
  ...host.status(),
163
+ pending_ready: pendingReady,
115
164
  launch: {
116
165
  cwd: config.cwd,
117
166
  config_dir: process.env.CLAUDE_CONFIG_DIR,
@@ -143,8 +192,11 @@ export async function serve(config, factory) {
143
192
  }, async () => {
144
193
  connected = true;
145
194
  host.controlRestored();
195
+ for (const params of acknowledged.values())
196
+ deliver(params);
146
197
  }, () => {
147
198
  connected = false;
199
+ generationOfConnection++;
148
200
  host.controlLost();
149
201
  }, true);
150
202
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pontia/claude-client",
3
- "version": "0.8.8",
3
+ "version": "0.8.9",
4
4
  "description": "Claude Code client for Pontia",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {