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

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 +48 -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-ch71kvcp.js +2 -0
  12. package/dist/chunk-ckym4cht.js +23 -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-x2skgx3m.js +5 -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,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,5 @@
1
+ import{l}from"./chunk-23tjmd39.js";import{z,ie}from"./chunk-83avbjns.js";import{m}from"./chunk-bd481sb7.js";import{d,y,x,h,v,k}from"./chunk-ch71kvcp.js";import{f}from"./chunk-9w9rddra.js";import{t,o,r,e,i,c,a}from"./chunk-xgxfy2n8.js";import{deflateRawSync as qe,inflateRawSync as Ue}from"node:zlib";import{posix as ze}from"node:path";var Pe=/^[a-z][a-z0-9_]{0,63}$/;function B(n="boat",s="Boat",p="BOAT_API_KEY",I=!1){function w(P,U){if(P instanceof e)return P;let M=m(P),C=M.responseStatus,j="provider";if(C===401||C===403)j="auth";else if(C===404)j="not_found";else if(C===402||C===429)j="quota";else if(C===400)j="invalid_argument";else if(C===408||M.name==="TimeoutError")j="timeout";else if(C!==void 0&&C>=500)j="unavailable";else if(M.name==="AbortError")j="aborted";let T=j==="auth"?`Set ${p} to a valid ${s} API key.`:`Check the sandbox and ${s} service before retrying.`,W=M.apiCode!==void 0&&Pe.test(M.apiCode)?` ${M.apiCode}`:"",Y=I&&C!==void 0?` (HTTP ${C}${W})`:"",J=i(P,{code:j,status:C===void 0?void 0:`HTTP ${C}${W}`,redact:c([process.env[p]])});return new e(`${s} request failed${Y}: ${a(j,J.detail)}. ${T}`,{code:j,provider:n,sandboxId:U,hint:T,retryable:j==="unavailable"||j==="quota",cause:J.cause})}function A(P,U="provider",M){let C=P.replaceAll("Boat",s);return new e(U==="auth"?C:`${C}. Check the ${s} provider configuration and retry.`,{code:U,provider:n,sandboxId:M})}return{boatError:w,failure:A}}var Te={idleMs:60000,retryWindowMs:60000,retryDelayMs:1000},fe=(n,s)=>{let p=n[s];return o(p)&&Number.isSafeInteger(p)&&p>=0?p:void 0};function Ee(n,s){if(!f(n)||!t(n.type))throw s("a frame has no type");switch(n.type){case"stdout":case"stderr":{if(!("data"in n)||!t(n.data))throw s("an output frame has no data");let p=fe(n,"nextOffset");return{type:n.type,data:n.data,...p===void 0?void 0:{nextOffset:p}}}case"attached":case"heartbeat":case"reconnect":{let p=fe(n,"stdoutOffset"),I=fe(n,"stderrOffset");return{type:n.type,...p===void 0?void 0:{stdoutOffset:p},...I===void 0?void 0:{stderrOffset:I}}}case"exit":{let p="exitCode"in n?n.exitCode:void 0;if(p!==null&&!o(p))throw s("the exit frame has no exit code","outcome_unknown");return{type:"exit",exitCode:p,timedOut:"timedOut"in n&&n.timedOut===!0}}case"error":return{type:"error"};default:return{type:"other"}}}function Ne(n){let s=z(n);if(s)return s==="disconnected"||s==="truncated";return n instanceof e&&(n.code==="unavailable"||n.code==="timeout")}async function*ge(n,s,p,I){let{signal:w}=I,A=I.timing??Te,P=n.label,U=()=>new e(`${P} command stream aborted. The signal was cancelled.`,{code:"aborted",provider:n.provider,sandboxId:s}),M=(W,Y="provider")=>new e(`${P} command stream is invalid: ${W}. Check the ${P} service and retry.`,{code:Y,provider:n.provider,sandboxId:s}),C={stdout:0,stderr:0},j=!1,T;for(;;){if(w.aborted)throw U();try{let W=await n.stream({method:"GET",path:"/sandboxes/{sandboxId}/commands/{processId}/stream",params:{sandboxId:s,processId:p},sandboxId:s,query:{stdoutOffset:C.stdout,stderrOffset:C.stderr},signal:w,startupTimeoutMs:A.idleMs,idleTimeoutMs:A.idleMs});if(j=!0,!W.body)throw new e(`${P} command stream has no body. The connection will be retried.`,{code:"unavailable",provider:n.provider,sandboxId:s,retryable:!0});let Y=!1;for await(let J of ie(W.body,{provider:n.provider,sandboxId:s,signal:w})){T=void 0;let F=Ee(J,M);switch(F.type){case"stdout":case"stderr":if(F.nextOffset!==void 0){if(F.nextOffset<=C[F.type])break;C[F.type]=F.nextOffset}if(F.data)yield{type:F.type,data:F.data};break;case"exit":case"error":yield F;return;case"attached":C.stdout=F.stdoutOffset??C.stdout,C.stderr=F.stderrOffset??C.stderr;break;case"heartbeat":case"reconnect":C.stdout=Math.max(C.stdout,F.stdoutOffset??0),C.stderr=Math.max(C.stderr,F.stderrOffset??0),Y=F.type==="reconnect";break;case"other":break;default:return F}if(Y)break}if(Y)continue;throw new e(`${P} command stream ended before the command did. The connection will be retried.`,{code:"unavailable",provider:n.provider,sandboxId:s,retryable:!0})}catch(W){if(w.aborted)throw U();if(T??=Date.now(),!j||!Ne(W)||Date.now()-T>=A.retryWindowMs)throw W;try{await y(A.retryDelayMs,d(A.retryWindowMs,w),n.provider)}catch{throw U()}}}}function me(n){return x({provider:n.provider,label:n.label,defaultPlane:"api",planes:{api:{baseUrl:n.baseUrl,auth:()=>({authorization:`Bearer ${n.credentials()}`})}},timeoutMs:n.timeoutMs,secrets:n.secrets,idempotencyHeader:"Idempotency-Key",authHint:`Set ${n.keyEnv} to a valid ${n.label} API key.`,...n.retries===void 0?void 0:{retries:n.retries},...n.fetch===void 0?void 0:{fetch:n.fetch}})}function ke(n,s,p,I){return new e(`${s} returned an invalid ${p}. Check the ${s} provider configuration and retry.`,{code:"provider",provider:n,sandboxId:I})}function Se(n,s,p){if(!r(n)||n===null||!("id"in n)||!t(n.id)||!n.id)throw ke(s,p,"sandbox");let I="name"in n&&t(n.name)?n.name:"",w="state"in n&&t(n.state)?n.state:"",A="createdAt"in n&&(t(n.createdAt)||o(n.createdAt))?new Date(n.createdAt).getTime():Number.NaN;return{id:n.id,name:I,state:w,createdAt:A,raw:n}}function ve(n,s,p){return Se(r(n)&&"sandbox"in n?n.sandbox:void 0,s,p)}function $e(n,s,p){if(!r(n)||n===null||!("sandboxes"in n)||!Array.isArray(n.sandboxes))throw ke(s,p,"sandbox list");let I=n.sandboxes.map((M)=>Se(M,s,p)),w="pageInfo"in n?n.pageInfo:void 0,A=r(w)&&"hasMore"in w&&w.hasMore===!0,P=r(w)&&w!==null&&"nextCursor"in w&&t(w.nextCursor)?w.nextCursor:void 0,U={sandboxes:I,hasMore:A};if(P!==void 0)U.nextCursor=P;return U}function je(n){if(!r(n)||n===null)return{kind:"unknown"};if("stdout"in n&&t(n.stdout)&&"stderr"in n&&t(n.stderr)&&"exitCode"in n&&(n.exitCode===null||o(n.exitCode))){let s="stdoutTruncated"in n&&n.stdoutTruncated===!0||"stderrTruncated"in n&&n.stderrTruncated===!0;return{kind:"finished",stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,truncated:s}}if("processId"in n&&o(n.processId))return{kind:"started",processId:n.processId};return{kind:"unknown"}}async function te(n,s,p,I=!1){let w={method:"POST",path:"/sandboxes/{sandboxId}/commands",params:{sandboxId:s},sandboxId:s,body:p};return je((await(I?n.cleanup(w):n.request(w))).json())}async function se(n,s,p){await n.request({method:"PUT",path:"/sandboxes/{sandboxId}/files",params:{sandboxId:s},sandboxId:s,body:p})}async function Ie(n,s,p){let I=await n.json({method:"DELETE",path:"/sandboxes/{sandboxId}/commands/{processId}",params:{sandboxId:s,processId:p},sandboxId:s});return r(I)&&"running"in I?I.running:void 0}var le=`flock -x /tmp/.sandbox-sdk-workspace-ready.lock sh -c 'if [ ! -f /tmp/.sandbox-sdk/prepared-workspace ]; then sudo mkdir -p /workspace && sudo chown "$(id -u):$(id -g)" /workspace && command -v node git tar setsid nohup mkfifo sed base64 >/dev/null && mkdir -p /tmp/.sandbox-sdk && touch /tmp/.sandbox-sdk/prepared-workspace || exit 1; fi' || exit 1`,E=(n)=>`'${n.replaceAll("'","'\\''")}'`,de=4194304;async function pe(n,s,p,I,w){let A=Array.from({length:Math.max(1,Math.ceil(I.length/de))},(U,M)=>`${p}/part-${M}`),P=await te(n,s,{command:`mkdir -p /tmp/.sandbox-sdk && mkdir -m 700 -- ${E(p)} && (umask 077 && touch -- ${A.map(E).join(" ")})`,timeoutSeconds:60});if(P.kind!=="finished"||P.exitCode!==0)throw w("Boat could not prepare private staging","provider",s);for(let[U,M]of A.entries())await se(n,s,{path:M,content:Buffer.from(I.subarray(U*de,(U+1)*de)).toString("base64"),encoding:"base64"});return A}async function Be(n,s,p,I={},w=new Map,A=B(),P={}){let{boatError:U,failure:M}=A;if(p.signal?.aborted)return{exitCode:null,timedOut:!0};let C=new AbortController,j=!1,T=()=>{},W=new Promise((b)=>{T=()=>{j=!0,b("cancelled")}}),Y=setTimeout(T,p.timeoutMs);p.signal?.addEventListener("abort",T,{once:!0});let J,F=!1,X=!1,Z,ae=!1,Q,u=`/tmp/.sandbox-sdk-setup-${crypto.randomUUID()}`;async function g(){if(J===void 0)return;try{if(await Ie(n,s,J)!==!1)throw M("Boat did not confirm process-tree cancellation","outcome_unknown",s)}catch{throw M("Remote cancellation could not be confirmed; destroy the sandbox before retrying","outcome_unknown",s)}}try{let b=Object.entries(p.env).filter(([O,R])=>!Object.entries(l).some(([re,ce])=>O===re&&R===ce)&&I[O]!==R),S=Object.entries(l).filter(([O,R])=>p.env[O]===R).map(([O,R])=>`export ${E(`${O}=${R}`)}`).join("; ");if(S)S+="; ";let N="/tmp/.sandbox-sdk/changes.git/sdk.index",D=b.filter(([O,R])=>O==="GIT_INDEX_FILE"&&R===N);b=b.filter(([O,R])=>O!=="GIT_INDEX_FILE"||R!==N);for(let[O,R]of D)S+=`export ${E(`${O}=${R}`)}; `;if(b.length){let O=JSON.stringify(b),R=p.envMode==="sandbox"?w.get(O):void 0;if(R)S+=`. ${E(await R)} || exit 1; `;else{Q=`/tmp/.sandbox-sdk/env-${crypto.randomUUID()}`;let re=`${Q}/env`,ce=Q,he=(async()=>{let we=await te(n,s,{command:`node -e ${E("const f=require('fs');f.mkdirSync('/tmp/.sandbox-sdk',{recursive:true});f.mkdirSync(process.argv[1],{mode:0o700});f.writeFileSync(process.argv[1]+'/env','',{flag:'wx',mode:0o600})")} ${E(ce)}`,timeoutSeconds:60});if(we.kind!=="finished"||we.exitCode!==0)throw M("Boat could not prepare command environment","provider",s);return await se(n,s,{path:re,content:b.map(([Me,Ae])=>`export ${E(`${Me}=${Ae}`)}`).join(`
2
+ `)+`
3
+ `,encoding:"utf8"}),re})();if(p.envMode==="sandbox")w.set(O,he);try{await he}catch(xe){if(p.envMode==="sandbox")w.delete(O);throw xe}if(p.envMode==="sandbox")Q=void 0,S+=`. ${E(re)} || exit 1; `;else S+=`chmod 600 ${E(re)} && . ${E(re)} && /bin/rm -f -- ${E(re)} && /bin/rmdir -- ${E(ce)} || exit 1; `}}let L=Buffer.from(p.stdin??""),H="/dev/null",G="",ne="";if(L.length){Z=`/tmp/.sandbox-sdk/stdin-${crypto.randomUUID()}`;let O=await pe(n,s,Z,L,M);if(H=O.length===1?`${Z}/part-0`:`${Z}/stdin`,O.length>1)ne=`(umask 077 && cat -- ${O.map(E).join(" ")} > ${E(H)}) || { echo setup-failed > ${E(u)}; exit 125; }; `;G=`/bin/rm -rf -- ${E(Z)}; `}if(j)return{exitCode:null,timedOut:!0};let ee=`(${le}) || { echo setup-failed > ${E(u)}; exit 125; }; ${ne}{ ${G}(${S}cd ${E(p.cwd)} && exec sh -c ${E(p.command)}); } < ${E(H)}`;X=!0;let K=await te(n,s,{command:ee,detached:!0});if(K.kind!=="started"||!Number.isSafeInteger(K.processId)||K.processId<1)throw M("Boat did not confirm a detached process ID","outcome_unknown",s);if(J=K.processId,p.signal?.aborted)T();let V=(async()=>{for await(let O of ge(P.http??n,s,K.processId,{signal:C.signal,...P.timing===void 0?void 0:{timing:P.timing}}))if(O.type==="stdout"||O.type==="stderr")p.onChunk({stream:O.type,text:O.data});else if(O.type==="exit")return F=!0,ae=O.exitCode!==125,{exitCode:O.exitCode,timedOut:O.timedOut};else if(O.type==="error")throw M("Boat command stream failed","provider",s);throw M("Boat stream ended without an exit result","outcome_unknown",s)})();V.catch(()=>{});let oe=await Promise.race([V,W]);if(oe==="cancelled"||j)return await g(),C.abort(),await V.catch(()=>{}),{exitCode:null,timedOut:!0};if(!oe.timedOut&&oe.exitCode===125){let O=await te(n,s,{command:`if [ -f ${E(u)} ]; then cat ${E(u)}; rm -f -- ${E(u)}; fi`,timeoutSeconds:10});if(O.kind!=="finished"||O.exitCode!==0)throw M("Boat could not confirm command initialization","outcome_unknown",s);if(O.stdout.trim()==="setup-failed")throw M("Boat workspace initialization failed; the requested command did not run","provider",s)}return oe}catch(b){if(J!==void 0&&!F)await g();if(X&&J===void 0&&!["auth","quota","invalid_argument","not_found"].includes(U(b,s).code))throw M("Command launch outcome is unknown; inspect or destroy the sandbox before retrying","outcome_unknown",s);throw b}finally{if(C.abort(),clearTimeout(Y),p.signal?.removeEventListener("abort",T),Q)await te(n,s,{command:`rm -rf -- ${E(Q)}`,timeoutSeconds:10},!0).catch(()=>{});if(Z&&!ae)await te(n,s,{command:`rm -rf -- ${E(Z)}`,timeoutSeconds:10},!0).catch(()=>{})}}var Fe={name:"boat",label:"Boat",keyEnv:"BOAT_API_KEY",baseEnv:"BOAT_API_BASE",baseUrl:"https://boat.dev/api/v1"},ue="@boatdev/sdk",ye="sandbox-sdk:1:",He={"sandbox-sdk":"1"},Je={small:"small",medium:"default",large:"large"};function De(n,s,p){let I={...n.labels};delete I["sandbox-sdk"];let w=JSON.stringify([n.key??null,I]);if(Buffer.byteLength(w)>65536)throw s("Key and labels exceed the metadata size limit","unsupported");let A=ye+qe(w).toString("base64url");if(A.length>120)throw s(`Key and labels exceed ${p}'s encoded name budget; shorten them`,"unsupported");return A}function _e(n){if(!n.startsWith(ye))return;try{let s=JSON.parse(Ue(Buffer.from(n.slice(ye.length),"base64url"),{maxOutputLength:65536}).toString());if(!Array.isArray(s)||s.length!==2)return;let[p,I]=s;if(p!==null&&!t(p))return;if(!r(I)||I===null||Array.isArray(I))return;let w={};for(let[A,P]of Object.entries(I)){if(!t(P))return;Object.defineProperty(w,A,{value:P,enumerable:!0,writable:!0,configurable:!0})}return{...p===null?void 0:{key:p},labels:{...w,...He}}}catch{return}}function be(n,s,p,I=[]){let w=_e(n.name);if(!w)throw s("Sandbox has no valid SDK metadata; connect an SDK-created sandbox","not_found",n.id);let A=n.createdAt;if(!Number.isFinite(A))throw s(`${p} returned no valid creation timestamp`,"provider",n.id);return{id:n.id,...w,createdAt:A,state:I.includes(n.state)?"paused":["ready","idle","running"].includes(n.state)?"running":"stopped"}}function Ce(n,s,p){if(!r(n)||n===null||!("path"in n)||!t(n.path)||!("type"in n)||!("size"in n)||!o(n.size)||!("modifiedAt"in n)||!o(n.modifiedAt))throw s(`Invalid file metadata from ${p}`);let I=n.type;if(I!=="file"&&I!=="directory"&&I!=="symlink")throw s(`Invalid file type from ${p}`);return{path:n.path,type:I,size:n.size,modifiedAt:n.modifiedAt}}var Oe="const fs=require('fs'),p=require('path');const stat=x=>{const s=fs.lstatSync(x);return {path:x,type:s.isSymbolicLink()?'symlink':s.isDirectory()?'directory':'file',size:s.size,modifiedAt:s.mtimeMs}};";function q(n={},s=Fe){let{failure:p,boatError:I}=B(s.name,s.label,s.keyEnv,s.name!=="boat"),w=s.label,A=new Map,P=new Map,U=n.requestTimeoutMs??90000,M=()=>n.apiKey??process.env[s.keyEnv];function C(){let u=M();if(!u)throw p(`${w} API key is missing. Authentication is required. Set ${s.keyEnv} or pass apiKey.`,"auth");if(!Number.isSafeInteger(U)||U<=0)throw p("requestTimeoutMs must be a positive integer","invalid_argument");return u}let j={provider:s.name,label:w,keyEnv:s.keyEnv,baseUrl:()=>n.baseUrl??n.apiUrl??(s.baseEnv?process.env[s.baseEnv]:void 0)??s.baseUrl,credentials:C,secrets:()=>[M()],timeoutMs:Number.isSafeInteger(U)&&U>0?U:90000},T=me(j),W=me({...j,retries:0}),Y=(u)=>{let g=ve(u,s.name,w);return s.observe?.(g),g};async function J(u,g){try{return await u()}catch(b){throw I(b,g)}}async function F(u,g,b=!1,_=!1){let S=await te(T,u,{command:_?`${le}; ${g}`:g,timeoutSeconds:60});if(S.kind!=="finished")throw p(`${w} returned an unexpected detached result`,"outcome_unknown",u);if(S.truncated)throw p(`${w} truncated operation output; no partial file data was returned`,"provider",u);if(S.exitCode!==0)throw p(b&&S.exitCode===44?"File does not exist":`${w} file or setup operation failed`,b&&S.exitCode===44?"file_not_found":"provider",u);return S.stdout}let X=(u,g,b=[])=>J(()=>F(u,`node -e ${E(`try {${g}} catch(e) {process.exit(e.code==='ENOENT'?44:45)}`)} ${b.map(E).join(" ")}`,!0,b.some((_)=>_==="/workspace"||_.startsWith("/workspace/"))),u);async function Z(u,g,b,_){let S=[];for(let N=0;N<_;N+=16384){let D=Math.min(16384,_-N),L=await X(u,"const f=require('fs'),fd=f.openSync(process.argv[1],'r');try{const b=Buffer.alloc(Number(process.argv[3]));const n=f.readSync(fd,b,0,b.length,Number(process.argv[2]));process.stdout.write(b.subarray(0,n).toString('base64'))}finally{f.closeSync(fd)}",[g,String(b+N),String(D)]),H=Buffer.from(L,"base64");if(S.push(H),H.length<D)break}return new Uint8Array(Buffer.concat(S))}let ae={package:ue,async connect(u,g){let b=v(u,"Configuration",[{...s.sdkConfiguration,basePath:j.baseUrl(),accessToken:C()}],ue),_=v(u,"BoatApi",[b],ue);if(g===void 0)return _;let S=await k(_,"get",[{sandboxId:g}],ue);return{client:_,sandbox:r(S)?"sandbox"in S?S.sandbox:void 0:void 0}}},Q={name:s.name,keyMode:"best-effort",capabilities:new Set(["size"]),create:(u)=>J(async()=>{if(u.network!==void 0&&u.network!=="all")throw p(`${w} network policy is unsupported by this adapter`,"unsupported");if(u.size!==void 0&&!t(u.size))throw p(`${w} supports small, medium and large presets; custom sizes are unavailable`,"unsupported");if(u.timeoutMs!==void 0)throw p(`${w} auto-stop archives the VM and restarts while its agent works, so it is not a hard lifetime; timeoutMs is unsupported. Set the provider's ttlSeconds option instead`,"unsupported");if(u.idleTimeoutMs!==void 0&&!s.idleStop)throw p(`${w} has no idle timer; idleTimeoutMs is unsupported`,"unsupported");let{ttlSeconds:g,snapshots:b,monitoring:_,org:S}=n;if(g!==void 0&&g!==null&&(!Number.isSafeInteger(g)||g<1||g>2592000))throw p("ttlSeconds must be null or an integer from 1 to 2592000","invalid_argument");let N;if(u.idleTimeoutMs!==void 0){if(N=Math.ceil(u.idleTimeoutMs/60000),N>10080)throw p(`${w} idle pause is at most 7 days`,"invalid_argument");if(b===!1)throw p(`${w} idle pause needs snapshots; drop idleTimeoutMs or snapshots: false`,"invalid_argument")}if(u.from!==void 0&&!s.createFrom)throw p(`${w} snapshots are not supported by this adapter`,"unsupported");let D=De(u,p,w);if(u.signal?.aborted)throw p("Creation was aborted","aborted");let L=crypto.randomUUID(),H={noEnv:!0,...u.from===void 0?void 0:{from:u.from},env:u.env,type:u.size===void 0?n.machine??n.type:Je[u.size],...g===void 0?void 0:{ttlSeconds:g},...b===void 0?void 0:{snapshots:b},..._===void 0?void 0:{monitoring:_},...S===void 0?void 0:{org:S},...N===void 0?void 0:{idleStopMinutes:N},...s.createFields},G=d(j.timeoutMs),ne=()=>p(`${w} create outcome remains unknown; recover with idempotency key ${L} and the same request body within 24 hours`,"outcome_unknown"),ee;for(let V=0;V<3;V++)try{ee=Y(await W.json({method:"POST",path:"/sandboxes",body:H,idempotencyKey:L,deadline:G}));break}catch(oe){let O=I(oe).code;if(["auth","invalid_argument","quota","not_found"].includes(O))throw oe;let R=250*(V+1);if(V===2||R>=G.remaining())throw ne();await y(R,G,s.name).catch(()=>{throw ne()})}if(!ee)throw p(`${w} returned no sandbox after create`,"outcome_unknown");let K=ee.id;P.set(K,{...u.env});try{if(u.signal?.aborted)throw p("Creation was aborted","aborted");let V=Y(await T.json({method:"PATCH",path:"/sandboxes/{sandboxId}",params:{sandboxId:K},sandboxId:K,body:{name:D},deadline:G}));if(u.signal?.aborted)throw p("Creation was aborted","aborted");if(V.name!==D)return await Q.connect(K);return{...be(V,p,w,s.pausedStates),state:"running"}}catch(V){throw await Q.destroy(K),V}}),connect:(u)=>J(async()=>be(Y(await T.json({method:"GET",path:"/sandboxes/{sandboxId}",params:{sandboxId:u},sandboxId:u})),p,w,s.pausedStates),u),list:(u)=>J(async()=>{let g=[],b,_=new Set;do{let S=$e(await T.json({method:"GET",path:"/sandboxes",query:{limit:200,cursor:b}}),s.name,w);for(let D of S.sandboxes){if(s.observe?.(D),!_e(D.name))continue;let L=be(D,p,w,s.pausedStates);if(Object.entries(u).every(([H,G])=>L.labels[H]===G))g.push(L)}if(!S.hasMore)break;let N=S.nextCursor;if(!N||_.has(N))throw p(`${w} returned an invalid pagination cursor`);_.add(N),b=N}while(b!==void 0);return g}),async find(u){return(await Q.list({})).find((g)=>g.key===u)},destroy:(u)=>J(async()=>{try{if(s.destroy)await s.destroy(T,u);else await T.request({method:"DELETE",path:"/sandboxes/{sandboxId}",params:{sandboxId:u},sandboxId:u,headers:{"X-Ascii-Confirm-Delete":u}})}catch(g){if(I(g).code!=="not_found")throw g}P.delete(u),A.delete(u)},u),exec:(u,g)=>J(async()=>{let b=A.get(u);if(!b)b=new Map,A.set(u,b);return Be(T,u,g,P.get(u),b,{failure:p,boatError:I},{http:W})},u),files:{writeCreatesParents:!0,writeSupportsMode:!0,readRange:(u,g,b)=>Z(u,g,b.offset,b.length),read:async(u,g)=>{let b=await X(u,"const f=require('fs'),fd=f.openSync(process.argv[1],'r');try{const size=f.fstatSync(fd).size,b=Buffer.alloc(Math.min(size,16384)),n=f.readSync(fd,b,0,b.length,0);process.stdout.write(size+'\\n'+b.subarray(0,n).toString('base64'))}finally{f.closeSync(fd)}",[g]),_=b.indexOf(`
4
+ `),S=Number(b.slice(0,_));if(_<0||!Number.isSafeInteger(S)||S<0)throw p(`Invalid ${w} file size`);let N=Buffer.from(b.slice(_+1),"base64");if(S<=16384)return new Uint8Array(N);if(S<=1048576)return new Uint8Array(Buffer.concat([N,await Z(u,g,N.length,S-N.length)]));if(s.downloadMaxBytes!==void 0&&S>s.downloadMaxBytes)return new Uint8Array(Buffer.concat([N,await Z(u,g,N.length,S-N.length)]));return J(async()=>{let D=`/tmp/.sandbox-sdk/download-${crypto.randomUUID()}`,L=`${D}/file`;try{let H=Number(await X(u,"const f=require('fs');f.mkdirSync('/tmp/.sandbox-sdk',{recursive:true});f.mkdirSync(process.argv[2],{mode:0o700});f.copyFileSync(process.argv[1],process.argv[2]+'/file');process.stdout.write(String(f.statSync(process.argv[2]+'/file').size))",[g,D]));if(!Number.isSafeInteger(H)||H<0)throw p("Invalid staged file size","provider",u);if(s.download){let K=await s.download(T,u,L);if(K.length!==H)throw p("Incomplete artifact download","provider",u);return K}let G=await T.json({method:"POST",path:"/sandboxes/{sandboxId}/files/download-url",params:{sandboxId:u},sandboxId:u,body:{path:L,ttlSeconds:300},readOnly:!0}),ne=r(G)&&G!==null&&"url"in G&&t(G.url)?G.url:void 0;if(!ne)throw p(`${w} returned no signed download URL`,"provider",u);let ee;try{ee=(await T.request({method:"GET",path:ne,auth:!1,sandboxId:u,maxBytes:H+1})).body}catch(K){let V=I(K,u).code;throw p("Signed file download failed",V==="aborted"||V==="timeout"?V:"unavailable",u)}if(ee.length!==H)throw p("Incomplete signed file download","provider",u);return ee}finally{await X(u,"require('fs').rmSync(process.argv[1],{recursive:true,force:true})",[D]).catch(()=>{})}},u)},write:(u,g,b,_={})=>J(async()=>{let{mode:S}=_;if(S!==void 0&&(!Number.isSafeInteger(S)||S<0||S>4095))throw p("mode must be an integer from 0 to 0o7777","invalid_argument",u);let N=ze.normalize(g);if(S===void 0&&b.length<=de&&(N.startsWith("/home/user/")||N.startsWith("/tmp/")))try{await se(T,u,{path:g,content:Buffer.from(b).toString("base64"),encoding:"base64"});return}catch(H){if(I(H).code!=="invalid_argument")throw H}let D=`/tmp/.sandbox-sdk/write-${crypto.randomUUID()}`,L=!1;try{let H=await pe(T,u,D,b,p);await X(u,"const f=require('fs'),[d,dir,n,m]=process.argv.slice(1);try{f.mkdirSync(require('path').dirname(d),{recursive:true});const fd=f.openSync(d,'w',m?0o600:0o666);try{if(m)f.fchmodSync(fd,Number(m));for(let i=0;i<Number(n);i++)f.writeFileSync(fd,f.readFileSync(dir+'/part-'+i))}finally{f.closeSync(fd)}}finally{f.rmSync(dir,{recursive:true,force:true})}",[g,D,String(H.length),S===void 0?"":String(S)]),L=!0}finally{if(!L)await X(u,"require('fs').rmSync(process.argv[1],{recursive:true,force:true})",[D]).catch(()=>{})}},u),stat:async(u,g)=>{let b=JSON.parse(await X(u,Oe+"process.stdout.write(JSON.stringify(stat(process.argv[1])))",[g]));return Ce(b,p,w)},list:async(u,g)=>{let b=JSON.parse(await X(u,Oe+"process.stdout.write(JSON.stringify(fs.readdirSync(process.argv[1]).map(x=>stat(p.join(process.argv[1],x)))))",[g]));if(!Array.isArray(b))throw p(`Invalid ${w} directory listing`);return b.map((_)=>Ce(_,p,w))},mkdir:async(u,g)=>{await X(u,"require('fs').mkdirSync(process.argv[1],{recursive:true})",[g])},remove:async(u,g,b)=>{await X(u,"require('fs').rmSync(process.argv[1],{recursive:process.argv[2]==='true'})",[g,String(b.recursive)])}},previewUrl:(u,g)=>J(async()=>{let b=await T.json({method:"POST",path:"/sandboxes/{sandboxId}/host",params:{sandboxId:u},sandboxId:u,body:{port:g}});if(!r(b)||b===null||!("url"in b)||!t(b.url)||!b.url)throw p(`${w} returned no preview URL`,"provider",u);if(s.preview)return s.preview(b.url);let _=new URL(b.url),S=_.searchParams.get("_token");if(S){if(!/^[A-Za-z0-9._~-]+$/.test(S))throw p("Invalid preview token","provider",u);return _.searchParams.delete("_token"),{url:_.toString(),headers:{Cookie:`_port_auth=${S}`}}}if("isProtected"in b&&b.isProtected===!0||"access"in b&&b.access==="private")throw p("Protected preview returned no token","provider",u);return{url:_.toString()}},u),native:(u)=>h({http:T,placeholder:"sandboxId",sandboxId:u,sdk:ae}),api:h({http:T,placeholder:"sandboxId",sdk:ae})};return{provider:Q,http:T}}
5
+ export{B,q};
@@ -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};
package/dist/keys.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  import type { Provider } from "./provider.js";
2
+ import type { CreateOptions } from "./types.js";
2
3
  export declare const knownKey: (provider: Provider, key: string) => string | undefined;
3
4
  export declare function rememberKey(provider: Provider, key: string, id: string): void;
4
5
  export declare function forgetKey(provider: Provider, key: string): void;
5
6
  export declare function forgetSandbox(provider: Provider, id: string): void;
7
+ export declare function withKeyLock<T>(provider: Provider, key: string, options: Pick<CreateOptions, "keyMode" | "locator">, action: () => Promise<T>): Promise<T>;
8
+ export declare function attachHandle(provider: Provider, id: string): void;
9
+ /** Drop one handle's claim. Returns whether it was the last open handle for the sandbox. */
10
+ export declare function detachHandle(provider: Provider, id: string): boolean;