@anusornneal/chat-relay 1.6.0 → 1.8.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
@@ -117,6 +117,9 @@ Depending on the device grants and local configuration, Chat Relay can expose:
117
117
  - Batched filesystem, terminal, and desktop operations to reduce remote round trips.
118
118
 
119
119
  Desktop access is opt-in. Linux desktop control is not currently implemented.
120
+ An optional headless accessibility adapter is described in
121
+ [Desktop Accessibility](docs/DESKTOP_ACCESSIBILITY.md). It is disabled by
122
+ default and requires a separately installed native CLI.
120
123
 
121
124
  ## How it works
122
125
 
@@ -0,0 +1,151 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+
4
+ const execFileAsync = promisify(execFile);
5
+ const REF = /^@[A-Za-z0-9_-]{2,80}:e[1-9][0-9]{0,7}$/;
6
+ const APP = /^[\p{L}\p{N}][\p{L}\p{N} ._()+-]{0,99}$/u;
7
+ const MAX_OUTPUT_BYTES = 256 * 1024;
8
+ const MAX_RESULT_BYTES = 45 * 1024;
9
+ const MAX_VALUE_LENGTH = 8192;
10
+
11
+ function failure(code) {
12
+ return { ok: false, error: { code } };
13
+ }
14
+
15
+ function parseEnvelope(stdout, kind) {
16
+ let result;
17
+ try {
18
+ result = JSON.parse(stdout);
19
+ } catch {
20
+ return failure("INVALID_OUTPUT");
21
+ }
22
+ if (!result || typeof result.ok !== "boolean") return failure("INVALID_OUTPUT");
23
+ if (!result.ok) {
24
+ // Never reflect raw messages, paths, stderr or CLI diagnostics to the remote caller.
25
+ const code = typeof result.error?.code === "string" && /^[A-Z_]{2,60}$/.test(result.error.code)
26
+ ? result.error.code : "COMMAND_FAILED";
27
+ const retry = result.error?.disposition?.retry;
28
+ const delivery = result.error?.disposition?.delivery;
29
+ return {
30
+ ok: false,
31
+ error: {
32
+ code,
33
+ ...(retry === "safe" || retry === "unsafe" ? { retry } : {}),
34
+ ...(typeof delivery === "string" && /^[a-z_]{1,40}$/.test(delivery) ? { delivery } : {}),
35
+ },
36
+ };
37
+ }
38
+ const data = result.data;
39
+ if (!data || typeof data !== "object") return failure("INVALID_OUTPUT");
40
+ if (kind === "snapshot" &&
41
+ (typeof data.app !== "string" || typeof data.snapshot_id !== "string" ||
42
+ typeof data.ref_count !== "number" || typeof data.complete !== "boolean" ||
43
+ !data.tree || typeof data.tree !== "object")) return failure("INVALID_OUTPUT");
44
+ if (kind === "status" && (typeof data.version !== "string" ||
45
+ typeof data.platform !== "string")) return failure("INVALID_OUTPUT");
46
+ if (kind === "action" && (typeof data.action !== "string" ||
47
+ typeof data.disposition?.delivery !== "string")) return failure("INVALID_OUTPUT");
48
+ let compact;
49
+ if (kind === "snapshot") {
50
+ compact = {
51
+ app: data.app,
52
+ window: data.window,
53
+ snapshot_id: data.snapshot_id,
54
+ ref_count: data.ref_count,
55
+ complete: data.complete,
56
+ ...(data.truncated ? { truncated: true } : {}),
57
+ tree: data.tree,
58
+ };
59
+ } else if (kind === "status") {
60
+ compact = {
61
+ platform: data.platform,
62
+ version: data.version,
63
+ accessibility: data.permissions?.accessibility?.state,
64
+ supported_surfaces: data.supported_surfaces,
65
+ };
66
+ } else {
67
+ compact = {
68
+ action: data.action,
69
+ disposition: data.disposition,
70
+ verification_scope: data.verification_scope,
71
+ };
72
+ }
73
+ const response = { ok: true, backend: "agent-desktop", data: compact };
74
+ return Buffer.byteLength(JSON.stringify(response), "utf8") <= MAX_RESULT_BYTES
75
+ ? response : failure("RESULT_TOO_LARGE");
76
+ }
77
+
78
+ /**
79
+ * Optional headless CLI adapter. Never invokes --headed or synthesizes physical input.
80
+ * The native binary is installed separately, not bundled with Chat Relay.
81
+ */
82
+ export class AgentDesktopAdapter {
83
+ constructor({ executable = process.env.AGENT_DESKTOP_BIN || (process.platform === "win32" ? "agent-desktop.exe" : "agent-desktop"), execute = execFileAsync, timeoutMs = 10000 } = {}) {
84
+ this.executable = executable;
85
+ this.execute = execute;
86
+ this.timeoutMs = Number.isFinite(timeoutMs) ? Math.min(Math.max(1000, timeoutMs), 30000) : 10000;
87
+ }
88
+
89
+ async #call(command, args = [], kind = "action") {
90
+ try {
91
+ const { stdout } = await this.execute(this.executable, [command, ...args], {
92
+ timeout: this.timeoutMs,
93
+ maxBuffer: MAX_OUTPUT_BYTES,
94
+ windowsHide: true,
95
+ shell: false,
96
+ });
97
+ return parseEnvelope(stdout, kind);
98
+ } catch (error) {
99
+ // agent-desktop returns its structured JSON even on nonzero exit codes.
100
+ if (typeof error?.stdout === "string" && error.stdout.trim()) {
101
+ return parseEnvelope(error.stdout, kind);
102
+ }
103
+ return failure(error?.code === "ENOENT" ? "NOT_INSTALLED"
104
+ : error?.killed || error?.code === "ETIMEDOUT" ? "TIMEOUT" : "EXECUTION_FAILED");
105
+ }
106
+ }
107
+
108
+ snapshot({ app, root, interactive = true, maxDepth = 6, skeleton = false } = {}) {
109
+ if (typeof app !== "string" || !APP.test(app)) return Promise.resolve(failure("INVALID_APP"));
110
+ if (root !== undefined && (typeof root !== "string" || !REF.test(root))) {
111
+ return Promise.resolve(failure("INVALID_REF"));
112
+ }
113
+ if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > 8 ||
114
+ typeof interactive !== "boolean" || typeof skeleton !== "boolean") {
115
+ return Promise.resolve(failure("INVALID_INPUT"));
116
+ }
117
+ return this.#call("snapshot", [
118
+ "--app", app, ...(interactive ? ["--interactive-only"] : []),
119
+ "--compact", "--max-depth", String(maxDepth),
120
+ ...(root ? ["--root", root] : []),
121
+ ...(skeleton ? ["--skeleton"] : []),
122
+ ], "snapshot");
123
+ }
124
+
125
+ click({ ref } = {}) {
126
+ if (typeof ref !== "string" || !REF.test(ref)) return Promise.resolve(failure("INVALID_REF"));
127
+ return this.#call("click", [ref]);
128
+ }
129
+
130
+ setValue({ ref, value } = {}) {
131
+ if (typeof ref !== "string" || !REF.test(ref) ||
132
+ typeof value !== "string" || value.length > MAX_VALUE_LENGTH) {
133
+ return Promise.resolve(failure("INVALID_INPUT"));
134
+ }
135
+ return this.#call("set-value", [ref, value]);
136
+ }
137
+
138
+ status() {
139
+ return this.#call("status", [], "status");
140
+ }
141
+
142
+ executeAction(action = {}) {
143
+ switch (action.operation) {
144
+ case "snapshot": return this.snapshot(action);
145
+ case "click": return this.click(action);
146
+ case "set-value": return this.setValue(action);
147
+ case "status": return this.status();
148
+ default: return Promise.resolve(failure("INVALID_OPERATION"));
149
+ }
150
+ }
151
+ }
@@ -93,6 +93,12 @@ export class CapabilityScheduler {
93
93
  ["process", lane("process", options.processConcurrency ?? 4)],
94
94
  ["terminalExec", lane("terminalExec", options.terminalExecConcurrency ?? 4)],
95
95
  ["terminalControl", lane("terminalControl", options.terminalControlConcurrency ?? 8)],
96
+ ["terminalWait", new BoundedLane({
97
+ name: "terminalWait",
98
+ concurrency: options.terminalWaitConcurrency ?? 2,
99
+ maxQueued: 2,
100
+ queueTimeoutMs: 1000,
101
+ })],
96
102
  ["desktopRead", lane("desktopRead", options.desktopReadConcurrency ?? 2)],
97
103
  ]);
98
104
  }
@@ -111,6 +117,7 @@ export class CapabilityScheduler {
111
117
  if (value.startsWith("fs.")) return this.lanes.get("filesystem");
112
118
  if (value.startsWith("process.")) return this.lanes.get("process");
113
119
  if (value === "terminal.exec") return this.lanes.get("terminalExec");
120
+ if (value === "terminal.read.wait") return this.lanes.get("terminalWait");
114
121
  if (value.startsWith("terminal.")) return this.lanes.get("terminalControl");
115
122
  if (["desktop.screenshot", "desktop.clipboard.read", "desktop.window.list"].includes(value)) {
116
123
  return this.lanes.get("desktopRead");
@@ -1,4 +1,5 @@
1
1
  import { BoundedLane } from "./capability-scheduler.mjs";
2
+ import { AgentDesktopAdapter } from "./agent-desktop-adapter.mjs";
2
3
  import { PersistentDesktopRunner } from "./windows-desktop-runner.mjs";
3
4
  import { MacOSDesktopRunner } from "./macos-desktop-runner.mjs";
4
5
 
@@ -160,6 +161,9 @@ export class DesktopManager {
160
161
  });
161
162
  this.platform = this.adapter.platform;
162
163
  this.runner = (operation, args) => this.adapter.run(operation, args);
164
+ this.accessibilityEnabled = options.accessibilityEnabled ?? process.env.DESKTOP_ACCESSIBILITY_ENABLED === "1";
165
+ this.accessibilityAdapter = this.accessibilityEnabled
166
+ ? (options.accessibilityAdapter ?? new AgentDesktopAdapter()) : null;
163
167
  this.controlLane = options.controlLane ?? new BoundedLane({
164
168
  name: "desktop_control",
165
169
  concurrency: 1,
@@ -174,6 +178,7 @@ export class DesktopManager {
174
178
  supported: this.adapter.supported,
175
179
  platform: this.adapter.platform,
176
180
  transport: this.adapter.transport,
181
+ accessibilityEnabled: this.accessibilityEnabled,
177
182
  controlQueue: this.controlLane.snapshot(),
178
183
  };
179
184
  }
@@ -354,6 +359,23 @@ export class DesktopManager {
354
359
  const actions = Array.isArray(input.actions) ? input.actions : [];
355
360
  if (actions.length < 1 || actions.length > 20) return { ok: false, error: "invalid_step_actions" };
356
361
 
362
+ // Keep semantic operations isolated from physical input and screenshot capture.
363
+ // Accessibility observation requires the desktop_read grant at the Worker.
364
+ if (actions.some((action) => action?.type === "accessibility")) {
365
+ if (actions.length !== 1 || input.captureAfter === true ||
366
+ input.settleMs !== undefined || input.monitor !== undefined ||
367
+ input.maxWidth !== undefined || input.quality !== undefined) {
368
+ return { ok: false, error: "invalid_accessibility_step" };
369
+ }
370
+ if (!this.accessibilityEnabled) return { ok: false, error: "accessibility_disabled" };
371
+ const startedAt = Date.now();
372
+ const result = await this.runControl(() => this.accessibilityAdapter.executeAction(actions[0]));
373
+ return {
374
+ ...result,
375
+ timing: { totalMs: Math.max(0, Date.now() - startedAt), requestedActions: 1, executedActions: 1 },
376
+ };
377
+ }
378
+
357
379
  const normalizedActions = [];
358
380
  for (const action of actions) {
359
381
  if (!action || typeof action !== "object") return { ok: false, error: "invalid_step_action" };
@@ -41,7 +41,7 @@ export const AGENT_UPGRADE_EXIT_CODE = 5;
41
41
 
42
42
  export function summarizeAgentWork({ terminal = {}, scheduler = {}, desktop = {} } = {}) {
43
43
  const terminalExec = scheduler.terminalExec || {};
44
- const otherSchedulerLanes = ["filesystem", "process", "terminalControl", "desktopRead"];
44
+ const otherSchedulerLanes = ["filesystem", "process", "terminalControl", "terminalWait", "desktopRead"];
45
45
  const activeOtherJobs = otherSchedulerLanes.reduce(
46
46
  (sum, name) => sum + Math.max(0, Number(scheduler[name]?.active) || 0),
47
47
  0,
@@ -290,7 +290,7 @@ async function handlePayload(payload) {
290
290
  return terminals.startShell(payload.cwd, payload.observability);
291
291
  case "terminal.read":
292
292
  if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
293
- return terminals.read(payload.sessionId, payload.afterSeq, payload.maxChars);
293
+ return terminals.readWithWait(payload.sessionId, payload.afterSeq, payload.maxChars, payload.waitMs ?? 0);
294
294
  case "terminal.write":
295
295
  if (!terminalEnabled) return { ok: false, error: "terminal_disabled" };
296
296
  return terminals.write(payload.sessionId, payload.input, payload.appendNewline !== false);
@@ -535,7 +535,9 @@ function connect() {
535
535
  let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
536
536
  let handlerDurationMs = 0;
537
537
  try {
538
- const result = await scheduler.run(action, async (meta = {}) => {
538
+ const schedulingAction = action === "terminal.read" && Number(message.payload?.waitMs) > 0
539
+ ? "terminal.read.wait" : action;
540
+ const result = await scheduler.run(schedulingAction, async (meta = {}) => {
539
541
  scheduleMeta = { ...scheduleMeta, ...meta };
540
542
  const handlerStartedAt = Date.now();
541
543
  try {
@@ -41,7 +41,7 @@ export function getAgentCapabilities(options = {}) {
41
41
  ];
42
42
 
43
43
  if (terminalEnabled) {
44
- capabilities.push("terminal.exec", "terminal.sessions", "terminal.batch");
44
+ capabilities.push("terminal.exec", "terminal.sessions", "terminal.batch", "terminal.read.wait");
45
45
  }
46
46
 
47
47
  if (desktopEnabled && ["win32", "darwin"].includes(platform)) {
@@ -11,6 +11,8 @@ import {
11
11
  const MAX_EXEC_BUFFER = 48 * 1024;
12
12
  const MAX_SESSION_BUFFER = 256 * 1024;
13
13
  const MAX_READ_CHARS = 24 * 1024;
14
+ const MAX_OUTPUT_WAIT_MS = 15_000;
15
+ const MAX_WAITERS_PER_SESSION = 8;
14
16
  const MAX_INPUT_CHARS = 8 * 1024;
15
17
  const MAX_SESSIONS = 8;
16
18
  const MAX_BATCH_SIZE = 20;
@@ -626,6 +628,7 @@ export class TerminalManager {
626
628
  }
627
629
 
628
630
  close() {
631
+ for (const session of this.sessions.values()) this.#notifyWaiters(session);
629
632
  this.fastExecPool?.close();
630
633
  }
631
634
 
@@ -726,6 +729,32 @@ export class TerminalManager {
726
729
  };
727
730
  }
728
731
 
732
+ async readWithWait(sessionId, afterSeq = 0, maxChars = MAX_READ_CHARS, waitMs = 0) {
733
+ if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > MAX_OUTPUT_WAIT_MS) {
734
+ throw new Error("invalid_wait_ms");
735
+ }
736
+ const initial = this.read(sessionId, afterSeq, maxChars);
737
+ if (!waitMs || initial.status !== "running" || initial.chunks.length || initial.truncated) {
738
+ return initial;
739
+ }
740
+ const session = this.#get(sessionId);
741
+ if (!session) return initial;
742
+ if (session.waiters.size >= MAX_WAITERS_PER_SESSION) throw new Error("too_many_terminal_waiters");
743
+
744
+ return new Promise((resolve) => {
745
+ let timer = null;
746
+ const finish = () => {
747
+ if (timer === null) return;
748
+ clearTimeout(timer);
749
+ timer = null;
750
+ session.waiters.delete(finish);
751
+ resolve(this.read(sessionId, afterSeq, maxChars));
752
+ };
753
+ session.waiters.add(finish);
754
+ timer = setTimeout(finish, waitMs);
755
+ });
756
+ }
757
+
729
758
  write(sessionId, input, appendNewline = true) {
730
759
  const session = this.#get(sessionId);
731
760
  if (!session) return terminalSessionMiss(sessionId, this.processEpoch);
@@ -897,6 +926,7 @@ export class TerminalManager {
897
926
  chunks: [],
898
927
  nextSeq: 1,
899
928
  totalChars: 0,
929
+ waiters: new Set(),
900
930
  observability: observability ?? null,
901
931
  };
902
932
 
@@ -909,6 +939,7 @@ export class TerminalManager {
909
939
  session.exitCode = code;
910
940
  session.signal = signal;
911
941
  session.endedAt = new Date().toISOString();
942
+ this.#notifyWaiters(session);
912
943
  });
913
944
 
914
945
  return this.#summary(session);
@@ -1016,6 +1047,11 @@ export class TerminalManager {
1016
1047
  const removed = session.chunks.shift();
1017
1048
  session.totalChars -= removed.text.length;
1018
1049
  }
1050
+ if (text.length) this.#notifyWaiters(session);
1051
+ }
1052
+
1053
+ #notifyWaiters(session) {
1054
+ for (const notify of session.waiters) notify();
1019
1055
  }
1020
1056
 
1021
1057
  #summary(session) {
@@ -219,7 +219,7 @@ export function humanizeToolCall(payload = {}) {
219
219
  case "terminal.shell.start":
220
220
  return withCwd("Open interactive shell", payload.cwd);
221
221
  case "terminal.read":
222
- return `Read terminal output · ${cleanText(payload.sessionId, 24)} · after #${number(payload.afterSeq)}`;
222
+ return `Read terminal output · ${cleanText(payload.sessionId, 24)} · after #${number(payload.afterSeq)}${Number(payload.waitMs) > 0 ? ` · wait up to ${number(payload.waitMs)}ms` : ""}`;
223
223
  case "terminal.write":
224
224
  return `Send input to terminal · ${String(payload.input ?? "").length} chars`;
225
225
  case "terminal.kill":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anusornneal/chat-relay",
3
- "version": "1.6.0",
3
+ "version": "1.8.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": {
@@ -50,7 +50,7 @@
50
50
  "test:dashboard": "node test/dashboard-smoke.mjs",
51
51
  "test:dashboard-timers": "node test/dashboard-timers.test.mjs",
52
52
  "test:ops": "node test/ops-smoke.mjs",
53
- "test:desktop": "node test/mcp-desktop-smoke.mjs",
53
+ "test:desktop": "node --test test/agent-desktop-adapter.test.mjs && node test/mcp-desktop-smoke.mjs",
54
54
  "test:device-management": "node test/device-management-smoke.mjs",
55
55
  "test:submission": "node test/submission-smoke.mjs",
56
56
  "test:agent-state": "node --experimental-strip-types --test test/agent-state.test.mjs test/reconnect-chaos.test.mjs",
@@ -63,7 +63,7 @@
63
63
  "bench:search-preview:e2e": "node test/search-preview-e2e-benchmark.mjs",
64
64
  "test:hardening": "npm run test:file-search && npm run test:batch-contract && npm run test:terminal-perf && npm run test:tool-guidance && 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",
65
65
  "test:batch-contract": "node --test test/tool-contract-batch.test.mjs",
66
- "test:terminal-perf": "node --test test/terminal-perf.test.mjs",
66
+ "test:terminal-perf": "node --test test/terminal-perf.test.mjs test/terminal-wait.test.mjs",
67
67
  "test:tool-guidance": "node --test test/tool-error-guidance.test.mjs",
68
68
  "verify:review": "node scripts/verify-review-artifacts.mjs",
69
69
  "test:learn": "node test/learning-smoke.mjs && node test/project-alias-sqlite.test.mjs && node test/project-merge-mcp.test.mjs && node --test test/shared-learn.test.mjs test/shared-learn-ui.test.mjs && npm run test:learn-usage",