@certalis/agent-smith 0.1.5 → 0.1.6

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
@@ -1,6 +1,6 @@
1
1
  # agent-smith
2
2
 
3
- **A proof-of-concept local proxy and provider pool for Claude Code and Codex.**
3
+ **A proof-of-concept proxy and provider pool for Claude Code and Codex.**
4
4
 
5
5
  > [!WARNING]
6
6
  > **This is a proof of concept for ideation, not a product.** It exists to
@@ -15,10 +15,10 @@
15
15
  > providers' terms.
16
16
  > - Not affiliated with, endorsed by or sponsored by Anthropic or OpenAI.
17
17
 
18
- Claude Code and Codex keep talking their own protocol. agent-smith sits on
19
- localhost between them and the provider: it chooses a provider from the pool you
20
- configure, then an account inside that provider, watches the quota each
21
- provider reports, and fails over when one cannot serve.
18
+ Claude Code and Codex keep talking their own protocol. agent-smith sits between
19
+ them and the provider: it chooses a provider from the pool you configure, then
20
+ an account inside that provider, watches the quota each provider reports, and
21
+ fails over when one cannot serve.
22
22
 
23
23
  ## How it works
24
24
 
@@ -85,6 +85,40 @@ 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 development caller through SSH
89
+
90
+ The agents box and a development laptop both send requests to one proxy with a
91
+ forwarding key. A laptop can reach a private server through an SSH tunnel in
92
+ v1.
93
+
94
+ This is connectivity only, not team tenancy: the shared forwarding key does
95
+ not identify an individual caller or enforce per-client fairness. Do not
96
+ distribute it team-wide until the B2/W7 tenancy work exists.
97
+
98
+ Copy [`team-client.json`](examples/config/team-client.json) into your private
99
+ Agent-smith config. Put the forwarding key in the owner-only file named by
100
+ `proxy_key_file`, not in the JSON or a shell profile. `base_url` is the endpoint
101
+ visible to your machine, not a second pool. The key can spend from the pool, but
102
+ cannot administer it.
103
+
104
+ For an SSH tunnel, forward a local port to the private server and leave that SSH
105
+ session running:
106
+
107
+ ```bash
108
+ ssh -N -L 18181:127.0.0.1:8080 agent-smith-pool
109
+ ```
110
+
111
+ Then install the normal `claude` and `codex` wrappers once:
112
+
113
+ ```bash
114
+ agent-smith install-client
115
+ ```
116
+
117
+ Open a new terminal and use `claude` or `codex` normally. The wrappers only add
118
+ their own marked `PATH` entry; they do not replace the real binaries or start a
119
+ second proxy. The forwarding key is for inference, not dashboard or management
120
+ access.
121
+
88
122
  ## Configuration
89
123
 
90
124
  The config file is JSON, read at startup from:
@@ -103,6 +137,7 @@ Restart agent-smith after changing `providers`, `provider_pools`, `alerts` or
103
137
  | `providers.<name>.base_url` | The upstream URL, for an endpoint compatible with one of the strategies. |
104
138
  | `providers.<name>.models` | The models a provider serves, as `"client model": "provider model"`. A trailing `*` matches a prefix. Without it, the provider serves every model name unchanged. |
105
139
  | `provider_pools.<protocol>` | The ordered providers for `anthropic-messages` or `openai-responses`. Clients reach it at `/v1/pool/<protocol>/*`, and the local wrappers use it automatically. |
140
+ | `client` | The Agent-smith origin and forwarding key used by `agent-smith install-client`. It is for this machine only; it does not define providers or a separate pool. |
106
141
  | `team_routing` | Which subscription accounts may share a pool, and their usage caps. See the [configuration guide](docs/configuration.md#team-routing). |
107
142
  | `alerts` | A Slack webhook or bot token and/or an email address that hear when a seat spends extra usage and when every account is full. A filled value turns its channel on. See [Alerts](docs/configuration.md#alerts). |
108
143
  | `block_when_all_full` | `true` by default: when every account is full, every request is refused until the soonest reset, so none spends extra usage. |
@@ -157,6 +192,20 @@ to `acme` and are sent as `acme-large`. `acme` serves no other model.
157
192
  }
158
193
  ```
159
194
 
195
+ **A laptop using a private shared pool**
196
+ ([`team-client.json`](examples/config/team-client.json)). The example uses an
197
+ SSH-local port; use the direct private origin instead on a host that can reach
198
+ the pool without SSH.
199
+
200
+ ```json
201
+ {
202
+ "client": {
203
+ "base_url": "http://127.0.0.1:18181",
204
+ "proxy_key_file": "~/.config/ccflare/team-pool.key"
205
+ }
206
+ }
207
+ ```
208
+
160
209
  The Claude Code and Codex subscription examples are in
161
210
  [Subscription sign-ins and provider terms](#subscription-sign-ins-and-provider-terms).
162
211
 
package/dist/bin.js CHANGED
@@ -1263,11 +1263,13 @@ var init_paths = __esm(() => {
1263
1263
  // ../../packages/config/src/index.ts
1264
1264
  import { EventEmitter as EventEmitter3 } from "events";
1265
1265
  import {
1266
+ chmodSync,
1266
1267
  existsSync as existsSync2,
1267
1268
  mkdirSync as mkdirSync2,
1268
1269
  readFileSync,
1269
1270
  renameSync,
1270
1271
  rmSync,
1272
+ statSync as statSync2,
1271
1273
  writeFileSync
1272
1274
  } from "fs";
1273
1275
  import { dirname } from "path";
@@ -1320,6 +1322,12 @@ function sanitizeConfigData(value) {
1320
1322
  sanitized.provider_pools = providerPools;
1321
1323
  continue;
1322
1324
  }
1325
+ if (key === "client") {
1326
+ const client = sanitizeClientRouting(entry);
1327
+ if (client)
1328
+ sanitized.client = client;
1329
+ continue;
1330
+ }
1323
1331
  if (key === "alerts") {
1324
1332
  const alerts = sanitizeAlerts(entry);
1325
1333
  if (alerts)
@@ -1409,6 +1417,23 @@ function sanitizeProviderBaseUrl(value) {
1409
1417
  return;
1410
1418
  }
1411
1419
  }
1420
+ function sanitizeClientRouting(value) {
1421
+ if (!isRecord(value))
1422
+ return;
1423
+ const client = {};
1424
+ if (typeof value.base_url === "string") {
1425
+ try {
1426
+ const url = new URL(value.base_url);
1427
+ if ((url.protocol === "http:" || url.protocol === "https:") && url.pathname === "/" && url.search === "" && url.hash === "" && url.username === "" && url.password === "") {
1428
+ client.base_url = url.origin;
1429
+ }
1430
+ } catch {}
1431
+ }
1432
+ if (typeof value.proxy_key_file === "string" && (value.proxy_key_file.startsWith("/") || value.proxy_key_file.startsWith("~/")) && value.proxy_key_file.length <= 1024) {
1433
+ client.proxy_key_file = value.proxy_key_file;
1434
+ }
1435
+ return Object.keys(client).length > 0 ? client : undefined;
1436
+ }
1412
1437
  function sanitizeProviderModels(value) {
1413
1438
  if (!isRecord(value))
1414
1439
  return;
@@ -1544,17 +1569,30 @@ var init_src4 = __esm(() => {
1544
1569
  try {
1545
1570
  const content = readFileSync(this.configPath, "utf8");
1546
1571
  this.data = sanitizeConfigData(JSON.parse(content));
1547
- if ("default_agent_model" in this.data) {
1548
- delete this.data.default_agent_model;
1549
- this.saveConfig();
1550
- }
1551
1572
  } catch (error) {
1552
1573
  log2.error(`Failed to parse config file: ${error}`);
1553
1574
  this.data = {};
1575
+ return;
1576
+ }
1577
+ try {
1578
+ chmodSync(this.configPath, 384);
1579
+ } catch {
1580
+ let ownerOnly = false;
1581
+ try {
1582
+ ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
1583
+ } catch {}
1584
+ if (!ownerOnly) {
1585
+ throw new Error("Config file must be owner-only");
1586
+ }
1587
+ }
1588
+ if ("default_agent_model" in this.data) {
1589
+ delete this.data.default_agent_model;
1590
+ this.saveConfig();
1554
1591
  }
1555
1592
  } else {
1556
1593
  const dir = dirname(this.configPath);
1557
- mkdirSync2(dir, { recursive: true });
1594
+ mkdirSync2(dir, { recursive: true, mode: 448 });
1595
+ chmodSync(dir, 448);
1558
1596
  this.data = {
1559
1597
  lb_strategy: DEFAULT_STRATEGY
1560
1598
  };
@@ -1685,6 +1723,15 @@ var init_src4 = __esm(() => {
1685
1723
  resendApiKey: file?.resend_api_key ?? null
1686
1724
  };
1687
1725
  }
1726
+ getClientRouting() {
1727
+ const client = this.data.client;
1728
+ return {
1729
+ ...client?.base_url && { baseUrl: client.base_url },
1730
+ ...client?.proxy_key_file && {
1731
+ proxyKeyFile: client.proxy_key_file
1732
+ }
1733
+ };
1734
+ }
1688
1735
  getBlockWhenAllFull() {
1689
1736
  return this.data.block_when_all_full !== false;
1690
1737
  }
@@ -11662,12 +11709,23 @@ function safeKeyEqual(candidate, expected) {
11662
11709
  }
11663
11710
  return timingSafeEqual(Buffer.from(candidate), Buffer.from(expected));
11664
11711
  }
11665
- function keyRole(req, config) {
11666
- const key = req.headers.get("x-api-key");
11667
- if (safeKeyEqual(key, config.adminKey)) {
11712
+ function bearerToken(req) {
11713
+ const authorization = req.headers.get("authorization");
11714
+ const match = authorization?.match(/^Bearer ([^\s]+)$/);
11715
+ return match?.[1] ?? null;
11716
+ }
11717
+ function isResponsesInferenceRoute(pathname) {
11718
+ return pathname === "/v1/codex/responses" || pathname === "/v1/pool/openai-responses/responses";
11719
+ }
11720
+ function keyRole(req, url, config) {
11721
+ const apiKey = req.headers.get("x-api-key");
11722
+ if (safeKeyEqual(apiKey, config.adminKey)) {
11668
11723
  return "admin";
11669
11724
  }
11670
- if (safeKeyEqual(key, config.proxyKey)) {
11725
+ if (safeKeyEqual(apiKey, config.proxyKey)) {
11726
+ return "proxy";
11727
+ }
11728
+ if (isResponsesInferenceRoute(url.pathname) && safeKeyEqual(bearerToken(req), config.proxyKey)) {
11671
11729
  return "proxy";
11672
11730
  }
11673
11731
  return null;
@@ -11707,7 +11765,7 @@ function jsonError(status, message) {
11707
11765
  function exposureFailure(req, url, server, config) {
11708
11766
  const remote = requestAddress(server, req);
11709
11767
  const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHost)) && !isForwardedRequest(req.headers);
11710
- const role = keyRole(req, config);
11768
+ const role = keyRole(req, url, config);
11711
11769
  if (!role && !loopbackExempt) {
11712
11770
  return jsonError(401, "A proxy key is required for this request");
11713
11771
  }
@@ -13820,6 +13878,9 @@ var init_analytics2 = __esm(() => {
13820
13878
  // src/core/args.ts
13821
13879
  import { parseArgs as nodeParseArgs } from "util";
13822
13880
  function parseArgs(args) {
13881
+ if (args.length === 1 && args[0] === "install-client") {
13882
+ return { installClient: true };
13883
+ }
13823
13884
  if (args[0] === "run") {
13824
13885
  const separator = args.indexOf("--");
13825
13886
  if (separator === -1) {
@@ -13895,11 +13956,12 @@ var init_args = () => {};
13895
13956
  // src/core/local-routing.ts
13896
13957
  import {
13897
13958
  accessSync,
13898
- chmodSync,
13959
+ chmodSync as chmodSync2,
13899
13960
  constants as constants2,
13900
13961
  existsSync as existsSync3,
13901
13962
  mkdirSync as mkdirSync4,
13902
13963
  readFileSync as readFileSync3,
13964
+ statSync as statSync3,
13903
13965
  unlinkSync as unlinkSync2,
13904
13966
  writeFileSync as writeFileSync2
13905
13967
  } from "fs";
@@ -13911,25 +13973,56 @@ function shellQuote(value) {
13911
13973
  function shellDoubleQuote(value) {
13912
13974
  return `"${value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
13913
13975
  }
13914
- function proxyBaseUrl(port, directProvider, wire, providerPoolWires) {
13976
+ function proxyBaseUrl(port, configuredBaseUrl, directProvider, wire, providerPoolWires) {
13915
13977
  const route = providerPoolWires?.includes(wire) ? `/v1/pool/${wire}` : `/v1/${directProvider}`;
13916
- return `http://127.0.0.1:${port}${route}`;
13978
+ return `${configuredBaseUrl ?? `http://127.0.0.1:${port}`}${route}`;
13917
13979
  }
13918
- function claudeWrapper(claudePath, baseUrl) {
13980
+ function validateProxyKeyFile(proxyKeyFile) {
13981
+ const resolvedPath = proxyKeyFile.startsWith("~/") ? join8(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
13982
+ let metadata;
13983
+ try {
13984
+ metadata = statSync3(resolvedPath);
13985
+ } catch {
13986
+ throw new Error("Agent-smith forwarding-key file is not readable");
13987
+ }
13988
+ if (!metadata.isFile()) {
13989
+ throw new Error("Agent-smith forwarding-key path must be a file");
13990
+ }
13991
+ if ((metadata.mode & 63) !== 0) {
13992
+ throw new Error("Agent-smith forwarding-key file must be owner-only");
13993
+ }
13994
+ const key = readFileSync3(resolvedPath, "utf8").trim();
13995
+ if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
13996
+ throw new Error("Agent-smith forwarding-key file is invalid");
13997
+ }
13998
+ return resolvedPath;
13999
+ }
14000
+ function proxyKeySetup(proxyKeyFile) {
14001
+ if (!proxyKeyFile) {
14002
+ return `export AGENT_SMITH_PROXY_KEY=${shellQuote(LOCAL_CLIENT_KEY)}`;
14003
+ }
14004
+ return `if [ ! -r ${shellQuote(proxyKeyFile)} ]; then
14005
+ echo "Agent-smith forwarding-key file is not readable" >&2
14006
+ exit 1
14007
+ fi
14008
+ export AGENT_SMITH_PROXY_KEY=$(cat ${shellQuote(proxyKeyFile)})`;
14009
+ }
14010
+ function claudeWrapper(claudePath, baseUrl, proxyKeyFile) {
13919
14011
  return `#!/bin/sh
13920
14012
  # Generated by agent-smith. This file delegates to the real Claude Code binary.
13921
14013
  unset CF_ADMIN_KEY
13922
14014
  unset CF_PROXY_KEY
13923
- export ANTHROPIC_API_KEY=${shellQuote(LOCAL_CLIENT_KEY)}
13924
- export ANTHROPIC_AUTH_TOKEN=${shellQuote(LOCAL_CLIENT_KEY)}
14015
+ ${proxyKeySetup(proxyKeyFile)}
14016
+ export ANTHROPIC_API_KEY="$AGENT_SMITH_PROXY_KEY"
14017
+ export ANTHROPIC_AUTH_TOKEN="$AGENT_SMITH_PROXY_KEY"
13925
14018
  export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
13926
14019
  exec ${shellQuote(claudePath)} "$@"
13927
14020
  `;
13928
14021
  }
13929
- function codexWrapper(codexPath, baseUrl) {
14022
+ function codexWrapper(codexPath, baseUrl, proxyKeyFile) {
13930
14023
  const config = [
13931
14024
  'model_provider="agent_smith"',
13932
- 'model_providers.agent_smith.name="Agent-smith local pool"',
14025
+ 'model_providers.agent_smith.name="Agent-smith"',
13933
14026
  `model_providers.agent_smith.base_url="${baseUrl}"`,
13934
14027
  'model_providers.agent_smith.env_key="AGENT_SMITH_PROXY_KEY"',
13935
14028
  'model_providers.agent_smith.wire_api="responses"',
@@ -13941,29 +14034,33 @@ function codexWrapper(codexPath, baseUrl) {
13941
14034
  # Generated by agent-smith. This file delegates to the real Codex binary.
13942
14035
  unset CF_ADMIN_KEY
13943
14036
  unset CF_PROXY_KEY
13944
- export AGENT_SMITH_PROXY_KEY=${shellQuote(LOCAL_CLIENT_KEY)}
14037
+ ${proxyKeySetup(proxyKeyFile)}
13945
14038
  exec ${shellQuote(codexPath)} \\
13946
14039
  ${overrides} \\
13947
14040
  "$@"
13948
14041
  `;
13949
14042
  }
13950
14043
  async function installClientWrappers(options) {
14044
+ if (options.baseUrl && !options.proxyKeyFile) {
14045
+ throw new Error("A configured Agent-smith server requires a forwarding key file");
14046
+ }
13951
14047
  mkdirSync4(options.binDir, { recursive: true, mode: 448 });
14048
+ const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
13952
14049
  if (options.claudePath) {
13953
14050
  const claude = join8(options.binDir, "claude");
13954
- writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, "claude-code", "anthropic-messages", options.providerPoolWires)), {
14051
+ writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile), {
13955
14052
  encoding: "utf8",
13956
14053
  mode: 448
13957
14054
  });
13958
- chmodSync(claude, 448);
14055
+ chmodSync2(claude, 448);
13959
14056
  }
13960
14057
  if (options.codexPath) {
13961
14058
  const codex = join8(options.binDir, "codex");
13962
- writeFileSync2(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, "codex", "openai-responses", options.providerPoolWires)), {
14059
+ writeFileSync2(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
13963
14060
  encoding: "utf8",
13964
14061
  mode: 448
13965
14062
  });
13966
- chmodSync(codex, 448);
14063
+ chmodSync2(codex, 448);
13967
14064
  }
13968
14065
  }
13969
14066
  function defaultShellProfile() {
@@ -14050,6 +14147,8 @@ async function enableLocalClientRouting(options) {
14050
14147
  claudePath,
14051
14148
  codexPath,
14052
14149
  port: options.port,
14150
+ baseUrl: options.baseUrl,
14151
+ proxyKeyFile: options.proxyKeyFile,
14053
14152
  providerPoolWires: options.providerPoolWires ?? Object.keys(new Config().getProviderPools())
14054
14153
  });
14055
14154
  const existingProfile = existsSync3(shellProfile) ? readFileSync3(shellProfile, "utf8") : "";
@@ -14059,7 +14158,7 @@ async function enableLocalClientRouting(options) {
14059
14158
  encoding: "utf8",
14060
14159
  mode: 384
14061
14160
  });
14062
- chmodSync(statePath, 384);
14161
+ chmodSync2(statePath, 384);
14063
14162
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
14064
14163
  }
14065
14164
  function disableLocalClientRouting(paths2 = {}) {
@@ -17788,6 +17887,7 @@ ${POC_NOTICE}
17788
17887
 
17789
17888
  Usage: agent-smith [options]
17790
17889
  agent-smith run [--port <number>] -- [claude arguments]
17890
+ agent-smith install-client
17791
17891
 
17792
17892
  Options:
17793
17893
  --serve Start API server with dashboard
@@ -17817,6 +17917,7 @@ Examples:
17817
17917
  agent-smith --pause work # Pause account
17818
17918
  agent-smith --analyze # Run performance analysis
17819
17919
  agent-smith --stats # View stats
17920
+ agent-smith install-client # Configure Claude Code and Codex for this Agent-smith server
17820
17921
  `);
17821
17922
  process.exit(0);
17822
17923
  }
@@ -17828,6 +17929,21 @@ Examples:
17828
17929
  await new Promise(() => {});
17829
17930
  return;
17830
17931
  }
17932
+ if (parsed.installClient) {
17933
+ const config2 = new Config;
17934
+ const client2 = config2.getClientRouting();
17935
+ if (!client2.baseUrl || !client2.proxyKeyFile) {
17936
+ throw new Error("client.base_url and client.proxy_key_file are required before installing client wrappers");
17937
+ }
17938
+ const port2 = config2.getRuntime().port || NETWORK.DEFAULT_PORT;
17939
+ await enableLocalClientRouting({
17940
+ port: port2,
17941
+ baseUrl: client2.baseUrl,
17942
+ proxyKeyFile: client2.proxyKeyFile
17943
+ });
17944
+ console.log(`Claude Code and Codex now route through ${client2.baseUrl}`);
17945
+ return;
17946
+ }
17831
17947
  if (parsed.run) {
17832
17948
  printPocNotice();
17833
17949
  const config2 = new Config;
@@ -1315,11 +1315,13 @@ var init_paths = __esm(() => {
1315
1315
  // ../../packages/config/src/index.ts
1316
1316
  import { EventEmitter as EventEmitter3 } from "events";
1317
1317
  import {
1318
+ chmodSync,
1318
1319
  existsSync as existsSync2,
1319
1320
  mkdirSync as mkdirSync2,
1320
1321
  readFileSync,
1321
1322
  renameSync,
1322
1323
  rmSync,
1324
+ statSync as statSync2,
1323
1325
  writeFileSync
1324
1326
  } from "fs";
1325
1327
  import { dirname } from "path";
@@ -1372,6 +1374,12 @@ function sanitizeConfigData(value) {
1372
1374
  sanitized.provider_pools = providerPools;
1373
1375
  continue;
1374
1376
  }
1377
+ if (key === "client") {
1378
+ const client = sanitizeClientRouting(entry);
1379
+ if (client)
1380
+ sanitized.client = client;
1381
+ continue;
1382
+ }
1375
1383
  if (key === "alerts") {
1376
1384
  const alerts = sanitizeAlerts(entry);
1377
1385
  if (alerts)
@@ -1461,6 +1469,23 @@ function sanitizeProviderBaseUrl(value) {
1461
1469
  return;
1462
1470
  }
1463
1471
  }
1472
+ function sanitizeClientRouting(value) {
1473
+ if (!isRecord(value))
1474
+ return;
1475
+ const client = {};
1476
+ if (typeof value.base_url === "string") {
1477
+ try {
1478
+ const url = new URL(value.base_url);
1479
+ if ((url.protocol === "http:" || url.protocol === "https:") && url.pathname === "/" && url.search === "" && url.hash === "" && url.username === "" && url.password === "") {
1480
+ client.base_url = url.origin;
1481
+ }
1482
+ } catch {}
1483
+ }
1484
+ if (typeof value.proxy_key_file === "string" && (value.proxy_key_file.startsWith("/") || value.proxy_key_file.startsWith("~/")) && value.proxy_key_file.length <= 1024) {
1485
+ client.proxy_key_file = value.proxy_key_file;
1486
+ }
1487
+ return Object.keys(client).length > 0 ? client : undefined;
1488
+ }
1464
1489
  function sanitizeProviderModels(value) {
1465
1490
  if (!isRecord(value))
1466
1491
  return;
@@ -1596,17 +1621,30 @@ var init_src4 = __esm(() => {
1596
1621
  try {
1597
1622
  const content = readFileSync(this.configPath, "utf8");
1598
1623
  this.data = sanitizeConfigData(JSON.parse(content));
1599
- if ("default_agent_model" in this.data) {
1600
- delete this.data.default_agent_model;
1601
- this.saveConfig();
1602
- }
1603
1624
  } catch (error) {
1604
1625
  log2.error(`Failed to parse config file: ${error}`);
1605
1626
  this.data = {};
1627
+ return;
1628
+ }
1629
+ try {
1630
+ chmodSync(this.configPath, 384);
1631
+ } catch {
1632
+ let ownerOnly = false;
1633
+ try {
1634
+ ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
1635
+ } catch {}
1636
+ if (!ownerOnly) {
1637
+ throw new Error("Config file must be owner-only");
1638
+ }
1639
+ }
1640
+ if ("default_agent_model" in this.data) {
1641
+ delete this.data.default_agent_model;
1642
+ this.saveConfig();
1606
1643
  }
1607
1644
  } else {
1608
1645
  const dir = dirname(this.configPath);
1609
- mkdirSync2(dir, { recursive: true });
1646
+ mkdirSync2(dir, { recursive: true, mode: 448 });
1647
+ chmodSync(dir, 448);
1610
1648
  this.data = {
1611
1649
  lb_strategy: DEFAULT_STRATEGY
1612
1650
  };
@@ -1737,6 +1775,15 @@ var init_src4 = __esm(() => {
1737
1775
  resendApiKey: file?.resend_api_key ?? null
1738
1776
  };
1739
1777
  }
1778
+ getClientRouting() {
1779
+ const client = this.data.client;
1780
+ return {
1781
+ ...client?.base_url && { baseUrl: client.base_url },
1782
+ ...client?.proxy_key_file && {
1783
+ proxyKeyFile: client.proxy_key_file
1784
+ }
1785
+ };
1786
+ }
1740
1787
  getBlockWhenAllFull() {
1741
1788
  return this.data.block_when_all_full !== false;
1742
1789
  }
package/dist/server.js CHANGED
@@ -3834,11 +3834,13 @@ var init_paths = __esm(() => {
3834
3834
  // ../../packages/config/src/index.ts
3835
3835
  import { EventEmitter as EventEmitter3 } from "events";
3836
3836
  import {
3837
+ chmodSync,
3837
3838
  existsSync as existsSync2,
3838
3839
  mkdirSync as mkdirSync2,
3839
3840
  readFileSync,
3840
3841
  renameSync,
3841
3842
  rmSync,
3843
+ statSync as statSync2,
3842
3844
  writeFileSync
3843
3845
  } from "fs";
3844
3846
  import { dirname } from "path";
@@ -3891,6 +3893,12 @@ function sanitizeConfigData(value) {
3891
3893
  sanitized.provider_pools = providerPools;
3892
3894
  continue;
3893
3895
  }
3896
+ if (key === "client") {
3897
+ const client2 = sanitizeClientRouting(entry);
3898
+ if (client2)
3899
+ sanitized.client = client2;
3900
+ continue;
3901
+ }
3894
3902
  if (key === "alerts") {
3895
3903
  const alerts = sanitizeAlerts(entry);
3896
3904
  if (alerts)
@@ -3980,6 +3988,23 @@ function sanitizeProviderBaseUrl(value) {
3980
3988
  return;
3981
3989
  }
3982
3990
  }
3991
+ function sanitizeClientRouting(value) {
3992
+ if (!isRecord(value))
3993
+ return;
3994
+ const client2 = {};
3995
+ if (typeof value.base_url === "string") {
3996
+ try {
3997
+ const url = new URL(value.base_url);
3998
+ if ((url.protocol === "http:" || url.protocol === "https:") && url.pathname === "/" && url.search === "" && url.hash === "" && url.username === "" && url.password === "") {
3999
+ client2.base_url = url.origin;
4000
+ }
4001
+ } catch {}
4002
+ }
4003
+ if (typeof value.proxy_key_file === "string" && (value.proxy_key_file.startsWith("/") || value.proxy_key_file.startsWith("~/")) && value.proxy_key_file.length <= 1024) {
4004
+ client2.proxy_key_file = value.proxy_key_file;
4005
+ }
4006
+ return Object.keys(client2).length > 0 ? client2 : undefined;
4007
+ }
3983
4008
  function sanitizeProviderModels(value) {
3984
4009
  if (!isRecord(value))
3985
4010
  return;
@@ -4115,17 +4140,30 @@ var init_src7 = __esm(() => {
4115
4140
  try {
4116
4141
  const content = readFileSync(this.configPath, "utf8");
4117
4142
  this.data = sanitizeConfigData(JSON.parse(content));
4118
- if ("default_agent_model" in this.data) {
4119
- delete this.data.default_agent_model;
4120
- this.saveConfig();
4121
- }
4122
4143
  } catch (error) {
4123
4144
  log6.error(`Failed to parse config file: ${error}`);
4124
4145
  this.data = {};
4146
+ return;
4147
+ }
4148
+ try {
4149
+ chmodSync(this.configPath, 384);
4150
+ } catch {
4151
+ let ownerOnly = false;
4152
+ try {
4153
+ ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
4154
+ } catch {}
4155
+ if (!ownerOnly) {
4156
+ throw new Error("Config file must be owner-only");
4157
+ }
4158
+ }
4159
+ if ("default_agent_model" in this.data) {
4160
+ delete this.data.default_agent_model;
4161
+ this.saveConfig();
4125
4162
  }
4126
4163
  } else {
4127
4164
  const dir = dirname(this.configPath);
4128
- mkdirSync2(dir, { recursive: true });
4165
+ mkdirSync2(dir, { recursive: true, mode: 448 });
4166
+ chmodSync(dir, 448);
4129
4167
  this.data = {
4130
4168
  lb_strategy: DEFAULT_STRATEGY
4131
4169
  };
@@ -4256,6 +4294,15 @@ var init_src7 = __esm(() => {
4256
4294
  resendApiKey: file?.resend_api_key ?? null
4257
4295
  };
4258
4296
  }
4297
+ getClientRouting() {
4298
+ const client2 = this.data.client;
4299
+ return {
4300
+ ...client2?.base_url && { baseUrl: client2.base_url },
4301
+ ...client2?.proxy_key_file && {
4302
+ proxyKeyFile: client2.proxy_key_file
4303
+ }
4304
+ };
4305
+ }
4259
4306
  getBlockWhenAllFull() {
4260
4307
  return this.data.block_when_all_full !== false;
4261
4308
  }
@@ -11661,12 +11708,23 @@ function safeKeyEqual(candidate, expected) {
11661
11708
  }
11662
11709
  return timingSafeEqual(Buffer.from(candidate), Buffer.from(expected));
11663
11710
  }
11664
- function keyRole(req, config) {
11665
- const key = req.headers.get("x-api-key");
11666
- if (safeKeyEqual(key, config.adminKey)) {
11711
+ function bearerToken(req) {
11712
+ const authorization = req.headers.get("authorization");
11713
+ const match = authorization?.match(/^Bearer ([^\s]+)$/);
11714
+ return match?.[1] ?? null;
11715
+ }
11716
+ function isResponsesInferenceRoute(pathname) {
11717
+ return pathname === "/v1/codex/responses" || pathname === "/v1/pool/openai-responses/responses";
11718
+ }
11719
+ function keyRole(req, url, config) {
11720
+ const apiKey = req.headers.get("x-api-key");
11721
+ if (safeKeyEqual(apiKey, config.adminKey)) {
11667
11722
  return "admin";
11668
11723
  }
11669
- if (safeKeyEqual(key, config.proxyKey)) {
11724
+ if (safeKeyEqual(apiKey, config.proxyKey)) {
11725
+ return "proxy";
11726
+ }
11727
+ if (isResponsesInferenceRoute(url.pathname) && safeKeyEqual(bearerToken(req), config.proxyKey)) {
11670
11728
  return "proxy";
11671
11729
  }
11672
11730
  return null;
@@ -11706,7 +11764,7 @@ function jsonError(status, message) {
11706
11764
  function exposureFailure(req, url, server, config) {
11707
11765
  const remote = requestAddress(server, req);
11708
11766
  const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHost)) && !isForwardedRequest(req.headers);
11709
- const role = keyRole(req, config);
11767
+ const role = keyRole(req, url, config);
11710
11768
  if (!role && !loopbackExempt) {
11711
11769
  return jsonError(401, "A proxy key is required for this request");
11712
11770
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@certalis/agent-smith",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
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",