@anusornneal/chat-relay 1.2.1 → 1.2.3

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
@@ -179,7 +179,7 @@ $env:CHAT_RELAY_SOAK_ITERATIONS=100000; npm run test:soak
179
179
 
180
180
  ## Administration
181
181
 
182
- Administration is separate from the public MCP interface. The admin tooling manages users, agents, grants, lifecycle, quotas, audit data, and operational cleanup.
182
+ Administration is separate from the public MCP interface. The admin tooling manages users, agents, grants, lifecycle, audit data, and operational cleanup.
183
183
 
184
184
  Operator commands are available through:
185
185
 
@@ -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,
@@ -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,
@@ -394,7 +394,8 @@ function scheduleReconnect(code, reason) {
394
394
  reconnects: connectionState.snapshot().reconnectCount,
395
395
  delayMs: delay,
396
396
  closeCode: code ?? null,
397
- reason: reason || "socket_closed",
397
+ reason: safeConnectionReason(reason) || "socket_closed",
398
+ category: connectionState.lastDisconnectCategory,
398
399
  });
399
400
  clearReconnectTimer();
400
401
  plainLog(`Reconnect scheduled in ${delay}ms`);
@@ -490,7 +491,12 @@ function connect() {
490
491
  return;
491
492
  }
492
493
  if (message?.control === "learn_activity") {
493
- emitUi("learn", { change: message.change && typeof message.change === "object" ? message.change : {} });
494
+ const activity = message.activity && typeof message.activity === "object" ? message.activity : null;
495
+ const change = message.change && typeof message.change === "object" ? message.change : null;
496
+ emitUi("learn", {
497
+ ...(activity ? { activity } : {}),
498
+ ...(change ? { change } : {}),
499
+ });
494
500
  return;
495
501
  }
496
502
  if (message?.control === "credential_revoked") {
@@ -509,7 +515,8 @@ function connect() {
509
515
  ? String(message.payload.action ?? "unknown")
510
516
  : "unknown";
511
517
  const callSummary = humanizeToolCall(message.payload);
512
- emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary });
518
+ const requestBytes = Buffer.byteLength(JSON.stringify(message), "utf8");
519
+ emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, requestBytes });
513
520
  let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
514
521
  let handlerDurationMs = 0;
515
522
  try {
@@ -536,19 +543,22 @@ function connect() {
536
543
  ok: !(result && typeof result === "object" && result.ok === false),
537
544
  });
538
545
  if (recentCalls.length > 100) recentCalls.shift();
546
+ const responseMeta = {
547
+ agentQueueWaitMs: scheduleMeta.queueWaitMs,
548
+ agentHandlerMs: handlerDurationMs,
549
+ lane: scheduleMeta.lane,
550
+ };
551
+ const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, result, responseMeta), "utf8");
539
552
  emitUi("tool:end", {
540
553
  requestId: message.requestId,
541
554
  action,
542
555
  summary: callSummary,
543
556
  ok: !(result && typeof result === "object" && result.ok === false),
544
557
  durationMs: Date.now() - startedAt,
558
+ responseBytes,
545
559
  ...(result && typeof result === "object" && result.ok === false && result.error ? { error: String(result.error) } : {}),
546
560
  });
547
- sendSocketResponse(socket, message.requestId, result, {
548
- agentQueueWaitMs: scheduleMeta.queueWaitMs,
549
- agentHandlerMs: handlerDurationMs,
550
- lane: scheduleMeta.lane,
551
- });
561
+ sendSocketResponse(socket, message.requestId, result, responseMeta);
552
562
  } catch (error) {
553
563
  recentCalls.push({
554
564
  at: new Date().toISOString(),
@@ -562,18 +572,21 @@ function connect() {
562
572
  error: error instanceof Error ? error.message : "agent_error",
563
573
  });
564
574
  if (recentCalls.length > 100) recentCalls.shift();
575
+ const errorPayload = {
576
+ ok: false,
577
+ error: error instanceof Error ? error.message : "agent_error",
578
+ };
579
+ const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, errorPayload), "utf8");
565
580
  emitUi("tool:end", {
566
581
  requestId: message.requestId,
567
582
  action,
568
583
  summary: callSummary,
569
584
  ok: false,
570
585
  durationMs: Date.now() - startedAt,
571
- error: error instanceof Error ? error.message : "agent_error",
572
- });
573
- sendSocketResponse(socket, message.requestId, {
574
- ok: false,
575
- error: error instanceof Error ? error.message : "agent_error",
586
+ responseBytes,
587
+ error: errorPayload.error,
576
588
  });
589
+ sendSocketResponse(socket, message.requestId, errorPayload);
577
590
  }
578
591
  });
579
592
 
@@ -597,7 +610,7 @@ function connect() {
597
610
  activeSocket = null;
598
611
  stopHeartbeat();
599
612
  const reasonText = reason.toString();
600
- plainLog("Agent disconnected (" + code + ") " + reasonText);
613
+ plainLog("Agent disconnected (" + code + ") " + (safeConnectionReason(reasonText) || "socket_closed"));
601
614
  if (code === 4001 || reasonText === "credential_revoked") {
602
615
  requireReauthorization("credential_revoked");
603
616
  return;
@@ -606,13 +619,13 @@ function connect() {
606
619
  requireProtocolUpdate({ receivedProtocolVersion: agentHello.protocolVersion });
607
620
  return;
608
621
  }
609
- scheduleReconnect(code, reasonText || "socket_closed");
622
+ scheduleReconnect(code, safeConnectionReason(reasonText) || "socket_closed");
610
623
  });
611
624
 
612
625
  socket.on("error", (error) => {
613
626
  if (socket === activeSocket && !stopping && !reauthorizationRequired) {
614
627
  connectionState.markSocketError(error.message);
615
- plainError("WebSocket error:", error.message);
628
+ plainError("WebSocket error:", safeConnectionReason(error.message));
616
629
  }
617
630
  });
618
631
  }
package/cli/tui.mjs CHANGED
@@ -191,6 +191,13 @@ function formatDuration(ms, status) {
191
191
  return (value / 1000).toFixed(value < 10000 ? 1 : 0) + "s";
192
192
  }
193
193
 
194
+ export function formatBytes(bytes) {
195
+ const value = Math.max(0, Number(bytes) || 0);
196
+ if (value < 1024) return Math.round(value) + " B";
197
+ if (value < 1024 * 1024) return (value / 1024).toFixed(value < 10 * 1024 ? 1 : 0) + " KB";
198
+ return (value / (1024 * 1024)).toFixed(value < 10 * 1024 * 1024 ? 1 : 0) + " MB";
199
+ }
200
+
194
201
  function clock(value) {
195
202
  const date = value ? new Date(value) : new Date();
196
203
  if (Number.isNaN(date.getTime())) return "--:--:--";
@@ -239,7 +246,11 @@ export function formatTransactionRows(item, width = 110, { color = false } = {})
239
246
  const prefixWidth = terminalCellWidth(prefix);
240
247
  const continuationPrefix = " ".repeat(prefixWidth);
241
248
  const duration = formatDuration(item.durationMs, item.status);
242
- const suffix = " " + duration.padStart(8);
249
+ const transfer = [
250
+ Number.isFinite(Number(item.requestBytes)) ? "↑ " + formatBytes(item.requestBytes) : null,
251
+ Number.isFinite(Number(item.responseBytes)) ? "↓ " + formatBytes(item.responseBytes) : null,
252
+ ].filter(Boolean).join(" ");
253
+ const suffix = " " + (transfer ? transfer + " " : "") + duration.padStart(8);
243
254
  const summaryWidth = Math.max(4, usable - prefixWidth - terminalCellWidth(suffix));
244
255
  const summaryLines = wrapText(item.summary || item.action || "Tool call", summaryWidth, 3);
245
256
 
@@ -464,6 +475,7 @@ export class RemoteTui {
464
475
  summary: message.summary || humanizeToolCall({ action: message.action }),
465
476
  status: "running",
466
477
  ok: null,
478
+ requestBytes: Number.isFinite(Number(message.requestBytes)) ? Number(message.requestBytes) : undefined,
467
479
  });
468
480
  } else if (message.event === "tool:end") {
469
481
  const item = [...this.transactions].reverse().find((entry) => entry.requestId === message.requestId);
@@ -471,26 +483,69 @@ export class RemoteTui {
471
483
  item.status = "done";
472
484
  item.ok = message.ok !== false;
473
485
  item.durationMs = message.durationMs;
486
+ if (Number.isFinite(Number(message.responseBytes))) item.responseBytes = Number(message.responseBytes);
474
487
  if (message.error && message.ok === false) item.summary += ` · ${truncate(message.error, 48)}`;
475
488
  }
476
489
  } else if (message.event === "learn") {
477
- const change = message.change && typeof message.change === "object" ? message.change : {};
478
- const marker = {
479
- created: "+",
480
- updated: "~",
481
- reinforced: "^",
482
- weakened: "v",
483
- removed: "-",
484
- }[String(change.type || "")] || "~";
485
- const detail = String(change.summary || change.key || "Learn updated").replace(/\s+/g, " ").trim();
486
- this.appendTransaction({
487
- requestId: "learn-" + String(change.eventId || Date.now()),
488
- at: change.at || message.at || new Date().toISOString(),
489
- action: "learn",
490
- summary: "Learn " + marker + " " + truncate(detail, 120),
491
- status: "done",
492
- ok: true,
493
- });
490
+ const activity = message.activity && typeof message.activity === "object" ? message.activity : null;
491
+ if (activity) {
492
+ const tool = String(activity.tool || "learn");
493
+ const change = activity.change && typeof activity.change === "object" ? activity.change : null;
494
+ const scopeSummary = String(activity.scopeSummary || "").trim();
495
+ const kind = String(change?.kind || activity.kind || "memory").trim() || "memory";
496
+ const key = String(change?.key || "").trim();
497
+ const verbs = {
498
+ created: "created",
499
+ updated: "updated",
500
+ reinforced: "reinforced",
501
+ weakened: "weakened",
502
+ removed: "removed",
503
+ };
504
+ let detail;
505
+ if (tool === "learn_prepare") {
506
+ detail = "prepare " + (scopeSummary || "relevant") + " context";
507
+ } else if (tool === "learn_get") {
508
+ detail = "read " + (scopeSummary || "memory") + " context";
509
+ } else if (change) {
510
+ detail = (verbs[String(change.type || "")] || "updated") + " " + kind + (key ? " · " + key : "");
511
+ } else if (tool === "learn_put") {
512
+ detail = "write " + kind + " · no change";
513
+ } else if (tool === "learn_delete") {
514
+ detail = "delete memory · no change";
515
+ } else if (tool === "learn_feedback") {
516
+ detail = String(activity.feedback || "feedback") + " memory · no change";
517
+ } else {
518
+ detail = tool.replace(/^learn_/, "").replace(/_/g, " ");
519
+ }
520
+ const durationMs = Number(activity.durationMs);
521
+ this.appendTransaction({
522
+ requestId: String(activity.eventId || "learn-call-" + Date.now()),
523
+ at: activity.at || message.at || new Date().toISOString(),
524
+ action: tool,
525
+ summary: "🧠 Learn · " + truncate(detail, 120),
526
+ status: "done",
527
+ ok: activity.ok !== false,
528
+ ...(Number.isFinite(durationMs) ? { durationMs } : {}),
529
+ });
530
+ } else {
531
+ const change = message.change && typeof message.change === "object" ? message.change : {};
532
+ const marker = {
533
+ created: "+",
534
+ updated: "~",
535
+ reinforced: "^",
536
+ weakened: "v",
537
+ removed: "-",
538
+ }[String(change.type || "")] || "~";
539
+ const detail = String(change.summary || change.key || "Learn updated").replace(/\s+/g, " ").trim();
540
+ this.appendTransaction({
541
+ requestId: "learn-" + String(change.eventId || Date.now()),
542
+ at: change.at || message.at || new Date().toISOString(),
543
+ action: "learn",
544
+ summary: "Learn " + marker + " " + truncate(detail, 120),
545
+ status: "done",
546
+ ok: true,
547
+ });
548
+ }
494
549
  } else if (message.event === "system") {
495
550
  this.appendTransaction({
496
551
  requestId: "system-" + Date.now() + "-" + Math.random(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anusornneal/chat-relay",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
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": {
@@ -40,11 +40,11 @@
40
40
  "test:oauth": "node test/oauth-smoke.mjs",
41
41
  "test:usage": "node test/usage-smoke.mjs",
42
42
  "test:usage-storage": "node test/usage-storage.test.mjs",
43
+ "test:no-quota": "node test/no-quota-regression.test.mjs",
43
44
  "test:admin-api": "node test/admin-api-smoke.mjs",
44
45
  "test:admin-auth": "node test/admin-auth-smoke.mjs",
45
46
  "test:dashboard": "node test/dashboard-smoke.mjs",
46
47
  "test:dashboard-timers": "node test/dashboard-timers.test.mjs",
47
- "test:quota": "node test/quota-smoke.mjs",
48
48
  "test:ops": "node test/ops-smoke.mjs",
49
49
  "test:desktop": "node test/mcp-desktop-smoke.mjs",
50
50
  "test:device-management": "node test/device-management-smoke.mjs",
@@ -55,10 +55,11 @@
55
55
  "test:self-update": "node --test test/self-update.test.mjs test/agent-lifecycle-upgrade.test.mjs",
56
56
  "test:budget": "node --test test/relay-health.test.mjs test/usage-budget.test.mjs",
57
57
  "test:soak": "node test/soak-smoke.mjs",
58
- "test:hardening": "npm run test:tui && npm run test:config-security && npm run test:self-update && npm run test:budget && node --test test/connection-generation.test.mjs && npm run test:agent-state && node test/heartbeat-ack-watchdog.test.mjs && npm run test:usage-storage && npm run test:learn && npm run test:learn-bootstrap && npm run test:soak",
58
+ "test:hardening": "npm run test:tui && npm run test:config-security && npm run test:self-update && npm run test:budget && npm run test:worker-hotpath && node --test test/connection-generation.test.mjs && npm run test:agent-state && node test/heartbeat-ack-watchdog.test.mjs && npm run test:no-quota && npm run test:usage-storage && npm run test:learn && npm run test:learn-bootstrap && npm run test:soak",
59
59
  "verify:review": "node scripts/verify-review-artifacts.mjs",
60
60
  "test:learn": "node test/learning-smoke.mjs",
61
- "test:learn-bootstrap": "node test/learning-bootstrap-smoke.mjs"
61
+ "test:learn-bootstrap": "node test/learning-bootstrap-smoke.mjs",
62
+ "test:worker-hotpath": "node --experimental-strip-types --test test/relay-result.test.mjs"
62
63
  },
63
64
  "dependencies": {
64
65
  "ws": "^8.22.0"