An open-source, faster Devin alternative
TypeScript
add bulk upload files, background service, kill sessions
motatoes2a4d859f59d8
diff --git a/Cargo.lock b/Cargo.lockindex 6e0ac889..cc3c282f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2,6 +2,15 @@# It is not intended for manual editing.version = 4+[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]+[[package]]name = "anstream"version = "0.6.21"@@ -52,6 +61,34 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "anyhow"+version = "1.0.100"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"++[[package]]+name = "async-stream"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"+dependencies = [+ "async-stream-impl",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-stream-impl"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "async-trait"version = "0.1.89"@@ -69,6 +106,12 @@ version = "1.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"+[[package]]+name = "autocfg"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"+[[package]]name = "axum"version = "0.7.9"@@ -77,6 +120,7 @@ checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"dependencies = ["async-trait","axum-core",+ "base64","bytes","futures-util","http",@@ -95,9 +139,11 @@ dependencies = ["serde_json","serde_path_to_error","serde_urlencoded",+ "sha1","sync_wrapper","tokio",- "tower",+ "tokio-tungstenite 0.24.0",+ "tower 0.5.3","tower-layer","tower-service","tracing",@@ -124,24 +170,55 @@ dependencies = ["tracing",]+[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]name = "bitflags"version = "2.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"+[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]+[[package]]name = "bumpalo"version = "3.19.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"+[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"+[[package]]name = "bytes"version = "1.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3"+[[package]]+name = "cc"+version = "1.2.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47b26a0954ae34af09b50f0de26458fa95369a0d478d8236d3f93082b219bd29"+dependencies = [+ "find-msvc-tools",+ "shlex",+]+[[package]]name = "cfg-if"version = "1.0.4"@@ -200,6 +277,64 @@ version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"+[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "data-encoding"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea"++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "displaydoc"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "either"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"+[[package]]name = "errno"version = "0.3.14"@@ -210,6 +345,30 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "fastrand"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"++[[package]]+name = "find-msvc-tools"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"++[[package]]+name = "fixedbitset"+version = "0.5.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"++[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"+[[package]]name = "form_urlencoded"version = "1.2.2"@@ -234,6 +393,23 @@ version = "0.3.31"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"+[[package]]+name = "futures-macro"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "futures-sink"+version = "0.3.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"+[[package]]name = "futures-task"version = "0.3.31"@@ -247,9 +423,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"dependencies = ["futures-core",+ "futures-macro",+ "futures-sink","futures-task","pin-project-lite","pin-utils",+ "slab",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "wasi",+ "wasm-bindgen",][[package]]@@ -259,11 +461,44 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"dependencies = ["cfg-if",+ "js-sys","libc","r-efi","wasip2",+ "wasm-bindgen",+]++[[package]]+name = "h2"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"+dependencies = [+ "atomic-waker",+ "bytes",+ "fnv",+ "futures-core",+ "futures-sink",+ "http",+ "indexmap 2.13.0",+ "slab",+ "tokio",+ "tokio-util",+ "tracing",]+[[package]]+name = "hashbrown"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"+[[package]]name = "heck"version = "0.5.0"@@ -325,6 +560,7 @@ dependencies = ["bytes","futures-channel","futures-core",+ "h2","http","http-body","httparse",@@ -334,6 +570,37 @@ dependencies = ["pin-utils","smallvec","tokio",+ "want",+]++[[package]]+name = "hyper-rustls"+version = "0.27.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "rustls-pki-types",+ "tokio",+ "tokio-rustls",+ "tower-service",+ "webpki-roots",+]++[[package]]+name = "hyper-timeout"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"+dependencies = [+ "hyper",+ "hyper-util",+ "pin-project-lite",+ "tokio",+ "tower-service",][[package]]@@ -342,14 +609,160 @@ version = "0.1.19"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "727805d60e7938b76b826a6ef209eb70eaa1812794f9424d4a4e2d740662df5f"dependencies = [+ "base64","bytes",+ "futures-channel","futures-core",+ "futures-util","http","http-body","hyper",+ "ipnet",+ "libc",+ "percent-encoding","pin-project-lite",+ "socket2 0.6.2","tokio","tower-service",+ "tracing",+]++[[package]]+name = "icu_collections"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43"+dependencies = [+ "displaydoc",+ "potential_utf",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a"++[[package]]+name = "icu_properties"+version = "2.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec"+dependencies = [+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af"++[[package]]+name = "icu_provider"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "indexmap"+version = "1.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"+dependencies = [+ "autocfg",+ "hashbrown 0.12.3",+]++[[package]]+name = "indexmap"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"+dependencies = [+ "equivalent",+ "hashbrown 0.16.1",+]++[[package]]+name = "ipnet"+version = "2.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"++[[package]]+name = "iri-string"+version = "0.7.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a"+dependencies = [+ "memchr",+ "serde",][[package]]@@ -363,18 +776,34 @@ name = "isolate"version = "0.1.0"dependencies = ["axum",+ "base64","clap",+ "futures-util","libc","nix",+ "prost",+ "reqwest","serde","serde_json","tokio",- "tower-http",+ "tokio-tungstenite 0.21.0",+ "tonic",+ "tonic-build",+ "tower-http 0.5.2","tracing","tracing-subscriber","uuid",]+[[package]]+name = "itertools"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+dependencies = [+ "either",+]+[[package]]name = "itoa"version = "1.0.17"@@ -403,6 +832,18 @@ version = "0.2.180"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc"+[[package]]+name = "linux-raw-sys"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"++[[package]]+name = "litemap"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"+[[package]]name = "lock_api"version = "0.4.14"@@ -418,6 +859,12 @@ version = "0.4.29"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"+[[package]]+name = "lru-slab"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"+[[package]]name = "matchit"version = "0.7.3"@@ -447,6 +894,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "multimap"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"+[[package]]name = "nix"version = "0.29.0"@@ -510,17 +963,75 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"[[package]]-name = "pin-project-lite"-version = "0.2.16"+name = "petgraph"+version = "0.7.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"+checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772"+dependencies = [+ "fixedbitset",+ "indexmap 2.13.0",+][[package]]-name = "pin-utils"-version = "0.1.0"+name = "pin-project"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a"+dependencies = [+ "pin-project-internal",+]++[[package]]+name = "pin-project-internal"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "pin-project-lite"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"++[[package]]+name = "pin-utils"+version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"+[[package]]+name = "potential_utf"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77"+dependencies = [+ "zerovec",+]++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "prettyplease"+version = "0.2.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"+dependencies = [+ "proc-macro2",+ "syn",+]+[[package]]name = "proc-macro2"version = "1.0.106"@@ -530,6 +1041,113 @@ dependencies = ["unicode-ident",]+[[package]]+name = "prost"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5"+dependencies = [+ "bytes",+ "prost-derive",+]++[[package]]+name = "prost-build"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf"+dependencies = [+ "heck",+ "itertools",+ "log",+ "multimap",+ "once_cell",+ "petgraph",+ "prettyplease",+ "prost",+ "prost-types",+ "regex",+ "syn",+ "tempfile",+]++[[package]]+name = "prost-derive"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"+dependencies = [+ "anyhow",+ "itertools",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "prost-types"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16"+dependencies = [+ "prost",+]++[[package]]+name = "quinn"+version = "0.11.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"+dependencies = [+ "bytes",+ "cfg_aliases",+ "pin-project-lite",+ "quinn-proto",+ "quinn-udp",+ "rustc-hash",+ "rustls",+ "socket2 0.6.2",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-proto"+version = "0.11.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"+dependencies = [+ "bytes",+ "getrandom 0.3.4",+ "lru-slab",+ "rand 0.9.2",+ "ring",+ "rustc-hash",+ "rustls",+ "rustls-pki-types",+ "slab",+ "thiserror 2.0.18",+ "tinyvec",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-udp"+version = "0.5.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"+dependencies = [+ "cfg_aliases",+ "libc",+ "once_cell",+ "socket2 0.6.2",+ "tracing",+ "windows-sys 0.60.2",+]+[[package]]name = "quote"version = "1.0.44"@@ -545,6 +1163,65 @@ version = "5.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"+[[package]]+name = "rand"+version = "0.8.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"+dependencies = [+ "libc",+ "rand_chacha 0.3.1",+ "rand_core 0.6.4",+]++[[package]]+name = "rand"+version = "0.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"+dependencies = [+ "rand_chacha 0.9.0",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_chacha"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"+dependencies = [+ "ppv-lite86",+ "rand_core 0.6.4",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom 0.2.17",+]++[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",+]+[[package]]name = "redox_syscall"version = "0.5.18"@@ -554,6 +1231,141 @@ dependencies = ["bitflags",]+[[package]]+name = "regex"+version = "1.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c"++[[package]]+name = "reqwest"+version = "0.12.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+dependencies = [+ "base64",+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "quinn",+ "rustls",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tower 0.5.3",+ "tower-http 0.6.8",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "webpki-roots",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustc-hash"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"++[[package]]+name = "rustix"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34"+dependencies = [+ "bitflags",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"+dependencies = [+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-pki-types"+version = "1.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"+dependencies = [+ "web-time",+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]+[[package]]name = "rustversion"version = "1.0.22"@@ -638,6 +1450,17 @@ dependencies = ["serde",]+[[package]]+name = "sha1"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]+[[package]]name = "sharded-slab"version = "0.1.7"@@ -647,6 +1470,12 @@ dependencies = ["lazy_static",]+[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]name = "signal-hook-registry"version = "1.4.8"@@ -657,12 +1486,28 @@ dependencies = ["libc",]+[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"+[[package]]name = "smallvec"version = "1.15.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"+[[package]]+name = "socket2"+version = "0.5.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"+dependencies = [+ "libc",+ "windows-sys 0.52.0",+]+[[package]]name = "socket2"version = "0.6.2"@@ -673,12 +1518,24 @@ dependencies = ["windows-sys 0.60.2",]+[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"+[[package]]name = "strsim"version = "0.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"+[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]name = "syn"version = "2.0.114"@@ -691,48 +1548,262 @@ dependencies = [][[package]]-name = "sync_wrapper"-version = "1.0.2"+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+dependencies = [+ "futures-core",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tempfile"+version = "3.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c"+dependencies = [+ "fastrand",+ "getrandom 0.3.4",+ "once_cell",+ "rustix",+ "windows-sys 0.61.2",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl 2.0.18",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "thread_local"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"+dependencies = [+ "cfg-if",+]++[[package]]+name = "tinystr"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tinyvec"+version = "1.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa"+dependencies = [+ "tinyvec_macros",+]++[[package]]+name = "tinyvec_macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"++[[package]]+name = "tokio"+version = "1.49.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "parking_lot",+ "pin-project-lite",+ "signal-hook-registry",+ "socket2 0.6.2",+ "tokio-macros",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-macros"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tokio-rustls"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-stream"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "tokio-tungstenite"+version = "0.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c83b561d025642014097b66e6c1bb422783339e0909e4429cde4749d1990bc38"+dependencies = [+ "futures-util",+ "log",+ "tokio",+ "tungstenite 0.21.0",+]++[[package]]+name = "tokio-tungstenite"+version = "0.24.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9"+dependencies = [+ "futures-util",+ "log",+ "tokio",+ "tungstenite 0.24.0",+][[package]]-name = "thread_local"-version = "1.1.9"+name = "tokio-util"+version = "0.7.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"dependencies = [- "cfg-if",+ "bytes",+ "futures-core",+ "futures-sink",+ "pin-project-lite",+ "tokio",][[package]]-name = "tokio"-version = "1.49.0"+name = "tonic"+version = "0.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"+checksum = "877c5b330756d856ffcc4553ab34a5684481ade925ecc54bcd1bf02b1d0d4d52"dependencies = [+ "async-stream",+ "async-trait",+ "axum",+ "base64","bytes",- "libc",- "mio",- "parking_lot",- "pin-project-lite",- "signal-hook-registry",- "socket2",- "tokio-macros",- "windows-sys 0.61.2",+ "h2",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-timeout",+ "hyper-util",+ "percent-encoding",+ "pin-project",+ "prost",+ "socket2 0.5.10",+ "tokio",+ "tokio-stream",+ "tower 0.4.13",+ "tower-layer",+ "tower-service",+ "tracing",][[package]]-name = "tokio-macros"-version = "2.6.0"+name = "tonic-build"+version = "0.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"+checksum = "9557ce109ea773b399c9b9e5dca39294110b74f1f342cb347a80d1fce8c26a11"dependencies = [+ "prettyplease","proc-macro2",+ "prost-build",+ "prost-types","quote","syn",]+[[package]]+name = "tower"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"+dependencies = [+ "futures-core",+ "futures-util",+ "indexmap 1.9.3",+ "pin-project",+ "pin-project-lite",+ "rand 0.8.5",+ "slab",+ "tokio",+ "tokio-util",+ "tower-layer",+ "tower-service",+ "tracing",+]+[[package]]name = "tower"version = "0.5.3"@@ -766,6 +1837,24 @@ dependencies = ["tracing",]+[[package]]+name = "tower-http"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"+dependencies = [+ "bitflags",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "iri-string",+ "pin-project-lite",+ "tower 0.5.3",+ "tower-layer",+ "tower-service",+]+[[package]]name = "tower-layer"version = "0.3.3"@@ -836,12 +1925,91 @@ dependencies = ["tracing-log",]+[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "tungstenite"+version = "0.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ef1a641ea34f399a848dea702823bbecfb4c486f911735368f1f137cb8257e1"+dependencies = [+ "byteorder",+ "bytes",+ "data-encoding",+ "http",+ "httparse",+ "log",+ "rand 0.8.5",+ "sha1",+ "thiserror 1.0.69",+ "url",+ "utf-8",+]++[[package]]+name = "tungstenite"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a"+dependencies = [+ "byteorder",+ "bytes",+ "data-encoding",+ "http",+ "httparse",+ "log",+ "rand 0.8.5",+ "sha1",+ "thiserror 1.0.69",+ "utf-8",+]++[[package]]+name = "typenum"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"+[[package]]name = "unicode-ident"version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"+[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf-8"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+[[package]]name = "utf8parse"version = "0.2.2"@@ -854,7 +2022,7 @@ version = "1.20.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ee48d38b119b0cd71fe4141b30f5ba9c7c5d9f4e7a3a8b4a674e4b6ef789976f"dependencies = [- "getrandom",+ "getrandom 0.3.4","js-sys","wasm-bindgen",]@@ -865,6 +2033,21 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"+[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "want"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"+dependencies = [+ "try-lock",+]+[[package]]name = "wasi"version = "0.11.1+wasi-snapshot-preview1"@@ -893,6 +2076,20 @@ dependencies = ["wasm-bindgen-shared",]+[[package]]+name = "wasm-bindgen-futures"+version = "0.4.58"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70a6e77fd0ae8029c9ea0063f87c46fde723e7d887703d74ad2616d792e51e6f"+dependencies = [+ "cfg-if",+ "futures-util",+ "js-sys",+ "once_cell",+ "wasm-bindgen",+ "web-sys",+]+[[package]]name = "wasm-bindgen-macro"version = "0.2.108"@@ -925,19 +2122,57 @@ dependencies = ["unicode-ident",]+[[package]]+name = "web-sys"+version = "0.3.85"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "webpki-roots"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed"+dependencies = [+ "rustls-pki-types",+]+[[package]]name = "windows-link"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"+[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets 0.52.6",+]+[[package]]name = "windows-sys"version = "0.60.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"dependencies = [- "windows-targets",+ "windows-targets 0.53.5",][[package]]@@ -949,6 +2184,22 @@ dependencies = ["windows-link",]+[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm 0.52.6",+ "windows_aarch64_msvc 0.52.6",+ "windows_i686_gnu 0.52.6",+ "windows_i686_gnullvm 0.52.6",+ "windows_i686_msvc 0.52.6",+ "windows_x86_64_gnu 0.52.6",+ "windows_x86_64_gnullvm 0.52.6",+ "windows_x86_64_msvc 0.52.6",+]+[[package]]name = "windows-targets"version = "0.53.5"@@ -956,58 +2207,106 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"dependencies = ["windows-link",- "windows_aarch64_gnullvm",- "windows_aarch64_msvc",- "windows_i686_gnu",- "windows_i686_gnullvm",- "windows_i686_msvc",- "windows_x86_64_gnu",- "windows_x86_64_gnullvm",- "windows_x86_64_msvc",+ "windows_aarch64_gnullvm 0.53.1",+ "windows_aarch64_msvc 0.53.1",+ "windows_i686_gnu 0.53.1",+ "windows_i686_gnullvm 0.53.1",+ "windows_i686_msvc 0.53.1",+ "windows_x86_64_gnu 0.53.1",+ "windows_x86_64_gnullvm 0.53.1",+ "windows_x86_64_msvc 0.53.1",]+[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"+[[package]]name = "windows_aarch64_gnullvm"version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"+[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"+[[package]]name = "windows_aarch64_msvc"version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"+[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"+[[package]]name = "windows_i686_gnu"version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"+[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"+[[package]]name = "windows_i686_gnullvm"version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"+[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"+[[package]]name = "windows_i686_msvc"version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"+[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"+[[package]]name = "windows_x86_64_gnu"version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"+[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"+[[package]]name = "windows_x86_64_gnullvm"version = "0.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"+[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"+[[package]]name = "windows_x86_64_msvc"version = "0.53.1"@@ -1020,6 +2319,115 @@ version = "0.51.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"+[[package]]+name = "writeable"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"++[[package]]+name = "yoke"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerocopy"+version = "0.8.38"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57cf3aa6855b23711ee9852dfc97dfaa51c45feaba5b645d0c777414d494a961"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.38"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a616990af1a287837c4fe6596ad77ef57948f787e46ce28e166facc0cc1cb75"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zerofrom"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"++[[package]]+name = "zerotrie"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "zmij"version = "1.0.17"diff --git a/Cargo.toml b/Cargo.tomlindex 6e587d95..454c18bc 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -11,7 +11,7 @@ nix = { version = "0.29", features = ["process", "mount", "sched", "resource", "clap = { version = "4", features = ["derive"] }libc = "0.2"tokio = { version = "1", features = ["full"] }-axum = { version = "0.7", features = ["json"] }+axum = { version = "0.7", features = ["json", "ws"] }serde = { version = "1", features = ["derive"] }serde_json = "1"uuid = { version = "1", features = ["v4"] }@@ -20,6 +20,10 @@ tracing = "0.1"tracing-subscriber = "0.3"tonic = "0.12"prost = "0.13"+base64 = "0.22"+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }+tokio-tungstenite = "0.21"+futures-util = "0.3"[build-dependencies]tonic-build = "0.12"diff --git a/Dockerfile b/Dockerfileindex 055f2c62..8029191c 100644--- a/Dockerfile+++ b/Dockerfile@@ -15,12 +15,15 @@ RUN cargo build --releaseFROM debian:bookworm-slim-# Install dependencies including git and gh CLI+# Install dependencies including git, gh CLI, and build toolsRUN apt-get update && apt-get install -y --no-install-recommends \ca-certificates \procps \git \curl \+ build-essential \+ python3 \+ python3-pip \&& rm -rf /var/lib/apt/lists/*# Install GitHub CLIdiff --git a/fly.toml b/fly.tomlindex 0f20532d..85ad7ab8 100644--- a/fly.toml+++ b/fly.toml@@ -41,3 +41,7 @@ primary_region = 'ord'memory = '2gb'cpus = 2memory_mb = 2048+++[env]+ PREVIEW_DOMAIN = "preview.opensandbox.ai"diff --git a/proto/sandbox.proto b/proto/sandbox.protoindex e6fbb7c1..9cdec94d 100644--- a/proto/sandbox.proto+++ b/proto/sandbox.proto@@ -7,6 +7,7 @@ service SandboxService {// File operationsrpc WriteFile(WriteFileRequest) returns (WriteFileResponse);+ rpc WriteFiles(WriteFilesRequest) returns (WriteFilesResponse);rpc ReadFile(ReadFileRequest) returns (ReadFileResponse);// Environment/CWD@@ -70,3 +71,23 @@ message SetCwdRequest {message SetCwdResponse {bool success = 1;}++message BulkFileEntry {+ string path = 1;+ bytes content = 2;+}++message WriteFilesRequest {+ string session_id = 1;+ repeated BulkFileEntry files = 2;+}++message WriteFilesResponse {+ bool success = 1;+ repeated FileError errors = 2;+}++message FileError {+ string path = 1;+ string error = 2;+}diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdnew file mode 100644index 00000000..11cb8086--- /dev/null+++ b/sdk/typescript/README.md@@ -0,0 +1,186 @@+# OpenSandbox TypeScript SDK++TypeScript/JavaScript SDK for [OpenSandbox](https://github.com/diggerhq/opensandbox) - secure code execution environments.++## Installation++```bash+npm install @opensandbox/sdk+```++## Quick Start++```typescript+import { OpenSandbox } from '@opensandbox/sdk';++// Create client+const client = new OpenSandbox('http://localhost:8080');++// Create a sandbox session+const sandbox = await client.create();++// Run commands+const result = await sandbox.run('echo "Hello, World!"');+console.log(result.stdout); // "Hello, World!\n"+console.log(result.exitCode); // 0++// Clean up+await sandbox.destroy();+await client.close();+```++## Features++### Command Execution++```typescript+// Basic command+const result = await sandbox.run('ls -la');++// With options+const result = await sandbox.run('node script.js', {+ timeoutMs: 60000, // 60 second timeout+ memKb: 512000, // 512MB memory limit+ env: { NODE_ENV: 'production' },+ cwd: '/home/app',+});++// Check result+if (result.exitCode === 0) {+ console.log('Success:', result.stdout);+} else {+ console.error('Failed:', result.stderr);+}+```++### File Operations++```typescript+// Write a file+await sandbox.writeFile('/home/test.txt', 'Hello, World!');++// Write binary data+const buffer = Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]);+await sandbox.writeFile('/home/binary.dat', buffer);++// Read a file as text+const text = await sandbox.readFileText('/home/test.txt');++// Read a file as binary+const data = await sandbox.readFile('/home/binary.dat');++// List directory contents+const files = await sandbox.listFiles('/home');+for (const file of files) {+ console.log(`${file.name} - ${file.isDirectory ? 'dir' : 'file'} - ${file.size} bytes`);+}+```++### Environment & Working Directory++```typescript+// Set environment variables+await sandbox.setEnv({+ API_KEY: 'secret',+ DEBUG: 'true',+});++// Set working directory+await sandbox.setCwd('/home/app');++// Now commands run with these settings+const result = await sandbox.run('pwd'); // /home/app+```++### Preview URLs++When the server is configured with a preview domain, sandboxes can expose web servers:++```typescript+const sandbox = await client.create();++// Start a web server+await sandbox.run('python3 -m http.server 5173 &');++// Access via preview URL+if (sandbox.previewUrl) {+ console.log(`Web server available at: ${sandbox.previewUrl}`);+ // e.g., https://abc-123.preview.opensandbox.fly.dev+}+```++## API Reference++### `OpenSandbox`++Main client for connecting to an OpenSandbox server.++```typescript+const client = new OpenSandbox(baseUrl, options?);+```++**Options:**+- `grpcPort?: number` - gRPC port (default: 50051)+- `grpcInsecure?: boolean` - Use insecure gRPC even for HTTPS+- `timeout?: number` - HTTP timeout in milliseconds (default: 30000)++**Methods:**+- `create(options?)` - Create a new sandbox session+- `close()` - Close all connections++### `Sandbox`++Represents a sandbox session.++**Properties:**+- `sessionId: string` - Unique session identifier+- `previewUrl: string | null` - Preview URL for web servers++**Methods:**+- `run(command, options?)` - Execute a shell command+- `writeFile(path, content)` - Write a file+- `readFile(path)` - Read a file as Buffer+- `readFileText(path, encoding?)` - Read a file as string+- `listFiles(path)` - List directory contents+- `setEnv(env)` - Set environment variables+- `setCwd(cwd)` - Set working directory+- `destroy()` - Destroy the sandbox++### Error Classes++- `OpenSandboxError` - Base error class+- `SandboxNotFoundError` - Session not found+- `ConnectionError` - Connection to server failed+- `CommandExecutionError` - Command execution failed+- `FileOperationError` - File operation failed++## Types++```typescript+interface CommandResult {+ stdout: string;+ stderr: string;+ exitCode: number;+ signal: number;+}++interface RunOptions {+ timeoutMs?: number;+ memKb?: number;+ fsizeKb?: number;+ nofile?: number;+ env?: Record<string, string>;+ cwd?: string;+}++interface FileEntry {+ name: string;+ path: string;+ isDirectory: boolean;+ size: number;+}+```++## License++MITdiff --git a/sdk/typescript/dist/client.d.ts b/sdk/typescript/dist/client.d.tsnew file mode 100644index 00000000..32c7df8d--- /dev/null+++ b/sdk/typescript/dist/client.d.ts@@ -0,0 +1,58 @@+/**+ * OpenSandbox client for creating and managing sandbox sessions.+ */+import { Sandbox } from './sandbox';+import type { ClientOptions, CreateOptions } from './types';+/**+ * Client for connecting to an OpenSandbox server.+ *+ * This client uses HTTP for sandbox lifecycle (create/destroy) and+ * optionally gRPC for fast command execution and file operations.+ *+ * @example+ * ```typescript+ * const client = new OpenSandbox('http://localhost:8080');+ * const sandbox = await client.create();+ * const result = await sandbox.run('echo hello');+ * console.log(result.stdout); // "hello\n"+ * await sandbox.destroy();+ * await client.close();+ * ```+ */+export declare class OpenSandbox {+ private _baseUrl;+ private _grpcPort;+ private _grpcInsecure;+ private _timeout;+ private _grpcChannel;+ private _grpcStub;+ private _host;+ private _grpcSecure;+ /**+ * Initialize the OpenSandbox client.+ *+ * @param baseUrl - Base URL of the OpenSandbox server (e.g., "http://localhost:8080")+ * @param options - Client options+ */+ constructor(baseUrl: string, options?: ClientOptions);+ /**+ * Create a new sandbox session.+ *+ * @param options - Options for creating the sandbox+ * @returns A Sandbox instance ready for use+ * @throws {ConnectionError} If connection to the server fails+ */+ create(options?: CreateOptions): Promise<Sandbox>;+ /**+ * Initialize gRPC connection (optional, for better performance).+ *+ * Call this method before creating sandboxes if you want to use gRPC+ * for command execution and file operations.+ */+ connectGrpc(): Promise<void>;+ /**+ * Close all connections to the server.+ */+ close(): Promise<void>;+}+//# sourceMappingURL=client.d.ts.map\ No newline at end of filediff --git a/sdk/typescript/dist/client.d.ts.map b/sdk/typescript/dist/client.d.ts.mapnew file mode 100644index 00000000..2a4bd37a--- /dev/null+++ b/sdk/typescript/dist/client.d.ts.map@@ -0,0 +1 @@+{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAa5D;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,aAAa,CAAU;IAC/B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,SAAS,CAAa;IAC9B,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,WAAW,CAAU;IAE7B;;;;;OAKG;gBACS,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,aAAkB;IAaxD;;;;;;OAMG;IACG,MAAM,CAAC,OAAO,GAAE,aAAkB,GAAG,OAAO,CAAC,OAAO,CAAC;IAwC3D;;;;;OAKG;IACG,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IA0BlC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAO7B"}\ No newline at end of filediff --git a/sdk/typescript/dist/client.js b/sdk/typescript/dist/client.jsnew file mode 100644index 00000000..3edf2e6b--- /dev/null+++ b/sdk/typescript/dist/client.js@@ -0,0 +1,161 @@+"use strict";+/**+ * OpenSandbox client for creating and managing sandbox sessions.+ */+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ var desc = Object.getOwnPropertyDescriptor(m, k);+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {+ desc = { enumerable: true, get: function() { return m[k]; } };+ }+ Object.defineProperty(o, k2, desc);+}) : (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ o[k2] = m[k];+}));+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {+ Object.defineProperty(o, "default", { enumerable: true, value: v });+}) : function(o, v) {+ o["default"] = v;+});+var __importStar = (this && this.__importStar) || (function () {+ var ownKeys = function(o) {+ ownKeys = Object.getOwnPropertyNames || function (o) {+ var ar = [];+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;+ return ar;+ };+ return ownKeys(o);+ };+ return function (mod) {+ if (mod && mod.__esModule) return mod;+ var result = {};+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);+ __setModuleDefault(result, mod);+ return result;+ };+})();+Object.defineProperty(exports, "__esModule", { value: true });+exports.OpenSandbox = void 0;+const grpc = __importStar(require("@grpc/grpc-js"));+const protoLoader = __importStar(require("@grpc/proto-loader"));+const sandbox_1 = require("./sandbox");+const errors_1 = require("./errors");+/**+ * Client for connecting to an OpenSandbox server.+ *+ * This client uses HTTP for sandbox lifecycle (create/destroy) and+ * optionally gRPC for fast command execution and file operations.+ *+ * @example+ * ```typescript+ * const client = new OpenSandbox('http://localhost:8080');+ * const sandbox = await client.create();+ * const result = await sandbox.run('echo hello');+ * console.log(result.stdout); // "hello\n"+ * await sandbox.destroy();+ * await client.close();+ * ```+ */+class OpenSandbox {+ _baseUrl;+ _grpcPort;+ _grpcInsecure;+ _timeout;+ _grpcChannel = null;+ _grpcStub = null;+ _host;+ _grpcSecure;+ /**+ * Initialize the OpenSandbox client.+ *+ * @param baseUrl - Base URL of the OpenSandbox server (e.g., "http://localhost:8080")+ * @param options - Client options+ */+ constructor(baseUrl, options = {}) {+ this._baseUrl = baseUrl.replace(/\/$/, '');+ this._grpcPort = options.grpcPort ?? 50051;+ this._grpcInsecure = options.grpcInsecure ?? false;+ this._timeout = options.timeout ?? 30000;+ // Parse URL to get host+ const url = new URL(this._baseUrl);+ this._host = url.hostname;+ // Use secure gRPC for HTTPS unless explicitly set to insecure+ this._grpcSecure = url.protocol === 'https:' && !this._grpcInsecure;+ }+ /**+ * Create a new sandbox session.+ *+ * @param options - Options for creating the sandbox+ * @returns A Sandbox instance ready for use+ * @throws {ConnectionError} If connection to the server fails+ */+ async create(options = {}) {+ const { env = {}, timeout = 300 } = options;+ try {+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), this._timeout);+ const response = await fetch(`${this._baseUrl}/sessions`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ env }),+ signal: controller.signal,+ });+ clearTimeout(timeoutId);+ if (!response.ok) {+ throw new errors_1.ConnectionError(`Failed to create sandbox: ${response.status} ${response.statusText}`);+ }+ // Server returns snake_case, we need to map to camelCase+ const data = await response.json();+ return new sandbox_1.Sandbox(data.session_id, this._grpcStub, this._baseUrl, data.preview_url);+ }+ catch (error) {+ if (error instanceof errors_1.ConnectionError) {+ throw error;+ }+ throw new errors_1.ConnectionError(`Failed to create sandbox: ${error}`);+ }+ }+ /**+ * Initialize gRPC connection (optional, for better performance).+ *+ * Call this method before creating sandboxes if you want to use gRPC+ * for command execution and file operations.+ */+ async connectGrpc() {+ const grpcTarget = `${this._host}:${this._grpcPort}`;+ const credentials = this._grpcSecure+ ? grpc.credentials.createSsl()+ : grpc.credentials.createInsecure();+ // Load proto file dynamically+ // Note: In a real implementation, you'd either bundle the proto file+ // or generate TypeScript types from it+ try {+ const packageDefinition = protoLoader.loadSync('sandbox.proto', {+ keepCase: true,+ longs: String,+ enums: String,+ defaults: true,+ oneofs: true,+ });+ const proto = grpc.loadPackageDefinition(packageDefinition);+ this._grpcStub = new proto.sandbox.SandboxService(grpcTarget, credentials);+ }+ catch {+ // gRPC connection is optional - SDK works with HTTP only+ console.warn('gRPC connection not available, using HTTP only');+ }+ }+ /**+ * Close all connections to the server.+ */+ async close() {+ if (this._grpcChannel) {+ this._grpcChannel.close();+ this._grpcChannel = null;+ }+ this._grpcStub = null;+ }+}+exports.OpenSandbox = OpenSandbox;+//# sourceMappingURL=client.js.map\ No newline at end of filediff --git a/sdk/typescript/dist/client.js.map b/sdk/typescript/dist/client.js.mapnew file mode 100644index 00000000..0ca9fddf--- /dev/null+++ b/sdk/typescript/dist/client.js.map@@ -0,0 +1 @@+{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,oDAAsC;AACtC,gEAAkD;AAClD,uCAAoC;AACpC,qCAA2C;AAc3C;;;;;;;;;;;;;;;GAeG;AACH,MAAa,WAAW;IACd,QAAQ,CAAS;IACjB,SAAS,CAAS;IAClB,aAAa,CAAU;IACvB,QAAQ,CAAS;IACjB,YAAY,GAAwB,IAAI,CAAC;IACzC,SAAS,GAAQ,IAAI,CAAC;IACtB,KAAK,CAAS;IACd,WAAW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ACxF,IAAI,CAAC,SAAS,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;QAC7E,CAAC;QAAC,MAAM,CAAC;YACP,yDAAyD;YACzD,OAAO,CAAC,IAAI,CAAC,gDAAgD,CAAC,CAAC;QACjE,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,KAAK;QACT,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;YAC1B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC3B,CAAC;QACD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;IACxB,CAAC;CACF;AAtHD,kCAsHC"}\ No newline at end of filediff --git a/sdk/typescript/dist/errors.d.ts b/sdk/typescript/dist/errors.d.tsnew file mode 100644index 00000000..c9b9ab63--- /dev/null+++ b/sdk/typescript/dist/errors.d.ts@@ -0,0 +1,40 @@+/**+ * Custom error classes for the OpenSandbox SDK.+ */+/**+ * Base error class for OpenSandbox errors.+ */+export declare class OpenSandboxError extends Error {+ constructor(message: string);+}+/**+ * Error thrown when a sandbox session is not found.+ */+export declare class SandboxNotFoundError extends OpenSandboxError {+ constructor(message?: string);+}+/**+ * Error thrown when connection to the sandbox server fails.+ */+export declare class ConnectionError extends OpenSandboxError {+ constructor(message: string);+}+/**+ * Error thrown when a command execution fails.+ */+export declare class CommandExecutionError extends OpenSandboxError {+ /** Exit code of the failed command */+ exitCode: number;+ /** Standard output from the command */+ stdout: string;+ /** Standard error from the command */+ stderr: string;+ constructor(message: string, exitCode?: number, stdout?: string, stderr?: string);+}+/**+ * Error thrown when a file operation fails.+ */+export declare class FileOperationError extends OpenSandboxError {+ constructor(message: string);+}+//# sourceMappingURL=errors.d.ts.map\ No newline at end of filediff --git a/sdk/typescript/dist/errors.d.ts.map b/sdk/typescript/dist/errors.d.ts.mapnew file mode 100644index 00000000..ec1141dd--- /dev/null+++ b/sdk/typescript/dist/errors.d.ts.map@@ -0,0 +1 @@+{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,KAAK;gBAC7B,OAAO,EAAE,MAAM;CAI5B;AAED;;GAEG;AACH,qBAAa,oBAAqB,SAAQ,gBAAgB;gBAC5C,OAAO,SAA8B;CAIlD;AAED;;GAEG;AACH,qBAAa,eAAgB,SAAQ,gBAAgB;gBACvC,OAAO,EAAE,MAAM;CAI5B;AAED;;GAEG;AACH,qBAAa,qBAAsB,SAAQ,gBAAgB;IACzD,sCAAsC;IACtC,QAAQ,EAAE,MAAM,CAAC;IACjB,uCAAuC;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,sCAAsC;IACtC,MAAM,EAAE,MAAM,CAAC;gBAEH,OAAO,EAAE,MAAM,EAAE,QAAQ,SAAI,EAAE,MAAM,SAAK,EAAE,MAAM,SAAK;CAOpE;AAED;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,gBAAgB;gBAC1C,OAAO,EAAE,MAAM;CAI5B"}\ No newline at end of filediff --git a/sdk/typescript/dist/errors.js b/sdk/typescript/dist/errors.jsnew file mode 100644index 00000000..f5d32fb0--- /dev/null+++ b/sdk/typescript/dist/errors.js@@ -0,0 +1,66 @@+"use strict";+/**+ * Custom error classes for the OpenSandbox SDK.+ */+Object.defineProperty(exports, "__esModule", { value: true });+exports.FileOperationError = exports.CommandExecutionError = exports.ConnectionError = exports.SandboxNotFoundError = exports.OpenSandboxError = void 0;+/**+ * Base error class for OpenSandbox errors.+ */+class OpenSandboxError extends Error {+ constructor(message) {+ super(message);+ this.name = 'OpenSandboxError';+ }+}+exports.OpenSandboxError = OpenSandboxError;+/**+ * Error thrown when a sandbox session is not found.+ */+class SandboxNotFoundError extends OpenSandboxError {+ constructor(message = 'Sandbox session not found') {+ super(message);+ this.name = 'SandboxNotFoundError';+ }+}+exports.SandboxNotFoundError = SandboxNotFoundError;+/**+ * Error thrown when connection to the sandbox server fails.+ */+class ConnectionError extends OpenSandboxError {+ constructor(message) {+ super(message);+ this.name = 'ConnectionError';+ }+}+exports.ConnectionError = ConnectionError;+/**+ * Error thrown when a command execution fails.+ */+class CommandExecutionError extends OpenSandboxError {+ /** Exit code of the failed command */+ exitCode;+ /** Standard output from the command */+ stdout;+ /** Standard error from the command */+ stderr;+ constructor(message, exitCode = 1, stdout = '', stderr = '') {+ super(message);+ this.name = 'CommandExecutionError';+ this.exitCode = exitCode;+ this.stdout = stdout;+ this.stderr = stderr;+ }+}+exports.CommandExecutionError = CommandExecutionError;+/**+ * Error thrown when a file operation fails.+ */+class FileOperationError extends OpenSandboxError {+ constructor(message) {+ super(message);+ this.name = 'FileOperationError';+ }+}+exports.FileOperationError = FileOperationError;+//# sourceMappingURL=errors.js.map\ No newline at end of filediff --git a/sdk/typescript/dist/errors.js.map b/sdk/typescript/dist/errors.js.mapnew file mode 100644index 00000000..d60bf7d8--- /dev/null+++ b/sdk/typescript/dist/errors.js.map@@ -0,0 +1 @@+{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAEH;;GAEG;AACH,MAAa,gBAAiB,SAAQ,KAAK;IACzC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;IACjC,CAAC;CACF;AALD,4CAKC;AAED;;GAEG;AACH,MAAa,oBAAqB,SAAQ,gBAAgB;IACxD,YAAY,OAAO,GAAG,2BAA2B;QAC/C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACrC,CAAC;CACF;AALD,oDAKC;AAED;;GAEG;AACH,MAAa,eAAgB,SAAQ,gBAAgB;IACnD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CACF;AALD,0CAKC;AAED;;GAEG;AACH,MAAa,qBAAsB,SAAQ,gBAAgB;IACzD,sCAAsC;IACtC,QAAQ,CAAS;IACjB,uCAAuC;IACvC,MAAM,CAAS;IACf,sCAAsC;IACtC,MAAM,CAAS;IAEf,YAAY,OAAe,EAAE,QAAQ,GAAG,CAAC,EAAE,MAAM,GAAG,EAAE,EAAE,MAAM,GAAG,EAAE;QACjE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAC;QACpC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAfD,sDAeC;AAED;;GAEG;AACH,MAAa,kBAAmB,SAAQ,gBAAgB;IACtD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AALD,gDAKC"}\ No newline at end of filediff --git a/sdk/typescript/dist/index.d.ts b/sdk/typescript/dist/index.d.tsnew file mode 100644index 00000000..92a8c710--- /dev/null+++ b/sdk/typescript/dist/index.d.ts@@ -0,0 +1,35 @@+/**+ * OpenSandbox TypeScript SDK+ *+ * A TypeScript SDK for interacting with OpenSandbox - secure code execution environments.+ *+ * @example+ * ```typescript+ * import { OpenSandbox } from '@opensandbox/sdk';+ *+ * const client = new OpenSandbox('http://localhost:8080');+ * const sandbox = await client.create();+ *+ * // Run commands+ * const result = await sandbox.run('echo "Hello, World!"');+ * console.log(result.stdout); // "Hello, World!\n"+ *+ * // File operations+ * await sandbox.writeFile('/home/test.txt', 'Hello from SDK!');+ * const content = await sandbox.readFileText('/home/test.txt');+ * console.log(content); // "Hello from SDK!"+ *+ * // List files+ * const files = await sandbox.listFiles('/home');+ * console.log(files);+ *+ * // Cleanup+ * await sandbox.destroy();+ * await client.close();+ * ```+ */+export { OpenSandbox } from './client';+export { Sandbox } from './sandbox';+export type { CommandResult, RunOptions, CreateOptions, ClientOptions, FileEntry, SessionInfo, CreateSessionResponse, BackgroundRunOptions, BackgroundRunResult, } from './types';+export { OpenSandboxError, SandboxNotFoundError, ConnectionError, CommandExecutionError, FileOperationError, } from './errors';+//# sourceMappingURL=index.d.ts.map\ No newline at end of filediff --git a/sdk/typescript/dist/index.d.ts.map b/sdk/typescript/dist/index.d.ts.mapnew file mode 100644index 00000000..37aac18f--- /dev/null+++ b/sdk/typescript/dist/index.d.ts.map@@ -0,0 +1 @@+{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,YAAY,EACV,aAAa,EACb,UAAU,EACV,aAAa,EACb,aAAa,EACb,SAAS,EACT,WAAW,EACX,qBAAqB,EACrB,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,UAAU,CAAC"}\ No newline at end of filediff --git a/sdk/typescript/dist/index.js b/sdk/typescript/dist/index.jsnew file mode 100644index 00000000..072aede0--- /dev/null+++ b/sdk/typescript/dist/index.js@@ -0,0 +1,46 @@+"use strict";+/**+ * OpenSandbox TypeScript SDK+ *+ * A TypeScript SDK for interacting with OpenSandbox - secure code execution environments.+ *+ * @example+ * ```typescript+ * import { OpenSandbox } from '@opensandbox/sdk';+ *+ * const client = new OpenSandbox('http://localhost:8080');+ * const sandbox = await client.create();+ *+ * // Run commands+ * const result = await sandbox.run('echo "Hello, World!"');+ * console.log(result.stdout); // "Hello, World!\n"+ *+ * // File operations+ * await sandbox.writeFile('/home/test.txt', 'Hello from SDK!');+ * const content = await sandbox.readFileText('/home/test.txt');+ * console.log(content); // "Hello from SDK!"+ *+ * // List files+ * const files = await sandbox.listFiles('/home');+ * console.log(files);+ *+ * // Cleanup+ * await sandbox.destroy();+ * await client.close();+ * ```+ */+Object.defineProperty(exports, "__esModule", { value: true });+exports.FileOperationError = exports.CommandExecutionError = exports.ConnectionError = exports.SandboxNotFoundError = exports.OpenSandboxError = exports.Sandbox = exports.OpenSandbox = void 0;+// Main exports+var client_1 = require("./client");+Object.defineProperty(exports, "OpenSandbox", { enumerable: true, get: function () { return client_1.OpenSandbox; } });+var sandbox_1 = require("./sandbox");+Object.defineProperty(exports, "Sandbox", { enumerable: true, get: function () { return sandbox_1.Sandbox; } });+// Error exports+var errors_1 = require("./errors");+Object.defineProperty(exports, "OpenSandboxError", { enumerable: true, get: function () { return errors_1.OpenSandboxError; } });+Object.defineProperty(exports, "SandboxNotFoundError", { enumerable: true, get: function () { return errors_1.SandboxNotFoundError; } });+Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return errors_1.ConnectionError; } });+Object.defineProperty(exports, "CommandExecutionError", { enumerable: true, get: function () { return errors_1.CommandExecutionError; } });+Object.defineProperty(exports, "FileOperationError", { enumerable: true, get: function () { return errors_1.FileOperationError; } });+//# sourceMappingURL=index.js.map\ No newline at end of filediff --git a/sdk/typescript/dist/index.js.map b/sdk/typescript/dist/index.js.mapnew file mode 100644index 00000000..416463be--- /dev/null+++ b/sdk/typescript/dist/index.js.map@@ -0,0 +1 @@+{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;;;AAEH,eAAe;AACf,mCAAuC;AAA9B,qGAAA,WAAW,OAAA;AACpB,qCAAoC;AAA3B,kGAAA,OAAO,OAAA;AAehB,gBAAgB;AAChB,mCAMkB;AALhB,0GAAA,gBAAgB,OAAA;AAChB,8GAAA,oBAAoB,OAAA;AACpB,yGAAA,eAAe,OAAA;AACf,+GAAA,qBAAqB,OAAA;AACrB,4GAAA,kBAAkB,OAAA"}\ No newline at end of filediff --git a/sdk/typescript/dist/sandbox.d.ts b/sdk/typescript/dist/sandbox.d.tsnew file mode 100644index 00000000..b620cc58--- /dev/null+++ b/sdk/typescript/dist/sandbox.d.ts@@ -0,0 +1,202 @@+/**+ * Sandbox session class for interacting with a running sandbox.+ */+import * as grpc from '@grpc/grpc-js';+import type { CommandResult, RunOptions, FileEntry, BackgroundRunOptions, BackgroundRunResult } from './types';+export interface SandboxServiceClient {+ runCommand(request: RunCommandRequest, callback: (error: grpc.ServiceError | null, response: RunCommandResponse) => void): void;+ writeFile(request: WriteFileRequest, callback: (error: grpc.ServiceError | null, response: WriteFileResponse) => void): void;+ writeFiles(request: GrpcWriteFilesRequest, callback: (error: grpc.ServiceError | null, response: GrpcWriteFilesResponse) => void): void;+ readFile(request: ReadFileRequest, callback: (error: grpc.ServiceError | null, response: ReadFileResponse) => void): void;+ setEnv(request: SetEnvRequest, callback: (error: grpc.ServiceError | null, response: SetEnvResponse) => void): void;+ setCwd(request: SetCwdRequest, callback: (error: grpc.ServiceError | null, response: SetCwdResponse) => void): void;+}+interface RunCommandRequest {+ session_id: string;+ command: string[];+ time_ms: number;+ mem_kb: number;+ fsize_kb: number;+ nofile: number;+ env: Record<string, string>;+ cwd: string;+}+interface RunCommandResponse {+ stdout: string;+ stderr: string;+ exit_code: number;+ signal: number;+}+interface WriteFileRequest {+ session_id: string;+ path: string;+ content: Buffer;+}+interface WriteFileResponse {+ success: boolean;+ error: string;+}+interface ReadFileRequest {+ session_id: string;+ path: string;+}+interface ReadFileResponse {+ content: Buffer;+ error: string;+}+interface SetEnvRequest {+ session_id: string;+ env: Record<string, string>;+}+interface SetEnvResponse {+ success: boolean;+}+interface SetCwdRequest {+ session_id: string;+ cwd: string;+}+interface SetCwdResponse {+ success: boolean;+}+interface GrpcBulkFileEntry {+ path: string;+ content: Buffer;+}+interface GrpcWriteFilesRequest {+ session_id: string;+ files: GrpcBulkFileEntry[];+}+interface GrpcFileError {+ path: string;+ error: string;+}+interface GrpcWriteFilesResponse {+ success: boolean;+ errors: GrpcFileError[];+}+/**+ * A sandbox session that can execute commands and manage files.+ *+ * This class uses gRPC for fast command execution and file operations,+ * with HTTP fallback for session lifecycle management.+ */+export declare class Sandbox {+ /** Unique session identifier */+ readonly sessionId: string;+ /** Preview URL for accessing web servers in the sandbox */+ readonly previewUrl: string | null;+ private _grpcStub;+ private _httpBaseUrl;+ private _destroyed;+ constructor(sessionId: string, grpcStub: SandboxServiceClient | null, httpBaseUrl: string, previewUrl?: string | null);+ /**+ * Execute a shell command in the sandbox.+ *+ * @param command - The shell command to execute+ * @param options - Execution options (timeout, memory, etc.)+ * @returns Command result with stdout, stderr, exitCode, and signal+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {CommandExecutionError} If there was an error executing the command+ */+ run(command: string, options?: RunOptions): Promise<CommandResult>;+ private _runViaGrpc;+ private _runViaHttp;+ /**+ * Write content to a file in the sandbox.+ *+ * @param path - Absolute path in the sandbox filesystem+ * @param content - File content (string or Buffer)+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If the file cannot be written+ */+ writeFile(path: string, content: string | Buffer): Promise<void>;+ private _writeFileViaGrpc;+ private _writeFileViaHttp;+ /**+ * Write multiple files to the sandbox in a single request.+ *+ * @param files - Array of files with path and content+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If any file cannot be written (partial success possible)+ */+ writeFiles(files: Array<{+ path: string;+ content: string | Buffer;+ }>): Promise<void>;+ private _writeFilesViaGrpc;+ private _writeFilesViaHttp;+ /**+ * Read a file from the sandbox.+ *+ * @param path - Absolute path in the sandbox filesystem+ * @returns File contents as a Buffer+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If the file cannot be read+ */+ readFile(path: string): Promise<Buffer>;+ private _readFileViaGrpc;+ private _readFileViaHttp;+ /**+ * Read a text file from the sandbox.+ *+ * @param path - Absolute path in the sandbox filesystem+ * @param encoding - Text encoding (default: utf-8)+ * @returns File contents as a string+ */+ readFileText(path: string, encoding?: BufferEncoding): Promise<string>;+ /**+ * List files in a directory within the sandbox.+ *+ * @param path - Directory path in the sandbox filesystem+ * @returns Array of file entries+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If the directory cannot be listed+ */+ listFiles(path: string): Promise<FileEntry[]>;+ /**+ * Set environment variables for subsequent commands.+ *+ * @param env - Dictionary of environment variables to set+ * @throws {SandboxNotFoundError} If the session no longer exists+ */+ setEnv(env: Record<string, string>): Promise<void>;+ private _setEnvViaGrpc;+ private _setEnvViaHttp;+ /**+ * Set the working directory for subsequent commands.+ *+ * @param cwd - The new working directory path+ * @throws {SandboxNotFoundError} If the session no longer exists+ */+ setCwd(cwd: string): Promise<void>;+ private _setCwdViaGrpc;+ private _setCwdViaHttp;+ /**+ * Start a long-running background process in the sandbox (e.g., a dev server).+ * Unlike `run()`, the process survives after the call returns.+ *+ * @param command - The shell command to execute (e.g., "npm run dev")+ * @param options - Background run options (port, env, cwd)+ * @returns Background process result with PID, port, and preview URL+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {CommandExecutionError} If the process couldn't be started+ */+ startBackground(command: string, options?: BackgroundRunOptions): Promise<BackgroundRunResult>;+ /**+ * Kill all background processes in this sandbox.+ *+ * Use this before starting a new background process to avoid port conflicts.+ */+ killBackground(): Promise<{+ killed: number[];+ total: number;+ }>;+ /**+ * Destroy this sandbox session.+ *+ * After calling this method, the sandbox cannot be used anymore.+ */+ destroy(): Promise<void>;+}+export {};+//# sourceMappingURL=sandbox.d.ts.map\ No newline at end of filediff --git a/sdk/typescript/dist/sandbox.d.ts.map b/sdk/typescript/dist/sandbox.d.ts.mapnew file mode 100644index 00000000..688f92e9--- /dev/null+++ b/sdk/typescript/dist/sandbox.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/B,gBAAgB;YAyBhB,gBAAgB;IAkB9B;;;;;;OAMG;IACG,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,GAAE,cAAwB,GAAG,OAAO,CAAC,MAAM,CAAC;IAKrF;;;;;;;OAOG;IACG,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAmCnD;;;;;OAKG;IACG,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;YAc1C,cAAc;YAqBd,cAAc;IAe5B;;;;;OAKG;IACG,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;YAc1B,cAAc;YAqBd,cAAc;IAe5B;;;;;;;;;OASG;IACG,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAuCxG;;;;OAIG;IACG,cAAc,IAAI,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,EAAE,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IAoBpE;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAiB/B"}\ No newline at end of filediff --git a/sdk/typescript/dist/sandbox.js b/sdk/typescript/dist/sandbox.jsnew file mode 100644index 00000000..3ac4ce82--- /dev/null+++ b/sdk/typescript/dist/sandbox.js@@ -0,0 +1,559 @@+"use strict";+/**+ * Sandbox session class for interacting with a running sandbox.+ */+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ var desc = Object.getOwnPropertyDescriptor(m, k);+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {+ desc = { enumerable: true, get: function() { return m[k]; } };+ }+ Object.defineProperty(o, k2, desc);+}) : (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ o[k2] = m[k];+}));+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {+ Object.defineProperty(o, "default", { enumerable: true, value: v });+}) : function(o, v) {+ o["default"] = v;+});+var __importStar = (this && this.__importStar) || (function () {+ var ownKeys = function(o) {+ ownKeys = Object.getOwnPropertyNames || function (o) {+ var ar = [];+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;+ return ar;+ };+ return ownKeys(o);+ };+ return function (mod) {+ if (mod && mod.__esModule) return mod;+ var result = {};+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);+ __setModuleDefault(result, mod);+ return result;+ };+})();+Object.defineProperty(exports, "__esModule", { value: true });+exports.Sandbox = void 0;+const grpc = __importStar(require("@grpc/grpc-js"));+const errors_1 = require("./errors");+/**+ * A sandbox session that can execute commands and manage files.+ *+ * This class uses gRPC for fast command execution and file operations,+ * with HTTP fallback for session lifecycle management.+ */+class Sandbox {+ /** Unique session identifier */+ sessionId;+ /** Preview URL for accessing web servers in the sandbox */+ previewUrl;+ _grpcStub;+ _httpBaseUrl;+ _destroyed = false;+ constructor(sessionId, grpcStub, httpBaseUrl, previewUrl = null) {+ this.sessionId = sessionId;+ this._grpcStub = grpcStub;+ this._httpBaseUrl = httpBaseUrl;+ this.previewUrl = previewUrl;+ }+ /**+ * Execute a shell command in the sandbox.+ *+ * @param command - The shell command to execute+ * @param options - Execution options (timeout, memory, etc.)+ * @returns Command result with stdout, stderr, exitCode, and signal+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {CommandExecutionError} If there was an error executing the command+ */+ async run(command, options = {}) {+ if (this._destroyed) {+ throw new errors_1.SandboxNotFoundError('Sandbox has been destroyed');+ }+ const { timeoutMs = 300000, memKb = 2097152, fsizeKb = 1048576, nofile = 256, env = {}, cwd = '', } = options;+ // Try gRPC first if available+ if (this._grpcStub) {+ return this._runViaGrpc(command, timeoutMs, memKb, fsizeKb, nofile, env, cwd);+ }+ // Fall back to HTTP+ return this._runViaHttp(command, timeoutMs, memKb, fsizeKb, nofile, env, cwd);+ }+ async _runViaGrpc(command, timeoutMs, memKb, fsizeKb, nofile, env, cwd) {+ const request = {+ session_id: this.sessionId,+ command: ['/bin/sh', '-c', command],+ time_ms: timeoutMs,+ mem_kb: memKb,+ fsize_kb: fsizeKb,+ nofile: nofile,+ env: env,+ cwd: cwd,+ };+ return new Promise((resolve, reject) => {+ this._grpcStub.runCommand(request, (error, response) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new errors_1.SandboxNotFoundError('Session not found'));+ }+ else {+ reject(new errors_1.CommandExecutionError(`gRPC error: ${error.message}`));+ }+ return;+ }+ resolve({+ stdout: response.stdout,+ stderr: response.stderr,+ exitCode: response.exit_code,+ signal: response.signal,+ });+ });+ });+ }+ async _runViaHttp(command, timeoutMs, memKb, fsizeKb, nofile, env, cwd) {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/run`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ command: ['/bin/sh', '-c', command],+ time: timeoutMs,+ mem: memKb,+ fsize: fsizeKb,+ nofile: nofile,+ env: env,+ cwd: cwd || '/',+ }),+ });+ if (!response.ok) {+ if (response.status === 404) {+ throw new errors_1.SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new errors_1.CommandExecutionError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }+ const result = await response.json();+ return {+ stdout: result.stdout,+ stderr: result.stderr,+ exitCode: result.exit_code ?? 0,+ signal: result.signal ?? 0,+ };+ }+ /**+ * Write content to a file in the sandbox.+ *+ * @param path - Absolute path in the sandbox filesystem+ * @param content - File content (string or Buffer)+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If the file cannot be written+ */+ async writeFile(path, content) {+ if (this._destroyed) {+ throw new errors_1.SandboxNotFoundError('Sandbox has been destroyed');+ }+ const buffer = typeof content === 'string' ? Buffer.from(content, 'utf-8') : content;+ // Try gRPC first if available+ if (this._grpcStub) {+ return this._writeFileViaGrpc(path, buffer);+ }+ // Fall back to HTTP+ return this._writeFileViaHttp(path, buffer);+ }+ async _writeFileViaGrpc(path, content) {+ const request = {+ session_id: this.sessionId,+ path: path,+ content: content,+ };+ return new Promise((resolve, reject) => {+ this._grpcStub.writeFile(request, (error, response) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new errors_1.SandboxNotFoundError('Session not found'));+ }+ else {+ reject(new errors_1.FileOperationError(`gRPC error: ${error.message}`));+ }+ return;+ }+ if (!response.success) {+ reject(new errors_1.FileOperationError(`Failed to write file: ${response.error}`));+ return;+ }+ resolve();+ });+ });+ }+ async _writeFileViaHttp(path, content) {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/files/write`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ path: path,+ content: content.toString('base64'),+ }),+ });+ if (!response.ok) {+ if (response.status === 404) {+ throw new errors_1.SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new errors_1.FileOperationError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }+ }+ /**+ * Write multiple files to the sandbox in a single request.+ *+ * @param files - Array of files with path and content+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If any file cannot be written (partial success possible)+ */+ async writeFiles(files) {+ if (this._destroyed) {+ throw new errors_1.SandboxNotFoundError('Sandbox has been destroyed');+ }+ const buffered = files.map((f) => ({+ path: f.path,+ content: typeof f.content === 'string' ? Buffer.from(f.content, 'utf-8') : f.content,+ }));+ // Try gRPC first if available+ if (this._grpcStub) {+ return this._writeFilesViaGrpc(buffered);+ }+ // Fall back to HTTP+ return this._writeFilesViaHttp(buffered);+ }+ async _writeFilesViaGrpc(files) {+ const request = {+ session_id: this.sessionId,+ files: files.map((f) => ({ path: f.path, content: f.content })),+ };+ return new Promise((resolve, reject) => {+ this._grpcStub.writeFiles(request, (error, response) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new errors_1.SandboxNotFoundError('Session not found'));+ }+ else {+ reject(new errors_1.FileOperationError(`gRPC error: ${error.message}`));+ }+ return;+ }+ if (!response.success) {+ const msgs = response.errors.map((e) => `${e.path}: ${e.error}`).join('; ');+ reject(new errors_1.FileOperationError(`Failed to write files: ${msgs}`));+ return;+ }+ resolve();+ });+ });+ }+ async _writeFilesViaHttp(files) {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/files/write-bulk`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ files: files.map((f) => ({+ path: f.path,+ content: f.content.toString('base64'),+ })),+ }),+ });+ if (!response.ok) {+ if (response.status === 404) {+ throw new errors_1.SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new errors_1.FileOperationError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }+ const result = await response.json();+ if (!result.success) {+ const msgs = result.errors.map((e) => `${e.path}: ${e.error}`).join('; ');+ throw new errors_1.FileOperationError(`Failed to write files: ${msgs}`);+ }+ }+ /**+ * Read a file from the sandbox.+ *+ * @param path - Absolute path in the sandbox filesystem+ * @returns File contents as a Buffer+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If the file cannot be read+ */+ async readFile(path) {+ if (this._destroyed) {+ throw new errors_1.SandboxNotFoundError('Sandbox has been destroyed');+ }+ // Try gRPC first if available+ if (this._grpcStub) {+ return this._readFileViaGrpc(path);+ }+ // Fall back to HTTP+ return this._readFileViaHttp(path);+ }+ async _readFileViaGrpc(path) {+ const request = {+ session_id: this.sessionId,+ path: path,+ };+ return new Promise((resolve, reject) => {+ this._grpcStub.readFile(request, (error, response) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new errors_1.SandboxNotFoundError('Session not found'));+ }+ else {+ reject(new errors_1.FileOperationError(`gRPC error: ${error.message}`));+ }+ return;+ }+ if (response.error) {+ reject(new errors_1.FileOperationError(`Failed to read file: ${response.error}`));+ return;+ }+ resolve(Buffer.from(response.content));+ });+ });+ }+ async _readFileViaHttp(path) {+ const url = new URL(`${this._httpBaseUrl}/sessions/${this.sessionId}/files/read`);+ url.searchParams.set('path', path);+ const response = await fetch(url.toString());+ if (!response.ok) {+ if (response.status === 404) {+ throw new errors_1.SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new errors_1.FileOperationError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }+ const result = await response.json();+ return Buffer.from(result.content, 'base64');+ }+ /**+ * Read a text file from the sandbox.+ *+ * @param path - Absolute path in the sandbox filesystem+ * @param encoding - Text encoding (default: utf-8)+ * @returns File contents as a string+ */+ async readFileText(path, encoding = 'utf-8') {+ const content = await this.readFile(path);+ return content.toString(encoding);+ }+ /**+ * List files in a directory within the sandbox.+ *+ * @param path - Directory path in the sandbox filesystem+ * @returns Array of file entries+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If the directory cannot be listed+ */+ async listFiles(path) {+ if (this._destroyed) {+ throw new errors_1.SandboxNotFoundError('Sandbox has been destroyed');+ }+ const url = new URL(`${this._httpBaseUrl}/sessions/${this.sessionId}/files/list`);+ url.searchParams.set('path', path);+ const response = await fetch(url.toString());+ if (!response.ok) {+ if (response.status === 404) {+ throw new errors_1.SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new errors_1.FileOperationError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }+ const result = await response.json();+ return result.files.map((f) => ({+ name: f.name,+ path: f.path,+ isDirectory: f.is_directory,+ size: f.size,+ }));+ }+ /**+ * Set environment variables for subsequent commands.+ *+ * @param env - Dictionary of environment variables to set+ * @throws {SandboxNotFoundError} If the session no longer exists+ */+ async setEnv(env) {+ if (this._destroyed) {+ throw new errors_1.SandboxNotFoundError('Sandbox has been destroyed');+ }+ // Try gRPC first if available+ if (this._grpcStub) {+ return this._setEnvViaGrpc(env);+ }+ // Fall back to HTTP+ return this._setEnvViaHttp(env);+ }+ async _setEnvViaGrpc(env) {+ const request = {+ session_id: this.sessionId,+ env: env,+ };+ return new Promise((resolve, reject) => {+ this._grpcStub.setEnv(request, (error) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new errors_1.SandboxNotFoundError('Session not found'));+ }+ else {+ reject(error);+ }+ return;+ }+ resolve();+ });+ });+ }+ async _setEnvViaHttp(env) {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/env`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ env }),+ });+ if (!response.ok) {+ if (response.status === 404) {+ throw new errors_1.SandboxNotFoundError('Session not found');+ }+ throw new Error(`HTTP error: ${response.status} ${response.statusText}`);+ }+ }+ /**+ * Set the working directory for subsequent commands.+ *+ * @param cwd - The new working directory path+ * @throws {SandboxNotFoundError} If the session no longer exists+ */+ async setCwd(cwd) {+ if (this._destroyed) {+ throw new errors_1.SandboxNotFoundError('Sandbox has been destroyed');+ }+ // Try gRPC first if available+ if (this._grpcStub) {+ return this._setCwdViaGrpc(cwd);+ }+ // Fall back to HTTP+ return this._setCwdViaHttp(cwd);+ }+ async _setCwdViaGrpc(cwd) {+ const request = {+ session_id: this.sessionId,+ cwd: cwd,+ };+ return new Promise((resolve, reject) => {+ this._grpcStub.setCwd(request, (error) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new errors_1.SandboxNotFoundError('Session not found'));+ }+ else {+ reject(error);+ }+ return;+ }+ resolve();+ });+ });+ }+ async _setCwdViaHttp(cwd) {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/cwd`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ cwd }),+ });+ if (!response.ok) {+ if (response.status === 404) {+ throw new errors_1.SandboxNotFoundError('Session not found');+ }+ throw new Error(`HTTP error: ${response.status} ${response.statusText}`);+ }+ }+ /**+ * Start a long-running background process in the sandbox (e.g., a dev server).+ * Unlike `run()`, the process survives after the call returns.+ *+ * @param command - The shell command to execute (e.g., "npm run dev")+ * @param options - Background run options (port, env, cwd)+ * @returns Background process result with PID, port, and preview URL+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {CommandExecutionError} If the process couldn't be started+ */+ async startBackground(command, options = {}) {+ if (this._destroyed) {+ throw new errors_1.SandboxNotFoundError('Sandbox has been destroyed');+ }+ const { port = 5173, env = {}, cwd = '' } = options;+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/background`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ command: ['/bin/sh', '-c', command],+ port,+ env,+ cwd: cwd || '/',+ }),+ });+ if (!response.ok) {+ if (response.status === 404) {+ throw new errors_1.SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new errors_1.CommandExecutionError(`Failed to start background process: ${response.status} - ${text}`);+ }+ const result = await response.json();+ return {+ pid: result.pid,+ port: result.port,+ previewUrl: result.preview_url,+ };+ }+ /**+ * Kill all background processes in this sandbox.+ *+ * Use this before starting a new background process to avoid port conflicts.+ */+ async killBackground() {+ if (this._destroyed) {+ throw new errors_1.SandboxNotFoundError('Sandbox has been destroyed');+ }+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/background`, {+ method: 'DELETE',+ });+ if (!response.ok) {+ if (response.status === 404) {+ throw new errors_1.SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new errors_1.CommandExecutionError(`Failed to kill background processes: ${response.status} - ${text}`);+ }+ return await response.json();+ }+ /**+ * Destroy this sandbox session.+ *+ * After calling this method, the sandbox cannot be used anymore.+ */+ async destroy() {+ if (this._destroyed) {+ return;+ }+ try {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}`, {+ method: 'DELETE',+ });+ // Best effort cleanup - ignore errors+ void response;+ }+ catch {+ // Ignore errors during cleanup+ }+ finally {+ this._destroyed = true;+ }+ }+}+exports.Sandbox = Sandbox;+//# sourceMappingURL=sandbox.js.map\ No newline at end of filediff --git a/sdk/typescript/dist/sandbox.js.map b/sdk/typescript/dist/sandbox.js.mapnew file mode 100644index 00000000..d7908602--- /dev/null+++ b/sdk/typescript/dist/sandbox.js.map@@ -0,0 +1 @@+{"version":3,"file":"sandbox.js","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,oDAAsC;AAQtC,qCAIkB;AA4GlB;;;;;GAKG;AACH,MAAa,OAAO;IAClB,gCAAgC;IACvB,SAAS,CAAS;IAE3B,2DAA2D;IAClD,UAAU,CAAgB;IAE3B,SAAS,CAA8B;IACvC,YAAY,CAAS;IACrB,UAAU,GAAG,KAAK,CAAC;IAE3B,YACE,SAAiB,EACjB,QAAqC,EACrC,WAAmB,EACnB,aAA4B,IAAI;QAEhC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QAChC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,GAAG,CAAC,OAAe,EAAE,UAAsB,EAAE;QACjD,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,MAAM,IAAI,6BAAoB,CAAC,4BAA4B,CAAC,CAAC;QAC/D,CAAC;QAED,MAAM,EACJ,SAAS,GAAG,MAAM,EAClB,KAAK,GAAG,OAAO,EACf,OAAO,GAAG,OAAO,EACjB,MAAM,GAAG,GAAG,EACZ,GAAG,GAAG,EAAE,EACR,GAAG,GAAG,EAAE,GACT,GAAG,OAAO,CAAC;QAEZ,8BAA8B;QAC9B,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,OAAO,IAAI,CAAC,W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AAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBAC5B,MAAM,IAAI,6BAAoB,CAAC,mBAAmB,CAAC,CAAC;YACtD,CAAC;YACD,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;YACnC,MAAM,IAAI,8BAAqB,CAAC,wCAAwC,QAAQ,CAAC,MAAM,MAAM,IAAI,EAAE,CAAC,CAAC;QACvG,CAAC;QAED,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAyC,CAAC;IACtE,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,OAAO;QACX,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,OAAO;QACT,CAAC;QAED,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,YAAY,aAAa,IAAI,CAAC,SAAS,EAAE,EAAE;gBAC9E,MAAM,EAAE,QAAQ;aACjB,CAAC,CAAC;YACH,sCAAsC;YACtC,KAAK,QAAQ,CAAC;QAChB,CAAC;QAAC,MAAM,CAAC;YACP,+BAA+B;QACjC,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACzB,CAAC;IACH,CAAC;CACF;AAzmBD,0BAymBC"}\ No newline at end of filediff --git a/sdk/typescript/dist/types.d.ts b/sdk/typescript/dist/types.d.tsnew file mode 100644index 00000000..51eb5463--- /dev/null+++ b/sdk/typescript/dist/types.d.ts@@ -0,0 +1,119 @@+/**+ * TypeScript type definitions for OpenSandbox SDK.+ */+/**+ * Result of a command execution in the sandbox.+ */+export interface CommandResult {+ /** Standard output from the command */+ stdout: string;+ /** Standard error from the command */+ stderr: string;+ /** Exit code (0 for success) */+ exitCode: number;+ /** Signal number if process was killed by a signal */+ signal: number;+}+/**+ * Options for running a command in the sandbox.+ */+export interface RunOptions {+ /** CPU time limit in milliseconds (default: 300000) */+ timeoutMs?: number;+ /** Memory limit in KB (default: 2097152) */+ memKb?: number;+ /** Maximum file size in KB (default: 1048576) */+ fsizeKb?: number;+ /** Maximum number of open files (default: 256) */+ nofile?: number;+ /** Additional environment variables */+ env?: Record<string, string>;+ /** Working directory for the command */+ cwd?: string;+}+/**+ * Options for creating a new sandbox session.+ */+export interface CreateOptions {+ /** Initial environment variables */+ env?: Record<string, string>;+ /** Session timeout in seconds (default: 300) */+ timeout?: number;+}+/**+ * Options for the OpenSandbox client.+ */+export interface ClientOptions {+ /** gRPC port (default: 50051) */+ grpcPort?: number;+ /** Use insecure gRPC connection even for HTTPS base URL */+ grpcInsecure?: boolean;+ /** HTTP request timeout in milliseconds (default: 30000) */+ timeout?: number;+}+/**+ * File entry from directory listing.+ */+export interface FileEntry {+ /** File or directory name */+ name: string;+ /** Full path within the sandbox */+ path: string;+ /** Whether this entry is a directory */+ isDirectory: boolean;+ /** File size in bytes (0 for directories) */+ size: number;+}+/**+ * Session information returned by the server.+ */+export interface SessionInfo {+ /** Unique session ID */+ id: string;+ /** Environment variables */+ env: Record<string, string>;+ /** Current working directory */+ cwd: string;+ /** Session age in seconds */+ ageSecs: number;+ /** Idle time in seconds */+ idleSecs: number;+ /** Preview URL for web servers (if configured) */+ previewUrl: string | null;+ /** Exposed ports */+ ports: number[];+ /** Session status */+ status: 'running' | 'idle' | 'terminating';+}+/**+ * Options for starting a background process (e.g., a dev server).+ */+export interface BackgroundRunOptions {+ /** Port the process will listen on (default: 5173) */+ port?: number;+ /** Additional environment variables */+ env?: Record<string, string>;+ /** Working directory for the command */+ cwd?: string;+}+/**+ * Result of starting a background process.+ */+export interface BackgroundRunResult {+ /** PID of the background process */+ pid: number;+ /** Port the process is listening on */+ port: number;+ /** Preview URL to access the web server */+ previewUrl: string | null;+}+/**+ * Response from creating a session.+ */+export interface CreateSessionResponse {+ /** Unique session ID */+ sessionId: string;+ /** Preview URL for web servers (if configured) */+ previewUrl: string | null;+}+//# sourceMappingURL=types.d.ts.map\ No newline at end of filediff --git a/sdk/typescript/dist/types.d.ts.map b/sdk/typescript/dist/types.d.ts.mapnew file mode 100644index 00000000..a630dee6--- /dev/null+++ b/sdk/typescript/dist/types.d.ts.map@@ -0,0 +1 @@+{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,uCAAuC;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,sCAAsC;IACtC,MAAM,EAAE,MAAM,CAAC;IACf,gCAAgC;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,sDAAsD;IACtD,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,uDAAuD;IACvD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4CAA4C;IAC5C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,iDAAiD;IACjD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,kDAAkD;IAClD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,uCAAuC;IACvC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,wCAAwC;IACxC,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,oCAAoC;IACpC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,gDAAgD;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,iCAAiC;IACjC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,2DAA2D;IAC3D,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,4DAA4D;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WA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 No newline at end of filediff --git a/sdk/typescript/dist/types.js b/sdk/typescript/dist/types.jsnew file mode 100644index 00000000..0bfaad42--- /dev/null+++ b/sdk/typescript/dist/types.js@@ -0,0 +1,6 @@+"use strict";+/**+ * TypeScript type definitions for OpenSandbox SDK.+ */+Object.defineProperty(exports, "__esModule", { value: true });+//# sourceMappingURL=types.js.map\ No newline at end of filediff --git a/sdk/typescript/dist/types.js.map b/sdk/typescript/dist/types.js.mapnew file mode 100644index 00000000..764f3122--- /dev/null+++ b/sdk/typescript/dist/types.js.map@@ -0,0 +1 @@+{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA;;GAEG"}\ No newline at end of filediff --git a/sdk/typescript/examples/demo.ts b/sdk/typescript/examples/demo.tsnew file mode 100644index 00000000..a8de1c7f--- /dev/null+++ b/sdk/typescript/examples/demo.ts@@ -0,0 +1,233 @@+/**+ * OpenSandbox TypeScript SDK Demo+ *+ * This demo showcases all the features of the SDK:+ * - Creating sandbox sessions+ * - Running commands+ * - File operations (write, read, list)+ * - Environment and working directory management+ * - Preview URLs+ *+ * Usage:+ * npx ts-node examples/demo.ts [server-url]+ *+ * Example:+ * npx ts-node examples/demo.ts http://localhost:8080+ */++import { OpenSandbox, Sandbox, CommandResult } from '../src/index';++// Configuration+const SERVER_URL = process.argv[2] || 'http://localhost:8080';++// Helper to print section headers+function section(title: string): void {+ console.log('\n' + '='.repeat(60));+ console.log(` ${title}`);+ console.log('='.repeat(60) + '\n');+}++// Helper to print command results+function printResult(label: string, result: CommandResult): void {+ console.log(`${label}:`);+ console.log(` Exit Code: ${result.exitCode}`);+ if (result.stdout.trim()) {+ console.log(` Stdout: ${result.stdout.trim()}`);+ }+ if (result.stderr.trim()) {+ console.log(` Stderr: ${result.stderr.trim()}`);+ }+}++async function main(): Promise<void> {+ console.log('OpenSandbox TypeScript SDK Demo');+ console.log(`Connecting to: ${SERVER_URL}`);++ const client = new OpenSandbox(SERVER_URL);+ let sandbox: Sandbox | null = null;++ try {+ // =========================================+ section('1. Creating a Sandbox Session');+ // =========================================++ sandbox = await client.create({+ env: { DEMO_VAR: 'hello-from-sdk' },+ });++ console.log(`Session ID: ${sandbox.sessionId}`);+ console.log(`Preview URL: ${sandbox.previewUrl || '(not configured)'}`);++ // =========================================+ section('2. Running Basic Commands');+ // =========================================++ // Simple echo+ const echoResult = await sandbox.run('echo "Hello from OpenSandbox!"');+ printResult('Echo command', echoResult);++ // Check environment variable+ const envResult = await sandbox.run('echo $DEMO_VAR');+ printResult('Environment variable', envResult);++ // List root directory+ const lsResult = await sandbox.run('ls -la /');+ printResult('List root directory', lsResult);++ // Check current user and working directory+ const whoamiResult = await sandbox.run('whoami && pwd');+ printResult('User and directory', whoamiResult);++ // =========================================+ section('3. File Operations');+ // =========================================++ // Write a text file+ console.log('Writing /home/test.txt...');+ await sandbox.writeFile('/home/test.txt', 'Hello, World!\nThis is a test file.');+ console.log(' Done!');++ // Write a JSON file+ const jsonData = {+ name: 'OpenSandbox Demo',+ version: '1.0.0',+ features: ['commands', 'files', 'isolation'],+ };+ console.log('Writing /home/config.json...');+ await sandbox.writeFile('/home/config.json', JSON.stringify(jsonData, null, 2));+ console.log(' Done!');++ // Read the text file back+ console.log('\nReading /home/test.txt...');+ const textContent = await sandbox.readFileText('/home/test.txt');+ console.log(` Content: "${textContent}"`);++ // Read the JSON file back+ console.log('\nReading /home/config.json...');+ const jsonContent = await sandbox.readFileText('/home/config.json');+ console.log(` Content: ${jsonContent}`);++ // List directory contents+ console.log('\nListing /home directory...');+ const files = await sandbox.listFiles('/home');+ console.log(' Files:');+ for (const file of files) {+ const type = file.isDirectory ? 'DIR ' : 'FILE';+ console.log(` [${type}] ${file.name} (${file.size} bytes) - ${file.path}`);+ }++ // =========================================+ section('4. Running Scripts');+ // =========================================++ // Create and run a shell script+ const shellScript = `#!/bin/bash+echo "Running shell script..."+echo "Date: $(date)"+echo "Hostname: $(hostname)"+echo "Files in /home:"+ls -la /home+`;+ console.log('Writing and running shell script...');+ await sandbox.writeFile('/home/script.sh', shellScript);+ const scriptResult = await sandbox.run('chmod +x /home/script.sh && /home/script.sh');+ printResult('Shell script', scriptResult);++ // Check if Node.js is available and run a JS script+ const nodeCheck = await sandbox.run('which node || echo "not found"');+ if (nodeCheck.stdout.includes('/node')) {+ console.log('\nNode.js is available, running JS script...');+ const jsScript = `+const os = require('os');+console.log('Node.js version:', process.version);+console.log('Platform:', os.platform());+console.log('Architecture:', os.arch());+console.log('Free memory:', Math.round(os.freemem() / 1024 / 1024), 'MB');+`;+ await sandbox.writeFile('/home/script.js', jsScript);+ const jsResult = await sandbox.run('node /home/script.js');+ printResult('Node.js script', jsResult);+ } else {+ console.log('\nNode.js not available in sandbox, skipping JS script test');+ }++ // =========================================+ section('5. Environment & Working Directory');+ // =========================================++ // Set additional environment variables+ console.log('Setting environment variables...');+ await sandbox.setEnv({+ API_KEY: 'test-api-key-12345',+ DEBUG: 'true',+ APP_ENV: 'development',+ });+ console.log(' Done!');++ // Verify environment+ const envCheckResult = await sandbox.run('echo "API_KEY=$API_KEY, DEBUG=$DEBUG, APP_ENV=$APP_ENV"');+ printResult('Environment check', envCheckResult);++ // Set working directory+ console.log('\nSetting working directory to /home...');+ await sandbox.setCwd('/home');+ console.log(' Done!');++ // Verify working directory+ const pwdResult = await sandbox.run('pwd && ls');+ printResult('Working directory check', pwdResult);++ // =========================================+ section('6. Resource Limits');+ // =========================================++ // Test with custom resource limits+ console.log('Running command with custom limits...');+ const limitedResult = await sandbox.run('echo "Running with limits"', {+ timeoutMs: 5000, // 5 second timeout+ memKb: 65536, // 64MB memory limit+ });+ printResult('Limited command', limitedResult);++ // =========================================+ section('7. Error Handling');+ // =========================================++ // Test command that fails+ console.log('Running a command that will fail...');+ const failResult = await sandbox.run('exit 42');+ printResult('Failed command', failResult);+ console.log(` (Expected exit code 42, got ${failResult.exitCode})`);++ // Test reading non-existent file+ console.log('\nTrying to read non-existent file...');+ try {+ await sandbox.readFile('/home/does-not-exist.txt');+ console.log(' ERROR: Should have thrown an error!');+ } catch (error) {+ console.log(` Caught expected error: ${(error as Error).message}`);+ }++ // =========================================+ section('Demo Complete!');+ // =========================================++ console.log('All tests passed successfully!\n');++ } catch (error) {+ console.error('\nError during demo:', error);+ process.exit(1);+ } finally {+ // Cleanup+ if (sandbox) {+ console.log('Cleaning up sandbox session...');+ await sandbox.destroy();+ console.log(' Session destroyed.');+ }+ await client.close();+ console.log(' Client closed.');+ }+}++// Run the demo+main().catch(console.error);diff --git a/sdk/typescript/examples/quickstart.ts b/sdk/typescript/examples/quickstart.tsnew file mode 100644index 00000000..58418a15--- /dev/null+++ b/sdk/typescript/examples/quickstart.ts@@ -0,0 +1,85 @@+/**+ * OpenSandbox Quick Start Example+ *+ * A minimal example showing basic usage of the SDK.+ *+ * Usage:+ * npx ts-node examples/quickstart.ts [server-url]+ */++import { OpenSandbox } from '../src/index';++const SERVER_URL = process.argv[2] || 'http://localhost:8080';++async function main() {+ // Create client+ const client = new OpenSandbox(SERVER_URL);++ // Create a sandbox session+ console.log('Creating sandbox...');+ const sandbox = await client.create();+ console.log(`Session ID: ${sandbox.sessionId}`);+ if (sandbox.previewUrl) {+ console.log(`Preview URL: ${sandbox.previewUrl}`);+ }++ try {+ // Run commands+ console.log('\n--- Running Commands ---');++ const result = await sandbox.run('echo "Hello from OpenSandbox!" && date');+ console.log('Output:', result.stdout.trim());++ const lsResult = await sandbox.run('ls -la /');+ console.log('\nRoot directory listing:');+ console.log(lsResult.stdout);++ // Test environment variables+ console.log('--- Environment Variables ---');+ await sandbox.setEnv({ MY_VAR: 'test-value' });+ const envResult = await sandbox.run('echo "MY_VAR=$MY_VAR"');+ console.log(envResult.stdout.trim());++ // Try file operations (may not be available on older servers)+ console.log('\n--- File Operations ---');+ try {+ // Write a file using echo command as fallback+ await sandbox.run('echo "Hello, World!" > /tmp/hello.txt');+ console.log('Wrote /tmp/hello.txt via command');++ // Try the HTTP file API+ await sandbox.writeFile('/home/test.txt', 'Hello from SDK!');+ console.log('Wrote /home/test.txt via HTTP API');++ const content = await sandbox.readFileText('/home/test.txt');+ console.log('Read back:', content);++ const files = await sandbox.listFiles('/home');+ console.log('Files in /home:');+ for (const f of files) {+ console.log(` - ${f.name} (${f.size} bytes)`);+ }+ } catch (err) {+ console.log('File API not available (server may need update)');+ console.log('Using command-based file operations instead...');++ // Fallback: use commands for file operations+ await sandbox.run('echo "Hello from SDK!" > /tmp/test.txt');+ const catResult = await sandbox.run('cat /tmp/test.txt');+ console.log('File content via cat:', catResult.stdout.trim());++ const lsHome = await sandbox.run('ls -la /tmp/');+ console.log('Files in /tmp:');+ console.log(lsHome.stdout);+ }++ } finally {+ // Cleanup+ console.log('\n--- Cleanup ---');+ await sandbox.destroy();+ await client.close();+ console.log('Done!');+ }+}++main().catch(console.error);diff --git a/sdk/typescript/package-lock.json b/sdk/typescript/package-lock.jsonnew file mode 100644index 00000000..53fd89a7--- /dev/null+++ b/sdk/typescript/package-lock.json@@ -0,0 +1,591 @@+{+ "name": "@opensandbox/sdk",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@opensandbox/sdk",+ "version": "0.1.0",+ "license": "MIT",+ "dependencies": {+ "@grpc/grpc-js": "^1.10.0",+ "@grpc/proto-loader": "^0.7.0",+ "google-protobuf": "^3.21.0"+ },+ "devDependencies": {+ "@types/google-protobuf": "^3.15.0",+ "@types/node": "^20.0.0",+ "ts-node": "^10.9.0",+ "typescript": "^5.0.0"+ }+ },+ "node_modules/@cspotcode/source-map-support": {+ "version": "0.8.1",+ "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",+ "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "0.3.9"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@grpc/grpc-js": {+ "version": "1.14.3",+ "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.3.tgz",+ "integrity": "sha512-Iq8QQQ/7X3Sac15oB6p0FmUg/klxQvXLeileoqrTRGJYLV+/9tubbr9ipz0GKHjmXVsgFPo/+W+2cA8eNcR+XA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@grpc/proto-loader": "^0.8.0",+ "@js-sdsl/ordered-map": "^4.4.2"+ },+ "engines": {+ "node": ">=12.10.0"+ }+ },+ "node_modules/@grpc/grpc-js/node_modules/@grpc/proto-loader": {+ "version": "0.8.0",+ "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.0.tgz",+ "integrity": "sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "lodash.camelcase": "^4.3.0",+ "long": "^5.0.0",+ "protobufjs": "^7.5.3",+ "yargs": "^17.7.2"+ },+ "bin": {+ "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/@grpc/proto-loader": {+ "version": "0.7.15",+ "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz",+ "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "lodash.camelcase": "^4.3.0",+ "long": "^5.0.0",+ "protobufjs": "^7.2.5",+ "yargs": "^17.7.2"+ },+ "bin": {+ "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.9",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",+ "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.0.3",+ "@jridgewell/sourcemap-codec": "^1.4.10"+ }+ },+ "node_modules/@js-sdsl/ordered-map": {+ "version": "4.4.2",+ "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz",+ "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/js-sdsl"+ }+ },+ "node_modules/@protobufjs/aspromise": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",+ "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/base64": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",+ "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/codegen": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz",+ "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/eventemitter": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz",+ "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/fetch": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz",+ "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@protobufjs/aspromise": "^1.1.1",+ "@protobufjs/inquire": "^1.1.0"+ }+ },+ "node_modules/@protobufjs/float": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",+ "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/inquire": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz",+ "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/path": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",+ "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/pool": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",+ "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@protobufjs/utf8": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz",+ "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==",+ "license": "BSD-3-Clause"+ },+ "node_modules/@tsconfig/node10": {+ "version": "1.0.12",+ "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.12.tgz",+ "integrity": "sha512-UCYBaeFvM11aU2y3YPZ//O5Rhj+xKyzy7mvcIoAjASbigy8mHMryP5cK7dgjlz2hWxh1g5pLw084E0a/wlUSFQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@tsconfig/node12": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz",+ "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@tsconfig/node14": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz",+ "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@tsconfig/node16": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz",+ "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/google-protobuf": {+ "version": "3.15.12",+ "resolved": "https://registry.npmjs.org/@types/google-protobuf/-/google-protobuf-3.15.12.tgz",+ "integrity": "sha512-40um9QqwHjRS92qnOaDpL7RmDK15NuZYo9HihiJRbYkMQZlWnuH8AdvbMy8/o6lgLmKbDUKa+OALCltHdbOTpQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "20.19.31",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.31.tgz",+ "integrity": "sha512-5jsi0wpncvTD33Sh1UCgacK37FFwDn+EG7wCmEvs62fCvBL+n8/76cAYDok21NF6+jaVWIqKwCZyX7Vbu8eB3A==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/acorn": {+ "version": "8.15.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",+ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",+ "dev": true,+ "license": "MIT",+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-walk": {+ "version": "8.3.4",+ "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz",+ "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "acorn": "^8.11.0"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/ansi-styles": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",+ "license": "MIT",+ "dependencies": {+ "color-convert": "^2.0.1"+ },+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/arg": {+ "version": "4.1.3",+ "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",+ "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/cliui": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",+ "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^4.2.0",+ "strip-ansi": "^6.0.1",+ "wrap-ansi": "^7.0.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/color-convert": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",+ "license": "MIT",+ "dependencies": {+ "color-name": "~1.1.4"+ },+ "engines": {+ "node": ">=7.0.0"+ }+ },+ "node_modules/color-name": {+ "version": "1.1.4",+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",+ "license": "MIT"+ },+ "node_modules/create-require": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",+ "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/diff": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz",+ "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.3.1"+ }+ },+ "node_modules/emoji-regex": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",+ "license": "MIT"+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/google-protobuf": {+ "version": "3.21.4",+ "resolved": "https://registry.npmjs.org/google-protobuf/-/google-protobuf-3.21.4.tgz",+ "integrity": "sha512-MnG7N936zcKTco4Jd2PX2U96Kf9PxygAPKBug+74LHzmHXmceN16MmRcdgZv+DGef/S9YvQAfRsNCn4cjf9yyQ==",+ "license": "(BSD-3-Clause AND Apache-2.0)"+ },+ "node_modules/is-fullwidth-code-point": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/lodash.camelcase": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz",+ "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==",+ "license": "MIT"+ },+ "node_modules/long": {+ "version": "5.3.2",+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",+ "license": "Apache-2.0"+ },+ "node_modules/make-error": {+ "version": "1.3.6",+ "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",+ "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/protobufjs": {+ "version": "7.5.4",+ "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.4.tgz",+ "integrity": "sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg==",+ "hasInstallScript": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "@protobufjs/aspromise": "^1.1.2",+ "@protobufjs/base64": "^1.1.2",+ "@protobufjs/codegen": "^2.0.4",+ "@protobufjs/eventemitter": "^1.1.0",+ "@protobufjs/fetch": "^1.1.0",+ "@protobufjs/float": "^1.0.2",+ "@protobufjs/inquire": "^1.1.0",+ "@protobufjs/path": "^1.1.2",+ "@protobufjs/pool": "^1.1.0",+ "@protobufjs/utf8": "^1.1.0",+ "@types/node": ">=13.7.0",+ "long": "^5.0.0"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/require-directory": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/string-width": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^8.0.0",+ "is-fullwidth-code-point": "^3.0.0",+ "strip-ansi": "^6.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/strip-ansi": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/ts-node": {+ "version": "10.9.2",+ "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",+ "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@cspotcode/source-map-support": "^0.8.0",+ "@tsconfig/node10": "^1.0.7",+ "@tsconfig/node12": "^1.0.7",+ "@tsconfig/node14": "^1.0.0",+ "@tsconfig/node16": "^1.0.2",+ "acorn": "^8.4.1",+ "acorn-walk": "^8.1.1",+ "arg": "^4.1.0",+ "create-require": "^1.1.0",+ "diff": "^4.0.1",+ "make-error": "^1.1.1",+ "v8-compile-cache-lib": "^3.0.1",+ "yn": "3.1.1"+ },+ "bin": {+ "ts-node": "dist/bin.js",+ "ts-node-cwd": "dist/bin-cwd.js",+ "ts-node-esm": "dist/bin-esm.js",+ "ts-node-script": "dist/bin-script.js",+ "ts-node-transpile-only": "dist/bin-transpile.js",+ "ts-script": "dist/bin-script-deprecated.js"+ },+ "peerDependencies": {+ "@swc/core": ">=1.2.50",+ "@swc/wasm": ">=1.2.50",+ "@types/node": "*",+ "typescript": ">=2.7"+ },+ "peerDependenciesMeta": {+ "@swc/core": {+ "optional": true+ },+ "@swc/wasm": {+ "optional": true+ }+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "peer": true,+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "license": "MIT"+ },+ "node_modules/v8-compile-cache-lib": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",+ "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/wrap-ansi": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.0.0",+ "string-width": "^4.1.0",+ "strip-ansi": "^6.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yargs": {+ "version": "17.7.2",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",+ "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^8.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "require-directory": "^2.1.1",+ "string-width": "^4.2.3",+ "y18n": "^5.0.5",+ "yargs-parser": "^21.1.1"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yargs-parser": {+ "version": "21.1.1",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",+ "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yn": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",+ "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ }+ }+}diff --git a/sdk/typescript/package.json b/sdk/typescript/package.jsonnew file mode 100644index 00000000..d4322e42--- /dev/null+++ b/sdk/typescript/package.json@@ -0,0 +1,49 @@+{+ "name": "@opensandbox/sdk",+ "version": "0.1.0",+ "description": "TypeScript SDK for OpenSandbox - secure code execution environments",+ "main": "dist/index.js",+ "types": "dist/index.d.ts",+ "exports": {+ ".": {+ "require": "./dist/index.js",+ "types": "./dist/index.d.ts"+ }+ },+ "files": [+ "dist",+ "src"+ ],+ "scripts": {+ "build": "tsc",+ "clean": "rm -rf dist",+ "prepublishOnly": "npm run build",+ "demo": "npx ts-node -T examples/demo.ts",+ "quickstart": "npx ts-node -T examples/quickstart.ts",+ "proto": "grpc_tools_node_protoc --js_out=import_style=commonjs,binary:./src/proto --grpc_out=grpc_js:./src/proto --plugin=protoc-gen-grpc=`which grpc_tools_node_protoc_plugin` -I ../../proto ../../proto/sandbox.proto"+ },+ "dependencies": {+ "@grpc/grpc-js": "^1.10.0",+ "@grpc/proto-loader": "^0.7.0",+ "google-protobuf": "^3.21.0"+ },+ "devDependencies": {+ "@types/google-protobuf": "^3.15.0",+ "@types/node": "^20.0.0",+ "ts-node": "^10.9.0",+ "typescript": "^5.0.0"+ },+ "keywords": [+ "sandbox",+ "opensandbox",+ "code-execution",+ "isolation",+ "container"+ ],+ "author": "",+ "license": "MIT",+ "repository": {+ "type": "git",+ "url": "https://github.com/diggerhq/opensandbox"+ }+}diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.tsnew file mode 100644index 00000000..490870d1--- /dev/null+++ b/sdk/typescript/src/client.ts@@ -0,0 +1,156 @@+/**+ * OpenSandbox client for creating and managing sandbox sessions.+ */++import * as grpc from '@grpc/grpc-js';+import * as protoLoader from '@grpc/proto-loader';+import { Sandbox } from './sandbox';+import { ConnectionError } from './errors';+import type { ClientOptions, CreateOptions } from './types';++// gRPC service definition loaded from proto+interface SandboxServiceClient {+ new (address: string, credentials: grpc.ChannelCredentials): SandboxServiceClient;+}++interface ProtoGrpcType {+ sandbox: {+ SandboxService: SandboxServiceClient;+ };+}++/**+ * Client for connecting to an OpenSandbox server.+ *+ * This client uses HTTP for sandbox lifecycle (create/destroy) and+ * optionally gRPC for fast command execution and file operations.+ *+ * @example+ * ```typescript+ * const client = new OpenSandbox('http://localhost:8080');+ * const sandbox = await client.create();+ * const result = await sandbox.run('echo hello');+ * console.log(result.stdout); // "hello\n"+ * await sandbox.destroy();+ * await client.close();+ * ```+ */+export class OpenSandbox {+ private _baseUrl: string;+ private _grpcPort: number;+ private _grpcInsecure: boolean;+ private _timeout: number;+ private _grpcChannel: grpc.Channel | null = null;+ private _grpcStub: any = null;+ private _host: string;+ private _grpcSecure: boolean;++ /**+ * Initialize the OpenSandbox client.+ *+ * @param baseUrl - Base URL of the OpenSandbox server (e.g., "http://localhost:8080")+ * @param options - Client options+ */+ constructor(baseUrl: string, options: ClientOptions = {}) {+ this._baseUrl = baseUrl.replace(/\/$/, '');+ this._grpcPort = options.grpcPort ?? 50051;+ this._grpcInsecure = options.grpcInsecure ?? false;+ this._timeout = options.timeout ?? 30000;++ // Parse URL to get host+ const url = new URL(this._baseUrl);+ this._host = url.hostname;+ // Use secure gRPC for HTTPS unless explicitly set to insecure+ this._grpcSecure = url.protocol === 'https:' && !this._grpcInsecure;+ }++ /**+ * Create a new sandbox session.+ *+ * @param options - Options for creating the sandbox+ * @returns A Sandbox instance ready for use+ * @throws {ConnectionError} If connection to the server fails+ */+ async create(options: CreateOptions = {}): Promise<Sandbox> {+ const { env = {}, timeout = 300 } = options;++ try {+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), this._timeout);++ const response = await fetch(`${this._baseUrl}/sessions`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ env }),+ signal: controller.signal,+ });++ clearTimeout(timeoutId);++ if (!response.ok) {+ throw new ConnectionError(`Failed to create sandbox: ${response.status} ${response.statusText}`);+ }++ // Server returns snake_case, we need to map to camelCase+ const data = await response.json() as {+ session_id: string;+ preview_url: string | null;+ };++ return new Sandbox(+ data.session_id,+ this._grpcStub,+ this._baseUrl,+ data.preview_url+ );+ } catch (error) {+ if (error instanceof ConnectionError) {+ throw error;+ }+ throw new ConnectionError(`Failed to create sandbox: ${error}`);+ }+ }++ /**+ * Initialize gRPC connection (optional, for better performance).+ *+ * Call this method before creating sandboxes if you want to use gRPC+ * for command execution and file operations.+ */+ async connectGrpc(): Promise<void> {+ const grpcTarget = `${this._host}:${this._grpcPort}`;++ const credentials = this._grpcSecure+ ? grpc.credentials.createSsl()+ : grpc.credentials.createInsecure();++ // Load proto file dynamically+ // Note: In a real implementation, you'd either bundle the proto file+ // or generate TypeScript types from it+ try {+ const packageDefinition = protoLoader.loadSync('sandbox.proto', {+ keepCase: true,+ longs: String,+ enums: String,+ defaults: true,+ oneofs: true,+ });+ const proto = grpc.loadPackageDefinition(packageDefinition) as unknown as ProtoGrpcType;+ this._grpcStub = new proto.sandbox.SandboxService(grpcTarget, credentials);+ } catch {+ // gRPC connection is optional - SDK works with HTTP only+ console.warn('gRPC connection not available, using HTTP only');+ }+ }++ /**+ * Close all connections to the server.+ */+ async close(): Promise<void> {+ if (this._grpcChannel) {+ this._grpcChannel.close();+ this._grpcChannel = null;+ }+ this._grpcStub = null;+ }+}diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.tsnew file mode 100644index 00000000..c84cadf2--- /dev/null+++ b/sdk/typescript/src/errors.ts@@ -0,0 +1,63 @@+/**+ * Custom error classes for the OpenSandbox SDK.+ */++/**+ * Base error class for OpenSandbox errors.+ */+export class OpenSandboxError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'OpenSandboxError';+ }+}++/**+ * Error thrown when a sandbox session is not found.+ */+export class SandboxNotFoundError extends OpenSandboxError {+ constructor(message = 'Sandbox session not found') {+ super(message);+ this.name = 'SandboxNotFoundError';+ }+}++/**+ * Error thrown when connection to the sandbox server fails.+ */+export class ConnectionError extends OpenSandboxError {+ constructor(message: string) {+ super(message);+ this.name = 'ConnectionError';+ }+}++/**+ * Error thrown when a command execution fails.+ */+export class CommandExecutionError extends OpenSandboxError {+ /** Exit code of the failed command */+ exitCode: number;+ /** Standard output from the command */+ stdout: string;+ /** Standard error from the command */+ stderr: string;++ constructor(message: string, exitCode = 1, stdout = '', stderr = '') {+ super(message);+ this.name = 'CommandExecutionError';+ this.exitCode = exitCode;+ this.stdout = stdout;+ this.stderr = stderr;+ }+}++/**+ * Error thrown when a file operation fails.+ */+export class FileOperationError extends OpenSandboxError {+ constructor(message: string) {+ super(message);+ this.name = 'FileOperationError';+ }+}diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsnew file mode 100644index 00000000..5fa5970d--- /dev/null+++ b/sdk/typescript/src/index.ts@@ -0,0 +1,56 @@+/**+ * OpenSandbox TypeScript SDK+ *+ * A TypeScript SDK for interacting with OpenSandbox - secure code execution environments.+ *+ * @example+ * ```typescript+ * import { OpenSandbox } from '@opensandbox/sdk';+ *+ * const client = new OpenSandbox('http://localhost:8080');+ * const sandbox = await client.create();+ *+ * // Run commands+ * const result = await sandbox.run('echo "Hello, World!"');+ * console.log(result.stdout); // "Hello, World!\n"+ *+ * // File operations+ * await sandbox.writeFile('/home/test.txt', 'Hello from SDK!');+ * const content = await sandbox.readFileText('/home/test.txt');+ * console.log(content); // "Hello from SDK!"+ *+ * // List files+ * const files = await sandbox.listFiles('/home');+ * console.log(files);+ *+ * // Cleanup+ * await sandbox.destroy();+ * await client.close();+ * ```+ */++// Main exports+export { OpenSandbox } from './client';+export { Sandbox } from './sandbox';++// Type exports+export type {+ CommandResult,+ RunOptions,+ CreateOptions,+ ClientOptions,+ FileEntry,+ SessionInfo,+ CreateSessionResponse,+ BackgroundRunOptions,+ BackgroundRunResult,+} from './types';++// Error exports+export {+ OpenSandboxError,+ SandboxNotFoundError,+ ConnectionError,+ CommandExecutionError,+ FileOperationError,+} from './errors';diff --git a/sdk/typescript/src/sandbox.ts b/sdk/typescript/src/sandbox.tsnew file mode 100644index 00000000..4a368f4b--- /dev/null+++ b/sdk/typescript/src/sandbox.ts@@ -0,0 +1,748 @@+/**+ * Sandbox session class for interacting with a running sandbox.+ */++import * as grpc from '@grpc/grpc-js';+import type {+ CommandResult,+ RunOptions,+ FileEntry,+ BackgroundRunOptions,+ BackgroundRunResult,+} from './types';+import {+ SandboxNotFoundError,+ CommandExecutionError,+ FileOperationError,+} from './errors';++// gRPC client stub type (generated from proto)+export interface SandboxServiceClient {+ runCommand(+ request: RunCommandRequest,+ callback: (error: grpc.ServiceError | null, response: RunCommandResponse) => void+ ): void;+ writeFile(+ request: WriteFileRequest,+ callback: (error: grpc.ServiceError | null, response: WriteFileResponse) => void+ ): void;+ writeFiles(+ request: GrpcWriteFilesRequest,+ callback: (error: grpc.ServiceError | null, response: GrpcWriteFilesResponse) => void+ ): void;+ readFile(+ request: ReadFileRequest,+ callback: (error: grpc.ServiceError | null, response: ReadFileResponse) => void+ ): void;+ setEnv(+ request: SetEnvRequest,+ callback: (error: grpc.ServiceError | null, response: SetEnvResponse) => void+ ): void;+ setCwd(+ request: SetCwdRequest,+ callback: (error: grpc.ServiceError | null, response: SetCwdResponse) => void+ ): void;+}++// Request/Response types matching the proto definitions+interface RunCommandRequest {+ session_id: string;+ command: string[];+ time_ms: number;+ mem_kb: number;+ fsize_kb: number;+ nofile: number;+ env: Record<string, string>;+ cwd: string;+}++interface RunCommandResponse {+ stdout: string;+ stderr: string;+ exit_code: number;+ signal: number;+}++interface WriteFileRequest {+ session_id: string;+ path: string;+ content: Buffer;+}++interface WriteFileResponse {+ success: boolean;+ error: string;+}++interface ReadFileRequest {+ session_id: string;+ path: string;+}++interface ReadFileResponse {+ content: Buffer;+ error: string;+}++interface SetEnvRequest {+ session_id: string;+ env: Record<string, string>;+}++interface SetEnvResponse {+ success: boolean;+}++interface SetCwdRequest {+ session_id: string;+ cwd: string;+}++interface SetCwdResponse {+ success: boolean;+}++interface GrpcBulkFileEntry {+ path: string;+ content: Buffer;+}++interface GrpcWriteFilesRequest {+ session_id: string;+ files: GrpcBulkFileEntry[];+}++interface GrpcFileError {+ path: string;+ error: string;+}++interface GrpcWriteFilesResponse {+ success: boolean;+ errors: GrpcFileError[];+}++/**+ * A sandbox session that can execute commands and manage files.+ *+ * This class uses gRPC for fast command execution and file operations,+ * with HTTP fallback for session lifecycle management.+ */+export class Sandbox {+ /** Unique session identifier */+ readonly sessionId: string;++ /** Preview URL for accessing web servers in the sandbox */+ readonly previewUrl: string | null;++ private _grpcStub: SandboxServiceClient | null;+ private _httpBaseUrl: string;+ private _destroyed = false;++ constructor(+ sessionId: string,+ grpcStub: SandboxServiceClient | null,+ httpBaseUrl: string,+ previewUrl: string | null = null+ ) {+ this.sessionId = sessionId;+ this._grpcStub = grpcStub;+ this._httpBaseUrl = httpBaseUrl;+ this.previewUrl = previewUrl;+ }++ /**+ * Execute a shell command in the sandbox.+ *+ * @param command - The shell command to execute+ * @param options - Execution options (timeout, memory, etc.)+ * @returns Command result with stdout, stderr, exitCode, and signal+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {CommandExecutionError} If there was an error executing the command+ */+ async run(command: string, options: RunOptions = {}): Promise<CommandResult> {+ if (this._destroyed) {+ throw new SandboxNotFoundError('Sandbox has been destroyed');+ }++ const {+ timeoutMs = 300000,+ memKb = 2097152,+ fsizeKb = 1048576,+ nofile = 256,+ env = {},+ cwd = '',+ } = options;++ // Try gRPC first if available+ if (this._grpcStub) {+ return this._runViaGrpc(command, timeoutMs, memKb, fsizeKb, nofile, env, cwd);+ }++ // Fall back to HTTP+ return this._runViaHttp(command, timeoutMs, memKb, fsizeKb, nofile, env, cwd);+ }++ private async _runViaGrpc(+ command: string,+ timeoutMs: number,+ memKb: number,+ fsizeKb: number,+ nofile: number,+ env: Record<string, string>,+ cwd: string+ ): Promise<CommandResult> {+ const request: RunCommandRequest = {+ session_id: this.sessionId,+ command: ['/bin/sh', '-c', command],+ time_ms: timeoutMs,+ mem_kb: memKb,+ fsize_kb: fsizeKb,+ nofile: nofile,+ env: env,+ cwd: cwd,+ };++ return new Promise((resolve, reject) => {+ this._grpcStub!.runCommand(request, (error, response) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new SandboxNotFoundError('Session not found'));+ } else {+ reject(new CommandExecutionError(`gRPC error: ${error.message}`));+ }+ return;+ }+ resolve({+ stdout: response.stdout,+ stderr: response.stderr,+ exitCode: response.exit_code,+ signal: response.signal,+ });+ });+ });+ }++ private async _runViaHttp(+ command: string,+ timeoutMs: number,+ memKb: number,+ fsizeKb: number,+ nofile: number,+ env: Record<string, string>,+ cwd: string+ ): Promise<CommandResult> {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/run`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ command: ['/bin/sh', '-c', command],+ time: timeoutMs,+ mem: memKb,+ fsize: fsizeKb,+ nofile: nofile,+ env: env,+ cwd: cwd || '/',+ }),+ });++ if (!response.ok) {+ if (response.status === 404) {+ throw new SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new CommandExecutionError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }++ const result = await response.json() as {+ stdout: string;+ stderr: string;+ exit_code: number | null;+ signal: number | null;+ };++ return {+ stdout: result.stdout,+ stderr: result.stderr,+ exitCode: result.exit_code ?? 0,+ signal: result.signal ?? 0,+ };+ }++ /**+ * Write content to a file in the sandbox.+ *+ * @param path - Absolute path in the sandbox filesystem+ * @param content - File content (string or Buffer)+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If the file cannot be written+ */+ async writeFile(path: string, content: string | Buffer): Promise<void> {+ if (this._destroyed) {+ throw new SandboxNotFoundError('Sandbox has been destroyed');+ }++ const buffer = typeof content === 'string' ? Buffer.from(content, 'utf-8') : content;++ // Try gRPC first if available+ if (this._grpcStub) {+ return this._writeFileViaGrpc(path, buffer);+ }++ // Fall back to HTTP+ return this._writeFileViaHttp(path, buffer);+ }++ private async _writeFileViaGrpc(path: string, content: Buffer): Promise<void> {+ const request: WriteFileRequest = {+ session_id: this.sessionId,+ path: path,+ content: content,+ };++ return new Promise((resolve, reject) => {+ this._grpcStub!.writeFile(request, (error, response) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new SandboxNotFoundError('Session not found'));+ } else {+ reject(new FileOperationError(`gRPC error: ${error.message}`));+ }+ return;+ }+ if (!response.success) {+ reject(new FileOperationError(`Failed to write file: ${response.error}`));+ return;+ }+ resolve();+ });+ });+ }++ private async _writeFileViaHttp(path: string, content: Buffer): Promise<void> {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/files/write`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ path: path,+ content: content.toString('base64'),+ }),+ });++ if (!response.ok) {+ if (response.status === 404) {+ throw new SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new FileOperationError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }+ }++ /**+ * Write multiple files to the sandbox in a single request.+ *+ * @param files - Array of files with path and content+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If any file cannot be written (partial success possible)+ */+ async writeFiles(files: Array<{ path: string; content: string | Buffer }>): Promise<void> {+ if (this._destroyed) {+ throw new SandboxNotFoundError('Sandbox has been destroyed');+ }++ const buffered = files.map((f) => ({+ path: f.path,+ content: typeof f.content === 'string' ? Buffer.from(f.content, 'utf-8') : f.content,+ }));++ // Try gRPC first if available+ if (this._grpcStub) {+ return this._writeFilesViaGrpc(buffered);+ }++ // Fall back to HTTP+ return this._writeFilesViaHttp(buffered);+ }++ private async _writeFilesViaGrpc(files: Array<{ path: string; content: Buffer }>): Promise<void> {+ const request: GrpcWriteFilesRequest = {+ session_id: this.sessionId,+ files: files.map((f) => ({ path: f.path, content: f.content })),+ };++ return new Promise((resolve, reject) => {+ this._grpcStub!.writeFiles(request, (error, response) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new SandboxNotFoundError('Session not found'));+ } else {+ reject(new FileOperationError(`gRPC error: ${error.message}`));+ }+ return;+ }+ if (!response.success) {+ const msgs = response.errors.map((e: GrpcFileError) => `${e.path}: ${e.error}`).join('; ');+ reject(new FileOperationError(`Failed to write files: ${msgs}`));+ return;+ }+ resolve();+ });+ });+ }++ private async _writeFilesViaHttp(files: Array<{ path: string; content: Buffer }>): Promise<void> {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/files/write-bulk`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ files: files.map((f) => ({+ path: f.path,+ content: f.content.toString('base64'),+ })),+ }),+ });++ if (!response.ok) {+ if (response.status === 404) {+ throw new SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new FileOperationError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }++ const result = await response.json() as { success: boolean; errors: Array<{ path: string; error: string }> };+ if (!result.success) {+ const msgs = result.errors.map((e) => `${e.path}: ${e.error}`).join('; ');+ throw new FileOperationError(`Failed to write files: ${msgs}`);+ }+ }++ /**+ * Read a file from the sandbox.+ *+ * @param path - Absolute path in the sandbox filesystem+ * @returns File contents as a Buffer+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If the file cannot be read+ */+ async readFile(path: string): Promise<Buffer> {+ if (this._destroyed) {+ throw new SandboxNotFoundError('Sandbox has been destroyed');+ }++ // Try gRPC first if available+ if (this._grpcStub) {+ return this._readFileViaGrpc(path);+ }++ // Fall back to HTTP+ return this._readFileViaHttp(path);+ }++ private async _readFileViaGrpc(path: string): Promise<Buffer> {+ const request: ReadFileRequest = {+ session_id: this.sessionId,+ path: path,+ };++ return new Promise((resolve, reject) => {+ this._grpcStub!.readFile(request, (error, response) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new SandboxNotFoundError('Session not found'));+ } else {+ reject(new FileOperationError(`gRPC error: ${error.message}`));+ }+ return;+ }+ if (response.error) {+ reject(new FileOperationError(`Failed to read file: ${response.error}`));+ return;+ }+ resolve(Buffer.from(response.content));+ });+ });+ }++ private async _readFileViaHttp(path: string): Promise<Buffer> {+ const url = new URL(`${this._httpBaseUrl}/sessions/${this.sessionId}/files/read`);+ url.searchParams.set('path', path);++ const response = await fetch(url.toString());++ if (!response.ok) {+ if (response.status === 404) {+ throw new SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new FileOperationError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }++ const result = await response.json() as { content: string };+ return Buffer.from(result.content, 'base64');+ }++ /**+ * Read a text file from the sandbox.+ *+ * @param path - Absolute path in the sandbox filesystem+ * @param encoding - Text encoding (default: utf-8)+ * @returns File contents as a string+ */+ async readFileText(path: string, encoding: BufferEncoding = 'utf-8'): Promise<string> {+ const content = await this.readFile(path);+ return content.toString(encoding);+ }++ /**+ * List files in a directory within the sandbox.+ *+ * @param path - Directory path in the sandbox filesystem+ * @returns Array of file entries+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {FileOperationError} If the directory cannot be listed+ */+ async listFiles(path: string): Promise<FileEntry[]> {+ if (this._destroyed) {+ throw new SandboxNotFoundError('Sandbox has been destroyed');+ }++ const url = new URL(`${this._httpBaseUrl}/sessions/${this.sessionId}/files/list`);+ url.searchParams.set('path', path);++ const response = await fetch(url.toString());++ if (!response.ok) {+ if (response.status === 404) {+ throw new SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new FileOperationError(`HTTP error: ${response.status} ${response.statusText} - ${text}`);+ }++ const result = await response.json() as {+ files: Array<{+ name: string;+ path: string;+ is_directory: boolean;+ size: number;+ }>;+ };++ return result.files.map((f) => ({+ name: f.name,+ path: f.path,+ isDirectory: f.is_directory,+ size: f.size,+ }));+ }++ /**+ * Set environment variables for subsequent commands.+ *+ * @param env - Dictionary of environment variables to set+ * @throws {SandboxNotFoundError} If the session no longer exists+ */+ async setEnv(env: Record<string, string>): Promise<void> {+ if (this._destroyed) {+ throw new SandboxNotFoundError('Sandbox has been destroyed');+ }++ // Try gRPC first if available+ if (this._grpcStub) {+ return this._setEnvViaGrpc(env);+ }++ // Fall back to HTTP+ return this._setEnvViaHttp(env);+ }++ private async _setEnvViaGrpc(env: Record<string, string>): Promise<void> {+ const request: SetEnvRequest = {+ session_id: this.sessionId,+ env: env,+ };++ return new Promise((resolve, reject) => {+ this._grpcStub!.setEnv(request, (error) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new SandboxNotFoundError('Session not found'));+ } else {+ reject(error);+ }+ return;+ }+ resolve();+ });+ });+ }++ private async _setEnvViaHttp(env: Record<string, string>): Promise<void> {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/env`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ env }),+ });++ if (!response.ok) {+ if (response.status === 404) {+ throw new SandboxNotFoundError('Session not found');+ }+ throw new Error(`HTTP error: ${response.status} ${response.statusText}`);+ }+ }++ /**+ * Set the working directory for subsequent commands.+ *+ * @param cwd - The new working directory path+ * @throws {SandboxNotFoundError} If the session no longer exists+ */+ async setCwd(cwd: string): Promise<void> {+ if (this._destroyed) {+ throw new SandboxNotFoundError('Sandbox has been destroyed');+ }++ // Try gRPC first if available+ if (this._grpcStub) {+ return this._setCwdViaGrpc(cwd);+ }++ // Fall back to HTTP+ return this._setCwdViaHttp(cwd);+ }++ private async _setCwdViaGrpc(cwd: string): Promise<void> {+ const request: SetCwdRequest = {+ session_id: this.sessionId,+ cwd: cwd,+ };++ return new Promise((resolve, reject) => {+ this._grpcStub!.setCwd(request, (error) => {+ if (error) {+ if (error.code === grpc.status.NOT_FOUND) {+ reject(new SandboxNotFoundError('Session not found'));+ } else {+ reject(error);+ }+ return;+ }+ resolve();+ });+ });+ }++ private async _setCwdViaHttp(cwd: string): Promise<void> {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/cwd`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ cwd }),+ });++ if (!response.ok) {+ if (response.status === 404) {+ throw new SandboxNotFoundError('Session not found');+ }+ throw new Error(`HTTP error: ${response.status} ${response.statusText}`);+ }+ }++ /**+ * Start a long-running background process in the sandbox (e.g., a dev server).+ * Unlike `run()`, the process survives after the call returns.+ *+ * @param command - The shell command to execute (e.g., "npm run dev")+ * @param options - Background run options (port, env, cwd)+ * @returns Background process result with PID, port, and preview URL+ * @throws {SandboxNotFoundError} If the session no longer exists+ * @throws {CommandExecutionError} If the process couldn't be started+ */+ async startBackground(command: string, options: BackgroundRunOptions = {}): Promise<BackgroundRunResult> {+ if (this._destroyed) {+ throw new SandboxNotFoundError('Sandbox has been destroyed');+ }++ const { port = 5173, env = {}, cwd = '' } = options;++ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/background`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ command: ['/bin/sh', '-c', command],+ port,+ env,+ cwd: cwd || '/',+ }),+ });++ if (!response.ok) {+ if (response.status === 404) {+ throw new SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new CommandExecutionError(`Failed to start background process: ${response.status} - ${text}`);+ }++ const result = await response.json() as {+ pid: number;+ port: number;+ preview_url: string | null;+ };++ return {+ pid: result.pid,+ port: result.port,+ previewUrl: result.preview_url,+ };+ }++ /**+ * Kill all background processes in this sandbox.+ *+ * Use this before starting a new background process to avoid port conflicts.+ */+ async killBackground(): Promise<{ killed: number[]; total: number }> {+ if (this._destroyed) {+ throw new SandboxNotFoundError('Sandbox has been destroyed');+ }++ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}/background`, {+ method: 'DELETE',+ });++ if (!response.ok) {+ if (response.status === 404) {+ throw new SandboxNotFoundError('Session not found');+ }+ const text = await response.text();+ throw new CommandExecutionError(`Failed to kill background processes: ${response.status} - ${text}`);+ }++ return await response.json() as { killed: number[]; total: number };+ }++ /**+ * Destroy this sandbox session.+ *+ * After calling this method, the sandbox cannot be used anymore.+ */+ async destroy(): Promise<void> {+ if (this._destroyed) {+ return;+ }++ try {+ const response = await fetch(`${this._httpBaseUrl}/sessions/${this.sessionId}`, {+ method: 'DELETE',+ });+ // Best effort cleanup - ignore errors+ void response;+ } catch {+ // Ignore errors during cleanup+ } finally {+ this._destroyed = true;+ }+ }+}diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsnew file mode 100644index 00000000..5cddd376--- /dev/null+++ b/sdk/typescript/src/types.ts@@ -0,0 +1,127 @@+/**+ * TypeScript type definitions for OpenSandbox SDK.+ */++/**+ * Result of a command execution in the sandbox.+ */+export interface CommandResult {+ /** Standard output from the command */+ stdout: string;+ /** Standard error from the command */+ stderr: string;+ /** Exit code (0 for success) */+ exitCode: number;+ /** Signal number if process was killed by a signal */+ signal: number;+}++/**+ * Options for running a command in the sandbox.+ */+export interface RunOptions {+ /** CPU time limit in milliseconds (default: 300000) */+ timeoutMs?: number;+ /** Memory limit in KB (default: 2097152) */+ memKb?: number;+ /** Maximum file size in KB (default: 1048576) */+ fsizeKb?: number;+ /** Maximum number of open files (default: 256) */+ nofile?: number;+ /** Additional environment variables */+ env?: Record<string, string>;+ /** Working directory for the command */+ cwd?: string;+}++/**+ * Options for creating a new sandbox session.+ */+export interface CreateOptions {+ /** Initial environment variables */+ env?: Record<string, string>;+ /** Session timeout in seconds (default: 300) */+ timeout?: number;+}++/**+ * Options for the OpenSandbox client.+ */+export interface ClientOptions {+ /** gRPC port (default: 50051) */+ grpcPort?: number;+ /** Use insecure gRPC connection even for HTTPS base URL */+ grpcInsecure?: boolean;+ /** HTTP request timeout in milliseconds (default: 30000) */+ timeout?: number;+}++/**+ * File entry from directory listing.+ */+export interface FileEntry {+ /** File or directory name */+ name: string;+ /** Full path within the sandbox */+ path: string;+ /** Whether this entry is a directory */+ isDirectory: boolean;+ /** File size in bytes (0 for directories) */+ size: number;+}++/**+ * Session information returned by the server.+ */+export interface SessionInfo {+ /** Unique session ID */+ id: string;+ /** Environment variables */+ env: Record<string, string>;+ /** Current working directory */+ cwd: string;+ /** Session age in seconds */+ ageSecs: number;+ /** Idle time in seconds */+ idleSecs: number;+ /** Preview URL for web servers (if configured) */+ previewUrl: string | null;+ /** Exposed ports */+ ports: number[];+ /** Session status */+ status: 'running' | 'idle' | 'terminating';+}++/**+ * Options for starting a background process (e.g., a dev server).+ */+export interface BackgroundRunOptions {+ /** Port the process will listen on (default: 5173) */+ port?: number;+ /** Additional environment variables */+ env?: Record<string, string>;+ /** Working directory for the command */+ cwd?: string;+}++/**+ * Result of starting a background process.+ */+export interface BackgroundRunResult {+ /** PID of the background process */+ pid: number;+ /** Port the process is listening on */+ port: number;+ /** Preview URL to access the web server */+ previewUrl: string | null;+}++/**+ * Response from creating a session.+ */+export interface CreateSessionResponse {+ /** Unique session ID */+ sessionId: string;+ /** Preview URL for web servers (if configured) */+ previewUrl: string | null;+}diff --git a/sdk/typescript/tsconfig.json b/sdk/typescript/tsconfig.jsonnew file mode 100644index 00000000..6a1e5817--- /dev/null+++ b/sdk/typescript/tsconfig.json@@ -0,0 +1,20 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "CommonJS",+ "moduleResolution": "Node",+ "lib": ["ES2022"],+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist", "examples"]+}diff --git a/src/grpc_server.rs b/src/grpc_server.rsindex a53d6ad6..3c2e099b 100644--- a/src/grpc_server.rs+++ b/src/grpc_server.rs@@ -17,6 +17,7 @@ use proto::{ReadFileRequest, ReadFileResponse, RunCommandRequest, RunCommandResponse,SetCwdRequest, SetCwdResponse, SetEnvRequest, SetEnvResponse,WriteFileRequest, WriteFileResponse,+ WriteFilesRequest, WriteFilesResponse, FileError,};/// gRPC service implementation.@@ -116,6 +117,51 @@ impl SandboxService for SandboxServiceImpl {}}+ async fn write_files(+ &self,+ request: Request<WriteFilesRequest>,+ ) -> Result<Response<WriteFilesResponse>, Status> {+ let req = request.into_inner();+ info!("gRPC WriteFiles: session={}, count={}", req.session_id, req.files.len());++ // Get sandbox root+ let sandbox_root = {+ let mut sessions = self.state.sessions.write().await;+ let session = sessions+ .get_mut(&req.session_id)+ .ok_or_else(|| Status::not_found("Session not found"))?;+ session.last_used = Instant::now();+ session.sandbox_root.clone()+ };++ // Collect files for the blocking task+ let files: Vec<(String, Vec<u8>)> = req+ .files+ .into_iter()+ .map(|f| (f.path, f.content))+ .collect();++ let errors = tokio::task::spawn_blocking(move || {+ let mut errors = Vec::new();+ for (path, content) in &files {+ if let Err(e) = sandbox::write_file_in_sandbox(&sandbox_root, path, content) {+ errors.push(FileError {+ path: path.clone(),+ error: e,+ });+ }+ }+ errors+ })+ .await+ .map_err(|e| Status::internal(e.to_string()))?;++ Ok(Response::new(WriteFilesResponse {+ success: errors.is_empty(),+ errors,+ }))+ }+async fn read_file(&self,request: Request<ReadFileRequest>,diff --git a/src/http_server.rs b/src/http_server.rsindex a286ec85..359d553d 100644--- a/src/http_server.rs+++ b/src/http_server.rs@@ -1,18 +1,24 @@//! HTTP server implementation using Axum.-use crate::sandbox::{self, RunConfig, RunResult};-use crate::state::{AppState, Session, Sessions, SESSION_TTL_SECS};+use crate::sandbox::{self, RunConfig, RunResult, SandboxFileEntry};+use crate::state::{AppState, Session, SessionStatus, Sessions, SESSION_TTL_SECS};use axum::{- extract::{Path, State},- http::StatusCode,+ body::Body,+ extract::{Host, Path, Query, State},+ extract::ws::{WebSocket, WebSocketUpgrade, Message as AxumWsMsg},+ http::{header, Request, StatusCode, Uri},+ response::{IntoResponse, Response},routing::{delete, get, post},Json, Router,};+use base64::{engine::general_purpose::STANDARD as BASE64, Engine};+use futures_util::{SinkExt, StreamExt};use serde::{Deserialize, Serialize};use std::collections::HashMap;use std::net::SocketAddr;use std::time::{Duration, Instant};use tokio::time::interval;+use tokio_tungstenite::tungstenite::Message as TungsteniteMsg;use tracing::info;// Request/Response types@@ -25,6 +31,7 @@ struct CreateSessionRequest {#[derive(Serialize)]struct CreateSessionResponse {session_id: String,+ preview_url: Option<String>,}#[derive(Deserialize)]@@ -57,6 +64,92 @@ struct SessionInfo {cwd: String,age_secs: u64,idle_secs: u64,+ preview_url: Option<String>,+ ports: Vec<u16>,+ status: String,+}++// File operation request/response types+#[derive(Deserialize)]+struct WriteFileRequest {+ path: String,+ content: String, // base64 encoded+}++#[derive(Serialize)]+struct WriteFileResponse {+ success: bool,+}++#[derive(Deserialize)]+struct WriteFilesRequest {+ files: Vec<WriteFileEntry>,+}++#[derive(Deserialize)]+struct WriteFileEntry {+ path: String,+ content: String, // base64 encoded+}++#[derive(Serialize)]+struct WriteFilesResponse {+ success: bool,+ errors: Vec<WriteFileError>,+}++#[derive(Serialize)]+struct WriteFileError {+ path: String,+ error: String,+}++#[derive(Deserialize)]+struct ReadFileQuery {+ path: String,+}++#[derive(Serialize)]+struct ReadFileResponse {+ content: String, // base64 encoded+}++#[derive(Deserialize)]+struct ListFilesQuery {+ path: String,+}++#[derive(Serialize)]+struct FileEntry {+ name: String,+ path: String,+ is_directory: bool,+ size: u64,+}++#[derive(Serialize)]+struct ListFilesResponse {+ files: Vec<FileEntry>,+}++#[derive(Deserialize)]+struct BackgroundRunRequest {+ command: Vec<String>,+ #[serde(default = "default_port")]+ port: u16,+ #[serde(default)]+ env: HashMap<String, String>,+ #[serde(default = "default_cwd")]+ cwd: String,+}++fn default_port() -> u16 { 5173 }++#[derive(Serialize)]+struct BackgroundRunResponse {+ pid: u32,+ port: u16,+ preview_url: Option<String>,}#[derive(Deserialize)]@@ -81,6 +174,8 @@ pub async fn run_server(port: u16, state: AppState) {}});+ let preview_domain = state.preview_domain.clone();+let app = Router::new()// Session management.route("/sessions", post(create_session))@@ -88,16 +183,30 @@ pub async fn run_server(port: u16, state: AppState) {.route("/sessions/:id", get(get_session)).route("/sessions/:id", delete(delete_session)).route("/sessions/:id/run", post(run_in_session))+ .route("/sessions/:id/background", post(run_background))+ .route("/sessions/:id/background", delete(kill_background)).route("/sessions/:id/env", post(set_env)).route("/sessions/:id/cwd", post(set_cwd))+ // File operations+ .route("/sessions/:id/files/write", post(write_file))+ .route("/sessions/:id/files/write-bulk", post(write_files_bulk))+ .route("/sessions/:id/files/read", get(read_file))+ .route("/sessions/:id/files/list", get(list_files))+ // Background diagnostics+ .route("/sessions/:id/background/status", get(background_status))// Stateless run.route("/run", post(run_oneshot))// Health check.route("/health", get(health))+ // Preview proxy: catches all unmatched requests and checks Host header+ .fallback(preview_proxy).with_state(state);let addr = SocketAddr::from(([0, 0, 0, 0], port));info!("Starting HTTP server on {}", addr);+ if let Some(ref domain) = preview_domain {+ info!("Preview domain: {}", domain);+ }let listener = tokio::net::TcpListener::bind(addr).await.unwrap();axum::serve(listener, app).await.unwrap();@@ -121,6 +230,12 @@ async fn create_session(.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;+ // Generate preview URL if preview_domain is configured+ let preview_url = state+ .preview_domain+ .as_ref()+ .map(|domain| format!("https://{}.{}", session_id, domain));+let session = Session {id: session_id.clone(),sandbox_root,@@ -128,12 +243,19 @@ async fn create_session(cwd: "/".to_string(),created_at: Instant::now(),last_used: Instant::now(),+ preview_url: preview_url.clone(),+ ports: Vec::new(),+ status: SessionStatus::Running,+ background_pids: Vec::new(),};state.sessions.write().await.insert(session_id.clone(), session);info!("Created session: {}", session_id);- Ok(Json(CreateSessionResponse { session_id }))+ Ok(Json(CreateSessionResponse {+ session_id,+ preview_url,+ }))}async fn list_sessions(@@ -149,6 +271,9 @@ async fn list_sessions(cwd: s.cwd.clone(),age_secs: now.duration_since(s.created_at).as_secs(),idle_secs: now.duration_since(s.last_used).as_secs(),+ preview_url: s.preview_url.clone(),+ ports: s.ports.clone(),+ status: format!("{:?}", s.status).to_lowercase(),}).collect();Json(list)@@ -167,6 +292,9 @@ async fn get_session(cwd: session.cwd.clone(),age_secs: now.duration_since(session.created_at).as_secs(),idle_secs: now.duration_since(session.last_used).as_secs(),+ preview_url: session.preview_url.clone(),+ ports: session.ports.clone(),+ status: format!("{:?}", session.status).to_lowercase(),}))}@@ -177,7 +305,15 @@ async fn delete_session(let mut sessions = state.sessions.write().await;if let Some(session) = sessions.remove(&id) {let sandbox_root = session.sandbox_root;+ let pids = session.background_pids;tokio::task::spawn_blocking(move || {+ // Kill background processes first+ for pid in pids {+ let _ = nix::sys::signal::kill(+ nix::unistd::Pid::from_raw(pid as i32),+ nix::sys::signal::Signal::SIGKILL,+ );+ }sandbox::destroy_session_sandbox(&sandbox_root);});info!("Deleted session: {}", id);@@ -288,9 +424,502 @@ async fn cleanup_expired_sessions(sessions: &Sessions) {if let Some(session) = sessions.remove(&id) {info!("Cleaning up expired session: {}", id);let sandbox_root = session.sandbox_root;+ let pids = session.background_pids;tokio::task::spawn_blocking(move || {+ for pid in pids {+ let _ = nix::sys::signal::kill(+ nix::unistd::Pid::from_raw(pid as i32),+ nix::sys::signal::Signal::SIGKILL,+ );+ }sandbox::destroy_session_sandbox(&sandbox_root);});}}}++// File operation handlers++async fn write_file(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Json(req): Json<WriteFileRequest>,+) -> Result<Json<WriteFileResponse>, (StatusCode, String)> {+ let sandbox_root = {+ let mut sessions = state.sessions.write().await;+ let session = sessions+ .get_mut(&id)+ .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;+ session.last_used = Instant::now();+ session.sandbox_root.clone()+ };++ // Decode base64 content+ let content = BASE64+ .decode(&req.content)+ .map_err(|e| (StatusCode::BAD_REQUEST, format!("Invalid base64: {}", e)))?;++ tokio::task::spawn_blocking(move || {+ sandbox::write_file_in_sandbox(&sandbox_root, &req.path, &content)+ })+ .await+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;++ Ok(Json(WriteFileResponse { success: true }))+}++async fn write_files_bulk(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Json(req): Json<WriteFilesRequest>,+) -> Result<Json<WriteFilesResponse>, (StatusCode, String)> {+ let sandbox_root = {+ let mut sessions = state.sessions.write().await;+ let session = sessions+ .get_mut(&id)+ .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;+ session.last_used = Instant::now();+ session.sandbox_root.clone()+ };++ // Decode all files from base64 first+ let mut decoded_files: Vec<(String, Vec<u8>)> = Vec::with_capacity(req.files.len());+ for entry in &req.files {+ let content = BASE64+ .decode(&entry.content)+ .map_err(|e| (StatusCode::BAD_REQUEST, format!("Invalid base64 for {}: {}", entry.path, e)))?;+ decoded_files.push((entry.path.clone(), content));+ }++ // Write all files in a single blocking task+ let errors = tokio::task::spawn_blocking(move || {+ let mut errors = Vec::new();+ for (path, content) in &decoded_files {+ if let Err(e) = sandbox::write_file_in_sandbox(&sandbox_root, path, content) {+ errors.push(WriteFileError {+ path: path.clone(),+ error: e,+ });+ }+ }+ errors+ })+ .await+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;++ Ok(Json(WriteFilesResponse {+ success: errors.is_empty(),+ errors,+ }))+}++async fn read_file(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Query(query): Query<ReadFileQuery>,+) -> Result<Json<ReadFileResponse>, (StatusCode, String)> {+ let sandbox_root = {+ let mut sessions = state.sessions.write().await;+ let session = sessions+ .get_mut(&id)+ .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;+ session.last_used = Instant::now();+ session.sandbox_root.clone()+ };++ let path = query.path.clone();+ let content = tokio::task::spawn_blocking(move || {+ sandbox::read_file_in_sandbox(&sandbox_root, &path)+ })+ .await+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?+ .map_err(|e| (StatusCode::NOT_FOUND, e))?;++ Ok(Json(ReadFileResponse {+ content: BASE64.encode(&content),+ }))+}++async fn list_files(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Query(query): Query<ListFilesQuery>,+) -> Result<Json<ListFilesResponse>, (StatusCode, String)> {+ let sandbox_root = {+ let mut sessions = state.sessions.write().await;+ let session = sessions+ .get_mut(&id)+ .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;+ session.last_used = Instant::now();+ session.sandbox_root.clone()+ };++ let path = query.path.clone();+ let entries = tokio::task::spawn_blocking(move || {+ sandbox::list_files_in_sandbox(&sandbox_root, &path)+ })+ .await+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?+ .map_err(|e| (StatusCode::NOT_FOUND, e))?;++ let files: Vec<FileEntry> = entries+ .into_iter()+ .map(|e| FileEntry {+ name: e.name,+ path: e.path,+ is_directory: e.is_directory,+ size: e.size,+ })+ .collect();++ Ok(Json(ListFilesResponse { files }))+}++// Background process handler++async fn run_background(+ State(state): State<AppState>,+ Path(id): Path<String>,+ Json(req): Json<BackgroundRunRequest>,+) -> Result<Json<BackgroundRunResponse>, (StatusCode, String)> {+ let (sandbox_root, mut env, cwd, preview_url) = {+ let mut sessions = state.sessions.write().await;+ let session = sessions+ .get_mut(&id)+ .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;+ session.last_used = Instant::now();+ (+ session.sandbox_root.clone(),+ session.env.clone(),+ session.cwd.clone(),+ session.preview_url.clone(),+ )+ };++ env.extend(req.env);+ let cwd = if req.cwd != "/" { req.cwd } else { cwd };++ // Auto-assign a unique port if client sends 0, otherwise use requested port+ let port = if req.port == 0 {+ state.allocate_port()+ } else {+ req.port+ };++ // Inject port as env var so vite/dev servers can use it+ env.insert("VITE_PORT".to_string(), port.to_string());+ env.insert("PORT".to_string(), port.to_string());++ info!("Assigning port {} for background process in session {}", port, id);++ let config = RunConfig {+ command: req.command,+ time_ms: 0,+ mem_kb: 0,+ fsize_kb: 0,+ nofile: 0,+ env,+ cwd,+ };++ let pid = tokio::task::spawn_blocking(move || {+ sandbox::run_background_in_session(&sandbox_root, &config)+ })+ .await+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;++ // Track the background process and port+ {+ let mut sessions = state.sessions.write().await;+ if let Some(session) = sessions.get_mut(&id) {+ session.background_pids.push(pid);+ if !session.ports.contains(&port) {+ session.ports.push(port);+ }+ }+ }++ info!("Started background process pid={} port={} session={}", pid, port, id);++ Ok(Json(BackgroundRunResponse {+ pid,+ port,+ preview_url,+ }))+}++// Kill all background processes for a session++async fn kill_background(+ State(state): State<AppState>,+ Path(id): Path<String>,+) -> Result<Json<serde_json::Value>, (StatusCode, String)> {+ let pids = {+ let mut sessions = state.sessions.write().await;+ let session = sessions+ .get_mut(&id)+ .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;+ session.last_used = Instant::now();+ let pids = session.background_pids.clone();+ session.background_pids.clear();+ session.ports.clear();+ pids+ };++ let killed: Vec<u32> = pids+ .iter()+ .filter(|&&pid| {+ let result = nix::sys::signal::kill(+ nix::unistd::Pid::from_raw(pid as i32),+ nix::sys::signal::Signal::SIGKILL,+ );+ result.is_ok()+ })+ .copied()+ .collect();++ info!("Killed {} background processes for session {}: {:?}", killed.len(), id, killed);++ Ok(Json(serde_json::json!({+ "killed": killed,+ "total": pids.len(),+ })))+}++// Background diagnostics handler++#[derive(Serialize)]+struct BackgroundStatusResponse {+ pids: Vec<BackgroundPidStatus>,+ log: String,+}++#[derive(Serialize)]+struct BackgroundPidStatus {+ pid: u32,+ alive: bool,+}++async fn background_status(+ State(state): State<AppState>,+ Path(id): Path<String>,+) -> Result<Json<BackgroundStatusResponse>, (StatusCode, String)> {+ let (sandbox_root, pids) = {+ let sessions = state.sessions.read().await;+ let session = sessions+ .get(&id)+ .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;+ (session.sandbox_root.clone(), session.background_pids.clone())+ };++ let (pid_statuses, log) = tokio::task::spawn_blocking(move || {+ let statuses: Vec<BackgroundPidStatus> = pids+ .iter()+ .map(|&pid| BackgroundPidStatus {+ pid,+ alive: sandbox::is_process_alive(pid),+ })+ .collect();+ let log = sandbox::read_background_log(&sandbox_root).unwrap_or_default();+ (statuses, log)+ })+ .await+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;++ Ok(Json(BackgroundStatusResponse {+ pids: pid_statuses,+ log,+ }))+}++// Preview proxy handler (HTTP + WebSocket)++async fn preview_proxy(+ State(state): State<AppState>,+ Host(host): Host,+ ws: Option<WebSocketUpgrade>,+ req: Request<Body>,+) -> Response {+ let preview_domain = match &state.preview_domain {+ Some(d) => d.clone(),+ None => {+ return (StatusCode::NOT_FOUND, "Not found").into_response();+ }+ };++ // Parse session ID from host: {session-id}.{preview_domain}+ let suffix = format!(".{}", preview_domain);+ let session_id = match host.strip_suffix(&suffix) {+ Some(id) => id.to_string(),+ None => {+ return (StatusCode::NOT_FOUND, "Not found").into_response();+ }+ };++ // Look up session and find the port+ let port = {+ let mut sessions = state.sessions.write().await;+ let session = match sessions.get_mut(&session_id) {+ Some(s) => s,+ None => {+ return (StatusCode::NOT_FOUND, format!("Session {} not found", session_id))+ .into_response();+ }+ };+ session.last_used = Instant::now();+ // Use first registered port, default to 5173+ session.ports.first().copied().unwrap_or(5173)+ };++ // Handle WebSocket upgrade+ if let Some(ws) = ws {+ let path = req.uri().path().to_string();+ let query = req.uri().query().map(|q| format!("?{}", q)).unwrap_or_default();+ let ws_url = format!("ws://127.0.0.1:{}{}{}", port, path, query);+ info!("WebSocket proxy: {} -> {}", host, ws_url);+ return ws.on_upgrade(move |socket| ws_proxy(socket, ws_url));+ }++ // Regular HTTP proxy+ let path = req.uri().path();+ let query = req.uri().query().map(|q| format!("?{}", q)).unwrap_or_default();+ let target_url = format!("http://127.0.0.1:{}{}{}", port, path, query);++ info!("Preview proxy: {} -> {}", host, target_url);++ let client = reqwest::Client::new();+ let method = match req.method().as_str() {+ "GET" => reqwest::Method::GET,+ "POST" => reqwest::Method::POST,+ "PUT" => reqwest::Method::PUT,+ "DELETE" => reqwest::Method::DELETE,+ "PATCH" => reqwest::Method::PATCH,+ "HEAD" => reqwest::Method::HEAD,+ "OPTIONS" => reqwest::Method::OPTIONS,+ _ => reqwest::Method::GET,+ };++ let mut proxy_req = client.request(method, &target_url);++ // Forward relevant headers+ for (name, value) in req.headers() {+ if name != header::HOST {+ if let Ok(v) = value.to_str() {+ proxy_req = proxy_req.header(name.as_str(), v);+ }+ }+ }++ // Forward body+ let body_bytes = match axum::body::to_bytes(req.into_body(), 10 * 1024 * 1024).await {+ Ok(b) => b,+ Err(e) => {+ return (StatusCode::BAD_REQUEST, format!("Failed to read body: {}", e))+ .into_response();+ }+ };+ if !body_bytes.is_empty() {+ proxy_req = proxy_req.body(body_bytes.to_vec());+ }++ // Execute the proxied request+ match proxy_req.send().await {+ Ok(proxy_resp) => {+ let status = StatusCode::from_u16(proxy_resp.status().as_u16())+ .unwrap_or(StatusCode::BAD_GATEWAY);+ let mut response = Response::builder().status(status);++ // Forward response headers+ for (name, value) in proxy_resp.headers() {+ response = response.header(name.as_str(), value.as_bytes());+ }++ match proxy_resp.bytes().await {+ Ok(body) => response+ .body(Body::from(body))+ .unwrap_or_else(|_| (StatusCode::BAD_GATEWAY, "Proxy error").into_response()),+ Err(e) => (StatusCode::BAD_GATEWAY, format!("Failed to read response: {}", e))+ .into_response(),+ }+ }+ Err(e) => {+ info!("Preview proxy error: {}", e);+ (+ StatusCode::BAD_GATEWAY,+ format!("Could not connect to sandbox web server on port {}: {}", port, e),+ )+ .into_response()+ }+ }+}++/// Bidirectional WebSocket proxy between client and backend (e.g., Vite HMR).+async fn ws_proxy(client_ws: WebSocket, backend_url: String) {+ // Connect to backend WebSocket+ let backend_result = tokio_tungstenite::connect_async(&backend_url).await;+ let (backend_ws, _) = match backend_result {+ Ok(conn) => conn,+ Err(e) => {+ info!("WebSocket backend connection failed: {} -> {}", backend_url, e);+ return;+ }+ };++ info!("WebSocket proxy connected: {}", backend_url);++ let (mut client_tx, mut client_rx) = client_ws.split();+ let (mut backend_tx, mut backend_rx) = backend_ws.split();++ // Relay: client -> backend+ let c2b = async move {+ while let Some(msg) = client_rx.next().await {+ match msg {+ Ok(axum_msg) => {+ let tung_msg = match axum_msg {+ AxumWsMsg::Text(t) => TungsteniteMsg::Text(t.to_string()),+ AxumWsMsg::Binary(b) => TungsteniteMsg::Binary(b.to_vec()),+ AxumWsMsg::Ping(p) => TungsteniteMsg::Ping(p.to_vec()),+ AxumWsMsg::Pong(p) => TungsteniteMsg::Pong(p.to_vec()),+ AxumWsMsg::Close(_) => return,+ };+ if backend_tx.send(tung_msg).await.is_err() {+ return;+ }+ }+ Err(_) => return,+ }+ }+ };++ // Relay: backend -> client+ let b2c = async move {+ while let Some(msg) = backend_rx.next().await {+ match msg {+ Ok(tung_msg) => {+ let axum_msg = match tung_msg {+ TungsteniteMsg::Text(t) => AxumWsMsg::Text(t.to_string()),+ TungsteniteMsg::Binary(b) => AxumWsMsg::Binary(b.into()),+ TungsteniteMsg::Ping(p) => AxumWsMsg::Ping(p.into()),+ TungsteniteMsg::Pong(p) => AxumWsMsg::Pong(p.into()),+ TungsteniteMsg::Close(_) => return,+ _ => continue,+ };+ if client_tx.send(axum_msg).await.is_err() {+ return;+ }+ }+ Err(_) => return,+ }+ }+ };++ // Run both directions concurrently; when one ends, drop the other+ tokio::select! {+ _ = c2b => {},+ _ = b2c => {},+ }++ info!("WebSocket proxy closed: {}", backend_url);+}diff --git a/src/main.rs b/src/main.rsindex b291e186..9629998b 100644--- a/src/main.rs+++ b/src/main.rs@@ -66,6 +66,11 @@ enum Commands {/// gRPC port to listen on#[arg(long, default_value = "50051")]grpc_port: u16,++ /// Preview domain for sandbox web servers (e.g., "preview.opensandbox.fly.dev")+ /// When set, sessions will get preview URLs like https://{session-id}.preview.opensandbox.fly.dev+ #[arg(long)]+ preview_domain: Option<String>,},}@@ -85,9 +90,12 @@ async fn main() {}match args.command {- Some(Commands::Serve { port, grpc_port }) => {- // Create shared state- let state = state::AppState::new();+ Some(Commands::Serve { port, grpc_port, preview_domain }) => {+ // CLI flag takes priority, then fall back to PREVIEW_DOMAIN env var+ let preview_domain = preview_domain.or_else(|| std::env::var("PREVIEW_DOMAIN").ok());++ // Create shared state with optional preview domain+ let state = state::AppState::with_preview_domain(preview_domain);// Spawn HTTP serverlet http_state = state.clone();diff --git a/src/sandbox.rs b/src/sandbox.rsindex 09266fa4..a170dd2e 100644--- a/src/sandbox.rs+++ b/src/sandbox.rs@@ -55,6 +55,123 @@ pub fn run_in_session(sandbox_root: &Path, config: &RunConfig) -> Result<RunResurun_in_sandbox(sandbox_root, config)}+/// Start a long-running background process in the sandbox.+/// Unlike `run_in_session`, this does NOT use CLONE_NEWPID so the process+/// survives after the call returns. Returns the PID of the background process.+pub fn run_background_in_session(sandbox_root: &Path, config: &RunConfig) -> Result<u32, String> {+ use std::fs::OpenOptions;+ use std::os::unix::process::CommandExt;+ use std::process::Command;++ info!(command = ?config.command, "Starting background process in {:?}", sandbox_root);++ // Build environment+ let mut env_vars: Vec<(String, String)> = config+ .env+ .iter()+ .map(|(k, v)| (k.clone(), v.clone()))+ .collect();+ env_vars.push(("PATH".to_string(), "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".to_string()));+ env_vars.push(("HOME".to_string(), "/home".to_string()));++ let cwd = if config.cwd.is_empty() || config.cwd == "/" {+ "/".to_string()+ } else {+ config.cwd.clone()+ };++ // Open a log file in sandbox's /tmp (host path, before chroot) for debugging+ let log_path = sandbox_root.join("tmp/background.log");+ let log_file = OpenOptions::new()+ .create(true)+ .write(true)+ .truncate(true)+ .open(&log_path)+ .map_err(|e| format!("open background log {}: {}", log_path.display(), e))?;+ let log_file_err = log_file+ .try_clone()+ .map_err(|e| format!("clone log file: {}", e))?;++ // Use pre_exec to chroot into the sandbox after fork but before exec.+ // This avoids needing the chroot binary (which may not be in PATH) and+ // avoids CLONE_NEWPID (which kills child processes when parent exits).+ let sandbox_root_owned = sandbox_root.to_path_buf();+ let cwd_for_preexec = cwd.clone();++ // Execute the command array directly instead of wrapping in sh -c.+ // The client may already send ["sh", "-c", "npm run dev"], so wrapping+ // again would break argument parsing (sh -c npm treats "run" as $0).+ // pre_exec handles chroot and chdir, so no need for a shell wrapper.+ if config.command.is_empty() {+ return Err("empty command".to_string());+ }+ let mut cmd = Command::new(&config.command[0]);+ for arg in &config.command[1..] {+ cmd.arg(arg);+ }+ cmd.env_clear()+ .envs(env_vars)+ .stdout(log_file)+ .stderr(log_file_err)+ .stdin(std::process::Stdio::null());++ unsafe {+ cmd.pre_exec(move || {+ // chroot into sandbox filesystem+ nix::unistd::chroot(&sandbox_root_owned)+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("chroot: {}", e)))?;+ // chdir to working directory+ nix::unistd::chdir(cwd_for_preexec.as_str())+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("chdir: {}", e)))?;+ Ok(())+ });+ }++ let child = cmd.spawn()+ .map_err(|e| format!("spawn background: {}", e))?;++ let pid = child.id();+ info!(pid = pid, log = %log_path.display(), "Background process started successfully");++ // Wait briefly and check if the process is still alive+ std::thread::sleep(std::time::Duration::from_millis(500));+ let alive = is_process_alive(pid);+ info!(pid = pid, alive = alive, "Background process status check");++ if !alive {+ // Process died immediately - read the log to see why+ let log_content = fs::read_to_string(&log_path).unwrap_or_default();+ let truncated = if log_content.len() > 2000 {+ &log_content[log_content.len() - 2000..]+ } else {+ &log_content+ };+ info!(pid = pid, "Background process died immediately. Log:\n{}", truncated);+ return Err(format!(+ "Background process (pid {}) died immediately. Log output:\n{}",+ pid, truncated+ ));+ }++ Ok(pid)+}++/// Check if a process is still alive.+pub fn is_process_alive(pid: u32) -> bool {+ // kill with signal 0 checks if process exists without sending a signal+ nix::sys::signal::kill(+ nix::unistd::Pid::from_raw(pid as i32),+ None, // signal 0+ )+ .is_ok()+}++/// Read the background process log file for a session.+pub fn read_background_log(sandbox_root: &Path) -> Result<String, String> {+ let log_path = sandbox_root.join("tmp/background.log");+ fs::read_to_string(&log_path).map_err(|e| format!("read log: {}", e))+}+/// Create a new session sandbox directory.pub fn create_session_sandbox(session_id: &str) -> Result<PathBuf, String> {let sandbox_root = PathBuf::from(format!("/tmp/sandbox-{}", session_id));@@ -106,6 +223,62 @@ pub fn read_file_in_sandbox(sandbox_root: &Path, path: &str) -> Result<Vec<u8>,fs::read(&full_path).map_err(|e| format!("read file: {}", e))}+/// Entry in a directory listing.+#[derive(Debug, Clone)]+pub struct SandboxFileEntry {+ pub name: String,+ pub path: String,+ pub is_directory: bool,+ pub size: u64,+}++/// List files in a directory within the sandbox filesystem.+pub fn list_files_in_sandbox(sandbox_root: &Path, path: &str) -> Result<Vec<SandboxFileEntry>, String> {+ // Normalize the path to be relative to sandbox root+ let normalized_path = if path.starts_with('/') {+ path.trim_start_matches('/')+ } else {+ path+ };++ let full_path = if normalized_path.is_empty() {+ sandbox_root.to_path_buf()+ } else {+ sandbox_root.join(normalized_path)+ };++ let entries = fs::read_dir(&full_path)+ .map_err(|e| format!("read dir {}: {}", full_path.display(), e))?;++ let mut result = Vec::new();+ for entry in entries {+ let entry = entry.map_err(|e| format!("read entry: {}", e))?;+ let metadata = entry.metadata().map_err(|e| format!("metadata: {}", e))?;+ let name = entry.file_name().to_string_lossy().to_string();++ // Compute the path as it appears inside the sandbox (with leading /)+ let entry_path = if normalized_path.is_empty() {+ format!("/{}", name)+ } else if path.starts_with('/') {+ format!("{}/{}", path.trim_end_matches('/'), name)+ } else {+ format!("/{}/{}", normalized_path.trim_end_matches('/'), name)+ };++ result.push(SandboxFileEntry {+ name,+ path: entry_path,+ is_directory: metadata.is_dir(),+ size: metadata.len(),+ });+ }++ // Sort by name for consistent ordering+ result.sort_by(|a, b| a.name.cmp(&b.name));++ Ok(result)+}+fn setup_sandbox_dir(sandbox_root: &Path) -> Result<(), String> {// Clean up if existsif sandbox_root.exists() {diff --git a/src/state.rs b/src/state.rsindex 31bfd66f..b2190647 100644--- a/src/state.rs+++ b/src/state.rs@@ -1,14 +1,28 @@//! Shared application state and session types.+use serde::Serialize;use std::collections::HashMap;use std::path::PathBuf;+use std::sync::atomic::{AtomicU16, Ordering};use std::sync::Arc;use std::time::Instant;use tokio::sync::RwLock;+/// Starting port for auto-assignment (each session gets a unique port)+const PORT_RANGE_START: u16 = 10000;+/// Session TTL in seconds (5 minutes)pub const SESSION_TTL_SECS: u64 = 300;+/// Status of a sandbox session.+#[derive(Debug, Clone, Copy, Serialize, PartialEq)]+#[serde(rename_all = "lowercase")]+pub enum SessionStatus {+ Running,+ Idle,+ Terminating,+}+/// A sandbox session with persistent environment and working directory.#[derive(Debug)]pub struct Session {@@ -18,6 +32,14 @@ pub struct Session {pub cwd: String,pub created_at: Instant,pub last_used: Instant,+ /// Preview URL for accessing web servers in the sandbox+ pub preview_url: Option<String>,+ /// Exposed ports+ pub ports: Vec<u16>,+ /// Current session status+ pub status: SessionStatus,+ /// PIDs of background processes (e.g., dev servers)+ pub background_pids: Vec<u32>,}/// Thread-safe session storage.@@ -27,14 +49,33 @@ pub type Sessions = Arc<RwLock<HashMap<String, Session>>>;#[derive(Clone)]pub struct AppState {pub sessions: Sessions,+ /// Preview domain for generating preview URLs (e.g., "preview.opensandbox.fly.dev")+ pub preview_domain: Option<String>,+ /// Port counter for auto-assigning unique ports to background processes+ pub next_port: Arc<AtomicU16>,}impl AppState {pub fn new() -> Self {Self {sessions: Arc::new(RwLock::new(HashMap::new())),+ preview_domain: None,+ next_port: Arc::new(AtomicU16::new(PORT_RANGE_START)),+ }+ }++ pub fn with_preview_domain(preview_domain: Option<String>) -> Self {+ Self {+ sessions: Arc::new(RwLock::new(HashMap::new())),+ preview_domain,+ next_port: Arc::new(AtomicU16::new(PORT_RANGE_START)),}}++ /// Allocate the next available port for a background process.+ pub fn allocate_port(&self) -> u16 {+ self.next_port.fetch_add(1, Ordering::Relaxed)+ }}impl Default for AppState {