@certalis/agent-smith 0.1.8 → 0.1.10

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.
@@ -10,11 +10,11 @@
10
10
  href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap"
11
11
  rel="stylesheet"
12
12
  />
13
- <title>ccflare Dashboard</title>
13
+ <title>Agent Smith Dashboard</title>
14
14
  <script>
15
15
  // Apply theme before first paint to prevent flash
16
16
  try {
17
- const raw = localStorage.getItem("ccflare-theme");
17
+ const raw = localStorage.getItem("agent-smith-theme");
18
18
  if (raw) {
19
19
  const { appearance } = JSON.parse(raw);
20
20
  if (appearance) document.documentElement.classList.add(appearance);
@@ -32,7 +32,7 @@
32
32
  }
33
33
  </script>
34
34
 
35
- <link rel="stylesheet" crossorigin href="./chunk-r6qvhv5e.css"><script type="module" crossorigin src="./chunk-h03pp3xg.js"></script></head>
35
+ <link rel="stylesheet" crossorigin href="./chunk-r6qvhv5e.css"><script type="module" crossorigin src="./chunk-rnbsj0t8.js"></script></head>
36
36
  <body>
37
37
  <div id="root"></div>
38
38
  </body>
@@ -1,7 +1,7 @@
1
1
  {
2
- "/chunk-h03pp3xg.js": "/chunk-h03pp3xg.js",
2
+ "/chunk-rnbsj0t8.js": "/chunk-rnbsj0t8.js",
3
3
  "/index.html": "/index.html",
4
4
  "/chunk-r6qvhv5e.css": "/chunk-r6qvhv5e.css",
5
- "/chunk-h03pp3xg.js.map": "/chunk-h03pp3xg.js.map",
5
+ "/chunk-rnbsj0t8.js.map": "/chunk-rnbsj0t8.js.map",
6
6
  "/favicon-7fef0tsq.svg": "/favicon-7fef0tsq.svg"
7
7
  }
package/dist/edge.js CHANGED
@@ -71,12 +71,14 @@ function createProxyEdgeHandler({
71
71
  origin,
72
72
  socketPath,
73
73
  maxBodyBytes = 64 * 1024 * 1024,
74
- timeoutMs = 300000
74
+ timeoutMs = 300000,
75
+ maxConcurrentRequests = 128
75
76
  }) {
76
77
  const url = new URL(origin);
77
- if (url.protocol !== "https:" || url.origin !== origin || !isAbsolute(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1) {
78
+ if (url.protocol !== "https:" || url.origin !== origin || !isAbsolute(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || !Number.isSafeInteger(maxConcurrentRequests) || maxConcurrentRequests < 1) {
78
79
  throw new Error("Proxy edge requires an exact HTTPS origin, an absolute socket path and positive limits");
79
80
  }
81
+ let activeRequests = 0;
80
82
  return (req, res) => {
81
83
  const finish = (status) => {
82
84
  if (res.writableEnded || res.destroyed)
@@ -94,6 +96,9 @@ function createProxyEdgeHandler({
94
96
  const rejected = requestFailure(req, origin, maxBodyBytes);
95
97
  if (rejected)
96
98
  return finish(rejected);
99
+ if (activeRequests >= maxConcurrentRequests)
100
+ return finish(503);
101
+ activeRequests++;
97
102
  const path = req.method === "GET" && req.url === "/pool-health" ? "/health" : req.url ?? "";
98
103
  const headers = selectHeaders(req.headers, REQUEST_HEADERS);
99
104
  headers.host = "localhost";
@@ -126,6 +131,7 @@ function createProxyEdgeHandler({
126
131
  finish(504);
127
132
  }, timeoutMs);
128
133
  res.once("close", () => {
134
+ activeRequests--;
129
135
  clearTimeout(timer);
130
136
  upstreamResponse?.destroy();
131
137
  upstream.destroy();
@@ -142,6 +148,7 @@ function createProxyEdgeHandler({
142
148
  finish(413);
143
149
  }
144
150
  });
151
+ upstream.flushHeaders();
145
152
  req.pipe(upstream);
146
153
  };
147
154
  }
package/dist/https.js ADDED
@@ -0,0 +1,420 @@
1
+ // src/https.ts
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ // ../../packages/config/src/standalone.ts
5
+ import {
6
+ closeSync,
7
+ constants,
8
+ fstatSync,
9
+ openSync,
10
+ readFileSync
11
+ } from "node:fs";
12
+ import { dirname, isAbsolute, join } from "node:path";
13
+ function readKeysFile(path) {
14
+ let descriptor;
15
+ try {
16
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
17
+ const stat = fstatSync(descriptor);
18
+ if (!stat.isFile() || stat.size > 4096 || (stat.mode & 63) !== 0 || stat.uid !== 0 && stat.uid !== process.getuid?.()) {
19
+ throw new Error("Unsafe keys file");
20
+ }
21
+ return JSON.parse(readFileSync(descriptor, "utf8"));
22
+ } catch {
23
+ throw new Error("Agent Smith requires a readable owner-only private keys file");
24
+ } finally {
25
+ if (descriptor !== undefined)
26
+ closeSync(descriptor);
27
+ }
28
+ }
29
+ function readStandaloneOptions(env) {
30
+ const origin = env.AGENT_SMITH_PUBLIC_ORIGIN ?? env.RENDER_EXTERNAL_URL;
31
+ try {
32
+ if (!origin || new URL(origin).protocol !== "https:" || new URL(origin).origin !== origin) {
33
+ throw new Error("Invalid origin");
34
+ }
35
+ } catch {
36
+ throw new Error("Agent Smith requires an exact HTTPS origin");
37
+ }
38
+ const port = Number(env.PORT ?? "10000");
39
+ const poolPort = Number(env.AGENT_SMITH_POOL_PORT ?? "8081");
40
+ if ([port, poolPort].some((value) => !Number.isSafeInteger(value) || value < 1 || value > 65535) || port === poolPort) {
41
+ throw new Error("Agent Smith public and private ports must be valid and distinct");
42
+ }
43
+ const stateDir = env.AGENT_SMITH_STATE_DIR ?? "/var/data/agent-smith/state";
44
+ const paths = {
45
+ stateDir,
46
+ socketPath: join(stateDir, "control.sock"),
47
+ configPath: env.AGENT_SMITH_CONFIG_PATH ?? join(stateDir, "config.json"),
48
+ dbPath: env.AGENT_SMITH_DB_PATH ?? join(stateDir, "pool.db"),
49
+ clientKeysFile: env.AGENT_SMITH_CLIENT_KEYS_FILE ?? join(stateDir, "clients.json")
50
+ };
51
+ const keysPath = env.AGENT_SMITH_KEYS_FILE ?? join(dirname(stateDir), "keys.json");
52
+ if ([...Object.values(paths), keysPath].some((path) => !isAbsolute(path))) {
53
+ throw new Error("Agent Smith state and key paths must be absolute");
54
+ }
55
+ const keys = env.AGENT_SMITH_ADMIN_KEY || env.AGENT_SMITH_PROXY_KEY ? {
56
+ adminKey: env.AGENT_SMITH_ADMIN_KEY,
57
+ proxyKey: env.AGENT_SMITH_PROXY_KEY
58
+ } : readKeysFile(keysPath);
59
+ if (!keys || typeof keys !== "object" || ![keys.adminKey, keys.proxyKey].every((key) => typeof key === "string" && /^[\x21-\x7e]{32,512}$/.test(key)) || keys.adminKey === keys.proxyKey) {
60
+ throw new Error("Agent Smith requires distinct administrator and proxy keys of at least 32 characters");
61
+ }
62
+ return {
63
+ origin,
64
+ port,
65
+ poolPort,
66
+ poolHost: env.AGENT_SMITH_POOL_HOST ?? "127.0.0.1",
67
+ ...paths,
68
+ adminKey: keys.adminKey,
69
+ proxyKey: keys.proxyKey
70
+ };
71
+ }
72
+ function poolEnvironment(options, env) {
73
+ return {
74
+ ...env,
75
+ PORT: String(options.poolPort),
76
+ AGENT_SMITH_POOL_PORT: String(options.poolPort),
77
+ AGENT_SMITH_HOST: options.poolHost,
78
+ AGENT_SMITH_STATE_DIR: options.stateDir,
79
+ AGENT_SMITH_TRUST_LOOPBACK: "false",
80
+ AGENT_SMITH_CONFIG_PATH: options.configPath,
81
+ AGENT_SMITH_DB_PATH: options.dbPath,
82
+ AGENT_SMITH_CLIENT_KEYS_FILE: options.clientKeysFile,
83
+ AGENT_SMITH_ADMIN_KEY: options.adminKey,
84
+ AGENT_SMITH_PROXY_KEY: options.proxyKey
85
+ };
86
+ }
87
+
88
+ // ../../packages/runtime-server/src/standalone.ts
89
+ import { spawn } from "node:child_process";
90
+ import { once } from "node:events";
91
+ import { lstat, mkdir, unlink } from "node:fs/promises";
92
+ import { createServer } from "node:http";
93
+ import { createConnection } from "node:net";
94
+
95
+ // ../../packages/runtime-server/src/proxy-edge.ts
96
+ import {
97
+ request
98
+ } from "node:http";
99
+ import { isAbsolute as isAbsolute2 } from "node:path";
100
+
101
+ // ../../packages/runtime-server/src/inference-routes.ts
102
+ var INFERENCE_ROUTES = new Set([
103
+ "POST /v1/claude-code/v1/messages",
104
+ "POST /v1/claude-code/v1/messages/count_tokens",
105
+ "POST /v1/pool/anthropic-messages/v1/messages",
106
+ "POST /v1/pool/anthropic-messages/v1/messages/count_tokens",
107
+ "POST /v1/codex/responses",
108
+ "POST /v1/pool/openai-responses/responses"
109
+ ]);
110
+ for (const route of [...INFERENCE_ROUTES]) {
111
+ if (route.endsWith("/messages") || route.endsWith("/count_tokens")) {
112
+ INFERENCE_ROUTES.add(`${route}?beta=true`);
113
+ }
114
+ }
115
+ function isInferenceRoute(method, path) {
116
+ return INFERENCE_ROUTES.has(`${method} ${path}`);
117
+ }
118
+
119
+ // ../../packages/runtime-server/src/proxy-edge.ts
120
+ var REQUEST_HEADERS = [
121
+ "content-type",
122
+ "accept",
123
+ "accept-encoding",
124
+ "anthropic-version",
125
+ "anthropic-beta",
126
+ "x-api-key",
127
+ "authorization",
128
+ "x-claude-code-session-id",
129
+ "session-id",
130
+ "openai-beta",
131
+ "x-client-request-id",
132
+ "user-agent"
133
+ ];
134
+ var RESPONSE_HEADERS = [
135
+ "content-type",
136
+ "content-encoding",
137
+ "retry-after",
138
+ "request-id",
139
+ "x-request-id",
140
+ "anthropic-ratelimit-requests-limit",
141
+ "anthropic-ratelimit-requests-remaining",
142
+ "anthropic-ratelimit-requests-reset",
143
+ "anthropic-ratelimit-tokens-limit",
144
+ "anthropic-ratelimit-tokens-remaining",
145
+ "anthropic-ratelimit-tokens-reset"
146
+ ];
147
+ function selectHeaders(headers, names) {
148
+ return Object.fromEntries(names.flatMap((name) => typeof headers[name] === "string" ? [[name, headers[name]]] : []));
149
+ }
150
+ function requestFailure(req, origin, maxBodyBytes) {
151
+ const health = req.method === "GET" && req.url === "/pool-health";
152
+ if (!health && !isInferenceRoute(req.method ?? "", req.url ?? ""))
153
+ return 404;
154
+ if (req.headers.host !== new URL(origin).host || req.headers.origin !== undefined && req.headers.origin !== origin || req.headers["sec-fetch-site"] !== undefined && !["none", "same-origin"].includes(String(req.headers["sec-fetch-site"])))
155
+ return 403;
156
+ if (req.headers.upgrade || req.headers.expect)
157
+ return 400;
158
+ if (req.headers["content-length"] !== undefined && (!/^\d+$/.test(req.headers["content-length"]) || Number(req.headers["content-length"]) > maxBodyBytes))
159
+ return 413;
160
+ if (!req.headers["x-api-key"] && !req.headers.authorization)
161
+ return 401;
162
+ return null;
163
+ }
164
+ function createProxyEdgeHandler({
165
+ origin,
166
+ socketPath,
167
+ maxBodyBytes = 64 * 1024 * 1024,
168
+ timeoutMs = 300000,
169
+ maxConcurrentRequests = 128
170
+ }) {
171
+ const url = new URL(origin);
172
+ if (url.protocol !== "https:" || url.origin !== origin || !isAbsolute2(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || !Number.isSafeInteger(maxConcurrentRequests) || maxConcurrentRequests < 1) {
173
+ throw new Error("Proxy edge requires an exact HTTPS origin, an absolute socket path and positive limits");
174
+ }
175
+ let activeRequests = 0;
176
+ return (req, res) => {
177
+ const finish = (status) => {
178
+ if (res.writableEnded || res.destroyed)
179
+ return;
180
+ if (res.headersSent) {
181
+ res.destroy();
182
+ return;
183
+ }
184
+ res.writeHead(status, {
185
+ "cache-control": "no-store",
186
+ connection: "close"
187
+ });
188
+ res.end();
189
+ };
190
+ const rejected = requestFailure(req, origin, maxBodyBytes);
191
+ if (rejected)
192
+ return finish(rejected);
193
+ if (activeRequests >= maxConcurrentRequests)
194
+ return finish(503);
195
+ activeRequests++;
196
+ const path = req.method === "GET" && req.url === "/pool-health" ? "/health" : req.url ?? "";
197
+ const headers = selectHeaders(req.headers, REQUEST_HEADERS);
198
+ headers.host = "localhost";
199
+ headers["x-forwarded-for"] = "proxy-edge";
200
+ let upstreamResponse;
201
+ const upstream = request({ socketPath, path, method: req.method, headers, agent: false }, (response) => {
202
+ upstreamResponse = response;
203
+ if (res.writableEnded || res.destroyed) {
204
+ response.destroy();
205
+ return;
206
+ }
207
+ const status = response.statusCode ?? 502;
208
+ if (status >= 300 && status < 400) {
209
+ response.destroy();
210
+ finish(502);
211
+ return;
212
+ }
213
+ res.writeHead(status, {
214
+ ...selectHeaders(response.headers, RESPONSE_HEADERS),
215
+ "cache-control": "no-store",
216
+ "x-content-type-options": "nosniff"
217
+ });
218
+ response.once("error", () => res.destroy());
219
+ response.once("aborted", () => res.destroy());
220
+ response.pipe(res);
221
+ });
222
+ const timer = setTimeout(() => {
223
+ upstreamResponse?.destroy();
224
+ upstream.destroy();
225
+ finish(504);
226
+ }, timeoutMs);
227
+ res.once("close", () => {
228
+ activeRequests--;
229
+ clearTimeout(timer);
230
+ upstreamResponse?.destroy();
231
+ upstream.destroy();
232
+ });
233
+ upstream.once("error", () => finish(502));
234
+ req.once("aborted", () => upstream.destroy());
235
+ req.once("error", () => upstream.destroy());
236
+ let bytes = 0;
237
+ req.on("data", (chunk) => {
238
+ bytes += chunk.length;
239
+ if (bytes > maxBodyBytes) {
240
+ req.unpipe(upstream);
241
+ upstream.destroy();
242
+ finish(413);
243
+ }
244
+ });
245
+ upstream.flushHeaders();
246
+ req.pipe(upstream);
247
+ };
248
+ }
249
+
250
+ // ../../packages/runtime-server/src/standalone.ts
251
+ async function bounded(promise, ms) {
252
+ let timer;
253
+ try {
254
+ return await Promise.race([
255
+ promise,
256
+ new Promise((_, reject) => {
257
+ timer = setTimeout(() => reject(new Error("Agent Smith lifecycle deadline exceeded")), ms);
258
+ })
259
+ ]);
260
+ } finally {
261
+ clearTimeout(timer);
262
+ }
263
+ }
264
+ async function prepareStandaloneState(options) {
265
+ await mkdir(options.stateDir, { recursive: true, mode: 448 });
266
+ const directory = await lstat(options.stateDir);
267
+ const owned = (uid) => uid === 0 || uid === process.getuid?.();
268
+ if (!directory.isDirectory() || (directory.mode & 63) !== 0 || !owned(directory.uid)) {
269
+ throw new Error("Agent Smith requires an owner-only state directory");
270
+ }
271
+ for (const path of [
272
+ options.configPath,
273
+ options.dbPath,
274
+ options.clientKeysFile
275
+ ]) {
276
+ const stat = await lstat(path).catch((error) => {
277
+ if (error.code === "ENOENT")
278
+ return;
279
+ throw error;
280
+ });
281
+ if (stat && (!stat.isFile() || (stat.mode & 63) !== 0 || !owned(stat.uid))) {
282
+ throw new Error("Agent Smith requires owner-only regular state files");
283
+ }
284
+ }
285
+ const socket = await lstat(options.socketPath).catch((error) => {
286
+ if (error.code === "ENOENT")
287
+ return;
288
+ throw error;
289
+ });
290
+ if (!socket)
291
+ return;
292
+ if (!socket.isSocket())
293
+ throw new Error("Agent Smith control path is not a socket");
294
+ const active = await bounded(new Promise((resolve, reject) => {
295
+ const probe = createConnection(options.socketPath);
296
+ probe.once("connect", () => {
297
+ probe.destroy();
298
+ resolve(true);
299
+ });
300
+ probe.once("error", (error) => {
301
+ probe.destroy();
302
+ if (error.code === "ECONNREFUSED" || error.code === "ENOENT")
303
+ resolve(false);
304
+ else
305
+ reject(error);
306
+ });
307
+ }), 2000);
308
+ if (active)
309
+ throw new Error("Agent Smith pool is already running");
310
+ await unlink(options.socketPath).catch((error) => {
311
+ if (error.code !== "ENOENT")
312
+ throw error;
313
+ });
314
+ }
315
+ async function startStandalone(options, poolEntry, env = process.env) {
316
+ process.umask(63);
317
+ await prepareStandaloneState(options);
318
+ const edge = createProxyEdgeHandler(options);
319
+ const server = createServer((req, res) => {
320
+ if (req.method === "GET" && req.url === "/readyz" && req.headers.host === new URL(options.origin).host) {
321
+ res.writeHead(200, {
322
+ "content-type": "text/plain",
323
+ "cache-control": "no-store"
324
+ });
325
+ res.end(`ready
326
+ `);
327
+ return;
328
+ }
329
+ edge(req, res);
330
+ });
331
+ server.on("checkContinue", (req, res) => edge(req, res));
332
+ const child = spawn("bun", [poolEntry], {
333
+ env: poolEnvironment(options, env),
334
+ stdio: ["ignore", "inherit", "inherit", "ipc"]
335
+ });
336
+ let stopping = false;
337
+ let exited = false;
338
+ const closed = new Promise((resolve) => child.once("close", () => {
339
+ exited = true;
340
+ if (!stopping) {
341
+ server.close();
342
+ server.closeAllConnections();
343
+ }
344
+ resolve();
345
+ }));
346
+ let stopPromise;
347
+ const stop = () => stopPromise ??= (async () => {
348
+ stopping = true;
349
+ try {
350
+ await bounded(new Promise((resolve) => server.close(() => resolve())), 1e4);
351
+ } catch {
352
+ server.closeAllConnections();
353
+ }
354
+ if (!exited)
355
+ child.kill("SIGTERM");
356
+ try {
357
+ await bounded(closed, 5000);
358
+ } catch {
359
+ child.kill("SIGKILL");
360
+ await closed;
361
+ }
362
+ })();
363
+ try {
364
+ await bounded(new Promise((resolve, reject) => {
365
+ const cleanup = () => {
366
+ child.off("message", ready);
367
+ child.off("error", failed);
368
+ child.off("close", failed);
369
+ };
370
+ const failed = () => {
371
+ cleanup();
372
+ reject(new Error("Agent Smith private pool failed to start"));
373
+ };
374
+ const ready = (message) => {
375
+ if (message && typeof message === "object" && "type" in message && message.type === "ready") {
376
+ cleanup();
377
+ resolve();
378
+ }
379
+ };
380
+ child.on("message", ready);
381
+ child.once("error", failed);
382
+ child.once("close", failed);
383
+ }), 30000);
384
+ server.listen(options.port, "0.0.0.0");
385
+ await once(server, "listening");
386
+ if (exited)
387
+ throw new Error("Agent Smith private pool exited during startup");
388
+ const address = server.address();
389
+ if (!address || typeof address === "string")
390
+ throw new Error("Agent Smith public listener did not bind");
391
+ return { port: address.port, pool: child, stop, exited: closed };
392
+ } catch (error) {
393
+ await stop();
394
+ throw error;
395
+ }
396
+ }
397
+
398
+ // src/https.ts
399
+ try {
400
+ const options = readStandaloneOptions(process.env);
401
+ const service = await startStandalone(options, fileURLToPath(new URL("./pool.js", import.meta.url)));
402
+ let stopping = false;
403
+ const stop = () => {
404
+ if (stopping)
405
+ return;
406
+ stopping = true;
407
+ service.stop().then(() => process.exit(0), () => process.exit(1));
408
+ };
409
+ process.on("SIGTERM", stop);
410
+ process.on("SIGINT", stop);
411
+ console.log(`Agent Smith HTTPS entrance ready on port ${options.port}`);
412
+ await service.exited;
413
+ if (!stopping) {
414
+ console.error("Agent Smith private pool exited; stopping the public entrance");
415
+ process.exitCode = 1;
416
+ }
417
+ } catch {
418
+ console.error("Agent Smith standalone startup failed; check origin, private state and key permissions");
419
+ process.exitCode = 1;
420
+ }