@opencoredev/sandbox-sdk 1.0.0-beta.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/README.md +70 -63
- package/dist/ai.js +1 -1
- package/dist/chunk-23tjmd39.js +8 -0
- package/dist/chunk-2ts3evzh.js +2 -0
- package/dist/chunk-83avbjns.js +2 -0
- package/dist/chunk-8786zrns.js +2 -0
- package/dist/chunk-8wq767xb.js +17 -0
- package/dist/chunk-9w9rddra.js +2 -0
- package/dist/chunk-bd481sb7.js +2 -0
- package/dist/chunk-ckym4cht.js +23 -0
- package/dist/chunk-gw3n7sx7.js +5 -0
- package/dist/chunk-hgrwyjrb.js +2 -0
- package/dist/chunk-hzbssbep.js +31 -0
- package/dist/chunk-k60b4r27.js +2 -0
- package/dist/chunk-kk1hw8wa.js +1 -0
- package/dist/chunk-nw845a93.js +27 -0
- package/dist/chunk-q5vqajhg.js +2 -0
- package/dist/chunk-vy1j4r8f.js +2 -0
- package/dist/chunk-x681p5d2.js +68 -0
- package/dist/chunk-xgxfy2n8.js +4 -0
- package/dist/core/process-records.d.ts +25 -0
- package/dist/errors.d.ts +67 -1
- package/dist/files.d.ts +11 -4
- package/dist/git.d.ts +1 -1
- package/dist/http.d.ts +225 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/keys.d.ts +5 -0
- package/dist/mastra.d.ts +1 -1
- package/dist/mastra.js +1 -1
- package/dist/memory.d.ts +4 -1
- package/dist/memory.js +11 -9
- package/dist/native.d.ts +127 -0
- package/dist/openai.js +1 -1
- package/dist/peer.d.ts +9 -0
- package/dist/provider.d.ts +38 -5
- package/dist/provider.js +1 -0
- package/dist/providers/agentos/errors.d.ts +3 -2
- package/dist/providers/agentos/index.d.ts +2 -9
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/agentos/provider.d.ts +50 -0
- package/dist/providers/boat/index.d.ts +52 -9
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boat-api/exec.d.ts +15 -2
- package/dist/providers/boat-api/follow.d.ts +24 -0
- package/dist/providers/boat-api/index.d.ts +45 -7
- package/dist/providers/boat-api/transport.d.ts +77 -0
- package/dist/providers/boxd/errors.d.ts +2 -2
- package/dist/providers/boxd/execute.d.ts +2 -2
- package/dist/providers/boxd/index.d.ts +2 -22
- package/dist/providers/boxd/index.js +24 -4
- package/dist/providers/boxd/provider.d.ts +74 -0
- package/dist/providers/boxd/transfers.d.ts +9 -0
- package/dist/providers/daytona/api.d.ts +124 -0
- package/dist/providers/daytona/buffered.d.ts +2 -2
- package/dist/providers/daytona/errors.d.ts +18 -2
- package/dist/providers/daytona/exec.d.ts +3 -3
- package/dist/providers/daytona/index.d.ts +53 -4
- package/dist/providers/daytona/index.js +18 -10
- package/dist/providers/daytona/multipart.d.ts +25 -0
- package/dist/providers/e2b/envd.d.ts +113 -0
- package/dist/providers/e2b/errors.d.ts +20 -3
- package/dist/providers/e2b/index.d.ts +41 -3
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/freestyle/client.d.ts +87 -0
- package/dist/providers/freestyle/deadline.d.ts +3 -2
- package/dist/providers/freestyle/errors.d.ts +14 -1
- package/dist/providers/freestyle/execute.d.ts +3 -7
- package/dist/providers/freestyle/index.d.ts +28 -2
- package/dist/providers/freestyle/index.js +5 -33
- package/dist/providers/local/docker.d.ts +10 -6
- package/dist/providers/local/index.d.ts +29 -0
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/railway/errors.d.ts +7 -1
- package/dist/providers/railway/index.d.ts +2 -23
- package/dist/providers/railway/index.js +1 -1
- package/dist/providers/railway/provider.d.ts +53 -0
- package/dist/providers/sandboxer/index.d.ts +15 -8
- package/dist/providers/sandboxer/index.js +1 -1
- package/dist/providers/superserve/errors.d.ts +2 -2
- package/dist/providers/superserve/execute.d.ts +3 -8
- package/dist/providers/superserve/index.d.ts +32 -3
- package/dist/providers/superserve/index.js +5 -37
- package/dist/providers/superserve/routes.d.ts +80 -0
- package/dist/providers/superserve/session.d.ts +33 -0
- package/dist/providers/tenki/deadline.d.ts +1 -1
- package/dist/providers/tenki/errors.d.ts +3 -3
- package/dist/providers/tenki/exec.d.ts +1 -1
- package/dist/providers/tenki/files.d.ts +1 -1
- package/dist/providers/tenki/index.d.ts +2 -27
- package/dist/providers/tenki/index.js +19 -16
- package/dist/providers/tenki/provider.d.ts +95 -0
- package/dist/providers/tenki/ready.d.ts +1 -1
- package/dist/providers/tenki/records.d.ts +16 -0
- package/dist/providers/tenki/stream.d.ts +2 -2
- package/dist/providers/upstash/buffered.d.ts +1 -1
- package/dist/providers/upstash/errors.d.ts +1 -1
- package/dist/providers/upstash/exec.d.ts +2 -2
- package/dist/providers/upstash/files.d.ts +1 -1
- package/dist/providers/upstash/index.d.ts +2 -34
- package/dist/providers/upstash/index.js +12 -18
- package/dist/providers/upstash/provider.d.ts +81 -0
- package/dist/providers/vercel/errors.d.ts +3 -1
- package/dist/providers/vercel/index.d.ts +13 -5
- package/dist/providers/vercel/index.js +1 -1
- package/dist/providers/vercel/provider.d.ts +50 -2
- package/dist/providers/vercel/transport.d.ts +7 -4
- package/dist/run.d.ts +6 -4
- package/dist/shared/deadline.d.ts +12 -0
- package/dist/shared/guest.d.ts +18 -0
- package/dist/shared/json.d.ts +11 -0
- package/dist/shared/metadata.d.ts +19 -0
- package/dist/shared/narrow.d.ts +8 -0
- package/dist/shared/native-error.d.ts +42 -0
- package/dist/shared/paged-exec.d.ts +22 -0
- package/dist/shared/shell.d.ts +2 -0
- package/dist/{providers/freestyle → shared}/wire.d.ts +1 -1
- package/dist/shell/process-records.d.ts +44 -0
- package/dist/streams.d.ts +72 -0
- package/dist/testing.d.ts +12 -2
- package/dist/testing.js +7 -4
- package/dist/tool-security.d.ts +4 -4
- package/dist/tools.d.ts +3 -2
- package/dist/tools.js +1 -1
- package/dist/types.d.ts +14 -6
- package/package.json +29 -46
- package/dist/chunk-59t3rqja.js +0 -2
- package/dist/chunk-cwx6cc31.js +0 -2
- package/dist/chunk-exv1kf89.js +0 -60
- package/dist/chunk-gc8zdxyb.js +0 -2
- package/dist/chunk-hjzhc3qg.js +0 -40
- package/dist/chunk-md6fmprc.js +0 -1
- package/dist/chunk-t5vr9nd8.js +0 -8
- package/dist/chunk-v6y7eqxw.js +0 -27
- package/dist/chunk-yed8mvs7.js +0 -2
- package/dist/chunk-yrsb6hws.js +0 -5
- package/dist/chunk-z9rjzn28.js +0 -2
- package/dist/providers/boxd/guest.d.ts +0 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o}from"../../chunk-yed8mvs7.js";import{e}from"../../chunk-gc8zdxyb.js";import{posix as N}from"node:path";function x(s,l){if(s instanceof e)return s;let u=s instanceof Error?s.constructor.name:"",m=typeof s==="object"&&s!==null&&"status"in s?s.status:void 0,d="provider";if(u==="RailwayAuthError"||m===401||m===403)d="auth";else if(u==="SandboxFileNotFoundError")d="file_not_found";else if(u==="SandboxNotFoundError"||m===404)d="not_found";else if(u==="ExecControlUnsupportedError")d="unsupported";else if(u==="ExecInterruptedError"||u==="RailwayConnectionError")d="outcome_unknown";else if(m===429||m===507)d="quota";else if(u==="ExecNotStartedError"||typeof m==="number"&&m>=500)d="unavailable";else if(u==="SandboxTimeoutError")d="timeout";else if(u==="AbortError")d="aborted";else if(s instanceof TypeError||m===400)d="invalid_argument";let y=d==="auth"?"Check RAILWAY_API_TOKEN and RAILWAY_ENVIRONMENT_ID.":"Check the sandbox and Railway service before retrying.";return new e(`Railway request failed. The provider reported ${d}. ${y}`,{code:d,provider:"railway",sandboxId:l,hint:y,retryable:["quota","unavailable"].includes(d)})}function h(s){throw new e(`${s}. Railway cannot enforce this request. Omit the option or use another provider.`,{code:"unsupported",provider:"railway"})}var I="/tmp/.sandbox-sdk/railway.json",k=(s)=>`'${s.replace(/'/g,`'"'"'`)}'`;function T(s){let l;try{l=JSON.parse(s)}catch{throw new e("Invalid Railway SDK metadata",{code:"not_found",provider:"railway"})}if(typeof l!=="object"||l===null||!("version"in l)||l.version!==1||!("labels"in l)||typeof l.labels!=="object"||l.labels===null||Array.isArray(l.labels)||"key"in l&&l.key!==void 0&&typeof l.key!=="string")throw new e("Invalid Railway SDK metadata",{code:"not_found",provider:"railway"});let u={};for(let[m,d]of Object.entries(l.labels)){if(typeof d!=="string")throw new e("Invalid Railway SDK label",{code:"not_found",provider:"railway"});Object.defineProperty(u,m,{value:d,enumerable:!0})}return{version:1,key:"key"in l&&typeof l.key==="string"?l.key:void 0,labels:u}}function E(s,l){let u=Date.parse(s.createdAt);if(!Number.isFinite(u))throw Error("Invalid Railway creation time");return{id:s.id,key:l.key,labels:l.labels,state:s.status==="RUNNING"?"running":"stopped",createdAt:u}}function D(s={}){let l,u=()=>l??=o("railway","railway",()=>import("railway")),m=()=>({token:s.token??process.env.RAILWAY_API_TOKEN,environmentId:s.environmentId??process.env.RAILWAY_ENVIRONMENT_ID,authType:s.authType}),d=new Map;async function y(t,n){try{return await n()}catch(r){throw x(r,t)}}async function b(t){let n=d.get(t);if(n)return n;let{Sandbox:r}=await u(),a=await r.connect(t,m());return d.set(t,a),a}async function A(){let t=m();if(!t.token||!t.environmentId)throw new e("Railway credentials are missing. Authentication requires a token and environment ID. Set RAILWAY_API_TOKEN and RAILWAY_ENVIRONMENT_ID or pass token and environmentId.",{code:"auth",provider:"railway"});let n=[],r=null;do{let a=await fetch((await u()).DEFAULT_RAILWAY_GRAPHQL_ENDPOINT,{method:"POST",headers:{"Content-Type":"application/json",...t.authType==="project-token"?{"Project-Access-Token":t.token}:{Authorization:`Bearer ${t.token}`}},signal:AbortSignal.timeout(30000),body:JSON.stringify({query:"query SandboxSdkRailwayList($environmentId: String!, $after: String) { sandboxes(environmentId: $environmentId, first: 100, after: $after) { edges { node { id } } pageInfo { hasNextPage endCursor } } }",variables:{environmentId:t.environmentId,after:r}})});if(!a.ok)throw Object.assign(Error("Railway list failed"),{status:a.status});let i=await a.json();if(typeof i!=="object"||i===null||"errors"in i&&i.errors||!("data"in i)||typeof i.data!=="object"||i.data===null||!("sandboxes"in i.data))throw Error("Invalid Railway list response");let c=i.data.sandboxes;if(typeof c!=="object"||c===null||!("edges"in c)||!Array.isArray(c.edges)||!("pageInfo"in c))throw Error("Invalid Railway connection");for(let f of c.edges){if(typeof f!=="object"||f===null||!("node"in f)||typeof f.node!=="object"||f.node===null||!("id"in f.node)||typeof f.node.id!=="string")throw Error("Invalid Railway sandbox ID");n.push(f.node.id)}let w=c.pageInfo;if(typeof w!=="object"||w===null||!("hasNextPage"in w)||typeof w.hasNextPage!=="boolean")throw Error("Invalid Railway pagination");if(!w.hasNextPage)break;if(!("endCursor"in w)||typeof w.endCursor!=="string"||!w.endCursor||w.endCursor===r)throw Error("Missing Railway cursor");r=w.endCursor}while(r!==null);return n}async function g(t,n){if(n.signal?.aborted)return{exitCode:null,timedOut:!0};let r=await b(t),a=new AbortController,i=()=>a.abort(),c=setTimeout(i,n.timeoutMs);if(n.signal?.addEventListener("abort",i,{once:!0}),n.signal?.aborted)i();try{let w=r.exec(n.command,{cwd:n.cwd,env:n.env,stdin:n.stdin!==void 0,ephemeral:!0,captureOutput:!1,signal:a.signal,onStdout:(p)=>n.onChunk({stream:"stdout",text:p}),onStderr:(p)=>n.onChunk({stream:"stderr",text:p})}),f=Promise.resolve(w);f.catch(()=>{});try{if(n.stdin!==void 0)try{await w.stdin.write(n.stdin),await w.stdin.end()}catch{await f}let p=await f;if(p.timedOut&&p.exitCode===null)await v.destroy(t);return{exitCode:p.timedOut?null:p.exitCode,timedOut:p.timedOut}}catch(p){if(a.signal.aborted){if(p!==a.signal.reason)await v.destroy(t);return await f.catch(()=>{}),{exitCode:null,timedOut:!0}}if(x(p,t).code==="outcome_unknown")await v.destroy(t);throw p}}finally{clearTimeout(c),n.signal?.removeEventListener("abort",i)}}async function R(t,n){let r="";if((await g(t,{command:`stat -c '%f %s %Y' -- ${k(n)}`,cwd:"/",env:{},timeoutMs:30000,onChunk:(S)=>{if(S.stream==="stdout")r+=S.text}})).exitCode!==0)throw await(await b(t)).files.stat(n),Error("Railway stat command failed");let[i,c,w]=r.trim().split(/\s+/),f=Number.parseInt(i??"",16),p=Number(c),C=Number(w)*1000;if(![f,p,C].every(Number.isFinite))throw Error("Invalid Railway stat output");return{path:n,type:(f&61440)===40960?"symlink":(f&61440)===16384?"directory":"file",size:p,modifiedAt:C}}let v={name:"railway",commandShell:"bash",keyMode:"best-effort",capabilities:new Set(["snapshot"]),create:(t)=>y(void 0,async()=>{if(t.size!==void 0)h("Railway resources set CPU and memory but cannot set diskGb; size presets and exact sizes are unavailable");if(t.network!==void 0&&t.network!=="all")h("Railway isolation modes retain outbound internet access");if(t.timeoutMs!==void 0)h("Railway has no hard sandbox lifetime; idle destruction is not a lifetime limit");if(t.signal?.aborted)throw new e("Creation aborted. The signal was cancelled. Retry with a fresh signal.",{code:"aborted",provider:"railway"});if(t.ports&&(t.ports.length>10||new Set(t.ports).size!==t.ports.length))h("Railway accepts at most 10 unique preview ports");if(t.ports?.length&&s.networkIsolation==="ISOLATED")h("Public domains require PRIVATE networking");if(t.idleTimeoutMs!==void 0&&(!Number.isFinite(t.idleTimeoutMs)||t.idleTimeoutMs<=0))throw new e("Invalid idle timeout. A positive duration is required. Set idleTimeoutMs above zero.",{code:"invalid_argument",provider:"railway"});let{Sandbox:n}=await u(),r={...m(),region:s.region,env:t.env,idleTimeoutMinutes:t.idleTimeoutMs===void 0?void 0:Math.ceil(t.idleTimeoutMs/60000),networkIsolation:t.ports?.length?"PRIVATE":s.networkIsolation,domains:t.ports?.map((c)=>({port:c}))},a=t.from??s.checkpoint??s.template,i=a===void 0?await n.create(r):typeof a==="string"?await n.create(a,r):await n.create(a,r);d.set(i.id,i);try{if(t.signal?.aborted)throw new e("Creation aborted. Cancellation arrived while provisioning. Retry with a fresh signal.",{code:"aborted",provider:"railway"});let c={version:1,key:t.key,labels:{...t.labels,"sandbox-sdk":"1"}},w=a===void 0?"":'for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/runs; ',f=await g(i.id,{command:`mkdir -p /workspace /tmp/.sandbox-sdk && { ${w}printf %s ${k(JSON.stringify(c))} > ${k(I)}; }`,cwd:"/",env:{},timeoutMs:30000,onChunk(){}});if(f.timedOut||f.exitCode!==0)throw Error("Railway workspace and ownership initialization failed");if(t.signal?.aborted)throw new e("Creation aborted. Cancellation arrived during initialization. Retry with a fresh signal.",{code:"aborted",provider:"railway"});return E(i,c)}catch(c){throw await v.destroy(i.id),c}}),connect:(t)=>y(t,async()=>{let{Sandbox:n}=await u(),r=await n.connect(t,m());return d.set(t,r),E(r,T(await r.files.read(I)))}),find:(t)=>y(void 0,async()=>(await v.list({})).find((n)=>n.key===t)),list:(t)=>y(void 0,async()=>{let n=[];for(let r of await A())try{let{Sandbox:a}=await u(),i=await a.connect(r,m());if(i.status!=="RUNNING")continue;let c=T(await i.files.read(I));if(c.labels["sandbox-sdk"]==="1"&&Object.entries(t).every(([w,f])=>c.labels[w]===f))n.push(E(i,c))}catch(a){if(!["not_found","file_not_found"].includes(x(a,r).code))throw a}return n}),destroy:(t)=>y(t,async()=>{try{await(await b(t)).destroy()}catch(n){if(x(n,t).code!=="not_found")throw n}d.delete(t)}),close:async(t)=>{d.delete(t)},native(t){let n=d.get(t);if(!n)throw new e("Sandbox client is detached. No cached Railway object exists. Connect first.",{code:"not_found",provider:"railway",sandboxId:t});return n},exec:(t,n)=>y(t,()=>g(t,n)),files:{writeCreatesParents:!0,read:(t,n)=>y(t,async()=>(await b(t)).files.read(n,{format:"bytes"})),readRange:(t,n,r)=>y(t,async()=>r.length===0?new Uint8Array:(await b(t)).files.read(n,{format:"bytes",...r})),write:(t,n,r)=>y(t,async()=>{await(await b(t)).files.write(n,r)}),mkdir:(t,n)=>y(t,async()=>{await(await b(t)).files.mkdir(n)}),stat:(t,n)=>y(t,()=>R(t,n)),list:(t,n)=>y(t,async()=>{let r=await(await b(t)).files.list(n),a=[];for(let i of r)a.push(await R(t,N.join(n,i.name)));return a}),remove:(t,n,r)=>y(t,async()=>{let a=await b(t);if(!r.recursive){await a.files.remove(n);return}if((await g(t,{command:`rm -rf -- ${k(n)}`,cwd:"/",env:{},timeoutMs:30000,onChunk(){}})).exitCode!==0)throw Error("Railway recursive removal failed")})},previewUrl:(t,n)=>y(t,async()=>{let a=(await b(t)).domains.find((i)=>i.port===n);if(!a)h("The preview port was not declared at creation; pass ports to createSandbox");return{url:`https://${a.domain}`}}),snapshot:(t)=>y(t,async()=>({id:(await(await b(t)).checkpoint(`sandbox-sdk-${crypto.randomUUID()}`)).key}))};return v}export{D as railway};
|
|
1
|
+
import{N}from"../../chunk-q5vqajhg.js";import{m}from"../../chunk-bd481sb7.js";import{g}from"../../chunk-k60b4r27.js";import{n}from"../../chunk-2ts3evzh.js";import{e,i,c,a}from"../../chunk-xgxfy2n8.js";import{posix as z}from"node:path";var j=new Set;function B(o){j.add(o)}function T(o,R){if(o instanceof e)return o;let k=m(o),{name:E,status:y}=k,b=(A)=>[...j].some((S)=>o instanceof S[A])||E===A,u="provider";if(b("RailwayAuthError")||y===401||y===403)u="auth";else if(b("SandboxFileNotFoundError"))u="file_not_found";else if(b("SandboxNotFoundError")||y===404)u="not_found";else if(b("ExecControlUnsupportedError"))u="unsupported";else if(b("ExecNotStartedError"))u="unavailable";else if(b("ExecInterruptedError")||b("RailwayConnectionError"))u="outcome_unknown";else if(y===429||y===507)u="quota";else if(y!==void 0&&y>=500)u="unavailable";else if(b("SandboxTimeoutError"))u="timeout";else if(E==="AbortError")u="aborted";else if(o instanceof TypeError&&o.message==="fetch failed")u="unavailable";else if(o instanceof TypeError||y===400)u="invalid_argument";let h=u==="auth"?"Check RAILWAY_API_TOKEN and RAILWAY_ENVIRONMENT_ID.":"Check the sandbox and Railway service before retrying.",v=i(o,{code:u,known:o instanceof TypeError?!1:void 0,status:y===void 0?void 0:`HTTP ${y}`,redact:c([process.env.RAILWAY_API_TOKEN])});return new e(`Railway request failed: ${a(u,v.detail)}. ${h}`,{code:u,provider:"railway",sandboxId:R,hint:h,retryable:["quota","unavailable"].includes(u),cause:v.cause})}function C(o){throw new e(`${o}. Railway cannot enforce this request. Omit the option or use another provider.`,{code:"unsupported",provider:"railway"})}var M="/tmp/.sandbox-sdk/railway.json",Y="SANDBOX_SDK_EXEC_ID",W=(o)=>`for f in $(grep -lzx ${n(`${Y}=${o}`)} /proc/[0-9]*/environ 2>/dev/null); do p=\${f#/proc/}; kill -KILL "\${p%/environ}" 2>/dev/null; done; true`;function U(o){let R=(b)=>{throw new e(`Invalid Railway SDK ${b}`,{code:"not_found",provider:"railway"})},{key:k,labels:E,version:y}=N(o,R);if(y!==1||k===null)R("metadata");return{version:1,key:k,labels:E}}function G(o){return typeof o==="object"&&o!==null&&!(("errors"in o)&&o.errors)&&"data"in o&&typeof o.data==="object"&&o.data!==null&&"sandboxes"in o.data}function K(o){return typeof o==="object"&&o!==null&&"edges"in o&&Array.isArray(o.edges)&&"pageInfo"in o}function H(o){return typeof o==="object"&&o!==null&&"node"in o&&typeof o.node==="object"&&o.node!==null&&"id"in o.node&&typeof o.node.id==="string"}function V(o){return typeof o==="object"&&o!==null&&"hasNextPage"in o&&typeof o.hasNextPage==="boolean"}function J(o){return"endCursor"in o&&typeof o.endCursor==="string"}function D(o,R){let k=Date.parse(o.createdAt);if(!Number.isFinite(k))throw Error("Invalid Railway creation time");return{id:o.id,key:R.key,labels:R.labels,state:o.status==="RUNNING"?"running":"stopped",createdAt:k}}function q(o,R){let k,E=()=>k??=g("railway","railway",R).then((t)=>(B(t),t)),y=()=>({token:o.token??process.env.RAILWAY_API_TOKEN,environmentId:o.environmentId??process.env.RAILWAY_ENVIRONMENT_ID,authType:o.authType}),b=new Map,u=new Map;async function h(t,r){try{return await r()}catch(s){throw T(s,t)}}async function v(t){let r=b.get(t);if(r)return r;let{Sandbox:s}=await E(),d=await s.connect(t,y());return b.set(t,d),d}async function A(){let t=y();if(!t.token||!t.environmentId)throw new e("Railway credentials are missing. Authentication requires a token and environment ID. Set RAILWAY_API_TOKEN and RAILWAY_ENVIRONMENT_ID or pass token and environmentId.",{code:"auth",provider:"railway"});let r=[],s=null;do{let d=await fetch((await E()).DEFAULT_RAILWAY_GRAPHQL_ENDPOINT,{method:"POST",headers:{"Content-Type":"application/json",...t.authType==="project-token"?{"Project-Access-Token":t.token}:{Authorization:`Bearer ${t.token}`}},signal:AbortSignal.timeout(30000),body:JSON.stringify({query:"query SandboxSdkRailwayList($environmentId: String!, $after: String) { sandboxes(environmentId: $environmentId, first: 100, after: $after) { edges { node { id } } pageInfo { hasNextPage endCursor } } }",variables:{environmentId:t.environmentId,after:s}})});if(!d.ok)throw Object.assign(Error("Railway list failed"),{status:d.status});let w=await d.json();if(!G(w))throw Error("Invalid Railway list response");let l=w.data.sandboxes;if(!K(l))throw Error("Invalid Railway connection");for(let x of l.edges){if(!H(x))throw Error("Invalid Railway sandbox ID");r.push(x.node.id)}let f=l.pageInfo;if(!V(f))throw Error("Invalid Railway pagination");if(!f.hasNextPage)break;if(!J(f)||!f.endCursor||f.endCursor===s)throw Error("Missing Railway cursor");s=f.endCursor}while(s!==null);return r}async function S(t,r){try{return(await O(t,{command:W(r),cwd:"/",env:{},timeoutMs:15000,onChunk(){}},!1)).exitCode===0}catch{return!1}}let L=(t)=>new e("Command outcome unknown. Railway did not confirm that the command stopped, and the cleanup command failed. Check the sandbox, or destroy it if the command must not keep running.",{code:"outcome_unknown",provider:"railway",sandboxId:t});async function O(t,r,s=!0){if(r.signal?.aborted)return{exitCode:null,timedOut:!0};let d=await v(t),w=new AbortController,l=()=>w.abort(),f=setTimeout(l,r.timeoutMs);if(r.signal?.addEventListener("abort",l,{once:!0}),r.signal?.aborted)l();let x=crypto.randomUUID();try{let I=d.exec(r.command,{cwd:r.cwd,env:{...r.env,[Y]:x},stdin:r.stdin!==void 0,ephemeral:!0,captureOutput:!1,signal:w.signal,onStdout:(p)=>r.onChunk({stream:"stdout",text:p}),onStderr:(p)=>r.onChunk({stream:"stderr",text:p})}),P=Promise.resolve(I);P.catch(()=>{});try{if(r.stdin!==void 0)try{await I.stdin.write(r.stdin),await I.stdin.end()}catch{await P}let p=await P;if(p.timedOut&&p.exitCode===null&&s&&!await S(t,x))throw L(t);return{exitCode:p.timedOut?null:p.exitCode,timedOut:p.timedOut}}catch(p){if(p instanceof e&&p.code==="outcome_unknown")throw p;if(w.signal.aborted){if(await P.catch(()=>{}),p!==w.signal.reason&&s&&!await S(t,x))throw L(t);return{exitCode:null,timedOut:!0}}if(s&&T(p,t).code==="outcome_unknown")await S(t,x);throw p}}finally{clearTimeout(f),r.signal?.removeEventListener("abort",l)}}async function F(t,r){let s="";if((await O(t,{command:`stat -c '%f %s %Y' -- ${n(r)}`,cwd:"/",env:{},timeoutMs:30000,onChunk:(p)=>{if(p.stream==="stdout")s+=p.text}})).exitCode!==0)throw await(await v(t)).files.stat(r),Error("Railway stat command failed");let[w,l,f]=s.trim().split(/\s+/),x=Number.parseInt(w??"",16),I=Number(l),P=Number(f)*1000;if(![x,I,P].every(Number.isFinite))throw Error("Invalid Railway stat output");return{path:r,type:(x&61440)===40960?"symlink":(x&61440)===16384?"directory":"file",size:I,modifiedAt:P}}let _={name:"railway",commandShell:"bash",keyMode:"best-effort",capabilities:new Set(["snapshot"]),create:(t)=>h(void 0,async()=>{if(t.size!==void 0)C("Railway resources set CPU and memory but cannot set diskGb; size presets and exact sizes are unavailable");if(t.network!==void 0&&t.network!=="all")C("Railway isolation modes retain outbound internet access");if(t.timeoutMs!==void 0)C("Railway has no hard sandbox lifetime; idle destruction is not a lifetime limit");if(t.signal?.aborted)throw new e("Creation aborted. The signal was cancelled. Retry with a fresh signal.",{code:"aborted",provider:"railway"});if(t.ports&&(t.ports.length>10||new Set(t.ports).size!==t.ports.length))C("Railway accepts at most 10 unique preview ports");if(t.ports?.length&&o.networkIsolation==="ISOLATED")C("Public domains require PRIVATE networking");if(t.idleTimeoutMs!==void 0&&(!Number.isFinite(t.idleTimeoutMs)||t.idleTimeoutMs<=0))throw new e("Invalid idle timeout. A positive duration is required. Set idleTimeoutMs above zero.",{code:"invalid_argument",provider:"railway"});let{Sandbox:r}=await E(),s={...y(),region:o.region,env:t.env,idleTimeoutMinutes:t.idleTimeoutMs===void 0?void 0:Math.ceil(t.idleTimeoutMs/60000),networkIsolation:t.ports?.length?"PRIVATE":o.networkIsolation,domains:t.ports?.map((f)=>({port:f}))};if(o.resources!==void 0)s.resources=o.resources;let d=t.from??o.checkpoint,w=d??o.template,l;if(d!==void 0)l=await r.create(d,s);else if(o.template!==void 0)l=await r.create(o.template,s);else l=await r.create(s);b.set(l.id,l);try{if(t.signal?.aborted)throw new e("Creation aborted. Cancellation arrived while provisioning. Retry with a fresh signal.",{code:"aborted",provider:"railway"});let f={version:1,key:t.key,labels:{...t.labels,"sandbox-sdk":"1"}},x=w===void 0?"":'for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/runs; ',I=await O(l.id,{command:`mkdir -p /workspace /tmp/.sandbox-sdk && { ${x}printf %s ${n(JSON.stringify(f))} > ${n(M)}; }`,cwd:"/",env:{},timeoutMs:30000,onChunk(){}});if(I.timedOut||I.exitCode!==0)throw Error("Railway workspace and ownership initialization failed");if(t.signal?.aborted)throw new e("Creation aborted. Cancellation arrived during initialization. Retry with a fresh signal.",{code:"aborted",provider:"railway"});return u.set(l.id,f),D(l,f)}catch(f){throw await _.destroy(l.id),f}}),connect:(t)=>h(t,async()=>{let{Sandbox:r}=await E(),s=await r.connect(t,y());if(s.status==="DESTROYED"||s.status==="DESTROYING")throw new e(`Railway sandbox ${t} was not found. It has been destroyed.`,{code:"not_found",provider:"railway",sandboxId:t});b.set(t,s);let d=U(await s.files.read(M));return u.set(t,d),D(s,d)}),find:(t)=>h(void 0,async()=>(await _.list({})).find((r)=>r.key===t)),list:(t)=>h(void 0,async()=>{let r=[];for(let s of await A())try{let{Sandbox:d}=await E(),w=await d.connect(s,y());if(w.status==="DESTROYED"||w.status==="DESTROYING")continue;let l;try{l=U(await w.files.read(M))}catch(f){if(l=u.get(s),w.status==="RUNNING"&&!l)throw f}if(l&&l.labels["sandbox-sdk"]==="1"&&Object.entries(t).every(([f,x])=>l.labels[f]===x))r.push(D(w,l))}catch(d){if(!["not_found","file_not_found"].includes(T(d,s).code))throw d}return r}),destroy:(t)=>h(t,async()=>{try{await(await v(t)).destroy()}catch(r){if(T(r,t).code!=="not_found")throw r}b.delete(t),u.delete(t)}),close:async(t)=>{b.delete(t)},native(t){let r=b.get(t);if(!r)throw new e("Sandbox client is detached. No cached Railway object exists. Connect first.",{code:"not_found",provider:"railway",sandboxId:t});return r},exec:(t,r)=>h(t,()=>O(t,r)),files:{writeCreatesParents:!0,writeSupportsMode:!0,read:(t,r)=>h(t,async()=>(await v(t)).files.read(r,{format:"bytes"})),readRange:(t,r,s)=>h(t,async()=>s.length===0?new Uint8Array:(await v(t)).files.read(r,{format:"bytes",...s})),write:(t,r,s,d)=>h(t,async()=>{await(await v(t)).files.write(r,s,d?.mode===void 0?void 0:{mode:d.mode})}),mkdir:(t,r)=>h(t,async()=>{await(await v(t)).files.mkdir(r)}),stat:(t,r)=>h(t,()=>F(t,r)),list:(t,r)=>h(t,async()=>{let s=await(await v(t)).files.list(r),d=[];for(let w of s)d.push(await F(t,z.join(r,w.name)));return d}),remove:(t,r,s)=>h(t,async()=>{let d=await v(t);if(!s.recursive){await d.files.remove(r);return}if((await O(t,{command:`rm -rf -- ${n(r)}`,cwd:"/",env:{},timeoutMs:30000,onChunk(){}})).exitCode!==0)throw Error("Railway recursive removal failed")})},previewUrl:(t,r)=>h(t,async()=>{let d=(await v(t)).domains.find((w)=>w.port===r);if(!d)C("The preview port was not declared at creation; pass ports to createSandbox");return{url:`https://${d.domain}`}}),snapshot:(t,r)=>h(t,async()=>{if(r?.expiresInMs)C("Checkpoint expiry is unavailable; Railway keeps checkpoints until you delete them. Omit expiresInMs, or pass 0");return{id:(await(await v(t)).checkpoint(`sandbox-sdk-${crypto.randomUUID()}`)).key}})};return _}function de(o={}){return q(o,()=>import("railway"))}export{de as railway};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Sandbox, SandboxTemplate, CreateOptions, ConnectOptions, ExecHandle, ExecOptions, FileReadOptions, FileWriteOptions, SandboxFileEntry } from "railway";
|
|
2
|
+
import type { Provider } from "../../provider.js";
|
|
3
|
+
import { type RailwayErrorClasses } from "./errors.js";
|
|
4
|
+
export type RailwayOptions = {
|
|
5
|
+
/** Defaults to RAILWAY_API_TOKEN; required for authentication. */
|
|
6
|
+
token?: CreateOptions["token"];
|
|
7
|
+
/** Defaults to RAILWAY_ENVIRONMENT_ID; required for authentication. */
|
|
8
|
+
environmentId?: CreateOptions["environmentId"];
|
|
9
|
+
/** Deployment region; default: the Railway service default. */
|
|
10
|
+
region?: CreateOptions["region"];
|
|
11
|
+
/** Network isolation; default: the native Railway SDK setting. */
|
|
12
|
+
networkIsolation?: CreateOptions["networkIsolation"];
|
|
13
|
+
/** Token kind; default: the native Railway SDK authentication mode. */
|
|
14
|
+
authType?: CreateOptions["authType"];
|
|
15
|
+
/** vCPUs (fractions allowed) and memory in decimal GB, such as `{ cpu: 2, memoryGB: 4 }`. Railway caps both at the workspace's VM maximum. Default: the plan default. */
|
|
16
|
+
resources?: CreateOptions["resources"];
|
|
17
|
+
} & ({
|
|
18
|
+
/** Base template; default: the Railway service default; mutually exclusive with checkpoint. */
|
|
19
|
+
template?: SandboxTemplate;
|
|
20
|
+
checkpoint?: never;
|
|
21
|
+
} | {
|
|
22
|
+
template?: never;
|
|
23
|
+
/** Checkpoint to restore; default: none; mutually exclusive with template. */
|
|
24
|
+
checkpoint?: string;
|
|
25
|
+
});
|
|
26
|
+
/** The parts of a Railway sandbox the adapter uses. */
|
|
27
|
+
export type RailwayBox = Pick<Sandbox, "id" | "createdAt" | "status" | "domains" | "checkpoint" | "destroy"> & {
|
|
28
|
+
files: {
|
|
29
|
+
read(path: string): Promise<string>;
|
|
30
|
+
read(path: string, options: FileReadOptions & {
|
|
31
|
+
format: "bytes";
|
|
32
|
+
}): Promise<Uint8Array>;
|
|
33
|
+
write(path: string, data: Uint8Array, options?: FileWriteOptions): Promise<void>;
|
|
34
|
+
list(path: string): Promise<SandboxFileEntry[]>;
|
|
35
|
+
stat(path: string): Promise<SandboxFileEntry>;
|
|
36
|
+
mkdir(path: string): Promise<void>;
|
|
37
|
+
remove(path: string): Promise<void>;
|
|
38
|
+
};
|
|
39
|
+
exec(command: string, options: ExecOptions): Pick<ExecHandle, "then" | "stdin">;
|
|
40
|
+
};
|
|
41
|
+
/** The parts of the Railway SDK the adapter uses: the real `railway` module, or a test fixture. */
|
|
42
|
+
export interface RailwayModule<B extends RailwayBox> extends RailwayErrorClasses {
|
|
43
|
+
Sandbox: {
|
|
44
|
+
create(options: CreateOptions): Promise<B>;
|
|
45
|
+
create(checkpointName: string, options: CreateOptions): Promise<B>;
|
|
46
|
+
create(template: SandboxTemplate, options: CreateOptions): Promise<B>;
|
|
47
|
+
connect(id: string, options: ConnectOptions): Promise<B>;
|
|
48
|
+
};
|
|
49
|
+
DEFAULT_RAILWAY_GRAPHQL_ENDPOINT: string;
|
|
50
|
+
}
|
|
51
|
+
export type RailwayProvider = Provider<Sandbox, "snapshot">;
|
|
52
|
+
/** @internal The adapter behind `railway()`. `load` imports the Railway SDK; tests pass a fixture. */
|
|
53
|
+
export declare function createRailwayProvider<B extends RailwayBox>(options: RailwayOptions, load: () => Promise<RailwayModule<B>>): Provider<B, "snapshot">;
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
/** Sandboxer API v1 derives from Boat API v1. https://sandboxer.com/api/v1/openapi.yaml */
|
|
2
|
-
import type { CreateSandboxRequest } from "@boatdev/sdk";
|
|
3
1
|
import type { Provider } from "../../provider.js";
|
|
4
|
-
import type {
|
|
2
|
+
import type { NativeApi } from "../../native.js";
|
|
3
|
+
import type { BoatClientSdk, BoatCreateOptions, BoatMachine, BoatSandboxSdk } from "../boat/index.js";
|
|
4
|
+
import type { BoatPlane } from "../boat-api/transport.js";
|
|
5
5
|
/** `GET /regions` lists them: us-east (Ashburn, Virginia), eu-central (Helsinki). */
|
|
6
6
|
export type SandboxerRegion = "us-east" | "eu-central" | (string & {});
|
|
7
|
-
export interface SandboxerOptions {
|
|
7
|
+
export interface SandboxerOptions extends BoatCreateOptions {
|
|
8
8
|
/** Defaults to SANDBOXER_API_KEY; required on first use. */
|
|
9
9
|
apiKey?: string;
|
|
10
10
|
/** Default: https://sandboxer.com/api/v1. */
|
|
11
11
|
baseUrl?: string;
|
|
12
12
|
/** Native machine size; default: Sandboxer default (4 CPU/8 GB). Per-create size wins. */
|
|
13
|
-
machine?:
|
|
13
|
+
machine?: BoatMachine;
|
|
14
14
|
/** Deadline for each control-plane request and lifecycle poll. Default: 90 seconds. */
|
|
15
15
|
requestTimeoutMs?: number;
|
|
16
16
|
/** Region for new sandboxes. Default: SANDBOXER_REGION, else the region
|
|
@@ -19,7 +19,11 @@ export interface SandboxerOptions {
|
|
|
19
19
|
}
|
|
20
20
|
declare const regionSources: readonly ["requested", "nearest", "default", "source"];
|
|
21
21
|
export type SandboxerRegionSource = (typeof regionSources)[number];
|
|
22
|
-
|
|
22
|
+
/**
|
|
23
|
+
* `box.native`: Sandboxer's HTTP API with this adapter's base URL, key, retries and redaction (plane `"api"`,
|
|
24
|
+
* `{sandboxId}` fills from the sandbox), plus where the VM landed and named snapshots.
|
|
25
|
+
*/
|
|
26
|
+
export interface SandboxerNative extends NativeApi<BoatPlane, BoatSandboxSdk> {
|
|
23
27
|
/** Null for sandboxes from before regions. */
|
|
24
28
|
readonly region: string | null;
|
|
25
29
|
readonly regionSource: SandboxerRegionSource | null;
|
|
@@ -27,7 +31,10 @@ export interface SandboxerNative extends BoatNative {
|
|
|
27
31
|
id: string;
|
|
28
32
|
}>;
|
|
29
33
|
}
|
|
30
|
-
export type SandboxerProvider = Provider<SandboxerNative, "size" | "pause" | "snapshot"
|
|
31
|
-
/** Sandboxer
|
|
34
|
+
export type SandboxerProvider = Provider<SandboxerNative, "size" | "pause" | "snapshot"> & {
|
|
35
|
+
/** Sandboxer's API with no sandbox bound, for account calls such as `GET /regions`. */
|
|
36
|
+
readonly api: NativeApi<BoatPlane, BoatClientSdk>;
|
|
37
|
+
};
|
|
38
|
+
/** Sandboxer through its Boat-compatible API, over plain HTTP. No other package to install. */
|
|
32
39
|
export declare function sandboxer(options?: SandboxerOptions): SandboxerProvider;
|
|
33
40
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../chunk-
|
|
1
|
+
import"../../chunk-23tjmd39.js";import{B,q}from"../../chunk-gw3n7sx7.js";import{d,y}from"../../chunk-vy1j4r8f.js";import{t,r}from"../../chunk-xgxfy2n8.js";var w=["requested","nearest","default","source"],{failure:i,boatError:v}=B("sandboxer","Sandboxer","SANDBOXER_API_KEY",!0),k="https://sandboxer.com/api/v1",g="X-Sandboxer-Confirm-Delete";function j(l={}){let S=l.requestTimeoutMs??90000,b=new Map,p=l.region??process.env.SANDBOXER_REGION;if(p!==void 0&&!/^[a-z][a-z0-9-]{0,31}$/.test(p))throw i("Invalid Sandboxer region","invalid_argument");let m=new Map;function I(n){if(!("id"in n)||!t(n.id)||!("region"in n))return;let e=t(n.region)?n.region:null,o="regionSource"in n?w.find((a)=>a===n.regionSource)??null:null;m.set(n.id,{region:e,regionSource:o})}async function c(n,e,o){let a=d(S);for(;;){if(o(await u.json({method:"GET",path:n,params:e,deadline:a})))return;if(a.remaining()<=0)break;try{await y(Math.min(250,a.remaining()),a,"sandboxer")}catch{break}}throw i("Sandboxer operation did not finish before its deadline","timeout")}async function h(n,e){if(!/^[a-z0-9][a-z0-9-]{0,62}$/.test(e))throw i("Invalid snapshot name","invalid_argument",n);try{return await u.json({method:"POST",path:"/named-snapshots",body:{sandboxId:n,name:e},sandboxId:n}),await c("/named-snapshots/{name}",{name:e},(o)=>{if(!r(o)||o===null||!("snapshot"in o))throw i("Invalid snapshot response");let a=o.snapshot;if(!r(a)||a===null||!("status"in a)||!("name"in a)||a.name!==e||!("sourceSandboxId"in a)||a.sourceSandboxId!==n)throw i("Invalid snapshot metadata");if(a.status==="failed")throw i("Sandboxer snapshot failed","provider",n);return a.status==="ready"}),{id:e}}catch(o){throw i(`Sandboxer snapshot ${e} did not complete; inspect this name before retrying`,v(o,n).code,n)}}let{provider:x,http:u}=q(l,{name:"sandboxer",label:"Sandboxer",keyEnv:"SANDBOXER_API_KEY",baseUrl:k,createFrom:!0,idleStop:!0,pausedStates:["archived","stopped"],...p===void 0?void 0:{createFields:{region:p}},observe:(n)=>I(n.raw),downloadMaxBytes:52428800,destroy:async(n,e)=>{let o=b.get(e);if(!o){let a=await n.json({method:"DELETE",path:"/sandboxes/{sandboxId}",params:{sandboxId:e},sandboxId:e,headers:{[g]:e,"X-Ascii-Confirm-Delete":e}}),s=r(a)&&"operation"in a?a.operation:void 0;if(!r(s)||s===null||!("targetId"in s)||s.targetId!==e||!("kind"in s)||s.kind!=="sandbox"||!("status"in s))throw i("Invalid deletion operation","outcome_unknown",e);if(s.status==="completed")return;if(!("id"in s)||!t(s.id)||!s.id)throw i("Invalid deletion operation","outcome_unknown",e);o=s.id,b.set(e,o)}await c("/deletion-operations/{operationId}",{operationId:o},(a)=>{if(!r(a)||a===null||!("operation"in a))throw i("Invalid deletion response");let s=a.operation;if(!r(s)||s===null||!("targetId"in s)||s.targetId!==e||!("status"in s))throw i("Invalid deletion metadata");return s.status==="completed"}),b.delete(e)},download:async(n,e,o)=>(await n.request({method:"GET",path:"/sandboxes/{sandboxId}/artifacts",params:{sandboxId:e},query:{path:o},sandboxId:e,maxBytes:52428801})).body,preview:async(n)=>{let e=new URL(n),o=e.searchParams.get("_token");if(o===null)return{url:n};if(!/^[A-Za-z0-9._~-]+$/.test(o))throw i("Invalid preview token");return e.searchParams.delete("_token"),{url:e.toString(),headers:{Cookie:`__sbx_auth=${o}`}}},sdkConfiguration:{middleware:[{async pre({url:n,init:e}){let o=new URL(n).pathname;if(e.method!=="DELETE"||!/\/sandboxes\/[^/]+$/.test(o))return;let a=new Headers(e.headers);return a.set(g,decodeURIComponent(o.slice(o.lastIndexOf("/")+1))),{url:n,init:{...e,headers:a}}}}]}}),f=(n,e)=>({method:"POST",path:`/sandboxes/{sandboxId}/${e}`,params:{sandboxId:n},sandboxId:n});return{...x,capabilities:new Set(["size","pause","snapshot"]),async pause(n){await u.json(f(n,"stop")),await c("/sandboxes/{sandboxId}",{sandboxId:n},(e)=>{if(!r(e)||e===null||!("sandbox"in e))throw i("Invalid stop response");let o=e.sandbox;if(!r(o)||o===null||!("id"in o)||o.id!==n||!("stop"in o))throw i("Invalid stop metadata");let a=o.stop;if(!r(a)||a===null||!("status"in a))return!1;return a.status==="completed"})},async resume(n){await u.json(f(n,"resume")),await c("/sandboxes/{sandboxId}",{sandboxId:n},(e)=>{if(!r(e)||e===null||!("sandbox"in e))throw i("Invalid resume response");let o=e.sandbox;if(!r(o)||o===null||!("id"in o)||o.id!==n||!("state"in o))throw i("Invalid resume metadata");return o.state==="ready"}),await x.connect(n)},async snapshot(n,e={}){if(e.expiresInMs!==void 0&&e.expiresInMs!==0)throw i("Sandboxer named snapshots never expire; expiresInMs is unsupported. Delete the snapshot yourself","unsupported",n);return h(n,`sdk-${crypto.randomUUID()}`)},native:(n)=>Object.assign(x.native(n),{region:null,regionSource:null,...m.get(n),createSnapshot:(e)=>h(n,e)})}}export{j as sandboxer};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { SandboxError, type ErrorCode } from "../../errors.js";
|
|
2
|
-
export declare function failure(message: string, code?: ErrorCode, sandboxId?: string): SandboxError;
|
|
3
|
-
export declare function superserveError(
|
|
2
|
+
export declare function failure(message: string, code?: ErrorCode, sandboxId?: string, cause?: string): SandboxError;
|
|
3
|
+
export declare function superserveError(cause: unknown, sandboxId?: string): SandboxError;
|
|
@@ -1,13 +1,8 @@
|
|
|
1
1
|
import type { ExecInput, ExecResult } from "../../provider.js";
|
|
2
|
-
|
|
3
|
-
export declare const supervisor = "import os,sys,marshal,_signal as signal,select,time,fcntl\ndef stdin_file():\n try: return os.fdopen(os.memfd_create('sandbox-sdk-stdin'),'w+b')\n except (AttributeError,OSError):\n import tempfile\n return tempfile.TemporaryFile()\nclass Process:\n def __init__(self,v,env,stdin,session=False):\n if not all(hasattr(os,name) for name in ['posix_spawn','waitstatus_to_exitcode']):\n self.legacy(v,env,stdin,session); return\n directory=os.open('.',os.O_RDONLY)\n r,w=os.pipe(); e,x=os.pipe()\n try:\n
|
|
4
|
-
export interface ExecutionGuest {
|
|
2
|
+
import { type PagedGuest } from "../../shared/paged-exec.js";
|
|
3
|
+
export declare const supervisor = "import os,sys,marshal,_signal as signal,select,time,fcntl\ndef stdin_file():\n try: return os.fdopen(os.memfd_create('sandbox-sdk-stdin'),'w+b')\n except (AttributeError,OSError):\n import tempfile\n return tempfile.TemporaryFile()\nclass Process:\n # A missing cwd fails the command, not the supervisor: the shell reports it on stderr and exits 2.\n def argv(self,v):\n try: os.chdir(v['cwd']); return ['sh','-c',v['command']]\n except OSError: return ['sh','-c','cd \"$1\" || exit 2','sh',v['cwd']]\n def __init__(self,v,env,stdin,session=False):\n if not all(hasattr(os,name) for name in ['posix_spawn','waitstatus_to_exitcode']):\n self.legacy(v,env,stdin,session); return\n directory=os.open('.',os.O_RDONLY)\n r,w=os.pipe(); e,x=os.pipe()\n try:\n argv=self.argv(v)\n error=FileNotFoundError(2,os.strerror(2),'sh')\n signals=[getattr(signal,s) for s in ['SIGPIPE','SIGXFZ','SIGXFSZ'] if hasattr(signal,s)]\n for path in os.get_exec_path(env):\n try:\n self.pid=os.posix_spawn(os.path.join(path,'sh'),argv,env,file_actions=[(os.POSIX_SPAWN_DUP2,stdin.fileno(),0),(os.POSIX_SPAWN_DUP2,w,1),(os.POSIX_SPAWN_DUP2,x,2)],setsid=session,setsigdef=signals)\n break\n except (FileNotFoundError,NotADirectoryError): pass\n except OSError as failure:\n if failure.errno==38: raise NotImplementedError()\n error=failure\n else: raise error\n except NotImplementedError:\n os.close(r); os.close(e)\n self.legacy(v,env,stdin,session); return\n except BaseException:\n os.close(r); os.close(e); raise\n finally:\n os.fchdir(directory); os.close(directory); os.close(w); os.close(x)\n self.stdout=os.fdopen(r,'rb',buffering=0); self.stderr=os.fdopen(e,'rb',buffering=0)\n self.code=None\n def legacy(self,v,env,stdin,session):\n import subprocess\n directory=os.open('.',os.O_RDONLY)\n try: self.child=subprocess.Popen(self.argv(v),env=env,stdin=stdin,stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=session)\n finally: os.fchdir(directory); os.close(directory)\n self.pid=self.child.pid; self.stdout=self.child.stdout; self.stderr=self.child.stderr\n def poll(self):\n if hasattr(self,'child'): return self.child.poll()\n if self.code is None:\n pid,status=os.waitpid(self.pid,os.WNOHANG)\n if pid: self.code=os.waitstatus_to_exitcode(status)\n return self.code\n def wait(self):\n if hasattr(self,'child'): return self.child.wait()\n if self.code is None: self.code=os.waitstatus_to_exitcode(os.waitpid(self.pid,0)[1])\n return self.code\n\nroot=sys.argv[1]\nv=marshal.loads(bytes.fromhex(sys.argv[2])) if len(sys.argv)>2 else marshal.loads(bytes.fromhex(sys.stdin.read()))\nif 'envKeys' in v: v['env']={k:os.environ[k] for k in v['envKeys']}\nos.makedirs(root,mode=0o700,exist_ok=True)\n# Keep small completed responses until their request deadline has passed.\n# Sweep expired responses inline, so no ack RPC or background daemon is needed.\nfor entry in os.scandir(os.path.dirname(root)):\n if not entry.name.startswith('run-') or entry.path==root: continue\n try:\n with open(entry.path+'/expires') as f: expired=time.time()>float(f.read())\n if expired:\n import shutil\n shutil.rmtree(entry.path,ignore_errors=True)\n except (FileNotFoundError,NotADirectoryError): pass\na=v.get('activityPath')\ntimed=False\ncode=127\ntry:\n if a:\n os.makedirs(os.path.dirname(a),exist_ok=True)\n with open(a,'w') as f: f.write('1')\n try:\n with open('/var/lib/sandbox-sdk-env.json') as f:\n import json\n saved=json.load(f)\n except FileNotFoundError: saved={}\n if os.environ.get('SANDBOX_SDK_BOOTSTRAP') not in (None,'{}'):\n bootstrap=os.environ.pop('SANDBOX_SDK_BOOTSTRAP')\n if bootstrap=='{\"env\":{}}': initial={}\n else:\n import json\n initial=json.loads(bootstrap).get('env')\n if initial is not None: saved=initial\n if initial is not None and (initial or os.path.exists('/var/lib/sandbox-sdk-env.json')):\n import json\n os.makedirs(os.path.dirname('/var/lib/sandbox-sdk-env.json'),exist_ok=True)\n tmp='/var/lib/sandbox-sdk-env.json.'+str(os.getpid())\n fd=os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)\n with os.fdopen(fd,'w') as f: json.dump(saved,f)\n os.replace(tmp,'/var/lib/sandbox-sdk-env.json')\n env={**os.environ,**saved,**v['env']}\n with stdin_file() as f, open(root+'/out','wb',buffering=0) as out:\n f.write(v.get('stdin','').encode()); f.seek(0)\n with open(root+'/lock','w') as lock:\n fcntl.flock(lock,fcntl.LOCK_EX)\n if os.path.exists(root+'/cancelled'): timed=True; p=None\n else:\n try: p=Process(v,env,f,True)\n except OSError as e:\n out.write(('[\"stderr\",\"'+str(e).encode().hex()+'\"]\\n').encode()); p=None\n if p:\n with open(root+'/pid','w') as m: m.write(str(p.pid))\n if p:\n stdout=p.stdout.fileno(); streams={stdout:'stdout',p.stderr.fileno():'stderr'}\n end=time.monotonic()+v['timeoutMs']/1000\n while streams or p.poll() is None:\n if not timed and time.monotonic()>=end:\n timed=True\n try: os.killpg(p.pid,signal.SIGKILL)\n except ProcessLookupError: pass\n for fd in select.select(list(streams),[],[],.01)[0]:\n data=os.read(fd,8192)\n if data: out.write(('[\"'+streams[fd]+'\",\"'+data.hex()+'\"]\\n').encode())\n else: del streams[fd]; (p.stdout if fd==stdout else p.stderr).close()\n code=p.wait()\n timed=timed or os.path.exists(root+'/cancelled')\n result='{\"exitCode\":%s,\"timedOut\":%s}'%('null' if timed else str(code if code>=0 else 128-code),str(timed).lower())\n with open(root+'/exit','w') as f: f.write(result)\n size=os.path.getsize(root+'/out')\n with open(root+'/out','rb') as f:\n chunks=[line.decode().strip() for _,line in zip(range(3),f)]\n offset=f.tell()\n if offset==size and not timed:\n with open(root+'/expires','w') as f: f.write(str(time.time()+v['timeoutMs']/1000+5))\n if timed and not p:\n import shutil\n shutil.rmtree(root)\n print('{\"result\":%s,\"chunks\":[%s],\"offset\":%d,\"size\":%d}'%(result,','.join(chunks),offset,size))\nfinally:\n if a:\n try: os.unlink(a)\n except FileNotFoundError: pass\n";
|
|
4
|
+
export interface ExecutionGuest extends PagedGuest {
|
|
5
5
|
exec(command: string, stdin: string, timeoutMs: number, signal?: AbortSignal): Promise<string>;
|
|
6
6
|
run?(command: string, env: Record<string, string>, timeoutMs: number, signal?: AbortSignal): Promise<string>;
|
|
7
|
-
raw(command: string): Promise<string>;
|
|
8
|
-
read(path: string, range: {
|
|
9
|
-
offset: number;
|
|
10
|
-
length: number;
|
|
11
|
-
}, signal?: AbortSignal): Promise<Uint8Array>;
|
|
12
7
|
}
|
|
13
8
|
export declare function execute(g: ExecutionGuest, input: ExecInput): Promise<ExecResult>;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
/** @superserve/sdk 0.11.4; https://docs.superserve.ai/sdk-reference/sandbox */
|
|
2
|
-
import type { Sandbox } from "@superserve/sdk";
|
|
3
1
|
import type { Provider } from "../../provider.js";
|
|
2
|
+
import { type NativeApi } from "../../native.js";
|
|
4
3
|
export interface SuperserveOptions {
|
|
5
4
|
/** Defaults to SUPERSERVE_API_KEY; required on first use. */
|
|
6
5
|
apiKey?: string;
|
|
@@ -18,6 +17,36 @@ export interface SuperserveOptions {
|
|
|
18
17
|
installPython?: boolean;
|
|
19
18
|
/** Native request deadline. Default: 90 s. */
|
|
20
19
|
requestTimeoutMs?: number;
|
|
20
|
+
/** Auto-pause after this much active time per session, re-armed on resume. Rounded up to whole seconds. Default: never. */
|
|
21
|
+
autoPauseMs?: number;
|
|
22
|
+
/** Delete the sandbox once it has been paused this long; `0` deletes it as soon as it pauses. Rounded up to whole seconds. Default: never. */
|
|
23
|
+
autoDeleteMs?: number;
|
|
24
|
+
/** Bind stored Superserve secrets to env vars: `{ ENV_VAR: secretName }`. The sandbox sees a proxy token; the real value is attached at egress. */
|
|
25
|
+
secretBindings?: Record<string, string>;
|
|
26
|
+
/** Access for preview ports. `private` returns a token header with each preview; `public` URLs need none. Default: `private`. */
|
|
27
|
+
previewAccess?: "private" | "public";
|
|
21
28
|
}
|
|
22
|
-
|
|
29
|
+
/** `api` is the control plane (the default); `data` is exec and files inside the sandbox. */
|
|
30
|
+
export type SuperservePlane = "api" | "data";
|
|
31
|
+
/** What `native.sdk(load)` needs from `@superserve/sdk`: its `Sandbox` class. */
|
|
32
|
+
export interface SuperserveModule {
|
|
33
|
+
Sandbox: {
|
|
34
|
+
connect(sandboxId: string, options?: {
|
|
35
|
+
apiKey?: string;
|
|
36
|
+
baseUrl?: string;
|
|
37
|
+
}): Promise<object>;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** `box.native.sdk(() => import("@superserve/sdk"))`: the SDK's `Sandbox` for this sandbox, from `Sandbox.connect`. */
|
|
41
|
+
export type SuperserveSandboxSdk = <M extends SuperserveModule>(load: () => Promise<M>) => Promise<Awaited<ReturnType<M["Sandbox"]["connect"]>>>;
|
|
42
|
+
/** `provider.api.sdk(() => import("@superserve/sdk"))`: the SDK's `Sandbox` class, whose static methods take `{ apiKey }`. */
|
|
43
|
+
export type SuperserveAccountSdk = <M extends SuperserveModule>(load: () => Promise<M>) => Promise<M["Sandbox"]>;
|
|
44
|
+
/** `box.native`. `{sandboxId}` in a path fills from the sandbox. */
|
|
45
|
+
export type SuperserveNative = NativeApi<SuperservePlane, SuperserveSandboxSdk>;
|
|
46
|
+
/** `provider.api`: the same API with no sandbox bound, so only the `api` plane. Use `box.native` for the `data` plane. */
|
|
47
|
+
export type SuperserveApi = NativeApi<SuperservePlane, SuperserveAccountSdk>;
|
|
48
|
+
export type SuperserveProvider = Provider<SuperserveNative, "pause" | "snapshot" | "network-policy"> & {
|
|
49
|
+
/** Account-level calls: `provider.api.request("GET", "/sandboxes")`. */
|
|
50
|
+
readonly api: SuperserveApi;
|
|
51
|
+
};
|
|
23
52
|
export declare function superserve(options?: SuperserveOptions): SuperserveProvider;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
2
|
-
${
|
|
1
|
+
import{U}from"../../chunk-hzbssbep.js";import{T}from"../../chunk-8786zrns.js";import{p,b,R}from"../../chunk-x681p5d2.js";import{m}from"../../chunk-bd481sb7.js";import{d,y,H,x,_,h,k}from"../../chunk-vy1j4r8f.js";import{f}from"../../chunk-9w9rddra.js";import{n}from"../../chunk-2ts3evzh.js";import{t,o,r,e,i,c,a,s}from"../../chunk-xgxfy2n8.js";function A(l,v="provider",S,P){return new e(v==="auth"?l:`${l}. Check superserve configuration and retry.`,{code:v,provider:"superserve",sandboxId:S,cause:P})}var Fe=new Map([[400,"invalid_argument"],[401,"auth"],[403,"auth"],[404,"not_found"],[408,"timeout"],[409,"unavailable"],[422,"invalid_argument"],[429,"quota"],[500,"unavailable"],[502,"unavailable"],[503,"unavailable"],[504,"timeout"]]),Je=new Map([["AuthenticationError","auth"],["NotFoundError","not_found"],["ValidationError","invalid_argument"],["TimeoutError","timeout"],["AbortError","aborted"],["ConflictError","unavailable"]]);function se(l,v){if(l instanceof e)return l;let S=m(l),P=S.statusCode,L=P===void 0?Je.get(S.name)??"provider":Fe.get(P)??"provider",B=i(l,{code:L,status:P===void 0?void 0:`HTTP ${P}`,redact:c([process.env.SUPERSERVE_API_KEY])});return A(`Superserve request failed: ${a(L,B.detail)}`,L,v,B.cause)}var ke=`import os,sys,marshal,_signal as signal,select,time,fcntl
|
|
2
|
+
${b}
|
|
3
3
|
root=sys.argv[1]
|
|
4
4
|
v=marshal.loads(bytes.fromhex(sys.argv[2])) if len(sys.argv)>2 else marshal.loads(bytes.fromhex(sys.stdin.read()))
|
|
5
5
|
if 'envKeys' in v: v['env']={k:os.environ[k] for k in v['envKeys']}
|
|
@@ -82,45 +82,13 @@ finally:
|
|
|
82
82
|
if a:
|
|
83
83
|
try: os.unlink(a)
|
|
84
84
|
except FileNotFoundError: pass
|
|
85
|
-
`;async function
|
|
86
|
-
root=sys.argv[1]
|
|
87
|
-
os.makedirs(root,mode=0o700,exist_ok=True)
|
|
88
|
-
with open(root+'/lock','w') as lock:
|
|
89
|
-
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
90
|
-
with open(root+'/cancelled','w') as f: f.write('1')
|
|
91
|
-
try:
|
|
92
|
-
with open(root+'/pid') as f: pid=int(f.read())
|
|
93
|
-
except FileNotFoundError: pid=None
|
|
94
|
-
if pid and not os.path.exists(root+'/exit'):
|
|
95
|
-
try: os.killpg(pid,signal.SIGKILL)
|
|
96
|
-
except ProcessLookupError: pass
|
|
97
|
-
# Wait for reaping and pipe drainage before recovering the bounded output tail.
|
|
98
|
-
end=time.monotonic()+2
|
|
99
|
-
while pid and not os.path.exists(root+'/exit') and time.monotonic()<end: time.sleep(.01)
|
|
100
|
-
if pid and not os.path.exists(root+'/exit'): sys.exit(1)
|
|
101
|
-
chunks=[]
|
|
102
|
-
start=int(sys.argv[2])
|
|
103
|
-
try:
|
|
104
|
-
with open(root+'/out','rb') as f:
|
|
105
|
-
size=os.fstat(f.fileno()).st_size
|
|
106
|
-
delivered=int(sys.argv[2])
|
|
107
|
-
start=max(delivered,size-65536); f.seek(start)
|
|
108
|
-
if start>delivered: f.readline(); start=f.tell()
|
|
109
|
-
chunks=[json.loads(line) for line in f]
|
|
110
|
-
except FileNotFoundError: pass
|
|
111
|
-
print(json.dumps(dict(chunks=chunks,offset=start)))
|
|
112
|
-
# Retain a tombstone if a delayed supervisor can still arrive.
|
|
113
|
-
if pid: shutil.rmtree(root,ignore_errors=True)`,p,String(E))),s=JSON.parse(x);if(!s||typeof s!=="object"||!("chunks"in s)||!Array.isArray(s.chunks)||s.chunks.length>65536||!("offset"in s)||typeof s.offset!=="number"||!Number.isSafeInteger(s.offset)||s.offset<E)throw f("Invalid cancellation output");if(s.offset!==E)z(v,u);for(let N of s.chunks)q(N,v,u);z(v,u)}let R=!1;async function T(){try{await k()}catch{throw f("Process cancellation could not be confirmed","outcome_unknown")}return R=!1,{exitCode:null,timedOut:!0}}try{let x;try{let w={command:u.command,cwd:u.cwd,timeoutMs:u.timeoutMs,activityPath:u.activityPath},t=m({...w,envKeys:Object.keys(u.env)}).toString("hex"),r=`python3 -S -c ${a(B)} ${a(p)} ${a(t)}`;if(i.run&&u.stdin===void 0&&Buffer.byteLength(r)<98304)x=await i.run(r,u.env,u.timeoutMs+5000,P);else x=await i.exec(`python3 -S -c ${a(B)} ${a(p)}`,m({...w,env:u.env,stdin:u.stdin??""}).toString("hex"),u.timeoutMs+5000,P)}catch(w){if(w instanceof e&&w.code==="unsupported")throw w;try{await k()}catch{throw f("Process cancellation could not be confirmed","outcome_unknown")}if(P.aborted)return{exitCode:null,timedOut:!0};throw w}let s=JSON.parse(x);if(!s||typeof s!=="object"||!("result"in s)||!s.result||typeof s.result!=="object"||!("exitCode"in s.result)||s.result.exitCode!==null&&typeof s.result.exitCode!=="number"||!("timedOut"in s.result)||typeof s.result.timedOut!=="boolean"||!("chunks"in s)||!Array.isArray(s.chunks)||s.chunks.length>3||!("offset"in s)||typeof s.offset!=="number"||!Number.isSafeInteger(s.offset)||s.offset<0||!("size"in s)||typeof s.size!=="number"||!Number.isSafeInteger(s.size)||s.size<s.offset)throw f("Invalid command response");let N=(w)=>q(w,v,u);if(R=s.offset<s.size||s.result.timedOut,P.aborted)return await T();s.chunks.forEach(N),E=s.offset;let A=s.offset,I="";while(A<s.size){if(P.aborted)return await T();let w;try{w=await i.read(p+"/out",{offset:A,length:Math.min(65536,s.size-A)},P)}catch(r){if(P.aborted)return await T();throw r}if(P.aborted)return await T();if(!w.length)throw f("Incomplete output read");A+=w.length,I+=new TextDecoder().decode(w);let t=I.split(`
|
|
114
|
-
`);I=t.pop()??"",t.forEach((r)=>{N(JSON.parse(r)),E+=Buffer.byteLength(r)+1})}if(I)throw f("Incomplete output record");return z(v,u),{exitCode:s.result.exitCode,timedOut:s.result.timedOut}}finally{if(clearTimeout(S),R)await i.raw(`rm -rf -- ${a(p)}`).catch(()=>{})}}function q(i,u,p){if(!Array.isArray(i)||i[0]!=="stdout"&&i[0]!=="stderr"||typeof i[1]!=="string"||i[1].length>21848)throw f("Invalid output record");let b=i[0]==="stdout"?"stdout":"stderr",S=u[b].decode(Buffer.from(i[1],"hex"),{stream:!0});if(S)p.onChunk({stream:b,text:S})}function z(i,u){for(let p of["stdout","stderr"]){let b=i[p].decode();if(b)u.onChunk({stream:p,text:b})}}var Y=n(`import os,json,shutil,sys,tempfile
|
|
85
|
+
`;async function Pe(l,v){return U({guest:l,input:v,fail:(S,P)=>A(S,P),launch:(S,P)=>{let L={command:v.command,cwd:v.cwd,timeoutMs:v.timeoutMs,activityPath:v.activityPath},B=T({...L,envKeys:Object.keys(v.env)}).toString("hex"),D=`python3 -S -c ${n(ke)} ${n(S)} ${n(B)}`;if(l.run&&v.stdin===void 0&&Buffer.byteLength(D)<98304)return l.run(D,v.env,v.timeoutMs+5000,P);return l.exec(`python3 -S -c ${n(ke)} ${n(S)}`,T({...L,env:v.env,stdin:v.stdin??""}).toString("hex"),v.timeoutMs+5000,P)}})}var Ve=p(`import os,json,shutil,sys,tempfile
|
|
115
86
|
v=json.loads(os.environ.pop('SANDBOX_SDK_BOOTSTRAP'))
|
|
116
87
|
if any(shutil.which(tool) is None for tool in ('git','tar','nohup')): sys.exit(79)
|
|
117
88
|
os.makedirs('/workspace',exist_ok=True)
|
|
118
89
|
os.makedirs('/tmp/.sandbox-sdk',exist_ok=True)
|
|
119
|
-
os.makedirs(os.path.dirname('
|
|
90
|
+
os.makedirs(os.path.dirname('/var/lib/sandbox-sdk-env.json'),exist_ok=True)
|
|
120
91
|
if v.get('env') is not None:
|
|
121
92
|
with tempfile.NamedTemporaryFile(mode='w',dir=os.path.dirname('/var/lib/sandbox-sdk-env.json'),delete=False) as f:
|
|
122
93
|
json.dump(v['env'],f)
|
|
123
|
-
os.replace(f.name,'/var/lib/sandbox-sdk-env.json')
|
|
124
|
-
if v.get('supervisor') is not None:
|
|
125
|
-
with tempfile.NamedTemporaryFile(mode='w',dir=os.path.dirname('/var/lib/sandbox-sdk-env.json'),delete=False) as f: f.write(v['supervisor'])
|
|
126
|
-
os.replace(f.name,'${U}')`);function X(i){let u=i.installPython===!0?"export DEBIAN_FRONTEND=noninteractive; apt-get update -qq && apt-get install -y -qq python3 python3-venv python3-pip >/dev/null || exit 1":"exit 78";if(i.execution)return{command:`if ! command -v python3 >/dev/null 2>&1; then ${u}; fi; command -v git tar nohup >/dev/null || exit 79; mkdir -p /workspace /tmp/.sandbox-sdk`,env:{SANDBOX_SDK_BOOTSTRAP:JSON.stringify({env:i.env})}};return{command:`if ! command -v python3 >/dev/null 2>&1; then ${u}; fi; ${Y}`,env:{SANDBOX_SDK_BOOTSTRAP:JSON.stringify({env:i.env,supervisor:i.execution?B:void 0})}}}function L(i,u){if(i===78)throw f("Template lacks python3; use a template with Python 3 or explicitly set installPython: true to allow apt installation","unsupported",u);if(i===79)throw f("Template must include git, tar and nohup","unsupported",u)}function pe(i={}){let u=new Map,p=new Map,b=new Set,S=new Set,P=new Map,E=()=>{let t=i.apiKey??process.env.SUPERSERVE_API_KEY;if(!t?.trim())throw f("Superserve API key is missing. Authentication is required. Set SUPERSERVE_API_KEY or pass apiKey.","auth");return{apiKey:t,baseUrl:i.baseUrl}},v=i.requestTimeoutMs??90000;async function k(t,r){try{return await r()}catch(c){throw K(c,t)}}let R;async function T(){return E(),R??=o("@superserve/sdk","superserve",()=>import("@superserve/sdk"))}async function x(t){let r=u.get(t);if(!r)r=await(await T()).Sandbox.connect(t,{...E(),signal:AbortSignal.timeout(v)}),u.set(t,r);return r}function s(t){if(t.metadata["sandbox-sdk"]!=="1")throw f("Not an SDK sandbox","not_found",t.id);let r={};for(let[c,l]of Object.entries(t.metadata))if(c.startsWith("label:"))r[c.slice(6)]=l;return{id:t.id,key:t.metadata["sdk-key"],labels:r,createdAt:t.createdAt.getTime(),state:t.status==="active"?"running":["paused","pausing"].includes(t.status)?"paused":"stopped"}}function N(t,r,c){if(c?S.has(t):b.has(t))return{command:r,env:{}};let l=X({env:p.get(t),installPython:i.installPython,execution:c});return{command:`${l.command} && ${r}`,env:l.env}}async function A(t,r,c,l=!1){let y=N(t,r,l),g=await(await x(t)).commands.run(y.command,{...c,env:{...c.env,...y.env}});if(L(g.exitCode,t),g.exitCode===0){if(b.add(t),l)S.add(t)}return g}async function I(t){let r=await x(t);return{name:"superserve",raw:async(c)=>{let l=await A(t,c,{timeoutMs:v});if(l.exitCode!==0)throw f("Guest operation failed","provider",t);return l.stdout},upload:async(c,l)=>r.files.write(c,l,{timeoutMs:v}),read:async(c,l)=>{try{if(l){let y=await A(t,n("import sys,base64; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(int(sys.argv[3]))).decode())",c,String(l.offset),String(l.length)),{timeoutMs:v});if(y.exitCode!==0)throw f("File range read failed","file_not_found",t);return new Uint8Array(Buffer.from(y.stdout.trim(),"base64"))}return await r.files.read(c,{timeoutMs:v})}catch(y){if(K(y).code==="not_found")throw f("File does not exist","file_not_found",t);throw y}}}}let w={name:"superserve",keyMode:"best-effort",inlineActivity:!0,capabilities:new Set(["pause","snapshot"]),create:(t)=>k(void 0,async()=>{if(t.size!==void 0||t.idleTimeoutMs!==void 0||t.timeoutMs!==void 0||t.network&&t.network!=="all")throw f("Template resources cannot be overridden; SDK idle/lifetime limits and network restrictions are not implemented","unsupported");if(!Number.isSafeInteger(v)||v<=0)throw f("requestTimeoutMs must be a positive integer","invalid_argument");if(t.signal?.aborted)throw f("Creation aborted","aborted");let r={"sandbox-sdk":"1",...t.key!==void 0?{"sdk-key":t.key}:{}};for(let[g,_]of Object.entries(t.labels))r[`label:${g}`]=_;let c=Date.now(),l,y=await T();try{l=await y.Sandbox.create({...E(),name:`sbxsdk-${crypto.randomUUID()}`,metadata:r,envVars:t.env,previewAccess:"private",...t.from?{fromSnapshot:t.from}:{fromTemplate:i.template??"superserve/node-22"},signal:AbortSignal.timeout(v)})}catch(g){let _=K(g);if(["timeout","unavailable","aborted"].includes(_.code))throw f("Creation outcome unknown; inspect SDK-labelled sandboxes before retrying","outcome_unknown");throw _}u.set(l.id,l);try{if(t.signal?.aborted)throw f("Creation aborted","aborted");if(p.set(l.id,{...t.env}),t.from){if((await l.getInfo()).timeoutSeconds!==void 0)await l.update({timeoutSeconds:null})}return{id:l.id,key:t.key,labels:{...t.labels,"sandbox-sdk":"1"},createdAt:c,state:"running"}}catch(g){throw await w.destroy(l.id),g}}),list:(t)=>k(void 0,async()=>(await(await T()).Sandbox.list({...E(),metadata:{"sandbox-sdk":"1"},signal:AbortSignal.timeout(v)})).filter((c)=>c.status!=="deleted").map(s).filter((c)=>Object.entries(t).every(([l,y])=>c.labels[l]===y))),async find(t){let r=(await w.list({})).find((c)=>c.key===t);return r?w.connect(r.id):void 0},connect:(t)=>k(t,async()=>s(await(await x(t)).getInfo())),destroy(t){let r=P.get(t);if(!r)r=k(t,async()=>{await(await T()).Sandbox.killById(t,{...E(),signal:AbortSignal.timeout(v)}),u.delete(t),p.delete(t),S.delete(t),b.delete(t)}),P.set(t,r),r.finally(()=>P.delete(t)).catch(()=>{});return r},async close(t){u.delete(t),p.delete(t),S.delete(t),b.delete(t)},exec:(t,r)=>k(t,async()=>{let c=await x(t),l=await I(t);return G({raw:l.raw,read:async(y,g)=>{let _=await l.raw(n("import sys,base64; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(int(sys.argv[3]))).decode())",y,String(g.offset),String(g.length)));return new Uint8Array(Buffer.from(_.trim(),"base64"))},run:async(y,g,_,O)=>{if(O?.aborted)throw f("Command interrupted","aborted",t);let M=()=>{},j=new Promise((D,C)=>{M=()=>C(f("Command interrupted","aborted",t))});O?.addEventListener("abort",M,{once:!0});try{let D=A(t,y,{env:g,timeoutMs:_},!0),C=await Promise.race([D,j]);if(C.exitCode!==0||C.truncated)throw f("Supervisor failed","provider",t);return C.stdout}finally{O?.removeEventListener("abort",M)}},exec:async(y,g,_,O)=>{let M=N(t,y,!0),j=await c.commands.spawn(M.command,{env:M.env,startupSignal:O,timeoutMs:_}),D=()=>{},C=!1;try{j.stdin.write(g),j.stdin.close();let J=new Promise((H,W)=>{D=()=>{W(f("Command interrupted","aborted",t))}});if(O?.addEventListener("abort",D,{once:!0}),O?.aborted)D();let V=j.wait().finally(()=>j.close());C=!0;let F=await Promise.race([V,J]);if(L(F.exitCode,t),F.exitCode!==0)throw f("Supervisor failed","provider",t);return S.add(t),b.add(t),F.stdout}finally{if(O?.removeEventListener("abort",D),!C)await j.close()}}},r)}),files:h(I,k),previewUrl:(t,r)=>k(t,async()=>{let c=await x(t);await c.publishPreviewPort(r,{access:"private"});let l=await c.getPreviewToken(r);return{url:c.getPreviewUrl(r),headers:{[l.header]:l.token},...l.expiresAt?{expiresAt:l.expiresAt.getTime()}:{}}}),pause:(t)=>k(t,async()=>{await(await x(t)).pause({wait:!0,timeoutMs:v})}),resume:(t)=>k(t,async()=>{await(await x(t)).resume({timeoutMs:v})}),snapshot:(t)=>k(t,async()=>{let r=`sbxsdk-${crypto.randomUUID()}`;try{return{id:(await(await x(t)).snapshot({name:r,idempotencyKey:r,timeoutMs:v})).id}}catch{throw f(`Snapshot outcome unknown; recover snapshot named ${r} from source ${t}`,"outcome_unknown",t)}}),native(t){let r=u.get(t);if(!r)throw f("Connect the sandbox first","not_found",t);return r}};return w}export{pe as superserve};
|
|
94
|
+
os.replace(f.name,'/var/lib/sandbox-sdk-env.json')`);function Ee(l){let v=l.installPython===!0?"export DEBIAN_FRONTEND=noninteractive; apt-get update -qq && apt-get install -y -qq python3 python3-venv python3-pip >/dev/null || exit 1":"exit 78";if(l.execution)return{command:`if ! command -v python3 >/dev/null 2>&1; then ${v}; fi; command -v git tar nohup >/dev/null || exit 79; mkdir -p /workspace /tmp/.sandbox-sdk`,env:{SANDBOX_SDK_BOOTSTRAP:JSON.stringify({env:l.env})}};return{command:`if ! command -v python3 >/dev/null 2>&1; then ${v}; fi; ${Ve}`,env:{SANDBOX_SDK_BOOTSTRAP:JSON.stringify({env:l.env})}}}function le(l,v){if(l===78)throw A("Template lacks python3; use a template with Python 3 or explicitly set installPython: true to allow apt installation","unsupported",v);if(l===79)throw A("Template must include git, tar and nohup","unsupported",v)}var ze="https://api.superserve.ai",Re="sandbox.superserve.ai",Oe=new Map([["use",{baseUrl:"https://api.superserve.ai",sandboxHost:"sandbox.superserve.ai"}],["usw",{baseUrl:"https://api-usw.superserve.ai",sandboxHost:"usw-sandbox.superserve.ai"}]]),Ge=/^ss_live_([a-z0-9]{1,17})_[A-Za-z0-9_-]{32}$/,We=new Set(["sandbox.superserve.ai","staging-sandbox.superserve.ai","usw-sandbox.superserve.ai"]);function Xe(l){try{let v=new URL(l).hostname;if(v==="api-staging.superserve.ai")return"staging-sandbox.superserve.ai";for(let S of Oe.values())if(new URL(S.baseUrl).hostname===v)return S.sandboxHost}catch{}return Re}function Ae(l){let v=l.apiKey??process.env.SUPERSERVE_API_KEY;if(!v?.trim())throw A("Superserve API key is missing. Authentication is required. Set SUPERSERVE_API_KEY or pass apiKey.","auth");let S=(l.baseUrl??process.env.SUPERSERVE_BASE_URL)?.trim()||void 0;if(S!==void 0)return{apiKey:v,baseUrl:S,sandboxHost:Xe(S)};let P=Oe.get(Ge.exec(v)?.[1]??"");return{apiKey:v,baseUrl:P?.baseUrl??ze,sandboxHost:P?.sandboxHost??Re}}var Ze="X-Superserve-Sandbox-Id",pe="X-Superserve-Routing-Hint",Ie="X-Access-Token";function fe(l,v){let S=v.toLowerCase();return We.has(S)?{url:`https://${S}`,headers:{[Ze]:l}}:{url:`https://boxd-${l}.${S}`,headers:{}}}function Me(l,v){return`wss://boxd-${l}.${v.toLowerCase()}/exec/connect`}function Te(l,v,S){if(!Number.isInteger(S)||S<1024||S>65535||S===49983)throw A(S===49983?"Preview port 49983 is reserved for sandbox control traffic":"Preview ports must be integers from 1024 to 65535","invalid_argument");return`https://${S}-${l}.${v}`}function Ye(l){try{let v=JSON.parse(atob((l.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"))),S=r(v)?"e"in v?v.e:void 0:void 0;return o(S)&&Number.isFinite(S)?S*1000:void 0}catch{return}}function _e(l,v,S){let P=r(l)?"access_token"in l?l.access_token:void 0:void 0,L=r(l)?"routing_hint"in l?l.routing_hint:void 0:void 0;if(!t(P)||!P)throw A(`Superserve ${S} returned no access token`,"provider",v);let B={token:P};if(t(L)&&L)B.hint=L;return B}function Qe(l,v){if(!v)return l;return new Promise((S,P)=>{let L=()=>P(Error("Superserve route activation abandoned by its caller"));if(v.aborted)return L();v.addEventListener("abort",L,{once:!0}),l.then(S,P).finally(()=>v.removeEventListener("abort",L))})}function Ne(l){let v=l.refreshBeforeMs??30000,S=new Map,P=(O)=>{let N=S.get(O);if(!N)S.set(O,N={issued:0});return N};function L(O,N,C){if(!O.current||N>O.current.revision)O.current={...C,revision:N};return O.current}async function B(O,N,C){let F=++N.issued;return L(N,F,_e(await l.rotate(O,C),O,`POST /sandboxes/{id}/${C}`))}function D(O,N){let C=P(O);if(!C.activating){let F=B(O,C,"activate"),q=()=>{if(C.activating===F)C.activating=void 0};F.then(q,q),C.activating=F}return Qe(C.activating,N)}let J=(O)=>{let N=O.hint===void 0?void 0:Ye(O.hint);return N!==void 0&&N-Date.now()<=v};return{async current(O,N){let C=S.get(O)?.current;return C&&!J(C)?C:D(O,N)},async refresh(O,N,C){let F=S.get(O)?.current;if(F&&N!==void 0&&F.revision>N&&!J(F))return F;return D(O,C)},activate:D,resume:(O)=>{let N=P(O);return B(O,N,"resume")},seed(O,N){let C=P(O);return L(C,++C.issued,_e(N,O,"POST /sandboxes"))},forget:(O)=>{S.delete(O)},secrets:()=>[...S.values()].flatMap((O)=>O.current?[O.current.token,...O.current.hint?[O.current.hint]:[]]:[])}}var et="superserve.exec.v1",Ce=32768,$e=10485760,tt=new TextEncoder,ne=(l)=>A("Command startup aborted","aborted",l);async function Ue(l){if(typeof WebSocket>"u")throw A("Superserve commands with stdin need a global WebSocket (Node 22 or later, or Bun)","unsupported",l.sandboxId);let v=l.startupSignal;if(v?.aborted)throw ne(l.sandboxId);let S=await l.route(v),P;try{P=await je(l,S)}catch{if(v?.aborted)throw ne(l.sandboxId);S=await l.refresh(S,v),P=await je(l,S)}if(v?.aborted)throw P.close(),ne(l.sandboxId);return P.send(JSON.stringify({command:l.command,...l.env===void 0?void 0:{env:l.env},...l.timeoutMs===void 0?void 0:{timeout_s:Math.ceil(l.timeoutMs/1000)}})),nt(P,l)}function je(l,v){let{sandboxId:S,startupSignal:P}=l;return new Promise((L,B)=>{if(P?.aborted)return B(ne(S));let D=new WebSocket(l.url,[et,`token.${v.token}`,...v.hint?[`route.${v.hint}`]:[]]);D.binaryType="arraybuffer";let J=()=>{D.removeEventListener("open",O),D.removeEventListener("error",N),D.removeEventListener("close",C),P?.removeEventListener("abort",F)},O=()=>{J(),L(D)},N=()=>{J(),B(A("Superserve exec/connect could not open the connection","unavailable",S))},C=(q)=>{J(),B(A(`Superserve exec/connect closed before it opened (code ${q.code})`,"unavailable",S))},F=()=>{J(),D.addEventListener("error",()=>{}),D.close(),B(ne(S))};D.addEventListener("open",O),D.addEventListener("error",N),D.addEventListener("close",C),P?.addEventListener("abort",F,{once:!0})})}function nt(l,v){let S={stdout:new TextDecoder,stderr:new TextDecoder},P={stdout:"",stderr:""},L=0,B,D=new Promise((q,G)=>{B={resolve:q,reject:G}});D.catch(()=>{});let J=()=>{P.stdout+=S.stdout.decode(),P.stderr+=S.stderr.decode()},O=(q)=>{let G=B;B=void 0,J(),G?.resolve({exitCode:q,...P})},N=(q)=>{let G=B;if(B=void 0,J(),G?.reject(q),l.readyState<=WebSocket.OPEN)l.close()},C=()=>l.readyState===WebSocket.OPEN;l.addEventListener("message",(q)=>{if(t(q.data)){let K;try{K=JSON.parse(q.data)}catch{return}if(!r(K)||K===null)return;let X="error"in K?K.error:void 0;if(t(X))P.stderr+=X;if(("finished"in K?K.finished:void 0)===!0){let Z="exit_code"in K?K.exit_code:void 0;O(o(Z)?Z:0)}return}if(!(q.data instanceof ArrayBuffer))return;let G=new Uint8Array(q.data);if(!G.length)return;if(L+=G.length,L>$e)return N(A(`Superserve exec/connect sent more than ${$e} bytes of output`,"unsupported",v.sandboxId));let W=G[0]===1?"stdout":G[0]===2?"stderr":void 0;if(W)P[W]+=S[W].decode(G.subarray(1),{stream:!0})}),l.addEventListener("close",(q)=>{let G=q.code===1009?"a frame exceeded the server's size limit":q.reason?v.redact(q.reason).slice(0,200):`close code ${q.code}`;N(A(`Superserve exec/connect closed before the command finished (${G})`,"provider",v.sandboxId))}),l.addEventListener("error",()=>N(A("Superserve exec/connect failed before the command finished","provider",v.sandboxId)));let F=()=>{if(C())l.send(JSON.stringify({type:"signal",name:"SIGTERM"}))};return{stdin:{write(q){if(!C())return;let G=t(q)?tt.encode(q):q;for(let W=0;W<G.length;W+=Ce){let K=G.subarray(W,W+Ce),X=new Uint8Array(K.length+1);X.set(K,1),l.send(X)}},close(){if(C())l.send(JSON.stringify({type:"stdin_close"}))}},wait:()=>D,async close(){F(),N(A("Superserve exec/connect session closed by the client","aborted",v.sandboxId)),await D.then(()=>{},()=>{})}}}var rt=["1.1.1.1/32","8.8.8.8/32"],me=(l)=>/^\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?$/.test(l);function st(l){if(l===void 0||l==="all")return;if(l==="none")return{allowOut:[],denyOut:["0.0.0.0/0"]};for(let P of l.allow)if(!me(P)&&!/^(\*\.)?(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(P))throw A("Network allow entries must be hostnames, *.wildcards, IPv4 addresses or IPv4 CIDRs","unsupported");let v=l.allow.map((P)=>me(P)&&!P.includes("/")?`${P}/32`:P),S=v.some((P)=>!me(P));return{allowOut:[...new Set([...v,...S?rt:[]])],denyOut:["0.0.0.0/0"]}}function ot(l,v){let S=(P=[],L=[])=>P.length===L.length&&P.every((B)=>L.includes(B));return S(l.allowOut,v?.allowOut)&&S(l.denyOut,v?.denyOut)}var Be=(l,v,S)=>{if(l===void 0)return;if(!Number.isSafeInteger(l)||l<0||!S&&l===0)throw A(`${v} must be a ${S?"non-negative":"positive"} integer of milliseconds`,"invalid_argument");return Math.ceil(l/1000)},z=(l,v)=>f(l)?l[v]:void 0,De=(l)=>Array.isArray(l)&&l.every((v)=>t(v))?l:void 0;function oe(l,v){let S=z(l,"id"),P=z(l,"status"),L=z(l,"created_at");if(!t(S)||!S||!t(P)||!P||!t(L))throw A("Superserve returned a sandbox without id, status or created_at","provider",v);let B={},D=z(l,"metadata");if(r(D)){for(let[N,C]of Object.entries(D))if(t(C))B[N]=C}let J=z(l,"timeout_seconds"),O=z(l,"network");return{id:S,status:P,metadata:B,createdAt:Date.parse(L),...o(J)?{timeoutSeconds:J}:void 0,...r(O)?{network:{allowOut:De(z(O,"allow_out")),denyOut:De(z(O,"deny_out"))}}:void 0}}var at=10485760,it=2147483648,dt=30000,Le=1000,ut=50,Ke=2000,ct=1000,lt=2000,pt=11,ae="@superserve/sdk",ft=(l)=>new Promise((v)=>setTimeout(v,l));function Ft(l={}){let v=new Map,S=new Set,P=new Set,L=new Map,B=new Map,D=()=>Ae(l),J=l.requestTimeoutMs??90000,O=Be(l.autoPauseMs,"autoPauseMs",!1),N=Be(l.autoDeleteMs,"autoDeleteMs",!0),C=l.previewAccess??"private";if(C!=="private"&&C!=="public")throw A("previewAccess must be private or public","invalid_argument");async function F(u,w){try{return await w()}catch(g){throw se(g,u)}}let q=(u)=>{if(u.sandboxId===void 0)s("The Superserve data plane needs a sandbox. Use box.native instead of provider.api");return u.sandboxId},G=new WeakMap,W=Ne({async rotate(u,w){let g={method:"POST",path:`/sandboxes/{sandboxId}/${w}`,params:{sandboxId:u},sandboxId:u,readOnly:!0},E=Date.now()+dt;for(;;)try{return await K.json(g)}catch(I){let M=H(I);if(w!=="activate"||M?.status!==409||M.code!=="sandbox_pausing"||E-Date.now()<=Le)throw I;await ft(Le)}}}),K=x({provider:"superserve",label:"Superserve",defaultPlane:"api",timeoutMs:J,secrets:()=>[l.apiKey,process.env.SUPERSERVE_API_KEY,...W.secrets()],authHint:"Set SUPERSERVE_API_KEY to a valid Superserve API key.",mapError:(u)=>u.kind==="status"&&u.status===409?"unavailable":void 0,planes:{api:{baseUrl:()=>D().baseUrl,auth:()=>({"X-API-Key":D().apiKey})},data:{baseUrl:(u)=>fe(q(u),D().sandboxHost).url,async auth(u){let w=q(u),g=await W.current(w,u.signal);return G.set(u,g.revision),{...fe(w,D().sandboxHost).headers,[Ie]:g.token,...g.hint?{[pe]:g.hint}:void 0}},async refresh(u){await W.refresh(q(u),G.get(u))},stale:({status:u,body:w,credentials:g})=>{if(u===404&&w.code==="sandbox_route_stale")return"refused";if(u!==503)return;if(w.code==="sandbox_unavailable"||/^sandbox is (paused|stopped)$/.test(w.text.trim()))return"refused";return g[pe]?void 0:"unsure"}}}});function X(u){let w=B.get(u);if(!w){let g=W.activate(u).then(()=>{return});w=g,B.set(u,g),g.catch(()=>{if(B.get(u)===g)B.delete(u)})}return w}let Z=(u)=>({params:{sandboxId:u},sandboxId:u}),ie=async(u)=>oe(await K.json({method:"GET",path:"/sandboxes/{sandboxId}",...Z(u)}),u);function ve(u){B.delete(u),W.forget(u),v.delete(u),P.delete(u),S.delete(u)}function be(u){if(u.metadata["sandbox-sdk"]!=="1")throw A("Not an SDK sandbox","not_found",u.id);let w={};for(let[g,E]of Object.entries(u.metadata))if(g.startsWith("label:"))w[g.slice(6)]=E;return{id:u.id,key:u.metadata["sdk-key"],labels:w,createdAt:u.createdAt,state:u.status==="active"?"running":["paused","pausing"].includes(u.status)?"paused":"stopped"}}function he(u,w,g){if(g?P.has(u):S.has(u))return{command:w,env:{}};let E=Ee({env:v.get(u),installPython:l.installPython,execution:g});return{command:`${E.command} && ${w}`,env:E.env}}async function He(u,w,g){let E=await K.json({method:"POST",path:"/exec",plane:"data",sandboxId:u,body:{command:w,...g.env===void 0?void 0:{env:g.env},timeout_s:Math.ceil(g.timeoutMs/1000)},timeoutMs:g.timeoutMs+5000,maxBytes:at}),I=z(E,"stdout"),M=z(E,"stderr"),j=z(E,"exit_code"),V=z(E,"truncated");return{stdout:t(I)?I:"",stderr:t(M)?M:"",exitCode:o(j)?j:0,truncated:V===!0}}async function de(u,w,g,E=!1){let I=he(u,w,E),M=await He(u,I.command,{...g,env:{...g.env,...I.env}});if(le(M.exitCode,u),M.exitCode===0){if(S.add(u),E)P.add(u)}return M}let ge=(u)=>{if(!u.startsWith("/")||u.split("/").includes(".."))throw A("Superserve file paths must be absolute without .. segments","invalid_argument");return u};async function xe(u){return await X(u),{name:"superserve",raw:async(w)=>{let g=await de(u,w,{timeoutMs:J});if(g.exitCode!==0)throw A("Guest operation failed","provider",u);return g.stdout},upload:async(w,g)=>{await K.request({method:"POST",path:"/files",plane:"data",sandboxId:u,query:{path:ge(w)},body:g,headers:{"content-type":"application/octet-stream"}})},read:async(w,g)=>{try{if(g){let E=await de(u,p("import sys,base64; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(int(sys.argv[3]))).decode())",w,String(g.offset),String(g.length)),{timeoutMs:J});if(E.exitCode!==0)throw A("File range read failed","file_not_found",u);return new Uint8Array(Buffer.from(E.stdout.trim(),"base64"))}return(await K.request({method:"GET",path:"/files",plane:"data",sandboxId:u,query:{path:ge(w)},maxBytes:it})).body}catch(E){if(se(E).code==="not_found")throw A("File does not exist","file_not_found",u);throw E}}}}async function we(u,w,g){let E=Date.now();for(let I=!0;;I=!1){if(!I)try{await y(Date.now()-E<Ke?ut:ct,w,"superserve")}catch{throw g()}let M;try{M=oe(await K.json({method:"GET",path:"/sandboxes/{sandboxId}",...Z(u),deadline:w}),u).status}catch(j){if(H(j)?.status===404)return;if(w.timeout.aborted)throw g();throw j}if(M==="paused"||M==="deleted")return;if(M==="active"&&Date.now()-E<Ke)continue;if(M!=="pausing")throw A(`Sandbox did not pause: its status is ${M.slice(0,32)}`,"provider",u)}}let ye=(u)=>({deadline:d(J),stillPausing:()=>A(`Sandbox is still pausing after ${J} ms; it finishes in the background`,"timeout",u)}),Se={package:ae,async connect(u,w){let g=u.Sandbox;if(!(g instanceof Function))s(`The module passed to native.sdk() has no Sandbox export. Pass () => import("${ae}")`);if(w===void 0)return g;return _(await k(g,"connect",[w,{apiKey:D().apiKey,baseUrl:l.baseUrl}],ae),"Sandbox.connect",ae)}},re={name:"superserve",keyMode:"best-effort",inlineActivity:!0,capabilities:new Set(["pause","snapshot","network-policy"]),api:h({http:K,placeholder:"sandboxId",sdk:Se}),create:(u)=>F(void 0,async()=>{if(u.size!==void 0||u.idleTimeoutMs!==void 0||u.timeoutMs!==void 0)throw A("Template resources cannot be overridden, and Superserve has no idle or hard lifetime; use autoPauseMs and autoDeleteMs","unsupported");let w=st(u.network);if(!Number.isSafeInteger(J)||J<=0)throw A("requestTimeoutMs must be a positive integer","invalid_argument");if(u.signal?.aborted)throw A("Creation aborted","aborted");D();let g=new Map([["sandbox-sdk","1"]]);if(u.key!==void 0)g.set("sdk-key",u.key);for(let[j,V]of Object.entries(u.labels))g.set(`label:${j}`,V);let E=Date.now(),I;try{I=await K.json({method:"POST",path:"/sandboxes",body:{name:`sbxsdk-${crypto.randomUUID()}`,metadata:Object.fromEntries(g),...u.env===void 0?void 0:{env_vars:u.env},preview_access:C,...w?{network:{allow_out:w.allowOut,deny_out:w.denyOut}}:void 0,...O===void 0?void 0:{timeout_seconds:O},...N===void 0?void 0:{auto_delete_seconds:N},...l.secretBindings&&Object.keys(l.secretBindings).length?{secrets:l.secretBindings}:void 0,...u.from?{from_snapshot:u.from}:{from_template:l.template??"superserve/node-22"}}})}catch(j){let V=se(j);if(["timeout","unavailable","aborted","outcome_unknown"].includes(V.code))throw A("Creation outcome unknown; inspect SDK-labelled sandboxes before retrying","outcome_unknown");throw V}let M=oe(I);W.seed(M.id,I),B.set(M.id,Promise.resolve());try{if(u.signal?.aborted)throw A("Creation aborted","aborted");if(v.set(M.id,{...u.env}),u.from||w){let j=await ie(M.id);if(u.from&&j.timeoutSeconds!==O)await K.request({method:"PATCH",path:"/sandboxes/{sandboxId}",...Z(M.id),body:{timeout_seconds:O??null}});if(w&&!ot(w,j.network))throw A("Superserve did not confirm the requested egress rules","unsupported",M.id)}return{id:M.id,key:u.key,labels:{...u.labels,"sandbox-sdk":"1"},createdAt:E,state:"running"}}catch(j){throw await re.destroy(M.id),j}}),list:(u)=>F(void 0,async()=>{let w=await K.json({method:"GET",path:"/sandboxes",query:{"metadata.sandbox-sdk":"1"}});if(!Array.isArray(w))throw A("Superserve returned a sandbox list that is not an array");return w.map((g)=>oe(g)).filter((g)=>g.status!=="deleted").map(be).filter((g)=>Object.entries(u).every(([E,I])=>g.labels[E]===I))}),async find(u){let w=(await re.list({})).find((g)=>g.key===u);return w?re.connect(w.id):void 0},connect:(u)=>F(u,async()=>(await X(u),be(await ie(u)))),destroy(u){let w=L.get(u);if(!w)w=F(u,async()=>{let g=d(J);for(let E=1;;E++)try{await K.request({method:"DELETE",path:"/sandboxes/{sandboxId}",...Z(u),deadline:g});break}catch(I){let M=H(I)?.status;if(M===404)break;let j=Math.min(100*2**(E-1)*(0.8+Math.random()*0.4),30000);if(M!==409||E>=pt||j>=g.remaining())throw I;await y(j,g,"superserve")}ve(u)}),L.set(u,w),w.finally(()=>L.delete(u)).catch(()=>{});return w},async close(u){ve(u)},exec:(u,w)=>F(u,async()=>{let g=await xe(u);return Pe({raw:g.raw,read:async(E,I)=>{let M=await g.raw(p("import sys,base64; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(int(sys.argv[3]))).decode())",E,String(I.offset),String(I.length)));return new Uint8Array(Buffer.from(M.trim(),"base64"))},run:async(E,I,M,j)=>{if(j?.aborted)throw A("Command interrupted","aborted",u);let V=()=>{},Y=new Promise((Q,ee)=>{V=()=>ee(A("Command interrupted","aborted",u))});j?.addEventListener("abort",V,{once:!0});try{let Q=de(u,E,{env:I,timeoutMs:M},!0),ee=await Promise.race([Q,Y]);if(ee.exitCode!==0||ee.truncated)throw A("Supervisor failed","provider",u);return ee.stdout}finally{j?.removeEventListener("abort",V)}},exec:async(E,I,M,j)=>{let V=he(u,E,!0),Y=await Ue({sandboxId:u,url:Me(u,D().sandboxHost),command:V.command,env:V.env,timeoutMs:M,startupSignal:j,route:(te)=>W.current(u,te),refresh:(te,ue)=>W.refresh(u,te.revision,ue),redact:K.redact}),Q=()=>{},ee=!1;try{Y.stdin.write(I),Y.stdin.close();let te=new Promise((mt,qe)=>{Q=()=>{qe(A("Command interrupted","aborted",u))}});if(j?.addEventListener("abort",Q,{once:!0}),j?.aborted)Q();let ue=Y.wait().finally(()=>Y.close());ee=!0;let ce=await Promise.race([ue,te]);if(le(ce.exitCode,u),ce.exitCode!==0)throw A("Supervisor failed","provider",u);return P.add(u),S.add(u),ce.stdout}finally{if(j?.removeEventListener("abort",Q),!ee)await Y.close()}}},w)}),files:R(xe,F),previewUrl:(u,w)=>F(u,async()=>{await X(u);let g=Te(u,D().sandboxHost,w),E=await K.json({method:"POST",path:"/sandboxes/{sandboxId}/preview-ports",...Z(u),body:{port:w,access:C}}),I=z(E,"access");if(!o(z(E,"port"))||I!=="public"&&I!=="private")throw A("Superserve returned an invalid preview port","provider",u);if(C==="public")return{url:g};let M=await K.json({method:"POST",path:"/sandboxes/{sandboxId}/preview-ports/{port}/token",params:{sandboxId:u,port:w},sandboxId:u,body:{}}),j=z(M,"token"),V=z(M,"header"),Y=z(M,"expires_at");if(!t(j)||!j||!t(V)||!V)throw A("Superserve returned an invalid preview token","provider",u);let Q=t(Y)?Date.parse(Y):NaN;return{url:g,headers:{[V]:j},...Number.isNaN(Q)?void 0:{expiresAt:Q}}}),pause:(u)=>F(u,async()=>{await X(u);let{deadline:w,stillPausing:g}=ye(u),E;try{E=z(await K.json({method:"POST",path:"/sandboxes/{sandboxId}/pause",...Z(u),timeoutMs:Math.min(30000,J),signal:w.signal}),"status")==="pausing"}catch(I){if(w.timeout.aborted)throw g();if(!(I instanceof e)||I.code!=="timeout"&&I.code!=="outcome_unknown")throw I;E=!0}if(E)await we(u,w,g)}),resume:(u)=>F(u,async()=>{await X(u);try{await W.resume(u)}catch(w){if(H(w)?.status!==409)throw w;let{status:g}=await ie(u);if(g!=="pausing"&&g!=="paused")throw w;if(g==="pausing"){let{deadline:E,stillPausing:I}=ye(u);await we(u,E,I)}await W.resume(u)}}),snapshot:(u,w)=>F(u,async()=>{if(w?.expiresInMs)throw A("Superserve keeps snapshots until they are deleted; omit expiresInMs","unsupported",u);await X(u);let g=`sbxsdk-${crypto.randomUUID()}`,E;try{let I=d(J),M=await K.json({method:"POST",path:"/sandboxes/{sandboxId}/snapshot",...Z(u),body:{kind:"mem+fs",idempotency_key:g,name:g},idempotencyKey:g,deadline:I});for(;;){let j=z(M,"id"),V=z(M,"status");if(!t(j)||!j)throw A("Superserve returned a snapshot without an id","provider",u);if(V==="ready")return{id:j};if(V==="failed"||V==="deleting")throw E=A(`Snapshot ${V}`,"provider",u),E;await y(Math.min(lt,I.remaining()),I,"superserve"),M=await K.json({method:"GET",path:"/snapshots/{snapshotId}",params:{snapshotId:j},sandboxId:u,deadline:I})}}catch{if(E)throw E;throw A(`Snapshot outcome unknown; recover snapshot named ${g} from source ${u}`,"outcome_unknown",u)}}),native:(u)=>h({http:K,placeholder:"sandboxId",sandboxId:u,sdk:Se})};return re}export{Ft as superserve};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Superserve endpoints and the data-plane route state machine, as @superserve/sdk 0.11.4 runs them
|
|
3
|
+
* (`resolveConfig`, `dataPlaneTarget`, `_postAndRotateToken`, `_refreshActivate`, `withTokenRetry`).
|
|
4
|
+
*
|
|
5
|
+
* The control plane takes the API key. The data plane (exec, files, `exec/connect`) takes an access token
|
|
6
|
+
* and a routing hint that `POST /sandboxes/{id}/activate` and `/resume` hand out. A route is replaced when:
|
|
7
|
+
* - its routing hint is about to expire (checked before every data-plane call),
|
|
8
|
+
* - the data plane answers 401, a 404 `sandbox_route_stale`, or a 503 meaning the sandbox is not running,
|
|
9
|
+
* - `exec/connect` fails to open.
|
|
10
|
+
* Concurrent activations for a sandbox share one request, so a paused sandbox is not resumed twice. Every
|
|
11
|
+
* activation or resume takes a revision when it starts; a response older than the route in use is dropped,
|
|
12
|
+
* so a slow activation never overwrites a newer resume.
|
|
13
|
+
*/
|
|
14
|
+
import type { JsonValue } from "../../shared/json.js";
|
|
15
|
+
export interface SuperserveConfig {
|
|
16
|
+
apiKey: string;
|
|
17
|
+
/** Control plane, e.g. https://api.superserve.ai. */
|
|
18
|
+
baseUrl: string;
|
|
19
|
+
/** Data plane and preview host, e.g. sandbox.superserve.ai. */
|
|
20
|
+
sandboxHost: string;
|
|
21
|
+
}
|
|
22
|
+
/** Reads the key and endpoints: an explicit base URL wins, then the key's region (`ss_live_<region>_`), then the default. */
|
|
23
|
+
export declare function resolveConfig(options: {
|
|
24
|
+
apiKey?: string;
|
|
25
|
+
baseUrl?: string;
|
|
26
|
+
}): SuperserveConfig;
|
|
27
|
+
export declare const sandboxIdHeader = "X-Superserve-Sandbox-Id";
|
|
28
|
+
export declare const routingHintHeader = "X-Superserve-Routing-Hint";
|
|
29
|
+
export declare const accessTokenHeader = "X-Access-Token";
|
|
30
|
+
/** Where data-plane HTTP for a sandbox goes, and the header a shared host routes by. */
|
|
31
|
+
export declare function dataPlane(sandboxId: string, sandboxHost: string): {
|
|
32
|
+
url: string;
|
|
33
|
+
headers: Record<string, string>;
|
|
34
|
+
};
|
|
35
|
+
/** `exec/connect` always dials the per-sandbox host; the route travels in the subprotocols. */
|
|
36
|
+
export declare function execConnectUrl(sandboxId: string, sandboxHost: string): string;
|
|
37
|
+
/** Preview ports Superserve proxies: 1024 to 65535, except its control port 49983. */
|
|
38
|
+
export declare function previewUrl(sandboxId: string, sandboxHost: string, port: number): string;
|
|
39
|
+
/** The expiry of a routing hint in ms since the epoch: its payload's `e`, in seconds. `undefined` when it has none. */
|
|
40
|
+
export declare function hintExpiry(hint: string): number | undefined;
|
|
41
|
+
/** The credentials one data-plane call uses. `revision` orders routes: a higher one is newer. */
|
|
42
|
+
export interface Route {
|
|
43
|
+
readonly token: string;
|
|
44
|
+
readonly hint?: string;
|
|
45
|
+
readonly revision: number;
|
|
46
|
+
}
|
|
47
|
+
/** A sandbox's data-plane token, and the routing hint that pins requests to its host. */
|
|
48
|
+
export interface RouteToken {
|
|
49
|
+
token: string;
|
|
50
|
+
hint?: string;
|
|
51
|
+
}
|
|
52
|
+
/** Reads `access_token` and `routing_hint` from a create, activate or resume response. */
|
|
53
|
+
export declare function parseRoute(raw: JsonValue | undefined, sandboxId: string, operation: string): RouteToken;
|
|
54
|
+
export type RotateEndpoint = "activate" | "resume";
|
|
55
|
+
export interface RouteBookOptions {
|
|
56
|
+
/** POST /sandboxes/{id}/{endpoint} and return the response body. */
|
|
57
|
+
rotate(sandboxId: string, endpoint: RotateEndpoint): Promise<JsonValue | undefined>;
|
|
58
|
+
/** Replace a route this long before its routing hint expires. Default: 30 s. */
|
|
59
|
+
refreshBeforeMs?: number;
|
|
60
|
+
}
|
|
61
|
+
export interface RouteBook {
|
|
62
|
+
/** The current route, activating first when there is none or its hint is about to expire. */
|
|
63
|
+
current(sandboxId: string, signal?: AbortSignal): Promise<Route>;
|
|
64
|
+
/**
|
|
65
|
+
* A route newer than `used`. When one was already applied since (another call refreshed or resumed),
|
|
66
|
+
* it is returned without a request; otherwise this joins or starts the sandbox's activation.
|
|
67
|
+
*/
|
|
68
|
+
refresh(sandboxId: string, used: number | undefined, signal?: AbortSignal): Promise<Route>;
|
|
69
|
+
/** Activate now, sharing a request already in flight. */
|
|
70
|
+
activate(sandboxId: string, signal?: AbortSignal): Promise<Route>;
|
|
71
|
+
/** POST `/resume` (not shared) and apply its route by revision. */
|
|
72
|
+
resume(sandboxId: string): Promise<Route>;
|
|
73
|
+
/** Apply a route from a create response. */
|
|
74
|
+
seed(sandboxId: string, raw: JsonValue | undefined): Route;
|
|
75
|
+
/** Drop a sandbox's state (destroy, close). An activation still in flight then applies to nothing. */
|
|
76
|
+
forget(sandboxId: string): void;
|
|
77
|
+
/** Every token and hint held, for redaction. */
|
|
78
|
+
secrets(): string[];
|
|
79
|
+
}
|
|
80
|
+
export declare function createRouteBook(options: RouteBookOptions): RouteBook;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Route } from "./routes.js";
|
|
2
|
+
export interface SessionResult {
|
|
3
|
+
exitCode: number;
|
|
4
|
+
stdout: string;
|
|
5
|
+
stderr: string;
|
|
6
|
+
}
|
|
7
|
+
export interface Session {
|
|
8
|
+
readonly stdin: {
|
|
9
|
+
write(data: string | Uint8Array): void;
|
|
10
|
+
close(): void;
|
|
11
|
+
};
|
|
12
|
+
/** Resolves when the command finishes; rejects when the connection ends first. */
|
|
13
|
+
wait(): Promise<SessionResult>;
|
|
14
|
+
/** Sends SIGTERM, closes the socket and settles the session. Never rejects. */
|
|
15
|
+
close(): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export interface SpawnOptions {
|
|
18
|
+
sandboxId: string;
|
|
19
|
+
url: string;
|
|
20
|
+
command: string;
|
|
21
|
+
env?: Record<string, string>;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
/** Aborts only the connection setup. */
|
|
24
|
+
startupSignal?: AbortSignal;
|
|
25
|
+
/** The route to dial with, activating first when needed. */
|
|
26
|
+
route(signal: AbortSignal | undefined): Promise<Route>;
|
|
27
|
+
/** A newer route after a failed dial. */
|
|
28
|
+
refresh(used: Route, signal: AbortSignal | undefined): Promise<Route>;
|
|
29
|
+
/** Scrubs credentials from server-supplied text. */
|
|
30
|
+
redact(text: string): string;
|
|
31
|
+
}
|
|
32
|
+
/** Opens a session. A dial that fails is retried once with a fresh route, like the SDK's `dialWithResume`. */
|
|
33
|
+
export declare function spawn(options: SpawnOptions): Promise<Session>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** The shared deadline, with Tenki's errors. The native client takes the signal as an argument. */
|
|
2
2
|
export declare function deadline<T>(action: (signal: AbortSignal) => PromiseLike<T>, timeoutMs: number, signal?: AbortSignal): Promise<T>;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { SandboxError, type ErrorCode } from "../../errors.js";
|
|
2
2
|
export type TenkiOperation = "request" | "create" | "list" | "connect" | "destroy" | "exec" | "files" | "preview" | "pause" | "resume" | "snapshot";
|
|
3
|
-
export declare function tenkiError(
|
|
3
|
+
export declare function tenkiError(cause: unknown, sandboxId?: string, operation?: TenkiOperation, secrets?: string[]): SandboxError;
|
|
4
4
|
export type CreateStage = "waitReady" | "validate" | "prepare";
|
|
5
|
-
export declare function createError(
|
|
5
|
+
export declare function createError(cause: unknown, context: {
|
|
6
6
|
id: string;
|
|
7
7
|
state: string;
|
|
8
8
|
stage: CreateStage;
|
|
9
|
-
}, secrets: string[],
|
|
9
|
+
}, secrets: string[], cleanupCode?: ErrorCode): SandboxError;
|
|
10
10
|
export declare function failure(message: string, code?: ErrorCode): SandboxError;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Session } from "
|
|
1
|
+
import type { TenkiSession as Session } from "./provider.js";
|
|
2
2
|
import type { ExecInput } from "../../provider.js";
|
|
3
3
|
export declare function raw(box: Session, argv: string[], stdin?: Uint8Array, timeoutMs?: number, signal?: AbortSignal): Promise<string>;
|
|
4
4
|
export declare function execute(box: Session, input: ExecInput, workspaceRoot?: (root: string, stable: boolean) => void): Promise<import("../../provider.js").ExecResult>;
|