import e from"node:fs";import t from"node:os";import n from"node:path";const r=`/tmp/qbotclaw`,i=e.constants.W_OK|e.constants.X_OK;function a(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}function o(o={}){let s=o.accessSync??e.accessSync,c=o.chmodSync??e.chmodSync,l=o.lstatSync??e.lstatSync,u=o.mkdirSync??e.mkdirSync,d=o.warn??(e=>console.warn(e)),f=o.getuid??(()=>{try{return typeof process.getuid==`function`?process.getuid():void 0}catch{return}}),p=o.tmpdir??t.tmpdir,m=f(),h=e=>m===void 0?!0:!(typeof e.uid==`number`&&e.uid!==m||typeof e.mode==`number`&&e.mode&18),g=()=>{let e=p(),t=m===void 0?`qbotclaw`:`qbotclaw-${m}`;return n.join(e,t)},_=e=>e.isDirectory()&&!e.isSymbolicLink()&&h(e),v=e=>{try{return _(l(e))?(s(e,i),`available`):`invalid`}catch(e){return a(e,`ENOENT`)?`missing`:`invalid`}},y=e=>{try{let t=l(e);return!t.isDirectory()||t.isSymbolicLink()||m!==void 0&&typeof t.uid==`number`&&t.uid!==m||typeof t.mode!=`number`||!(t.mode&18)?!1:(c(e,448),d(`[openclaw] tightened permissions on temp dir: ${e}`),v(e)===`available`)}catch{return!1}},b=()=>{let e=g(),t=v(e);if(t===`available`)return e;if(t===`invalid`){if(y(e))return e;throw Error(`Unsafe fallback OpenClaw temp dir: ${e}`)}try{u(e,{recursive:!0,mode:448}),c(e,448)}catch{throw Error(`Unable to create fallback OpenClaw temp dir: ${e}`)}if(v(e)!==`available`&&!y(e))throw Error(`Unsafe fallback OpenClaw temp dir: ${e}`);return e};if(process.platform===`win32`)return b();let x=v(r);if(x===`available`)return r;if(x===`invalid`)return y(`/tmp/qbotclaw`)?r:b();try{return s(`/tmp`,i),u(r,{recursive:!0,mode:448}),c(r,448),v(`/tmp/qbotclaw`)!==`available`&&!y(`/tmp/qbotclaw`)?b():r}catch{return b()}}export{o as resolvePreferredOpenClawTmpDir};
