computesdk 2.5.3 → 2.6.0

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/dist/index.mjs CHANGED
@@ -3491,16 +3491,15 @@ API request failed (${response.status}): ${error}`
3491
3491
  const parts = url.hostname.split(".");
3492
3492
  const subdomain = parts[0];
3493
3493
  const baseDomain = parts.slice(1).join(".");
3494
- const previewDomain = baseDomain.replace("sandbox.computesdk.com", "preview.computesdk.com");
3495
- return `${protocol}://${subdomain}-${options.port}.${previewDomain}`;
3494
+ return `${protocol}://${subdomain}-${options.port}.${baseDomain}`;
3496
3495
  }
3497
3496
  /**
3498
3497
  * Get provider instance
3499
- * Note: Not available when using Sandbox directly - only available through gateway provider
3498
+ * Note: Not available on direct Sandbox client instances
3500
3499
  */
3501
3500
  getProvider() {
3502
3501
  throw new Error(
3503
- "getProvider() is not available on Sandbox. This method is only available when using provider sandboxes through the gateway."
3502
+ "getProvider() is not available on Sandbox. This method is only available on provider SDK sandbox wrappers."
3504
3503
  );
3505
3504
  }
3506
3505
  /**
@@ -3513,7 +3512,7 @@ API request failed (${response.status}): ${error}`
3513
3512
  /**
3514
3513
  * Destroy the sandbox (Sandbox interface method)
3515
3514
  *
3516
- * If a destroyHandler was provided (e.g., from gateway), calls it to destroy
3515
+ * If a destroyHandler was provided, calls it to destroy
3517
3516
  * the sandbox on the backend. Otherwise, only disconnects the WebSocket.
3518
3517
  */
3519
3518
  async destroy() {
@@ -3574,1003 +3573,331 @@ var encodeSetupPayload = (options) => {
3574
3573
  return encodeBase64(JSON.stringify(payload));
3575
3574
  };
3576
3575
 
3577
- // src/provider-config.ts
3578
- var PROVIDER_AUTH = {
3579
- e2b: [["E2B_API_KEY"]],
3580
- modal: [["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"]],
3581
- railway: [["RAILWAY_API_KEY", "RAILWAY_PROJECT_ID", "RAILWAY_ENVIRONMENT_ID"]],
3582
- render: [["RENDER_API_KEY", "RENDER_OWNER_ID"]],
3583
- daytona: [["DAYTONA_API_KEY"]],
3584
- vercel: [
3585
- ["VERCEL_OIDC_TOKEN"],
3586
- ["VERCEL_TOKEN", "VERCEL_TEAM_ID", "VERCEL_PROJECT_ID"]
3587
- ],
3588
- runloop: [["RUNLOOP_API_KEY"]],
3589
- cloudflare: [
3590
- ["CLOUDFLARE_SANDBOX_URL", "CLOUDFLARE_SANDBOX_SECRET"],
3591
- ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"]
3592
- ],
3593
- codesandbox: [["CSB_API_KEY"]],
3594
- blaxel: [["BL_API_KEY", "BL_WORKSPACE"]],
3595
- namespace: [["NSC_TOKEN"], ["NSC_TOKEN_FILE"]],
3596
- hopx: [["HOPX_API_KEY"]],
3597
- beam: [["BEAM_TOKEN", "BEAM_WORKSPACE_ID"]],
3598
- sprites: [["SPRITES_TOKEN"]],
3599
- freestyle: [["FREESTYLE_API_KEY"]],
3600
- upstash: [["UPSTASH_BOX_API_KEY"]],
3601
- "just-bash": [[]],
3602
- "secure-exec": [[]]
3603
- };
3604
- var PROVIDER_NAMES = Object.keys(PROVIDER_AUTH);
3605
- var PROVIDER_HEADERS = {
3606
- e2b: {
3607
- apiKey: "X-E2B-API-Key"
3608
- },
3609
- modal: {
3610
- tokenId: "X-Modal-Token-Id",
3611
- tokenSecret: "X-Modal-Token-Secret"
3612
- },
3613
- railway: {
3614
- apiToken: "X-Railway-API-Key",
3615
- projectId: "X-Railway-Project-ID",
3616
- environmentId: "X-Railway-Environment-ID"
3617
- },
3618
- render: {
3619
- apiKey: "X-Render-API-Key",
3620
- ownerId: "X-Render-Owner-ID"
3621
- },
3622
- daytona: {
3623
- apiKey: "X-Daytona-API-Key"
3624
- },
3625
- vercel: {
3626
- oidcToken: "X-Vercel-OIDC-Token",
3627
- token: "X-Vercel-Token",
3628
- teamId: "X-Vercel-Team-Id",
3629
- projectId: "X-Vercel-Project-Id"
3630
- },
3631
- runloop: {
3632
- apiKey: "X-Runloop-API-Key"
3633
- },
3634
- cloudflare: {
3635
- sandboxUrl: "X-Cloudflare-Sandbox-Url",
3636
- sandboxSecret: "X-Cloudflare-Sandbox-Secret",
3637
- apiToken: "X-Cloudflare-API-Token",
3638
- accountId: "X-Cloudflare-Account-Id"
3639
- },
3640
- codesandbox: {
3641
- apiKey: "X-CODESANDBOX-API-Key"
3642
- },
3643
- blaxel: {
3644
- apiKey: "X-Blaxel-API-Key",
3645
- workspace: "X-Blaxel-Workspace"
3646
- },
3647
- namespace: {
3648
- token: "X-Namespace-Token"
3649
- },
3650
- hopx: {
3651
- apiKey: "X-HOPX-API-Key"
3652
- },
3653
- beam: {
3654
- token: "X-Beam-Token",
3655
- workspaceId: "X-Beam-Workspace-Id"
3656
- },
3657
- sprites: {
3658
- apiKey: "X-Sprites-Token"
3659
- },
3660
- freestyle: {
3661
- apiKey: "X-Freestyle-API-Key"
3662
- },
3663
- upstash: {
3664
- apiKey: "X-Upstash-Box-API-Key"
3665
- },
3666
- "just-bash": {},
3667
- "secure-exec": {}
3668
- };
3669
- var PROVIDER_ENV_MAP = {
3670
- e2b: {
3671
- E2B_API_KEY: "apiKey"
3672
- },
3673
- modal: {
3674
- MODAL_TOKEN_ID: "tokenId",
3675
- MODAL_TOKEN_SECRET: "tokenSecret"
3676
- },
3677
- railway: {
3678
- RAILWAY_API_KEY: "apiToken",
3679
- RAILWAY_PROJECT_ID: "projectId",
3680
- RAILWAY_ENVIRONMENT_ID: "environmentId"
3681
- },
3682
- render: {
3683
- RENDER_API_KEY: "apiKey",
3684
- RENDER_OWNER_ID: "ownerId"
3685
- },
3686
- daytona: {
3687
- DAYTONA_API_KEY: "apiKey"
3688
- },
3689
- vercel: {
3690
- VERCEL_OIDC_TOKEN: "oidcToken",
3691
- VERCEL_TOKEN: "token",
3692
- VERCEL_TEAM_ID: "teamId",
3693
- VERCEL_PROJECT_ID: "projectId"
3694
- },
3695
- runloop: {
3696
- RUNLOOP_API_KEY: "apiKey"
3697
- },
3698
- cloudflare: {
3699
- CLOUDFLARE_SANDBOX_URL: "sandboxUrl",
3700
- CLOUDFLARE_SANDBOX_SECRET: "sandboxSecret",
3701
- CLOUDFLARE_API_TOKEN: "apiToken",
3702
- CLOUDFLARE_ACCOUNT_ID: "accountId"
3703
- },
3704
- codesandbox: {
3705
- CSB_API_KEY: "apiKey"
3706
- },
3707
- blaxel: {
3708
- BL_API_KEY: "apiKey",
3709
- BL_WORKSPACE: "workspace"
3710
- },
3711
- namespace: {
3712
- NSC_TOKEN: "token",
3713
- NSC_TOKEN_FILE: "tokenFile"
3714
- },
3715
- hopx: {
3716
- HOPX_API_KEY: "apiKey"
3717
- },
3718
- beam: {
3719
- BEAM_TOKEN: "token",
3720
- BEAM_WORKSPACE_ID: "workspaceId"
3721
- },
3722
- sprites: {
3723
- SPRITES_TOKEN: "apiKey"
3724
- },
3725
- freestyle: {
3726
- FREESTYLE_API_KEY: "apiKey"
3727
- },
3728
- upstash: {
3729
- UPSTASH_BOX_API_KEY: "apiKey"
3730
- },
3731
- "just-bash": {},
3732
- "secure-exec": {}
3733
- };
3734
- var PROVIDER_DASHBOARD_URLS = {
3735
- e2b: "https://e2b.dev/dashboard",
3736
- modal: "https://modal.com/settings",
3737
- railway: "https://railway.app/account/tokens",
3738
- render: "https://dashboard.render.com/account",
3739
- daytona: "https://daytona.io/dashboard",
3740
- vercel: "https://vercel.com/account/tokens",
3741
- runloop: "https://runloop.ai/dashboard",
3742
- cloudflare: "https://dash.cloudflare.com/profile/api-tokens",
3743
- codesandbox: "https://codesandbox.io/dashboard/settings",
3744
- blaxel: "https://blaxel.ai/dashboard",
3745
- namespace: "https://cloud.namespace.so",
3746
- hopx: "https://hopx.ai/dashboard",
3747
- beam: "https://app.beam.cloud",
3748
- sprites: "https://sprites.dev",
3749
- freestyle: "https://dash.freestyle.sh",
3750
- upstash: "https://console.upstash.com",
3751
- "just-bash": "https://github.com/vercel-labs/just-bash",
3752
- "secure-exec": "https://github.com/anomalyco/secure-exec"
3753
- };
3754
- function isValidProvider(name) {
3755
- return name in PROVIDER_AUTH;
3756
- }
3757
- function buildProviderHeaders(provider, config) {
3758
- const headers = {};
3759
- const headerMap = PROVIDER_HEADERS[provider];
3760
- for (const [configKey, headerName] of Object.entries(headerMap)) {
3761
- const value = config[configKey];
3762
- if (value) {
3763
- headers[headerName] = value;
3764
- }
3765
- }
3766
- return headers;
3767
- }
3768
- function getProviderConfigFromEnv(provider) {
3769
- const config = {};
3770
- const envMap = PROVIDER_ENV_MAP[provider];
3771
- for (const [envVar, configKey] of Object.entries(envMap)) {
3772
- const value = process.env[envVar];
3773
- if (value) {
3774
- config[configKey] = value;
3775
- }
3776
- }
3777
- return config;
3778
- }
3779
- function isProviderAuthComplete(provider) {
3780
- const authOptions = PROVIDER_AUTH[provider];
3781
- for (const option of authOptions) {
3782
- const allPresent = option.every((envVar) => !!process.env[envVar]);
3783
- if (allPresent) return true;
3784
- }
3785
- return false;
3786
- }
3787
- function getMissingEnvVars(provider) {
3788
- const authOptions = PROVIDER_AUTH[provider];
3789
- let bestOption = null;
3790
- for (const option of authOptions) {
3791
- const missing = [];
3792
- let presentCount = 0;
3793
- for (const envVar of option) {
3794
- if (process.env[envVar]) {
3795
- presentCount++;
3796
- } else {
3797
- missing.push(envVar);
3798
- }
3799
- }
3800
- if (missing.length === 0) return [];
3801
- if (!bestOption || presentCount > bestOption.presentCount) {
3802
- bestOption = { presentCount, missing };
3803
- }
3804
- }
3805
- return bestOption?.missing ?? [];
3806
- }
3807
-
3808
- // src/constants.ts
3809
- var TRIBUTARY_URL = "https://tributary.edge.computesdk.com";
3810
- var PROVIDER_PRIORITY = [
3811
- "e2b",
3812
- "railway",
3813
- "render",
3814
- "daytona",
3815
- "modal",
3816
- "runloop",
3817
- "vercel",
3818
- "cloudflare",
3819
- "codesandbox",
3820
- "blaxel",
3821
- "namespace",
3822
- "hopx",
3823
- "beam",
3824
- "sprites",
3825
- "freestyle",
3826
- "upstash",
3827
- "secure-exec"
3828
- ];
3829
- var PROVIDER_ENV_VARS = {
3830
- e2b: ["E2B_API_KEY"],
3831
- railway: ["RAILWAY_API_KEY", "RAILWAY_PROJECT_ID", "RAILWAY_ENVIRONMENT_ID"],
3832
- render: ["RENDER_API_KEY", "RENDER_OWNER_ID"],
3833
- daytona: ["DAYTONA_API_KEY"],
3834
- modal: ["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"],
3835
- runloop: ["RUNLOOP_API_KEY"],
3836
- vercel: ["VERCEL_TOKEN", "VERCEL_TEAM_ID", "VERCEL_PROJECT_ID"],
3837
- cloudflare: ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"],
3838
- codesandbox: ["CSB_API_KEY"],
3839
- blaxel: ["BL_API_KEY", "BL_WORKSPACE"],
3840
- namespace: ["NSC_TOKEN"],
3841
- hopx: ["HOPX_API_KEY"],
3842
- beam: ["BEAM_TOKEN", "BEAM_WORKSPACE_ID"],
3843
- sprites: ["SPRITES_TOKEN"],
3844
- freestyle: ["FREESTYLE_API_KEY"],
3845
- upstash: ["UPSTASH_BOX_API_KEY"],
3846
- "just-bash": [],
3847
- "secure-exec": []
3848
- };
3849
-
3850
- // src/auto-detect.ts
3851
- function isGatewayModeEnabled() {
3852
- return !!(typeof process !== "undefined" && process.env?.COMPUTESDK_API_KEY);
3853
- }
3854
- function hasProviderEnv(provider) {
3855
- if (typeof process === "undefined") return false;
3856
- const requiredVars = PROVIDER_ENV_VARS[provider];
3857
- if (!requiredVars || requiredVars.length === 0) return false;
3858
- return requiredVars.every((varName) => !!process.env?.[varName]);
3859
- }
3860
- function getProviderEnvStatus(provider) {
3861
- const requiredVars = PROVIDER_ENV_VARS[provider];
3862
- if (typeof process === "undefined" || !requiredVars) {
3863
- return { provider, present: [], missing: requiredVars ? [...requiredVars] : [], isComplete: false };
3864
- }
3865
- const present = requiredVars.filter((varName) => !!process.env?.[varName]);
3866
- const missing = requiredVars.filter((varName) => !process.env?.[varName]);
3867
- return {
3868
- provider,
3869
- present: [...present],
3870
- missing: [...missing],
3871
- isComplete: missing.length === 0
3872
- };
3873
- }
3874
- function detectProvider() {
3875
- if (typeof process === "undefined") return null;
3876
- const explicit = process.env.COMPUTESDK_PROVIDER?.toLowerCase();
3877
- if (explicit && hasProviderEnv(explicit)) {
3878
- return explicit;
3879
- }
3880
- if (explicit && !hasProviderEnv(explicit)) {
3881
- console.warn(
3882
- `\u26A0\uFE0F COMPUTESDK_PROVIDER is set to "${explicit}" but required credentials are missing.
3883
- Required: ${PROVIDER_ENV_VARS[explicit]?.join(", ") || "unknown"}
3884
- Falling back to auto-detection...`
3885
- );
3886
- }
3887
- for (const provider of PROVIDER_PRIORITY) {
3888
- if (hasProviderEnv(provider)) {
3889
- return provider;
3890
- }
3891
- }
3892
- return null;
3893
- }
3894
- function getProviderHeaders(provider) {
3895
- if (typeof process === "undefined") return {};
3896
- const headers = {};
3897
- switch (provider) {
3898
- case "e2b":
3899
- if (process.env.E2B_API_KEY) {
3900
- headers["X-E2B-API-Key"] = process.env.E2B_API_KEY;
3901
- }
3902
- break;
3903
- case "railway":
3904
- if (process.env.RAILWAY_API_KEY) {
3905
- headers["X-Railway-API-Key"] = process.env.RAILWAY_API_KEY;
3906
- }
3907
- if (process.env.RAILWAY_PROJECT_ID) {
3908
- headers["X-Railway-Project-ID"] = process.env.RAILWAY_PROJECT_ID;
3909
- }
3910
- if (process.env.RAILWAY_ENVIRONMENT_ID) {
3911
- headers["X-Railway-Environment-ID"] = process.env.RAILWAY_ENVIRONMENT_ID;
3912
- }
3913
- break;
3914
- case "daytona":
3915
- if (process.env.DAYTONA_API_KEY) {
3916
- headers["X-Daytona-API-Key"] = process.env.DAYTONA_API_KEY;
3917
- }
3918
- break;
3919
- case "modal":
3920
- if (process.env.MODAL_TOKEN_ID) {
3921
- headers["X-Modal-Token-ID"] = process.env.MODAL_TOKEN_ID;
3922
- }
3923
- if (process.env.MODAL_TOKEN_SECRET) {
3924
- headers["X-Modal-Token-Secret"] = process.env.MODAL_TOKEN_SECRET;
3925
- }
3926
- break;
3927
- case "runloop":
3928
- if (process.env.RUNLOOP_API_KEY) {
3929
- headers["X-Runloop-API-Key"] = process.env.RUNLOOP_API_KEY;
3930
- }
3931
- break;
3932
- case "vercel":
3933
- if (process.env.VERCEL_TOKEN) {
3934
- headers["X-Vercel-Token"] = process.env.VERCEL_TOKEN;
3935
- }
3936
- if (process.env.VERCEL_TEAM_ID) {
3937
- headers["X-Vercel-Team-ID"] = process.env.VERCEL_TEAM_ID;
3938
- }
3939
- if (process.env.VERCEL_PROJECT_ID) {
3940
- headers["X-Vercel-Project-ID"] = process.env.VERCEL_PROJECT_ID;
3941
- }
3942
- break;
3943
- case "cloudflare":
3944
- if (process.env.CLOUDFLARE_API_TOKEN) {
3945
- headers["X-Cloudflare-API-Token"] = process.env.CLOUDFLARE_API_TOKEN;
3946
- }
3947
- if (process.env.CLOUDFLARE_ACCOUNT_ID) {
3948
- headers["X-Cloudflare-Account-ID"] = process.env.CLOUDFLARE_ACCOUNT_ID;
3949
- }
3950
- break;
3951
- case "codesandbox":
3952
- if (process.env.CSB_API_KEY) {
3953
- headers["X-CodeSandbox-API-Key"] = process.env.CSB_API_KEY;
3954
- }
3955
- break;
3956
- case "blaxel":
3957
- if (process.env.BL_API_KEY) {
3958
- headers["X-Blaxel-API-Key"] = process.env.BL_API_KEY;
3959
- }
3960
- if (process.env.BL_WORKSPACE) {
3961
- headers["X-Blaxel-Workspace"] = process.env.BL_WORKSPACE;
3962
- }
3963
- break;
3964
- case "namespace":
3965
- if (process.env.NSC_TOKEN) {
3966
- headers["X-Namespace-Token"] = process.env.NSC_TOKEN;
3967
- }
3968
- break;
3969
- case "hopx":
3970
- if (process.env.HOPX_API_KEY) {
3971
- headers["X-HOPX-API-Key"] = process.env.HOPX_API_KEY;
3972
- }
3973
- break;
3974
- case "render":
3975
- if (process.env.RENDER_API_KEY) {
3976
- headers["X-Render-API-Key"] = process.env.RENDER_API_KEY;
3977
- }
3978
- if (process.env.RENDER_OWNER_ID) {
3979
- headers["X-Render-Owner-ID"] = process.env.RENDER_OWNER_ID;
3980
- }
3981
- break;
3982
- case "beam":
3983
- if (process.env.BEAM_TOKEN) {
3984
- headers["X-Beam-Token"] = process.env.BEAM_TOKEN;
3985
- }
3986
- if (process.env.BEAM_WORKSPACE_ID) {
3987
- headers["X-Beam-Workspace-Id"] = process.env.BEAM_WORKSPACE_ID;
3988
- }
3989
- break;
3990
- case "sprites":
3991
- if (process.env.SPRITES_TOKEN) {
3992
- headers["X-Sprites-Token"] = process.env.SPRITES_TOKEN;
3993
- }
3994
- break;
3995
- case "just-bash":
3996
- break;
3997
- case "secure-exec":
3998
- break;
3999
- case "upstash":
4000
- if (process.env.UPSTASH_BOX_API_KEY) {
4001
- headers["X-Upstash-Box-API-Key"] = process.env.UPSTASH_BOX_API_KEY;
4002
- }
4003
- break;
4004
- }
4005
- return headers;
3576
+ // src/compute.ts
3577
+ function isProviderLike(value) {
3578
+ if (!value || typeof value !== "object") return false;
3579
+ const candidate = value;
3580
+ const sandbox = candidate.sandbox;
3581
+ return !!(sandbox && typeof sandbox.create === "function" && typeof sandbox.getById === "function" && typeof sandbox.destroy === "function");
4006
3582
  }
4007
- function autoConfigureCompute() {
4008
- if (!isGatewayModeEnabled()) {
4009
- return null;
4010
- }
4011
- const provider = detectProvider();
4012
- if (!provider) {
4013
- const detectionResults = PROVIDER_PRIORITY.map((p) => getProviderEnvStatus(p));
4014
- const statusLines = detectionResults.map((result) => {
4015
- const status = result.isComplete ? "\u2705" : result.present.length > 0 ? "\u26A0\uFE0F " : "\u274C";
4016
- const ratio = `${result.present.length}/${result.present.length + result.missing.length}`;
4017
- let line = ` ${status} ${result.provider.padEnd(12)} ${ratio} credentials`;
4018
- if (result.present.length > 0 && result.missing.length > 0) {
4019
- line += ` (missing: ${result.missing.join(", ")})`;
4020
- }
4021
- return line;
4022
- });
4023
- throw new Error(
4024
- `COMPUTESDK_API_KEY is set but no provider detected.
4025
-
4026
- Provider detection results:
4027
- ` + statusLines.join("\n") + `
4028
-
4029
- To fix this, set one of the following:
4030
-
4031
- E2B: export E2B_API_KEY=xxx
4032
- Railway: export RAILWAY_API_KEY=xxx RAILWAY_PROJECT_ID=xxx RAILWAY_ENVIRONMENT_ID=xxx
4033
- Daytona: export DAYTONA_API_KEY=xxx
4034
- Modal: export MODAL_TOKEN_ID=xxx MODAL_TOKEN_SECRET=xxx
4035
- Runloop: export RUNLOOP_API_KEY=xxx
4036
- Vercel: export VERCEL_TOKEN=xxx VERCEL_TEAM_ID=xxx VERCEL_PROJECT_ID=xxx
4037
- Cloudflare: export CLOUDFLARE_API_TOKEN=xxx CLOUDFLARE_ACCOUNT_ID=xxx
4038
- CodeSandbox: export CSB_API_KEY=xxx
4039
- Blaxel: export BL_API_KEY=xxx BL_WORKSPACE=xxx
4040
- Namespace: export NSC_TOKEN=xxx
4041
- HopX: export HOPX_API_KEY=xxx
4042
- Render: export RENDER_API_KEY=xxx RENDER_OWNER_ID=xxx
4043
- Beam: export BEAM_TOKEN=xxx BEAM_WORKSPACE_ID=xxx
4044
- Sprites: export SPRITES_TOKEN=xxx
4045
- Upstash: export UPSTASH_BOX_API_KEY=xxx
4046
- just-bash: (no credentials needed - local sandbox)
4047
- secure-exec: (no credentials needed - local sandbox)
4048
-
4049
- Or set COMPUTESDK_PROVIDER to specify explicitly:
4050
- export COMPUTESDK_PROVIDER=<provider>
4051
-
4052
- Docs: https://computesdk.com/docs/quickstart`
4053
- );
4054
- }
4055
- const gatewayUrl = process.env.COMPUTESDK_TRIBUTARY_URL || TRIBUTARY_URL;
4056
- const computesdkApiKey = process.env.COMPUTESDK_API_KEY;
4057
- const providerHeaders = getProviderHeaders(provider);
4058
- try {
4059
- new URL(gatewayUrl);
4060
- } catch (error) {
4061
- throw new Error(
4062
- `Invalid gateway URL: "${gatewayUrl}"
4063
-
4064
- The URL must be a valid HTTP/HTTPS URL.
4065
- Check your COMPUTESDK_TRIBUTARY_URL environment variable.`
4066
- );
4067
- }
4068
- if (process.env.COMPUTESDK_DEBUG) {
4069
- console.log(`\u2728 ComputeSDK: Auto-detected ${provider} provider`);
4070
- console.log(`\u{1F310} Gateway: ${gatewayUrl}`);
4071
- console.log(`\u{1F511} Provider headers:`, Object.keys(providerHeaders).join(", "));
4072
- }
4073
- const config = {
4074
- apiKey: computesdkApiKey,
4075
- gatewayUrl,
4076
- provider,
4077
- providerHeaders
4078
- };
4079
- return config;
3583
+ function getProviderLabel(provider, index) {
3584
+ return provider.name || `provider-${index + 1}`;
4080
3585
  }
4081
-
4082
- // src/explicit-config.ts
4083
- function buildProviderHeaders2(config) {
4084
- const headers = {};
4085
- const provider = config.provider;
4086
- const headerMap = PROVIDER_HEADERS[provider];
4087
- const providerConfig = config[provider];
4088
- if (!providerConfig || !headerMap) return headers;
4089
- for (const [configKey, headerName] of Object.entries(headerMap)) {
4090
- const value = providerConfig[configKey];
4091
- if (value) {
4092
- headers[headerName] = value;
4093
- }
3586
+ function getProviderErrorDetail(error) {
3587
+ if (error instanceof Error) {
3588
+ return error.message;
4094
3589
  }
4095
- return headers;
3590
+ return String(error);
4096
3591
  }
4097
- function validateProviderConfig(config) {
4098
- const provider = config.provider;
4099
- const authOptions = PROVIDER_AUTH[provider];
4100
- const providerConfig = config[provider];
4101
- const dashboardUrl = PROVIDER_DASHBOARD_URLS[provider];
4102
- if (!authOptions) {
4103
- throw new Error(`Unknown provider: ${provider}`);
4104
- }
4105
- for (const option of authOptions) {
4106
- const allPresent = option.every((envVar) => {
4107
- const configField = envVarToConfigField(provider, envVar);
4108
- return providerConfig?.[configField];
4109
- });
4110
- if (allPresent) return;
3592
+ function resolveProviders(config) {
3593
+ const candidates = [];
3594
+ if (config.provider) {
3595
+ candidates.push(config.provider);
3596
+ }
3597
+ if (Array.isArray(config.providers)) {
3598
+ candidates.push(...config.providers);
3599
+ }
3600
+ const providers = [];
3601
+ const seen = /* @__PURE__ */ new Set();
3602
+ const seenNames = /* @__PURE__ */ new Set();
3603
+ for (const candidate of candidates) {
3604
+ if (!isProviderLike(candidate)) continue;
3605
+ if (seen.has(candidate)) continue;
3606
+ const name = candidate.name;
3607
+ if (name && seenNames.has(name)) continue;
3608
+ providers.push(candidate);
3609
+ seen.add(candidate);
3610
+ if (name) {
3611
+ seenNames.add(name);
3612
+ }
3613
+ }
3614
+ if (providers.length > 0) {
3615
+ return providers;
4111
3616
  }
4112
- const configExample = buildConfigExample(provider, authOptions);
4113
3617
  throw new Error(
4114
- `Missing ${provider} configuration. When using provider: '${provider}', you must provide:
4115
- ${configExample}
4116
-
4117
- Get your credentials at: ${dashboardUrl}`
4118
- );
4119
- }
4120
- function envVarToConfigField(provider, envVar) {
4121
- return PROVIDER_ENV_MAP[provider]?.[envVar] ?? envVar.toLowerCase();
4122
- }
4123
- function buildConfigExample(provider, authOptions) {
4124
- if (authOptions.length === 1) {
4125
- const fields = authOptions[0].map((envVar) => {
4126
- const field = envVarToConfigField(provider, envVar);
4127
- return `${field}: '...'`;
4128
- });
4129
- return ` ${provider}: { ${fields.join(", ")} }`;
4130
- }
4131
- const options = authOptions.map((option, i) => {
4132
- const fields = option.map((envVar) => {
4133
- const field = envVarToConfigField(provider, envVar);
4134
- return `${field}: '...'`;
4135
- });
4136
- return ` Option ${i + 1}:
4137
- ${provider}: { ${fields.join(", ")} }`;
4138
- });
4139
- return options.join("\n\n");
4140
- }
4141
- function createConfigFromExplicit(config) {
4142
- const computesdkApiKey = config.computesdkApiKey || config.apiKey;
4143
- if (!computesdkApiKey) {
4144
- throw new Error(
4145
- `Missing ComputeSDK API key. Set 'computesdkApiKey' in your config.
4146
-
4147
- Example:
4148
- compute.setConfig({
4149
- provider: 'e2b',
4150
- computesdkApiKey: process.env.COMPUTESDK_API_KEY,
4151
- e2b: { apiKey: process.env.E2B_API_KEY }
4152
- })
4153
-
4154
- Get your API key at: https://computesdk.com/dashboard`
4155
- );
4156
- }
4157
- validateProviderConfig(config);
4158
- const providerHeaders = buildProviderHeaders2(config);
4159
- return {
4160
- apiKey: computesdkApiKey,
4161
- gatewayUrl: config.gatewayUrl || process.env.COMPUTESDK_TRIBUTARY_URL || TRIBUTARY_URL,
4162
- provider: config.provider,
4163
- providerHeaders,
4164
- requestTimeoutMs: config.requestTimeoutMs,
4165
- WebSocket: config.WebSocket
4166
- };
4167
- }
4168
-
4169
- // src/compute-daemon/lifecycle.ts
4170
- async function waitForComputeReady(client, options = {}) {
4171
- const maxRetries = options.maxRetries ?? 30;
4172
- const initialDelayMs = options.initialDelayMs ?? 500;
4173
- const maxDelayMs = options.maxDelayMs ?? 5e3;
4174
- const backoffFactor = options.backoffFactor ?? 1.5;
4175
- let lastError = null;
4176
- let currentDelay = initialDelayMs;
4177
- for (let i = 0; i < maxRetries; i++) {
4178
- try {
4179
- await client.health();
4180
- if (process.env.COMPUTESDK_DEBUG) {
4181
- console.log(`[Lifecycle] Sandbox ready after ${i + 1} attempt${i === 0 ? "" : "s"}`);
4182
- }
4183
- return;
4184
- } catch (error) {
4185
- lastError = error instanceof Error ? error : new Error(String(error));
4186
- if (i === maxRetries - 1) {
4187
- throw new Error(
4188
- `Sandbox failed to become ready after ${maxRetries} attempts.
4189
- Last error: ${lastError.message}
4190
-
4191
- Possible causes:
4192
- 1. Sandbox failed to start (check provider dashboard for errors)
4193
- 2. Network connectivity issues between your app and the sandbox
4194
- 3. Sandbox is taking longer than expected to initialize
4195
- 4. Invalid sandbox URL or authentication credentials
4196
-
4197
- Troubleshooting:
4198
- - Check sandbox logs in your provider dashboard
4199
- - Verify your network connection
4200
- - Try increasing maxRetries if initialization is slow
4201
- - Enable debug mode: export COMPUTESDK_DEBUG=1`
4202
- );
4203
- }
4204
- await new Promise((resolve) => setTimeout(resolve, currentDelay));
4205
- currentDelay = Math.min(currentDelay * backoffFactor, maxDelayMs);
4206
- }
4207
- }
4208
- }
4209
-
4210
- // src/compute.ts
4211
- async function tributaryFetch(url, config, options = {}) {
4212
- const timeout = config.requestTimeoutMs ?? 3e4;
4213
- const controller = new AbortController();
4214
- const timeoutId = setTimeout(() => controller.abort(), timeout);
4215
- try {
4216
- const response = await fetch(url, {
4217
- ...options,
4218
- signal: controller.signal,
4219
- headers: {
4220
- "Content-Type": "application/json",
4221
- "X-ComputeSDK-API-Key": config.apiKey,
4222
- "X-Provider": config.provider,
4223
- ...config.providerHeaders,
4224
- ...options.headers
4225
- }
4226
- });
4227
- clearTimeout(timeoutId);
4228
- if (!response.ok) {
4229
- if (response.status === 404) {
4230
- return { success: false };
4231
- }
4232
- const errorText = await response.text().catch(() => response.statusText);
4233
- let errorMessage = `Gateway API error: ${errorText}`;
4234
- if (response.status === 401) {
4235
- errorMessage = `Invalid ComputeSDK API key. Check your COMPUTESDK_API_KEY environment variable.`;
4236
- } else if (response.status === 403) {
4237
- errorMessage = `Access forbidden. Your API key may not have permission to use provider "${config.provider}".`;
4238
- }
4239
- throw new Error(errorMessage);
4240
- }
4241
- return await response.json();
4242
- } catch (error) {
4243
- clearTimeout(timeoutId);
4244
- if (error instanceof Error && error.name === "AbortError") {
4245
- throw new Error(`Request timed out after ${timeout}ms`);
4246
- }
4247
- throw error;
4248
- }
4249
- }
4250
- async function waitForSandboxStatus(config, endpoint, body, options = {}) {
4251
- const maxWaitMs = options.maxWaitMs ?? 6e4;
4252
- const initialDelayMs = 500;
4253
- const maxDelayMs = 2e3;
4254
- const backoffFactor = 1.5;
4255
- const startTime = Date.now();
4256
- let currentDelay = initialDelayMs;
4257
- while (Date.now() - startTime < maxWaitMs) {
4258
- const result = await tributaryFetch(endpoint, config, {
4259
- method: "POST",
4260
- body: JSON.stringify(body)
4261
- });
4262
- if (!result.success || !result.data) {
4263
- return result;
4264
- }
4265
- if (result.data.status !== "creating") {
4266
- return result;
4267
- }
4268
- if (process.env.COMPUTESDK_DEBUG) {
4269
- console.log(`[Compute] Sandbox still creating, waiting ${currentDelay}ms...`);
4270
- }
4271
- await new Promise((resolve) => setTimeout(resolve, currentDelay));
4272
- currentDelay = Math.min(currentDelay * backoffFactor, maxDelayMs);
4273
- }
4274
- throw new Error(
4275
- `Sandbox is still being created after ${maxWaitMs}ms. This may indicate the sandbox failed to start. Check your provider dashboard.`
3618
+ "No provider instance configured.\n\nConfigure compute with provider instances:\n\n compute.setConfig({ providers: [e2b({...}), modal({...})] })\n // or: compute.setConfig({ provider: e2b({...}) })"
4276
3619
  );
4277
3620
  }
4278
3621
  var ComputeManager = class {
4279
3622
  constructor() {
4280
- this.config = null;
4281
- this.autoConfigured = false;
3623
+ this.providers = [];
3624
+ this.providerStrategy = "priority";
3625
+ this.fallbackOnError = true;
3626
+ this.roundRobinCursor = 0;
3627
+ this.sandboxProviders = /* @__PURE__ */ new Map();
3628
+ this.snapshotProviders = /* @__PURE__ */ new Map();
4282
3629
  this.sandbox = {
4283
- /**
4284
- * Create a new sandbox
4285
- *
4286
- * @example
4287
- * ```typescript
4288
- * const sandbox = await compute.sandbox.create({
4289
- * directory: '/custom/path',
4290
- * overlays: [
4291
- * {
4292
- * source: '/templates/nextjs',
4293
- * target: 'app',
4294
- * strategy: 'smart',
4295
- * },
4296
- * ],
4297
- * servers: [
4298
- * {
4299
- * slug: 'web',
4300
- * start: 'npm run dev',
4301
- * path: '/app',
4302
- * },
4303
- * ],
4304
- * });
4305
- * ```
4306
- */
4307
3630
  create: async (options) => {
4308
- const config = this.getGatewayConfig();
4309
- const result = await tributaryFetch(`${config.gatewayUrl}/v1/sandboxes`, config, {
4310
- method: "POST",
4311
- body: JSON.stringify(options || {})
4312
- });
4313
- if (!result.success || !result.data) {
4314
- throw new Error(`Gateway returned invalid response`);
4315
- }
4316
- const { sandboxId, url, token, provider, metadata, name, namespace, overlays, servers } = result.data;
4317
- const sandbox = new Sandbox({
4318
- sandboxUrl: url,
4319
- sandboxId,
4320
- provider,
4321
- token: token || config.apiKey,
4322
- metadata: {
4323
- ...metadata,
4324
- ...name && { name },
4325
- ...namespace && { namespace },
4326
- ...overlays && { overlays },
4327
- ...servers && { servers }
4328
- },
4329
- WebSocket: config.WebSocket || globalThis.WebSocket,
4330
- destroyHandler: async () => {
4331
- await tributaryFetch(`${config.gatewayUrl}/v1/sandboxes/${sandboxId}`, config, {
4332
- method: "DELETE"
4333
- });
4334
- }
4335
- });
4336
- await waitForComputeReady(sandbox);
4337
- return sandbox;
3631
+ return this.createWithFallback(options);
4338
3632
  },
4339
- /**
4340
- * Get an existing sandbox by ID
4341
- */
4342
3633
  getById: async (sandboxId) => {
4343
- const config = this.getGatewayConfig();
4344
- const result = await tributaryFetch(`${config.gatewayUrl}/v1/sandboxes/${sandboxId}`, config);
4345
- if (!result.success || !result.data) {
4346
- return null;
4347
- }
4348
- const { url, token, provider, metadata } = result.data;
4349
- const sandbox = new Sandbox({
4350
- sandboxUrl: url,
4351
- sandboxId,
4352
- provider,
4353
- token: token || config.apiKey,
4354
- metadata,
4355
- WebSocket: config.WebSocket || globalThis.WebSocket,
4356
- destroyHandler: async () => {
4357
- await tributaryFetch(`${config.gatewayUrl}/v1/sandboxes/${sandboxId}`, config, {
4358
- method: "DELETE"
4359
- });
3634
+ for (const provider of this.getByIdCandidates(sandboxId)) {
3635
+ const sandbox = await provider.sandbox.getById(sandboxId);
3636
+ if (sandbox) {
3637
+ this.registerSandboxProvider(sandbox, provider);
3638
+ return sandbox;
4360
3639
  }
4361
- });
4362
- await waitForComputeReady(sandbox);
4363
- return sandbox;
3640
+ }
3641
+ this.sandboxProviders.delete(sandboxId);
3642
+ return null;
4364
3643
  },
4365
- /**
4366
- * List all active sandboxes
4367
- */
4368
3644
  list: async () => {
4369
- throw new Error(
4370
- "The gateway does not support listing sandboxes. Use getById() with a known sandbox ID instead."
4371
- );
3645
+ const all = [];
3646
+ for (const provider of this.getProviders()) {
3647
+ if (!provider.sandbox.list) {
3648
+ continue;
3649
+ }
3650
+ const sandboxes = await provider.sandbox.list();
3651
+ for (const sandbox of sandboxes) {
3652
+ this.registerSandboxProvider(sandbox, provider);
3653
+ }
3654
+ all.push(...sandboxes);
3655
+ }
3656
+ return all;
4372
3657
  },
4373
- /**
4374
- * Destroy a sandbox
4375
- */
4376
3658
  destroy: async (sandboxId) => {
4377
- const config = this.getGatewayConfig();
4378
- await tributaryFetch(`${config.gatewayUrl}/v1/sandboxes/${sandboxId}`, config, {
4379
- method: "DELETE"
4380
- });
4381
- },
4382
- /**
4383
- * Find existing or create new sandbox by (namespace, name)
4384
- */
4385
- findOrCreate: async (options) => {
4386
- const config = this.getGatewayConfig();
4387
- const { name, namespace, ...restOptions } = options;
4388
- const result = await waitForSandboxStatus(
4389
- config,
4390
- `${config.gatewayUrl}/v1/sandboxes/find-or-create`,
4391
- {
4392
- namespace: namespace || "default",
4393
- name,
4394
- ...restOptions
3659
+ const candidates = this.getByIdCandidates(sandboxId);
3660
+ const errors = [];
3661
+ for (const [index, provider] of candidates.entries()) {
3662
+ try {
3663
+ await provider.sandbox.destroy(sandboxId);
3664
+ this.sandboxProviders.delete(sandboxId);
3665
+ return;
3666
+ } catch (error) {
3667
+ errors.push(`${getProviderLabel(provider, index)}: ${getProviderErrorDetail(error)}`);
4395
3668
  }
4396
- );
4397
- if (!result.success || !result.data) {
4398
- throw new Error(`Gateway returned invalid response`);
4399
3669
  }
4400
- const { sandboxId, url, token, provider, metadata } = result.data;
4401
- const sandbox = new Sandbox({
4402
- sandboxUrl: url,
4403
- sandboxId,
4404
- provider,
4405
- token: token || config.apiKey,
4406
- metadata: {
4407
- ...metadata,
4408
- name: result.data.name,
4409
- namespace: result.data.namespace
4410
- },
4411
- WebSocket: config.WebSocket || globalThis.WebSocket,
4412
- destroyHandler: async () => {
4413
- await tributaryFetch(`${config.gatewayUrl}/v1/sandboxes/${sandboxId}`, config, {
4414
- method: "DELETE"
4415
- });
4416
- }
4417
- });
4418
- await waitForComputeReady(sandbox);
4419
- return sandbox;
3670
+ throw new Error(
3671
+ `Failed to destroy sandbox "${sandboxId}" across ${candidates.length} provider(s).
3672
+ ` + errors.map((error) => `- ${error}`).join("\n")
3673
+ );
3674
+ },
3675
+ findOrCreate: async (options) => {
3676
+ return this.findOrCreateWithFallback(options);
4420
3677
  },
4421
- /**
4422
- * Find existing sandbox by (namespace, name) without creating
4423
- */
4424
3678
  find: async (options) => {
4425
- const config = this.getGatewayConfig();
4426
- const result = await waitForSandboxStatus(
4427
- config,
4428
- `${config.gatewayUrl}/v1/sandboxes/find`,
4429
- {
4430
- namespace: options.namespace || "default",
4431
- name: options.name
3679
+ const preferredProviderName = options.provider;
3680
+ const { provider: _providerName, ...providerOptions } = options;
3681
+ const candidates = this.getCreateCandidates(preferredProviderName);
3682
+ for (const provider of candidates) {
3683
+ if (!provider.sandbox.find) {
3684
+ continue;
4432
3685
  }
4433
- );
4434
- if (!result.success || !result.data) {
4435
- return null;
4436
- }
4437
- const { sandboxId, url, token, provider, metadata, name, namespace } = result.data;
4438
- const sandbox = new Sandbox({
4439
- sandboxUrl: url,
4440
- sandboxId,
4441
- provider,
4442
- token: token || config.apiKey,
4443
- metadata: {
4444
- ...metadata,
4445
- name,
4446
- namespace
4447
- },
4448
- WebSocket: config.WebSocket || globalThis.WebSocket,
4449
- destroyHandler: async () => {
4450
- await tributaryFetch(`${config.gatewayUrl}/v1/sandboxes/${sandboxId}`, config, {
4451
- method: "DELETE"
4452
- });
3686
+ const sandbox = await provider.sandbox.find(providerOptions);
3687
+ if (sandbox) {
3688
+ this.registerSandboxProvider(sandbox, provider);
3689
+ return sandbox;
4453
3690
  }
4454
- });
4455
- await waitForComputeReady(sandbox);
4456
- return sandbox;
3691
+ }
3692
+ return null;
4457
3693
  },
4458
- /**
4459
- * Extend sandbox timeout/expiration
4460
- */
4461
3694
  extendTimeout: async (sandboxId, options) => {
4462
- const config = this.getGatewayConfig();
4463
- const duration = options?.duration ?? 9e5;
4464
- await tributaryFetch(`${config.gatewayUrl}/v1/sandboxes/${sandboxId}/extend`, config, {
4465
- method: "POST",
4466
- body: JSON.stringify({ duration })
4467
- });
3695
+ const candidates = this.getByIdCandidates(sandboxId);
3696
+ const errors = [];
3697
+ for (const [index, provider] of candidates.entries()) {
3698
+ if (!provider.sandbox.extendTimeout) {
3699
+ errors.push(`${getProviderLabel(provider, index)}: extendTimeout() not supported`);
3700
+ continue;
3701
+ }
3702
+ try {
3703
+ await provider.sandbox.extendTimeout(sandboxId, options);
3704
+ this.sandboxProviders.set(sandboxId, provider);
3705
+ return;
3706
+ } catch (error) {
3707
+ errors.push(`${getProviderLabel(provider, index)}: ${getProviderErrorDetail(error)}`);
3708
+ }
3709
+ }
3710
+ throw new Error(
3711
+ `Failed to extend timeout for sandbox "${sandboxId}" across ${candidates.length} provider(s).
3712
+ ` + errors.map((error) => `- ${error}`).join("\n")
3713
+ );
4468
3714
  }
4469
3715
  };
4470
3716
  this.snapshot = {
4471
- /**
4472
- * Create a snapshot from a running sandbox
4473
- *
4474
- * @param sandboxId ID of the sandbox to snapshot
4475
- * @param options Snapshot options (name, metadata)
4476
- */
4477
3717
  create: async (sandboxId, options) => {
4478
- const config = this.getGatewayConfig();
4479
- const result = await tributaryFetch(`${config.gatewayUrl}/v1/snapshots`, config, {
4480
- method: "POST",
4481
- body: JSON.stringify({ sandboxId, ...options })
4482
- });
4483
- if (!result.success || !result.data) {
4484
- throw new Error(`Gateway returned invalid response`);
3718
+ const preferredProviderName = options?.provider;
3719
+ const { provider: _providerName, ...providerOptions } = options || {};
3720
+ const candidates = this.getSnapshotCreateCandidates(sandboxId, preferredProviderName);
3721
+ const errors = [];
3722
+ for (const [index, provider] of candidates.entries()) {
3723
+ if (!provider.snapshot) {
3724
+ errors.push(`${getProviderLabel(provider, index)}: snapshots not supported`);
3725
+ continue;
3726
+ }
3727
+ try {
3728
+ const snapshot = await provider.snapshot.create(sandboxId, providerOptions);
3729
+ this.snapshotProviders.set(snapshot.id, provider);
3730
+ return {
3731
+ ...snapshot,
3732
+ createdAt: new Date(snapshot.createdAt)
3733
+ };
3734
+ } catch (error) {
3735
+ errors.push(`${getProviderLabel(provider, index)}: ${getProviderErrorDetail(error)}`);
3736
+ }
4485
3737
  }
4486
- return {
4487
- ...result.data,
4488
- createdAt: new Date(result.data.createdAt)
4489
- };
3738
+ throw new Error(
3739
+ `Failed to create snapshot for sandbox "${sandboxId}" across ${candidates.length} provider(s).
3740
+ ` + errors.map((error) => `- ${error}`).join("\n")
3741
+ );
4490
3742
  },
4491
- /**
4492
- * List all snapshots
4493
- */
4494
3743
  list: async () => {
4495
- const config = this.getGatewayConfig();
4496
- const result = await tributaryFetch(`${config.gatewayUrl}/v1/snapshots`, config);
4497
- if (!result.success || !result.data) {
4498
- return [];
3744
+ const snapshots = [];
3745
+ for (const provider of this.getProviders()) {
3746
+ if (!provider.snapshot) continue;
3747
+ const listed = await provider.snapshot.list();
3748
+ for (const snapshot of listed) {
3749
+ this.snapshotProviders.set(snapshot.id, provider);
3750
+ snapshots.push({
3751
+ ...snapshot,
3752
+ createdAt: new Date(snapshot.createdAt)
3753
+ });
3754
+ }
4499
3755
  }
4500
- return result.data.map((s) => ({
4501
- ...s,
4502
- createdAt: new Date(s.createdAt)
4503
- }));
3756
+ return snapshots;
4504
3757
  },
4505
- /**
4506
- * Delete a snapshot
4507
- */
4508
3758
  delete: async (snapshotId) => {
4509
- const config = this.getGatewayConfig();
4510
- await tributaryFetch(`${config.gatewayUrl}/v1/snapshots/${snapshotId}`, config, {
4511
- method: "DELETE"
4512
- });
3759
+ const candidates = this.getSnapshotDeleteCandidates(snapshotId);
3760
+ const errors = [];
3761
+ for (const [index, provider] of candidates.entries()) {
3762
+ if (!provider.snapshot) continue;
3763
+ try {
3764
+ await provider.snapshot.delete(snapshotId);
3765
+ this.snapshotProviders.delete(snapshotId);
3766
+ return;
3767
+ } catch (error) {
3768
+ errors.push(`${getProviderLabel(provider, index)}: ${getProviderErrorDetail(error)}`);
3769
+ }
3770
+ }
3771
+ throw new Error(
3772
+ `Failed to delete snapshot "${snapshotId}" across ${candidates.length} provider(s).
3773
+ ` + errors.map((error) => `- ${error}`).join("\n")
3774
+ );
4513
3775
  }
4514
3776
  };
4515
3777
  }
4516
- /**
4517
- * Lazy auto-configure from environment if not explicitly configured
4518
- */
4519
- ensureConfigured() {
4520
- if (this.config) return;
4521
- if (this.autoConfigured) return;
4522
- const config = autoConfigureCompute();
4523
- this.autoConfigured = true;
4524
- if (config) {
4525
- this.config = config;
4526
- }
4527
- }
4528
- /**
4529
- * Get gateway config, throwing if not configured
4530
- */
4531
- getGatewayConfig() {
4532
- this.ensureConfigured();
4533
- if (!this.config) {
3778
+ getProviders() {
3779
+ if (this.providers.length === 0) {
4534
3780
  throw new Error(
4535
- `No ComputeSDK configuration found.
4536
-
4537
- Options:
4538
- 1. Zero-config: Set COMPUTESDK_API_KEY and provider credentials (e.g., E2B_API_KEY)
4539
- 2. Explicit: Call compute.setConfig({ provider: "e2b", computesdkApiKey: "...", e2b: { apiKey: "..." } })
4540
- 3. Use provider directly: import { e2b } from '@computesdk/e2b'
4541
-
4542
- Docs: https://computesdk.com/docs/quickstart`
3781
+ "No compute provider configured.\n\nOptions:\n1. Configure providers: compute.setConfig({ providers: [e2b({...}), modal({...})] })\n2. Configure a single provider: compute.setConfig({ provider: e2b({...}) })\n3. Use provider directly: const sdk = e2b({...}); await sdk.sandbox.create()"
4543
3782
  );
4544
3783
  }
4545
- return this.config;
3784
+ return this.providers;
3785
+ }
3786
+ getProviderByName(name) {
3787
+ const provider = this.getProviders().find((p) => p.name === name);
3788
+ if (!provider) {
3789
+ const names = this.getProviders().map((p, i) => getProviderLabel(p, i)).join(", ");
3790
+ throw new Error(`Provider "${name}" is not configured. Configured providers: ${names || "(none)"}.`);
3791
+ }
3792
+ return provider;
3793
+ }
3794
+ registerSandboxProvider(sandbox, provider) {
3795
+ const sandboxId = sandbox?.sandboxId;
3796
+ if (sandboxId) {
3797
+ this.sandboxProviders.set(sandboxId, provider);
3798
+ }
3799
+ }
3800
+ getCreateCandidates(preferredProviderName) {
3801
+ const providers = this.getProviders();
3802
+ if (preferredProviderName) {
3803
+ return [this.getProviderByName(preferredProviderName)];
3804
+ }
3805
+ if (providers.length <= 1 || this.providerStrategy === "priority") {
3806
+ return [...providers];
3807
+ }
3808
+ const start = this.roundRobinCursor % providers.length;
3809
+ this.roundRobinCursor = (this.roundRobinCursor + 1) % providers.length;
3810
+ return [
3811
+ ...providers.slice(start),
3812
+ ...providers.slice(0, start)
3813
+ ];
3814
+ }
3815
+ getByIdCandidates(sandboxId) {
3816
+ const known = this.sandboxProviders.get(sandboxId);
3817
+ if (!known) return this.getProviders();
3818
+ const providers = this.getProviders();
3819
+ return [known, ...providers.filter((p) => p !== known)];
3820
+ }
3821
+ getSnapshotDeleteCandidates(snapshotId) {
3822
+ const known = this.snapshotProviders.get(snapshotId);
3823
+ const providers = this.getProviders().filter((p) => !!p.snapshot);
3824
+ if (!known) return providers;
3825
+ return [known, ...providers.filter((p) => p !== known)];
3826
+ }
3827
+ getSnapshotCreateCandidates(sandboxId, preferredProviderName) {
3828
+ if (preferredProviderName) {
3829
+ return [this.getProviderByName(preferredProviderName)];
3830
+ }
3831
+ const known = this.sandboxProviders.get(sandboxId);
3832
+ const providers = this.getProviders().filter((p) => !!p.snapshot);
3833
+ if (known && known.snapshot) {
3834
+ return [known, ...providers.filter((p) => p !== known)];
3835
+ }
3836
+ return providers;
3837
+ }
3838
+ async createWithFallback(options) {
3839
+ const preferredProviderName = options?.provider;
3840
+ const { provider: _providerName, ...providerOptions } = options || {};
3841
+ const candidates = this.getCreateCandidates(preferredProviderName);
3842
+ const canFallback = this.fallbackOnError && !preferredProviderName;
3843
+ const errors = [];
3844
+ for (const [index, provider] of candidates.entries()) {
3845
+ try {
3846
+ const sandbox = await provider.sandbox.create(providerOptions);
3847
+ this.registerSandboxProvider(sandbox, provider);
3848
+ return sandbox;
3849
+ } catch (error) {
3850
+ errors.push(`${getProviderLabel(provider, index)}: ${getProviderErrorDetail(error)}`);
3851
+ if (!canFallback) {
3852
+ throw error;
3853
+ }
3854
+ }
3855
+ }
3856
+ throw new Error(
3857
+ `Failed to create sandbox across ${candidates.length} provider(s).
3858
+ ` + errors.map((error) => `- ${error}`).join("\n")
3859
+ );
3860
+ }
3861
+ async findOrCreateWithFallback(options) {
3862
+ const preferredProviderName = options.provider;
3863
+ const { provider: _providerName, ...providerOptions } = options;
3864
+ const candidates = this.getCreateCandidates(preferredProviderName);
3865
+ const canFallback = this.fallbackOnError && !preferredProviderName;
3866
+ const errors = [];
3867
+ for (const [index, provider] of candidates.entries()) {
3868
+ try {
3869
+ if (!provider.sandbox.findOrCreate) {
3870
+ errors.push(`${getProviderLabel(provider, index)}: findOrCreate() not supported`);
3871
+ continue;
3872
+ }
3873
+ const sandbox = await provider.sandbox.findOrCreate(providerOptions);
3874
+ this.registerSandboxProvider(sandbox, provider);
3875
+ return sandbox;
3876
+ } catch (error) {
3877
+ errors.push(`${getProviderLabel(provider, index)}: ${getProviderErrorDetail(error)}`);
3878
+ if (!canFallback) {
3879
+ throw error;
3880
+ }
3881
+ }
3882
+ }
3883
+ throw new Error(
3884
+ `Failed to findOrCreate sandbox across ${candidates.length} provider(s).
3885
+ ` + errors.map((error) => `- ${error}`).join("\n")
3886
+ );
4546
3887
  }
4547
- /**
4548
- * Explicitly configure the compute singleton
4549
- *
4550
- * @example
4551
- * ```typescript
4552
- * import { compute } from 'computesdk';
4553
- *
4554
- * compute.setConfig({
4555
- * provider: 'e2b',
4556
- * apiKey: 'computesdk_xxx',
4557
- * e2b: { apiKey: 'e2b_xxx' }
4558
- * });
4559
- *
4560
- * const sandbox = await compute.sandbox.create();
4561
- * ```
4562
- */
4563
3888
  setConfig(config) {
4564
- const gatewayConfig = createConfigFromExplicit(config);
4565
- this.config = gatewayConfig;
4566
- this.autoConfigured = false;
3889
+ this.providers = resolveProviders(config);
3890
+ this.providerStrategy = config.providerStrategy ?? "priority";
3891
+ this.fallbackOnError = config.fallbackOnError ?? true;
3892
+ this.roundRobinCursor = 0;
3893
+ this.sandboxProviders.clear();
3894
+ this.snapshotProviders.clear();
4567
3895
  }
4568
3896
  };
4569
3897
  var singletonInstance = new ComputeManager();
4570
3898
  function computeFactory(config) {
4571
- const gatewayConfig = createConfigFromExplicit(config);
4572
3899
  const manager = new ComputeManager();
4573
- manager["config"] = gatewayConfig;
3900
+ manager.setConfig(config);
4574
3901
  return manager;
4575
3902
  }
4576
3903
  var compute = new Proxy(
@@ -4592,33 +3919,15 @@ var compute = new Proxy(
4592
3919
  export {
4593
3920
  CommandExitError,
4594
3921
  FileWatcher,
4595
- Sandbox as GatewaySandbox,
4596
3922
  MessageType,
4597
- PROVIDER_AUTH,
4598
- PROVIDER_DASHBOARD_URLS,
4599
- PROVIDER_ENV_MAP,
4600
- PROVIDER_ENV_VARS,
4601
- PROVIDER_HEADERS,
4602
- PROVIDER_NAMES,
4603
- PROVIDER_PRIORITY,
4604
3923
  Sandbox,
4605
3924
  SignalService,
4606
- TRIBUTARY_URL,
4607
3925
  TerminalInstance,
4608
- autoConfigureCompute,
4609
- buildProviderHeaders,
4610
3926
  buildSetupPayload,
4611
3927
  compute,
4612
3928
  decodeBinaryMessage,
4613
- detectProvider,
4614
3929
  encodeBinaryMessage,
4615
3930
  encodeSetupPayload,
4616
- getMissingEnvVars,
4617
- getProviderConfigFromEnv,
4618
- getProviderHeaders,
4619
- isCommandExitError,
4620
- isGatewayModeEnabled,
4621
- isProviderAuthComplete,
4622
- isValidProvider
3931
+ isCommandExitError
4623
3932
  };
4624
3933
  //# sourceMappingURL=index.mjs.map