@opencoredev/sandbox-sdk 0.2.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 +74 -11
- package/README.md +357 -25
- package/dist/ai.d.ts +5 -0
- package/dist/ai.js +1 -0
- 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 +126 -0
- package/dist/files.d.ts +64 -0
- package/dist/git.d.ts +28 -0
- package/dist/handle.d.ts +4 -0
- package/dist/http.d.ts +225 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +1 -0
- package/dist/keys.d.ts +10 -0
- package/dist/logs.d.ts +8 -0
- package/dist/mastra.d.ts +43 -0
- package/dist/mastra.js +1 -0
- package/dist/memory.d.ts +37 -0
- package/dist/memory.js +13 -0
- package/dist/native.d.ts +127 -0
- package/dist/openai.d.ts +39 -0
- package/dist/openai.js +1 -0
- package/dist/peer.d.ts +14 -0
- package/dist/processes.d.ts +71 -0
- package/dist/provider.d.ts +171 -0
- package/dist/provider.js +1 -0
- package/dist/providers/agentos/errors.d.ts +5 -0
- package/dist/providers/agentos/index.d.ts +4 -0
- package/dist/providers/agentos/index.js +2 -0
- package/dist/providers/agentos/provider.d.ts +50 -0
- package/dist/providers/boat/index.d.ts +66 -0
- package/dist/providers/boat/index.js +1 -0
- package/dist/providers/boat-api/errors.d.ts +6 -0
- package/dist/providers/boat-api/exec.d.ts +24 -0
- package/dist/providers/boat-api/follow.d.ts +24 -0
- package/dist/providers/boat-api/index.d.ts +60 -0
- package/dist/providers/boat-api/transport.d.ts +77 -0
- package/dist/providers/boxd/errors.d.ts +3 -0
- package/dist/providers/boxd/execute.d.ts +3 -0
- package/dist/providers/boxd/index.d.ts +3 -0
- package/dist/providers/boxd/index.js +105 -0
- package/dist/providers/boxd/provider.d.ts +74 -0
- package/dist/providers/boxd/transfers.d.ts +28 -0
- package/dist/providers/daytona/api.d.ts +124 -0
- package/dist/providers/daytona/buffered.d.ts +3 -0
- package/dist/providers/daytona/errors.d.ts +19 -0
- package/dist/providers/daytona/exec.d.ts +14 -0
- package/dist/providers/daytona/index.d.ts +73 -0
- package/dist/providers/daytona/index.js +96 -0
- 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 -0
- package/dist/providers/e2b/index.d.ts +53 -0
- package/dist/providers/e2b/index.js +1 -0
- package/dist/providers/freestyle/client.d.ts +87 -0
- package/dist/providers/freestyle/deadline.d.ts +5 -0
- package/dist/providers/freestyle/errors.d.ts +29 -0
- package/dist/providers/freestyle/execute.d.ts +8 -0
- package/dist/providers/freestyle/index.d.ts +40 -0
- package/dist/providers/freestyle/index.js +105 -0
- package/dist/providers/local/docker.d.ts +36 -0
- package/dist/providers/local/index.d.ts +46 -0
- package/dist/providers/local/index.js +2 -0
- package/dist/providers/railway/errors.d.ts +10 -0
- package/dist/providers/railway/index.d.ts +3 -0
- package/dist/providers/railway/index.js +1 -0
- package/dist/providers/railway/provider.d.ts +53 -0
- package/dist/providers/sandboxer/index.d.ts +40 -0
- package/dist/providers/sandboxer/index.js +1 -0
- package/dist/providers/superserve/bootstrap.d.ts +11 -0
- package/dist/providers/superserve/errors.d.ts +3 -0
- package/dist/providers/superserve/execute.d.ts +8 -0
- package/dist/providers/superserve/index.d.ts +52 -0
- package/dist/providers/superserve/index.js +94 -0
- 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 +2 -0
- package/dist/providers/tenki/errors.d.ts +10 -0
- package/dist/providers/tenki/exec.d.ts +4 -0
- package/dist/providers/tenki/files.d.ts +3 -0
- package/dist/providers/tenki/index.d.ts +3 -0
- package/dist/providers/tenki/index.js +175 -0
- package/dist/providers/tenki/provider.d.ts +95 -0
- package/dist/providers/tenki/ready.d.ts +7 -0
- package/dist/providers/tenki/records.d.ts +16 -0
- package/dist/providers/tenki/stream.d.ts +3 -0
- package/dist/providers/upstash/buffered.d.ts +3 -0
- package/dist/providers/upstash/errors.d.ts +3 -0
- package/dist/providers/upstash/exec.d.ts +18 -0
- package/dist/providers/upstash/files.d.ts +15 -0
- package/dist/providers/upstash/index.d.ts +6 -0
- package/dist/providers/upstash/index.js +105 -0
- package/dist/providers/upstash/provider.d.ts +81 -0
- package/dist/providers/vercel/errors.d.ts +5 -0
- package/dist/providers/vercel/index.d.ts +22 -0
- package/dist/providers/vercel/index.js +1 -0
- package/dist/providers/vercel/provider.d.ts +58 -0
- package/dist/providers/vercel/transport.d.ts +43 -0
- package/dist/run.d.ts +43 -0
- 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/shared/wire.d.ts +10 -0
- package/dist/shell/process-records.d.ts +44 -0
- package/dist/streams.d.ts +72 -0
- package/dist/testing.d.ts +27 -0
- package/dist/testing.js +9 -0
- package/dist/tool-security.d.ts +9 -0
- package/dist/tools.d.ts +118 -0
- package/dist/tools.js +1 -0
- package/dist/types.d.ts +197 -0
- package/package.json +143 -102
- package/dist/agentos-CbrZW7R0.mjs +0 -390
- package/dist/agentos-CbrZW7R0.mjs.map +0 -1
- package/dist/ai/harness.d.mts +0 -16
- package/dist/ai/harness.mjs +0 -69
- package/dist/ai/harness.mjs.map +0 -1
- package/dist/ai/index.d.mts +0 -54
- package/dist/ai/index.mjs +0 -4
- package/dist/ai-DeFa8yPk.mjs +0 -243
- package/dist/ai-DeFa8yPk.mjs.map +0 -1
- package/dist/capabilities-BWvOVFbH.d.mts +0 -15
- package/dist/capabilities-CaSNd6J1.mjs +0 -125
- package/dist/capabilities-CaSNd6J1.mjs.map +0 -1
- package/dist/capabilities-xs9kaHrK.mjs +0 -28
- package/dist/capabilities-xs9kaHrK.mjs.map +0 -1
- package/dist/errors-BuF9bYOQ.mjs +0 -68
- package/dist/errors-BuF9bYOQ.mjs.map +0 -1
- package/dist/eve/index.d.mts +0 -19
- package/dist/eve/index.mjs +0 -155
- package/dist/eve/index.mjs.map +0 -1
- package/dist/index-CkTwqD0X.d.mts +0 -25
- package/dist/index-Dh9xob2s.d.mts +0 -31
- package/dist/index.d.mts +0 -5
- package/dist/index.mjs +0 -40
- package/dist/index.mjs.map +0 -1
- package/dist/managed-provider-BsZGVQ4I.mjs +0 -148
- package/dist/managed-provider-BsZGVQ4I.mjs.map +0 -1
- package/dist/mastra/index.d.mts +0 -118
- package/dist/mastra/index.mjs +0 -662
- package/dist/mastra/index.mjs.map +0 -1
- package/dist/metadata.d.mts +0 -34
- package/dist/metadata.mjs +0 -135
- package/dist/metadata.mjs.map +0 -1
- package/dist/provider-DOBErkBO.d.mts +0 -91
- package/dist/provider-utils-CfB9nvJx.mjs +0 -57
- package/dist/provider-utils-CfB9nvJx.mjs.map +0 -1
- package/dist/providers/agentos/index.d.mts +0 -7
- package/dist/providers/agentos/index.mjs +0 -9
- package/dist/providers/box/index.d.mts +0 -34
- package/dist/providers/box/index.mjs +0 -348
- package/dist/providers/box/index.mjs.map +0 -1
- package/dist/providers/daytona/index.d.mts +0 -21
- package/dist/providers/daytona/index.mjs +0 -206
- package/dist/providers/daytona/index.mjs.map +0 -1
- package/dist/providers/e2b/index.d.mts +0 -17
- package/dist/providers/e2b/index.mjs +0 -169
- package/dist/providers/e2b/index.mjs.map +0 -1
- package/dist/providers/local/index.d.mts +0 -22
- package/dist/providers/local/index.mjs +0 -22
- package/dist/providers/local/index.mjs.map +0 -1
- package/dist/providers/railway/index.d.mts +0 -29
- package/dist/providers/railway/index.mjs +0 -211
- package/dist/providers/railway/index.mjs.map +0 -1
- package/dist/providers/upstash/index.d.mts +0 -17
- package/dist/providers/upstash/index.mjs +0 -211
- package/dist/providers/upstash/index.mjs.map +0 -1
- package/dist/providers/vercel/index.d.mts +0 -28
- package/dist/providers/vercel/index.mjs +0 -186
- package/dist/providers/vercel/index.mjs.map +0 -1
- package/dist/sandbox-DdEqoXJF.d.mts +0 -26
- package/dist/sandbox-DgtY5hvt.mjs +0 -112
- package/dist/sandbox-DgtY5hvt.mjs.map +0 -1
- package/dist/testing/index.d.mts +0 -27
- package/dist/testing/index.mjs +0 -173
- package/dist/testing/index.mjs.map +0 -1
- package/dist/types-Bv6I2U1c.d.mts +0 -103
|
@@ -0,0 +1,94 @@
|
|
|
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
|
+
root=sys.argv[1]
|
|
4
|
+
v=marshal.loads(bytes.fromhex(sys.argv[2])) if len(sys.argv)>2 else marshal.loads(bytes.fromhex(sys.stdin.read()))
|
|
5
|
+
if 'envKeys' in v: v['env']={k:os.environ[k] for k in v['envKeys']}
|
|
6
|
+
os.makedirs(root,mode=0o700,exist_ok=True)
|
|
7
|
+
# Keep small completed responses until their request deadline has passed.
|
|
8
|
+
# Sweep expired responses inline, so no ack RPC or background daemon is needed.
|
|
9
|
+
for entry in os.scandir(os.path.dirname(root)):
|
|
10
|
+
if not entry.name.startswith('run-') or entry.path==root: continue
|
|
11
|
+
try:
|
|
12
|
+
with open(entry.path+'/expires') as f: expired=time.time()>float(f.read())
|
|
13
|
+
if expired:
|
|
14
|
+
import shutil
|
|
15
|
+
shutil.rmtree(entry.path,ignore_errors=True)
|
|
16
|
+
except (FileNotFoundError,NotADirectoryError): pass
|
|
17
|
+
a=v.get('activityPath')
|
|
18
|
+
timed=False
|
|
19
|
+
code=127
|
|
20
|
+
try:
|
|
21
|
+
if a:
|
|
22
|
+
os.makedirs(os.path.dirname(a),exist_ok=True)
|
|
23
|
+
with open(a,'w') as f: f.write('1')
|
|
24
|
+
try:
|
|
25
|
+
with open('/var/lib/sandbox-sdk-env.json') as f:
|
|
26
|
+
import json
|
|
27
|
+
saved=json.load(f)
|
|
28
|
+
except FileNotFoundError: saved={}
|
|
29
|
+
if os.environ.get('SANDBOX_SDK_BOOTSTRAP') not in (None,'{}'):
|
|
30
|
+
bootstrap=os.environ.pop('SANDBOX_SDK_BOOTSTRAP')
|
|
31
|
+
if bootstrap=='{"env":{}}': initial={}
|
|
32
|
+
else:
|
|
33
|
+
import json
|
|
34
|
+
initial=json.loads(bootstrap).get('env')
|
|
35
|
+
if initial is not None: saved=initial
|
|
36
|
+
if initial is not None and (initial or os.path.exists('/var/lib/sandbox-sdk-env.json')):
|
|
37
|
+
import json
|
|
38
|
+
os.makedirs(os.path.dirname('/var/lib/sandbox-sdk-env.json'),exist_ok=True)
|
|
39
|
+
tmp='/var/lib/sandbox-sdk-env.json.'+str(os.getpid())
|
|
40
|
+
fd=os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
|
41
|
+
with os.fdopen(fd,'w') as f: json.dump(saved,f)
|
|
42
|
+
os.replace(tmp,'/var/lib/sandbox-sdk-env.json')
|
|
43
|
+
env={**os.environ,**saved,**v['env']}
|
|
44
|
+
with stdin_file() as f, open(root+'/out','wb',buffering=0) as out:
|
|
45
|
+
f.write(v.get('stdin','').encode()); f.seek(0)
|
|
46
|
+
with open(root+'/lock','w') as lock:
|
|
47
|
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
48
|
+
if os.path.exists(root+'/cancelled'): timed=True; p=None
|
|
49
|
+
else:
|
|
50
|
+
try: p=Process(v,env,f,True)
|
|
51
|
+
except OSError as e:
|
|
52
|
+
out.write(('["stderr","'+str(e).encode().hex()+'"]\\n').encode()); p=None
|
|
53
|
+
if p:
|
|
54
|
+
with open(root+'/pid','w') as m: m.write(str(p.pid))
|
|
55
|
+
if p:
|
|
56
|
+
stdout=p.stdout.fileno(); streams={stdout:'stdout',p.stderr.fileno():'stderr'}
|
|
57
|
+
end=time.monotonic()+v['timeoutMs']/1000
|
|
58
|
+
while streams or p.poll() is None:
|
|
59
|
+
if not timed and time.monotonic()>=end:
|
|
60
|
+
timed=True
|
|
61
|
+
try: os.killpg(p.pid,signal.SIGKILL)
|
|
62
|
+
except ProcessLookupError: pass
|
|
63
|
+
for fd in select.select(list(streams),[],[],.01)[0]:
|
|
64
|
+
data=os.read(fd,8192)
|
|
65
|
+
if data: out.write(('["'+streams[fd]+'","'+data.hex()+'"]\\n').encode())
|
|
66
|
+
else: del streams[fd]; (p.stdout if fd==stdout else p.stderr).close()
|
|
67
|
+
code=p.wait()
|
|
68
|
+
timed=timed or os.path.exists(root+'/cancelled')
|
|
69
|
+
result='{"exitCode":%s,"timedOut":%s}'%('null' if timed else str(code if code>=0 else 128-code),str(timed).lower())
|
|
70
|
+
with open(root+'/exit','w') as f: f.write(result)
|
|
71
|
+
size=os.path.getsize(root+'/out')
|
|
72
|
+
with open(root+'/out','rb') as f:
|
|
73
|
+
chunks=[line.decode().strip() for _,line in zip(range(3),f)]
|
|
74
|
+
offset=f.tell()
|
|
75
|
+
if offset==size and not timed:
|
|
76
|
+
with open(root+'/expires','w') as f: f.write(str(time.time()+v['timeoutMs']/1000+5))
|
|
77
|
+
if timed and not p:
|
|
78
|
+
import shutil
|
|
79
|
+
shutil.rmtree(root)
|
|
80
|
+
print('{"result":%s,"chunks":[%s],"offset":%d,"size":%d}'%(result,','.join(chunks),offset,size))
|
|
81
|
+
finally:
|
|
82
|
+
if a:
|
|
83
|
+
try: os.unlink(a)
|
|
84
|
+
except FileNotFoundError: pass
|
|
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
|
|
86
|
+
v=json.loads(os.environ.pop('SANDBOX_SDK_BOOTSTRAP'))
|
|
87
|
+
if any(shutil.which(tool) is None for tool in ('git','tar','nohup')): sys.exit(79)
|
|
88
|
+
os.makedirs('/workspace',exist_ok=True)
|
|
89
|
+
os.makedirs('/tmp/.sandbox-sdk',exist_ok=True)
|
|
90
|
+
os.makedirs(os.path.dirname('/var/lib/sandbox-sdk-env.json'),exist_ok=True)
|
|
91
|
+
if v.get('env') is not None:
|
|
92
|
+
with tempfile.NamedTemporaryFile(mode='w',dir=os.path.dirname('/var/lib/sandbox-sdk-env.json'),delete=False) as f:
|
|
93
|
+
json.dump(v['env'],f)
|
|
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>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { SandboxError, type ErrorCode } from "../../errors.js";
|
|
2
|
+
export type TenkiOperation = "request" | "create" | "list" | "connect" | "destroy" | "exec" | "files" | "preview" | "pause" | "resume" | "snapshot";
|
|
3
|
+
export declare function tenkiError(cause: unknown, sandboxId?: string, operation?: TenkiOperation, secrets?: string[]): SandboxError;
|
|
4
|
+
export type CreateStage = "waitReady" | "validate" | "prepare";
|
|
5
|
+
export declare function createError(cause: unknown, context: {
|
|
6
|
+
id: string;
|
|
7
|
+
state: string;
|
|
8
|
+
stage: CreateStage;
|
|
9
|
+
}, secrets: string[], cleanupCode?: ErrorCode): SandboxError;
|
|
10
|
+
export declare function failure(message: string, code?: ErrorCode): SandboxError;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { TenkiSession as Session } from "./provider.js";
|
|
2
|
+
import type { ExecInput } from "../../provider.js";
|
|
3
|
+
export declare function raw(box: Session, argv: string[], stdin?: Uint8Array, timeoutMs?: number, signal?: AbortSignal): Promise<string>;
|
|
4
|
+
export declare function execute(box: Session, input: ExecInput, workspaceRoot?: (root: string, stable: boolean) => void): Promise<import("../../provider.js").ExecResult>;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { TenkiSession as Session } from "./provider.js";
|
|
2
|
+
import type { ProviderFiles } from "../../provider.js";
|
|
3
|
+
export declare function files(get: (id: string) => Promise<Session>, safe: <T>(id: string, action: () => Promise<T>) => Promise<T>, workspaceRoot: (box: Session) => string | undefined, invalidateWorkspace: (box: Session) => void): ProviderFiles;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import{T}from"../../chunk-8786zrns.js";import{b,L,F}from"../../chunk-x681p5d2.js";import{m}from"../../chunk-bd481sb7.js";import{g}from"../../chunk-k60b4r27.js";import{t,o,I,r,e,i,se,c,a}from"../../chunk-xgxfy2n8.js";async function oe(n){let{action:u,timeoutMs:h,signal:y}=n;if(y?.aborted)throw n.aborted();let x=new AbortController,_=()=>x.abort(n.aborted());y?.addEventListener("abort",_,{once:!0});let k=setTimeout(()=>x.abort(n.expired()),h),E=()=>{},f=new Promise((S,v)=>{E=()=>v(x.signal.reason),x.signal.addEventListener("abort",E,{once:!0})});try{return await Promise.race([f,u(x.signal)])}finally{clearTimeout(k),y?.removeEventListener("abort",_),x.signal.removeEventListener("abort",E)}}var ne=new Map([["MissingAuthTokenError","auth"],["InvalidAuthTokenError","auth"],["UnauthorizedError","auth"],["PermissionDeniedError","auth"],["SessionNotFoundError","not_found"],["SessionExpiredError","not_found"],["SessionTerminatedError","not_found"],["SnapshotNotFoundError","not_found"],["FileNotFoundError","file_not_found"],["QuotaExceededError","quota"],["PortLimitExceededError","quota"],["RateLimitedError","quota"],["CapacityUnavailableError","unavailable"],["SSHUnavailableError","unavailable"],["DataPlaneNotReadyError","unavailable"],["CommandTimeoutError","timeout"],["SnapshotWaitTimeoutError","timeout"],["PrimitiveTimeoutError","timeout"],["InvalidResourceConfigError","invalid_argument"],["InvalidStateError","invalid_argument"],["InboundDisabledError","unsupported"],["CapabilityUnavailableError","unsupported"]]),ke=new Set(["ResumeFailedError","PauseFailedError","WaitReadyFailedError","StreamClosedError"]);function ie(n,u){let h={},y=new Set,x=n;for(let _=0;_<4&&r(x)&&!y.has(x);_++){y.add(x);let k=m(x);if(ne.has(k.name)||ke.has(k.name))h.nativeName??=k.name;let E=k.status??k.statusCode;if(E!==void 0&&Number.isInteger(E)&&E>=100&&E<=599)h.status??=E;let f=k.code;if(o(f)&&Number.isInteger(f)&&f>=0&&f<=16||t(f)&&/^[A-Z][A-Z0-9_]{0,63}$/.test(f)&&!u.some((v)=>f.includes(v)))h.providerCode??=f;let S=k.requestId??k.metadata.get("x-request-id")??k.metadata.get("request-id");if(S!==void 0&&/^[A-Za-z0-9_-]{1,128}$/.test(S)&&!u.some((v)=>S.includes(v)))h.requestId??=S;x=k.cause}return h}function ae(n,u,h,y){let x=h.status??h.providerCode,{detail:_}=i(n,{code:u,known:h.nativeName===void 0?void 0:!0,status:x===void 0?void 0:String(x),redact:c(y)});return _===void 0?{}:{native:_}}function G(n,u,h="request",y=[]){if(n instanceof e)return n;let x=n instanceof Error?n.name:"",_=ne.get(x)??"provider",k=[...y,process.env.TENKI_API_KEY??"",process.env.TENKI_AUTH_TOKEN??""].filter(Boolean),E=ie(n,k),f={operation:h,...E,...ae(n,_,E,k)};return new e(`Tenki request failed: ${a(_,f.native)}. Check credentials, quotas, and session state.`,{code:_,provider:"tenki",sandboxId:u,cause:se(f),retryable:["quota","unavailable","timeout"].includes(_)})}function de(n,u,h,y){let x=G(n,u.id,"create",h),_=[...h,process.env.TENKI_API_KEY??"",process.env.TENKI_AUTH_TOKEN??""].filter(Boolean),k={operation:"create",admittedByThisCall:!0,stage:u.stage};if(/^[0-9a-f-]{36}$/i.test(u.id)&&!_.some((f)=>u.id.includes(f)))k.sandboxId=u.id;if(/^[A-Z_]{1,32}$/.test(u.state))k.state=u.state;let E=ie(n,_);if(Object.assign(k,E,ae(n,x.code,E,_)),y!==void 0)k.cleanupCode=y;return new e(x.message,{code:x.code,provider:"tenki",sandboxId:u.id,retryable:x.retryable,hint:x.hint,cause:se(k)})}function p(n,u="provider"){return new e(u==="auth"?n:`${n}. Tenki could not honor the request. Check the provider options.`,{code:u,provider:"tenki"})}function U(n,u,h){return oe({action:n,timeoutMs:u,signal:h,aborted:()=>p("Request aborted","aborted"),expired:()=>p("Request deadline exceeded","timeout")})}import{setTimeout as he}from"node:timers/promises";async function ce(n,u,h){let y=Date.now()+u,x=()=>n.state==="RUNNING";if(h?.aborted)throw p("Creation aborted","aborted");if(x()&&n.dataPlaneRPC!==void 0&&n.dataPlaneRPC())return;try{await U((k)=>n.waitReady(u,k),Math.min(5000,u/2),h);return}catch(k){if(h?.aborted)throw p("Creation aborted","aborted");if(G(k).code!=="timeout")throw k}if(x())return;let _;while(Date.now()<y){if(h?.aborted)throw p("Creation aborted","aborted");try{if(await U(()=>n.refresh(),Math.min(1e4,y-Date.now()),h),h?.aborted)throw p("Creation aborted","aborted");if(x())return;if(["TERMINATED","TERMINATING"].includes(n.state))throw p("Session terminated before readiness","not_found")}catch(E){let f=G(E).code;if(["auth","not_found","invalid_argument","aborted"].includes(f))throw E;_=E}let k=y-Date.now();if(k>0)try{await he(Math.min(1000,k),void 0,{signal:h})}catch{throw p("Creation aborted","aborted")}}throw new e("Tenki session did not become ready within its readiness budget.",{code:"timeout",provider:"tenki",sandboxId:n.id,cause:_})}var V=`workspace=globals().get('v',{}).get('workspace','/workspace')
|
|
2
|
+
home=os.path.join(os.path.dirname(workspace),'home','tenki')
|
|
3
|
+
tmp=os.path.join(os.path.dirname(workspace),'tmp')
|
|
4
|
+
os.makedirs(home+'/.sandbox-sdk',exist_ok=True)
|
|
5
|
+
os.makedirs(tmp,exist_ok=True)
|
|
6
|
+
import fcntl
|
|
7
|
+
with open(home+'/.sandbox-sdk/setup.lock','w') as setup_lock:
|
|
8
|
+
fcntl.flock(setup_lock,fcntl.LOCK_EX)
|
|
9
|
+
if not os.path.exists(home+'/.sandbox-sdk/prepared'):
|
|
10
|
+
if not os.path.exists(workspace):
|
|
11
|
+
os.makedirs(home+'/workspace',exist_ok=True)
|
|
12
|
+
try: os.symlink(home+'/workspace',workspace)
|
|
13
|
+
except FileExistsError: pass
|
|
14
|
+
elif not os.path.islink(workspace) and not os.path.exists(home+'/workspace'):
|
|
15
|
+
os.rename(workspace,home+'/workspace'); os.symlink(home+'/workspace',workspace)
|
|
16
|
+
with open(home+'/.sandbox-sdk/prepared','w'): pass
|
|
17
|
+
if not os.path.exists(tmp+'/.sandbox-sdk'):
|
|
18
|
+
try: os.symlink(home+'/.sandbox-sdk',tmp+'/.sandbox-sdk')
|
|
19
|
+
except FileExistsError: pass
|
|
20
|
+
`;function Q(n){return Array.isArray(n)&&n.length===2&&(n[0]==="stdout"||n[0]==="stderr")&&t(n[1])&&n[1].length<=21848}function X(n){return r(n)&&"exitCode"in n&&(n.exitCode===null||o(n.exitCode)&&Number.isInteger(n.exitCode))&&"timedOut"in n&&I(n.timedOut)&&(!("workspaceStable"in n)||I(n.workspaceStable))&&(!("workspaceRoot"in n)||t(n.workspaceRoot))&&(!("workspaceRootHex"in n)||t(n.workspaceRootHex))}var be=`import os,sys,marshal,_signal as signal,select,time,pwd
|
|
21
|
+
${b}
|
|
22
|
+
v=marshal.loads(bytes.fromhex(sys.stdin.read()))
|
|
23
|
+
${V}
|
|
24
|
+
def processes():
|
|
25
|
+
ids=set()
|
|
26
|
+
for e in os.scandir('/proc'):
|
|
27
|
+
if not e.name.isdecimal(): continue
|
|
28
|
+
try: ids.add((e.name,e.inode()))
|
|
29
|
+
except FileNotFoundError: continue
|
|
30
|
+
if len(ids)>4096: return None
|
|
31
|
+
return ids
|
|
32
|
+
before=processes()
|
|
33
|
+
def stable():
|
|
34
|
+
after=processes()
|
|
35
|
+
return before is not None and after is not None and after.issubset(before)
|
|
36
|
+
env={**os.environ,**v['env'],'PWD':v['cwd']}
|
|
37
|
+
if os.geteuid()==0 and 'SUDO_UID' not in env:
|
|
38
|
+
try: env['SUDO_UID']=str(pwd.getpwnam('tenki').pw_uid)
|
|
39
|
+
except KeyError: pass
|
|
40
|
+
with stdin_file() as f:
|
|
41
|
+
f.write(v['stdin'].encode()); f.seek(0)
|
|
42
|
+
p=Process(v,env,f,True)
|
|
43
|
+
try:
|
|
44
|
+
with open(v['marker'],'w') as m: m.write(str(p.pid))
|
|
45
|
+
if v.get('activityPath'):
|
|
46
|
+
os.makedirs(os.path.dirname(v['activityPath']),exist_ok=True)
|
|
47
|
+
with open(v['activityPath'],'w') as a: a.write('1')
|
|
48
|
+
stdout=p.stdout.fileno(); streams={stdout:'stdout',p.stderr.fileno():'stderr'}
|
|
49
|
+
end=time.monotonic()+v['timeoutMs']/1000
|
|
50
|
+
timed=False
|
|
51
|
+
while streams or p.poll() is None:
|
|
52
|
+
if not timed and time.monotonic()>=end:
|
|
53
|
+
timed=True
|
|
54
|
+
try: os.killpg(p.pid,signal.SIGKILL)
|
|
55
|
+
except ProcessLookupError: pass
|
|
56
|
+
for fd in select.select(list(streams),[],[],.01)[0]:
|
|
57
|
+
data=os.read(fd,8192)
|
|
58
|
+
if data: print('["'+streams[fd]+'","'+data.hex()+'"]',flush=True)
|
|
59
|
+
else: del streams[fd]; (p.stdout if fd==stdout else p.stderr).close()
|
|
60
|
+
code=p.wait()
|
|
61
|
+
print('{"exitCode":%s,"timedOut":%s,"workspaceStable":%s,"workspaceRootHex":"%s"}'%('null' if timed else str(code if code>=0 else 128-code),str(timed).lower(),str(stable()).lower(),os.path.realpath(v['workspace']).encode().hex()),flush=True)
|
|
62
|
+
except BaseException:
|
|
63
|
+
try: os.killpg(p.pid,signal.SIGKILL)
|
|
64
|
+
except ProcessLookupError: pass
|
|
65
|
+
raise
|
|
66
|
+
finally:
|
|
67
|
+
for path in [v['marker'],v.get('activityPath')]:
|
|
68
|
+
if path:
|
|
69
|
+
try: os.unlink(path)
|
|
70
|
+
except FileNotFoundError: pass
|
|
71
|
+
`,ye=`import os,sys,time,signal
|
|
72
|
+
for _ in range(100):
|
|
73
|
+
try:
|
|
74
|
+
with open(sys.argv[1]) as f: pid=int(f.read())
|
|
75
|
+
os.killpg(pid,signal.SIGKILL)
|
|
76
|
+
break
|
|
77
|
+
except ProcessLookupError: break
|
|
78
|
+
except (FileNotFoundError,ValueError): time.sleep(.01)
|
|
79
|
+
else: raise RuntimeError('PID unavailable')`;async function ue(n,u,h){if(u.signal?.aborted)return{exitCode:null,timedOut:!0};let y=`/home/tenki/.sandbox-sdk-run-${crypto.randomUUID()}`,x=Buffer.from(T({command:u.command,cwd:u.cwd,env:u.env,stdin:u.stdin??"",timeoutMs:u.timeoutMs,marker:y,activityPath:u.activityPath,workspace:"/workspace"}).toString("hex")),_=new AbortController,k,E=!1,f=!1,S={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})},v=new TextDecoder,P="";function C(D){let M=JSON.parse(D);if(Q(M)){let[A,q]=M,K=S[A].decode(Buffer.from(q,"hex"),{stream:!0});if(K)u.onChunk({stream:A,text:K});return}if(!X(M))throw p("Invalid command output record");if(M.workspaceRootHex!==void 0)h?.(Buffer.from(M.workspaceRootHex,"hex").toString(),M.workspaceStable===!0);k={exitCode:M.exitCode,timedOut:M.timedOut}}let R=(async()=>{for(let D=0;D<2;D++){let M=new AbortController,A=AbortSignal.any([_.signal,M.signal]),q,K=!1;async function*d(){A.throwIfAborted(),yield{frame:{payload:{case:"start",value:{sessionId:n.id,cmd:["python3","-S","-c",be],privileged:!0,streamStdin:!0}}}},A.throwIfAborted(),f=!0,yield{frame:{payload:{case:"stdin",value:x}}},yield{frame:{payload:{case:"stdinClose",value:!0}}},await new Promise((s)=>{if(A.aborted)s();else A.addEventListener("abort",()=>s(),{once:!0})})}try{A.throwIfAborted(),q=await n.requireDataPlane(!1),A.throwIfAborted();for await(let s of q.run(d(),{signal:A})){let l=s.frame?.payload;if(!l)continue;if(l.case!=="keepalive")K=!0;if(l.case==="started")n.markDataPlaneServing(q);else if(l.case==="stdout"){P+=v.decode(l.value,{stream:!0});let w;while((w=P.indexOf(`
|
|
80
|
+
`))!==-1)C(P.slice(0,w)),P=P.slice(w+1);if(P.length>24000)throw p("Oversized command output record")}else if(l.case==="exit"){if(l.value.exitCode!==0||!k||P)throw p("Command supervisor failed");E=!0;for(let w of["stdout","stderr"]){let N=S[w].decode();if(N)u.onChunk({stream:w,text:N})}return k}}throw p("Command stream closed before exit")}catch(s){if(M.abort(),_.signal.aborted)throw s;let l=r(s)&&"code"in s?s.code:void 0,w=s instanceof Error?s.message:"",N=l===16||G(s).code==="auth",j=l===5&&/\bsession not found\b/i.test(w)&&q!==void 0&&n.dataPlaneProvisioningPending(q),z=N||j||l===12&&/\b404\b/.test(w)||(l===10||l===13||l===14)&&/REFUSED_STREAM/i.test(w);if(!K&&(z||!f)){if(f=!1,N){if(D===0&&await n.reauthOnUnauthenticated(s))continue;throw p("Command authorization rejected before launch","auth")}if(z||l===14){if(D===0){if(j&&q)await n.refreshHintedDataPlane(q);continue}throw p("Command transport rejected before launch","unavailable")}}if(f)throw p("Command stream failed after submission; execution outcome is unknown","outcome_unknown");throw s}finally{M.abort()}}throw p("Command recovery exhausted","unavailable")})();R.catch(()=>{});try{return await U(()=>R,u.timeoutMs+1000,u.signal)}catch(D){if(f&&!E)try{await H(n,["python3","-c",ye,y],void 0,1500)}catch{if(!E)throw p("Process cancellation could not be confirmed; execution outcome is unknown","outcome_unknown")}if(u.signal?.aborted||G(D).code==="timeout")return{exitCode:null,timedOut:!0};throw D}finally{_.abort()}}var ve=`import os,sys,json,base64,signal,selectors,time,pwd
|
|
81
|
+
${b}
|
|
82
|
+
v=json.load(sys.stdin)
|
|
83
|
+
${V}
|
|
84
|
+
def processes():
|
|
85
|
+
ids=set()
|
|
86
|
+
for e in os.scandir('/proc'):
|
|
87
|
+
if not e.name.isdecimal(): continue
|
|
88
|
+
try: ids.add((e.name,e.inode()))
|
|
89
|
+
except FileNotFoundError: continue
|
|
90
|
+
if len(ids)>4096: return None
|
|
91
|
+
return ids
|
|
92
|
+
before=processes()
|
|
93
|
+
def stable():
|
|
94
|
+
after=processes()
|
|
95
|
+
return before is not None and after is not None and after.issubset(before)
|
|
96
|
+
env={**os.environ,**v['env'],'PWD':v['cwd']}
|
|
97
|
+
if os.geteuid()==0 and 'SUDO_UID' not in env:
|
|
98
|
+
try: env['SUDO_UID']=str(pwd.getpwnam('tenki').pw_uid)
|
|
99
|
+
except KeyError: pass
|
|
100
|
+
try:
|
|
101
|
+
with stdin_file() as f, open(v['marker']+'.out','wb',buffering=0) as out:
|
|
102
|
+
f.write(base64.b64decode(v['stdin'])); f.seek(0)
|
|
103
|
+
p=Process(v,env,f,True)
|
|
104
|
+
with open(v['marker'],'w') as m: m.write(str(p.pid))
|
|
105
|
+
if v.get('activityPath'):
|
|
106
|
+
os.makedirs(os.path.dirname(v['activityPath']),exist_ok=True)
|
|
107
|
+
with open(v['activityPath'],'w') as a: a.write('1')
|
|
108
|
+
sel=selectors.DefaultSelector()
|
|
109
|
+
sel.register(p.stdout,selectors.EVENT_READ,'stdout'); sel.register(p.stderr,selectors.EVENT_READ,'stderr')
|
|
110
|
+
end=time.monotonic()+v['timeoutMs']/1000
|
|
111
|
+
timed=False
|
|
112
|
+
while sel.get_map() or p.poll() is None:
|
|
113
|
+
if not timed and time.monotonic()>=end:
|
|
114
|
+
timed=True
|
|
115
|
+
try: os.killpg(p.pid,signal.SIGKILL)
|
|
116
|
+
except ProcessLookupError: pass
|
|
117
|
+
for key,_ in sel.select(.01):
|
|
118
|
+
data=os.read(key.fd,16384)
|
|
119
|
+
if data: out.write((json.dumps([key.data,base64.b64encode(data).decode()])+'\\n').encode())
|
|
120
|
+
else: sel.unregister(key.fileobj); key.fileobj.close()
|
|
121
|
+
code=p.wait()
|
|
122
|
+
with open(v['marker']+'.exit','w') as m: json.dump({'exitCode':None if timed else (code if code>=0 else 128-code),'timedOut':timed,'workspaceStable':stable(),'workspaceRoot':os.path.realpath(v['workspace'])},m)
|
|
123
|
+
finally:
|
|
124
|
+
if v.get('activityPath'):
|
|
125
|
+
try: os.unlink(v['activityPath'])
|
|
126
|
+
except FileNotFoundError: pass
|
|
127
|
+
`,ge=`import sys,json
|
|
128
|
+
pos=int(sys.argv[2]); chunks=[]
|
|
129
|
+
try:
|
|
130
|
+
with open(sys.argv[1],'rb') as f:
|
|
131
|
+
f.seek(pos)
|
|
132
|
+
for _ in range(3):
|
|
133
|
+
line=f.readline(24000)
|
|
134
|
+
if not line.endswith(b'\\n'): break
|
|
135
|
+
chunks.append(json.loads(line)); pos=f.tell()
|
|
136
|
+
except FileNotFoundError: pass
|
|
137
|
+
print(json.dumps({'offset':pos,'chunks':chunks}))
|
|
138
|
+
`,xe=`import os,sys,time,signal
|
|
139
|
+
p=sys.argv[1]
|
|
140
|
+
for _ in range(3000):
|
|
141
|
+
try:
|
|
142
|
+
with open(p) as f: pid=int(f.read())
|
|
143
|
+
break
|
|
144
|
+
except (FileNotFoundError,ValueError): time.sleep(.01)
|
|
145
|
+
else: raise RuntimeError('PID unavailable')
|
|
146
|
+
try: os.killpg(pid,signal.SIGKILL)
|
|
147
|
+
except ProcessLookupError: pass`;async function H(n,u,h,y=30000,x){let _=new ReadableStream({start(E){if(h)E.enqueue(h);E.close()}}),k=await U((E)=>n.run(u,{privileged:!0,stdin:_,timeoutMs:y,signal:E}),y,x);if(k.exitCode!==0||k.timedOut)throw p("Guest operation failed",k.timedOut?"timeout":"provider");return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(k.stdout)}function Se(n){return n.requireDataPlane!==void 0}async function le(n,u,h){if(Se(n))return ue(n,u,h);if(u.signal?.aborted)return{exitCode:null,timedOut:!0};let y=`/home/tenki/.sandbox-sdk-run-${crypto.randomUUID()}`,x=Buffer.from(JSON.stringify({command:u.command,cwd:u.cwd,env:u.env,stdin:Buffer.from(u.stdin??"").toString("base64"),timeoutMs:u.timeoutMs,marker:y,activityPath:u.activityPath,workspace:"/workspace"})),_=!1,k=()=>{},E=new Promise((s)=>{k=()=>{_=!0,s("cancelled")}});u.signal?.addEventListener("abort",k,{once:!0});let f=setTimeout(k,u.timeoutMs),S=new ReadableStream({start(s){s.enqueue(x),s.close()}}),v=new AbortController,P=n.run(["python3","-S","-c",ve],{privileged:!0,stdin:S,signal:v.signal}),C=[];async function R(s,l){let w=new TextDecoder("utf-8",{ignoreBOM:!0}),N=s.getReader();C.push(N);try{while(!0){let{value:z,done:O}=await N.read();if(O)break;let Z=w.decode(z,{stream:!0});if(Z)u.onChunk({stream:l,text:Z})}}finally{N.releaseLock()}let j=w.decode();if(j)u.onChunk({stream:l,text:j})}let D=!1,M=new AbortController,A=Promise.resolve(P).finally(()=>{D=!0});async function q(){let s=0,l={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})};while(!M.signal.aborted){let w=D,N=JSON.parse(await H(n,["python3","-c",ge,`${y}.out`,String(s)],void 0,30000,M.signal));if(!r(N)||!("offset"in N)||!o(N.offset)||!Number.isSafeInteger(N.offset)||N.offset<s||!("chunks"in N)||!Array.isArray(N.chunks)||N.chunks.length>3)throw p("Invalid output page");let j=s;s=N.offset;for(let z of N.chunks){if(!Q(z))throw p("Invalid output chunk");let[O,Z]=z,B=l[O].decode(Buffer.from(Z,"base64"),{stream:!0});if(B&&!M.signal.aborted)u.onChunk({stream:O,text:B})}if(s===j){if(w)break;await new Promise((z)=>setTimeout(z,10))}}for(let w of["stdout","stderr"]){let N=l[w].decode();if(N&&!M.signal.aborted)u.onChunk({stream:w,text:N})}}let K=Promise.all([A,R(P.stdout,"stdout"),R(P.stderr,"stderr"),q()]).then(async()=>{let s=JSON.parse(await H(n,["cat",`${y}.exit`],void 0,30000,M.signal));if(!X(s))throw p("Invalid command result");if(s.workspaceRoot!==void 0)h?.(s.workspaceRoot,s.workspaceStable===!0);return{exitCode:s.exitCode,timedOut:s.timedOut}});K.catch(()=>{});async function d(){await H(n,["python3","-c",xe,y],void 0,1000)}try{if(u.signal?.aborted)k();let s=_?"cancelled":await Promise.race([K,E]);if(s==="cancelled"){try{await d()}catch{throw await U(()=>n.close(),1000).catch(()=>{}),p("Process cancellation could not be confirmed; VM termination was requested","outcome_unknown")}return await U(()=>K,250).catch(()=>{}),v.abort(),{exitCode:null,timedOut:!0}}return s}catch(s){try{await d()}catch{await U(()=>n.close(),1000).catch(()=>{})}throw s}finally{M.abort(),v.abort();for(let s of C)s.cancel().catch(()=>{});clearTimeout(f),u.signal?.removeEventListener("abort",k),await H(n,["rm","-f",y,`${y}.exit`,`${y}.out`],void 0,250).catch(()=>{})}}import{posix as J}from"node:path";var Te=`import os,sys,json,stat
|
|
148
|
+
${V}
|
|
149
|
+
op,p=sys.argv[1:3]
|
|
150
|
+
def info(p):
|
|
151
|
+
s=os.stat(p) if os.path.normpath(p)==workspace else os.lstat(p)
|
|
152
|
+
return dict(path=p,type='symlink' if stat.S_ISLNK(s.st_mode) else 'directory' if stat.S_ISDIR(s.st_mode) else 'file',size=s.st_size,modifiedAt=s.st_mtime*1000)
|
|
153
|
+
try:
|
|
154
|
+
if op=='read':
|
|
155
|
+
import base64
|
|
156
|
+
with open(p,'rb') as f: print(base64.b64encode(f.read()).decode())
|
|
157
|
+
elif op=='write':
|
|
158
|
+
os.makedirs(os.path.dirname(p),exist_ok=True)
|
|
159
|
+
m=int(sys.argv[3],8) if sys.argv[3] else None
|
|
160
|
+
fd=os.open(p,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,0o666 if m is None else m)
|
|
161
|
+
if m is not None: os.fchmod(fd,m)
|
|
162
|
+
with os.fdopen(fd,'wb') as f: f.write(sys.stdin.buffer.read())
|
|
163
|
+
elif op=='mkdir': os.makedirs(p,exist_ok=True)
|
|
164
|
+
elif op=='stat': print(json.dumps(info(p)))
|
|
165
|
+
elif op=='list': print(json.dumps([info(os.path.join(p,n)) for n in os.listdir(p)]))
|
|
166
|
+
elif op=='remove':
|
|
167
|
+
if os.path.isdir(p) and not os.path.islink(p):
|
|
168
|
+
if sys.argv[3]=='true':
|
|
169
|
+
import shutil
|
|
170
|
+
shutil.rmtree(p)
|
|
171
|
+
else: os.rmdir(p)
|
|
172
|
+
else: os.unlink(p)
|
|
173
|
+
except FileNotFoundError: print('SDK_FILE_NOT_FOUND')
|
|
174
|
+
except OSError: print('SDK_FILE_ERROR')
|
|
175
|
+
`,Ee=134217728;function me(n,u){let h=u.modifiedUnixNs/1000000000n,y=u.modifiedUnixNs-h*1000000000n;return{path:n,type:u.isSymlink||u.mode&Ee?"symlink":u.isDir?"directory":"file",size:Number(u.size),modifiedAt:(Number(h)+Number(y)*0.000000001)*1000}}function fe(n,u,h,y){let x=(f,S,v,P,C="")=>u(f,async()=>{let R=await H(await n(f),["python3","-c",Te,S,v,C],P);if(R.trim()==="SDK_FILE_NOT_FOUND")throw p("File does not exist","file_not_found");if(R.trim()==="SDK_FILE_ERROR")throw p("File operation failed; check permissions and recursive removal","invalid_argument");return R});function _(f,S){let v=J.normalize(S);if(S!==v)return;if(v==="/workspace"||v.startsWith("/workspace/")){let P=h(f);if(!P)return;let C=J.join(P,v.slice(10));return C===P||C.startsWith(`${P}/`)?C:void 0}return v.startsWith("/home/tenki/")?v:void 0}async function k(f,S,v){let P=Promise.resolve().then(S);try{return await U(()=>P,30000)}catch(C){let R=G(C).code;if(f==="write"&&R==="timeout")throw await P.catch(()=>{}),p("File write exceeded its deadline; the native write was drained and may have completed","outcome_unknown");if(R==="auth"||R==="invalid_argument"||R==="unsupported")return v();throw C}}let E=(f,S,v,P)=>u(f,async()=>{let C=await n(f),R=_(C,S);if(!R)return P();try{return await U(()=>v(C,R),30000)}catch(D){if(G(D).code==="file_not_found")throw p("File does not exist","file_not_found");return P()}});return{writeCreatesParents:!0,writeSupportsMode:!0,read:(f,S)=>u(f,async()=>{let v=_(await n(f),S),P=async()=>new Uint8Array(Buffer.from(await x(f,"read",S),"base64"));return v?k("read",async()=>(await n(f)).readFile(v),P):P()}),write:(f,S,v,P)=>u(f,async()=>{let C=_(await n(f),S),R=P?.mode,D=async()=>{await x(f,"write",S,v,R===void 0?"":R.toString(8))},M=async()=>{let A=await n(f);if(R===void 0)return A.writeFile(C??S,v);await A.writeFileStream(C??S,new Blob([new Uint8Array(v)]).stream(),{mode:R,truncate:!0})};if(C)await k("write",M,D);else await D()}),mkdir:async(f,S)=>{if(["/","/workspace"].includes(J.normalize(S)))y(await n(f));try{await x(f,"mkdir",S)}finally{if(["/","/workspace"].includes(J.normalize(S)))y(await n(f))}},remove:async(f,S,v)=>{y(await n(f));try{await x(f,"remove",S,void 0,String(v.recursive))}finally{y(await n(f))}},stat:(f,S)=>E(f,S,async(v,P)=>me(S,await v.fs.stat(P)),async()=>{let v=JSON.parse(await x(f,"stat",S));if(!L(v))throw p("Invalid file metadata");return F(v)}),list:(f,S)=>E(f,S,async(v,P)=>(await v.fs.list(P,{includeHidden:!0})).map((C)=>me(J.join(S,J.basename(C.path)),C)),async()=>{let v=JSON.parse(await x(f,"list",S));if(!Array.isArray(v))throw p("Invalid file listing");return v.map((P)=>{if(!L(P))throw p("Invalid file metadata");return F(P)})})}}var Y="sandbox-sdk-key",te="sandbox-sdk-created-at",Pe=new Set([Y,te,"enable_opencode"]),Ne={small:{cpu:1,memoryMb:1024,diskGb:10},medium:{cpu:2,memoryMb:4096,diskGb:20},large:{cpu:4,memoryMb:8192,diskGb:40}};function _e(n){if(n===void 0)return{};let u=t(n)?Ne[n]:n,h=u?.diskGb??5;if(!u||!Number.isInteger(u.cpu)||u.cpu<1||u.cpu>128||!Number.isInteger(u.memoryMb)||u.memoryMb<128||u.memoryMb>524288||u.memoryMb%2||!Number.isInteger(h)||h<5||h>100)throw p("Size requires 1–128 CPUs, even memoryMb from 128–524288, and 5–100 diskGb","unsupported");return{cpuCores:u.cpu,memoryMb:u.memoryMb,diskSizeGb:h}}function ee(n){let u=Number(n.metadata[te]);if(!Number.isFinite(u)||u<=0||n.metadata["sandbox-sdk"]!=="1")throw p("Session was not created by Sandbox SDK or its metadata is missing","not_found");return{id:n.id,key:n.metadata[Y],labels:Object.fromEntries(Object.entries(n.metadata).filter(([h])=>!Pe.has(h))),createdAt:u,state:n.state==="RUNNING"?"running":["PAUSED","PAUSING","RESUMING"].includes(n.state)?"paused":"stopped"}}var Re=["sh","-c","set -e; mkdir -p /home/tenki/.sandbox-sdk /tmp; exec 9>/home/tenki/.sandbox-sdk/setup.lock; flock -x 9; if [ ! -e /workspace ]; then mkdir -p /home/tenki/workspace; ln -s /home/tenki/workspace /workspace; elif [ ! -L /workspace ] && [ ! -e /home/tenki/workspace ]; then mv /workspace /home/tenki/workspace; ln -s /home/tenki/workspace /workspace; fi; flock -u 9; if [ ! -e /tmp/.sandbox-sdk ]; then ln -s /home/tenki/.sandbox-sdk /tmp/.sandbox-sdk; fi; test -L /tmp/.sandbox-sdk; command -v python3 git tar nohup setsid >/dev/null; readlink -f /workspace"];function pe(n,u){let h,y=new Map,x=new Map,_=new WeakMap,k=new Map;function E(d){let s=k.get(d.id);if(!s)s={active:0,revision:0,overlap:!1,untracked:!1},k.set(d.id,s);return s}function f(d){_.delete(d),E(d).revision++}function S(d,s){let l=E(d);if(!l.active&&!l.untracked&&(s==="/home/tenki"||s.startsWith("/home/tenki/")))_.set(d,s)}async function v(d){f(d);let s=E(d).revision,l=(await H(d,Re)).replace(/\n$/,"");if(s===E(d).revision)S(d,l)}let P=n.requestTimeoutMs??30000,C=n.resumeTimeoutMs??180000,R=(d,s)=>U(d,P,s),D=(d,s,l)=>U(d,s,l);async function M(){return h??=(async()=>{if(!Number.isSafeInteger(P)||P<=0)throw p("requestTimeoutMs must be a positive integer","invalid_argument");if(!Number.isSafeInteger(C)||C<=0||C>900000)throw p("resumeTimeoutMs must be an integer from 1 to 900000","invalid_argument");if(n.waitTimeoutMs!==void 0&&(!Number.isSafeInteger(n.waitTimeoutMs)||n.waitTimeoutMs<=0||n.waitTimeoutMs>900000))throw p("waitTimeoutMs must be an integer from 1 to 900000","invalid_argument");let d=n.apiKey??n.authToken??(process.env.TENKI_AUTH_TOKEN?.trim()||process.env.TENKI_API_KEY?.trim());if(!d)throw p("Tenki API key is missing. Authentication is required. Set TENKI_API_KEY or TENKI_AUTH_TOKEN or pass apiKey.","auth");let{TenkiSandbox:s}=await g("@tenkicloud/sandbox","tenki",u);return new s({authToken:d,baseUrl:n.baseUrl})})()}async function A(d,s,l){try{return await l()}catch(w){throw G(w,s,d,[n.apiKey??n.authToken??""])}}async function q(d){let s=y.get(d);if(s)return s;await K.connect(d);let l=y.get(d);if(!l)throw p("Session is detached","not_found");return l}let K={name:"tenki",keyMode:"best-effort",inlineActivity:!0,processRecordRoot:"/home/tenki/.sandbox-sdk/procs",capabilities:new Set(["pause","snapshot","size","network-policy"]),create:(d)=>A("create",void 0,async()=>{if(d.idleTimeoutMs!==void 0)throw p("Tenki no longer auto-pauses on idle; idleTimeoutMs is unavailable","unsupported");if(d.timeoutMs!==void 0&&(!Number.isSafeInteger(d.timeoutMs)||d.timeoutMs<=0))throw p("timeoutMs must be a positive integer","invalid_argument");if(d.signal?.aborted)throw p("Creation aborted","aborted");let s=_e(d.size),l=r(d.network)?d.network.allow:void 0;if(l?.some((B)=>B.length>253||!/^(\*\.)?(?:[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(B)))throw p("Network allow entries must be DNS hostnames or leading wildcard domains","unsupported");let w={...d.labels,"sandbox-sdk":"1",[te]:String(Date.now())};if(delete w[Y],d.key!==void 0)w[Y]=d.key;let N={...s,metadata:w,env:d.env,sticky:!1,maxDurationMs:d.timeoutMs,allowInbound:!0,allowOutbound:d.network!=="none"&&l?.length!==0,allowDomains:l,waitReady:!1};if(d.from)N.snapshotId=d.from;else N.image=n.image;if(n.pauseRetentionMs!==void 0)N.pauseRetentionMs=n.pauseRetentionMs;if(n.volumes!==void 0)N.volumes=n.volumes;if(n.workspaceId!==void 0)N.workspaceId=n.workspaceId;let z=(await M()).create(N),O;try{O=await R(()=>z,d.signal)}catch(B){throw z.then((W)=>R(()=>W.close())).catch(()=>{}),B}y.set(O.id,O);let Z="waitReady";try{let B=n.waitTimeoutMs??180000;if(await ce(O,B,d.signal),Z="validate",d.signal?.aborted)throw p("Creation aborted","aborted");if(s.cpuCores!==void 0&&(O.cpuCores!==s.cpuCores||O.memoryMb!==s.memoryMb||O.diskSizeGb!==s.diskSizeGb))throw p("Tenki returned different resources than requested","unsupported");if(O.outboundEnabled!==N.allowOutbound||l?.length&&(l.some((W)=>!O.egress.allowDomains.includes(W))||O.egress.allowDomains.some((W)=>!l.includes(W))||O.egress.allowCidrs.length))throw p("Tenki did not confirm the requested network policy","unsupported");return ee(O)}catch(B){let W={id:O.id,state:O.state,stage:Z},re;try{await K.destroy(O.id)}catch(we){re=G(we).code}throw de(d.signal?.aborted?p("Creation aborted","aborted"):B,W,[n.apiKey??n.authToken??""],re)}}),list:(d)=>A("list",void 0,async()=>(await R(async()=>(await M()).list(n.workspaceId===void 0?void 0:{workspaceId:n.workspaceId}))).filter((s)=>s.state!=="TERMINATED"&&s.state!=="TERMINATING"&&Object.entries({...d,"sandbox-sdk":"1"}).every(([l,w])=>s.metadata[l]===w)).flatMap((s)=>{try{return[ee(s)]}catch(l){if(G(l).code!=="not_found")throw l;return[]}})),async find(d){let s=(await K.list({[Y]:d}))[0];return s?K.connect(s.id):void 0},connect:(d)=>A("connect",d,async()=>{let s=await R(async()=>(await M()).get(d)),l=ee(s);if(["TERMINATED","TERMINATING"].includes(s.state))throw p("Session has terminated","not_found");if(l.state==="running")await v(s);return y.set(d,s),l}),destroy(d){let s=x.get(d);if(s)return s;let l=A("destroy",d,async()=>{let w=!1;try{await R(async()=>(await q(d)).close()),w=!0}catch(N){if(G(N).code!=="not_found")throw N;w=!0}finally{if(y.delete(d),w)k.delete(d)}}).finally(()=>x.delete(d));return x.set(d,l),l},async close(d){y.delete(d)},exec:(d,s)=>A("exec",d,async()=>{let l=await q(d);f(l);let w=E(l),N=w.revision;if(w.active++,w.active>1)w.overlap=!0;let j;try{return await le(l,s,(z,O)=>{if(!O)w.untracked=!0;j=z})}finally{if(j===void 0)w.untracked=!0;if(w.active--,!w.overlap&&N===w.revision&&j!==void 0)S(l,j);if(!w.active)w.overlap=!1}}),files:fe(q,(d,s)=>A("files",d,s),(d)=>{let s=E(d);return s.active||s.untracked?void 0:_.get(d)},f),previewUrl:(d,s)=>A("preview",d,async()=>{let l=await q(d),w=await R(()=>l.exposePort(s,n.previewTtlMs===void 0?void 0:{ttlMs:n.previewTtlMs}));return{url:w.previewUrl,expiresAt:w.expiresAt?.getTime()}}),pause:(d)=>A("pause",d,async()=>{let s=await q(d),l=n.waitTimeoutMs??180000;await U(()=>s.pause(),l),await D((w)=>s.waitPaused(l,w),l)}),resume:(d)=>A("resume",d,async()=>{let s=await q(d);await U(()=>s.resume(),C);let l=n.waitTimeoutMs??180000;await D((w)=>s.waitResumed(l,w),l),await v(s)}),snapshot:(d,s)=>A("snapshot",d,async()=>{let l=s?.expiresInMs;if(l!==void 0&&(!Number.isSafeInteger(l)||l<0))throw p("expiresInMs must be a non-negative integer","invalid_argument");let w=await M(),N=await R(()=>w.createSnapshot(d,l?{async:!0,expiresAt:new Date(Date.now()+l)}:{async:!0})),j=n.waitTimeoutMs??300000;return{id:(await U((O)=>w.waitSnapshotReady(N.id,j,O),j)).id}}),native(d){let s=y.get(d);if(!s)throw p("Session is detached; connect first","not_found");return f(s),E(s).untracked=!0,s}};return K}function Tt(n={}){return pe(n,()=>import("@tenkicloud/sandbox"))}export{Tt as tenki};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** Official API sources (checked against @tenkicloud/sandbox 1.4.1 types):
|
|
2
|
+
* https://tenki.cloud/docs/sandbox/sdk.md
|
|
3
|
+
* https://tenki.cloud/docs/sandbox/sessions.md
|
|
4
|
+
* https://tenki.cloud/docs/sandbox/snapshots.md
|
|
5
|
+
* https://tenki.cloud/docs/sandbox/base-image.md
|
|
6
|
+
* https://www.npmjs.com/package/@tenkicloud/sandbox
|
|
7
|
+
*/
|
|
8
|
+
import type { ClientOptions, CreateOptions, CreateSnapshotOptions, ListOptions, Session as NativeSession, SessionFs, Snapshot } from "@tenkicloud/sandbox";
|
|
9
|
+
import type { Provider } from "../../provider.js";
|
|
10
|
+
export interface TenkiOptions {
|
|
11
|
+
/** Defaults to TENKI_AUTH_TOKEN, then TENKI_API_KEY; required on first use. */
|
|
12
|
+
apiKey?: string;
|
|
13
|
+
/** @deprecated Use apiKey. Removed in 1.0.0. */
|
|
14
|
+
authToken?: string;
|
|
15
|
+
/** Defaults to TENKI_API_ENDPOINT, then TENKI_API_URL, then https://api.tenki.cloud. */
|
|
16
|
+
baseUrl?: string;
|
|
17
|
+
/** Base image; default: the Tenki service default image. */
|
|
18
|
+
image?: string;
|
|
19
|
+
/** Control-plane deadline. Default: 30 s. */
|
|
20
|
+
requestTimeoutMs?: number;
|
|
21
|
+
/** Readiness budget, 1–900000 ms. Default: 180 s; snapshots: 300 s. */
|
|
22
|
+
waitTimeoutMs?: number;
|
|
23
|
+
/** Resume RPC deadline, separate from readiness. Default: 180 seconds; maximum: 15 minutes. */
|
|
24
|
+
resumeTimeoutMs?: number;
|
|
25
|
+
/** How long Tenki keeps a paused sandbox before deleting it. Default: Tenki's retention. */
|
|
26
|
+
pauseRetentionMs?: number;
|
|
27
|
+
/** Tenki volumes to mount, such as `[{ volumeId: "vol_123", mountPath: "/data" }]`. */
|
|
28
|
+
volumes?: CreateOptions["volumes"];
|
|
29
|
+
/** Workspace for service credentials that span workspaces. Workspace API keys infer it. */
|
|
30
|
+
workspaceId?: string;
|
|
31
|
+
/** Lifetime of each preview URL. Default: Tenki's preview TTL. */
|
|
32
|
+
previewTtlMs?: number;
|
|
33
|
+
}
|
|
34
|
+
export type TenkiCapability = "pause" | "snapshot" | "size" | "network-policy";
|
|
35
|
+
export type TenkiProvider = Provider<NativeSession, TenkiCapability>;
|
|
36
|
+
type DataPlaneClient = Awaited<ReturnType<NativeSession["requireDataPlane"]>>;
|
|
37
|
+
type NativeRun = DataPlaneClient["run"];
|
|
38
|
+
/** True when `T` is `any`, which is what an uninstalled optional peer's types resolve to. */
|
|
39
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
40
|
+
/** A request frame for the data-plane `run` stream. */
|
|
41
|
+
export type TenkiRunRequest = Parameters<NativeRun>[0] extends AsyncIterable<infer T> ? T : never;
|
|
42
|
+
type NativeRunResponse = IsAny<NativeRun> extends true ? any : ReturnType<NativeRun> extends AsyncIterable<infer T> ? T : never;
|
|
43
|
+
type NativeRunOptions = IsAny<NativeRun> extends true ? {
|
|
44
|
+
signal?: AbortSignal;
|
|
45
|
+
} : NonNullable<Parameters<NativeRun>[1]>;
|
|
46
|
+
type NativeRunPayload = NonNullable<NativeRunResponse["frame"]>["payload"];
|
|
47
|
+
type NativeRunVariant<Case extends NativeRunPayload["case"]> = Extract<NativeRunPayload, {
|
|
48
|
+
case: Case;
|
|
49
|
+
}>;
|
|
50
|
+
/** A response frame from the data-plane `run` stream. Each variant keeps only the
|
|
51
|
+
* fields the adapter reads, so the native frames satisfy it and test fixtures can
|
|
52
|
+
* build it without protobuf message metadata.
|
|
53
|
+
*/
|
|
54
|
+
export interface TenkiRunResponse {
|
|
55
|
+
frame?: {
|
|
56
|
+
payload: NativeRunVariant<"stdout" | "stderr"> | {
|
|
57
|
+
case: "exit";
|
|
58
|
+
value: Pick<NativeRunVariant<"exit">["value"], "exitCode">;
|
|
59
|
+
} | {
|
|
60
|
+
case: Exclude<NativeRunPayload["case"], "stdout" | "stderr" | "exit">;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** The data-plane client calls the adapter makes. */
|
|
65
|
+
export interface TenkiDataPlane {
|
|
66
|
+
run(requests: AsyncIterable<TenkiRunRequest>, options: Required<Pick<NativeRunOptions, "signal">>): AsyncIterable<TenkiRunResponse>;
|
|
67
|
+
}
|
|
68
|
+
/** The parts of a Tenki session the adapter uses. The data-plane entry points are
|
|
69
|
+
* optional: without them, commands fall back to buffered `run()` pages.
|
|
70
|
+
*/
|
|
71
|
+
export type TenkiSession = Pick<NativeSession, "id" | "state" | "metadata" | "cpuCores" | "memoryMb" | "diskSizeGb" | "outboundEnabled" | "egress" | "run" | "readFile" | "writeFile" | "writeFileStream" | "waitReady" | "waitPaused" | "waitResumed" | "refresh" | "pause" | "resume" | "close" | "exposePort" | "reauthOnUnauthenticated"> & {
|
|
72
|
+
fs: Pick<SessionFs, "stat" | "list">;
|
|
73
|
+
dataPlaneRPC?(): TenkiDataPlane | undefined;
|
|
74
|
+
requireDataPlane?(verifyServing?: boolean): Promise<TenkiDataPlane>;
|
|
75
|
+
dataPlaneProvisioningPending(plane: TenkiDataPlane): boolean;
|
|
76
|
+
markDataPlaneServing(plane: TenkiDataPlane): void;
|
|
77
|
+
refreshHintedDataPlane(plane: TenkiDataPlane): Promise<boolean>;
|
|
78
|
+
};
|
|
79
|
+
/** A session whose client streams commands over the data plane. */
|
|
80
|
+
export type StreamingSession = TenkiSession & Required<Pick<TenkiSession, "requireDataPlane">>;
|
|
81
|
+
/** The parts of a Tenki client the adapter uses. */
|
|
82
|
+
export interface TenkiClient<S extends TenkiSession> {
|
|
83
|
+
create(options: CreateOptions): Promise<S>;
|
|
84
|
+
get(id: string): Promise<S>;
|
|
85
|
+
list(options: ListOptions | undefined): Promise<S[]>;
|
|
86
|
+
createSnapshot(id: string, options: CreateSnapshotOptions): Promise<Pick<Snapshot, "id">>;
|
|
87
|
+
waitSnapshotReady(id: string, timeoutMs: number, signal: AbortSignal): Promise<Pick<Snapshot, "id">>;
|
|
88
|
+
}
|
|
89
|
+
/** The parts of the Tenki SDK the adapter uses: the real `@tenkicloud/sandbox` module, or a test fixture. */
|
|
90
|
+
export interface TenkiModule<S extends TenkiSession> {
|
|
91
|
+
TenkiSandbox: new (options: ClientOptions) => TenkiClient<S>;
|
|
92
|
+
}
|
|
93
|
+
/** @internal The adapter behind `tenki()`. `load` imports the Tenki SDK; tests pass a fixture. */
|
|
94
|
+
export declare function createTenkiProvider<S extends TenkiSession>(options: TenkiOptions, load: () => Promise<TenkiModule<S>>): Provider<S, TenkiCapability>;
|
|
95
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { TenkiSession as Session } from "./provider.js";
|
|
2
|
+
/** SDK 1.4.1 waits for stream EOF even after RUNNING, and does not recover a
|
|
3
|
+
* silent stream. Reserve the rest of the original budget for bounded refreshes.
|
|
4
|
+
* Successful streams keep their existing path and make no additional RPCs.
|
|
5
|
+
*/
|
|
6
|
+
export declare function waitReady(value: Session, timeoutMs: number, signal?: AbortSignal): Promise<void>;
|
|
7
|
+
export declare const workspaceSetup = "workspace=globals().get('v',{}).get('workspace','/workspace')\nhome=os.path.join(os.path.dirname(workspace),'home','tenki')\ntmp=os.path.join(os.path.dirname(workspace),'tmp')\nos.makedirs(home+'/.sandbox-sdk',exist_ok=True)\nos.makedirs(tmp,exist_ok=True)\nimport fcntl\nwith open(home+'/.sandbox-sdk/setup.lock','w') as setup_lock:\n fcntl.flock(setup_lock,fcntl.LOCK_EX)\n if not os.path.exists(home+'/.sandbox-sdk/prepared'):\n if not os.path.exists(workspace):\n os.makedirs(home+'/workspace',exist_ok=True)\n try: os.symlink(home+'/workspace',workspace)\n except FileExistsError: pass\n elif not os.path.islink(workspace) and not os.path.exists(home+'/workspace'):\n os.rename(workspace,home+'/workspace'); os.symlink(home+'/workspace',workspace)\n with open(home+'/.sandbox-sdk/prepared','w'): pass\nif not os.path.exists(tmp+'/.sandbox-sdk'):\n try: os.symlink(home+'/.sandbox-sdk',tmp+'/.sandbox-sdk')\n except FileExistsError: pass\n";
|