withruntime 0.49.0 → 1.0.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.
Files changed (491) hide show
  1. package/dist/generated/apps.d.ts +309 -0
  2. package/dist/generated/apps.js +333 -0
  3. package/dist/generated/audit.d.ts +47 -0
  4. package/dist/generated/audit.js +14 -0
  5. package/dist/generated/browsers.d.ts +309 -0
  6. package/dist/generated/browsers.js +333 -0
  7. package/dist/generated/builds.d.ts +309 -0
  8. package/dist/generated/builds.js +333 -0
  9. package/dist/generated/ci.d.ts +309 -0
  10. package/dist/generated/ci.js +333 -0
  11. package/dist/generated/containers.d.ts +309 -0
  12. package/dist/generated/containers.js +333 -0
  13. package/dist/generated/desktops.d.ts +309 -0
  14. package/dist/generated/desktops.js +333 -0
  15. package/dist/generated/domains.d.ts +80 -0
  16. package/dist/generated/domains.js +58 -0
  17. package/dist/generated/egressIps.d.ts +36 -0
  18. package/dist/generated/egressIps.js +14 -0
  19. package/dist/generated/events.d.ts +37 -0
  20. package/dist/generated/events.js +14 -0
  21. package/dist/generated/feedback.d.ts +44 -0
  22. package/dist/generated/feedback.js +13 -0
  23. package/dist/generated/functions.d.ts +309 -0
  24. package/dist/generated/functions.js +333 -0
  25. package/dist/generated/identities.d.ts +36 -0
  26. package/dist/generated/identities.js +22 -0
  27. package/dist/generated/images.d.ts +200 -0
  28. package/dist/generated/images.js +65 -0
  29. package/dist/generated/index.d.ts +143 -0
  30. package/dist/generated/index.js +184 -0
  31. package/dist/generated/jobRuns.d.ts +68 -0
  32. package/dist/generated/jobRuns.js +22 -0
  33. package/dist/generated/jobs.d.ts +144 -0
  34. package/dist/generated/jobs.js +85 -0
  35. package/dist/generated/keys.d.ts +105 -0
  36. package/dist/generated/keys.js +26 -0
  37. package/dist/generated/me.d.ts +33 -0
  38. package/dist/generated/me.js +13 -0
  39. package/dist/generated/networks.d.ts +32 -0
  40. package/dist/generated/networks.js +14 -0
  41. package/dist/generated/notebooks.d.ts +309 -0
  42. package/dist/generated/notebooks.js +333 -0
  43. package/dist/generated/otel.d.ts +46 -0
  44. package/dist/generated/otel.js +22 -0
  45. package/dist/generated/ports.d.ts +55 -0
  46. package/dist/generated/ports.js +22 -0
  47. package/dist/generated/previews.d.ts +86 -0
  48. package/dist/generated/previews.js +67 -0
  49. package/dist/generated/projects.d.ts +47 -0
  50. package/dist/generated/projects.js +26 -0
  51. package/dist/generated/roles.d.ts +36 -0
  52. package/dist/generated/roles.js +22 -0
  53. package/dist/generated/routes.d.ts +3 -0
  54. package/dist/generated/routes.js +4 -0
  55. package/dist/generated/runtime.d.ts +176 -0
  56. package/dist/generated/runtime.js +416 -0
  57. package/dist/generated/sandboxes.d.ts +952 -0
  58. package/dist/generated/sandboxes.js +342 -0
  59. package/dist/generated/secrets.d.ts +116 -0
  60. package/dist/generated/secrets.js +54 -0
  61. package/dist/generated/sessions.d.ts +47 -0
  62. package/dist/generated/sessions.js +17 -0
  63. package/dist/generated/signing.d.ts +68 -0
  64. package/dist/generated/signing.js +187 -0
  65. package/dist/generated/sites.d.ts +309 -0
  66. package/dist/generated/sites.js +333 -0
  67. package/dist/generated/snapshots.d.ts +27 -0
  68. package/dist/generated/snapshots.js +22 -0
  69. package/dist/generated/tunnels.d.ts +68 -0
  70. package/dist/generated/tunnels.js +14 -0
  71. package/dist/generated/usage.d.ts +155 -0
  72. package/dist/generated/usage.js +17 -0
  73. package/dist/generated/volumes.d.ts +36 -0
  74. package/dist/generated/volumes.js +26 -0
  75. package/dist/generated/webhooks.d.ts +44 -0
  76. package/dist/generated/webhooks.js +22 -0
  77. package/dist/generated/workspaces.d.ts +309 -0
  78. package/dist/generated/workspaces.js +333 -0
  79. package/dist/v2/cli.d.ts +7 -0
  80. package/dist/v2/cli.js +283 -0
  81. package/dist/v2/index.d.ts +1 -0
  82. package/dist/v2/index.js +4 -0
  83. package/dist/v2/login.d.ts +35 -0
  84. package/dist/v2/login.js +225 -0
  85. package/dist/v2/mcp.d.ts +1 -0
  86. package/dist/v2/mcp.js +49 -0
  87. package/dist/v2/openapi.json +75750 -0
  88. package/dist/v2/shims/base.d.ts +33 -0
  89. package/dist/v2/shims/base.js +54 -0
  90. package/dist/v2/shims/blaxel.d.ts +60 -0
  91. package/dist/v2/shims/blaxel.js +71 -0
  92. package/dist/v2/shims/cloudflare.d.ts +52 -0
  93. package/dist/v2/shims/cloudflare.js +55 -0
  94. package/dist/v2/shims/daytona.d.ts +58 -0
  95. package/dist/v2/shims/daytona.js +74 -0
  96. package/dist/v2/shims/e2b.d.ts +142 -0
  97. package/dist/v2/shims/e2b.js +238 -0
  98. package/dist/v2/shims/fly.d.ts +6 -0
  99. package/dist/v2/shims/fly.js +91 -0
  100. package/dist/v2/shims/modal.d.ts +54 -0
  101. package/dist/v2/shims/modal.js +79 -0
  102. package/dist/v2/shims/morph.d.ts +60 -0
  103. package/dist/v2/shims/morph.js +87 -0
  104. package/dist/v2/shims/vercel.d.ts +53 -0
  105. package/dist/v2/shims/vercel.js +90 -0
  106. package/dist/v2/table.d.ts +53 -0
  107. package/dist/v2/table.js +122 -0
  108. package/package.json +20 -310
  109. package/BLAXEL.md +0 -290
  110. package/COMPATIBILITY.md +0 -447
  111. package/DAYTONA.md +0 -237
  112. package/E2B.md +0 -314
  113. package/README.md +0 -331
  114. package/README.src.md +0 -333
  115. package/VERCEL.md +0 -230
  116. package/agent-platforms-inventory.json +0 -387
  117. package/compatibility-lock.json +0 -305
  118. package/dist/agents/browser.d.ts +0 -12
  119. package/dist/agents/browser.js +0 -12
  120. package/dist/agents/index.d.ts +0 -11
  121. package/dist/agents/index.js +0 -11
  122. package/dist/agents-cli.d.ts +0 -16
  123. package/dist/agents-cli.js +0 -1237
  124. package/dist/agents-deploy.d.ts +0 -196
  125. package/dist/agents-deploy.js +0 -872
  126. package/dist/agents-file.d.ts +0 -19
  127. package/dist/agents-file.js +0 -135
  128. package/dist/ai/index.d.ts +0 -49
  129. package/dist/ai/index.js +0 -31
  130. package/dist/ai-harness/index.d.ts +0 -194
  131. package/dist/ai-harness/index.js +0 -522
  132. package/dist/api-defaults.d.ts +0 -17
  133. package/dist/api-defaults.js +0 -22
  134. package/dist/apps/index.d.ts +0 -10
  135. package/dist/apps/index.js +0 -11
  136. package/dist/apps-cli.d.ts +0 -16
  137. package/dist/apps-cli.js +0 -1021
  138. package/dist/billing-cli.d.ts +0 -23
  139. package/dist/billing-cli.js +0 -264
  140. package/dist/blaxel/client.d.ts +0 -59
  141. package/dist/blaxel/client.js +0 -86
  142. package/dist/blaxel/context.d.ts +0 -59
  143. package/dist/blaxel/context.js +0 -162
  144. package/dist/blaxel/errors.d.ts +0 -130
  145. package/dist/blaxel/errors.js +0 -315
  146. package/dist/blaxel/filesystem.d.ts +0 -147
  147. package/dist/blaxel/filesystem.js +0 -585
  148. package/dist/blaxel/index.d.ts +0 -287
  149. package/dist/blaxel/index.js +0 -351
  150. package/dist/blaxel/interpreter.d.ts +0 -71
  151. package/dist/blaxel/interpreter.js +0 -256
  152. package/dist/blaxel/lookup.d.ts +0 -39
  153. package/dist/blaxel/lookup.js +0 -84
  154. package/dist/blaxel/pagination.d.ts +0 -39
  155. package/dist/blaxel/pagination.js +0 -88
  156. package/dist/blaxel/preview.d.ts +0 -136
  157. package/dist/blaxel/preview.js +0 -304
  158. package/dist/blaxel/process.d.ts +0 -126
  159. package/dist/blaxel/process.js +0 -581
  160. package/dist/blaxel/sandbox.d.ts +0 -198
  161. package/dist/blaxel/sandbox.js +0 -856
  162. package/dist/blaxel/session.d.ts +0 -31
  163. package/dist/blaxel/session.js +0 -136
  164. package/dist/blaxel/snapshot.d.ts +0 -123
  165. package/dist/blaxel/snapshot.js +0 -199
  166. package/dist/blaxel/types.d.ts +0 -145
  167. package/dist/blaxel/types.js +0 -60
  168. package/dist/blaxel/unsupported.d.ts +0 -20
  169. package/dist/blaxel/unsupported.js +0 -32
  170. package/dist/browser-stub.d.ts +0 -1
  171. package/dist/browser-stub.js +0 -1
  172. package/dist/browsers/index.d.ts +0 -9
  173. package/dist/browsers/index.js +0 -10
  174. package/dist/browsers-cli.d.ts +0 -13
  175. package/dist/browsers-cli.js +0 -279
  176. package/dist/builds/index.d.ts +0 -10
  177. package/dist/builds/index.js +0 -11
  178. package/dist/ci/index.d.ts +0 -13
  179. package/dist/ci/index.js +0 -14
  180. package/dist/ci-cli.d.ts +0 -20
  181. package/dist/ci-cli.js +0 -537
  182. package/dist/ci-import.d.ts +0 -23
  183. package/dist/ci-import.js +0 -565
  184. package/dist/claude-agent-sdk/index.d.ts +0 -7
  185. package/dist/claude-agent-sdk/index.js +0 -65
  186. package/dist/cli/logs.d.ts +0 -21
  187. package/dist/cli/logs.js +0 -188
  188. package/dist/cli-extras.d.ts +0 -39
  189. package/dist/cli-extras.js +0 -267
  190. package/dist/cli-name.d.ts +0 -6
  191. package/dist/cli-name.js +0 -8
  192. package/dist/cli-update.d.ts +0 -11
  193. package/dist/cli-update.js +0 -46
  194. package/dist/cli-words.d.ts +0 -36
  195. package/dist/cli-words.js +0 -167
  196. package/dist/cli.d.ts +0 -92
  197. package/dist/cli.js +0 -5463
  198. package/dist/client.d.ts +0 -189
  199. package/dist/client.js +0 -205
  200. package/dist/cloudflare/errors.d.ts +0 -166
  201. package/dist/cloudflare/errors.js +0 -183
  202. package/dist/cloudflare/identity.d.ts +0 -7
  203. package/dist/cloudflare/identity.js +0 -13
  204. package/dist/cloudflare/index.d.ts +0 -545
  205. package/dist/cloudflare/index.js +0 -1106
  206. package/dist/cloudflare/interpreter.d.ts +0 -119
  207. package/dist/cloudflare/interpreter.js +0 -232
  208. package/dist/cloudflare/mime.d.ts +0 -1
  209. package/dist/cloudflare/mime.js +0 -66
  210. package/dist/cloudflare/streams.d.ts +0 -46
  211. package/dist/cloudflare/streams.js +0 -175
  212. package/dist/cloudflare/types.d.ts +0 -338
  213. package/dist/cloudflare/types.js +0 -80
  214. package/dist/cloudflare/watch.d.ts +0 -9
  215. package/dist/cloudflare/watch.js +0 -24
  216. package/dist/cloudflare/worker.d.ts +0 -706
  217. package/dist/cloudflare/worker.js +0 -633
  218. package/dist/codesandbox/guest-service.d.ts +0 -31
  219. package/dist/codesandbox/guest-service.js +0 -490
  220. package/dist/codesandbox/index.d.ts +0 -574
  221. package/dist/codesandbox/index.js +0 -1747
  222. package/dist/compat/core.d.ts +0 -58
  223. package/dist/compat/core.js +0 -267
  224. package/dist/compat/files.d.ts +0 -27
  225. package/dist/compat/files.js +0 -157
  226. package/dist/compat/lease.d.ts +0 -37
  227. package/dist/compat/lease.js +0 -93
  228. package/dist/compat/shell.d.ts +0 -4
  229. package/dist/compat/shell.js +0 -165
  230. package/dist/containers/index.d.ts +0 -10
  231. package/dist/containers/index.js +0 -11
  232. package/dist/credentials.d.ts +0 -71
  233. package/dist/credentials.js +0 -340
  234. package/dist/daytona/client.d.ts +0 -48
  235. package/dist/daytona/client.js +0 -45
  236. package/dist/daytona/computer-use.d.ts +0 -171
  237. package/dist/daytona/computer-use.js +0 -382
  238. package/dist/daytona/context.d.ts +0 -41
  239. package/dist/daytona/context.js +0 -50
  240. package/dist/daytona/daytona.d.ts +0 -213
  241. package/dist/daytona/daytona.js +0 -578
  242. package/dist/daytona/errors.d.ts +0 -117
  243. package/dist/daytona/errors.js +0 -201
  244. package/dist/daytona/filesystem.d.ts +0 -99
  245. package/dist/daytona/filesystem.js +0 -300
  246. package/dist/daytona/git.d.ts +0 -33
  247. package/dist/daytona/git.js +0 -128
  248. package/dist/daytona/image.d.ts +0 -49
  249. package/dist/daytona/image.js +0 -146
  250. package/dist/daytona/index.d.ts +0 -87
  251. package/dist/daytona/index.js +0 -102
  252. package/dist/daytona/process.d.ts +0 -143
  253. package/dist/daytona/process.js +0 -565
  254. package/dist/daytona/sandbox.d.ts +0 -222
  255. package/dist/daytona/sandbox.js +0 -505
  256. package/dist/desktops/index.d.ts +0 -9
  257. package/dist/desktops/index.js +0 -10
  258. package/dist/domains/index.d.ts +0 -9
  259. package/dist/domains/index.js +0 -10
  260. package/dist/e2b/client.d.ts +0 -76
  261. package/dist/e2b/client.js +0 -124
  262. package/dist/e2b/code-interpreter.d.ts +0 -134
  263. package/dist/e2b/code-interpreter.js +0 -239
  264. package/dist/e2b/commands.d.ts +0 -135
  265. package/dist/e2b/commands.js +0 -452
  266. package/dist/e2b/errors.d.ts +0 -125
  267. package/dist/e2b/errors.js +0 -247
  268. package/dist/e2b/filesystem.d.ts +0 -111
  269. package/dist/e2b/filesystem.js +0 -374
  270. package/dist/e2b/index.d.ts +0 -35
  271. package/dist/e2b/index.js +0 -69
  272. package/dist/e2b/pty.d.ts +0 -24
  273. package/dist/e2b/pty.js +0 -83
  274. package/dist/e2b/sandbox.d.ts +0 -248
  275. package/dist/e2b/sandbox.js +0 -781
  276. package/dist/e2b/unsupported.d.ts +0 -38
  277. package/dist/e2b/unsupported.js +0 -48
  278. package/dist/e2b/users.d.ts +0 -39
  279. package/dist/e2b/users.js +0 -207
  280. package/dist/errors.d.ts +0 -100
  281. package/dist/errors.js +0 -198
  282. package/dist/file-source.d.ts +0 -16
  283. package/dist/file-source.js +0 -162
  284. package/dist/fly/index.d.ts +0 -102
  285. package/dist/fly/index.js +0 -930
  286. package/dist/freestyle/index.d.ts +0 -629
  287. package/dist/freestyle/index.js +0 -1187
  288. package/dist/functions/index.d.ts +0 -10
  289. package/dist/functions/index.js +0 -11
  290. package/dist/identity.d.ts +0 -30
  291. package/dist/identity.js +0 -141
  292. package/dist/image-context.d.ts +0 -39
  293. package/dist/image-context.js +0 -176
  294. package/dist/images/index.d.ts +0 -9
  295. package/dist/images/index.js +0 -10
  296. package/dist/index.d.ts +0 -87
  297. package/dist/index.js +0 -51
  298. package/dist/inngest/index.d.ts +0 -96
  299. package/dist/inngest/index.js +0 -183
  300. package/dist/ips/index.d.ts +0 -9
  301. package/dist/ips/index.js +0 -10
  302. package/dist/jobs/index.d.ts +0 -9
  303. package/dist/jobs/index.js +0 -10
  304. package/dist/jobs-code/cron.d.ts +0 -12
  305. package/dist/jobs-code/cron.js +0 -93
  306. package/dist/jobs-code/registry.d.ts +0 -31
  307. package/dist/jobs-code/registry.js +0 -30
  308. package/dist/jobs-code/runner.d.ts +0 -1
  309. package/dist/jobs-code/runner.js +0 -74
  310. package/dist/jobs-deploy.d.ts +0 -22
  311. package/dist/jobs-deploy.js +0 -247
  312. package/dist/jobs-import.d.ts +0 -15
  313. package/dist/jobs-import.js +0 -231
  314. package/dist/keys.d.ts +0 -55
  315. package/dist/keys.js +0 -211
  316. package/dist/login.d.ts +0 -88
  317. package/dist/login.js +0 -369
  318. package/dist/machine.d.ts +0 -222
  319. package/dist/machine.js +0 -578
  320. package/dist/mcp.d.ts +0 -16
  321. package/dist/mcp.js +0 -377
  322. package/dist/modal/index.d.ts +0 -532
  323. package/dist/modal/index.js +0 -1284
  324. package/dist/morph/index.d.ts +0 -255
  325. package/dist/morph/index.js +0 -641
  326. package/dist/network-cli.d.ts +0 -17
  327. package/dist/network-cli.js +0 -523
  328. package/dist/networks/index.d.ts +0 -11
  329. package/dist/networks/index.js +0 -10
  330. package/dist/openai-agents/index.d.ts +0 -132
  331. package/dist/openai-agents/index.js +0 -738
  332. package/dist/page.d.ts +0 -13
  333. package/dist/page.js +0 -39
  334. package/dist/ports/index.d.ts +0 -9
  335. package/dist/ports/index.js +0 -10
  336. package/dist/product-names.d.ts +0 -52
  337. package/dist/product-names.js +0 -174
  338. package/dist/product-renames.d.ts +0 -103
  339. package/dist/product-renames.js +0 -189
  340. package/dist/products/agents.d.ts +0 -935
  341. package/dist/products/agents.js +0 -581
  342. package/dist/products/api-keys.d.ts +0 -113
  343. package/dist/products/api-keys.js +0 -32
  344. package/dist/products/apps.d.ts +0 -409
  345. package/dist/products/apps.js +0 -231
  346. package/dist/products/audit.d.ts +0 -51
  347. package/dist/products/audit.js +0 -10
  348. package/dist/products/balancers.d.ts +0 -87
  349. package/dist/products/balancers.js +0 -8
  350. package/dist/products/billing.d.ts +0 -76
  351. package/dist/products/billing.js +0 -26
  352. package/dist/products/browser.d.ts +0 -73
  353. package/dist/products/browser.js +0 -29
  354. package/dist/products/browsers.d.ts +0 -184
  355. package/dist/products/browsers.js +0 -180
  356. package/dist/products/builds.d.ts +0 -175
  357. package/dist/products/builds.js +0 -234
  358. package/dist/products/ci.d.ts +0 -406
  359. package/dist/products/ci.js +0 -133
  360. package/dist/products/containers.d.ts +0 -71
  361. package/dist/products/containers.js +0 -6
  362. package/dist/products/desktop.d.ts +0 -141
  363. package/dist/products/desktop.js +0 -83
  364. package/dist/products/desktops.d.ts +0 -71
  365. package/dist/products/desktops.js +0 -27
  366. package/dist/products/functions.d.ts +0 -2
  367. package/dist/products/functions.js +0 -5
  368. package/dist/products/images.d.ts +0 -229
  369. package/dist/products/images.js +0 -235
  370. package/dist/products/index.d.ts +0 -84
  371. package/dist/products/index.js +0 -105
  372. package/dist/products/interpreter.d.ts +0 -97
  373. package/dist/products/interpreter.js +0 -106
  374. package/dist/products/jobs.d.ts +0 -408
  375. package/dist/products/jobs.js +0 -256
  376. package/dist/products/limits.d.ts +0 -61
  377. package/dist/products/limits.js +0 -10
  378. package/dist/products/logs.d.ts +0 -245
  379. package/dist/products/logs.js +0 -274
  380. package/dist/products/mcp.d.ts +0 -88
  381. package/dist/products/mcp.js +0 -58
  382. package/dist/products/mounts.d.ts +0 -49
  383. package/dist/products/mounts.js +0 -21
  384. package/dist/products/network-products.d.ts +0 -268
  385. package/dist/products/network-products.js +0 -127
  386. package/dist/products/network.d.ts +0 -62
  387. package/dist/products/network.js +0 -19
  388. package/dist/products/observability.d.ts +0 -264
  389. package/dist/products/observability.js +0 -123
  390. package/dist/products/plans.d.ts +0 -133
  391. package/dist/products/plans.js +0 -24
  392. package/dist/products/previews.d.ts +0 -70
  393. package/dist/products/previews.js +0 -39
  394. package/dist/products/private-network.d.ts +0 -22
  395. package/dist/products/private-network.js +0 -10
  396. package/dist/products/queues.d.ts +0 -149
  397. package/dist/products/queues.js +0 -213
  398. package/dist/products/referrals.d.ts +0 -50
  399. package/dist/products/referrals.js +0 -8
  400. package/dist/products/reservations.d.ts +0 -108
  401. package/dist/products/reservations.js +0 -41
  402. package/dist/products/resources.d.ts +0 -55
  403. package/dist/products/resources.js +0 -122
  404. package/dist/products/secrets.d.ts +0 -316
  405. package/dist/products/secrets.js +0 -333
  406. package/dist/products/signed-requests.d.ts +0 -21
  407. package/dist/products/signed-requests.js +0 -11
  408. package/dist/products/sso.d.ts +0 -44
  409. package/dist/products/sso.js +0 -8
  410. package/dist/products/streams.d.ts +0 -73
  411. package/dist/products/streams.js +0 -17
  412. package/dist/products/switching.d.ts +0 -123
  413. package/dist/products/switching.js +0 -26
  414. package/dist/products/tailscale.d.ts +0 -57
  415. package/dist/products/tailscale.js +0 -17
  416. package/dist/products/uptime.d.ts +0 -97
  417. package/dist/products/uptime.js +0 -42
  418. package/dist/products/volumes.d.ts +0 -190
  419. package/dist/products/volumes.js +0 -114
  420. package/dist/products/watch.d.ts +0 -112
  421. package/dist/products/watch.js +0 -249
  422. package/dist/proxy.d.ts +0 -30
  423. package/dist/proxy.js +0 -200
  424. package/dist/record-cli.d.ts +0 -23
  425. package/dist/record-cli.js +0 -308
  426. package/dist/renamed-products.d.ts +0 -38
  427. package/dist/renamed-products.js +0 -34
  428. package/dist/resumable.d.ts +0 -32
  429. package/dist/resumable.js +0 -201
  430. package/dist/runloop/index.d.ts +0 -333
  431. package/dist/runloop/index.js +0 -560
  432. package/dist/runloop/pagination.d.ts +0 -46
  433. package/dist/runloop/pagination.js +0 -82
  434. package/dist/runloop/sdk.d.ts +0 -131
  435. package/dist/runloop/sdk.js +0 -167
  436. package/dist/runloop/snapshots.d.ts +0 -52
  437. package/dist/runloop/snapshots.js +0 -244
  438. package/dist/sandbox.d.ts +0 -371
  439. package/dist/sandbox.js +0 -1500
  440. package/dist/sandboxes/index.d.ts +0 -11
  441. package/dist/sandboxes/index.js +0 -12
  442. package/dist/sealing.d.ts +0 -6
  443. package/dist/sealing.js +0 -14
  444. package/dist/snapshots/index.d.ts +0 -9
  445. package/dist/snapshots/index.js +0 -11
  446. package/dist/snapshots.d.ts +0 -82
  447. package/dist/snapshots.js +0 -65
  448. package/dist/sprites/index.d.ts +0 -563
  449. package/dist/sprites/index.js +0 -1370
  450. package/dist/ssh.d.ts +0 -56
  451. package/dist/ssh.js +0 -416
  452. package/dist/switched-off.d.ts +0 -5
  453. package/dist/switched-off.js +0 -8
  454. package/dist/tar.d.ts +0 -15
  455. package/dist/tar.js +0 -526
  456. package/dist/terminal.d.ts +0 -24
  457. package/dist/terminal.js +0 -32
  458. package/dist/tools/index.d.ts +0 -62
  459. package/dist/tools/index.js +0 -181
  460. package/dist/transport.d.ts +0 -165
  461. package/dist/transport.js +0 -883
  462. package/dist/trigger/index.d.ts +0 -202
  463. package/dist/trigger/index.js +0 -244
  464. package/dist/tunnel.d.ts +0 -70
  465. package/dist/tunnel.js +0 -316
  466. package/dist/types.d.ts +0 -574
  467. package/dist/types.js +0 -1
  468. package/dist/vercel/client.d.ts +0 -40
  469. package/dist/vercel/client.js +0 -39
  470. package/dist/vercel/command.d.ts +0 -117
  471. package/dist/vercel/command.js +0 -391
  472. package/dist/vercel/errors.d.ts +0 -53
  473. package/dist/vercel/errors.js +0 -131
  474. package/dist/vercel/filesystem.d.ts +0 -153
  475. package/dist/vercel/filesystem.js +0 -297
  476. package/dist/vercel/index.d.ts +0 -24
  477. package/dist/vercel/index.js +0 -36
  478. package/dist/vercel/sandbox-user.d.ts +0 -70
  479. package/dist/vercel/sandbox-user.js +0 -207
  480. package/dist/vercel/sandbox.d.ts +0 -372
  481. package/dist/vercel/sandbox.js +0 -1037
  482. package/dist/vercel/snapshot.d.ts +0 -94
  483. package/dist/vercel/snapshot.js +0 -137
  484. package/dist/volumes/index.d.ts +0 -9
  485. package/dist/volumes/index.js +0 -10
  486. package/dist/wait.d.ts +0 -12
  487. package/dist/wait.js +0 -47
  488. package/dist/wallet.d.ts +0 -45
  489. package/dist/wallet.js +0 -56
  490. package/dist/wireguard.d.ts +0 -7
  491. package/dist/wireguard.js +0 -13
@@ -1,1747 +0,0 @@
1
- import { all, client, CompatibilityError, create, destroy, execOptions, only, quote, ready, refuse, } from "../compat/core.js";
2
- import { GuestFiles } from "../compat/files.js";
3
- import { ManagedTasks } from "./guest-service.js";
4
- export { CompatibilityError };
5
- export class VMTier {
6
- name;
7
- cpuCores;
8
- memoryGiB;
9
- diskGB;
10
- constructor(name, cpuCores, memoryGiB, diskGB = 20) {
11
- this.name = name;
12
- this.cpuCores = cpuCores;
13
- this.memoryGiB = memoryGiB;
14
- this.diskGB = diskGB;
15
- }
16
- static Pico = new VMTier("pico", 1, 2);
17
- static Nano = new VMTier("nano", 2, 4);
18
- static Micro = new VMTier("micro", 4, 8);
19
- static Small = new VMTier("small", 8, 16);
20
- static Medium = new VMTier("medium", 16, 32);
21
- static Large = new VMTier("large", 32, 64);
22
- static XLarge = new VMTier("xlarge", 64, 128);
23
- static All = [
24
- VMTier.Pico,
25
- VMTier.Nano,
26
- VMTier.Micro,
27
- VMTier.Small,
28
- VMTier.Medium,
29
- VMTier.Large,
30
- VMTier.XLarge,
31
- ];
32
- static fromName(name) {
33
- const tier = this.All.find((t) => t.name === name);
34
- if (!tier)
35
- throw new TypeError(`Unknown VM tier: ${name}`);
36
- return tier;
37
- }
38
- static fromSpecs(specs) {
39
- return this.All.find((t) => t.cpuCores >= specs.cpu && t.memoryGiB >= specs.memGiB && t.diskGB >= (specs.diskGB ?? 0));
40
- }
41
- }
42
- export class CodeSandbox {
43
- sandboxes;
44
- hosts = new HostTokens();
45
- constructor(apiToken, options = {}) {
46
- const { headers, tracer, ...rest } = options;
47
- if (headers && Object.keys(headers).length)
48
- throw new CompatibilityError("CodeSandbox", "custom API headers");
49
- if (tracer)
50
- throw new CompatibilityError("CodeSandbox", "an OpenTelemetry tracer; export Runtime's sandbox telemetry with runtime.observability");
51
- this.sandboxes = new Sandboxes(client({ ...rest, apiKey: rest.apiKey ?? apiToken }));
52
- }
53
- }
54
- /** CodeSandbox's host tokens open private previews. Runtime's private
55
- * previews carry their own signed token: `sandbox.previews.create(port)`. */
56
- export class HostTokens {
57
- }
58
- const PREVIEW_TOKENS = "use Runtime's private previews, sandbox.previews.create(port), which carry a signed token";
59
- refuse("CodeSandbox", "HostTokens", HostTokens, {
60
- createToken: PREVIEW_TOKENS,
61
- listTokens: PREVIEW_TOKENS,
62
- revokeToken: PREVIEW_TOKENS,
63
- revokeAllTokens: PREVIEW_TOKENS,
64
- updateToken: PREVIEW_TOKENS,
65
- });
66
- refuse("CodeSandbox", "HostTokens", HostTokens, { getUrl: PREVIEW_TOKENS, getHeaders: PREVIEW_TOKENS, getCookies: PREVIEW_TOKENS }, { sync: true });
67
- /** Passing it to create() makes a fresh sandbox from Runtime's default image. */
68
- const DEFAULT_TEMPLATE = "runtime-default";
69
- function wakeup(config) {
70
- if (!config)
71
- return undefined;
72
- if (config.http !== config.websocket)
73
- throw new CompatibilityError("CodeSandbox", "waking on HTTP but not WebSocket requests, or the reverse; Runtime wakes on both");
74
- return config.http;
75
- }
76
- const metadata = (s) => ({
77
- id: s.id,
78
- createdAt: new Date(s.info.createdAt),
79
- updatedAt: new Date(s.info.createdAt),
80
- title: s.info.name ?? undefined,
81
- description: s.info.labels["cs.description"],
82
- privacy: s.info.labels["cs.privacy"] === "public"
83
- ? "unlisted"
84
- : s.info.labels["cs.privacy"] === "public-hosts"
85
- ? "private"
86
- : (s.info.labels["cs.privacy"] ?? "private"),
87
- tags: JSON.parse(s.info.labels["cs.tags"] ?? "[]"),
88
- });
89
- function validateHibernationTimeout(seconds) {
90
- if (seconds !== undefined && (!Number.isSafeInteger(seconds) || seconds < 0 || seconds > 86_400))
91
- throw new RangeError("hibernationTimeoutSeconds must be an integer from 0 to 86400.");
92
- }
93
- export class Sandboxes {
94
- runtime;
95
- constructor(runtime) {
96
- this.runtime = runtime;
97
- }
98
- get defaultTemplateId() {
99
- return DEFAULT_TEMPLATE;
100
- }
101
- async create(options = {}) {
102
- only("CodeSandbox create", options, [
103
- "id",
104
- "title",
105
- "description",
106
- "tags",
107
- "privacy",
108
- "vmTier",
109
- "hibernationTimeoutSeconds",
110
- "automaticWakeupConfig",
111
- "ipcountry",
112
- ]);
113
- if (options.ipcountry)
114
- throw new CompatibilityError("CodeSandbox", "ipcountry; Runtime's sandboxes run in us-east");
115
- validateHibernationTimeout(options.hibernationTimeoutSeconds);
116
- const autoWake = wakeup(options.automaticWakeupConfig);
117
- const labels = {
118
- "compat.provider": "codesandbox",
119
- "cs.tags": JSON.stringify([...new Set([...(options.tags ?? []), "sdk"])]),
120
- "cs.privacy": options.privacy ?? "public-hosts",
121
- "cs.description": options.description ?? "",
122
- };
123
- if (options.id && options.id !== DEFAULT_TEMPLATE) {
124
- const source = await this.runtime.sandboxes.get(options.id);
125
- const fork = await source.fork({ name: options.title, labels });
126
- if (options.hibernationTimeoutSeconds !== undefined || autoWake !== undefined)
127
- await fork.update({
128
- ...(options.hibernationTimeoutSeconds !== undefined
129
- ? { idlePauseSeconds: options.hibernationTimeoutSeconds }
130
- : {}),
131
- ...(autoWake !== undefined ? { autoWake } : {}),
132
- });
133
- const sandbox = new Sandbox(fork, "FORK");
134
- if (options.vmTier)
135
- await sandbox.updateTier(options.vmTier);
136
- return sandbox;
137
- }
138
- const tier = options.vmTier ?? VMTier.Pico;
139
- const sandbox = await create(this.runtime, "codesandbox", {
140
- name: options.title,
141
- labels,
142
- vcpu: tier.cpuCores,
143
- memoryMiB: tier.memoryGiB * 1024,
144
- diskMiB: Math.ceil((tier.diskGB * 1e9) / 1048576),
145
- idlePauseSeconds: options.hibernationTimeoutSeconds,
146
- persistent: true,
147
- ...(autoWake !== undefined ? { autoWake } : {}),
148
- }, {}, async (sandbox) => {
149
- await sandbox.exec(["sudo", "mkdir", "-p", "/project/sandbox"], { check: true });
150
- await sandbox.exec("sudo chown $(id -u):$(id -g) /project/sandbox", { check: true });
151
- });
152
- return new Sandbox(sandbox, "CLEAN");
153
- }
154
- async resume(id) {
155
- const s = await this.runtime.sandboxes.get(id);
156
- const boot = s.state === "paused" ? "RESUME" : s.state === "stopped" ? "CLEAN" : "RUNNING";
157
- return new Sandbox(await ready(s), boot);
158
- }
159
- async hibernate(id) {
160
- await (await this.runtime.sandboxes.get(id)).pause();
161
- }
162
- async shutdown(id) {
163
- await (await this.runtime.sandboxes.get(id)).stop();
164
- }
165
- async delete(id) {
166
- await destroy(await this.runtime.sandboxes.get(id));
167
- }
168
- async restart(id, options = {}) {
169
- only("CodeSandbox restart", options, ["hibernationTimeoutSeconds"]);
170
- validateHibernationTimeout(options.hibernationTimeoutSeconds);
171
- const s = await this.runtime.sandboxes.get(id);
172
- await s.stop();
173
- await s.restart();
174
- if (options.hibernationTimeoutSeconds !== undefined)
175
- await s.update({ idlePauseSeconds: options.hibernationTimeoutSeconds });
176
- return new Sandbox(s, "CLEAN");
177
- }
178
- fork(id, options = {}) {
179
- return this.create({ ...options, id });
180
- }
181
- /** The account's running CodeSandbox-adapter sandboxes. Runtime has no
182
- * per-account count of running machines, so the limit is null. */
183
- async listRunning() {
184
- const running = (await all(this.runtime, "codesandbox")).filter((s) => s.state === "running");
185
- return {
186
- concurrentVmCount: running.length,
187
- concurrentVmLimit: null,
188
- vms: running.map((s) => ({
189
- id: s.id,
190
- creditBasis: undefined,
191
- lastActiveAt: s.info.lastActiveAt ? new Date(s.info.lastActiveAt) : undefined,
192
- sessionStartedAt: s.info.readyAt ? new Date(s.info.readyAt) : undefined,
193
- specs: {
194
- cpu: s.info.vcpu,
195
- memory: s.info.memoryMiB / 1024,
196
- storage: s.info.diskMiB / 1024,
197
- },
198
- })),
199
- };
200
- }
201
- async get(id) {
202
- return metadata(await this.runtime.sandboxes.get(id));
203
- }
204
- async list(options = {}) {
205
- only("CodeSandbox list", options, [
206
- "tags",
207
- "status",
208
- "limit",
209
- "pagination",
210
- "direction",
211
- "orderBy",
212
- ]);
213
- if (options.orderBy === "updated_at")
214
- throw new CompatibilityError("CodeSandbox", "sorting by updated_at");
215
- const limit = options.limit ?? 50;
216
- let currentPage = options.pagination?.page ?? 1;
217
- const pageSize = options.pagination?.pageSize ?? limit;
218
- for (const [name, value] of [
219
- ["limit", limit],
220
- ["page", currentPage],
221
- ["pageSize", pageSize],
222
- ])
223
- if (!Number.isSafeInteger(value) || value <= 0)
224
- throw new RangeError(`${name} must be a positive safe integer.`);
225
- const sandboxes = (await all(this.runtime, "codesandbox"))
226
- .filter((s) => (!options.status || s.state === "running") &&
227
- (options.tags ?? []).every((tag) => metadata(s).tags.includes(tag)))
228
- .map(metadata);
229
- sandboxes.sort((a, b) => (a.createdAt.getTime() - b.createdAt.getTime()) * (options.direction === "desc" ? -1 : 1));
230
- const totalCount = sandboxes.length;
231
- const selected = [];
232
- let nextPage;
233
- for (;;) {
234
- const offset = (currentPage - 1) * pageSize;
235
- selected.push(...sandboxes.slice(offset, offset + pageSize));
236
- nextPage = offset + pageSize < totalCount ? currentPage + 1 : null;
237
- if (nextPage === null || selected.length >= limit)
238
- break;
239
- currentPage = nextPage;
240
- }
241
- return {
242
- sandboxes: selected,
243
- totalCount,
244
- hasMore: totalCount > selected.length,
245
- pagination: { currentPage, nextPage, pageSize },
246
- };
247
- }
248
- }
249
- export class Sandbox {
250
- native;
251
- bootupType;
252
- constructor(native, bootupType) {
253
- this.native = native;
254
- this.bootupType = bootupType;
255
- }
256
- get id() {
257
- return this.native.id;
258
- }
259
- get cluster() {
260
- return this.native.info.region;
261
- }
262
- /** Runtime's guest agent is updated with the host: always current. */
263
- get isUpToDate() {
264
- return true;
265
- }
266
- /** Resizes to the tier's CPUs and memory; a running sandbox restarts, as CodeSandbox's does. */
267
- async updateTier(tier) {
268
- await this.native.resize({ vcpu: tier.cpuCores, memoryMiB: tier.memoryGiB * 1024 });
269
- }
270
- async updateHibernationTimeout(timeoutSeconds) {
271
- await this.native.update({ idlePauseSeconds: timeoutSeconds });
272
- }
273
- async connect(options = {}) {
274
- only("CodeSandbox session", options, ["id", "env", "permission"]);
275
- if (options.permission === "read")
276
- throw new CompatibilityError("CodeSandbox", "read-only editor sessions");
277
- const client = new SandboxClient(this.native, options.env ?? {});
278
- await client.initialize();
279
- return client;
280
- }
281
- }
282
- refuse("CodeSandbox", "Sandbox", Sandbox, {
283
- createSession: "use sandbox.connect(); a browser reaches a Runtime sandbox with a session token from the native sandbox.sessions.create()",
284
- createBrowserSession: "make a session token with the native sandbox.sessions.create() and open it with Runtime's Sandbox.fromSession",
285
- });
286
- export class CommandError extends Error {
287
- exitCode;
288
- output;
289
- constructor(message, exitCode, output) {
290
- super(message);
291
- this.exitCode = exitCode;
292
- this.output = output;
293
- this.name = "CommandError";
294
- }
295
- }
296
- function emitter() {
297
- const listeners = new Set();
298
- return {
299
- event: (listener) => {
300
- listeners.add(listener);
301
- return { dispose: () => listeners.delete(listener) };
302
- },
303
- fire: (value) => {
304
- for (const listener of listeners)
305
- listener(value);
306
- },
307
- clear: () => listeners.clear(),
308
- };
309
- }
310
- export class Command {
311
- process;
312
- command;
313
- name;
314
- startAgain;
315
- onOutput;
316
- onStatusChange;
317
- outputEvent = emitter();
318
- statusEvent = emitter();
319
- output = "";
320
- result;
321
- resolveResult;
322
- rejectResult;
323
- generation = 0;
324
- subscription = new AbortController();
325
- transition = Promise.resolve();
326
- currentStatus = "RUNNING";
327
- get status() {
328
- return this.currentStatus;
329
- }
330
- set status(value) {
331
- if (value === this.currentStatus)
332
- return;
333
- this.currentStatus = value;
334
- this.statusEvent.fire(value);
335
- }
336
- constructor(process, command, name, startAgain) {
337
- this.process = process;
338
- this.command = command;
339
- this.name = name;
340
- this.startAgain = startAgain;
341
- this.onOutput = this.outputEvent.event;
342
- this.onStatusChange = this.statusEvent.event;
343
- this.result = new Promise((resolve, reject) => {
344
- this.resolveResult = resolve;
345
- this.rejectResult = reject;
346
- });
347
- this.result.catch(() => undefined);
348
- void this.follow(process, this.generation, this.subscription.signal);
349
- }
350
- setStatus(status) {
351
- this.status = status;
352
- }
353
- async follow(process, generation, signal) {
354
- try {
355
- let ended = false;
356
- for await (const event of process.output({ signal })) {
357
- if (generation !== this.generation)
358
- return;
359
- if (event.type === "stdout" || event.type === "stderr") {
360
- this.output += event.data;
361
- this.outputEvent.fire(event.data);
362
- }
363
- else if (event.type === "truncated") {
364
- throw new Error("Command output was truncated by the host.");
365
- }
366
- else if (event.type === "exit") {
367
- ended = true;
368
- this.setStatus(event.exitCode === 0 ? "FINISHED" : "ERROR");
369
- if (event.exitCode !== 0)
370
- throw new CommandError(`Command failed with exit code ${event.exitCode ?? "unknown"}`, event.exitCode ?? 1, this.output);
371
- this.resolveResult(this.output);
372
- }
373
- }
374
- if (!ended && generation === this.generation)
375
- throw new Error("Command output ended before its exit status arrived.");
376
- }
377
- catch (error) {
378
- if (generation !== this.generation)
379
- return;
380
- this.setStatus("ERROR");
381
- this.rejectResult(error instanceof Error ? error : new Error(String(error)));
382
- }
383
- }
384
- /** Detach this client's subscription without terminating the guest command. */
385
- detach() {
386
- this.generation++;
387
- this.subscription.abort();
388
- this.setStatus("ERROR");
389
- this.rejectResult(new Error("Sandbox client is disconnected."));
390
- }
391
- async open(dimensions) {
392
- if (dimensions)
393
- await this.process.resize(dimensions.cols, dimensions.rows);
394
- return this.output;
395
- }
396
- /** Internal task bridge: read without yielding between log handoff and events. */
397
- get bufferedOutput() {
398
- return this.output;
399
- }
400
- waitUntilComplete() {
401
- return this.result;
402
- }
403
- serial(work) {
404
- const pending = this.transition.then(work);
405
- this.transition = pending.catch(() => undefined);
406
- return pending;
407
- }
408
- restart() {
409
- return this.serial(async () => {
410
- if (this.status !== "RUNNING")
411
- throw new Error("Command is not running");
412
- if (!this.startAgain)
413
- throw new CompatibilityError("CodeSandbox", "restarting a command from a different client");
414
- // Fence the old subscription before killing: its delayed exit must not
415
- // complete a waiter or overwrite the replacement command's status.
416
- this.generation++;
417
- this.subscription.abort();
418
- try {
419
- await this.process.kill("SIGKILL");
420
- this.process = await this.startAgain();
421
- this.subscription = new AbortController();
422
- void this.follow(this.process, this.generation, this.subscription.signal);
423
- }
424
- catch (error) {
425
- this.setStatus("ERROR");
426
- const failure = error instanceof Error ? error : new Error(String(error));
427
- this.rejectResult(failure);
428
- throw failure;
429
- }
430
- });
431
- }
432
- kill() {
433
- return this.serial(async () => {
434
- this.generation++;
435
- this.subscription.abort();
436
- try {
437
- await this.process.kill("SIGKILL");
438
- this.setStatus("KILLED");
439
- this.rejectResult(new CommandError("Command failed with exit code unknown", 1, this.output));
440
- }
441
- catch (error) {
442
- this.setStatus("ERROR");
443
- const failure = error instanceof Error ? error : new Error(String(error));
444
- this.rejectResult(failure);
445
- throw failure;
446
- }
447
- });
448
- }
449
- }
450
- export class FileSystem {
451
- native;
452
- files;
453
- constructor(native) {
454
- this.native = native;
455
- this.files = new GuestFiles(async () => native, "/project/sandbox");
456
- }
457
- async writeFile(path, content, options = {}) {
458
- only("CodeSandbox file write", options, ["create", "overwrite"]);
459
- const exists = await this.files.exists(path);
460
- if (!exists && options.create === false)
461
- throw new Error(`File does not exist: ${path}`);
462
- if (exists && options.overwrite === false)
463
- throw new Error(`File already exists: ${path}`);
464
- await this.files.writeFile(path, content);
465
- }
466
- writeTextFile(path, content, options) {
467
- return this.writeFile(path, new TextEncoder().encode(content), options);
468
- }
469
- async batchWrite(files) {
470
- for (const f of files)
471
- await this.files.writeFile(f.path, f.content);
472
- }
473
- readFile(path) {
474
- return this.files.readFile(path);
475
- }
476
- readTextFile(path) {
477
- return this.files.readTextFile(path);
478
- }
479
- mkdir(path, recursive = false) {
480
- return this.files.mkdir(path, recursive);
481
- }
482
- remove(path, recursive = false) {
483
- return this.files.remove(path, recursive);
484
- }
485
- rename(from, to, overwrite = false) {
486
- return this.files.rename(from, to, overwrite);
487
- }
488
- copy(from, to, recursive = false, overwrite = false) {
489
- return this.files.copy(from, to, recursive, overwrite);
490
- }
491
- async readdir(path) {
492
- return (await this.files.readdir(path)).map((e) => ({
493
- name: e.name,
494
- type: e.type === "directory" ? "directory" : "file",
495
- isSymlink: e.type === "symlink",
496
- }));
497
- }
498
- /** Changes under a path, as CodeSandbox's add, change and remove events. */
499
- async watch(path, options = {}) {
500
- only("CodeSandbox watch", options, ["recursive", "excludes"]);
501
- const events = emitter();
502
- const handle = await this.native.files.watch(this.files.path(path), (e) => {
503
- if (e.type === "rename") {
504
- if (e.oldPath)
505
- events.fire({ paths: [e.oldPath], type: "remove" });
506
- events.fire({ paths: [e.path], type: "add" });
507
- }
508
- else
509
- events.fire({
510
- paths: [e.path],
511
- type: e.type === "create" ? "add" : e.type === "remove" ? "remove" : "change",
512
- });
513
- }, {
514
- recursive: options.recursive ?? false,
515
- ...(options.excludes?.length ? { exclude: [...options.excludes] } : {}),
516
- timeoutMs: 0,
517
- });
518
- return {
519
- onEvent: events.event,
520
- dispose: () => {
521
- events.clear();
522
- void handle.stop().catch(() => undefined);
523
- },
524
- };
525
- }
526
- async stat(path) {
527
- const e = await this.files.stat(path);
528
- const r = await this.native.exec(["stat", "-c", "%X %Y %Z", "--", this.files.path(path)], {
529
- check: true,
530
- });
531
- const [atime, mtime, ctime] = r.stdout.trim().split(" ").map(Number);
532
- return {
533
- type: e.type === "directory" ? "directory" : "file",
534
- isSymlink: e.type === "symlink",
535
- size: e.size,
536
- atime: atime * 1000,
537
- mtime: mtime * 1000,
538
- ctime: ctime * 1000,
539
- };
540
- }
541
- }
542
- refuse("CodeSandbox", "FileSystem", FileSystem, {
543
- download: "read it with fs.readFile, or with the native sandbox.files.download(); Runtime has no signed download links",
544
- });
545
- const commandPath = (id) => `/workspace/.runtime-compat/codesandbox/commands/${encodeURIComponent(id)}.json`;
546
- /** A shell CodeSandbox lists: a command's name is JSON whose type is "command". */
547
- export function isCommandShell(shell) {
548
- try {
549
- return JSON.parse(shell.name).type === "command";
550
- }
551
- catch {
552
- return false;
553
- }
554
- }
555
- export class SandboxCommands {
556
- session;
557
- constructor(session) {
558
- this.session = session;
559
- }
560
- async runBackground(command, options = {}) {
561
- only("CodeSandbox command", options, ["env", "cwd", "name", "dimensions", "asGlobalSession"]);
562
- if (options.asGlobalSession)
563
- throw new CompatibilityError("CodeSandbox", "global editor sessions");
564
- const { native, env, workspacePath } = this.session;
565
- this.session.assertConnected();
566
- const { stdin: _stdin, ...spawnOptions } = await execOptions(native, {
567
- env: { ...env, ...options.env },
568
- cwd: options.cwd ?? workspacePath,
569
- });
570
- // The published SDK treats arrays as sequential shell commands, not argv.
571
- const saved = {
572
- version: 1,
573
- command: Array.isArray(command) ? command.join(" && ") : command,
574
- name: options.name,
575
- options: {
576
- ...spawnOptions,
577
- env: { ...spawnOptions.env },
578
- pty: { ...(options.dimensions ?? { cols: 128, rows: 24 }) },
579
- },
580
- };
581
- return this.session.attach(await this.session.start(saved), saved);
582
- }
583
- async run(command, options) {
584
- return (await this.runBackground(command, options)).waitUntilComplete();
585
- }
586
- async getAll() {
587
- const { native } = this.session;
588
- this.session.assertConnected();
589
- const commands = [];
590
- for (const saved of await savedShells(native))
591
- if (saved.taskId === undefined && saved.kind !== "terminal")
592
- commands.push(this.session.attach(await native.processes.get(saved.processId), saved));
593
- return commands;
594
- }
595
- }
596
- /** The running processes this adapter started, with what it saved about each. */
597
- async function savedShells(native) {
598
- const shells = [];
599
- for (const process of await native.processes.list()) {
600
- if (process.state !== "running" || !(await native.files.exists(commandPath(process.id))))
601
- continue;
602
- const saved = JSON.parse(await native.files.readText(commandPath(process.id)));
603
- if (saved.version !== 1 || typeof saved.command !== "string" || !saved.options)
604
- throw new Error(`Invalid saved CodeSandbox command: ${process.id}`);
605
- shells.push({ ...saved, processId: process.id });
606
- }
607
- return shells;
608
- }
609
- /** The ports listening in the sandbox, from the kernel's socket tables. */
610
- const LISTENING = String.raw `import sys
611
- ports=set()
612
- for name in ("/proc/net/tcp","/proc/net/tcp6"):
613
- try:
614
- for line in open(name).readlines()[1:]:
615
- f=line.split()
616
- if f[3]=="0A": ports.add(int(f[1].rsplit(":",1)[1],16))
617
- except FileNotFoundError: pass
618
- print(" ".join(str(p) for p in sorted(ports)))`;
619
- export class Ports {
620
- session;
621
- opened = emitter();
622
- closed = emitter();
623
- watching;
624
- known;
625
- polling = false;
626
- constructor(session) {
627
- this.session = session;
628
- }
629
- /** A port's events start a watch of the sandbox's listening ports, once a second. */
630
- get onDidPortOpen() {
631
- return (listener) => this.subscribe(this.opened.event(listener));
632
- }
633
- get onDidPortClose() {
634
- return (listener) => this.subscribe(this.closed.event(listener));
635
- }
636
- subscribe(subscription) {
637
- this.watching ??= setInterval(() => void this.poll(), 1000);
638
- void this.poll();
639
- return {
640
- dispose: () => {
641
- subscription.dispose();
642
- },
643
- };
644
- }
645
- /** The ports listening now. */
646
- async listening() {
647
- const r = await this.session.native.exec(["python3", "-c", LISTENING], { check: true });
648
- return r.stdout.trim() ? r.stdout.trim().split(" ").map(Number) : [];
649
- }
650
- async poll() {
651
- if (this.polling)
652
- return;
653
- this.polling = true;
654
- try {
655
- const now = new Set(await this.listening());
656
- const before = this.known;
657
- this.known = now;
658
- if (!before)
659
- return;
660
- for (const port of now)
661
- if (!before.has(port))
662
- this.opened.fire(await this.get(port));
663
- for (const port of before)
664
- if (!now.has(port))
665
- this.closed.fire(port);
666
- }
667
- catch {
668
- // A failed look is tried again at the next tick.
669
- }
670
- finally {
671
- this.polling = false;
672
- }
673
- }
674
- dispose() {
675
- clearInterval(this.watching);
676
- this.watching = undefined;
677
- this.opened.clear();
678
- this.closed.clear();
679
- }
680
- async get(port) {
681
- const { native, previewURLs } = this.session;
682
- this.session.assertConnected();
683
- if (native.info.labels["cs.privacy"] === "private")
684
- throw new CompatibilityError("CodeSandbox", "private port host authentication; use Runtime signed preview URLs");
685
- const p = await native.previews.create(port, { visibility: "public" });
686
- previewURLs.set(port, p.urlWithToken ?? p.url);
687
- return { port, host: new URL(p.urlWithToken ?? p.url).host };
688
- }
689
- async getAll() {
690
- this.session.assertConnected();
691
- return (await this.session.native.previews.list()).map((p) => {
692
- this.session.previewURLs.set(p.port, p.urlWithToken ?? p.url);
693
- return { port: p.port, host: new URL(p.url).host };
694
- });
695
- }
696
- async waitForPort(port, options = {}) {
697
- only("CodeSandbox waitForPort", options, ["timeoutMs"]);
698
- this.session.assertConnected();
699
- if (!Number.isInteger(port) || port < 1 || port > 65535)
700
- throw new TypeError("Invalid port");
701
- await this.session.native.exec([
702
- "python3",
703
- "-c",
704
- 'import socket,sys,time\nport=int(sys.argv[1]); end=time.monotonic()+float(sys.argv[2])/1000\nwhile True:\n try:\n s=socket.create_connection(("127.0.0.1",port),timeout=0.25); s.close(); break\n except OSError:\n if time.monotonic() >= end: raise TimeoutError("Port did not open")\n time.sleep(0.1)',
705
- String(port),
706
- String(options.timeoutMs ?? 30000),
707
- ], { check: true, timeoutMs: (options.timeoutMs ?? 30000) + 1000 });
708
- return this.get(port);
709
- }
710
- }
711
- /** URLs of the ports this client exposed with ports.get or listed with ports.getAll. */
712
- export class Hosts {
713
- session;
714
- constructor(session) {
715
- this.session = session;
716
- }
717
- getUrl(port, protocol = "https") {
718
- const url = this.session.previewURLs.get(port);
719
- if (!url)
720
- throw new Error(`Port ${port} has not been exposed; call ports.get(${port}) first`);
721
- const at = new URL(url);
722
- at.protocol = `${protocol}:`;
723
- return at.toString();
724
- }
725
- /** Public previews need no token: nothing to send. */
726
- getHeaders() {
727
- return {};
728
- }
729
- getCookies() {
730
- return {};
731
- }
732
- }
733
- /** Interactive shells, each a process with a terminal of its own. */
734
- export class Terminals {
735
- session;
736
- constructor(session) {
737
- this.session = session;
738
- }
739
- async create(command = "bash", options = {}) {
740
- only("CodeSandbox terminal", options, ["env", "cwd", "name", "dimensions", "asGlobalSession"]);
741
- if (options.asGlobalSession)
742
- throw new CompatibilityError("CodeSandbox", "global editor sessions");
743
- if (!["bash", "zsh", "fish", "ksh", "dash"].includes(command))
744
- throw new TypeError(`Unknown shell: ${command}`);
745
- const { native, env, workspacePath } = this.session;
746
- this.session.assertConnected();
747
- const { stdin: _stdin, ...spawnOptions } = await execOptions(native, {
748
- env: { ...env, ...options.env },
749
- cwd: options.cwd ?? workspacePath,
750
- });
751
- const saved = {
752
- version: 1,
753
- kind: "terminal",
754
- command,
755
- name: options.name,
756
- options: {
757
- ...spawnOptions,
758
- env: { ...spawnOptions.env },
759
- stdin: "pipe",
760
- pty: { ...(options.dimensions ?? { cols: 80, rows: 24 }) },
761
- },
762
- };
763
- const process = await this.session.start(saved);
764
- return new Terminal(process, options.name ?? command);
765
- }
766
- async get(shellId) {
767
- return (await this.getAll()).find((terminal) => terminal.id === shellId);
768
- }
769
- async getAll() {
770
- const { native } = this.session;
771
- this.session.assertConnected();
772
- const terminals = [];
773
- for (const saved of await savedShells(native))
774
- if (saved.kind === "terminal")
775
- terminals.push(new Terminal(await native.processes.get(saved.processId), saved.name ?? saved.command));
776
- return terminals;
777
- }
778
- }
779
- export class Terminal {
780
- process;
781
- name;
782
- outputEvent = emitter();
783
- onOutput = this.outputEvent.event;
784
- output = [];
785
- following;
786
- constructor(process, name) {
787
- this.process = process;
788
- this.name = name;
789
- }
790
- get id() {
791
- return this.process.id;
792
- }
793
- /** Its output so far, and what it prints from now on through onOutput. */
794
- async open(dimensions = { cols: 80, rows: 24 }) {
795
- await this.process.resize(dimensions.cols, dimensions.rows);
796
- if (!this.following) {
797
- const info = await this.process.refresh();
798
- const end = info.outputBytes;
799
- const signal = (this.following = new AbortController()).signal;
800
- let replayed = "";
801
- let caughtUp;
802
- const ready = new Promise((resolve) => (caughtUp = resolve));
803
- if (end <= info.firstOffset)
804
- caughtUp();
805
- void (async () => {
806
- try {
807
- for await (const e of this.process.output({ signal }))
808
- if (e.type === "stdout" || e.type === "stderr") {
809
- if (e.offset < end)
810
- replayed += e.data;
811
- else {
812
- this.output.push(e.data);
813
- this.outputEvent.fire(e.data);
814
- }
815
- if (e.offset + new TextEncoder().encode(e.data).length >= end)
816
- caughtUp();
817
- }
818
- else if (e.type === "exit")
819
- break;
820
- }
821
- catch {
822
- // The terminal ended, or this client let go of it.
823
- }
824
- finally {
825
- caughtUp();
826
- }
827
- })();
828
- await ready;
829
- this.output.unshift(replayed);
830
- }
831
- return this.output.join("");
832
- }
833
- async write(input, dimensions) {
834
- if (dimensions)
835
- await this.process.resize(dimensions.cols, dimensions.rows);
836
- await this.process.write(input);
837
- }
838
- run(input, dimensions) {
839
- return this.write(`${input}\n`, dimensions);
840
- }
841
- async kill() {
842
- this.following?.abort();
843
- await this.process.kill("SIGKILL");
844
- }
845
- }
846
- /** One-off JavaScript and Python snippets, run as CodeSandbox runs them: the
847
- * last line's value is printed. */
848
- export class Interpreters {
849
- commands;
850
- constructor(commands) {
851
- this.commands = commands;
852
- }
853
- javascript(code) {
854
- const body = code
855
- .split("\n")
856
- .map((line, i, lines) => i === lines.length - 1 && !line.startsWith("return") ? `return ${line}` : line)
857
- .join("\n");
858
- return this.commands.run(`node -p "$(cat <<'EOF'\n(() => {${body}})()\nEOF\n)"`, {
859
- env: { NO_COLOR: "true" },
860
- });
861
- }
862
- python(code) {
863
- const body = code
864
- .split("\n")
865
- .map((line, i, lines) => i === lines.length - 1 && !line.startsWith("print") ? `print(${line})` : line)
866
- .join("\n");
867
- return this.commands.run(`python3 <<'PYCODE'\n${body}\nPYCODE\n`);
868
- }
869
- }
870
- export class SandboxClient {
871
- native;
872
- env;
873
- fs;
874
- commands;
875
- ports;
876
- terminals;
877
- interpreters;
878
- hosts;
879
- tasks;
880
- setup;
881
- workspacePath = "/project/sandbox";
882
- disconnected = false;
883
- attached = new Set();
884
- previewURLs = new Map();
885
- stateEvent = emitter();
886
- stopKeepAlive;
887
- constructor(native, env) {
888
- this.native = native;
889
- this.env = env;
890
- this.fs = new FileSystem(native);
891
- this.tasks = new Tasks(this, native);
892
- this.setup = new Setup(this, native);
893
- const session = {
894
- native,
895
- env,
896
- workspacePath: this.workspacePath,
897
- assertConnected: () => this.assertConnected(),
898
- start: (saved) => this.start(saved),
899
- attach: (process, saved) => this.attach(process, saved),
900
- previewURLs: this.previewURLs,
901
- };
902
- this.commands = new SandboxCommands(session);
903
- this.ports = new Ports(session);
904
- this.terminals = new Terminals(session);
905
- this.interpreters = new Interpreters(this.commands);
906
- this.hosts = new Hosts(session);
907
- }
908
- /** Runtime's guest agent is updated with the host: always current. */
909
- get isUpToDate() {
910
- return true;
911
- }
912
- /** The sandbox's page in Runtime's console. */
913
- get editorUrl() {
914
- return `https://withruntime.com/account/sandboxes/${encodeURIComponent(this.native.id)}`;
915
- }
916
- get onStateChange() {
917
- return this.stateEvent.event;
918
- }
919
- async initialize() {
920
- await this.tasks.getAll();
921
- await this.setup.initialize(true);
922
- }
923
- previewURL(port) {
924
- const url = this.previewURLs.get(port);
925
- if (!url)
926
- throw new Error("Port has not been exposed");
927
- return url;
928
- }
929
- assertConnected() {
930
- if (this.disconnected)
931
- throw new Error("Sandbox client is disconnected.");
932
- }
933
- async start(saved) {
934
- this.assertConnected();
935
- const process = await this.native.spawn(saved.command, saved.options);
936
- try {
937
- // Arguments and environment may contain credentials. Keep them in the
938
- // guest's private file, never resource labels or public process metadata.
939
- await this.native.files.write(commandPath(process.id), JSON.stringify(saved), {
940
- mode: 0o600,
941
- });
942
- return process;
943
- }
944
- catch (error) {
945
- try {
946
- await process.kill("SIGKILL");
947
- }
948
- catch (cleanup) {
949
- throw new AggregateError([error, cleanup], "Command metadata failed and cleanup could not be confirmed");
950
- }
951
- throw error;
952
- }
953
- }
954
- attach(process, saved) {
955
- const command = new Command(process, saved.command, saved.name, () => this.start(saved));
956
- this.attached.add(command);
957
- return command;
958
- }
959
- get id() {
960
- return this.native.id;
961
- }
962
- get state() {
963
- return this.disconnected ? "DISCONNECTED" : "CONNECTED";
964
- }
965
- async disconnect() {
966
- if (!this.disconnected)
967
- this.stateEvent.fire("DISCONNECTED");
968
- this.disconnected = true;
969
- this.ports.dispose();
970
- this.tasks.dispose();
971
- this.setup.dispose();
972
- for (const command of this.attached)
973
- command.detach();
974
- this.attached.clear();
975
- this.stopKeepAlive?.();
976
- }
977
- async reconnect() {
978
- await ready(await this.native.refresh());
979
- if (this.disconnected)
980
- this.stateEvent.fire("CONNECTED");
981
- this.disconnected = false;
982
- await this.tasks.reconnect();
983
- await this.setup.reconnect();
984
- }
985
- keepActiveWhileConnected(enabled) {
986
- this.stopKeepAlive?.();
987
- if (enabled)
988
- this.stopKeepAlive = this.native.keepAlive();
989
- }
990
- dispose() {
991
- if (!this.disconnected)
992
- this.stateEvent.fire("DISCONNECTED");
993
- this.disconnected = true;
994
- this.ports.dispose();
995
- this.tasks.dispose();
996
- this.setup.dispose();
997
- for (const command of this.attached)
998
- command.detach();
999
- this.attached.clear();
1000
- this.stopKeepAlive?.();
1001
- this.stateEvent.clear();
1002
- }
1003
- }
1004
- refuse("CodeSandbox", "SandboxClient", { prototype: SandboxClient }, {
1005
- create: "connect with sandbox.connect(); Runtime has no separate session handshake",
1006
- });
1007
- /** Configured tasks share durable native processes between client connections. */
1008
- export class Tasks {
1009
- client;
1010
- native;
1011
- cached;
1012
- managed;
1013
- loaded = [];
1014
- cancelled = new AbortController();
1015
- constructor(client, native) {
1016
- this.client = client;
1017
- this.native = native;
1018
- this.managed = new ManagedTasks(native);
1019
- }
1020
- getAll() {
1021
- if (this.client.state !== "CONNECTED")
1022
- return Promise.reject(new Error("Sandbox client is disconnected."));
1023
- return (this.cached ??= this.load().catch((error) => {
1024
- this.cached = undefined;
1025
- throw error;
1026
- }));
1027
- }
1028
- async get(id) {
1029
- return (await this.getAll()).find((task) => task.id === id);
1030
- }
1031
- async reconnect() {
1032
- if (this.cached)
1033
- for (const task of await this.cached)
1034
- task.dispose();
1035
- this.cached = undefined;
1036
- this.cancelled = new AbortController();
1037
- await this.getAll();
1038
- }
1039
- dispose() {
1040
- this.cancelled.abort();
1041
- for (const task of this.loaded)
1042
- task.dispose();
1043
- }
1044
- async load() {
1045
- const path = `${this.client.workspacePath}/.codesandbox/tasks.json`;
1046
- let config;
1047
- if (await this.native.files.exists(path)) {
1048
- config = JSON.parse(await this.native.files.readText(path));
1049
- only("CodeSandbox tasks config", config, ["$schema", "tasks", "setupTasks"]);
1050
- }
1051
- else {
1052
- const packagePath = `${this.client.workspacePath}/package.json`;
1053
- if (!(await this.native.files.exists(packagePath)))
1054
- return [];
1055
- const pkg = JSON.parse(await this.native.files.readText(packagePath));
1056
- config = {
1057
- tasks: Object.fromEntries(Object.keys(pkg.scripts ?? {}).map((name) => [
1058
- name,
1059
- { name, command: `npm run ${quote(name)}` },
1060
- ])),
1061
- };
1062
- }
1063
- const tasks = [];
1064
- for (const [id, definition] of Object.entries(config.tasks ?? {})) {
1065
- only("CodeSandbox task", definition, ["name", "command", "runAtStart", "preview"]);
1066
- if (typeof definition.name !== "string" || typeof definition.command !== "string")
1067
- throw new TypeError(`Task ${id} requires a name and command`);
1068
- if (definition.runAtStart !== undefined && typeof definition.runAtStart !== "boolean")
1069
- throw new TypeError(`Task ${id} runAtStart must be a boolean`);
1070
- if (definition.preview) {
1071
- only("CodeSandbox task preview", definition.preview, ["port", "prLink", "pr-link"]);
1072
- if (definition.preview.port !== undefined &&
1073
- (!Number.isInteger(definition.preview.port) ||
1074
- definition.preview.port < 1 ||
1075
- definition.preview.port > 65535))
1076
- throw new TypeError(`Task ${id} has an invalid preview port`);
1077
- }
1078
- tasks.push(new Task(this.client, id, structuredClone(definition), this.managed));
1079
- }
1080
- if (tasks.length) {
1081
- const steps = (config.setupTasks ?? []).map((step) => typeof step === "string" ? { name: step, command: step } : step);
1082
- for (const step of steps) {
1083
- only("CodeSandbox setup step", step, ["name", "command"]);
1084
- if (typeof step.name !== "string" || typeof step.command !== "string")
1085
- throw new TypeError("Setup steps require a name and command");
1086
- }
1087
- const { env } = await execOptions(this.native, {});
1088
- await this.managed.install(config.tasks ?? {}, env ?? {}, { steps, source: setupRunner });
1089
- for (const task of tasks)
1090
- await task.reconnect();
1091
- }
1092
- this.loaded = tasks;
1093
- if (tasks.length)
1094
- this.monitor();
1095
- return tasks;
1096
- }
1097
- monitor() {
1098
- const signal = this.cancelled.signal;
1099
- void (async () => {
1100
- while (!signal.aborted) {
1101
- try {
1102
- for (const run of await this.managed.list(signal)) {
1103
- if (signal.aborted)
1104
- return;
1105
- this.loaded.find((task) => task.id === run.taskId)?.observe(run.process);
1106
- }
1107
- }
1108
- catch (error) {
1109
- if (signal.aborted)
1110
- return;
1111
- for (const task of this.loaded)
1112
- task.unavailable(error);
1113
- }
1114
- await new Promise((resolve) => {
1115
- const stop = () => {
1116
- clearTimeout(timer);
1117
- signal.removeEventListener("abort", stop);
1118
- resolve();
1119
- };
1120
- const timer = setTimeout(stop, 500);
1121
- signal.addEventListener("abort", stop, { once: true });
1122
- if (signal.aborted)
1123
- stop();
1124
- });
1125
- }
1126
- })();
1127
- }
1128
- }
1129
- export class Task {
1130
- client;
1131
- id;
1132
- definition;
1133
- managed;
1134
- process;
1135
- processId;
1136
- fault;
1137
- disposed = false;
1138
- opened = false;
1139
- streamedLength = 0;
1140
- openedLength = 0;
1141
- outputEvent = emitter();
1142
- statusEvent = emitter();
1143
- onOutput = this.outputEvent.event;
1144
- onStatusChange = this.statusEvent.event;
1145
- subscriptions = [];
1146
- transition = Promise.resolve();
1147
- exposed = [];
1148
- constructor(client, id, definition, managed) {
1149
- this.client = client;
1150
- this.id = id;
1151
- this.definition = definition;
1152
- this.managed = managed;
1153
- }
1154
- async reconnect() {
1155
- const process = await this.managed.get(this.id);
1156
- if (process)
1157
- this.observe(process);
1158
- }
1159
- observe(process) {
1160
- if (this.disposed)
1161
- return;
1162
- this.fault = undefined;
1163
- if (process.id === this.processId)
1164
- return;
1165
- this.process?.detach();
1166
- this.processId = process.id;
1167
- this.exposed = [];
1168
- this.streamedLength = 0;
1169
- this.openedLength = 0;
1170
- const command = new Command(process, this.command, this.name, () => this.managed.start(this.id));
1171
- if (process.info.state !== "running")
1172
- command.status = process.info.exitCode === 0 ? "FINISHED" : "ERROR";
1173
- this.attach(command);
1174
- this.statusEvent.fire(this.status);
1175
- }
1176
- unavailable(error) {
1177
- if (this.disposed)
1178
- return;
1179
- this.fault = error;
1180
- this.statusEvent.fire("ERROR");
1181
- }
1182
- get name() {
1183
- return this.definition.name;
1184
- }
1185
- get command() {
1186
- return this.definition.command;
1187
- }
1188
- get runAtStart() {
1189
- return Boolean(this.definition.runAtStart);
1190
- }
1191
- get status() {
1192
- if (this.fault)
1193
- return "ERROR";
1194
- return this.process?.status ?? "IDLE";
1195
- }
1196
- get ports() {
1197
- return this.exposed;
1198
- }
1199
- attach(command) {
1200
- for (const subscription of this.subscriptions)
1201
- subscription.dispose();
1202
- this.process = command;
1203
- this.subscriptions = [
1204
- command.onStatusChange((status) => this.statusEvent.fire(status)),
1205
- command.onOutput((output) => {
1206
- const start = this.streamedLength;
1207
- this.streamedLength += output.length;
1208
- if (this.opened && this.streamedLength > this.openedLength)
1209
- this.outputEvent.fire(output.slice(Math.max(0, this.openedLength - start)));
1210
- }),
1211
- ];
1212
- }
1213
- async open(dimensions) {
1214
- if (!this.process)
1215
- throw new Error("Task is not running");
1216
- await this.process.open(dimensions);
1217
- const output = await this.managed.output(this.processId);
1218
- const followed = this.process.bufferedOutput;
1219
- this.openedLength = Math.max(output.length, followed.length);
1220
- this.opened = true;
1221
- if (followed.length > output.length)
1222
- this.outputEvent.fire(followed.slice(output.length));
1223
- return output;
1224
- }
1225
- serial(work) {
1226
- const result = this.transition.then(work);
1227
- this.transition = result.catch(() => undefined);
1228
- return result;
1229
- }
1230
- run() {
1231
- return this.serial(async () => {
1232
- if (this.client.state !== "CONNECTED")
1233
- throw new Error("Sandbox client is disconnected.");
1234
- this.observe(await this.managed.start(this.id));
1235
- });
1236
- }
1237
- restart() {
1238
- return this.run();
1239
- }
1240
- stop() {
1241
- return this.serial(async () => {
1242
- if (this.client.state !== "CONNECTED")
1243
- throw new Error("Sandbox client is disconnected.");
1244
- const current = await this.managed.stop(this.id);
1245
- if (current) {
1246
- this.observe(current);
1247
- await this.process.kill();
1248
- }
1249
- });
1250
- }
1251
- async waitForPort(timeout = 30000) {
1252
- if (this.exposed.length)
1253
- return this.exposed[0];
1254
- const port = this.definition.preview?.port;
1255
- if (!port)
1256
- throw new CompatibilityError("CodeSandbox", "automatic task-to-port discovery; configure task.preview.port");
1257
- try {
1258
- const result = await this.client.ports.waitForPort(port, { timeoutMs: timeout });
1259
- const opened = { port: result.port, url: this.client.previewURL(result.port) };
1260
- this.exposed = [opened];
1261
- return opened;
1262
- }
1263
- catch (error) {
1264
- if (error.stderr?.includes("TimeoutError: Port did not open"))
1265
- throw new Error("Timeout waiting for port", { cause: error });
1266
- throw error;
1267
- }
1268
- }
1269
- dispose() {
1270
- this.disposed = true;
1271
- for (const subscription of this.subscriptions)
1272
- subscription.dispose();
1273
- this.subscriptions = [];
1274
- this.process?.detach();
1275
- this.outputEvent.clear();
1276
- this.statusEvent.clear();
1277
- }
1278
- }
1279
- const setupRoot = "/workspace/.runtime-compat/codesandbox/setup";
1280
- // The guest owns the sequence and lock; progress survives SDK disconnects.
1281
- const setupRunner = String.raw `import errno,fcntl,json,os,pty,select,signal,struct,subprocess,sys,termios,threading
1282
- with open(sys.argv[1]) as f: config=json.load(f)
1283
- root=os.path.dirname(sys.argv[1])
1284
- os.umask(0o077)
1285
- lock=open(os.path.join(root,'lock'),'a')
1286
- try: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
1287
- except BlockingIOError: sys.exit(0)
1288
- state={'state':'IN_PROGRESS','currentStepIndex':0,'runId':config['runId'],'config':config['config'],'steps':[dict(x,status='IDLE',log=os.path.join(root,config['runId']+'-'+str(i)+'.log')) for i,x in enumerate(config['steps'])]}
1289
- def save():
1290
- temp=os.path.join(root,'progress-'+config['runId']+'.tmp')
1291
- with open(temp,'w') as f: json.dump(state,f)
1292
- os.replace(temp,os.path.join(root,'progress.json'))
1293
- child=None
1294
- def stop(signum,frame):
1295
- if child is not None and child.poll() is None:
1296
- try: os.killpg(child.pid,signal.SIGTERM)
1297
- except ProcessLookupError: pass
1298
- try: child.wait(timeout=2)
1299
- except subprocess.TimeoutExpired:
1300
- try: os.killpg(child.pid,signal.SIGKILL)
1301
- except ProcessLookupError: pass
1302
- child.wait()
1303
- state['state']='STOPPED'
1304
- save()
1305
- sys.exit(128+signum)
1306
- signal.signal(signal.SIGTERM,stop)
1307
- signal.signal(signal.SIGINT,stop)
1308
- save()
1309
- try:
1310
- for i,step in enumerate(state['steps']):
1311
- state['currentStepIndex']=i
1312
- master,slave=pty.openpty()
1313
- fcntl.ioctl(slave,termios.TIOCSWINSZ,struct.pack('HHHH',24,128,0,0))
1314
- step['tty']=os.ttyname(slave)
1315
- save()
1316
- with open(step['log'],'wb',buffering=0) as output:
1317
- finished=threading.Event()
1318
- errors=[]
1319
- def collect():
1320
- try:
1321
- while True:
1322
- ready,_,_=select.select([master],[],[],0.05)
1323
- if not ready:
1324
- if finished.is_set(): break
1325
- continue
1326
- try: data=os.read(master,65536)
1327
- except OSError as e:
1328
- if e.errno==errno.EIO: break
1329
- raise
1330
- if not data: break
1331
- output.write(data)
1332
- except BaseException as e:
1333
- errors.append(str(e))
1334
- try: os.killpg(child.pid,signal.SIGKILL)
1335
- except ProcessLookupError: pass
1336
- finally: os.close(master)
1337
- try: child=subprocess.Popen(['bash','-c',step['command']],cwd=config['cwd'],stdin=slave,stdout=slave,stderr=slave,start_new_session=True)
1338
- finally: os.close(slave)
1339
- collector=threading.Thread(target=collect,daemon=True)
1340
- collector.start()
1341
- code=child.wait()
1342
- finished.set()
1343
- collector.join()
1344
- if errors: code=125
1345
- step['status']='SUCCEEDED' if code==0 else 'FAILED'
1346
- if code!=0:
1347
- state['state']='STOPPED'
1348
- save()
1349
- sys.exit(code)
1350
- save()
1351
- state['state']='FINISHED'
1352
- save()
1353
- except BaseException:
1354
- if state['state']=='IN_PROGRESS':
1355
- state['state']='STOPPED'
1356
- save()
1357
- raise
1358
- `;
1359
- // The cached progress can be stale: the step may have ended and its terminal
1360
- // closed, or on Linux its /dev/pts number been reused. Resize only while the
1361
- // guest's own progress still names this run's running step and terminal; a
1362
- // terminal that has gone needs no resize. O_NOCTTY keeps it from becoming the
1363
- // helper's controlling terminal.
1364
- const resizeStep = String.raw `import errno,fcntl,json,os,struct,sys,termios
1365
- progress,run,index,tty,rows,cols=sys.argv[1:7]
1366
- try:
1367
- with open(progress) as f: state=json.load(f)
1368
- except FileNotFoundError: sys.exit(0)
1369
- steps=state.get('steps') or []
1370
- i=int(index)
1371
- if state.get('runId')!=run or i>=len(steps) or steps[i].get('status')!='IDLE' or steps[i].get('tty')!=tty: sys.exit(0)
1372
- try: fd=os.open(tty,os.O_RDWR|os.O_NOCTTY)
1373
- except OSError as e:
1374
- if e.errno in (errno.ENOENT,errno.ENXIO,errno.EIO): sys.exit(0)
1375
- raise
1376
- try: fcntl.ioctl(fd,termios.TIOCSWINSZ,struct.pack('HHHH',int(rows),int(cols),0,0))
1377
- finally: os.close(fd)
1378
- `;
1379
- export class Setup {
1380
- client;
1381
- native;
1382
- progress = { state: "IDLE", currentStepIndex: 0, config: "", steps: [] };
1383
- steps = [];
1384
- loaded;
1385
- active;
1386
- starting;
1387
- failure;
1388
- ignoredRunId;
1389
- managedBoot = false;
1390
- cancelled = new AbortController();
1391
- changed = emitter();
1392
- onSetupProgressChange = this.changed.event;
1393
- constructor(client, native) {
1394
- this.client = client;
1395
- this.native = native;
1396
- }
1397
- get status() {
1398
- return this.progress.state;
1399
- }
1400
- get currentStepIndex() {
1401
- return this.progress.currentStepIndex;
1402
- }
1403
- getSteps() {
1404
- return this.steps;
1405
- }
1406
- async initialize(automatic = false) {
1407
- await (this.loaded ??= this.load());
1408
- if (automatic && this.status === "IDLE")
1409
- await this.run();
1410
- if (this.status === "IN_PROGRESS")
1411
- this.monitor();
1412
- }
1413
- async reconnect() {
1414
- await this.active;
1415
- this.cancelled = new AbortController();
1416
- this.failure = undefined;
1417
- this.ignoredRunId = undefined;
1418
- this.loaded = undefined;
1419
- await this.initialize(true);
1420
- }
1421
- async load() {
1422
- const path = `${this.client.workspacePath}/.codesandbox/tasks.json`;
1423
- const config = (await this.native.files.exists(path))
1424
- ? JSON.parse(await this.native.files.readText(path))
1425
- : {};
1426
- const definitions = (config.setupTasks ?? []).map((step) => typeof step === "string" ? { name: step, command: step } : step);
1427
- for (const definition of definitions) {
1428
- only("CodeSandbox setup step", definition, ["name", "command"]);
1429
- if (typeof definition.name !== "string" || typeof definition.command !== "string")
1430
- throw new TypeError("Setup steps require a name and command");
1431
- }
1432
- const identity = JSON.stringify(definitions);
1433
- this.progress = {
1434
- state: definitions.length ? "IDLE" : "FINISHED",
1435
- currentStepIndex: 0,
1436
- config: identity,
1437
- steps: definitions.map((step) => ({ ...step, status: "IDLE" })),
1438
- };
1439
- if (await this.native.files.exists(`${setupRoot}/progress.json`)) {
1440
- const stored = JSON.parse(await this.native.files.readText(`${setupRoot}/progress.json`));
1441
- if (stored.config === identity)
1442
- this.progress = stored;
1443
- }
1444
- this.steps = definitions.map((definition, index) => new Step(this, index, definition));
1445
- const boot = await new ManagedTasks(this.native).boot();
1446
- this.managedBoot = Boolean(boot && boot.config === identity && boot.state !== "ready");
1447
- if (this.managedBoot) {
1448
- if (boot.state === "failed") {
1449
- this.progress.state = "STOPPED";
1450
- this.failure = new Error(boot.error);
1451
- }
1452
- else if (this.status === "IDLE")
1453
- this.progress.state = "IN_PROGRESS";
1454
- }
1455
- }
1456
- run() {
1457
- return (this.starting ??= this.start().finally(() => {
1458
- this.starting = undefined;
1459
- }));
1460
- }
1461
- async start() {
1462
- await this.initialize();
1463
- if (this.client.state !== "CONNECTED")
1464
- throw new Error("Sandbox client is disconnected.");
1465
- if (this.status === "IN_PROGRESS" || !this.steps.length)
1466
- return;
1467
- this.managedBoot = false;
1468
- await this.active;
1469
- this.ignoredRunId = this.progress.runId;
1470
- const runId = crypto.randomUUID();
1471
- const input = `${setupRoot}/${runId}.json`;
1472
- const config = {
1473
- runId,
1474
- config: this.progress.config,
1475
- cwd: this.client.workspacePath,
1476
- steps: this.steps.map((step) => ({ name: step.name, command: step.command })),
1477
- };
1478
- await this.native.files.write(input, JSON.stringify(config), { mode: 0o600 });
1479
- const { stdin: _stdin, ...options } = await execOptions(this.native, {
1480
- cwd: this.client.workspacePath,
1481
- });
1482
- const process = await this.native.spawn(["python3", "-c", setupRunner, input], options);
1483
- try {
1484
- await this.native.files.write(`${setupRoot}/${runId}.process.json`, JSON.stringify({ id: process.id }), { mode: 0o600 });
1485
- // Do not return a connection before the guest has published ownership.
1486
- // A second connection can otherwise launch a duplicate supervisor while
1487
- // the first Python interpreter is still starting.
1488
- const until = Date.now() + 5000;
1489
- for (;;) {
1490
- if (await this.native.files.exists(`${setupRoot}/progress.json`)) {
1491
- const accepted = JSON.parse(await this.native.files.readText(`${setupRoot}/progress.json`));
1492
- if (accepted.config === config.config && accepted.runId !== this.ignoredRunId)
1493
- break;
1494
- }
1495
- if (Date.now() >= until)
1496
- throw new Error("Setup supervisor did not acknowledge startup");
1497
- await new Promise((resolve) => setTimeout(resolve, 10));
1498
- }
1499
- }
1500
- catch (error) {
1501
- try {
1502
- await process.kill("SIGKILL");
1503
- }
1504
- catch (cleanup) {
1505
- throw new AggregateError([error, cleanup], "Setup tracking failed and process cleanup could not be confirmed");
1506
- }
1507
- throw error;
1508
- }
1509
- this.failure = undefined;
1510
- this.progress = {
1511
- ...this.progress,
1512
- state: "IN_PROGRESS",
1513
- runId,
1514
- currentStepIndex: 0,
1515
- steps: config.steps.map((step) => ({ ...step, status: "IDLE" })),
1516
- };
1517
- this.changed.fire();
1518
- // Native process failure is observed independently of progress-file polling.
1519
- void process
1520
- .wait({ signal: this.cancelled.signal })
1521
- .then(async (result) => {
1522
- if (this.progress.runId !== runId || this.cancelled.signal.aborted)
1523
- return;
1524
- if (result.exitCode !== 0) {
1525
- if (await this.native.files.exists(`${setupRoot}/progress.json`)) {
1526
- const stored = JSON.parse(await this.native.files.readText(`${setupRoot}/progress.json`));
1527
- if (stored.runId === runId) {
1528
- this.progress = stored;
1529
- for (const step of this.steps)
1530
- await step.refresh();
1531
- }
1532
- }
1533
- this.failure = new Error("Setup Failed");
1534
- this.progress.state = "STOPPED";
1535
- this.changed.fire();
1536
- }
1537
- })
1538
- .catch((error) => {
1539
- if (this.cancelled.signal.aborted)
1540
- return;
1541
- this.failure = error instanceof Error ? error : new Error(String(error));
1542
- this.progress.state = "STOPPED";
1543
- this.changed.fire();
1544
- });
1545
- this.monitor();
1546
- }
1547
- monitor() {
1548
- if (this.active)
1549
- return;
1550
- const signal = this.cancelled.signal;
1551
- this.active = (async () => {
1552
- while (this.status === "IN_PROGRESS") {
1553
- signal.throwIfAborted();
1554
- if (this.managedBoot) {
1555
- const boot = await new ManagedTasks(this.native).boot(signal);
1556
- if (boot?.state === "failed")
1557
- throw new Error(boot.error);
1558
- }
1559
- if (await this.native.files.exists(`${setupRoot}/progress.json`, { signal })) {
1560
- const next = JSON.parse(await this.native.files.readText(`${setupRoot}/progress.json`, { signal }));
1561
- if (next.config === this.progress.config && next.runId !== this.ignoredRunId) {
1562
- this.progress = next;
1563
- for (const step of this.steps)
1564
- await step.refresh();
1565
- if (this.status === "IN_PROGRESS" && next.runId) {
1566
- const tracking = `${setupRoot}/${next.runId}.process.json`;
1567
- if (await this.native.files.exists(tracking, { signal })) {
1568
- const { id } = JSON.parse(await this.native.files.readText(tracking, { signal }));
1569
- const process = await this.native.processes.get(id);
1570
- if (process.info.state !== "running") {
1571
- // Read again after observing exit: the supervisor writes its
1572
- // final progress before it exits; the earlier read can race.
1573
- this.progress = JSON.parse(await this.native.files.readText(`${setupRoot}/progress.json`, { signal }));
1574
- if (this.progress.state === "IN_PROGRESS")
1575
- this.progress.state = "STOPPED";
1576
- for (const step of this.steps)
1577
- await step.refresh();
1578
- }
1579
- }
1580
- }
1581
- this.changed.fire();
1582
- }
1583
- }
1584
- if (this.status !== "IN_PROGRESS")
1585
- break;
1586
- await new Promise((resolve, reject) => {
1587
- const abort = () => {
1588
- clearTimeout(timer);
1589
- reject(signal.reason instanceof Error
1590
- ? signal.reason
1591
- : new Error("Setup subscription cancelled"));
1592
- };
1593
- const timer = setTimeout(() => {
1594
- signal.removeEventListener("abort", abort);
1595
- resolve();
1596
- }, 100);
1597
- signal.addEventListener("abort", abort, { once: true });
1598
- if (signal.aborted)
1599
- abort();
1600
- });
1601
- }
1602
- })()
1603
- .catch((error) => {
1604
- this.failure = error instanceof Error ? error : new Error(String(error));
1605
- this.progress.state = "STOPPED";
1606
- this.changed.fire();
1607
- })
1608
- .finally(() => {
1609
- this.active = undefined;
1610
- });
1611
- }
1612
- async waitUntilComplete() {
1613
- await this.initialize();
1614
- if (this.failure)
1615
- throw this.failure;
1616
- if (this.status === "STOPPED")
1617
- throw new Error("Setup Failed");
1618
- if (this.status === "FINISHED")
1619
- return;
1620
- await new Promise((resolve, reject) => {
1621
- const listener = this.onSetupProgressChange(() => {
1622
- if (this.status === "FINISHED" || this.status === "STOPPED") {
1623
- listener.dispose();
1624
- if (this.status === "FINISHED")
1625
- resolve();
1626
- else
1627
- reject(this.failure ?? new Error("Setup Failed"));
1628
- }
1629
- });
1630
- });
1631
- }
1632
- step(index) {
1633
- return this.progress.steps[index];
1634
- }
1635
- async output(index) {
1636
- const log = this.step(index).log;
1637
- if (!log || !(await this.native.files.exists(log)))
1638
- return "";
1639
- return this.native.files.readText(log);
1640
- }
1641
- async open(index, dimensions) {
1642
- if (dimensions &&
1643
- (!Number.isInteger(dimensions.cols) ||
1644
- !Number.isInteger(dimensions.rows) ||
1645
- dimensions.cols < 1 ||
1646
- dimensions.rows < 1 ||
1647
- dimensions.cols > 65535 ||
1648
- dimensions.rows > 65535))
1649
- throw new TypeError("Invalid terminal dimensions");
1650
- const available = () => this.step(index).tty || this.step(index).status !== "IDLE";
1651
- if (!available())
1652
- await new Promise((resolve, reject) => {
1653
- const changed = () => {
1654
- if (available()) {
1655
- listener.dispose();
1656
- resolve();
1657
- }
1658
- else if (this.status === "STOPPED") {
1659
- listener.dispose();
1660
- reject(new Error("Step Failed"));
1661
- }
1662
- };
1663
- const listener = this.onSetupProgressChange(changed);
1664
- changed();
1665
- });
1666
- const step = this.step(index);
1667
- if (dimensions && step.tty && step.status === "IDLE")
1668
- await this.native.exec([
1669
- "python3",
1670
- "-c",
1671
- resizeStep,
1672
- `${setupRoot}/progress.json`,
1673
- this.progress.runId ?? "",
1674
- String(index),
1675
- step.tty,
1676
- String(dimensions.rows),
1677
- String(dimensions.cols),
1678
- ], { check: true });
1679
- }
1680
- dispose() {
1681
- const error = new Error("Sandbox client is disconnected.");
1682
- this.cancelled.abort(error);
1683
- if (this.status === "IDLE" || this.status === "IN_PROGRESS") {
1684
- this.failure = error;
1685
- this.progress.state = "STOPPED";
1686
- this.changed.fire();
1687
- }
1688
- }
1689
- }
1690
- export class Step {
1691
- setup;
1692
- index;
1693
- definition;
1694
- output = "";
1695
- previousStatus = "IDLE";
1696
- outputEvent = emitter();
1697
- statusEvent = emitter();
1698
- onOutput = this.outputEvent.event;
1699
- onStatusChange = this.statusEvent.event;
1700
- constructor(setup, index, definition) {
1701
- this.setup = setup;
1702
- this.index = index;
1703
- this.definition = definition;
1704
- }
1705
- get name() {
1706
- return this.definition.name;
1707
- }
1708
- get command() {
1709
- return this.definition.command;
1710
- }
1711
- get status() {
1712
- return this.setup.step(this.index).status;
1713
- }
1714
- async refresh() {
1715
- const next = await this.setup.output(this.index);
1716
- if (next.length > this.output.length)
1717
- this.outputEvent.fire(next.slice(this.output.length));
1718
- this.output = next;
1719
- if (this.status !== this.previousStatus) {
1720
- this.previousStatus = this.status;
1721
- this.statusEvent.fire(this.status);
1722
- }
1723
- }
1724
- async open(dimensions) {
1725
- await this.setup.open(this.index, dimensions);
1726
- await this.refresh();
1727
- return this.output;
1728
- }
1729
- async waitUntilComplete() {
1730
- if (this.status === "FAILED" || this.setup.status === "STOPPED")
1731
- throw new Error("Step Failed");
1732
- if (this.status === "SUCCEEDED" || this.status === "SKIPPED")
1733
- return;
1734
- await new Promise((resolve, reject) => {
1735
- const listener = this.setup.onSetupProgressChange(() => {
1736
- if (this.status === "SUCCEEDED" || this.status === "SKIPPED") {
1737
- listener.dispose();
1738
- resolve();
1739
- }
1740
- else if (this.status === "FAILED" || this.setup.status === "STOPPED") {
1741
- listener.dispose();
1742
- reject(new Error("Step Failed"));
1743
- }
1744
- });
1745
- });
1746
- }
1747
- }