@anusornneal/chat-relay 1.2.2 → 1.3.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/README.md CHANGED
@@ -246,6 +246,7 @@ flowchart TD
246
246
  The decision boundary is deliberate:
247
247
 
248
248
  - **Chat decides semantic Learn use:** whether to prepare context, whether a correction/preference/workflow is durable enough to learn, and when a targeted raw `learn_get` is needed.
249
+ - **Reusable user corrections are active-learning signals by default:** when a user directly corrects a reusable mistake in workflow, tool usage, coding conventions, or response behavior, Chat should call `learn_put` in the same turn without waiting for an explicit "learn". Use global scope for cross-project behavior, project scope for project-specific behavior, and skip one-off situational details.
249
250
  - **Relay performs mechanical preparation only after `learn_prepare` is explicitly called:** account isolation, project routing from explicit `project-root:<projectKey>` memories or explicit `projectKey`, preferred-agent routing, bounded reads, relevance ranking, and compaction.
250
251
  - **Ordinary tools stay hot-path clean:** `ping_agent`, file tools, terminal tools, desktop tools, and other MCP calls do not automatically read, rank, inject, or write Learn.
251
252
  - Learned hints remain advisory and never override authorization, grants, allowed roots, destructive-tool policy, capability checks, safety, or the current user request.
@@ -9,9 +9,31 @@ function isoTime(value) {
9
9
  return new Date(Number.isFinite(number) ? number : Date.now()).toISOString();
10
10
  }
11
11
 
12
- function cleanReason(value) {
13
- const reason = String(value || "").trim();
14
- return reason ? reason.slice(0, 160) : null;
12
+ const SAFE_REASONS = new Set([
13
+ "socket_closed", "socket_error", "transport_pong_timeout", "transport_ping_failed",
14
+ "heartbeat_ack_timeout", "connection_generation_changed", "credential_revoked",
15
+ "credential_rejected", "protocol_incompatible", "restart_requested",
16
+ "upgrade_requested", "client_shutdown", "shutdown", "replaced", "SIGINT", "SIGTERM",
17
+ ]);
18
+
19
+ export function safeConnectionReason(value) {
20
+ if (typeof value !== "string") return null;
21
+ const reason = value.trim();
22
+ if (!reason) return null;
23
+ if (SAFE_REASONS.has(reason) || /^unexpected_response_[1-5][0-9]{2}$/.test(reason)) return reason;
24
+ const networkError = reason.match(/\b(ENOTFOUND|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE)\b/);
25
+ return networkError ? networkError[1] : "socket_error";
26
+ }
27
+
28
+ export function classifySocketDisconnect(code, reason, socketError = null) {
29
+ if (code === 4001 || reason === "credential_revoked" || reason === "credential_rejected") return "authorization";
30
+ if (code === 4002 || reason === "protocol_incompatible") return "protocol";
31
+ if (reason?.startsWith("unexpected_response_")) return "handshake";
32
+ if (["transport_pong_timeout", "heartbeat_ack_timeout"].includes(socketError)) return "timeout";
33
+ if (code === 1006) return "abnormal_transport";
34
+ if (code === 1012 || reason === "restart_requested" || reason === "upgrade_requested") return "restart";
35
+ if (code === 1000 || code === 1001) return "normal";
36
+ return "remote_close";
15
37
  }
16
38
 
17
39
  export function computeReconnectDelay(attempt, options = {}) {
@@ -39,8 +61,10 @@ export class AgentConnectionState {
39
61
  this.lastHeartbeatAt = null;
40
62
  this.lastCloseCode = null;
41
63
  this.lastDisconnectReason = null;
64
+ this.lastDisconnectCategory = null;
42
65
  this.lastConnectionDurationMs = null;
43
66
  this.lastSocketError = null;
67
+ this.socketErrorForConnection = null;
44
68
  this.serverConnectionGeneration = null;
45
69
  this.reconnectAttempt = 0;
46
70
  this.reconnectCount = 0;
@@ -58,6 +82,7 @@ export class AgentConnectionState {
58
82
  markConnected(now = Date.now()) {
59
83
  this.state = "connected";
60
84
  this.connectedAt = isoTime(now);
85
+ this.socketErrorForConnection = null;
61
86
  this.disconnectedAt = null;
62
87
  this.serverConnectionGeneration = null;
63
88
  this.reconnectAttempt = 0;
@@ -77,7 +102,8 @@ export class AgentConnectionState {
77
102
  this.lastDisconnectedAt = disconnectedAt;
78
103
  const closeCode = code === null || code === undefined ? NaN : Number(code);
79
104
  this.lastCloseCode = Number.isFinite(closeCode) ? closeCode : null;
80
- this.lastDisconnectReason = cleanReason(reason);
105
+ this.lastDisconnectReason = safeConnectionReason(reason);
106
+ this.lastDisconnectCategory = classifySocketDisconnect(this.lastCloseCode, this.lastDisconnectReason, this.socketErrorForConnection);
81
107
  this.lastConnectionDurationMs = Number.isFinite(connectedAtMs)
82
108
  ? Math.max(0, Math.trunc(Number(now) - connectedAtMs))
83
109
  : null;
@@ -86,7 +112,8 @@ export class AgentConnectionState {
86
112
  }
87
113
 
88
114
  markSocketError(reason) {
89
- this.lastSocketError = cleanReason(reason);
115
+ this.socketErrorForConnection = safeConnectionReason(reason);
116
+ this.lastSocketError = this.socketErrorForConnection;
90
117
  }
91
118
 
92
119
  markServerConnectionGeneration(value) {
@@ -122,7 +149,7 @@ export class AgentConnectionState {
122
149
  markReauthorization(reason = "credential_revoked", now = Date.now()) {
123
150
  this.state = "reauthorization-required";
124
151
  this.disconnectedAt = isoTime(now);
125
- this.lastDisconnectReason = cleanReason(reason);
152
+ this.lastDisconnectReason = safeConnectionReason(reason);
126
153
  this.nextReconnectAt = null;
127
154
  this.nextReconnectDelayMs = null;
128
155
  }
@@ -130,7 +157,7 @@ export class AgentConnectionState {
130
157
  markStopping(reason = "shutdown", now = Date.now()) {
131
158
  this.state = "stopping";
132
159
  this.disconnectedAt = isoTime(now);
133
- this.lastDisconnectReason = cleanReason(reason);
160
+ this.lastDisconnectReason = safeConnectionReason(reason);
134
161
  this.nextReconnectAt = null;
135
162
  this.nextReconnectDelayMs = null;
136
163
  }
@@ -146,6 +173,7 @@ export class AgentConnectionState {
146
173
  lastHeartbeatAt: this.lastHeartbeatAt,
147
174
  lastCloseCode: this.lastCloseCode,
148
175
  lastDisconnectReason: this.lastDisconnectReason,
176
+ lastDisconnectCategory: this.lastDisconnectCategory,
149
177
  lastConnectionDurationMs: this.lastConnectionDurationMs,
150
178
  lastSocketError: this.lastSocketError,
151
179
  serverConnectionGeneration: this.serverConnectionGeneration,
@@ -310,7 +310,35 @@ export class DesktopManager {
310
310
  return this.runControl(() => this.runner("mouse_click", { x, y, button, clicks }));
311
311
  }
312
312
 
313
- async keyboardInput(input = {}) {
313
+ async clickImageTarget(input = {}) {
314
+ const gate = this.gate();
315
+ if (gate) return gate;
316
+ const { imageWidth, imageHeight, desktopOriginX, desktopOriginY, desktopWidth, desktopHeight } = input;
317
+ const numbers = [imageWidth, imageHeight, desktopOriginX, desktopOriginY, desktopWidth, desktopHeight, input.x, input.y];
318
+ if (numbers.some((value) => !Number.isFinite(value)) ||
319
+ !numbers.every(Number.isInteger) ||
320
+ imageWidth <= 0 || imageHeight <= 0 || desktopWidth <= 0 || desktopHeight <= 0 ||
321
+ input.x < 0 || input.x >= imageWidth || input.y < 0 || input.y >= imageHeight) {
322
+ return { ok: false, error: "invalid_image_coordinates" };
323
+ }
324
+ const targetWidth = input.targetWidth ?? 1;
325
+ const targetHeight = input.targetHeight ?? 1;
326
+ if (![targetWidth, targetHeight].every(Number.isInteger) ||
327
+ targetWidth <= 0 || targetHeight <= 0 ||
328
+ input.x + targetWidth > imageWidth || input.y + targetHeight > imageHeight) {
329
+ return { ok: false, error: "invalid_target_bounds" };
330
+ }
331
+ const x = desktopOriginX + Math.floor((input.x + targetWidth / 2) * desktopWidth / imageWidth);
332
+ const y = desktopOriginY + Math.floor((input.y + targetHeight / 2) * desktopHeight / imageHeight);
333
+ const button = String(input.button || "left").toLowerCase();
334
+ const clicks = Number(input.clicks ?? 1);
335
+ if (!["left", "right", "middle"].includes(button)) return { ok: false, error: "invalid_button" };
336
+ if (clicks !== 1 && clicks !== 2) return { ok: false, error: "invalid_click_count" };
337
+ return this.runControl(async () => {
338
+ const result = await this.runner("mouse_click", { x, y, button, clicks });
339
+ return { ...result, target: { x, y, source: "image", verified: false } };
340
+ });
341
+ } async keyboardInput(input = {}) {
314
342
  const gate = this.gate();
315
343
  if (gate) return gate;
316
344
 
@@ -5,7 +5,7 @@ import { GitWorktreeManager } from "./git-worktree-manager.mjs";
5
5
  import { ProcessManager } from "./process-manager.mjs";
6
6
  import { TerminalManager } from "./terminal-manager.mjs";
7
7
  import { CapabilityScheduler } from "./capability-scheduler.mjs";
8
- import { AgentConnectionState } from "./connection-state.mjs";
8
+ import { AgentConnectionState, safeConnectionReason } from "./connection-state.mjs";
9
9
  import { buildAgentHello } from "./protocol.mjs";
10
10
  import {
11
11
  AgentLifecycle,
@@ -246,6 +246,8 @@ async function handlePayload(payload) {
246
246
  return desktop.listWindows(payload);
247
247
  case "desktop.window.focus":
248
248
  return desktop.focusWindow(payload);
249
+ case "desktop.mouse.click_image":
250
+ return desktop.clickImageTarget(payload);
249
251
  case "desktop.mouse.click":
250
252
  return desktop.mouseClick(payload);
251
253
  case "desktop.keyboard.input":
@@ -394,7 +396,8 @@ function scheduleReconnect(code, reason) {
394
396
  reconnects: connectionState.snapshot().reconnectCount,
395
397
  delayMs: delay,
396
398
  closeCode: code ?? null,
397
- reason: reason || "socket_closed",
399
+ reason: safeConnectionReason(reason) || "socket_closed",
400
+ category: connectionState.lastDisconnectCategory,
398
401
  });
399
402
  clearReconnectTimer();
400
403
  plainLog(`Reconnect scheduled in ${delay}ms`);
@@ -609,7 +612,7 @@ function connect() {
609
612
  activeSocket = null;
610
613
  stopHeartbeat();
611
614
  const reasonText = reason.toString();
612
- plainLog("Agent disconnected (" + code + ") " + reasonText);
615
+ plainLog("Agent disconnected (" + code + ") " + (safeConnectionReason(reasonText) || "socket_closed"));
613
616
  if (code === 4001 || reasonText === "credential_revoked") {
614
617
  requireReauthorization("credential_revoked");
615
618
  return;
@@ -618,13 +621,13 @@ function connect() {
618
621
  requireProtocolUpdate({ receivedProtocolVersion: agentHello.protocolVersion });
619
622
  return;
620
623
  }
621
- scheduleReconnect(code, reasonText || "socket_closed");
624
+ scheduleReconnect(code, safeConnectionReason(reasonText) || "socket_closed");
622
625
  });
623
626
 
624
627
  socket.on("error", (error) => {
625
628
  if (socket === activeSocket && !stopping && !reauthorizationRequired) {
626
629
  connectionState.markSocketError(error.message);
627
- plainError("WebSocket error:", error.message);
630
+ plainError("WebSocket error:", safeConnectionReason(error.message));
628
631
  }
629
632
  });
630
633
  }
@@ -247,6 +247,8 @@ export function humanizeToolCall(payload = {}) {
247
247
  return "List open windows";
248
248
  case "desktop.window.focus":
249
249
  return `Focus window · ${cleanText(payload.title ?? payload.windowId ?? payload.handle ?? "", 64)}`;
250
+ case "desktop.mouse.click_image":
251
+ return "Click screenshot target";
250
252
  case "desktop.mouse.click": {
251
253
  const button = cleanText(payload.button || "left", 12);
252
254
  return `${button[0]?.toUpperCase() || "L"}${button.slice(1)} click`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anusornneal/chat-relay",
3
- "version": "1.2.2",
3
+ "version": "1.3.0",
4
4
  "description": "Zero-checkout remote MCP agent for ChatGPT with terminal, filesystem, process, multi-user, and multi-agent support.",
5
5
  "type": "module",
6
6
  "bin": {