@certalis/agent-smith 0.3.2 → 0.3.3

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.
@@ -1984,6 +1984,9 @@ function sanitizeClientRouting(value) {
1984
1984
  if (typeof value.keep_claude_login === "boolean") {
1985
1985
  client.keep_claude_login = value.keep_claude_login;
1986
1986
  }
1987
+ if (typeof value.remote_control === "boolean") {
1988
+ client.remote_control = value.remote_control;
1989
+ }
1987
1990
  if (typeof value.pool_ssh_host === "string" && POOL_SSH_HOST_PATTERN.test(value.pool_ssh_host)) {
1988
1991
  client.pool_ssh_host = value.pool_ssh_host;
1989
1992
  }
@@ -2255,6 +2258,7 @@ function clientRouting(client) {
2255
2258
  ...client?.base_url && { baseUrl: client.base_url },
2256
2259
  ...client?.proxy_key_file && { proxyKeyFile: client.proxy_key_file },
2257
2260
  ...client?.keep_claude_login === true && { keepClaudeLogin: true },
2261
+ ...client?.remote_control === false && { remoteControl: false },
2258
2262
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
2259
2263
  };
2260
2264
  }
@@ -2885,35 +2889,31 @@ async function compressedBody(req, headers2) {
2885
2889
  headers2.set("content-encoding", "gzip");
2886
2890
  return Bun.gzipSync(body);
2887
2891
  }
2892
+ async function fetchUpstream(target, init, unreachable) {
2893
+ try {
2894
+ const upstream = await fetch(target, { ...init, redirect: "manual" });
2895
+ return withSanitizedProxyHeaders(upstream);
2896
+ } catch (error) {
2897
+ const reason = error instanceof Error ? error.message : String(error);
2898
+ return Response.json({
2899
+ type: "error",
2900
+ error: { type: "api_error", message: `${unreachable}: ${reason}` }
2901
+ }, { status: 502 });
2902
+ }
2903
+ }
2904
+ async function relayToPool(req, target, headers2) {
2905
+ const body = await compressedBody(req, headers2);
2906
+ return fetchUpstream(target, { method: req.method, headers: headers2, body, signal: req.signal }, "Agent Smith relay could not reach the pool");
2907
+ }
2888
2908
  function startClientRelay(remoteBaseUrl) {
2889
2909
  const remote = remoteBaseUrl.replace(/\/+$/, "");
2890
2910
  const server = Bun.serve({
2891
2911
  hostname: "127.0.0.1",
2892
2912
  port: 0,
2893
2913
  idleTimeout: 0,
2894
- async fetch(req) {
2914
+ fetch(req) {
2895
2915
  const url = new URL(req.url);
2896
- const headers2 = forwardedHeaders(req.headers);
2897
- const body = await compressedBody(req, headers2);
2898
- try {
2899
- const upstream = await fetch(`${remote}${url.pathname}${url.search}`, {
2900
- method: req.method,
2901
- headers: headers2,
2902
- body,
2903
- signal: req.signal,
2904
- redirect: "manual"
2905
- });
2906
- return withSanitizedProxyHeaders(upstream);
2907
- } catch (error) {
2908
- const reason = error instanceof Error ? error.message : String(error);
2909
- return Response.json({
2910
- type: "error",
2911
- error: {
2912
- type: "api_error",
2913
- message: `Agent Smith relay could not reach the pool: ${reason}`
2914
- }
2915
- }, { status: 502 });
2916
- }
2916
+ return relayToPool(req, `${remote}${url.pathname}${url.search}`, forwardedHeaders(req.headers));
2917
2917
  }
2918
2918
  });
2919
2919
  return {
@@ -2934,22 +2934,373 @@ var init_client_relay = __esm(() => {
2934
2934
  ];
2935
2935
  });
2936
2936
 
2937
- // src/core/local-routing.ts
2937
+ // src/core/client-forward-proxy.ts
2938
+ import { randomBytes, timingSafeEqual, X509Certificate } from "crypto";
2938
2939
  import {
2939
- accessSync as accessSync2,
2940
2940
  chmodSync as chmodSync2,
2941
- constants as constants2,
2942
- copyFileSync,
2943
2941
  existsSync as existsSync3,
2944
2942
  mkdirSync as mkdirSync3,
2943
+ mkdtempSync,
2945
2944
  readFileSync as readFileSync3,
2945
+ renameSync as renameSync3,
2946
2946
  rmSync as rmSync2,
2947
+ writeFileSync as writeFileSync3
2948
+ } from "fs";
2949
+ import {
2950
+ createConnection,
2951
+ createServer
2952
+ } from "net";
2953
+ import { tmpdir as tmpdir3 } from "os";
2954
+ import { join as join6 } from "path";
2955
+ function readCertificate(dir, renewAfter = Number.NEGATIVE_INFINITY) {
2956
+ try {
2957
+ const caFile = join6(dir, "ca.pem");
2958
+ const cert = readFileSync3(join6(dir, "leaf.pem"), "utf8");
2959
+ const key = readFileSync3(join6(dir, "leaf.key"), "utf8");
2960
+ if (!existsSync3(caFile))
2961
+ return;
2962
+ const expiresAt = Date.parse(new X509Certificate(cert).validTo);
2963
+ if (expiresAt - RENEW_BEFORE_MS <= renewAfter)
2964
+ return;
2965
+ return { caFile, cert, key };
2966
+ } catch {
2967
+ return;
2968
+ }
2969
+ }
2970
+ function runOpenssl(dir, args) {
2971
+ let result;
2972
+ try {
2973
+ result = Bun.spawnSync(["openssl", ...args], {
2974
+ cwd: dir,
2975
+ stdout: "ignore",
2976
+ stderr: "pipe"
2977
+ });
2978
+ } catch {
2979
+ throw new Error("Remote Control mode needs openssl on PATH");
2980
+ }
2981
+ if (!result.success)
2982
+ throw new Error(`openssl ${args[0]} failed: ${result.stderr?.toString().trim()}`);
2983
+ }
2984
+ function generateCertificate(dir) {
2985
+ mkdirSync3(dir, { recursive: true, mode: 448 });
2986
+ writeFileSync3(join6(dir, "openssl.cnf"), OPENSSL_CONFIG, { mode: 384 });
2987
+ const newKey = (file) => runOpenssl(dir, [
2988
+ "ecparam",
2989
+ "-name",
2990
+ "prime256v1",
2991
+ "-genkey",
2992
+ "-noout",
2993
+ "-out",
2994
+ file
2995
+ ]);
2996
+ newKey("ca.key");
2997
+ runOpenssl(dir, [
2998
+ "req",
2999
+ "-x509",
3000
+ "-new",
3001
+ "-key",
3002
+ "ca.key",
3003
+ "-sha256",
3004
+ "-days",
3005
+ String(LEAF_DAYS + 1),
3006
+ "-subj",
3007
+ "/CN=Agent Smith Remote Control CA",
3008
+ "-config",
3009
+ "openssl.cnf",
3010
+ "-extensions",
3011
+ "v3_ca",
3012
+ "-out",
3013
+ "ca.pem"
3014
+ ]);
3015
+ newKey("leaf.key");
3016
+ runOpenssl(dir, [
3017
+ "req",
3018
+ "-new",
3019
+ "-key",
3020
+ "leaf.key",
3021
+ "-subj",
3022
+ `/CN=${INTERCEPTED_HOST}`,
3023
+ "-config",
3024
+ "openssl.cnf",
3025
+ "-out",
3026
+ "leaf.csr"
3027
+ ]);
3028
+ runOpenssl(dir, [
3029
+ "x509",
3030
+ "-req",
3031
+ "-in",
3032
+ "leaf.csr",
3033
+ "-CA",
3034
+ "ca.pem",
3035
+ "-CAkey",
3036
+ "ca.key",
3037
+ "-set_serial",
3038
+ `0x${randomBytes(16).toString("hex")}`,
3039
+ "-days",
3040
+ String(LEAF_DAYS),
3041
+ "-sha256",
3042
+ "-extfile",
3043
+ "openssl.cnf",
3044
+ "-extensions",
3045
+ "v3_leaf",
3046
+ "-out",
3047
+ "leaf.pem"
3048
+ ]);
3049
+ for (const file of ["ca.key", "leaf.csr", "openssl.cnf"])
3050
+ rmSync2(join6(dir, file), { force: true });
3051
+ for (const file of ["ca.pem", "leaf.pem", "leaf.key"])
3052
+ chmodSync2(join6(dir, file), 384);
3053
+ }
3054
+ function ensureInterceptionCertificate(dir, now = Date.now()) {
3055
+ const current = readCertificate(dir, now);
3056
+ if (current)
3057
+ return current;
3058
+ const suffix = `${process.pid}-${randomBytes(4).toString("hex")}`;
3059
+ const staging = `${dir}.staging-${suffix}`;
3060
+ const retired = `${dir}.retired-${suffix}`;
3061
+ try {
3062
+ generateCertificate(staging);
3063
+ if (existsSync3(dir))
3064
+ renameSync3(dir, retired);
3065
+ renameSync3(staging, dir);
3066
+ } catch (error) {
3067
+ const raced = readCertificate(dir);
3068
+ if (raced)
3069
+ return raced;
3070
+ throw error;
3071
+ } finally {
3072
+ rmSync2(staging, { force: true, recursive: true });
3073
+ rmSync2(retired, { force: true, recursive: true });
3074
+ }
3075
+ const created = readCertificate(dir);
3076
+ if (!created)
3077
+ throw new Error("Agent Smith could not create its interception certificate");
3078
+ return created;
3079
+ }
3080
+ function parseConnectRequest(head) {
3081
+ const [requestLine = "", ...headerLines] = head.split(`\r
3082
+ `);
3083
+ const match = CONNECT_LINE.exec(requestLine);
3084
+ if (!match)
3085
+ return;
3086
+ const port = Number(match[2]);
3087
+ if (port < 1 || port > 65535)
3088
+ return;
3089
+ const authorization = headerLines.map((line) => line.split(/:(.*)/s, 2)).find(([name]) => name?.trim().toLowerCase() === "proxy-authorization");
3090
+ return {
3091
+ host: match[1].replace(/^\[|\]$/g, ""),
3092
+ port,
3093
+ ...authorization?.[1] && {
3094
+ proxyAuthorization: authorization[1].trim()
3095
+ }
3096
+ };
3097
+ }
3098
+ function sameSecret(actual, expected) {
3099
+ if (actual === undefined)
3100
+ return false;
3101
+ const a = Buffer.from(actual);
3102
+ const b = Buffer.from(expected);
3103
+ return a.length === b.length && timingSafeEqual(a, b);
3104
+ }
3105
+ function poolHeaders(original, deviceKey) {
3106
+ const headers2 = forwardedHeaders(original);
3107
+ headers2.delete("authorization");
3108
+ headers2.set("x-api-key", deviceKey);
3109
+ return headers2;
3110
+ }
3111
+ async function passThrough(req, target) {
3112
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
3113
+ return fetchUpstream(target, {
3114
+ method: req.method,
3115
+ headers: forwardedHeaders(req.headers),
3116
+ body: hasBody ? await req.arrayBuffer() : undefined,
3117
+ signal: req.signal
3118
+ }, "Agent Smith proxy could not reach Anthropic");
3119
+ }
3120
+ function webSocketRelay(req, upstreamUrl) {
3121
+ const headers2 = forwardedHeaders(req.headers);
3122
+ for (const name of [...headers2.keys()])
3123
+ if (name.startsWith("sec-websocket-") || name === "upgrade")
3124
+ headers2.delete(name);
3125
+ const protocols = (req.headers.get("sec-websocket-protocol") ?? "").split(",").map((protocol) => protocol.trim()).filter(Boolean);
3126
+ return {
3127
+ upstreamUrl,
3128
+ headers: Object.fromEntries(headers2),
3129
+ protocols,
3130
+ queued: []
3131
+ };
3132
+ }
3133
+ function refuse(client2, status, extra = "") {
3134
+ client2.end(`HTTP/1.1 ${status}\r
3135
+ ${extra}Connection: close\r
3136
+ \r
3137
+ `);
3138
+ }
3139
+ async function startForwardProxy(options) {
3140
+ const token = randomBytes(24).toString("hex");
3141
+ const expectedAuthorization = `Basic ${Buffer.from(`${FORWARD_PROXY_USER}:${token}`).toString("base64")}`;
3142
+ const anthropic = (options.anthropicOrigin ?? ANTHROPIC_ORIGIN).replace(/\/+$/, "");
3143
+ const pool = options.poolUrl.replace(/\/+$/, "");
3144
+ const socketDir = mkdtempSync(join6(tmpdir3(), "agent-smith-proxy-"));
3145
+ const interceptSocket = join6(socketDir, "tls.sock");
3146
+ const intercept = Bun.serve({
3147
+ unix: interceptSocket,
3148
+ idleTimeout: 0,
3149
+ tls: { cert: options.certificate.cert, key: options.certificate.key },
3150
+ fetch(req, server) {
3151
+ const url = new URL(req.url);
3152
+ const path = `${url.pathname}${url.search}`;
3153
+ if (POOL_PATHS.has(url.pathname))
3154
+ return relayToPool(req, `${pool}${path}`, poolHeaders(req.headers, options.deviceKey));
3155
+ if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
3156
+ const relay = webSocketRelay(req, `${anthropic.replace(/^http/, "ws")}${path}`);
3157
+ if (server.upgrade(req, { data: relay }))
3158
+ return;
3159
+ return new Response("WebSocket upgrade failed", { status: 400 });
3160
+ }
3161
+ return passThrough(req, `${anthropic}${path}`);
3162
+ },
3163
+ websocket: {
3164
+ open(ws) {
3165
+ const upstream = new WebSocket(ws.data.upstreamUrl, {
3166
+ headers: ws.data.headers,
3167
+ protocols: ws.data.protocols
3168
+ });
3169
+ upstream.binaryType = "arraybuffer";
3170
+ ws.data.upstream = upstream;
3171
+ upstream.onopen = () => {
3172
+ for (const message of ws.data.queued.splice(0))
3173
+ upstream.send(message);
3174
+ };
3175
+ upstream.onmessage = (event) => ws.send(typeof event.data === "string" ? event.data : new Uint8Array(event.data));
3176
+ upstream.onclose = (event) => ws.close(closeCode(event.code), event.reason);
3177
+ upstream.onerror = () => ws.close(1011, "upstream error");
3178
+ },
3179
+ message(ws, message) {
3180
+ const payload = typeof message === "string" ? message : new Uint8Array(message);
3181
+ const upstream = ws.data.upstream;
3182
+ if (upstream?.readyState === WebSocket.OPEN)
3183
+ upstream.send(payload);
3184
+ else
3185
+ ws.data.queued.push(payload);
3186
+ },
3187
+ close(ws, code, reason) {
3188
+ ws.data.upstream?.close(closeCode(code), reason);
3189
+ }
3190
+ }
3191
+ });
3192
+ const sockets = new Set;
3193
+ const front = createServer((client2) => {
3194
+ sockets.add(client2);
3195
+ client2.on("close", () => sockets.delete(client2));
3196
+ client2.on("error", () => client2.destroy());
3197
+ let head = Buffer.alloc(0);
3198
+ const onData = (chunk) => {
3199
+ head = Buffer.concat([head, chunk]);
3200
+ const end = head.indexOf(`\r
3201
+ \r
3202
+ `);
3203
+ if (end === -1) {
3204
+ if (head.length > MAX_CONNECT_HEAD_BYTES)
3205
+ refuse(client2, "431 Request Header Fields Too Large");
3206
+ return;
3207
+ }
3208
+ client2.off("data", onData);
3209
+ client2.pause();
3210
+ const request2 = parseConnectRequest(head.subarray(0, end).toString("latin1"));
3211
+ const rest = head.subarray(end + 4);
3212
+ if (!request2)
3213
+ return refuse(client2, "405 Method Not Allowed");
3214
+ if (!sameSecret(request2.proxyAuthorization, expectedAuthorization))
3215
+ return refuse(client2, "407 Proxy Authentication Required", `Proxy-Authenticate: Basic realm="agent-smith"\r
3216
+ `);
3217
+ const intercepted = request2.host.toLowerCase() === INTERCEPTED_HOST && request2.port === 443;
3218
+ const upstream = createConnection(intercepted ? { path: interceptSocket } : { host: request2.host, port: request2.port });
3219
+ sockets.add(upstream);
3220
+ let connected = false;
3221
+ upstream.on("close", () => {
3222
+ sockets.delete(upstream);
3223
+ if (connected)
3224
+ client2.destroy();
3225
+ });
3226
+ upstream.on("error", () => {
3227
+ if (connected)
3228
+ client2.destroy();
3229
+ else
3230
+ refuse(client2, "502 Bad Gateway");
3231
+ });
3232
+ client2.on("close", () => upstream.destroy());
3233
+ upstream.on("connect", () => {
3234
+ connected = true;
3235
+ client2.write(`HTTP/1.1 200 Connection Established\r
3236
+ \r
3237
+ `);
3238
+ if (rest.length > 0)
3239
+ upstream.write(rest);
3240
+ client2.pipe(upstream);
3241
+ upstream.pipe(client2);
3242
+ client2.resume();
3243
+ });
3244
+ };
3245
+ client2.on("data", onData);
3246
+ });
3247
+ await new Promise((resolve2, reject) => {
3248
+ front.once("error", reject);
3249
+ front.listen(0, "127.0.0.1", () => resolve2());
3250
+ });
3251
+ const { port } = front.address();
3252
+ return {
3253
+ url: `http://${FORWARD_PROXY_USER}:${token}@127.0.0.1:${port}`,
3254
+ stop: () => {
3255
+ front.close();
3256
+ for (const socket of sockets)
3257
+ socket.destroy();
3258
+ intercept.stop(true);
3259
+ rmSync2(socketDir, { force: true, recursive: true });
3260
+ }
3261
+ };
3262
+ }
3263
+ var INTERCEPTED_HOST = "api.anthropic.com", FORWARD_PROXY_USER = "agent-smith", ANTHROPIC_ORIGIN, POOL_PATHS, MAX_CONNECT_HEAD_BYTES = 8192, LEAF_DAYS = 397, RENEW_BEFORE_MS, CONNECT_LINE, OPENSSL_CONFIG, closeCode = (code) => code >= 1000 && code <= 4999 && ![1004, 1005, 1006, 1015].includes(code) ? code : 1000;
3264
+ var init_client_forward_proxy = __esm(() => {
3265
+ init_client_relay();
3266
+ ANTHROPIC_ORIGIN = `https://${INTERCEPTED_HOST}`;
3267
+ POOL_PATHS = new Set(["/v1/messages", "/v1/messages/count_tokens"]);
3268
+ RENEW_BEFORE_MS = 30 * 24 * 60 * 60 * 1000;
3269
+ CONNECT_LINE = /^CONNECT ([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\]):(\d{1,5}) HTTP\/1\.[01]$/;
3270
+ OPENSSL_CONFIG = `[req]
3271
+ distinguished_name = dn
3272
+ [dn]
3273
+ [v3_ca]
3274
+ basicConstraints = critical,CA:TRUE,pathlen:0
3275
+ keyUsage = critical,keyCertSign,cRLSign
3276
+ subjectKeyIdentifier = hash
3277
+ nameConstraints = critical,permitted;DNS:${INTERCEPTED_HOST}
3278
+ [v3_leaf]
3279
+ basicConstraints = critical,CA:FALSE
3280
+ keyUsage = critical,digitalSignature
3281
+ extendedKeyUsage = serverAuth
3282
+ subjectAltName = DNS:${INTERCEPTED_HOST}
3283
+ authorityKeyIdentifier = keyid
3284
+ subjectKeyIdentifier = hash
3285
+ `;
3286
+ });
3287
+
3288
+ // src/core/local-routing.ts
3289
+ import {
3290
+ accessSync as accessSync2,
3291
+ chmodSync as chmodSync3,
3292
+ constants as constants2,
3293
+ copyFileSync,
3294
+ existsSync as existsSync4,
3295
+ mkdirSync as mkdirSync4,
3296
+ readFileSync as readFileSync4,
3297
+ rmSync as rmSync3,
2947
3298
  statSync as statSync4,
2948
3299
  unlinkSync as unlinkSync3,
2949
- writeFileSync as writeFileSync3
3300
+ writeFileSync as writeFileSync4
2950
3301
  } from "fs";
2951
3302
  import { homedir as homedir2 } from "os";
2952
- import { dirname as dirname3, join as join6 } from "path";
3303
+ import { dirname as dirname3, join as join7 } from "path";
2953
3304
  import { fileURLToPath } from "url";
2954
3305
  function shellQuote(value) {
2955
3306
  return `'${value.replaceAll("'", `'"'"'`)}'`;
@@ -2962,7 +3313,7 @@ function proxyBaseUrl(port, configuredBaseUrl, directProvider, wire, providerPoo
2962
3313
  return `${configuredBaseUrl ?? `http://127.0.0.1:${port}`}${route}`;
2963
3314
  }
2964
3315
  function validateProxyKeyFile(proxyKeyFile) {
2965
- const resolvedPath = proxyKeyFile.startsWith("~/") ? join6(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
3316
+ const resolvedPath = proxyKeyFile.startsWith("~/") ? join7(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
2966
3317
  let metadata;
2967
3318
  try {
2968
3319
  metadata = statSync4(resolvedPath);
@@ -2975,7 +3326,7 @@ function validateProxyKeyFile(proxyKeyFile) {
2975
3326
  if ((metadata.mode & 63) !== 0) {
2976
3327
  throw new Error("Agent Smith forwarding-key file must be owner-only");
2977
3328
  }
2978
- const key = readFileSync3(resolvedPath, "utf8").trim();
3329
+ const key = readFileSync4(resolvedPath, "utf8").trim();
2979
3330
  if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
2980
3331
  throw new Error("Agent Smith forwarding-key file is invalid");
2981
3332
  }
@@ -3000,32 +3351,32 @@ export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_
3000
3351
  }x-api-key: $AGENT_SMITH_PROXY_KEY"`;
3001
3352
  }
3002
3353
  function claudeCompanionSourceDir() {
3003
- const bundled = join6(import.meta.dir, "claude-companion");
3004
- if (existsSync3(join6(bundled, ".claude-plugin", "plugin.json"))) {
3354
+ const bundled = join7(import.meta.dir, "claude-companion");
3355
+ if (existsSync4(join7(bundled, ".claude-plugin", "plugin.json"))) {
3005
3356
  return bundled;
3006
3357
  }
3007
- const source = join6(import.meta.dir, "..", "claude-companion");
3008
- if (existsSync3(join6(source, ".claude-plugin", "plugin.json"))) {
3358
+ const source = join7(import.meta.dir, "..", "claude-companion");
3359
+ if (existsSync4(join7(source, ".claude-plugin", "plugin.json"))) {
3009
3360
  return source;
3010
3361
  }
3011
3362
  throw new Error("Agent-smith Claude companion files are missing");
3012
3363
  }
3013
3364
  function installClaudeCompanion(binDir) {
3014
3365
  const sourceDir = claudeCompanionSourceDir();
3015
- const targetDir = join6(binDir, CLAUDE_COMPANION_DIRNAME);
3016
- rmSync2(targetDir, { force: true, recursive: true });
3366
+ const targetDir = join7(binDir, CLAUDE_COMPANION_DIRNAME);
3367
+ rmSync3(targetDir, { force: true, recursive: true });
3017
3368
  for (const relativePath of CLAUDE_COMPANION_FILES) {
3018
- const target = join6(targetDir, relativePath);
3019
- mkdirSync3(dirname3(target), { recursive: true, mode: 448 });
3020
- copyFileSync(join6(sourceDir, relativePath), target, constants2.COPYFILE_FICLONE);
3021
- chmodSync2(target, 384);
3369
+ const target = join7(targetDir, relativePath);
3370
+ mkdirSync4(dirname3(target), { recursive: true, mode: 448 });
3371
+ copyFileSync(join7(sourceDir, relativePath), target, constants2.COPYFILE_FICLONE);
3372
+ chmodSync3(target, 384);
3022
3373
  }
3023
3374
  for (const directory of [
3024
3375
  targetDir,
3025
- join6(targetDir, ".claude-plugin"),
3026
- join6(targetDir, "hooks")
3376
+ join7(targetDir, ".claude-plugin"),
3377
+ join7(targetDir, "hooks")
3027
3378
  ]) {
3028
- chmodSync2(directory, 448);
3379
+ chmodSync3(directory, 448);
3029
3380
  }
3030
3381
  return targetDir;
3031
3382
  }
@@ -3042,6 +3393,36 @@ export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
3042
3393
  exec ${shellQuote(claudePath)} --plugin-dir ${shellQuote(companionDir)} "$@"
3043
3394
  `;
3044
3395
  }
3396
+ function dropInheritedForwardProxy(env) {
3397
+ for (const name of PROXY_VARIABLES)
3398
+ if (env[name]?.startsWith(`http://${FORWARD_PROXY_USER}:`))
3399
+ delete env[name];
3400
+ }
3401
+ function remoteControlCertificate(configPath) {
3402
+ try {
3403
+ return ensureInterceptionCertificate(join7(dirname3(configPath), "remote-control"));
3404
+ } catch (error) {
3405
+ const reason = error instanceof Error ? error.message : String(error);
3406
+ console.error(`Agent Smith: Remote Control is off for this session: ${reason}`);
3407
+ return;
3408
+ }
3409
+ }
3410
+ function forwardProxyClientEnv(env, proxyUrl, caFile) {
3411
+ const routed = { ...env };
3412
+ for (const name of [
3413
+ "ANTHROPIC_API_KEY",
3414
+ "ANTHROPIC_AUTH_TOKEN",
3415
+ "ANTHROPIC_BASE_URL",
3416
+ "ANTHROPIC_UNIX_SOCKET"
3417
+ ])
3418
+ delete routed[name];
3419
+ for (const name of PROXY_VARIABLES)
3420
+ routed[name] = proxyUrl;
3421
+ routed.NO_PROXY = NO_PROXY_HOSTS;
3422
+ routed.no_proxy = NO_PROXY_HOSTS;
3423
+ routed.NODE_EXTRA_CA_CERTS = caFile;
3424
+ return routed;
3425
+ }
3045
3426
  function codexWrapper(codexPath, baseUrl, proxyKeyFile) {
3046
3427
  const config = [
3047
3428
  'model_provider="agent_smith"',
@@ -3066,58 +3447,58 @@ ${overrides} \\
3066
3447
  async function installClientWrappers(options) {
3067
3448
  if (options.clientConfigPath) {
3068
3449
  const launcher = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./client-launcher.ts" : "./client-launcher.js", import.meta.url));
3069
- mkdirSync3(options.binDir, { recursive: true, mode: 448 });
3450
+ mkdirSync4(options.binDir, { recursive: true, mode: 448 });
3070
3451
  for (const [tool, target] of [
3071
3452
  ["claude", options.claudePath],
3072
3453
  ["codex", options.codexPath]
3073
3454
  ]) {
3074
3455
  if (!target)
3075
3456
  continue;
3076
- if (target === join6(options.binDir, tool))
3457
+ if (target === join7(options.binDir, tool))
3077
3458
  throw new Error("A client launcher cannot call itself");
3078
- const wrapper = join6(options.binDir, tool);
3459
+ const wrapper = join7(options.binDir, tool);
3079
3460
  const companionDir = tool === "claude" ? installClaudeCompanion(options.binDir) : "";
3080
- writeFileSync3(wrapper, `#!/bin/sh
3461
+ writeFileSync4(wrapper, `#!/bin/sh
3081
3462
  ${CONFIG_CLIENT_MARKER}
3082
3463
  exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, companionDir].map(shellQuote).join(" ")} "$@"
3083
3464
  `, { encoding: "utf8", mode: 448 });
3084
- chmodSync2(wrapper, 448);
3465
+ chmodSync3(wrapper, 448);
3085
3466
  }
3086
3467
  return;
3087
3468
  }
3088
3469
  if (options.baseUrl && !options.proxyKeyFile) {
3089
3470
  throw new Error("A configured Agent Smith server requires a forwarding key file");
3090
3471
  }
3091
- mkdirSync3(options.binDir, { recursive: true, mode: 448 });
3472
+ mkdirSync4(options.binDir, { recursive: true, mode: 448 });
3092
3473
  const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
3093
3474
  if (options.claudePath) {
3094
- const claude = join6(options.binDir, "claude");
3475
+ const claude = join7(options.binDir, "claude");
3095
3476
  const companionDir = installClaudeCompanion(options.binDir);
3096
- writeFileSync3(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
3477
+ writeFileSync4(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
3097
3478
  encoding: "utf8",
3098
3479
  mode: 448
3099
3480
  });
3100
- chmodSync2(claude, 448);
3481
+ chmodSync3(claude, 448);
3101
3482
  }
3102
3483
  if (options.codexPath) {
3103
- const codex = join6(options.binDir, "codex");
3104
- writeFileSync3(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
3484
+ const codex = join7(options.binDir, "codex");
3485
+ writeFileSync4(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
3105
3486
  encoding: "utf8",
3106
3487
  mode: 448
3107
3488
  });
3108
- chmodSync2(codex, 448);
3489
+ chmodSync3(codex, 448);
3109
3490
  }
3110
3491
  }
3111
3492
  function defaultShellProfile() {
3112
3493
  const shell = process.env.SHELL?.split("/").pop();
3113
- return join6(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
3494
+ return join7(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
3114
3495
  }
3115
3496
  function getLocalRoutingPaths() {
3116
3497
  const configDir = dirname3(resolveConfigPath());
3117
3498
  return {
3118
- binDir: join6(configDir, "client-bin"),
3499
+ binDir: join7(configDir, "client-bin"),
3119
3500
  shellProfile: defaultShellProfile(),
3120
- statePath: join6(configDir, "client-routing.json")
3501
+ statePath: join7(configDir, "client-routing.json")
3121
3502
  };
3122
3503
  }
3123
3504
  function isExecutable(path) {
@@ -3132,17 +3513,17 @@ function findClientExecutable(name, binDir, path) {
3132
3513
  for (const directory of path.split(":")) {
3133
3514
  if (!directory || directory === binDir)
3134
3515
  continue;
3135
- const candidate = join6(directory, name);
3516
+ const candidate = join7(directory, name);
3136
3517
  if (isExecutable(candidate))
3137
3518
  return candidate;
3138
3519
  }
3139
3520
  throw new Error(`${name} was not found in PATH`);
3140
3521
  }
3141
3522
  function readSavedClientPaths(statePath) {
3142
- if (!existsSync3(statePath))
3523
+ if (!existsSync4(statePath))
3143
3524
  return null;
3144
3525
  try {
3145
- const saved = JSON.parse(readFileSync3(statePath, "utf8"));
3526
+ const saved = JSON.parse(readFileSync4(statePath, "utf8"));
3146
3527
  if (typeof saved === "object" && saved !== null) {
3147
3528
  const { claudePath, codexPath } = saved;
3148
3529
  const validClaude = typeof claudePath === "string" && isExecutable(claudePath) ? claudePath : undefined;
@@ -3160,10 +3541,10 @@ function installedRoutingStatus(paths = {}) {
3160
3541
  const shellProfile = paths.shellProfile ?? defaults.shellProfile;
3161
3542
  let shellProfileHasRouting = false;
3162
3543
  try {
3163
- shellProfileHasRouting = existsSync3(shellProfile) && readFileSync3(shellProfile, "utf8").includes(ROUTING_BEGIN);
3544
+ shellProfileHasRouting = existsSync4(shellProfile) && readFileSync4(shellProfile, "utf8").includes(ROUTING_BEGIN);
3164
3545
  } catch {}
3165
3546
  return {
3166
- enabled: shellProfileHasRouting && (existsSync3(join6(binDir, "claude")) || existsSync3(join6(binDir, "codex"))),
3547
+ enabled: shellProfileHasRouting && (existsSync4(join7(binDir, "claude")) || existsSync4(join7(binDir, "codex"))),
3167
3548
  binDir,
3168
3549
  shellProfile
3169
3550
  };
@@ -3180,28 +3561,48 @@ function getLocalRoutingStatus(paths = {}) {
3180
3561
  }
3181
3562
  function configClientWrappersInstalled(paths = {}) {
3182
3563
  const binDir = paths.binDir ?? getLocalRoutingPaths().binDir;
3183
- const files = ["claude", "codex"].map((name) => join6(binDir, name)).filter(existsSync3);
3184
- return installedRoutingStatus(paths).enabled && files.length > 0 && files.every((path) => readFileSync3(path, "utf8").includes(CONFIG_CLIENT_MARKER));
3564
+ const files = ["claude", "codex"].map((name) => join7(binDir, name)).filter(existsSync4);
3565
+ return installedRoutingStatus(paths).enabled && files.length > 0 && files.every((path) => readFileSync4(path, "utf8").includes(CONFIG_CLIENT_MARKER));
3185
3566
  }
3186
3567
  async function launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args) {
3187
3568
  if (tool !== "claude" && tool !== "codex")
3188
3569
  throw new Error("Unknown Agent Smith client");
3570
+ dropInheritedForwardProxy(process.env);
3189
3571
  const client2 = readClientRouting(configPath);
3190
- const env = { ...process.env };
3572
+ let env = { ...process.env };
3191
3573
  delete env.AGENT_SMITH_ADMIN_KEY;
3192
3574
  delete env.AGENT_SMITH_PROXY_KEY;
3193
3575
  let command = [target, ...args];
3194
3576
  let relay;
3577
+ let forwardProxy;
3195
3578
  if (client2.enabled) {
3196
3579
  if (!client2.baseUrl || !client2.proxyKeyFile)
3197
3580
  throw new Error("client.base_url and client.proxy_key_file are required");
3198
3581
  const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
3199
3582
  const wires = Object.keys(new Config(configPath).getProviderPools());
3200
- if (client2.baseUrl.startsWith("https://"))
3201
- relay = startClientRelay(client2.baseUrl);
3202
- const base = proxyBaseUrl(8080, relay?.url ?? client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
3203
- const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
3204
- command = ["/bin/sh", "-c", script, "--", ...args];
3583
+ const certificate = tool === "claude" && client2.remoteControl !== false ? remoteControlCertificate(configPath) : undefined;
3584
+ if (certificate) {
3585
+ forwardProxy = await startForwardProxy({
3586
+ poolUrl: proxyBaseUrl(8080, client2.baseUrl, "claude-code", "anthropic-messages", wires),
3587
+ deviceKey: readFileSync4(keyFile, "utf8").trim(),
3588
+ certificate
3589
+ });
3590
+ env = forwardProxyClientEnv(env, forwardProxy.url, certificate.caFile);
3591
+ command = [
3592
+ target,
3593
+ "--settings",
3594
+ BASH_WITHOUT_PROXY_SETTINGS,
3595
+ "--plugin-dir",
3596
+ claudeCompanionDir,
3597
+ ...args
3598
+ ];
3599
+ } else {
3600
+ if (client2.baseUrl.startsWith("https://"))
3601
+ relay = startClientRelay(client2.baseUrl);
3602
+ const base = proxyBaseUrl(8080, relay?.url ?? client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
3603
+ const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
3604
+ command = ["/bin/sh", "-c", script, "--", ...args];
3605
+ }
3205
3606
  }
3206
3607
  const child = Bun.spawn(command, {
3207
3608
  env,
@@ -3222,6 +3623,7 @@ async function launchConfiguredClient(configPath, tool, target, claudeCompanionD
3222
3623
  for (const [signal, listener] of Object.entries(forward))
3223
3624
  process.off(signal, listener);
3224
3625
  relay?.stop();
3626
+ forwardProxy?.stop();
3225
3627
  }
3226
3628
  }
3227
3629
  async function enableLocalClientRouting(options) {
@@ -3254,14 +3656,14 @@ async function enableLocalClientRouting(options) {
3254
3656
  clientConfigPath: options.clientConfigPath,
3255
3657
  providerPoolWires: options.providerPoolWires ?? (options.clientConfigPath ? [] : Object.keys(new Config().getProviderPools()))
3256
3658
  });
3257
- const existingProfile = existsSync3(shellProfile) ? readFileSync3(shellProfile, "utf8") : "";
3258
- writeFileSync3(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
3259
- mkdirSync3(dirname3(statePath), { recursive: true, mode: 448 });
3260
- writeFileSync3(statePath, JSON.stringify({ claudePath, codexPath }), {
3659
+ const existingProfile = existsSync4(shellProfile) ? readFileSync4(shellProfile, "utf8") : "";
3660
+ writeFileSync4(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
3661
+ mkdirSync4(dirname3(statePath), { recursive: true, mode: 448 });
3662
+ writeFileSync4(statePath, JSON.stringify({ claudePath, codexPath }), {
3261
3663
  encoding: "utf8",
3262
3664
  mode: 384
3263
3665
  });
3264
- chmodSync2(statePath, 384);
3666
+ chmodSync3(statePath, 384);
3265
3667
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
3266
3668
  }
3267
3669
  function disableLocalClientRouting(paths = {}) {
@@ -3269,19 +3671,19 @@ function disableLocalClientRouting(paths = {}) {
3269
3671
  const binDir = paths.binDir ?? defaults.binDir;
3270
3672
  const shellProfile = paths.shellProfile ?? defaults.shellProfile;
3271
3673
  const statePath = paths.statePath ?? defaults.statePath;
3272
- if (existsSync3(shellProfile)) {
3273
- writeFileSync3(shellProfile, removeRoutingFromShellProfile(readFileSync3(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
3674
+ if (existsSync4(shellProfile)) {
3675
+ writeFileSync4(shellProfile, removeRoutingFromShellProfile(readFileSync4(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
3274
3676
  }
3275
3677
  for (const name of ["claude", "codex"]) {
3276
- const wrapper = join6(binDir, name);
3277
- if (existsSync3(wrapper))
3678
+ const wrapper = join7(binDir, name);
3679
+ if (existsSync4(wrapper))
3278
3680
  unlinkSync3(wrapper);
3279
3681
  }
3280
- rmSync2(join6(binDir, CLAUDE_COMPANION_DIRNAME), {
3682
+ rmSync3(join7(binDir, CLAUDE_COMPANION_DIRNAME), {
3281
3683
  force: true,
3282
3684
  recursive: true
3283
3685
  });
3284
- if (existsSync3(statePath))
3686
+ if (existsSync4(statePath))
3285
3687
  unlinkSync3(statePath);
3286
3688
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
3287
3689
  }
@@ -3307,9 +3709,10 @@ export PATH=${shellDoubleQuote(`${binDir}:$PATH`)}
3307
3709
  ${ROUTING_END}
3308
3710
  `;
3309
3711
  }
3310
- var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CLAUDE_COMPANION_DIRNAME = "agent-smith-claude-companion", CLAUDE_COMPANION_FILES, CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
3712
+ var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CLAUDE_COMPANION_DIRNAME = "agent-smith-claude-companion", CLAUDE_COMPANION_FILES, CONFIG_CLIENT_MARKER = "# agent-smith config-driven client", PROXY_VARIABLES, NO_PROXY_HOSTS = "localhost,127.0.0.1,::1", BASH_WITHOUT_PROXY_SETTINGS;
3311
3713
  var init_local_routing = __esm(() => {
3312
3714
  init_src4();
3715
+ init_client_forward_proxy();
3313
3716
  init_client_relay();
3314
3717
  CLAUDE_COMPANION_FILES = [
3315
3718
  ".claude-plugin/plugin.json",
@@ -3317,6 +3720,21 @@ var init_local_routing = __esm(() => {
3317
3720
  "hooks/provider-choice.js",
3318
3721
  "hooks/register.js"
3319
3722
  ];
3723
+ PROXY_VARIABLES = ["HTTPS_PROXY", "https_proxy"];
3724
+ BASH_WITHOUT_PROXY_SETTINGS = JSON.stringify({
3725
+ hooks: {
3726
+ SessionStart: [
3727
+ {
3728
+ hooks: [
3729
+ {
3730
+ type: "command",
3731
+ command: `[ -z "$CLAUDE_ENV_FILE" ] || echo 'unset ${PROXY_VARIABLES.join(" ")}' >> "$CLAUDE_ENV_FILE"`
3732
+ }
3733
+ ]
3734
+ }
3735
+ ]
3736
+ }
3737
+ });
3320
3738
  });
3321
3739
 
3322
3740
  // src/core/client-launcher.ts