luxray-agent 0.0.0-stage → 0.1.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 +76 -2
- package/dist/bin/luxray-agent.d.ts +1 -0
- package/dist/bin/luxray-agent.js +9289 -0
- package/dist/bin/luxray-agent.js.map +1 -0
- package/dist/client/agent-client.d.ts +93 -0
- package/dist/client/agent-client.js +326 -0
- package/dist/client/agent-client.js.map +1 -0
- package/dist/client/luxray-api-client.d.ts +63 -0
- package/dist/client/luxray-api-client.js +69 -0
- package/dist/client/luxray-api-client.js.map +1 -0
- package/dist/client/task-stream.d.ts +88 -0
- package/dist/client/task-stream.js +474 -0
- package/dist/client/task-stream.js.map +1 -0
- package/dist/execution/exploration-job.d.ts +90 -0
- package/dist/execution/exploration-job.js +5625 -0
- package/dist/execution/exploration-job.js.map +1 -0
- package/dist/execution/openapi-spec.d.ts +59 -0
- package/dist/execution/openapi-spec.js +4694 -0
- package/dist/execution/openapi-spec.js.map +1 -0
- package/dist/execution/task-executor.d.ts +160 -0
- package/dist/execution/task-executor.js +577 -0
- package/dist/execution/task-executor.js.map +1 -0
- package/dist/execution/test-job.d.ts +34 -0
- package/dist/execution/test-job.js +42 -0
- package/dist/execution/test-job.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +1018 -0
- package/dist/index.js.map +1 -0
- package/dist/vault/credential-vault.d.ts +30 -0
- package/dist/vault/credential-vault.js +116 -0
- package/dist/vault/credential-vault.js.map +1 -0
- package/package.json +50 -4
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { AgentPlatform, AgentArchitecture, AgentConnectedMessage, AgentHeartbeatAckMessage, AgentRevokedMessage } from '@luxray/shared';
|
|
2
|
+
|
|
3
|
+
type AgentClientState = 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'stopped' | 'revoked';
|
|
4
|
+
interface AgentClientOptions {
|
|
5
|
+
wsUrl: string;
|
|
6
|
+
agentId: string;
|
|
7
|
+
token: string;
|
|
8
|
+
version?: string;
|
|
9
|
+
platform?: AgentPlatform;
|
|
10
|
+
arch?: AgentArchitecture;
|
|
11
|
+
heartbeatIntervalMs?: number;
|
|
12
|
+
autoReconnect?: boolean;
|
|
13
|
+
initialBackoffMs?: number;
|
|
14
|
+
maxBackoffMs?: number;
|
|
15
|
+
onConnected?: (msg: AgentConnectedMessage) => void;
|
|
16
|
+
onHeartbeatAck?: (msg: AgentHeartbeatAckMessage) => void;
|
|
17
|
+
onRevoked?: (msg: AgentRevokedMessage) => void;
|
|
18
|
+
onError?: (err: Error) => void;
|
|
19
|
+
onDisconnect?: (code: number, reason: string) => void;
|
|
20
|
+
logger?: {
|
|
21
|
+
info: (...args: any[]) => void;
|
|
22
|
+
warn: (...args: any[]) => void;
|
|
23
|
+
error: (...args: any[]) => void;
|
|
24
|
+
debug: (...args: any[]) => void;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
declare class AgentClient {
|
|
28
|
+
private readonly options;
|
|
29
|
+
private ws;
|
|
30
|
+
private state;
|
|
31
|
+
private heartbeatTimer;
|
|
32
|
+
private reconnectTimer;
|
|
33
|
+
private reconnectAttempt;
|
|
34
|
+
private isIntentionallyClosed;
|
|
35
|
+
private activeHeartbeatIntervalMs;
|
|
36
|
+
private connectionId;
|
|
37
|
+
private readonly wsUrl;
|
|
38
|
+
private readonly agentId;
|
|
39
|
+
private readonly token;
|
|
40
|
+
private readonly version;
|
|
41
|
+
private readonly platform;
|
|
42
|
+
private readonly arch;
|
|
43
|
+
private readonly autoReconnect;
|
|
44
|
+
private readonly initialBackoffMs;
|
|
45
|
+
private readonly maxBackoffMs;
|
|
46
|
+
private readonly logger;
|
|
47
|
+
constructor(options: AgentClientOptions);
|
|
48
|
+
getState(): AgentClientState;
|
|
49
|
+
getConnectionId(): string | null;
|
|
50
|
+
isConnected(): boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Connects to the Luxray Cloud WebSocket server and completes the hello handshake.
|
|
53
|
+
*/
|
|
54
|
+
connect(): Promise<AgentConnectedMessage>;
|
|
55
|
+
/**
|
|
56
|
+
* Sends the agent.hello greeting to identify and authenticate this agent.
|
|
57
|
+
*/
|
|
58
|
+
private sendHello;
|
|
59
|
+
/**
|
|
60
|
+
* Handles incoming protocol messages.
|
|
61
|
+
*/
|
|
62
|
+
private handleIncomingMessage;
|
|
63
|
+
/**
|
|
64
|
+
* Starts periodic heartbeat transmission.
|
|
65
|
+
*/
|
|
66
|
+
private startHeartbeatLoop;
|
|
67
|
+
private stopHeartbeatLoop;
|
|
68
|
+
/**
|
|
69
|
+
* Transmits heartbeat metrics to the cloud.
|
|
70
|
+
*/
|
|
71
|
+
private sendHeartbeat;
|
|
72
|
+
/**
|
|
73
|
+
* Handles WebSocket closure and schedules reconnection if appropriate.
|
|
74
|
+
*/
|
|
75
|
+
private handleClose;
|
|
76
|
+
/**
|
|
77
|
+
* Exponential backoff with random jitter for reconnects.
|
|
78
|
+
*/
|
|
79
|
+
private scheduleReconnect;
|
|
80
|
+
/**
|
|
81
|
+
* Gracefully stops the agent connection and notifies cloud.
|
|
82
|
+
*
|
|
83
|
+
* Resolves once the socket has actually closed, not when closing was
|
|
84
|
+
* requested. A job's terminal frame (a completion or a failure) may still be
|
|
85
|
+
* in the send buffer, and the peer processes frames in order: waiting for the
|
|
86
|
+
* close handshake means the report was delivered before this process exits
|
|
87
|
+
* and claims the run ended.
|
|
88
|
+
*/
|
|
89
|
+
disconnect(timeoutMs?: number): Promise<void>;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export { AgentClient };
|
|
93
|
+
export type { AgentClientOptions, AgentClientState };
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// src/client/agent-client.ts
|
|
2
|
+
import { WebSocket } from "ws";
|
|
3
|
+
import * as os from "os";
|
|
4
|
+
var AgentClient = class {
|
|
5
|
+
constructor(options) {
|
|
6
|
+
this.options = options;
|
|
7
|
+
this.wsUrl = options.wsUrl;
|
|
8
|
+
this.agentId = options.agentId;
|
|
9
|
+
this.token = options.token;
|
|
10
|
+
this.version = options.version || "0.1.0";
|
|
11
|
+
this.platform = options.platform || os.platform();
|
|
12
|
+
this.arch = options.arch || os.arch();
|
|
13
|
+
this.autoReconnect = options.autoReconnect ?? true;
|
|
14
|
+
this.initialBackoffMs = options.initialBackoffMs ?? 1e3;
|
|
15
|
+
this.maxBackoffMs = options.maxBackoffMs ?? 3e4;
|
|
16
|
+
this.activeHeartbeatIntervalMs = options.heartbeatIntervalMs ?? 1e4;
|
|
17
|
+
this.logger = options.logger ?? {
|
|
18
|
+
info: (...args) => console.log("[LuxrayAgent]", ...args),
|
|
19
|
+
warn: (...args) => console.warn("[LuxrayAgent:WARN]", ...args),
|
|
20
|
+
error: (...args) => console.error("[LuxrayAgent:ERROR]", ...args),
|
|
21
|
+
debug: (...args) => {
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
options;
|
|
26
|
+
ws = null;
|
|
27
|
+
state = "idle";
|
|
28
|
+
heartbeatTimer = null;
|
|
29
|
+
reconnectTimer = null;
|
|
30
|
+
reconnectAttempt = 0;
|
|
31
|
+
isIntentionallyClosed = false;
|
|
32
|
+
activeHeartbeatIntervalMs = 1e4;
|
|
33
|
+
connectionId = null;
|
|
34
|
+
wsUrl;
|
|
35
|
+
agentId;
|
|
36
|
+
token;
|
|
37
|
+
version;
|
|
38
|
+
platform;
|
|
39
|
+
arch;
|
|
40
|
+
autoReconnect;
|
|
41
|
+
initialBackoffMs;
|
|
42
|
+
maxBackoffMs;
|
|
43
|
+
logger;
|
|
44
|
+
getState() {
|
|
45
|
+
return this.state;
|
|
46
|
+
}
|
|
47
|
+
getConnectionId() {
|
|
48
|
+
return this.connectionId;
|
|
49
|
+
}
|
|
50
|
+
isConnected() {
|
|
51
|
+
return this.state === "connected" && this.ws?.readyState === WebSocket.OPEN;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Connects to the Luxray Cloud WebSocket server and completes the hello handshake.
|
|
55
|
+
*/
|
|
56
|
+
connect() {
|
|
57
|
+
if (this.state === "revoked") {
|
|
58
|
+
return Promise.reject(new Error("Agent credentials have been revoked. Cannot connect."));
|
|
59
|
+
}
|
|
60
|
+
this.isIntentionallyClosed = false;
|
|
61
|
+
this.state = "connecting";
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
let isResolved = false;
|
|
64
|
+
try {
|
|
65
|
+
this.ws = new WebSocket(this.wsUrl);
|
|
66
|
+
} catch (err) {
|
|
67
|
+
this.state = "idle";
|
|
68
|
+
return reject(err);
|
|
69
|
+
}
|
|
70
|
+
const connectionTimeout = setTimeout(() => {
|
|
71
|
+
if (!isResolved) {
|
|
72
|
+
isResolved = true;
|
|
73
|
+
this.logger.error("Connection timed out waiting for server response.");
|
|
74
|
+
this.ws?.terminate();
|
|
75
|
+
reject(new Error("Connection timed out."));
|
|
76
|
+
}
|
|
77
|
+
}, 15e3);
|
|
78
|
+
this.ws.on("open", () => {
|
|
79
|
+
this.logger.info(`WebSocket transport opened to ${this.wsUrl}. Sending agent.hello...`);
|
|
80
|
+
this.sendHello();
|
|
81
|
+
});
|
|
82
|
+
this.ws.on("message", (raw) => {
|
|
83
|
+
try {
|
|
84
|
+
const msg = JSON.parse(raw.toString());
|
|
85
|
+
this.handleIncomingMessage(msg, (connected) => {
|
|
86
|
+
if (!isResolved) {
|
|
87
|
+
isResolved = true;
|
|
88
|
+
clearTimeout(connectionTimeout);
|
|
89
|
+
resolve(connected);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
} catch (err) {
|
|
93
|
+
this.logger.error("Failed to parse incoming WebSocket message:", err.message);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
this.ws.on("close", (code, reasonBuf) => {
|
|
97
|
+
clearTimeout(connectionTimeout);
|
|
98
|
+
const reason = reasonBuf.toString();
|
|
99
|
+
this.handleClose(code, reason);
|
|
100
|
+
if (!isResolved) {
|
|
101
|
+
isResolved = true;
|
|
102
|
+
reject(new Error(`WebSocket closed during handshake (code: ${code}, reason: ${reason})`));
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
this.ws.on("error", (err) => {
|
|
106
|
+
this.logger.error("WebSocket transport error:", err.message);
|
|
107
|
+
if (this.options.onError) {
|
|
108
|
+
this.options.onError(err);
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Sends the agent.hello greeting to identify and authenticate this agent.
|
|
115
|
+
*/
|
|
116
|
+
sendHello() {
|
|
117
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
|
|
118
|
+
const helloPayload = {
|
|
119
|
+
type: "agent.hello",
|
|
120
|
+
version: "1.0",
|
|
121
|
+
agentId: this.agentId,
|
|
122
|
+
token: this.token,
|
|
123
|
+
agentVersion: this.version,
|
|
124
|
+
platform: this.platform,
|
|
125
|
+
arch: this.arch,
|
|
126
|
+
timestamp: Date.now()
|
|
127
|
+
};
|
|
128
|
+
this.ws.send(JSON.stringify(helloPayload));
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Handles incoming protocol messages.
|
|
132
|
+
*/
|
|
133
|
+
handleIncomingMessage(msg, onConnectedFirstTime) {
|
|
134
|
+
switch (msg.type) {
|
|
135
|
+
case "agent.connected": {
|
|
136
|
+
const connectedMsg = msg;
|
|
137
|
+
this.state = "connected";
|
|
138
|
+
this.reconnectAttempt = 0;
|
|
139
|
+
this.connectionId = connectedMsg.connectionId;
|
|
140
|
+
this.activeHeartbeatIntervalMs = connectedMsg.heartbeatIntervalMs || 1e4;
|
|
141
|
+
this.logger.info(
|
|
142
|
+
`Successfully connected & authenticated with Luxray Cloud! Connection ID: ${connectedMsg.connectionId}`
|
|
143
|
+
);
|
|
144
|
+
this.startHeartbeatLoop();
|
|
145
|
+
onConnectedFirstTime(connectedMsg);
|
|
146
|
+
if (this.options.onConnected) {
|
|
147
|
+
this.options.onConnected(connectedMsg);
|
|
148
|
+
}
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
case "agent.heartbeat.ack": {
|
|
152
|
+
const ackMsg = msg;
|
|
153
|
+
this.logger.debug(`Heartbeat acknowledged by server (ack: ${ackMsg.timestamp})`);
|
|
154
|
+
if (this.options.onHeartbeatAck) {
|
|
155
|
+
this.options.onHeartbeatAck(ackMsg);
|
|
156
|
+
}
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
case "agent.revoked": {
|
|
160
|
+
const revokedMsg = msg;
|
|
161
|
+
this.state = "revoked";
|
|
162
|
+
this.isIntentionallyClosed = true;
|
|
163
|
+
this.logger.error(`CRITICAL: Agent credentials have been revoked. Reason: ${revokedMsg.reason}`);
|
|
164
|
+
this.stopHeartbeatLoop();
|
|
165
|
+
if (this.options.onRevoked) {
|
|
166
|
+
this.options.onRevoked(revokedMsg);
|
|
167
|
+
}
|
|
168
|
+
this.ws?.close(4401, "Agent Revoked");
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
case "agent.error": {
|
|
172
|
+
const errMsg = msg;
|
|
173
|
+
this.logger.error(`Server error [${errMsg.code}]: ${errMsg.message}`);
|
|
174
|
+
if (errMsg.fatal) {
|
|
175
|
+
this.logger.error("Fatal server error encountered. Closing connection.");
|
|
176
|
+
this.ws?.close(4e3, errMsg.message);
|
|
177
|
+
}
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
default:
|
|
181
|
+
this.logger.debug("Unhandled message type:", msg.type);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Starts periodic heartbeat transmission.
|
|
186
|
+
*/
|
|
187
|
+
startHeartbeatLoop() {
|
|
188
|
+
this.stopHeartbeatLoop();
|
|
189
|
+
this.heartbeatTimer = setInterval(() => {
|
|
190
|
+
this.sendHeartbeat();
|
|
191
|
+
}, this.activeHeartbeatIntervalMs);
|
|
192
|
+
}
|
|
193
|
+
stopHeartbeatLoop() {
|
|
194
|
+
if (this.heartbeatTimer) {
|
|
195
|
+
clearInterval(this.heartbeatTimer);
|
|
196
|
+
this.heartbeatTimer = null;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Transmits heartbeat metrics to the cloud.
|
|
201
|
+
*/
|
|
202
|
+
sendHeartbeat() {
|
|
203
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
|
|
204
|
+
const memoryMb = Math.round(process.memoryUsage().rss / (1024 * 1024));
|
|
205
|
+
const uptime = Math.round(process.uptime());
|
|
206
|
+
const heartbeatPayload = {
|
|
207
|
+
type: "agent.heartbeat",
|
|
208
|
+
version: "1.0",
|
|
209
|
+
agentId: this.agentId,
|
|
210
|
+
memoryUsageMb: memoryMb,
|
|
211
|
+
uptimeSeconds: uptime,
|
|
212
|
+
timestamp: Date.now()
|
|
213
|
+
};
|
|
214
|
+
try {
|
|
215
|
+
this.ws.send(JSON.stringify(heartbeatPayload));
|
|
216
|
+
this.logger.debug(`Heartbeat sent: memory=${memoryMb}MB, uptime=${uptime}s`);
|
|
217
|
+
} catch (err) {
|
|
218
|
+
this.logger.warn("Failed to transmit heartbeat:", err.message);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Handles WebSocket closure and schedules reconnection if appropriate.
|
|
223
|
+
*/
|
|
224
|
+
handleClose(code, reason) {
|
|
225
|
+
this.stopHeartbeatLoop();
|
|
226
|
+
this.connectionId = null;
|
|
227
|
+
if (this.options.onDisconnect) {
|
|
228
|
+
this.options.onDisconnect(code, reason);
|
|
229
|
+
}
|
|
230
|
+
if (code === 4401 || this.state === "revoked") {
|
|
231
|
+
this.state = "revoked";
|
|
232
|
+
this.logger.error("Connection closed: Agent credentials revoked. Will NOT reconnect.");
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (this.isIntentionallyClosed) {
|
|
236
|
+
this.state = "stopped";
|
|
237
|
+
this.logger.info("Agent stopped gracefully.");
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (code === 4009) {
|
|
241
|
+
this.logger.warn("Another instance of this agent connected elsewhere. Backing off.");
|
|
242
|
+
}
|
|
243
|
+
if (!this.autoReconnect) {
|
|
244
|
+
this.state = "idle";
|
|
245
|
+
this.logger.info(`Connection closed (code: ${code}, reason: ${reason}). Auto-reconnect is disabled.`);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
this.scheduleReconnect();
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Exponential backoff with random jitter for reconnects.
|
|
252
|
+
*/
|
|
253
|
+
scheduleReconnect() {
|
|
254
|
+
this.state = "reconnecting";
|
|
255
|
+
this.reconnectAttempt++;
|
|
256
|
+
const exponential = this.initialBackoffMs * Math.pow(1.5, Math.min(this.reconnectAttempt, 10));
|
|
257
|
+
const jitter = Math.floor(Math.random() * 1e3);
|
|
258
|
+
const delay = Math.min(exponential + jitter, this.maxBackoffMs);
|
|
259
|
+
this.logger.warn(
|
|
260
|
+
`Connection lost. Reconnecting in ${(delay / 1e3).toFixed(1)}s (attempt ${this.reconnectAttempt})...`
|
|
261
|
+
);
|
|
262
|
+
if (this.reconnectTimer) {
|
|
263
|
+
clearTimeout(this.reconnectTimer);
|
|
264
|
+
}
|
|
265
|
+
this.reconnectTimer = setTimeout(async () => {
|
|
266
|
+
try {
|
|
267
|
+
await this.connect();
|
|
268
|
+
} catch (err) {
|
|
269
|
+
this.logger.warn("Reconnect attempt failed:", err.message);
|
|
270
|
+
}
|
|
271
|
+
}, delay);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Gracefully stops the agent connection and notifies cloud.
|
|
275
|
+
*
|
|
276
|
+
* Resolves once the socket has actually closed, not when closing was
|
|
277
|
+
* requested. A job's terminal frame (a completion or a failure) may still be
|
|
278
|
+
* in the send buffer, and the peer processes frames in order: waiting for the
|
|
279
|
+
* close handshake means the report was delivered before this process exits
|
|
280
|
+
* and claims the run ended.
|
|
281
|
+
*/
|
|
282
|
+
async disconnect(timeoutMs = 1e3) {
|
|
283
|
+
this.isIntentionallyClosed = true;
|
|
284
|
+
this.state = "stopped";
|
|
285
|
+
if (this.reconnectTimer) {
|
|
286
|
+
clearTimeout(this.reconnectTimer);
|
|
287
|
+
this.reconnectTimer = null;
|
|
288
|
+
}
|
|
289
|
+
this.stopHeartbeatLoop();
|
|
290
|
+
const ws = this.ws;
|
|
291
|
+
this.ws = null;
|
|
292
|
+
if (!ws) return;
|
|
293
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
294
|
+
const goodbyePayload = {
|
|
295
|
+
type: "agent.status",
|
|
296
|
+
version: "1.0",
|
|
297
|
+
agentId: this.agentId,
|
|
298
|
+
status: "DISCONNECTED",
|
|
299
|
+
timestamp: Date.now()
|
|
300
|
+
};
|
|
301
|
+
try {
|
|
302
|
+
ws.send(JSON.stringify(goodbyePayload));
|
|
303
|
+
} catch {
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (ws.readyState === WebSocket.CLOSED) return;
|
|
307
|
+
await new Promise((resolve) => {
|
|
308
|
+
const timer = setTimeout(resolve, timeoutMs);
|
|
309
|
+
timer.unref?.();
|
|
310
|
+
ws.once("close", () => {
|
|
311
|
+
clearTimeout(timer);
|
|
312
|
+
resolve();
|
|
313
|
+
});
|
|
314
|
+
try {
|
|
315
|
+
ws.close(1e3, "Agent Stopped Manually");
|
|
316
|
+
} catch {
|
|
317
|
+
clearTimeout(timer);
|
|
318
|
+
resolve();
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
export {
|
|
324
|
+
AgentClient
|
|
325
|
+
};
|
|
326
|
+
//# sourceMappingURL=agent-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/client/agent-client.ts"],"sourcesContent":["import { WebSocket } from 'ws';\nimport * as os from 'node:os';\nimport type {\n AgentPlatform,\n AgentArchitecture,\n AgentProtocolMessage,\n AgentConnectedMessage,\n AgentHeartbeatAckMessage,\n AgentErrorMessage,\n AgentRevokedMessage,\n AgentStatusMessage,\n} from '@luxray/shared';\n\nexport type AgentClientState =\n | 'idle'\n | 'connecting'\n | 'connected'\n | 'reconnecting'\n | 'stopped'\n | 'revoked';\n\nexport interface AgentClientOptions {\n wsUrl: string;\n agentId: string;\n token: string;\n version?: string;\n platform?: AgentPlatform;\n arch?: AgentArchitecture;\n heartbeatIntervalMs?: number;\n autoReconnect?: boolean;\n initialBackoffMs?: number;\n maxBackoffMs?: number;\n onConnected?: (msg: AgentConnectedMessage) => void;\n onHeartbeatAck?: (msg: AgentHeartbeatAckMessage) => void;\n onRevoked?: (msg: AgentRevokedMessage) => void;\n onError?: (err: Error) => void;\n onDisconnect?: (code: number, reason: string) => void;\n logger?: {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n };\n}\n\nexport class AgentClient {\n private ws: WebSocket | null = null;\n private state: AgentClientState = 'idle';\n private heartbeatTimer: NodeJS.Timeout | null = null;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private reconnectAttempt = 0;\n private isIntentionallyClosed = false;\n private activeHeartbeatIntervalMs = 10000;\n private connectionId: string | null = null;\n\n private readonly wsUrl: string;\n private readonly agentId: string;\n private readonly token: string;\n private readonly version: string;\n private readonly platform: AgentPlatform;\n private readonly arch: AgentArchitecture;\n private readonly autoReconnect: boolean;\n private readonly initialBackoffMs: number;\n private readonly maxBackoffMs: number;\n private readonly logger: NonNullable<AgentClientOptions['logger']>;\n\n constructor(private readonly options: AgentClientOptions) {\n this.wsUrl = options.wsUrl;\n this.agentId = options.agentId;\n this.token = options.token;\n this.version = options.version || '0.1.0';\n this.platform = options.platform || (os.platform() as AgentPlatform);\n this.arch = options.arch || (os.arch() as AgentArchitecture);\n this.autoReconnect = options.autoReconnect ?? true;\n this.initialBackoffMs = options.initialBackoffMs ?? 1000;\n this.maxBackoffMs = options.maxBackoffMs ?? 30000;\n this.activeHeartbeatIntervalMs = options.heartbeatIntervalMs ?? 10000;\n this.logger = options.logger ?? {\n info: (...args) => console.log('[LuxrayAgent]', ...args),\n warn: (...args) => console.warn('[LuxrayAgent:WARN]', ...args),\n error: (...args) => console.error('[LuxrayAgent:ERROR]', ...args),\n debug: (...args) => {},\n };\n }\n\n public getState(): AgentClientState {\n return this.state;\n }\n\n public getConnectionId(): string | null {\n return this.connectionId;\n }\n\n public isConnected(): boolean {\n return this.state === 'connected' && this.ws?.readyState === WebSocket.OPEN;\n }\n\n /**\n * Connects to the Luxray Cloud WebSocket server and completes the hello handshake.\n */\n public connect(): Promise<AgentConnectedMessage> {\n if (this.state === 'revoked') {\n return Promise.reject(new Error('Agent credentials have been revoked. Cannot connect.'));\n }\n\n this.isIntentionallyClosed = false;\n this.state = 'connecting';\n\n return new Promise((resolve, reject) => {\n let isResolved = false;\n\n try {\n this.ws = new WebSocket(this.wsUrl);\n } catch (err: any) {\n this.state = 'idle';\n return reject(err);\n }\n\n const connectionTimeout = setTimeout(() => {\n if (!isResolved) {\n isResolved = true;\n this.logger.error('Connection timed out waiting for server response.');\n this.ws?.terminate();\n reject(new Error('Connection timed out.'));\n }\n }, 15000);\n\n this.ws.on('open', () => {\n this.logger.info(`WebSocket transport opened to ${this.wsUrl}. Sending agent.hello...`);\n this.sendHello();\n });\n\n this.ws.on('message', (raw: Buffer | string) => {\n try {\n const msg = JSON.parse(raw.toString()) as AgentProtocolMessage;\n this.handleIncomingMessage(msg, (connected) => {\n if (!isResolved) {\n isResolved = true;\n clearTimeout(connectionTimeout);\n resolve(connected);\n }\n });\n } catch (err: any) {\n this.logger.error('Failed to parse incoming WebSocket message:', err.message);\n }\n });\n\n this.ws.on('close', (code, reasonBuf) => {\n clearTimeout(connectionTimeout);\n const reason = reasonBuf.toString();\n this.handleClose(code, reason);\n if (!isResolved) {\n isResolved = true;\n reject(new Error(`WebSocket closed during handshake (code: ${code}, reason: ${reason})`));\n }\n });\n\n this.ws.on('error', (err) => {\n this.logger.error('WebSocket transport error:', err.message);\n if (this.options.onError) {\n this.options.onError(err);\n }\n });\n });\n }\n\n /**\n * Sends the agent.hello greeting to identify and authenticate this agent.\n */\n private sendHello(): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n\n const helloPayload = {\n type: 'agent.hello' as const,\n version: '1.0' as const,\n agentId: this.agentId,\n token: this.token,\n agentVersion: this.version,\n platform: this.platform,\n arch: this.arch,\n timestamp: Date.now(),\n };\n\n this.ws.send(JSON.stringify(helloPayload));\n }\n\n /**\n * Handles incoming protocol messages.\n */\n private handleIncomingMessage(\n msg: AgentProtocolMessage,\n onConnectedFirstTime: (connected: AgentConnectedMessage) => void,\n ): void {\n switch (msg.type) {\n case 'agent.connected': {\n const connectedMsg = msg as AgentConnectedMessage;\n this.state = 'connected';\n this.reconnectAttempt = 0;\n this.connectionId = connectedMsg.connectionId;\n this.activeHeartbeatIntervalMs = connectedMsg.heartbeatIntervalMs || 10000;\n this.logger.info(\n `Successfully connected & authenticated with Luxray Cloud! Connection ID: ${connectedMsg.connectionId}`,\n );\n\n this.startHeartbeatLoop();\n onConnectedFirstTime(connectedMsg);\n\n if (this.options.onConnected) {\n this.options.onConnected(connectedMsg);\n }\n break;\n }\n\n case 'agent.heartbeat.ack': {\n const ackMsg = msg as AgentHeartbeatAckMessage;\n this.logger.debug(`Heartbeat acknowledged by server (ack: ${ackMsg.timestamp})`);\n if (this.options.onHeartbeatAck) {\n this.options.onHeartbeatAck(ackMsg);\n }\n break;\n }\n\n case 'agent.revoked': {\n const revokedMsg = msg as AgentRevokedMessage;\n this.state = 'revoked';\n this.isIntentionallyClosed = true;\n this.logger.error(`CRITICAL: Agent credentials have been revoked. Reason: ${revokedMsg.reason}`);\n this.stopHeartbeatLoop();\n if (this.options.onRevoked) {\n this.options.onRevoked(revokedMsg);\n }\n this.ws?.close(4401, 'Agent Revoked');\n break;\n }\n\n case 'agent.error': {\n const errMsg = msg as AgentErrorMessage;\n this.logger.error(`Server error [${errMsg.code}]: ${errMsg.message}`);\n if (errMsg.fatal) {\n this.logger.error('Fatal server error encountered. Closing connection.');\n this.ws?.close(4000, errMsg.message);\n }\n break;\n }\n\n default:\n // Task frames do not travel over this socket any more. One arriving\n // here is either a stale server or a bug worth noticing.\n this.logger.debug('Unhandled message type:', (msg as any).type);\n }\n }\n\n /**\n * Starts periodic heartbeat transmission.\n */\n private startHeartbeatLoop(): void {\n this.stopHeartbeatLoop();\n this.heartbeatTimer = setInterval(() => {\n this.sendHeartbeat();\n }, this.activeHeartbeatIntervalMs);\n }\n\n private stopHeartbeatLoop(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n /**\n * Transmits heartbeat metrics to the cloud.\n */\n private sendHeartbeat(): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n\n const memoryMb = Math.round(process.memoryUsage().rss / (1024 * 1024));\n const uptime = Math.round(process.uptime());\n\n const heartbeatPayload = {\n type: 'agent.heartbeat' as const,\n version: '1.0' as const,\n agentId: this.agentId,\n memoryUsageMb: memoryMb,\n uptimeSeconds: uptime,\n timestamp: Date.now(),\n };\n\n try {\n this.ws.send(JSON.stringify(heartbeatPayload));\n this.logger.debug(`Heartbeat sent: memory=${memoryMb}MB, uptime=${uptime}s`);\n } catch (err: any) {\n this.logger.warn('Failed to transmit heartbeat:', err.message);\n }\n }\n\n /**\n * Handles WebSocket closure and schedules reconnection if appropriate.\n */\n private handleClose(code: number, reason: string): void {\n this.stopHeartbeatLoop();\n this.connectionId = null;\n\n if (this.options.onDisconnect) {\n this.options.onDisconnect(code, reason);\n }\n\n if (code === 4401 || this.state === 'revoked') {\n this.state = 'revoked';\n this.logger.error('Connection closed: Agent credentials revoked. Will NOT reconnect.');\n return;\n }\n\n if (this.isIntentionallyClosed) {\n this.state = 'stopped';\n this.logger.info('Agent stopped gracefully.');\n return;\n }\n\n if (code === 4009) {\n this.logger.warn('Another instance of this agent connected elsewhere. Backing off.');\n }\n\n if (!this.autoReconnect) {\n this.state = 'idle';\n this.logger.info(`Connection closed (code: ${code}, reason: ${reason}). Auto-reconnect is disabled.`);\n return;\n }\n\n this.scheduleReconnect();\n }\n\n /**\n * Exponential backoff with random jitter for reconnects.\n */\n private scheduleReconnect(): void {\n this.state = 'reconnecting';\n this.reconnectAttempt++;\n\n // Backoff formula: initialBackoffMs * 1.5^(attempt - 1) + jitter (0 - 1000ms)\n const exponential = this.initialBackoffMs * Math.pow(1.5, Math.min(this.reconnectAttempt, 10));\n const jitter = Math.floor(Math.random() * 1000);\n const delay = Math.min(exponential + jitter, this.maxBackoffMs);\n\n this.logger.warn(\n `Connection lost. Reconnecting in ${(delay / 1000).toFixed(1)}s (attempt ${this.reconnectAttempt})...`,\n );\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n }\n\n this.reconnectTimer = setTimeout(async () => {\n try {\n await this.connect();\n } catch (err: any) {\n this.logger.warn('Reconnect attempt failed:', err.message);\n // The close event will trigger the next reconnect attempt\n }\n }, delay);\n }\n\n /**\n * Gracefully stops the agent connection and notifies cloud.\n *\n * Resolves once the socket has actually closed, not when closing was\n * requested. A job's terminal frame (a completion or a failure) may still be\n * in the send buffer, and the peer processes frames in order: waiting for the\n * close handshake means the report was delivered before this process exits\n * and claims the run ended.\n */\n public async disconnect(timeoutMs = 1_000): Promise<void> {\n this.isIntentionallyClosed = true;\n this.state = 'stopped';\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n this.stopHeartbeatLoop();\n\n const ws = this.ws;\n this.ws = null;\n if (!ws) return;\n\n // Send a graceful goodbye status before closing if socket is open\n if (ws.readyState === WebSocket.OPEN) {\n const goodbyePayload: AgentStatusMessage = {\n type: 'agent.status',\n version: '1.0',\n agentId: this.agentId,\n status: 'DISCONNECTED',\n timestamp: Date.now(),\n };\n try {\n ws.send(JSON.stringify(goodbyePayload));\n } catch {}\n }\n\n if (ws.readyState === WebSocket.CLOSED) return;\n\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, timeoutMs);\n timer.unref?.();\n\n ws.once('close', () => {\n clearTimeout(timer);\n resolve();\n });\n\n try {\n ws.close(1000, 'Agent Stopped Manually');\n } catch {\n clearTimeout(timer);\n resolve();\n }\n });\n }\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,YAAY,QAAQ;AA4Cb,IAAM,cAAN,MAAkB;AAAA,EAqBvB,YAA6B,SAA6B;AAA7B;AAC3B,SAAK,QAAQ,QAAQ;AACrB,SAAK,UAAU,QAAQ;AACvB,SAAK,QAAQ,QAAQ;AACrB,SAAK,UAAU,QAAQ,WAAW;AAClC,SAAK,WAAW,QAAQ,YAAgB,YAAS;AACjD,SAAK,OAAO,QAAQ,QAAY,QAAK;AACrC,SAAK,gBAAgB,QAAQ,iBAAiB;AAC9C,SAAK,mBAAmB,QAAQ,oBAAoB;AACpD,SAAK,eAAe,QAAQ,gBAAgB;AAC5C,SAAK,4BAA4B,QAAQ,uBAAuB;AAChE,SAAK,SAAS,QAAQ,UAAU;AAAA,MAC9B,MAAM,IAAI,SAAS,QAAQ,IAAI,iBAAiB,GAAG,IAAI;AAAA,MACvD,MAAM,IAAI,SAAS,QAAQ,KAAK,sBAAsB,GAAG,IAAI;AAAA,MAC7D,OAAO,IAAI,SAAS,QAAQ,MAAM,uBAAuB,GAAG,IAAI;AAAA,MAChE,OAAO,IAAI,SAAS;AAAA,MAAC;AAAA,IACvB;AAAA,EACF;AAAA,EAjB6B;AAAA,EApBrB,KAAuB;AAAA,EACvB,QAA0B;AAAA,EAC1B,iBAAwC;AAAA,EACxC,iBAAwC;AAAA,EACxC,mBAAmB;AAAA,EACnB,wBAAwB;AAAA,EACxB,4BAA4B;AAAA,EAC5B,eAA8B;AAAA,EAErB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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BAAQ;AAAA,MACV,CAAC;AAED,UAAI;AACF,WAAG,MAAM,KAAM,wBAAwB;AAAA,MACzC,QAAQ;AACN,qBAAa,KAAK;AAClB,gBAAQ;AAAA,MACV;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { ExplorationJobType, ExplorationTaskScope, AgentPlatform, AgentArchitecture, ExplorationTask, LoginResponse, RegisterAgentResponse } from '@luxray/shared';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Minimal HTTP client for the Luxray API.
|
|
5
|
+
*
|
|
6
|
+
* Kept separate from the CLI entry point so the authentication and
|
|
7
|
+
* registration flows can be tested without spawning a process or a server.
|
|
8
|
+
* `fetch` is injected for exactly that reason.
|
|
9
|
+
*/
|
|
10
|
+
interface HttpResponseLike {
|
|
11
|
+
readonly ok: boolean;
|
|
12
|
+
readonly status: number;
|
|
13
|
+
text(): Promise<string>;
|
|
14
|
+
json(): Promise<unknown>;
|
|
15
|
+
}
|
|
16
|
+
interface RequestOptionsLike {
|
|
17
|
+
method?: string;
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
body?: string;
|
|
20
|
+
}
|
|
21
|
+
type FetchLike = (url: string, init: RequestOptionsLike) => Promise<HttpResponseLike>;
|
|
22
|
+
declare class LuxrayApiError extends Error {
|
|
23
|
+
readonly status: number;
|
|
24
|
+
constructor(status: number, message: string);
|
|
25
|
+
}
|
|
26
|
+
interface RegisterAgentPayload {
|
|
27
|
+
readonly name: string;
|
|
28
|
+
readonly platform: AgentPlatform | string;
|
|
29
|
+
readonly arch: AgentArchitecture | string;
|
|
30
|
+
readonly version: string;
|
|
31
|
+
readonly metadata?: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Exchanges user credentials for a short-lived access token.
|
|
35
|
+
* This is the only way the CLI obtains authority to act on a workspace.
|
|
36
|
+
*/
|
|
37
|
+
declare function login(fetchImpl: FetchLike, apiUrl: string, email: string, password: string): Promise<LoginResponse>;
|
|
38
|
+
/**
|
|
39
|
+
* Registers a local agent. The workspace is part of the URL and is authorized
|
|
40
|
+
* by the bearer token; it is deliberately NOT sent in the body (the API
|
|
41
|
+
* rejects unknown body properties).
|
|
42
|
+
*/
|
|
43
|
+
declare function registerAgent(fetchImpl: FetchLike, apiUrl: string, workspaceId: string, accessToken: string, payload: RegisterAgentPayload): Promise<RegisterAgentResponse>;
|
|
44
|
+
interface CreateAgentTaskPayload {
|
|
45
|
+
readonly startUrl: string;
|
|
46
|
+
readonly jobType?: ExplorationJobType;
|
|
47
|
+
readonly name?: string;
|
|
48
|
+
readonly scope?: ExplorationTaskScope;
|
|
49
|
+
readonly maxAttempts?: number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Asks the control plane to run a URL the operator typed in the terminal.
|
|
53
|
+
*
|
|
54
|
+
* Authenticated with the agent token rather than a user session: the machine
|
|
55
|
+
* issuing the command may not have one, and the task it creates is leased to
|
|
56
|
+
* that same agent in the same request.
|
|
57
|
+
*/
|
|
58
|
+
declare function createAgentExplorationTask(fetchImpl: FetchLike, apiUrl: string, agentToken: string, payload: CreateAgentTaskPayload): Promise<{
|
|
59
|
+
task: ExplorationTask;
|
|
60
|
+
}>;
|
|
61
|
+
|
|
62
|
+
export { LuxrayApiError, createAgentExplorationTask, login, registerAgent };
|
|
63
|
+
export type { CreateAgentTaskPayload, FetchLike, HttpResponseLike, RegisterAgentPayload, RequestOptionsLike };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// src/client/luxray-api-client.ts
|
|
2
|
+
var LuxrayApiError = class extends Error {
|
|
3
|
+
constructor(status, message) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.status = status;
|
|
6
|
+
this.name = "LuxrayApiError";
|
|
7
|
+
}
|
|
8
|
+
status;
|
|
9
|
+
};
|
|
10
|
+
function normalizeBaseUrl(apiUrl) {
|
|
11
|
+
return apiUrl.replace(/\/+$/, "");
|
|
12
|
+
}
|
|
13
|
+
async function postJson(fetchImpl, url, body, accessToken) {
|
|
14
|
+
const headers = { "Content-Type": "application/json" };
|
|
15
|
+
if (accessToken) {
|
|
16
|
+
headers["Authorization"] = `Bearer ${accessToken}`;
|
|
17
|
+
}
|
|
18
|
+
let response;
|
|
19
|
+
try {
|
|
20
|
+
response = await fetchImpl(url, {
|
|
21
|
+
method: "POST",
|
|
22
|
+
headers,
|
|
23
|
+
body: JSON.stringify(body)
|
|
24
|
+
});
|
|
25
|
+
} catch (err) {
|
|
26
|
+
throw new LuxrayApiError(0, `Could not reach ${url}: ${err.message}`);
|
|
27
|
+
}
|
|
28
|
+
if (!response.ok) {
|
|
29
|
+
let detail = "";
|
|
30
|
+
try {
|
|
31
|
+
detail = (await response.text()).trim();
|
|
32
|
+
} catch {
|
|
33
|
+
}
|
|
34
|
+
throw new LuxrayApiError(
|
|
35
|
+
response.status,
|
|
36
|
+
`HTTP ${response.status}${detail ? `: ${detail}` : ""}`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
return await response.json();
|
|
40
|
+
}
|
|
41
|
+
function login(fetchImpl, apiUrl, email, password) {
|
|
42
|
+
return postJson(fetchImpl, `${normalizeBaseUrl(apiUrl)}/v1/auth/login`, {
|
|
43
|
+
email,
|
|
44
|
+
password
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
function registerAgent(fetchImpl, apiUrl, workspaceId, accessToken, payload) {
|
|
48
|
+
return postJson(
|
|
49
|
+
fetchImpl,
|
|
50
|
+
`${normalizeBaseUrl(apiUrl)}/v1/workspaces/${encodeURIComponent(workspaceId)}/agents/register`,
|
|
51
|
+
payload,
|
|
52
|
+
accessToken
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
function createAgentExplorationTask(fetchImpl, apiUrl, agentToken, payload) {
|
|
56
|
+
return postJson(
|
|
57
|
+
fetchImpl,
|
|
58
|
+
`${normalizeBaseUrl(apiUrl)}/v1/agent/tasks/explore`,
|
|
59
|
+
payload,
|
|
60
|
+
agentToken
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
export {
|
|
64
|
+
LuxrayApiError,
|
|
65
|
+
createAgentExplorationTask,
|
|
66
|
+
login,
|
|
67
|
+
registerAgent
|
|
68
|
+
};
|
|
69
|
+
//# sourceMappingURL=luxray-api-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/client/luxray-api-client.ts"],"sourcesContent":["import type {\n AgentArchitecture,\n AgentPlatform,\n ExplorationJobType,\n ExplorationTask,\n ExplorationTaskScope,\n LoginResponse,\n RegisterAgentResponse,\n} from '@luxray/shared';\n\n/**\n * Minimal HTTP client for the Luxray API.\n *\n * Kept separate from the CLI entry point so the authentication and\n * registration flows can be tested without spawning a process or a server.\n * `fetch` is injected for exactly that reason.\n */\n\nexport interface HttpResponseLike {\n readonly ok: boolean;\n readonly status: number;\n text(): Promise<string>;\n json(): Promise<unknown>;\n}\n\nexport interface RequestOptionsLike {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n}\n\nexport type FetchLike = (url: string, init: RequestOptionsLike) => Promise<HttpResponseLike>;\n\nexport class LuxrayApiError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = 'LuxrayApiError';\n }\n}\n\nexport interface RegisterAgentPayload {\n readonly name: string;\n readonly platform: AgentPlatform | string;\n readonly arch: AgentArchitecture | string;\n readonly version: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nfunction normalizeBaseUrl(apiUrl: string): string {\n return apiUrl.replace(/\\/+$/, '');\n}\n\nasync function postJson<T>(\n fetchImpl: FetchLike,\n url: string,\n body: unknown,\n accessToken?: string,\n): Promise<T> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (accessToken) {\n headers['Authorization'] = `Bearer ${accessToken}`;\n }\n\n let response: HttpResponseLike;\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new LuxrayApiError(0, `Could not reach ${url}: ${(err as Error).message}`);\n }\n\n if (!response.ok) {\n let detail = '';\n try {\n detail = (await response.text()).trim();\n } catch {\n // A failure to read the error body must not hide the status code.\n }\n throw new LuxrayApiError(\n response.status,\n `HTTP ${response.status}${detail ? `: ${detail}` : ''}`,\n );\n }\n\n return (await response.json()) as T;\n}\n\n/**\n * Exchanges user credentials for a short-lived access token.\n * This is the only way the CLI obtains authority to act on a workspace.\n */\nexport function login(\n fetchImpl: FetchLike,\n apiUrl: string,\n email: string,\n password: string,\n): Promise<LoginResponse> {\n return postJson<LoginResponse>(fetchImpl, `${normalizeBaseUrl(apiUrl)}/v1/auth/login`, {\n email,\n password,\n });\n}\n\n/**\n * Registers a local agent. The workspace is part of the URL and is authorized\n * by the bearer token; it is deliberately NOT sent in the body (the API\n * rejects unknown body properties).\n */\nexport function registerAgent(\n fetchImpl: FetchLike,\n apiUrl: string,\n workspaceId: string,\n accessToken: string,\n payload: RegisterAgentPayload,\n): Promise<RegisterAgentResponse> {\n return postJson<RegisterAgentResponse>(\n fetchImpl,\n `${normalizeBaseUrl(apiUrl)}/v1/workspaces/${encodeURIComponent(workspaceId)}/agents/register`,\n payload,\n accessToken,\n );\n}\n\nexport interface CreateAgentTaskPayload {\n readonly startUrl: string;\n readonly jobType?: ExplorationJobType;\n readonly name?: string;\n readonly scope?: ExplorationTaskScope;\n readonly maxAttempts?: number;\n}\n\n/**\n * Asks the control plane to run a URL the operator typed in the terminal.\n *\n * Authenticated with the agent token rather than a user session: the machine\n * issuing the command may not have one, and the task it creates is leased to\n * that same agent in the same request.\n */\nexport function createAgentExplorationTask(\n fetchImpl: FetchLike,\n apiUrl: string,\n agentToken: string,\n payload: CreateAgentTaskPayload,\n): Promise<{ task: ExplorationTask }> {\n return postJson<{ task: ExplorationTask }>(\n fetchImpl,\n `${normalizeBaseUrl(apiUrl)}/v1/agent/tasks/explore`,\n payload,\n agentToken,\n );\n}\n"],"mappings":";AAiCO,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