@opencoredev/sandbox-sdk 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/ai.js +1 -1
  3. package/dist/chunk-11mbpwem.js +17 -0
  4. package/dist/{chunk-q5vqajhg.js → chunk-19gteae8.js} +2 -2
  5. package/dist/chunk-1k6yz176.js +1 -0
  6. package/dist/chunk-2z6fxyg5.js +2 -0
  7. package/dist/chunk-305dymgq.js +2 -0
  8. package/dist/chunk-348pdz09.js +5 -0
  9. package/dist/{chunk-k60b4r27.js → chunk-3zd78ha4.js} +2 -2
  10. package/dist/chunk-5gnqph3c.js +78 -0
  11. package/dist/chunk-6bemkxcx.js +290 -0
  12. package/dist/chunk-6nf686jb.js +26 -0
  13. package/dist/{chunk-nw845a93.js → chunk-c1wemt0y.js} +8 -8
  14. package/dist/{chunk-bd481sb7.js → chunk-drgkmewv.js} +1 -1
  15. package/dist/chunk-ea8y7y2p.js +2 -0
  16. package/dist/{chunk-bfzdkjjw.js → chunk-g0vk7g1k.js} +2 -2
  17. package/dist/chunk-n7x9ha44.js +4 -0
  18. package/dist/{chunk-8786zrns.js → chunk-r8xnq6v3.js} +2 -2
  19. package/dist/{chunk-hzbssbep.js → chunk-rnksrxfc.js} +4 -4
  20. package/dist/chunk-tvw3kb8b.js +2 -0
  21. package/dist/http.d.ts +3 -0
  22. package/dist/index.js +1 -1
  23. package/dist/mastra.js +1 -1
  24. package/dist/memory.js +1 -1
  25. package/dist/openai.js +1 -1
  26. package/dist/provider.d.ts +25 -0
  27. package/dist/provider.js +1 -1
  28. package/dist/providers/agentos/index.js +2 -2
  29. package/dist/providers/boat/index.js +1 -1
  30. package/dist/providers/boxd/index.js +11 -13
  31. package/dist/providers/daytona/index.js +12 -12
  32. package/dist/providers/e2b/index.js +1 -1
  33. package/dist/providers/freestyle/execute.d.ts +3 -1
  34. package/dist/providers/freestyle/index.js +6 -15
  35. package/dist/providers/local/index.js +2 -2
  36. package/dist/providers/railway/index.js +1 -1
  37. package/dist/providers/sandboxer/index.js +1 -1
  38. package/dist/providers/superserve/execute.d.ts +3 -1
  39. package/dist/providers/superserve/index.js +21 -23
  40. package/dist/providers/tenki/index.js +14 -24
  41. package/dist/providers/upstash/index.js +10 -10
  42. package/dist/providers/upstash/provider.d.ts +1 -1
  43. package/dist/providers/vercel/index.js +1 -1
  44. package/dist/run.d.ts +9 -0
  45. package/dist/shared/guest.d.ts +28 -1
  46. package/dist/testing.js +3 -3
  47. package/dist/tools.js +1 -1
  48. package/dist/types.d.ts +5 -1
  49. package/package.json +1 -1
  50. package/dist/chunk-23tjmd39.js +0 -8
  51. package/dist/chunk-6a3wkj84.js +0 -2
  52. package/dist/chunk-8wq767xb.js +0 -17
  53. package/dist/chunk-9w9rddra.js +0 -2
  54. package/dist/chunk-ckym4cht.js +0 -23
  55. package/dist/chunk-hgrwyjrb.js +0 -2
  56. package/dist/chunk-kk1hw8wa.js +0 -1
  57. package/dist/chunk-vz47a139.js +0 -5
  58. package/dist/chunk-x681p5d2.js +0 -68
  59. package/dist/chunk-xgxfy2n8.js +0 -4
@@ -0,0 +1,290 @@
1
+ import{n}from"./chunk-2ts3evzh.js";import{t,o,r,e}from"./chunk-n7x9ha44.js";import{createHash as g}from"node:crypto";var p=(s,...l)=>`python3 -S -c ${n(s)} ${l.map(n).join(" ")}`;function j(s,l="exec(c,{'__name__':'__main__','__builtins__':__builtins__})",f="True"){if(s.includes("'''")||s.endsWith("\\"))throw Error("Supervisor source cannot be embedded");let i=g("sha256").update(s).digest("hex").slice(0,16);return`import os,sys,marshal
2
+ s=r'''${s}'''
3
+ p='/tmp/.sandbox-sdk/py-${i}.'+sys.implementation.cache_tag
4
+ c=None
5
+ try:
6
+ with open(p,'rb') as f:
7
+ t=os.fstat(f.fileno())
8
+ if t.st_uid==os.geteuid() and not t.st_mode&0o022:
9
+ k,c=marshal.load(f)
10
+ if k!=(sys.version,s): c=None
11
+ except Exception: c=None
12
+ w=c is None
13
+ if w: c=compile(s,'<sandbox-sdk>','exec')
14
+ if w and ${f}:
15
+ t=p+'.'+str(os.getpid())
16
+ try:
17
+ with open(os.open(t,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600),'wb') as f: marshal.dump(((sys.version,s),c),f)
18
+ os.replace(t,p)
19
+ except OSError:
20
+ try: os.unlink(t)
21
+ except OSError: pass
22
+ ${l}
23
+ `}var y=`def serve(code,z):
24
+ import fcntl,_signal as signal
25
+ base=os.path.dirname(z)
26
+ try:
27
+ os.makedirs(z,mode=0o700,exist_ok=True)
28
+ lock=os.open(z+'/lock',os.O_WRONLY|os.O_CREAT,0o600)
29
+ except OSError: return
30
+ try: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
31
+ except OSError: return
32
+ try:
33
+ with open('/proc/sys/kernel/random/boot_id') as f: boot=f.read().strip()
34
+ try: os.unlink(z+'/fifo')
35
+ except FileNotFoundError: pass
36
+ os.mkfifo(z+'/fifo',0o600)
37
+ q=os.open(z+'/fifo',os.O_RDWR|os.O_NONBLOCK)
38
+ except OSError:
39
+ # A sandbox that cannot host a zygote must not relaunch one for every command.
40
+ with open(z+'/off','w'): pass
41
+ return
42
+ me=('%d %s\\n'%(os.getpid(),boot)).encode()
43
+ t=z+'/pid.%d'%os.getpid()
44
+ with open(t,'wb') as f: f.write(me)
45
+ os.replace(t,z+'/pid')
46
+ signal.signal(signal.SIGCHLD,signal.SIG_IGN)
47
+ def mine():
48
+ try:
49
+ with open(z+'/pid','rb') as f: return f.read()==me
50
+ except OSError: return False
51
+ try: loop(code,z,base,q,lock,mine)
52
+ finally:
53
+ # Any exit withdraws the record: new commands skip it, waiting ones take theirs back.
54
+ if mine(): os.unlink(z+'/pid')
55
+ def loop(code,z,base,q,lock,mine):
56
+ import select,time
57
+ idle=time.monotonic()+30
58
+ pending=b''
59
+ while True:
60
+ ready=select.select([q],[],[],5)[0]
61
+ if not ready:
62
+ # Stop when replaced, cleared by a client or removed with the sandbox's files.
63
+ if not mine(): break
64
+ # A claim matters while its client waits or its worker runs. Age alone never
65
+ # releases one: only proof that both are gone, or a claim from another boot.
66
+ for entry in os.scandir(z):
67
+ try:
68
+ if entry.name.startswith('c-') and released(entry.path): os.unlink(entry.path)
69
+ except FileNotFoundError: pass
70
+ if time.monotonic()<idle: continue
71
+ # Idle: stop advertising, then serve whatever was already queued.
72
+ if mine(): os.unlink(z+'/pid')
73
+ try: pending+=os.read(q,65536)
74
+ except BlockingIOError: pass
75
+ *lines,pending=pending.split(b'\\n')
76
+ for line in lines:
77
+ try:
78
+ c,i=line.decode().split(' ')
79
+ c=int(c)
80
+ except ValueError: continue
81
+ if len(i)!=36 or i.strip('0123456789abcdef-'): continue
82
+ if os.fork()==0:
83
+ try:
84
+ # The lock and queue belong to this zygote, not to a long command.
85
+ os.close(lock); os.close(q)
86
+ handle(code,z,c,base+'/run-'+i,z+'/c-'+i)
87
+ finally: os._exit(0)
88
+ if not ready: break
89
+ idle=time.monotonic()+30
90
+ def birth(pid):
91
+ # A process's start time: with the boot ID, a PID that was reused is not the same process.
92
+ try:
93
+ with open('/proc/%d/stat'%pid,'rb') as f: return f.read().rsplit(b')',1)[1].split()[19].decode()
94
+ except (OSError,IndexError,ValueError): return None
95
+ def released(path):
96
+ # Claim line 1: worker PID and start, client PID and start, boot ID; '-' when unknown.
97
+ # The client writes '- - pid - boot' when it runs a request itself. A claim still
98
+ # being written, or in a form this code cannot read, stays.
99
+ try:
100
+ with open(path) as f: fields=f.readline().split()
101
+ with open('/proc/sys/kernel/random/boot_id') as f: boot=f.read().strip()
102
+ except OSError: return False
103
+ if len(fields)!=5: return False
104
+ if fields[4]!=boot: return True
105
+ for pid,start in ((fields[0],fields[1]),(fields[2],fields[3])):
106
+ if pid=='-': continue
107
+ try: now=birth(int(pid))
108
+ except ValueError: return False
109
+ if now is not None and start in ('-',now): return False
110
+ return True
111
+ def handle(code,z,c,root,claim):
112
+ import _signal as signal
113
+ signal.signal(signal.SIGCHLD,signal.SIG_DFL)
114
+ def started(): return birth(c)
115
+ start=started()
116
+ # A client that is gone has no one to run the command for.
117
+ if start is None: return
118
+ try:
119
+ with open('/proc/sys/kernel/random/boot_id') as f: boot=f.read().strip()
120
+ except OSError: return
121
+ # Whoever creates the claim owns the request: this child, or the client giving up.
122
+ try: fd=os.open(claim,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
123
+ except OSError: return
124
+ os.write(fd,('%d %s %d %s %s\\n'%(os.getpid(),birth(os.getpid()) or '-',c,start,boot)).encode())
125
+ try:
126
+ # The client keeps its own stdio on fds 7-9, which it never redirects.
127
+ fds=[os.open('/proc/%d/fd/%d'%(c,7+n),os.O_RDONLY if n==0 else os.O_WRONLY) for n in range(3)]
128
+ cwd=os.open('/proc/%d/cwd'%c,os.O_RDONLY)
129
+ with open('/proc/%d/environ'%c,'rb') as f: env=f.read()
130
+ with open('/proc/%d/status'%c) as f: mask=int(next(l for l in f if l.startswith('Umask:')).split()[1],8)
131
+ except (OSError,StopIteration,ValueError):
132
+ if started()!=start: return
133
+ # Nothing has run: hand the request back. A live client whose stdio cannot be
134
+ # adopted, such as sockets, means this sandbox should not route commands here.
135
+ with open(z+'/off','w'): pass
136
+ os.kill(c,signal.SIGUSR2)
137
+ gone(c,start,claim)
138
+ return
139
+ if started()!=start: return
140
+ for n,x in enumerate(fds): os.dup2(x,n); os.close(x)
141
+ os.fchdir(cwd); os.close(cwd)
142
+ os.umask(mask)
143
+ os.environ.clear()
144
+ for item in env.split(b'\\0'):
145
+ k,s,v=item.partition(b'=')
146
+ if s: os.environb[k]=v
147
+ sys.argv=['-c',root]
148
+ status=0
149
+ try: exec(code,{'__name__':'__main__','__builtins__':__builtins__})
150
+ except SystemExit as e:
151
+ if isinstance(e.code,int): status=e.code
152
+ elif e.code is not None: print(e.code,file=sys.stderr); status=1
153
+ except BaseException:
154
+ import traceback
155
+ traceback.print_exc(); status=1
156
+ for f in (sys.stdout,sys.stderr):
157
+ try: f.flush()
158
+ except Exception: pass
159
+ os.write(fd,b'%d\\n'%(status&255)); os.close(fd)
160
+ # Release the client's pipes before waking it, so its exit ends the native exec.
161
+ null=os.open('/dev/null',os.O_RDWR)
162
+ for n in range(3): os.dup2(null,n)
163
+ if started()==start: os.kill(c,signal.SIGUSR1)
164
+ gone(c,start,claim)
165
+ def gone(c,start,claim):
166
+ import time
167
+ # The claim is only needed while its client can still decide; drop it after.
168
+ # A client still alive after 2 s leaves the claim to the zygote's liveness sweep.
169
+ for _ in range(2000):
170
+ if birth(c)!=start:
171
+ os.unlink(claim); return
172
+ time.sleep(.001)
173
+ `,w=(s)=>`/tmp/.sandbox-sdk/z-${g("sha256").update(s).digest("hex").slice(0,16)}`;function x(s){if(y.includes("'''"))throw Error("Zygote source cannot be embedded");return j(s,`if sys.argv[1:2]==['--serve']:
174
+ exec(r'''${y}''')
175
+ serve(c,sys.argv[2])
176
+ else: exec(c,{'__name__':'__main__','__builtins__':__builtins__})`,"sys.argv[1:2]==['--serve']")}function _(s,l){let f=w(s);return`{ P=${n(s)}; r=${n(l)}; z=${n(f)}; f="$z/c-\${r##*/run-}"; n=1
177
+ if [ ! -e "$z/off" ] && read -r k b 2>/dev/null <"$z/pid" && read -r o </proc/sys/kernel/random/boot_id && [ "$b" = "$o" ] && kill -0 "$k" 2>/dev/null; then
178
+ trap 'kill "$w" 2>/dev/null; { read -r o; read -r c; } <"$f"; exit "\${c:-70}"' USR1
179
+ trap 'kill "$w" 2>/dev/null; n=1' USR2
180
+ n=0; t=0
181
+ exec 7<&0 8>&1 9>&2
182
+ sleep 1 </dev/null >/dev/null 2>&1 7<&- 8>&- 9>&- & w=$!
183
+ printf '%s %s\\n' "$$" "\${r##*/run-}" 1<>"$z/fifo"
184
+ while :; do
185
+ wait "$w"
186
+ [ "$n" = 0 ] || break
187
+ t=$((t+1))
188
+ if [ -s "$f" ]; then
189
+ { read -r o _ <"$f" && kill -0 "$o"; } 2>/dev/null || exit 70
190
+ elif { ! kill -0 "$k" || [ "$t" -ge 3 ]; } 2>/dev/null && (set -C; printf '%s\\n' "- - $$ - $b" >"$f") 2>/dev/null; then
191
+ : >"$z/pid"; n=1; break
192
+ fi
193
+ sleep 1 </dev/null >/dev/null 2>&1 7<&- 8>&- 9>&- & w=$!
194
+ done
195
+ exec 7<&- 8>&- 9>&-
196
+ fi
197
+ python3 -S -c "$P" "$r"; c=$?
198
+ if [ -e "$z.seen" ]; then
199
+ { [ -e "$z/off" ] || ! command -v setsid >/dev/null || exec setsid env -i PATH="$PATH" python3 -S -c "$P" --serve "$z"; } </dev/null >/dev/null 2>&1 &
200
+ else : >"$z.seen" 2>/dev/null; fi
201
+ exit "$c"; }`}function z(s){let l=x(s),f=`${w(l)}.seen`,i=new Set;return{command(a,c,d){if(d!==void 0&&!/^[0-9a-f]*$/.test(d))throw Error("Supervisor spec must be hex");if(i.has(a))return d===void 0?_(l,c):`${_(l,c)} <<'SDKSPEC'
202
+ ${d}
203
+ SDKSPEC`;if(i.size>=1e4)i.clear();return i.add(a),`{ python3 -S -c ${n(s)} ${n(c)}${d===void 0?"":` ${d}`}; c=$?; : >${n(f)} 2>/dev/null; exit "$c"; }`},zygote:(a)=>_(l,a)}}var b=`def stdin_file():
204
+ try: return os.fdopen(os.memfd_create('sandbox-sdk-stdin'),'w+b')
205
+ except (AttributeError,OSError):
206
+ import tempfile
207
+ return tempfile.TemporaryFile()
208
+ class Process:
209
+ # A missing cwd fails the command, not the supervisor: the shell reports it on stderr and exits 2.
210
+ def argv(self,v):
211
+ try: os.chdir(v['cwd']); return ['sh','-c',v['command']]
212
+ except OSError: return ['sh','-c','cd "$1" || exit 2','sh',v['cwd']]
213
+ def __init__(self,v,env,stdin,session=False):
214
+ if not all(hasattr(os,name) for name in ['posix_spawn','waitstatus_to_exitcode']):
215
+ self.legacy(v,env,stdin,session); return
216
+ directory=os.open('.',os.O_RDONLY)
217
+ r,w=os.pipe(); e,x=os.pipe()
218
+ try:
219
+ argv=self.argv(v)
220
+ error=FileNotFoundError(2,os.strerror(2),'sh')
221
+ signals=[getattr(signal,s) for s in ['SIGPIPE','SIGXFZ','SIGXFSZ'] if hasattr(signal,s)]
222
+ for path in os.get_exec_path(env):
223
+ # A missing candidate would cost a whole spawn and failed exec; skip it with one stat.
224
+ if not os.path.exists(os.path.join(path,'sh')): continue
225
+ try:
226
+ 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)
227
+ break
228
+ except (FileNotFoundError,NotADirectoryError): pass
229
+ except OSError as failure:
230
+ if failure.errno==38: raise NotImplementedError()
231
+ error=failure
232
+ else: raise error
233
+ except NotImplementedError:
234
+ os.close(r); os.close(e)
235
+ self.legacy(v,env,stdin,session); return
236
+ except BaseException:
237
+ os.close(r); os.close(e); raise
238
+ finally:
239
+ os.fchdir(directory); os.close(directory); os.close(w); os.close(x)
240
+ self.stdout=os.fdopen(r,'rb',buffering=0); self.stderr=os.fdopen(e,'rb',buffering=0)
241
+ self.code=None
242
+ def legacy(self,v,env,stdin,session):
243
+ import subprocess
244
+ directory=os.open('.',os.O_RDONLY)
245
+ try: self.child=subprocess.Popen(self.argv(v),env=env,stdin=stdin,stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=session)
246
+ finally: os.fchdir(directory); os.close(directory)
247
+ self.pid=self.child.pid; self.stdout=self.child.stdout; self.stderr=self.child.stderr
248
+ def poll(self):
249
+ if hasattr(self,'child'): return self.child.poll()
250
+ if self.code is None:
251
+ pid,status=os.waitpid(self.pid,os.WNOHANG)
252
+ if pid: self.code=os.waitstatus_to_exitcode(status)
253
+ return self.code
254
+ def wait(self):
255
+ if hasattr(self,'child'): return self.child.wait()
256
+ if self.code is None: self.code=os.waitstatus_to_exitcode(os.waitpid(self.pid,0)[1])
257
+ return self.code
258
+ `,M=`def pump(p,emit,end):
259
+ r,w=os.pipe(); os.set_blocking(w,False)
260
+ signal.set_wakeup_fd(w,warn_on_full_buffer=False)
261
+ signal.signal(signal.SIGCHLD,lambda *_:None)
262
+ streams={p.stdout.fileno():('stdout',p.stdout),p.stderr.fileno():('stderr',p.stderr)}
263
+ timed=False
264
+ while streams or p.poll() is None:
265
+ left=end-time.monotonic()
266
+ if not timed and left<=0:
267
+ timed=True
268
+ try: os.killpg(p.pid,signal.SIGKILL)
269
+ except ProcessLookupError: pass
270
+ for fd in select.select(list(streams)+[r],[],[],None if timed else max(left,0))[0]:
271
+ if fd==r: os.read(r,512); continue
272
+ data=os.read(fd,8192)
273
+ if data: emit(streams[fd][0],data)
274
+ else: streams.pop(fd)[1].close()
275
+ return timed
276
+ `,h=(s,l,f="provider")=>new e(`${l}. Check the ${s.name} sandbox before retrying.`,{code:f,provider:s.name}),v=`import os,sys,json,stat
277
+ p=sys.argv[1]
278
+ def info(p):
279
+ s=os.lstat(p)
280
+ 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)
281
+ try: print(json.dumps([info(os.path.join(p,n)) for n in os.listdir(p)] if sys.argv[2]=='list' else info(p)))
282
+ except FileNotFoundError: print('SDK_FILE_NOT_FOUND')`,k="import os,sys; os.makedirs(os.path.dirname(sys.argv[1]),exist_ok=True)",S="import os,sys; os.makedirs(sys.argv[1],exist_ok=True)",O=`import os,sys,shutil
283
+ p=sys.argv[1]
284
+ try:
285
+ if os.path.isdir(p) and not os.path.islink(p):
286
+ if sys.argv[2]=='true': shutil.rmtree(p)
287
+ else: os.rmdir(p)
288
+ else: os.unlink(p)
289
+ except FileNotFoundError: print('SDK_FILE_NOT_FOUND')`;function H(s){return r(s)&&"path"in s&&t(s.path)&&"type"in s&&(s.type==="file"||s.type==="directory"||s.type==="symlink")&&"size"in s&&o(s.size)&&"modifiedAt"in s&&o(s.modifiedAt)}function V(s){return{path:s.path,type:s.type,size:s.size,modifiedAt:s.modifiedAt}}function N(s,l){let f=async(i,a,c)=>{let d=await s(i),u=await d.raw(p(v,a,c));if(u.trim()==="SDK_FILE_NOT_FOUND")throw h(d,"File does not exist","file_not_found");let m=JSON.parse(u);return{g:d,value:m}};return{writeCreatesParents:!0,listOrder:"directory",readRange:(i,a,c)=>l(i,async()=>(await s(i)).read(a,c)),read:(i,a)=>l(i,async()=>(await s(i)).read(a)),write:(i,a,c,d)=>l(i,async()=>{let u=await s(i);try{await l(i,()=>u.upload(a,c,d?.mode))}catch(m){if(!(m instanceof e)||!["not_found","file_not_found"].includes(m.code))throw m;await u.raw(p(k,a)),await u.upload(a,c,d?.mode)}}),stat:(i,a)=>l(i,async()=>{let{g:c,value:d}=await f(i,a,"stat");if(!H(d))throw h(c,"Invalid file metadata");return V(d)}),list:(i,a)=>l(i,async()=>{let{g:c,value:d}=await f(i,a,"list");if(!Array.isArray(d))throw h(c,"Invalid directory listing");return d.map((u)=>{if(!H(u))throw h(c,"Invalid file metadata");return V(u)})}),mkdir:(i,a)=>l(i,async()=>{await(await s(i)).raw(p(S,a))}),remove:(i,a,c)=>l(i,async()=>{let d=await s(i);if((await d.raw(p(O,a,String(c.recursive)))).trim()==="SDK_FILE_NOT_FOUND")throw h(d,"File does not exist","file_not_found")})}}
290
+ export{p,j,z,b,M,H,V,N};
@@ -0,0 +1,26 @@
1
+ import{n}from"./chunk-2ts3evzh.js";import{s}from"./chunk-n7x9ha44.js";import{posix as H}from"node:path";var I="SANDBOX_SDK_RUN",u={CI:"1",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",DEBIAN_FRONTEND:"noninteractive",TERM:"dumb",NO_COLOR:"1",[I]:"1"},c=(t=".")=>H.resolve("/workspace",t),ae="if [ -f /tmp/.sandbox-sdk/secret-names.json ]; then cat /tmp/.sandbox-sdk/secret-names.json || exit 1; printf '\\000'; env -0; fi",z=`[ -d "\${2%/*}" ] || (umask 077; mkdir -p "\${2%/*}") || exit 1
2
+ trap 'rm -f -- "$2"' EXIT
3
+ : > "$2" || exit 1
4
+ { { "$3" -c "$1" 3>&- 4>&-; printf '%s\\n' "$?" > "$2"; } 2>&1 >&3 | cat >&4; } 3>&1 4>&2 | cat
5
+ read -r code < "$2"
6
+ exit "$code"`,G=(t,e,o="sh")=>`sh -c ${n(z)} sh ${n(t)} ${n(e)} ${n(o)}`,U=`exec 7>&1
7
+ c=$({ { { "$2" -c "$1" 3>&- 4>&- 6>&- 7>&-; echo "$?" >&6; } 2>&1 >&3 | cat >&4; } 3>&1 4>&2 | cat >&7; } 6>&1)
8
+ exit "\${c:-1}"`,W=(t,e="sh")=>`sh -c ${n(U)} sh ${n(t)} ${n(e)}`,ye=`t=${I}=1
9
+ set -- /proc/[0-9]*/environ
10
+ [ -e "$1" ] || exit 2
11
+ grep -s -q -a -F -e "$t" -- "$@"; c=$?
12
+ [ "$c" = 0 ] && exit 10
13
+ [ "$c" = 1 ] && exit 0
14
+ [ "$c" = 2 ] || exit 2
15
+ u=
16
+ for f in "$@"; do
17
+ grep -s -q -a -F -e "$t" -- "$f"; c=$?
18
+ [ "$c" = 0 ] && exit 10
19
+ [ "$c" = 2 ] && [ -d "\${f%/environ}" ] && u="$u $f"
20
+ done
21
+ [ -z "$u" ] && exit 0
22
+ [ "$(id -u)" = 0 ] && exit 11
23
+ sudo -n sh -c 'for f; do grep -s -q -a -F -e "$0" -- "$f"; c=$?; [ "$c" = 0 ] && exit 10; [ "$c" = 2 ] && [ -d "\${f%/environ}" ] && exit 11; done; exit 0' "$t" $u </dev/null 2>/dev/null`,M=new Map,ge=(t,e)=>(M.get(t)?.get(e)??0)>0;function X(t,e){let o=M.get(t);if(!o)o=new Map,M.set(t,o);let a=o;return a.set(e,(a.get(e)??0)+1),()=>{let d=(a.get(e)??1)-1;if(d)a.set(e,d);else a.delete(e);if(!a.size)M.delete(t)}}class A{limit;head=Buffer.alloc(0);tail=Buffer.alloc(0);total=0;constructor(t){this.limit=t}add(t){let e=Buffer.from(t);this.total+=e.length;let o=Math.ceil(this.limit/2),a=Math.min(e.length,o-this.head.length);if(a>0)this.head=Buffer.concat([this.head,e.subarray(0,a)]);if(this.tail=Buffer.concat([this.tail,e.subarray(Math.max(0,a))]),this.tail.length>this.limit-o)this.tail=this.tail.subarray(this.tail.length-(this.limit-o))}get truncated(){return this.total>this.limit}text(){if(!this.truncated)return Buffer.concat([this.head,this.tail]).toString();let t=new TextDecoder().decode(this.head,{stream:!0}),e=0;while(e<this.tail.length&&((this.tail[e]??0)&192)===128)e++;let o=this.tail.subarray(e).toString();return t+`
24
+ [${this.total-Buffer.byteLength(t)-Buffer.byteLength(o)} bytes cut]
25
+ `+o}}class Y{listeners=new Set;ended=!1;failure;emit(t){for(let e of this.listeners)e(t)}fail(t){this.failure=t,this.end()}end(){this.ended=!0;for(let t of this.listeners)t()}async*stream(){let t=[],e=0,o=()=>{},a=(d)=>{if(d){let h=Buffer.byteLength(d.text)>1048576?Buffer.from(d.text).subarray(-1048576).toString():d.text;t.push({...d,text:h}),e+=Buffer.byteLength(h);while(e>1048576&&t.length>1)e-=Buffer.byteLength(t.shift()?.text??"")}o()};this.listeners.add(a);try{while(!this.ended||t.length){let d=t.shift();if(d)e-=Buffer.byteLength(d.text),yield d;else await new Promise((h)=>{o=h})}if(this.failure)throw this.failure}finally{this.listeners.delete(a)}}}function E(t,e,o=!1){let a=[];function d(h=!1){let y=t.secrets,w=new Set(y.map((i)=>i[0]));while(a.length){let i=a[0];if(!i)break;if(!w.has(i.text[0])){let r=1;while(r<i.text.length&&!w.has(i.text[r]))r++;if(e({stream:i.stream,text:i.text.slice(0,r)}),i.text=i.text.slice(r),!i.text)a.shift();continue}let v=a.flatMap((r)=>o||r.stream===i.stream?[r.text]:[]).join(""),b=y.find((r)=>v.startsWith(r));if(b){e({stream:i.stream,text:"[REDACTED]"});let r=b.length;for(let x of a)if((o||x.stream===i.stream)&&r){let p=Math.min(r,x.text.length);x.text=x.text.slice(p),r-=p}}else{if(!h&&y.some((x)=>x.startsWith(v))){if(a.reduce((x,p)=>x+Buffer.byteLength(p.text),0)<=1048576)break;e({stream:i.stream,text:"[REDACTED]"}),a.shift();continue}let r=1;while(r<i.text.length&&!w.has(i.text[r]))r++;e({stream:i.stream,text:i.text.slice(0,r)}),i.text=i.text.slice(r)}for(let r=a.length-1;r>=0;r--)if(!a[r]?.text)a.splice(r,1)}}return{push(h){if(!t.secrets.length){e(h);return}a.push({...h}),d()},flush(){d(!0)}}}function de(t,e,o,a,d,h=()=>{}){return(y,w={})=>{let i={...w},v,b=new Y,r=(l=!1)=>v??=x(l).catch((g)=>{let m=o.error(g,t.name,e);throw b.fail(m),m});async function x(l){await h();let g=i.timeoutMs??120000,m=i.maxOutputBytes??1048576;if(!Number.isFinite(g)||g<=0||!Number.isSafeInteger(m)||m<1)s("timeoutMs and maxOutputBytes must be positive");let L=c(i.cwd),q=Date.now(),C=new A(m),O=new A(m),_=new A(m*2),S=new AbortController,R=i.signal?.aborted??!1,B=()=>{R=!0,S.abort()};i.signal?.addEventListener("abort",B,{once:!0});let j=setTimeout(B,g),T=`/tmp/.sandbox-sdk/runs/${crypto.randomUUID()}`,N=!1,F=X(t.name,e),D=E(o,(f)=>{_.add(f.text),b.emit(f)},!0),P=E(o,(f)=>{(f.stream==="stdout"?C:O).add(f.text),D.push(f)});try{if(R)S.abort();let f=R?{exitCode:null,timedOut:!0}:await t.exec(e,{command:t.inlineActivity?y:t.procActivity?W(y,t.commandShell):G(y,T,t.commandShell),cwd:L,env:{...a,...i.env,...u},stdin:i.stdin,timeoutMs:g,signal:S.signal,streaming:l,envMode:i.env===void 0?"sandbox":void 0,activityPath:t.inlineActivity?T:void 0,onChunk:(k)=>P.push(k)});return N=f.exitCode!==null&&f.exitCode>=0&&f.exitCode<128&&!f.timedOut&&!S.signal.aborted,R||=f.timedOut,P.flush(),D.flush(),d(C.total+O.total),{ok:!R&&f.exitCode===0,exitCode:R?null:f.exitCode,stdout:C.text(),stderr:O.text(),output:_.text(),durationMs:Date.now()-q,truncated:C.truncated||O.truncated||_.truncated,timedOut:R,cwd:L,command:o.text(y)}}catch(f){P.flush(),D.flush();let k=o.error(f,t.name,e);throw b.fail(k),k}finally{if(clearTimeout(j),i.signal?.removeEventListener("abort",B),!N&&!t.inlineActivity&&!t.procActivity)await Promise.resolve().then(()=>t.files.remove(e,T,{recursive:!0})).catch(()=>{});F(),b.end()}}let p={[Symbol.toStringTag]:"RunHandle",then(l,g){return r().then(l,g)},catch(l){return r().catch(l)},finally(l){return r().finally(l)},[Symbol.asyncIterator](){let l=b.stream(),g=l.next();r(!0).catch(()=>{});let m=!0;return{next:()=>{if(m)return m=!1,g;return l.next()},return:()=>l.return(void 0)}},cwd(l){if(v)s("Run already started");return i.cwd=l,p},env(l){if(v)s("Run already started");return i.env={...i.env,...l},p},timeout(l){if(v)s("Run already started");return i.timeoutMs=l,p}};return p}}
26
+ export{u,c,ae,ye,ge,A,Y,E,de};
@@ -1,11 +1,11 @@
1
- import{A}from"./chunk-23tjmd39.js";import{ue,te,ne}from"./chunk-ckym4cht.js";import{t,e,s}from"./chunk-xgxfy2n8.js";import{createHash as le}from"node:crypto";import{posix as K}from"node:path";import{z as i}from"zod";var b=i.string(),G=i.number().int().positive(),W=i.string().regex(/^[a-zA-Z0-9_-]{1,128}$/),Y=G.max(65535),P={run:i.object({command:b,cwd:b.optional(),timeoutMs:G.optional()}).strict(),read_file:i.object({path:b,offset:i.number().int().nonnegative().optional(),limit:G.optional()}).strict(),write_file:i.object({path:b,content:b}).strict(),edit_file:i.object({path:b,find:b.min(1),replace:b}).strict(),start_process:i.object({name:W,command:b,cwd:b.optional(),port:Y.optional()}).strict(),process_logs:i.object({name:W,cursor:b.optional()}).strict(),stop_process:i.object({name:W}).strict(),search:i.object({query:b,path:b.optional(),glob:b.optional()}).strict(),list_files:i.object({path:b.optional(),glob:b.optional()}).strict(),changes:i.object({}).strict(),preview:i.object({port:Y,path:b.optional()}).strict()},fe={run:"Run a noninteractive command with a timeout. cwd and exports do not persist. Do not use for servers; use start_process, or file tools for reading and editing.",read_file:"Read numbered lines and a SHA-256; offset is a zero-based line index. Do not use for directory listings or binary contents.",write_file:"Create or replace a UTF-8 file. Do not use for a small change to an existing file; use edit_file.",edit_file:"Replace exactly one literal match. Do not use ambiguous snippets; include surrounding lines when a match is repeated.",start_process:"Start a named background process; with port, wait for readiness and return its URL. Do not use for short commands; use run.",process_logs:"Read a page of a named process's logs; pass the returned cursor for the next page. Do not restart a process to retrieve output.",stop_process:"Stop a named background process. Do not use to destroy the sandbox or stop unrelated processes.",search:"Find literal text in files under a path. Do not use for regular expressions; use run with rg instead.",list_files:"List files recursively under a path. Do not use to read file contents.",changes:"Show added, modified and removed files since these tools were created. Do not use for Git history.",preview:"Get the preview URL for a port. Do not use to start a server; use start_process first. Access headers stay server-side."},de=["run","read_file","write_file","edit_file","start_process","process_logs","stop_process"],ee=(p)=>le("sha256").update(p).digest("hex");function M(p,L={}){te(p,"");let E=K.resolve("/workspace",L.root??"."),V=new Set(L.allow??de);for(let n of L.deny??[])V.delete(n);function oe(n="."){let l=K.resolve(E,n);if(l!==E&&!l.startsWith(E==="/"?"/":`${E}/`))s("Path escapes tool root. Use a path inside the configured root");return l}async function j(n="."){let l=oe(n),u="/";for(let r of l.split("/").filter(Boolean)){u=K.join(u,r);try{if((await p.files.stat(u)).type==="symlink")s("Symlink path rejected. It may escape tool root. Use a regular path")}catch(m){if(!(m instanceof e&&m.code==="file_not_found"))throw m}}return l}async function Z(n){let l=await L.beforeRun?.(n);if(l===!1)s("Command denied by beforeRun. Application policy refused execution. Choose an allowed command");return t(l)?l:n}let R=(n)=>te(p,n),O=new Map;function J(n,l){let u=O.get(n)??{buffer:Buffer.alloc(0),base:0,total:0},r=Buffer.from(R(l)),m=Buffer.concat([u.buffer,r]),y=u.total+r.length,N=m.subarray(-1048576);O.set(n,{buffer:N,base:y-N.length,total:y});while(O.size>8){let T=O.keys().next().value;if(T)O.delete(T)}}let S=new Map,F=new Map;function re(n,l){let u=S.get(n);if(S.delete(n),u&&l>=u.base)return S.set(n,u),u;let r={after:void 0,more:!0,base:0,buffer:Buffer.alloc(0),pending:[],end:0,filter:ne(p,(m)=>{let y=Buffer.from(m.text);r.pending.push(y),r.end+=y.length})};S.set(n,r);while(S.size>8){let m=S.keys().next().value;if(m)S.delete(m)}return r}async function se(n,l,u){let r=re(n,l),m=p.process(n);while(r.end<l+u){let f=await m.logs({after:r.after,maxBytes:1048576});if(r.filter.push({stream:"stdout",text:f.text}),r.more=f.truncated&&f.nextCursor!==r.after,r.after=f.nextCursor,!r.more)break}if(!r.more&&(m.status==="exited"||m.status==="failed"))r.filter.flush();if(r.pending.length)r.buffer=Buffer.concat([r.buffer,...r.pending]),r.pending=[];if(l>r.end)s("Log cursor is invalid or expired after rotation. The retained log view changed. Use cursor=0 to replay");let y=r.buffer,N=(f)=>((y[f-r.base]??0)&192)===128,T=l,B=Math.min(r.end,l+u);while(T<r.end&&N(T))T++;while(B>T&&B<r.end&&N(B))B--;let I=y.subarray(T-r.base,B-r.base).toString(),U=Math.max(r.base,T-1048576);if(U>r.base)r.buffer=Buffer.from(y.subarray(U-r.base)),r.base=U;return{text:I,end:B,more:B<r.end||r.more}}async function ae(n,l,u){let r=(F.get(n)??Promise.resolve()).catch(()=>{}).then(()=>se(n,l,u));F.set(n,r);try{return await r}finally{if(F.get(n)===r)F.delete(n)}}async function Q(){let n=new Map,l=await j();if(!await p.files.exists(l))return n;for(let u of await p.files.list(l,{recursive:!0}))if(u.type==="file")n.set(u.path,ee(await p.files.read(await j(u.path),{as:"bytes"})));return n}let q=V.has("changes")?Q().then((n)=>({value:n}),(n)=>({error:n})):void 0;function ie(n){let l=P[n],u=L.limits?.[n]??{},r=u.maxOutputBytes??16384,m=u.timeoutMs??30000;if(!Number.isSafeInteger(r)||r<256||!Number.isSafeInteger(m)||m<1)s("Tool limits must have maxOutputBytes >= 256 and timeoutMs > 0");for(let y of[u.maxReadBytes,u.maxMatches])if(y!==void 0&&(!Number.isSafeInteger(y)||y<1))s("maxReadBytes and maxMatches must be positive integers");return{name:n,description:fe[n],inputSchema:l,async execute(y,N,T){let B=Date.now(),I=!1;function U(d){try{L.onEvent?.(d)}catch{I=!0}try{N?.(d)}catch{I=!0}}function f(d,o,a="",c,x=""){let g=R(`${d?"OK":"FAILED"}${a?` ${a}`:""} ${((Date.now()-B)/1000).toFixed(1)}s${c?` cwd=${c}`:""}`),_=new A(Math.floor(r/4));_.add(g);let w=_.text(),h=new A(Math.max(1,r-Buffer.byteLength(w)-Buffer.byteLength(x)-100));return h.add(R(o+(I?`
2
- UI streaming callback failed. Execution was allowed to finish. Fix onEvent before reconnecting the UI.`:""))),{text:R(`${w}
1
+ import{A}from"./chunk-6nf686jb.js";import{pe,se,ie}from"./chunk-5gnqph3c.js";import{t,e,s}from"./chunk-n7x9ha44.js";import{createHash as le}from"node:crypto";import{posix as K}from"node:path";import{z as i}from"zod";var b=i.string(),G=i.number().int().positive(),W=i.string().regex(/^[a-zA-Z0-9_-]{1,128}$/),Y=G.max(65535),P={run:i.object({command:b,cwd:b.optional(),timeoutMs:G.optional()}).strict(),read_file:i.object({path:b,offset:i.number().int().nonnegative().optional(),limit:G.optional()}).strict(),write_file:i.object({path:b,content:b}).strict(),edit_file:i.object({path:b,find:b.min(1),replace:b}).strict(),start_process:i.object({name:W,command:b,cwd:b.optional(),port:Y.optional()}).strict(),process_logs:i.object({name:W,cursor:b.optional()}).strict(),stop_process:i.object({name:W}).strict(),search:i.object({query:b,path:b.optional(),glob:b.optional()}).strict(),list_files:i.object({path:b.optional(),glob:b.optional()}).strict(),changes:i.object({}).strict(),preview:i.object({port:Y,path:b.optional()}).strict()},ue={run:"Run a noninteractive command with a timeout. cwd and exports do not persist. Do not use for servers; use start_process, or file tools for reading and editing.",read_file:"Read numbered lines and a SHA-256; offset is a zero-based line index. Do not use for directory listings or binary contents.",write_file:"Create or replace a UTF-8 file. Do not use for a small change to an existing file; use edit_file.",edit_file:"Replace exactly one literal match. Do not use ambiguous snippets; include surrounding lines when a match is repeated.",start_process:"Start a named background process; with port, wait for readiness and return its URL. Do not use for short commands; use run.",process_logs:"Read a page of a named process's logs; pass the returned cursor for the next page. Do not restart a process to retrieve output.",stop_process:"Stop a named background process. Do not use to destroy the sandbox or stop unrelated processes.",search:"Find literal text in files under a path. Do not use for regular expressions; use run with rg instead.",list_files:"List files recursively under a path. Do not use to read file contents.",changes:"Show added, modified and removed files since these tools were created. Do not use for Git history.",preview:"Get the preview URL for a port. Do not use to start a server; use start_process first. Access headers stay server-side."},fe=["run","read_file","write_file","edit_file","start_process","process_logs","stop_process"],ee=(p)=>le("sha256").update(p).digest("hex");function R(p,L={}){se(p,"");let E=K.resolve("/workspace",L.root??"."),V=new Set(L.allow??fe);for(let n of L.deny??[])V.delete(n);function te(n="."){let l=K.resolve(E,n);if(l!==E&&!l.startsWith(E==="/"?"/":`${E}/`))s("Path escapes tool root. Use a path inside the configured root");return l}async function j(n="."){let l=te(n),u="/";for(let r of l.split("/").filter(Boolean)){u=K.join(u,r);try{if((await p.files.stat(u)).type==="symlink")s("Symlink path rejected. It may escape tool root. Use a regular path")}catch(m){if(!(m instanceof e&&m.code==="file_not_found"))throw m}}return l}async function Z(n){let l=await L.beforeRun?.(n);if(l===!1)s("Command denied by beforeRun. Application policy refused execution. Choose an allowed command");return t(l)?l:n}let M=(n)=>se(p,n),O=new Map;function J(n,l){let u=O.get(n)??{buffer:Buffer.alloc(0),base:0,total:0},r=Buffer.from(M(l)),m=Buffer.concat([u.buffer,r]),y=u.total+r.length,N=m.subarray(-1048576);O.set(n,{buffer:N,base:y-N.length,total:y});while(O.size>8){let T=O.keys().next().value;if(T)O.delete(T)}}let S=new Map,F=new Map;function oe(n,l){let u=S.get(n);if(S.delete(n),u&&l>=u.base)return S.set(n,u),u;let r={after:void 0,more:!0,base:0,buffer:Buffer.alloc(0),pending:[],end:0,filter:ie(p,(m)=>{let y=Buffer.from(m.text);r.pending.push(y),r.end+=y.length})};S.set(n,r);while(S.size>8){let m=S.keys().next().value;if(m)S.delete(m)}return r}async function re(n,l,u){let r=oe(n,l),m=p.process(n);while(r.end<l+u){let f=await m.logs({after:r.after,maxBytes:1048576});if(r.filter.push({stream:"stdout",text:f.text}),r.more=f.truncated&&f.nextCursor!==r.after,r.after=f.nextCursor,!r.more)break}if(!r.more&&(m.status==="exited"||m.status==="failed"))r.filter.flush();if(r.pending.length)r.buffer=Buffer.concat([r.buffer,...r.pending]),r.pending=[];if(l>r.end)s("Log cursor is invalid or expired after rotation. The retained log view changed. Use cursor=0 to replay");let y=r.buffer,N=(f)=>((y[f-r.base]??0)&192)===128,T=l,B=Math.min(r.end,l+u);while(T<r.end&&N(T))T++;while(B>T&&B<r.end&&N(B))B--;let I=y.subarray(T-r.base,B-r.base).toString(),U=Math.max(r.base,T-1048576);if(U>r.base)r.buffer=Buffer.from(y.subarray(U-r.base)),r.base=U;return{text:I,end:B,more:B<r.end||r.more}}async function ne(n,l,u){let r=(F.get(n)??Promise.resolve()).catch(()=>{}).then(()=>re(n,l,u));F.set(n,r);try{return await r}finally{if(F.get(n)===r)F.delete(n)}}async function Q(){let n=new Map,l=await j();if(!await p.files.exists(l))return n;for(let u of await p.files.list(l,{recursive:!0}))if(u.type==="file")n.set(u.path,ee(await p.files.read(await j(u.path),{as:"bytes"})));return n}let q=V.has("changes")?Q().then((n)=>({value:n}),(n)=>({error:n})):void 0;function ae(n){let l=P[n],u=L.limits?.[n]??{},r=u.maxOutputBytes??16384,m=u.timeoutMs??30000;if(!Number.isSafeInteger(r)||r<256||!Number.isSafeInteger(m)||m<1)s("Tool limits must have maxOutputBytes >= 256 and timeoutMs > 0");for(let y of[u.maxReadBytes,u.maxMatches])if(y!==void 0&&(!Number.isSafeInteger(y)||y<1))s("maxReadBytes and maxMatches must be positive integers");return{name:n,description:ue[n],inputSchema:l,async execute(y,N,T){let B=Date.now(),I=!1;function U(d){try{L.onEvent?.(d)}catch{I=!0}try{N?.(d)}catch{I=!0}}function f(d,o,a="",c,x=""){let g=M(`${d?"OK":"FAILED"}${a?` ${a}`:""} ${((Date.now()-B)/1000).toFixed(1)}s${c?` cwd=${c}`:""}`),_=new A(Math.floor(r/4));_.add(g);let w=_.text(),h=new A(Math.max(1,r-Buffer.byteLength(w)-Buffer.byteLength(x)-100));return h.add(M(o+(I?`
2
+ UI streaming callback failed. Execution was allowed to finish. Fix onEvent before reconnecting the UI.`:""))),{text:M(`${w}
3
3
  output:
4
- ${x}${h.text()}`)}}try{let d=pe.parse({tool:n,input:y});if(q){let o=await q;if("error"in o&&d.tool==="changes")throw o.error}if(T?.aborted)s("Tool cancelled. The calling agent aborted execution. Retry only if still needed");switch(d.tool){case"run":{let o=d.input,a=await j(o.cwd),c=p.run(await Z(o.command),{cwd:a,timeoutMs:Math.min(o.timeoutMs??m,m),maxOutputBytes:r,signal:T}),x=new A(Math.max(1,r-512)),g=`run_${crypto.randomUUID().replaceAll("-","")}`;J(g,"");let _=ne(p,(v)=>{x.add(v.text),J(g,v.text);let k={tool:n,kind:"output",stream:v.stream,text:R(v.text)};U(k)});try{for await(let v of c)_.push(v)}finally{_.flush()}let w=await c,h=x.text().replace(/\[(\d+) bytes cut\]/,"[$1 bytes cut, use process_logs]");return f(w.ok,`${h}${w.timedOut?T?.aborted?`
4
+ ${x}${h.text()}`)}}try{let d=de.parse({tool:n,input:y});if(q){let o=await q;if("error"in o&&d.tool==="changes")throw o.error}if(T?.aborted)s("Tool cancelled. The calling agent aborted execution. Retry only if still needed");switch(d.tool){case"run":{let o=d.input,a=await j(o.cwd),c=p.run(await Z(o.command),{cwd:a,timeoutMs:Math.min(o.timeoutMs??m,m),maxOutputBytes:r,signal:T}),x=new A(Math.max(1,r-512)),g=`run_${crypto.randomUUID().replaceAll("-","")}`;J(g,"");let _=ie(p,(v)=>{x.add(v.text),J(g,v.text);let k={tool:n,kind:"output",stream:v.stream,text:M(v.text)};U(k)});try{for await(let v of c)_.push(v)}finally{_.flush()}let w=await c,h=x.text().replace(/\[(\d+) bytes cut\]/,"[$1 bytes cut, use process_logs]");return f(w.ok,`${h}${w.timedOut?T?.aborted?`
5
5
  Aborted. The calling agent cancelled execution and the command was terminated. Retry only if still needed.`:`
6
6
  Timed out. Command exceeded its limit and was terminated. Increase the configured timeout or use start_process for servers.`:""}${!w.ok&&!w.timedOut?`
7
7
  Command exited with status ${w.exitCode}. Inspect the output and correct the command before retrying.`:""}`,`exit=${w.exitCode}`,a,x.truncated?`name=${g} cursor=0 use=process_logs
8
- `:"")}case"read_file":{let o=d.input,a=await j(o.path),c=u.maxReadBytes??1048576,x=(await p.files.stat(a)).size;if(x>c)return f(!1,`File is ${x} bytes, above maxReadBytes=${c}. Raise read_file's maxReadBytes or use run to extract a smaller file.`);let g=await ue(p.files,a,c);if(g.length>c)return f(!1,`File grew above maxReadBytes=${c} while being read. Raise read_file's maxReadBytes or use run to extract a smaller file.`);let _=ee(g),w;try{if(w=new TextDecoder("utf-8",{fatal:!0}).decode(g),w.includes("\x00"))throw Error("binary")}catch{return f(!0,`binary file; size=${g.length} bytes; sha=${_}. Use download outside the agent tools to retrieve bytes.`)}let h=R(w).split(`
8
+ `:"")}case"read_file":{let o=d.input,a=await j(o.path),c=u.maxReadBytes??1048576,x=(await p.files.stat(a)).size;if(x>c)return f(!1,`File is ${x} bytes, above maxReadBytes=${c}. Raise read_file's maxReadBytes or use run to extract a smaller file.`);let g=await pe(p.files,a,c);if(g.length>c)return f(!1,`File grew above maxReadBytes=${c} while being read. Raise read_file's maxReadBytes or use run to extract a smaller file.`);let _=ee(g),w;try{if(w=new TextDecoder("utf-8",{fatal:!0}).decode(g),w.includes("\x00"))throw Error("binary")}catch{return f(!0,`binary file; size=${g.length} bytes; sha=${_}. Use download outside the agent tools to retrieve bytes.`)}let h=M(w).split(`
9
9
  `),v=o.offset??0,k=[],C=0;for(let[z,ce]of h.slice(v,v+(o.limit??200)).entries()){let H=`${v+z+1}: ${ce}`;if(k.length&&C+Buffer.byteLength(H)>r-600)break;k.push(H),C+=Buffer.byteLength(H)+1}let D=v+k.length,X="";if(C>r-600){let z=`read_${crypto.randomUUID().replaceAll("-","")}`;J(z,k.join(`
10
10
  `)),X=`name=${z} cursor=0 use=process_logs
11
11
  `}return f(!0,`${k.join(`
@@ -16,12 +16,12 @@ ${c.message}
16
16
  Use process_logs to inspect startup or stop_process to terminate it.`)}return f(a.status!=="failed",`name=${o.name} ready=${a.ready} status=${a.status} url=${a.url??"none"}
17
17
  cursor=0
18
18
  Use process_logs to inspect output.${!a.ready?`
19
- Not ready. The process may still be running. Use stop_process to stop it.`:""}`)}case"process_logs":{let o=d.input,a=O.get(o.name);if(a){let g=o.cursor===void 0?a.base:Number(o.cursor);if(!Number.isSafeInteger(g)||g<0||g>a.total)s("Invalid foreground log cursor. It is outside the retained output. Use cursor=0 to replay");let _=Math.max(g,a.base),w=(C)=>{let D=a.buffer[C-a.base];return D!==void 0&&(D&192)===128};while(_<a.total&&w(_))_++;let h=Math.min(a.total,_+Math.max(64,r-512));while(h>_&&h<a.total&&w(h))h--;let v=a.buffer.subarray(_-a.base,h-a.base).toString(),k={tool:n,kind:"output",stream:"stdout",text:R(v)};return U(k),f(!0,`cursor=${h} more=${h<a.total}
19
+ Not ready. The process may still be running. Use stop_process to stop it.`:""}`)}case"process_logs":{let o=d.input,a=O.get(o.name);if(a){let g=o.cursor===void 0?a.base:Number(o.cursor);if(!Number.isSafeInteger(g)||g<0||g>a.total)s("Invalid foreground log cursor. It is outside the retained output. Use cursor=0 to replay");let _=Math.max(g,a.base),w=(C)=>{let D=a.buffer[C-a.base];return D!==void 0&&(D&192)===128};while(_<a.total&&w(_))_++;let h=Math.min(a.total,_+Math.max(64,r-512));while(h>_&&h<a.total&&w(h))h--;let v=a.buffer.subarray(_-a.base,h-a.base).toString(),k={tool:n,kind:"output",stream:"stdout",text:M(v)};return U(k),f(!0,`cursor=${h} more=${h<a.total}
20
20
  ${g<a.base?`[${a.base-g} bytes expired from replay window]
21
21
  `:""}${v}${h<a.total?`
22
- [more output; use process_logs with cursor]`:""}`)}let c=o.cursor===void 0?0:Number(o.cursor);if(!Number.isSafeInteger(c)||c<0)s("Log cursor is invalid or expired after rotation. The retained log view changed. Use cursor=0 to replay");let x=await ae(o.name,c,Math.max(32,r-512));return U({tool:n,kind:"output",stream:"stdout",text:x.text}),f(!0,`${x.text}${x.more?`
22
+ [more output; use process_logs with cursor]`:""}`)}let c=o.cursor===void 0?0:Number(o.cursor);if(!Number.isSafeInteger(c)||c<0)s("Log cursor is invalid or expired after rotation. The retained log view changed. Use cursor=0 to replay");let x=await ne(o.name,c,Math.max(32,r-512));return U({tool:n,kind:"output",stream:"stdout",text:x.text}),f(!0,`${x.text}${x.more?`
23
23
  [more output; use process_logs with cursor]`:""}`,"",void 0,`cursor=${x.end} more=${x.more}
24
24
  `)}case"stop_process":return await p.process(d.input.name).stop(),f(!0,"Process stopped.");case"search":{let o=d.input;return f(!0,JSON.stringify(await p.files.search(o.query,{path:await j(o.path),glob:o.glob,maxMatches:u.maxMatches??100})))}case"list_files":{let o=d.input;return f(!0,JSON.stringify(await p.files.list(await j(o.path),{recursive:!0,glob:o.glob})))}case"changes":{let o=await q;if(!o||!("value"in o))s("Changes baseline unavailable");let a=await Q();return f(!0,JSON.stringify({added:[...a.keys()].filter((c)=>!o.value.has(c)),modified:[...a.keys()].filter((c)=>o.value.has(c)&&o.value.get(c)!==a.get(c)),removed:[...o.value.keys()].filter((c)=>!a.has(c))}))}case"preview":{let o=d.input;if(o.path&&(!o.path.startsWith("/")||o.path.startsWith("//")))s("Preview path must be an absolute URL path. External URLs are not allowed. Use /path");let a=await p.preview(o.port,{path:o.path});return f(!0,`url=${a.url}`)}default:return d}}catch(d){if(d instanceof e)return f(!1,`${d.message}
25
25
  code=${d.code} retryable=${d.retryable}
26
- Next: ${d.hint}`);if(d instanceof i.ZodError)return f(!1,"Invalid tool input. Parameters do not match the tool schema. Check the required fields and types, then retry.");return f(!1,"Tool failed. An unexpected execution or callback error occurred. Check server-side diagnostics and retry.")}}}}return[...V].map((n)=>ie(n))}var pe=i.discriminatedUnion("tool",[i.object({tool:i.literal("run"),input:P.run}),i.object({tool:i.literal("read_file"),input:P.read_file}),i.object({tool:i.literal("write_file"),input:P.write_file}),i.object({tool:i.literal("edit_file"),input:P.edit_file}),i.object({tool:i.literal("start_process"),input:P.start_process}),i.object({tool:i.literal("process_logs"),input:P.process_logs}),i.object({tool:i.literal("stop_process"),input:P.stop_process}),i.object({tool:i.literal("search"),input:P.search}),i.object({tool:i.literal("list_files"),input:P.list_files}),i.object({tool:i.literal("changes"),input:P.changes}),i.object({tool:i.literal("preview"),input:P.preview})]);
27
- export{P,M};
26
+ Next: ${d.hint}`);if(d instanceof i.ZodError)return f(!1,"Invalid tool input. Parameters do not match the tool schema. Check the required fields and types, then retry.");return f(!1,"Tool failed. An unexpected execution or callback error occurred. Check server-side diagnostics and retry.")}}}}return[...V].map((n)=>ae(n))}var de=i.discriminatedUnion("tool",[i.object({tool:i.literal("run"),input:P.run}),i.object({tool:i.literal("read_file"),input:P.read_file}),i.object({tool:i.literal("write_file"),input:P.write_file}),i.object({tool:i.literal("edit_file"),input:P.edit_file}),i.object({tool:i.literal("start_process"),input:P.start_process}),i.object({tool:i.literal("process_logs"),input:P.process_logs}),i.object({tool:i.literal("stop_process"),input:P.stop_process}),i.object({tool:i.literal("search"),input:P.search}),i.object({tool:i.literal("list_files"),input:P.list_files}),i.object({tool:i.literal("changes"),input:P.changes}),i.object({tool:i.literal("preview"),input:P.preview})]);
27
+ export{P,R};
@@ -1,2 +1,2 @@
1
- import{t,o,r}from"./chunk-xgxfy2n8.js";function m(n){let e={name:"",message:"",headers:new Map,metadata:new Map};if(n instanceof Error)e.name=n.name,e.message=n.message;if(!r(n))return e;if("status"in n&&o(n.status))e.status=n.status;if("statusCode"in n&&o(n.statusCode))e.statusCode=n.statusCode;if("response"in n&&n.response instanceof Response)e.responseStatus=n.response.status;if("grpcCode"in n&&o(n.grpcCode))e.grpcCode=n.grpcCode;if("code"in n&&(t(n.code)||o(n.code)))e.code=n.code;if("apiCode"in n&&t(n.apiCode))e.apiCode=n.apiCode;if("json"in n&&r(n.json)&&"error"in n.json&&r(n.json.error)&&"code"in n.json.error&&t(n.json.error.code))e.bodyCode=n.json.error.code;if("source"in n&&t(n.source))e.source=n.source;if("path"in n&&t(n.path))e.path=n.path;if("requestId"in n&&t(n.requestId))e.requestId=n.requestId;if("sandboxId"in n&&t(n.sandboxId))e.sandboxId=n.sandboxId;if("headers"in n&&r(n.headers)){let i=n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers);e.headers=new Map(i.filter((d)=>t(d[1])))}if("metadata"in n&&n.metadata instanceof Headers)e.metadata=new Map(n.metadata);if("cause"in n)e.cause=n.cause;return e}
1
+ import{t,o,r}from"./chunk-n7x9ha44.js";function m(n){let e={name:"",message:"",headers:new Map,metadata:new Map};if(n instanceof Error)e.name=n.name,e.message=n.message;if(!r(n))return e;if("status"in n&&o(n.status))e.status=n.status;if("statusCode"in n&&o(n.statusCode))e.statusCode=n.statusCode;if("response"in n&&n.response instanceof Response)e.responseStatus=n.response.status;if("grpcCode"in n&&o(n.grpcCode))e.grpcCode=n.grpcCode;if("code"in n&&(t(n.code)||o(n.code)))e.code=n.code;if("apiCode"in n&&t(n.apiCode))e.apiCode=n.apiCode;if("json"in n&&r(n.json)&&"error"in n.json&&r(n.json.error)&&"code"in n.json.error&&t(n.json.error.code))e.bodyCode=n.json.error.code;if("source"in n&&t(n.source))e.source=n.source;if("path"in n&&t(n.path))e.path=n.path;if("requestId"in n&&t(n.requestId))e.requestId=n.requestId;if("sandboxId"in n&&t(n.sandboxId))e.sandboxId=n.sandboxId;if("headers"in n&&r(n.headers)){let i=n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers);e.headers=new Map(i.filter((d)=>t(d[1])))}if("metadata"in n&&n.metadata instanceof Headers)e.metadata=new Map(n.metadata);if("cause"in n)e.cause=n.cause;return e}
2
2
  export{m};
@@ -0,0 +1,2 @@
1
+ import{e,I,S,s}from"./chunk-n7x9ha44.js";var u=new WeakMap,g=(n,t)=>u.get(n)?.get(t);function k(n,t,a){let r=u.get(n);if(!r)r=new Map,u.set(n,r);if(r.delete(t),r.set(t,a),r.size>256){let o=r.keys().next().value;if(o!==void 0)r.delete(o)}}function h(n,t){u.get(n)?.delete(t)}function G(n,t){let a=u.get(n);if(!a)return;for(let[r,o]of a)if(o===t)a.delete(r)}var p=new WeakMap;async function Z(n,t,a,r){let o=p.get(n);if(!o)o=new Map,p.set(n,o);let i=o.get(t)??Promise.resolve(),c=a.locator,d=i.catch(()=>{}).then(()=>a.keyMode==="exact"&&n.keyMode==="best-effort"&&c?.withLock?c.withLock(t,r):r());o.set(t,d);try{return await d}finally{if(o.get(t)===d)o.delete(t)}}var m=new WeakMap;function te(n,t){let a=m.get(n);if(!a)a=new Map,m.set(n,a);a.set(t,(a.get(t)??0)+1)}function me(n,t){let a=m.get(n),r=a?.get(t)??0;if(r>1)return a?.set(t,r-1),!1;return a?.delete(t),!0}function ne(n,t){return n.capabilities.has(t)}var v={"sandbox-sdk":"1"};function C(n,t){for(let a of Object.keys({...t.env,...t.secrets}))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))s("Invalid environment variable name");for(let a of n.capabilities)if(a==="pause"&&(!n.pause||!n.resume)||a==="snapshot"&&!n.snapshot||a==="terminal"&&!n.terminal)throw new e("Invalid adapter capabilities. A declared method is missing. Fix the adapter contract.",{code:"provider"});if(t.size!==void 0&&!n.capabilities.has("size"))throw new e("Creation refused. Provider cannot enforce size. Choose a provider with size support.",{code:"unsupported"});if(t.network!==void 0&&t.network!=="all"&&!n.capabilities.has("network-policy"))throw new e("Creation refused. Provider cannot enforce network policy. Choose a provider with network-policy support.",{code:"unsupported"});if(t.from!==void 0&&!n.capabilities.has("snapshot"))throw new e("Creation refused. Provider cannot restore snapshots. Choose a provider with snapshot support.",{code:"unsupported"});if(t.keyMode==="exact"&&n.keyMode!=="exact"&&!t.locator?.withLock)throw new e("Exact key mode unavailable. Two-function locator storage cannot enforce distributed uniqueness. Supply locator.withLock or use an exact provider.",{code:"unsupported"});for(let a of t.ports??[])if(!Number.isInteger(a)||a<1||a>65535)s("Invalid port");for(let a of[t.timeoutMs,t.idleTimeoutMs])if(a!==void 0&&(!Number.isFinite(a)||a<=0))s("Timeouts must be positive milliseconds")}async function O(n,t={}){let a=new S;a.add(Object.values(t.secrets??{}));async function r(){let o;try{if(C(n,t),t.signal?.aborted)throw new e("Creation aborted. Signal was already aborted. Retry with a fresh signal.",{code:"aborted"});let i;if(t.key){let w=await t.locator?.get(t.key)??g(n,t.key);if(w)try{i=await n.connect(w)}catch(y){if(!(y instanceof e)||y.code!=="not_found")throw y;h(n,t.key)}if(i?.state==="stopped")i=void 0,h(n,t.key);i??=await n.find(t.key)}let c=!i;if(!i){let{secrets:w,locator:y,keyMode:B,trackChanges:F,...M}=t,x=n.create({...M,env:{...t.env,...w},labels:{...t.labels,...v}}).catch(async(l)=>{if(t.key&&n.keyMode==="exact"&&!t.signal?.aborted){let f=await n.find(t.key);if(f)return c=!1,f}throw l});if(t.signal){let l=t.signal,f=()=>{},L=new Promise((b,R)=>{if(f=()=>R(new e("Creation aborted. The signal was cancelled. Any late sandbox will be destroyed.",{code:"aborted"})),l.addEventListener("abort",f,{once:!0}),l.aborted)f()}),j=x.then(async(b)=>{if(l.aborted){if(c)await n.destroy(b.id);throw new e("Creation aborted. Late sandbox destroyed. Retry with a fresh signal.",{code:"aborted"})}return b});try{i=await Promise.race([j,L])}finally{l.removeEventListener("abort",f)}}else i=await x;if(c)o=i}if(t.signal?.aborted){if(o)await n.destroy(o.id);throw o=void 0,new e("Creation aborted. Sandbox arrived after cancellation and was destroyed. Retry with a fresh signal.",{code:"aborted"})}if(t.key)await t.locator?.set(t.key,i.id),k(n,t.key,i.id);let{makeHandle:d}=await import("./chunk-11mbpwem.js");return await d(n,i,c,t,a)}catch(i){if(o)G(n,o.id),await n.destroy(o.id).catch(()=>{});throw a.error(i,n.name)}}if(!t.key)return r();return Z(n,t.key,t,r)}async function U(n,t,a={}){let r=new S;r.add(Object.values(a.secrets??{}));try{C(n,a);let o=await n.connect(t),{makeHandle:i}=await import("./chunk-11mbpwem.js");return await i(n,o,!1,{...a,key:o.key},r,a.recoverSecrets??!0)}catch(o){throw r.error(o,n.name,t)}}async function Q(n,t={}){try{return(await n.list({...t.labels,...v})).filter((a)=>a.labels["sandbox-sdk"]==="1")}catch(a){throw new S().error(a,n.name)}}async function re(n,t={}){if(t.olderThanMs!==void 0&&(!Number.isFinite(t.olderThanMs)||t.olderThanMs<0))s("olderThanMs must be non-negative");let a=t.idleOnly?(await import("./chunk-1k6yz176.js")).isRunActive:()=>!1,r=t.olderThanMs??0,o=0;try{for(let i of await Q(n,t)){if(Date.now()-i.createdAt<r)continue;if(t.idleOnly){if(a(n.name,i.id))continue;let c=await K(n,i.id);if(c==="gone"){o++;continue}if(c==="busy")continue}if(a(n.name,i.id))continue;G(n,i.id);try{await n.destroy(i.id)}catch(c){if(!(c instanceof e)||c.code!=="not_found")throw c}o++}return o}catch(i){throw new S().error(i,n.name)}}var P="/tmp/.sandbox-sdk/runs";async function T(n,t){if(!n.procActivity)return!1;let{activityScanCommand:a}=await import("./chunk-1k6yz176.js");try{let r=await n.exec(t,{command:a,cwd:"/",env:{},timeoutMs:30000,onChunk(){}});return r.timedOut||r.exitCode!==0}catch{return!0}}async function K(n,t){let a;try{let r=await n.connect(t),{makeHandle:o}=await import("./chunk-11mbpwem.js");a=await o(n,r,!1,{},new S,!1)}catch(r){if(r instanceof e&&r.code==="not_found")return"gone";throw r}try{let[r,o,i]=await Promise.all([a.processes(),A(a),T(n,t)]);return r.some((d)=>d.status==="running"||d.status==="starting")||o.length>0||i?"busy":"idle"}finally{await a.close()}}async function A(n){try{return await n.files.list(P)}catch(t){if(I(t))return[];if(t instanceof e&&t.code==="provider"&&!await n.files.exists(P))return[];throw t}}
2
+ export{G,Z,te,me,ne,O,U,Q,re};
@@ -1,2 +1,2 @@
1
- import{t,r,e,w}from"./chunk-xgxfy2n8.js";var A=new WeakMap;function z(i){return i instanceof e?A.get(i):void 0}var _={disconnected:"unavailable",truncated:"unavailable",frame_too_large:"unsupported",malformed:"provider"};function h(i,a,s,n){let o=new e(`${a}. The stream from ${s.provider} cannot be read further.`,{code:_[i],provider:s.provider,sandboxId:s.sandboxId,retryable:i==="disconnected"||i==="truncated",cause:n===void 0?void 0:w(n)??i});return A.set(o,i),o}class k{chunks=[];head=0;length=0;push(i){if(i.byteLength)this.chunks.push(i),this.length+=i.byteLength}find(i,a=0){let s=0;for(let n=0;n<this.chunks.length;n++){let o=this.chunks[n],l=n===0?this.head:0,u=o.byteLength-l;if(a<s+u){for(let d=Math.max(l,l+a-s);d<o.byteLength;d++)if(i(o[d]))return s+d-l}s+=u}return-1}at(i){let a=i;for(let s=0;s<this.chunks.length;s++){let n=this.chunks[s],o=s===0?this.head:0;if(a<n.byteLength-o)return n[o+a];a-=n.byteLength-o}return}take(i){let a=new Uint8Array(i),s=0;while(s<i){let n=this.chunks[0],o=Math.min(i-s,n.byteLength-this.head);if(a.set(n.subarray(this.head,this.head+o),s),s+=o,this.head+=o,this.head===n.byteLength)this.chunks.shift(),this.head=0}return this.length-=i,a}}async function*p(i,a){let s=i.getReader(),{signal:n}=a,o=!1,l=()=>{s.cancel(n?.reason).catch(()=>{})};n?.addEventListener("abort",l,{once:!0});try{if(n?.aborted)throw S(a);for(;;){let u;try{u=await s.read()}catch(d){if(o=!0,n?.aborted)throw S(a);if(d instanceof e){if(d.code==="unavailable"||d.code==="outcome_unknown")A.set(d,"disconnected");throw d}throw h("disconnected","The connection dropped mid-stream",a,d)}if(n?.aborted)throw o=!0,S(a);if(u.done){o=!0;return}yield u.value}}finally{if(n?.removeEventListener("abort",l),!o)await s.cancel().catch(()=>{});s.releaseLock()}}function S(i){return new e("Stream aborted. The signal was cancelled.",{code:"aborted",provider:i.provider,sandboxId:i.sandboxId})}var O=new TextDecoder;var C=16777216;async function*ie(i,a){let s=a.maxFrameBytes??C,n=new k,o=(l,u)=>{let d=O.decode(l).replace(/\r$/,"");try{return JSON.parse(d)}catch{throw u?h("truncated","The stream ended inside a JSON line",a):h("malformed","A line is not valid JSON",a)}};for await(let l of p(i,a)){let u=n.length;n.push(l);for(let d=n.find((f)=>f===10,u);d>=0;d=n.find((f)=>f===10)){if(d>s)throw h("frame_too_large",`A JSON line exceeds ${s} bytes`,a);let f=n.take(d+1).subarray(0,d);if(f.some((c)=>c!==13&&c!==32&&c!==9))yield o(f,!1)}if(n.length>s)throw h("frame_too_large",`A JSON line exceeds ${s} bytes`,a)}if(n.length){let l=n.take(n.length);if(l.some((u)=>u!==13&&u!==32&&u!==9))yield o(l,!0)}}async function*ae(i,a){let s=a.maxFrameBytes??C,n=new k,o=p(i,a),l=async(f)=>{while(n.length<f){let c=await o.next();if(c.done)return!1;n.push(c.value)}return!0};try{for(let f=!1;;){if(!await l(5)){if(n.length)throw h("truncated","The stream ended inside a Connect frame header",a);if(!f)throw h("truncated","The stream ended before the Connect end-of-stream frame",a);return}if(f)throw h("malformed","A Connect frame followed the end-of-stream frame",a);let c=n.take(5),b=c[0],m=new DataView(c.buffer,c.byteOffset,5).getUint32(1);if(b&1)throw h("malformed","A Connect frame is compressed, but no compression was negotiated",a);if(b&-4)throw h("malformed","A Connect frame has unknown flags",a);if(m>s)throw h("frame_too_large",`A Connect frame exceeds ${s} bytes`,a);if(!await l(m))throw h("truncated","The stream ended inside a Connect frame",a);let g=u(n.take(m));if(b&2)f=!0,yield d(g);else yield{kind:"message",message:g}}}finally{await o.return()}function u(f){try{return JSON.parse(O.decode(f))}catch{throw h("malformed","A Connect frame is not valid JSON",a)}}function d(f){if(!r(f)||f===null)throw h("malformed","The Connect end-of-stream frame is not an object",a);let c="error"in f?f.error:void 0,b="metadata"in f?f.metadata:void 0,m={kind:"end"};if(c!==void 0){if(!r(c)||c===null)throw h("malformed","The Connect end-of-stream error is not an object",a);let g="code"in c?c.code:void 0,y="message"in c?c.message:void 0,x="details"in c?c.details:void 0;if(!t(g))throw h("malformed","The Connect end-of-stream error has no code",a);let v={code:g};if(t(y))v.message=y;if(Array.isArray(x))v.details=x;m.error=v}if(r(b)){let g=Object.entries(b).filter((y)=>Array.isArray(y[1])&&y[1].every((x)=>t(x)));m.metadata=Object.fromEntries(g)}return m}}function de(i,a=!1){let s=new TextEncoder().encode(JSON.stringify(i)),n=new Uint8Array(5+s.byteLength);return n[0]=a?2:0,new DataView(n.buffer).setUint32(1,s.byteLength),n.set(s,5),n}
2
- export{z,ie,ae,de};
1
+ import{t,r,e,h}from"./chunk-n7x9ha44.js";var A=new WeakMap;function J(i){return i instanceof e?A.get(i):void 0}var _={disconnected:"unavailable",truncated:"unavailable",frame_too_large:"unsupported",malformed:"provider"};function m(i,a,s,n){let o=new e(`${a}. The stream from ${s.provider} cannot be read further.`,{code:_[i],provider:s.provider,sandboxId:s.sandboxId,retryable:i==="disconnected"||i==="truncated",cause:n===void 0?void 0:h(n)??i});return A.set(o,i),o}class k{chunks=[];head=0;length=0;push(i){if(i.byteLength)this.chunks.push(i),this.length+=i.byteLength}find(i,a=0){let s=0;for(let n=0;n<this.chunks.length;n++){let o=this.chunks[n],l=n===0?this.head:0,u=o.byteLength-l;if(a<s+u){for(let d=Math.max(l,l+a-s);d<o.byteLength;d++)if(i(o[d]))return s+d-l}s+=u}return-1}at(i){let a=i;for(let s=0;s<this.chunks.length;s++){let n=this.chunks[s],o=s===0?this.head:0;if(a<n.byteLength-o)return n[o+a];a-=n.byteLength-o}return}take(i){let a=new Uint8Array(i),s=0;while(s<i){let n=this.chunks[0],o=Math.min(i-s,n.byteLength-this.head);if(a.set(n.subarray(this.head,this.head+o),s),s+=o,this.head+=o,this.head===n.byteLength)this.chunks.shift(),this.head=0}return this.length-=i,a}}async function*p(i,a){let s=i.getReader(),{signal:n}=a,o=!1,l=()=>{s.cancel(n?.reason).catch(()=>{})};n?.addEventListener("abort",l,{once:!0});try{if(n?.aborted)throw S(a);for(;;){let u;try{u=await s.read()}catch(d){if(o=!0,n?.aborted)throw S(a);if(d instanceof e){if(d.code==="unavailable"||d.code==="outcome_unknown")A.set(d,"disconnected");throw d}throw m("disconnected","The connection dropped mid-stream",a,d)}if(n?.aborted)throw o=!0,S(a);if(u.done){o=!0;return}yield u.value}}finally{if(n?.removeEventListener("abort",l),!o)await s.cancel().catch(()=>{});s.releaseLock()}}function S(i){return new e("Stream aborted. The signal was cancelled.",{code:"aborted",provider:i.provider,sandboxId:i.sandboxId})}var O=new TextDecoder;var C=16777216;async function*le(i,a){let s=a.maxFrameBytes??C,n=new k,o=(l,u)=>{let d=O.decode(l).replace(/\r$/,"");try{return JSON.parse(d)}catch{throw u?m("truncated","The stream ended inside a JSON line",a):m("malformed","A line is not valid JSON",a)}};for await(let l of p(i,a)){let u=n.length;n.push(l);for(let d=n.find((f)=>f===10,u);d>=0;d=n.find((f)=>f===10)){if(d>s)throw m("frame_too_large",`A JSON line exceeds ${s} bytes`,a);let f=n.take(d+1).subarray(0,d);if(f.some((c)=>c!==13&&c!==32&&c!==9))yield o(f,!1)}if(n.length>s)throw m("frame_too_large",`A JSON line exceeds ${s} bytes`,a)}if(n.length){let l=n.take(n.length);if(l.some((u)=>u!==13&&u!==32&&u!==9))yield o(l,!0)}}async function*ue(i,a){let s=a.maxFrameBytes??C,n=new k,o=p(i,a),l=async(f)=>{while(n.length<f){let c=await o.next();if(c.done)return!1;n.push(c.value)}return!0};try{for(let f=!1;;){if(!await l(5)){if(n.length)throw m("truncated","The stream ended inside a Connect frame header",a);if(!f)throw m("truncated","The stream ended before the Connect end-of-stream frame",a);return}if(f)throw m("malformed","A Connect frame followed the end-of-stream frame",a);let c=n.take(5),y=c[0],g=new DataView(c.buffer,c.byteOffset,5).getUint32(1);if(y&1)throw m("malformed","A Connect frame is compressed, but no compression was negotiated",a);if(y&-4)throw m("malformed","A Connect frame has unknown flags",a);if(g>s)throw m("frame_too_large",`A Connect frame exceeds ${s} bytes`,a);if(!await l(g))throw m("truncated","The stream ended inside a Connect frame",a);let b=u(n.take(g));if(y&2)f=!0,yield d(b);else yield{kind:"message",message:b}}}finally{await o.return()}function u(f){try{return JSON.parse(O.decode(f))}catch{throw m("malformed","A Connect frame is not valid JSON",a)}}function d(f){if(!r(f)||f===null)throw m("malformed","The Connect end-of-stream frame is not an object",a);let c="error"in f?f.error:void 0,y="metadata"in f?f.metadata:void 0,g={kind:"end"};if(c!==void 0){if(!r(c)||c===null)throw m("malformed","The Connect end-of-stream error is not an object",a);let b="code"in c?c.code:void 0,w="message"in c?c.message:void 0,x="details"in c?c.details:void 0;if(!t(b))throw m("malformed","The Connect end-of-stream error has no code",a);let v={code:b};if(t(w))v.message=w;if(Array.isArray(x))v.details=x;g.error=v}if(r(y)){let b=Object.entries(y).filter((w)=>Array.isArray(w[1])&&w[1].every((x)=>t(x)));g.metadata=Object.fromEntries(b)}return g}}function fe(i,a=!1){let s=new TextEncoder().encode(JSON.stringify(i)),n=new Uint8Array(5+s.byteLength);return n[0]=a?2:0,new DataView(n.buffer).setUint32(1,s.byteLength),n.set(s,5),n}
2
+ export{J,le,ue,fe};
@@ -0,0 +1,4 @@
1
+ function t(n){return typeof n==="string"}function o(n){return typeof n==="number"}function _(n){return typeof n==="boolean"}function r(n){return typeof n==="object"&&n!==null}var g={auth:"Set the provider's API key environment variable or pass it to the provider factory.",not_found:"Create a new sandbox, or pass a key to createSandbox so it recreates one for you.",quota:"Wait and retry, destroy unused sandboxes with reapSandboxes, or raise the provider plan.",unavailable:"Retry with backoff. Check the provider's status page if it persists.",unsupported:"Remove the option or choose a provider that supports it. Check box.capabilities.",timeout:"Retry, or raise the relevant timeout option.",aborted:"Retry with a fresh AbortSignal if you still need the result.",outcome_unknown:"Check the sandbox state before retrying. If in doubt, destroy it.",process_exited:"Read the exit code and log tail in the message, fix the command, and start it again.",port_not_ready:"Check that the server listens on 0.0.0.0 and the right port, then read its logs.",edit_not_found:"Read the file again and use text that is in it.",edit_not_unique:"Add surrounding lines to find so it matches exactly once.",file_not_found:"Check the path. Relative paths resolve against /workspace.",invalid_argument:"Fix the input. Retrying the same call will not help.",provider:"Read the message and cause. Report it if it looks like an SDK bug."};class e extends Error{code;retryable;hint;provider;sandboxId;constructor(n,d){super(n,{cause:d.cause});this.name="SandboxError",this.code=d.code,this.retryable=d.retryable??!1,this.hint=d.hint??g[d.code]??g.provider,this.provider=d.provider??"unknown",this.sandboxId=d.sandboxId}static{Object.defineProperty(this,"name",{value:"SandboxError"})}[Symbol.for("nodejs.util.inspect.custom")](n,d,u){let c=this.stack??"",p=c.indexOf(`
2
+ at `)>=0?c.slice(c.indexOf(`
3
+ at `)):"",f={code:this.code,provider:this.provider,sandboxId:this.sandboxId,retryable:this.retryable,hint:this.hint,cause:this.cause};return`SandboxError [${this.code}]: ${this.message}${p} ${u(f,d)}`}}function I(n){return n instanceof e&&(n.code==="file_not_found"||n.code==="not_found")}class S{values=new Set;add(n){for(let d of n)if(d)this.values.add(d)}text(n){for(let d of[...this.values].sort((u,c)=>c.length-u.length))n=n.split(d).join("[REDACTED]");return n}get secrets(){return[...this.values].sort((n,d)=>d.length-n.length)}get maxLength(){return Math.max(1,...[...this.values].map((n)=>n.length))}error(n,d,u){if(n instanceof e)return new e(b(this.text(n.message)),{code:n.code,retryable:n.retryable,hint:b(this.text(n.hint)),provider:d,sandboxId:u??n.sandboxId,cause:n.cause===void 0?void 0:B(this.text(n.cause instanceof Error?n.cause.message:String(n.cause)))});let c=B(this.text(n instanceof Error?n.message:t(n)?n:"Non-Error value thrown"));return new e(`${c}. Provider request failed. Check the provider settings and retry.`,{code:"provider",hint:g.provider,provider:d,sandboxId:u,cause:h(n,(p)=>this.text(p))})}}var v=[[/https?:\/\/[^\s"'<>]+/gi,"[URL REDACTED]"],[/(\bauthorization["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\r\n;]+)/gi,"$1[REDACTED]"],[/\bBearer\s+[^\s"',;]+/gi,"Bearer [REDACTED]"],[/((?:["']?(?:api[-_]?key|access[-_]?token|token|password|secret)["']?)\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;]+)/gi,"$1[REDACTED]"]];function b(n){for(let[d,u]of v)n=n.replace(d,u);return n}function B(n){return b(n).replace(/\p{Cc}+/gu," ").slice(0,1000)}function h(n,d=(c)=>c,u=0){if(!(n instanceof Error))return;let c=B(d(n.message?`${n.name}: ${n.message}`:n.name)),p=u<2?h(n.cause,d,u+1):void 0;return p===void 0?c:`${c}; caused by ${p}`}var x={auth:"the credentials are missing or were rejected",not_found:"the sandbox does not exist",quota:"a provider limit or billing stopped the request",unavailable:"the service is down or unreachable",unsupported:"the provider cannot do what was asked",timeout:"the operation took too long",aborted:"the request was aborted",outcome_unknown:"the request may or may not have happened",process_exited:"the process exited before it was ready",port_not_ready:"the port did not become ready",edit_not_found:"the text to replace was not found",edit_not_unique:"the text to replace matched more than once",file_not_found:"the path does not exist",invalid_argument:"the provider rejected the request as invalid",provider:"the provider returned an unexpected error"};function i(n,d){let c=!(d.known??d.code!=="provider")&&d.status===void 0?h(n,d.redact):void 0,p=[n instanceof Error?n.name:void 0,d.status].filter((f)=>f!==void 0).join(" ");return{detail:c,cause:c??(p||void 0)}}function ce(n){return Object.assign(Error(JSON.stringify(n)),n)}function l(n){let d=new S;for(let u of n)if(u)d.add([u]);return(u)=>d.text(u)}function a(n,d){return d??x[n]}function we(n){if(n===400||n===422)return"invalid_argument";if(n===401||n===403)return"auth";if(n===402||n===429)return"quota";if(n===404||n===410)return"not_found";if(n===408||n===504)return"timeout";if(n===413)return"unsupported";if(n>=500&&n<=599)return"unavailable";return"provider"}function s(n){throw new e(`${n}. The request is invalid. Check the supplied options.`,{code:"invalid_argument"})}
4
+ export{t,o,_,r,e,I,S,B,h,i,ce,l,a,we,s};
@@ -1,2 +1,2 @@
1
- import{t,o}from"./chunk-xgxfy2n8.js";function T(s){let i=[];function f(r){if(t(r)){let e=Buffer.from(r),n=Buffer.alloc(5);n[0]=117,n.writeUInt32LE(e.length,1),i.push(n,e)}else if(o(r)){let e=Buffer.alloc(9);e[0]=103,e.writeDoubleLE(r,1),i.push(e)}else if(Array.isArray(r)){let e=Buffer.alloc(5);e[0]=91,e.writeUInt32LE(r.length,1),i.push(e);for(let n of r)f(n)}else if(r!==void 0){i.push(Buffer.from("{"));for(let[e,n]of Object.entries(r))if(n!==void 0)f(e),f(n);i.push(Buffer.from("0"))}}return f(s),Buffer.concat(i)}
2
- export{T};
1
+ import{t,o}from"./chunk-n7x9ha44.js";function C(s){let i=[];function f(r){if(t(r)){let e=Buffer.from(r),n=Buffer.alloc(5);n[0]=117,n.writeUInt32LE(e.length,1),i.push(n,e)}else if(o(r)){let e=Buffer.alloc(9);e[0]=103,e.writeDoubleLE(r,1),i.push(e)}else if(Array.isArray(r)){let e=Buffer.alloc(5);e[0]=91,e.writeUInt32LE(r.length,1),i.push(e);for(let n of r)f(n)}else if(r!==void 0){i.push(Buffer.from("{"));for(let[e,n]of Object.entries(r))if(n!==void 0)f(e),f(n);i.push(Buffer.from("0"))}}return f(s),Buffer.concat(i)}
2
+ export{C};
@@ -1,4 +1,4 @@
1
- import{p}from"./chunk-x681p5d2.js";import{n}from"./chunk-2ts3evzh.js";import{t,o,I,r,e}from"./chunk-xgxfy2n8.js";function C(s){return Array.isArray(s)&&(s[0]==="stdout"||s[0]==="stderr")&&t(s[1])&&s[1].length<=21848}function D(s){return r(s)&&"chunks"in s&&Array.isArray(s.chunks)&&"offset"in s&&o(s.offset)}function T(s){return r(s)&&"result"in s&&r(s.result)&&"exitCode"in s.result&&(s.result.exitCode===null||o(s.result.exitCode))&&"timedOut"in s.result&&I(s.result.timedOut)&&"chunks"in s&&Array.isArray(s.chunks)&&"offset"in s&&o(s.offset)&&"size"in s&&o(s.size)}var F=`import os,sys,fcntl,signal,shutil,time,json
1
+ import{p}from"./chunk-6bemkxcx.js";import{n}from"./chunk-2ts3evzh.js";import{t,o,_,r,e}from"./chunk-n7x9ha44.js";function I(s){return Array.isArray(s)&&(s[0]==="stdout"||s[0]==="stderr")&&t(s[1])&&s[1].length<=21848}function N(s){return r(s)&&"chunks"in s&&Array.isArray(s.chunks)&&"offset"in s&&o(s.offset)}function D(s){return r(s)&&"result"in s&&r(s.result)&&"exitCode"in s.result&&(s.result.exitCode===null||o(s.result.exitCode))&&"timedOut"in s.result&&_(s.result.timedOut)&&"chunks"in s&&Array.isArray(s.chunks)&&"offset"in s&&o(s.offset)&&"size"in s&&o(s.size)}var T=`import os,sys,fcntl,signal,shutil,time,json
2
2
  root=sys.argv[1]
3
3
  os.makedirs(root,mode=0o700,exist_ok=True)
4
4
  with open(root+'/lock','w') as lock:
@@ -26,6 +26,6 @@ try:
26
26
  except FileNotFoundError: pass
27
27
  print(json.dumps(dict(chunks=chunks,offset=start)))
28
28
  # Retain a tombstone if a delayed supervisor can still arrive.
29
- if pid: shutil.rmtree(root,ignore_errors=True)`;async function U(s){let{guest:d,input:a,launch:f,fail:u}=s;if(a.signal?.aborted)return{exitCode:null,timedOut:!0};let l=`/tmp/.sandbox-sdk/run-${crypto.randomUUID()}`,E=new AbortController,N=setTimeout(()=>E.abort(),a.timeoutMs),m=a.signal?AbortSignal.any([a.signal,E.signal]):E.signal,w=0,g={stdout:new TextDecoder,stderr:new TextDecoder};async function A(){let y=await d.raw(p(F,l,String(w))),i=JSON.parse(y);if(!D(i)||i.chunks.length>65536||!Number.isSafeInteger(i.offset)||i.offset<w)throw u("Invalid cancellation output");if(i.offset!==w)S(g,a);for(let h of i.chunks){if(!C(h))throw u("Invalid output record");P(h,g,a)}S(g,a)}let O=!1;async function x(){try{await A()}catch{throw u("Process cancellation could not be confirmed","outcome_unknown")}return O=!1,{exitCode:null,timedOut:!0}}try{let y;try{y=await f(l,m)}catch(c){if(c instanceof e&&c.code==="unsupported")throw c;try{await A()}catch{throw u("Process cancellation could not be confirmed","outcome_unknown")}if(m.aborted)return{exitCode:null,timedOut:!0};throw c}let i=JSON.parse(y);if(!T(i)||i.chunks.length>3||!Number.isSafeInteger(i.offset)||i.offset<0||!Number.isSafeInteger(i.size)||i.size<i.offset)throw u("Invalid command response");if(O=i.offset<i.size||i.result.timedOut,m.aborted)return await x();for(let c of i.chunks){if(!C(c))throw u("Invalid output record");P(c,g,a)}w=i.offset;let h=i.offset,k="";while(h<i.size){if(m.aborted)return await x();let c;try{c=await d.read(l+"/out",{offset:h,length:Math.min(65536,i.size-h)},m)}catch(b){if(m.aborted)return await x();throw b}if(m.aborted)return await x();if(!c.length)throw u("Incomplete output read");h+=c.length,k+=new TextDecoder().decode(c);let R=k.split(`
30
- `);k=R.pop()??"";for(let b of R){let z=JSON.parse(b);if(!C(z))throw u("Invalid output record");P(z,g,a),w+=Buffer.byteLength(b)+1}}if(k)throw u("Incomplete output record");return S(g,a),{exitCode:i.result.exitCode,timedOut:i.result.timedOut}}finally{if(clearTimeout(N),O)await d.raw(`rm -rf -- ${n(l)}`).catch(()=>{})}}function P(s,d,a){let[f,u]=s,l=d[f].decode(Buffer.from(u,"hex"),{stream:!0});if(l)a.onChunk({stream:f,text:l})}function S(s,d){for(let a of["stdout","stderr"]){let f=s[a].decode();if(f)d.onChunk({stream:a,text:f})}}
31
- export{U};
29
+ if pid: shutil.rmtree(root,ignore_errors=True)`;async function q(s){let{guest:d,input:a,launch:f,fail:u}=s;if(a.signal?.aborted)return{exitCode:null,timedOut:!0};let l=`/tmp/.sandbox-sdk/run-${crypto.randomUUID()}`,E=new AbortController,z=setTimeout(()=>E.abort(),a.timeoutMs),m=a.signal?AbortSignal.any([a.signal,E.signal]):E.signal,w=0,g={stdout:new TextDecoder,stderr:new TextDecoder};async function S(){let y=await d.raw(p(T,l,String(w))),i=JSON.parse(y);if(!N(i)||i.chunks.length>65536||!Number.isSafeInteger(i.offset)||i.offset<w)throw u("Invalid cancellation output");if(i.offset!==w)P(g,a);for(let h of i.chunks){if(!I(h))throw u("Invalid output record");C(h,g,a)}P(g,a)}let O=!1;async function x(){try{await S()}catch{throw u("Process cancellation could not be confirmed","outcome_unknown")}return O=!1,{exitCode:null,timedOut:!0}}try{let y;try{y=await f(l,m)}catch(c){if(c instanceof e&&c.code==="unsupported")throw c;try{await S()}catch{throw u("Process cancellation could not be confirmed","outcome_unknown")}if(m.aborted)return{exitCode:null,timedOut:!0};throw c}let i=JSON.parse(y);if(!D(i)||i.chunks.length>3||!Number.isSafeInteger(i.offset)||i.offset<0||!Number.isSafeInteger(i.size)||i.size<i.offset)throw u("Invalid command response");if(O=i.offset<i.size||i.result.timedOut,m.aborted)return await x();for(let c of i.chunks){if(!I(c))throw u("Invalid output record");C(c,g,a)}w=i.offset;let h=i.offset,k="";while(h<i.size){if(m.aborted)return await x();let c;try{c=await d.read(l+"/out",{offset:h,length:Math.min(65536,i.size-h)},m)}catch(b){if(m.aborted)return await x();throw b}if(m.aborted)return await x();if(!c.length)throw u("Incomplete output read");h+=c.length,k+=new TextDecoder().decode(c);let A=k.split(`
30
+ `);k=A.pop()??"";for(let b of A){let R=JSON.parse(b);if(!I(R))throw u("Invalid output record");C(R,g,a),w+=Buffer.byteLength(b)+1}}if(k)throw u("Incomplete output record");return P(g,a),{exitCode:i.result.exitCode,timedOut:i.result.timedOut}}finally{if(clearTimeout(z),O)await d.raw(`rm -rf -- ${n(l)}`).catch(()=>{})}}function C(s,d,a){let[f,u]=s,l=d[f].decode(Buffer.from(u,"hex"),{stream:!0});if(l)a.onChunk({stream:f,text:l})}function P(s,d){for(let a of["stdout","stderr"]){let f=s[a].decode();if(f)d.onChunk({stream:a,text:f})}}
31
+ export{q};
@@ -0,0 +1,2 @@
1
+ import{r}from"./chunk-n7x9ha44.js";function f(e){return r(e)&&!Array.isArray(e)}
2
+ export{f};
package/dist/http.d.ts CHANGED
@@ -218,6 +218,9 @@ export declare function httpStatus(cause: unknown): {
218
218
  status: number;
219
219
  code?: string;
220
220
  } | undefined;
221
+ /** @internal Whether a rejection proves the request never left this process, so no server saw it:
222
+ * a fetch failure, an error caused by one, or this client's failure for such a request. */
223
+ export declare const neverSent: (cause: unknown) => boolean;
221
224
  /** Pulls the code and message out of the error shapes providers use: `{ code, message }`, `{ error: { code, message } }`, `{ error: "text" }`, RFC 7807. */
222
225
  export declare function parseErrorBody(text: string): ErrorBody;
223
226
  /** Builds the client. Planes are fixed; their base URLs and credentials are read per request. */
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{X,O,j,W,Q}from"./chunk-hgrwyjrb.js";import{e}from"./chunk-xgxfy2n8.js";export{e as SandboxError,j as connectSandbox,O as createSandbox,X as hasCapability,W as listSandboxes,Q as reapSandboxes};
1
+ import{ne,O,U,Q,re}from"./chunk-ea8y7y2p.js";import{e}from"./chunk-n7x9ha44.js";export{e as SandboxError,U as connectSandbox,O as createSandbox,ne as hasCapability,Q as listSandboxes,re as reapSandboxes};
package/dist/mastra.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-23tjmd39.js";import{M}from"./chunk-nw845a93.js";import"./chunk-ckym4cht.js";import{createTool as s}from"@mastra/core/tools";import{z as e}from"zod";function c(p,r){return Object.fromEntries(M(p,r).map((o)=>[o.name,s({id:o.name,description:o.description,inputSchema:o.inputSchema,outputSchema:e.object({text:e.string()}),execute:(t,a)=>o.execute(t,void 0,a?.abortSignal),toModelOutput:(t)=>({type:"text",value:t.text})})]))}export{c as sandboxTools};
1
+ import"./chunk-6nf686jb.js";import{R}from"./chunk-c1wemt0y.js";import"./chunk-5gnqph3c.js";import{createTool as s}from"@mastra/core/tools";import{z as e}from"zod";function c(p,r){return Object.fromEntries(R(p,r).map((o)=>[o.name,s({id:o.name,description:o.description,inputSchema:o.inputSchema,outputSchema:e.object({text:e.string()}),execute:(t,a)=>o.execute(t,void 0,a?.abortSignal),toModelOutput:(t)=>({type:"text",value:t.text})})]))}export{c as sandboxTools};
package/dist/memory.js CHANGED
@@ -1,4 +1,4 @@
1
- import{e}from"./chunk-xgxfy2n8.js";import{posix as u}from"node:path";function V(L={}){let b=new Map,g=new Map,w=(r,t)=>new e(`${r}. Memory resource does not exist or request is invalid. Check the path or ID.`,{code:t,provider:"memory"}),v=(r)=>{let t=b.get(r);if(!t)throw w(`Sandbox ${r} not found`,"not_found");if(t.idleTimeoutMs)clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.active.size)v(r);else S.destroy(r)},t.idleTimeoutMs),t.idleTimer.unref?.();return t},M=(r,t)=>{let n=v(r).nodes.get(u.resolve("/",t));if(!n)throw w(`File ${t} not found`,"file_not_found");return n},I=()=>Date.now();function P(r,t){let n=v(r);for(let o=u.resolve("/",t);;o=u.dirname(o)){let s=n.nodes.get(o);if(s?.data)throw w(`${o} is not a directory`,"invalid_argument");if(!s)n.nodes.set(o,{data:null,modifiedAt:I(),mode:493});if(o==="/")break}}let C={transfer:"files",checkpoints:"files",writeCreatesParents:!0,writeSupportsMode:!0,async readRange(r,t,n){let o=M(r,t);if(o.data===null)throw w(`${t} is a directory`,"invalid_argument");return o.data.slice(n.offset,n.offset+n.length)},async read(r,t){let n=M(r,t);if(n.data===null)throw w(`${t} is a directory`,"invalid_argument");return n.data.slice()},async write(r,t,n,o){let s=v(r);P(r,u.dirname(t));let i=u.resolve("/",t),m=s.nodes.get(i);s.nodes.set(i,{data:n.slice(),modifiedAt:Math.max(I(),(m?.modifiedAt??0)+1),mode:o?.mode??m?.mode??420})},async stat(r,t){let n=M(r,t);return{path:u.resolve("/",t),type:n.data===null?"directory":"file",size:n.data?.length??0,modifiedAt:n.modifiedAt}},async list(r,t){let n=u.resolve("/",t);if(M(r,t).data!==null)throw w(`${t} is not a directory`,"invalid_argument");let o=[];for(let s of v(r).nodes.keys())if(s!==n&&u.dirname(s)===n)o.push(await C.stat(r,s));return o.sort((s,i)=>s.path.localeCompare(i.path))},async remove(r,t,n){let o=v(r),s=u.resolve("/",t);M(r,s);let i=[...o.nodes.keys()].filter((m)=>m.startsWith(s+"/"));if(i.length&&!n.recursive)throw w(`${t} is not empty`,"invalid_argument");for(let m of i)o.nodes.delete(m);o.nodes.delete(s)},async mkdir(r,t){P(r,t)}},Z=({args:r,signal:t})=>new Promise((n)=>{if(t.aborted){n(137);return}let o=setTimeout(()=>{t.removeEventListener("abort",s),n(0)},Math.max(0,Number(r[0]??0)*1000)),s=()=>{clearTimeout(o),n(137)};t.addEventListener("abort",s,{once:!0})});g.set("echo",({args:r,stdout:t})=>{let n=r[0]==="-n";return t((n?r.slice(1):r).join(" ")+(n?"":`
1
+ import{e}from"./chunk-n7x9ha44.js";import{posix as u}from"node:path";function V(L={}){let b=new Map,g=new Map,w=(r,t)=>new e(`${r}. Memory resource does not exist or request is invalid. Check the path or ID.`,{code:t,provider:"memory"}),v=(r)=>{let t=b.get(r);if(!t)throw w(`Sandbox ${r} not found`,"not_found");if(t.idleTimeoutMs)clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.active.size)v(r);else S.destroy(r)},t.idleTimeoutMs),t.idleTimer.unref?.();return t},M=(r,t)=>{let n=v(r).nodes.get(u.resolve("/",t));if(!n)throw w(`File ${t} not found`,"file_not_found");return n},I=()=>Date.now();function P(r,t){let n=v(r);for(let o=u.resolve("/",t);;o=u.dirname(o)){let s=n.nodes.get(o);if(s?.data)throw w(`${o} is not a directory`,"invalid_argument");if(!s)n.nodes.set(o,{data:null,modifiedAt:I(),mode:493});if(o==="/")break}}let C={transfer:"files",checkpoints:"files",writeCreatesParents:!0,writeSupportsMode:!0,async readRange(r,t,n){let o=M(r,t);if(o.data===null)throw w(`${t} is a directory`,"invalid_argument");return o.data.slice(n.offset,n.offset+n.length)},async read(r,t){let n=M(r,t);if(n.data===null)throw w(`${t} is a directory`,"invalid_argument");return n.data.slice()},async write(r,t,n,o){let s=v(r);P(r,u.dirname(t));let i=u.resolve("/",t),m=s.nodes.get(i);s.nodes.set(i,{data:n.slice(),modifiedAt:Math.max(I(),(m?.modifiedAt??0)+1),mode:o?.mode??m?.mode??420})},async stat(r,t){let n=M(r,t);return{path:u.resolve("/",t),type:n.data===null?"directory":"file",size:n.data?.length??0,modifiedAt:n.modifiedAt}},async list(r,t){let n=u.resolve("/",t);if(M(r,t).data!==null)throw w(`${t} is not a directory`,"invalid_argument");let o=[];for(let s of v(r).nodes.keys())if(s!==n&&u.dirname(s)===n)o.push(await C.stat(r,s));return o.sort((s,i)=>s.path.localeCompare(i.path))},async remove(r,t,n){let o=v(r),s=u.resolve("/",t);M(r,s);let i=[...o.nodes.keys()].filter((m)=>m.startsWith(s+"/"));if(i.length&&!n.recursive)throw w(`${t} is not empty`,"invalid_argument");for(let m of i)o.nodes.delete(m);o.nodes.delete(s)},async mkdir(r,t){P(r,t)}},Z=({args:r,signal:t})=>new Promise((n)=>{if(t.aborted){n(137);return}let o=setTimeout(()=>{t.removeEventListener("abort",s),n(0)},Math.max(0,Number(r[0]??0)*1000)),s=()=>{clearTimeout(o),n(137)};t.addEventListener("abort",s,{once:!0})});g.set("echo",({args:r,stdout:t})=>{let n=r[0]==="-n";return t((n?r.slice(1):r).join(" ")+(n?"":`
2
2
  `)),0}),g.set("printf",({args:r,stdout:t})=>{let n=1;return t((r[0]??"").replace(/\\n/g,`
3
3
  `).replace(/\\t/g,"\t").replace(/%[sd%]/g,(o)=>o==="%%"?"%":r[n++]??"")),0}),g.set("pwd",({cwd:r,stdout:t})=>(t(r+`
4
4
  `),0)),g.set("true",()=>0),g.set("false",()=>1),g.set("exit",({args:r})=>Number(r[0]??0)),g.set("sleep",Z),g.set("cat",async({args:r,stdin:t,stdout:n,stderr:o,files:s})=>{if(!r.length)n(t);else for(let i of r)try{n(new TextDecoder().decode(await s.read(i)))}catch{return o(`cat: ${i}: No such file or directory
package/dist/openai.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-23tjmd39.js";import{M}from"./chunk-nw845a93.js";import"./chunk-ckym4cht.js";import{tool as r}from"@openai/agents";function m(t,e){return M(t,e).map((o)=>r({name:o.name,description:o.description,parameters:o.inputSchema,strict:!0,execute:async(s,n,a)=>(await o.execute(s,void 0,a?.signal)).text}))}export{m as sandboxTools};
1
+ import"./chunk-6nf686jb.js";import{R}from"./chunk-c1wemt0y.js";import"./chunk-5gnqph3c.js";import{tool as r}from"@openai/agents";function m(t,e){return R(t,e).map((o)=>r({name:o.name,description:o.description,parameters:o.inputSchema,strict:!0,execute:async(s,n,a)=>(await o.execute(s,void 0,a?.signal)).text}))}export{m as sandboxTools};
@@ -78,6 +78,25 @@ export interface ProviderFiles {
78
78
  readonly checkpoints?: "files";
79
79
  /** Write handles missing parents itself, avoiding an unconditional mkdir RPC. */
80
80
  readonly writeCreatesParents?: boolean;
81
+ /**
82
+ * One exec carrying a small environment variable costs less than a read plus a write, so `files.edit`
83
+ * runs as one guest python3 call that changes the file the way `write` does: `"in-place"` when `write`
84
+ * truncates and rewrites the existing inode, `"replace"` when it renames a new file over it. Leave it
85
+ * unset where extra env is staged through more requests; edit then reads and writes.
86
+ */
87
+ readonly editInGuest?: "in-place" | "replace";
88
+ /**
89
+ * The order `list` returns entries in: `"name"` sorted by name bytes, `"directory"` the filesystem's
90
+ * own order (what `os.listdir` returns). When set, `files.search` walks the tree in one guest python3
91
+ * call in that order, so `maxMatches` stops at the same files. Unset, search lists and reads each file.
92
+ */
93
+ readonly listOrder?: "name" | "directory";
94
+ /**
95
+ * How guest file commands (edit and search above) may take their input in this sandbox: `"stdin"`,
96
+ * the default, also accepts input over 32 KiB on stdin; `"env"` only the environment, so larger input
97
+ * uses the RPC path; `"none"` keeps those commands on the RPC path.
98
+ */
99
+ guestInput?(id: string): Promise<"stdin" | "env" | "none">;
81
100
  /** Write applies `options.mode` itself. Without it, the core runs `chmod` after the write. */
82
101
  readonly writeSupportsMode?: boolean;
83
102
  /** Top-level /workspace entries the provider itself owns. File checkpoints and changes() skip them. */
@@ -130,6 +149,12 @@ export interface Provider<Native = unknown, C extends Capability = Capability> {
130
149
  readonly previewMode?: "placeholder";
131
150
  /** Exec creates/removes input.activityPath without separate file RPCs. */
132
151
  readonly inlineActivity?: boolean;
152
+ /**
153
+ * Every exec from every client shares one Linux PID namespace with `/proc` mounted, and the exec user
154
+ * can read each process's environ (directly, or through passwordless sudo for root-owned ones). The
155
+ * core then runs commands without a marker and idle reaping scans `/proc` for the SDK's env tag.
156
+ */
157
+ readonly procActivity?: boolean;
133
158
  /** Native command dialect for portable run wrappers; defaults to POSIX sh. */
134
159
  readonly commandShell?: "bash";
135
160
  /** Durable absolute directory for core-owned process records. */