@certalis/agent-smith 0.1.7 → 0.1.8

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 CHANGED
@@ -85,24 +85,30 @@ startServer({
85
85
 
86
86
  Codex works the same way with an OpenAI API key and an `openai-responses` pool.
87
87
 
88
- ## Connect an authorized caller to a private shared pool
88
+ ## Connect an authorized caller to a shared pool
89
89
 
90
- The agents service and a laptop can send requests to one proxy with a
91
- forwarding key. Put the server and callers on a private network first; the
92
- recommended WireGuard shape is documented in the
93
- [private-network guide](docs/private-network.md). It keeps the database and
94
- provider tokens on the server, and exposes the proxy only on the private
95
- network.
90
+ The agents service and laptops can use one server-side pool through the
91
+ [authenticated HTTPS entrance](docs/https-edge.md) on managed HTTP hosts such as
92
+ Render. HTTPS needs no VPN or extra server: an existing web service forwards
93
+ only inference to the pool's private socket. Each device has its own revocable
94
+ key; provider tokens and the single database stay on the server.
96
95
 
97
- This is connectivity only, not team tenancy: the shared forwarding key does
98
- not identify an individual caller or enforce per-client fairness. Do not
99
- distribute it team-wide until the B2/W7 tenancy work exists.
96
+ Device keys allow independent revocation and cannot read management data.
97
+ This does not add per-client fairness or budgets.
100
98
 
101
- Copy [`private-network-client.json`](examples/config/private-network-client.json)
102
- into your private Agent-smith config. Put the forwarding key in the owner-only
103
- file named by `proxy_key_file`, not in the JSON or a shell profile. `base_url`
104
- is the private endpoint visible to that machine, not a second pool. The key can
105
- spend from the pool, but cannot administer it.
99
+ Copy [`https-client.json`](examples/config/https-client.json) into your private
100
+ Agent-smith config. Put the device key in the owner-only file named by
101
+ `proxy_key_file`, not in the JSON or a shell profile. `base_url` is the endpoint
102
+ visible to your machine, not a second pool. The key can spend from the pool, but
103
+ cannot administer it.
104
+
105
+ An SSH tunnel remains an option for development. Use
106
+ [`team-client.json`](examples/config/team-client.json) and forward its local port
107
+ to the private server:
108
+
109
+ ```bash
110
+ ssh -N -L 18181:127.0.0.1:8080 agent-smith-pool
111
+ ```
106
112
 
107
113
  Then install the normal `claude` and `codex` wrappers once:
108
114
 
@@ -112,9 +118,8 @@ agent-smith install-client
112
118
 
113
119
  Open a new terminal and use `claude` or `codex` normally. The wrappers only add
114
120
  their own marked `PATH` entry; they do not replace the real binaries or start a
115
- second proxy. Edit the `client` section and rerun `agent-smith install-client`
116
- when the private address changes; do not hand-edit the generated wrappers. The
117
- forwarding key is for inference, not dashboard or management access.
121
+ second proxy. The forwarding key is for inference, not dashboard or management
122
+ access.
118
123
 
119
124
  ## Configuration
120
125
 
@@ -190,14 +195,14 @@ to `acme` and are sent as `acme-large`. `acme` serves no other model.
190
195
  ```
191
196
 
192
197
  **A laptop using a private shared pool**
193
- ([`private-network-client.json`](examples/config/private-network-client.json)).
194
- The address is reachable only through the private network described in the
195
- [deployment guide](docs/private-network.md).
198
+ ([`team-client.json`](examples/config/team-client.json)). The example uses an
199
+ SSH-local port; use the direct private origin instead on a host that can reach
200
+ the pool without SSH.
196
201
 
197
202
  ```json
198
203
  {
199
204
  "client": {
200
- "base_url": "http://10.76.0.1:8080",
205
+ "base_url": "http://127.0.0.1:18181",
201
206
  "proxy_key_file": "~/.config/ccflare/team-pool.key"
202
207
  }
203
208
  }
package/dist/bin.js CHANGED
@@ -11670,8 +11670,71 @@ var init_src10 = __esm(() => {
11670
11670
  init_websocket_proxy();
11671
11671
  });
11672
11672
 
11673
+ // ../../packages/runtime-server/src/device-keys.ts
11674
+ import { createHash as createHash3, timingSafeEqual } from "crypto";
11675
+ import {
11676
+ closeSync,
11677
+ constants,
11678
+ fstatSync,
11679
+ openSync,
11680
+ readFileSync as readFileSync2
11681
+ } from "fs";
11682
+ import { isAbsolute as isAbsolute2 } from "path";
11683
+ function deviceKeyMatches(key, path) {
11684
+ if (!key || !path || !isAbsolute2(path) || !/^[\x21-\x7e]{32,512}$/.test(key))
11685
+ return false;
11686
+ let fd;
11687
+ try {
11688
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
11689
+ const stat = fstatSync(fd);
11690
+ if (!stat.isFile() || stat.size > MAX_REGISTRY_BYTES || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.() && stat.uid !== 0)
11691
+ return false;
11692
+ const registry = JSON.parse(readFileSync2(fd, "utf8"));
11693
+ if (!registry || typeof registry !== "object" || Array.isArray(registry))
11694
+ return false;
11695
+ const entries = Object.entries(registry);
11696
+ if (entries.length > MAX_DEVICES || entries.some(([name, digest2]) => !/^[-a-zA-Z0-9_]{1,64}$/.test(name) || typeof digest2 !== "string" || !/^[a-f0-9]{64}$/.test(digest2)))
11697
+ return false;
11698
+ const digest = createHash3("sha256").update(key).digest();
11699
+ return entries.some(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")));
11700
+ } catch {
11701
+ return false;
11702
+ } finally {
11703
+ if (fd !== undefined)
11704
+ closeSync(fd);
11705
+ }
11706
+ }
11707
+ var MAX_REGISTRY_BYTES, MAX_DEVICES = 128;
11708
+ var init_device_keys = __esm(() => {
11709
+ MAX_REGISTRY_BYTES = 32 * 1024;
11710
+ });
11711
+
11712
+ // ../../packages/runtime-server/src/inference-routes.ts
11713
+ function isInferenceRoute(method, path) {
11714
+ return INFERENCE_ROUTES.has(`${method} ${path}`);
11715
+ }
11716
+ function isDeviceRoute(method, path) {
11717
+ return method === "GET" && path === "/health" || isInferenceRoute(method, path);
11718
+ }
11719
+ var INFERENCE_ROUTES;
11720
+ var init_inference_routes = __esm(() => {
11721
+ INFERENCE_ROUTES = new Set([
11722
+ "POST /v1/claude-code/v1/messages",
11723
+ "POST /v1/claude-code/v1/messages/count_tokens",
11724
+ "POST /v1/pool/anthropic-messages/v1/messages",
11725
+ "POST /v1/pool/anthropic-messages/v1/messages/count_tokens",
11726
+ "POST /v1/codex/responses",
11727
+ "POST /v1/pool/openai-responses/responses"
11728
+ ]);
11729
+ for (const route of [...INFERENCE_ROUTES]) {
11730
+ if (route.endsWith("/messages") || route.endsWith("/count_tokens")) {
11731
+ INFERENCE_ROUTES.add(`${route}?beta=true`);
11732
+ }
11733
+ }
11734
+ });
11735
+
11673
11736
  // ../../packages/runtime-server/src/exposure.ts
11674
- import { timingSafeEqual } from "crypto";
11737
+ import { timingSafeEqual as timingSafeEqual2 } from "crypto";
11675
11738
  function requestAddress(server, req) {
11676
11739
  if (!server || typeof server.requestIP !== "function") {
11677
11740
  return { address: undefined, hasRequestIp: false };
@@ -11684,25 +11747,14 @@ function requestAddress(server, req) {
11684
11747
  function configuredKey(value) {
11685
11748
  return typeof value === "string" && value.length > 0 ? value : undefined;
11686
11749
  }
11687
- function configuredBindHosts(value) {
11688
- if (value === undefined)
11689
- return;
11690
- const bindHosts = [
11691
- ...new Set(value.split(",").map((host) => host.trim()).filter(Boolean))
11692
- ];
11693
- return bindHosts.length > 0 ? bindHosts : undefined;
11694
- }
11695
11750
  function createExposureConfig(config) {
11696
11751
  const configuredHost = configuredKey(process.env.CF_HOST) ?? configuredKey(config.get("host"));
11697
- const bindHosts = configuredBindHosts(process.env.CF_BIND_HOSTS) ?? [
11698
- configuredHost ?? "127.0.0.1"
11699
- ];
11700
11752
  const configuredTrustLoopback = process.env.CF_TRUST_LOOPBACK;
11701
11753
  return {
11702
11754
  adminKey: configuredKey(process.env.CF_ADMIN_KEY),
11703
- bindHost: bindHosts[0],
11704
- bindHosts,
11755
+ bindHost: configuredHost ?? "127.0.0.1",
11705
11756
  proxyKey: configuredKey(process.env.CF_PROXY_KEY),
11757
+ clientKeysFile: configuredKey(process.env.CF_CLIENT_KEYS_FILE),
11706
11758
  trustLoopback: configuredTrustLoopback === undefined ? config.get("trust_loopback") !== false : configuredTrustLoopback !== "false"
11707
11759
  };
11708
11760
  }
@@ -11716,10 +11768,10 @@ function isLoopbackAddress(address) {
11716
11768
  return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
11717
11769
  }
11718
11770
  function safeKeyEqual(candidate, expected) {
11719
- if (!candidate || !expected || candidate.length !== expected.length) {
11771
+ if (!candidate || !expected || Buffer.byteLength(candidate) !== Buffer.byteLength(expected)) {
11720
11772
  return false;
11721
11773
  }
11722
- return timingSafeEqual(Buffer.from(candidate), Buffer.from(expected));
11774
+ return timingSafeEqual2(Buffer.from(candidate), Buffer.from(expected));
11723
11775
  }
11724
11776
  function bearerToken(req) {
11725
11777
  const authorization = req.headers.get("authorization");
@@ -11740,6 +11792,9 @@ function keyRole(req, url, config) {
11740
11792
  if (isResponsesInferenceRoute(url.pathname) && safeKeyEqual(bearerToken(req), config.proxyKey)) {
11741
11793
  return "proxy";
11742
11794
  }
11795
+ if (deviceKeyMatches(apiKey, config.clientKeysFile) || isResponsesInferenceRoute(url.pathname) && deviceKeyMatches(bearerToken(req), config.clientKeysFile)) {
11796
+ return "device";
11797
+ }
11743
11798
  return null;
11744
11799
  }
11745
11800
  function hostnameFromHostHeader(host) {
@@ -11753,7 +11808,7 @@ function hostnameFromHostHeader(host) {
11753
11808
  function isWildcardHost(host) {
11754
11809
  return host === "0.0.0.0" || host === "::";
11755
11810
  }
11756
- function isLocalHostHeader(hostHeader, bindHosts) {
11811
+ function isLocalHostHeader(hostHeader, bindHost) {
11757
11812
  if (hostHeader === null) {
11758
11813
  return true;
11759
11814
  }
@@ -11761,8 +11816,7 @@ function isLocalHostHeader(hostHeader, bindHosts) {
11761
11816
  if (!hostname) {
11762
11817
  return false;
11763
11818
  }
11764
- const configuredHosts = typeof bindHosts === "string" ? [bindHosts] : bindHosts;
11765
- return LOOPBACK_HOSTS.has(hostname) || configuredHosts.some((bindHost) => !isWildcardHost(bindHost) && hostname === bindHost.toLowerCase());
11819
+ return LOOPBACK_HOSTS.has(hostname) || !isWildcardHost(bindHost) && hostname === bindHost.toLowerCase();
11766
11820
  }
11767
11821
  function isSameOriginManagementRequest(req, url) {
11768
11822
  const fetchSite = req.headers.get("sec-fetch-site");
@@ -11777,12 +11831,15 @@ function jsonError(status, message) {
11777
11831
  }
11778
11832
  function exposureFailure(req, url, server, config) {
11779
11833
  const remote = requestAddress(server, req);
11780
- const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHosts)) && !isForwardedRequest(req.headers);
11834
+ const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHost)) && !isForwardedRequest(req.headers);
11781
11835
  const role = keyRole(req, url, config);
11836
+ if (role === "device" && !isDeviceRoute(req.method, url.pathname + url.search)) {
11837
+ return jsonError(403, "Device keys only allow health and inference");
11838
+ }
11782
11839
  if (!role && !loopbackExempt) {
11783
11840
  return jsonError(401, "A proxy key is required for this request");
11784
11841
  }
11785
- if (!role && !isLocalHostHeader(req.headers.get("host"), config.bindHosts)) {
11842
+ if (!role && !isLocalHostHeader(req.headers.get("host"), config.bindHost)) {
11786
11843
  return jsonError(403, "Host header is not allowed for a loopback request");
11787
11844
  }
11788
11845
  if (url.pathname.startsWith("/api/")) {
@@ -11799,6 +11856,8 @@ function exposureFailure(req, url, server, config) {
11799
11856
  }
11800
11857
  var FORWARDED_HEADERS, LOOPBACK_HOSTS, MUTATING_METHODS;
11801
11858
  var init_exposure = __esm(() => {
11859
+ init_device_keys();
11860
+ init_inference_routes();
11802
11861
  FORWARDED_HEADERS = [
11803
11862
  "forwarded",
11804
11863
  "x-forwarded-for",
@@ -11952,10 +12011,10 @@ var init_bootstrap_runtime = __esm(() => {
11952
12011
  });
11953
12012
 
11954
12013
  // ../../packages/runtime-server/src/dashboard-assets.ts
11955
- import { readFileSync as readFileSync2 } from "fs";
11956
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join7, resolve as resolve2 } from "path";
12014
+ import { readFileSync as readFileSync3 } from "fs";
12015
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, resolve as resolve2 } from "path";
11957
12016
  function resolveConfiguredPath(configuredPath) {
11958
- return isAbsolute2(configuredPath) ? configuredPath : resolve2(process.cwd(), configuredPath);
12017
+ return isAbsolute3(configuredPath) ? configuredPath : resolve2(process.cwd(), configuredPath);
11959
12018
  }
11960
12019
  function resolveDashboardManifestPath() {
11961
12020
  const configuredManifestPath = process.env[DASHBOARD_MANIFEST_PATH_ENV]?.trim();
@@ -11977,7 +12036,7 @@ function loadDashboardAssets() {
11977
12036
  }
11978
12037
  const manifestPath = resolveDashboardManifestPath();
11979
12038
  dashboardAssets = {
11980
- manifest: JSON.parse(readFileSync2(manifestPath, "utf8")),
12039
+ manifest: JSON.parse(readFileSync3(manifestPath, "utf8")),
11981
12040
  distDir: dirname3(manifestPath)
11982
12041
  };
11983
12042
  return dashboardAssets;
@@ -12066,7 +12125,6 @@ function createServerFetchHandler({
12066
12125
  withDashboard,
12067
12126
  exposureConfig = {
12068
12127
  bindHost: "127.0.0.1",
12069
- bindHosts: ["127.0.0.1"],
12070
12128
  trustLoopback: true
12071
12129
  },
12072
12130
  handleProxyRequest = handleProxy,
@@ -12187,7 +12245,7 @@ var init_startup_maintenance = __esm(() => {
12187
12245
  });
12188
12246
 
12189
12247
  // ../../packages/runtime-server/src/index.ts
12190
- import { isAbsolute as isAbsolute3 } from "path";
12248
+ import { isAbsolute as isAbsolute4 } from "path";
12191
12249
  var {serve } = globalThis.Bun;
12192
12250
  function stopRetentionMaintenance() {
12193
12251
  if (stopRetentionJob) {
@@ -12213,10 +12271,8 @@ async function stopServerRuntime() {
12213
12271
  serverStopPromise = (async () => {
12214
12272
  const errors2 = [];
12215
12273
  const activeServer = serverInstance;
12216
- const activeAdditionalServers = additionalServerInstances;
12217
12274
  const activeUnixServer = unixServerInstance;
12218
12275
  serverInstance = null;
12219
- additionalServerInstances = [];
12220
12276
  unixServerInstance = null;
12221
12277
  try {
12222
12278
  await activeUnixServer?.stop(true);
@@ -12228,13 +12284,6 @@ async function stopServerRuntime() {
12228
12284
  } catch (error) {
12229
12285
  errors2.push(toError("Failed to stop Bun server", error));
12230
12286
  }
12231
- for (const [index, server] of activeAdditionalServers.entries()) {
12232
- try {
12233
- await server.stop(true);
12234
- } catch (error) {
12235
- errors2.push(toError(`Failed to stop additional Bun server ${index + 1}`, error));
12236
- }
12237
- }
12238
12287
  stopRetentionMaintenance();
12239
12288
  try {
12240
12289
  await waitForProxyBackgroundTasks();
@@ -12267,7 +12316,7 @@ async function stopServerRuntime() {
12267
12316
  }
12268
12317
  }
12269
12318
  function startServer(options) {
12270
- if (options?.additionalUnixSocket !== undefined && !isAbsolute3(options.additionalUnixSocket)) {
12319
+ if (options?.additionalUnixSocket !== undefined && !isAbsolute4(options.additionalUnixSocket)) {
12271
12320
  throw new Error("Additional Unix socket must be an absolute path");
12272
12321
  }
12273
12322
  if (serverInstance) {
@@ -12313,16 +12362,6 @@ function startServer(options) {
12313
12362
  fetch: fetchHandler,
12314
12363
  websocket: websocketProxyHandler
12315
12364
  });
12316
- const activePort2 = serverInstance.port ?? runtimeConfig2.port;
12317
- for (const hostname of exposureConfig.bindHosts.slice(1)) {
12318
- additionalServerInstances.push(serve({
12319
- hostname,
12320
- port: activePort2,
12321
- idleTimeout: NETWORK.IDLE_TIMEOUT_MAX,
12322
- fetch: fetchHandler,
12323
- websocket: websocketProxyHandler
12324
- }));
12325
- }
12326
12365
  } catch (error) {
12327
12366
  stopServerRuntime().catch(() => {
12328
12367
  lifecycleLog.error("Failed to clean up after listener startup failure");
@@ -12358,7 +12397,7 @@ async function handleGracefulShutdown(signal) {
12358
12397
  process.exit(1);
12359
12398
  }
12360
12399
  }
12361
- var serverLog, lifecycleLog, serverInstance = null, additionalServerInstances, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null;
12400
+ var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null;
12362
12401
  var init_src11 = __esm(() => {
12363
12402
  init_src9();
12364
12403
  init_src2();
@@ -12376,7 +12415,6 @@ var init_src11 = __esm(() => {
12376
12415
  lifecycleLog = new Logger("ServerLifecycle", 1 /* INFO */, {
12377
12416
  silentConsole: false
12378
12417
  });
12379
- additionalServerInstances = [];
12380
12418
  process.on("SIGINT", () => handleGracefulShutdown("SIGINT"));
12381
12419
  process.on("SIGTERM", () => handleGracefulShutdown("SIGTERM"));
12382
12420
  if (false) {}
@@ -13991,10 +14029,10 @@ var init_args = () => {};
13991
14029
  import {
13992
14030
  accessSync,
13993
14031
  chmodSync as chmodSync2,
13994
- constants as constants2,
14032
+ constants as constants3,
13995
14033
  existsSync as existsSync3,
13996
14034
  mkdirSync as mkdirSync4,
13997
- readFileSync as readFileSync3,
14035
+ readFileSync as readFileSync4,
13998
14036
  statSync as statSync3,
13999
14037
  unlinkSync as unlinkSync2,
14000
14038
  writeFileSync as writeFileSync2
@@ -14025,7 +14063,7 @@ function validateProxyKeyFile(proxyKeyFile) {
14025
14063
  if ((metadata.mode & 63) !== 0) {
14026
14064
  throw new Error("Agent-smith forwarding-key file must be owner-only");
14027
14065
  }
14028
- const key = readFileSync3(resolvedPath, "utf8").trim();
14066
+ const key = readFileSync4(resolvedPath, "utf8").trim();
14029
14067
  if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
14030
14068
  throw new Error("Agent-smith forwarding-key file is invalid");
14031
14069
  }
@@ -14111,7 +14149,7 @@ function getLocalRoutingPaths() {
14111
14149
  }
14112
14150
  function isExecutable(path) {
14113
14151
  try {
14114
- accessSync(path, constants2.X_OK);
14152
+ accessSync(path, constants3.X_OK);
14115
14153
  return true;
14116
14154
  } catch {
14117
14155
  return false;
@@ -14131,7 +14169,7 @@ function readSavedClientPaths(statePath) {
14131
14169
  if (!existsSync3(statePath))
14132
14170
  return null;
14133
14171
  try {
14134
- const saved = JSON.parse(readFileSync3(statePath, "utf8"));
14172
+ const saved = JSON.parse(readFileSync4(statePath, "utf8"));
14135
14173
  if (typeof saved === "object" && saved !== null) {
14136
14174
  const { claudePath, codexPath } = saved;
14137
14175
  const validClaude = typeof claudePath === "string" && isExecutable(claudePath) ? claudePath : undefined;
@@ -14149,7 +14187,7 @@ function getLocalRoutingStatus(paths2 = {}) {
14149
14187
  const shellProfile = paths2.shellProfile ?? defaults.shellProfile;
14150
14188
  let shellProfileHasRouting = false;
14151
14189
  try {
14152
- shellProfileHasRouting = existsSync3(shellProfile) && readFileSync3(shellProfile, "utf8").includes(ROUTING_BEGIN);
14190
+ shellProfileHasRouting = existsSync3(shellProfile) && readFileSync4(shellProfile, "utf8").includes(ROUTING_BEGIN);
14153
14191
  } catch {}
14154
14192
  return {
14155
14193
  enabled: shellProfileHasRouting && (existsSync3(join8(binDir, "claude")) || existsSync3(join8(binDir, "codex"))),
@@ -14185,7 +14223,7 @@ async function enableLocalClientRouting(options) {
14185
14223
  proxyKeyFile: options.proxyKeyFile,
14186
14224
  providerPoolWires: options.providerPoolWires ?? Object.keys(new Config().getProviderPools())
14187
14225
  });
14188
- const existingProfile = existsSync3(shellProfile) ? readFileSync3(shellProfile, "utf8") : "";
14226
+ const existingProfile = existsSync3(shellProfile) ? readFileSync4(shellProfile, "utf8") : "";
14189
14227
  writeFileSync2(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
14190
14228
  mkdirSync4(dirname4(statePath), { recursive: true, mode: 448 });
14191
14229
  writeFileSync2(statePath, JSON.stringify({ claudePath, codexPath }), {
@@ -14201,7 +14239,7 @@ function disableLocalClientRouting(paths2 = {}) {
14201
14239
  const shellProfile = paths2.shellProfile ?? defaults.shellProfile;
14202
14240
  const statePath = paths2.statePath ?? defaults.statePath;
14203
14241
  if (existsSync3(shellProfile)) {
14204
- writeFileSync2(shellProfile, removeRoutingFromShellProfile(readFileSync3(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
14242
+ writeFileSync2(shellProfile, removeRoutingFromShellProfile(readFileSync4(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
14205
14243
  }
14206
14244
  for (const name of ["claude", "codex"]) {
14207
14245
  const wrapper = join8(binDir, name);
@@ -14461,13 +14499,13 @@ __export(exports_theme, {
14461
14499
  NAV_ITEMS: () => NAV_ITEMS,
14462
14500
  C: () => C
14463
14501
  });
14464
- import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
14502
+ import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
14465
14503
  import { homedir as homedir3 } from "os";
14466
14504
  import { join as join9 } from "path";
14467
14505
  function loadPersistedThemeId() {
14468
14506
  try {
14469
14507
  if (existsSync4(CONFIG_FILE)) {
14470
- const data = JSON.parse(readFileSync4(CONFIG_FILE, "utf-8"));
14508
+ const data = JSON.parse(readFileSync5(CONFIG_FILE, "utf-8"));
14471
14509
  if (data?.themeId && getThemeById(data.themeId)) {
14472
14510
  return data.themeId;
14473
14511
  }
package/dist/edge.js ADDED
@@ -0,0 +1,150 @@
1
+ // ../../packages/runtime-server/src/proxy-edge.ts
2
+ import {
3
+ request
4
+ } from "node:http";
5
+ import { isAbsolute } from "node:path";
6
+
7
+ // ../../packages/runtime-server/src/inference-routes.ts
8
+ var INFERENCE_ROUTES = new Set([
9
+ "POST /v1/claude-code/v1/messages",
10
+ "POST /v1/claude-code/v1/messages/count_tokens",
11
+ "POST /v1/pool/anthropic-messages/v1/messages",
12
+ "POST /v1/pool/anthropic-messages/v1/messages/count_tokens",
13
+ "POST /v1/codex/responses",
14
+ "POST /v1/pool/openai-responses/responses"
15
+ ]);
16
+ for (const route of [...INFERENCE_ROUTES]) {
17
+ if (route.endsWith("/messages") || route.endsWith("/count_tokens")) {
18
+ INFERENCE_ROUTES.add(`${route}?beta=true`);
19
+ }
20
+ }
21
+ function isInferenceRoute(method, path) {
22
+ return INFERENCE_ROUTES.has(`${method} ${path}`);
23
+ }
24
+
25
+ // ../../packages/runtime-server/src/proxy-edge.ts
26
+ var REQUEST_HEADERS = [
27
+ "content-type",
28
+ "accept",
29
+ "accept-encoding",
30
+ "anthropic-version",
31
+ "anthropic-beta",
32
+ "x-api-key",
33
+ "authorization",
34
+ "x-claude-code-session-id",
35
+ "session-id",
36
+ "openai-beta",
37
+ "x-client-request-id",
38
+ "user-agent"
39
+ ];
40
+ var RESPONSE_HEADERS = [
41
+ "content-type",
42
+ "content-encoding",
43
+ "retry-after",
44
+ "request-id",
45
+ "x-request-id",
46
+ "anthropic-ratelimit-requests-limit",
47
+ "anthropic-ratelimit-requests-remaining",
48
+ "anthropic-ratelimit-requests-reset",
49
+ "anthropic-ratelimit-tokens-limit",
50
+ "anthropic-ratelimit-tokens-remaining",
51
+ "anthropic-ratelimit-tokens-reset"
52
+ ];
53
+ function selectHeaders(headers, names) {
54
+ return Object.fromEntries(names.flatMap((name) => typeof headers[name] === "string" ? [[name, headers[name]]] : []));
55
+ }
56
+ function requestFailure(req, origin, maxBodyBytes) {
57
+ const health = req.method === "GET" && req.url === "/pool-health";
58
+ if (!health && !isInferenceRoute(req.method ?? "", req.url ?? ""))
59
+ return 404;
60
+ 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"])))
61
+ return 403;
62
+ if (req.headers.upgrade || req.headers.expect)
63
+ return 400;
64
+ if (req.headers["content-length"] !== undefined && (!/^\d+$/.test(req.headers["content-length"]) || Number(req.headers["content-length"]) > maxBodyBytes))
65
+ return 413;
66
+ if (!req.headers["x-api-key"] && !req.headers.authorization)
67
+ return 401;
68
+ return null;
69
+ }
70
+ function createProxyEdgeHandler({
71
+ origin,
72
+ socketPath,
73
+ maxBodyBytes = 64 * 1024 * 1024,
74
+ timeoutMs = 300000
75
+ }) {
76
+ 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
+ throw new Error("Proxy edge requires an exact HTTPS origin, an absolute socket path and positive limits");
79
+ }
80
+ return (req, res) => {
81
+ const finish = (status) => {
82
+ if (res.writableEnded || res.destroyed)
83
+ return;
84
+ if (res.headersSent) {
85
+ res.destroy();
86
+ return;
87
+ }
88
+ res.writeHead(status, {
89
+ "cache-control": "no-store",
90
+ connection: "close"
91
+ });
92
+ res.end();
93
+ };
94
+ const rejected = requestFailure(req, origin, maxBodyBytes);
95
+ if (rejected)
96
+ return finish(rejected);
97
+ const path = req.method === "GET" && req.url === "/pool-health" ? "/health" : req.url ?? "";
98
+ const headers = selectHeaders(req.headers, REQUEST_HEADERS);
99
+ headers.host = "localhost";
100
+ headers["x-forwarded-for"] = "proxy-edge";
101
+ let upstreamResponse;
102
+ const upstream = request({ socketPath, path, method: req.method, headers, agent: false }, (response) => {
103
+ upstreamResponse = response;
104
+ if (res.writableEnded || res.destroyed) {
105
+ response.destroy();
106
+ return;
107
+ }
108
+ const status = response.statusCode ?? 502;
109
+ if (status >= 300 && status < 400) {
110
+ response.destroy();
111
+ finish(502);
112
+ return;
113
+ }
114
+ res.writeHead(status, {
115
+ ...selectHeaders(response.headers, RESPONSE_HEADERS),
116
+ "cache-control": "no-store",
117
+ "x-content-type-options": "nosniff"
118
+ });
119
+ response.once("error", () => res.destroy());
120
+ response.once("aborted", () => res.destroy());
121
+ response.pipe(res);
122
+ });
123
+ const timer = setTimeout(() => {
124
+ upstreamResponse?.destroy();
125
+ upstream.destroy();
126
+ finish(504);
127
+ }, timeoutMs);
128
+ res.once("close", () => {
129
+ clearTimeout(timer);
130
+ upstreamResponse?.destroy();
131
+ upstream.destroy();
132
+ });
133
+ upstream.once("error", () => finish(502));
134
+ req.once("aborted", () => upstream.destroy());
135
+ req.once("error", () => upstream.destroy());
136
+ let bytes = 0;
137
+ req.on("data", (chunk) => {
138
+ bytes += chunk.length;
139
+ if (bytes > maxBodyBytes) {
140
+ req.unpipe(upstream);
141
+ upstream.destroy();
142
+ finish(413);
143
+ }
144
+ });
145
+ req.pipe(upstream);
146
+ };
147
+ }
148
+ export {
149
+ createProxyEdgeHandler
150
+ };
package/dist/server.js CHANGED
@@ -11669,8 +11669,71 @@ var init_src10 = __esm(() => {
11669
11669
  init_websocket_proxy();
11670
11670
  });
11671
11671
 
11672
+ // ../../packages/runtime-server/src/device-keys.ts
11673
+ import { createHash as createHash3, timingSafeEqual } from "crypto";
11674
+ import {
11675
+ closeSync,
11676
+ constants,
11677
+ fstatSync,
11678
+ openSync,
11679
+ readFileSync as readFileSync2
11680
+ } from "fs";
11681
+ import { isAbsolute as isAbsolute2 } from "path";
11682
+ function deviceKeyMatches(key, path) {
11683
+ if (!key || !path || !isAbsolute2(path) || !/^[\x21-\x7e]{32,512}$/.test(key))
11684
+ return false;
11685
+ let fd;
11686
+ try {
11687
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
11688
+ const stat = fstatSync(fd);
11689
+ if (!stat.isFile() || stat.size > MAX_REGISTRY_BYTES || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.() && stat.uid !== 0)
11690
+ return false;
11691
+ const registry = JSON.parse(readFileSync2(fd, "utf8"));
11692
+ if (!registry || typeof registry !== "object" || Array.isArray(registry))
11693
+ return false;
11694
+ const entries = Object.entries(registry);
11695
+ if (entries.length > MAX_DEVICES || entries.some(([name, digest2]) => !/^[-a-zA-Z0-9_]{1,64}$/.test(name) || typeof digest2 !== "string" || !/^[a-f0-9]{64}$/.test(digest2)))
11696
+ return false;
11697
+ const digest = createHash3("sha256").update(key).digest();
11698
+ return entries.some(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")));
11699
+ } catch {
11700
+ return false;
11701
+ } finally {
11702
+ if (fd !== undefined)
11703
+ closeSync(fd);
11704
+ }
11705
+ }
11706
+ var MAX_REGISTRY_BYTES, MAX_DEVICES = 128;
11707
+ var init_device_keys = __esm(() => {
11708
+ MAX_REGISTRY_BYTES = 32 * 1024;
11709
+ });
11710
+
11711
+ // ../../packages/runtime-server/src/inference-routes.ts
11712
+ function isInferenceRoute(method, path) {
11713
+ return INFERENCE_ROUTES.has(`${method} ${path}`);
11714
+ }
11715
+ function isDeviceRoute(method, path) {
11716
+ return method === "GET" && path === "/health" || isInferenceRoute(method, path);
11717
+ }
11718
+ var INFERENCE_ROUTES;
11719
+ var init_inference_routes = __esm(() => {
11720
+ INFERENCE_ROUTES = new Set([
11721
+ "POST /v1/claude-code/v1/messages",
11722
+ "POST /v1/claude-code/v1/messages/count_tokens",
11723
+ "POST /v1/pool/anthropic-messages/v1/messages",
11724
+ "POST /v1/pool/anthropic-messages/v1/messages/count_tokens",
11725
+ "POST /v1/codex/responses",
11726
+ "POST /v1/pool/openai-responses/responses"
11727
+ ]);
11728
+ for (const route of [...INFERENCE_ROUTES]) {
11729
+ if (route.endsWith("/messages") || route.endsWith("/count_tokens")) {
11730
+ INFERENCE_ROUTES.add(`${route}?beta=true`);
11731
+ }
11732
+ }
11733
+ });
11734
+
11672
11735
  // ../../packages/runtime-server/src/exposure.ts
11673
- import { timingSafeEqual } from "crypto";
11736
+ import { timingSafeEqual as timingSafeEqual2 } from "crypto";
11674
11737
  function requestAddress(server, req) {
11675
11738
  if (!server || typeof server.requestIP !== "function") {
11676
11739
  return { address: undefined, hasRequestIp: false };
@@ -11683,25 +11746,14 @@ function requestAddress(server, req) {
11683
11746
  function configuredKey(value) {
11684
11747
  return typeof value === "string" && value.length > 0 ? value : undefined;
11685
11748
  }
11686
- function configuredBindHosts(value) {
11687
- if (value === undefined)
11688
- return;
11689
- const bindHosts = [
11690
- ...new Set(value.split(",").map((host) => host.trim()).filter(Boolean))
11691
- ];
11692
- return bindHosts.length > 0 ? bindHosts : undefined;
11693
- }
11694
11749
  function createExposureConfig(config) {
11695
11750
  const configuredHost = configuredKey(process.env.CF_HOST) ?? configuredKey(config.get("host"));
11696
- const bindHosts = configuredBindHosts(process.env.CF_BIND_HOSTS) ?? [
11697
- configuredHost ?? "127.0.0.1"
11698
- ];
11699
11751
  const configuredTrustLoopback = process.env.CF_TRUST_LOOPBACK;
11700
11752
  return {
11701
11753
  adminKey: configuredKey(process.env.CF_ADMIN_KEY),
11702
- bindHost: bindHosts[0],
11703
- bindHosts,
11754
+ bindHost: configuredHost ?? "127.0.0.1",
11704
11755
  proxyKey: configuredKey(process.env.CF_PROXY_KEY),
11756
+ clientKeysFile: configuredKey(process.env.CF_CLIENT_KEYS_FILE),
11705
11757
  trustLoopback: configuredTrustLoopback === undefined ? config.get("trust_loopback") !== false : configuredTrustLoopback !== "false"
11706
11758
  };
11707
11759
  }
@@ -11715,10 +11767,10 @@ function isLoopbackAddress(address) {
11715
11767
  return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
11716
11768
  }
11717
11769
  function safeKeyEqual(candidate, expected) {
11718
- if (!candidate || !expected || candidate.length !== expected.length) {
11770
+ if (!candidate || !expected || Buffer.byteLength(candidate) !== Buffer.byteLength(expected)) {
11719
11771
  return false;
11720
11772
  }
11721
- return timingSafeEqual(Buffer.from(candidate), Buffer.from(expected));
11773
+ return timingSafeEqual2(Buffer.from(candidate), Buffer.from(expected));
11722
11774
  }
11723
11775
  function bearerToken(req) {
11724
11776
  const authorization = req.headers.get("authorization");
@@ -11739,6 +11791,9 @@ function keyRole(req, url, config) {
11739
11791
  if (isResponsesInferenceRoute(url.pathname) && safeKeyEqual(bearerToken(req), config.proxyKey)) {
11740
11792
  return "proxy";
11741
11793
  }
11794
+ if (deviceKeyMatches(apiKey, config.clientKeysFile) || isResponsesInferenceRoute(url.pathname) && deviceKeyMatches(bearerToken(req), config.clientKeysFile)) {
11795
+ return "device";
11796
+ }
11742
11797
  return null;
11743
11798
  }
11744
11799
  function hostnameFromHostHeader(host) {
@@ -11752,7 +11807,7 @@ function hostnameFromHostHeader(host) {
11752
11807
  function isWildcardHost(host) {
11753
11808
  return host === "0.0.0.0" || host === "::";
11754
11809
  }
11755
- function isLocalHostHeader(hostHeader, bindHosts) {
11810
+ function isLocalHostHeader(hostHeader, bindHost) {
11756
11811
  if (hostHeader === null) {
11757
11812
  return true;
11758
11813
  }
@@ -11760,8 +11815,7 @@ function isLocalHostHeader(hostHeader, bindHosts) {
11760
11815
  if (!hostname) {
11761
11816
  return false;
11762
11817
  }
11763
- const configuredHosts = typeof bindHosts === "string" ? [bindHosts] : bindHosts;
11764
- return LOOPBACK_HOSTS.has(hostname) || configuredHosts.some((bindHost) => !isWildcardHost(bindHost) && hostname === bindHost.toLowerCase());
11818
+ return LOOPBACK_HOSTS.has(hostname) || !isWildcardHost(bindHost) && hostname === bindHost.toLowerCase();
11765
11819
  }
11766
11820
  function isSameOriginManagementRequest(req, url) {
11767
11821
  const fetchSite = req.headers.get("sec-fetch-site");
@@ -11776,12 +11830,15 @@ function jsonError(status, message) {
11776
11830
  }
11777
11831
  function exposureFailure(req, url, server, config) {
11778
11832
  const remote = requestAddress(server, req);
11779
- const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHosts)) && !isForwardedRequest(req.headers);
11833
+ const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHost)) && !isForwardedRequest(req.headers);
11780
11834
  const role = keyRole(req, url, config);
11835
+ if (role === "device" && !isDeviceRoute(req.method, url.pathname + url.search)) {
11836
+ return jsonError(403, "Device keys only allow health and inference");
11837
+ }
11781
11838
  if (!role && !loopbackExempt) {
11782
11839
  return jsonError(401, "A proxy key is required for this request");
11783
11840
  }
11784
- if (!role && !isLocalHostHeader(req.headers.get("host"), config.bindHosts)) {
11841
+ if (!role && !isLocalHostHeader(req.headers.get("host"), config.bindHost)) {
11785
11842
  return jsonError(403, "Host header is not allowed for a loopback request");
11786
11843
  }
11787
11844
  if (url.pathname.startsWith("/api/")) {
@@ -11798,6 +11855,8 @@ function exposureFailure(req, url, server, config) {
11798
11855
  }
11799
11856
  var FORWARDED_HEADERS, LOOPBACK_HOSTS, MUTATING_METHODS;
11800
11857
  var init_exposure = __esm(() => {
11858
+ init_device_keys();
11859
+ init_inference_routes();
11801
11860
  FORWARDED_HEADERS = [
11802
11861
  "forwarded",
11803
11862
  "x-forwarded-for",
@@ -11951,10 +12010,10 @@ var init_bootstrap_runtime = __esm(() => {
11951
12010
  });
11952
12011
 
11953
12012
  // ../../packages/runtime-server/src/dashboard-assets.ts
11954
- import { readFileSync as readFileSync2 } from "fs";
11955
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join7, resolve as resolve2 } from "path";
12013
+ import { readFileSync as readFileSync3 } from "fs";
12014
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, resolve as resolve2 } from "path";
11956
12015
  function resolveConfiguredPath(configuredPath) {
11957
- return isAbsolute2(configuredPath) ? configuredPath : resolve2(process.cwd(), configuredPath);
12016
+ return isAbsolute3(configuredPath) ? configuredPath : resolve2(process.cwd(), configuredPath);
11958
12017
  }
11959
12018
  function resolveDashboardManifestPath() {
11960
12019
  const configuredManifestPath = process.env[DASHBOARD_MANIFEST_PATH_ENV]?.trim();
@@ -11976,7 +12035,7 @@ function loadDashboardAssets() {
11976
12035
  }
11977
12036
  const manifestPath = resolveDashboardManifestPath();
11978
12037
  dashboardAssets = {
11979
- manifest: JSON.parse(readFileSync2(manifestPath, "utf8")),
12038
+ manifest: JSON.parse(readFileSync3(manifestPath, "utf8")),
11980
12039
  distDir: dirname3(manifestPath)
11981
12040
  };
11982
12041
  return dashboardAssets;
@@ -12065,7 +12124,6 @@ function createServerFetchHandler({
12065
12124
  withDashboard,
12066
12125
  exposureConfig = {
12067
12126
  bindHost: "127.0.0.1",
12068
- bindHosts: ["127.0.0.1"],
12069
12127
  trustLoopback: true
12070
12128
  },
12071
12129
  handleProxyRequest = handleProxy,
@@ -12186,7 +12244,7 @@ var init_startup_maintenance = __esm(() => {
12186
12244
  });
12187
12245
 
12188
12246
  // ../../packages/runtime-server/src/index.ts
12189
- import { isAbsolute as isAbsolute3 } from "path";
12247
+ import { isAbsolute as isAbsolute4 } from "path";
12190
12248
  var {serve } = globalThis.Bun;
12191
12249
  function stopRetentionMaintenance() {
12192
12250
  if (stopRetentionJob) {
@@ -12212,10 +12270,8 @@ async function stopServerRuntime() {
12212
12270
  serverStopPromise = (async () => {
12213
12271
  const errors2 = [];
12214
12272
  const activeServer = serverInstance;
12215
- const activeAdditionalServers = additionalServerInstances;
12216
12273
  const activeUnixServer = unixServerInstance;
12217
12274
  serverInstance = null;
12218
- additionalServerInstances = [];
12219
12275
  unixServerInstance = null;
12220
12276
  try {
12221
12277
  await activeUnixServer?.stop(true);
@@ -12227,13 +12283,6 @@ async function stopServerRuntime() {
12227
12283
  } catch (error) {
12228
12284
  errors2.push(toError("Failed to stop Bun server", error));
12229
12285
  }
12230
- for (const [index, server] of activeAdditionalServers.entries()) {
12231
- try {
12232
- await server.stop(true);
12233
- } catch (error) {
12234
- errors2.push(toError(`Failed to stop additional Bun server ${index + 1}`, error));
12235
- }
12236
- }
12237
12286
  stopRetentionMaintenance();
12238
12287
  try {
12239
12288
  await waitForProxyBackgroundTasks();
@@ -12266,7 +12315,7 @@ async function stopServerRuntime() {
12266
12315
  }
12267
12316
  }
12268
12317
  function startServer(options) {
12269
- if (options?.additionalUnixSocket !== undefined && !isAbsolute3(options.additionalUnixSocket)) {
12318
+ if (options?.additionalUnixSocket !== undefined && !isAbsolute4(options.additionalUnixSocket)) {
12270
12319
  throw new Error("Additional Unix socket must be an absolute path");
12271
12320
  }
12272
12321
  if (serverInstance) {
@@ -12312,16 +12361,6 @@ function startServer(options) {
12312
12361
  fetch: fetchHandler,
12313
12362
  websocket: websocketProxyHandler
12314
12363
  });
12315
- const activePort2 = serverInstance.port ?? runtimeConfig2.port;
12316
- for (const hostname of exposureConfig.bindHosts.slice(1)) {
12317
- additionalServerInstances.push(serve({
12318
- hostname,
12319
- port: activePort2,
12320
- idleTimeout: NETWORK.IDLE_TIMEOUT_MAX,
12321
- fetch: fetchHandler,
12322
- websocket: websocketProxyHandler
12323
- }));
12324
- }
12325
12364
  } catch (error) {
12326
12365
  stopServerRuntime().catch(() => {
12327
12366
  lifecycleLog.error("Failed to clean up after listener startup failure");
@@ -12357,7 +12396,7 @@ async function handleGracefulShutdown(signal) {
12357
12396
  process.exit(1);
12358
12397
  }
12359
12398
  }
12360
- var serverLog, lifecycleLog, serverInstance = null, additionalServerInstances, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null;
12399
+ var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null;
12361
12400
  var init_src11 = __esm(() => {
12362
12401
  init_src9();
12363
12402
  init_src2();
@@ -12375,7 +12414,6 @@ var init_src11 = __esm(() => {
12375
12414
  lifecycleLog = new Logger("ServerLifecycle", 1 /* INFO */, {
12376
12415
  silentConsole: false
12377
12416
  });
12378
- additionalServerInstances = [];
12379
12417
  process.on("SIGINT", () => handleGracefulShutdown("SIGINT"));
12380
12418
  process.on("SIGTERM", () => handleGracefulShutdown("SIGTERM"));
12381
12419
  if (false) {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@certalis/agent-smith",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "PROOF OF CONCEPT for ideation only: an experimental local proxy and provider pool for Claude Code and Codex",
5
5
  "license": "MIT",
6
6
  "author": "Certalis",
@@ -16,6 +16,7 @@
16
16
  "agent-smith": "dist/bin.js"
17
17
  },
18
18
  "exports": {
19
+ "./edge": "./dist/edge.js",
19
20
  "./server": "./dist/server.js",
20
21
  "./package.json": "./package.json"
21
22
  },