@pontia/claude-client 0.8.10 → 0.8.11

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.
@@ -1,20 +1,29 @@
1
1
  import { RpcError } from "./rpc-error.js";
2
2
  export { RpcError } from "./rpc-error.js";
3
3
  import { createConnection } from "node:net";
4
- import { isAbsolute, join } from "node:path";
4
+ import { isAbsolute } from "node:path";
5
5
  import { statSync } from "node:fs";
6
6
  export const CONTROL_VERSION = 8;
7
+ export const UNSUPPORTED_CONTROL_VERSION = -32012;
7
8
  export const MAX_CONTROL_FRAME_BYTES = 64 * 1024;
8
9
  // Match the former HTTP event body limit, including the RPC envelope.
9
10
  export const MAX_RPC_FRAME_BYTES = 2 * 1024 * 1024 + 1024;
10
11
  const REQUEST_TIMEOUT_MS = 5_000;
11
12
  export class AttachmentRejected extends Error {
12
13
  }
14
+ // Pi plugins, Claude hosts and ACP relays keep computing this path with their startup
15
+ // version across pontiad upgrades. Moving it in 9d550ec6 from $PONTIA_HOME/state/pi/rpc.sock
16
+ // left running agents retrying the old path, disconnected and impossible to close from Pontia.
17
+ // /tmp fits the ~104–108 byte Unix socket limit even with a long PONTIA_HOME.
18
+ // Changing this path requires project owner approval.
13
19
  export function controlSocketPath(pontiaHome) {
14
20
  if (!isAbsolute(pontiaHome) || pontiaHome.includes("\0"))
15
21
  throw new Error("Control home requires an absolute path without NUL");
16
22
  const home = statSync(pontiaHome, { bigint: true });
17
- return join(`/tmp/pontia-control-${home.uid}-${home.dev.toString(16)}-${home.ino.toString(16)}`, "rpc.sock");
23
+ return formatSocketPath(home.uid, home.dev, home.ino);
24
+ }
25
+ export function formatSocketPath(uid, dev, ino) {
26
+ return `/tmp/pontia-control-${uid}-${dev.toString(16)}-${ino.toString(16)}/rpc.sock`;
18
27
  }
19
28
  class RpcSocket {
20
29
  sequence = 0;
@@ -261,15 +270,25 @@ export async function connectRuntime(pontiaHome, onError, onRequest, onReconnect
261
270
  async request(method, params) {
262
271
  if (method === "event.report" || method === "host.event")
263
272
  await ready();
264
- else if (identity && !attached)
265
- throw new Error("Control connection is unavailable");
266
273
  if (reconnectRejected)
267
274
  throw reconnectRejected;
268
275
  if (stopped)
269
276
  throw new AttachmentRejected("Control connection closed");
277
+ if (identity && !attached)
278
+ throw new Error("Control connection is unavailable");
270
279
  if (!current)
271
280
  return Promise.reject(new Error("Control connection is unavailable"));
272
- return current.request(method, params);
281
+ try {
282
+ return await current.request(method, params);
283
+ }
284
+ catch (error) {
285
+ if (error instanceof RpcError && error.code === UNSUPPORTED_CONTROL_VERSION) {
286
+ reconnectRejected = new AttachmentRejected(error.message);
287
+ onError(error);
288
+ wakeRequests();
289
+ }
290
+ throw error;
291
+ }
273
292
  },
274
293
  registered(value) {
275
294
  identity = value;
@@ -0,0 +1,190 @@
1
+ function scope(update) {
2
+ switch (update.type) {
3
+ case "setMode":
4
+ return update.mode + " mode";
5
+ case "addDirectories":
6
+ return "access " + update.directories.join(", ");
7
+ case "removeDirectories":
8
+ return "remove access to " + update.directories.join(", ");
9
+ default: {
10
+ const rules = update.rules.map((rule) => rule.ruleContent ? rule.toolName + "(" + rule.ruleContent + ")" : rule.toolName);
11
+ return ((update.type === "addRules" && update.behavior === "allow"
12
+ ? ""
13
+ : update.type + " " + update.behavior + ": ") + rules.join(", "));
14
+ }
15
+ }
16
+ }
17
+ const positive = (key, label) => ({
18
+ key,
19
+ label,
20
+ intent: "positive",
21
+ });
22
+ const negative = (key, label) => ({
23
+ key,
24
+ label,
25
+ intent: "negative",
26
+ });
27
+ export function approval(tool, input, context) {
28
+ const options = [positive("allow", "Allow once")];
29
+ const results = new Map();
30
+ results.set("allow", {
31
+ behavior: "allow",
32
+ updatedInput: input,
33
+ decisionClassification: "user_temporary",
34
+ });
35
+ if (context.suggestions?.length && !context.suppressAlwaysAllowRule) {
36
+ options.push(positive("allow_always", "Always allow in this session: " + context.suggestions.map(scope).join("; ")));
37
+ results.set("allow_always", {
38
+ behavior: "allow",
39
+ updatedInput: input,
40
+ updatedPermissions: context.suggestions.map((update) => ({
41
+ ...update,
42
+ destination: "session",
43
+ })),
44
+ decisionClassification: "user_permanent",
45
+ });
46
+ }
47
+ options.push(negative("deny", "Deny"));
48
+ results.set("deny", {
49
+ behavior: "deny",
50
+ message: "User denied this tool use.",
51
+ decisionClassification: "user_reject",
52
+ });
53
+ const summary = tool === "Bash"
54
+ ? input.command
55
+ : ["Read", "Edit", "Write"].includes(tool)
56
+ ? input.file_path
57
+ : JSON.stringify(input);
58
+ return {
59
+ results,
60
+ card: {
61
+ title: context.title ?? "Allow " + (context.displayName ?? tool) + "?",
62
+ description: [context.description, context.decisionReason, context.blockedPath, summary]
63
+ .filter(Boolean)
64
+ .join("\n"),
65
+ options,
66
+ },
67
+ };
68
+ }
69
+ function object(value) {
70
+ return typeof value === "object" && value !== null && !Array.isArray(value);
71
+ }
72
+ function fields(fields, decline) {
73
+ const cards = fields.map((field, index) => ({
74
+ index,
75
+ title: field.title,
76
+ description: field.description,
77
+ options: [
78
+ ...field.choices.slice(0, 7).map((choice, j) => positive("option_" + j, choice.label)),
79
+ negative("decline", decline),
80
+ ],
81
+ }));
82
+ return {
83
+ cards,
84
+ answers: (picked) => Object.fromEntries(fields.map((field, i) => {
85
+ const index = cards[i].options.findIndex((o) => o.key === picked[i]);
86
+ return [field.name, field.choices[index].value];
87
+ })),
88
+ };
89
+ }
90
+ export function questions(input) {
91
+ const questions = input.questions;
92
+ const invalid = "Invalid question. Ask the user in plain text.";
93
+ if (!Array.isArray(questions) || !questions.length)
94
+ return invalid;
95
+ const parsed = [];
96
+ for (const [index, q] of questions.entries()) {
97
+ if (!object(q))
98
+ return invalid;
99
+ if (q.multiSelect === true)
100
+ return "Multi-select questions are not supported in this session. Ask single-choice questions, or ask the user in plain text.";
101
+ if (typeof q.question !== "string" ||
102
+ typeof q.header !== "string" ||
103
+ !Array.isArray(q.options) ||
104
+ !q.options.length)
105
+ return invalid;
106
+ const choices = [];
107
+ const descriptions = [];
108
+ for (const option of q.options) {
109
+ if (!object(option) ||
110
+ typeof option.label !== "string" ||
111
+ typeof option.description !== "string")
112
+ return invalid;
113
+ choices.push({ label: option.label, value: option.label });
114
+ descriptions.push(option.label + " — " + option.description);
115
+ }
116
+ const prefix = questions.length > 1 ? "(" + (index + 1) + "/" + questions.length + ") " : "";
117
+ parsed.push({
118
+ name: q.question,
119
+ title: prefix + q.header + ": " + q.question,
120
+ description: descriptions.join("\n"),
121
+ choices,
122
+ });
123
+ }
124
+ return fields(parsed, "None of these, I'll reply in chat");
125
+ }
126
+ function fieldChoices(schema) {
127
+ if (schema.type === "boolean")
128
+ return [
129
+ { label: "Yes", value: true },
130
+ { label: "No", value: false },
131
+ ];
132
+ if (schema.type !== "string")
133
+ return;
134
+ if (Array.isArray(schema.enum) && schema.enum.every((v) => typeof v === "string")) {
135
+ const names = schema.enumNames;
136
+ return schema.enum.map((value, i) => ({
137
+ value,
138
+ label: Array.isArray(names) && typeof names[i] === "string" ? names[i] : value,
139
+ }));
140
+ }
141
+ if (Array.isArray(schema.oneOf)) {
142
+ const choices = [];
143
+ for (const variant of schema.oneOf) {
144
+ if (!object(variant) || typeof variant.const !== "string")
145
+ return;
146
+ choices.push({
147
+ value: variant.const,
148
+ label: typeof variant.title === "string" ? variant.title : variant.const,
149
+ });
150
+ }
151
+ return choices;
152
+ }
153
+ }
154
+ export function elicitation(request) {
155
+ if (request.mode === "url")
156
+ return "URL confirmation requires a browser. Ask the user in plain text.";
157
+ const title = request.title ?? request.displayName ?? request.serverName;
158
+ const schema = request.requestedSchema;
159
+ const parsed = [];
160
+ for (const [name, field] of Object.entries(schema?.properties ?? {})) {
161
+ const choices = object(field) && fieldChoices(field);
162
+ if (!choices || !choices.length) {
163
+ if (object(field) &&
164
+ field.type === "string" &&
165
+ !(Array.isArray(schema?.required) && schema.required.includes(name)))
166
+ continue;
167
+ return "This form requires an unsupported field. Ask the user in plain text.";
168
+ }
169
+ parsed.push({
170
+ name,
171
+ title,
172
+ description: [request.message, field.title ?? name, field.description]
173
+ .filter(Boolean)
174
+ .join("\n"),
175
+ choices,
176
+ });
177
+ }
178
+ if (parsed.length)
179
+ return fields(parsed, "Decline");
180
+ return {
181
+ cards: [
182
+ {
183
+ title,
184
+ description: request.message,
185
+ options: [positive("accept", "Accept"), negative("decline", "Decline")],
186
+ },
187
+ ],
188
+ answers: () => ({}),
189
+ };
190
+ }
package/dist/src/facts.js CHANGED
@@ -1,9 +1,9 @@
1
1
  function reportKey(host, sequence, event) {
2
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`;
3
+ case "interaction_requested":
4
+ return `claude:${host}:${event.interaction_key}`;
5
+ case "interaction_settled":
6
+ return `claude:${host}:${event.interaction_key}:settled`;
7
7
  case "started":
8
8
  return `claude:${host}:${event.input_id}:start`;
9
9
  case "finished":
@@ -20,8 +20,8 @@ export function hostObservation(host, sequence, event) {
20
20
  host_id: host,
21
21
  sequence,
22
22
  report_key: reportKey(host, sequence, event),
23
- ...(event.kind === "permission_settled"
24
- ? { registration_key: `claude:${host}:${event.permission_id}` }
23
+ ...(event.kind === "interaction_settled"
24
+ ? { registration_key: `claude:${host}:${event.interaction_key}` }
25
25
  : {}),
26
26
  event,
27
27
  };
@@ -51,7 +51,8 @@ function outcome(message) {
51
51
  return "failed";
52
52
  if (((message.subtype === "error_during_execution" && message.is_error) ||
53
53
  (message.subtype === "success" && !message.is_error)) &&
54
- ((message.stop_reason === null && message.terminal_reason === "aborted_streaming") ||
54
+ (((message.stop_reason === null || message.stop_reason === "tool_use") &&
55
+ message.terminal_reason === "aborted_streaming") ||
55
56
  (message.stop_reason === "tool_use" && message.terminal_reason === "aborted_tools")))
56
57
  return "interrupted";
57
58
  return undefined;
package/dist/src/host.js CHANGED
@@ -1,7 +1,7 @@
1
- import { query } from "@anthropic-ai/claude-agent-sdk";
1
+ import { query, } from "@anthropic-ai/claude-agent-sdk";
2
2
  import { Compaction } from "./compaction.js";
3
3
  import { Input } from "./input.js";
4
- import { Permissions } from "./permissions.js";
4
+ import { Interactions } from "./interactions.js";
5
5
  import { FactError, InputFacts } from "./facts.js";
6
6
  export class ControlError extends Error {
7
7
  code;
@@ -18,15 +18,18 @@ export class Host {
18
18
  createQuery;
19
19
  input = new Input();
20
20
  compaction;
21
- permissions;
21
+ interactions;
22
22
  execution;
23
23
  reader;
24
24
  current;
25
25
  native;
26
26
  unavailable;
27
27
  retrying = false;
28
- usagePending = false;
29
- usageReading = false;
28
+ usageRevision = 0;
29
+ contextModel;
30
+ usageMessageId;
31
+ streamUsage;
32
+ contextSummary;
30
33
  controlConnected = true;
31
34
  closing = false;
32
35
  closed = false;
@@ -35,7 +38,7 @@ export class Host {
35
38
  this.options = options;
36
39
  this.emit = emit;
37
40
  this.createQuery = createQuery;
38
- this.permissions = new Permissions(emit);
41
+ this.interactions = new Interactions(emit);
39
42
  this.compaction = new Compaction(emit);
40
43
  }
41
44
  status() {
@@ -96,7 +99,7 @@ export class Host {
96
99
  settingSources: ["user", "project", "local"],
97
100
  settings: { env: { PONTIA_SESSION_ID: this.options.session_id } },
98
101
  disallowedTools: [
99
- "AskUserQuestion",
102
+ ...(policy?.yolo ? ["AskUserQuestion"] : []),
100
103
  ...(policy?.disabled_tools ?? []),
101
104
  ...(policy?.disable_mcp ? ["mcp__*"] : []),
102
105
  ],
@@ -105,9 +108,15 @@ export class Host {
105
108
  return Promise.resolve({ behavior: "deny", message: "Tool approval is unavailable." });
106
109
  if (policy?.yolo)
107
110
  return Promise.resolve({ behavior: "allow", updatedInput: input });
108
- return this.permissions.request(tool, input, context);
111
+ return this.interactions.request(tool, input, context);
112
+ },
113
+ onElicitation: (request, context) => {
114
+ if (policy?.yolo)
115
+ return Promise.resolve({ action: "decline" });
116
+ if (this.closed || this.closing || this.unavailable)
117
+ return Promise.resolve({ action: "cancel" });
118
+ return this.interactions.elicit(request, context);
109
119
  },
110
- onElicitation: async () => ({ action: "decline" }),
111
120
  // Raw stderr may include credentials or tool arguments. It is not a control fact.
112
121
  stderr: () => { },
113
122
  };
@@ -176,21 +185,21 @@ export class Host {
176
185
  }
177
186
  // The result, not this acknowledgement, decides whether interruption won.
178
187
  }
179
- hasPermission(id) {
180
- return this.permissions.has(id);
188
+ hasInteraction(id) {
189
+ return this.interactions.has(id);
181
190
  }
182
- cancelPermission(id) {
183
- this.permissions.cancel(id);
191
+ cancelInteraction(id) {
192
+ this.interactions.cancel(id);
184
193
  }
185
- resolvePermission(id, option) {
186
- if (!this.acceptsControl() || !this.permissions.resolve(id, option))
194
+ resolveInteraction(id, option) {
195
+ if (!this.acceptsControl() || !this.interactions.resolve(id, option))
187
196
  throw new ControlError("rejected", "permission_expired_or_invalid");
188
197
  }
189
198
  async close() {
190
199
  if (this.closed)
191
200
  return;
192
201
  this.closing = true;
193
- this.permissions.expire();
202
+ this.interactions.expire();
194
203
  if (this.execution) {
195
204
  try {
196
205
  this.execution.close();
@@ -222,7 +231,7 @@ export class Host {
222
231
  return;
223
232
  this.unavailable = reason;
224
233
  this.compaction.closed(false);
225
- this.permissions.expire();
234
+ this.interactions.expire();
226
235
  this.emit({ kind: "unavailable", reason, ...(result ? { result } : {}) });
227
236
  }
228
237
  async consume(execution) {
@@ -230,14 +239,6 @@ export class Host {
230
239
  for await (const message of execution) {
231
240
  try {
232
241
  this.message(message);
233
- if (!this.unavailable &&
234
- message.session_id === this.native &&
235
- !("parent_tool_use_id" in message && message.parent_tool_use_id) &&
236
- (message.type === "assistant" ||
237
- message.type === "result" ||
238
- (message.type === "system" &&
239
- (message.subtype === "init" || message.subtype === "compact_boundary"))))
240
- void this.refreshContextUsage(execution);
241
242
  }
242
243
  catch (error) {
243
244
  this.fail(error instanceof Error ? error.message : "sdk_message_invalid", error instanceof FactError ? error.result : undefined);
@@ -256,40 +257,80 @@ export class Host {
256
257
  this.fail("sdk_reader_failed");
257
258
  }
258
259
  }
259
- async refreshContextUsage(execution) {
260
- this.usagePending = true;
261
- if (this.usageReading)
262
- return;
263
- this.usageReading = true;
260
+ async reportContextUsage(usage) {
261
+ const revision = ++this.usageRevision;
264
262
  try {
265
- while (this.usagePending && !this.closing && !this.unavailable) {
266
- this.usagePending = false;
267
- const usage = await execution.getContextUsage({ detail: "summary" });
268
- if (this.closing || this.unavailable)
269
- return;
270
- const used = usage.totalTokens;
271
- const max = usage.rawMaxTokens;
272
- if (!Number.isSafeInteger(used) || used < 0 || !Number.isSafeInteger(max) || max <= 0)
273
- continue;
274
- this.emit({
275
- kind: "context_usage",
276
- context_usage: {
277
- used_tokens: used,
278
- max_tokens: max,
279
- remaining_tokens: Math.max(0, max - used),
280
- usage_ratio: Math.min(1, used / max),
281
- confidence: "estimated",
282
- },
283
- });
263
+ // /context measures against the resolved compaction window, including policy overrides.
264
+ if (!usage || !this.contextSummary)
265
+ this.contextSummary = this.execution.getContextUsage({ detail: "summary" });
266
+ const { rawMaxTokens: max, totalTokens } = await this.contextSummary;
267
+ if (revision !== this.usageRevision || this.closing || this.unavailable)
268
+ return;
269
+ const cache = (usage?.cache_creation_input_tokens ?? 0) + (usage?.cache_read_input_tokens ?? 0);
270
+ const used = usage ? usage.input_tokens + cache : totalTokens;
271
+ if (!Number.isSafeInteger(max) || max <= 0) {
272
+ this.contextSummary = undefined;
273
+ return;
284
274
  }
275
+ if (!Number.isSafeInteger(used) || used < 0)
276
+ return;
277
+ this.emit({
278
+ kind: "context_usage",
279
+ context_usage: {
280
+ used_tokens: used,
281
+ max_tokens: max,
282
+ remaining_tokens: Math.max(0, max - used),
283
+ usage_ratio: Math.min(1, used / max),
284
+ ...(usage
285
+ ? {
286
+ confidence: "exact",
287
+ input_tokens: usage.input_tokens,
288
+ output_tokens: usage.output_tokens,
289
+ cache_tokens: cache,
290
+ }
291
+ : { confidence: "estimated" }),
292
+ },
293
+ });
285
294
  }
286
295
  catch {
287
- // Usage observation must not interrupt the task or expose SDK diagnostics.
296
+ if (revision !== this.usageRevision)
297
+ return;
298
+ this.contextSummary = undefined;
288
299
  if (!this.closing)
289
300
  console.error("Claude context usage query failed");
290
301
  }
291
- finally {
292
- this.usageReading = false;
302
+ }
303
+ observeReply(message) {
304
+ if (message.parent_tool_use_id)
305
+ return;
306
+ if (message.type === "assistant") {
307
+ if (message.agent_id ||
308
+ message.error ||
309
+ message.message.model === "<synthetic>" ||
310
+ message.message.id === this.usageMessageId ||
311
+ !message.message.usage)
312
+ return;
313
+ this.usageMessageId = message.message.id;
314
+ void this.reportContextUsage(message.message.usage);
315
+ return;
316
+ }
317
+ const event = message.event;
318
+ if (event.type === "message_start") {
319
+ this.usageMessageId = event.message.id;
320
+ this.streamUsage = event.message.usage;
321
+ }
322
+ if (event.type === "message_delta" && this.streamUsage) {
323
+ // Streamed assistant envelopes carry the initial counts. The delta finalizes this request.
324
+ const initial = this.streamUsage;
325
+ this.streamUsage = undefined;
326
+ const final = event.usage;
327
+ void this.reportContextUsage({
328
+ ...initial,
329
+ input_tokens: final.input_tokens ?? initial.input_tokens,
330
+ cache_creation_input_tokens: final.cache_creation_input_tokens ?? initial.cache_creation_input_tokens,
331
+ cache_read_input_tokens: final.cache_read_input_tokens ?? initial.cache_read_input_tokens,
332
+ output_tokens: final.output_tokens ?? initial.output_tokens,
333
+ });
293
334
  }
294
335
  }
295
336
  message(message) {
@@ -305,6 +346,10 @@ export class Host {
305
346
  this.emit({ kind: "ready", native_session_id: this.native });
306
347
  }
307
348
  this.emit({ kind: "model", model: message.model });
349
+ if (this.contextModel !== message.model) {
350
+ this.contextModel = message.model;
351
+ void this.reportContextUsage();
352
+ }
308
353
  return;
309
354
  }
310
355
  if (message.type === "system" && message.subtype === "api_retry") {
@@ -324,6 +369,11 @@ export class Host {
324
369
  if (!this.native || message.session_id !== this.native)
325
370
  throw new Error("native_identity_mismatch");
326
371
  this.compaction.accept(message);
372
+ if (message.subtype === "compact_boundary" &&
373
+ !("parent_tool_use_id" in message && message.parent_tool_use_id)) {
374
+ this.streamUsage = undefined;
375
+ void this.reportContextUsage();
376
+ }
327
377
  return;
328
378
  }
329
379
  if (["stream_event", "assistant", "result", "user"].includes(message.type)) {
@@ -333,8 +383,11 @@ export class Host {
333
383
  this.retrying = false;
334
384
  this.emit({ kind: "retry", reason: null });
335
385
  }
336
- if (!this.compaction.accept(message))
337
- this.current?.accept(message);
386
+ if (this.compaction.accept(message))
387
+ return;
388
+ this.current?.accept(message);
389
+ if (message.type === "assistant" || message.type === "stream_event")
390
+ this.observeReply(message);
338
391
  }
339
392
  }
340
393
  }
@@ -0,0 +1,153 @@
1
+ import { createHash } from "node:crypto";
2
+ import { approval, questions, elicitation } from "./choices.js";
3
+ // Object member order is immaterial. Array order, tool arguments and SDK permission
4
+ // context are part of the authorization. The signal and correlation ID are transport state.
5
+ function digest(tool, input, context) {
6
+ const content = JSON.stringify({ tool, input, context }, (_key, value) => {
7
+ if (typeof value !== "object" || value === null || Array.isArray(value))
8
+ return value;
9
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
10
+ });
11
+ return createHash("sha256").update(content).digest("hex");
12
+ }
13
+ function shorten(value, limit) {
14
+ const characters = Array.from(value);
15
+ return characters.length <= limit ? value : characters.slice(0, limit - 1).join("") + "…";
16
+ }
17
+ export class Interactions {
18
+ emit;
19
+ pending = new Map();
20
+ groups = new Map();
21
+ constructor(emit) {
22
+ this.emit = emit;
23
+ }
24
+ wait(id, digest, signal, blocking, cards) {
25
+ if (signal.aborted)
26
+ return Promise.resolve(undefined);
27
+ const reports = cards.map((card) => {
28
+ const key = card.index === undefined ? id : id + ":" + card.index;
29
+ return {
30
+ kind: "interaction_requested",
31
+ interaction_key: key,
32
+ blocking,
33
+ authorization_digest: key === id
34
+ ? digest
35
+ : createHash("sha256")
36
+ .update(digest + ":" + key)
37
+ .digest("hex"),
38
+ title: shorten(card.title, 256),
39
+ description: shorten(card.description, 4000),
40
+ options: card.options.map((o) => ({ ...o, label: shorten(o.label, 200) })),
41
+ };
42
+ });
43
+ const existing = this.groups.get(id);
44
+ if (existing) {
45
+ if (existing.digest !== digest) {
46
+ for (const report of reports)
47
+ if (this.pending.has(report.interaction_key))
48
+ this.emit(report);
49
+ existing.expire();
50
+ }
51
+ return existing.answer;
52
+ }
53
+ const answers = [];
54
+ const keys = new Set();
55
+ let complete;
56
+ const answer = new Promise((resolve) => {
57
+ complete = resolve;
58
+ });
59
+ const expire = () => finishGroup(undefined);
60
+ const finishGroup = (result) => {
61
+ for (const key of keys)
62
+ this.pending.get(key).expire();
63
+ signal.removeEventListener("abort", expire);
64
+ this.groups.delete(id);
65
+ complete(result);
66
+ };
67
+ this.groups.set(id, { digest, answer, expire });
68
+ signal.addEventListener("abort", expire, { once: true });
69
+ for (const [index, report] of reports.entries()) {
70
+ const key = report.interaction_key;
71
+ keys.add(key);
72
+ const settle = (outcome) => {
73
+ keys.delete(key);
74
+ this.pending.delete(key);
75
+ this.emit({
76
+ kind: "interaction_settled",
77
+ interaction_key: key,
78
+ authorization_digest: report.authorization_digest,
79
+ outcome,
80
+ });
81
+ };
82
+ this.pending.set(key, {
83
+ options: report.options,
84
+ expire: () => settle("expired"),
85
+ finish: (option) => {
86
+ if (option === undefined)
87
+ return expire();
88
+ settle("resolved");
89
+ if (option === "decline")
90
+ return finishGroup(option);
91
+ answers[index] = option;
92
+ if (!keys.size)
93
+ finishGroup(answers);
94
+ },
95
+ });
96
+ this.emit(report);
97
+ }
98
+ return answer;
99
+ }
100
+ request = async (tool, input, { signal, requestId, ...context }) => {
101
+ const hash = digest(tool, input, context);
102
+ if (tool === "AskUserQuestion") {
103
+ const parsed = questions(input);
104
+ if (typeof parsed === "string")
105
+ return { behavior: "deny", message: parsed };
106
+ const picked = await this.wait(requestId, hash, signal, !context.agentID, parsed.cards);
107
+ if (!Array.isArray(picked))
108
+ return {
109
+ behavior: "deny",
110
+ message: picked === "decline"
111
+ ? "The user chose not to pick an option and will reply in chat."
112
+ : "Question expired.",
113
+ };
114
+ return {
115
+ behavior: "allow",
116
+ updatedInput: { questions: input.questions, answers: parsed.answers(picked) },
117
+ };
118
+ }
119
+ const { card, results } = approval(tool, input, context);
120
+ const picked = await this.wait(requestId, hash, signal, !context.agentID, [card]);
121
+ return Array.isArray(picked)
122
+ ? results.get(picked[0])
123
+ : { behavior: "deny", message: "Tool approval expired." };
124
+ };
125
+ elicit = async (request, { signal, requestId }) => {
126
+ const parsed = elicitation(request);
127
+ if (typeof parsed === "string") {
128
+ console.error("Claude MCP elicitation declined:", parsed);
129
+ return { action: "decline" };
130
+ }
131
+ const picked = await this.wait("elicitation:" + requestId, digest("elicitation", request, {}), signal, true, parsed.cards);
132
+ if (!Array.isArray(picked))
133
+ return { action: picked === "decline" ? "decline" : "cancel" };
134
+ return { action: "accept", content: parsed.answers(picked) };
135
+ };
136
+ resolve(id, option) {
137
+ const pending = this.pending.get(id);
138
+ if (!pending?.options.some((o) => o.key === option))
139
+ return false;
140
+ pending.finish(option);
141
+ return true;
142
+ }
143
+ has(id) {
144
+ return this.pending.has(id);
145
+ }
146
+ cancel(id) {
147
+ this.pending.get(id)?.finish();
148
+ }
149
+ expire() {
150
+ for (const group of this.groups.values())
151
+ group.expire();
152
+ }
153
+ }
@@ -73,17 +73,17 @@ export async function serve(config, factory) {
73
73
  throw new RpcError(-32602, "Invalid Claude fact acknowledgement");
74
74
  if (event.kind === "ready")
75
75
  pendingReady = undefined;
76
- if (event.kind === "permission_requested" && host.hasPermission(event.permission_id)) {
76
+ if (event.kind === "interaction_requested" && host.hasInteraction(event.interaction_key)) {
77
77
  if (receipt.ended === true)
78
- host.cancelPermission(event.permission_id);
78
+ host.cancelInteraction(event.interaction_key);
79
79
  else
80
- acknowledged.set(event.permission_id, params);
80
+ acknowledged.set(event.interaction_key, params);
81
81
  }
82
82
  })
83
83
  .catch((error) => {
84
84
  console.error("Claude host fact discarded", params.report_key, String(error));
85
- if (event.kind === "permission_requested")
86
- host.cancelPermission(event.permission_id);
85
+ if (event.kind === "interaction_requested")
86
+ host.cancelInteraction(event.interaction_key);
87
87
  });
88
88
  reports.add(report);
89
89
  void report.finally(() => reports.delete(report));
@@ -101,8 +101,8 @@ export async function serve(config, factory) {
101
101
  native_session_id: event.native_session_id,
102
102
  };
103
103
  }
104
- if (event.kind === "permission_settled")
105
- acknowledged.delete(event.permission_id);
104
+ if (event.kind === "interaction_settled")
105
+ acknowledged.delete(event.interaction_key);
106
106
  if (params.report_key || event.kind === "closed" || event.kind === "unavailable") {
107
107
  deliver(params);
108
108
  }
@@ -135,8 +135,8 @@ export async function serve(config, factory) {
135
135
  case "interrupt":
136
136
  await host.interrupt(string(request.input_id));
137
137
  break;
138
- case "permission":
139
- host.resolvePermission(string(request.permission_id), string(request.option));
138
+ case "interaction":
139
+ host.resolveInteraction(string(request.interaction_key), string(request.option));
140
140
  break;
141
141
  case "is_idle":
142
142
  return { status: "accepted", idle: host.isIdle() };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pontia/claude-client",
3
- "version": "0.8.10",
3
+ "version": "0.8.11",
4
4
  "description": "Claude Code client for Pontia",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -1,85 +0,0 @@
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
- }
12
- export class Permissions {
13
- emit;
14
- pending = new Map();
15
- constructor(emit) {
16
- this.emit = emit;
17
- }
18
- request = (tool, input, { signal, requestId: id, ...context }) => {
19
- if (tool === "AskUserQuestion" || signal.aborted) {
20
- return Promise.resolve({
21
- behavior: "deny",
22
- message: "This interaction is unsupported or expired.",
23
- });
24
- }
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);
50
- this.emit({
51
- kind: "permission_settled",
52
- permission_id: id,
53
- authorization_digest,
54
- outcome: option ? "resolved" : "expired",
55
- });
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;
67
- };
68
- resolve(id, option) {
69
- const pending = this.pending.get(id);
70
- if (!pending || (option !== "allow" && option !== "deny"))
71
- return false;
72
- pending.finish(option);
73
- return true;
74
- }
75
- has(id) {
76
- return this.pending.has(id);
77
- }
78
- cancel(id) {
79
- this.pending.get(id)?.finish();
80
- }
81
- expire() {
82
- for (const pending of this.pending.values())
83
- pending.finish();
84
- }
85
- }