@opencoredev/sandbox-sdk 1.0.0-beta.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +70 -63
  3. package/dist/ai.js +1 -1
  4. package/dist/chunk-23tjmd39.js +8 -0
  5. package/dist/chunk-2ts3evzh.js +2 -0
  6. package/dist/chunk-83avbjns.js +2 -0
  7. package/dist/chunk-8786zrns.js +2 -0
  8. package/dist/chunk-8wq767xb.js +17 -0
  9. package/dist/chunk-9w9rddra.js +2 -0
  10. package/dist/chunk-bd481sb7.js +2 -0
  11. package/dist/chunk-ckym4cht.js +23 -0
  12. package/dist/chunk-gw3n7sx7.js +5 -0
  13. package/dist/chunk-hgrwyjrb.js +2 -0
  14. package/dist/chunk-hzbssbep.js +31 -0
  15. package/dist/chunk-k60b4r27.js +2 -0
  16. package/dist/chunk-kk1hw8wa.js +1 -0
  17. package/dist/chunk-nw845a93.js +27 -0
  18. package/dist/chunk-q5vqajhg.js +2 -0
  19. package/dist/chunk-vy1j4r8f.js +2 -0
  20. package/dist/chunk-x681p5d2.js +68 -0
  21. package/dist/chunk-xgxfy2n8.js +4 -0
  22. package/dist/core/process-records.d.ts +25 -0
  23. package/dist/errors.d.ts +67 -1
  24. package/dist/files.d.ts +11 -4
  25. package/dist/git.d.ts +1 -1
  26. package/dist/http.d.ts +225 -0
  27. package/dist/index.d.ts +3 -1
  28. package/dist/index.js +1 -1
  29. package/dist/keys.d.ts +5 -0
  30. package/dist/mastra.d.ts +1 -1
  31. package/dist/mastra.js +1 -1
  32. package/dist/memory.d.ts +4 -1
  33. package/dist/memory.js +11 -9
  34. package/dist/native.d.ts +127 -0
  35. package/dist/openai.js +1 -1
  36. package/dist/peer.d.ts +9 -0
  37. package/dist/provider.d.ts +38 -5
  38. package/dist/provider.js +1 -0
  39. package/dist/providers/agentos/errors.d.ts +3 -2
  40. package/dist/providers/agentos/index.d.ts +2 -9
  41. package/dist/providers/agentos/index.js +2 -2
  42. package/dist/providers/agentos/provider.d.ts +50 -0
  43. package/dist/providers/boat/index.d.ts +52 -9
  44. package/dist/providers/boat/index.js +1 -1
  45. package/dist/providers/boat-api/exec.d.ts +15 -2
  46. package/dist/providers/boat-api/follow.d.ts +24 -0
  47. package/dist/providers/boat-api/index.d.ts +45 -7
  48. package/dist/providers/boat-api/transport.d.ts +77 -0
  49. package/dist/providers/boxd/errors.d.ts +2 -2
  50. package/dist/providers/boxd/execute.d.ts +2 -2
  51. package/dist/providers/boxd/index.d.ts +2 -22
  52. package/dist/providers/boxd/index.js +24 -4
  53. package/dist/providers/boxd/provider.d.ts +74 -0
  54. package/dist/providers/boxd/transfers.d.ts +9 -0
  55. package/dist/providers/daytona/api.d.ts +124 -0
  56. package/dist/providers/daytona/buffered.d.ts +2 -2
  57. package/dist/providers/daytona/errors.d.ts +18 -2
  58. package/dist/providers/daytona/exec.d.ts +3 -3
  59. package/dist/providers/daytona/index.d.ts +53 -4
  60. package/dist/providers/daytona/index.js +18 -10
  61. package/dist/providers/daytona/multipart.d.ts +25 -0
  62. package/dist/providers/e2b/envd.d.ts +113 -0
  63. package/dist/providers/e2b/errors.d.ts +20 -3
  64. package/dist/providers/e2b/index.d.ts +41 -3
  65. package/dist/providers/e2b/index.js +1 -1
  66. package/dist/providers/freestyle/client.d.ts +87 -0
  67. package/dist/providers/freestyle/deadline.d.ts +3 -2
  68. package/dist/providers/freestyle/errors.d.ts +14 -1
  69. package/dist/providers/freestyle/execute.d.ts +3 -7
  70. package/dist/providers/freestyle/index.d.ts +28 -2
  71. package/dist/providers/freestyle/index.js +5 -33
  72. package/dist/providers/local/docker.d.ts +10 -6
  73. package/dist/providers/local/index.d.ts +29 -0
  74. package/dist/providers/local/index.js +2 -2
  75. package/dist/providers/railway/errors.d.ts +7 -1
  76. package/dist/providers/railway/index.d.ts +2 -23
  77. package/dist/providers/railway/index.js +1 -1
  78. package/dist/providers/railway/provider.d.ts +53 -0
  79. package/dist/providers/sandboxer/index.d.ts +15 -8
  80. package/dist/providers/sandboxer/index.js +1 -1
  81. package/dist/providers/superserve/errors.d.ts +2 -2
  82. package/dist/providers/superserve/execute.d.ts +3 -8
  83. package/dist/providers/superserve/index.d.ts +32 -3
  84. package/dist/providers/superserve/index.js +5 -37
  85. package/dist/providers/superserve/routes.d.ts +80 -0
  86. package/dist/providers/superserve/session.d.ts +33 -0
  87. package/dist/providers/tenki/deadline.d.ts +1 -1
  88. package/dist/providers/tenki/errors.d.ts +3 -3
  89. package/dist/providers/tenki/exec.d.ts +1 -1
  90. package/dist/providers/tenki/files.d.ts +1 -1
  91. package/dist/providers/tenki/index.d.ts +2 -27
  92. package/dist/providers/tenki/index.js +19 -16
  93. package/dist/providers/tenki/provider.d.ts +95 -0
  94. package/dist/providers/tenki/ready.d.ts +1 -1
  95. package/dist/providers/tenki/records.d.ts +16 -0
  96. package/dist/providers/tenki/stream.d.ts +2 -2
  97. package/dist/providers/upstash/buffered.d.ts +1 -1
  98. package/dist/providers/upstash/errors.d.ts +1 -1
  99. package/dist/providers/upstash/exec.d.ts +2 -2
  100. package/dist/providers/upstash/files.d.ts +1 -1
  101. package/dist/providers/upstash/index.d.ts +2 -34
  102. package/dist/providers/upstash/index.js +12 -18
  103. package/dist/providers/upstash/provider.d.ts +81 -0
  104. package/dist/providers/vercel/errors.d.ts +3 -1
  105. package/dist/providers/vercel/index.d.ts +13 -5
  106. package/dist/providers/vercel/index.js +1 -1
  107. package/dist/providers/vercel/provider.d.ts +50 -2
  108. package/dist/providers/vercel/transport.d.ts +7 -4
  109. package/dist/run.d.ts +6 -4
  110. package/dist/shared/deadline.d.ts +12 -0
  111. package/dist/shared/guest.d.ts +18 -0
  112. package/dist/shared/json.d.ts +11 -0
  113. package/dist/shared/metadata.d.ts +19 -0
  114. package/dist/shared/narrow.d.ts +8 -0
  115. package/dist/shared/native-error.d.ts +42 -0
  116. package/dist/shared/paged-exec.d.ts +22 -0
  117. package/dist/shared/shell.d.ts +2 -0
  118. package/dist/{providers/freestyle → shared}/wire.d.ts +1 -1
  119. package/dist/shell/process-records.d.ts +44 -0
  120. package/dist/streams.d.ts +72 -0
  121. package/dist/testing.d.ts +12 -2
  122. package/dist/testing.js +7 -4
  123. package/dist/tool-security.d.ts +4 -4
  124. package/dist/tools.d.ts +3 -2
  125. package/dist/tools.js +1 -1
  126. package/dist/types.d.ts +14 -6
  127. package/package.json +29 -46
  128. package/dist/chunk-59t3rqja.js +0 -2
  129. package/dist/chunk-cwx6cc31.js +0 -2
  130. package/dist/chunk-exv1kf89.js +0 -60
  131. package/dist/chunk-gc8zdxyb.js +0 -2
  132. package/dist/chunk-hjzhc3qg.js +0 -40
  133. package/dist/chunk-md6fmprc.js +0 -1
  134. package/dist/chunk-t5vr9nd8.js +0 -8
  135. package/dist/chunk-v6y7eqxw.js +0 -27
  136. package/dist/chunk-yed8mvs7.js +0 -2
  137. package/dist/chunk-yrsb6hws.js +0 -5
  138. package/dist/chunk-z9rjzn28.js +0 -2
  139. package/dist/providers/boxd/guest.d.ts +0 -14
@@ -0,0 +1,31 @@
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
2
+ root=sys.argv[1]
3
+ os.makedirs(root,mode=0o700,exist_ok=True)
4
+ with open(root+'/lock','w') as lock:
5
+ fcntl.flock(lock,fcntl.LOCK_EX)
6
+ with open(root+'/cancelled','w') as f: f.write('1')
7
+ try:
8
+ with open(root+'/pid') as f: pid=int(f.read())
9
+ except FileNotFoundError: pid=None
10
+ if pid and not os.path.exists(root+'/exit'):
11
+ try: os.killpg(pid,signal.SIGKILL)
12
+ except ProcessLookupError: pass
13
+ # Wait for reaping and pipe drainage before recovering the bounded output tail.
14
+ end=time.monotonic()+2
15
+ while pid and not os.path.exists(root+'/exit') and time.monotonic()<end: time.sleep(.01)
16
+ if pid and not os.path.exists(root+'/exit'): sys.exit(1)
17
+ chunks=[]
18
+ start=int(sys.argv[2])
19
+ try:
20
+ with open(root+'/out','rb') as f:
21
+ size=os.fstat(f.fileno()).st_size
22
+ delivered=int(sys.argv[2])
23
+ start=max(delivered,size-65536); f.seek(start)
24
+ if start>delivered: f.readline(); start=f.tell()
25
+ chunks=[json.loads(line) for line in f]
26
+ except FileNotFoundError: pass
27
+ print(json.dumps(dict(chunks=chunks,offset=start)))
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};
@@ -0,0 +1,2 @@
1
+ import{r,e}from"./chunk-xgxfy2n8.js";var c=(n)=>`Bundle with a createRequire banner (import { createRequire } from "node:module"; const require = createRequire(import.meta.url);) or mark @opencoredev/sandbox-sdk and ${n} as external.`;async function g(n,i,o){let a;try{a=await o()}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ERR_MODULE_NOT_FOUND"&&t.message.includes(`'${n}'`))throw new e(`${n} is not installed. The ${i} adapter loads it as an optional peer. Install ${n} next to @opencoredev/sandbox-sdk.`,{code:"unavailable",provider:i,cause:t});let s=t instanceof Error?/Dynamic require of "[^"]{1,100}" is not supported/.exec(t.message)?.[0]:void 0;if(s===void 0)throw t;throw new e(`${n} could not load in this bundle: ${s}. ${c(n)}`,{code:"unavailable",provider:i,hint:c(n),cause:s})}return Y(a)}function Y(n){if(!r(n)||!("default"in n))return n;let i=n.default;if(!r(i))return n;if(Object.keys(i).every((o)=>(o in n)))return n;return Object.assign({},i,n)}
2
+ export{g,Y};
@@ -0,0 +1 @@
1
+ import{l,u,re,me,A,J,E,oe}from"./chunk-23tjmd39.js";export{A as BufferCap,J as OutputBus,E as chunkRedactor,l as defaults,me as isRunActive,oe as makeRun,u as pathOf,re as secretRecoveryCommand};
@@ -0,0 +1,27 @@
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}
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?`
5
+ Aborted. The calling agent cancelled execution and the command was terminated. Retry only if still needed.`:`
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
+ 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(`
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
+ `)),X=`name=${z} cursor=0 use=process_logs
11
+ `}return f(!0,`${k.join(`
12
+ `)}
13
+ ${D<h.length?"[more lines; use read_file with nextOffset as offset]":""}`,"",void 0,`sha=${_} lines=${h.length} nextOffset=${D<h.length?D:"end"}
14
+ ${X}`)}case"write_file":{let o=d.input;return await p.files.write(await j(o.path),o.content),f(!0,"File written.")}case"edit_file":{let o=d.input;return await p.files.edit(await j(o.path),{find:o.find,replace:o.replace}),f(!0,"One exact match replaced.")}case"start_process":{let o=d.input,a;try{a=await p.start(await Z(o.command),{name:o.name,cwd:await j(o.cwd),ready:o.port?{port:o.port}:void 0,readyTimeoutMs:m})}catch(c){if(!(c instanceof e&&c.code==="timeout"))throw c;return f(!1,`name=${o.name} ready=false cursor=0
15
+ ${c.message}
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
+ cursor=0
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}
20
+ ${g<a.base?`[${a.base-g} bytes expired from replay window]
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?`
23
+ [more output; use process_logs with cursor]`:""}`,"",void 0,`cursor=${x.end} more=${x.more}
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
+ 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};
@@ -0,0 +1,2 @@
1
+ import{f}from"./chunk-9w9rddra.js";import{t,o}from"./chunk-xgxfy2n8.js";function s(n){if(!f(n))return;let e={};for(let[a,r]of Object.entries(n)){if(!t(r))return;Object.defineProperty(e,a,{value:r,enumerable:!0,writable:!0,configurable:!0})}return e}function N(n,e){let a;try{a=JSON.parse(n)}catch{e("metadata")}if(!f(a)||!f(a.labels))e("metadata");let{key:r,version:d,createdAt:l}=a;if(r!==void 0&&r!==null&&!t(r)||d!==void 0&&!o(d)||l!==void 0&&!o(l))e("metadata");let u=s(a.labels)??e("label");return{key:r,labels:u,version:d,createdAt:l}}
2
+ export{N};
@@ -0,0 +1,2 @@
1
+ import{f}from"./chunk-9w9rddra.js";import{Y}from"./chunk-k60b4r27.js";import{t,r,e,D,w,c,fe,s}from"./chunk-xgxfy2n8.js";function Ze(o){return["localhost","127.0.0.1","[::1]"].includes(o)||/\.(test|invalid|example|localhost)$/.test(o)}function d(o,a){let u=Date.now()+o,p=AbortSignal.timeout(Math.max(0,o));return{signal:a?AbortSignal.any([a,p]):p,timeout:p,parent:a,remaining:()=>Math.max(0,u-Date.now())}}function y(o,a,u){return new Promise((p,g)=>{let O=()=>{clearTimeout(W),a.signal.removeEventListener("abort",C)},C=()=>{O(),g(We(a,u))},W=setTimeout(()=>{O(),p()},o);if(a.signal.aborted)C();else a.signal.addEventListener("abort",C,{once:!0})})}function Re(o,a){if(a.aborted)return Promise.reject(a.reason);return new Promise((u,p)=>{let g=()=>p(a.reason);a.addEventListener("abort",g,{once:!0}),o.then(u,p).finally(()=>a.removeEventListener("abort",g))})}function We(o,a,u){return o.parent?.aborted&&!o.timeout.aborted?new e("Request aborted. The signal was cancelled.",{code:"aborted",provider:a,sandboxId:u}):new e("Request timed out. The operation took too long.",{code:"timeout",provider:a,sandboxId:u,retryable:!0})}var _e=new WeakMap;function H(o){return o instanceof e?_e.get(o):void 0}var Xe=65536,Ye=33554432,Qe=20000,Ue=1e4,Ce=5,Le=new Set([429,502,503,504]),qe=new Set([301,302,303,307,308]),Se=new Set(["GET","HEAD","PUT","DELETE"]),et=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","UND_ERR_CONNECT_TIMEOUT","ConnectionRefused","FailedToOpenSocket","ERR_INVALID_URL","ERR_TLS_CERT_ALTNAME_INVALID","UNABLE_TO_VERIFY_LEAF_SIGNATURE","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_HAS_EXPIRED"]),tt=/^(?:authorization|proxy-authorization|cookie|x-api-key|api-key|apikey)$|[-_](?:token|key|secret|password)$/,nt=/^(?:x-)?idempotency-key$/,rt=/^\s*(?:bearer|basic|token|bot|digest)\s+(\S.*?)\s*$/i,ot=/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,je=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/,at=/^[A-Za-z0-9_.:-]{1,128}$/;function De(o,a=0){if(!r(o)||a>3)return[];return[..."code"in o&&t(o.code)?[o.code]:[],...De("cause"in o?o.cause:void 0,a+1)]}function st(o){return typeof o==="string"||o instanceof Uint8Array||o instanceof ArrayBuffer||ArrayBuffer.isView(o)||o instanceof Blob||o instanceof FormData||o instanceof URLSearchParams||o instanceof ReadableStream}function it(o){let a=o.get("retry-after");if(a===null)return;if(/^\d+$/.test(a.trim()))return Number(a.trim())*1000;let u=Date.parse(a);return Number.isNaN(u)?void 0:Math.max(0,u-Date.now())}function he(o,a){if(!f(o))return;for(let u of a){let p=Object.hasOwn(o,u)?o[u]:void 0;if(t(p)&&p)return p}return}function ve(o){let a;try{a=o?JSON.parse(o):void 0}catch{a=void 0}let u=f(a)?a.error:void 0,p=he(a,["code","error_code","errorCode","type"])??he(u,["code","type"])??(t(u)&&je.test(u)?u:void 0),g=he(a,["message","detail","error_description","title"])??he(u,["message"])??(t(u)?u:void 0)??(a===void 0&&o.trim()?o.trim():void 0);return{text:o,json:a,...p===void 0?void 0:{code:p},...g===void 0?void 0:{message:g}}}async function Ne(o,a,u){if(!o)return new Uint8Array;let p=o.getReader(),g=[],O=0;try{for(;;){let{done:q,value:N}=await p.read();if(q)break;if(O+N.byteLength>a){let M=u();if(g.push(N.subarray(0,a-O)),O=a,await p.cancel().catch(()=>{}),M)throw M;break}g.push(N),O+=N.byteLength}}finally{p.releaseLock()}let C=new Uint8Array(O),W=0;for(let q of g)C.set(q,W),W+=q.byteLength;return C}var Pe=new TextDecoder;function dt(o,a,u,p){return{status:o,headers:a,body:u,text:()=>Pe.decode(u),json(){let g=Pe.decode(u);if(!g.trim())return;try{return JSON.parse(g)}catch{throw p("returned a body that is not JSON. Use fetch for text, bytes or streams")}}}}function x(o){let{provider:a,label:u}=o,p=o.timeoutMs??60000,g=o.retries??2,O=o.backoffMs??250,C=new Set,W=(n)=>{C.delete(n),C.add(n);for(let i of C){if(C.size<=256)break;C.delete(i)}},q=(n)=>{if(!n)return;W(n);let i=rt.exec(n)?.[1];if(i)W(i)},N=(n)=>D(c([...C,...o.secrets?.()??[]])(n)),M=new Map,L=(n,i)=>{let l=i.toLowerCase();return M.get(n)?.has(l)===!0||tt.test(l)&&!nt.test(l)},S=new Map,re=o.planes;function ie(n){let i=n??o.defaultPlane,l=Object.hasOwn(re,i)?re[i]:void 0;if(!l)throw j(`Unknown plane "${String(i).slice(0,32)}". Use one of: ${Object.keys(re).join(", ")}`);return{name:i,plane:l}}function j(n,i){return new e(`${N(n)}. The request is invalid. Check the supplied options.`,{code:"invalid_argument",provider:a,sandboxId:i})}function me(n){let i=/^[a-z][a-z0-9+.-]*:/i.test(n.path)?"[absolute URL]":(n.path.split("?")[0]??"").slice(0,200);return`${n.method} ${D(i)}`}function Fe(n){let i=n.params??{},l=new Set,m=n.path.replace(ot,(P,T)=>{if(!Object.hasOwn(i,T))throw j(`The path has a {${T}} placeholder but params.${T} is missing`,n.sandboxId);let E=String(i[T]);if(E===""||E==="."||E==="..")throw j(`params.${T} must not be empty, "." or ".."`,n.sandboxId);return l.add(T),encodeURIComponent(E)}),b=Object.keys(i).filter((P)=>!l.has(P));if(b.length)throw j(`params.${b[0]} has no {${b[0]}} placeholder in the path`,n.sandboxId);return m}function Be(n,i){let l=Fe(i),m;if(/^[a-z][a-z0-9+.-]*:/i.test(l)){try{m=new URL(l)}catch{throw j("The path is not a valid URL",i.sandboxId)}if(m.protocol!=="https:"&&m.protocol!=="http:")throw j("Only http and https URLs are supported",i.sandboxId)}else{if(!l.startsWith("/"))throw j('The path must start with "/" or be an absolute URL',i.sandboxId);if(l.split("?")[0]?.split("/").some((b)=>b==="."||b===".."))throw j('The path must not contain "." or ".." segments',i.sandboxId);m=new URL(n.replace(/\/+$/,"")+l)}for(let[b,P]of Object.entries(i.query??{}))if(P!==void 0)m.searchParams.append(b,String(P));return m}function I(n,i,l,m,b=n==="unavailable"||n==="quota"){let P=n==="auth"?o.authHint:void 0;return new e(N(`${u} ${me(i)} failed${l}`),{code:n,provider:a,sandboxId:i.sandboxId,retryable:b,...P===void 0?void 0:{hint:P},...m===void 0?void 0:{cause:N(m)}})}function F(n,i,l,m=!1){let b=Ve(n,i,l,m),P=o.cause?.(n,{method:i.method,plane:l,operation:me(i),sandboxId:i.sandboxId});if(P===void 0)return b;return new e(b.message,{code:b.code,provider:a,sandboxId:b.sandboxId,retryable:b.retryable,...b.hint===void 0?void 0:{hint:b.hint},cause:P})}function Ve(n,i,l,m){let b=!Se.has(i.method)&&!i.readOnly,P=o.mapError?.(n,{method:i.method,plane:l,operation:me(i),sandboxId:i.sandboxId});switch(n.kind){case"status":{let T=P??fe(n.status);if(b&&(T==="timeout"||m))T="outcome_unknown";let E=n.body.code!==void 0&&je.test(n.body.code)?` ${n.body.code}`:"",oe=["x-request-id","request-id","x-amzn-requestid","cf-ray"].map((X)=>n.headers.get(X)).find((X)=>X!==null&&at.test(X)),B=`HTTP ${n.status}${E}`,J=i.detail==="message"&&n.body.message?`: ${D(N(n.body.message)).slice(0,300)}`:"",ee=`${B}${oe?` (request ${oe})`:""}${J}`,Z=I(T,i,` (${B})${J}.${T==="outcome_unknown"?" The request may or may not have taken effect; check before repeating it.":""}`,ee,T==="unavailable"||T==="quota"||T==="timeout");return _e.set(Z,{status:n.status,...E?{code:E.trim()}:void 0}),Z}case"network":{let T=w(n.error,N);if(b&&n.sent)return I(P??"outcome_unknown",i,": the connection failed after the request was sent, so it may or may not have taken effect. Check before repeating it.",T,!1);return I(P??"unavailable",i,`: ${n.sent?"the connection failed":"the service is unreachable"}.`,T,!0)}case"timeout":if(b&&n.sent)return I(P??"outcome_unknown",i,": no response before the deadline, so it may or may not have taken effect. Check before repeating it.",void 0,!1);return I(P??"timeout",i,": no response before the deadline.",void 0,!0);case"aborted":return I(P??"aborted",i,": the signal was cancelled.",void 0,!1);default:return n}}function ze(n){if(n.body===void 0)return{body:void 0,replayable:!0};if(n.method==="GET"||n.method==="HEAD")throw j(`A ${n.method} request cannot have a body`,n.sandboxId);if(st(n.body))return{body:n.body,replayable:!(n.body instanceof ReadableStream)};return{body:JSON.stringify(n.body),contentType:"application/json",replayable:!0}}async function Ee(n,i){let{name:l,plane:m}=ie(n.plane),{body:b,contentType:P,replayable:T}=ze(n),E=!Se.has(n.method),oe=T&&(!E||n.idempotencyKey!==void 0),{signal:B}=i,J={signal:B,...n.sandboxId===void 0?void 0:{sandboxId:n.sandboxId}},ee=o.fetch??((z,G)=>globalThis.fetch(z,G)),Z=`${l}\x00${n.sandboxId??""}`,X=!1,V=()=>i.parent?.aborted&&!i.timeout.aborted?{kind:"aborted"}:B.aborted?{kind:"timeout",sent:!1}:void 0,ae=async(z)=>{try{return Pe.decode(await Ne(z.body,Xe,()=>{return}))}catch{let G=V();if(G)throw F(G,n,l);return""}};for(let z=0;;z++){let G=V();if(G)throw F(G,n,l);let ge,de,{baseUrl:ye,auth:He}=m;try{ge=t(ye)?ye:await Re(Promise.resolve().then(()=>ye(J)),B),de=n.auth===!1||!He?{}:await Re(Promise.resolve().then(()=>He(J)),B)}catch(U){if(U instanceof e)throw U;let A=V();if(A)throw F(A,n,l);throw I("auth",n,`: resolving ${u} credentials failed.`,w(U,N),!1)}let $e=V();if($e)throw F($e,n,l);let we=M.get(l);if(!we)M.set(l,we=new Set);for(let[U,A]of Object.entries(de))we.add(U.toLowerCase()),q(A);let Ge=S.get(Z)?.generation??0,ue,le;try{le=new URL(ge)}catch{throw I("provider",n,`: the ${u} base URL is invalid.`,void 0,!1)}if(ue=le.origin,Object.keys(de).length>0&&le.protocol==="http:"&&!Ze(le.hostname))throw I("invalid_argument",n,`: the ${u} base URL uses plain HTTP, which would send credentials unencrypted. Use an https URL.`,void 0,!1);let te=Be(ge,n),ke=n.method,pe=b,R,Q;for(let U=0;;U++){let A=new Headers({...m.headers,...P&&pe!==void 0?{"content-type":P}:void 0});if(n.idempotencyKey!==void 0&&o.idempotencyHeader)A.set(o.idempotencyHeader,n.idempotencyKey);if(te.origin===ue)for(let[K,ne]of Object.entries(de))A.set(K,ne);for(let[K,ne]of Object.entries(n.headers??{}))A.set(K,ne);if(te.origin!==ue){for(let K of Array.from(A.keys()))if(L(l,K))A.delete(K)}for(let[K,ne]of A)if(L(l,K))q(ne);let ce={method:ke,headers:A,body:pe,signal:B,redirect:"manual"};if(pe instanceof ReadableStream)ce.duplex="half";try{R=await ee(te.href,ce)}catch(K){R=void 0;let ne=V();Q=ne?.kind==="timeout"?{kind:"timeout",sent:!0}:ne??{kind:"network",sent:!De(K).some((Ke)=>et.has(Ke)),error:K};break}let Ie=R.headers.get("location");if(!qe.has(R.status)||Ie===null)break;if(await R.body?.cancel().catch(()=>{}),U>=Ce)throw I("provider",n,`: more than ${Ce} redirects.`,void 0,!1);try{te=new URL(Ie,te)}catch{throw I("provider",n,": the redirect location is invalid.",void 0,!1)}if(te.protocol!=="https:"&&te.protocol!=="http:")throw I("provider",n,": the redirect left http and https.",void 0,!1);if(R.status===303||(R.status===301||R.status===302)&&ke==="POST")ke="GET",pe=void 0;else if(!T)throw I("provider",n,": the server redirected a streamed upload, which cannot be sent twice.",void 0,!1)}let Ae=R!==void 0&&m.refresh!==void 0&&!X&&T&&n.auth!==!1&&te.origin===ue,se;if(Ae&&m.stale&&R&&R.status>=400&&R.status!==401)se=ve(await ae(R));let Me=!Ae||!R?void 0:R.status===401?"refused":se!==void 0?m.stale?.({status:R.status,body:se,credentials:de},J):void 0;if(Me!==void 0&&m.refresh&&R){if(se===void 0)await R.body?.cancel().catch(()=>{});X=!0;let U=S.get(Z)??{generation:0};if(S.set(Z,U),U.generation===Ge){U.pending??=m.refresh(J).then(()=>{U.generation++}).finally(()=>{U.pending=void 0});try{await Re(U.pending,B)}catch(A){let ce=V();if(ce)throw F(ce,n,l);if(A instanceof e)throw A;throw I("auth",n,`: refreshing ${u} credentials failed.`,w(A,N),!1)}}if(Me==="refused"||oe){z--;continue}throw F({kind:"status",status:R.status,headers:R.headers,body:se??ve("")},n,l,!0)}let Oe;if(R&&R.status>=200&&R.status<300)return R;if(R){let U=se??ve(await ae(R));if(Q={kind:"status",status:R.status,headers:R.headers,body:U},Le.has(R.status)){let A=it(R.headers);Oe=A===void 0?void 0:A<=Qe?A:1/0}if(!Le.has(R.status))throw F(Q,n,l)}if(!Q)throw new e(`${u} request produced no response`,{code:"provider",provider:a});if(Q.kind==="aborted"||Q.kind==="timeout")throw F(Q,n,l);let xe=Oe??O*2**z*(0.5+Math.random()/2);if(!oe||z>=g||xe===1/0||xe>=i.remaining())throw F(Q,n,l);try{await y(xe,i,a)}catch{throw F(V()??Q,n,l)}}}async function be(n){let i=n.deadline??d(n.timeoutMs??p,n.signal),l=await Ee(n,i),m=n.maxBytes??Ye,b;try{b=await Ne(l.body,m,()=>I("unsupported",n,`: the response is larger than ${m} bytes.`,void 0,!1))}catch(P){if(P instanceof e)throw P;let{name:T}=ie(n.plane);if(i.parent?.aborted&&!i.timeout.aborted)throw F({kind:"aborted"},n,T);throw F(i.signal.aborted?{kind:"timeout",sent:!0}:{kind:"network",sent:!0,error:P},n,T)}return dt(l.status,l.headers,b,(P)=>I("provider",{...n,detail:"status"},` (HTTP ${l.status}): the response ${P}.`,void 0,!1))}async function Je(n){let i=n.deadline??(n.timeoutMs===void 0?d(2147483647,n.signal):d(n.timeoutMs,n.signal)),l=d(n.startupTimeoutMs??p),m=new AbortController,b=()=>m.abort(),P=AbortSignal.any([i.signal,l.signal]);P.addEventListener("abort",b,{once:!0});let T={signal:m.signal,timeout:i.timeout,parent:i.parent,remaining:()=>Math.min(i.remaining(),l.remaining())},E;try{E=await Ee(n,T)}finally{P.removeEventListener("abort",b)}if(!E.body||E.status===204||E.status===205)return E;i.signal.addEventListener("abort",b,{once:!0});let{name:oe}=ie(n.plane),B=E.body.getReader(),J,ee=!1,Z=()=>{clearTimeout(J),i.signal.removeEventListener("abort",b)},X=new ReadableStream({async pull(V){if(n.idleTimeoutMs!==void 0)J=setTimeout(()=>{ee=!0,B.cancel().catch(()=>{}),m.abort()},n.idleTimeoutMs);try{let{done:ae,value:z}=await B.read();if(clearTimeout(J),ee)throw Error("idle");if(ae){Z(),V.close();return}V.enqueue(z)}catch(ae){Z();let z=i.parent?.aborted&&!i.timeout.aborted?{kind:"aborted"}:ee||i.timeout.aborted?{kind:"timeout",sent:!0}:{kind:"network",sent:!0,error:ae},G=!Se.has(n.method)&&!n.readOnly;V.error(ee&&z.kind==="timeout"?I(G?"outcome_unknown":"timeout",n,`: no data for ${n.idleTimeoutMs} ms${G?", so its result is unconfirmed. Check before repeating it.":"."}`,void 0,!G):F(z,n,oe))}},async cancel(V){Z(),await B.cancel(V).catch(()=>{}),m.abort()}},{highWaterMark:0});return new Response(X,{status:E.status,statusText:E.statusText,headers:E.headers})}return{provider:a,label:u,redact:N,request:be,async json(n){return(await be(n)).json()},stream:Je,cleanup(n){let{signal:i,deadline:l,...m}=n;return be({...m,timeoutMs:Math.min(n.timeoutMs??Ue,Ue)})}}}function Te(o){return o instanceof Function||r(o)&&!Array.isArray(o)}function _(o,a,u){if(!Te(o))s(`${a} from ${u} is not an object. Install a supported version of ${u}`);return o}var ct=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE"]);function h(o){let{http:a,placeholder:u,sandboxId:p,sdk:g}=o,O=t(u)?[u]:u;function C(M,L,S={}){if(!t(M)||!ct.has(M))s(`Unsupported HTTP method ${String(M).slice(0,16)}`);if(!t(L))s("The path must be a string");let re=O.filter((j)=>L.includes(`{${j}}`)&&S.params?.[j]===void 0),ie=p===void 0||re.length===0?S.params:{...S.params,...Object.fromEntries(re.map((j)=>[j,p]))};return{method:M,path:L,plane:S.plane,sandboxId:p,params:ie,query:S.query,body:S.body,headers:S.headers,signal:S.signal,timeoutMs:S.timeoutMs,detail:"message"}}async function W(M){if(!g)throw new e(`${a.label} has no official SDK binding. Use native.request or native.fetch.`,{code:"unsupported",provider:a.provider,sandboxId:p});if(!(M instanceof Function))s(`Pass a function that imports the SDK: native.sdk(() => import("${g.package}"))`);let L;try{L=Y(await M())}catch(S){if(S instanceof Error&&(("code"in S)&&(S.code==="ERR_MODULE_NOT_FOUND"||S.code==="MODULE_NOT_FOUND")||/Cannot find (?:package|module)/.test(S.message)))throw new e(`${g.package} could not be imported. Install it next to @opencoredev/sandbox-sdk to use native.sdk().`,{code:"unavailable",provider:a.provider,sandboxId:p,hint:`npm i ${g.package}`,cause:w(S,a.redact)});throw new e(`Loading ${g.package} failed: ${w(S,a.redact)??"a non-Error value was thrown"}. Check the import passed to native.sdk().`,{code:"provider",provider:a.provider,sandboxId:p})}if(!Te(L)||Array.isArray(L))s(`native.sdk() needs the module object. Pass () => import("${g.package}")`);try{return await g.connect(L,p)}catch(S){if(S instanceof e)throw S;throw new e(`${g.package} failed in native.sdk(): ${w(S,a.redact)??"a non-Error value was thrown"}. Check the SDK version and the sandbox.`,{code:"provider",provider:a.provider,sandboxId:p,cause:w(S,a.redact)})}}return{sandboxId:p,async request(M,L,S){return await a.json(C(M,L,S))},fetch(M,L,S){return a.stream(C(M,L,S))},sdk:W}}function v(o,a,u,p){let g=o[a];if(!(g instanceof Function))s(`The module passed to native.sdk() has no ${a} export. Pass () => import("${p}")`);try{return _(Reflect.construct(g,u),a,p)}catch(O){if(O instanceof TypeError&&/constructor/i.test(O.message))s(`${a} from the module passed to native.sdk() is not a class. Pass () => import("${p}")`);throw O}}async function k(o,a,u,p){let g=Te(o)?o[a]:void 0;if(!(g instanceof Function))s(`The ${p} object has no ${a} method. Install a supported version of ${p}`);return await g.apply(o,u)}
2
+ export{d,y,H,x,_,h,v,k};
@@ -0,0 +1,68 @@
1
+ import{n}from"./chunk-2ts3evzh.js";import{t,o,r,e}from"./chunk-xgxfy2n8.js";var p=(s,...f)=>`python3 -c ${n(s)} ${f.map(n).join(" ")}`,b=`def stdin_file():
2
+ try: return os.fdopen(os.memfd_create('sandbox-sdk-stdin'),'w+b')
3
+ except (AttributeError,OSError):
4
+ import tempfile
5
+ return tempfile.TemporaryFile()
6
+ class Process:
7
+ # A missing cwd fails the command, not the supervisor: the shell reports it on stderr and exits 2.
8
+ def argv(self,v):
9
+ try: os.chdir(v['cwd']); return ['sh','-c',v['command']]
10
+ except OSError: return ['sh','-c','cd "$1" || exit 2','sh',v['cwd']]
11
+ def __init__(self,v,env,stdin,session=False):
12
+ if not all(hasattr(os,name) for name in ['posix_spawn','waitstatus_to_exitcode']):
13
+ self.legacy(v,env,stdin,session); return
14
+ directory=os.open('.',os.O_RDONLY)
15
+ r,w=os.pipe(); e,x=os.pipe()
16
+ try:
17
+ argv=self.argv(v)
18
+ error=FileNotFoundError(2,os.strerror(2),'sh')
19
+ signals=[getattr(signal,s) for s in ['SIGPIPE','SIGXFZ','SIGXFSZ'] if hasattr(signal,s)]
20
+ for path in os.get_exec_path(env):
21
+ try:
22
+ 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)
23
+ break
24
+ except (FileNotFoundError,NotADirectoryError): pass
25
+ except OSError as failure:
26
+ if failure.errno==38: raise NotImplementedError()
27
+ error=failure
28
+ else: raise error
29
+ except NotImplementedError:
30
+ os.close(r); os.close(e)
31
+ self.legacy(v,env,stdin,session); return
32
+ except BaseException:
33
+ os.close(r); os.close(e); raise
34
+ finally:
35
+ os.fchdir(directory); os.close(directory); os.close(w); os.close(x)
36
+ self.stdout=os.fdopen(r,'rb',buffering=0); self.stderr=os.fdopen(e,'rb',buffering=0)
37
+ self.code=None
38
+ def legacy(self,v,env,stdin,session):
39
+ import subprocess
40
+ directory=os.open('.',os.O_RDONLY)
41
+ try: self.child=subprocess.Popen(self.argv(v),env=env,stdin=stdin,stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=session)
42
+ finally: os.fchdir(directory); os.close(directory)
43
+ self.pid=self.child.pid; self.stdout=self.child.stdout; self.stderr=self.child.stderr
44
+ def poll(self):
45
+ if hasattr(self,'child'): return self.child.poll()
46
+ if self.code is None:
47
+ pid,status=os.waitpid(self.pid,os.WNOHANG)
48
+ if pid: self.code=os.waitstatus_to_exitcode(status)
49
+ return self.code
50
+ def wait(self):
51
+ if hasattr(self,'child'): return self.child.wait()
52
+ if self.code is None: self.code=os.waitstatus_to_exitcode(os.waitpid(self.pid,0)[1])
53
+ return self.code
54
+ `,u=(s,f,y="provider")=>new e(`${f}. Check the ${s.name} sandbox before retrying.`,{code:y,provider:s.name}),_=`import os,sys,json,stat
55
+ p=sys.argv[1]
56
+ def info(p):
57
+ s=os.lstat(p)
58
+ 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)
59
+ try: print(json.dumps([info(os.path.join(p,n)) for n in os.listdir(p)] if sys.argv[2]=='list' else info(p)))
60
+ except FileNotFoundError: print('SDK_FILE_NOT_FOUND')`,h="import os,sys; os.makedirs(os.path.dirname(sys.argv[1]),exist_ok=True)",w="import os,sys; os.makedirs(sys.argv[1],exist_ok=True)",g=`import os,sys,shutil
61
+ p=sys.argv[1]
62
+ try:
63
+ if os.path.isdir(p) and not os.path.islink(p):
64
+ if sys.argv[2]=='true': shutil.rmtree(p)
65
+ else: os.rmdir(p)
66
+ else: os.unlink(p)
67
+ except FileNotFoundError: print('SDK_FILE_NOT_FOUND')`;function L(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 F(s){return{path:s.path,type:s.type,size:s.size,modifiedAt:s.modifiedAt}}function R(s,f){let y=async(i,a,l)=>{let d=await s(i),c=await d.raw(p(_,a,l));if(c.trim()==="SDK_FILE_NOT_FOUND")throw u(d,"File does not exist","file_not_found");let m=JSON.parse(c);return{g:d,value:m}};return{writeCreatesParents:!0,readRange:(i,a,l)=>f(i,async()=>(await s(i)).read(a,l)),read:(i,a)=>f(i,async()=>(await s(i)).read(a)),write:(i,a,l,d)=>f(i,async()=>{let c=await s(i);try{await f(i,()=>c.upload(a,l,d?.mode))}catch(m){if(!(m instanceof e)||!["not_found","file_not_found"].includes(m.code))throw m;await c.raw(p(h,a)),await c.upload(a,l,d?.mode)}}),stat:(i,a)=>f(i,async()=>{let{g:l,value:d}=await y(i,a,"stat");if(!L(d))throw u(l,"Invalid file metadata");return F(d)}),list:(i,a)=>f(i,async()=>{let{g:l,value:d}=await y(i,a,"list");if(!Array.isArray(d))throw u(l,"Invalid directory listing");return d.map((c)=>{if(!L(c))throw u(l,"Invalid file metadata");return F(c)})}),mkdir:(i,a)=>f(i,async()=>{await(await s(i)).raw(p(w,a))}),remove:(i,a,l)=>f(i,async()=>{let d=await s(i);if((await d.raw(p(g,a,String(l.recursive)))).trim()==="SDK_FILE_NOT_FOUND")throw u(d,"File does not exist","file_not_found")})}}
68
+ export{p,b,L,F,R};
@@ -0,0 +1,4 @@
1
+ function t(n){return typeof n==="string"}function o(n){return typeof n==="number"}function I(n){return typeof n==="boolean"}function r(n){return typeof n==="object"&&n!==null}var f={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??f[d.code]??f.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 l=this.stack??"",p=l.indexOf(`
2
+ at `)>=0?l.slice(l.indexOf(`
3
+ at `)):"",h={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(h,d)}`}}function C(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,l)=>l.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(g(this.text(n.message)),{code:n.code,retryable:n.retryable,hint:g(this.text(n.hint)),provider:d,sandboxId:u,cause:n.cause===void 0?void 0:D(this.text(n.cause instanceof Error?n.cause.message:String(n.cause)))});let l=D(this.text(n instanceof Error?n.message:t(n)?n:"Non-Error value thrown"));return new e(`${l}. Provider request failed. Check the provider settings and retry.`,{code:"provider",hint:f.provider,provider:d,sandboxId:u,cause:w(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 g(n){for(let[d,u]of v)n=n.replace(d,u);return n}function D(n){return g(n).replace(/\p{Cc}+/gu," ").slice(0,1000)}function w(n,d=(l)=>l,u=0){if(!(n instanceof Error))return;let l=D(d(n.message?`${n.name}: ${n.message}`:n.name)),p=u<2?w(n.cause,d,u+1):void 0;return p===void 0?l:`${l}; caused by ${p}`}var b={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 l=!(d.known??d.code!=="provider")&&d.status===void 0?w(n,d.redact):void 0,p=[n instanceof Error?n.name:void 0,d.status].filter((h)=>h!==void 0).join(" ");return{detail:l,cause:l??(p||void 0)}}function se(n){return Object.assign(Error(JSON.stringify(n)),n)}function c(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??b[n]}function fe(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,I,r,e,C,S,D,w,i,se,c,a,fe,s};
@@ -0,0 +1,25 @@
1
+ import type { StartOptions } from "../processes.js";
2
+ /** The fields of spec.json the core reads back. */
3
+ export interface ProcessRecord {
4
+ command: string;
5
+ startedAt: number;
6
+ port: number | undefined;
7
+ }
8
+ /** What restart.json holds: the original command and its start options. */
9
+ export interface RestartRecord {
10
+ command: string | undefined;
11
+ options: StartOptions;
12
+ }
13
+ /** Where a lines() cursor resumes: a log offset plus each stream's unfinished line. */
14
+ export interface LinePosition {
15
+ offset: string | undefined;
16
+ pending: {
17
+ stdout: string;
18
+ stderr: string;
19
+ };
20
+ }
21
+ export declare function parseProcessRecord(text: string): ProcessRecord;
22
+ /** Fields of the wrong type are dropped, so a record from an older SDK still restarts. */
23
+ export declare function parseRestartRecord(text: string, name: string): RestartRecord;
24
+ /** A cursor is a bare log offset, or JSON that also carries each stream's partial line. */
25
+ export declare function parseLineCursor(after: string | undefined): LinePosition;
package/dist/errors.d.ts CHANGED
@@ -47,6 +47,10 @@ export declare class SandboxError extends Error {
47
47
  readonly sandboxId?: string;
48
48
  constructor(message: string, options: ErrorOptions);
49
49
  }
50
+ /** @internal Whether an error says the path or the sandbox does not exist. */
51
+ export declare function isNotFound(error: unknown): error is SandboxError & {
52
+ code: "file_not_found" | "not_found";
53
+ };
50
54
  /** @internal Redacts registered secrets from text and errors. */
51
55
  export declare class Redactor {
52
56
  private values;
@@ -54,7 +58,69 @@ export declare class Redactor {
54
58
  text(value: string): string;
55
59
  get secrets(): string[];
56
60
  get maxLength(): number;
57
- error(error: unknown, provider: string, sandboxId?: string): SandboxError;
61
+ /** Map any thrown value to a scrubbed SandboxError. */
62
+ error(cause: unknown, provider: string, sandboxId?: string): SandboxError;
58
63
  }
64
+ /** @internal Removes credential-shaped text (URLs, auth headers, key=value secrets, control characters) and bounds the length. */
65
+ export declare function scrub(text: string): string;
66
+ /**
67
+ * @internal `Name: message` of a native failure, redacted, scrubbed and bounded, with up to two nested causes.
68
+ * Undefined for thrown values that are not Errors, which carry no message to keep.
69
+ */
70
+ export declare function nativeDetail(cause: unknown, redact?: (text: string) => string, depth?: number): string | undefined;
71
+ /** @internal What {@link describeNative} keeps: text for the message, and the error's cause. */
72
+ export interface NativeDescription {
73
+ detail?: string;
74
+ cause?: string;
75
+ }
76
+ /**
77
+ * @internal What an adapter keeps from a native failure. Only a failure the adapter did not recognize
78
+ * (`code` is `provider`, unless `known` says otherwise) and that carries no `status` keeps its text:
79
+ * that is an SDK bug or a network error, and the text is the only clue. A recognized error type or a response may carry server text that
80
+ * echoes the request, so it keeps only its name and status. `detail` is the kept text, for the message;
81
+ * `cause` is the detail, or else the name and status.
82
+ */
83
+ export declare function describeNative(cause: unknown, options: {
84
+ code: ErrorCode;
85
+ known?: boolean;
86
+ status?: string;
87
+ redact?: (text: string) => string;
88
+ }): NativeDescription;
89
+ /**
90
+ * @internal Bounded machine fields an adapter copies from a native failure, each already checked
91
+ * against an allowlist and the secrets it knows. Never a response's message, body, headers or URL;
92
+ * `native` is at most the scrubbed text {@link describeNative} keeps.
93
+ */
94
+ export interface NativeEvidence {
95
+ operation?: string;
96
+ status?: number;
97
+ providerCode?: string | number;
98
+ requestId?: string;
99
+ source?: string;
100
+ nativeName?: string;
101
+ native?: string;
102
+ /** Tenki create: the session this call created, and how far it got. */
103
+ admittedByThisCall?: true;
104
+ stage?: string;
105
+ sandboxId?: string;
106
+ state?: string;
107
+ cleanupCode?: ErrorCode;
108
+ }
109
+ /**
110
+ * @internal The one form an adapter passes {@link NativeEvidence} to the core in: the `cause` of its
111
+ * SandboxError, an Error whose message is the fields as JSON. {@link Redactor.error} reduces every
112
+ * cause to its message, so the JSON is what reaches users; the fields stay readable on the adapter's
113
+ * own error.
114
+ */
115
+ export declare function evidenceCause(evidence: NativeEvidence): Error & NativeEvidence;
116
+ /** @internal A redact function for values an adapter knows, such as its API key. Empty values are skipped. */
117
+ export declare function redacting(values: Iterable<string | undefined>): (text: string) => string;
118
+ /** @internal Why an adapter request failed, as a clause, never the code itself: the kept detail, or what `code` means. */
119
+ export declare function reason(code: ErrorCode, detail?: string): string;
120
+ /**
121
+ * @internal The shared HTTP status mapper. Provider hooks refine it (a 404 for a missing file, a stale route).
122
+ * A 504 is a timeout; the HTTP client turns it into `outcome_unknown` for a request that may have had an effect.
123
+ */
124
+ export declare function statusCode(status: number): ErrorCode;
59
125
  /** @internal Throws an `invalid_argument` SandboxError. */
60
126
  export declare function invalid(message: string): never;
package/dist/files.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Provider, FileInfo } from "./provider.js";
1
+ import type { Provider, FileInfo, WriteOptions } from "./provider.js";
2
2
  import { SandboxError, type Redactor } from "./errors.js";
3
3
  export interface FileEvent {
4
4
  type: "added" | "modified" | "removed";
@@ -15,8 +15,8 @@ export interface Files {
15
15
  read(path: string, options: {
16
16
  as: "bytes";
17
17
  }): Promise<Uint8Array>;
18
- write(path: string, data: string | Uint8Array): Promise<void>;
19
- write(files: Record<string, string | Uint8Array>): Promise<void>;
18
+ write(path: string, data: string | Uint8Array, options?: WriteOptions): Promise<void>;
19
+ write(files: Record<string, string | Uint8Array>, options?: WriteOptions): Promise<void>;
20
20
  edit(path: string, edit: {
21
21
  find: string;
22
22
  replace: string;
@@ -53,5 +53,12 @@ export interface Files {
53
53
  since?: string;
54
54
  }): Promise<FileDiff>;
55
55
  }
56
+ /** @internal Remove a file; one that is already gone is not an error. Some adapters report
57
+ * a missing path as a generic provider error, so a stat confirms that case. */
58
+ export declare function removeIfPresent(files: Pick<Files, "remove" | "exists">, path: string): Promise<void>;
56
59
  export declare function globMatch(path: string, glob: string): boolean;
57
- export declare function makeFiles(provider: Provider, id: string, redactor: Redactor, guard?: () => void): Files & Disposable;
60
+ /** @internal Read at most `maxBytes + 1` bytes when the adapter has ranged reads, so a caller can
61
+ * refuse an oversized file without downloading all of it. Without them, read the whole file. */
62
+ export declare function readAtMost(files: Files, path: string, maxBytes: number): Promise<Uint8Array<ArrayBufferLike>>;
63
+ /** `guard` throws synchronously when the handle is closed; `ready` resolves once the handle may touch the sandbox (secret recovery). */
64
+ export declare function makeFiles(provider: Provider, id: string, redactor: Redactor, guard?: () => void, ready?: () => Promise<void>): Files & Disposable;
package/dist/git.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { RunHandle, RunOptions, RunResult } from "./types.js";
2
- import type { Files } from "./files.js";
2
+ import { type Files } from "./files.js";
3
3
  import type { Redactor } from "./errors.js";
4
4
  export interface Git {
5
5
  clone(url: string, options?: {
package/dist/http.d.ts ADDED
@@ -0,0 +1,225 @@
1
+ /**
2
+ * The HTTP client converted adapters and `box.native` share. One client per provider instance.
3
+ *
4
+ * - Planes: each provider API surface (control plane, Daytona's toolbox, Superserve's data plane) has a base
5
+ * URL, possibly per sandbox, and its own credentials. Credentials attach only to that plane's origin; an
6
+ * absolute URL or redirect elsewhere (signed upload URLs, poll URLs) gets none. That holds for credential
7
+ * headers a caller passes too (`authorization`, `cookie`, `*-token`, `*-key`, the plane's own auth headers).
8
+ * - Retries: at most `retries` more attempts on 429, 502, 503, 504 and network errors, only for GET, HEAD, PUT
9
+ * and DELETE, or a POST/PATCH that carries a server-supported idempotency key. Never with a streamed body.
10
+ * `Retry-After` is honoured up to 20 s and never past the deadline.
11
+ * - Outcomes: a POST or PATCH that fails after it may have reached the server (a network error once sent, a
12
+ * timeout, a 504) is `outcome_unknown`, not `unavailable`: the caller must check before repeating it.
13
+ * - Deadlines: `timeoutMs` (or a shared {@link Deadline}) covers credentials, every attempt, backoff and the
14
+ * body. Streams have a startup timeout (until headers) and an idle timeout (between chunks) instead.
15
+ * - Redaction: credential header values (the adapter's and the caller's, with and without a `Bearer` scheme),
16
+ * `secrets()` and credential-shaped text never reach a SandboxError.
17
+ * Response text is kept only for native calls (`detail: "message"`), scrubbed; adapter calls keep the
18
+ * status and the provider's error code.
19
+ */
20
+ import { type JsonValue } from "./shared/json.js";
21
+ import { type ErrorCode } from "./errors.js";
22
+ import type { HttpMethod } from "./native.js";
23
+ /** Blocks inference from a position, like TypeScript 5.4's `NoInfer`, for consumers on older compilers. */
24
+ type NoInfer<T> = [T][T extends unknown ? 0 : never];
25
+ /** The subset of `fetch` the client calls. `globalThis.fetch` and test doubles both fit. */
26
+ export type Fetch = (input: string, init: RequestInit) => Promise<Response>;
27
+ /** What a plane's base URL and credential callbacks get. One call passes the same object to every callback. */
28
+ export interface PlaneContext {
29
+ /** The sandbox the request is for, when there is one. */
30
+ sandboxId?: string;
31
+ /** Fires when the request's deadline or the caller's signal does. */
32
+ signal: AbortSignal;
33
+ }
34
+ /** One API surface of a provider. */
35
+ export interface HttpPlane {
36
+ /**
37
+ * The base URL, including any path prefix (`https://app.daytona.io/api`). Paths are appended to it. A
38
+ * function can resolve it per sandbox, such as a regional proxy; cache inside it.
39
+ */
40
+ baseUrl: string | ((context: PlaneContext) => string | Promise<string>);
41
+ /** Credential headers, read once per attempt so rotated tokens apply. Sent only to the base URL's origin. */
42
+ auth?: (context: PlaneContext) => Record<string, string> | Promise<Record<string, string>>;
43
+ /**
44
+ * Refresh the credentials `auth` returns. Called once after a 401 from this plane, shared between
45
+ * concurrent requests, and the request is sent again with fresh credentials. `context` is the first
46
+ * waiter's; a waiter whose signal fires stops waiting, so do not abort the shared work on `context.signal`.
47
+ */
48
+ refresh?: (context: PlaneContext) => Promise<void>;
49
+ /**
50
+ * Which failed responses besides a 401 mean stale credentials or a stale route, such as a 404 whose error
51
+ * code says the route moved. Either verdict refreshes once. `"refused"` resends any request, like a 401;
52
+ * `"unsure"` resends only a request that may be retried, and an unconfirmed write is `outcome_unknown`.
53
+ * `credentials` are the headers `auth` returned for that attempt. Default: only a 401.
54
+ */
55
+ stale?: (failure: {
56
+ status: number;
57
+ body: ErrorBody;
58
+ credentials: Readonly<Record<string, string>>;
59
+ }, context: PlaneContext) => StaleVerdict | undefined;
60
+ /** Headers for every request to this plane that are not credentials (`Accept`, API version pins). */
61
+ headers?: Record<string, string>;
62
+ }
63
+ /**
64
+ * Why a response means stale credentials or a stale route. `"refused"`: the server turned the request away
65
+ * before running anything (a moved route, a stopped sandbox), so any request may be sent again. `"unsure"`:
66
+ * the request may have run before the failure.
67
+ */
68
+ export type StaleVerdict = "refused" | "unsure";
69
+ /** What a provider error hook sees. `body` is bounded to 64 KB and must never be copied into messages. */
70
+ export type HttpFailure = {
71
+ kind: "status";
72
+ status: number;
73
+ headers: Headers;
74
+ body: ErrorBody;
75
+ } | {
76
+ kind: "network";
77
+ sent: boolean;
78
+ error: unknown;
79
+ } | {
80
+ kind: "timeout";
81
+ sent: boolean;
82
+ } | {
83
+ kind: "aborted";
84
+ };
85
+ /** A non-2xx response's body, as far as the client parsed it. */
86
+ export interface ErrorBody {
87
+ /** The first 64 KB of the body, decoded as UTF-8. */
88
+ text: string;
89
+ /** `text` parsed as JSON, or `undefined` when it is not JSON. */
90
+ json: JsonValue | undefined;
91
+ /** The provider's error code (`sandbox_not_found`), from `code`, `error.code`, `error` or `type`. */
92
+ code?: string;
93
+ /** The provider's error message, from `message`, `error.message`, `error`, `detail` or `title`. */
94
+ message?: string;
95
+ }
96
+ /** The request a hook classifies. */
97
+ export interface FailedRequest {
98
+ method: HttpMethod;
99
+ plane: string;
100
+ /** `METHOD /path/{template}`, without query strings or filled values. */
101
+ operation: string;
102
+ sandboxId?: string;
103
+ }
104
+ export interface HttpClientOptions<Plane extends string> {
105
+ /** Provider name on errors: `"daytona"`. */
106
+ provider: string;
107
+ /** Display name in messages: `"Daytona"`. */
108
+ label: string;
109
+ planes: Record<Plane, HttpPlane>;
110
+ /** The plane a request without `plane` uses. Plane names are inferred from `planes` only. */
111
+ defaultPlane: NoInfer<Plane>;
112
+ /** Default: `globalThis.fetch`, looked up per request so test stubs apply. */
113
+ fetch?: Fetch;
114
+ /** Default overall deadline per call, in ms. Default: 60000. */
115
+ timeoutMs?: number;
116
+ /** Extra attempts for retryable failures. Default: 2. */
117
+ retries?: number;
118
+ /** First backoff, doubled per attempt with jitter. Default: 250. */
119
+ backoffMs?: number;
120
+ /** Values to redact besides the credential headers, read on each error (API keys, tokens). */
121
+ secrets?: () => Iterable<string | undefined>;
122
+ /** Header that carries `idempotencyKey`. Leave it out when the key travels in the body. */
123
+ idempotencyHeader?: string;
124
+ /** Next step for `auth` errors: `"Set DAYTONA_API_KEY to a valid Daytona API key."` */
125
+ authHint?: string;
126
+ /**
127
+ * Refine the shared status mapping, such as a 404 for a missing file (`file_not_found`) or a stale route.
128
+ * Return `undefined` to keep the default. Never put `failure.body` text in errors.
129
+ */
130
+ mapError?: (failure: HttpFailure, request: FailedRequest) => ErrorCode | undefined;
131
+ /**
132
+ * Build the error's `cause` instead of the default `HTTP <status> (request <id>)` text, such as an Error with
133
+ * machine-readable evidence fields. Return `undefined` to keep the default. It is not redacted: copy only
134
+ * bounded, validated values, never `failure.body` text.
135
+ */
136
+ cause?: (failure: HttpFailure, request: FailedRequest) => Error | undefined;
137
+ }
138
+ /** One request. */
139
+ export interface HttpRequest<Plane extends string = string> {
140
+ method: HttpMethod;
141
+ /** A path under the plane's base URL, with `{name}` placeholders, or an absolute `https:` URL. */
142
+ path: string;
143
+ plane?: Plane;
144
+ /** The sandbox this is for: passed to plane callbacks and put on errors. */
145
+ sandboxId?: string;
146
+ /** Values for every `{name}` placeholder in `path`, URI-encoded. Missing or unused names are `invalid_argument`. */
147
+ params?: Readonly<Record<string, string | number>>;
148
+ query?: Readonly<Record<string, string | number | boolean | undefined>>;
149
+ /** Sent as is when it is a `BodyInit` (string, bytes, Blob, FormData, URLSearchParams, ReadableStream), else as JSON. */
150
+ body?: unknown;
151
+ headers?: Readonly<Record<string, string>>;
152
+ signal?: AbortSignal;
153
+ /** Overall deadline for this call. Ignored when `deadline` is given. Default: the client's `timeoutMs`. */
154
+ timeoutMs?: number;
155
+ /** A deadline shared with other calls of the same operation (create then poll). */
156
+ deadline?: Deadline;
157
+ /** A server-supported idempotency key. It makes a POST or PATCH retryable; with `idempotencyHeader`, the client sends it. */
158
+ idempotencyKey?: string;
159
+ /** A POST or PATCH that changes nothing (a search). Failures after sending map like a GET's, not `outcome_unknown`. Still not retried. */
160
+ readOnly?: boolean;
161
+ /** `false` sends no credentials, even to the plane's origin (signed URLs). */
162
+ auth?: false;
163
+ /** Largest buffered response body in bytes. Default: 32 MiB. */
164
+ maxBytes?: number;
165
+ /** `"message"` keeps the provider's scrubbed error message in the error (native calls). Default: `"status"`. */
166
+ detail?: "status" | "message";
167
+ }
168
+ /** A stream request: the overall deadline is off unless `timeoutMs` or `deadline` is set. */
169
+ export interface StreamRequest<Plane extends string = string> extends HttpRequest<Plane> {
170
+ /** Time until response headers. Default: the client's `timeoutMs`. */
171
+ startupTimeoutMs?: number;
172
+ /** Longest gap between body chunks. Default: none. */
173
+ idleTimeoutMs?: number;
174
+ }
175
+ /** A buffered response. */
176
+ export interface HttpResponse {
177
+ readonly status: number;
178
+ readonly headers: Headers;
179
+ readonly body: Uint8Array;
180
+ /** The body as UTF-8 text. */
181
+ text(): string;
182
+ /** The body parsed as JSON, or `undefined` when it is empty. Invalid JSON is a `provider` SandboxError. */
183
+ json(): JsonValue | undefined;
184
+ }
185
+ export interface HttpClient<Plane extends string = string> {
186
+ readonly provider: string;
187
+ readonly label: string;
188
+ /** Redacts credentials seen so far, `secrets()` and credential-shaped text. */
189
+ readonly redact: (text: string) => string;
190
+ /** Send a request and buffer the response body (bounded by `maxBytes`). Non-2xx rejects. */
191
+ request(request: HttpRequest<Plane>): Promise<HttpResponse>;
192
+ /** `request(...).json()`. */
193
+ json(request: HttpRequest<Plane>): Promise<JsonValue | undefined>;
194
+ /** Send a request and return once headers arrive. The body enforces the idle timeout and deadline; the caller reads or cancels it. */
195
+ stream(request: StreamRequest<Plane>): Promise<Response>;
196
+ /** A best-effort request after an abort: no caller signal, its own deadline of at most 10 s. */
197
+ cleanup(request: HttpRequest<Plane>): Promise<HttpResponse>;
198
+ }
199
+ /** A deadline several calls share. */
200
+ export interface Deadline {
201
+ /** Fires on the timeout or the caller's signal. */
202
+ readonly signal: AbortSignal;
203
+ /** Fires only on the timeout. */
204
+ readonly timeout: AbortSignal;
205
+ /** The caller's signal, if any. */
206
+ readonly parent?: AbortSignal;
207
+ /** Milliseconds left, never negative. */
208
+ remaining(): number;
209
+ }
210
+ export declare function createDeadline(timeoutMs: number, parent?: AbortSignal): Deadline;
211
+ /** Waits `ms`, rejecting with a `timeout` or `aborted` SandboxError when `deadline` fires first. For polling loops. */
212
+ export declare function sleep(ms: number, deadline: Deadline, provider: string): Promise<void>;
213
+ /**
214
+ * The HTTP status and provider error code (when it is a safe token) behind a client error, or `undefined`
215
+ * for errors that are not a non-2xx response. For adapters that branch on a status, such as a 409 retry.
216
+ */
217
+ export declare function httpStatus(cause: unknown): {
218
+ status: number;
219
+ code?: string;
220
+ } | undefined;
221
+ /** Pulls the code and message out of the error shapes providers use: `{ code, message }`, `{ error: { code, message } }`, `{ error: "text" }`, RFC 7807. */
222
+ export declare function parseErrorBody(text: string): ErrorBody;
223
+ /** Builds the client. Planes are fixed; their base URLs and credentials are read per request. */
224
+ export declare function createHttpClient<Plane extends string>(options: HttpClientOptions<Plane>): HttpClient<Plane>;
225
+ export {};
package/dist/index.d.ts CHANGED
@@ -2,7 +2,9 @@ import type { Provider, Capability, SandboxInfo } from "./provider.js";
2
2
  import type { ConnectOptions, CreateOptions, ListOptions, MethodsFor, ProviderSandbox, ReapOptions, SandboxBase } from "./types.js";
3
3
  export { SandboxError } from "./errors.js";
4
4
  export type { ErrorCode, ErrorOptions } from "./errors.js";
5
- export type { Sandbox, SandboxBase, ProviderSandbox, CreateOptions, ConnectOptions, ListOptions, ReapOptions, PreviewOptions, Usage, Locator, RunOptions, RunHandle, RunResult, OutputChunk, Capability, CapabilityMethods, MethodsFor, SandboxInfo, FileInfo, Labels, Preview, Terminal } from "./types.js";
5
+ export type { Sandbox, SandboxBase, ProviderSandbox, CreateOptions, ConnectOptions, ListOptions, ReapOptions, PreviewOptions, Usage, Locator, RunOptions, RunHandle, RunResult, OutputChunk, Capability, CapabilityMethods, MethodsFor, SandboxInfo, FileInfo, Labels, Preview, Terminal, } from "./types.js";
6
+ export type { WriteOptions, SnapshotOptions } from "./provider.js";
7
+ export type { NativeApi, NativeRequestOptions, HttpMethod } from "./native.js";
6
8
  export type { Files, FileDiff, FileEvent } from "./files.js";
7
9
  export type { ProcessHandle, ProcessInfo, StartOptions, Readiness } from "./processes.js";
8
10
  export type { Git } from "./git.js";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{T,p,g,S,E}from"./chunk-59t3rqja.js";import{e}from"./chunk-gc8zdxyb.js";export{e as SandboxError,g as connectSandbox,p as createSandbox,T as hasCapability,S as listSandboxes,E as reapSandboxes};
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};