@certalis/agent-smith 0.1.13 → 0.1.15

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
@@ -105,8 +105,7 @@ Copy [`https-client.json`](examples/config/https-client.json) into your private
105
105
  Agent Smith config. Put the device key in the owner-only file named by
106
106
  `proxy_key_file`, not in the JSON or a shell profile. `base_url` is the endpoint
107
107
  visible to your machine, not a second pool. The key can spend from the pool, but
108
- cannot administer it. Remote client routing is off by default: set
109
- `client.enabled` to `true` when this machine should use the shared pool.
108
+ cannot administer it. Remote client routing is off by default.
110
109
 
111
110
  An SSH tunnel remains an option for development. Use
112
111
  [`team-client.json`](examples/config/team-client.json) and forward its local port
@@ -116,10 +115,10 @@ to the private server:
116
115
  ssh -N -L 18181:127.0.0.1:8080 agent-smith-pool
117
116
  ```
118
117
 
119
- Then apply the flag with the normal client setup command:
118
+ Then turn on shared-pool use with the shipped command:
120
119
 
121
120
  ```bash
122
- agent-smith install-client
121
+ agent-smith client on
123
122
  ```
124
123
 
125
124
  Open a new terminal and use `claude` or `codex` normally. The wrappers only add
@@ -128,12 +127,21 @@ second proxy. The forwarding key is for inference, not dashboard or management
128
127
  access.
129
128
 
130
129
  Claude sends one device credential in the API-key header to the gateway; it is
131
- not an Anthropic Console key. Claude.ai cloud connectors are not available by default in this
132
- mode; see the [client behavior and limits](docs/https-edge.md#configure-and-prove).
133
-
134
- To switch back to ordinary local Claude Code/Codex, set `client.enabled` to
135
- `false` and run `agent-smith install-client` again. It removes only its wrappers
136
- and marked shell entry; it does not change the real clients or their credentials.
130
+ not an Anthropic Console key. Claude in Chrome and claude.ai cloud connectors are not available by default in this
131
+ mode; `client.keep_claude_login` keeps them on. See the
132
+ [client behavior and limits](docs/https-edge.md#configure-and-prove).
133
+
134
+ Use `agent-smith client off` to use ordinary local Claude Code/Codex again;
135
+ `agent-smith client status` shows the switch and launcher setup. Add `--raw` for
136
+ JSON instead of readable text. These commands work outside any repository.
137
+
138
+ The first `on` installs the launchers (or updates previously generated ones).
139
+ Later switches change only `client.enabled`: each new client process reads the
140
+ current origin, key-file path and flag. Off keeps the launchers installed, reads
141
+ no forwarding key and delegates to the native client without changing its login.
142
+ Restart/resume existing sessions after switching. No proxy restart is needed.
143
+ `install-client` remains the explicit setup/removal command; it is not needed
144
+ between on/off switches.
137
145
 
138
146
  ## Configuration
139
147
 
@@ -153,7 +161,7 @@ Restart agent-smith after changing `providers`, `provider_pools`, `alerts` or
153
161
  | `providers.<name>.base_url` | The upstream URL, for an endpoint compatible with one of the strategies. |
154
162
  | `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. |
155
163
  | `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. |
156
- | `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. |
164
+ | `client` | This machine's shared-pool switch, origin and forwarding-key file. Use `agent-smith client on`, `off` or `status`; it does not define providers or a separate pool. |
157
165
  | `team_routing` | Which subscription accounts may share a pool, and their usage caps. See the [configuration guide](docs/configuration.md#team-routing). |
158
166
  | `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). |
159
167
  | `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. |
package/dist/bin.js CHANGED
@@ -239,9 +239,11 @@ var init_errors = __esm(() => {
239
239
  };
240
240
  ServiceUnavailableError = class ServiceUnavailableError extends AppError {
241
241
  service;
242
- constructor(message, service) {
242
+ retryAfterSeconds;
243
+ constructor(message, service, retryAfterSeconds) {
243
244
  super(message, "SERVICE_UNAVAILABLE", 503, { service });
244
245
  this.service = service;
246
+ this.retryAfterSeconds = retryAfterSeconds;
245
247
  }
246
248
  };
247
249
  });
@@ -1434,6 +1436,9 @@ function sanitizeClientRouting(value) {
1434
1436
  if (typeof value.proxy_key_file === "string" && (value.proxy_key_file.startsWith("/") || value.proxy_key_file.startsWith("~/")) && value.proxy_key_file.length <= 1024) {
1435
1437
  client.proxy_key_file = value.proxy_key_file;
1436
1438
  }
1439
+ if (typeof value.keep_claude_login === "boolean") {
1440
+ client.keep_claude_login = value.keep_claude_login;
1441
+ }
1437
1442
  return Object.keys(client).length > 0 ? client : undefined;
1438
1443
  }
1439
1444
  function sanitizeProviderModels(value) {
@@ -1524,6 +1529,26 @@ function sanitizeTeamRouting(value) {
1524
1529
  }
1525
1530
  return result;
1526
1531
  }
1532
+ function readClientRouting(configPath = resolveConfigPath()) {
1533
+ let data;
1534
+ try {
1535
+ data = JSON.parse(readFileSync(configPath, "utf8"));
1536
+ } catch {
1537
+ throw new Error("Agent Smith client config could not be read");
1538
+ }
1539
+ if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
1540
+ throw new Error("Agent Smith client config is invalid");
1541
+ }
1542
+ return clientRouting(sanitizeClientRouting(data.client));
1543
+ }
1544
+ function clientRouting(client) {
1545
+ return {
1546
+ enabled: client?.enabled === true,
1547
+ ...client?.base_url && { baseUrl: client.base_url },
1548
+ ...client?.proxy_key_file && { proxyKeyFile: client.proxy_key_file },
1549
+ ...client?.keep_claude_login === true && { keepClaudeLogin: true }
1550
+ };
1551
+ }
1527
1552
  var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
1528
1553
  var init_src4 = __esm(() => {
1529
1554
  init_src2();
@@ -1726,14 +1751,10 @@ var init_src4 = __esm(() => {
1726
1751
  };
1727
1752
  }
1728
1753
  getClientRouting() {
1729
- const client = this.data.client;
1730
- return {
1731
- enabled: client?.enabled === true,
1732
- ...client?.base_url && { baseUrl: client.base_url },
1733
- ...client?.proxy_key_file && {
1734
- proxyKeyFile: client.proxy_key_file
1735
- }
1736
- };
1754
+ return clientRouting(this.data.client);
1755
+ }
1756
+ setClientRoutingEnabled(enabled) {
1757
+ this.persistStrictly("client", { ...this.data.client, enabled });
1737
1758
  }
1738
1759
  getBlockWhenAllFull() {
1739
1760
  return this.data.block_when_all_full !== false;
@@ -4505,7 +4526,8 @@ function errorResponse(error) {
4505
4526
  }
4506
4527
  if (error instanceof Error && "statusCode" in error && typeof error.statusCode === "number") {
4507
4528
  const details = "context" in error && error.context !== undefined ? { details: error.context } : {};
4508
- return jsonResponse({ error: error.message, ...details }, error.statusCode);
4529
+ const retryAfter = error.statusCode === 503 && "retryAfterSeconds" in error && typeof error.retryAfterSeconds === "number" && Number.isSafeInteger(error.retryAfterSeconds) && error.retryAfterSeconds > 0 ? { "Retry-After": String(error.retryAfterSeconds) } : undefined;
4530
+ return jsonResponse({ error: error.message, ...details }, error.statusCode, retryAfter);
4509
4531
  }
4510
4532
  const message = error instanceof Error ? error.message : "Internal server error";
4511
4533
  const status = 500;
@@ -5111,7 +5133,7 @@ function utilization(value) {
5111
5133
  const raw = number(value.used_percentage ?? value.usedPercentage ?? value.percent ?? value.utilization);
5112
5134
  if (raw === null)
5113
5135
  return null;
5114
- return raw > 1 ? raw / 100 : raw;
5136
+ return raw / 100;
5115
5137
  }
5116
5138
  function resetAt(value) {
5117
5139
  const raw = value.resets_at ?? value.reset_at ?? value.resetAt;
@@ -8111,6 +8133,18 @@ class APIRouter {
8111
8133
  this.registerHandlers();
8112
8134
  }
8113
8135
  registerHandlers() {
8136
+ if (this.context.deploymentDrain) {
8137
+ const control = this.context.deploymentDrain;
8138
+ for (const [method, action] of [
8139
+ ["GET", "status"],
8140
+ ["POST", "start"],
8141
+ ["DELETE", "resume"]
8142
+ ]) {
8143
+ this.staticHandlers.set(`${method}:/api/drain`, () => Response.json(control(action), {
8144
+ headers: { "cache-control": "no-store" }
8145
+ }));
8146
+ }
8147
+ }
8114
8148
  if (this.enrollment) {
8115
8149
  this.staticHandlers.set("POST:/api/enrollment-invitations", this.enrollment.issue);
8116
8150
  this.staticHandlers.set("POST:/api/enrollment-emails", this.enrollment.emails);
@@ -8145,6 +8179,9 @@ class APIRouter {
8145
8179
  this.staticHandlers.set("GET:/api/stats", () => statsHandler());
8146
8180
  this.staticHandlers.set("GET:/api/status", () => fleetStatusHandler());
8147
8181
  this.staticHandlers.set("GET:/api/pool-status", (_req, url) => {
8182
+ if (this.context.deploymentDrain?.("status").draining) {
8183
+ return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
8184
+ }
8148
8185
  const provider = url.searchParams.get("provider") ?? "";
8149
8186
  const model = url.searchParams.get("model") ?? undefined;
8150
8187
  if (!isAccountProvider(provider) || !getProviders().includes(provider) || model !== undefined && (model.trim().length === 0 || model.length > 200)) {
@@ -9834,6 +9871,15 @@ var init_proxy_operations = __esm(() => {
9834
9871
  });
9835
9872
 
9836
9873
  // ../../packages/proxy/src/handlers/proxy-attempts.ts
9874
+ function admissionRetrySeconds(req) {
9875
+ if (req.signal.aborted)
9876
+ return;
9877
+ const count = req.headers.get("x-stainless-retry-count") ?? "0";
9878
+ if (!/^\d+$/.test(count))
9879
+ return 1;
9880
+ const ordinal = Number(count);
9881
+ return ordinal === 0 ? 1 : ordinal === 1 ? 10 : 30;
9882
+ }
9837
9883
  function createBodyStream(body) {
9838
9884
  if (!body)
9839
9885
  return;
@@ -9893,7 +9939,7 @@ async function attemptAccount(request2, account2, failoverAttempts) {
9893
9939
  permit = request2.ctx.runtime.teamRouting.enabled ? await admission?.acquire(account2.id, request2.ctx.runtime.teamRouting, request2.req.signal) : undefined;
9894
9940
  } catch (error) {
9895
9941
  if (error instanceof TeamAdmissionError) {
9896
- throw new ServiceUnavailableError(error.message, request2.ctx.providerName);
9942
+ throw new ServiceUnavailableError(error.message, request2.ctx.providerName, admissionRetrySeconds(request2.req));
9897
9943
  }
9898
9944
  throw error;
9899
9945
  }
@@ -11864,7 +11910,7 @@ function exposureFailure(req, url, server, config) {
11864
11910
  if (!isSameOriginManagementRequest(req, url)) {
11865
11911
  return jsonError(403, "Cross-origin management requests are not allowed");
11866
11912
  }
11867
- if (MUTATING_METHODS.has(req.method)) {
11913
+ if (url.pathname === "/api/drain" || MUTATING_METHODS.has(req.method)) {
11868
11914
  if (role !== "admin") {
11869
11915
  return jsonError(401, "An admin key is required for management writes");
11870
11916
  }
@@ -11921,7 +11967,7 @@ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig
11921
11967
  }
11922
11968
  });
11923
11969
  }
11924
- function bootstrapRuntime(port, serverLog) {
11970
+ function bootstrapRuntime(port, serverLog, deploymentDrain) {
11925
11971
  container.registerInstance(SERVICE_KEYS.Config, new Config);
11926
11972
  container.registerInstance(SERVICE_KEYS.Logger, serverLog);
11927
11973
  const config = container.resolve(SERVICE_KEYS.Config);
@@ -11940,6 +11986,7 @@ function bootstrapRuntime(port, serverLog) {
11940
11986
  container.registerInstance(SERVICE_KEYS.PricingLogger, pricingLogger);
11941
11987
  setPricingLogger(pricingLogger);
11942
11988
  const apiRouter = new APIRouter({
11989
+ deploymentDrain,
11943
11990
  enrollmentOrigin: process.env.AGENT_SMITH_ENROLLMENT_ORIGIN,
11944
11991
  config,
11945
11992
  dbOps,
@@ -12100,6 +12147,48 @@ var init_dashboard_assets = __esm(() => {
12100
12147
  init_src2();
12101
12148
  });
12102
12149
 
12150
+ // ../../packages/runtime-server/src/deployment-drain.ts
12151
+ class DeploymentDrain {
12152
+ activity;
12153
+ now;
12154
+ expiresAt = null;
12155
+ stopping = false;
12156
+ log = new Logger("DeploymentDrain");
12157
+ constructor(activity, now = () => Date.now()) {
12158
+ this.activity = activity;
12159
+ this.now = now;
12160
+ }
12161
+ isDraining = () => {
12162
+ if (this.expiresAt !== null && this.now() >= this.expiresAt) {
12163
+ this.expiresAt = null;
12164
+ this.log.info("Deployment pause expired; accepting new inference");
12165
+ }
12166
+ return this.stopping || this.expiresAt !== null;
12167
+ };
12168
+ control = (action) => {
12169
+ if (action === "start" && !this.stopping) {
12170
+ if (!this.isDraining())
12171
+ this.log.info("Deployment pause started");
12172
+ this.expiresAt = this.now() + 120000;
12173
+ } else if (action === "resume" && !this.stopping) {
12174
+ this.expiresAt = null;
12175
+ this.log.info("Deployment pause cancelled; accepting new inference");
12176
+ }
12177
+ return {
12178
+ draining: this.isDraining(),
12179
+ expiresAt: this.expiresAt,
12180
+ ...this.activity()
12181
+ };
12182
+ };
12183
+ shutdown() {
12184
+ this.stopping = true;
12185
+ this.expiresAt = null;
12186
+ }
12187
+ }
12188
+ var init_deployment_drain = __esm(() => {
12189
+ init_src3();
12190
+ });
12191
+
12103
12192
  // ../../packages/runtime-server/src/oauth-token.ts
12104
12193
  async function forwardOAuthTokenRequest(req, body) {
12105
12194
  const headers3 = new Headers(req.headers);
@@ -12148,7 +12237,8 @@ function createServerFetchHandler({
12148
12237
  handleProxyRequest = handleProxy,
12149
12238
  handleWebSocketUpgrade = handleWebSocketUpgradeRequest,
12150
12239
  handleOAuthTokenRequest = forwardOAuthTokenRequest,
12151
- serveDashboardAsset = serveDashboardRoute
12240
+ serveDashboardAsset = serveDashboardRoute,
12241
+ isDeploymentDraining = () => false
12152
12242
  }) {
12153
12243
  return async (req, server) => {
12154
12244
  const url = new URL(req.url);
@@ -12176,6 +12266,9 @@ function createServerFetchHandler({
12176
12266
  }
12177
12267
  const isProviderRoute = url.pathname === "/v1" || url.pathname.startsWith("/v1/") || url.pathname.startsWith("/tc-acct/");
12178
12268
  if (isProviderRoute) {
12269
+ if (isDeploymentDraining()) {
12270
+ return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
12271
+ }
12179
12272
  if (server) {
12180
12273
  const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server);
12181
12274
  if (websocketResponse) {
@@ -12290,17 +12383,38 @@ async function stopServerRuntime() {
12290
12383
  const errors2 = [];
12291
12384
  const activeServer = serverInstance;
12292
12385
  const activeUnixServer = unixServerInstance;
12293
- serverInstance = null;
12294
- unixServerInstance = null;
12386
+ deploymentDrain?.shutdown();
12387
+ const listeners = [activeUnixServer, activeServer].filter((listener) => listener !== null);
12388
+ const shutdownDeadline = Date.now() + 25000;
12295
12389
  try {
12296
- await activeUnixServer?.stop(true);
12297
- } catch (error) {
12298
- errors2.push(toError("Failed to stop Unix server", error));
12299
- }
12300
- try {
12301
- await activeServer?.stop(true);
12302
- } catch (error) {
12303
- errors2.push(toError("Failed to stop Bun server", error));
12390
+ await new Promise((resolve3) => {
12391
+ let timer;
12392
+ const finish = () => {
12393
+ clearInterval(timer);
12394
+ resolve3();
12395
+ };
12396
+ const check = () => {
12397
+ const pending = listeners.some((listener) => listener.pendingRequests > 0 || listener.pendingWebSockets > 0);
12398
+ if (!pending)
12399
+ finish();
12400
+ else if (Date.now() >= shutdownDeadline) {
12401
+ lifecycleLog.warn("Shutdown grace expired; closing remaining connections");
12402
+ finish();
12403
+ }
12404
+ };
12405
+ checkShutdownDrain = check;
12406
+ timer = setInterval(check, 50);
12407
+ check();
12408
+ });
12409
+ const stopped = await Promise.allSettled(listeners.map((listener) => listener.stop(true)));
12410
+ for (const result of stopped) {
12411
+ if (result.status === "rejected")
12412
+ errors2.push(toError("Failed to stop listener", result.reason));
12413
+ }
12414
+ } finally {
12415
+ checkShutdownDrain = undefined;
12416
+ serverInstance = null;
12417
+ unixServerInstance = null;
12304
12418
  }
12305
12419
  stopRetentionMaintenance();
12306
12420
  try {
@@ -12348,6 +12462,11 @@ function startServer(options) {
12348
12462
  if (withDashboard) {
12349
12463
  loadDashboardAssets();
12350
12464
  }
12465
+ const drain = new DeploymentDrain(() => ({
12466
+ activeRequests: Math.max(0, (serverInstance?.pendingRequests ?? 0) + (unixServerInstance?.pendingRequests ?? 0) - 1),
12467
+ activeWebSockets: (serverInstance?.pendingWebSockets ?? 0) + (unixServerInstance?.pendingWebSockets ?? 0)
12468
+ }));
12469
+ deploymentDrain = drain;
12351
12470
  const {
12352
12471
  config,
12353
12472
  dbOps,
@@ -12357,13 +12476,14 @@ function startServer(options) {
12357
12476
  proxyContext,
12358
12477
  providerRegistry,
12359
12478
  runtimeConfig: runtimeConfig2
12360
- } = bootstrapRuntime(port, serverLog);
12479
+ } = bootstrapRuntime(port, serverLog, drain.control);
12361
12480
  stopRetentionJob = runStartupMaintenance(config, dbOps);
12362
12481
  const fetchHandler = createServerFetchHandler({
12363
12482
  apiRouter,
12364
12483
  exposureConfig,
12365
12484
  proxyContext,
12366
- withDashboard
12485
+ withDashboard,
12486
+ isDeploymentDraining: drain.isDraining
12367
12487
  });
12368
12488
  try {
12369
12489
  if (options?.additionalUnixSocket) {
@@ -12402,6 +12522,7 @@ function startServer(options) {
12402
12522
  advanceRoutingClock: () => {
12403
12523
  proxyContext.teamAdmission?.advance();
12404
12524
  proxyContext.quotaHold?.advance();
12525
+ checkShutdownDrain?.();
12405
12526
  }
12406
12527
  };
12407
12528
  }
@@ -12416,7 +12537,7 @@ async function handleGracefulShutdown(signal) {
12416
12537
  process.exit(1);
12417
12538
  }
12418
12539
  }
12419
- var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null;
12540
+ var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null, deploymentDrain, checkShutdownDrain;
12420
12541
  var init_src11 = __esm(() => {
12421
12542
  init_src9();
12422
12543
  init_src2();
@@ -12425,6 +12546,7 @@ var init_src11 = __esm(() => {
12425
12546
  init_src10();
12426
12547
  init_bootstrap_runtime();
12427
12548
  init_dashboard_assets();
12549
+ init_deployment_drain();
12428
12550
  init_fetch_handler();
12429
12551
  init_startup_banner();
12430
12552
  init_startup_maintenance();
@@ -14058,6 +14180,7 @@ import {
14058
14180
  } from "fs";
14059
14181
  import { homedir as homedir2 } from "os";
14060
14182
  import { dirname as dirname4, join as join8 } from "path";
14183
+ import { fileURLToPath } from "url";
14061
14184
  function shellQuote(value) {
14062
14185
  return `'${value.replaceAll("'", `'"'"'`)}'`;
14063
14186
  }
@@ -14098,14 +14221,22 @@ function proxyKeySetup(proxyKeyFile) {
14098
14221
  fi
14099
14222
  export AGENT_SMITH_PROXY_KEY=$(cat ${shellQuote(proxyKeyFile)})`;
14100
14223
  }
14101
- function claudeWrapper(claudePath, baseUrl, proxyKeyFile) {
14224
+ function claudeProxyCredential(keepClaudeLogin) {
14225
+ if (!keepClaudeLogin) {
14226
+ return `export ANTHROPIC_API_KEY="$AGENT_SMITH_PROXY_KEY"`;
14227
+ }
14228
+ return `unset ANTHROPIC_API_KEY
14229
+ export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_HEADERS
14230
+ }x-api-key: $AGENT_SMITH_PROXY_KEY"`;
14231
+ }
14232
+ function claudeWrapper(claudePath, baseUrl, proxyKeyFile, keepClaudeLogin) {
14102
14233
  return `#!/bin/sh
14103
14234
  # Generated by agent-smith. This file delegates to the real Claude Code binary.
14104
14235
  unset AGENT_SMITH_ADMIN_KEY
14105
14236
  unset AGENT_SMITH_PROXY_KEY
14106
14237
  unset ANTHROPIC_AUTH_TOKEN
14107
14238
  ${proxyKeySetup(proxyKeyFile)}
14108
- export ANTHROPIC_API_KEY="$AGENT_SMITH_PROXY_KEY"
14239
+ ${claudeProxyCredential(keepClaudeLogin)}
14109
14240
  unset AGENT_SMITH_PROXY_KEY
14110
14241
  export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
14111
14242
  exec ${shellQuote(claudePath)} "$@"
@@ -14133,6 +14264,26 @@ ${overrides} \\
14133
14264
  `;
14134
14265
  }
14135
14266
  async function installClientWrappers(options) {
14267
+ if (options.clientConfigPath) {
14268
+ const launcher = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./client-launcher.ts" : "./client-launcher.js", import.meta.url));
14269
+ mkdirSync4(options.binDir, { recursive: true, mode: 448 });
14270
+ for (const [tool, target] of [
14271
+ ["claude", options.claudePath],
14272
+ ["codex", options.codexPath]
14273
+ ]) {
14274
+ if (!target)
14275
+ continue;
14276
+ if (target === join8(options.binDir, tool))
14277
+ throw new Error("A client launcher cannot call itself");
14278
+ const wrapper = join8(options.binDir, tool);
14279
+ writeFileSync2(wrapper, `#!/bin/sh
14280
+ ${CONFIG_CLIENT_MARKER}
14281
+ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(shellQuote).join(" ")} "$@"
14282
+ `, { encoding: "utf8", mode: 448 });
14283
+ chmodSync2(wrapper, 448);
14284
+ }
14285
+ return;
14286
+ }
14136
14287
  if (options.baseUrl && !options.proxyKeyFile) {
14137
14288
  throw new Error("A configured Agent Smith server requires a forwarding key file");
14138
14289
  }
@@ -14140,7 +14291,7 @@ async function installClientWrappers(options) {
14140
14291
  const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
14141
14292
  if (options.claudePath) {
14142
14293
  const claude = join8(options.binDir, "claude");
14143
- writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile), {
14294
+ writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true), {
14144
14295
  encoding: "utf8",
14145
14296
  mode: 448
14146
14297
  });
@@ -14201,7 +14352,7 @@ function readSavedClientPaths(statePath) {
14201
14352
  } catch {}
14202
14353
  return null;
14203
14354
  }
14204
- function getLocalRoutingStatus(paths2 = {}) {
14355
+ function installedRoutingStatus(paths2 = {}) {
14205
14356
  const defaults = getLocalRoutingPaths();
14206
14357
  const binDir = paths2.binDir ?? defaults.binDir;
14207
14358
  const shellProfile = paths2.shellProfile ?? defaults.shellProfile;
@@ -14215,6 +14366,58 @@ function getLocalRoutingStatus(paths2 = {}) {
14215
14366
  shellProfile
14216
14367
  };
14217
14368
  }
14369
+ function getLocalRoutingStatus(paths2 = {}) {
14370
+ const status = installedRoutingStatus(paths2);
14371
+ if (!configClientWrappersInstalled(paths2))
14372
+ return status;
14373
+ try {
14374
+ return { ...status, enabled: readClientRouting().enabled };
14375
+ } catch {
14376
+ return { ...status, enabled: false };
14377
+ }
14378
+ }
14379
+ function configClientWrappersInstalled(paths2 = {}) {
14380
+ const binDir = paths2.binDir ?? getLocalRoutingPaths().binDir;
14381
+ const files = ["claude", "codex"].map((name) => join8(binDir, name)).filter(existsSync3);
14382
+ return installedRoutingStatus(paths2).enabled && files.length > 0 && files.every((path) => readFileSync4(path, "utf8").includes(CONFIG_CLIENT_MARKER));
14383
+ }
14384
+ async function launchConfiguredClient(configPath, tool, target, args) {
14385
+ if (tool !== "claude" && tool !== "codex")
14386
+ throw new Error("Unknown Agent Smith client");
14387
+ const client2 = readClientRouting(configPath);
14388
+ const env = { ...process.env };
14389
+ delete env.AGENT_SMITH_ADMIN_KEY;
14390
+ delete env.AGENT_SMITH_PROXY_KEY;
14391
+ let command = [target, ...args];
14392
+ if (client2.enabled) {
14393
+ if (!client2.baseUrl || !client2.proxyKeyFile)
14394
+ throw new Error("client.base_url and client.proxy_key_file are required");
14395
+ const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
14396
+ const wires = Object.keys(new Config(configPath).getProviderPools());
14397
+ const base = proxyBaseUrl(8080, client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
14398
+ const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true) : codexWrapper(target, base, keyFile);
14399
+ command = ["/bin/sh", "-c", script, "--", ...args];
14400
+ }
14401
+ const child = Bun.spawn(command, {
14402
+ env,
14403
+ stdin: "inherit",
14404
+ stdout: "inherit",
14405
+ stderr: "inherit"
14406
+ });
14407
+ const forward = {
14408
+ SIGINT: () => child.kill("SIGINT"),
14409
+ SIGTERM: () => child.kill("SIGTERM"),
14410
+ SIGHUP: () => child.kill("SIGHUP")
14411
+ };
14412
+ for (const [signal, listener] of Object.entries(forward))
14413
+ process.on(signal, listener);
14414
+ try {
14415
+ return await child.exited;
14416
+ } finally {
14417
+ for (const [signal, listener] of Object.entries(forward))
14418
+ process.off(signal, listener);
14419
+ }
14420
+ }
14218
14421
  async function enableLocalClientRouting(options) {
14219
14422
  const defaults = getLocalRoutingPaths();
14220
14423
  const binDir = options.binDir ?? defaults.binDir;
@@ -14241,7 +14444,9 @@ async function enableLocalClientRouting(options) {
14241
14444
  port: options.port,
14242
14445
  baseUrl: options.baseUrl,
14243
14446
  proxyKeyFile: options.proxyKeyFile,
14244
- providerPoolWires: options.providerPoolWires ?? Object.keys(new Config().getProviderPools())
14447
+ keepClaudeLogin: options.keepClaudeLogin,
14448
+ clientConfigPath: options.clientConfigPath,
14449
+ providerPoolWires: options.providerPoolWires ?? (options.clientConfigPath ? [] : Object.keys(new Config().getProviderPools()))
14245
14450
  });
14246
14451
  const existingProfile = existsSync3(shellProfile) ? readFileSync4(shellProfile, "utf8") : "";
14247
14452
  writeFileSync2(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
@@ -14292,7 +14497,7 @@ export PATH=${shellDoubleQuote(`${binDir}:$PATH`)}
14292
14497
  ${ROUTING_END}
14293
14498
  `;
14294
14499
  }
14295
- var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local";
14500
+ var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
14296
14501
  var init_local_routing = __esm(() => {
14297
14502
  init_src4();
14298
14503
  });
@@ -14500,6 +14705,58 @@ var init_core = __esm(() => {
14500
14705
  init_strategy3();
14501
14706
  });
14502
14707
 
14708
+ // src/core/client-command.ts
14709
+ import { existsSync as existsSync4 } from "fs";
14710
+ import { parseArgs as parseArgs2 } from "util";
14711
+ async function runClientCommand(argv) {
14712
+ const { positionals, values } = parseArgs2({
14713
+ args: argv,
14714
+ options: { raw: { type: "boolean" } },
14715
+ allowPositionals: true,
14716
+ strict: true
14717
+ });
14718
+ const [command] = positionals;
14719
+ if (positionals.length !== 1 || !["on", "off", "status"].includes(command ?? ""))
14720
+ throw new Error("usage: agent-smith client on|off|status [--raw]");
14721
+ const configPath = resolveConfigPath();
14722
+ const client2 = existsSync4(configPath) ? readClientRouting(configPath) : { enabled: false };
14723
+ let installed = configClientWrappersInstalled();
14724
+ if (command !== "status") {
14725
+ const enabled = command === "on";
14726
+ if (enabled) {
14727
+ if (!client2.baseUrl || !client2.proxyKeyFile)
14728
+ throw new Error("Set client.base_url and client.proxy_key_file before enabling the pool");
14729
+ validateProxyKeyFile(client2.proxyKeyFile);
14730
+ }
14731
+ if (!installed && (enabled || getLocalRoutingStatus().enabled)) {
14732
+ await enableLocalClientRouting({
14733
+ port: 8080,
14734
+ clientConfigPath: configPath
14735
+ });
14736
+ installed = true;
14737
+ }
14738
+ new Config(configPath).setClientRoutingEnabled(enabled);
14739
+ client2.enabled = enabled;
14740
+ }
14741
+ const status = {
14742
+ enabled: client2.enabled,
14743
+ installed,
14744
+ ...client2.baseUrl && { baseUrl: client2.baseUrl }
14745
+ };
14746
+ if (values.raw)
14747
+ console.log(JSON.stringify(status));
14748
+ else {
14749
+ console.log(`Shared pool: ${status.enabled ? "on" : "off"}`);
14750
+ console.log(`Launchers: ${installed ? "installed" : "not configured; use client on to set up"}`);
14751
+ if (command !== "status")
14752
+ console.log("Restart existing Claude/Codex sessions to use this setting. After first setup, open a new terminal.");
14753
+ }
14754
+ }
14755
+ var init_client_command = __esm(() => {
14756
+ init_src4();
14757
+ init_local_routing();
14758
+ });
14759
+
14503
14760
  // src/poc-notice.ts
14504
14761
  var POC_BANNER = "PROOF OF CONCEPT \xB7 read the README before enabling sign-ins", POC_NOTICE = `\u26A0 PROOF OF CONCEPT, FOR IDEATION ONLY
14505
14762
  agent-smith is an experiment, not a product: no warranty and no support.
@@ -14519,12 +14776,12 @@ __export(exports_theme, {
14519
14776
  NAV_ITEMS: () => NAV_ITEMS,
14520
14777
  C: () => C
14521
14778
  });
14522
- import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
14779
+ import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
14523
14780
  import { homedir as homedir3 } from "os";
14524
14781
  import { join as join9 } from "path";
14525
14782
  function loadPersistedThemeId() {
14526
14783
  try {
14527
- if (existsSync4(CONFIG_FILE)) {
14784
+ if (existsSync5(CONFIG_FILE)) {
14528
14785
  const data = JSON.parse(readFileSync5(CONFIG_FILE, "utf-8"));
14529
14786
  if (data?.themeId && getThemeById(data.themeId)) {
14530
14787
  return data.themeId;
@@ -14535,7 +14792,7 @@ function loadPersistedThemeId() {
14535
14792
  }
14536
14793
  function persistThemeId(themeId) {
14537
14794
  try {
14538
- if (!existsSync4(CONFIG_DIR)) {
14795
+ if (!existsSync5(CONFIG_DIR)) {
14539
14796
  mkdirSync5(CONFIG_DIR, { recursive: true });
14540
14797
  }
14541
14798
  writeFileSync3(CONFIG_FILE, JSON.stringify({ themeId }), "utf-8");
@@ -17964,6 +18221,10 @@ Accounts:`);
17964
18221
  }
17965
18222
  }
17966
18223
  async function main() {
18224
+ if (process.argv[2] === "client") {
18225
+ await runClientCommand(process.argv.slice(3));
18226
+ return;
18227
+ }
17967
18228
  container.registerInstance(SERVICE_KEYS.Config, new Config);
17968
18229
  container.registerInstance(SERVICE_KEYS.Logger, new Logger("TUI"));
17969
18230
  DatabaseFactory.initialize();
@@ -17980,6 +18241,7 @@ ${POC_NOTICE}
17980
18241
  Usage: agent-smith [options]
17981
18242
  agent-smith run [--port <number>] -- [claude arguments]
17982
18243
  agent-smith install-client
18244
+ agent-smith client on|off|status [--raw]
17983
18245
 
17984
18246
  Options:
17985
18247
  --serve Start API server with dashboard
@@ -18036,7 +18298,9 @@ Examples:
18036
18298
  await enableLocalClientRouting({
18037
18299
  port: port2,
18038
18300
  baseUrl: client2.baseUrl,
18039
- proxyKeyFile: client2.proxyKeyFile
18301
+ proxyKeyFile: client2.proxyKeyFile,
18302
+ keepClaudeLogin: client2.keepClaudeLogin,
18303
+ clientConfigPath: resolveConfigPath()
18040
18304
  });
18041
18305
  console.log(`Client wrappers configured for ${client2.baseUrl}.`);
18042
18306
  console.log("Open a new shell and launch Claude Code or Codex through these wrappers. Already-running sessions are unchanged; restart or resume them through the wrapper.");
@@ -18168,6 +18432,7 @@ var init_main = __esm(() => {
18168
18432
  init_src11();
18169
18433
  init_core();
18170
18434
  init_core();
18435
+ init_client_command();
18171
18436
  main().catch(async (error) => {
18172
18437
  console.error("Error:", error.message);
18173
18438
  try {