@agents24/node 0.5.26 → 0.5.28
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 +7 -1
- package/compatibility.json +7 -7
- package/dist/artifacts.cjs +2 -1
- package/dist/artifacts.cjs.map +1 -1
- package/dist/artifacts.d.cts +23 -2
- package/dist/artifacts.d.ts +23 -2
- package/dist/artifacts.js +2 -1
- package/dist/artifacts.js.map +1 -1
- package/dist/bff.cjs +60 -11
- package/dist/bff.cjs.map +1 -1
- package/dist/bff.d.cts +2 -1
- package/dist/bff.d.ts +2 -1
- package/dist/bff.js +60 -11
- package/dist/bff.js.map +1 -1
- package/dist/{client-yYT9UnqF.d.cts → client-yHQmkcMz.d.cts} +269 -12
- package/dist/{client-yYT9UnqF.d.ts → client-yHQmkcMz.d.ts} +269 -12
- package/dist/index.cjs +174 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -3
- package/dist/index.d.ts +12 -3
- package/dist/index.js +173 -15
- package/dist/index.js.map +1 -1
- package/dist/relay.cjs +514 -0
- package/dist/relay.cjs.map +1 -0
- package/dist/relay.d.cts +98 -0
- package/dist/relay.d.ts +98 -0
- package/dist/relay.js +511 -0
- package/dist/relay.js.map +1 -0
- package/dist/server.cjs +80 -10
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +3 -0
- package/dist/server.d.ts +3 -0
- package/dist/server.js +80 -10
- package/dist/server.js.map +1 -1
- package/dist/types/agents.d.ts +1 -0
- package/dist/types/agents.d.ts.map +1 -1
- package/dist/types/artifacts.d.ts +22 -1
- package/dist/types/artifacts.d.ts.map +1 -1
- package/dist/types/bff-request.d.ts +5 -3
- package/dist/types/bff-request.d.ts.map +1 -1
- package/dist/types/bff.d.ts.map +1 -1
- package/dist/types/client.d.ts +4 -0
- package/dist/types/client.d.ts.map +1 -1
- package/dist/types/embed-run-wait.d.ts +9 -0
- package/dist/types/embed-run-wait.d.ts.map +1 -0
- package/dist/types/embed-types.d.ts +15 -2
- package/dist/types/embed-types.d.ts.map +1 -1
- package/dist/types/embed.d.ts +5 -1
- package/dist/types/embed.d.ts.map +1 -1
- package/dist/types/generated/delegation-types.d.ts +3 -2
- package/dist/types/generated/delegation-types.d.ts.map +1 -1
- package/dist/types/generated/ingestion-types.d.ts +33 -1
- package/dist/types/generated/ingestion-types.d.ts.map +1 -1
- package/dist/types/generated/ingestionJobs.d.ts +2 -2
- package/dist/types/generated/ingestionJobs.d.ts.map +1 -1
- package/dist/types/generated/knowledgeStores.d.ts +2 -1
- package/dist/types/generated/knowledgeStores.d.ts.map +1 -1
- package/dist/types/generated/manifest.d.ts +1 -1
- package/dist/types/generated/manifest.d.ts.map +1 -1
- package/dist/types/generated/model-capabilities.d.ts +4 -0
- package/dist/types/generated/model-capabilities.d.ts.map +1 -1
- package/dist/types/generated/relayClients.d.ts +13 -0
- package/dist/types/generated/relayClients.d.ts.map +1 -0
- package/dist/types/generated/resourceInstallations.d.ts +1 -2
- package/dist/types/generated/resourceInstallations.d.ts.map +1 -1
- package/dist/types/generated/run-usage.d.ts +12 -0
- package/dist/types/generated/run-usage.d.ts.map +1 -0
- package/dist/types/http.d.ts +1 -0
- package/dist/types/http.d.ts.map +1 -1
- package/dist/types/index.d.ts +3 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/models.d.ts +92 -0
- package/dist/types/models.d.ts.map +1 -0
- package/dist/types/relay-http.d.ts +14 -0
- package/dist/types/relay-http.d.ts.map +1 -0
- package/dist/types/relay.d.ts +89 -0
- package/dist/types/relay.d.ts.map +1 -0
- package/dist/types/server.d.ts +3 -0
- package/dist/types/server.d.ts.map +1 -1
- package/dist/types/types.d.ts +95 -6
- package/dist/types/types.d.ts.map +1 -1
- package/package.json +9 -3
package/dist/relay.cjs
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
require('buffer');
|
|
5
|
+
require('http');
|
|
6
|
+
|
|
7
|
+
// src/relay.ts
|
|
8
|
+
var ARTIFACT_VERIFICATION_PURPOSE = "agents24.artifact.verify.v1";
|
|
9
|
+
function signArtifactPayload(input) {
|
|
10
|
+
const timestamp = String(input.timestamp || Date.now());
|
|
11
|
+
const signature = crypto.createHmac("sha256", input.signingSecret).update(`${timestamp}.${input.body}`).digest("hex");
|
|
12
|
+
return { "x-agents24-timestamp": timestamp, "x-agents24-signature": `sha256=${signature}` };
|
|
13
|
+
}
|
|
14
|
+
function createArtifactVerificationProof(input) {
|
|
15
|
+
const proof = crypto.createHmac("sha256", input.signingSecret).update(`${ARTIFACT_VERIFICATION_PURPOSE}.${input.challenge}`).digest("hex");
|
|
16
|
+
return `sha256=${proof}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// src/relay-http.ts
|
|
20
|
+
var RELAY_MESSAGE_LIMIT = 1048576;
|
|
21
|
+
async function boundedJson(response) {
|
|
22
|
+
if (!response.body) throw new Error("Artifact returned an empty response");
|
|
23
|
+
const reader = response.body.getReader();
|
|
24
|
+
const chunks = [];
|
|
25
|
+
let length = 0;
|
|
26
|
+
try {
|
|
27
|
+
while (true) {
|
|
28
|
+
const next = await reader.read();
|
|
29
|
+
if (next.done) break;
|
|
30
|
+
length += next.value.byteLength;
|
|
31
|
+
if (length > RELAY_MESSAGE_LIMIT) throw new Error("Artifact response exceeds 1 MiB");
|
|
32
|
+
chunks.push(next.value);
|
|
33
|
+
}
|
|
34
|
+
} catch (error) {
|
|
35
|
+
await reader.cancel().catch(() => {
|
|
36
|
+
});
|
|
37
|
+
throw error;
|
|
38
|
+
} finally {
|
|
39
|
+
reader.releaseLock();
|
|
40
|
+
}
|
|
41
|
+
const result = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
42
|
+
if (!result || typeof result !== "object" || Array.isArray(result)) throw new Error("Artifact returned invalid JSON");
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
function localUrl(endpoint, path) {
|
|
46
|
+
const base = new URL(endpoint.baseUrl);
|
|
47
|
+
if (!["127.0.0.1", "localhost", "[::1]"].includes(base.hostname) || base.protocol !== "http:" || base.username || base.password) {
|
|
48
|
+
throw new TypeError("Relay Artifact endpoints must use local loopback HTTP");
|
|
49
|
+
}
|
|
50
|
+
if (!path.startsWith("/") || path.startsWith("//") || /[\\?#\s]/.test(path)) throw new TypeError("Invalid Artifact endpoint path");
|
|
51
|
+
return new URL(path, base);
|
|
52
|
+
}
|
|
53
|
+
function localPost(endpoint, path, payload, signal, fetchImpl = fetch) {
|
|
54
|
+
const body = JSON.stringify(payload);
|
|
55
|
+
if (Buffer.byteLength(body) > RELAY_MESSAGE_LIMIT) throw new Error("Artifact request exceeds 1 MiB");
|
|
56
|
+
const signature = endpoint.signingSecret ? signArtifactPayload({ body, signingSecret: endpoint.signingSecret }) : {};
|
|
57
|
+
return fetchImpl(localUrl(endpoint, path), {
|
|
58
|
+
method: "POST",
|
|
59
|
+
headers: { "content-type": "application/json", ...signature },
|
|
60
|
+
body,
|
|
61
|
+
signal,
|
|
62
|
+
redirect: "error"
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
async function inspectEndpoint(endpoint, fetchImpl = fetch) {
|
|
66
|
+
const manifestResponse = await fetchImpl(localUrl(endpoint, endpoint.manifestPath || "/.well-known/agents24/artifact"), {
|
|
67
|
+
signal: AbortSignal.timeout(15e3),
|
|
68
|
+
redirect: "error"
|
|
69
|
+
});
|
|
70
|
+
if (!manifestResponse.ok) throw new Error("Artifact manifest is unavailable");
|
|
71
|
+
const manifest = await boundedJson(manifestResponse);
|
|
72
|
+
const healthResponse = await fetchImpl(localUrl(endpoint, endpoint.healthPath || manifest.endpoints?.health_path || "/.well-known/agents24/artifact/health"), {
|
|
73
|
+
signal: AbortSignal.timeout(15e3),
|
|
74
|
+
redirect: "error"
|
|
75
|
+
});
|
|
76
|
+
const health = await boundedJson(healthResponse);
|
|
77
|
+
if (!healthResponse.ok || !["ok", "healthy", "online"].includes(health.status)) throw new Error("Artifact is unhealthy");
|
|
78
|
+
if (manifest.invocation_auth?.mode === "hmac_sha256" && !endpoint.signingSecret) throw new Error("Artifact requires a local signing secret");
|
|
79
|
+
const challenge = `${crypto.randomUUID()}-${crypto.randomUUID()}`;
|
|
80
|
+
const verifyResponse = await localPost(endpoint, endpoint.verifyPath || manifest.endpoints?.verify_path || "/.well-known/agents24/artifact/verify", {
|
|
81
|
+
challenge,
|
|
82
|
+
purpose: ARTIFACT_VERIFICATION_PURPOSE
|
|
83
|
+
}, AbortSignal.timeout(15e3), fetchImpl);
|
|
84
|
+
const verification = await boundedJson(verifyResponse);
|
|
85
|
+
if (!verifyResponse.ok || verification.status !== "ok" || verification.challenge !== challenge || verification.auth_mode !== manifest.invocation_auth?.mode || manifest.invocation_auth?.mode === "none" && verification.proof != null && verification.proof !== "" || manifest.invocation_auth?.mode === "hmac_sha256" && endpoint.signingSecret && verification.proof !== createArtifactVerificationProof({ challenge, signingSecret: endpoint.signingSecret })) {
|
|
86
|
+
throw new Error("Artifact connection verification failed");
|
|
87
|
+
}
|
|
88
|
+
return manifest;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/relay.ts
|
|
92
|
+
var keyOf = (artifactId, target) => `${artifactId}:${target}`;
|
|
93
|
+
var terminalAuth = (error) => [401, 403, 404, 410].includes(error?.status);
|
|
94
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
95
|
+
var ArtifactRelay = class {
|
|
96
|
+
constructor(options) {
|
|
97
|
+
this.options = options;
|
|
98
|
+
this.clientId = options.clientId;
|
|
99
|
+
this.fetchImpl = options.fetchImpl || fetch;
|
|
100
|
+
const base = new URL(options.baseUrl);
|
|
101
|
+
if (base.protocol !== "https:" && !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname))) {
|
|
102
|
+
throw new TypeError("Agents24 relay requires HTTPS or local loopback HTTP");
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
options;
|
|
106
|
+
clientId;
|
|
107
|
+
desired = /* @__PURE__ */ new Map();
|
|
108
|
+
pending = /* @__PURE__ */ new Map();
|
|
109
|
+
invocations = /* @__PURE__ */ new Map();
|
|
110
|
+
socket = null;
|
|
111
|
+
generation = 0;
|
|
112
|
+
state = "idle";
|
|
113
|
+
stopped = false;
|
|
114
|
+
supervisor = null;
|
|
115
|
+
startupResolve = null;
|
|
116
|
+
startupReject = null;
|
|
117
|
+
startup = null;
|
|
118
|
+
queue = [];
|
|
119
|
+
queuedBytes = 0;
|
|
120
|
+
flushing = false;
|
|
121
|
+
restoreTail = Promise.resolve();
|
|
122
|
+
fetchImpl;
|
|
123
|
+
get status() {
|
|
124
|
+
return { clientId: this.clientId, state: this.state, registrations: [...this.desired.values()].map((e) => ({
|
|
125
|
+
artifactId: e.config.artifactId,
|
|
126
|
+
target: e.config.target,
|
|
127
|
+
ready: e.ready,
|
|
128
|
+
contractStatus: e.contractStatus,
|
|
129
|
+
manifestHash: e.manifestHash
|
|
130
|
+
})) };
|
|
131
|
+
}
|
|
132
|
+
report(state = this.state) {
|
|
133
|
+
this.state = state;
|
|
134
|
+
try {
|
|
135
|
+
this.options.onStatus?.(this.status);
|
|
136
|
+
} catch {
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
grants() {
|
|
140
|
+
return [...this.desired.values()].map(({ config: c }) => ({
|
|
141
|
+
artifact_id: c.artifactId,
|
|
142
|
+
target: c.target,
|
|
143
|
+
...c.authoring ? { authoring: true } : {},
|
|
144
|
+
...c.installationId ? { installation_id: c.installationId } : {},
|
|
145
|
+
...c.resourceKey ? { resource_key: c.resourceKey } : {}
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
148
|
+
async register(config) {
|
|
149
|
+
if (this.stopped) throw new Error("Relay is closed");
|
|
150
|
+
const key = keyOf(config.artifactId, config.target);
|
|
151
|
+
const entry = { config: { ...config }, id: this.desired.get(key)?.id, ready: false, contractStatus: "unverified" };
|
|
152
|
+
this.desired.set(key, entry);
|
|
153
|
+
try {
|
|
154
|
+
entry.manifest = await inspectEndpoint(config, this.fetchImpl);
|
|
155
|
+
} catch (error) {
|
|
156
|
+
entry.contractStatus = "unavailable";
|
|
157
|
+
if (entry.id && this.state === "connected") await this.command({ type: "unregister", registration_id: entry.id }).catch(() => {
|
|
158
|
+
});
|
|
159
|
+
this.report();
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
if (this.state === "connected") {
|
|
163
|
+
await this.serializeRestore(async () => {
|
|
164
|
+
await this.authorize();
|
|
165
|
+
await this.publishRegistration(entry);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
this.report();
|
|
169
|
+
return this.status;
|
|
170
|
+
}
|
|
171
|
+
async unregister(artifactId, target) {
|
|
172
|
+
const key = keyOf(artifactId, target);
|
|
173
|
+
const entry = this.desired.get(key);
|
|
174
|
+
this.desired.delete(key);
|
|
175
|
+
if (entry?.id && this.state === "connected") await this.command({ type: "unregister", registration_id: entry.id });
|
|
176
|
+
this.report();
|
|
177
|
+
}
|
|
178
|
+
/** Development callers use this after observing a local manifest change. */
|
|
179
|
+
async refresh(artifactId, target) {
|
|
180
|
+
const entry = this.desired.get(keyOf(artifactId, target));
|
|
181
|
+
if (!entry) return;
|
|
182
|
+
const manifest = await inspectEndpoint(entry.config, this.fetchImpl);
|
|
183
|
+
if (entry.ready && JSON.stringify(manifest) === JSON.stringify(entry.manifest)) return;
|
|
184
|
+
entry.manifest = manifest;
|
|
185
|
+
entry.ready = false;
|
|
186
|
+
if (this.state === "connected") await this.serializeRestore(() => this.publishRegistration(entry));
|
|
187
|
+
}
|
|
188
|
+
async connect() {
|
|
189
|
+
if (this.stopped) throw new Error("Relay is closed");
|
|
190
|
+
if (this.state === "connected") return;
|
|
191
|
+
if (!this.supervisor) {
|
|
192
|
+
this.startup = new Promise((resolve, reject) => {
|
|
193
|
+
this.startupResolve = resolve;
|
|
194
|
+
this.startupReject = reject;
|
|
195
|
+
});
|
|
196
|
+
this.supervisor = this.supervise();
|
|
197
|
+
}
|
|
198
|
+
let timer;
|
|
199
|
+
try {
|
|
200
|
+
await Promise.race([this.startup, new Promise((_, reject) => {
|
|
201
|
+
timer = setTimeout(() => reject(new Error("Relay startup timed out; reconnect continues in the background")), this.options.startupTimeoutMs ?? 3e4);
|
|
202
|
+
})]);
|
|
203
|
+
} finally {
|
|
204
|
+
if (timer) clearTimeout(timer);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
serializeRestore(operation) {
|
|
208
|
+
const result = this.restoreTail.then(operation);
|
|
209
|
+
this.restoreTail = result.catch(() => {
|
|
210
|
+
});
|
|
211
|
+
return result;
|
|
212
|
+
}
|
|
213
|
+
async ticket() {
|
|
214
|
+
const controller = new AbortController();
|
|
215
|
+
let timer;
|
|
216
|
+
try {
|
|
217
|
+
const ticket = await Promise.race([
|
|
218
|
+
this.options.getTicket({ clientId: this.clientId, registrations: this.grants(), signal: controller.signal }),
|
|
219
|
+
new Promise((_, reject) => {
|
|
220
|
+
timer = setTimeout(() => {
|
|
221
|
+
controller.abort();
|
|
222
|
+
reject(new Error("Relay ticket request timed out"));
|
|
223
|
+
}, 15e3);
|
|
224
|
+
})
|
|
225
|
+
]);
|
|
226
|
+
if (ticket.client_id !== this.clientId || ticket.protocol !== "agents24-artifact-relay.v2") throw new Error("Relay admission protocol mismatch");
|
|
227
|
+
return ticket;
|
|
228
|
+
} finally {
|
|
229
|
+
clearTimeout(timer);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
async authorize() {
|
|
233
|
+
const ticket = await this.ticket();
|
|
234
|
+
await this.command({ type: "authorize", relay_token: ticket.relay_token });
|
|
235
|
+
}
|
|
236
|
+
async supervise() {
|
|
237
|
+
let attempts = 0;
|
|
238
|
+
while (!this.stopped) {
|
|
239
|
+
this.report(attempts ? "reconnecting" : "connecting");
|
|
240
|
+
try {
|
|
241
|
+
const ticket = await this.ticket();
|
|
242
|
+
if (this.stopped) break;
|
|
243
|
+
await this.connection(ticket);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (terminalAuth(error)) {
|
|
246
|
+
this.stopped = true;
|
|
247
|
+
this.report("failed");
|
|
248
|
+
this.startupReject?.(new Error("Relay authentication failed"));
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (this.stopped) break;
|
|
253
|
+
const delay = Math.min(3e4, 1e3 * 2 ** Math.min(attempts++, 5) * (0.75 + Math.random() * 0.5));
|
|
254
|
+
const end = Date.now() + delay;
|
|
255
|
+
while (!this.stopped && Date.now() < end) await sleep(Math.min(100, end - Date.now()));
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
connection(ticket) {
|
|
259
|
+
return new Promise((resolve, reject) => {
|
|
260
|
+
const url = new URL(ticket.relay_path, this.options.baseUrl);
|
|
261
|
+
const expected = new URL(this.options.baseUrl);
|
|
262
|
+
if (url.origin !== expected.origin || url.username || url.password) {
|
|
263
|
+
reject(new Error("Invalid relay admission URL"));
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
267
|
+
const generation = ++this.generation;
|
|
268
|
+
const socket = (this.options.webSocketFactory || ((u, p) => new WebSocket(u, p)))(url.href, [ticket.protocol, `agents24-credential-${ticket.relay_token}`]);
|
|
269
|
+
this.socket = socket;
|
|
270
|
+
let heartbeat;
|
|
271
|
+
let endpointHealth;
|
|
272
|
+
let inspecting = false;
|
|
273
|
+
let unanswered = 0;
|
|
274
|
+
let initialized = false;
|
|
275
|
+
const startupTimer = setTimeout(() => socket.close(1e3, "Relay READY timed out"), 15e3);
|
|
276
|
+
const current = () => this.socket === socket && generation === this.generation;
|
|
277
|
+
socket.addEventListener("message", (event) => {
|
|
278
|
+
if (!current()) return;
|
|
279
|
+
void (async () => {
|
|
280
|
+
if (typeof event.data !== "string" || Buffer.byteLength(event.data) > RELAY_MESSAGE_LIMIT) throw new Error("Invalid relay frame");
|
|
281
|
+
const frame = JSON.parse(event.data);
|
|
282
|
+
if (frame.type === "ready") {
|
|
283
|
+
if (initialized || frame.client_id !== this.clientId) throw new Error("Invalid relay READY");
|
|
284
|
+
initialized = true;
|
|
285
|
+
clearTimeout(startupTimer);
|
|
286
|
+
this.report("connected");
|
|
287
|
+
heartbeat = setInterval(() => {
|
|
288
|
+
if (!current()) return;
|
|
289
|
+
if (++unanswered >= 3) {
|
|
290
|
+
socket.close(1e3, "Relay heartbeat timed out");
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
this.send({ type: "ping", id: crypto.randomUUID() });
|
|
294
|
+
}, 3e4);
|
|
295
|
+
const restore = async () => {
|
|
296
|
+
if (inspecting || !current() || this.stopped) return;
|
|
297
|
+
inspecting = true;
|
|
298
|
+
try {
|
|
299
|
+
const entries = [...this.desired.values()];
|
|
300
|
+
for (let i = 0; i < entries.length; i += 8) await Promise.allSettled(entries.slice(i, i + 8).map(async (entry) => {
|
|
301
|
+
try {
|
|
302
|
+
const manifest = await inspectEndpoint(entry.config, this.fetchImpl);
|
|
303
|
+
if (!current() || this.stopped || this.desired.get(keyOf(entry.config.artifactId, entry.config.target)) !== entry) return;
|
|
304
|
+
const changed = JSON.stringify(manifest) !== JSON.stringify(entry.manifest);
|
|
305
|
+
entry.manifest = manifest;
|
|
306
|
+
if (!entry.ready || changed) await this.publishRegistration(entry);
|
|
307
|
+
} catch {
|
|
308
|
+
entry.ready = false;
|
|
309
|
+
entry.contractStatus = "unavailable";
|
|
310
|
+
if (entry.id && current()) await this.command({ type: "unregister", registration_id: entry.id }).catch(() => {
|
|
311
|
+
});
|
|
312
|
+
this.report();
|
|
313
|
+
}
|
|
314
|
+
}));
|
|
315
|
+
} finally {
|
|
316
|
+
inspecting = false;
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
endpointHealth = setInterval(() => {
|
|
320
|
+
void this.serializeRestore(restore);
|
|
321
|
+
}, 3e4);
|
|
322
|
+
await this.serializeRestore(restore);
|
|
323
|
+
this.report();
|
|
324
|
+
this.startupResolve?.();
|
|
325
|
+
} else if (frame.type === "pong") unanswered = 0;
|
|
326
|
+
else if (frame.type === "invoke") void this.invoke(frame).catch(() => socket.close(1e3, "Relay invocation transport failed"));
|
|
327
|
+
else if (frame.type === "cancel") void this.cancel(String(frame.run_id));
|
|
328
|
+
else {
|
|
329
|
+
const pending = this.pending.get(frame.request_id);
|
|
330
|
+
if (pending) {
|
|
331
|
+
this.pending.delete(frame.request_id);
|
|
332
|
+
clearTimeout(pending.timer);
|
|
333
|
+
if (frame.type === "error") pending.reject(Object.assign(new Error("Relay operation rejected"), { code: frame.failure?.code }));
|
|
334
|
+
else pending.resolve(frame);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
})().catch(() => {
|
|
338
|
+
if (current()) socket.close(1002, "Invalid relay protocol");
|
|
339
|
+
});
|
|
340
|
+
});
|
|
341
|
+
socket.addEventListener("error", () => {
|
|
342
|
+
});
|
|
343
|
+
socket.addEventListener("close", (event) => {
|
|
344
|
+
clearTimeout(startupTimer);
|
|
345
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
346
|
+
if (endpointHealth) clearInterval(endpointHealth);
|
|
347
|
+
if (current()) {
|
|
348
|
+
this.socket = null;
|
|
349
|
+
this.queue = [];
|
|
350
|
+
this.queuedBytes = 0;
|
|
351
|
+
for (const pending of this.pending.values()) {
|
|
352
|
+
clearTimeout(pending.timer);
|
|
353
|
+
pending.reject(new Error("Relay disconnected"));
|
|
354
|
+
}
|
|
355
|
+
this.pending.clear();
|
|
356
|
+
for (const entry of this.desired.values()) {
|
|
357
|
+
entry.ready = false;
|
|
358
|
+
entry.id = void 0;
|
|
359
|
+
}
|
|
360
|
+
for (const runId of this.invocations.keys()) void this.cancel(runId);
|
|
361
|
+
if (event.code === 1008) {
|
|
362
|
+
this.stopped = true;
|
|
363
|
+
this.report(event.reason.includes("revoked") ? "revoked" : "failed");
|
|
364
|
+
this.startupReject?.(new Error("Relay connection revoked or replaced"));
|
|
365
|
+
} else if (!this.stopped) this.report("reconnecting");
|
|
366
|
+
}
|
|
367
|
+
if (!initialized) this.startupReject?.(new Error("Relay closed before READY; transient reconnect continues in the background"));
|
|
368
|
+
if (!initialized && event.code === 1008) reject(Object.assign(new Error("Relay admission rejected"), { status: 403 }));
|
|
369
|
+
else resolve();
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
async publishRegistration(entry) {
|
|
374
|
+
const result = await this.command({
|
|
375
|
+
type: "register",
|
|
376
|
+
artifact_id: entry.config.artifactId,
|
|
377
|
+
target: entry.config.target,
|
|
378
|
+
manifest: entry.manifest,
|
|
379
|
+
cancel_supported: Boolean(entry.manifest?.runtime?.cancel_path)
|
|
380
|
+
});
|
|
381
|
+
entry.id = result.registration_id;
|
|
382
|
+
entry.manifestHash = result.manifest_hash;
|
|
383
|
+
entry.contractStatus = result.contract_status;
|
|
384
|
+
entry.ready = result.contract_status === "healthy";
|
|
385
|
+
this.report();
|
|
386
|
+
}
|
|
387
|
+
command(frame) {
|
|
388
|
+
return new Promise((resolve, reject) => {
|
|
389
|
+
const id = crypto.randomUUID();
|
|
390
|
+
const timer = setTimeout(() => {
|
|
391
|
+
this.pending.delete(id);
|
|
392
|
+
reject(new Error("Relay operation timed out"));
|
|
393
|
+
}, 15e3);
|
|
394
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
395
|
+
try {
|
|
396
|
+
this.send({ ...frame, request_id: id });
|
|
397
|
+
} catch (error) {
|
|
398
|
+
this.pending.delete(id);
|
|
399
|
+
clearTimeout(timer);
|
|
400
|
+
reject(error);
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
send(frame, control = true) {
|
|
405
|
+
if (!this.socket || this.socket.readyState !== 1) throw new Error("Relay is disconnected");
|
|
406
|
+
const data = JSON.stringify(frame), size = Buffer.byteLength(data);
|
|
407
|
+
if (size > RELAY_MESSAGE_LIMIT || this.queuedBytes + size > 8 * RELAY_MESSAGE_LIMIT || this.queue.length >= 1024) throw new Error("Relay output limit exceeded");
|
|
408
|
+
this.queuedBytes += size;
|
|
409
|
+
if (control) this.queue.splice(this.queue.findIndex((item) => !item.control) < 0 ? this.queue.length : this.queue.findIndex((item) => !item.control), 0, { data, control });
|
|
410
|
+
else this.queue.push({ data, control });
|
|
411
|
+
void this.flush();
|
|
412
|
+
}
|
|
413
|
+
async flush() {
|
|
414
|
+
if (this.flushing) return;
|
|
415
|
+
this.flushing = true;
|
|
416
|
+
const socket = this.socket;
|
|
417
|
+
let stalled = 0;
|
|
418
|
+
try {
|
|
419
|
+
while (this.queue.length && socket === this.socket && socket?.readyState === 1) {
|
|
420
|
+
if (socket.bufferedAmount > 512 * 1024) {
|
|
421
|
+
if (++stalled > 500) {
|
|
422
|
+
socket.close(1e3, "Relay output stalled");
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
await sleep(10);
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
stalled = 0;
|
|
429
|
+
const next = this.queue.shift();
|
|
430
|
+
this.queuedBytes -= Buffer.byteLength(next.data);
|
|
431
|
+
socket.send(next.data);
|
|
432
|
+
}
|
|
433
|
+
} catch {
|
|
434
|
+
socket?.close(1e3, "Relay write failed");
|
|
435
|
+
} finally {
|
|
436
|
+
this.flushing = false;
|
|
437
|
+
if (this.queue.length && this.socket?.readyState === 1) void this.flush();
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
async invoke(frame) {
|
|
441
|
+
const entry = this.desired.get(keyOf(frame.artifact_id, frame.target));
|
|
442
|
+
const reject = () => this.send({
|
|
443
|
+
type: "response",
|
|
444
|
+
request_id: frame.request_id,
|
|
445
|
+
status: 503,
|
|
446
|
+
body: { status: "failed", error: { code: "ARTIFACT_NOT_READY", message: "Local Artifact is unavailable", safe: true } }
|
|
447
|
+
});
|
|
448
|
+
if (!entry?.ready || entry.id !== frame.registration_id || entry.manifestHash !== frame.manifest_hash || this.invocations.has(frame.run_id) || !Number.isFinite(frame.deadline) || Number(frame.deadline) * 1e3 <= Date.now()) {
|
|
449
|
+
reject();
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
if (this.invocations.size >= 64 || [...this.invocations.values()].filter((i) => i.entry === entry).length >= 16) {
|
|
453
|
+
reject();
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
const controller = new AbortController();
|
|
457
|
+
const generation = this.generation;
|
|
458
|
+
const timer = setTimeout(() => void this.cancel(frame.run_id), Math.max(1, Number(frame.deadline) * 1e3 - Date.now()));
|
|
459
|
+
this.invocations.set(frame.run_id, { controller, entry, cancelPath: entry.manifest?.runtime?.cancel_path });
|
|
460
|
+
this.send({ type: "accepted", request_id: frame.request_id });
|
|
461
|
+
try {
|
|
462
|
+
const response = await localPost(entry.config, entry.config.invokePath || "/agents24/artifact/invoke", {
|
|
463
|
+
...frame.body,
|
|
464
|
+
deadline: frame.deadline
|
|
465
|
+
}, controller.signal, this.fetchImpl);
|
|
466
|
+
const body = await boundedJson(response);
|
|
467
|
+
if (this.generation === generation && this.socket?.readyState === 1) this.send({ type: "response", request_id: frame.request_id, status: response.status, body }, false);
|
|
468
|
+
} catch {
|
|
469
|
+
if (this.generation === generation && this.socket?.readyState === 1) this.send({
|
|
470
|
+
type: "response",
|
|
471
|
+
request_id: frame.request_id,
|
|
472
|
+
status: 200,
|
|
473
|
+
body: {
|
|
474
|
+
status: "failed",
|
|
475
|
+
error: { code: "TOOL_EXECUTION_INDETERMINATE", message: "Local execution outcome is unknown", safe: true }
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
} finally {
|
|
479
|
+
clearTimeout(timer);
|
|
480
|
+
this.invocations.delete(frame.run_id);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
async cancel(runId) {
|
|
484
|
+
const active = this.invocations.get(runId);
|
|
485
|
+
if (!active) return;
|
|
486
|
+
active.controller.abort();
|
|
487
|
+
if (active.cancelPath) {
|
|
488
|
+
try {
|
|
489
|
+
await localPost(active.entry.config, active.cancelPath, { run_id: runId }, AbortSignal.timeout(5e3), this.fetchImpl);
|
|
490
|
+
} catch {
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
async close() {
|
|
495
|
+
this.stopped = true;
|
|
496
|
+
for (const pending of this.pending.values()) {
|
|
497
|
+
clearTimeout(pending.timer);
|
|
498
|
+
pending.reject(new Error("Relay closed"));
|
|
499
|
+
}
|
|
500
|
+
this.pending.clear();
|
|
501
|
+
this.startupReject?.(new Error("Relay closed before startup"));
|
|
502
|
+
await Promise.allSettled([...this.invocations.keys()].map((id) => this.cancel(id)));
|
|
503
|
+
this.socket?.close(1e3, "Application relay closed");
|
|
504
|
+
this.report("closed");
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
function createArtifactRelay(options) {
|
|
508
|
+
return new ArtifactRelay(options);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
exports.ArtifactRelay = ArtifactRelay;
|
|
512
|
+
exports.createArtifactRelay = createArtifactRelay;
|
|
513
|
+
//# sourceMappingURL=relay.cjs.map
|
|
514
|
+
//# sourceMappingURL=relay.cjs.map
|