supertag-ai 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/LICENSE +21 -0
- package/README.md +51 -0
- package/dist/chunk-B3EVEGNZ.js +13 -0
- package/dist/chunk-B3EVEGNZ.js.map +1 -0
- package/dist/chunk-ES42FTPC.js +1068 -0
- package/dist/chunk-ES42FTPC.js.map +1 -0
- package/dist/chunk-L7S2TKUG.js +656 -0
- package/dist/chunk-L7S2TKUG.js.map +1 -0
- package/dist/connectors.d.ts +45 -0
- package/dist/connectors.js +39 -0
- package/dist/connectors.js.map +1 -0
- package/dist/core.d.ts +721 -0
- package/dist/core.js +3 -0
- package/dist/core.js.map +1 -0
- package/dist/environments/e2b.d.ts +69 -0
- package/dist/environments/e2b.js +268 -0
- package/dist/environments/e2b.js.map +1 -0
- package/dist/gateway.d.ts +59 -0
- package/dist/gateway.js +1215 -0
- package/dist/gateway.js.map +1 -0
- package/dist/harnesses/claude-code.d.ts +67 -0
- package/dist/harnesses/claude-code.js +565 -0
- package/dist/harnesses/claude-code.js.map +1 -0
- package/dist/harnesses/codex.d.ts +68 -0
- package/dist/harnesses/codex.js +690 -0
- package/dist/harnesses/codex.js.map +1 -0
- package/dist/index.d.ts +100 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/resources/github.d.ts +80 -0
- package/dist/resources/github.js +374 -0
- package/dist/resources/github.js.map +1 -0
- package/dist/resources/linear.d.ts +25 -0
- package/dist/resources/linear.js +92 -0
- package/dist/resources/linear.js.map +1 -0
- package/dist/resources/slack.d.ts +25 -0
- package/dist/resources/slack.js +98 -0
- package/dist/resources/slack.js.map +1 -0
- package/dist/resources/teams.d.ts +27 -0
- package/dist/resources/teams.js +101 -0
- package/dist/resources/teams.js.map +1 -0
- package/dist/transport.d.ts +5 -0
- package/dist/transport.js +3 -0
- package/dist/transport.js.map +1 -0
- package/dist/worker.d.ts +634 -0
- package/dist/worker.js +3 -0
- package/dist/worker.js.map +1 -0
- package/package.json +127 -0
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
import { randomUUID, timingSafeEqual, createHash } from 'crypto';
|
|
2
|
+
import WebSocket, { WebSocketServer } from 'ws';
|
|
3
|
+
|
|
4
|
+
// ../runtime/transport/src/index.ts
|
|
5
|
+
var WORKER_PROTOCOL_VERSION = 7;
|
|
6
|
+
var DEFAULT_PATH = "/workers";
|
|
7
|
+
var DEFAULT_AUTH_TIMEOUT_MS = 1e4;
|
|
8
|
+
var DEFAULT_HEARTBEAT_INTERVAL_MS = 15e3;
|
|
9
|
+
var DEFAULT_HEARTBEAT_TIMEOUT_MS = 45e3;
|
|
10
|
+
var DEFAULT_JOB_TIMEOUT_MS = 5 * 6e4;
|
|
11
|
+
var DEFAULT_RECONNECT_INTERVAL_MS = 1e3;
|
|
12
|
+
var DEFAULT_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
|
|
13
|
+
var RemoteWorkerServer = class {
|
|
14
|
+
#httpServer;
|
|
15
|
+
#pairingToken;
|
|
16
|
+
#path;
|
|
17
|
+
#fallbackId;
|
|
18
|
+
#authTimeoutMs;
|
|
19
|
+
#heartbeatIntervalMs;
|
|
20
|
+
#heartbeatTimeoutMs;
|
|
21
|
+
#jobTimeoutMs;
|
|
22
|
+
#webSocketServer;
|
|
23
|
+
#onError;
|
|
24
|
+
#onWorkerConnected;
|
|
25
|
+
#onWorkerDisconnected;
|
|
26
|
+
#connections = /* @__PURE__ */ new Set();
|
|
27
|
+
#pendingJobs = /* @__PURE__ */ new Map();
|
|
28
|
+
#activeConnection;
|
|
29
|
+
#heartbeatTimer;
|
|
30
|
+
#started = false;
|
|
31
|
+
constructor(options) {
|
|
32
|
+
requireNonEmpty(options.pairingToken, "pairingToken");
|
|
33
|
+
this.#httpServer = options.server;
|
|
34
|
+
this.#pairingToken = options.pairingToken;
|
|
35
|
+
this.#path = normalizePath(options.path ?? DEFAULT_PATH);
|
|
36
|
+
this.#fallbackId = options.id ?? "remote";
|
|
37
|
+
this.#authTimeoutMs = positiveDuration(
|
|
38
|
+
options.authTimeoutMs,
|
|
39
|
+
DEFAULT_AUTH_TIMEOUT_MS,
|
|
40
|
+
"authTimeoutMs"
|
|
41
|
+
);
|
|
42
|
+
this.#heartbeatIntervalMs = positiveDuration(
|
|
43
|
+
options.heartbeatIntervalMs,
|
|
44
|
+
DEFAULT_HEARTBEAT_INTERVAL_MS,
|
|
45
|
+
"heartbeatIntervalMs"
|
|
46
|
+
);
|
|
47
|
+
this.#heartbeatTimeoutMs = positiveDuration(
|
|
48
|
+
options.heartbeatTimeoutMs,
|
|
49
|
+
DEFAULT_HEARTBEAT_TIMEOUT_MS,
|
|
50
|
+
"heartbeatTimeoutMs"
|
|
51
|
+
);
|
|
52
|
+
this.#jobTimeoutMs = positiveDuration(
|
|
53
|
+
options.jobTimeoutMs,
|
|
54
|
+
DEFAULT_JOB_TIMEOUT_MS,
|
|
55
|
+
"jobTimeoutMs"
|
|
56
|
+
);
|
|
57
|
+
if (this.#heartbeatTimeoutMs <= this.#heartbeatIntervalMs) {
|
|
58
|
+
throw new Error("heartbeatTimeoutMs must be greater than heartbeatIntervalMs");
|
|
59
|
+
}
|
|
60
|
+
this.#onError = options.onError;
|
|
61
|
+
this.#onWorkerConnected = options.onWorkerConnected;
|
|
62
|
+
this.#onWorkerDisconnected = options.onWorkerDisconnected;
|
|
63
|
+
this.#webSocketServer = new WebSocketServer({
|
|
64
|
+
noServer: true,
|
|
65
|
+
maxPayload: positiveInteger(
|
|
66
|
+
options.maxPayloadBytes,
|
|
67
|
+
DEFAULT_MAX_PAYLOAD_BYTES,
|
|
68
|
+
"maxPayloadBytes"
|
|
69
|
+
)
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
get id() {
|
|
73
|
+
return this.#activeConnection?.descriptor?.id ?? this.#fallbackId;
|
|
74
|
+
}
|
|
75
|
+
get isWorkerConnected() {
|
|
76
|
+
return this.#activeConnection?.socket.readyState === WebSocket.OPEN;
|
|
77
|
+
}
|
|
78
|
+
get isConnected() {
|
|
79
|
+
return this.isWorkerConnected;
|
|
80
|
+
}
|
|
81
|
+
get workerRegistration() {
|
|
82
|
+
return this.#activeConnection?.descriptor;
|
|
83
|
+
}
|
|
84
|
+
start() {
|
|
85
|
+
if (this.#started) return;
|
|
86
|
+
this.#started = true;
|
|
87
|
+
this.#httpServer.on("upgrade", this.#handleUpgrade);
|
|
88
|
+
this.#webSocketServer.on("connection", this.#handleConnection);
|
|
89
|
+
this.#heartbeatTimer = setInterval(
|
|
90
|
+
this.#evictUnresponsiveConnections,
|
|
91
|
+
this.#heartbeatIntervalMs
|
|
92
|
+
);
|
|
93
|
+
this.#heartbeatTimer.unref();
|
|
94
|
+
}
|
|
95
|
+
async stop() {
|
|
96
|
+
if (!this.#started) return;
|
|
97
|
+
this.#started = false;
|
|
98
|
+
this.#httpServer.off("upgrade", this.#handleUpgrade);
|
|
99
|
+
this.#webSocketServer.off("connection", this.#handleConnection);
|
|
100
|
+
if (this.#heartbeatTimer !== void 0) clearInterval(this.#heartbeatTimer);
|
|
101
|
+
this.#heartbeatTimer = void 0;
|
|
102
|
+
for (const connection of this.#connections)
|
|
103
|
+
connection.socket.close(1001, "Gateway shutting down");
|
|
104
|
+
this.#failAllJobs(new Error("Remote Worker Host server stopped"));
|
|
105
|
+
await new Promise((resolve) => this.#webSocketServer.close(() => resolve()));
|
|
106
|
+
}
|
|
107
|
+
async describe() {
|
|
108
|
+
const descriptor = this.#activeConnection?.descriptor;
|
|
109
|
+
if (descriptor === void 0) throw new Error("No remote Worker Host is connected");
|
|
110
|
+
return descriptor;
|
|
111
|
+
}
|
|
112
|
+
execute(spec, signal) {
|
|
113
|
+
return this.#streamExecution(spec, signal);
|
|
114
|
+
}
|
|
115
|
+
async *#streamExecution(spec, signal) {
|
|
116
|
+
const connection = this.#activeConnection;
|
|
117
|
+
if (connection?.descriptor === void 0 || connection.socket.readyState !== WebSocket.OPEN) {
|
|
118
|
+
throw new Error("No remote Worker Host is connected");
|
|
119
|
+
}
|
|
120
|
+
if (this.#pendingJobs.size > 0)
|
|
121
|
+
throw new Error("Remote Worker Host is already executing a job");
|
|
122
|
+
if (signal?.aborted) throw abortError(signal.reason);
|
|
123
|
+
const jobId = randomUUID();
|
|
124
|
+
const timeout = setTimeout(() => {
|
|
125
|
+
this.#failJob(jobId, new Error(`Remote Worker Host job ${jobId} timed out`));
|
|
126
|
+
safeSend(connection.socket, { type: "cancel", jobId, reason: "Gateway timeout" });
|
|
127
|
+
}, this.#jobTimeoutMs);
|
|
128
|
+
timeout.unref();
|
|
129
|
+
const job = {
|
|
130
|
+
socket: connection.socket,
|
|
131
|
+
events: [],
|
|
132
|
+
waiters: [],
|
|
133
|
+
timeout,
|
|
134
|
+
done: false
|
|
135
|
+
};
|
|
136
|
+
this.#pendingJobs.set(jobId, job);
|
|
137
|
+
const onAbort = () => {
|
|
138
|
+
this.#failJob(jobId, abortError(signal?.reason));
|
|
139
|
+
safeSend(connection.socket, { type: "cancel", jobId, reason: "Task Attempt cancelled" });
|
|
140
|
+
};
|
|
141
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
142
|
+
try {
|
|
143
|
+
sendJson(connection.socket, { type: "job", jobId, spec });
|
|
144
|
+
while (true) {
|
|
145
|
+
while (job.events.length > 0) yield job.events.shift();
|
|
146
|
+
if (job.error !== void 0) throw job.error;
|
|
147
|
+
if (job.done) return;
|
|
148
|
+
await new Promise((resolve) => job.waiters.push(resolve));
|
|
149
|
+
}
|
|
150
|
+
} finally {
|
|
151
|
+
signal?.removeEventListener("abort", onAbort);
|
|
152
|
+
this.#finishJob(jobId);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
#handleUpgrade = (request, socket, head) => {
|
|
156
|
+
if (!this.#started) return;
|
|
157
|
+
let pathname;
|
|
158
|
+
try {
|
|
159
|
+
pathname = new URL(request.url ?? "", "http://gateway.local").pathname;
|
|
160
|
+
} catch {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (pathname !== this.#path) return;
|
|
164
|
+
this.#webSocketServer.handleUpgrade(request, socket, head, (webSocket) => {
|
|
165
|
+
this.#webSocketServer.emit("connection", webSocket, request);
|
|
166
|
+
});
|
|
167
|
+
};
|
|
168
|
+
#handleConnection = (socket) => {
|
|
169
|
+
const connection = { socket, lastSeenAt: Date.now() };
|
|
170
|
+
this.#connections.add(connection);
|
|
171
|
+
const authTimeout = setTimeout(() => {
|
|
172
|
+
if (connection.descriptor === void 0) socket.close(4001, "Authentication timed out");
|
|
173
|
+
}, this.#authTimeoutMs);
|
|
174
|
+
authTimeout.unref();
|
|
175
|
+
socket.on("message", (data) => {
|
|
176
|
+
connection.lastSeenAt = Date.now();
|
|
177
|
+
try {
|
|
178
|
+
this.#handleMessage(connection, data);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
this.#reportError(error);
|
|
181
|
+
sendProtocolError(socket, "invalid_message", errorMessage(error));
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
socket.on("error", (error) => this.#reportError(error));
|
|
185
|
+
socket.on("close", () => {
|
|
186
|
+
clearTimeout(authTimeout);
|
|
187
|
+
this.#connections.delete(connection);
|
|
188
|
+
if (this.#activeConnection === connection) this.#activeConnection = void 0;
|
|
189
|
+
this.#failJobsForSocket(socket, new Error("Remote Worker Host disconnected"));
|
|
190
|
+
if (connection.descriptor !== void 0) this.#onWorkerDisconnected?.(connection.descriptor);
|
|
191
|
+
});
|
|
192
|
+
};
|
|
193
|
+
#handleMessage(connection, raw) {
|
|
194
|
+
const message = parseObjectMessage(raw);
|
|
195
|
+
if (connection.descriptor === void 0) {
|
|
196
|
+
this.#authenticate(connection, message);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
switch (message["type"]) {
|
|
200
|
+
case "heartbeat":
|
|
201
|
+
sendJson(connection.socket, { type: "heartbeat_ack", at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
202
|
+
return;
|
|
203
|
+
case "task_attempt_event": {
|
|
204
|
+
const jobId = requiredString(message, "jobId");
|
|
205
|
+
const event = taskAttemptEventFromMessage(message);
|
|
206
|
+
const job = this.#pendingJobs.get(jobId);
|
|
207
|
+
if (job === void 0 || job.socket !== connection.socket) {
|
|
208
|
+
sendProtocolError(
|
|
209
|
+
connection.socket,
|
|
210
|
+
"unknown_job",
|
|
211
|
+
`Job ${jobId} is no longer active`,
|
|
212
|
+
jobId
|
|
213
|
+
);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
job.events.push(event);
|
|
217
|
+
wake(job);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
case "job_done": {
|
|
221
|
+
const jobId = requiredString(message, "jobId");
|
|
222
|
+
const job = this.#pendingJobs.get(jobId);
|
|
223
|
+
if (job === void 0 || job.socket !== connection.socket) {
|
|
224
|
+
sendProtocolError(
|
|
225
|
+
connection.socket,
|
|
226
|
+
"unknown_job",
|
|
227
|
+
`Job ${jobId} is no longer active`,
|
|
228
|
+
jobId
|
|
229
|
+
);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
job.done = true;
|
|
233
|
+
clearTimeout(job.timeout);
|
|
234
|
+
wake(job);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
case "job_error": {
|
|
238
|
+
const jobId = requiredString(message, "jobId");
|
|
239
|
+
const error = requiredObject(message, "error");
|
|
240
|
+
this.#failJob(
|
|
241
|
+
jobId,
|
|
242
|
+
new Error(`Remote Worker Host failed: ${requiredString(error, "message")}`)
|
|
243
|
+
);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
default:
|
|
247
|
+
throw new Error("Unsupported authenticated Worker Host message");
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
#authenticate(connection, message) {
|
|
251
|
+
if (message["type"] !== "hello") {
|
|
252
|
+
connection.socket.close(4001, "First message must authenticate");
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (message["protocolVersion"] !== WORKER_PROTOCOL_VERSION) {
|
|
256
|
+
connection.socket.close(4002, "Unsupported protocol version");
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (!tokensMatch(requiredString(message, "pairingToken"), this.#pairingToken)) {
|
|
260
|
+
connection.socket.close(4003, "Authentication failed");
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (this.#activeConnection !== void 0) {
|
|
264
|
+
connection.socket.close(4004, "A Worker Host is already connected");
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
connection.descriptor = workerHostDescriptorFromMessage(message);
|
|
268
|
+
this.#activeConnection = connection;
|
|
269
|
+
sendJson(connection.socket, {
|
|
270
|
+
type: "ready",
|
|
271
|
+
protocolVersion: WORKER_PROTOCOL_VERSION,
|
|
272
|
+
heartbeatIntervalMs: this.#heartbeatIntervalMs
|
|
273
|
+
});
|
|
274
|
+
this.#onWorkerConnected?.(connection.descriptor);
|
|
275
|
+
}
|
|
276
|
+
#failJob(jobId, error) {
|
|
277
|
+
const job = this.#pendingJobs.get(jobId);
|
|
278
|
+
if (job === void 0) return;
|
|
279
|
+
job.error = error;
|
|
280
|
+
clearTimeout(job.timeout);
|
|
281
|
+
wake(job);
|
|
282
|
+
}
|
|
283
|
+
#finishJob(jobId) {
|
|
284
|
+
const job = this.#pendingJobs.get(jobId);
|
|
285
|
+
if (job === void 0) return;
|
|
286
|
+
clearTimeout(job.timeout);
|
|
287
|
+
this.#pendingJobs.delete(jobId);
|
|
288
|
+
wake(job);
|
|
289
|
+
}
|
|
290
|
+
#failJobsForSocket(socket, error) {
|
|
291
|
+
for (const [jobId, job] of this.#pendingJobs)
|
|
292
|
+
if (job.socket === socket) this.#failJob(jobId, error);
|
|
293
|
+
}
|
|
294
|
+
#failAllJobs(error) {
|
|
295
|
+
for (const jobId of this.#pendingJobs.keys()) this.#failJob(jobId, error);
|
|
296
|
+
}
|
|
297
|
+
#evictUnresponsiveConnections = () => {
|
|
298
|
+
const cutoff = Date.now() - this.#heartbeatTimeoutMs;
|
|
299
|
+
for (const connection of this.#connections) {
|
|
300
|
+
if (connection.lastSeenAt < cutoff) connection.socket.close(4005, "Heartbeat timed out");
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
#reportError(error) {
|
|
304
|
+
try {
|
|
305
|
+
this.#onError?.(error);
|
|
306
|
+
} catch {
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
var WorkerConnection = class {
|
|
311
|
+
#url;
|
|
312
|
+
#pairingToken;
|
|
313
|
+
#host;
|
|
314
|
+
#reconnectIntervalMs;
|
|
315
|
+
#onError;
|
|
316
|
+
#onConnected;
|
|
317
|
+
#onDisconnected;
|
|
318
|
+
#running = false;
|
|
319
|
+
#connected = false;
|
|
320
|
+
#socket;
|
|
321
|
+
#loop;
|
|
322
|
+
#firstReady;
|
|
323
|
+
#resolveFirstReady;
|
|
324
|
+
#rejectFirstReady;
|
|
325
|
+
#wakeReconnect;
|
|
326
|
+
#activeJob;
|
|
327
|
+
constructor(options) {
|
|
328
|
+
requireNonEmpty(options.url, "url");
|
|
329
|
+
requireNonEmpty(options.pairingToken, "pairingToken");
|
|
330
|
+
this.#url = options.url;
|
|
331
|
+
this.#pairingToken = options.pairingToken;
|
|
332
|
+
this.#host = options.host;
|
|
333
|
+
this.#reconnectIntervalMs = positiveDuration(
|
|
334
|
+
options.reconnectIntervalMs,
|
|
335
|
+
DEFAULT_RECONNECT_INTERVAL_MS,
|
|
336
|
+
"reconnectIntervalMs"
|
|
337
|
+
);
|
|
338
|
+
this.#onError = options.onError;
|
|
339
|
+
this.#onConnected = options.onConnected;
|
|
340
|
+
this.#onDisconnected = options.onDisconnected;
|
|
341
|
+
}
|
|
342
|
+
get isConnected() {
|
|
343
|
+
return this.#connected;
|
|
344
|
+
}
|
|
345
|
+
async start() {
|
|
346
|
+
if (this.#running) return await this.#firstReady;
|
|
347
|
+
this.#running = true;
|
|
348
|
+
this.#firstReady = new Promise((resolve, reject) => {
|
|
349
|
+
this.#resolveFirstReady = resolve;
|
|
350
|
+
this.#rejectFirstReady = reject;
|
|
351
|
+
});
|
|
352
|
+
this.#loop = this.#runConnectionLoop();
|
|
353
|
+
await this.#firstReady;
|
|
354
|
+
}
|
|
355
|
+
async stop() {
|
|
356
|
+
if (!this.#running) return;
|
|
357
|
+
this.#running = false;
|
|
358
|
+
this.#activeJob?.controller.abort(new Error("Worker Host shutting down"));
|
|
359
|
+
this.#rejectFirstReady?.(new Error("Remote Worker Host client stopped before connecting"));
|
|
360
|
+
this.#resolveFirstReady = void 0;
|
|
361
|
+
this.#rejectFirstReady = void 0;
|
|
362
|
+
this.#wakeReconnect?.();
|
|
363
|
+
this.#socket?.close(1e3, "Worker Host shutting down");
|
|
364
|
+
await this.#loop;
|
|
365
|
+
this.#loop = void 0;
|
|
366
|
+
this.#firstReady = void 0;
|
|
367
|
+
}
|
|
368
|
+
async #runConnectionLoop() {
|
|
369
|
+
while (this.#running) {
|
|
370
|
+
try {
|
|
371
|
+
await this.#runSession();
|
|
372
|
+
} catch (error) {
|
|
373
|
+
this.#reportError(error);
|
|
374
|
+
}
|
|
375
|
+
if (this.#running) await this.#waitBeforeReconnect();
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
async #runSession() {
|
|
379
|
+
const descriptor = await this.#host.describe();
|
|
380
|
+
await new Promise((resolve) => {
|
|
381
|
+
const socket = new WebSocket(this.#url);
|
|
382
|
+
this.#socket = socket;
|
|
383
|
+
let heartbeatTimer;
|
|
384
|
+
let settled = false;
|
|
385
|
+
let registered = false;
|
|
386
|
+
const endSession = () => {
|
|
387
|
+
if (settled) return;
|
|
388
|
+
settled = true;
|
|
389
|
+
if (heartbeatTimer !== void 0) clearInterval(heartbeatTimer);
|
|
390
|
+
this.#activeJob?.controller.abort(new Error("Gateway connection closed"));
|
|
391
|
+
this.#activeJob = void 0;
|
|
392
|
+
const wasConnected = this.#connected;
|
|
393
|
+
this.#connected = false;
|
|
394
|
+
if (this.#socket === socket) this.#socket = void 0;
|
|
395
|
+
if (wasConnected) this.#onDisconnected?.();
|
|
396
|
+
resolve();
|
|
397
|
+
};
|
|
398
|
+
socket.on("open", () => {
|
|
399
|
+
sendJson(socket, {
|
|
400
|
+
type: "hello",
|
|
401
|
+
protocolVersion: WORKER_PROTOCOL_VERSION,
|
|
402
|
+
pairingToken: this.#pairingToken,
|
|
403
|
+
host: descriptor
|
|
404
|
+
});
|
|
405
|
+
});
|
|
406
|
+
socket.on("message", (data) => {
|
|
407
|
+
try {
|
|
408
|
+
const message = parseObjectMessage(data);
|
|
409
|
+
if (message["type"] === "ready") {
|
|
410
|
+
if (message["protocolVersion"] !== WORKER_PROTOCOL_VERSION) {
|
|
411
|
+
throw new Error("Gateway selected an unsupported Worker protocol version");
|
|
412
|
+
}
|
|
413
|
+
registered = true;
|
|
414
|
+
this.#connected = true;
|
|
415
|
+
this.#resolveFirstReady?.();
|
|
416
|
+
this.#resolveFirstReady = void 0;
|
|
417
|
+
this.#rejectFirstReady = void 0;
|
|
418
|
+
this.#onConnected?.();
|
|
419
|
+
heartbeatTimer = setInterval(
|
|
420
|
+
() => {
|
|
421
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
422
|
+
sendJson(socket, { type: "heartbeat", at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
423
|
+
}
|
|
424
|
+
},
|
|
425
|
+
requiredPositiveNumber(message, "heartbeatIntervalMs")
|
|
426
|
+
);
|
|
427
|
+
heartbeatTimer.unref();
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
if (message["type"] === "job") {
|
|
431
|
+
void this.#executeJob(socket, message).catch(
|
|
432
|
+
(error) => this.#reportError(error)
|
|
433
|
+
);
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
if (message["type"] === "cancel") {
|
|
437
|
+
const jobId = requiredString(message, "jobId");
|
|
438
|
+
if (this.#activeJob?.id === jobId)
|
|
439
|
+
this.#activeJob.controller.abort(new Error("Task Attempt cancelled"));
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (message["type"] === "protocol_error") {
|
|
443
|
+
this.#reportError(new Error(requiredString(message, "message")));
|
|
444
|
+
}
|
|
445
|
+
} catch (error) {
|
|
446
|
+
this.#reportError(error);
|
|
447
|
+
socket.close(4006, "Invalid Gateway message");
|
|
448
|
+
}
|
|
449
|
+
});
|
|
450
|
+
socket.on("error", (error) => this.#reportError(error));
|
|
451
|
+
socket.on("close", (code, reason) => {
|
|
452
|
+
if (!registered && isPermanentRegistrationFailure(code)) {
|
|
453
|
+
const error = new Error(
|
|
454
|
+
reason.toString() || `Gateway rejected Worker Host registration (${code})`
|
|
455
|
+
);
|
|
456
|
+
this.#running = false;
|
|
457
|
+
this.#rejectFirstReady?.(error);
|
|
458
|
+
this.#resolveFirstReady = void 0;
|
|
459
|
+
this.#rejectFirstReady = void 0;
|
|
460
|
+
this.#reportError(error);
|
|
461
|
+
}
|
|
462
|
+
endSession();
|
|
463
|
+
});
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
async #executeJob(socket, message) {
|
|
467
|
+
const jobId = requiredString(message, "jobId");
|
|
468
|
+
if (this.#activeJob !== void 0) {
|
|
469
|
+
sendJson(socket, {
|
|
470
|
+
type: "job_error",
|
|
471
|
+
jobId,
|
|
472
|
+
error: { message: "Worker Host is already executing a job", retryable: true }
|
|
473
|
+
});
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
const spec = taskAttemptSpecFromMessage(message);
|
|
477
|
+
const controller = new AbortController();
|
|
478
|
+
this.#activeJob = { id: jobId, controller };
|
|
479
|
+
try {
|
|
480
|
+
for await (const event of this.#host.execute(spec, controller.signal)) {
|
|
481
|
+
if (this.#activeJob?.id !== jobId || socket.readyState !== WebSocket.OPEN) return;
|
|
482
|
+
sendJson(socket, { type: "task_attempt_event", jobId, event });
|
|
483
|
+
}
|
|
484
|
+
if (this.#activeJob?.id === jobId && socket.readyState === WebSocket.OPEN) {
|
|
485
|
+
sendJson(socket, { type: "job_done", jobId });
|
|
486
|
+
}
|
|
487
|
+
} catch (error) {
|
|
488
|
+
if (this.#activeJob?.id === jobId && socket.readyState === WebSocket.OPEN) {
|
|
489
|
+
sendJson(socket, {
|
|
490
|
+
type: "job_error",
|
|
491
|
+
jobId,
|
|
492
|
+
error: { message: errorMessage(error), retryable: !controller.signal.aborted }
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
} finally {
|
|
496
|
+
if (this.#activeJob?.id === jobId) this.#activeJob = void 0;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
async #waitBeforeReconnect() {
|
|
500
|
+
await new Promise((resolve) => {
|
|
501
|
+
const timeout = setTimeout(() => {
|
|
502
|
+
this.#wakeReconnect = void 0;
|
|
503
|
+
resolve();
|
|
504
|
+
}, this.#reconnectIntervalMs);
|
|
505
|
+
this.#wakeReconnect = () => {
|
|
506
|
+
clearTimeout(timeout);
|
|
507
|
+
this.#wakeReconnect = void 0;
|
|
508
|
+
resolve();
|
|
509
|
+
};
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
#reportError(error) {
|
|
513
|
+
try {
|
|
514
|
+
this.#onError?.(error);
|
|
515
|
+
} catch {
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
async function connectWorkerHost(options) {
|
|
520
|
+
const connection = new WorkerConnection(options);
|
|
521
|
+
await connection.start();
|
|
522
|
+
return connection;
|
|
523
|
+
}
|
|
524
|
+
function workerHostDescriptorFromMessage(message) {
|
|
525
|
+
const host = requiredObject(message, "host");
|
|
526
|
+
requiredString(host, "id");
|
|
527
|
+
if (host["protocolVersion"] !== 1)
|
|
528
|
+
throw new Error("Worker Host descriptor protocolVersion must be 1");
|
|
529
|
+
if (!Array.isArray(host["workers"]) || host["workers"].length === 0) {
|
|
530
|
+
throw new Error("Worker Host descriptor workers must be a non-empty array");
|
|
531
|
+
}
|
|
532
|
+
for (const value of host["workers"]) {
|
|
533
|
+
if (!isObject(value)) throw new Error("Worker Host descriptor worker must be an object");
|
|
534
|
+
requiredString(value, "id");
|
|
535
|
+
requiredString(value, "type");
|
|
536
|
+
if (!Array.isArray(value["capabilities"]) || !Array.isArray(value["profiles"])) {
|
|
537
|
+
throw new Error("Worker descriptor capabilities and profiles must be arrays");
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
return host;
|
|
541
|
+
}
|
|
542
|
+
function taskAttemptSpecFromMessage(message) {
|
|
543
|
+
const spec = requiredObject(message, "spec");
|
|
544
|
+
if (spec["version"] !== 1) throw new Error("Task Attempt Spec version must be 1");
|
|
545
|
+
requiredString(spec, "taskId");
|
|
546
|
+
requiredString(spec, "attemptId");
|
|
547
|
+
const tag = requiredObject(spec, "tag");
|
|
548
|
+
requiredString(tag, "id");
|
|
549
|
+
requiredString(tag, "name");
|
|
550
|
+
const profile = requiredObject(spec, "workerProfile");
|
|
551
|
+
requiredString(profile, "id");
|
|
552
|
+
requiredString(profile, "revision");
|
|
553
|
+
const input = requiredObject(spec, "input");
|
|
554
|
+
requiredObject(input, "origin");
|
|
555
|
+
if (!Array.isArray(input["messages"]))
|
|
556
|
+
throw new Error("Task Attempt Spec input.messages must be an array");
|
|
557
|
+
const authorization = requiredObject(spec, "authorization");
|
|
558
|
+
if (authorization["version"] !== 2)
|
|
559
|
+
throw new Error("Task Attempt Spec authorization version must be 2");
|
|
560
|
+
const contextPlan = requiredObject(spec, "contextPlan");
|
|
561
|
+
if (contextPlan["version"] !== 4 || !Array.isArray(contextPlan["sets"])) {
|
|
562
|
+
throw new Error("Task Attempt Spec Context Plan must be version 4 with a sets array");
|
|
563
|
+
}
|
|
564
|
+
return spec;
|
|
565
|
+
}
|
|
566
|
+
function taskAttemptEventFromMessage(message) {
|
|
567
|
+
const event = requiredObject(message, "event");
|
|
568
|
+
requiredString(event, "taskId");
|
|
569
|
+
requiredString(event, "attemptId");
|
|
570
|
+
requiredString(event, "at");
|
|
571
|
+
requiredString(event, "type");
|
|
572
|
+
return event;
|
|
573
|
+
}
|
|
574
|
+
function parseObjectMessage(raw) {
|
|
575
|
+
const value = JSON.parse(raw.toString());
|
|
576
|
+
if (!isObject(value)) throw new Error("Worker protocol message must be a JSON object");
|
|
577
|
+
return value;
|
|
578
|
+
}
|
|
579
|
+
function requiredObject(object, key) {
|
|
580
|
+
const value = object[key];
|
|
581
|
+
if (!isObject(value)) throw new Error(`Worker protocol ${key} must be an object`);
|
|
582
|
+
return value;
|
|
583
|
+
}
|
|
584
|
+
function isObject(value) {
|
|
585
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
586
|
+
}
|
|
587
|
+
function requiredString(object, key) {
|
|
588
|
+
const value = object[key];
|
|
589
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
590
|
+
throw new Error(`Worker protocol ${key} must be non-empty`);
|
|
591
|
+
}
|
|
592
|
+
return value;
|
|
593
|
+
}
|
|
594
|
+
function requiredPositiveNumber(object, key) {
|
|
595
|
+
const value = object[key];
|
|
596
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
597
|
+
throw new Error(`Worker protocol ${key} must be a positive number`);
|
|
598
|
+
}
|
|
599
|
+
return value;
|
|
600
|
+
}
|
|
601
|
+
function sendJson(socket, message) {
|
|
602
|
+
if (socket.readyState !== WebSocket.OPEN) throw new Error("Worker protocol socket is not open");
|
|
603
|
+
socket.send(JSON.stringify(message));
|
|
604
|
+
}
|
|
605
|
+
function safeSend(socket, message) {
|
|
606
|
+
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message));
|
|
607
|
+
}
|
|
608
|
+
function sendProtocolError(socket, code, message, jobId) {
|
|
609
|
+
if (socket.readyState !== WebSocket.OPEN) return;
|
|
610
|
+
sendJson(socket, {
|
|
611
|
+
type: "protocol_error",
|
|
612
|
+
code,
|
|
613
|
+
message,
|
|
614
|
+
...jobId === void 0 ? {} : { jobId }
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
function wake(job) {
|
|
618
|
+
for (const resolve of job.waiters.splice(0)) resolve();
|
|
619
|
+
}
|
|
620
|
+
function tokensMatch(received, expected) {
|
|
621
|
+
return timingSafeEqual(
|
|
622
|
+
createHash("sha256").update(received).digest(),
|
|
623
|
+
createHash("sha256").update(expected).digest()
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
function errorMessage(error) {
|
|
627
|
+
return error instanceof Error ? error.message : String(error);
|
|
628
|
+
}
|
|
629
|
+
function abortError(reason) {
|
|
630
|
+
return reason instanceof Error ? reason : new Error("Task Attempt aborted");
|
|
631
|
+
}
|
|
632
|
+
function normalizePath(path) {
|
|
633
|
+
const normalized = path.startsWith("/") ? path : `/${path}`;
|
|
634
|
+
return normalized.length > 1 && normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
|
|
635
|
+
}
|
|
636
|
+
function positiveDuration(value, fallback, name) {
|
|
637
|
+
const resolved = value ?? fallback;
|
|
638
|
+
if (!Number.isFinite(resolved) || resolved <= 0)
|
|
639
|
+
throw new Error(`${name} must be a positive number`);
|
|
640
|
+
return resolved;
|
|
641
|
+
}
|
|
642
|
+
function positiveInteger(value, fallback, name) {
|
|
643
|
+
const resolved = positiveDuration(value, fallback, name);
|
|
644
|
+
if (!Number.isInteger(resolved)) throw new Error(`${name} must be an integer`);
|
|
645
|
+
return resolved;
|
|
646
|
+
}
|
|
647
|
+
function requireNonEmpty(value, name) {
|
|
648
|
+
if (value.trim().length === 0) throw new Error(`${name} must not be empty`);
|
|
649
|
+
}
|
|
650
|
+
function isPermanentRegistrationFailure(code) {
|
|
651
|
+
return code === 4002 || code === 4003 || code === 4004;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
export { RemoteWorkerServer, WORKER_PROTOCOL_VERSION, WorkerConnection, connectWorkerHost };
|
|
655
|
+
//# sourceMappingURL=chunk-L7S2TKUG.js.map
|
|
656
|
+
//# sourceMappingURL=chunk-L7S2TKUG.js.map
|