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