@reason-machines/cli-linux-x64 0.2.416 → 0.2.418

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 (117) hide show
  1. package/bin/reason +1 -1
  2. package/bin/runtime/srt/sandbox-runtime.mjs +38 -38
  3. package/bin/vm-hands/api-18d75dfn.js +2 -0
  4. package/bin/vm-hands/api-credentials-3vhge1ap.js +2 -0
  5. package/bin/vm-hands/connect-cli-pn1h0b08.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-17t4efc4.js +2 -0
  7. package/bin/vm-hands/desktop-account-6sjrxy69.js +2 -0
  8. package/bin/vm-hands/device-workspace-s50q53sz.js +2 -0
  9. package/bin/vm-hands/{fsevents-ekt70rcc.js → fsevents-p3d8kd0p.js} +1 -1
  10. package/bin/vm-hands/hands-worker-source-kddz4y15.js +2 -0
  11. package/bin/vm-hands/{index-k8kcz8a3.js → index-wrw65904.js} +35 -35
  12. package/bin/vm-hands/install-receipt-ysa70fvh.js +2 -0
  13. package/bin/vm-hands/local-automation-7nc6cgjp.js +2 -0
  14. package/bin/vm-hands/local-capabilities-5f36fr9x.js +2 -0
  15. package/bin/vm-hands/local-desktop-users-cppjjr81.js +2 -0
  16. package/bin/vm-hands/local-display-mac-0qz3b627.js +2 -0
  17. package/bin/vm-hands/local-display-session-zg4dpnf1.js +2 -0
  18. package/bin/vm-hands/local-display-video-remg1c30.js +2 -0
  19. package/bin/vm-hands/local-managed-process-gjc8gvgb.js +2 -0
  20. package/bin/vm-hands/local-pty-session-rpk05ap5.js +2 -0
  21. package/bin/vm-hands/managed-runtime-f85h6h7f.js +2 -0
  22. package/bin/vm-hands/network-contract-trkxqc0w.js +2 -0
  23. package/bin/vm-hands/package-xqbhdf15.js +2 -0
  24. package/bin/vm-hands/permissions-bhbnb1bp.js +2 -0
  25. package/bin/vm-hands/reason-hands-protocol-xn3ddz70.js +2 -0
  26. package/bin/vm-hands/serve-service-58ea9cwx.js +2 -0
  27. package/bin/vm-hands/status-z9r8nq3y.js +10 -0
  28. package/bin/vm-hands/version-p0g28erd.js +2 -0
  29. package/bin/vm-hands/{vm-hands-entry-lite-bdhjpv7g.js → vm-hands-entry-lite-21qpxvt8.js} +2 -2
  30. package/bin/vm-hands/vm-hands-entry-lite-2nkj0dpx.js +539 -0
  31. package/bin/vm-hands/vm-hands-entry-lite-2wzsnnsp.js +3 -0
  32. package/bin/vm-hands/{vm-hands-entry-lite-8t9xssf9.js → vm-hands-entry-lite-3krzmhkk.js} +2 -2
  33. package/bin/vm-hands/{vm-hands-entry-lite-k278g9kj.js → vm-hands-entry-lite-4vks5phw.js} +5 -5
  34. package/bin/vm-hands/{vm-hands-entry-lite-1cwqa4jr.js → vm-hands-entry-lite-50zbqwkv.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-1rrb66r9.js → vm-hands-entry-lite-5dtfehjv.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-6aeea05q.js → vm-hands-entry-lite-60pg3wxj.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-9ay6f56v.js → vm-hands-entry-lite-6c67a3jc.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-zybbbegw.js → vm-hands-entry-lite-6wt5ja1k.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-zg36myyf.js → vm-hands-entry-lite-8r31b0ps.js} +4 -4
  40. package/bin/vm-hands/vm-hands-entry-lite-ah6fwqxp.js +128 -0
  41. package/bin/vm-hands/{vm-hands-entry-lite-ckv17tn8.js → vm-hands-entry-lite-aj139v8j.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-907pa7f9.js → vm-hands-entry-lite-avc65bd7.js} +6 -6
  43. package/bin/vm-hands/{vm-hands-entry-lite-9c95p6n9.js → vm-hands-entry-lite-beyyy1gz.js} +37 -37
  44. package/bin/vm-hands/{vm-hands-entry-lite-ab2m9erf.js → vm-hands-entry-lite-bx5zy5bd.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-pgb514h0.js → vm-hands-entry-lite-dk79tnax.js} +2 -2
  46. package/bin/vm-hands/vm-hands-entry-lite-ec9jemny.js +5 -0
  47. package/bin/vm-hands/{vm-hands-entry-lite-gvwdy3rf.js → vm-hands-entry-lite-fbhqfzbq.js} +3 -3
  48. package/bin/vm-hands/{vm-hands-entry-lite-t7an5zg2.js → vm-hands-entry-lite-fcvf8md1.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-qysyf65v.js → vm-hands-entry-lite-g4zd2d5n.js} +1 -1
  50. package/bin/vm-hands/{vm-hands-entry-lite-0xrsph3r.js → vm-hands-entry-lite-hbs3tpdg.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-f5e3dbgk.js → vm-hands-entry-lite-hk6trmwa.js} +3 -3
  52. package/bin/vm-hands/{vm-hands-entry-lite-qk4kexta.js → vm-hands-entry-lite-hn76pcgk.js} +5 -5
  53. package/bin/vm-hands/vm-hands-entry-lite-j43nqe8y.js +452 -0
  54. package/bin/vm-hands/{vm-hands-entry-lite-89z488gz.js → vm-hands-entry-lite-jev771b3.js} +2 -2
  55. package/bin/vm-hands/{vm-hands-entry-lite-eqgj4acy.js → vm-hands-entry-lite-jzz73e3f.js} +10 -10
  56. package/bin/vm-hands/vm-hands-entry-lite-m8nqnd9j.js +126 -0
  57. package/bin/vm-hands/vm-hands-entry-lite-mmdwr0mf.js +2 -0
  58. package/bin/vm-hands/{vm-hands-entry-lite-enah5gv4.js → vm-hands-entry-lite-nefcet81.js} +2 -2
  59. package/bin/vm-hands/{vm-hands-entry-lite-hj8n59y9.js → vm-hands-entry-lite-np07qyeq.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-1rtkf2xm.js → vm-hands-entry-lite-nzmkyezg.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-q0k6kx6d.js → vm-hands-entry-lite-pf5qtbj5.js} +4 -4
  62. package/bin/vm-hands/{vm-hands-entry-lite-cs5t8eyd.js → vm-hands-entry-lite-ppmvge7n.js} +5 -5
  63. package/bin/vm-hands/{vm-hands-entry-lite-m11j0f9q.js → vm-hands-entry-lite-rfz60hb3.js} +2 -2
  64. package/bin/vm-hands/vm-hands-entry-lite-s3cg1dsk.js +52 -0
  65. package/bin/vm-hands/vm-hands-entry-lite-s4bharcb.js +9 -0
  66. package/bin/vm-hands/{vm-hands-entry-lite-88swf2qr.js → vm-hands-entry-lite-s5qkb1fk.js} +3 -3
  67. package/bin/vm-hands/{vm-hands-entry-lite-dqd4p5kw.js → vm-hands-entry-lite-stmbekq0.js} +16 -16
  68. package/bin/vm-hands/{vm-hands-entry-lite-6sgfhegd.js → vm-hands-entry-lite-svvysppj.js} +4 -4
  69. package/bin/vm-hands/{vm-hands-entry-lite-22kfyvnk.js → vm-hands-entry-lite-tdgtpx8e.js} +1 -1
  70. package/bin/vm-hands/{vm-hands-entry-lite-b885gwfh.js → vm-hands-entry-lite-vpz54vwj.js} +6 -6
  71. package/bin/vm-hands/vm-hands-entry-lite-w8w451gj.js +4 -0
  72. package/bin/vm-hands/{vm-hands-entry-lite-09m2cdkw.js → vm-hands-entry-lite-wx4ax7wg.js} +3 -3
  73. package/bin/vm-hands/vm-hands-entry-lite-yretc2th.js +3 -0
  74. package/bin/vm-hands/vm-hands-entry-lite-z76nfb19.js +3 -0
  75. package/bin/vm-hands/vm-hands-entry-lite-zp6naptr.js +3 -0
  76. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  77. package/bin/vm-hands/vm-hands-executor-73b49jkg.js +11 -0
  78. package/bin/vm-hands/vm-hands-op-runner-ef9ts9c6.js +2 -0
  79. package/bin/vm-hands/vm-hands-runtime-8z6rx1fj.js +4 -0
  80. package/bin/vm-hands/worker-preview-readiness-w62n91kr.js +2 -0
  81. package/bin/vm-hands/worker-sandbox-2r5nseff.js +2 -0
  82. package/package.json +1 -1
  83. package/bin/vm-hands/api-cjv8m2zy.js +0 -2
  84. package/bin/vm-hands/api-credentials-m5akr9fv.js +0 -2
  85. package/bin/vm-hands/connect-cli-pcfvh00f.js +0 -2
  86. package/bin/vm-hands/custom-endpoint-device-dkqb4rqy.js +0 -2
  87. package/bin/vm-hands/desktop-account-5v7x0ajx.js +0 -2
  88. package/bin/vm-hands/device-workspace-p9q9dckg.js +0 -2
  89. package/bin/vm-hands/hands-worker-source-cgrpm21b.js +0 -2
  90. package/bin/vm-hands/install-receipt-7vt2y2vh.js +0 -2
  91. package/bin/vm-hands/local-automation-zj5h05b9.js +0 -2
  92. package/bin/vm-hands/local-capabilities-gkdh1z5z.js +0 -2
  93. package/bin/vm-hands/local-desktop-users-q886k0mm.js +0 -2
  94. package/bin/vm-hands/local-display-mac-w85956f1.js +0 -2
  95. package/bin/vm-hands/local-display-session-m6an1hqp.js +0 -2
  96. package/bin/vm-hands/local-pty-session-5f50sqq0.js +0 -2
  97. package/bin/vm-hands/managed-runtime-esfmzn6z.js +0 -2
  98. package/bin/vm-hands/network-contract-9x9kc5vv.js +0 -2
  99. package/bin/vm-hands/package-78fkast4.js +0 -2
  100. package/bin/vm-hands/permissions-bvfecyb8.js +0 -2
  101. package/bin/vm-hands/reason-hands-protocol-2tnghj3b.js +0 -2
  102. package/bin/vm-hands/serve-service-mr4mkymv.js +0 -2
  103. package/bin/vm-hands/status-7m9d0yek.js +0 -10
  104. package/bin/vm-hands/version-4bsjs55h.js +0 -2
  105. package/bin/vm-hands/vm-hands-entry-lite-7n60veqy.js +0 -458
  106. package/bin/vm-hands/vm-hands-entry-lite-8ns59paz.js +0 -3
  107. package/bin/vm-hands/vm-hands-entry-lite-8vfd0kez.js +0 -250
  108. package/bin/vm-hands/vm-hands-entry-lite-pmcz7j7t.js +0 -3
  109. package/bin/vm-hands/vm-hands-entry-lite-sm5nkxpw.js +0 -540
  110. package/bin/vm-hands/vm-hands-entry-lite-t7n6t3j9.js +0 -2
  111. package/bin/vm-hands/vm-hands-entry-lite-vq14wv7h.js +0 -52
  112. package/bin/vm-hands/vm-hands-entry-lite-vrqzr15t.js +0 -3
  113. package/bin/vm-hands/vm-hands-entry-lite-zjn2nsth.js +0 -3
  114. package/bin/vm-hands/vm-hands-executor-a7aqej5n.js +0 -11
  115. package/bin/vm-hands/vm-hands-op-runner-k4n3zrqb.js +0 -2
  116. package/bin/vm-hands/vm-hands-runtime-z6ydmvqc.js +0 -4
  117. package/bin/vm-hands/worker-sandbox-smqj3mbe.js +0 -2
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{readdirSync as b,readFileSync as P}from"fs";import{userInfo as k}from"os";var ar="--vm-hands-op-runner-kind=person",cr="--vm-hands-op-runner-kind=surface",Ct="--vm-hands-surface-uid=",At="--vm-hands-surface-dir=",Pt=new Set(["automation.call.v1","display.stream.v1","preview.serve.v1"]);function R(t){let c=new Set([t]),l=[];try{l=b("/proc")}catch{}for(let o of l){if(!/^\d+$/.test(o))continue;try{let d=P(`/proc/${o}/stat`,"utf8");if(Number(d.slice(d.lastIndexOf(")")+2).split(" ")[3])===t)c.add(Number(o))}catch{}}for(let o of c)try{process.kill(o,"SIGKILL")}catch{}}var A=(t)=>{let c=globalThis.Bun;if(!c)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");let l=c.spawn({cmd:[t.shell,...t.args],cwd:t.cwd,env:{...t.environment,TERM:"xterm-256color"},terminal:{cols:t.cols,rows:t.rows,data:(i,s)=>t.onData(s)}}),o=l.terminal,d=()=>{R(l.pid);try{o?.close()}catch{}};if(!o)throw d(),new r("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(i)=>o.write(i),resize:(i,s)=>o.resize(i,s),kill:d,exited:l.exited.then((i)=>typeof i==="number"?i:null,()=>null)}};function x(){let t=(()=>{try{return k().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...t?{USER:t,LOGNAME:t}:{}}}async function E(t){let[{localAutomationAvailable:c},{localDisplayReady:l},{localDisplayVideoAvailable:o},{probeWorkerPreview:d},y]=await Promise.all([import("./local-automation-7nc6cgjp.js"),import("./local-display-session-zg4dpnf1.js"),import("./local-display-video-remg1c30.js"),import("./worker-preview-readiness-w62n91kr.js"),import("fs")]),i=AbortSignal.timeout(15000),s=null;try{y.mkdirSync(t,{recursive:!0,mode:448}),s=y.mkdtempSync(`${t}/probe-`);let[g,p,m]=await Promise.all([Promise.resolve().then(()=>c()).catch(()=>!1),l().catch(()=>!1),d(s,i).catch(()=>!1)]);return{t:"readiness",display_video:p&&await o().catch(()=>!1),lanes:{"automation.call.v1":g,"display.stream.v1":p,"preview.serve.v1":m,"tunnel.open":m,"tunnel.close":m}}}finally{if(s)y.rmSync(s,{recursive:!0,force:!0})}}async function as(){let[{executeLocalOperation:t,spawnCaptured:c},{runLocalPtySession:l},{configureDesktopAccount:o,desktopAccount:d},{configureWorkerSandbox:y}]=await Promise.all([import("./local-capabilities-5f36fr9x.js"),import("./local-pty-session-rpk05ap5.js"),import("./desktop-account-6sjrxy69.js"),import("./worker-sandbox-2r5nseff.js")]);y();let i=process.argv.includes(ar),s=process.argv.includes(cr),g=(a,e,u)=>c(a,e[0]==="-lic"?["-lc",...e.slice(1)]:e,u),p=(process.geteuid?.()??0)!==0;if(s){p=!1;let a=process.argv.find((e)=>e.startsWith(Ct))?.slice(Ct.length);if((process.geteuid?.()??-1)===0&&a)try{p=o({value:a})!==null&&d()!==null}catch{p=!1}}let m=new Map,v=new Map,f=(a)=>{try{process.send?.(a)}catch{}};if(process.on("message",(a)=>{let e=a;if(e?.t==="cancel"){m.get(e.id)?.abort();return}if(e?.t==="control"){let n=v.get(e.id);if(s&&n&&e.control&&typeof e.control.kind==="string")import("./local-managed-process-gjc8gvgb.js").then(({controlManagedDeviceProcess:_})=>_(n,{kind:e.control.kind,payload:e.control.payload??{}})).catch(()=>!1);return}if(e?.t==="retire"){if(s&&typeof e.operation_id==="string"&&typeof e.status==="string")import("./local-managed-process-gjc8gvgb.js").then(({retireManagedDeviceProcess:n})=>n(e.operation_id,e.status)).catch(()=>!1);return}if(e?.t!=="op")return;if(!p){f({t:"done",id:e.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let u=e.claim.capability;if(u==="pty.start"&&!i){f({t:"done",id:e.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}if(Pt.has(u)!==s){f({t:"done",id:e.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let w=new AbortController;m.set(e.id,w),v.set(e.id,e.claim);let S=u==="pty.start"?{runPtySession:(n)=>l(n,{spawnPty:A,environment:x(),loadProxy:()=>null})}:{worker:e.worker,...u==="exec.full"?{spawnFullControl:g}:{}};t(e.state,e.claim,{...S,signal:w.signal,emit:(n)=>{let{deliverySignal:_,...h}=n;f({t:"event",id:e.id,event:h})}}).then((n)=>f({t:"done",id:e.id,completion:n}),(n)=>f({t:"done",id:e.id,completion:{status:"failed",error_code:n&&typeof n==="object"&&"code"in n&&typeof n.code==="string"?n.code:"vm_hands_op_failed"}})).finally(()=>{m.delete(e.id),v.delete(e.id)})}),process.on("disconnect",()=>process.exit(0)),s){let a=process.argv.find((u)=>u.startsWith(At))?.slice(At.length),e={t:"readiness",display_video:!1,lanes:{}};f(p&&a?await E(a).catch(()=>e):e)}await new Promise(()=>{})}
3
+ export{ar,cr,Ct,At,Pt,as};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var ue=".reason/workspace",Ee="workspace_base",J="sessions",xe="workspace_layout",de=".reason/workspace/sessions",zt=/^[0-9a-f]{8}$/;function We(t){if(!Z(t))return!1;let e=".reason/workspace/sessions/";if(!t.startsWith(e))return!1;let n=t.slice(e.length).split("/");return n.length===2&&zt.test(n[0])}var i=4096,S="workspaces/pi";function Z(t){if(typeof t!=="string"||!t||t.length>i)return!1;if(t.startsWith("/")||t.includes("\x00")||t.includes("\\"))return!1;return t.split("/").every((e)=>e!==""&&e!=="."&&e!=="..")}function T(t){if(t.kind==="root"){if(t.path===void 0)return".";if(!Z(t.path))throw Error("invalid_device_workspace_identity");return t.path}if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(t.workspaceId)||t.workspaceId==="."||t.workspaceId==="..")throw Error("invalid_device_workspace_identity");let e=t.layout==="sessions"?"sessions":S;return`${t.base?`${t.base}/`:""}${e}/${t.workspaceId}/repo`}function H(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(e.kind==="root"&&Object.keys(e).length===1)return{kind:"root"};if(e.kind==="root"&&Object.keys(e).length===2&&Z(e.path))return{kind:"root",path:e.path};if(e.kind!=="managed"||typeof e.workspaceId!=="string"||Object.keys(e).length!==2+(e.base===void 0?0:1)+(e.layout===void 0?0:1)||e.base!==void 0&&e.base!==".reason/workspace"||e.layout!==void 0&&e.layout!=="sessions")return null;let n={kind:"managed",workspaceId:e.workspaceId,...e.base===".reason/workspace"?{base:".reason/workspace"}:{},...e.layout==="sessions"?{layout:"sessions"}:{}};try{return T(n),n}catch{return null}}var c="/home/runner";var Hr="/run/reason/sessions",O=/^(?:\/[A-Za-z0-9._-]+)+$/,qr=/-sidechat-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,zr=/^(.+)-repository-[a-z0-9][a-z0-9._-]*-[0-9a-f]{12}$/;function a(t){return qr.exec(t)?.[1]??zr.exec(t)?.[1]??t}var Wt=/^((?:\/[A-Za-z0-9._-]+)+)\/\.reason\/workspace\/(workspaces\/pi|sessions)\/([^/]+)$/;function _(t,e=c,n="sessions"){if(!O.test(e)||e.split("/").some((s)=>s==="."||s===".."))throw Error("invalid_cloud_payload_home");let r=`${e}/${T({kind:"managed",workspaceId:t,base:".reason/workspace",...n?{layout:n}:{}})}`,o=`${Hr}/${a(t)}`;return{home:e,root:r.slice(0,-5),checkout:r,control:o,jobEnv:`${o}/job.env`,cloudAccess:`${o}/cloud-access`,logs:`${o}/logs`,pin:`${o}/ws`}}function E(t){return Wt.exec(t.replace(/\/+$/,""))?.[2]==="sessions"?"sessions":null}function Wr(t){let e=Wt.exec(t.replace(/\/+$/,""));if(!e)return null;try{let n=_(e[3],e[1],E(t));return n.root===t.replace(/\/+$/,"")?n:null}catch{return null}}
3
- export{ue,Ee,J,xe,de,zt,We,Z,T,H,Hr,qr,zr,Wt,Wr};
2
+ var ue=".reason/workspace",Ce="workspace_base",Z="sessions",Ae="workspace_layout",de=".reason/workspace/sessions",rr=/^[0-9a-f]{8}$/;function Qe(t){if(!X(t))return!1;let e=".reason/workspace/sessions/";if(!t.startsWith(e))return!1;let n=t.slice(e.length).split("/");return n.length===2&&rr.test(n[0])}var i=4096,S="workspaces/pi";function X(t){if(typeof t!=="string"||!t||t.length>i)return!1;if(t.startsWith("/")||t.includes("\x00")||t.includes("\\"))return!1;return t.split("/").every((e)=>e!==""&&e!=="."&&e!=="..")}function O(t){if(t.kind==="root"){if(t.path===void 0)return".";if(!X(t.path))throw Error("invalid_device_workspace_identity");return t.path}if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(t.workspaceId)||t.workspaceId==="."||t.workspaceId==="..")throw Error("invalid_device_workspace_identity");let e=t.layout==="sessions"?"sessions":S;return`${t.base?`${t.base}/`:""}${e}/${t.workspaceId}/repo`}function H(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(e.kind==="root"&&Object.keys(e).length===1)return{kind:"root"};if(e.kind==="root"&&Object.keys(e).length===2&&X(e.path))return{kind:"root",path:e.path};if(e.kind!=="managed"||typeof e.workspaceId!=="string"||Object.keys(e).length!==2+(e.base===void 0?0:1)+(e.layout===void 0?0:1)||e.base!==void 0&&e.base!==".reason/workspace"||e.layout!==void 0&&e.layout!=="sessions")return null;let n={kind:"managed",workspaceId:e.workspaceId,...e.base===".reason/workspace"?{base:".reason/workspace"}:{},...e.layout==="sessions"?{layout:"sessions"}:{}};try{return O(n),n}catch{return null}}var c="/home/runner";var Yr="/run/reason/sessions",a=/^(?:\/[A-Za-z0-9._-]+)+$/,Qr=/-sidechat-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,en=/^(.+)-repository-[a-z0-9][a-z0-9._-]*-[0-9a-f]{12}$/;function _(t){return Qr.exec(t)?.[1]??en.exec(t)?.[1]??t}var nr=/^((?:\/[A-Za-z0-9._-]+)+)\/\.reason\/workspace\/(workspaces\/pi|sessions)\/([^/]+)$/;function E(t,e=c,n="sessions"){if(!a.test(e)||e.split("/").some((s)=>s==="."||s===".."))throw Error("invalid_cloud_payload_home");let r=`${e}/${O({kind:"managed",workspaceId:t,base:".reason/workspace",...n?{layout:n}:{}})}`,o=`${Yr}/${_(t)}`;return{home:e,root:r.slice(0,-5),checkout:r,control:o,jobEnv:`${o}/job.env`,cloudAccess:`${o}/cloud-access`,logs:`${o}/logs`,pin:`${o}/ws`}}function A(t){return nr.exec(t.replace(/\/+$/,""))?.[2]==="sessions"?"sessions":null}function tn(t){let e=nr.exec(t.replace(/\/+$/,""));if(!e)return null;try{let n=E(e[3],e[1],A(t));return n.root===t.replace(/\/+$/,"")?n:null}catch{return null}}
3
+ export{ue,Ce,Z,Ae,de,rr,Qe,X,O,H,Yr,Qr,en,nr,tn};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{t,ft,A,o,d,u,c,_,oe,s,n}from"./vm-hands-entry-lite-907pa7f9.js";var T=t().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((e)=>e.split("/").every((r)=>r!=="."&&r!=="..")),y=t().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((e)=>!e.includes("..")&&!e.includes("//")&&!e.endsWith("/")&&!e.endsWith(".lock")),x=t().regex(/^[a-f0-9]{40}$/),O=o().int().positive(),k=t().min(1).max(256),D=t().max(60000),L={version:n(1),repoFullName:T},N=u(t().max(1024).regex(/^(?:Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>|Reason-Contributor-ID: rc_[a-f0-9]{32})$/)).max(1000),j=c({expectedTrailers:N,missingFromHead:N}),z=_("action",[c({action:n("edit"),title:k.optional(),body:D.optional(),base:y.optional()}),c({action:s(["ready","draft","close"])}),c({action:n("metadata"),field:s(["reviewer","assignee","label"]),change:s(["add","remove"]),value:t().min(1).max(100).refine((e)=>!/[\r\n\0]/.test(e))})]),ke=_("kind",[c({...L,kind:n("read"),path:t().min(1).max(2048),accept:s(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),c({...L,kind:n("pr_review_context"),number:O,after:t().min(1).max(1024).optional()}),c({...L,kind:n("prepare"),branch:y,baseSha:x,defaultBranch:y,diagnosticsVersion:n(1).optional()}),c({...L,kind:n("publish"),branch:y,defaultBranch:y,baseSha:x,remoteHeadSha:x.nullable(),contributorTrailers:N.optional()}),c({...L,kind:n("pr_create"),head:y,base:y,title:k,body:D,draft:d()}),c({...L,kind:n("pr_mutation"),number:O,mutation:z}),c({...L,kind:n("pr_merge"),number:O,expectedHeadSha:x,expectedBaseRef:y,method:s(["merge","squash","rebase"]),commitBody:t().max(65536).optional()})]),V=["local_device_gh_prepare_setup","local_device_gh_prepare_metadata","local_device_gh_prepare_private_init","local_device_gh_prepare_fetch","local_device_gh_prepare_base_mismatch","local_device_gh_prepare_checkout_validation","local_device_gh_prepare_checkout_init","local_device_gh_prepare_materialization"];function F(e){return V.some((r)=>r===e)}class Vt extends Error{code;constructor(e){super(e);this.code=e}}function $n(e,r,i){let l=ke.safeParse(e);return r==="failed"&&l.success&&l.data.kind==="prepare"&&l.data.diagnosticsVersion===1&&F(i)}var lt=245760,ho=_("kind",[c({kind:n("pr_review_context"),body:t().max(lt)}),c({kind:n("prepare"),headSha:x}),c({kind:n("read"),status:o().int().min(200).max(599),headers:oe(t(),t().max(8192)).refine((e)=>Object.keys(e).every((r)=>r==="link"||r==="content-type")),body:t().max(lt)}),c({kind:n("publish"),headSha:x,scannedObjectCount:o().int().min(0).max(5000),attribution:j.optional()}),c({kind:n("pr_create"),url:t().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),c({kind:n("pr_mutation"),number:O,applied:n(!0)}),c({kind:n("pr_merge"),number:O,merged:n(!0)})]).refine((e)=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=lt,"local_device_gh_result_too_large"),B=c({source:s(["agent","human"]),operationId:A()}),ie=c({version:n(1),userId:ft(),deviceId:ft(),rootId:ft(),runId:ft(),merge:B.optional(),contributorRefresh:ft().optional(),repoFullName:T.nullable(),rootRevision:t().regex(/^[1-9][0-9]*$/),readOnly:d(),generation:o().int().positive().nullable(),fenceId:ft().nullable()}).refine((e)=>e.generation===null===(e.fenceId===null));function I(e){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(e)&&e.split("/").every((r)=>r!=="."&&r!=="..")}function fo(e,r,i={},l="read"){if(I(e)&&(r==="/search/issues"||r.startsWith("/search/issues?")))return W(e,r,i);if(!I(e)||!r.startsWith(`/repos/${e}/`)&&r!==`/repos/${e}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(r)||/%(?:2e|5c|00)/i.test(r))throw Error("local_device_gh_path_denied");let g=new URL(r,"https://api.github.com");if(g.pathname!==r.split("?")[0]||g.username||g.password)throw Error("local_device_gh_path_denied");let h;try{h=decodeURIComponent(g.pathname.slice(`/repos/${e}`.length))}catch{throw Error("local_device_gh_path_denied")}if(h.includes("%")||h.split("/").some((p)=>p==="."||p===".."))throw Error("local_device_gh_path_denied");if((i.method??"GET").toUpperCase()!=="GET"||i.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((p)=>p.test(h)))throw Error("local_device_gh_path_denied");if(g.searchParams.forEach((p,b)=>{if(b==="per_page"&&/^[1-9][0-9]*$/.test(p)&&Number(p)<=100)return;if(b==="page"&&/^[1-9][0-9]*$/.test(p)&&Number(p)<=100)return;if(h==="/pulls"&&b==="state"&&["open","closed","all"].includes(p))return;if(h==="/pulls"&&b==="sort"&&p==="updated")return;if(h==="/pulls"&&b==="direction"&&p==="desc")return;if(h==="/pulls"&&["head","base"].includes(b)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(p))return;throw Error("local_device_gh_query_denied")}),i.headers)new Headers(i.headers).forEach((b,G)=>{if(G!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(b))throw Error("local_device_gh_header_denied")})}function W(e,r,i){if(/[\\#\u0000-\u001f]/.test(r))throw Error("local_device_gh_path_denied");let l=new URL(r,"https://api.github.com");if(l.pathname!=="/search/issues"||l.username||l.password)throw Error("local_device_gh_path_denied");if((i.method??"GET").toUpperCase()!=="GET"||i.body!=null)throw Error("local_device_gh_mutation_not_admitted");let g=null;l.searchParams.forEach((f,p)=>{if(p==="q"&&g===null){g=f;return}if(p==="per_page"&&/^[1-9][0-9]*$/.test(f)&&Number(f)<=100)return;if(p==="page"&&/^[1-9][0-9]*$/.test(f)&&Number(f)<=100)return;throw Error("local_device_gh_query_denied")});let h=`repo:${e.toLowerCase()} `,S=g?.toLowerCase()??"";if(S.length>512||!(S+" ").startsWith(h)||/(?:^|\s)(?:repo|org|user):/.test(S.slice(h.length)))throw Error("local_device_gh_query_denied");if(i.headers)new Headers(i.headers).forEach((f,p)=>{if(p!=="accept"||f!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var mo=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
2
+ import{t,Et,k,o,d,u,c,_,ee,s,n}from"./vm-hands-entry-lite-avc65bd7.js";var I=t().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((e)=>e.split("/").every((r)=>r!=="."&&r!=="..")),y=t().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((e)=>!e.includes("..")&&!e.includes("//")&&!e.endsWith("/")&&!e.endsWith(".lock")),x=t().regex(/^[a-f0-9]{40}$/),O=o().int().positive(),T=t().min(1).max(256),D=t().max(60000),L={version:n(1),repoFullName:I},C=u(t().max(1024).regex(/^(?:Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>|Reason-Contributor-ID: rc_[a-f0-9]{32})$/)).max(1000),j=c({expectedTrailers:C,missingFromHead:C}),z=_("action",[c({action:n("edit"),title:T.optional(),body:D.optional(),base:y.optional()}),c({action:s(["ready","draft","close"])}),c({action:n("metadata"),field:s(["reviewer","assignee","label"]),change:s(["add","remove"]),value:t().min(1).max(100).refine((e)=>!/[\r\n\0]/.test(e))})]),Pe=_("kind",[c({...L,kind:n("read"),path:t().min(1).max(2048),accept:s(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),c({...L,kind:n("pr_review_context"),number:O,after:t().min(1).max(1024).optional()}),c({...L,kind:n("prepare"),branch:y,baseSha:x,defaultBranch:y,diagnosticsVersion:n(1).optional()}),c({...L,kind:n("publish"),branch:y,defaultBranch:y,baseSha:x,remoteHeadSha:x.nullable(),contributorTrailers:C.optional()}),c({...L,kind:n("pr_create"),head:y,base:y,title:T,body:D,draft:d()}),c({...L,kind:n("pr_mutation"),number:O,mutation:z}),c({...L,kind:n("pr_merge"),number:O,expectedHeadSha:x,expectedBaseRef:y,method:s(["merge","squash","rebase"]),commitBody:t().max(65536).optional()})]),V=["local_device_gh_prepare_setup","local_device_gh_prepare_metadata","local_device_gh_prepare_private_init","local_device_gh_prepare_fetch","local_device_gh_prepare_base_mismatch","local_device_gh_prepare_checkout_validation","local_device_gh_prepare_checkout_init","local_device_gh_prepare_materialization"];function F(e){return V.some((r)=>r===e)}class ir extends Error{code;constructor(e){super(e);this.code=e}}function Qn(e,r,i){let l=Pe.safeParse(e);return r==="failed"&&l.success&&l.data.kind==="prepare"&&l.data.diagnosticsVersion===1&&F(i)}var yt=245760,No=_("kind",[c({kind:n("pr_review_context"),body:t().max(yt)}),c({kind:n("prepare"),headSha:x}),c({kind:n("read"),status:o().int().min(200).max(599),headers:ee(t(),t().max(8192)).refine((e)=>Object.keys(e).every((r)=>r==="link"||r==="content-type")),body:t().max(yt)}),c({kind:n("publish"),headSha:x,scannedObjectCount:o().int().min(0).max(5000),attribution:j.optional()}),c({kind:n("pr_create"),url:t().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),c({kind:n("pr_mutation"),number:O,applied:n(!0)}),c({kind:n("pr_merge"),number:O,merged:n(!0)})]).refine((e)=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=yt,"local_device_gh_result_too_large"),B=c({source:s(["agent","human"]),operationId:k()}),oe=c({version:n(1),userId:Et(),deviceId:Et(),rootId:Et(),runId:Et(),merge:B.optional(),contributorRefresh:Et().optional(),repoFullName:I.nullable(),rootRevision:t().regex(/^[1-9][0-9]*$/),readOnly:d(),generation:o().int().positive().nullable(),fenceId:Et().nullable()}).refine((e)=>e.generation===null===(e.fenceId===null));function w(e){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(e)&&e.split("/").every((r)=>r!=="."&&r!=="..")}function Lo(e,r,i={},l="read"){if(w(e)&&(r==="/search/issues"||r.startsWith("/search/issues?")))return W(e,r,i);if(!w(e)||!r.startsWith(`/repos/${e}/`)&&r!==`/repos/${e}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(r)||/%(?:2e|5c|00)/i.test(r))throw Error("local_device_gh_path_denied");let g=new URL(r,"https://api.github.com");if(g.pathname!==r.split("?")[0]||g.username||g.password)throw Error("local_device_gh_path_denied");let h;try{h=decodeURIComponent(g.pathname.slice(`/repos/${e}`.length))}catch{throw Error("local_device_gh_path_denied")}if(h.includes("%")||h.split("/").some((p)=>p==="."||p===".."))throw Error("local_device_gh_path_denied");if((i.method??"GET").toUpperCase()!=="GET"||i.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((p)=>p.test(h)))throw Error("local_device_gh_path_denied");if(g.searchParams.forEach((p,b)=>{if(b==="per_page"&&/^[1-9][0-9]*$/.test(p)&&Number(p)<=100)return;if(b==="page"&&/^[1-9][0-9]*$/.test(p)&&Number(p)<=100)return;if(h==="/pulls"&&b==="state"&&["open","closed","all"].includes(p))return;if(h==="/pulls"&&b==="sort"&&p==="updated")return;if(h==="/pulls"&&b==="direction"&&p==="desc")return;if(h==="/pulls"&&["head","base"].includes(b)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(p))return;throw Error("local_device_gh_query_denied")}),i.headers)new Headers(i.headers).forEach((b,G)=>{if(G!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(b))throw Error("local_device_gh_header_denied")})}function W(e,r,i){if(/[\\#\u0000-\u001f]/.test(r))throw Error("local_device_gh_path_denied");let l=new URL(r,"https://api.github.com");if(l.pathname!=="/search/issues"||l.username||l.password)throw Error("local_device_gh_path_denied");if((i.method??"GET").toUpperCase()!=="GET"||i.body!=null)throw Error("local_device_gh_mutation_not_admitted");let g=null;l.searchParams.forEach((f,p)=>{if(p==="q"&&g===null){g=f;return}if(p==="per_page"&&/^[1-9][0-9]*$/.test(f)&&Number(f)<=100)return;if(p==="page"&&/^[1-9][0-9]*$/.test(f)&&Number(f)<=100)return;throw Error("local_device_gh_query_denied")});let h=`repo:${e.toLowerCase()} `,S=g?.toLowerCase()??"";if(S.length>512||!(S+" ").startsWith(h)||/(?:^|\s)(?:repo|org|user):/.test(S.slice(h.length)))throw Error("local_device_gh_query_denied");if(i.headers)new Headers(i.headers).forEach((f,p)=>{if(p!=="accept"||f!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var Mo=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
3
3
  repository(owner: $owner, name: $repo) {
4
4
  nameWithOwner
5
5
  pullRequest(number: $number) {
@@ -34,9 +34,9 @@ import{t,ft,A,o,d,u,c,_,oe,s,n}from"./vm-hands-entry-lite-907pa7f9.js";var T=t()
34
34
  }
35
35
  }
36
36
  }
37
- }`;function Ve(e){return e.kind==="read"||e.kind==="pr_review_context"}var ut=["inspect_project","fs.read","fs.write","fs.search","fs.watch","fs.upload","fs.export","fs.import","fs.download","exec.run","exec.full","process.run.v1","process.full.v1","pty.start","pty.input","pty.resize","pty.close","git.run","process.list","process.signal","ports.list","tunnel.open","tunnel.close","env.discover","setup.run","mcp.discover","mcp.start","mcp.proxy","browser.snapshot","browser.navigate","browser.act","computer.snapshot","computer.act","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.ollama.v1","inference.custom.v1","delegate.devin.copy.v1","delegate.cursor.copy.v1","display.stream.v1","automation.call.v1","preview.serve.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"];var Ge=2,w="/app/local-runtime",Ce=262144,vs="x-reason-relay-host-alias",Ss="v1";function m(e,r){return{path:`${w}${e}`,routerPath:e,auth:r}}function E(e,r){return{...m(e,"device_proof"),forOperation(i){return m(`/operations/${encodeURIComponent(i)}${r}`,"device_proof")}}}var Es={register:m("/register","registration_bearer"),enroll:m("/enroll","none"),authChallenge:m("/auth/challenge","none"),identity:m("/identity","device_proof"),heartbeat:m("/heartbeat","device_proof"),rootsSync:m("/roots/sync","device_proof"),disconnect:m("/disconnect","device_proof"),lifecycle:m("/lifecycle","device_proof"),localSubscription:m("/local-subscription","device_proof"),ownerWorkspaces:m("/owner-workspaces","device_proof"),ownerWorkspaceEnrollment:m("/owner-workspaces/enrollment","device_proof"),sessionWorktrees:m("/session-worktrees","device_proof"),operationClaim:m("/operations/claim","device_proof"),operationHeartbeat:E("/operations/:operationId/heartbeat","/heartbeat"),operationEvents:E("/operations/:operationId/events","/events"),operationComplete:E("/operations/:operationId/complete","/complete"),operationEnvironment:E("/operations/:operationId/environment","/environment"),operationEnvironmentAck:E("/operations/:operationId/environment-ack","/environment-ack"),operationCustomEndpointCredential:E("/operations/:operationId/custom-endpoint-credential","/custom-endpoint-credential")},Bn=`${w}/session`;var J=[/^\/app\/local-runtime\/heartbeat$/,/^\/app\/local-runtime\/operations\/claim$/,/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/(?:heartbeat|events|complete|environment|environment-ack)$/];function xs(e){return J.some((r)=>r.test(e))}var Vr=60000;var Fn="hands_control_v1",dt="environment.deliver",Ae="vm_hands_workspace_deferred",pt="vm_hands.workspace_grant",jn="hands.unbind_unverified",Un="claim_v1",Hn="environment_at_claim",qn="ready_v1",zn="workspace_check",Wn="rebind_v1",Vn="grant_v1",Gn="workspace_grant",Kn="resident_rebind",Jn="hands.rebind",Zn="snapshot_v1",Xn="cloud_access",Yn="playwright_v1",Qn="headless_browser",ei="v1",ti="job_env_large_values",pe="srt_root_v1",X="hands_confinement",Pe="gid_v1",q="model_jobs_egress",ri="setpriv_v1",ni="jobs_user",ii="spawning_attempt_v1",Y="hands_session_group";var oi="session_cap",si="none",ai="same_launch_v1",ci="exit_v1",li="start_wait",ht="user_chrome",ui="cloud_sessions";function v(e){if(!a(e)||Object.keys(e).length!==5||e.version!==1)return!1;let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["boot_generation","recording_operation_id","recording_attempt_id"].every((i)=>typeof e[i]==="string"&&r.test(e[i]))&&typeof e.root_version==="string"&&/^[0-9]{1,20}(?:\.[0-9]{1,6})?$/.test(e.root_version)}function C(e){if(!a(e)||Object.keys(e).length!==6)return!1;let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return typeof e.device_id==="string"&&r.test(e.device_id)&&(e.binding==="workspace_source"||e.binding==="mcp_control")&&Number.isSafeInteger(e.target_revision)&&Number(e.target_revision)>=0&&Number.isSafeInteger(e.root_grant_revision)&&Number(e.root_grant_revision)>0&&Number.isSafeInteger(e.target_generation)&&Number(e.target_generation)>0&&typeof e.target_fence_id==="string"&&r.test(e.target_fence_id)}var ks=["lock_acquired","enrollment_started","enrollment_completed","readiness_started","readiness_completed","inventory_completed","control_ready"],Gt=86400000;var K=["production","staging"];function P(e){if(!a(e)||Object.keys(e).length!==3)return!1;let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["organization_id","user_id","device_id"].every((i)=>Object.hasOwn(e,i)&&typeof e[i]==="string"&&r.test(e[i])&&e[i]!=="00000000-0000-0000-0000-000000000000")}var Z="DEVICE-PROOF-V2";function di(e,r=Z){let i=e.method.toUpperCase();if(!/^[A-Z]+$/.test(i)||!e.pathAndQuery.startsWith(`${w}/`)||e.pathAndQuery.includes(`
37
+ }`;function et(e){return e.kind==="read"||e.kind==="pr_review_context"}var wt=["inspect_project","fs.read","fs.write","fs.search","fs.watch","fs.upload","fs.export","fs.import","fs.download","exec.run","exec.full","process.run.v1","process.full.v1","pty.start","pty.input","pty.resize","pty.close","git.run","process.list","process.signal","ports.list","tunnel.open","tunnel.close","env.discover","setup.run","mcp.discover","mcp.start","mcp.proxy","browser.snapshot","browser.navigate","browser.act","computer.snapshot","computer.act","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.ollama.v1","inference.custom.v1","delegate.devin.copy.v1","delegate.cursor.copy.v1","display.stream.v1","automation.call.v1","preview.serve.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"];var tt=2,v="/app/local-runtime",Te=262144,Ws="x-reason-relay-host-alias",Vs="v1";function m(e,r){return{path:`${v}${e}`,routerPath:e,auth:r}}function E(e,r){return{...m(e,"device_proof"),forOperation(i){return m(`/operations/${encodeURIComponent(i)}${r}`,"device_proof")}}}var Gs={register:m("/register","registration_bearer"),enroll:m("/enroll","none"),authChallenge:m("/auth/challenge","none"),identity:m("/identity","device_proof"),heartbeat:m("/heartbeat","device_proof"),rootsSync:m("/roots/sync","device_proof"),disconnect:m("/disconnect","device_proof"),lifecycle:m("/lifecycle","device_proof"),localSubscription:m("/local-subscription","device_proof"),ownerWorkspaces:m("/owner-workspaces","device_proof"),ownerWorkspaceEnrollment:m("/owner-workspaces/enrollment","device_proof"),sessionWorktrees:m("/session-worktrees","device_proof"),operationClaim:m("/operations/claim","device_proof"),operationHeartbeat:E("/operations/:operationId/heartbeat","/heartbeat"),operationEvents:E("/operations/:operationId/events","/events"),operationComplete:E("/operations/:operationId/complete","/complete"),operationEnvironment:E("/operations/:operationId/environment","/environment"),operationEnvironmentAck:E("/operations/:operationId/environment-ack","/environment-ack"),operationCustomEndpointCredential:E("/operations/:operationId/custom-endpoint-credential","/custom-endpoint-credential")},ei=`${v}/session`;var J=[/^\/app\/local-runtime\/heartbeat$/,/^\/app\/local-runtime\/operations\/claim$/,/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/(?:heartbeat|events|complete|environment|environment-ack)$/];function Ks(e){return J.some((r)=>r.test(e))}var rn=60000;var ti="hands_control_v1",bt="environment.deliver",Re="vm_hands_workspace_deferred",vt="vm_hands.workspace_grant",ri="hands.unbind_unverified",ni="claim_v1",ii="environment_at_claim",oi="ready_v1",si="workspace_check",ai="rebind_v1",ci="grant_v1",li="workspace_grant",ui="resident_rebind",di="hands.rebind",pi="snapshot_v1",hi="cloud_access",fi="playwright_v1",mi="headless_browser",gi="v1",_i="job_env_large_values",pe="srt_root_v1",Y="hands_confinement",Oe="gid_v1",q="model_jobs_egress",yi="setpriv_v1",wi="jobs_user",bi="spawning_attempt_v1",Q="hands_session_group";var vi="session_cap",Si="none",Ei="same_launch_v1",xi="exit_v1",ki="start_wait",St="user_chrome",Ci="cloud_sessions";function N(e){if(!a(e)||Object.keys(e).length!==5||e.version!==1)return!1;let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["boot_generation","recording_operation_id","recording_attempt_id"].every((i)=>typeof e[i]==="string"&&r.test(e[i]))&&typeof e.root_version==="string"&&/^[0-9]{1,20}(?:\.[0-9]{1,6})?$/.test(e.root_version)}function A(e){if(!a(e)||Object.keys(e).length!==6)return!1;let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return typeof e.device_id==="string"&&r.test(e.device_id)&&(e.binding==="workspace_source"||e.binding==="mcp_control")&&Number.isSafeInteger(e.target_revision)&&Number(e.target_revision)>=0&&Number.isSafeInteger(e.root_grant_revision)&&Number(e.root_grant_revision)>0&&Number.isSafeInteger(e.target_generation)&&Number(e.target_generation)>0&&typeof e.target_fence_id==="string"&&r.test(e.target_fence_id)}var Js=["lock_acquired","enrollment_started","enrollment_completed","readiness_started","readiness_completed","inventory_completed","control_ready"],or=86400000;var K=["production","staging"];function P(e){if(!a(e)||Object.keys(e).length!==3)return!1;let r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["organization_id","user_id","device_id"].every((i)=>Object.hasOwn(e,i)&&typeof e[i]==="string"&&r.test(e[i])&&e[i]!=="00000000-0000-0000-0000-000000000000")}var Z="DEVICE-PROOF-V2";function Ai(e,r=Z){let i=e.method.toUpperCase();if(!/^[A-Z]+$/.test(i)||!e.pathAndQuery.startsWith(`${v}/`)||e.pathAndQuery.includes(`
38
38
  `)||!/^[0-9]{1,20}$/.test(e.timestamp)||!/^[A-Za-z0-9_-]{22,43}$/.test(e.nonce)||e.challenge.length<16||e.challenge.length>1024||e.challenge.includes(`
39
39
  `)||!/^[a-f0-9]{64}$/.test(e.bodySha256))throw Error("Invalid Reason Device proof input.");return Buffer.from([r,i,e.pathAndQuery,e.timestamp,e.nonce,e.challenge,e.bodySha256].join(`
40
- `),"utf8")}function a(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Q(e,r){return typeof e==="string"&&r.some((i)=>i===e)}function H(e){return a(e)&&typeof e.id==="string"&&typeof e.label==="string"&&typeof e.path_fingerprint==="string"}function ee(e){return a(e)&&Number.isInteger(e.seq)&&Number(e.seq)>=0&&typeof e.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(e.kind)&&a(e.payload)}function R(e){throw Error(e)}function Cs(e,r){let i=a(e)?e:{},l=typeof i.error==="string"?i.error:`http_${r}`,g=typeof i.detail==="string"?i.detail:typeof i.message==="string"?i.message:`Reason Device request failed (${r})`;return{code:l,message:g}}function No(e){if(!a(e)||typeof e.challenge!=="string"||e.challenge.length<16||e.challenge.length>1024||e.challenge.includes(`
41
- `)||typeof e.expires_at!=="string"||!Number.isFinite(Date.parse(e.expires_at)))R("Reason returned an invalid Device proof challenge.");return{challenge:e.challenge,expires_at:e.expires_at}}function M(e,r){if(!a(e)||typeof e.device_id!=="string"||e.auth_scheme!=="p256"||e.organization_id!==void 0&&typeof e.organization_id!=="string"||e.protocol_version!==Ge||!Array.isArray(e.roots)||!e.roots.every(H)||r&&typeof e.organization_id!=="string"||e.device_credential!==void 0)R(r?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:e.device_id,...typeof e.organization_id==="string"?{organization_id:e.organization_id}:{},protocol_version:Ge,roots:e.roots},auth_scheme:"p256"}}function As(e){return M(e,!1)}function Ps(e){let r=M(e,!0);if(typeof r.organization_id!=="string")return R("Reason returned an invalid Device enrollment.");return{...r,organization_id:r.organization_id}}function Ts(e){if(!a(e)||typeof e.server_time!=="string"||typeof e.drain!=="boolean")return R("Reason returned an invalid Device heartbeat.");return{server_time:e.server_time,drain:e.drain,...U(e),...typeof e.update_policy==="string"||e.update_policy===null?{update_policy:e.update_policy}:{},...typeof e.supported_protocol_version==="number"?{supported_protocol_version:e.supported_protocol_version}:{},...ne(e.latest_cli_versions),...e.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var te=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function U(e){return Object.fromEntries(te.filter((r)=>e[r]===!0).map((r)=>[r,!0]))}function Rs(e){if(!a(e))return;try{return{...No(e),...U(e)}}catch{return}}function ne(e){if(!a(e))return{};let r={};for(let i of K){let l=e[i];if(typeof l==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(l))r[i]=l}return Object.keys(r).length>0?{latest_cli_versions:r}:{}}function Os(e){if(!a(e)||!Array.isArray(e.roots)||!e.roots.every(H))return R("Reason returned an invalid Device root sync.");return{roots:e.roots}}function Is(e){if(!a(e)||e.user_id!==void 0&&typeof e.user_id!=="string"||typeof e.organization_id!=="string"||typeof e.organization_name!=="string"||typeof e.organization_slug!=="string")return R("Reason returned an invalid Device identity.");return{...typeof e.user_id==="string"?{user_id:e.user_id}:{},organization_id:e.organization_id,organization_name:e.organization_name,organization_slug:e.organization_slug}}function Ds(e){if(!a(e)||e.disconnected!==!0)return R("Reason did not disconnect this Device.");let r=e.sessions_moved;return typeof r==="number"&&Number.isSafeInteger(r)&&r>=0?{disconnected:!0,sessions_moved:r}:{disconnected:!0}}function Ns(e){if(a(e)&&e.ok===!0&&typeof e.expires==="number")return{ok:!0,expires:e.expires};if(a(e)&&e.ok===!1&&typeof e.error==="string")return{ok:!1,error:e.error};return R("Reason did not answer the local login hand-over.")}function Ls(e){if(!a(e)||e.accepted!==!0)return R("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function re(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Ms(e,r=ut){if(!a(e)||typeof e.operation_id!=="string"||typeof e.attempt_id!=="string"||typeof e.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(e.attempt_token)||typeof e.lease_until!=="string"||typeof e.run_id!=="string"||typeof e.root_id!=="string"||e.owner!==void 0&&!P(e.owner)||!Q(e.capability,r)||!a(e.payload)||e.protocol_version!==Ge||re(e.payload)>Ce||e.authority!==void 0&&!C(e.authority)||e.local_github_authority!==void 0&&!ie.safeParse(e.local_github_authority).success||e.capability==="github.local.v1"&&!ie.safeParse(e.local_github_authority).success||e.recording_authority!==void 0&&!v(e.recording_authority)||e.capability==="browser.recording.v1"&&(!v(e.recording_authority)||!P(e.owner))||e.capability!=="browser.recording.v1"&&e.recording_authority!==void 0)return R("Reason returned an invalid Device operation claim.");let i={operation_id:e.operation_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,lease_until:e.lease_until,run_id:e.run_id,root_id:e.root_id,capability:e.capability,payload:e.payload,...C(e.authority)?{authority:e.authority}:{},...v(e.recording_authority)?{recording_authority:Object.freeze({...e.recording_authority})}:{},...e.local_github_authority!==void 0?{local_github_authority:ie.parse(e.local_github_authority)}:{},...e.capability==="hands.connect"&&a(e.environment)&&a(e.environment.payload)&&C(e.environment.authority)?{environment:{payload:e.environment.payload,authority:e.environment.authority}}:{},protocol_version:Ge};if(e.owner!==void 0)i.owner=Object.freeze({...e.owner});return i}function $s(e){if(!a(e)||typeof e.lease_until!=="string"||!Array.isArray(e.controls)||!e.controls.every(ee)||!Number.isInteger(e.next_control_seq)||Number(e.next_control_seq)<0)return R("Reason returned an invalid Device operation heartbeat.");return{lease_until:e.lease_until,controls:e.controls,next_control_seq:Number(e.next_control_seq)}}function Bs(e){if(!a(e)||!Number.isInteger(e.next_event_seq)||Number(e.next_event_seq)<0||typeof e.duplicate!=="boolean"||!Number.isInteger(e.accepted_count)||Number(e.accepted_count)<0)return R("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(e.next_event_seq),duplicate:e.duplicate,accepted_count:Number(e.accepted_count)}}function Fs(e){if(!a(e)||!a(e.payload)||!C(e.authority))return R("Reason returned an invalid Device environment delivery.");return{payload:e.payload,authority:e.authority}}function ae(e){return e==="succeeded"||e==="failed"||e==="cancelled"||e==="expired"}function js(e){if(!a(e)||!ae(e.status)||typeof e.idempotent!=="boolean")return R("Reason returned an invalid Device operation completion.");return{status:e.status,idempotent:e.idempotent}}
42
- export{ke,Vt,$n,lt,ho,ie,fo,mo,Ve,ut,Ge,Ce,vs,Ss,Es,Bn,xs,Vr,Fn,dt,Ae,pt,jn,Un,Hn,qn,zn,Wn,Vn,Gn,Kn,Jn,Zn,Xn,Yn,Qn,ei,ti,pe,X,Pe,q,ri,ni,ii,Y,oi,si,ai,ci,li,ht,ui,ks,Gt,di,Cs,No,As,Ps,Ts,Rs,Os,Is,Ds,Ns,Ls,Ms,$s,Bs,Fs,js};
40
+ `),"utf8")}function a(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function X(e,r){return typeof e==="string"&&r.some((i)=>i===e)}function H(e){return a(e)&&typeof e.id==="string"&&typeof e.label==="string"&&typeof e.path_fingerprint==="string"}function te(e){return a(e)&&Number.isInteger(e.seq)&&Number(e.seq)>=0&&typeof e.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(e.kind)&&a(e.payload)}function R(e){throw Error(e)}function Zs(e,r){let i=a(e)?e:{},l=typeof i.error==="string"?i.error:`http_${r}`,g=typeof i.detail==="string"?i.detail:typeof i.message==="string"?i.message:`Reason Device request failed (${r})`;return{code:l,message:g}}function ts(e){if(!a(e)||typeof e.challenge!=="string"||e.challenge.length<16||e.challenge.length>1024||e.challenge.includes(`
41
+ `)||typeof e.expires_at!=="string"||!Number.isFinite(Date.parse(e.expires_at)))R("Reason returned an invalid Device proof challenge.");return{challenge:e.challenge,expires_at:e.expires_at}}function M(e,r){if(!a(e)||typeof e.device_id!=="string"||e.auth_scheme!=="p256"||e.organization_id!==void 0&&typeof e.organization_id!=="string"||e.protocol_version!==tt||!Array.isArray(e.roots)||!e.roots.every(H)||r&&typeof e.organization_id!=="string"||e.device_credential!==void 0)R(r?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:e.device_id,...typeof e.organization_id==="string"?{organization_id:e.organization_id}:{},protocol_version:tt,roots:e.roots},auth_scheme:"p256"}}function Xs(e){return M(e,!1)}function Ys(e){let r=M(e,!0);if(typeof r.organization_id!=="string")return R("Reason returned an invalid Device enrollment.");return{...r,organization_id:r.organization_id}}function Qs(e){if(!a(e)||typeof e.server_time!=="string"||typeof e.drain!=="boolean")return R("Reason returned an invalid Device heartbeat.");return{server_time:e.server_time,drain:e.drain,...U(e),...typeof e.update_policy==="string"||e.update_policy===null?{update_policy:e.update_policy}:{},...typeof e.supported_protocol_version==="number"?{supported_protocol_version:e.supported_protocol_version}:{},...re(e.latest_cli_versions),...e.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var ne=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function U(e){return Object.fromEntries(ne.filter((r)=>e[r]===!0).map((r)=>[r,!0]))}function ea(e){if(!a(e))return;try{return{...ts(e),...U(e)}}catch{return}}function re(e){if(!a(e))return{};let r={};for(let i of K){let l=e[i];if(typeof l==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(l))r[i]=l}return Object.keys(r).length>0?{latest_cli_versions:r}:{}}function ta(e){if(!a(e)||!Array.isArray(e.roots)||!e.roots.every(H))return R("Reason returned an invalid Device root sync.");return{roots:e.roots}}function ra(e){if(!a(e)||e.user_id!==void 0&&typeof e.user_id!=="string"||typeof e.organization_id!=="string"||typeof e.organization_name!=="string"||typeof e.organization_slug!=="string")return R("Reason returned an invalid Device identity.");return{...typeof e.user_id==="string"?{user_id:e.user_id}:{},organization_id:e.organization_id,organization_name:e.organization_name,organization_slug:e.organization_slug}}function na(e){if(!a(e)||e.disconnected!==!0)return R("Reason did not disconnect this Device.");let r=e.sessions_moved;return typeof r==="number"&&Number.isSafeInteger(r)&&r>=0?{disconnected:!0,sessions_moved:r}:{disconnected:!0}}function ia(e){if(a(e)&&e.ok===!0&&typeof e.expires==="number")return{ok:!0,expires:e.expires};if(a(e)&&e.ok===!1&&typeof e.error==="string")return{ok:!1,error:e.error};return R("Reason did not answer the local login hand-over.")}function oa(e){if(!a(e)||e.accepted!==!0)return R("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function ie(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function sa(e,r=wt){if(!a(e)||typeof e.operation_id!=="string"||typeof e.attempt_id!=="string"||typeof e.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(e.attempt_token)||typeof e.lease_until!=="string"||typeof e.run_id!=="string"||typeof e.root_id!=="string"||e.owner!==void 0&&!P(e.owner)||!X(e.capability,r)||!a(e.payload)||e.protocol_version!==tt||ie(e.payload)>Te||e.authority!==void 0&&!A(e.authority)||e.local_github_authority!==void 0&&!oe.safeParse(e.local_github_authority).success||e.capability==="github.local.v1"&&!oe.safeParse(e.local_github_authority).success||e.recording_authority!==void 0&&!N(e.recording_authority)||e.capability==="browser.recording.v1"&&(!N(e.recording_authority)||!P(e.owner))||e.capability!=="browser.recording.v1"&&e.recording_authority!==void 0)return R("Reason returned an invalid Device operation claim.");let i={operation_id:e.operation_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,lease_until:e.lease_until,run_id:e.run_id,root_id:e.root_id,capability:e.capability,payload:e.payload,...A(e.authority)?{authority:e.authority}:{},...N(e.recording_authority)?{recording_authority:Object.freeze({...e.recording_authority})}:{},...e.local_github_authority!==void 0?{local_github_authority:oe.parse(e.local_github_authority)}:{},...e.capability==="hands.connect"&&a(e.environment)&&a(e.environment.payload)&&A(e.environment.authority)?{environment:{payload:e.environment.payload,authority:e.environment.authority}}:{},protocol_version:tt};if(e.owner!==void 0)i.owner=Object.freeze({...e.owner});return i}function aa(e){if(!a(e)||typeof e.lease_until!=="string"||!Array.isArray(e.controls)||!e.controls.every(te)||!Number.isInteger(e.next_control_seq)||Number(e.next_control_seq)<0)return R("Reason returned an invalid Device operation heartbeat.");return{lease_until:e.lease_until,controls:e.controls,next_control_seq:Number(e.next_control_seq)}}function ca(e){if(!a(e)||!Number.isInteger(e.next_event_seq)||Number(e.next_event_seq)<0||typeof e.duplicate!=="boolean"||!Number.isInteger(e.accepted_count)||Number(e.accepted_count)<0)return R("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(e.next_event_seq),duplicate:e.duplicate,accepted_count:Number(e.accepted_count)}}function la(e){if(!a(e)||!a(e.payload)||!A(e.authority))return R("Reason returned an invalid Device environment delivery.");return{payload:e.payload,authority:e.authority}}function ae(e){return e==="succeeded"||e==="failed"||e==="cancelled"||e==="expired"}function ua(e){if(!a(e)||!ae(e.status)||typeof e.idempotent!=="boolean")return R("Reason returned an invalid Device operation completion.");return{status:e.status,idempotent:e.idempotent}}
42
+ export{Pe,ir,Qn,yt,No,oe,Lo,Mo,et,wt,tt,Te,Ws,Vs,Gs,ei,Ks,rn,ti,bt,Re,vt,ri,ni,ii,oi,si,ai,ci,li,ui,di,pi,hi,fi,mi,gi,_i,pe,Y,Oe,q,yi,wi,bi,Q,vi,Si,Ei,xi,ki,St,Ci,Js,or,Ai,Zs,ts,Xs,Ys,Qs,ea,ta,ra,na,ia,oa,sa,aa,ca,la,ua};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{_t,R}from"./vm-hands-entry-lite-zg36myyf.js";import{C}from"./vm-hands-entry-lite-t7an5zg2.js";import{g,$t}from"./vm-hands-entry-lite-ckv17tn8.js";import{_e}from"./vm-hands-entry-lite-pmcz7j7t.js";function yi(e,i){let r=C(e,"REASON_API_URL")?.trim();if(!r)return $t(i);let t=new URL(r);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return t.origin}function l(e){return C(e,"REASON_API_URL")?.trim()?yi(e,"production"):void 0}function vo(e){return C(e,"REASON_API_KEY")?.trim()||void 0}async function So(e,i){let r=e.env??process.env,t=vo(r);if(!t)return(e.getCredentials??_t)({apiOrigin:l(r),signal:i});let a=yi(r,e.channel??g({env:r})),o=await(e.fetchImpl??fetch)(a+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+t,accept:"application/json"},signal:i}),p=await o.json().catch(()=>({})),n=_e(p)?p:{};if(!o.ok){let s=typeof n.detail==="string"?n.detail:typeof n.message==="string"?n.message:"API key authentication failed ("+o.status+")";throw new R(o.status,typeof n.error==="string"?n.error:"api_key_auth_failed",s)}if(typeof n.org_id!=="string"||!n.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let c=Array.isArray(n.scopes)?n.scopes.filter((s)=>typeof s==="string"):[];return{credentialKind:"api_key",apiOrigin:a,accessToken:t,orgId:n.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:c}}async function Wo(e){let i=await So(e),r=l(e.env??process.env);if(!i)throw Error(r?`Not signed in to ${r}. Set REASON_API_KEY, or run \`reason login --api-url ${r}\`.`:"Not signed in. Run `reason login`, or set REASON_API_KEY.");return i}
3
- export{yi,vo,So,Wo};
2
+ import{Tt,I}from"./vm-hands-entry-lite-8r31b0ps.js";import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{g,Kt}from"./vm-hands-entry-lite-aj139v8j.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";function Ni(e,i){let r=T(e,"REASON_API_URL")?.trim();if(!r)return Kt(i);let t=new URL(r);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return t.origin}function l(e){return T(e,"REASON_API_URL")?.trim()?Ni(e,"production"):void 0}function Ho(e){return T(e,"REASON_API_KEY")?.trim()||void 0}async function zo(e,i){let r=e.env??process.env,t=Ho(r);if(!t)return(e.getCredentials??Tt)({apiOrigin:l(r),signal:i});let a=Ni(r,e.channel??g({env:r})),o=await(e.fetchImpl??fetch)(a+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+t,accept:"application/json"},signal:i}),p=await o.json().catch(()=>({})),n=be(p)?p:{};if(!o.ok){let s=typeof n.detail==="string"?n.detail:typeof n.message==="string"?n.message:"API key authentication failed ("+o.status+")";throw new I(o.status,typeof n.error==="string"?n.error:"api_key_auth_failed",s)}if(typeof n.org_id!=="string"||!n.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let c=Array.isArray(n.scopes)?n.scopes.filter((s)=>typeof s==="string"):[];return{credentialKind:"api_key",apiOrigin:a,accessToken:t,orgId:n.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:c}}async function hs(e){let i=await zo(e),r=l(e.env??process.env);if(!i)throw Error(r?`Not signed in to ${r}. Set REASON_API_KEY, or run \`reason login --api-url ${r}\`.`:"Not signed in. Run `reason login`, or set REASON_API_KEY.");return i}
3
+ export{Ni,Ho,zo,hs};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var i="libara_device_keychain.dylib",e="libreason_device_keychain.dylib";class rt extends Error{code;constructor(n,t){super(t);this.code=n;this.name="ManagedRuntimeError"}}import{existsSync as s}from"fs";import{join as a}from"path";function Vi(n){let t=a(n,e);return s(t)?t:a(n,i)}
3
- export{rt,Vi};
2
+ var i="libara_device_keychain.dylib",e="libreason_device_keychain.dylib";class dt extends Error{code;constructor(n,t){super(t);this.code=n;this.name="ManagedRuntimeError"}}import{existsSync as s}from"fs";import{join as a}from"path";function fo(n){let t=a(n,e);return s(t)?t:a(n,i)}
3
+ export{dt,fo};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{he}from"./vm-hands-entry-lite-0xrsph3r.js";var Yr=he(function(t,e){e.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
3
- export{Yr};
2
+ import{he}from"./vm-hands-entry-lite-hbs3tpdg.js";var cn=he(function(t,e){e.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
3
+ export{cn};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Zt}from"./vm-hands-entry-lite-m11j0f9q.js";import{Ie}from"./vm-hands-entry-lite-8ns59paz.js";import{execFileSync as p}from"child_process";import{realpathSync as S,statSync as w}from"fs";import{tmpdir as P}from"os";import{createRequire as b}from"module";import{win32 as r}from"path";var h=["/bin/bash","/usr/bin/bash"],g="Git Bash was not found. Install Git for Windows (https://git-scm.com/download/win), then run `reason connect`.";function c(o){try{return w(o).isFile()}catch{return!1}}var i=(o)=>[r.join(o,"bin","bash.exe"),r.join(o,"usr","bin","bash.exe")];function J(o,e){let t=r.normalize(o).toLowerCase(),s=(e.SystemRoot??e.SYSTEMROOT??"C:\\Windows").toLowerCase();return t.startsWith(r.join(s,"system32").toLowerCase()+"\\")||t.startsWith(r.join(s,"sysnative").toLowerCase()+"\\")||t.includes("\\windowsapps\\")}function f(o=process.env,e=c){let t=[];for(let s of(o.PATH??o.Path??"").split(";"))if(s&&r.isAbsolute(s))t.push(r.join(s,"git.exe"));for(let s of[o.ProgramW6432,o.ProgramFiles,o["ProgramFiles(x86)"]])if(s)t.push(r.join(s,"Git","cmd","git.exe"));if(o.LOCALAPPDATA)t.push(r.join(o.LOCALAPPDATA,"Programs","Git","cmd","git.exe"));return t.find(e)??null}var a;function wo(o=process.platform){if(o!=="win32")return"git";return a??=f(),a}function y(o){let e=process.platform==="win32"?f(o):"git";if(!e)return null;try{return p(e,["--exec-path"],{encoding:"utf8",timeout:5000,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:o}).trim()||null}catch{return null}}function N(o=process.env,e=y,t=c){let s=[],l=e(o);if(l)s.push(...i(r.resolve(l,"..","..","..")));for(let n of[o.ProgramW6432,o.ProgramFiles,o["ProgramFiles(x86)"]])if(n)s.push(...i(r.join(n,"Git")));if(o.LOCALAPPDATA)s.push(...i(r.join(o.LOCALAPPDATA,"Programs","Git")));for(let n of(o.PATH??o.Path??"").split(";"))if(n&&r.isAbsolute(n))s.push(r.join(n,"bash.exe"));return s.find((n)=>!J(n,o)&&t(n))??null}var d;function fe(o=process.platform){if(o!=="win32")return h.find(c)??null;return d??=N(),d}function se(o=process.platform){let e=fe(o);if(!e)throw Error(o==="win32"?g:"bash_unavailable");return e}function bo(o=process.platform){return S(o==="win32"?P():"/tmp")}function Re(o=process.platform,e=process.env){if(o!=="win32")return"/usr/bin:/bin";let t=e.SystemRoot??e.SYSTEMROOT??"C:\\Windows";return[r.join(t,"System32"),t,r.join(t,"System32","Wbem"),r.join(t,"System32","WindowsPowerShell","v1.0")].join(";")}function x(o,e=process.platform){if(e!=="win32"||/[\\/]/.test(o))return o;let t=/\.exe$/i.test(o)?o:`${o}.exe`,s=Re(e).split(";");return r.join(t.toLowerCase()==="powershell.exe"?s[3]:s[0],t)}function Jr(o=process.platform,e=process.env){if(o!=="win32")return{PATH:Re(o)};let t=e.SystemRoot??e.SYSTEMROOT??"C:\\Windows";return{PATH:Re(o,e),SystemRoot:t,WINDIR:t}}function Kt(o=process.platform){return o==="win32"?{windowsHide:!0}:{detached:!0}}var u;function m(){if(u===void 0)u=Ie(Zt)(b(import.meta.url));return u}function Jt(o,e=process.platform){let t=o.pid;if(e!=="win32"||t===void 0)return;let s=m();if(s?.track(t))o.once("close",()=>s.release(t))}function Oe(o,e="SIGTERM",t=process.platform){if(t!=="win32"){process.kill(-o,e);return}if(e===0){process.kill(o,0);return}if(m()?.terminate(o))return;p(x("taskkill",t),["/PID",String(o),"/T","/F"],{stdio:"ignore",timeout:1e4,windowsHide:!0})}function I(o,e=63,t=process.platform){return t==="win32"||o.uid===process.getuid?.()&&(o.mode&e)===0}var A=/^(?:con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3]|conin\$|conout\$)(?:\..*)?$|:|[. ]$/i;function Zr(o){return o!=="."&&o!==".."&&A.test(o)}
3
- export{wo,fe,se,bo,Re,x,Jr,Kt,Jt,Oe,I,Zr};
2
+ import{sr}from"./vm-hands-entry-lite-rfz60hb3.js";import{Be}from"./vm-hands-entry-lite-zp6naptr.js";import{execFileSync as p}from"child_process";import{realpathSync as S,statSync as w}from"fs";import{tmpdir as P}from"os";import{createRequire as b}from"module";import{win32 as r}from"path";var h=["/bin/bash","/usr/bin/bash"],g="Git Bash was not found. Install Git for Windows (https://git-scm.com/download/win), then run `reason connect`.";function c(o){try{return w(o).isFile()}catch{return!1}}var i=(o)=>[r.join(o,"bin","bash.exe"),r.join(o,"usr","bin","bash.exe")];function x(o,e){let t=r.normalize(o).toLowerCase(),s=(e.SystemRoot??e.SYSTEMROOT??"C:\\Windows").toLowerCase();return t.startsWith(r.join(s,"system32").toLowerCase()+"\\")||t.startsWith(r.join(s,"sysnative").toLowerCase()+"\\")||t.includes("\\windowsapps\\")}function f(o=process.env,e=c){let t=[];for(let s of(o.PATH??o.Path??"").split(";"))if(s&&r.isAbsolute(s))t.push(r.join(s,"git.exe"));for(let s of[o.ProgramW6432,o.ProgramFiles,o["ProgramFiles(x86)"]])if(s)t.push(r.join(s,"Git","cmd","git.exe"));if(o.LOCALAPPDATA)t.push(r.join(o.LOCALAPPDATA,"Programs","Git","cmd","git.exe"));return t.find(e)??null}var a;function jo(o=process.platform){if(o!=="win32")return"git";return a??=f(),a}function J(o){let e=process.platform==="win32"?f(o):"git";if(!e)return null;try{return p(e,["--exec-path"],{encoding:"utf8",timeout:5000,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:o}).trim()||null}catch{return null}}function y(o=process.env,e=J,t=c){let s=[],l=e(o);if(l)s.push(...i(r.resolve(l,"..","..","..")));for(let n of[o.ProgramW6432,o.ProgramFiles,o["ProgramFiles(x86)"]])if(n)s.push(...i(r.join(n,"Git")));if(o.LOCALAPPDATA)s.push(...i(r.join(o.LOCALAPPDATA,"Programs","Git")));for(let n of(o.PATH??o.Path??"").split(";"))if(n&&r.isAbsolute(n))s.push(r.join(n,"bash.exe"));return s.find((n)=>!x(n,o)&&t(n))??null}var d;function fe(o=process.platform){if(o!=="win32")return h.find(c)??null;return d??=y(),d}function se(o=process.platform){let e=fe(o);if(!e)throw Error(o==="win32"?g:"bash_unavailable");return e}function Uo(o=process.platform){return S(o==="win32"?P():"/tmp")}function De(o=process.platform,e=process.env){if(o!=="win32")return"/usr/bin:/bin";let t=e.SystemRoot??e.SYSTEMROOT??"C:\\Windows";return[r.join(t,"System32"),t,r.join(t,"System32","Wbem"),r.join(t,"System32","WindowsPowerShell","v1.0")].join(";")}function C(o,e=process.platform){if(e!=="win32"||/[\\/]/.test(o))return o;let t=/\.exe$/i.test(o)?o:`${o}.exe`,s=De(e).split(";");return r.join(t.toLowerCase()==="powershell.exe"?s[3]:s[0],t)}function Ne(o=process.platform,e=process.env){if(o!=="win32")return{PATH:De(o)};let t=e.SystemRoot??e.SYSTEMROOT??"C:\\Windows";return{PATH:De(o,e),SystemRoot:t,WINDIR:t}}function Le(o=process.platform){return o==="win32"?{windowsHide:!0}:{detached:!0}}var u;function m(){if(u===void 0)u=Be(sr)(b(import.meta.url));return u}function Me(o,e=process.platform){let t=o.pid;if(e!=="win32"||t===void 0)return;let s=m();if(s?.track(t))o.once("close",()=>s.release(t))}function $e(o,e="SIGTERM",t=process.platform){if(t!=="win32"){process.kill(-o,e);return}if(e===0){process.kill(o,0);return}if(m()?.terminate(o))return;p(C("taskkill",t),["/PID",String(o),"/T","/F"],{stdio:"ignore",timeout:1e4,windowsHide:!0})}function A(o,e=63,t=process.platform){return t==="win32"||o.uid===process.getuid?.()&&(o.mode&e)===0}var N=/^(?:con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3]|conin\$|conout\$)(?:\..*)?$|:|[. ]$/i;function sn(o){return o!=="."&&o!==".."&&N.test(o)}
3
+ export{jo,fe,se,Uo,De,C,Ne,Le,Me,$e,A,sn};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var Ht={name:"github-native-engineer-device-worker-production",version:"0.2.416",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
3
- export{Ht};
2
+ var er={name:"github-native-engineer-device-worker-production",version:"0.2.418",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
3
+ export{er};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{C}from"./vm-hands-entry-lite-t7an5zg2.js";import{g,Mr,Gi,ve}from"./vm-hands-entry-lite-ckv17tn8.js";import{t,o,d,u,i,Mo,Q,_,s,n}from"./vm-hands-entry-lite-907pa7f9.js";var J=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function P(e){let r=typeof e==="string"?J.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var K=25,Le=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(K).optional()}),W=_("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),x=i({job:W.nullable(),retry_after_seconds:o().optional()}),V=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),Y=i({person:t(),machine:t(),online:d()}),X=i({team:t().nullable(),sessions:u(V).max(2000),machines:u(Y).max(500),all:d().optional()}),Z=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Ne=Q([i({who:X}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(Z).max(500).optional()})}),i({error:t().min(1).max(2000)})]),ee=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),De=i({messages:u(ee).max(100)});import{randomBytes as ne}from"crypto";import{chmodSync as A,existsSync as U,lstatSync as te,mkdirSync as se,readFileSync as T,renameSync as oe,unlinkSync as q,writeFileSync as O}from"fs";import{homedir as re}from"os";import{dirname as ie,join as I}from"path";function b(e=process.env,r=re()){let a=e.XDG_CONFIG_HOME?.trim()||I(r,".config"),c=g({env:e})==="staging"?["staging"]:[];return I(ve(a,...c),"credentials.json")}function z(e,r=b()){return se(ie(r),{recursive:!0,mode:448}),O(r,`${JSON.stringify(e,null,2)}
3
- `,{mode:384}),A(r,384),r}function v(e=b()){if(!U(e))return null;try{let r=T(e,"utf8"),a=JSON.parse(r);if(typeof a.apiOrigin!=="string"||typeof a.clientId!=="string"||typeof a.accessToken!=="string"||typeof a.refreshToken!=="string"||typeof a.expiresAt!=="string"||typeof a.orgId!=="string"||!Array.isArray(a.scopes))return null;let l=new URL(a.apiOrigin).origin,c=Mr(l);if(c!==l)ae(e,r,c);return{apiOrigin:c,clientId:a.clientId,accessToken:a.accessToken,refreshToken:a.refreshToken,expiresAt:a.expiresAt,scopes:a.scopes.filter((m)=>typeof m==="string"),orgId:a.orgId}}catch{return null}}function ae(e,r,a){let l=`${e}.${process.pid}.${ne(6).toString("hex")}.tmp`;try{let c=te(e);if(!c.isFile()||process.platform!=="win32"&&c.uid!==process.geteuid?.())return;let m=JSON.parse(r);if(O(l,`${JSON.stringify({...m,apiOrigin:a},null,2)}
4
- `,{mode:384,flag:"wx"}),A(l,384),T(e,"utf8")!==r)throw Error("credentials_changed");oe(l,e)}catch{try{q(l)}catch{}}}function M(e=b()){if(!U(e))return!1;return q(e),!0}var j=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var cn=j.filter((e)=>e!=="network:read"&&e!=="network:write");class w extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function le(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new w(l,a)}async function ce(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw le(m,`OAuth token request failed (${c.status})`);return m}var de=1e4;async function me(e,r={}){let a=r.fetchImpl??fetch,l=await ce(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(de)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new w("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new w("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return z(c,r.path??b()),c}var S=new Map;function E(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function _t(e={}){let r=e.path??b(),a=v(r);if(!a)return null;let l=e.apiOrigin??C(process.env,"REASON_API_URL")?.trim();if(l&&!Gi(a.apiOrigin,new URL(l).origin))return null;let c=Date.parse(a.expiresAt)<=Date.now()+60000;if(!e.forceRefresh&&!c)return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=S.get(m);if(p)return E(p,e.signal);let f;return f=me(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof w)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let k=v(r),B=y.oauthCode==="invalid_client"?k?.clientId!==a.clientId:k?.refreshToken!==a.refreshToken;if(k&&B)return _t({fetchImpl:e.fetchImpl,path:r});return M(r),null}).finally(()=>{if(S.get(m)===f)S.delete(m)}),S.set(m,f),E(f,e.signal)}var ue=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ge=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function he(e){let r=ge.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class R extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(e,r,a,l,c,m){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof R)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var pe=["minimal","low","medium","high","xhigh","max"],fe=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),ye=i({devices:u(fe),end_cursor:t().nullish(),has_next_page:d().optional()}),_e=i({id:t().min(1),name:t()}),be=i({items:u(_e)}),Re=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),we=i({items:u(Re)}),Se=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),ke=i({items:u(Se).default([])}),Pe=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),N=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(Pe).default([])}),xe=i({items:u(N).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),Ie=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),Ce=i({items:u(Ie).default([])}),$e=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),L=i({tags:u(t()).default([])}),Ae=s(["linux","macos"]),D=i({id:t().min(1),name:t().min(1),platform:Ae.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),Ue=i({machines:u(D)}),Te=i({machine:D}),qe=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),Oe=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),H=Mo({machine_id:t().min(1),machine_name:t().min(1)}),ze=H.extend({organization_id:t().min(1)}),pn=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var fn=Q([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new R(502,a,"Reason returned an unexpected response.");return l.data}var Me=i({error:i({type:t(),message:t()})});function F(e,r,a){let l=Me.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new R(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0)}async function Vo(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw F(r.status,a,r.headers.get("retry-after"));return h(ze,a,"invalid_machine_ticket")}class Eo{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await _t({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,signal:r.signal});if(p)return this.credentials=p,this.request(e,r,!0)}if(!c.ok)throw F(c.status,m,c.headers.get("retry-after"));return m}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof R&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(Ue,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Te,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(qe,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(Oe,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(H,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(x,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:{messages:e},signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=be.safeParse(e);if(!r.success)throw new R(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(we,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(ke,e,"invalid_skill_list").items}catch(e){if(e instanceof R&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=ye.safeParse(l);if(!c.success)throw new R(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:pe.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof R&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return P(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=ue.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=he(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof R&&(e.status===403||e.status===404))return null;throw e}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof R)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof R&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(L,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(L,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h($e,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(xe,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(N,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(Ce,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
5
- export{_t,R,Vo,Eo};
2
+ import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{g,Gr,mo,xe}from"./vm-hands-entry-lite-aj139v8j.js";import{t,o,d,u,i,ns,W,_,s,n}from"./vm-hands-entry-lite-avc65bd7.js";var J=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function v(e){let r=typeof e==="string"?J.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var Q=25,Le=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(Q).optional()}),K=_("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),P=i({job:K.nullable(),retry_after_seconds:o().optional()}),V=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),Y=i({person:t(),machine:t(),online:d()}),X=i({team:t().nullable(),sessions:u(V).max(2000),machines:u(Y).max(500),all:d().optional()}),Z=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Ne=W([i({who:X}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(Z).max(500).optional()})}),i({error:t().min(1).max(2000)})]),ee=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),De=i({messages:u(ee).max(100)});import{randomBytes as ne}from"crypto";import{chmodSync as C,existsSync as A,lstatSync as te,mkdirSync as se,readFileSync as U,renameSync as oe,unlinkSync as q,writeFileSync as O}from"fs";import{homedir as re}from"os";import{dirname as ie,join as x}from"path";function b(e=process.env,r=re()){let a=e.XDG_CONFIG_HOME?.trim()||x(r,".config"),c=g({env:e})==="staging"?["staging"]:[];return x(xe(a,...c),"credentials.json")}function z(e,r=b()){return se(ie(r),{recursive:!0,mode:448}),O(r,`${JSON.stringify(e,null,2)}
3
+ `,{mode:384}),C(r,384),r}function k(e=b()){if(!A(e))return null;try{let r=U(e,"utf8"),a=JSON.parse(r);if(typeof a.apiOrigin!=="string"||typeof a.clientId!=="string"||typeof a.accessToken!=="string"||typeof a.refreshToken!=="string"||typeof a.expiresAt!=="string"||typeof a.orgId!=="string"||!Array.isArray(a.scopes))return null;let l=new URL(a.apiOrigin).origin,c=Gr(l);if(c!==l)ae(e,r,c);return{apiOrigin:c,clientId:a.clientId,accessToken:a.accessToken,refreshToken:a.refreshToken,expiresAt:a.expiresAt,scopes:a.scopes.filter((m)=>typeof m==="string"),orgId:a.orgId}}catch{return null}}function ae(e,r,a){let l=`${e}.${process.pid}.${ne(6).toString("hex")}.tmp`;try{let c=te(e);if(!c.isFile()||process.platform!=="win32"&&c.uid!==process.geteuid?.())return;let m=JSON.parse(r);if(O(l,`${JSON.stringify({...m,apiOrigin:a},null,2)}
4
+ `,{mode:384,flag:"wx"}),C(l,384),U(e,"utf8")!==r)throw Error("credentials_changed");oe(l,e)}catch{try{q(l)}catch{}}}function M(e=b()){if(!A(e))return!1;return q(e),!0}var j=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var cn=j.filter((e)=>e!=="network:read"&&e!=="network:write");class R extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function le(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new R(l,a)}async function ce(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw le(m,`OAuth token request failed (${c.status})`);return m}var de=1e4;async function me(e,r={}){let a=r.fetchImpl??fetch,l=await ce(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(de)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new R("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new R("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return z(c,r.path??b()),c}var w=new Map;function E(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Tt(e={}){let r=e.path??b(),a=k(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!mo(a.apiOrigin,new URL(l).origin))return null;let c=Date.parse(a.expiresAt)<=Date.now()+60000;if(!e.forceRefresh&&!c)return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=w.get(m);if(p)return E(p,e.signal);let f;return f=me(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof R)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let S=k(r),B=y.oauthCode==="invalid_client"?S?.clientId!==a.clientId:S?.refreshToken!==a.refreshToken;if(S&&B)return Tt({fetchImpl:e.fetchImpl,path:r});return M(r),null}).finally(()=>{if(w.get(m)===f)w.delete(m)}),w.set(m,f),E(f,e.signal)}var ue=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ge=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function he(e){let r=ge.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(e,r,a,l,c,m){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var pe=["minimal","low","medium","high","xhigh","max"],fe=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),ye=i({devices:u(fe),end_cursor:t().nullish(),has_next_page:d().optional()}),_e=i({id:t().min(1),name:t()}),be=i({items:u(_e)}),Re=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),we=i({items:u(Re)}),Se=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),ke=i({items:u(Se).default([])}),ve=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),N=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(ve).default([])}),Pe=i({items:u(N).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),Ie=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),Ce=i({items:u(Ie).default([])}),$e=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),L=i({tags:u(t()).default([])}),Ae=s(["linux","macos"]),D=i({id:t().min(1),name:t().min(1),platform:Ae.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),Ue=i({machines:u(D)}),Te=i({machine:D}),qe=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),Oe=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),H=ns({machine_id:t().min(1),machine_name:t().min(1)}),ze=H.extend({organization_id:t().min(1)}),pn=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var fn=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var Me=i({error:i({type:t(),message:t()})});function F(e,r,a){let l=Me.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0)}async function fs(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw F(r.status,a,r.headers.get("retry-after"));return h(ze,a,"invalid_machine_ticket")}class qo{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Tt({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,signal:r.signal});if(p)return this.credentials=p,this.request(e,r,!0)}if(!c.ok)throw F(c.status,m,c.headers.get("retry-after"));return m}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(Ue,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Te,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(qe,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(Oe,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(H,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(P,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:{messages:e},signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=be.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(we,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(ke,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=ye.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:pe.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return v(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=ue.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=he(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(L,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(L,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h($e,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(Pe,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(N,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(Ce,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
5
+ export{Tt,I,fs,qo};
@@ -0,0 +1,128 @@
1
+ // @bun
2
+ import{Gn,Ao,Jt}from"./vm-hands-entry-lite-jzz73e3f.js";import{Pn,Ve,ao,Tn,Rn,On,Pr,x}from"./vm-hands-entry-lite-m8nqnd9j.js";import{kt}from"./vm-hands-entry-lite-fbhqfzbq.js";import{Ir}from"./vm-hands-entry-lite-nzmkyezg.js";import{j}from"./vm-hands-entry-lite-pf5qtbj5.js";import{a}from"./vm-hands-entry-lite-jev771b3.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as Y,spawn as z}from"child_process";import{randomBytes as Te}from"crypto";import{chmodSync as he,existsSync as H,lstatSync as Qe,mkdirSync as _e,readFileSync as De,rmSync as I,writeFileSync as C}from"fs";import{connect as we}from"net";import{join as y}from"path";var P=32,w=76;var W="./desktop-wallpaper-0pjhgyfk.jpg";var B="./dock-browser-afp005mt.png";var O="./dock-files-rywdm96b.png";var F="./dock-terminal-s41cj1jp.png";var k=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
3
+ # The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
4
+ # python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
5
+ # Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
6
+ import ctypes, sys
7
+ import gi
8
+ gi.require_version("GdkPixbuf", "2.0")
9
+ from gi.repository import GdkPixbuf
10
+ x = ctypes.cdll.LoadLibrary("libX11.so.6")
11
+ x.XOpenDisplay.restype = ctypes.c_void_p
12
+ x.XOpenDisplay.argtypes = [ctypes.c_char_p]
13
+ d = x.XOpenDisplay(None)
14
+ if not d: sys.exit("no display")
15
+ for name, res, args in [
16
+ ("XDefaultScreen", ctypes.c_int, [ctypes.c_void_p]),
17
+ ("XRootWindow", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_int]),
18
+ ("XDisplayWidth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
19
+ ("XDisplayHeight", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
20
+ ("XDefaultDepth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
21
+ ("XDefaultVisual", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
22
+ ("XDefaultGC", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
23
+ ("XCreatePixmap", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]),
24
+ ("XCreateImage", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_int, ctypes.c_int]),
25
+ ("XPutImage", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint]),
26
+ ("XInternAtom", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]),
27
+ ("XChangeProperty", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]),
28
+ ("XSetWindowBackgroundPixmap", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]),
29
+ ("XClearWindow", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong]),
30
+ ("XSetCloseDownMode", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
31
+ ("XCloseDisplay", ctypes.c_int, [ctypes.c_void_p]),
32
+ ]:
33
+ f = getattr(x, name); f.restype = res; f.argtypes = args
34
+ s = x.XDefaultScreen(d); root = x.XRootWindow(d, s)
35
+ w, h = x.XDisplayWidth(d, s), x.XDisplayHeight(d, s)
36
+ if x.XDefaultDepth(d, s) != 24: sys.exit("unsupported depth")
37
+ # Scale to cover the screen, then crop the centre.
38
+ src = GdkPixbuf.Pixbuf.new_from_file(sys.argv[1])
39
+ k = max(w / src.get_width(), h / src.get_height())
40
+ sw, sh = max(w, round(src.get_width() * k)), max(h, round(src.get_height() * k))
41
+ pb = src.scale_simple(sw, sh, GdkPixbuf.InterpType.BILINEAR).new_subpixbuf((sw - w) // 2, (sh - h) // 2, w, h).copy()
42
+ if pb.get_has_alpha(): pb = pb.composite_color_simple(w, h, GdkPixbuf.InterpType.NEAREST, 255, 1, 0, 0)
43
+ rgb, stride = pb.get_pixels(), pb.get_rowstride()
44
+ bgrx = bytearray(w * h * 4)
45
+ for y in range(h):
46
+ row = rgb[y * stride:y * stride + w * 3]; o = y * w * 4
47
+ bgrx[o:o + w * 4:4] = row[2::3]; bgrx[o + 1:o + w * 4:4] = row[1::3]; bgrx[o + 2:o + w * 4:4] = row[0::3]
48
+ buf = ctypes.create_string_buffer(bytes(bgrx), len(bgrx))
49
+ pix = x.XCreatePixmap(d, root, w, h, 24)
50
+ img = x.XCreateImage(d, x.XDefaultVisual(d, s), 24, 2, 0, buf, w, h, 32, 0) # ZPixmap
51
+ x.XPutImage(d, pix, x.XDefaultGC(d, s), img, 0, 0, 0, 0, w, h)
52
+ ref = ctypes.c_ulong(pix)
53
+ for atom in (b"_XROOTPMAP_ID", b"ESETROOT_PMAP_ID"):
54
+ x.XChangeProperty(d, root, x.XInternAtom(d, atom, 0), 20, 32, 0, ctypes.byref(ref), 1) # XA_PIXMAP, PropModeReplace
55
+ x.XSetWindowBackgroundPixmap(d, root, pix)
56
+ x.XClearWindow(d, root)
57
+ x.XSetCloseDownMode(d, 1) # RetainPermanent: the pixmap outlives this process
58
+ x.XCloseDisplay(d)
59
+ `;function ce(e){return`<?xml version="1.0" encoding="UTF-8"?>
60
+ <openbox_config xmlns="http://openbox.org/3.4/rc">
61
+ <theme><keepBorder>no</keepBorder></theme>
62
+ <applications>
63
+ <!-- Debian Chromium is "Chromium"; Chrome for Testing is "Chromium-browser". -->
64
+ <application class="Chromium*">
65
+ <decor>no</decor>
66
+ <position force="yes"><x>${P}</x><y>${P}</y></position>
67
+ <size><width>${e.width-P*2}</width><height>${e.height-P-w}</height></size>
68
+ </application>
69
+ </applications>
70
+ </openbox_config>`}var be=`# Remote sandbox dock \u2014 launcher icons only, centred, no panel fill
71
+ panel_items = L
72
+ panel_size = 100% 46
73
+ panel_margin = 0 10
74
+ panel_padding = 0 0 10
75
+ panel_position = bottom center horizontal
76
+ panel_shrink = 1
77
+ panel_background_id = 0
78
+ panel_layer = top
79
+ mouse_effects = 1
80
+ mouse_hover_icon_asb = 100 0 12
81
+ mouse_pressed_icon_asb = 100 0 -12
82
+
83
+ launcher_icon_size = 46
84
+ launcher_padding = 0 0 10
85
+ launcher_background_id = 0
86
+ launcher_tooltip = 1
87
+
88
+ launcher_item_app = /tmp/ara-chromium.desktop
89
+ launcher_item_app = /tmp/ara-terminal.desktop
90
+ launcher_item_app = /tmp/ara-files.desktop
91
+ `,ye=`corner-radius = 12;
92
+ rounded-corners-exclude = [
93
+ "class_g = 'tint2'",
94
+ "window_type = 'dock'",
95
+ "window_type = 'desktop'"
96
+ ];
97
+ backend = "xrender";
98
+ shadow = false;
99
+ fading = false;
100
+ vsync = false;
101
+ inactive-opacity = 1.0;
102
+ active-opacity = 1.0;
103
+ `,le="/tmp/ara-dock-browser.png",ue=`[Desktop Entry]
104
+ Name=Chrome
105
+ Exec=chromium --no-sandbox %U
106
+ Icon=${le}
107
+ Type=Application
108
+ Categories=Network;WebBrowser;
109
+ `,Pe=`[Desktop Entry]
110
+ Name=Terminal
111
+ Exec=bash -c "DISPLAY=:99 xterm -fa DejaVuSansMono -fs 11 -bg black -fg white"
112
+ Icon=/tmp/ara-dock-terminal.png
113
+ Type=Application
114
+ Categories=System;TerminalEmulator;
115
+ `,Se=`[Desktop Entry]
116
+ Name=Files
117
+ Exec=bash -c "DISPLAY=:99 pcmanfm --no-desktop"
118
+ Icon=/tmp/ara-dock-files.png
119
+ Type=Application
120
+ Categories=System;FileManager;
121
+ `;var K={"wallpaper.jpg":W,"dock-browser.png":B,"dock-terminal.png":F,"dock-files.png":O},Xe=k,fe='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function v(e){let s=(i)=>i.replaceAll("DISPLAY=:99",`DISPLAY=${e.display}`).replaceAll("/tmp/ara-",`${e.root}/ara-`),p=new Set(e.absent??[]),n=be.split(`
122
+ `).filter((i)=>!(p.has("terminal")&&i.endsWith("/ara-terminal.desktop"))&&!(p.has("files")&&i.endsWith("/ara-files.desktop"))).join(`
123
+ `);return{files:{"openbox/rc.xml":ce(e.screen),"tint2/tint2rc":s(n),"picom/picom.conf":ye,...p.has("terminal")?{}:{"ara-terminal.desktop":s(Pe)},...p.has("files")?{}:{"ara-files.desktop":s(Se)},"ara-chromium.desktop":s(ue).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Xe},start:['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }',fe,'[ ! -f "$ROOT/ara-wallpaper.jpg" ] || set_wallpaper "$ROOT/ara-wallpaper.jpg" "$ROOT/ara-set-root-wallpaper.py" || true','if ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi']}}var Re=43200000,_=":99",de=60000,D=15000,L={width:1280,height:800},Ae=/^[A-Za-z0-9._:-]{1,160}$/;function Ne(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var Ee=["video","viewer","viewer_same_network","viewer_network"];function Le(e,s=Date.now()){let p=["relay_url","session_id","expires_at"];if(!Ne(e)||p.some((c)=>!(c in e))||Object.keys(e).some((c)=>!p.includes(c)&&!Ee.includes(c)))throw new r("invalid_display_request","Reason desktop request is malformed.");let n="video"in e?Ao(e.video):void 0,t="viewer"in e?Gn(e.viewer):null;if(n===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let o=null;try{o=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!o||o.protocol!=="wss:"&&o.protocol!=="ws:"||o.username||o.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!Ae.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let i=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(i)||i<=s)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(i,s+Re)).toISOString(),...n?{video:n}:{},...t?{viewer:t}:{},...n&&e.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function $t(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&x()?.features.display===!0}async function Ls(){if(process.platform==="win32")return $t()&&await Pr();if(process.platform!=="darwin")return $t();return await Pr()}function G(e){_e(e,{recursive:!0,mode:448});let s=Qe(e);if(!s.isDirectory()||s.isSymbolicLink()||process.getuid&&s.uid!==process.getuid())throw new r("display_unavailable","Reason desktop state directory is not private.");he(e,448)}function Je(e,s){let p=(t)=>{let o=Buffer.alloc(2);return o.writeUInt16BE(t.length),Buffer.concat([o,t])},n=Buffer.from([255,255]);return Buffer.concat([n,p(Buffer.alloc(0)),p(Buffer.from(e)),p(Buffer.from("MIT-MAGIC-COOKIE-1")),p(s)])}function f(e,s,p=2000){return new Promise((n)=>{let t=we(e),o="",i=(c)=>{t.destroy(),n(c)};t.setTimeout(p,()=>i(!1)),t.once("error",()=>i(!1)),t.once("close",()=>i(!1)),t.once("connect",()=>{if(!s)i(!0)}),t.on("data",(c)=>{if(o+=c.toString("latin1"),o.length>=4)i(o.startsWith("RFB "))})})}async function U(e,s){let p=Date.now()+s;while(Date.now()<p){if(await e())return!0;await new Promise((n)=>setTimeout(n,100))}return!1}function R(e,s,p){return new Promise((n)=>{let t=z(e,s,{detached:!0,stdio:"ignore",env:p});t.once("error",()=>n(-1)),t.once("exit",(o)=>n(o)),t.unref(),setTimeout(()=>n(null),D).unref()})}var J=null;function qe(e=a()){return J??=Ce(e).finally(()=>{J=null}),J}async function Ce(e){let s=x({home:e});if(!s?.xvfb||!s.x11vnc||!s.openbox)throw new r("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");kt({root:s.root,automation:s.automation,extensionDir:s.extensionDir});let p=y(s.root,"display");G(p);let n=await ge(e,p,s.x11vnc);if(n)return n;let t={display:_,xauthority:y(p,"Xauthority"),rfbSocket:y(p,"rfb.sock")},o=y(p,"pulse"),i=(async()=>{try{G(o)}catch{return null}return await ao(o,s.pulseaudio)})();G(y(p,"home"));let c=ee(p,t,s.pulseaudio),T=async()=>({...t,sound:await i});if(await f({path:t.rfbSocket},!0))return await T();if(!H(t.xauthority))C(t.xauthority,Je(_.slice(1),Te(16)),{mode:384,flag:"wx"});let l=se(y(p,"theme"),t.display,L),S={path:`/tmp/.X11-unix/X${_.slice(1)}`};if(!await f(S,!1)){let q=`${L.width}x${L.height}`;if(s.xvnc)I(t.rfbSocket,{force:!0}),R(s.xvnc,[t.display,"-geometry",q,"-depth","24","-nolisten","tcp","-auth",t.xauthority,"-rfbport","-1","-rfbunixpath",t.rfbSocket,"-SecurityTypes","None","-AlwaysShared","-desktop","Reason"],c);else R(s.xvfb,[t.display,"-screen","0",`${q}x24`,"-nolisten","tcp","-auth",t.xauthority],c);if(!await U(()=>f(S,!1),D)||s.xvnc&&!await U(()=>f({path:t.rfbSocket},!0),D))throw new r("display_unavailable","Reason could not start the virtual display.");R(s.openbox,["--config-file",l.openboxConfig],c)}if(await te(l,c),!await re(s.x11vnc,t,p,"x11vnc.log",c))throw new r("display_unavailable","Reason could not start the desktop server.");return await T()}function ee(e,s,p){let n={HOME:y(e,"home"),PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:s.display,XAUTHORITY:s.xauthority};if(p)n.PULSE_SERVER=Ve(Pn(y(e,"pulse")));return n}async function re(e,s,p,n,t){if(await f({path:s.rfbSocket},!0))return!0;I(s.rfbSocket,{force:!0});let o=await R(e,["-display",s.display,"-auth",s.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",s.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",y(p,n)],t);if(o!==null&&o!==0)return!1;return await U(()=>f({path:s.rfbSocket},!0),D)}async function Ue(){let e=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],s=(p)=>Object.fromEntries(e.flatMap((n)=>p[n]?[[n,p[n]]]:[]));if(process.env.DISPLAY)return s(process.env);try{let p=await new Promise((n,t)=>Y("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(o,i)=>o?t(o):n(i)));return s(Object.fromEntries(p.split(`
124
+ `).flatMap((n)=>{let t=n.indexOf("=");return t>0?[[n.slice(0,t),n.slice(t+1)]]:[]})))}catch{return{}}}var V=new Set;async function ge(e,s,p){let n=await Ue(),t=/^:(\d+)(?:\.\d+)?$/.exec(n.DISPLAY??"")?.[1];if(!t||`:${t}`===_||n.WAYLAND_DISPLAY||n.XDG_SESSION_TYPE==="wayland")return null;let o={display:`:${t}`,xauthority:n.XAUTHORITY??y(e,".Xauthority"),rfbSocket:y(s,`rfb-${t}.sock`)},i=`${o.display} ${o.xauthority}`;if(V.has(i)||!await f({path:`/tmp/.X11-unix/X${t}`},!1))return null;let c={HOME:e,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:o.display,XAUTHORITY:o.xauthority};if(await re(p,o,s,`x11vnc-${t}.log`,c))return{...o,sound:null};return V.add(i),process.stderr.write(`Reason worker: your screen ${o.display} could not be served; using the virtual desktop
125
+ `),null}function se(e,s,p){let n=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,t=[["terminal","xterm"],["files","pcmanfm"]].filter(([,i])=>!H(`/usr/bin/${i}`)).map(([i])=>i),o=v({root:e,display:s,screen:p,browserExec:n,absent:t});for(let i of["","openbox","tint2","picom"])G(y(e,i));for(let[i,c]of Object.entries(o.files))C(y(e,i),c,{mode:384});for(let[i,c]of Object.entries(K))C(y(e,`ara-${i}`),De(c),{mode:384});return{root:e,openboxConfig:y(e,"openbox","rc.xml"),start:o.start}}async function te(e,s){let p=[`ROOT=${JSON.stringify(e.root)}`,...e.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
126
+ `);await new Promise((n)=>{let t=z("/bin/sh",["-c",p],{stdio:"ignore",env:{...s,PATH:"/usr/bin:/bin"}}),o=setTimeout(()=>{t.kill(),n()},D);t.once("error",()=>{clearTimeout(o),n()}),t.once("exit",()=>{clearTimeout(o),n()})})}var me=2073600,Me=320;function We(e,s){let p=Math.min(1,Math.sqrt(me/(e.width*e.height))),n=(t,o)=>Math.min(Math.floor(o/8)*8,Math.max(Me,Math.round(t*p/8)*8));return{width:n(e.width,s.width),height:n(e.height,s.height)}}function ne(e,s,p){return new Promise((n)=>Y(e,s,{env:p,encoding:"utf8",timeout:5000},(t,o)=>n(t?null:o)))}function je(e){let s=/current (\d+) x (\d+), maximum (\d+) x (\d+)/.exec(e),p=e.split(`
127
+ `),n=p.findIndex((o)=>/^\S+ connected/.test(o));if(!s||n<0)return null;let t=[];for(let o of p.slice(n+1)){let i=/^\s+(\d+x\d+)\s/.exec(o);if(!i)break;t.push(i[1])}return{current:{width:Number(s[1]),height:Number(s[2])},maximum:{width:Number(s[3]),height:Number(s[4])},output:p[n].split(" ")[0],modes:t}}async function Be(e,s,p){if(e.display!==_)return null;let n={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(T)=>ne("xrandr",T,n),o=je(await t(["--query"])??"");if(!o||o.maximum.width<=o.current.width&&o.maximum.height<=o.current.height)return null;let i=We(s,o.maximum);if(i.width===o.current.width&&i.height===o.current.height)return{size:i,changed:!1};let c=`${i.width}x${i.height}`;if(!o.modes.includes(c)){if(await t(["--newmode",c,"60",...[i.width,i.width,i.width,i.width,i.height,i.height,i.height,i.height].map(String)]),await t(["--addmode",o.output,c])===null)return null}return p(),await t(["--output",o.output,"--mode",c])===null?null:{size:i,changed:!0}}async function Oe(e,s){let p=x({home:a()});if(!p)return;let n=y(p.root,"display"),t=ee(n,e,p.pulseaudio);await te(se(y(n,"theme"),e.display,s),t);let o=s.width-P*2,i=s.height-P-w;await ne("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(o),String(i),"windowmove","%@",String(P),String(P)],{...t,PATH:"/usr/bin:/bin"})}var Z=Promise.resolve();function Fe(e,s,p=()=>{}){let n=Z.then(()=>Be(e,s,p));return Z=n.then((t)=>t?.changed?Oe(e,t.size):void 0).catch(()=>{}),n.then((t)=>t?.size??null,()=>null)}async function Bt(e,s={}){let p=s.now??Date.now,n=Le(e.payload,p());if(e.signal.throwIfAborted(),!n.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let t=s.platform??process.platform;if(t!=="linux"&&t!=="darwin"&&t!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let o=n.video,i=(s.video?.desktop??(t==="darwin"?async()=>Tn:t==="win32"?async()=>Rn:qe))();return await ke(e.signal,n,s,p,(c)=>On(c,{request:o,desktop:i,...n.viewer?{viewer:n.viewer}:{},viewerSameNetwork:n.viewer_same_network===!0},{resizeDesktop:Fe,...s.video}),(c)=>Jt({type:"error",code:c}))}function ke(e,s,p,n,t,o){let i=n();return new Promise((c,T)=>{let l=null,S=!1,q=!1,g,d,h,m=!1,u=null,X=(b)=>{if(q)return;if(u)b=u;q=!0,clearTimeout(g),clearTimeout(d),e.removeEventListener("abort",N),h?.close();try{l?.close(1000,"display_session_over")}catch{}if("error"in b){T(b.error);return}c({reason:b.reason,...h?.summary(),duration_ms:Math.max(0,n()-i)})},A=()=>X({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),N=()=>{let b=e.reason;X({error:b instanceof r?b:new r("cancelled","Reason closed the desktop session.")})},M=()=>{if(!u||!l)return;let b=u.error;try{l.send(o(b instanceof r?b.code:"display_unavailable"))}catch{}X(u)};if(h=t({get done(){return q||u!==null},get open(){return S&&!q&&u===null},get bufferedAmount(){return l?.bufferedAmount??0},send(b){if(q||u||!S||!l)return;try{l.send(b)}catch{X({reason:"relay_closed"})}},end:(b)=>{if(q||u)return;if(!("error"in b)){X(b);return}if(u=b,m&&S)M()}}),q){h.close();return}if(e.aborted){N();return}e.addEventListener("abort",N,{once:!0}),g=setTimeout(()=>X({reason:"session_expired"}),Math.max(1,Date.parse(s.expires_at)-n())),d=setTimeout(()=>X({reason:"viewer_absent"}),p.viewerWaitMs??de);try{l=(p.connect??Ir)(s.relay_url,(p.loadProxy??j)()?.url)}catch{A();return}l.binaryType="arraybuffer",l.onopen=()=>{if(q||!l)return;S=!0,h?.opened()},l.onmessage=(b)=>{if(q)return;let Q=b.data,E=Q instanceof ArrayBuffer?new Uint8Array(Q):ArrayBuffer.isView(Q)?new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength):null;if(!E||E.byteLength===0)return;if(clearTimeout(d),m=!0,u){M();return}h?.received(E)},l.onclose=()=>{if(q)return;if(!S){A();return}X({reason:"relay_closed"})},l.onerror=()=>{if(q||S)return;A()}})}
128
+ export{$t,Ls,G,qe,Bt};