@anusornneal/chat-relay 0.11.2 → 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.
- package/README.md +21 -2
- package/agent/capability-scheduler.mjs +3 -1
- package/agent/connection-state.mjs +19 -0
- package/agent/lifecycle.mjs +68 -4
- package/agent/local-agent.mjs +34 -10
- package/cli/config.mjs +45 -9
- package/cli/index.mjs +37 -5
- package/cli/relay-health.mjs +185 -0
- package/cli/remote.mjs +37 -5
- package/cli/secret-store.mjs +223 -0
- package/cli/self-update.mjs +88 -0
- package/cli/tui.mjs +289 -52
- package/package.json +8 -2
package/README.md
CHANGED
|
@@ -37,7 +37,7 @@ npx @anusornneal/chat-relay@latest remote
|
|
|
37
37
|
|
|
38
38
|
On the first run, Chat Relay opens browser-based device authorization. Choose **Continue with Google and authorize computer**, sign in with the same Google account used for the ChatGPT connector, then return to the terminal. Device sign-in requires configured Google OAuth and does not accept a local username/password.
|
|
39
39
|
|
|
40
|
-
The CLI saves the device credentials in your user profile, so later you can reconnect with the same command:
|
|
40
|
+
The CLI saves the device credentials in your user profile using Windows DPAPI or macOS Keychain when available (with a permission-restricted file fallback), so later you can reconnect with the same command:
|
|
41
41
|
|
|
42
42
|
```bash
|
|
43
43
|
npx @anusornneal/chat-relay@latest remote
|
|
@@ -67,6 +67,7 @@ npx @anusornneal/chat-relay@latest remote --root "C:\Users\you\Projects"
|
|
|
67
67
|
| `npx @anusornneal/chat-relay@latest drain` | Stops accepting new long-running work so active work can finish before a restart. |
|
|
68
68
|
| `npx @anusornneal/chat-relay@latest resume` | Cancels drain mode and resumes normal work admission. |
|
|
69
69
|
| `npx @anusornneal/chat-relay@latest restart` | Restarts the local agent after drain has completed and the agent is ready to restart. |
|
|
70
|
+
| `npx @anusornneal/chat-relay@latest upgrade` | After drain has completed, hands off the local agent to `@anusornneal/chat-relay@latest` and reconnects with the saved configuration. |
|
|
70
71
|
| `npx @anusornneal/chat-relay@latest logout` | Revokes this computer login and removes its local credentials. |
|
|
71
72
|
| `npx @anusornneal/chat-relay@latest help` | Shows CLI usage and available options. |
|
|
72
73
|
|
|
@@ -92,6 +93,7 @@ Depending on the device grants and local configuration, Chat Relay can expose:
|
|
|
92
93
|
- Process inspection and termination.
|
|
93
94
|
- Windows/macOS screenshots, mouse input, and keyboard input when desktop access is explicitly enabled.
|
|
94
95
|
- Multiple computers under one account, with per-device routing and permissions.
|
|
96
|
+
- Agent lifecycle control from ChatGPT with process permission: inspect status, drain/resume, restart, and safely hand off to the latest published package.
|
|
95
97
|
- Batched filesystem, terminal, and desktop operations to reduce remote round trips.
|
|
96
98
|
|
|
97
99
|
Desktop access is opt-in. Linux desktop control is not currently implemented.
|
|
@@ -128,6 +130,7 @@ ChatGPT talks only to the cloud MCP endpoint. The local computer opens the outbo
|
|
|
128
130
|
- Access is scope-based: read, write, terminal, process, desktop read, and desktop control can be granted separately.
|
|
129
131
|
- Desktop access is disabled by default.
|
|
130
132
|
- Stored credentials are hashed server-side where applicable.
|
|
133
|
+
- Local user and agent tokens are kept outside `config.json`; Windows uses user-bound DPAPI and macOS uses Keychain when available.
|
|
131
134
|
- Persisted usage/audit telemetry is metadata-only and excludes commands, file contents, screenshots, clipboard contents, and credentials.
|
|
132
135
|
|
|
133
136
|
Chat Relay is currently intended for small trusted teams rather than an enterprise zero-trust control plane.
|
|
@@ -139,7 +142,7 @@ Default CLI config locations:
|
|
|
139
142
|
- Windows: `%LOCALAPPDATA%\chat-relay\config.json`
|
|
140
143
|
- macOS/Linux: `$XDG_CONFIG_HOME/chat-relay/config.json` or `~/.config/chat-relay/config.json`
|
|
141
144
|
|
|
142
|
-
Set `CHAT_RELAY_HOME` to override the config directory.
|
|
145
|
+
Set `CHAT_RELAY_HOME` to override the config directory. `config.json` stores non-secret settings plus the credential storage type; authentication tokens are stored separately. Linux and CI environments use a mode-`0600` secret-file fallback unless another store is explicitly selected.
|
|
143
146
|
|
|
144
147
|
A single account can own multiple computers. Each computer keeps its own agent identity and credential.
|
|
145
148
|
|
|
@@ -153,9 +156,23 @@ Common development commands:
|
|
|
153
156
|
npm install
|
|
154
157
|
npm start
|
|
155
158
|
npm run dev
|
|
159
|
+
npm run test:hardening
|
|
160
|
+
npm run test:soak
|
|
156
161
|
npm run verify:publish
|
|
157
162
|
```
|
|
158
163
|
|
|
164
|
+
The default soak test runs 2,000 deterministic reconnect/telemetry/TUI iterations without a live cloud relay. For a longer local run:
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
CHAT_RELAY_SOAK_ITERATIONS=100000 npm run test:soak
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
PowerShell:
|
|
171
|
+
|
|
172
|
+
```powershell
|
|
173
|
+
$env:CHAT_RELAY_SOAK_ITERATIONS=100000; npm run test:soak
|
|
174
|
+
```
|
|
175
|
+
|
|
159
176
|
`npm run verify:publish` checks the publish file set, CLI entrypoint, Worker dry-run build, review artifacts, and production dependency audit.
|
|
160
177
|
|
|
161
178
|
## Administration
|
|
@@ -170,6 +187,8 @@ npm run admin -- <command>
|
|
|
170
187
|
|
|
171
188
|
Keep `ADMIN_TOKEN` and other deployment secrets out of client configuration and source control.
|
|
172
189
|
|
|
190
|
+
Optional Cloudflare-pressure circuit breakers can be configured with `USAGE_RECORD_DAILY_BUDGET` (skip optional usage-record DO calls after the per-isolate budget) and `USAGE_DASHBOARD_PUBLISH_DAILY_BUDGET` (cap optional dashboard publish calls from the Usage Durable Object). Both default to disabled and are safeguards, not exact Cloudflare billing meters. The local TUI health monitor also backs off automatically after Cloudflare 1027/429/resource errors.
|
|
191
|
+
|
|
173
192
|
## Platform notes
|
|
174
193
|
|
|
175
194
|
- Local agent: Windows and macOS.
|
|
@@ -112,7 +112,9 @@ export class CapabilityScheduler {
|
|
|
112
112
|
if (value.startsWith("process.")) return this.lanes.get("process");
|
|
113
113
|
if (value === "terminal.exec") return this.lanes.get("terminalExec");
|
|
114
114
|
if (value.startsWith("terminal.")) return this.lanes.get("terminalControl");
|
|
115
|
-
if (
|
|
115
|
+
if (["desktop.screenshot", "desktop.clipboard.read", "desktop.window.list"].includes(value)) {
|
|
116
|
+
return this.lanes.get("desktopRead");
|
|
117
|
+
}
|
|
116
118
|
if (value.startsWith("desktop.")) return null;
|
|
117
119
|
return this.lanes.get("agent");
|
|
118
120
|
}
|
|
@@ -41,6 +41,7 @@ export class AgentConnectionState {
|
|
|
41
41
|
this.lastDisconnectReason = null;
|
|
42
42
|
this.lastConnectionDurationMs = null;
|
|
43
43
|
this.lastSocketError = null;
|
|
44
|
+
this.serverConnectionGeneration = null;
|
|
44
45
|
this.reconnectAttempt = 0;
|
|
45
46
|
this.reconnectCount = 0;
|
|
46
47
|
this.nextReconnectAt = null;
|
|
@@ -58,6 +59,7 @@ export class AgentConnectionState {
|
|
|
58
59
|
this.state = "connected";
|
|
59
60
|
this.connectedAt = isoTime(now);
|
|
60
61
|
this.disconnectedAt = null;
|
|
62
|
+
this.serverConnectionGeneration = null;
|
|
61
63
|
this.reconnectAttempt = 0;
|
|
62
64
|
this.nextReconnectAt = null;
|
|
63
65
|
this.nextReconnectDelayMs = null;
|
|
@@ -87,6 +89,22 @@ export class AgentConnectionState {
|
|
|
87
89
|
this.lastSocketError = cleanReason(reason);
|
|
88
90
|
}
|
|
89
91
|
|
|
92
|
+
markServerConnectionGeneration(value) {
|
|
93
|
+
if (value === null || value === undefined) return true;
|
|
94
|
+
const generation = Number(value);
|
|
95
|
+
if (!Number.isSafeInteger(generation) || generation <= 0) {
|
|
96
|
+
this.markSocketError("connection_generation_changed");
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
if (this.serverConnectionGeneration === null) {
|
|
100
|
+
this.serverConnectionGeneration = generation;
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
if (this.serverConnectionGeneration === generation) return true;
|
|
104
|
+
this.markSocketError("connection_generation_changed");
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
|
|
90
108
|
scheduleReconnect(delayMs, now = Date.now()) {
|
|
91
109
|
const delay = boundedInteger(delayMs, this.baseReconnectMs, 100, this.maxReconnectMs);
|
|
92
110
|
this.nextReconnectDelayMs = delay;
|
|
@@ -130,6 +148,7 @@ export class AgentConnectionState {
|
|
|
130
148
|
lastDisconnectReason: this.lastDisconnectReason,
|
|
131
149
|
lastConnectionDurationMs: this.lastConnectionDurationMs,
|
|
132
150
|
lastSocketError: this.lastSocketError,
|
|
151
|
+
serverConnectionGeneration: this.serverConnectionGeneration,
|
|
133
152
|
reconnectAttempt: this.reconnectAttempt,
|
|
134
153
|
reconnectCount: this.reconnectCount,
|
|
135
154
|
nextReconnectAt: this.nextReconnectAt,
|
package/agent/lifecycle.mjs
CHANGED
|
@@ -6,6 +6,7 @@ const ALLOWED_WHILE_DRAINING = new Set([
|
|
|
6
6
|
"agent.lifecycle.drain",
|
|
7
7
|
"agent.lifecycle.resume",
|
|
8
8
|
"agent.lifecycle.restart",
|
|
9
|
+
"agent.lifecycle.upgrade",
|
|
9
10
|
"fs.stat",
|
|
10
11
|
"fs.list",
|
|
11
12
|
"fs.read",
|
|
@@ -29,7 +30,41 @@ const ALLOWED_WHILE_DRAINING = new Set([
|
|
|
29
30
|
"terminal.observability",
|
|
30
31
|
]);
|
|
31
32
|
|
|
33
|
+
const ALLOWED_WHILE_FINALIZING = new Set([
|
|
34
|
+
"ping",
|
|
35
|
+
"agent.config",
|
|
36
|
+
"agent.lifecycle.status",
|
|
37
|
+
]);
|
|
38
|
+
|
|
32
39
|
export const AGENT_RESTART_EXIT_CODE = 4;
|
|
40
|
+
export const AGENT_UPGRADE_EXIT_CODE = 5;
|
|
41
|
+
|
|
42
|
+
export function summarizeAgentWork({ terminal = {}, scheduler = {}, desktop = {} } = {}) {
|
|
43
|
+
const terminalExec = scheduler.terminalExec || {};
|
|
44
|
+
const otherSchedulerLanes = ["filesystem", "process", "terminalControl", "desktopRead"];
|
|
45
|
+
const activeOtherJobs = otherSchedulerLanes.reduce(
|
|
46
|
+
(sum, name) => sum + Math.max(0, Number(scheduler[name]?.active) || 0),
|
|
47
|
+
0,
|
|
48
|
+
);
|
|
49
|
+
const queuedOtherJobs = otherSchedulerLanes.reduce(
|
|
50
|
+
(sum, name) => sum + Math.max(0, Number(scheduler[name]?.queued) || 0),
|
|
51
|
+
0,
|
|
52
|
+
);
|
|
53
|
+
const desktopControl = desktop.controlQueue || {};
|
|
54
|
+
return {
|
|
55
|
+
activeSessions: Array.isArray(terminal.sessions)
|
|
56
|
+
? terminal.sessions.filter((item) => item?.status === "running").length
|
|
57
|
+
: 0,
|
|
58
|
+
activeBatchJobs: Math.max(0, Number(terminal.activeExecJobs) || 0),
|
|
59
|
+
queuedBatchJobs: Math.max(0, Number(terminal.queuedJobs) || 0),
|
|
60
|
+
activeTerminalExecs: Math.max(0, Number(terminalExec.active) || 0),
|
|
61
|
+
queuedTerminalExecs: Math.max(0, Number(terminalExec.queued) || 0),
|
|
62
|
+
activeOtherJobs,
|
|
63
|
+
queuedOtherJobs,
|
|
64
|
+
activeDesktopControls: Math.max(0, Number(desktopControl.active) || 0),
|
|
65
|
+
queuedDesktopControls: Math.max(0, Number(desktopControl.queued) || 0),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
33
68
|
|
|
34
69
|
function normalizeWork(value = {}) {
|
|
35
70
|
const count = (key) => Math.max(0, Number(value[key]) || 0);
|
|
@@ -39,6 +74,10 @@ function normalizeWork(value = {}) {
|
|
|
39
74
|
queuedBatchJobs: count("queuedBatchJobs"),
|
|
40
75
|
activeTerminalExecs: count("activeTerminalExecs"),
|
|
41
76
|
queuedTerminalExecs: count("queuedTerminalExecs"),
|
|
77
|
+
activeOtherJobs: count("activeOtherJobs"),
|
|
78
|
+
queuedOtherJobs: count("queuedOtherJobs"),
|
|
79
|
+
activeDesktopControls: count("activeDesktopControls"),
|
|
80
|
+
queuedDesktopControls: count("queuedDesktopControls"),
|
|
42
81
|
};
|
|
43
82
|
work.total = Object.values(work).reduce((sum, item) => sum + item, 0);
|
|
44
83
|
return work;
|
|
@@ -49,6 +88,7 @@ export class AgentLifecycle {
|
|
|
49
88
|
this.state = "running";
|
|
50
89
|
this.drainStartedAt = null;
|
|
51
90
|
this.restartRequestedAt = null;
|
|
91
|
+
this.upgradeRequestedAt = null;
|
|
52
92
|
this.now = options.now ?? (() => Date.now());
|
|
53
93
|
this.workSummary = options.workSummary ?? (() => ({}));
|
|
54
94
|
}
|
|
@@ -59,13 +99,15 @@ export class AgentLifecycle {
|
|
|
59
99
|
state: this.state,
|
|
60
100
|
drainStartedAt: this.drainStartedAt,
|
|
61
101
|
restartRequestedAt: this.restartRequestedAt,
|
|
102
|
+
upgradeRequestedAt: this.upgradeRequestedAt,
|
|
62
103
|
readyToRestart: this.state === "draining" && work.total === 0,
|
|
104
|
+
readyToUpgrade: this.state === "draining" && work.total === 0,
|
|
63
105
|
work,
|
|
64
106
|
};
|
|
65
107
|
}
|
|
66
108
|
|
|
67
109
|
drain() {
|
|
68
|
-
if (this.state !== "restart-pending") {
|
|
110
|
+
if (this.state !== "restart-pending" && this.state !== "upgrade-pending") {
|
|
69
111
|
this.state = "draining";
|
|
70
112
|
this.drainStartedAt ??= new Date(this.now()).toISOString();
|
|
71
113
|
}
|
|
@@ -73,8 +115,12 @@ export class AgentLifecycle {
|
|
|
73
115
|
}
|
|
74
116
|
|
|
75
117
|
resume() {
|
|
76
|
-
if (this.state === "restart-pending") {
|
|
77
|
-
return {
|
|
118
|
+
if (this.state === "restart-pending" || this.state === "upgrade-pending") {
|
|
119
|
+
return {
|
|
120
|
+
ok: false,
|
|
121
|
+
error: this.state === "upgrade-pending" ? "upgrade_pending" : "restart_pending",
|
|
122
|
+
lifecycle: this.snapshot(),
|
|
123
|
+
};
|
|
78
124
|
}
|
|
79
125
|
this.state = "running";
|
|
80
126
|
this.drainStartedAt = null;
|
|
@@ -82,7 +128,12 @@ export class AgentLifecycle {
|
|
|
82
128
|
}
|
|
83
129
|
|
|
84
130
|
guard(action) {
|
|
85
|
-
|
|
131
|
+
const name = String(action);
|
|
132
|
+
if (this.state === "running") return null;
|
|
133
|
+
if ((this.state === "restart-pending" || this.state === "upgrade-pending") && ALLOWED_WHILE_FINALIZING.has(name)) {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
if (this.state === "draining" && ALLOWED_WHILE_DRAINING.has(name)) return null;
|
|
86
137
|
return { ok: false, error: "agent_draining", lifecycle: this.snapshot() };
|
|
87
138
|
}
|
|
88
139
|
|
|
@@ -98,4 +149,17 @@ export class AgentLifecycle {
|
|
|
98
149
|
this.restartRequestedAt = new Date(this.now()).toISOString();
|
|
99
150
|
return { ok: true, restart: true, lifecycle: this.snapshot() };
|
|
100
151
|
}
|
|
152
|
+
|
|
153
|
+
requestUpgrade() {
|
|
154
|
+
if (this.state !== "draining") {
|
|
155
|
+
return { ok: false, error: "drain_required", lifecycle: this.snapshot() };
|
|
156
|
+
}
|
|
157
|
+
const snapshot = this.snapshot();
|
|
158
|
+
if (snapshot.work.total > 0) {
|
|
159
|
+
return { ok: false, error: "active_work_remaining", lifecycle: snapshot };
|
|
160
|
+
}
|
|
161
|
+
this.state = "upgrade-pending";
|
|
162
|
+
this.upgradeRequestedAt = new Date(this.now()).toISOString();
|
|
163
|
+
return { ok: true, upgrade: true, lifecycle: this.snapshot() };
|
|
164
|
+
}
|
|
101
165
|
}
|
package/agent/local-agent.mjs
CHANGED
|
@@ -6,7 +6,12 @@ import { TerminalManager } from "./terminal-manager.mjs";
|
|
|
6
6
|
import { CapabilityScheduler } from "./capability-scheduler.mjs";
|
|
7
7
|
import { AgentConnectionState } from "./connection-state.mjs";
|
|
8
8
|
import { buildAgentHello } from "./protocol.mjs";
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
AgentLifecycle,
|
|
11
|
+
AGENT_RESTART_EXIT_CODE,
|
|
12
|
+
AGENT_UPGRADE_EXIT_CODE,
|
|
13
|
+
summarizeAgentWork,
|
|
14
|
+
} from "./lifecycle.mjs";
|
|
10
15
|
import { humanizeToolCall } from "./toolcall-summary.mjs";
|
|
11
16
|
import {
|
|
12
17
|
HeartbeatAckWatchdog,
|
|
@@ -109,15 +114,11 @@ const heartbeatAckWatchdog = new HeartbeatAckWatchdog({
|
|
|
109
114
|
});
|
|
110
115
|
|
|
111
116
|
function currentWorkSummary() {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
queuedBatchJobs: terminal.queuedJobs,
|
|
118
|
-
activeTerminalExecs: terminalExec.active,
|
|
119
|
-
queuedTerminalExecs: terminalExec.queued,
|
|
120
|
-
};
|
|
117
|
+
return summarizeAgentWork({
|
|
118
|
+
terminal: terminals.observability(),
|
|
119
|
+
scheduler: scheduler.snapshot(),
|
|
120
|
+
desktop: desktop.getConfig(),
|
|
121
|
+
});
|
|
121
122
|
}
|
|
122
123
|
|
|
123
124
|
const lifecycle = new AgentLifecycle({ workSummary: currentWorkSummary });
|
|
@@ -192,6 +193,11 @@ async function handlePayload(payload) {
|
|
|
192
193
|
if (result.ok) setTimeout(restartAgentProcess, 150);
|
|
193
194
|
return result;
|
|
194
195
|
}
|
|
196
|
+
case "agent.lifecycle.upgrade": {
|
|
197
|
+
const result = lifecycle.requestUpgrade();
|
|
198
|
+
if (result.ok) setTimeout(upgradeAgentProcess, 150);
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
195
201
|
|
|
196
202
|
case "fs.stat":
|
|
197
203
|
return files.stat(payload.path);
|
|
@@ -347,6 +353,7 @@ function sendHeartbeat(socket) {
|
|
|
347
353
|
lastDisconnectReason: connectionState.lastDisconnectReason,
|
|
348
354
|
lastConnectionDurationMs: connectionState.lastConnectionDurationMs,
|
|
349
355
|
lastSocketError: connectionState.lastSocketError,
|
|
356
|
+
serverConnectionGeneration: connectionState.serverConnectionGeneration,
|
|
350
357
|
heartbeatAckWatchdog: heartbeatAckWatchdog.snapshot(now),
|
|
351
358
|
queues: scheduler.snapshot(),
|
|
352
359
|
},
|
|
@@ -472,6 +479,9 @@ function connect() {
|
|
|
472
479
|
|
|
473
480
|
if (message?.control === "agent_heartbeat_ack") {
|
|
474
481
|
heartbeatAckWatchdog.acknowledge();
|
|
482
|
+
if (!connectionState.markServerConnectionGeneration(message.connectionGeneration)) {
|
|
483
|
+
try { socket.terminate(); } catch {}
|
|
484
|
+
}
|
|
475
485
|
return;
|
|
476
486
|
}
|
|
477
487
|
if (message?.control === "credential_revoked") {
|
|
@@ -612,6 +622,20 @@ function restartAgentProcess() {
|
|
|
612
622
|
setTimeout(() => process.exit(AGENT_RESTART_EXIT_CODE), 50);
|
|
613
623
|
}
|
|
614
624
|
|
|
625
|
+
function upgradeAgentProcess() {
|
|
626
|
+
if (stopping) return;
|
|
627
|
+
stopping = true;
|
|
628
|
+
connectionState.markStopping("upgrade_requested");
|
|
629
|
+
clearReconnectTimer();
|
|
630
|
+
stopHeartbeat();
|
|
631
|
+
const socket = activeSocket;
|
|
632
|
+
activeSocket = null;
|
|
633
|
+
try { socket?.close(1012, "upgrade_requested"); } catch {}
|
|
634
|
+
terminals.close();
|
|
635
|
+
desktop.close();
|
|
636
|
+
setTimeout(() => process.exit(AGENT_UPGRADE_EXIT_CODE), 50);
|
|
637
|
+
}
|
|
638
|
+
|
|
615
639
|
function shutdown(reason) {
|
|
616
640
|
if (stopping) return;
|
|
617
641
|
stopping = true;
|
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
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
-
|
|
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
|
|
111
|
-
: agentStatus.response.status === 401
|
|
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
|
|
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
|
-
|
|
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}`);
|