@anusornneal/chat-relay 1.5.0 → 1.7.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
+ }
@@ -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" };
@@ -7,6 +7,7 @@ const DEFAULT_READ_RESPONSE_BYTES = 32 * 1024;
7
7
  const DEFAULT_MULTI_READ_RESPONSE_BYTES = 48 * 1024;
8
8
  const DEFAULT_BATCH_RESPONSE_BYTES = 48 * 1024;
9
9
  const MAX_BATCH_OPERATIONS = 20;
10
+ const MAX_BATCH_SEARCHES = 8;
10
11
  const MAX_ARTIFACT_BYTES = 40 * 1024;
11
12
  const ARTIFACT_MIME_TYPES = new Map([
12
13
  [".txt", "text/plain; charset=utf-8"],
@@ -305,6 +306,9 @@ export class FileManager {
305
306
  throw new Error("invalid_batch");
306
307
  }
307
308
 
309
+ if (operations.filter((item) => item?.op === "search").length > MAX_BATCH_SEARCHES) {
310
+ throw new Error("too_many_batch_searches");
311
+ }
308
312
  const totalBudget = boundedReadBytes(maxTotalBytes, DEFAULT_BATCH_RESPONSE_BYTES, 4 * 1024);
309
313
  const results = [];
310
314
  let nextIndex = null;
@@ -336,6 +340,8 @@ export class FileManager {
336
340
  result = await this.read(operation.path, operation.offset, operation.length, operationBudget);
337
341
  } else if (op === "list") {
338
342
  result = await this.list(operation.path, operation.depth, operation.offset, operation.limit, operationBudget);
343
+ } else if (op === "search") {
344
+ result = await this.startSearch(operation.path, operation.pattern, operation.searchType, operation.maxResults ?? 10, operation.previewLines);
339
345
  } else {
340
346
  throw new Error("invalid_batch_operation");
341
347
  }
@@ -349,6 +355,25 @@ export class FileManager {
349
355
  maxTotalBytes: totalBudget,
350
356
  };
351
357
  if (byteSize(projected) <= totalBudget) break;
358
+ if (op === "search") {
359
+ // Keep the session usable even when first-page previews exceed
360
+ // the aggregate response budget. The caller can continue from
361
+ // sessionId + nextOffset without repeating the scan.
362
+ candidate = undefined;
363
+ for (let keep = result.results.length - 1; keep >= 0; keep--) {
364
+ const page = {
365
+ ...result,
366
+ results: result.results.slice(0, keep),
367
+ nextOffset: keep < result.totalResults ? keep : null,
368
+ };
369
+ const reduced = { ...base, ok: true, result: page };
370
+ if (byteSize({ ...projected, results: [...results, reduced] }) <= totalBudget) {
371
+ candidate = reduced;
372
+ break;
373
+ }
374
+ }
375
+ break;
376
+ }
352
377
  if (op === "stat") {
353
378
  candidate = undefined;
354
379
  break;
@@ -385,7 +410,9 @@ export class FileManager {
385
410
  results.push(candidate);
386
411
  }
387
412
 
388
- const nestedTruncated = results.some((entry) => entry.ok && entry.result?.truncated === true);
413
+ const nestedTruncated = results.some((entry) => entry.ok && (
414
+ entry.result?.truncated === true || (entry.op === "search" && entry.result?.nextOffset !== null)
415
+ ));
389
416
  return {
390
417
  results,
391
418
  totalOperations: operations.length,
@@ -483,7 +510,7 @@ export class FileManager {
483
510
  }
484
511
  }
485
512
 
486
- async startSearch(input, pattern, searchType = "files", maxResults = 100) {
513
+ async startSearch(input, pattern, searchType = "files", maxResults = 100, previewLines = 0) {
487
514
  const target = await this.#resolveExisting(input);
488
515
  if (typeof pattern !== "string" || pattern.length === 0 || pattern.length > 300) {
489
516
  throw new Error("invalid_pattern");
@@ -568,9 +595,10 @@ export class FileManager {
568
595
  for (const item of session.results.slice(0, MAX_SEARCH_FIRST_PAGE_RESULTS)) {
569
596
  const size = byteSize(item);
570
597
  if (firstPage.length > 0 && pageBytes + size > MAX_SEARCH_FIRST_PAGE_BYTES) break;
571
- firstPage.push(item);
598
+ firstPage.push({ ...item });
572
599
  pageBytes += size;
573
600
  }
601
+ await this.#addSearchPreviews(firstPage, previewLines);
574
602
  return {
575
603
  sessionId,
576
604
  status: session.status,
@@ -585,6 +613,39 @@ export class FileManager {
585
613
  };
586
614
  }
587
615
 
616
+ // A page of matches can be expanded without repeating the original search.
617
+ async getSearchResultsWithPreview(sessionId, offset = 0, length = 50, previewLines = 0) {
618
+ const requested = Number(previewLines) > 0 ? Math.min(Math.max(Number(length) || 50, 1), 20) : length;
619
+ const page = this.getSearchResults(sessionId, offset, requested);
620
+ page.results = page.results.map((item) => ({ ...item }));
621
+ await this.#addSearchPreviews(page.results, previewLines);
622
+ return page;
623
+ }
624
+
625
+ async #addSearchPreviews(results, requestedLines) {
626
+ const count = Math.min(60, Math.max(0, Math.trunc(Number(requestedLines) || 0)));
627
+ if (count === 0) return;
628
+ let remaining = 16 * 1024;
629
+ for (const item of results) {
630
+ if (remaining < 1024) break;
631
+ if (!item.path || item.type === "directory") continue;
632
+ const matchSnippet = typeof item.preview === "string" ? item.preview : undefined;
633
+ const start = Number.isInteger(item.line)
634
+ ? Math.max(0, item.line - 1 - Math.floor(count / 2)) : 0;
635
+ try {
636
+ const read = await this.read(item.path, start, count, Math.min(4096, remaining));
637
+ const context = { offset: read.offset, length: read.length, totalLines: read.totalLines,
638
+ content: read.content, truncated: read.truncated, nextOffset: read.nextOffset };
639
+ if (matchSnippet && read.offset + read.length < item.line) context.matchSnippet = matchSnippet;
640
+ if (byteSize(context) > remaining) break;
641
+ item.preview = context;
642
+ remaining -= byteSize(context);
643
+ } catch {
644
+ item.preview = { unavailable: true, ...(matchSnippet ? { matchSnippet } : {}) };
645
+ }
646
+ }
647
+ }
648
+
588
649
  getSearchResults(sessionId, offset = 0, length = 50) {
589
650
  this.#pruneSearchSessions();
590
651
  const key = String(sessionId);
@@ -236,9 +236,9 @@ async function handlePayload(payload) {
236
236
  case "fs.delete":
237
237
  return files.remove(payload.path, payload.recursive);
238
238
  case "fs.search.start":
239
- return files.startSearch(payload.path, payload.pattern, payload.searchType, payload.maxResults);
239
+ return files.startSearch(payload.path, payload.pattern, payload.searchType, payload.maxResults, payload.previewLines);
240
240
  case "fs.search.results":
241
- return files.getSearchResults(payload.sessionId, payload.offset, payload.length);
241
+ return files.getSearchResultsWithPreview(payload.sessionId, payload.offset, payload.length, payload.previewLines);
242
242
 
243
243
  case "git.worktree.cleanup":
244
244
  return gitWorktrees.cleanup(payload.repoPath, payload.worktreePath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anusornneal/chat-relay",
3
- "version": "1.5.0",
3
+ "version": "1.7.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",
@@ -59,7 +59,8 @@
59
59
  "test:self-update": "node --test test/self-update.test.mjs test/agent-lifecycle-upgrade.test.mjs",
60
60
  "test:budget": "node --test test/relay-health.test.mjs test/usage-budget.test.mjs",
61
61
  "test:soak": "node test/soak-smoke.mjs",
62
- "test:file-search": "node --test test/file-search.test.mjs",
62
+ "test:file-search": "node --test test/file-search.test.mjs test/search-preview.test.mjs test/adaptive-tools.test.mjs",
63
+ "bench:search-preview:e2e": "node test/search-preview-e2e-benchmark.mjs",
63
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",
64
65
  "test:batch-contract": "node --test test/tool-contract-batch.test.mjs",
65
66
  "test:terminal-perf": "node --test test/terminal-perf.test.mjs",