@anusornneal/chat-relay 0.11.1 → 0.12.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.
@@ -1,4 +1,4 @@
1
- const MAX_TEXT = 96;
1
+ const MAX_TEXT = 160;
2
2
 
3
3
  function cleanText(value, max = MAX_TEXT) {
4
4
  const text = String(value ?? "").replace(/\s+/g, " ").trim();
@@ -6,16 +6,33 @@ function cleanText(value, max = MAX_TEXT) {
6
6
  return text.slice(0, Math.max(0, max - 1)) + "…";
7
7
  }
8
8
 
9
+ function normalizedPath(value) {
10
+ return cleanText(value, 260).replace(/\\/g, "/");
11
+ }
12
+
9
13
  function compactPath(value) {
10
- const normalized = cleanText(value, 120).replace(/\\/g, "/");
11
- if (normalized.length <= 72) return normalized || "-";
14
+ const normalized = normalizedPath(value);
15
+ if (!normalized) return "-";
16
+
17
+ const projectMatch = normalized.match(/\/Projects\/[^/]+\/(.+)$/i);
18
+ if (projectMatch?.[1]) return cleanText(projectMatch[1], 120);
19
+
12
20
  const parts = normalized.split("/").filter(Boolean);
13
- if (parts.length <= 2) return "…" + normalized.slice(-68);
21
+ if (parts.length <= 3) return cleanText(normalized, 120);
14
22
  return "…/" + parts.slice(-3).join("/");
15
23
  }
16
24
 
25
+ function cwdLabel(value) {
26
+ const normalized = normalizedPath(value).replace(/\/$/, "");
27
+ if (!normalized) return "";
28
+ const projectMatch = normalized.match(/\/Projects\/([^/]+)(?:\/.*)?$/i);
29
+ if (projectMatch?.[1]) return projectMatch[1];
30
+ const parts = normalized.split("/").filter(Boolean);
31
+ return parts.at(-1) || normalized;
32
+ }
33
+
17
34
  function redactCommand(value) {
18
- let text = cleanText(value, 220);
35
+ let text = cleanText(value, 520);
19
36
  const patterns = [
20
37
  /(authorization\s*[:=]\s*bearer\s+)[^\s"']+/ig,
21
38
  /((?:token|password|passwd|secret|api[_-]?key|access[_-]?key)\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s;]+)/ig,
@@ -30,6 +47,13 @@ function number(value, fallback = 0) {
30
47
  return Number.isFinite(parsed) ? parsed : fallback;
31
48
  }
32
49
 
50
+ function humanBytes(value) {
51
+ const bytes = Math.max(0, Number(value) || 0);
52
+ if (bytes < 1024) return Math.round(bytes) + " B";
53
+ if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0) + " KB";
54
+ return (bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0) + " MB";
55
+ }
56
+
33
57
  function lineRange(payload) {
34
58
  const offset = Math.max(0, number(payload.offset));
35
59
  const length = Math.max(1, number(payload.length, 200));
@@ -43,106 +67,198 @@ function countKeyboardInput(payload) {
43
67
  return "input";
44
68
  }
45
69
 
70
+ function quotedCommitMessage(command) {
71
+ const match = command.match(/git\s+commit\s+-m\s+["']([^"']+)["']/i);
72
+ return match?.[1] ? cleanText(match[1], 96) : "";
73
+ }
74
+
75
+ function diffTargets(command) {
76
+ const match = command.match(/git\s+diff(?:\s+--check)?\s+--\s+([^;]+)/i);
77
+ if (!match?.[1]) return [];
78
+ return (match[1].match(/"[^"]+"|'[^']+'|\S+/g) || [])
79
+ .map((value) => value.replace(/^["']|["']$/g, ""))
80
+ .filter(Boolean);
81
+ }
82
+
83
+ function humanizeCommand(value) {
84
+ const command = redactCommand(value);
85
+ const lower = command.toLowerCase();
86
+
87
+ const pushTag = command.match(/git\s+push\s+origin\s+main[\s\S]*?git\s+push\s+origin\s+([^\s;]+)/i);
88
+ if (pushTag?.[1]) return `Push main and ${cleanText(pushTag[1], 48)} to origin`;
89
+
90
+ if (/node\s+--test\s+test[\\/]cli-tui\.test\.mjs/i.test(command) &&
91
+ /npm\s+run\s+test:platform/i.test(command) &&
92
+ /git\s+diff\s+--check/i.test(command)) {
93
+ return "Validate terminal UI · unit tests, platform smoke, and Git checks";
94
+ }
95
+
96
+ const version = command.match(/npm\s+version\s+([^\s;]+)/i);
97
+ const commitMessage = quotedCommitMessage(command);
98
+ if (version?.[1] && commitMessage) {
99
+ return `Prepare release ${cleanText(version[1], 32)} · ${commitMessage}`;
100
+ }
101
+
102
+ if (/git\s+status\s+--short/i.test(command) && /git\s+branch\s+--show-current/i.test(command) && /git\s+log\b/i.test(command)) {
103
+ return "Check Git status, current branch, and recent commits";
104
+ }
105
+
106
+ if (/git\s+status\b/i.test(command) && /git\s+log\b/i.test(command)) {
107
+ return "Check Git status and recent commits";
108
+ }
109
+
110
+ if (/git\s+tag\s+--list/i.test(command) && /git\s+status\b/i.test(command)) {
111
+ return "Check release tag and Git status";
112
+ }
113
+
114
+ if (/git\s+add\b/i.test(command) && /git\s+commit\b/i.test(command)) {
115
+ return commitMessage ? `Commit changes · ${commitMessage}` : "Stage and commit changes";
116
+ }
117
+
118
+ if (/git\s+diff\s+--check/i.test(command) && !/git\s+diff\s+--\s+/i.test(command)) {
119
+ return "Check changes for whitespace errors";
120
+ }
121
+
122
+ if (/git\s+diff\b/i.test(command)) {
123
+ const targets = diffTargets(command);
124
+ if (targets.length === 1) return `Review changes · ${compactPath(targets[0])}`;
125
+ if (targets.length > 1) return `Review changes · ${targets.length} files`;
126
+ return "Review Git changes";
127
+ }
128
+
129
+ if (/npm\s+publish(?:\s|$)/i.test(command)) {
130
+ return "Publish package to npm";
131
+ }
132
+
133
+ const npmView = command.match(/npm\s+view\s+([^\s;]+)\s+version/i);
134
+ if (npmView?.[1]) return `Check published version · ${cleanText(npmView[1], 72)}`;
135
+
136
+ if (/node\s+--check\b/i.test(command)) {
137
+ return "Check JavaScript syntax";
138
+ }
139
+
140
+ if (/node\s+--test\b/i.test(command) && /cli-tui\.test\.mjs/i.test(command)) {
141
+ return "Run terminal UI tests";
142
+ }
143
+
144
+ const npmRun = command.match(/^npm\s+run\s+([^\s;]+)/i);
145
+ if (npmRun?.[1] && !/[;&|]/.test(command)) {
146
+ return `Run npm script · ${cleanText(npmRun[1], 64)}`;
147
+ }
148
+
149
+ if (lower === "git status" || lower === "git status --short") return "Check Git status";
150
+
151
+ return `Run ${command}`;
152
+ }
153
+
154
+ function withCwd(summary, cwd) {
155
+ const label = cwdLabel(cwd);
156
+ return label ? `${summary} · in ${label}` : summary;
157
+ }
158
+
46
159
  export function humanizeToolCall(payload = {}) {
47
160
  const action = String(payload?.action || "unknown");
48
161
 
49
162
  switch (action) {
50
163
  case "ping":
51
- return "Ping agent";
164
+ return "Check agent connection";
52
165
  case "agent.config":
53
- return "Get agent config";
166
+ return "Read agent configuration";
54
167
  case "agent.recentCalls":
55
- return `Get recent tool calls · limit ${number(payload.limit, 50)}`;
168
+ return `Read recent activity · up to ${number(payload.limit, 50)} calls`;
56
169
  case "agent.lifecycle.status":
57
- return "Get lifecycle status";
170
+ return "Check agent lifecycle";
58
171
  case "agent.lifecycle.drain":
59
- return "Drain agent";
172
+ return "Pause new long-running work";
60
173
  case "agent.lifecycle.resume":
61
- return "Resume agent";
174
+ return "Resume normal work";
62
175
  case "agent.lifecycle.restart":
63
- return "Restart agent";
176
+ return "Restart local agent";
64
177
 
65
178
  case "fs.stat":
66
- return `Stat ${compactPath(payload.path)}`;
179
+ return `Inspect ${compactPath(payload.path)}`;
67
180
  case "fs.list":
68
- return `List ${compactPath(payload.path)} · depth ${number(payload.depth)} · limit ${number(payload.limit, 100)}`;
181
+ return `Browse ${compactPath(payload.path)} · depth ${number(payload.depth)} · up to ${number(payload.limit, 100)} items`;
69
182
  case "fs.read":
70
183
  return `Read ${compactPath(payload.path)} · ${lineRange(payload)}`;
71
184
  case "fs.readMany":
72
185
  return `Read ${Array.isArray(payload.paths) ? payload.paths.length : 0} files`;
73
186
  case "fs.batch":
74
- return `Filesystem batch · ${Array.isArray(payload.operations) ? payload.operations.length : 0} ops`;
187
+ return `Inspect filesystem · ${Array.isArray(payload.operations) ? payload.operations.length : 0} operations`;
75
188
  case "fs.artifact":
76
189
  return `Export ${compactPath(payload.path)}`;
77
190
  case "fs.write": {
78
191
  const bytes = Buffer.byteLength(String(payload.content ?? ""), "utf8");
79
- return `Write ${compactPath(payload.path)} · ${payload.mode || "rewrite"} · ${bytes} B`;
192
+ const mode = payload.mode === "append" ? "append" : "replace file";
193
+ return `Write ${compactPath(payload.path)} · ${mode} · ${humanBytes(bytes)}`;
194
+ }
195
+ case "fs.edit": {
196
+ const count = Math.max(1, number(payload.expectedReplacements, 1));
197
+ return `Edit ${compactPath(payload.path)} · ${count} change${count === 1 ? "" : "s"}`;
80
198
  }
81
- case "fs.edit":
82
- return `Edit ${compactPath(payload.path)} · replace ×${number(payload.expectedReplacements, 1)}`;
83
199
  case "fs.mkdir":
84
200
  return `Create folder ${compactPath(payload.path)}`;
85
201
  case "fs.move":
86
202
  return `Move ${compactPath(payload.source)} → ${compactPath(payload.destination)}`;
87
203
  case "fs.delete":
88
- return `Delete ${compactPath(payload.path)}${payload.recursive ? " · recursive" : ""}`;
204
+ return `Delete ${compactPath(payload.path)}${payload.recursive ? " and contents" : ""}`;
89
205
  case "fs.search.start":
90
- return `Search "${cleanText(payload.pattern, 56)}" in ${compactPath(payload.path)}`;
206
+ return `Search "${cleanText(payload.pattern, 72)}" · ${compactPath(payload.path)}`;
91
207
  case "fs.search.results":
92
- return `Read search results · offset ${number(payload.offset)} · ${number(payload.length, 50)} rows`;
208
+ return `Read search results · ${number(payload.length, 50)} items from offset ${number(payload.offset)}`;
93
209
 
94
210
  case "process.list":
95
- return `List processes${payload.filter ? ` · "${cleanText(payload.filter, 52)}"` : ""}`;
211
+ return `Find processes${payload.filter ? ` matching "${cleanText(payload.filter, 52)}"` : ""}`;
96
212
  case "process.kill":
97
- return `Kill process ${number(payload.pid)}`;
213
+ return `Stop process ${number(payload.pid)}`;
98
214
 
99
215
  case "terminal.exec":
100
- return `Run ${redactCommand(payload.command)}${payload.cwd ? ` · in ${compactPath(payload.cwd)}` : ""}`;
216
+ return withCwd(humanizeCommand(payload.command), payload.cwd);
101
217
  case "terminal.start":
102
- return `Start ${redactCommand(payload.command)}${payload.cwd ? ` · in ${compactPath(payload.cwd)}` : ""}`;
218
+ return withCwd(`Start background task · ${humanizeCommand(payload.command).replace(/^Run /, "")}`, payload.cwd);
103
219
  case "terminal.shell.start":
104
- return `Start shell${payload.cwd ? ` · in ${compactPath(payload.cwd)}` : ""}`;
220
+ return withCwd("Open interactive shell", payload.cwd);
105
221
  case "terminal.read":
106
- return `Read terminal ${cleanText(payload.sessionId, 32)} · after #${number(payload.afterSeq)}`;
222
+ return `Read terminal output · ${cleanText(payload.sessionId, 24)} · after #${number(payload.afterSeq)}`;
107
223
  case "terminal.write":
108
- return `Write terminal ${cleanText(payload.sessionId, 32)} · ${String(payload.input ?? "").length} chars`;
224
+ return `Send input to terminal · ${String(payload.input ?? "").length} chars`;
109
225
  case "terminal.kill":
110
- return `Stop terminal ${cleanText(payload.sessionId, 32)}`;
226
+ return `Stop terminal session · ${cleanText(payload.sessionId, 24)}`;
111
227
  case "terminal.list":
112
228
  return "List terminal sessions";
113
229
  case "terminal.observability":
114
- return "Get terminal status";
230
+ return "Check terminal activity";
115
231
  case "terminal.batch.start":
116
- return `Run terminal batch · ${Array.isArray(payload.jobs) ? payload.jobs.length : 0} jobs · concurrency ${number(payload.concurrency, 1)}`;
232
+ return `Run terminal batch · ${Array.isArray(payload.jobs) ? payload.jobs.length : 0} jobs · ${number(payload.concurrency, 1)} at a time`;
117
233
  case "terminal.batch.status":
118
- return `Get batch status ${cleanText(payload.batchId, 32)}`;
234
+ return `Check batch progress · ${cleanText(payload.batchId, 24)}`;
119
235
  case "terminal.batch.read":
120
- return `Read batch ${cleanText(payload.batchId, 32)}`;
236
+ return `Read batch output · ${cleanText(payload.batchId, 24)}`;
121
237
  case "terminal.batch.cancel":
122
- return `Cancel batch ${cleanText(payload.batchId, 32)}`;
238
+ return `Cancel batch · ${cleanText(payload.batchId, 24)}`;
123
239
 
124
240
  case "desktop.screenshot":
125
- return "Capture screen";
241
+ return "Capture desktop screenshot";
126
242
  case "desktop.clipboard.read":
127
243
  return "Read clipboard";
128
244
  case "desktop.clipboard.write":
129
245
  return `Write clipboard · ${String(payload.text ?? payload.content ?? "").length} chars`;
130
246
  case "desktop.window.list":
131
- return "List windows";
247
+ return "List open windows";
132
248
  case "desktop.window.focus":
133
- return `Focus window ${cleanText(payload.title ?? payload.windowId ?? payload.handle ?? "", 64)}`;
249
+ return `Focus window · ${cleanText(payload.title ?? payload.windowId ?? payload.handle ?? "", 64)}`;
134
250
  case "desktop.mouse.click": {
135
251
  const button = cleanText(payload.button || "left", 12);
136
252
  const x = number(payload.x);
137
253
  const y = number(payload.y);
138
- return `${button[0]?.toUpperCase() || "L"}${button.slice(1)} click · ${x},${y}`;
254
+ return `${button[0]?.toUpperCase() || "L"}${button.slice(1)} click · x ${x}, y ${y}`;
139
255
  }
140
256
  case "desktop.keyboard.input":
141
- return `Keyboard input · ${countKeyboardInput(payload)}`;
257
+ return `Type on keyboard · ${countKeyboardInput(payload)}`;
142
258
  case "desktop.step":
143
- return `Desktop step · ${Array.isArray(payload.actions) ? payload.actions.length : 0} actions`;
259
+ return `Desktop actions · ${Array.isArray(payload.actions) ? payload.actions.length : 0} steps`;
144
260
 
145
261
  default:
146
- return cleanText(action.replace(/[._]/g, " ").replace(/\b\w/g, (char) => char.toUpperCase()), 100) || "Tool call";
262
+ return cleanText(action.replace(/[._]/g, " ").replace(/\b\w/g, (char) => char.toUpperCase()), 140) || "Tool call";
147
263
  }
148
264
  }
@@ -228,20 +228,26 @@ function Invoke-Screenshot($Payload) {
228
228
  Select-Object -First 1
229
229
  if ($null -eq $codec) { return Result-Error "capture_failed" }
230
230
 
231
- $maxBytes = 32768
231
+ $native = $Payload.native -eq $true
232
+ $maxBytes = if ($native) { 2097152 } else { 32768 }
232
233
  $requestedMaxWidth = if ($null -eq $Payload.maxWidth) { 960 } else { [int]$Payload.maxWidth }
233
- if ($requestedMaxWidth -lt 320 -or $requestedMaxWidth -gt 1920) { return Result-Error "invalid_max_width" }
234
+ if (-not $native -and ($requestedMaxWidth -lt 320 -or $requestedMaxWidth -gt 1920)) { return Result-Error "invalid_max_width" }
234
235
  $requestedQuality = if ($null -eq $Payload.quality) { 58 } else { [int]$Payload.quality }
235
236
  if ($requestedQuality -lt 20 -or $requestedQuality -gt 85) { return Result-Error "invalid_quality" }
236
- $targetWidth = [Math]::Min($bounds.Width, $requestedMaxWidth)
237
+ $targetWidth = if ($native) { $bounds.Width } else { [Math]::Min($bounds.Width, $requestedMaxWidth) }
237
238
  $targetHeight = [Math]::Max(1, [int][Math]::Round($bounds.Height * ($targetWidth / [double]$bounds.Width)))
238
- $qualities = @([long]$requestedQuality, [long][Math]::Min($requestedQuality, 42), [long][Math]::Min($requestedQuality, 30), 20L) | Select-Object -Unique
239
+ $qualities = if ($native) {
240
+ @([long]$requestedQuality, 75L, 60L, 45L, 30L, 20L) | Where-Object { $_ -le $requestedQuality } | Select-Object -Unique
241
+ } else {
242
+ @([long]$requestedQuality, [long][Math]::Min($requestedQuality, 42), [long][Math]::Min($requestedQuality, 30), 20L) | Select-Object -Unique
243
+ }
239
244
  $bytes = $null
240
245
  $finalWidth = $targetWidth
241
246
  $finalHeight = $targetHeight
242
247
  $finalQuality = $requestedQuality
243
248
 
244
- for ($sizeAttempt = 0; $sizeAttempt -lt 3 -and $null -eq $bytes; $sizeAttempt++) {
249
+ $maxSizeAttempts = if ($native) { 1 } else { 3 }
250
+ for ($sizeAttempt = 0; $sizeAttempt -lt $maxSizeAttempts -and $null -eq $bytes; $sizeAttempt++) {
245
251
  $resized = New-Object System.Drawing.Bitmap $targetWidth, $targetHeight
246
252
  $draw = [System.Drawing.Graphics]::FromImage($resized)
247
253
  try {
@@ -305,6 +311,7 @@ function Invoke-Screenshot($Payload) {
305
311
  virtualDesktopHeight = $virtualBounds.Height
306
312
  monitorCount = $monitorCount
307
313
  jpegQuality = $finalQuality
314
+ native = $native
308
315
  desktopOriginX = $bounds.Left
309
316
  desktopOriginY = $bounds.Top
310
317
  desktopWidth = $bounds.Width
package/cli/config.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { clearSecrets, readSecrets, writeSecrets } from "./secret-store.mjs";
4
5
 
5
6
  export function configDir() {
6
7
  if (process.env.CHAT_RELAY_HOME) return path.resolve(process.env.CHAT_RELAY_HOME);
@@ -80,17 +81,21 @@ function migrateLegacyConfig() {
80
81
  return config;
81
82
  }
82
83
 
83
- export function loadConfig() {
84
- const file = configPath();
85
- if (!fs.existsSync(file)) return migrateLegacyConfig();
86
- try {
87
- return JSON.parse(fs.readFileSync(file, "utf8"));
88
- } catch {
89
- throw new Error(`Invalid Chat Relay config: ${file}`);
90
- }
84
+ function configSecrets(config = {}) {
85
+ return {
86
+ ...(typeof config.userToken === "string" && config.userToken ? { userToken: config.userToken } : {}),
87
+ ...(typeof config.agentToken === "string" && config.agentToken ? { agentToken: config.agentToken } : {}),
88
+ };
91
89
  }
92
90
 
93
- export function saveConfig(config) {
91
+ function persistedConfig(config, credentialStorage) {
92
+ const persisted = { ...config, credentialStorage };
93
+ delete persisted.userToken;
94
+ delete persisted.agentToken;
95
+ return persisted;
96
+ }
97
+
98
+ function writeConfigFile(config) {
94
99
  const dir = configDir();
95
100
  fs.mkdirSync(dir, { recursive: true });
96
101
  const file = configPath();
@@ -102,8 +107,39 @@ export function saveConfig(config) {
102
107
  return file;
103
108
  }
104
109
 
110
+ export function loadConfig() {
111
+ const file = configPath();
112
+ if (!fs.existsSync(file)) return migrateLegacyConfig();
113
+ try {
114
+ const stored = JSON.parse(fs.readFileSync(file, "utf8"));
115
+ const embeddedSecrets = configSecrets(stored);
116
+ if (embeddedSecrets.userToken || embeddedSecrets.agentToken) {
117
+ // One-time migration from pre-0.11.3 plaintext config storage.
118
+ saveConfig(stored);
119
+ return stored;
120
+ }
121
+ const secrets = readSecrets(configDir(), { store: stored.credentialStorage });
122
+ return { ...stored, ...secrets };
123
+ } catch (error) {
124
+ if (error instanceof SyntaxError) throw new Error(`Invalid Chat Relay config: ${file}`);
125
+ throw error;
126
+ }
127
+ }
128
+
129
+ export function saveConfig(config) {
130
+ const dir = configDir();
131
+ fs.mkdirSync(dir, { recursive: true });
132
+ const storage = writeSecrets(dir, configSecrets(config));
133
+ return writeConfigFile(persistedConfig(config, storage));
134
+ }
135
+
105
136
  export function clearConfig() {
106
137
  const file = configPath();
138
+ let storage;
139
+ if (fs.existsSync(file)) {
140
+ try { storage = JSON.parse(fs.readFileSync(file, "utf8"))?.credentialStorage; } catch {}
141
+ }
142
+ clearSecrets(configDir(), { store: storage });
107
143
  if (fs.existsSync(file)) fs.rmSync(file, { force: true });
108
144
  }
109
145
 
package/cli/index.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  import { clearConfig, configPath, loadConfig, saveConfig } from "./config.mjs";
2
2
  import { login, requestJson } from "./device-login.mjs";
3
3
  import { protocolCompatibility, remote, validateConfig } from "./remote.mjs";
4
+ import { launchLatestRemote } from "./self-update.mjs";
5
+ import { AGENT_UPGRADE_EXIT_CODE } from "../agent/lifecycle.mjs";
4
6
 
5
7
  function parseOptions(args) {
6
8
  const options = {};
@@ -36,6 +38,7 @@ Usage:
36
38
  chat-relay drain Stop accepting new long-running work
37
39
  chat-relay resume Resume normal work admission
38
40
  chat-relay restart Restart after drain completes
41
+ chat-relay upgrade Relaunch the latest package after drain completes
39
42
  chat-relay logout Revoke this computer login
40
43
  chat-relay help Show this help
41
44
 
@@ -107,8 +110,14 @@ async function status() {
107
110
  }
108
111
 
109
112
  const reauthorizationRequired = agentStatus.response.ok
110
- ? agentStatus.data.reauthorizationRequired === true || agentStatus.data.authorized === false
111
- : agentStatus.response.status === 401 || agentStatus.response.status === 403;
113
+ ? agentStatus.data.reauthorizationRequired === true
114
+ : agentStatus.response.status === 401;
115
+ const agentDisabled = agentStatus.response.ok && agentStatus.data.enabled === false && !reauthorizationRequired;
116
+ const agentAccessUnavailable = agentStatus.response.ok && agentStatus.data.authorized === false &&
117
+ !reauthorizationRequired && !agentDisabled;
118
+ const accessDenied = !agentStatus.response.ok && agentStatus.response.status === 403;
119
+ const relayUnavailable = !agentStatus.response.ok && agentStatus.data?.error === "relay_unavailable";
120
+ const rateLimited = !agentStatus.response.ok && agentStatus.response.status === 429;
112
121
 
113
122
  console.log("Chat Relay");
114
123
  console.log("----------");
@@ -120,10 +129,13 @@ async function status() {
120
129
  console.log("Login: " + (me.data.user?.login || "-"));
121
130
  console.log("Device: " + serverAgentName + " (" + config.agentId + ")");
122
131
  console.log("Relay: " + config.relayUrl);
123
- console.log("Access: " + (reauthorizationRequired ? "re-authorization required" : "authorized"));
132
+ console.log("Access: " + (reauthorizationRequired
133
+ ? "re-authorization required"
134
+ : agentDisabled ? "agent disabled" : agentAccessUnavailable ? "agent access unavailable"
135
+ : accessDenied ? "access denied" : "authorized"));
124
136
  console.log(
125
137
  "Remote: " +
126
- (agentStatus.response.ok && agentStatus.data.online ? "connected" : "offline"),
138
+ (relayUnavailable ? "relay unavailable" : rateLimited ? "rate limited" : agentStatus.response.ok && agentStatus.data.online ? "connected" : "offline"),
127
139
  );
128
140
  if (agentStatus.response.ok) {
129
141
  console.log("LastSeen: " + (agentStatus.data.lastSeenAt || "-"));
@@ -149,6 +161,14 @@ async function status() {
149
161
  console.log('Recovery: run "chat-relay login --force", then "chat-relay remote".');
150
162
  return 1;
151
163
  }
164
+ if (agentDisabled || agentAccessUnavailable || accessDenied) {
165
+ console.log("Recovery: ask the Relay administrator to restore Agent access.");
166
+ return 1;
167
+ }
168
+ if (relayUnavailable || rateLimited) {
169
+ console.log("Recovery: retry status when the Relay service is available.");
170
+ return 1;
171
+ }
152
172
  if (!agentStatus.response.ok && agentStatus.response.status === 0) {
153
173
  console.log("Recovery: retry status when the relay is reachable.");
154
174
  return 1;
@@ -234,8 +254,20 @@ export async function runCli(argv = process.argv.slice(2)) {
234
254
  if (command === "drain") return lifecycleAction("drain");
235
255
  if (command === "resume") return lifecycleAction("resume");
236
256
  if (command === "restart") return lifecycleAction("restart");
257
+ if (command === "upgrade") return lifecycleAction("upgrade");
237
258
  if (command === "remote") {
238
- return (await remote(options)) || 0;
259
+ const remoteCode = (await remote(options)) || 0;
260
+ if (remoteCode === AGENT_UPGRADE_EXIT_CODE) {
261
+ const relaunched = launchLatestRemote(options);
262
+ if (!relaunched.ok) {
263
+ console.error("Upgrade relaunch failed: " + (relaunched.message || relaunched.error || "unknown_error"));
264
+ if (relaunched.retryAt) console.error("Retry after: " + relaunched.retryAt);
265
+ return 1;
266
+ }
267
+ console.log("Upgrade handoff started with " + relaunched.package + ".");
268
+ return 0;
269
+ }
270
+ return remoteCode;
239
271
  }
240
272
 
241
273
  console.error(`Unknown command: ${command}`);