@anusornneal/chat-relay 1.8.0 → 2.0.1
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 +60 -0
- package/agent/activity-capture.mjs +165 -0
- package/agent/capability-scheduler.mjs +83 -6
- package/agent/file-manager.mjs +188 -77
- package/agent/fs-batch-preview.mjs +70 -0
- package/agent/full-bridge.mjs +53 -0
- package/agent/full-desktop-actions.mjs +124 -0
- package/agent/full-desktop-auth.mjs +53 -0
- package/agent/full-desktop-broker.mjs +308 -0
- package/agent/full-host.mjs +153 -0
- package/agent/full-job-broker.mjs +360 -0
- package/agent/full-native-job.mjs +205 -0
- package/agent/full-presentation-changes.mjs +191 -0
- package/agent/full-remote-diagnostics.mjs +129 -0
- package/agent/full-resources.mjs +343 -0
- package/agent/full-runtime-supervisor.mjs +67 -0
- package/agent/full-session-dispatch.mjs +167 -0
- package/agent/full-workspace-broker.mjs +290 -0
- package/agent/git-worktree-manager.mjs +170 -4
- package/agent/lifecycle.mjs +17 -0
- package/agent/local-agent.mjs +182 -33
- package/agent/local-usage.mjs +275 -0
- package/agent/monitor-activity.mjs +111 -0
- package/agent/presentation-redaction.mjs +10 -0
- package/agent/process-manager.mjs +32 -0
- package/agent/protocol.mjs +5 -1
- package/agent/terminal-manager.mjs +240 -29
- package/agent/terminal-output.mjs +136 -0
- package/agent/toolcall-context.mjs +35 -5
- package/agent/toolcall-summary.mjs +10 -0
- package/agent/windows-desktop-runner.mjs +65 -61
- package/agent/windows-desktop-worker.ps1 +33 -18
- package/agent/windows-powershell.mjs +51 -0
- package/cli/full-background.mjs +69 -0
- package/cli/full-launch.mjs +94 -0
- package/cli/full-prepare-child.mjs +48 -0
- package/cli/full-prepare.mjs +171 -0
- package/cli/full-release-default.json +4 -0
- package/cli/full-release-files.mjs +36 -0
- package/cli/full-release-official.mjs +48 -0
- package/cli/full-release-source.mjs +37 -0
- package/cli/index.mjs +8 -4
- package/cli/mod-cache.mjs +170 -0
- package/cli/mod-loader.mjs +67 -0
- package/cli/mod-manifest.mjs +63 -0
- package/cli/remote.mjs +172 -17
- package/cli/runner-ownership.mjs +116 -3
- package/cli/self-update.mjs +1 -1
- package/cli/tui.mjs +2 -20
- package/package.json +9 -6
- package/packages/full-contracts/index.mjs +193 -0
- package/packages/full-contracts/native-job.mjs +13 -0
- package/packages/full-contracts/package.json +7 -0
- package/packages/full-contracts/remote-session.mjs +239 -0
package/cli/remote.mjs
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import { execFile, spawn } from "node:child_process";
|
|
2
2
|
import { fileURLToPath } from "node:url";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
4
5
|
import { loadConfig, saveConfig } from "./config.mjs";
|
|
5
6
|
import { login, needsRelayLogin, requestJson } from "./device-login.mjs";
|
|
6
|
-
import { acquireRunnerOwnership, RunnerAlreadyActiveError } from "./runner-ownership.mjs";
|
|
7
|
+
import { acquireRunnerOwnership, requestFullDesktopOpen, RunnerAlreadyActiveError } from "./runner-ownership.mjs";
|
|
7
8
|
import { getAgentVersion } from "../agent/protocol.mjs";
|
|
8
9
|
import { AGENT_UPGRADE_EXIT_CODE } from "../agent/lifecycle.mjs";
|
|
10
|
+
import { FULL_STARTUP_EXIT_CODE } from "../agent/full-session-dispatch.mjs";
|
|
11
|
+
import { attachDesktopAuthorization } from "../agent/full-desktop-auth.mjs";
|
|
9
12
|
import { RemoteTui, shouldUseTui } from "./tui.mjs";
|
|
10
13
|
import { startRelayHealthMonitor } from "./relay-health.mjs";
|
|
14
|
+
import {createBackgroundHandoff,launchFullBackground,shouldLaunchFullBackground} from "./full-background.mjs";
|
|
11
15
|
|
|
12
16
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
13
17
|
let stopping = false;
|
|
@@ -16,7 +20,8 @@ export function shouldRestartAgent(result, stoppingNow = false) {
|
|
|
16
20
|
return !stoppingNow
|
|
17
21
|
&& result?.code !== 2
|
|
18
22
|
&& result?.code !== 3
|
|
19
|
-
&& result?.code !== AGENT_UPGRADE_EXIT_CODE
|
|
23
|
+
&& result?.code !== AGENT_UPGRADE_EXIT_CODE
|
|
24
|
+
&& result?.code !== FULL_STARTUP_EXIT_CODE;
|
|
20
25
|
}
|
|
21
26
|
|
|
22
27
|
export function protocolCompatibility(agentProtocolVersion, expectedProtocolVersion) {
|
|
@@ -41,11 +46,12 @@ function terminateChildTree(child) {
|
|
|
41
46
|
child.kill("SIGTERM");
|
|
42
47
|
}
|
|
43
48
|
|
|
44
|
-
async function validateConfig(config) {
|
|
49
|
+
async function validateConfig(config, { onVerified } = {}) {
|
|
45
50
|
if (!config?.relayUrl || !config?.userToken || !config?.agentToken || !config?.agentId) return false;
|
|
46
|
-
const { response } = await requestJson(`${config.relayUrl}/auth/me`, {
|
|
51
|
+
const { response, data } = await requestJson(`${config.relayUrl}/auth/me`, {
|
|
47
52
|
headers: { authorization: `Bearer ${config.userToken}` },
|
|
48
53
|
}).catch(() => ({ response: { ok: false } }));
|
|
54
|
+
if(response.ok)onVerified?.(data);
|
|
49
55
|
return Boolean(response.ok);
|
|
50
56
|
}
|
|
51
57
|
|
|
@@ -62,14 +68,17 @@ function printSummary(config) {
|
|
|
62
68
|
console.log("");
|
|
63
69
|
}
|
|
64
70
|
|
|
65
|
-
function spawnAgent(config, { tui = null, onConnectionState = null } = {}) {
|
|
71
|
+
function spawnAgent(config, { tui = null, onConnectionState = null, fullBootstrap = null, authorizeDesktop = null } = {}) {
|
|
66
72
|
const agentPath = path.join(packageRoot, "agent", "local-agent.mjs");
|
|
67
73
|
const cwd = String(config.allowedRoots || process.cwd()).split(";")[0] || process.cwd();
|
|
68
74
|
const useTui = Boolean(tui);
|
|
75
|
+
const environment = { ...process.env };
|
|
76
|
+
delete environment.CHAT_RELAY_FULL_BOOTSTRAP;
|
|
77
|
+
if (fullBootstrap) environment.CHAT_RELAY_FULL_BOOTSTRAP = JSON.stringify(fullBootstrap);
|
|
69
78
|
const child = spawn(process.execPath, [agentPath], {
|
|
70
79
|
cwd,
|
|
71
80
|
env: {
|
|
72
|
-
...
|
|
81
|
+
...environment,
|
|
73
82
|
RELAY_URL: config.relayUrl,
|
|
74
83
|
AGENT_ID: config.agentId,
|
|
75
84
|
AGENT_NAME: config.agentName,
|
|
@@ -79,9 +88,14 @@ function spawnAgent(config, { tui = null, onConnectionState = null } = {}) {
|
|
|
79
88
|
ALLOWED_ROOTS: config.allowedRoots,
|
|
80
89
|
CHAT_RELAY_UI: useTui ? "ipc" : "plain",
|
|
81
90
|
},
|
|
82
|
-
stdio: useTui ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
|
|
83
|
-
|
|
91
|
+
stdio: useTui || fullBootstrap ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
|
|
92
|
+
// Full GUI owns the visible window; its Core must not allocate a console.
|
|
93
|
+
windowsHide: fullBootstrap?.headless === false,
|
|
84
94
|
});
|
|
95
|
+
if(fullBootstrap?.headless===false){
|
|
96
|
+
const stopAuthorization=attachDesktopAuthorization(child,{principal:fullBootstrap.localPrincipal,authenticate:authorizeDesktop});
|
|
97
|
+
child.once("exit",stopAuthorization);child.once("error",stopAuthorization);
|
|
98
|
+
}
|
|
85
99
|
if (useTui) child.on("message", (message) => {
|
|
86
100
|
tui.handleMessage(message);
|
|
87
101
|
if (message?.type === "chat-relay-ui" && message.event === "connection") {
|
|
@@ -91,19 +105,110 @@ function spawnAgent(config, { tui = null, onConnectionState = null } = {}) {
|
|
|
91
105
|
return child;
|
|
92
106
|
}
|
|
93
107
|
|
|
108
|
+
function openDesktopOnChild(child, accountId) {
|
|
109
|
+
const failure = code => Object.assign(new Error(code), { code });
|
|
110
|
+
if (!child?.connected) return Promise.reject(failure("full_unavailable"));
|
|
111
|
+
return new Promise((resolve, reject) => {
|
|
112
|
+
const requestId = randomUUID();
|
|
113
|
+
let settled = false;
|
|
114
|
+
const finish = (error, result) => {
|
|
115
|
+
if (settled) return;
|
|
116
|
+
settled = true; clearTimeout(timer);
|
|
117
|
+
child.removeListener("message", onMessage);
|
|
118
|
+
child.removeListener("exit", onExit);
|
|
119
|
+
child.removeListener("disconnect", onExit);
|
|
120
|
+
child.removeListener("error", onExit);
|
|
121
|
+
if (error) reject(error); else resolve(result);
|
|
122
|
+
};
|
|
123
|
+
const onExit = () => finish(failure("full_unavailable"));
|
|
124
|
+
const onMessage = message => {
|
|
125
|
+
if (message?.type !== "chat-relay-full-desktop" || message.kind !== "result" || message.requestId !== requestId) return;
|
|
126
|
+
if (message.ok === true && typeof message.alreadyOpen === "boolean")
|
|
127
|
+
finish(null, { alreadyOpen: message.alreadyOpen });
|
|
128
|
+
else finish(failure(typeof message.error === "string" && /^full_[a-z0-9_]+$/.test(message.error)
|
|
129
|
+
? message.error : "full_desktop_reopen_unavailable"));
|
|
130
|
+
};
|
|
131
|
+
const timer = setTimeout(() => finish(failure("full_desktop_reopen_timeout")), 10000);
|
|
132
|
+
child.on("message", onMessage);
|
|
133
|
+
child.once("exit", onExit); child.once("disconnect", onExit); child.once("error", onExit);
|
|
134
|
+
try {
|
|
135
|
+
child.send({ type: "chat-relay-full-desktop", kind: "open", requestId, accountId },
|
|
136
|
+
error => { if (error) onExit(); });
|
|
137
|
+
} catch { onExit(); }
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
94
141
|
export async function remote(options = {}) {
|
|
142
|
+
const background=createBackgroundHandoff();
|
|
143
|
+
let fullSettings=null, prepareFullLaunch=null, localFullPrincipal=null;
|
|
144
|
+
if (options.full === true) {
|
|
145
|
+
try {
|
|
146
|
+
const full=await import("./full-launch.mjs");
|
|
147
|
+
fullSettings=await full.readFullReleaseSettings({headless:options.headless===true});
|
|
148
|
+
if(!full.supportedFullNode())throw Object.assign(new Error("Unsupported Node.js"),{code:"full_node_unsupported"});
|
|
149
|
+
prepareFullLaunch=full.prepareFullLaunch;
|
|
150
|
+
localFullPrincipal=full.localFullPrincipal;
|
|
151
|
+
} catch(error) {
|
|
152
|
+
console.error("Full runtime unavailable: "+(error?.code||"full_release_unconfigured")+". No Core fallback was started.");
|
|
153
|
+
return 1;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (options.headless === true && options.full !== true) {
|
|
157
|
+
console.error("--headless requires --full.");
|
|
158
|
+
return 1;
|
|
159
|
+
}
|
|
95
160
|
stopping = false;
|
|
96
|
-
let config = loadConfig();
|
|
97
|
-
|
|
161
|
+
let config = loadConfig(), authentication=null;
|
|
162
|
+
const authenticated=data=>{authentication=data;};
|
|
163
|
+
if (needsRelayLogin(config, options.relayUrl) || !(await validateConfig(config,{onVerified:authenticated}))) {
|
|
164
|
+
if(background){console.error("Background Full requires a valid saved login.");return 1;}
|
|
98
165
|
console.log("No valid Chat Relay login found. Starting sign in...");
|
|
99
166
|
config = await login(options);
|
|
100
167
|
}
|
|
101
168
|
|
|
102
|
-
let
|
|
169
|
+
let fullPrincipal;
|
|
170
|
+
if(fullSettings?.headless===false){
|
|
171
|
+
try{
|
|
172
|
+
if(!authentication&&!await validateConfig(config,{onVerified:authenticated}))throw new Error("authorization unavailable");
|
|
173
|
+
fullPrincipal=localFullPrincipal(config,authentication);
|
|
174
|
+
}catch{console.error("Full desktop unavailable: signed-in account and read grant for this agent are required.");return 1;}
|
|
175
|
+
}
|
|
176
|
+
let ownership, activeDesktopChild = null;
|
|
177
|
+
const desktopMode = fullSettings?.headless === false;
|
|
178
|
+
if(background&&!process.connected)return 1;
|
|
179
|
+
if(shouldLaunchFullBackground(options))return launchFullBackground({entrypoint:path.join(packageRoot,"bin","chat-relay.js"),args:options.launchArgs});
|
|
103
180
|
try {
|
|
104
|
-
ownership = await acquireRunnerOwnership({
|
|
181
|
+
ownership = await acquireRunnerOwnership({
|
|
182
|
+
relayUrl: config.relayUrl, agentId: config.agentId,
|
|
183
|
+
...(desktopMode ? {
|
|
184
|
+
desktopIdentity: { accountId: fullPrincipal.accountId, version: fullSettings.requestedVersion },
|
|
185
|
+
onOpenFullDesktop: () => {
|
|
186
|
+
if (stopping || !activeDesktopChild?.connected)
|
|
187
|
+
throw Object.assign(new Error("Full desktop is starting or stopping"), { code: "full_unavailable" });
|
|
188
|
+
return openDesktopOnChild(activeDesktopChild, fullPrincipal.accountId);
|
|
189
|
+
},
|
|
190
|
+
} : {}),
|
|
191
|
+
});
|
|
105
192
|
} catch (error) {
|
|
106
193
|
if (!(error instanceof RunnerAlreadyActiveError)) throw error;
|
|
194
|
+
if (desktopMode) {
|
|
195
|
+
if ((options.allowedRoot && options.allowedRoot !== config.allowedRoots) ||
|
|
196
|
+
(options.desktopEnabled !== undefined && Boolean(options.desktopEnabled) !== Boolean(config.desktopEnabled))) {
|
|
197
|
+
console.error("Full desktop reopen cannot reconfigure an active runner. Drain and stop it before changing roots or desktop settings.");
|
|
198
|
+
return 1;
|
|
199
|
+
}
|
|
200
|
+
const opened = await requestFullDesktopOpen({
|
|
201
|
+
relayUrl: config.relayUrl, agentId: config.agentId,
|
|
202
|
+
accountId: fullPrincipal.accountId, version: fullSettings.requestedVersion,
|
|
203
|
+
});
|
|
204
|
+
if (opened.ok) {
|
|
205
|
+
console.log(opened.alreadyOpen
|
|
206
|
+
? "Full desktop is already open. The existing Core runner remains connected."
|
|
207
|
+
: "Full desktop reopened on the existing Core runner.");
|
|
208
|
+
return background && !(await background.announce()) ? 1 : 0;
|
|
209
|
+
}
|
|
210
|
+
console.error("Full desktop reopen unavailable: " + opened.error + ". The existing runner was not changed.");
|
|
211
|
+
}
|
|
107
212
|
console.error(error.message);
|
|
108
213
|
return 1;
|
|
109
214
|
}
|
|
@@ -120,7 +225,7 @@ export async function remote(options = {}) {
|
|
|
120
225
|
saveConfig(config);
|
|
121
226
|
}
|
|
122
227
|
|
|
123
|
-
const useTui = shouldUseTui(options);
|
|
228
|
+
const useTui = options.full !== true && shouldUseTui(options);
|
|
124
229
|
tui = useTui ? new RemoteTui({ config, version: getAgentVersion() }) : null;
|
|
125
230
|
if (tui) {
|
|
126
231
|
tui.start();
|
|
@@ -130,31 +235,80 @@ export async function remote(options = {}) {
|
|
|
130
235
|
onStatus: (health) => tui?.setRelayHealth(health),
|
|
131
236
|
});
|
|
132
237
|
}
|
|
133
|
-
else printSummary(config);
|
|
238
|
+
else if(!desktopMode) printSummary(config);
|
|
134
239
|
|
|
135
240
|
while (!stopping) {
|
|
241
|
+
if(background&&!background.acknowledged&&!process.connected){supervisorCode=1;break;}
|
|
242
|
+
let fullBootstrap=null;
|
|
243
|
+
if(fullSettings){
|
|
244
|
+
try{fullBootstrap=await prepareFullLaunch({settings:fullSettings,config,principal:fullPrincipal});}
|
|
245
|
+
catch(error){console.error("Full runtime unavailable: "+(error?.code||"full_startup_failed")+". No Core fallback was started.");supervisorCode=1;break;}
|
|
246
|
+
}
|
|
247
|
+
if(background&&!background.acknowledged&&!process.connected){supervisorCode=1;break;}
|
|
136
248
|
const child = spawnAgent(config, {
|
|
137
|
-
tui,
|
|
249
|
+
tui, fullBootstrap,
|
|
250
|
+
authorizeDesktop:async()=>{
|
|
251
|
+
const {response,data}=await requestJson(config.relayUrl+"/auth/me",{headers:{authorization:"Bearer "+config.userToken}},7500);
|
|
252
|
+
if(!response.ok)throw new Error("authorization unavailable");
|
|
253
|
+
return localFullPrincipal(config,data);
|
|
254
|
+
},
|
|
138
255
|
onConnectionState: (state) => {
|
|
139
256
|
if (state === "connected") stopRelayHealthMonitor?.checkNow?.();
|
|
140
257
|
},
|
|
141
258
|
});
|
|
142
259
|
|
|
260
|
+
activeDesktopChild = desktopMode ? child : null;
|
|
261
|
+
let forceStopTimer;
|
|
143
262
|
const stop = () => {
|
|
263
|
+
if(stopping)return;
|
|
144
264
|
stopping = true;
|
|
145
|
-
|
|
265
|
+
if(fullBootstrap&&child.connected){
|
|
266
|
+
// Give the supervised Full host a chance to commit and release its
|
|
267
|
+
// store before Windows tree termination. Timeout is not proof of recovery.
|
|
268
|
+
forceStopTimer=setTimeout(()=>terminateChildTree(child),20000);
|
|
269
|
+
try{child.send({type:"chat-relay-runner",command:"shutdown"},error=>{if(error){clearTimeout(forceStopTimer);terminateChildTree(child);}});}
|
|
270
|
+
catch{clearTimeout(forceStopTimer);terminateChildTree(child);}
|
|
271
|
+
}else terminateChildTree(child);
|
|
272
|
+
};
|
|
273
|
+
const backgroundReady=message=>{
|
|
274
|
+
if(message?.type==="chat-relay-runner"&&message.event==="full-gui-ready"&&background&&!background.acknowledged){
|
|
275
|
+
void background.announce().then(ok=>{if(!ok)stop();});
|
|
276
|
+
}
|
|
146
277
|
};
|
|
278
|
+
if(background&&!background.acknowledged)child.on("message",backgroundReady);
|
|
279
|
+
const parentDisconnected=()=>{if(!background?.acknowledged)stop();};
|
|
147
280
|
process.once("SIGINT", stop);
|
|
148
281
|
process.once("SIGTERM", stop);
|
|
282
|
+
// A managed Full runner may have its own supervisor IPC. A normal
|
|
283
|
+
// parent disconnect requests the same bounded graceful shutdown.
|
|
284
|
+
if(fullBootstrap&&typeof process.send==="function"&&!background?.acknowledged){
|
|
285
|
+
process.once("disconnect",parentDisconnected);
|
|
286
|
+
if(!process.connected)parentDisconnected();
|
|
287
|
+
}
|
|
149
288
|
|
|
150
289
|
const result = await new Promise((resolve) => {
|
|
151
290
|
child.once("exit", (code, signal) => resolve({ code, signal }));
|
|
291
|
+
child.once("error", () => resolve({code:fullBootstrap?FULL_STARTUP_EXIT_CODE:1,signal:null}));
|
|
152
292
|
});
|
|
293
|
+
clearTimeout(forceStopTimer);
|
|
294
|
+
if (activeDesktopChild === child) activeDesktopChild = null;
|
|
153
295
|
|
|
154
296
|
process.removeListener("SIGINT", stop);
|
|
155
297
|
process.removeListener("SIGTERM", stop);
|
|
156
|
-
|
|
298
|
+
process.removeListener("disconnect", parentDisconnected);
|
|
299
|
+
child.removeListener("message",backgroundReady);
|
|
300
|
+
if (stopping) {
|
|
301
|
+
if(fullBootstrap && result.code !== 0)supervisorCode=1;
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
157
304
|
|
|
305
|
+
if (fullBootstrap && result.code === 0) { stopping=true; break; }
|
|
306
|
+
if (result.code === FULL_STARTUP_EXIT_CODE) {
|
|
307
|
+
stopping=true;
|
|
308
|
+
supervisorCode=1;
|
|
309
|
+
console.error("Full agent failed or its shutdown could not be confirmed. No automatic Lite fallback or datastore recovery.");
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
158
312
|
if (result.code === 2) {
|
|
159
313
|
stopping = true;
|
|
160
314
|
console.error("Agent authorization is no longer valid. Run chat-relay login --force, then chat-relay remote.");
|
|
@@ -185,6 +339,7 @@ export async function remote(options = {}) {
|
|
|
185
339
|
}
|
|
186
340
|
}
|
|
187
341
|
} finally {
|
|
342
|
+
activeDesktopChild = null;
|
|
188
343
|
try { stopRelayHealthMonitor?.(); } catch {}
|
|
189
344
|
try { tui?.stop?.(); } catch {}
|
|
190
345
|
await ownership.release();
|
package/cli/runner-ownership.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
1
|
+
import { createHash, randomUUID, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import net from "node:net";
|
|
4
4
|
import os from "node:os";
|
|
@@ -8,6 +8,10 @@ import { configDir } from "./config.mjs";
|
|
|
8
8
|
|
|
9
9
|
const DEFAULT_STARTUP_GRACE_MS = 1_500;
|
|
10
10
|
const DEFAULT_PROBE_TIMEOUT_MS = 400;
|
|
11
|
+
const CONTROL_MAX_BYTES = 2048;
|
|
12
|
+
const accountIdPattern = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
13
|
+
const versionPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[A-Za-z0-9.-]+)?$/;
|
|
14
|
+
const controlFailure = error => ({ ok: false, error });
|
|
11
15
|
|
|
12
16
|
export class RunnerAlreadyActiveError extends Error {
|
|
13
17
|
constructor({ agentId, relayUrl, pid }) {
|
|
@@ -84,6 +88,52 @@ function probeOwner(metadata, timeoutMs) {
|
|
|
84
88
|
});
|
|
85
89
|
}
|
|
86
90
|
|
|
91
|
+
/** Explicit same-owner GUI reopen. No takeover, credentials or Core spawn. */
|
|
92
|
+
export async function requestFullDesktopOpen({
|
|
93
|
+
relayUrl, agentId, accountId, version, directory = configDir(), timeoutMs = 11000,
|
|
94
|
+
} = {}) {
|
|
95
|
+
if (!relayUrl || !agentId || typeof accountId !== "string" || !accountIdPattern.test(accountId) ||
|
|
96
|
+
typeof version !== "string" || version.length > 64 || !versionPattern.test(version) ||
|
|
97
|
+
!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 15000)
|
|
98
|
+
return controlFailure("full_invalid_desktop_reopen");
|
|
99
|
+
const key = ownershipKey(relayUrl, agentId);
|
|
100
|
+
const metadata = readMetadata(path.join(directory, "runner-locks", key));
|
|
101
|
+
if (typeof metadata?.token !== "string" || !/^[a-f0-9-]{36}$/.test(metadata.token) ||
|
|
102
|
+
typeof metadata.endpoint !== "string" || !/^[a-f0-9]{64}$/.test(metadata.controlToken ?? "") ||
|
|
103
|
+
metadata.agentId !== String(agentId) || metadata.relayUrl !== normalizeRelayUrl(relayUrl) ||
|
|
104
|
+
metadata.endpoint !== socketEndpoint(key, metadata.token))
|
|
105
|
+
return controlFailure("full_desktop_reopen_unavailable");
|
|
106
|
+
return new Promise(resolve => {
|
|
107
|
+
let settled = false, response = "";
|
|
108
|
+
const socket = net.createConnection(metadata.endpoint);
|
|
109
|
+
const finish = value => {
|
|
110
|
+
if (settled) return;
|
|
111
|
+
settled = true; clearTimeout(timer); socket.destroy(); resolve(value);
|
|
112
|
+
};
|
|
113
|
+
const timer = setTimeout(() => finish(controlFailure("full_desktop_reopen_timeout")), timeoutMs);
|
|
114
|
+
socket.setEncoding("utf8");
|
|
115
|
+
socket.once("connect", () => socket.write(JSON.stringify({
|
|
116
|
+
version: 1, command: "full.gui.open", controlToken: metadata.controlToken,
|
|
117
|
+
accountId, artifactVersion: version,
|
|
118
|
+
}) + "\n"));
|
|
119
|
+
socket.on("data", chunk => {
|
|
120
|
+
response += chunk;
|
|
121
|
+
if (Buffer.byteLength(response) > CONTROL_MAX_BYTES) return finish(controlFailure("full_invalid_desktop_reopen"));
|
|
122
|
+
if (!response.includes("\n")) return;
|
|
123
|
+
try {
|
|
124
|
+
const result = JSON.parse(response.trim());
|
|
125
|
+
if (result?.ok === true && typeof result.alreadyOpen === "boolean")
|
|
126
|
+
return finish({ ok: true, alreadyOpen: result.alreadyOpen });
|
|
127
|
+
if (result?.ok === false && /^full_[a-z0-9_]+$/.test(result.error ?? ""))
|
|
128
|
+
return finish(controlFailure(result.error));
|
|
129
|
+
} catch {}
|
|
130
|
+
finish(controlFailure("full_desktop_reopen_unavailable"));
|
|
131
|
+
});
|
|
132
|
+
socket.once("error", () => finish(controlFailure("full_desktop_reopen_unavailable")));
|
|
133
|
+
socket.once("end", () => finish(controlFailure("full_desktop_reopen_unavailable")));
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
87
137
|
function listen(server, endpoint) {
|
|
88
138
|
return new Promise((resolve, reject) => {
|
|
89
139
|
const onError = (error) => reject(error);
|
|
@@ -129,8 +179,17 @@ export async function acquireRunnerOwnership({
|
|
|
129
179
|
directory = configDir(),
|
|
130
180
|
startupGraceMs = DEFAULT_STARTUP_GRACE_MS,
|
|
131
181
|
probeTimeoutMs = DEFAULT_PROBE_TIMEOUT_MS,
|
|
182
|
+
desktopIdentity = null,
|
|
183
|
+
onOpenFullDesktop = null,
|
|
132
184
|
} = {}) {
|
|
133
185
|
if (!relayUrl || !agentId) throw new Error("Runner ownership requires relayUrl and agentId");
|
|
186
|
+
const desktop = onOpenFullDesktop === null ? null : {
|
|
187
|
+
accountId: desktopIdentity?.accountId, version: desktopIdentity?.version,
|
|
188
|
+
};
|
|
189
|
+
if (desktop && (typeof onOpenFullDesktop !== "function" || typeof desktop.accountId !== "string" ||
|
|
190
|
+
!accountIdPattern.test(desktop.accountId) || typeof desktop.version !== "string" ||
|
|
191
|
+
desktop.version.length > 64 || !versionPattern.test(desktop.version)))
|
|
192
|
+
throw new Error("Invalid desktop runner identity");
|
|
134
193
|
|
|
135
194
|
const key = ownershipKey(relayUrl, agentId);
|
|
136
195
|
const locksDir = path.join(directory, "runner-locks");
|
|
@@ -160,19 +219,71 @@ export async function acquireRunnerOwnership({
|
|
|
160
219
|
}
|
|
161
220
|
|
|
162
221
|
const token = randomUUID();
|
|
222
|
+
const controlToken = desktop ? randomBytes(32).toString("hex") : null;
|
|
163
223
|
const endpoint = socketEndpoint(key, token);
|
|
164
224
|
const metadata = {
|
|
165
225
|
version: 1,
|
|
166
226
|
pid: process.pid,
|
|
167
227
|
token,
|
|
228
|
+
...(controlToken ? { controlToken } : {}),
|
|
168
229
|
endpoint,
|
|
169
230
|
relayUrl: normalizeRelayUrl(relayUrl),
|
|
170
231
|
agentId: String(agentId),
|
|
171
232
|
createdAt: new Date().toISOString(),
|
|
172
233
|
};
|
|
173
|
-
const
|
|
234
|
+
const sockets = new Set();
|
|
235
|
+
let opening = null, releasing = false, controlWaiters = 0;
|
|
236
|
+
const server = net.createServer(socket => {
|
|
237
|
+
sockets.add(socket);
|
|
238
|
+
socket.once("close", () => sockets.delete(socket));
|
|
239
|
+
socket.on("error", () => {});
|
|
240
|
+
socket.setTimeout(1500, () => socket.destroy());
|
|
174
241
|
socket.setEncoding("utf8");
|
|
175
|
-
|
|
242
|
+
let input = "", handled = false;
|
|
243
|
+
socket.on("data", chunk => {
|
|
244
|
+
if (handled) return;
|
|
245
|
+
input += chunk;
|
|
246
|
+
if (Buffer.byteLength(input) > CONTROL_MAX_BYTES) {
|
|
247
|
+
handled = true; socket.end(JSON.stringify(controlFailure("full_invalid_desktop_reopen")) + "\n"); return;
|
|
248
|
+
}
|
|
249
|
+
if (!input.includes("\n")) return;
|
|
250
|
+
handled = true;
|
|
251
|
+
if (input.trim() === "PING") { socket.end(`OWNER ${token}\n`); return; }
|
|
252
|
+
const reply = value => { if (!socket.destroyed) socket.end(JSON.stringify(value) + "\n"); };
|
|
253
|
+
let request;
|
|
254
|
+
try { request = JSON.parse(input.trim()); } catch { reply(controlFailure("full_invalid_desktop_reopen")); return; }
|
|
255
|
+
const allowed = ["version", "command", "controlToken", "accountId", "artifactVersion"];
|
|
256
|
+
if (releasing || !desktop || !request || typeof request !== "object" || Array.isArray(request) ||
|
|
257
|
+
Object.keys(request).length !== allowed.length || Object.keys(request).some(key => !allowed.includes(key)) ||
|
|
258
|
+
request.version !== 1 || request.command !== "full.gui.open" ||
|
|
259
|
+
typeof request.controlToken !== "string" || !/^[a-f0-9]{64}$/.test(request.controlToken) ||
|
|
260
|
+
!timingSafeEqual(Buffer.from(request.controlToken), Buffer.from(controlToken)) ||
|
|
261
|
+
request.accountId !== desktop.accountId) {
|
|
262
|
+
reply(controlFailure("full_desktop_reopen_denied")); return;
|
|
263
|
+
}
|
|
264
|
+
if (request.artifactVersion !== desktop.version) {
|
|
265
|
+
reply(controlFailure("full_active_version_mismatch")); return;
|
|
266
|
+
}
|
|
267
|
+
if (controlWaiters >= 8) { reply(controlFailure("full_desktop_reopen_busy")); return; }
|
|
268
|
+
controlWaiters++;
|
|
269
|
+
socket.setTimeout(12000);
|
|
270
|
+
// Concurrent explicit reopen requests join one action; never start a
|
|
271
|
+
// second Core or permit the caller to change roots, version or scopes.
|
|
272
|
+
if (!opening) {
|
|
273
|
+
const pending = Promise.resolve().then(() => {
|
|
274
|
+
if (releasing) throw new Error("runner closing");
|
|
275
|
+
return onOpenFullDesktop();
|
|
276
|
+
});
|
|
277
|
+
opening = pending;
|
|
278
|
+
void pending.finally(() => { if (opening === pending) opening = null; }).catch(() => {});
|
|
279
|
+
}
|
|
280
|
+
void opening.then(result => {
|
|
281
|
+
if (typeof result?.alreadyOpen !== "boolean") throw new Error("invalid desktop response");
|
|
282
|
+
reply({ ok: true, alreadyOpen: result.alreadyOpen });
|
|
283
|
+
}).catch(error => reply(controlFailure(
|
|
284
|
+
typeof error?.code === "string" && /^full_[a-z0-9_]+$/.test(error.code)
|
|
285
|
+
? error.code : "full_desktop_reopen_unavailable"))).finally(() => { controlWaiters--; }).catch(() => {});
|
|
286
|
+
});
|
|
176
287
|
});
|
|
177
288
|
|
|
178
289
|
try {
|
|
@@ -200,6 +311,8 @@ export async function acquireRunnerOwnership({
|
|
|
200
311
|
async release() {
|
|
201
312
|
if (released) return;
|
|
202
313
|
released = true;
|
|
314
|
+
releasing = true;
|
|
315
|
+
for (const socket of sockets) socket.destroy();
|
|
203
316
|
await close(server);
|
|
204
317
|
removeSocket(endpoint);
|
|
205
318
|
if (readMetadata(lockDir)?.token === token) fs.rmSync(lockDir, { recursive: true, force: true });
|
package/cli/self-update.mjs
CHANGED
|
@@ -30,7 +30,7 @@ export function createUpgradeRelaunchSpec(options = {}, {
|
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
const args = uiArgs(options);
|
|
33
|
+
const args = [...(options.full === true ? ["--full", ...(options.headless === true ? ["--headless"] : [])] : []), ...uiArgs(options)];
|
|
34
34
|
const childEnv = {
|
|
35
35
|
...env,
|
|
36
36
|
[UPGRADE_LOOP_GUARD_ENV]: String(now + UPGRADE_LOOP_GUARD_MS),
|
package/cli/tui.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { humanizeToolCall } from "../agent/toolcall-summary.mjs";
|
|
2
|
+
import { activityCategory, activityIcon } from "../agent/toolcall-context.mjs";
|
|
2
3
|
|
|
3
4
|
const ESC = "\x1b[";
|
|
4
5
|
const RESET = "\x1b[0m";
|
|
@@ -284,6 +285,7 @@ function normalizeRelay(value) {
|
|
|
284
285
|
}
|
|
285
286
|
|
|
286
287
|
export function shouldUseTui(options = {}, stdout = process.stdout) {
|
|
288
|
+
if (options.full === true) return false;
|
|
287
289
|
if (options.tuiEnabled === false) return false;
|
|
288
290
|
if (options.tuiEnabled === true) return true;
|
|
289
291
|
return Boolean(stdout?.isTTY);
|
|
@@ -317,26 +319,6 @@ function cellPad(value, width) {
|
|
|
317
319
|
return clipped + " ".repeat(Math.max(0, width - terminalCellWidth(clipped)));
|
|
318
320
|
}
|
|
319
321
|
|
|
320
|
-
function activityCategory(item) {
|
|
321
|
-
if (item.category) return String(item.category);
|
|
322
|
-
const action = String(item.action || "");
|
|
323
|
-
if (action.startsWith("fs.")) return "Filesystem";
|
|
324
|
-
if (action.startsWith("terminal.")) return "Terminal";
|
|
325
|
-
if (action.startsWith("desktop.")) return "Desktop";
|
|
326
|
-
if (action.startsWith("learn")) return "Learn";
|
|
327
|
-
return "Agent";
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
function activityIcon(item) {
|
|
331
|
-
const action = String(item.action || "").toLowerCase();
|
|
332
|
-
const title = String(item.operation || item.summary || "").toLowerCase();
|
|
333
|
-
if (/search/.test(action) || /^(start|search)\b/.test(title)) return "🔎";
|
|
334
|
-
if (/(^|\.)(read|readmany|getcontent)(_|$|\.)/.test(action) || /^read\b/.test(title)) return "📖";
|
|
335
|
-
if (/(^|\.)(write|edit|move|mkdir|delete)(_|$|\.)/.test(action) || /^(write|edit|create|delete|move)\b/.test(title)) return "✏️";
|
|
336
|
-
if (activityCategory(item) === "Terminal") return "📟";
|
|
337
|
-
if (activityCategory(item) === "Filesystem") return "📁";
|
|
338
|
-
return "";
|
|
339
|
-
}
|
|
340
322
|
|
|
341
323
|
function shortActivityDetail(value, project) {
|
|
342
324
|
const normalized = String(value || "").replace(/\\/g, "/").replace(/\s+/g, " ").trim();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anusornneal/chat-relay",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.1",
|
|
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": {
|
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
"files": [
|
|
10
10
|
"bin/",
|
|
11
11
|
"cli/",
|
|
12
|
+
"cli/full-release-default.json",
|
|
12
13
|
"agent/",
|
|
14
|
+
"packages/full-contracts/",
|
|
13
15
|
"README.md"
|
|
14
16
|
],
|
|
15
17
|
"engines": {
|
|
@@ -43,14 +45,14 @@
|
|
|
43
45
|
"prepublishOnly": "npm run verify:publish",
|
|
44
46
|
"test:oauth": "node test/oauth-smoke.mjs",
|
|
45
47
|
"test:usage": "node test/usage-smoke.mjs",
|
|
46
|
-
"test:usage-storage": "node test/usage-storage.test.mjs && node --test test/usage-batch.test.mjs",
|
|
48
|
+
"test:usage-storage": "node test/usage-storage.test.mjs && node --test test/usage-batch.test.mjs test/usage-fourhour-profile.test.mjs",
|
|
47
49
|
"test:no-quota": "node test/no-quota-regression.test.mjs",
|
|
48
50
|
"test:admin-api": "node test/admin-api-smoke.mjs",
|
|
49
51
|
"test:admin-auth": "node test/admin-auth-smoke.mjs",
|
|
50
|
-
"test:dashboard": "node test/dashboard-smoke.mjs",
|
|
52
|
+
"test:dashboard": "node --test test/dashboard-ui-contract.test.mjs test/dashboard-theme.test.mjs && node test/dashboard-smoke.mjs",
|
|
51
53
|
"test:dashboard-timers": "node test/dashboard-timers.test.mjs",
|
|
52
54
|
"test:ops": "node test/ops-smoke.mjs",
|
|
53
|
-
"test:desktop": "node --test test/agent-desktop-adapter.test.mjs && node test/mcp-desktop-smoke.mjs",
|
|
55
|
+
"test:desktop": "node --test test/agent-desktop-adapter.test.mjs test/windows-desktop-runner.test.mjs && node test/mcp-desktop-smoke.mjs",
|
|
54
56
|
"test:device-management": "node test/device-management-smoke.mjs",
|
|
55
57
|
"test:submission": "node test/submission-smoke.mjs",
|
|
56
58
|
"test:agent-state": "node --experimental-strip-types --test test/agent-state.test.mjs test/reconnect-chaos.test.mjs",
|
|
@@ -61,9 +63,10 @@
|
|
|
61
63
|
"test:soak": "node test/soak-smoke.mjs",
|
|
62
64
|
"test:file-search": "node --test test/file-search.test.mjs test/search-preview.test.mjs test/adaptive-tools.test.mjs",
|
|
63
65
|
"bench:search-preview:e2e": "node test/search-preview-e2e-benchmark.mjs",
|
|
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",
|
|
66
|
+
"test:hardening": "npm run test:file-search && npm run test:batch-contract && npm run test:tool-efficiency && 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
67
|
"test:batch-contract": "node --test test/tool-contract-batch.test.mjs",
|
|
66
|
-
"test:
|
|
68
|
+
"test:tool-efficiency": "node --test --test-concurrency=1 test/tool-efficiency.test.mjs test/tool-efficiency-mcp.test.mjs",
|
|
69
|
+
"test:terminal-perf": "node --test test/terminal-perf.test.mjs test/terminal-wait.test.mjs test/terminal-retention.test.mjs test/terminal-capture-drain.test.mjs",
|
|
67
70
|
"test:tool-guidance": "node --test test/tool-error-guidance.test.mjs",
|
|
68
71
|
"verify:review": "node scripts/verify-review-artifacts.mjs",
|
|
69
72
|
"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",
|