@getenergy/gke-sandboxes 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,260 @@
1
- # Temporary Holding Version
1
+ # GKE Sandboxes
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Give each cloud agent a Linux sandbox in your own Google Cloud project. It can run a command, write files, and wait for the user. While it waits, put the sandbox to sleep and free up the machine for another agent. When the user comes back, open the same sandbox ID to get the files back.
4
+
5
+ <picture>
6
+ <source media="(max-width: 600px)" srcset="docs/assets/running-sandbox.png">
7
+ <img src="docs/assets/running-sandbox-wide.png" width="100%" alt="Monthly compute cost for 730 running hours at 4 vCPU and 8 GB. GKE on C4D costs an estimated $7.80 per sandbox when many sandboxes split the machine costs (1×). At list price, Agent37 costs $8.80 (1.13×), Vercel Sandbox $161.18 at 10% CPU use (20.7×), Daytona $241.78 (31×), and E2B $241.78 (31×). Disk and plan fees are extra.">
8
+ </picture>
9
+
10
+ [Deploy on GKE](#try-it-in-your-own-project) · [Use the TypeScript client](#use-from-a-backend) · [Compare providers](#when-to-choose-a-managed-provider)
11
+
12
+ ## Set it up with your coding agent
13
+
14
+ Paste this into Claude Code, Cursor, Codex or another coding agent:
15
+
16
+ ```text
17
+ Set up GKE Sandboxes in my Google Cloud project.
18
+
19
+ Clone https://github.com/comp-work/gke-sandboxes and follow skills/setup-gke-sandboxes/SKILL.md step by step.
20
+ Ask me for my project ID, region and Google account before creating anything, and tell me what it will cost.
21
+ ```
22
+
23
+ The agent deploys the cluster with Terraform, runs the verifier, and shows you how to connect your backend. [Read the instructions it follows](skills/setup-gke-sandboxes/SKILL.md), or [do it by hand](#try-it-in-your-own-project).
24
+
25
+ ## Where GKE Sandboxes works well
26
+
27
+ Use it when your product runs agents for many users and each session needs its own files, tools, and processes. You choose the container image. One agent might patch a repo and run its test suite. Another might run Python over a customer’s data and save a report. Each runs in its own gVisor pod. Your backend decides who can open each sandbox.
28
+
29
+ This setup pays off when you have **many sessions to keep and only some of them are busy at once**. Active agents share the cluster’s machines. Sleeping agents leave a snapshot in Cloud Storage. A 20 GB snapshot costs about **37¢ for a month** in Iowa. Putting an agent to sleep frees CPU and memory immediately after its pod is removed. Your compute bill falls when the cluster can use fewer machines. [Storage rates and comparison](#storage-for-a-20-gb-sleeping-sandbox)
30
+
31
+ ## Running cost at 4 vCPU and 8 GB
32
+
33
+ For **730 running hours**, we estimate **$7.80 per sandbox** when many sandboxes share GKE machines at on-demand rates. Agent37 standard lists **$8.80** for compute. Daytona and E2B each list **$241.78** for 4 vCPU and 8 GiB, about **31×** the GKE estimate. [Agent37 pricing](https://www.agent37.com/pricing) · [Daytona pricing](https://www.daytona.io/pricing) · [E2B pricing](https://e2b.dev/pricing)
34
+
35
+ **Vercel Sandbox costs $161.18** for the same 730 running hours at 10% average CPU use, the assumption Vercel uses in its pricing examples. At Pro list rates in its default region (iad1), Vercel bills $0.0212 per GB-hour for memory and $0.128 per active CPU-hour. The 8 GB alone costs $123.81 over 730 hours, even when the code is waiting. Those hours span sessions because Pro allows up to 24 hours per session. [Vercel Sandbox pricing](https://vercel.com/docs/sandbox/pricing)
36
+
37
+ The $7.80 figure is for `c4d-highmem-16` machines, about $709 a month each in Iowa, holding **128 sandboxes** apiece. It adds 40% for spare machines, node disks, system nodes, and the cluster fee. A sandbox can use up to four CPUs and spends much of its time below that limit. If every agent needs all four at once, budget for more machines. [Deploy that configuration](#deploy-on-c4d)
38
+
39
+ The quickstart’s defaults are E2 machines holding about 64 sandboxes each, which comes to about **$12 per sandbox** by the same method. The managed providers’ figures exclude disks, plan fees, credits, and discounts. On GKE you operate the cluster yourself. On E2B this configuration requires a Pro plan, and the hours can span sessions.
40
+
41
+ ## Storage for a 20 GB sleeping sandbox
42
+
43
+ <img src="docs/assets/monthly-cost.png" width="100%" alt="Storage for 20 GB retained for 730 hours. GKE snapshot about $0.37, Agent37 retained disk $1.80, Vercel Sandbox snapshot $1.60 on Pro, Daytona archived container $0, E2B paused sandbox $0 extra on Pro. Plan fees and infrastructure are excluded.">
44
+
45
+ For the same **20 billion bytes kept for 730 hours**, a GKE file snapshot in Iowa costs about **$0.37** (18.63 GiB in Cloud Storage Standard). Agent37 stops charging for compute during sleep and charges **$1.80** for a 20 GB disk. GKE machines you keep running still appear on your cluster bill. [Google Cloud Storage pricing](https://cloud.google.com/storage/pricing) · [Agent37 pricing](https://www.agent37.com/pricing)
46
+
47
+ **Vercel Sandbox charges $1.60 a month** to keep a 20 GB filesystem snapshot on Pro, at $0.08 per GB-month. For the full 730 hours, set retention to at least 31 days. The default is 30 days after last use. [Vercel Sandbox pricing](https://vercel.com/docs/sandbox/pricing) · [Snapshot retention](https://vercel.com/docs/sandbox/concepts/snapshots#snapshot-retention)
48
+
49
+ **Daytona charges $0 once a container is archived.** Its files can be restored when you start it again. If you leave it stopped instead, Daytona bills for reserved disk at $0.000108 per GiB-hour after the first 5 GiB. [Daytona billing](https://www.daytona.io/docs/billing) · [Daytona pricing](https://www.daytona.io/pricing)
50
+
51
+ **E2B charges $0 extra to keep this sandbox paused on Pro.** The $150 monthly plan includes 20 GiB of disk **per sandbox**. Its separate concurrency limit covers 100 running sandboxes, with paid options for more. Paused sandboxes can retain files and memory indefinitely. [E2B pricing](https://e2b.dev/pricing) · [E2B disk and concurrency limits](https://github.com/e2b-dev/e2b/blob/main/spec/openapi.yml) · [E2B pause and resume](https://docs.e2b.dev/sandbox/persistence)
52
+
53
+ ## Performance against Agent37
54
+
55
+ We ran the same commands on the same revision of Better Auth. **The build took 67 seconds on GKE and 100 seconds on Agent37 standard.** The GKE column is one run per test on a C4D machine with one sandbox. Agent37 publishes medians. Both used a 4 vCPU / 8 GB limit. The V8 row uses the benchmark’s current GitHub version on GKE and a pinned Phoronix profile on Agent37. [GKE benchmark script](examples/benchmark-build.sh) · [Agent37 results and benchmark code](https://www.agent37.com/benchmarks)
56
+
57
+ | Metric | GKE on C4D | Agent37 standard |
58
+ | --- | ---: | ---: |
59
+ | Compute per sandbox, 730 hours | $7.80 at scale, estimated | $8.80 list price |
60
+ | Clone the repo | 1.6 s | 8.3 s |
61
+ | Cold dependency install | 13.5 s | 24.1 s |
62
+ | Build | 67 s | 100 s |
63
+ | V8 web tooling throughput | 22.8 runs/s | 17.5 runs/s |
64
+
65
+ On the same machine packed with 95 other sandboxes, each using about 7% of a CPU as an idle agent sandbox does, the build took **81 seconds** and V8 throughput fell to **16.1 runs/s**. With four builds running at once among them, each took about **155 seconds**. Agent37’s VM tier reports a **65.9-second** median build. The 67-second result is for a sandbox alone on its machine, and the $7.80 estimate is for a packed one. We have no matching test under load on Agent37 or head-to-head speed measurements for Daytona, E2B, or Vercel. The quickstart’s default E2 machines are slower: the same build took 154 seconds alone on `e2-highmem-16`. [Agent37 benchmark](https://www.agent37.com/benchmarks)
66
+
67
+ ## Create, sleep, and wake times
68
+
69
+ Sandbox Bench tested ten managed sandbox configurations at **4 vCPU and 8 GB** from one server in Florida. Energy ran GKE separately at the same CPU and memory limits. Both start timers end when the first shell command (`true`) succeeds. For gke-sandboxes, the startup median includes all 60 requests with a two-pod pool. Managed providers report medians over 100 starts each. Snapshot medians come from 30 separate trials per configuration where measured. [Benchmark](https://aisandboxbench.com/) · [Pinned results](https://github.com/opencoredev/sandbox-bench/blob/2b179ae31e90bb3f0ff7e50994e1fb2124818a93/src/data/benchmark.same-spec.json) · [Timer code](https://github.com/opencoredev/sandbox-sdk/blob/56e60d6f42a9b11efb487b5364efc325831e976a/bench/src/v2-runner.ts)
70
+
71
+ <img src="docs/assets/sandbox-lifecycle.png" width="100%" alt="Median fresh start, snapshot save and start from snapshot for GKE and ten managed configurations. All timings are in the table below.">
72
+
73
+ <details>
74
+ <summary>Read the timings as a table</summary>
75
+
76
+ | Provider | Start fresh | Save snapshot | Start from snapshot |
77
+ | --- | ---: | ---: | ---: |
78
+ | gke-sandboxes | 1.06 s | 2.82 s | 3.54 s |
79
+ | Modal | 0.38 s | 0.94 s | 0.98 s |
80
+ | Vercel Sandbox | 0.52 s | 1.15 s | 1.12 s |
81
+ | Superserve | 0.52 s | 0.38 s | 0.55 s |
82
+ | Upstash Ephemeral Box | 0.68 s | 2.12 s | 1.13 s |
83
+ | Freestyle | 0.69 s | 0.43 s | 0.75 s |
84
+ | E2B | 0.79 s | 1.83 s | 1.12 s |
85
+ | Luxor | 1.09 s | 6.87 s | 1.88 s |
86
+ | Boat | 1.12 s | — | — |
87
+ | Daytona | 1.25 s | 7.35 s | 2.38 s |
88
+ | Upstash Box | 2.68 s | 2.14 s | 4.89 s |
89
+
90
+ </details>
91
+
92
+ Saving a snapshot times the provider’s snapshot call. Starting from it creates a new sandbox and runs a command. The saved image and its size can differ by provider. Vercel also stops the source sandbox when it snapshots. Boat had no snapshot result. The benchmark excluded an earlier batch after Daytona snapshot timeouts. [Benchmark notes](https://aisandboxbench.com/) · [Published exclusions](https://github.com/opencoredev/sandbox-bench/blob/2b179ae31e90bb3f0ff7e50994e1fb2124818a93/src/data/benchmark.same-spec.json)
93
+
94
+ <details>
95
+ <summary>Pause and resume an existing sandbox</summary>
96
+
97
+ For providers the benchmark classified as preserving running processes, it also timed the pause and resume calls separately. These medians end when each call returns. The first command after resume was timed separately. [Stage timings](https://github.com/opencoredev/sandbox-bench/blob/2b179ae31e90bb3f0ff7e50994e1fb2124818a93/src/data/traces.same-spec.json) · [Run notes](https://github.com/opencoredev/sandbox-bench/blob/2b179ae31e90bb3f0ff7e50994e1fb2124818a93/src/data/benchmark.same-spec.json)
98
+
99
+ | Provider | Runs | Pause | Resume |
100
+ | --- | ---: | ---: | ---: |
101
+ | E2B | 100 | 1.30 s | 0.36 s |
102
+ | Freestyle | 100 | 0.32 s | 0.19 s |
103
+ | Luxor | 77 | 60.53 s | 2.13 s |
104
+ | Superserve | 100 | 0.40 s | 0.22 s |
105
+ | Upstash Box | 99 | 0.84 s | 0.33 s |
106
+
107
+ </details>
108
+
109
+ **How we measured GKE.** We ran 100 fresh starts and 30 save, sleep and restore cycles from a Mac against a warm GKE node in Iowa. The node already had the Debian image. Creating a new gVisor pod and reaching its first command took 2.33 s at the median in this run, and 2.68 s over the 60 on-demand requests of the pool comparison below, which ran later the same day. Each restore reopened the sandbox in a new pod and ran `true`. The six source files from Sandbox Bench’s Vite app totaled 36,324 bytes. The median saved snapshot occupied **74.3 KiB** in Cloud Storage. Sleep, including removal of the old pod, took **4.02 s** at the median. We checked all six files after every restore. The shared benchmark used a Florida client and its own prepared images, so the network path and snapshot contents differ. [GKE measurements](docs/benchmarks/gke-lifecycle-2026-11-17.csv) · [GKE benchmark code](examples/benchmark-lifecycle.ts)
110
+
111
+ **How many sandboxes should you keep ready?** We sent one request, then two at once, alternating every six seconds. The earlier one-pod test missed once in each of the 20 two-request bursts. We replayed this traffic with the packaged client and measured from the request through its first successful shell command.
112
+
113
+ | Ready sandboxes | Requests that got a ready pod | Median start | 95th percentile |
114
+ | --- | ---: | ---: | ---: |
115
+ | 1 | 40 / 60 | 1.16 s | 3.63 s |
116
+ | 2 | 60 / 60 | 1.06 s | 1.60 s |
117
+
118
+ Each request got its own sandbox. After its first command, we checked its ID and deleted the pod. Longer agent sessions can leave less room for replacements. The quickstart creates pods on demand. To reproduce the table, run the pool benchmark with `--baselineSize 1 --poolSize 2`. [Enable a warm pool](#keep-sandboxes-ready-for-new-sessions) · [Benchmark code](examples/benchmark-warm-pool.ts) · [All 120 starts](docs/benchmarks/gke-warm-pool-sizing-2026-11-17.csv)
119
+
120
+ In the earlier test, creating a pod on demand took **2.68 s** at the median and **3.18 s** at the 95th percentile. Keeping one pod ready gave **1.32 s** and **3.50 s** respectively across all 60 requests. [Earlier measurements](docs/benchmarks/gke-warm-pool-2026-11-17.csv)
121
+
122
+ **Cost of keeping two sandboxes ready.** Together the two unused pods reserved 8 vCPU and 16 GiB. Both pool sizes fit on the same sandbox node throughout the test. An extra Iowa `e2-highmem-16` node with a 150 GiB balanced boot disk would add about $543 for 730 hours at on-demand list rates. [Google VM rates](https://cloud.google.com/products/compute/pricing/general-purpose) · [Disk rates](https://cloud.google.com/compute/disks-image-pricing)
123
+
124
+ ## When to choose a managed provider
125
+
126
+ | If you need… | What to consider |
127
+ | --- | --- |
128
+ | A handful of sandboxes and no cluster to run | Agent37 meters compute by the minute. Daytona offers pay-as-you-go compute. With GKE, you manage capacity, upgrades, and recovery, and pay for machines between jobs. [Agent37](https://www.agent37.com/pricing) · [Daytona](https://www.daytona.io/pricing) |
129
+ | A running process to pick up where it left off | E2B and Agent37 can preserve memory through sleep. This quickstart restores files. GKE supports whole-pod snapshots on compatible machines, but this client has only been verified with file restores. [GKE snapshot modes](https://docs.cloud.google.com/kubernetes-engine/docs/concepts/pod-snapshots) · [E2B](https://docs.e2b.dev/sandbox/persistence) · [Agent37](https://www.agent37.com/compare/daytona) |
130
+ | A preview URL to send to a user | Daytona ships expiring, revocable links. Agent37 offers authenticated URLs and custom domains. This setup keeps pods private. To share a preview, add a proxy that checks access to the sandbox and port. [Daytona previews](https://www.daytona.io/docs/en/preview/) · [Agent37 networking](https://www.agent37.com/) |
131
+ | GPU access or a separate VM kernel per sandbox | The quickstart runs on CPUs with gVisor. Daytona offers GPU sandboxes. E2B gives each sandbox a Firecracker microVM. [Daytona GPUs](https://www.daytona.io/pricing) · [E2B isolation](https://e2b.dev/security) |
132
+
133
+ ## Use from a backend
134
+
135
+ Install the client in your backend. It runs on Node.js 22 or later and on Bun.
136
+
137
+ ```sh
138
+ npm install @getenergy/gke-sandboxes
139
+ ```
140
+
141
+ Your backend chooses a sandbox ID after checking the user’s access. Calling `acquire` with that ID creates a sandbox, returns the running one, or wakes it from its snapshot.
142
+
143
+ ```ts
144
+ import { GkeSandboxes, KubernetesApi } from '@getenergy/gke-sandboxes';
145
+
146
+ const sandboxes = new GkeSandboxes(new KubernetesApi(clusterUrl, getGoogleAccessToken), {
147
+ namespace: 'sandboxes',
148
+ serviceAccount: 'sandbox',
149
+ image: 'docker.io/library/debian:bookworm-slim',
150
+ });
151
+
152
+ const { sandbox } = await sandboxes.acquire('session-42', AbortSignal.timeout(300_000));
153
+ await sandbox.fs.uploadFile('./input.txt', '/var/tmp/input.txt');
154
+ const { exitCode, result } = await sandbox.process.executeCommand('wc -l /var/tmp/input.txt');
155
+ if (exitCode !== 0) throw new Error(result);
156
+ await sandboxes.checkpoint(sandbox.id);
157
+ ```
158
+
159
+ - **Keep active work running.** Call the returned `touch()` periodically while an agent is busy. Schedule `sleepUnused()` from your backend. By default a sandbox can sleep after five idle minutes. If jobs run in the background, supply `drain(sandbox)` to check for work before sleep. Returning `false` keeps it awake. Explicit `sleep(id)` checks the same conditions.
160
+ - **Manage saved files.** Use `find(id)` to inspect a sandbox without waking it. Call `delete(id)` when its files can be discarded and other callers have finished with the ID.
161
+ - **Bring your tools.** Use a stable image with POSIX shell utilities and writable `/var/tmp`. Pin the image digest in production. To share a read-only set of tools across sandboxes, pass `runtime: { image, mountPath }`. Use `boot(labels)` to start a service once the filesystem is ready.
162
+ - **Size the sandbox.** Pass `resources: { requests, limits }` to set what a sandbox reserves on its node and the most it may use. The requests decide how many sandboxes fit on a machine.
163
+
164
+ ### Keep sandboxes ready for new sessions
165
+
166
+ Run one pool maintainer in your backend. This example keeps two unused sandboxes ready so two agents can start at once. Give every backend replica the same pool name, namespace, image and resource settings.
167
+
168
+ ```ts
169
+ const pool = sandboxes.warmPool('agents');
170
+
171
+ // In one long-running worker. Abort the signal on shutdown.
172
+ await pool.maintain(2, shutdownSignal);
173
+ ```
174
+
175
+ In the request handler, call `create` for a new session. It claims a ready sandbox once or creates one on demand when the pool is empty. Store the returned ID with its owner. When the user comes back, call `sandboxes.acquire(id, signal)` to reopen it.
176
+
177
+ ```ts
178
+ const { sandbox, fromPool, touch } = await pool.create(signal);
179
+ ```
180
+
181
+ The maintainer checks capacity once a second. It picks up unused pods after a worker restart. To remove spare capacity, stop the maintainer and call `await pool.reconcile(0)`. Assigned sandboxes keep running. Pools support prebuilt images. Use `acquire` directly if your startup command depends on caller labels through `boot(labels)`.
182
+
183
+ ## Try it in your own project
184
+
185
+ Use a test Google Cloud project with billing enabled. Terraform creates a regional GKE Standard cluster, two autoscaling node pools, a private network with Cloud NAT, a snapshot bucket, and a controller service account. Google bills for those resources. Allow for a 150 GB balanced disk per sandbox node and 100 GB per system node when checking regional SSD and E2 CPU quotas.
186
+
187
+ Install Bun 1.4.4+, Terraform 1.15+, the Google Cloud CLI, kubectl, and gke-gcloud-auth-plugin. Configure Google Cloud CLI and application-default credentials with permission to create the resources, enable APIs, and grant IAM and Kubernetes permissions. The verifier impersonates the controller service account. Choose a region and GKE version that support gVisor file snapshots. [GKE Pod snapshots](https://docs.cloud.google.com/kubernetes-engine/docs/concepts/pod-snapshots)
188
+
189
+ From the repo root, replace the project ID and email below, then run the commands in one shell.
190
+
191
+ ```sh
192
+ export TF_VAR_project_id=your-disposable-project
193
+ export TF_VAR_operator_member=user:you@example.com
194
+ export TF_VAR_region=us-central1
195
+ export TF_VAR_max_sandbox_nodes=3
196
+
197
+ bun install
198
+ terraform -chdir=infra init
199
+ terraform -chdir=infra apply
200
+ export KUBECONFIG="$(mktemp)"
201
+ gcloud container clusters get-credentials sandboxes --dns-endpoint \
202
+ --project="$TF_VAR_project_id" --region="$TF_VAR_region"
203
+ terraform -chdir=infra output -raw manifests | kubectl apply -f -
204
+ bun examples/verify.ts \
205
+ --endpoint "$(terraform -chdir=infra output -raw endpoint)" \
206
+ --controller "$(terraform -chdir=infra output -raw controller)"
207
+ ```
208
+
209
+ The verifier creates a sandbox, writes a file, puts the sandbox to sleep, and waits for the original pod to disappear. It then wakes the sandbox, checks the file contents, and deletes the sandbox. Add `--concurrency 4 --rounds 3` to time twelve cycles, four at a time.
210
+
211
+ ### Deploy on C4D
212
+
213
+ The cost estimate and the build benchmark above use C4D machines with 4 vCPU / 8 GiB sandboxes. To deploy that, set these before `terraform apply`. C4D needs Hyperdisk, and a node needs room for more than the default 110 pods.
214
+
215
+ ```sh
216
+ export TF_VAR_sandbox_machine_type=c4d-highmem-16
217
+ export TF_VAR_sandbox_node_disk_type=hyperdisk-balanced
218
+ export TF_VAR_sandbox_max_pods_per_node=256
219
+ ```
220
+
221
+ Then give the client the matching sandbox size:
222
+
223
+ ```ts
224
+ resources: {
225
+ requests: { cpu: '100m', memory: '850Mi', 'ephemeral-storage': '4Gi' },
226
+ limits: { cpu: '4', memory: '8Gi', 'ephemeral-storage': '20Gi' },
227
+ },
228
+ ```
229
+
230
+ These requests fit 128 sandboxes on a `c4d-highmem-16`, which has about 116 GiB of memory left for pods. Memory is the limit to watch. A node that runs out evicts sandboxes, and they come back from their last snapshot. Measure what your agents use before lowering the memory request. C4D capacity varies by zone. When we tested, one of three Iowa zones had none.
231
+
232
+ ### Clean up
233
+
234
+ Check for leftover pods and snapshots, then remove the test infrastructure. Keep the local Terraform state until teardown finishes. The example disables bucket soft delete and the bucket must be empty before Terraform can delete it.
235
+
236
+ ```sh
237
+ kubectl get pods,podsnapshots -n sandboxes
238
+ terraform -chdir=infra output -raw manifests | kubectl delete --ignore-not-found -f -
239
+ terraform -chdir=infra destroy
240
+ ```
241
+
242
+ ## Live verification
243
+
244
+ On November 17, 2026, we ran the lifecycle benchmark on GKE 1.36.4 in `us-central1` with gVisor on an `e2-highmem-16` node. Each of the 30 restores ran in a new pod and passed all six file checksums. The published sample excludes preliminary runs used to check the timing and storage counters. To repeat it, run the quickstart’s verifier command with `examples/benchmark-lifecycle.ts` in place of `examples/verify.ts`. The signed-in gcloud account needs permission to list objects in the snapshot bucket. [Timings and stored snapshot sizes](#create-sleep-and-wake-times)
245
+
246
+ ## Operating limits
247
+
248
+ - **Persistence.** Sleep and checkpoint save the container’s root filesystem. Mounted volumes, including scratch `/tmp`, are excluded. If GKE evicts a pod, the last completed snapshot is the recovery point. Keep separate backups for history.
249
+ - **Wake time and snapshot size.** Both grow with the number of files, more than with their bytes. GKE recreates every file before the sandbox starts. In Energy’s production cluster a sandbox with about 25,000 files wakes in about 6.5 s, and ones with about 200,000 files took 30 to 45 s. In a test, 200,000 small files totaling 98 MB produced a 3 GB snapshot. Keep package caches and other disposable files on `/tmp`.
250
+ - **Capacity.** By default a sandbox requests 0.25 vCPU, 1 GiB of memory, and 4 GiB of temporary storage. Its limits are 2 vCPU, 4 GiB, and 20 GiB respectively. Change them with `resources`. A low-priority placeholder pod keeps capacity available for new sandboxes. Size the pool for your peak traffic and regional quota.
251
+ - **Access.** Keep the client in a trusted backend. It can execute commands and read files across its namespace. Your app owns user authorization and billing. The network rules allow DNS and outgoing public internet traffic and block incoming pod traffic. Keep the workload identity metadata endpoint blocked.
252
+ - **Identity.** Use a DNS-label sandbox ID of up to 56 characters. To keep custom labels across sleep, include them in the snapshot policy’s grouping rules. Use separate manager selectors or namespaces for independent deployments. The `onOperation` and `onPodLost` callbacks report timings and failures.
253
+
254
+ ## Estimate your sandbox costs
255
+
256
+ ```sh
257
+ bun examples/cost.ts examples/cost-inputs.json
258
+ ```
259
+
260
+ Edit the [example inputs](examples/cost-inputs.json) to match your machine prices, sandboxes per machine, spare machines, and running hours. This example compares total cluster costs with a managed **2 vCPU / 4 GiB** sandbox at $0.1656/hour. It assumes a 500 GB node disk. The quickstart defaults to 150 GB, configurable with `TF_VAR_sandbox_node_disk_gb`. The 4 vCPU compute estimate above is a separate scenario. For traffic that changes over the day, model the number of machines hour by hour.
@@ -0,0 +1,183 @@
1
+ import { z } from 'zod';
2
+ import { type KubernetesApi } from './kubernetes-api.js';
3
+ export { KubernetesApi, KubernetesApiError } from './kubernetes-api.js';
4
+ export type SandboxEnvironment = {
5
+ id: string;
6
+ state: 'started' | 'stopped';
7
+ process: {
8
+ executeCommand(command: string, cwd?: string, env?: Record<string, string>, timeout?: number): Promise<{
9
+ exitCode: number;
10
+ result: string;
11
+ }>;
12
+ };
13
+ fs: {
14
+ uploadFile(local: string, remote: string, timeout?: number): Promise<void>;
15
+ };
16
+ };
17
+ type Labels = Record<string, string>;
18
+ export type SandboxEvent = {
19
+ operation: 'create' | 'wake' | 'sleep' | 'checkpoint';
20
+ outcome: 'succeeded' | 'aborted' | 'failed';
21
+ labels: Labels;
22
+ pod?: string;
23
+ podIp?: string;
24
+ durationMs: number;
25
+ error: unknown;
26
+ };
27
+ type ResourceList = {
28
+ cpu: string;
29
+ memory: string;
30
+ 'ephemeral-storage': string;
31
+ };
32
+ export type SandboxResources = {
33
+ requests: ResourceList;
34
+ limits: ResourceList;
35
+ };
36
+ export declare const DEFAULT_RESOURCES: SandboxResources;
37
+ export type GkeSandboxOptions = {
38
+ namespace: string;
39
+ image: string;
40
+ serviceAccount: string;
41
+ managerLabels?: Labels;
42
+ idleTimeoutMs?: number;
43
+ runtime?: {
44
+ image: string;
45
+ mountPath: string;
46
+ };
47
+ /** What a sandbox reserves on its node and may use at most. Defaults to `DEFAULT_RESOURCES`. */
48
+ resources?: SandboxResources;
49
+ boot?: (labels: Labels) => {
50
+ shell: string;
51
+ args: string[];
52
+ };
53
+ drain?: (sandbox: SandboxEnvironment) => Promise<boolean>;
54
+ onOperation?: (event: SandboxEvent) => void;
55
+ onPodLost?: (labels: Labels, phase: string, reason: string, hasSnapshot: boolean) => void;
56
+ };
57
+ declare const PodSchema: z.ZodObject<{
58
+ metadata: z.ZodObject<{
59
+ name: z.ZodString;
60
+ uid: z.ZodString;
61
+ resourceVersion: z.ZodString;
62
+ creationTimestamp: z.ZodString;
63
+ deletionTimestamp: z.ZodOptional<z.ZodString>;
64
+ labels: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
65
+ annotations: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
66
+ }, z.core.$strip>;
67
+ status: z.ZodObject<{
68
+ phase: z.ZodString;
69
+ podIP: z.ZodOptional<z.ZodString>;
70
+ conditions: z.ZodDefault<z.ZodArray<z.ZodObject<{
71
+ type: z.ZodString;
72
+ status: z.ZodString;
73
+ }, z.core.$strip>>>;
74
+ reason: z.ZodOptional<z.ZodString>;
75
+ containerStatuses: z.ZodDefault<z.ZodArray<z.ZodObject<{
76
+ state: z.ZodOptional<z.ZodObject<{
77
+ terminated: z.ZodOptional<z.ZodObject<{
78
+ reason: z.ZodOptional<z.ZodString>;
79
+ }, z.core.$strip>>;
80
+ }, z.core.$strip>>;
81
+ }, z.core.$strip>>>;
82
+ }, z.core.$strip>;
83
+ }, z.core.$strip>;
84
+ type Pod = z.infer<typeof PodSchema>;
85
+ export type SandboxRecord = {
86
+ name: string;
87
+ labels: Record<string, string>;
88
+ createdMs: number;
89
+ pod: Pod | null;
90
+ /** Ready snapshots, newest first. */
91
+ snapshots: string[];
92
+ /** When the newest snapshot was taken. */
93
+ sleptMs: number | null;
94
+ };
95
+ export declare const terminating: (pod: Pod) => boolean;
96
+ export declare const sandboxState: ({ pod }: SandboxRecord) => "started" | "stopped";
97
+ export declare class SandboxInUseError extends Error {
98
+ constructor(name: string);
99
+ }
100
+ export declare class GkeSandboxes {
101
+ private readonly kubernetes;
102
+ private readonly options;
103
+ private readonly pods;
104
+ private readonly triggers;
105
+ private readonly snapshotsPath;
106
+ private readonly manager;
107
+ private readonly idleTimeoutMs;
108
+ constructor(kubernetes: KubernetesApi, options: GkeSandboxOptions);
109
+ private selector;
110
+ acquire(id: string, signal: AbortSignal, initialLabels?: Labels): Promise<{
111
+ sandbox: SandboxEnvironment;
112
+ startState: string;
113
+ labels: Record<string, string>;
114
+ podName: string;
115
+ createdMs: number;
116
+ touch: () => Promise<void>;
117
+ }>;
118
+ /** Creates single-use sandboxes with generated IDs. Reopen a saved ID with acquire(). */
119
+ warmPool(name: string): {
120
+ create: (signal: AbortSignal, labels?: Labels) => Promise<{
121
+ sandbox: SandboxEnvironment;
122
+ podName: string;
123
+ fromPool: boolean;
124
+ touch: () => Promise<void>;
125
+ }>;
126
+ reconcile: (size: number) => Promise<void>;
127
+ maintain(size: number, signal: AbortSignal): Promise<void>;
128
+ };
129
+ /** Open a previously listed workspace without extending its idle period on a read. */
130
+ open(record: SandboxRecord, signal: AbortSignal, freshLabels: Labels): Promise<SandboxEnvironment>;
131
+ labelPod(podName: string, labels: Labels): Promise<void>;
132
+ endpoint(sandbox: {
133
+ id: string;
134
+ }, port: number): Promise<{
135
+ url: string;
136
+ headers: {};
137
+ }>;
138
+ endpointIsCurrent(sandboxId: string, endpoint: {
139
+ url: string;
140
+ }): Promise<boolean>;
141
+ /**
142
+ * Snapshots a running sandbox and lets it run on, so a pod that dies later loses only what was
143
+ * written since. The sandbox is paused while the snapshot is taken.
144
+ */
145
+ checkpoint(sandboxId: string): Promise<void>;
146
+ sleepUnused(): Promise<void>;
147
+ /**
148
+ * Every sandbox that exists, awake or asleep, with whose it is and where its snapshots are
149
+ * stored. Usage is metered by pod and by stored snapshot, and neither names an owner.
150
+ */
151
+ inventory(): Promise<{
152
+ sandboxId: string;
153
+ labels: Labels;
154
+ state: 'running' | 'stopped';
155
+ snapshots: {
156
+ path: string;
157
+ createdAt: string;
158
+ }[];
159
+ }[]>;
160
+ deleteMatching(match: Labels): Promise<void>;
161
+ find(id: string): Promise<SandboxRecord | null>;
162
+ /** Every sandbox with these labels, awake or asleep, newest first. */
163
+ list(labels: Record<string, string>): Promise<SandboxRecord[]>;
164
+ private livePods;
165
+ /** The sandbox's pod to use: the one that is not shutting down, or null. */
166
+ private livePod;
167
+ /** Returns the sandbox's running pod, waking or creating it first. */
168
+ private start;
169
+ private report;
170
+ private confirmRestored;
171
+ private manifest;
172
+ private claim;
173
+ /** Records the dispatch. Returns false when the sweep claimed the pod first. */
174
+ private markAcquired;
175
+ /** Reports that the sandbox is in use, which restarts its idle period. */
176
+ private touch;
177
+ sleep(id: string): Promise<void>;
178
+ private sleepPod;
179
+ private dropOlderSnapshots;
180
+ private snapshot;
181
+ delete(id: string): Promise<void>;
182
+ environment(name: string, state: 'started' | 'stopped'): SandboxEnvironment;
183
+ }