@certalis/agent-smith 0.3.0 → 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.
- package/README.md +8 -3
- package/dist/bin.js +792 -177
- package/dist/claude-companion/hooks/provider-choice.js +6 -1
- package/dist/client-launcher.js +689 -66
- package/dist/edge.js +15 -3
- package/dist/https.js +17 -4
- package/dist/pool.js +217 -86
- package/dist/post-processor.worker.js +92 -42
- package/dist/server.js +217 -86
- package/package.json +2 -1
package/dist/client-launcher.js
CHANGED
|
@@ -1791,6 +1791,13 @@ import {
|
|
|
1791
1791
|
writeFileSync as writeFileSync2
|
|
1792
1792
|
} from "fs";
|
|
1793
1793
|
import { dirname as dirname2 } from "path";
|
|
1794
|
+
function callerWeeklyCap(caps, callerId) {
|
|
1795
|
+
if (!Object.hasOwn(caps, callerId))
|
|
1796
|
+
return;
|
|
1797
|
+
const cap = caps[callerId];
|
|
1798
|
+
const shared = typeof cap === "string" && Object.hasOwn(caps, cap) ? caps[cap] : cap;
|
|
1799
|
+
return typeof shared === "number" ? shared : undefined;
|
|
1800
|
+
}
|
|
1794
1801
|
function runtimeForProvider(runtime, provider) {
|
|
1795
1802
|
return {
|
|
1796
1803
|
...runtime,
|
|
@@ -1977,6 +1984,9 @@ function sanitizeClientRouting(value) {
|
|
|
1977
1984
|
if (typeof value.keep_claude_login === "boolean") {
|
|
1978
1985
|
client.keep_claude_login = value.keep_claude_login;
|
|
1979
1986
|
}
|
|
1987
|
+
if (typeof value.remote_control === "boolean") {
|
|
1988
|
+
client.remote_control = value.remote_control;
|
|
1989
|
+
}
|
|
1980
1990
|
if (typeof value.pool_ssh_host === "string" && POOL_SSH_HOST_PATTERN.test(value.pool_ssh_host)) {
|
|
1981
1991
|
client.pool_ssh_host = value.pool_ssh_host;
|
|
1982
1992
|
}
|
|
@@ -2092,8 +2102,9 @@ function sanitizeTeamRouting(value) {
|
|
|
2092
2102
|
if (weeklyMaxUsageByEmail)
|
|
2093
2103
|
result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
|
|
2094
2104
|
if (isRecord(value.caller_weekly_max_usage)) {
|
|
2095
|
-
const
|
|
2096
|
-
|
|
2105
|
+
const caps = value.caller_weekly_max_usage;
|
|
2106
|
+
const entries = Object.entries(caps);
|
|
2107
|
+
if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && (isCallerWeeklyCap(cap) || sharesACallerCap(caps, cap)))) {
|
|
2097
2108
|
result.caller_weekly_max_usage = Object.fromEntries(entries);
|
|
2098
2109
|
}
|
|
2099
2110
|
}
|
|
@@ -2247,10 +2258,11 @@ function clientRouting(client) {
|
|
|
2247
2258
|
...client?.base_url && { baseUrl: client.base_url },
|
|
2248
2259
|
...client?.proxy_key_file && { proxyKeyFile: client.proxy_key_file },
|
|
2249
2260
|
...client?.keep_claude_login === true && { keepClaudeLogin: true },
|
|
2261
|
+
...client?.remote_control === false && { remoteControl: false },
|
|
2250
2262
|
...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
|
|
2251
2263
|
};
|
|
2252
2264
|
}
|
|
2253
|
-
var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
|
|
2265
|
+
var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, isCallerWeeklyCap = (cap) => isFiniteNumber(cap) && cap > 0 && cap <= 0.95, sharesACallerCap = (caps, cap) => typeof cap === "string" && Object.hasOwn(caps, cap) && isCallerWeeklyCap(caps[cap]), POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
|
|
2254
2266
|
var init_src4 = __esm(() => {
|
|
2255
2267
|
init_src2();
|
|
2256
2268
|
init_src3();
|
|
@@ -2734,22 +2746,561 @@ var init_src4 = __esm(() => {
|
|
|
2734
2746
|
};
|
|
2735
2747
|
});
|
|
2736
2748
|
|
|
2737
|
-
// src/
|
|
2749
|
+
// ../../packages/http/src/errors.ts
|
|
2750
|
+
var ERROR_TYPES, HttpError, BadRequest = (message, details) => new HttpError(400, message, details), NotFound = (message, details) => new HttpError(404, message, details), InternalServerError = (message, details) => new HttpError(500, message, details), ServiceUnavailable = (message, details) => new HttpError(503, message, details), DEFAULT_ERROR_MESSAGES;
|
|
2751
|
+
var init_errors2 = __esm(() => {
|
|
2752
|
+
ERROR_TYPES = {
|
|
2753
|
+
NETWORK: "network",
|
|
2754
|
+
AUTH: "auth",
|
|
2755
|
+
RATE_LIMIT: "rate-limit",
|
|
2756
|
+
VALIDATION: "validation",
|
|
2757
|
+
SERVER: "server",
|
|
2758
|
+
UNKNOWN: "unknown"
|
|
2759
|
+
};
|
|
2760
|
+
HttpError = class HttpError extends Error {
|
|
2761
|
+
status;
|
|
2762
|
+
details;
|
|
2763
|
+
constructor(status, message, details) {
|
|
2764
|
+
super(message);
|
|
2765
|
+
this.status = status;
|
|
2766
|
+
this.details = details;
|
|
2767
|
+
this.name = "HttpError";
|
|
2768
|
+
}
|
|
2769
|
+
};
|
|
2770
|
+
DEFAULT_ERROR_MESSAGES = {
|
|
2771
|
+
[ERROR_TYPES.NETWORK]: "Network error. Please check your connection and try again.",
|
|
2772
|
+
[ERROR_TYPES.AUTH]: "Authentication failed. Please sign in again.",
|
|
2773
|
+
[ERROR_TYPES.RATE_LIMIT]: "Too many requests. Please try again later.",
|
|
2774
|
+
[ERROR_TYPES.VALIDATION]: "Invalid request. Please check your input.",
|
|
2775
|
+
[ERROR_TYPES.SERVER]: "Server error. Please try again later.",
|
|
2776
|
+
[ERROR_TYPES.UNKNOWN]: "An unexpected error occurred."
|
|
2777
|
+
};
|
|
2778
|
+
});
|
|
2779
|
+
|
|
2780
|
+
// ../../packages/http/src/client.ts
|
|
2781
|
+
var init_client = __esm(() => {
|
|
2782
|
+
init_errors2();
|
|
2783
|
+
});
|
|
2784
|
+
|
|
2785
|
+
// ../../packages/http/src/headers.ts
|
|
2786
|
+
function sanitizeProxyHeaders(original) {
|
|
2787
|
+
const sanitized = new Headers(original);
|
|
2788
|
+
sanitized.delete("content-encoding");
|
|
2789
|
+
sanitized.delete("content-length");
|
|
2790
|
+
sanitized.delete("transfer-encoding");
|
|
2791
|
+
return sanitized;
|
|
2792
|
+
}
|
|
2793
|
+
function sanitizeRequestHeaders(original) {
|
|
2794
|
+
const h = new Headers(original);
|
|
2795
|
+
h.delete("accept-encoding");
|
|
2796
|
+
h.delete("content-encoding");
|
|
2797
|
+
h.delete("content-length");
|
|
2798
|
+
h.delete("transfer-encoding");
|
|
2799
|
+
h.delete("authorization");
|
|
2800
|
+
h.delete("proxy-authorization");
|
|
2801
|
+
h.delete("x-api-key");
|
|
2802
|
+
h.delete(DEVICE_KEY_HEADER);
|
|
2803
|
+
h.delete("api-key");
|
|
2804
|
+
h.delete("cookie");
|
|
2805
|
+
h.delete("set-cookie");
|
|
2806
|
+
return h;
|
|
2807
|
+
}
|
|
2808
|
+
function withSanitizedProxyHeaders(res) {
|
|
2809
|
+
return new Response(res.body, {
|
|
2810
|
+
status: res.status,
|
|
2811
|
+
statusText: res.statusText,
|
|
2812
|
+
headers: sanitizeProxyHeaders(res.headers)
|
|
2813
|
+
});
|
|
2814
|
+
}
|
|
2815
|
+
var DEVICE_KEY_HEADER = "x-agent-smith-device-key";
|
|
2816
|
+
|
|
2817
|
+
// ../../packages/http/src/responses.ts
|
|
2818
|
+
function writeUnhandledError(error) {
|
|
2819
|
+
if (typeof process === "undefined") {
|
|
2820
|
+
return;
|
|
2821
|
+
}
|
|
2822
|
+
const formattedError = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
2823
|
+
process.stderr?.write?.(`Unhandled error: ${formattedError}
|
|
2824
|
+
`);
|
|
2825
|
+
}
|
|
2826
|
+
function jsonResponse(data, status = 200, headers) {
|
|
2827
|
+
return new Response(JSON.stringify(data), {
|
|
2828
|
+
status,
|
|
2829
|
+
headers: {
|
|
2830
|
+
"Content-Type": "application/json",
|
|
2831
|
+
...headers
|
|
2832
|
+
}
|
|
2833
|
+
});
|
|
2834
|
+
}
|
|
2835
|
+
function errorResponse(error) {
|
|
2836
|
+
if (error instanceof HttpError) {
|
|
2837
|
+
const body = {
|
|
2838
|
+
error: error.message
|
|
2839
|
+
};
|
|
2840
|
+
if (error.details !== undefined) {
|
|
2841
|
+
body.details = error.details;
|
|
2842
|
+
}
|
|
2843
|
+
return jsonResponse(body, error.status);
|
|
2844
|
+
}
|
|
2845
|
+
if (error instanceof Error && "statusCode" in error && typeof error.statusCode === "number") {
|
|
2846
|
+
const details = "context" in error && error.context !== undefined ? { details: error.context } : {};
|
|
2847
|
+
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;
|
|
2848
|
+
return jsonResponse({ error: error.message, ...details }, error.statusCode, retryAfter);
|
|
2849
|
+
}
|
|
2850
|
+
const message = error instanceof Error ? error.message : "Internal server error";
|
|
2851
|
+
const status = 500;
|
|
2852
|
+
writeUnhandledError(error);
|
|
2853
|
+
return jsonResponse({ error: message }, status);
|
|
2854
|
+
}
|
|
2855
|
+
function sseResponse(stream, headers) {
|
|
2856
|
+
return new Response(stream, {
|
|
2857
|
+
headers: {
|
|
2858
|
+
"Content-Type": "text/event-stream",
|
|
2859
|
+
"Cache-Control": "no-cache",
|
|
2860
|
+
Connection: "keep-alive",
|
|
2861
|
+
...headers
|
|
2862
|
+
}
|
|
2863
|
+
});
|
|
2864
|
+
}
|
|
2865
|
+
var init_responses = __esm(() => {
|
|
2866
|
+
init_errors2();
|
|
2867
|
+
});
|
|
2868
|
+
|
|
2869
|
+
// ../../packages/http/src/index.ts
|
|
2870
|
+
var init_src5 = __esm(() => {
|
|
2871
|
+
init_client();
|
|
2872
|
+
init_errors2();
|
|
2873
|
+
init_responses();
|
|
2874
|
+
});
|
|
2875
|
+
|
|
2876
|
+
// src/core/client-relay.ts
|
|
2877
|
+
function forwardedHeaders(original) {
|
|
2878
|
+
const headers2 = new Headers(original);
|
|
2879
|
+
for (const name of UNFORWARDED_REQUEST_HEADERS)
|
|
2880
|
+
headers2.delete(name);
|
|
2881
|
+
return headers2;
|
|
2882
|
+
}
|
|
2883
|
+
async function compressedBody(req, headers2) {
|
|
2884
|
+
const body = new Uint8Array(await req.arrayBuffer());
|
|
2885
|
+
if (body.length === 0)
|
|
2886
|
+
return;
|
|
2887
|
+
if (headers2.has("content-encoding"))
|
|
2888
|
+
return body;
|
|
2889
|
+
headers2.set("content-encoding", "gzip");
|
|
2890
|
+
return Bun.gzipSync(body);
|
|
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
|
+
}
|
|
2908
|
+
function startClientRelay(remoteBaseUrl) {
|
|
2909
|
+
const remote = remoteBaseUrl.replace(/\/+$/, "");
|
|
2910
|
+
const server = Bun.serve({
|
|
2911
|
+
hostname: "127.0.0.1",
|
|
2912
|
+
port: 0,
|
|
2913
|
+
idleTimeout: 0,
|
|
2914
|
+
fetch(req) {
|
|
2915
|
+
const url = new URL(req.url);
|
|
2916
|
+
return relayToPool(req, `${remote}${url.pathname}${url.search}`, forwardedHeaders(req.headers));
|
|
2917
|
+
}
|
|
2918
|
+
});
|
|
2919
|
+
return {
|
|
2920
|
+
url: `http://127.0.0.1:${server.port}`,
|
|
2921
|
+
stop: () => server.stop(true)
|
|
2922
|
+
};
|
|
2923
|
+
}
|
|
2924
|
+
var UNFORWARDED_REQUEST_HEADERS;
|
|
2925
|
+
var init_client_relay = __esm(() => {
|
|
2926
|
+
init_src5();
|
|
2927
|
+
UNFORWARDED_REQUEST_HEADERS = [
|
|
2928
|
+
"accept-encoding",
|
|
2929
|
+
"connection",
|
|
2930
|
+
"content-length",
|
|
2931
|
+
"host",
|
|
2932
|
+
"keep-alive",
|
|
2933
|
+
"transfer-encoding"
|
|
2934
|
+
];
|
|
2935
|
+
});
|
|
2936
|
+
|
|
2937
|
+
// src/core/client-forward-proxy.ts
|
|
2938
|
+
import { randomBytes, timingSafeEqual, X509Certificate } from "crypto";
|
|
2738
2939
|
import {
|
|
2739
|
-
accessSync as accessSync2,
|
|
2740
2940
|
chmodSync as chmodSync2,
|
|
2741
|
-
constants as constants2,
|
|
2742
|
-
copyFileSync,
|
|
2743
2941
|
existsSync as existsSync3,
|
|
2744
2942
|
mkdirSync as mkdirSync3,
|
|
2943
|
+
mkdtempSync,
|
|
2745
2944
|
readFileSync as readFileSync3,
|
|
2945
|
+
renameSync as renameSync3,
|
|
2746
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,
|
|
2747
3298
|
statSync as statSync4,
|
|
2748
3299
|
unlinkSync as unlinkSync3,
|
|
2749
|
-
writeFileSync as
|
|
3300
|
+
writeFileSync as writeFileSync4
|
|
2750
3301
|
} from "fs";
|
|
2751
3302
|
import { homedir as homedir2 } from "os";
|
|
2752
|
-
import { dirname as dirname3, join as
|
|
3303
|
+
import { dirname as dirname3, join as join7 } from "path";
|
|
2753
3304
|
import { fileURLToPath } from "url";
|
|
2754
3305
|
function shellQuote(value) {
|
|
2755
3306
|
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
@@ -2762,7 +3313,7 @@ function proxyBaseUrl(port, configuredBaseUrl, directProvider, wire, providerPoo
|
|
|
2762
3313
|
return `${configuredBaseUrl ?? `http://127.0.0.1:${port}`}${route}`;
|
|
2763
3314
|
}
|
|
2764
3315
|
function validateProxyKeyFile(proxyKeyFile) {
|
|
2765
|
-
const resolvedPath = proxyKeyFile.startsWith("~/") ?
|
|
3316
|
+
const resolvedPath = proxyKeyFile.startsWith("~/") ? join7(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
|
|
2766
3317
|
let metadata;
|
|
2767
3318
|
try {
|
|
2768
3319
|
metadata = statSync4(resolvedPath);
|
|
@@ -2775,7 +3326,7 @@ function validateProxyKeyFile(proxyKeyFile) {
|
|
|
2775
3326
|
if ((metadata.mode & 63) !== 0) {
|
|
2776
3327
|
throw new Error("Agent Smith forwarding-key file must be owner-only");
|
|
2777
3328
|
}
|
|
2778
|
-
const key =
|
|
3329
|
+
const key = readFileSync4(resolvedPath, "utf8").trim();
|
|
2779
3330
|
if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
|
|
2780
3331
|
throw new Error("Agent Smith forwarding-key file is invalid");
|
|
2781
3332
|
}
|
|
@@ -2800,32 +3351,32 @@ export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_
|
|
|
2800
3351
|
}x-api-key: $AGENT_SMITH_PROXY_KEY"`;
|
|
2801
3352
|
}
|
|
2802
3353
|
function claudeCompanionSourceDir() {
|
|
2803
|
-
const bundled =
|
|
2804
|
-
if (
|
|
3354
|
+
const bundled = join7(import.meta.dir, "claude-companion");
|
|
3355
|
+
if (existsSync4(join7(bundled, ".claude-plugin", "plugin.json"))) {
|
|
2805
3356
|
return bundled;
|
|
2806
3357
|
}
|
|
2807
|
-
const source =
|
|
2808
|
-
if (
|
|
3358
|
+
const source = join7(import.meta.dir, "..", "claude-companion");
|
|
3359
|
+
if (existsSync4(join7(source, ".claude-plugin", "plugin.json"))) {
|
|
2809
3360
|
return source;
|
|
2810
3361
|
}
|
|
2811
3362
|
throw new Error("Agent-smith Claude companion files are missing");
|
|
2812
3363
|
}
|
|
2813
3364
|
function installClaudeCompanion(binDir) {
|
|
2814
3365
|
const sourceDir = claudeCompanionSourceDir();
|
|
2815
|
-
const targetDir =
|
|
2816
|
-
|
|
3366
|
+
const targetDir = join7(binDir, CLAUDE_COMPANION_DIRNAME);
|
|
3367
|
+
rmSync3(targetDir, { force: true, recursive: true });
|
|
2817
3368
|
for (const relativePath of CLAUDE_COMPANION_FILES) {
|
|
2818
|
-
const target =
|
|
2819
|
-
|
|
2820
|
-
copyFileSync(
|
|
2821
|
-
|
|
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);
|
|
2822
3373
|
}
|
|
2823
3374
|
for (const directory of [
|
|
2824
3375
|
targetDir,
|
|
2825
|
-
|
|
2826
|
-
|
|
3376
|
+
join7(targetDir, ".claude-plugin"),
|
|
3377
|
+
join7(targetDir, "hooks")
|
|
2827
3378
|
]) {
|
|
2828
|
-
|
|
3379
|
+
chmodSync3(directory, 448);
|
|
2829
3380
|
}
|
|
2830
3381
|
return targetDir;
|
|
2831
3382
|
}
|
|
@@ -2842,6 +3393,36 @@ export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
|
|
|
2842
3393
|
exec ${shellQuote(claudePath)} --plugin-dir ${shellQuote(companionDir)} "$@"
|
|
2843
3394
|
`;
|
|
2844
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
|
+
}
|
|
2845
3426
|
function codexWrapper(codexPath, baseUrl, proxyKeyFile) {
|
|
2846
3427
|
const config = [
|
|
2847
3428
|
'model_provider="agent_smith"',
|
|
@@ -2866,58 +3447,58 @@ ${overrides} \\
|
|
|
2866
3447
|
async function installClientWrappers(options) {
|
|
2867
3448
|
if (options.clientConfigPath) {
|
|
2868
3449
|
const launcher = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./client-launcher.ts" : "./client-launcher.js", import.meta.url));
|
|
2869
|
-
|
|
3450
|
+
mkdirSync4(options.binDir, { recursive: true, mode: 448 });
|
|
2870
3451
|
for (const [tool, target] of [
|
|
2871
3452
|
["claude", options.claudePath],
|
|
2872
3453
|
["codex", options.codexPath]
|
|
2873
3454
|
]) {
|
|
2874
3455
|
if (!target)
|
|
2875
3456
|
continue;
|
|
2876
|
-
if (target ===
|
|
3457
|
+
if (target === join7(options.binDir, tool))
|
|
2877
3458
|
throw new Error("A client launcher cannot call itself");
|
|
2878
|
-
const wrapper =
|
|
3459
|
+
const wrapper = join7(options.binDir, tool);
|
|
2879
3460
|
const companionDir = tool === "claude" ? installClaudeCompanion(options.binDir) : "";
|
|
2880
|
-
|
|
3461
|
+
writeFileSync4(wrapper, `#!/bin/sh
|
|
2881
3462
|
${CONFIG_CLIENT_MARKER}
|
|
2882
3463
|
exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, companionDir].map(shellQuote).join(" ")} "$@"
|
|
2883
3464
|
`, { encoding: "utf8", mode: 448 });
|
|
2884
|
-
|
|
3465
|
+
chmodSync3(wrapper, 448);
|
|
2885
3466
|
}
|
|
2886
3467
|
return;
|
|
2887
3468
|
}
|
|
2888
3469
|
if (options.baseUrl && !options.proxyKeyFile) {
|
|
2889
3470
|
throw new Error("A configured Agent Smith server requires a forwarding key file");
|
|
2890
3471
|
}
|
|
2891
|
-
|
|
3472
|
+
mkdirSync4(options.binDir, { recursive: true, mode: 448 });
|
|
2892
3473
|
const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
|
|
2893
3474
|
if (options.claudePath) {
|
|
2894
|
-
const claude =
|
|
3475
|
+
const claude = join7(options.binDir, "claude");
|
|
2895
3476
|
const companionDir = installClaudeCompanion(options.binDir);
|
|
2896
|
-
|
|
3477
|
+
writeFileSync4(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
|
|
2897
3478
|
encoding: "utf8",
|
|
2898
3479
|
mode: 448
|
|
2899
3480
|
});
|
|
2900
|
-
|
|
3481
|
+
chmodSync3(claude, 448);
|
|
2901
3482
|
}
|
|
2902
3483
|
if (options.codexPath) {
|
|
2903
|
-
const codex =
|
|
2904
|
-
|
|
3484
|
+
const codex = join7(options.binDir, "codex");
|
|
3485
|
+
writeFileSync4(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
|
|
2905
3486
|
encoding: "utf8",
|
|
2906
3487
|
mode: 448
|
|
2907
3488
|
});
|
|
2908
|
-
|
|
3489
|
+
chmodSync3(codex, 448);
|
|
2909
3490
|
}
|
|
2910
3491
|
}
|
|
2911
3492
|
function defaultShellProfile() {
|
|
2912
3493
|
const shell = process.env.SHELL?.split("/").pop();
|
|
2913
|
-
return
|
|
3494
|
+
return join7(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
|
|
2914
3495
|
}
|
|
2915
3496
|
function getLocalRoutingPaths() {
|
|
2916
3497
|
const configDir = dirname3(resolveConfigPath());
|
|
2917
3498
|
return {
|
|
2918
|
-
binDir:
|
|
3499
|
+
binDir: join7(configDir, "client-bin"),
|
|
2919
3500
|
shellProfile: defaultShellProfile(),
|
|
2920
|
-
statePath:
|
|
3501
|
+
statePath: join7(configDir, "client-routing.json")
|
|
2921
3502
|
};
|
|
2922
3503
|
}
|
|
2923
3504
|
function isExecutable(path) {
|
|
@@ -2932,17 +3513,17 @@ function findClientExecutable(name, binDir, path) {
|
|
|
2932
3513
|
for (const directory of path.split(":")) {
|
|
2933
3514
|
if (!directory || directory === binDir)
|
|
2934
3515
|
continue;
|
|
2935
|
-
const candidate =
|
|
3516
|
+
const candidate = join7(directory, name);
|
|
2936
3517
|
if (isExecutable(candidate))
|
|
2937
3518
|
return candidate;
|
|
2938
3519
|
}
|
|
2939
3520
|
throw new Error(`${name} was not found in PATH`);
|
|
2940
3521
|
}
|
|
2941
3522
|
function readSavedClientPaths(statePath) {
|
|
2942
|
-
if (!
|
|
3523
|
+
if (!existsSync4(statePath))
|
|
2943
3524
|
return null;
|
|
2944
3525
|
try {
|
|
2945
|
-
const saved = JSON.parse(
|
|
3526
|
+
const saved = JSON.parse(readFileSync4(statePath, "utf8"));
|
|
2946
3527
|
if (typeof saved === "object" && saved !== null) {
|
|
2947
3528
|
const { claudePath, codexPath } = saved;
|
|
2948
3529
|
const validClaude = typeof claudePath === "string" && isExecutable(claudePath) ? claudePath : undefined;
|
|
@@ -2960,10 +3541,10 @@ function installedRoutingStatus(paths = {}) {
|
|
|
2960
3541
|
const shellProfile = paths.shellProfile ?? defaults.shellProfile;
|
|
2961
3542
|
let shellProfileHasRouting = false;
|
|
2962
3543
|
try {
|
|
2963
|
-
shellProfileHasRouting =
|
|
3544
|
+
shellProfileHasRouting = existsSync4(shellProfile) && readFileSync4(shellProfile, "utf8").includes(ROUTING_BEGIN);
|
|
2964
3545
|
} catch {}
|
|
2965
3546
|
return {
|
|
2966
|
-
enabled: shellProfileHasRouting && (
|
|
3547
|
+
enabled: shellProfileHasRouting && (existsSync4(join7(binDir, "claude")) || existsSync4(join7(binDir, "codex"))),
|
|
2967
3548
|
binDir,
|
|
2968
3549
|
shellProfile
|
|
2969
3550
|
};
|
|
@@ -2980,25 +3561,48 @@ function getLocalRoutingStatus(paths = {}) {
|
|
|
2980
3561
|
}
|
|
2981
3562
|
function configClientWrappersInstalled(paths = {}) {
|
|
2982
3563
|
const binDir = paths.binDir ?? getLocalRoutingPaths().binDir;
|
|
2983
|
-
const files = ["claude", "codex"].map((name) =>
|
|
2984
|
-
return installedRoutingStatus(paths).enabled && files.length > 0 && files.every((path) =>
|
|
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));
|
|
2985
3566
|
}
|
|
2986
3567
|
async function launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args) {
|
|
2987
3568
|
if (tool !== "claude" && tool !== "codex")
|
|
2988
3569
|
throw new Error("Unknown Agent Smith client");
|
|
2989
|
-
|
|
2990
|
-
const
|
|
3570
|
+
dropInheritedForwardProxy(process.env);
|
|
3571
|
+
const client2 = readClientRouting(configPath);
|
|
3572
|
+
let env = { ...process.env };
|
|
2991
3573
|
delete env.AGENT_SMITH_ADMIN_KEY;
|
|
2992
3574
|
delete env.AGENT_SMITH_PROXY_KEY;
|
|
2993
3575
|
let command = [target, ...args];
|
|
2994
|
-
|
|
2995
|
-
|
|
3576
|
+
let relay;
|
|
3577
|
+
let forwardProxy;
|
|
3578
|
+
if (client2.enabled) {
|
|
3579
|
+
if (!client2.baseUrl || !client2.proxyKeyFile)
|
|
2996
3580
|
throw new Error("client.base_url and client.proxy_key_file are required");
|
|
2997
|
-
const keyFile = validateProxyKeyFile(
|
|
3581
|
+
const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
|
|
2998
3582
|
const wires = Object.keys(new Config(configPath).getProviderPools());
|
|
2999
|
-
const
|
|
3000
|
-
|
|
3001
|
-
|
|
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
|
+
}
|
|
3002
3606
|
}
|
|
3003
3607
|
const child = Bun.spawn(command, {
|
|
3004
3608
|
env,
|
|
@@ -3018,6 +3622,8 @@ async function launchConfiguredClient(configPath, tool, target, claudeCompanionD
|
|
|
3018
3622
|
} finally {
|
|
3019
3623
|
for (const [signal, listener] of Object.entries(forward))
|
|
3020
3624
|
process.off(signal, listener);
|
|
3625
|
+
relay?.stop();
|
|
3626
|
+
forwardProxy?.stop();
|
|
3021
3627
|
}
|
|
3022
3628
|
}
|
|
3023
3629
|
async function enableLocalClientRouting(options) {
|
|
@@ -3050,14 +3656,14 @@ async function enableLocalClientRouting(options) {
|
|
|
3050
3656
|
clientConfigPath: options.clientConfigPath,
|
|
3051
3657
|
providerPoolWires: options.providerPoolWires ?? (options.clientConfigPath ? [] : Object.keys(new Config().getProviderPools()))
|
|
3052
3658
|
});
|
|
3053
|
-
const existingProfile =
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
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 }), {
|
|
3057
3663
|
encoding: "utf8",
|
|
3058
3664
|
mode: 384
|
|
3059
3665
|
});
|
|
3060
|
-
|
|
3666
|
+
chmodSync3(statePath, 384);
|
|
3061
3667
|
return getLocalRoutingStatus({ binDir, shellProfile, statePath });
|
|
3062
3668
|
}
|
|
3063
3669
|
function disableLocalClientRouting(paths = {}) {
|
|
@@ -3065,19 +3671,19 @@ function disableLocalClientRouting(paths = {}) {
|
|
|
3065
3671
|
const binDir = paths.binDir ?? defaults.binDir;
|
|
3066
3672
|
const shellProfile = paths.shellProfile ?? defaults.shellProfile;
|
|
3067
3673
|
const statePath = paths.statePath ?? defaults.statePath;
|
|
3068
|
-
if (
|
|
3069
|
-
|
|
3674
|
+
if (existsSync4(shellProfile)) {
|
|
3675
|
+
writeFileSync4(shellProfile, removeRoutingFromShellProfile(readFileSync4(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
|
|
3070
3676
|
}
|
|
3071
3677
|
for (const name of ["claude", "codex"]) {
|
|
3072
|
-
const wrapper =
|
|
3073
|
-
if (
|
|
3678
|
+
const wrapper = join7(binDir, name);
|
|
3679
|
+
if (existsSync4(wrapper))
|
|
3074
3680
|
unlinkSync3(wrapper);
|
|
3075
3681
|
}
|
|
3076
|
-
|
|
3682
|
+
rmSync3(join7(binDir, CLAUDE_COMPANION_DIRNAME), {
|
|
3077
3683
|
force: true,
|
|
3078
3684
|
recursive: true
|
|
3079
3685
|
});
|
|
3080
|
-
if (
|
|
3686
|
+
if (existsSync4(statePath))
|
|
3081
3687
|
unlinkSync3(statePath);
|
|
3082
3688
|
return getLocalRoutingStatus({ binDir, shellProfile, statePath });
|
|
3083
3689
|
}
|
|
@@ -3103,15 +3709,32 @@ export PATH=${shellDoubleQuote(`${binDir}:$PATH`)}
|
|
|
3103
3709
|
${ROUTING_END}
|
|
3104
3710
|
`;
|
|
3105
3711
|
}
|
|
3106
|
-
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;
|
|
3107
3713
|
var init_local_routing = __esm(() => {
|
|
3108
3714
|
init_src4();
|
|
3715
|
+
init_client_forward_proxy();
|
|
3716
|
+
init_client_relay();
|
|
3109
3717
|
CLAUDE_COMPANION_FILES = [
|
|
3110
3718
|
".claude-plugin/plugin.json",
|
|
3111
3719
|
"hooks/hooks.json",
|
|
3112
3720
|
"hooks/provider-choice.js",
|
|
3113
3721
|
"hooks/register.js"
|
|
3114
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
|
+
});
|
|
3115
3738
|
});
|
|
3116
3739
|
|
|
3117
3740
|
// src/core/client-launcher.ts
|