@certalis/agent-smith 0.1.15 → 0.1.17

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.
@@ -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-rnbsj0t8.js"></script></head>
35
+ <link rel="stylesheet" crossorigin href="./chunk-re8nxxzq.css"><script type="module" crossorigin src="./chunk-v15gev12.js"></script></head>
36
36
  <body>
37
37
  <div id="root"></div>
38
38
  </body>
@@ -1,7 +1,7 @@
1
1
  {
2
- "/chunk-rnbsj0t8.js": "/chunk-rnbsj0t8.js",
2
+ "/chunk-v15gev12.js": "/chunk-v15gev12.js",
3
3
  "/index.html": "/index.html",
4
- "/chunk-r6qvhv5e.css": "/chunk-r6qvhv5e.css",
5
- "/chunk-rnbsj0t8.js.map": "/chunk-rnbsj0t8.js.map",
4
+ "/chunk-re8nxxzq.css": "/chunk-re8nxxzq.css",
5
+ "/chunk-v15gev12.js.map": "/chunk-v15gev12.js.map",
6
6
  "/favicon-7fef0tsq.svg": "/favicon-7fef0tsq.svg"
7
7
  }
package/dist/edge.js CHANGED
@@ -55,7 +55,15 @@ var RESPONSE_HEADERS = [
55
55
  "x-frame-options"
56
56
  ];
57
57
  function isEnrollmentRoute(method, path) {
58
- return method === "GET" && path === "/pool-enroll" || method === "POST" && ["request", "start", "verify", "confirm", "disconnect"].some((action) => path === `/pool-enroll/${action}`);
58
+ return method === "GET" && path === "/pool-enroll" || method === "POST" && [
59
+ "request",
60
+ "start",
61
+ "verify",
62
+ "confirm",
63
+ "disconnect",
64
+ "resume",
65
+ "reset"
66
+ ].some((action) => path === `/pool-enroll/${action}`);
59
67
  }
60
68
  function selectHeaders(headers, names) {
61
69
  return Object.fromEntries(names.flatMap((name) => typeof headers[name] === "string" ? [[name, headers[name]]] : []));
@@ -117,6 +125,8 @@ function createProxyEdgeHandler({
117
125
  headers.host = enrollment ? url.host : "localhost";
118
126
  if (enrollment && req.headers.origin)
119
127
  headers.origin = req.headers.origin;
128
+ if (enrollment && req.headers.cookie)
129
+ headers.cookie = req.headers.cookie;
120
130
  headers.connection = "keep-alive";
121
131
  headers["x-forwarded-for"] = "proxy-edge";
122
132
  let upstreamResponse;
@@ -134,6 +144,7 @@ function createProxyEdgeHandler({
134
144
  }
135
145
  res.writeHead(status, {
136
146
  ...selectHeaders(response.headers, RESPONSE_HEADERS),
147
+ ...enrollment && response.headers["set-cookie"] ? { "set-cookie": response.headers["set-cookie"] } : {},
137
148
  "cache-control": "no-store",
138
149
  "x-content-type-options": "nosniff"
139
150
  });
package/dist/https.js CHANGED
@@ -151,7 +151,15 @@ var RESPONSE_HEADERS = [
151
151
  "x-frame-options"
152
152
  ];
153
153
  function isEnrollmentRoute(method, path) {
154
- return method === "GET" && path === "/pool-enroll" || method === "POST" && ["request", "start", "verify", "confirm", "disconnect"].some((action) => path === `/pool-enroll/${action}`);
154
+ return method === "GET" && path === "/pool-enroll" || method === "POST" && [
155
+ "request",
156
+ "start",
157
+ "verify",
158
+ "confirm",
159
+ "disconnect",
160
+ "resume",
161
+ "reset"
162
+ ].some((action) => path === `/pool-enroll/${action}`);
155
163
  }
156
164
  function selectHeaders(headers, names) {
157
165
  return Object.fromEntries(names.flatMap((name) => typeof headers[name] === "string" ? [[name, headers[name]]] : []));
@@ -213,6 +221,8 @@ function createProxyEdgeHandler({
213
221
  headers.host = enrollment ? url.host : "localhost";
214
222
  if (enrollment && req.headers.origin)
215
223
  headers.origin = req.headers.origin;
224
+ if (enrollment && req.headers.cookie)
225
+ headers.cookie = req.headers.cookie;
216
226
  headers.connection = "keep-alive";
217
227
  headers["x-forwarded-for"] = "proxy-edge";
218
228
  let upstreamResponse;
@@ -230,6 +240,7 @@ function createProxyEdgeHandler({
230
240
  }
231
241
  res.writeHead(status, {
232
242
  ...selectHeaders(response.headers, RESPONSE_HEADERS),
243
+ ...enrollment && response.headers["set-cookie"] ? { "set-cookie": response.headers["set-cookie"] } : {},
233
244
  "cache-control": "no-store",
234
245
  "x-content-type-options": "nosniff"
235
246
  });
@@ -402,7 +413,7 @@ async function startStandalone(options, poolEntry, env = process.env) {
402
413
  child.on("message", ready);
403
414
  child.once("error", failed);
404
415
  child.once("close", failed);
405
- }), 30000);
416
+ }), 120000);
406
417
  server.listen(options.port, "0.0.0.0");
407
418
  await once(server, "listening");
408
419
  if (exited)
@@ -0,0 +1,170 @@
1
+ // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true,
8
+ configurable: true,
9
+ set: (newValue) => all[name] = () => newValue
10
+ });
11
+ };
12
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
13
+ var __require = import.meta.require;
14
+
15
+ // ../../packages/config/src/standalone.ts
16
+ import {
17
+ closeSync,
18
+ constants,
19
+ fstatSync,
20
+ openSync,
21
+ readFileSync
22
+ } from "fs";
23
+ import { dirname, isAbsolute, join } from "path";
24
+ function readKeysFile(path) {
25
+ let descriptor;
26
+ try {
27
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
28
+ const stat = fstatSync(descriptor);
29
+ if (!stat.isFile() || stat.size > 4096 || (stat.mode & 63) !== 0 || stat.uid !== 0 && stat.uid !== process.getuid?.()) {
30
+ throw new Error("Unsafe keys file");
31
+ }
32
+ return JSON.parse(readFileSync(descriptor, "utf8"));
33
+ } catch {
34
+ throw new Error("Agent Smith requires a readable owner-only private keys file");
35
+ } finally {
36
+ if (descriptor !== undefined)
37
+ closeSync(descriptor);
38
+ }
39
+ }
40
+ function readStandaloneOptions(env) {
41
+ const origin = env.AGENT_SMITH_PUBLIC_ORIGIN ?? env.RENDER_EXTERNAL_URL;
42
+ try {
43
+ if (!origin || new URL(origin).protocol !== "https:" || new URL(origin).origin !== origin) {
44
+ throw new Error("Invalid origin");
45
+ }
46
+ } catch {
47
+ throw new Error("Agent Smith requires an exact HTTPS origin");
48
+ }
49
+ const port = Number(env.PORT ?? "10000");
50
+ const poolPort = Number(env.AGENT_SMITH_POOL_PORT ?? "8081");
51
+ if ([port, poolPort].some((value) => !Number.isSafeInteger(value) || value < 1 || value > 65535) || port === poolPort) {
52
+ throw new Error("Agent Smith public and private ports must be valid and distinct");
53
+ }
54
+ const stateDir = env.AGENT_SMITH_STATE_DIR ?? "/var/data/agent-smith/state";
55
+ const paths = {
56
+ stateDir,
57
+ socketPath: join(stateDir, "control.sock"),
58
+ configPath: env.AGENT_SMITH_CONFIG_PATH ?? join(stateDir, "config.json"),
59
+ dbPath: env.AGENT_SMITH_DB_PATH ?? join(stateDir, "pool.db"),
60
+ clientKeysFile: env.AGENT_SMITH_CLIENT_KEYS_FILE ?? join(stateDir, "clients.json")
61
+ };
62
+ const keysPath = env.AGENT_SMITH_KEYS_FILE ?? join(dirname(stateDir), "keys.json");
63
+ if ([...Object.values(paths), keysPath].some((path) => !isAbsolute(path))) {
64
+ throw new Error("Agent Smith state and key paths must be absolute");
65
+ }
66
+ const keys = env.AGENT_SMITH_ADMIN_KEY || env.AGENT_SMITH_PROXY_KEY ? {
67
+ adminKey: env.AGENT_SMITH_ADMIN_KEY,
68
+ proxyKey: env.AGENT_SMITH_PROXY_KEY
69
+ } : readKeysFile(keysPath);
70
+ if (!keys || typeof keys !== "object" || ![keys.adminKey, keys.proxyKey].every((key) => typeof key === "string" && /^[\x21-\x7e]{32,512}$/.test(key)) || keys.adminKey === keys.proxyKey) {
71
+ throw new Error("Agent Smith requires distinct administrator and proxy keys of at least 32 characters");
72
+ }
73
+ return {
74
+ origin,
75
+ port,
76
+ poolPort,
77
+ poolHost: env.AGENT_SMITH_POOL_HOST ?? "127.0.0.1",
78
+ dashboard: env.AGENT_SMITH_POOL_DASHBOARD === "1",
79
+ ...paths,
80
+ adminKey: keys.adminKey,
81
+ proxyKey: keys.proxyKey
82
+ };
83
+ }
84
+
85
+ // src/core/pool-status.ts
86
+ import { Database } from "bun:sqlite";
87
+ var MODEL_WINDOWS = ["Sonnet", "Opus", "Fable"];
88
+ function summarizePool({
89
+ accounts,
90
+ routing,
91
+ emails,
92
+ memberships,
93
+ origin
94
+ }) {
95
+ const byId = new Map(memberships.map((row) => [row.id, row]));
96
+ const allowed = new Set(routing.allowlistedAccountUuids);
97
+ return {
98
+ routingEnabled: routing.enabled,
99
+ maxUsagePercent: routing.maxUsage * 100,
100
+ enrollmentUrl: `${origin}/pool-enroll`,
101
+ emails,
102
+ accounts: accounts.map((account) => {
103
+ const identity = byId.get(account.id);
104
+ const windows = account.quotaWindows ?? {};
105
+ return {
106
+ name: account.name,
107
+ paused: account.paused,
108
+ blocked: Boolean(account.blockedReason),
109
+ poolAllowed: routing.enabled && identity?.auth_method === "oauth" && allowed.has(identity.account_uuid ?? ""),
110
+ tokenStatus: account.tokenStatus,
111
+ usage: {
112
+ fiveHour: windows.unified5h ?? null,
113
+ sevenDay: windows.unified7d ?? null,
114
+ weeklyByModel: Object.fromEntries(MODEL_WINDOWS.flatMap((model) => {
115
+ const window = windows[`unified7d${model}`];
116
+ return window ? [[model, window]] : [];
117
+ }))
118
+ }
119
+ };
120
+ })
121
+ };
122
+ }
123
+ function readMemberships(dbPath) {
124
+ const database = new Database(dbPath, { readonly: true });
125
+ try {
126
+ return database.query("SELECT id, account_uuid, auth_method FROM accounts").all();
127
+ } finally {
128
+ database.close();
129
+ }
130
+ }
131
+ async function readPoolStatus(options) {
132
+ const admin = async (path, body) => {
133
+ const response = await fetch(`http://127.0.0.1/api/${path}`, {
134
+ unix: options.socketPath,
135
+ method: body ? "POST" : "GET",
136
+ headers: {
137
+ "x-api-key": options.adminKey,
138
+ "content-type": "application/json"
139
+ },
140
+ ...body && { body: JSON.stringify(body) },
141
+ signal: AbortSignal.timeout(1e4),
142
+ redirect: "error"
143
+ });
144
+ if (!response.ok)
145
+ throw new Error(`Pool refused /api/${path}`);
146
+ return await response.json();
147
+ };
148
+ const [{ accounts }, routing, { emails }] = await Promise.all([
149
+ admin("status"),
150
+ admin("config/team-routing"),
151
+ admin("enrollment-emails", {})
152
+ ]);
153
+ if (!Array.isArray(accounts) || typeof routing.enabled !== "boolean" || !Array.isArray(routing.allowlistedAccountUuids) || !Number.isFinite(routing.maxUsage) || !Array.isArray(emails) || !emails.every((email) => typeof email === "string"))
154
+ throw new Error("Pool returned an unexpected status");
155
+ return summarizePool({
156
+ accounts,
157
+ routing,
158
+ emails,
159
+ memberships: readMemberships(options.dbPath),
160
+ origin: options.origin
161
+ });
162
+ }
163
+
164
+ // src/pool-status.ts
165
+ try {
166
+ console.log(JSON.stringify(await readPoolStatus(readStandaloneOptions(process.env))));
167
+ } catch (error) {
168
+ console.error(error instanceof Error ? error.message : "Pool status could not be read");
169
+ process.exitCode = 1;
170
+ }